text
stringlengths
8
4.13M
#[cfg(feature = "ops")] pub(crate) mod deref; #[cfg(feature = "ops")] pub(crate) mod deref_mut; #[cfg(feature = "fn_traits")] pub(crate) mod fn_; #[cfg(feature = "fn_traits")] pub(crate) mod fn_mut; #[cfg(feature = "fn_traits")] pub(crate) mod fn_once; #[cfg(feature = "generator_trait")] pub(crate) mod generator; #[cfg(feature = "ops")] pub(crate) mod index; #[cfg(feature = "ops")] pub(crate) mod index_mut; #[cfg(feature = "ops")] pub(crate) mod range_bounds;
#[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::DMARIS { #[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 EMAC_DMARIS_TIR { bits: bool, } impl EMAC_DMARIS_TIR { #[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 _EMAC_DMARIS_TIW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_TIW<'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 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_TPSR { bits: bool, } impl EMAC_DMARIS_TPSR { #[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 _EMAC_DMARIS_TPSW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_TPSW<'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 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_TUR { bits: bool, } impl EMAC_DMARIS_TUR { #[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 _EMAC_DMARIS_TUW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_TUW<'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 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_TJTR { bits: bool, } impl EMAC_DMARIS_TJTR { #[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 _EMAC_DMARIS_TJTW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_TJTW<'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 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_OVFR { bits: bool, } impl EMAC_DMARIS_OVFR { #[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 _EMAC_DMARIS_OVFW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_OVFW<'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 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_UNFR { bits: bool, } impl EMAC_DMARIS_UNFR { #[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 _EMAC_DMARIS_UNFW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_UNFW<'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 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_RIR { bits: bool, } impl EMAC_DMARIS_RIR { #[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 _EMAC_DMARIS_RIW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_RIW<'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 << 6); self.w.bits |= ((value as u32) & 1) << 6; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_RUR { bits: bool, } impl EMAC_DMARIS_RUR { #[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 _EMAC_DMARIS_RUW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_RUW<'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 << 7); self.w.bits |= ((value as u32) & 1) << 7; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_RPSR { bits: bool, } impl EMAC_DMARIS_RPSR { #[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 _EMAC_DMARIS_RPSW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_RPSW<'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 << 8); self.w.bits |= ((value as u32) & 1) << 8; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_RWTR { bits: bool, } impl EMAC_DMARIS_RWTR { #[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 _EMAC_DMARIS_RWTW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_RWTW<'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 << 9); self.w.bits |= ((value as u32) & 1) << 9; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_ETIR { bits: bool, } impl EMAC_DMARIS_ETIR { #[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 _EMAC_DMARIS_ETIW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_ETIW<'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 << 10); self.w.bits |= ((value as u32) & 1) << 10; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_FBIR { bits: bool, } impl EMAC_DMARIS_FBIR { #[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 _EMAC_DMARIS_FBIW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_FBIW<'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 << 13); self.w.bits |= ((value as u32) & 1) << 13; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_ERIR { bits: bool, } impl EMAC_DMARIS_ERIR { #[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 _EMAC_DMARIS_ERIW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_ERIW<'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 << 14); self.w.bits |= ((value as u32) & 1) << 14; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_AISR { bits: bool, } impl EMAC_DMARIS_AISR { #[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 _EMAC_DMARIS_AISW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_AISW<'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 << 15); self.w.bits |= ((value as u32) & 1) << 15; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_NISR { bits: bool, } impl EMAC_DMARIS_NISR { #[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 _EMAC_DMARIS_NISW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_NISW<'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 = "Possible values of the field `EMAC_DMARIS_RS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EMAC_DMARIS_RSR { #[doc = "Stopped: Reset or stop receive command issued"] EMAC_DMARIS_RS_STOP, #[doc = "Running: Fetching receive transfer descriptor"] EMAC_DMARIS_RS_RUNRXTD, #[doc = "Running: Waiting for receive packet"] EMAC_DMARIS_RS_RUNRXD, #[doc = "Suspended: Receive descriptor unavailable"] EMAC_DMARIS_RS_SUSPEND, #[doc = "Running: Closing receive descriptor"] EMAC_DMARIS_RS_RUNCRD, #[doc = "Writing Timestamp"] EMAC_DMARIS_RS_TSWS, #[doc = "Running: Transferring the receive packet data from receive buffer to host memory"] EMAC_DMARIS_RS_RUNTXD, #[doc = r"Reserved"] _Reserved(u8), } impl EMAC_DMARIS_RSR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { EMAC_DMARIS_RSR::EMAC_DMARIS_RS_STOP => 0, EMAC_DMARIS_RSR::EMAC_DMARIS_RS_RUNRXTD => 1, EMAC_DMARIS_RSR::EMAC_DMARIS_RS_RUNRXD => 3, EMAC_DMARIS_RSR::EMAC_DMARIS_RS_SUSPEND => 4, EMAC_DMARIS_RSR::EMAC_DMARIS_RS_RUNCRD => 5, EMAC_DMARIS_RSR::EMAC_DMARIS_RS_TSWS => 6, EMAC_DMARIS_RSR::EMAC_DMARIS_RS_RUNTXD => 7, EMAC_DMARIS_RSR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> EMAC_DMARIS_RSR { match value { 0 => EMAC_DMARIS_RSR::EMAC_DMARIS_RS_STOP, 1 => EMAC_DMARIS_RSR::EMAC_DMARIS_RS_RUNRXTD, 3 => EMAC_DMARIS_RSR::EMAC_DMARIS_RS_RUNRXD, 4 => EMAC_DMARIS_RSR::EMAC_DMARIS_RS_SUSPEND, 5 => EMAC_DMARIS_RSR::EMAC_DMARIS_RS_RUNCRD, 6 => EMAC_DMARIS_RSR::EMAC_DMARIS_RS_TSWS, 7 => EMAC_DMARIS_RSR::EMAC_DMARIS_RS_RUNTXD, i => EMAC_DMARIS_RSR::_Reserved(i), } } #[doc = "Checks if the value of the field is `EMAC_DMARIS_RS_STOP`"] #[inline(always)] pub fn is_emac_dmaris_rs_stop(&self) -> bool { *self == EMAC_DMARIS_RSR::EMAC_DMARIS_RS_STOP } #[doc = "Checks if the value of the field is `EMAC_DMARIS_RS_RUNRXTD`"] #[inline(always)] pub fn is_emac_dmaris_rs_runrxtd(&self) -> bool { *self == EMAC_DMARIS_RSR::EMAC_DMARIS_RS_RUNRXTD } #[doc = "Checks if the value of the field is `EMAC_DMARIS_RS_RUNRXD`"] #[inline(always)] pub fn is_emac_dmaris_rs_runrxd(&self) -> bool { *self == EMAC_DMARIS_RSR::EMAC_DMARIS_RS_RUNRXD } #[doc = "Checks if the value of the field is `EMAC_DMARIS_RS_SUSPEND`"] #[inline(always)] pub fn is_emac_dmaris_rs_suspend(&self) -> bool { *self == EMAC_DMARIS_RSR::EMAC_DMARIS_RS_SUSPEND } #[doc = "Checks if the value of the field is `EMAC_DMARIS_RS_RUNCRD`"] #[inline(always)] pub fn is_emac_dmaris_rs_runcrd(&self) -> bool { *self == EMAC_DMARIS_RSR::EMAC_DMARIS_RS_RUNCRD } #[doc = "Checks if the value of the field is `EMAC_DMARIS_RS_TSWS`"] #[inline(always)] pub fn is_emac_dmaris_rs_tsws(&self) -> bool { *self == EMAC_DMARIS_RSR::EMAC_DMARIS_RS_TSWS } #[doc = "Checks if the value of the field is `EMAC_DMARIS_RS_RUNTXD`"] #[inline(always)] pub fn is_emac_dmaris_rs_runtxd(&self) -> bool { *self == EMAC_DMARIS_RSR::EMAC_DMARIS_RS_RUNTXD } } #[doc = "Values that can be written to the field `EMAC_DMARIS_RS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EMAC_DMARIS_RSW { #[doc = "Stopped: Reset or stop receive command issued"] EMAC_DMARIS_RS_STOP, #[doc = "Running: Fetching receive transfer descriptor"] EMAC_DMARIS_RS_RUNRXTD, #[doc = "Running: Waiting for receive packet"] EMAC_DMARIS_RS_RUNRXD, #[doc = "Suspended: Receive descriptor unavailable"] EMAC_DMARIS_RS_SUSPEND, #[doc = "Running: Closing receive descriptor"] EMAC_DMARIS_RS_RUNCRD, #[doc = "Writing Timestamp"] EMAC_DMARIS_RS_TSWS, #[doc = "Running: Transferring the receive packet data from receive buffer to host memory"] EMAC_DMARIS_RS_RUNTXD, } impl EMAC_DMARIS_RSW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { EMAC_DMARIS_RSW::EMAC_DMARIS_RS_STOP => 0, EMAC_DMARIS_RSW::EMAC_DMARIS_RS_RUNRXTD => 1, EMAC_DMARIS_RSW::EMAC_DMARIS_RS_RUNRXD => 3, EMAC_DMARIS_RSW::EMAC_DMARIS_RS_SUSPEND => 4, EMAC_DMARIS_RSW::EMAC_DMARIS_RS_RUNCRD => 5, EMAC_DMARIS_RSW::EMAC_DMARIS_RS_TSWS => 6, EMAC_DMARIS_RSW::EMAC_DMARIS_RS_RUNTXD => 7, } } } #[doc = r"Proxy"] pub struct _EMAC_DMARIS_RSW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_RSW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EMAC_DMARIS_RSW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Stopped: Reset or stop receive command issued"] #[inline(always)] pub fn emac_dmaris_rs_stop(self) -> &'a mut W { self.variant(EMAC_DMARIS_RSW::EMAC_DMARIS_RS_STOP) } #[doc = "Running: Fetching receive transfer descriptor"] #[inline(always)] pub fn emac_dmaris_rs_runrxtd(self) -> &'a mut W { self.variant(EMAC_DMARIS_RSW::EMAC_DMARIS_RS_RUNRXTD) } #[doc = "Running: Waiting for receive packet"] #[inline(always)] pub fn emac_dmaris_rs_runrxd(self) -> &'a mut W { self.variant(EMAC_DMARIS_RSW::EMAC_DMARIS_RS_RUNRXD) } #[doc = "Suspended: Receive descriptor unavailable"] #[inline(always)] pub fn emac_dmaris_rs_suspend(self) -> &'a mut W { self.variant(EMAC_DMARIS_RSW::EMAC_DMARIS_RS_SUSPEND) } #[doc = "Running: Closing receive descriptor"] #[inline(always)] pub fn emac_dmaris_rs_runcrd(self) -> &'a mut W { self.variant(EMAC_DMARIS_RSW::EMAC_DMARIS_RS_RUNCRD) } #[doc = "Writing Timestamp"] #[inline(always)] pub fn emac_dmaris_rs_tsws(self) -> &'a mut W { self.variant(EMAC_DMARIS_RSW::EMAC_DMARIS_RS_TSWS) } #[doc = "Running: Transferring the receive packet data from receive buffer to host memory"] #[inline(always)] pub fn emac_dmaris_rs_runtxd(self) -> &'a mut W { self.variant(EMAC_DMARIS_RSW::EMAC_DMARIS_RS_RUNTXD) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(7 << 17); self.w.bits |= ((value as u32) & 7) << 17; self.w } } #[doc = "Possible values of the field `EMAC_DMARIS_TS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EMAC_DMARIS_TSR { #[doc = "Stopped; Reset or Stop transmit command processed"] EMAC_DMARIS_TS_STOP, #[doc = "Running; Fetching transmit transfer descriptor"] EMAC_DMARIS_TS_RUNTXTD, #[doc = "Running; Waiting for status"] EMAC_DMARIS_TS_STATUS, #[doc = "Running; Reading data from host memory buffer and queuing it to transmit buffer (TX FIFO)"] EMAC_DMARIS_TS_RUNTX, #[doc = "Writing Timestamp"] EMAC_DMARIS_TS_TSTAMP, #[doc = "Suspended; Transmit descriptor unavailable or transmit buffer underflow"] EMAC_DMARIS_TS_SUSPEND, #[doc = "Running; Closing transmit descriptor"] EMAC_DMARIS_TS_RUNCTD, #[doc = r"Reserved"] _Reserved(u8), } impl EMAC_DMARIS_TSR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { EMAC_DMARIS_TSR::EMAC_DMARIS_TS_STOP => 0, EMAC_DMARIS_TSR::EMAC_DMARIS_TS_RUNTXTD => 1, EMAC_DMARIS_TSR::EMAC_DMARIS_TS_STATUS => 2, EMAC_DMARIS_TSR::EMAC_DMARIS_TS_RUNTX => 3, EMAC_DMARIS_TSR::EMAC_DMARIS_TS_TSTAMP => 4, EMAC_DMARIS_TSR::EMAC_DMARIS_TS_SUSPEND => 6, EMAC_DMARIS_TSR::EMAC_DMARIS_TS_RUNCTD => 7, EMAC_DMARIS_TSR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> EMAC_DMARIS_TSR { match value { 0 => EMAC_DMARIS_TSR::EMAC_DMARIS_TS_STOP, 1 => EMAC_DMARIS_TSR::EMAC_DMARIS_TS_RUNTXTD, 2 => EMAC_DMARIS_TSR::EMAC_DMARIS_TS_STATUS, 3 => EMAC_DMARIS_TSR::EMAC_DMARIS_TS_RUNTX, 4 => EMAC_DMARIS_TSR::EMAC_DMARIS_TS_TSTAMP, 6 => EMAC_DMARIS_TSR::EMAC_DMARIS_TS_SUSPEND, 7 => EMAC_DMARIS_TSR::EMAC_DMARIS_TS_RUNCTD, i => EMAC_DMARIS_TSR::_Reserved(i), } } #[doc = "Checks if the value of the field is `EMAC_DMARIS_TS_STOP`"] #[inline(always)] pub fn is_emac_dmaris_ts_stop(&self) -> bool { *self == EMAC_DMARIS_TSR::EMAC_DMARIS_TS_STOP } #[doc = "Checks if the value of the field is `EMAC_DMARIS_TS_RUNTXTD`"] #[inline(always)] pub fn is_emac_dmaris_ts_runtxtd(&self) -> bool { *self == EMAC_DMARIS_TSR::EMAC_DMARIS_TS_RUNTXTD } #[doc = "Checks if the value of the field is `EMAC_DMARIS_TS_STATUS`"] #[inline(always)] pub fn is_emac_dmaris_ts_status(&self) -> bool { *self == EMAC_DMARIS_TSR::EMAC_DMARIS_TS_STATUS } #[doc = "Checks if the value of the field is `EMAC_DMARIS_TS_RUNTX`"] #[inline(always)] pub fn is_emac_dmaris_ts_runtx(&self) -> bool { *self == EMAC_DMARIS_TSR::EMAC_DMARIS_TS_RUNTX } #[doc = "Checks if the value of the field is `EMAC_DMARIS_TS_TSTAMP`"] #[inline(always)] pub fn is_emac_dmaris_ts_tstamp(&self) -> bool { *self == EMAC_DMARIS_TSR::EMAC_DMARIS_TS_TSTAMP } #[doc = "Checks if the value of the field is `EMAC_DMARIS_TS_SUSPEND`"] #[inline(always)] pub fn is_emac_dmaris_ts_suspend(&self) -> bool { *self == EMAC_DMARIS_TSR::EMAC_DMARIS_TS_SUSPEND } #[doc = "Checks if the value of the field is `EMAC_DMARIS_TS_RUNCTD`"] #[inline(always)] pub fn is_emac_dmaris_ts_runctd(&self) -> bool { *self == EMAC_DMARIS_TSR::EMAC_DMARIS_TS_RUNCTD } } #[doc = "Values that can be written to the field `EMAC_DMARIS_TS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EMAC_DMARIS_TSW { #[doc = "Stopped; Reset or Stop transmit command processed"] EMAC_DMARIS_TS_STOP, #[doc = "Running; Fetching transmit transfer descriptor"] EMAC_DMARIS_TS_RUNTXTD, #[doc = "Running; Waiting for status"] EMAC_DMARIS_TS_STATUS, #[doc = "Running; Reading data from host memory buffer and queuing it to transmit buffer (TX FIFO)"] EMAC_DMARIS_TS_RUNTX, #[doc = "Writing Timestamp"] EMAC_DMARIS_TS_TSTAMP, #[doc = "Suspended; Transmit descriptor unavailable or transmit buffer underflow"] EMAC_DMARIS_TS_SUSPEND, #[doc = "Running; Closing transmit descriptor"] EMAC_DMARIS_TS_RUNCTD, } impl EMAC_DMARIS_TSW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { EMAC_DMARIS_TSW::EMAC_DMARIS_TS_STOP => 0, EMAC_DMARIS_TSW::EMAC_DMARIS_TS_RUNTXTD => 1, EMAC_DMARIS_TSW::EMAC_DMARIS_TS_STATUS => 2, EMAC_DMARIS_TSW::EMAC_DMARIS_TS_RUNTX => 3, EMAC_DMARIS_TSW::EMAC_DMARIS_TS_TSTAMP => 4, EMAC_DMARIS_TSW::EMAC_DMARIS_TS_SUSPEND => 6, EMAC_DMARIS_TSW::EMAC_DMARIS_TS_RUNCTD => 7, } } } #[doc = r"Proxy"] pub struct _EMAC_DMARIS_TSW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_TSW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EMAC_DMARIS_TSW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Stopped; Reset or Stop transmit command processed"] #[inline(always)] pub fn emac_dmaris_ts_stop(self) -> &'a mut W { self.variant(EMAC_DMARIS_TSW::EMAC_DMARIS_TS_STOP) } #[doc = "Running; Fetching transmit transfer descriptor"] #[inline(always)] pub fn emac_dmaris_ts_runtxtd(self) -> &'a mut W { self.variant(EMAC_DMARIS_TSW::EMAC_DMARIS_TS_RUNTXTD) } #[doc = "Running; Waiting for status"] #[inline(always)] pub fn emac_dmaris_ts_status(self) -> &'a mut W { self.variant(EMAC_DMARIS_TSW::EMAC_DMARIS_TS_STATUS) } #[doc = "Running; Reading data from host memory buffer and queuing it to transmit buffer (TX FIFO)"] #[inline(always)] pub fn emac_dmaris_ts_runtx(self) -> &'a mut W { self.variant(EMAC_DMARIS_TSW::EMAC_DMARIS_TS_RUNTX) } #[doc = "Writing Timestamp"] #[inline(always)] pub fn emac_dmaris_ts_tstamp(self) -> &'a mut W { self.variant(EMAC_DMARIS_TSW::EMAC_DMARIS_TS_TSTAMP) } #[doc = "Suspended; Transmit descriptor unavailable or transmit buffer underflow"] #[inline(always)] pub fn emac_dmaris_ts_suspend(self) -> &'a mut W { self.variant(EMAC_DMARIS_TSW::EMAC_DMARIS_TS_SUSPEND) } #[doc = "Running; Closing transmit descriptor"] #[inline(always)] pub fn emac_dmaris_ts_runctd(self) -> &'a mut W { self.variant(EMAC_DMARIS_TSW::EMAC_DMARIS_TS_RUNCTD) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(7 << 20); self.w.bits |= ((value as u32) & 7) << 20; self.w } } #[doc = "Possible values of the field `EMAC_DMARIS_AE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EMAC_DMARIS_AER { #[doc = "Error during RX DMA Write Data Transfer"] EMAC_DMARIS_AE_RXDMAWD, #[doc = "Error during TX DMA Read Data Transfer"] EMAC_DMARIS_AE_TXDMARD, #[doc = "Error during RX DMA Descriptor Write Access"] EMAC_DMARIS_AE_RXDMADW, #[doc = "Error during TX DMA Descriptor Write Access"] EMAC_DMARIS_AE_TXDMADW, #[doc = "Error during RX DMA Descriptor Read Access"] EMAC_DMARIS_AE_RXDMADR, #[doc = "Error during TX DMA Descriptor Read Access"] EMAC_DMARIS_AE_TXDMADR, #[doc = r"Reserved"] _Reserved(u8), } impl EMAC_DMARIS_AER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { EMAC_DMARIS_AER::EMAC_DMARIS_AE_RXDMAWD => 0, EMAC_DMARIS_AER::EMAC_DMARIS_AE_TXDMARD => 3, EMAC_DMARIS_AER::EMAC_DMARIS_AE_RXDMADW => 4, EMAC_DMARIS_AER::EMAC_DMARIS_AE_TXDMADW => 5, EMAC_DMARIS_AER::EMAC_DMARIS_AE_RXDMADR => 6, EMAC_DMARIS_AER::EMAC_DMARIS_AE_TXDMADR => 7, EMAC_DMARIS_AER::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> EMAC_DMARIS_AER { match value { 0 => EMAC_DMARIS_AER::EMAC_DMARIS_AE_RXDMAWD, 3 => EMAC_DMARIS_AER::EMAC_DMARIS_AE_TXDMARD, 4 => EMAC_DMARIS_AER::EMAC_DMARIS_AE_RXDMADW, 5 => EMAC_DMARIS_AER::EMAC_DMARIS_AE_TXDMADW, 6 => EMAC_DMARIS_AER::EMAC_DMARIS_AE_RXDMADR, 7 => EMAC_DMARIS_AER::EMAC_DMARIS_AE_TXDMADR, i => EMAC_DMARIS_AER::_Reserved(i), } } #[doc = "Checks if the value of the field is `EMAC_DMARIS_AE_RXDMAWD`"] #[inline(always)] pub fn is_emac_dmaris_ae_rxdmawd(&self) -> bool { *self == EMAC_DMARIS_AER::EMAC_DMARIS_AE_RXDMAWD } #[doc = "Checks if the value of the field is `EMAC_DMARIS_AE_TXDMARD`"] #[inline(always)] pub fn is_emac_dmaris_ae_txdmard(&self) -> bool { *self == EMAC_DMARIS_AER::EMAC_DMARIS_AE_TXDMARD } #[doc = "Checks if the value of the field is `EMAC_DMARIS_AE_RXDMADW`"] #[inline(always)] pub fn is_emac_dmaris_ae_rxdmadw(&self) -> bool { *self == EMAC_DMARIS_AER::EMAC_DMARIS_AE_RXDMADW } #[doc = "Checks if the value of the field is `EMAC_DMARIS_AE_TXDMADW`"] #[inline(always)] pub fn is_emac_dmaris_ae_txdmadw(&self) -> bool { *self == EMAC_DMARIS_AER::EMAC_DMARIS_AE_TXDMADW } #[doc = "Checks if the value of the field is `EMAC_DMARIS_AE_RXDMADR`"] #[inline(always)] pub fn is_emac_dmaris_ae_rxdmadr(&self) -> bool { *self == EMAC_DMARIS_AER::EMAC_DMARIS_AE_RXDMADR } #[doc = "Checks if the value of the field is `EMAC_DMARIS_AE_TXDMADR`"] #[inline(always)] pub fn is_emac_dmaris_ae_txdmadr(&self) -> bool { *self == EMAC_DMARIS_AER::EMAC_DMARIS_AE_TXDMADR } } #[doc = "Values that can be written to the field `EMAC_DMARIS_AE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EMAC_DMARIS_AEW { #[doc = "Error during RX DMA Write Data Transfer"] EMAC_DMARIS_AE_RXDMAWD, #[doc = "Error during TX DMA Read Data Transfer"] EMAC_DMARIS_AE_TXDMARD, #[doc = "Error during RX DMA Descriptor Write Access"] EMAC_DMARIS_AE_RXDMADW, #[doc = "Error during TX DMA Descriptor Write Access"] EMAC_DMARIS_AE_TXDMADW, #[doc = "Error during RX DMA Descriptor Read Access"] EMAC_DMARIS_AE_RXDMADR, #[doc = "Error during TX DMA Descriptor Read Access"] EMAC_DMARIS_AE_TXDMADR, } impl EMAC_DMARIS_AEW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { EMAC_DMARIS_AEW::EMAC_DMARIS_AE_RXDMAWD => 0, EMAC_DMARIS_AEW::EMAC_DMARIS_AE_TXDMARD => 3, EMAC_DMARIS_AEW::EMAC_DMARIS_AE_RXDMADW => 4, EMAC_DMARIS_AEW::EMAC_DMARIS_AE_TXDMADW => 5, EMAC_DMARIS_AEW::EMAC_DMARIS_AE_RXDMADR => 6, EMAC_DMARIS_AEW::EMAC_DMARIS_AE_TXDMADR => 7, } } } #[doc = r"Proxy"] pub struct _EMAC_DMARIS_AEW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_AEW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EMAC_DMARIS_AEW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Error during RX DMA Write Data Transfer"] #[inline(always)] pub fn emac_dmaris_ae_rxdmawd(self) -> &'a mut W { self.variant(EMAC_DMARIS_AEW::EMAC_DMARIS_AE_RXDMAWD) } #[doc = "Error during TX DMA Read Data Transfer"] #[inline(always)] pub fn emac_dmaris_ae_txdmard(self) -> &'a mut W { self.variant(EMAC_DMARIS_AEW::EMAC_DMARIS_AE_TXDMARD) } #[doc = "Error during RX DMA Descriptor Write Access"] #[inline(always)] pub fn emac_dmaris_ae_rxdmadw(self) -> &'a mut W { self.variant(EMAC_DMARIS_AEW::EMAC_DMARIS_AE_RXDMADW) } #[doc = "Error during TX DMA Descriptor Write Access"] #[inline(always)] pub fn emac_dmaris_ae_txdmadw(self) -> &'a mut W { self.variant(EMAC_DMARIS_AEW::EMAC_DMARIS_AE_TXDMADW) } #[doc = "Error during RX DMA Descriptor Read Access"] #[inline(always)] pub fn emac_dmaris_ae_rxdmadr(self) -> &'a mut W { self.variant(EMAC_DMARIS_AEW::EMAC_DMARIS_AE_RXDMADR) } #[doc = "Error during TX DMA Descriptor Read Access"] #[inline(always)] pub fn emac_dmaris_ae_txdmadr(self) -> &'a mut W { self.variant(EMAC_DMARIS_AEW::EMAC_DMARIS_AE_TXDMADR) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(7 << 23); self.w.bits |= ((value as u32) & 7) << 23; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_MMCR { bits: bool, } impl EMAC_DMARIS_MMCR { #[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 _EMAC_DMARIS_MMCW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_MMCW<'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 } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_PMTR { bits: bool, } impl EMAC_DMARIS_PMTR { #[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 _EMAC_DMARIS_PMTW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_PMTW<'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 << 28); self.w.bits |= ((value as u32) & 1) << 28; self.w } } #[doc = r"Value of the field"] pub struct EMAC_DMARIS_TTR { bits: bool, } impl EMAC_DMARIS_TTR { #[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 _EMAC_DMARIS_TTW<'a> { w: &'a mut W, } impl<'a> _EMAC_DMARIS_TTW<'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 << 29); self.w.bits |= ((value as u32) & 1) << 29; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Transmit Interrupt"] #[inline(always)] pub fn emac_dmaris_ti(&self) -> EMAC_DMARIS_TIR { let bits = ((self.bits >> 0) & 1) != 0; EMAC_DMARIS_TIR { bits } } #[doc = "Bit 1 - Transmit Process Stopped"] #[inline(always)] pub fn emac_dmaris_tps(&self) -> EMAC_DMARIS_TPSR { let bits = ((self.bits >> 1) & 1) != 0; EMAC_DMARIS_TPSR { bits } } #[doc = "Bit 2 - Transmit Buffer Unavailable"] #[inline(always)] pub fn emac_dmaris_tu(&self) -> EMAC_DMARIS_TUR { let bits = ((self.bits >> 2) & 1) != 0; EMAC_DMARIS_TUR { bits } } #[doc = "Bit 3 - Transmit Jabber Timeout"] #[inline(always)] pub fn emac_dmaris_tjt(&self) -> EMAC_DMARIS_TJTR { let bits = ((self.bits >> 3) & 1) != 0; EMAC_DMARIS_TJTR { bits } } #[doc = "Bit 4 - Receive Overflow"] #[inline(always)] pub fn emac_dmaris_ovf(&self) -> EMAC_DMARIS_OVFR { let bits = ((self.bits >> 4) & 1) != 0; EMAC_DMARIS_OVFR { bits } } #[doc = "Bit 5 - Transmit Underflow"] #[inline(always)] pub fn emac_dmaris_unf(&self) -> EMAC_DMARIS_UNFR { let bits = ((self.bits >> 5) & 1) != 0; EMAC_DMARIS_UNFR { bits } } #[doc = "Bit 6 - Receive Interrupt"] #[inline(always)] pub fn emac_dmaris_ri(&self) -> EMAC_DMARIS_RIR { let bits = ((self.bits >> 6) & 1) != 0; EMAC_DMARIS_RIR { bits } } #[doc = "Bit 7 - Receive Buffer Unavailable"] #[inline(always)] pub fn emac_dmaris_ru(&self) -> EMAC_DMARIS_RUR { let bits = ((self.bits >> 7) & 1) != 0; EMAC_DMARIS_RUR { bits } } #[doc = "Bit 8 - Receive Process Stopped"] #[inline(always)] pub fn emac_dmaris_rps(&self) -> EMAC_DMARIS_RPSR { let bits = ((self.bits >> 8) & 1) != 0; EMAC_DMARIS_RPSR { bits } } #[doc = "Bit 9 - Receive Watchdog Timeout"] #[inline(always)] pub fn emac_dmaris_rwt(&self) -> EMAC_DMARIS_RWTR { let bits = ((self.bits >> 9) & 1) != 0; EMAC_DMARIS_RWTR { bits } } #[doc = "Bit 10 - Early Transmit Interrupt"] #[inline(always)] pub fn emac_dmaris_eti(&self) -> EMAC_DMARIS_ETIR { let bits = ((self.bits >> 10) & 1) != 0; EMAC_DMARIS_ETIR { bits } } #[doc = "Bit 13 - Fatal Bus Error Interrupt"] #[inline(always)] pub fn emac_dmaris_fbi(&self) -> EMAC_DMARIS_FBIR { let bits = ((self.bits >> 13) & 1) != 0; EMAC_DMARIS_FBIR { bits } } #[doc = "Bit 14 - Early Receive Interrupt"] #[inline(always)] pub fn emac_dmaris_eri(&self) -> EMAC_DMARIS_ERIR { let bits = ((self.bits >> 14) & 1) != 0; EMAC_DMARIS_ERIR { bits } } #[doc = "Bit 15 - Abnormal Interrupt Summary"] #[inline(always)] pub fn emac_dmaris_ais(&self) -> EMAC_DMARIS_AISR { let bits = ((self.bits >> 15) & 1) != 0; EMAC_DMARIS_AISR { bits } } #[doc = "Bit 16 - Normal Interrupt Summary"] #[inline(always)] pub fn emac_dmaris_nis(&self) -> EMAC_DMARIS_NISR { let bits = ((self.bits >> 16) & 1) != 0; EMAC_DMARIS_NISR { bits } } #[doc = "Bits 17:19 - Received Process State"] #[inline(always)] pub fn emac_dmaris_rs(&self) -> EMAC_DMARIS_RSR { EMAC_DMARIS_RSR::_from(((self.bits >> 17) & 7) as u8) } #[doc = "Bits 20:22 - Transmit Process State"] #[inline(always)] pub fn emac_dmaris_ts(&self) -> EMAC_DMARIS_TSR { EMAC_DMARIS_TSR::_from(((self.bits >> 20) & 7) as u8) } #[doc = "Bits 23:25 - Access Error"] #[inline(always)] pub fn emac_dmaris_ae(&self) -> EMAC_DMARIS_AER { EMAC_DMARIS_AER::_from(((self.bits >> 23) & 7) as u8) } #[doc = "Bit 27 - MAC MMC Interrupt"] #[inline(always)] pub fn emac_dmaris_mmc(&self) -> EMAC_DMARIS_MMCR { let bits = ((self.bits >> 27) & 1) != 0; EMAC_DMARIS_MMCR { bits } } #[doc = "Bit 28 - MAC PMT Interrupt Status"] #[inline(always)] pub fn emac_dmaris_pmt(&self) -> EMAC_DMARIS_PMTR { let bits = ((self.bits >> 28) & 1) != 0; EMAC_DMARIS_PMTR { bits } } #[doc = "Bit 29 - Timestamp Trigger Interrupt Status"] #[inline(always)] pub fn emac_dmaris_tt(&self) -> EMAC_DMARIS_TTR { let bits = ((self.bits >> 29) & 1) != 0; EMAC_DMARIS_TTR { 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 = "Bit 0 - Transmit Interrupt"] #[inline(always)] pub fn emac_dmaris_ti(&mut self) -> _EMAC_DMARIS_TIW { _EMAC_DMARIS_TIW { w: self } } #[doc = "Bit 1 - Transmit Process Stopped"] #[inline(always)] pub fn emac_dmaris_tps(&mut self) -> _EMAC_DMARIS_TPSW { _EMAC_DMARIS_TPSW { w: self } } #[doc = "Bit 2 - Transmit Buffer Unavailable"] #[inline(always)] pub fn emac_dmaris_tu(&mut self) -> _EMAC_DMARIS_TUW { _EMAC_DMARIS_TUW { w: self } } #[doc = "Bit 3 - Transmit Jabber Timeout"] #[inline(always)] pub fn emac_dmaris_tjt(&mut self) -> _EMAC_DMARIS_TJTW { _EMAC_DMARIS_TJTW { w: self } } #[doc = "Bit 4 - Receive Overflow"] #[inline(always)] pub fn emac_dmaris_ovf(&mut self) -> _EMAC_DMARIS_OVFW { _EMAC_DMARIS_OVFW { w: self } } #[doc = "Bit 5 - Transmit Underflow"] #[inline(always)] pub fn emac_dmaris_unf(&mut self) -> _EMAC_DMARIS_UNFW { _EMAC_DMARIS_UNFW { w: self } } #[doc = "Bit 6 - Receive Interrupt"] #[inline(always)] pub fn emac_dmaris_ri(&mut self) -> _EMAC_DMARIS_RIW { _EMAC_DMARIS_RIW { w: self } } #[doc = "Bit 7 - Receive Buffer Unavailable"] #[inline(always)] pub fn emac_dmaris_ru(&mut self) -> _EMAC_DMARIS_RUW { _EMAC_DMARIS_RUW { w: self } } #[doc = "Bit 8 - Receive Process Stopped"] #[inline(always)] pub fn emac_dmaris_rps(&mut self) -> _EMAC_DMARIS_RPSW { _EMAC_DMARIS_RPSW { w: self } } #[doc = "Bit 9 - Receive Watchdog Timeout"] #[inline(always)] pub fn emac_dmaris_rwt(&mut self) -> _EMAC_DMARIS_RWTW { _EMAC_DMARIS_RWTW { w: self } } #[doc = "Bit 10 - Early Transmit Interrupt"] #[inline(always)] pub fn emac_dmaris_eti(&mut self) -> _EMAC_DMARIS_ETIW { _EMAC_DMARIS_ETIW { w: self } } #[doc = "Bit 13 - Fatal Bus Error Interrupt"] #[inline(always)] pub fn emac_dmaris_fbi(&mut self) -> _EMAC_DMARIS_FBIW { _EMAC_DMARIS_FBIW { w: self } } #[doc = "Bit 14 - Early Receive Interrupt"] #[inline(always)] pub fn emac_dmaris_eri(&mut self) -> _EMAC_DMARIS_ERIW { _EMAC_DMARIS_ERIW { w: self } } #[doc = "Bit 15 - Abnormal Interrupt Summary"] #[inline(always)] pub fn emac_dmaris_ais(&mut self) -> _EMAC_DMARIS_AISW { _EMAC_DMARIS_AISW { w: self } } #[doc = "Bit 16 - Normal Interrupt Summary"] #[inline(always)] pub fn emac_dmaris_nis(&mut self) -> _EMAC_DMARIS_NISW { _EMAC_DMARIS_NISW { w: self } } #[doc = "Bits 17:19 - Received Process State"] #[inline(always)] pub fn emac_dmaris_rs(&mut self) -> _EMAC_DMARIS_RSW { _EMAC_DMARIS_RSW { w: self } } #[doc = "Bits 20:22 - Transmit Process State"] #[inline(always)] pub fn emac_dmaris_ts(&mut self) -> _EMAC_DMARIS_TSW { _EMAC_DMARIS_TSW { w: self } } #[doc = "Bits 23:25 - Access Error"] #[inline(always)] pub fn emac_dmaris_ae(&mut self) -> _EMAC_DMARIS_AEW { _EMAC_DMARIS_AEW { w: self } } #[doc = "Bit 27 - MAC MMC Interrupt"] #[inline(always)] pub fn emac_dmaris_mmc(&mut self) -> _EMAC_DMARIS_MMCW { _EMAC_DMARIS_MMCW { w: self } } #[doc = "Bit 28 - MAC PMT Interrupt Status"] #[inline(always)] pub fn emac_dmaris_pmt(&mut self) -> _EMAC_DMARIS_PMTW { _EMAC_DMARIS_PMTW { w: self } } #[doc = "Bit 29 - Timestamp Trigger Interrupt Status"] #[inline(always)] pub fn emac_dmaris_tt(&mut self) -> _EMAC_DMARIS_TTW { _EMAC_DMARIS_TTW { w: self } } }
use std::fs::File; use std::io::{BufReader, Read}; use bencode::FromBencode; use serde_bencode::de; use serde_bytes::ByteBuf; use serde_derive::Deserialize; fn main() { // let s = TorrentFile { announce: "http://bttracker.debian.org:6969/announce".to_string(), info: Info { name: "debian-10.3.0-amd64-netinst.iso".to_string(), piece_length: 262144, length: 351272960, pieces } }; let mut file = File::open("debian-10.3.0-amd64-netinst.iso.torrent").unwrap(); let mut buf_reader = BufReader::new(file); let mut vec = Vec::<u8>::new(); buf_reader.read_to_end(&mut vec); // let vec_clone = vec.clone(); // stream_parse(vec); // let bencode: bencode::Bencode = bencode::from_vec(vec_clone).unwrap(); // let result: TorrentFile = FromBencode::from_bencode(&bencode).unwrap(); // assert_eq!(s, result); }
use onnx_pb::ModelProto; use prost::Message; use crate::shape_inference_proto; /// Error type. #[derive(Debug)] pub enum Error { /// Decode error. Decode(prost::DecodeError), /// Encode error. Encode(prost::EncodeError), } /// Infers model shapes. pub fn shape_inference(model: &ModelProto) -> Result<ModelProto, Error> { let mut body = Vec::new(); model.encode(&mut body).map_err(|e| Error::Encode(e))?; let inferred = shape_inference_proto(body.as_slice()); ModelProto::decode(inferred.as_slice()).map_err(|e| Error::Decode(e)) }
use std::collections::HashMap; pub type Id = i32; pub type UUID = String; pub type Urgency = f32; /// static std::string defaultProject; static default_project: &str = ""; /// static std::string defaultDue static default_due: &str = ""; /// static std::string defaultScheduled; static default_scheduled: &str = ""; /// static bool searchCaseSensitive; static search_case_sensitive: bool = true; /// static bool regex; static regex: bool = false; /// static std::map <std::string, std::string> attributes; // name -> type // TODO this is suposed to be a hashmap literal. Find alternative // static attributes: HashMap<String, String>, // name -> type /// static std::map <std::string, float> coefficients; // TODO this is suposed to be a hashmap literal. Find alternative // static coefficients: HashMap<String, f32>, /// static std::map <std::string, std::vector <std::string>> customOrder; // TODO this is suposed to be a hashmap literal. Find alternative // static custom_order: HashMap<String, Vec<String>>, /// static float urgencyProjectCoefficient; pub static urgency_project_coefficient: Urgency = 0.0; /// static float urgencyActiveCoefficient; pub static urgency_active_coefficient: Urgency = 0.0; /// static float urgencyScheduledCoefficient; pub static urgency_scheduled_coefficient: Urgency = 0.0; /// static float urgencyWaitingCoefficient; pub static urgency_waiting_coefficient: Urgency = 0.0; /// static float urgencyBlockedCoefficient; pub static urgency_blocked_coefficient: Urgency = 0.0; /// static float urgencyAnnotationsCoefficient; pub static urgency_annotations_coefficient: Urgency = 0.0; /// static float urgencyTagsCoefficient; pub static urgency_tags_coefficient: Urgency = 0.0; /// static float urgencyDueCoefficient; pub static urgency_due_coefficient: Urgency = 0.0; /// static float urgencyBlockingCoefficient; pub static urgency_blocking_coefficient: Urgency = 0.0; /// static float urgencyAgeCoefficient; pub static urgency_age_coefficient: Urgency = 0.0; /// static float urgencyAgeMax; pub static urgency_age_max: Urgency = 0.0; /// static const std::string dummy (""); const dummy: &str = ""; pub struct Task { /// std::map <std::string, std::string> data {}; data: HashMap<String, String>, /// int id {0}; id: Id, /// float urgency_value {0.0}; urgency_value: Urgency, /// bool recalc_urgency {true}; recalc_urgency: bool, /// bool is_blocked {false}; is_blocked: bool, /// bool is_blocking {false}; is_blocking: bool, /// int annotation_count {0}; // TODO why not unsigned? annotation_count: i32, } /// enum status {pending, completed, deleted, recurring, waiting}; pub enum Status { Pending, Completed, Deleted, Recurring, Waiting, } /// enum dateState {dateNotDue, dateAfterToday, dateLaterToday, dateEarlierToday, dateBeforeToday}; pub enum DateState { DateNotDue, DateAfterToday, DateLaterToday, DateEarlierToday, DateBeforeToday, } /// enum modType {modReplace, modPrepend, modAppend, modAnnotate}; pub enum ModType { ModReplace, ModPrepend, ModAppend, ModAnnotate, } impl Status { /// static status textToStatus (const std::string&); pub fn from_text(rep: &str) -> Self { todo!() } /// static std::string statusToText (status); pub fn to_string(&self) -> String { todo!() } } impl Default for Task { /// Task () = default; // NOTE in the cpp version this (i think) has recalc_urgency = false due // to being simply.. defaults fn default() -> Self { Task { data: HashMap::new(), id: 0, urgency_value: 0.0, recalc_urgency: true, is_blocked: false, is_blocking: false, annotation_count: 0, } } } impl Task { /// Task (const std::string&); // TODO check https://doc.rust-lang.org/std/convert/trait.From.html // (must be infalible) pub fn from_string(input: &str) -> Self { let mut task: Task = Default::default(); task.parse(input); task } /// Task (const json::object*); pub fn from_json(obj: &str) -> Self { // TODO this is supposed to receive a "json::object*". check if can be // made with serialization // TODO check https://doc.rust-lang.org/std/convert/trait.From.html let mut task: Task = Default::default(); task.parse_json(obj); task } /// void parse (const std::string&); pub fn parse(&mut self, inp: &str) { // no idea what this does / should do todo!() } /// std::string composeF4 () const; pub fn compose_f4(&self) -> String { todo!() } /// std::string composeJSON (bool decorate = false) const; pub fn compose_json(&self, decorate: bool) -> String { // TODO check if this can be done using serialization todo!() } /// void setAsNow (const std::string&); pub fn set_as_now(&mut self, rep: &str) { todo!() } /// bool has (const std::string&) const; pub fn has(&self, smt: &str) -> bool { todo!() } /// std::vector <std::string> all (); pub fn all(&self) -> Vec<String> { todo!() } /// const std::string identifier (bool shortened = false) const; pub fn identifier(&self, shortened: bool) -> String { todo!() } /// const std::string get (const std::string&) const; pub fn get(&self, smt: &str) -> String { todo!() } /// const std::string& get_ref (const std::string&) const; pub fn get_ref(&self, smt: &str) -> &str { todo!() } /// int get_int (const std::string&) const; pub fn get_int(&self, smt: &str) -> i32 { todo!() } /// unsigned long get_ulong (const std::string&) const; pub fn get_ulong(&self, smt: &str) -> u64 { todo!() } /// float get_float (const std::string&) const; pub fn get_float(&self, smt: &str) -> f32 { todo!() } /// time_t get_date (const std::string&) const; pub fn get_date(&self, smt: &str) -> i64 { todo!() } /// void set (const std::string&, const std::string&); pub fn set_str(&mut self, smt0: &str, smt1: &str) { todo!() } /// void set (const std::string&, int); pub fn set_int(&mut self, smt0: &str, smt1: i32) { todo!() } /// void remove (const std::string&); pub fn remove(&mut self, smt0: &str) { todo!() } /// bool is_ready () const; pub fn is_ready(&self) { todo!() } /// bool is_due () const; pub fn is_due(&self) -> bool { todo!() } /// bool is_dueyesterday () const; pub fn is_due_yesterday(&self) -> bool { todo!() } /// bool is_duetoday () const; pub fn is_due_today(&self) -> bool { todo!() } /// bool is_duetomorrow () const; pub fn is_due_tomorrow(&self) -> bool { todo!() } /// bool is_dueweek () const; pub fn is_due_week(&self) -> bool { todo!() } /// bool is_duemonth () const; pub fn is_due_month(&self) -> bool { todo!() } /// bool is_duequarter () const; pub fn is_due_quarter(&self) -> bool { todo!() } /// bool is_dueyear () const; pub fn is_due_year(&self) -> bool { todo!() } /// bool is_overdue () const; pub fn is_overdue(&self) -> bool { todo!() } /// bool is_udaPresent () const; pub fn is_uda_present(&self) -> bool { todo!() } /// bool is_orphanPresent () const; pub fn is_orphan_present(&self) -> bool { todo!() } /// status getStatus () const; pub fn get_status(&self) -> Status { todo!() } ///void setStatus (status); pub fn set_status(&mut self, status: Status) { todo!() } /// dateState getDateState (const std::string&) const; pub fn get_date_state(&self, smt: &str) -> DateState { todo!() } /// int getTagCount () const; pub fn get_tag_count(&self) -> i32 { todo!() } /// bool hasTag (const std::string&) const; pub fn has_tag(&self, tag: &str) -> bool { todo!() } /// void addTag (const std::string&); pub fn add_tag(&mut self, tag: &str) { todo!() } /// void addTags (const std::vector <std::string>&); pub fn add_tags(&mut self, tags: &Vec<String>) { todo!() } /// std::vector <std::string> getTags () const; pub fn get_tags(&self) -> Vec<String> { todo!() } /// void removeTag (const std::string&); pub fn remove_tag(&mut self, tag: &str) { todo!() } /// int getAnnotationCount () const; pub fn get_annotation_count(&self) -> i32 { todo!() } /// bool hasAnnotations () const; pub fn has_annotations(&self) -> bool { todo!() } /// std::map <std::string, std::string> getAnnotations () const; pub fn get_annotations(&self) -> HashMap<String, String> { todo!() } /// void setAnnotations (const std::map <std::string, std::string>&); pub fn set_annotations(&mut self, annotations: &HashMap<String, String>) { todo!() } /// void addAnnotation (const std::string&); pub fn add_annotation(&mut self, annotation: &str) { todo!() } /// void removeAnnotations (); pub fn remove_annotations(&mut self) { todo!() } /// void addDependency (int); pub fn add_dependency_by_id(&mut self, dep: i32) { todo!() } /// void addDependency (const std::string&); pub fn add_dependency_by_uuid(&mut self, smt: &UUID) { todo!() } /// void removeDependency (int); pub fn remove_dependency_by_id(&mut self, id: Id) { todo!() } /// void removeDependency (const std::string&); pub fn remove_dependency_by_uuid(&mut self, uuid: &UUID) { todo!() } /// std::vector <int> getDependencyIDs () const; pub fn get_dependency_ids(&self) -> Vec<Id> { todo!() } /// std::vector <std::string> getDependencyUUIDs () const; pub fn get_dependency_uuids(&self) -> Vec<UUID> { todo!() } /// std::vector <Task> getDependencyTasks () const; pub fn get_dependency_tasks(&self) -> Vec<Task> { todo!() } /// std::vector <std::string> getUDAOrphanUUIDs () const; pub fn get_uda_orphan_uuids(&self) -> Vec<UUID> { todo!() } /// void substitute (const std::string&, const std::string&, const std::string&); pub fn substitute(&mut self, from: &str, to: &str, flags: &str) { todo!() } /// void validate (bool applyDefault = true); pub fn validate(&self, apply_default: bool) { todo!() } /// float urgency_c () const; pub fn urgency_c(&self) -> Urgency { todo!() } /// float urgency (); pub fn urgency(&self) -> Urgency { todo!() } /// void modify (modType, bool text_required = false); pub fn modify(&mut self, mode: ModType, text_required: bool) { todo!() } // private stuff /// int determineVersion (const std::string&); fn determine_version(&self, smt: &str) -> i32 { todo!() } /// void parseJSON (const std::string&); fn parse_json_string(&self, text: &str) { todo!() } /// void parseJSON (const json::object*); fn parse_json(&self, json: &str) { // TODO this receives a json object todo!() } /// void parseLegacy (const std::string&); fn parse_legacy(text: &str) { todo!() } /// void validate_before (const std::string&, const std::string&); fn validate_before(&self, smt0: &str, smt1: &str) {} /// const std::string encode (const std::string&) const; fn encode(&self, text: &str) -> String { todo!() } /// const std::string decode (const std::string&) const; fn decode(text: &str) -> String { todo!() } // now more public stuff /// float urgency_project () const; pub fn urgency_project(&self) -> Urgency { todo!() } /// float urgency_active () const; pub fn urgency_active(&self) -> Urgency { todo!() } /// float urgency_scheduled () const; pub fn urgency_scheduled(&self) -> Urgency { todo!() } /// float urgency_waiting () const; pub fn urgency_waiting(&self) -> Urgency { todo!() } /// float urgency_blocked () const; pub fn urgency_blocked(&self) -> Urgency { todo!() } /// float urgency_inherit () const; pub fn urgency_inherit(&self) -> Urgency { todo!() } /// float urgency_annotations () const; pub fn urgency_annotations(&self) -> Urgency { todo!() } /// float urgency_tags () const; pub fn urgency_tags(&self) -> Urgency { todo!() } /// float urgency_due () const; pub fn urgency_due(&self) -> Urgency { todo!() } /// float urgency_blocking () const; pub fn urgency_blocking(&self) -> Urgency { todo!() } /// float urgency_age () const; pub fn urgency_age(&self) -> Urgency { todo!() } } impl PartialEq for Task { /// bool operator== (const Task&); /// tasks are equal if they are a bijection without ids and uuids fn eq(&self, other: &Task) -> bool { if self.data.len() != other.data.len() { return false; } for (k, v) in &self.data { if k != "uuid" { if let Some(v_other) = other.data.get(k) { if v != v_other { // attribute present, different value return false; } } else { // missing attribute return false; } } } true } }
pub struct Solution; impl Solution { pub fn shortest_palindrome(s: String) -> String { if s.is_empty() { return s; } let bytes = s.into_bytes(); let l = bytes.len(); let nan = std::usize::MAX; let shift = { let mut shift = vec![nan; l / 2]; let mut i = 1; let mut j = 0; while i < shift.len() { if bytes[i] == bytes[j] { i += 1; j += 1; } else { if shift[i] == nan { shift[i] = j; } if shift[j] == nan { i += 1; j = 0; } else { j = shift[j]; } } } shift }; let k = { let mut i = 0; let mut j = bytes.len() - 1; while i < j { if bytes[i] == bytes[j] { i += 1; j -= 1; } else if shift[i] == nan { i = 0; j -= 1; } else { i = shift[i]; } } l - (i + j + 1) }; let mut bytes = bytes; bytes.resize(l + k, 0); for i in (0..l).rev() { bytes[i + k] = bytes[i]; } for i in 0..k { bytes[i] = bytes[l + k - 1 - i]; } String::from_utf8(bytes).unwrap() } } #[test] fn test0214() { fn case(s: &str, want: &str) { let got = Solution::shortest_palindrome(s.to_string()); assert_eq!(got, want); } case("aacecaaa", "aaacecaaa"); case("abcd", "dcbabcd"); case("", ""); }
// 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::vec::Vec; use alloc::str; pub struct CString { pub data: Vec<u8> } impl CString { pub fn New(s: &str) -> Self { let s = s.as_bytes(); let mut data = Vec::with_capacity(s.len() + 1); for i in 0..s.len() { data.push(s[i]) } data.push(0); return Self { data } } pub fn Ptr(&self) -> u64 { return &self.data[0] as *const _ as u64; } pub fn Len(&self) -> usize { return self.data.len(); } pub fn Slice(&self) -> &[u8] { return &self.data[..] } }
pub trait KtStd { fn let_ref<R>(&self, block: impl FnOnce(&Self) -> R) -> R { block(self) } fn let_mut<R>(&mut self, mut block: impl FnMut(&mut Self) -> R) -> R { block(self) } fn let_owned<R>(self, block: impl FnOnce(Self) -> R) -> R where Self: Sized { block(self) } fn also_ref(&self, block: impl FnOnce(&Self)) -> &Self { block(self); self } fn also_mut(&mut self, mut block: impl FnMut(&mut Self)) -> &mut Self { block(self); self } fn also_ref_ret_owned(self, block: impl FnOnce(&Self)) -> Self where Self: Sized { block(&self); self } fn also_mut_ret_owned(mut self, mut block: impl FnMut(&mut Self)) -> Self where Self: Sized { block(&mut self); self } } impl <T> KtStd for T {} pub trait IterExt<T> { fn on_each(&self, f: impl Fn(&T)) -> &Self; } impl<T> IterExt<T> for Vec<T> { fn on_each(&self, f: impl Fn(&T)) -> &Self { self.also_ref(|v| v.iter().for_each(|e| f(e))) } }
use opentelemetry::trace::StatusCode; use std::{fmt::Display, str::FromStr}; pub(crate) enum Status { Success, Failure, } impl Display for Status { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Status::Success => "success", Status::Failure => "failure", }) } } impl FromStr for Status { type Err = Box<dyn std::error::Error>; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "success" => Ok(Status::Success), "failure" => Ok(Status::Failure), _ => Err("invalid status; valid are: success, failure".into()), } } } impl From<&Status> for StatusCode { fn from(status: &Status) -> Self { match status { Status::Success => StatusCode::Ok, Status::Failure => StatusCode::Error, } } }
use std::fmt; pub struct Slope { pub right: usize, pub down: usize, } impl fmt::Display for Slope { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "(right {}, down {})", self.right, self.down) } }
use crate::ast::context::CheckerContext; use crate::ast::error::TypeError; use crate::ast::{type_check_code, Condition, VarDef, VarMap}; use crate::constraint::dedup_inputs; use crate::ir::{self, Adaptable}; use utils::RcStr; use itertools::Itertools; use log::trace; #[derive(Clone, Debug)] pub struct TriggerDef { pub foralls: Vec<VarDef>, pub conditions: Vec<Condition>, pub code: String, } impl TriggerDef { /// Typecheck and registers a trigger. pub fn register_trigger(&self, ir_desc: &mut ir::IrDesc) { trace!("defining trigger '{}'", self.code); // Type check the code and the conditions. let var_map = &mut VarMap::default(); let foralls = self .foralls .iter() .map(|def| var_map.decl_forall(&ir_desc, def.to_owned())) .collect(); let mut inputs = Vec::new(); let conditions = self .conditions .iter() .map(|c| c.to_owned().type_check(&ir_desc, var_map, &mut inputs)) .collect_vec(); let code = type_check_code(RcStr::new(self.code.to_owned()), var_map); // Groups similiar inputs. let (inputs, input_adaptator) = dedup_inputs(inputs, &ir_desc); let conditions = conditions .into_iter() .map(|c| c.adapt(&input_adaptator)) .collect_vec(); // Adapt the trigger to the point of view of each inputs. let onchange_actions = inputs .iter() .enumerate() .map(|(pos, input)| { let (foralls, set_constraints, condition, adaptator) = ir::ChoiceCondition::new( &ir_desc, inputs.clone(), pos, &conditions, var_map.env(), ); let code = code.adapt(&adaptator); ( input.choice.clone(), foralls, set_constraints, condition, code, ) }) .collect_vec(); // Add the trigger to the IR. let trigger = ir::Trigger { foralls, inputs, conditions, code, }; let id = ir_desc.add_trigger(trigger); // Register the triggers to to be called when each input is modified. for (choice, forall_vars, set_constraints, condition, code) in onchange_actions { let action = ir::ChoiceAction::Trigger { id, condition, code, inverse_self_cond: false, }; let on_change = ir::OnChangeAction { forall_vars, set_constraints, action, }; ir_desc.add_onchange(&choice, on_change); } } /// Type checks the define's condition. pub fn define( self, context: &CheckerContext, triggers: &mut Vec<TriggerDef>, ) -> Result<(), TypeError> { triggers.push(self); Ok(()) } }
extern crate chrono; extern crate gluster; extern crate init_daemon; extern crate juju; extern crate rand; extern crate rustc_serialize; extern crate uuid; use std::fs::{create_dir, File, OpenOptions}; use std::io::{BufRead, BufReader, Read, Write}; use std::path::Path; use std::thread; use self::chrono::*; use self::gluster::peer::Peer; use self::gluster::volume::volume_info; use self::rand::distributions::{IndependentSample, Range}; use self::rustc_serialize::json; use self::uuid::Uuid; use super::apt; use super::debian::version::Version; use super::get_glusterfs_version; fn get_local_uuid() -> Result<Uuid, String> { // File looks like this: // UUID=30602134-698f-4e53-8503-163e175aea85 // operating-version=30800 let f = File::open("/var/lib/glusterd/glusterd.info").map_err(|e| e.to_string())?; let mut reader = BufReader::new(f); let mut line = String::new(); reader.read_line(&mut line).map_err(|e| e.to_string())?; if line.contains("UUID") { let parts: Vec<&str> = line.split("=").collect(); let uuid = Uuid::parse_str(parts[1].trim()).map_err(|e| e.to_string())?; return Ok(uuid); } Err("Unable to find UUID".to_string()) } // Edge cases: // 1. Previous node dies on upgrade, can we retry? pub fn roll_cluster(new_version: &Version) -> Result<(), String> { // This is tricky to get right so here's what we're going to do. // :param new_version: str of the version to upgrade to // There's 2 possible cases: Either I'm first in line or not. // If I'm not first in line I'll wait a random time between 5-30 seconds // and test to see if the previous peer is upgraded yet. // log!(format!("roll_cluster called with {}", new_version)); let volume_name = juju::config_get(&"volume_name".to_string()).map_err(|e| e.to_string())?; let my_uuid = get_local_uuid()?; // volume_name always has a default let volume_bricks = volume_info(&volume_name.unwrap()).map_err(|e| e.to_string())?.bricks; let mut peer_list: Vec<Peer> = volume_bricks.iter().map(|x| x.peer.clone()).collect(); log!(format!("peer_list: {:?}", peer_list)); // Sort by UUID peer_list.sort(); // We find our position by UUID let position = match peer_list.iter().position(|x| x.uuid == my_uuid) { Some(p) => p, None => { log!(format!("Unable to determine upgrade position from: {:?}", peer_list), Error); return Err("Unable to determine upgrade position".to_string()); } }; log!(format!("upgrade position: {}", position)); if position == 0 { // I'm first! Roll // First set a key to inform others I'm about to roll lock_and_roll(&my_uuid, new_version)?; } else { // Check if the previous node has finished juju::status_set(juju::Status { status_type: juju::StatusType::Waiting, message: format!("Waiting on {:?} to finish upgrading", peer_list[position - 1]), }).map_err(|e| e.to_string())?; wait_on_previous_node(&peer_list[position - 1], new_version)?; lock_and_roll(&my_uuid, new_version)?; } Ok(()) } pub fn upgrade_peer(new_version: &Version) -> Result<(), String> { let current_version = get_glusterfs_version().map_err(|e| e.to_string())?; juju::status_set(juju::Status { status_type: juju::StatusType::Maintenance, message: "Upgrading peer".to_string(), }).map_err(|e| e.to_string())?; log!(format!("Current ceph version is {}", current_version)); log!(format!("Upgrading to: {}", new_version)); apt::service_stop("glusterfs-server")?; apt::apt_install(vec!["glusterfs-server", "glusterfs-common", "glusterfs-client"])?; apt::service_start("glusterfs-server")?; super::update_status()?; return Ok(()); } fn lock_and_roll(my_uuid: &Uuid, version: &Version) -> Result<(), String> { let start_timestamp = Local::now(); log!(format!("gluster_key_set {}_{}_start {}", my_uuid, version, start_timestamp)); gluster_key_set(&format!("{}_{}_start", &my_uuid, version), start_timestamp)?; log!("Rolling"); // This should be quick upgrade_peer(&version)?; log!("Done"); let stop_timestamp = Local::now(); // Set a key to inform others I am finished log!(format!("gluster_key_set {}_{}_done {}", my_uuid, version, stop_timestamp)); gluster_key_set(&format!("{}_{}_done", &my_uuid, version), stop_timestamp)?; return Ok(()); } fn gluster_key_get(key: &str) -> Option<DateTime<Local>> { let mut f = match File::open(&format!("/mnt/glusterfs/.upgrade/{}", key)) { Ok(f) => f, Err(_) => { return None; } }; let mut s = String::new(); match f.read_to_string(&mut s) { Ok(bytes) => { log!(format!("gluster_key_get read {} bytes", bytes)); } Err(e) => { log!(format!("gluster_key_get failed to read file \ /mnt/glusterfs/.upgraded/{}. Error: {}", key, e), Error); return None; } }; let decoded: DateTime<Local> = match json::decode(&s) { Ok(d) => d, Err(e) => { log!(format!("Failed to decode json file in gluster_key_get(): {}", e), Error); return None; } }; Some(decoded) } fn gluster_key_set(key: &str, timestamp: DateTime<Local>) -> Result<(), String> { if !Path::new("/mnt/glusterfs/.upgrade").exists() { create_dir("/mnt/glusterfs/.upgrade").map_err(|e| e.to_string())?; } let mut file = try!(OpenOptions::new() .write(true) .create(true) .open(&format!("/mnt/glusterfs/.upgrade/{}", key)) .map_err(|e| e.to_string())); let encoded = json::encode(&timestamp).map_err(|e| e.to_string())?; try!(file.write(&encoded.as_bytes()).map_err(|e| e.to_string())); Ok(()) } fn gluster_key_exists(key: &str) -> bool { let location = format!("/mnt/glusterfs/.upgrade/{}", key); let p = Path::new(&location); return p.exists(); } pub fn wait_on_previous_node(previous_node: &Peer, version: &Version) -> Result<(), String> { log!(format!("Previous node is: {:?}", previous_node)); let mut previous_node_finished = gluster_key_exists(&format!("{}_{}_done", previous_node.uuid, version)); while !previous_node_finished { log!(format!("{} is not finished. Waiting", previous_node.uuid)); // Has this node been trying to upgrade for longer than // 10 minutes? // If so then move on and consider that node dead. // NOTE: This assumes the clusters clocks are somewhat accurate // If the hosts clock is really far off it may cause it to skip // the previous node even though it shouldn't. let current_timestamp = Local::now(); let previous_node_start_time = gluster_key_get(&format!("{}_{}_start", previous_node.uuid, version)); match previous_node_start_time { Some(previous_start_time) => { if (current_timestamp - Duration::minutes(10)) > previous_start_time { // Previous node is probably dead. Lets move on if previous_node_start_time.is_some() { log!(format!("Waited 10 mins on node {}. current time: {} > \ previous node start time: {} Moving on", previous_node.uuid, (current_timestamp - Duration::minutes(10)), previous_start_time)); return Ok(()); } } else { // I have to wait. Sleep a random amount of time and then // check if I can lock,upgrade and roll. let between = Range::new(5, 30); let mut rng = rand::thread_rng(); let wait_time = between.ind_sample(&mut rng); log!(format!("waiting for {} seconds", wait_time)); thread::sleep(::std::time::Duration::from_secs(wait_time)); previous_node_finished = gluster_key_exists(&format!("{}_{}_done", previous_node.uuid, version)); } } None => { // There is no previous start time. What should we do? } } } Ok(()) }
//! Classes for describing instruction operands. // FIXUP: These will be used eventually. // use cdsl::_camel_case; // use cdsl::types::ValueType; // use cdsl::typevar::_TypeVar;
use crate::wallet::keypair::*; use crate::base::serialize::signed_obj::{SignedTxJson, TxJsonTxnSignatureBuilder, TxJsonBuilder}; use crate::base::crypto::signature::traits::signature::SignatureI; use crate::base::crypto::signature::builder::SignatureBuilder; use crate::base::data::inverse_fields_map::INVERSE_FIELDS_MAP; use crate::api::payment::data::{TxJson}; use crate::api::set_relation::data::{RelationTxJson}; use crate::api::create_offer::data::{OfferCreateTxJson}; use crate::api::cancel_offer::data::OfferCancelTxJson; use crate::api::set_fee_rate::data::SetBrokerageTxJson; use hex; use crate::base::data::constants::TX_SIGNATURE; use crate::base::local_sign::sign_pay::{SignTxPay}; use crate::base::local_sign::sign_relate::{SignTxRelate}; use crate::base::local_sign::sign_cancel_offer::{SignTxCancelOffer}; use crate::base::local_sign::sign_create_offer::{SignTxCreateOffer}; use crate::base::local_sign::sign_brokerage::{SignTxBrokerage}; use crate::address::types::seed::SeedBuilder; use crate::address::traits::address::AddressI; use crate::address::builder::AddressBuilder; use crate::wallet::wallet::WalletType; use crate::wallet::builder::WalletBuilder; pub const PRE_FIELDS: [&'static str; 6] = ["Flags", "Fee", "TransactionType", "Account", "SigningPubKey", "Sequence"]; pub struct SignTx { pub sequence: u32, //account seq pub keypair: Keypair, } impl SignTx { pub fn with_params(sequence: u32, secret: &str) -> Self { let seed = SeedBuilder::secret_to_seed(&secret.to_string()); let key_type: WalletType = WalletBuilder::get_wallet_type_from_seed(&secret); let address = AddressBuilder::new(key_type, &seed); let keypair = Keypair { public_key: address.public_key_hex(), private_key: address.private_key(), }; SignTx { sequence: sequence, keypair : keypair, } } } //Entrance impl SignTx { pub fn pay(&self, tx_json: &TxJson) -> String { SignTxPay::with_params(&self.keypair, &tx_json, self.sequence).build(self) } pub fn relate(&self, tx_json: &RelationTxJson) -> String { SignTxRelate::with_params(&self.keypair, &tx_json, self.sequence).build(self) } pub fn create_offer(&self, tx_json: &OfferCreateTxJson) -> String { SignTxCreateOffer::with_params(&self.keypair, &tx_json, self.sequence).build(self) } pub fn cancel_offer(&self, tx_json: &OfferCancelTxJson) -> String { SignTxCancelOffer::with_params(&self.keypair, &tx_json, self.sequence).build(self) } pub fn set_rate(&self, tx_json: &SetBrokerageTxJson) -> String { SignTxBrokerage::with_params(&self.keypair, &tx_json, self.sequence).build(self) } } //common impl SignTx { pub fn get_blob(&self, signed_tx_json: &mut SignedTxJson) -> String { let output: Vec<u8> = signed_tx_json.serialize(); hex::encode(&output).to_ascii_uppercase() } pub fn get_txn_signature(&self, fields: &mut Vec<&str>, signed_tx_json: &mut SignedTxJson) { let output: Vec<u8> = signed_tx_json.serialize(); let signature_builder = SignatureBuilder::new(WalletType::SM2P256V1, Keypair { private_key: self.keypair.private_key.to_owned(), public_key : self.keypair.public_key.to_owned() }); let txn_signature = signature_builder.sign_txn_signature(&output); self.update(fields, TX_SIGNATURE); let mut index = 0; for x in fields { if *x == TX_SIGNATURE { break; } index += 1; } let txn_signature = TxJsonTxnSignatureBuilder::new(txn_signature).build(); signed_tx_json.insert(index, txn_signature); } pub fn update(&self, fields: &mut Vec<&str>, field: &'static str) { fields.push(field); SignTx::sort_fields(fields); } pub fn sort_fields(fields: &mut Vec<&str>) { fields.sort_by( |a, b| { let a_field_coordinates = INVERSE_FIELDS_MAP.get(a).unwrap(); let a_type_bits = a_field_coordinates[0]; let a_field_bits = a_field_coordinates[1]; let b_field_coordinates = INVERSE_FIELDS_MAP.get(b).unwrap(); let b_type_bits = b_field_coordinates[0]; let b_field_bits = b_field_coordinates[1]; // Sort by type id first, then by field id if a_type_bits != b_type_bits { // a_type_bits - b_type_bits a_type_bits.cmp(&b_type_bits) } else { // a_field_bits - b_field_bits a_field_bits.cmp(&b_field_bits) } }); } }
use std::collections::HashMap; use std::rc::Rc; use std::sync::{mpsc, Arc}; use std::time::Duration; use dbus::arg::{RefArg, Variant}; use dbus::ffidisp::stdintf::org_freedesktop_dbus::PropertiesPropertiesChanged; use dbus::message::SignalArgs; use dbus::tree::{Access, Factory}; use dbus::Path; use crate::album::Album; use crate::episode::Episode; use crate::playable::Playable; use crate::playlist::Playlist; use crate::queue::{Queue, RepeatSetting}; use crate::show::Show; use crate::spotify::{PlayerEvent, Spotify, URIType}; use crate::track::Track; use crate::traits::ListItem; type Metadata = HashMap<String, Variant<Box<dyn RefArg>>>; struct MprisState(String, Option<Playable>); fn get_playbackstatus(spotify: Arc<Spotify>) -> String { match spotify.get_current_status() { PlayerEvent::Playing => "Playing", PlayerEvent::Paused => "Paused", _ => "Stopped", } .to_string() } fn get_metadata(playable: Option<Playable>) -> Metadata { let mut hm: Metadata = HashMap::new(); let playable = playable.as_ref(); hm.insert( "mpris:trackid".to_string(), Variant(Box::new(Path::from(format!( "/org/ncspot/{}", playable .map(|t| t.uri().replace(':', "/")) .unwrap_or_else(|| "0".to_string()) )))), ); hm.insert( "mpris:length".to_string(), Variant(Box::new(i64::from( playable.map(|t| t.duration() * 1_000).unwrap_or(0), ))), ); hm.insert( "mpris:artUrl".to_string(), Variant(Box::new( playable .map(|t| t.cover_url().unwrap_or_default()) .unwrap_or_default(), )), ); hm.insert( "xesam:album".to_string(), Variant(Box::new( playable .and_then(|p| p.track()) .map(|t| t.album) .unwrap_or_default(), )), ); hm.insert( "xesam:albumArtist".to_string(), Variant(Box::new( playable .and_then(|p| p.track()) .map(|t| t.album_artists) .unwrap_or_default(), )), ); hm.insert( "xesam:artist".to_string(), Variant(Box::new( playable .and_then(|p| p.track()) .map(|t| t.artists) .unwrap_or_default(), )), ); hm.insert( "xesam:discNumber".to_string(), Variant(Box::new( playable .and_then(|p| p.track()) .map(|t| t.disc_number) .unwrap_or(0), )), ); hm.insert( "xesam:title".to_string(), Variant(Box::new( playable .map(|t| match t { Playable::Track(t) => t.title.clone(), Playable::Episode(ep) => ep.name.clone(), }) .unwrap_or_default(), )), ); hm.insert( "xesam:trackNumber".to_string(), Variant(Box::new( playable .and_then(|p| p.track()) .map(|t| t.track_number) .unwrap_or(0) as i32, )), ); hm.insert( "xesam:url".to_string(), Variant(Box::new( playable .map(|t| t.share_url().unwrap_or_default()) .unwrap_or_default(), )), ); hm } fn run_dbus_server(spotify: Arc<Spotify>, queue: Arc<Queue>, rx: mpsc::Receiver<MprisState>) { let conn = Rc::new( dbus::ffidisp::Connection::get_private(dbus::ffidisp::BusType::Session) .expect("Failed to connect to dbus"), ); conn.register_name( "org.mpris.MediaPlayer2.ncspot", dbus::ffidisp::NameFlag::ReplaceExisting as u32, ) .expect("Failed to register dbus player name"); let f = Factory::new_fn::<()>(); let property_canquit = f .property::<bool, _>("CanQuit", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(false); // TODO Ok(()) }); let property_canraise = f .property::<bool, _>("CanRaise", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(false); Ok(()) }); let property_cansetfullscreen = f .property::<bool, _>("CanSetFullscreen", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(false); Ok(()) }); let property_hastracklist = f .property::<bool, _>("HasTrackList", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(false); // TODO Ok(()) }); let property_identity = f .property::<String, _>("Identity", ()) .access(Access::Read) .on_get(|iter, _| { iter.append("ncspot".to_string()); Ok(()) }); let property_urischemes = f .property::<Vec<String>, _>("SupportedUriSchemes", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(vec!["spotify".to_string()]); Ok(()) }); let property_mimetypes = f .property::<Vec<String>, _>("SupportedMimeTypes", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(Vec::new() as Vec<String>); Ok(()) }); // https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html let interface = f .interface("org.mpris.MediaPlayer2", ()) .add_p(property_canquit) .add_p(property_canraise) .add_p(property_cansetfullscreen) .add_p(property_hastracklist) .add_p(property_identity) .add_p(property_urischemes) .add_p(property_mimetypes); let property_playbackstatus = { let spotify = spotify.clone(); f.property::<String, _>("PlaybackStatus", ()) .access(Access::Read) .on_get(move |iter, _| { let status = get_playbackstatus(spotify.clone()); iter.append(status); Ok(()) }) }; let property_loopstatus = { let queue = queue.clone(); f.property::<String, _>("LoopStatus", ()) .access(Access::Read) .on_get(move |iter, _| { iter.append( match queue.get_repeat() { RepeatSetting::None => "None", RepeatSetting::RepeatTrack => "Track", RepeatSetting::RepeatPlaylist => "Playlist", } .to_string(), ); Ok(()) }) }; let property_metadata = { let queue = queue.clone(); f.property::<HashMap<String, Variant<Box<dyn RefArg>>>, _>("Metadata", ()) .access(Access::Read) .on_get(move |iter, _| { let hm = get_metadata(queue.clone().get_current()); iter.append(hm); Ok(()) }) }; let property_position = { let spotify = spotify.clone(); f.property::<i64, _>("Position", ()) .access(Access::Read) .on_get(move |iter, _| { let progress = spotify.get_current_progress(); iter.append(progress.as_micros() as i64); Ok(()) }) }; let property_volume = f .property::<f64, _>("Volume", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(1.0); Ok(()) }); let property_rate = f .property::<f64, _>("Rate", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(1.0); Ok(()) }); let property_minrate = f .property::<f64, _>("MinimumRate", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(1.0); Ok(()) }); let property_maxrate = f .property::<f64, _>("MaximumRate", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(1.0); Ok(()) }); let property_canplay = f .property::<bool, _>("CanPlay", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(true); Ok(()) }); let property_canpause = f .property::<bool, _>("CanPause", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(true); Ok(()) }); let property_canseek = f .property::<bool, _>("CanSeek", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(true); Ok(()) }); let property_cancontrol = f .property::<bool, _>("CanControl", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(true); Ok(()) }); let property_cangonext = f .property::<bool, _>("CanGoNext", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(true); Ok(()) }); let property_cangoprevious = f .property::<bool, _>("CanGoPrevious", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(true); Ok(()) }); let property_shuffle = { let queue = queue.clone(); f.property::<bool, _>("Shuffle", ()) .access(Access::Read) .on_get(move |iter, _| { iter.append(queue.get_shuffle()); Ok(()) }) }; let property_cangoforward = f .property::<bool, _>("CanGoForward", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(true); Ok(()) }); let property_canrewind = f .property::<bool, _>("CanRewind", ()) .access(Access::Read) .on_get(|iter, _| { iter.append(true); Ok(()) }); let method_playpause = { let spotify = spotify.clone(); f.method("PlayPause", (), move |m| { spotify.toggleplayback(); Ok(vec![m.msg.method_return()]) }) }; let method_play = { let spotify = spotify.clone(); f.method("Play", (), move |m| { spotify.play(); Ok(vec![m.msg.method_return()]) }) }; let method_pause = { let spotify = spotify.clone(); f.method("Pause", (), move |m| { spotify.pause(); Ok(vec![m.msg.method_return()]) }) }; let method_stop = { let spotify = spotify.clone(); f.method("Stop", (), move |m| { spotify.stop(); Ok(vec![m.msg.method_return()]) }) }; let method_next = { let queue = queue.clone(); f.method("Next", (), move |m| { queue.next(true); Ok(vec![m.msg.method_return()]) }) }; let method_previous = { let spotify = spotify.clone(); let queue = queue.clone(); f.method("Previous", (), move |m| { if spotify.get_current_progress() < Duration::from_secs(5) { queue.previous(); } else { spotify.seek(0); } Ok(vec![m.msg.method_return()]) }) }; let method_forward = { let spotify = spotify.clone(); f.method("Forward", (), move |m| { spotify.seek_relative(5000); Ok(vec![m.msg.method_return()]) }) }; let method_rewind = { let spotify = spotify.clone(); f.method("Rewind", (), move |m| { spotify.seek_relative(-5000); Ok(vec![m.msg.method_return()]) }) }; let method_seek = { let queue = queue.clone(); let spotify = spotify.clone(); f.method("Seek", (), move |m| { if let Some(current_track) = queue.get_current() { let offset = m.msg.get1::<i64>().unwrap_or(0); // micros let progress = spotify.get_current_progress(); let new_position = (progress.as_secs() * 1000) as i32 + progress.subsec_millis() as i32 + (offset / 1000) as i32; let new_position = new_position.max(0) as u32; let duration = current_track.duration(); if new_position < duration { spotify.seek(new_position); } else { queue.next(true); } } Ok(vec![m.msg.method_return()]) }) }; let method_set_position = { let queue = queue.clone(); let spotify = spotify.clone(); f.method("SetPosition", (), move |m| { if let Some(current_track) = queue.get_current() { let (_, position) = m.msg.get2::<Path, i64>(); // micros let position = (position.unwrap_or(0) / 1000) as u32; let duration = current_track.duration(); if position < duration { spotify.seek(position); } } Ok(vec![m.msg.method_return()]) }) }; let method_openuri = { f.method("OpenUri", (), move |m| { let uri_data: Option<&str> = m.msg.get1(); let uri = match uri_data { Some(s) => s, None => "", }; let id = &uri[uri.rfind(':').unwrap_or(0) + 1..uri.len()]; let uri_type = URIType::from_uri(uri); match uri_type { Some(URIType::Album) => { if let Some(a) = spotify.album(&id) { if let Some(t) = &Album::from(&a).tracks { queue.clear(); let index = queue.append_next( t.iter() .map(|track| Playable::Track(track.clone())) .collect(), ); queue.play(index, false, false) } } } Some(URIType::Track) => { if let Some(t) = spotify.track(&id) { queue.clear(); queue.append(Playable::Track(Track::from(&t))); queue.play(0, false, false) } } Some(URIType::Playlist) => { if let Some(p) = spotify.playlist(&id) { let mut playlist = Playlist::from(&p); let spotify = spotify.clone(); playlist.load_tracks(spotify); if let Some(t) = &playlist.tracks { queue.clear(); let index = queue.append_next( t.iter() .map(|track| Playable::Track(track.clone())) .collect(), ); queue.play(index, false, false) } } } Some(URIType::Show) => { if let Some(s) = spotify.get_show(&id) { let mut show = Show::from(&s); let spotify = spotify.clone(); show.load_episodes(spotify); if let Some(e) = &show.episodes { queue.clear(); let mut ep = e.clone(); ep.reverse(); let index = queue.append_next( ep.iter() .map(|episode| Playable::Episode(episode.clone())) .collect(), ); queue.play(index, false, false) } } } Some(URIType::Episode) => { if let Some(e) = spotify.episode(&id) { queue.clear(); queue.append(Playable::Episode(Episode::from(&e))); queue.play(0, false, false) } } Some(URIType::Artist) => {} None => {} } Ok(vec![m.msg.method_return()]) }) }; // https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html let interface_player = f .interface("org.mpris.MediaPlayer2.Player", ()) .add_p(property_playbackstatus) .add_p(property_loopstatus) .add_p(property_metadata) .add_p(property_position) .add_p(property_volume) .add_p(property_rate) .add_p(property_minrate) .add_p(property_maxrate) .add_p(property_canplay) .add_p(property_canpause) .add_p(property_canseek) .add_p(property_cancontrol) .add_p(property_cangonext) .add_p(property_cangoprevious) .add_p(property_shuffle) .add_p(property_cangoforward) .add_p(property_canrewind) .add_m(method_playpause) .add_m(method_play) .add_m(method_pause) .add_m(method_stop) .add_m(method_next) .add_m(method_previous) .add_m(method_forward) .add_m(method_rewind) .add_m(method_seek) .add_m(method_set_position) .add_m(method_openuri); let tree = f.tree(()).add( f.object_path("/org/mpris/MediaPlayer2", ()) .introspectable() .add(interface) .add(interface_player), ); tree.set_registered(&conn, true) .expect("failed to register tree"); conn.add_handler(tree); loop { if let Some(m) = conn.incoming(200).next() { warn!("Unhandled dbus message: {:?}", m); } if let Ok(state) = rx.try_recv() { let mut changed: PropertiesPropertiesChanged = Default::default(); debug!( "mpris PropertiesChanged: status {}, track: {:?}", state.0, state.1 ); changed.interface_name = "org.mpris.MediaPlayer2.Player".to_string(); changed.changed_properties.insert( "Metadata".to_string(), Variant(Box::new(get_metadata(state.1))), ); changed .changed_properties .insert("PlaybackStatus".to_string(), Variant(Box::new(state.0))); conn.send( changed.to_emit_message(&Path::new("/org/mpris/MediaPlayer2".to_string()).unwrap()), ) .unwrap(); } } } #[derive(Clone)] pub struct MprisManager { tx: mpsc::Sender<MprisState>, queue: Arc<Queue>, spotify: Arc<Spotify>, } impl MprisManager { pub fn new(spotify: Arc<Spotify>, queue: Arc<Queue>) -> Self { let (tx, rx) = mpsc::channel::<MprisState>(); { let spotify = spotify.clone(); let queue = queue.clone(); std::thread::spawn(move || { run_dbus_server(spotify.clone(), queue.clone(), rx); }); } MprisManager { tx, queue, spotify } } pub fn update(&self) { let status = get_playbackstatus(self.spotify.clone()); let track = self.queue.get_current(); self.tx.send(MprisState(status, track)).unwrap(); } }
// Copyright 2018 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; use wayland::{WlDataDeviceManager, WlDataDeviceManagerRequest}; use crate::client::Client; use crate::object::{ObjectRef, RequestReceiver}; /// An implementation of the wl_data_device_manager global. pub struct DataDeviceManager; impl DataDeviceManager { /// Creates a new `DataDeviceManager`. pub fn new() -> Self { DataDeviceManager } } impl RequestReceiver<WlDataDeviceManager> for DataDeviceManager { fn receive( _this: ObjectRef<Self>, request: WlDataDeviceManagerRequest, _client: &mut Client, ) -> Result<(), Error> { match request { WlDataDeviceManagerRequest::CreateDataSource { .. } => {} WlDataDeviceManagerRequest::GetDataDevice { .. } => {} } Ok(()) } }
pub mod command_raw; pub mod command; pub use command_raw::CommandRaw; pub use command::Command;
use crate::challenges::Challenge; use crate::ResultHashMap; use crate::file_lines_to_string_vec; use crate::ExpenseReport; pub fn challenge() -> Challenge { return Challenge::new( expense_report_product_from_2_sum, expense_report_product_from_3_sum, String::from("resources/expense_report.txt"), ); } pub fn expense_report_product_from_2_sum(args: &[String]) -> ResultHashMap { let raw_lines = file_lines_to_string_vec(&args[0])?; let mut expense_report = ExpenseReport::new(&raw_lines)?; let target_sum = 2020; return Ok( [(String::from("expense report values product"), expense_report.product_from_target_two_sum(target_sum))] .iter() .cloned() .collect() ); } fn expense_report_product_from_3_sum(args: &[String]) -> ResultHashMap { let raw_lines = file_lines_to_string_vec(&args[0])?; let mut expense_report = ExpenseReport::new(&raw_lines)?; let target_sum = 2020; return Ok( [(String::from("expense report values product"), expense_report.product_from_target_three_sum(target_sum))] .iter() .cloned() .collect() ); } #[cfg(test)] mod tests { use super::challenge; crate::challenge_tests!(121396, 73616634); }
pub enum UnitType { SVG_ANGLETYPE_UNKNOWN = 0, SVG_ANGLETYPE_UNSPECIFIED = 1, SVG_ANGLETYPE_DEG = 2, SVG_ANGLETYPE_RAD = 3, SVG_ANGLETYPE_GRAD = 4 } pub struct SVGAngle { unit_type : UnitType, value : f32 }
#[derive(Clone)] pub struct GitUrl { host: String, path: String, } impl GitUrl { const HTTP_PREFIX: &'static str = "http://"; const HTTPS_PREFIX: &'static str = "https://"; #[allow(dead_code)] pub fn parse(value: &str) -> Option<Self> { if value.starts_with(Self::HTTP_PREFIX) { value[Self::HTTP_PREFIX.len()..].find("/").map(|p| Self { host: value[..Self::HTTP_PREFIX.len() + p].to_string(), path: value[Self::HTTP_PREFIX.len() + p + 1..].to_string(), }) } else if value.starts_with(Self::HTTPS_PREFIX) { value[Self::HTTPS_PREFIX.len()..].find("/").map(|p| Self { host: value[..Self::HTTPS_PREFIX.len() + p].to_string(), path: value[Self::HTTPS_PREFIX.len() + p + 1..].to_string(), }) } else { value.find(":").map(|p| Self { host: value[..p].to_string(), path: value[p + 1..].to_string(), }) } } #[allow(dead_code)] pub fn to_string(&self) -> String { match self.path.len() { 0 => self.host.to_string(), _ => self.host.to_string() + ":" + &self.path, } } #[allow(dead_code)] pub fn pop(&self) -> Option<Self> { let mut temp = self.clone(); match temp.pop_mut() { true => Some(temp), false => None, } } #[allow(dead_code)] pub fn pop_mut(&mut self) -> bool { Self::pop_helper(&mut self.path) } #[allow(dead_code)] pub fn join(&self, child_path: &str) -> Option<Self> { let mut temp = self.clone(); match temp.join_mut(child_path) { true => Some(temp), false => None, } } #[allow(dead_code)] pub fn join_mut(&mut self, child_path: &str) -> bool { let mut path = self.path.clone(); for part in child_path.split("/") { if part.len() == 0 { return false; } else if part == ".." { if !Self::pop_helper(&mut path) { return false; } } else if part != "." { if path.len() > 0 { path += "/" } path += part } } self.path = path; true } fn pop_helper(path: &mut String) -> bool { if path.len() == 0 { false } else { match path.rfind('/') { Some(pos) => path.truncate(pos), None => path.clear(), } true } } } impl std::fmt::Display for GitUrl { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str(&self.to_string()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_pop_https() { let x0 = GitUrl::parse("https://github.com/user/foo/bar/quux.git").expect("parse failed"); assert_eq!(x0.host, "https://github.com"); assert_eq!(x0.path, "user/foo/bar/quux.git"); let x1 = GitUrl::parse("http://github.com/user/foo/bar/quux.git").expect("parse failed"); assert_eq!(x1.host, "http://github.com"); assert_eq!(x1.path, "user/foo/bar/quux.git"); let x2 = GitUrl::parse("git@github.com:user/foo/bar/quux.git").expect("parse failed"); assert_eq!(x2.host, "git@github.com"); assert_eq!(x2.path, "user/foo/bar/quux.git"); } #[test] fn test_pop() { let x0 = GitUrl::parse("git@github.com:user/foo/bar/quux.git").expect("parse failed"); assert_eq!(x0.host, "git@github.com"); assert_eq!(x0.path, "user/foo/bar/quux.git"); assert_eq!(x0.to_string(), "git@github.com:user/foo/bar/quux.git"); let x1 = x0.pop().expect("pop failed"); assert_eq!(x1.host, "git@github.com"); assert_eq!(x1.path, "user/foo/bar"); assert_eq!(x1.to_string(), "git@github.com:user/foo/bar"); let x2 = x1.pop().expect("pop failed"); assert_eq!(x2.host, "git@github.com"); assert_eq!(x2.path, "user/foo"); assert_eq!(x2.to_string(), "git@github.com:user/foo"); let x3 = x2.pop().expect("pop failed"); assert_eq!(x3.host, "git@github.com"); assert_eq!(x3.path, "user"); assert_eq!(x3.to_string(), "git@github.com:user"); let x4 = x3.pop().expect("pop failed"); assert_eq!(x4.host, "git@github.com"); assert_eq!(x4.path, ""); assert_eq!(x4.to_string(), "git@github.com"); assert!(x4.pop().is_none()) } #[test] fn test_pop_mut() { let mut git_url = GitUrl::parse("git@github.com:user/foo/bar/quux.git").expect("parse failed"); assert_eq!(git_url.host, "git@github.com"); assert_eq!(git_url.path, "user/foo/bar/quux.git"); assert_eq!(git_url.to_string(), "git@github.com:user/foo/bar/quux.git"); assert!(git_url.pop_mut()); assert_eq!(git_url.host, "git@github.com"); assert_eq!(git_url.path, "user/foo/bar"); assert_eq!(git_url.to_string(), "git@github.com:user/foo/bar"); assert!(git_url.pop_mut()); assert_eq!(git_url.host, "git@github.com"); assert_eq!(git_url.path, "user/foo"); assert_eq!(git_url.to_string(), "git@github.com:user/foo"); assert!(git_url.pop_mut()); assert_eq!(git_url.host, "git@github.com"); assert_eq!(git_url.path, "user"); assert_eq!(git_url.to_string(), "git@github.com:user"); assert!(git_url.pop_mut()); assert_eq!(git_url.host, "git@github.com"); assert_eq!(git_url.path, ""); assert_eq!(git_url.to_string(), "git@github.com"); assert!(!git_url.pop_mut()); assert_eq!(git_url.host, "git@github.com"); assert_eq!(git_url.path, ""); assert_eq!(git_url.to_string(), "git@github.com"); } #[test] fn test_join() { let git_url = GitUrl::parse("git@github.com:user/foo/bar/quux.git").expect("parse failed"); assert_eq!( git_url.join("aaa").expect("join failed").to_string(), "git@github.com:user/foo/bar/quux.git/aaa" ); assert_eq!( git_url.join("aaa/bbb").expect("join failed").to_string(), "git@github.com:user/foo/bar/quux.git/aaa/bbb" ); assert_eq!( git_url.join(".").expect("join failed").to_string(), "git@github.com:user/foo/bar/quux.git" ); assert_eq!( git_url.join("..").expect("join failed").to_string(), "git@github.com:user/foo/bar" ); assert_eq!( git_url.join("../aaa").expect("join failed").to_string(), "git@github.com:user/foo/bar/aaa" ); assert_eq!( git_url.join("../aaa/bbb").expect("join failed").to_string(), "git@github.com:user/foo/bar/aaa/bbb" ); assert_eq!( git_url .join("../../../aaa/bbb") .expect("join failed") .to_string(), "git@github.com:user/aaa/bbb" ); assert_eq!( git_url .join("../../../../aaa/bbb") .expect("join failed") .to_string(), "git@github.com:aaa/bbb" ); assert!(git_url.join("/aaa").is_none()); } #[test] fn test_join_mut() { { let mut git_url = GitUrl::parse("git@github.com:user/foo/bar/quux.git").expect("parse failed"); assert!(git_url.join_mut("aaa")); assert_eq!( git_url.to_string(), "git@github.com:user/foo/bar/quux.git/aaa" ) } { let mut git_url = GitUrl::parse("git@github.com:user/foo/bar/quux.git").expect("parse failed"); assert!(git_url.join_mut("aaa/bbb")); assert_eq!( git_url.to_string(), "git@github.com:user/foo/bar/quux.git/aaa/bbb" ) } { let mut git_url = GitUrl::parse("git@github.com:user/foo/bar/quux.git").expect("parse failed"); assert!(git_url.join_mut(".")); assert_eq!(git_url.to_string(), "git@github.com:user/foo/bar/quux.git") } { let mut git_url = GitUrl::parse("git@github.com:user/foo/bar/quux.git").expect("parse failed"); assert!(git_url.join_mut("..")); assert_eq!(git_url.to_string(), "git@github.com:user/foo/bar") } { let mut git_url = GitUrl::parse("git@github.com:user/foo/bar/quux.git").expect("parse failed"); assert!(git_url.join_mut("../aaa")); assert_eq!(git_url.to_string(), "git@github.com:user/foo/bar/aaa") } { let mut git_url = GitUrl::parse("git@github.com:user/foo/bar/quux.git").expect("parse failed"); assert!(git_url.join_mut("../aaa/bbb")); assert_eq!(git_url.to_string(), "git@github.com:user/foo/bar/aaa/bbb") } { let mut git_url = GitUrl::parse("git@github.com:user/foo/bar/quux.git").expect("parse failed"); assert!(git_url.join_mut("../../../aaa/bbb")); assert_eq!(git_url.to_string(), "git@github.com:user/aaa/bbb") } { let mut git_url = GitUrl::parse("git@github.com:user/foo/bar/quux.git").expect("parse failed"); assert!(git_url.join_mut("../../../../aaa/bbb")); assert_eq!(git_url.to_string(), "git@github.com:aaa/bbb") } { let mut git_url = GitUrl::parse("git@github.com:user/foo/bar/quux.git").expect("parse failed"); assert!(!git_url.join_mut("/aaa")) } } }
mod hui_works; pub mod material; pub mod env;
mod file; mod flush; mod graphite; mod internal; mod native; mod statsd; pub use self::file::{FileServer, FileServerConfig}; pub use self::flush::FlushTimer; pub use self::graphite::{Graphite, GraphiteConfig}; pub use self::internal::{Internal, InternalConfig, report_full_telemetry, report_telemetry}; pub use self::native::{NativeServer, NativeServerConfig}; pub use self::statsd::{Statsd, StatsdConfig}; pub trait Source { fn run(&mut self) -> (); }
#![feature(mpsc_select)] extern crate time; use std::thread; use std::sync::mpsc; use std::sync::mpsc::{SyncSender, Receiver}; use std::sync::mpsc::Select; use std::io::prelude::*; use std::fs::File; use std::vec::Vec; use time::PreciseTime; struct StressedPacket { writer : i32, n : i32, } fn writer(out : SyncSender<StressedPacket>, writer : i32, writes : i32) { for i in 0..writes { out.send(StressedPacket{writer : writer, n : i}).unwrap(); } } fn save_results(N : usize, results : Vec<u64>) { let mut buffer = File::create(format!("st-rust-{}.csv", N)).unwrap(); for r in results { write!(buffer, "{}\n", r); } buffer.flush(); } fn do_select1(in0 : &Receiver<StressedPacket>) { select! { _ = in0.recv() => println!("") } } fn do_select2(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>) { select! { _ = in0.recv() => (), _ = in1.recv() => () } } fn do_select4(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>) { select! { _ = in0.recv() => (), _ = in1.recv() => (), _ = in2.recv() => (), _ = in3.recv() => () } } fn do_select8(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>, in4 : &Receiver<StressedPacket>, in5 : &Receiver<StressedPacket>, in6 : &Receiver<StressedPacket>, in7 : &Receiver<StressedPacket>) { select! { _ = in0.recv() => (), _ = in1.recv() => (), _ = in2.recv() => (), _ = in3.recv() => (), _ = in4.recv() => (), _ = in5.recv() => (), _ = in6.recv() => (), _ = in7.recv() => () } } fn do_select(N : i32, input : &Vec<Receiver<StressedPacket>>) { match N { 1 => do_select1(&input[0]), 2 => do_select2(&input[0], &input[1]), 4 => do_select4(&input[0], &input[1], &input[2], &input[3]), 8 => do_select8(&input[0], &input[1], &input[2], &input[3], &input[4], &input[5], &input[6], &input[7]), _ => () } } fn reader(N : i32, input : Vec<Receiver<StressedPacket>>, total : i32) { let mut results = Vec::new(); let mut start = time::precise_time_ns(); let mut i = 0; for count in 0..total { if count % 65536 == 0 { let total = (time::precise_time_ns() - start) / 65536; results.push(total); println!("{}", i); println!("{} ns", total); start = time::precise_time_ns(); i += 1; } do_select(N, &input); } save_results(input.len(), results); } fn experiment(iterations : i32, threads : i32) { let mut chans = Vec::new(); for i in 0..threads { let (tx, rx) : (SyncSender<StressedPacket>, Receiver<StressedPacket>) = mpsc::sync_channel(0); chans.push(rx); thread::spawn(move || { writer(tx, i, iterations / threads); } ); } reader(threads, chans, iterations); } fn main() { let x : i32 = 2; experiment(x.pow(24), 1); experiment(x.pow(24), 2); experiment(x.pow(24), 4); experiment(x.pow(24), 8); }
use crate::models::*; use std::vec::Vec; pub trait UserRepository { fn find(&self, id: &i64) -> Result<User, diesel::result::Error>; fn delete(&self, id: &i64) -> bool; fn create(&self, u: NewUser) -> Result<User, diesel::result::Error>; fn message(&self) -> String; fn find_all(&self) -> Result<Vec<User>, diesel::result::Error>; }
// 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::alloc::AllocError; use std::alloc::Allocator; use std::alloc::GlobalAlloc; use std::alloc::Layout; use std::ptr::null_mut; use std::ptr::NonNull; use crate::mem_allocator::DefaultAllocator; /// Global allocator, default is JeAllocator. #[derive(Debug, Clone, Copy, Default)] pub struct GlobalAllocator; impl GlobalAllocator { pub fn name() -> String { DefaultAllocator::name() } pub fn conf() -> String { DefaultAllocator::conf() } } unsafe impl Allocator for GlobalAllocator { #[inline(always)] fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { DefaultAllocator::default().allocate(layout) } #[inline(always)] fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { DefaultAllocator::default().allocate_zeroed(layout) } #[inline(always)] unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { DefaultAllocator::default().deallocate(ptr, layout) } #[inline(always)] unsafe fn grow( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { DefaultAllocator::default().grow(ptr, old_layout, new_layout) } #[inline(always)] unsafe fn grow_zeroed( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { DefaultAllocator::default().grow_zeroed(ptr, old_layout, new_layout) } #[inline(always)] unsafe fn shrink( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { DefaultAllocator::default().shrink(ptr, old_layout, new_layout) } } unsafe impl GlobalAlloc for GlobalAllocator { #[inline] unsafe fn alloc(&self, layout: Layout) -> *mut u8 { if let Ok(ptr) = GlobalAllocator.allocate(layout) { ptr.as_ptr() as *mut u8 } else { null_mut() } } #[inline] unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { let ptr = NonNull::new(ptr).unwrap_unchecked(); GlobalAllocator.deallocate(ptr, layout); } #[inline] unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { if let Ok(ptr) = GlobalAllocator.allocate_zeroed(layout) { ptr.as_ptr() as *mut u8 } else { null_mut() } } #[inline(always)] unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { use std::cmp::Ordering::*; let ptr = NonNull::new(ptr).unwrap_unchecked(); let new_layout = Layout::from_size_align(new_size, layout.align()).unwrap(); match layout.size().cmp(&new_size) { Less => { if let Ok(ptr) = GlobalAllocator.grow(ptr, layout, new_layout) { ptr.as_ptr() as *mut u8 } else { null_mut() } } Greater => { if let Ok(ptr) = GlobalAllocator.shrink(ptr, layout, new_layout) { ptr.as_ptr() as *mut u8 } else { null_mut() } } Equal => ptr.as_ptr() as *mut u8, } } }
use input_i_scanner::{scan_with, InputIScanner}; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); let (h, w) = scan_with!(_i_i, (usize, usize)); let mut a = vec![vec![]; h]; for i in 0..h { a[i] = scan_with!(_i_i, u64; w); } let mut ok = true; for i1 in 0..h { for i2 in (i1 + 1)..h { for j1 in 0..w { for j2 in (j1 + 1)..w { if a[i1][j1] + a[i2][j2] > a[i2][j1] + a[i1][j2] { ok = false; } } } } } if ok { println!("Yes"); } else { println!("No"); } }
//! Package implement Write-Ahead-Logging. //! //! Write-Ahead-Logging is implemented by [Wal] type, to get started create //! a configuration [Config] value. Subsequently, a fresh Wal instance can be //! created or existing Wal from disk can be loaded, using the configuration. //! Wal optionally takes a type parameter `S` for state, that can be used by //! application to persist storage state along with each batch. //! By default, `NoState` is used. //! //! Concurrent writers //! ------------------ //! //! [Wal] writes are batch-processed, where batching is automatically dictated //! by storage (disk, ssd) latency. Latency can get higher when `fsync` is //! enabled for every batch flush. With fsync enabled it is hard to reduce //! the latency, and to get better throughput applications can do concurrent //! writes. This is possible because [Wal] type can be cloned with underlying //! structure safely shared among all the clones. For example, //! //! ```ignore //! let wal = wral::Wal::create(config, wral::NoState).unwrap(); //! let mut writers = vec![]; //! for id in 0..n_threads { //! let wal = wal.clone(); //! writers.push(std::thread::spawn(move || writer(id, wal))); //! } //! ``` //! //! Application employing concurrent [Wal] must keep in mind that `seqno` //! generated for consecutive ops may not be monotonically increasing within //! the same thread, and must make sure to serialize operations across the //! writers through other means. //! //! Concurrent readers //! ------------------ //! //! It is possible for a [Wal] value and its clones to concurrently read the //! log journal (typically iterating over its entries). Remember that read //! operations shall block concurrent writes and vice-versa. But concurrent //! reads shall be allowed. #![feature(unboxed_closures)] #![feature(fn_traits)] use std::{error, fmt, result}; // Short form to compose Error values. // // Here are few possible ways: // // ```ignore // use crate::Error; // err_at!(ParseError, msg: format!("bad argument")); // ``` // // ```ignore // use crate::Error; // err_at!(ParseError, std::io::read(buf)); // ``` // // ```ignore // use crate::Error; // err_at!(ParseError, std::fs::read(file_path), format!("read failed")); // ``` // macro_rules! err_at { ($v:ident, msg: $($arg:expr),+) => {{ let prefix = format!("{}:{}", file!(), line!()); Err(Error::$v(prefix, format!($($arg),+))) }}; ($v:ident, $e:expr) => {{ match $e { Ok(val) => Ok(val), Err(err) => { let prefix = format!("{}:{}", file!(), line!()); Err(Error::$v(prefix, format!("{}", err))) } } }}; ($v:ident, $e:expr, $($arg:expr),+) => {{ match $e { Ok(val) => Ok(val), Err(err) => { let prefix = format!("{}:{}", file!(), line!()); let msg = format!($($arg),+); Err(Error::$v(prefix, format!("{} {}", err, msg))) } } }}; } mod batch; mod entry; mod files; mod journal; mod state; mod util; mod wral; mod writer; pub use crate::entry::Entry; pub use crate::state::{NoState, State}; pub use crate::wral::Config; pub use crate::wral::Wal; /// Type alias for Result return type, used by this package. pub type Result<T> = result::Result<T, Error>; /// Error variants that can be returned by this package's API. /// /// Each variant carries a prefix, typically identifying the /// error location. pub enum Error { FailConvert(String, String), FailCbor(String, String), IOError(String, String), Fatal(String, String), Invalid(String, String), IPCFail(String, String), ThreadFail(String, String), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> { use Error::*; match self { FailConvert(p, msg) => write!(f, "{} FailConvert: {}", p, msg), FailCbor(p, msg) => write!(f, "{} FailCbor: {}", p, msg), IOError(p, msg) => write!(f, "{} IOError: {}", p, msg), Fatal(p, msg) => write!(f, "{} Fatal: {}", p, msg), Invalid(p, msg) => write!(f, "{} Invalid: {}", p, msg), IPCFail(p, msg) => write!(f, "{} IPCFail: {}", p, msg), ThreadFail(p, msg) => write!(f, "{} ThreadFail: {}", p, msg), } } } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> { write!(f, "{}", self) } } impl error::Error for Error {} impl From<mkit::Error> for Error { fn from(err: mkit::Error) -> Error { match err { mkit::Error::Fatal(p, m) => Error::Fatal(p, m), mkit::Error::FailConvert(p, m) => Error::FailConvert(p, m), mkit::Error::IOError(p, m) => Error::IOError(p, m), mkit::Error::FailCbor(p, m) => Error::FailCbor(p, m), mkit::Error::IPCFail(p, m) => Error::IPCFail(p, m), mkit::Error::ThreadFail(p, m) => Error::ThreadFail(p, m), } } }
/// A trait describing a buffer that is interleaved and mutable. /// /// This allows for accessing the raw underlying interleaved buffer. pub trait AsInterleavedMut<T> { /// Access the underlying interleaved mutable buffer. /// /// # Examples /// /// ```rust /// use audio::{Channels, AsInterleaved, AsInterleavedMut}; /// use audio::wrap; /// /// fn test<B>(mut buffer: B) where B: Channels<i16> + AsInterleaved<i16> + AsInterleavedMut<i16> { /// buffer.as_interleaved_mut().copy_from_slice(&[1, 1, 2, 2, 3, 3, 4, 4]); /// /// assert_eq! { /// buffer.channel(0).iter().collect::<Vec<_>>(), /// &[1, 2, 3, 4], /// }; /// /// assert_eq! { /// buffer.channel(1).iter().collect::<Vec<_>>(), /// &[1, 2, 3, 4], /// }; /// /// assert_eq!(buffer.as_interleaved(), &[1, 1, 2, 2, 3, 3, 4, 4]); /// } /// /// test(audio::interleaved![[0; 4]; 2]); /// let mut buf = [0; 8]; /// test(wrap::interleaved(&mut buf, 2)); /// ``` fn as_interleaved_mut(&mut self) -> &mut [T]; /// Access a pointer to the underlying interleaved mutable buffer. /// /// The length of the buffer is unspecified, unless preceded by a call to /// [reserve_frames]. Assuming the call doesn't panic, the pointed to buffer /// is guaranteed to be both allocated and initialized up until the number /// of frames as specified as argument to [reserve_frames]. /// /// [reserve_frames]: crate::InterleavedBuf::reserve_frames /// /// # Examples /// /// ```rust /// use audio::{AsInterleavedMut, InterleavedBuf, Channels}; /// # unsafe fn fill_with_ones(buf: *mut i16, len: usize) -> (usize, usize) { /// # let buf = std::slice::from_raw_parts_mut(buf, len); /// # /// # for (o, b) in buf.iter_mut().zip(std::iter::repeat(1)) { /// # *o = b; /// # } /// # /// # (2, len / 2) /// # } /// /// fn test<B>(mut buffer: B) where B: InterleavedBuf + AsInterleavedMut<i16> { /// buffer.reserve_frames(16); /// // Note: call fills the buffer with ones. /// // Safety: We've initialized exactly 16 frames before calling this /// // function. /// let (channels, frames) = unsafe { fill_with_ones(buffer.as_interleaved_mut_ptr(), 16) }; /// buffer.set_topology(channels, frames); /// } /// /// let mut buf = audio::Interleaved::new(); /// test(&mut buf); /// /// assert_eq! { /// buf.channel(0).iter().collect::<Vec<_>>(), /// &[1, 1, 1, 1, 1, 1, 1, 1], /// }; /// assert_eq! { /// buf.channel(1).iter().collect::<Vec<_>>(), /// &[1, 1, 1, 1, 1, 1, 1, 1], /// }; /// ``` fn as_interleaved_mut_ptr(&mut self) -> *mut T; } impl<B, T> AsInterleavedMut<T> for &mut B where B: ?Sized + AsInterleavedMut<T>, { fn as_interleaved_mut(&mut self) -> &mut [T] { (**self).as_interleaved_mut() } fn as_interleaved_mut_ptr(&mut self) -> *mut T { (**self).as_interleaved_mut_ptr() } }
use super::*; use crate::StableAbi; use std::{ error::Error as ErrorTrait, fmt::{self, Debug, Display}, }; /////////////////////////////////////////////////////////////////////////////// #[repr(transparent)] #[derive(PartialEq, Eq, Clone, Copy, StableAbi)] pub struct RSendError<T>(pub T); impl<T> RSendError<T> { pub fn into_inner(self) -> T { self.0 } } impl<T> Debug for RSendError<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad("RSendError{..}") } } impl<T> Display for RSendError<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad("Attempting to send on a disconnected channel") } } impl<T> ErrorTrait for RSendError<T> {} impl_from_rust_repr! { impl[T] From<SendError<T>> for RSendError<T> { fn(this){ RSendError(this.into_inner()) } } } impl_into_rust_repr! { impl[T] Into<SendError<T>> for RSendError<T> { fn(this){ SendError(this.into_inner()) } } } /////////////////////////////////////////////////////////////////////////////// #[repr(C)] #[derive(PartialEq, Eq, Clone, Copy, StableAbi)] pub struct RRecvError; impl Debug for RRecvError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad("RRecvError{..}") } } impl Display for RRecvError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad("Attempting to recv on a disconnected channel") } } impl ErrorTrait for RRecvError {} impl_from_rust_repr! { impl From<RecvError> for RRecvError { fn(_this){ RRecvError } } } impl_into_rust_repr! { impl Into<RecvError> for RRecvError { fn(_this){ RecvError } } } /////////////////////////////////////////////////////////////////////////////// #[repr(u8)] #[derive(PartialEq, Eq, Clone, Copy, StableAbi)] pub enum RTrySendError<T> { Full(T), Disconnected(T), } impl<T> RTrySendError<T> { pub fn into_inner(self) -> T { match self { RTrySendError::Full(v) => v, RTrySendError::Disconnected(v) => v, } } pub fn is_full(&self) -> bool { matches!(self, RTrySendError::Full { .. }) } pub fn is_disconnected(&self) -> bool { matches!(self, RTrySendError::Disconnected { .. }) } } impl<T> Debug for RTrySendError<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let msg = match self { RTrySendError::Full { .. } => "Full{..}", RTrySendError::Disconnected { .. } => "Disconnected{..}", }; f.pad(msg) } } impl<T> Display for RTrySendError<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let msg = match self { RTrySendError::Full { .. } => "Attempting to send on a full channel", RTrySendError::Disconnected { .. } => "Attempting to send on a disconnected channel", }; f.pad(msg) } } impl<T> ErrorTrait for RTrySendError<T> {} impl_from_rust_repr! { impl[T] From<TrySendError<T>> for RTrySendError<T> { fn(this){ match this { TrySendError::Full(v)=> RTrySendError::Full(v), TrySendError::Disconnected(v)=> RTrySendError::Disconnected(v), } } } } impl_into_rust_repr! { impl[T] Into<TrySendError<T>> for RTrySendError<T> { fn(this){ match this { RTrySendError::Full(v)=>TrySendError::Full(v), RTrySendError::Disconnected(v)=>TrySendError::Disconnected(v), } } } } /////////////////////////////////////////////////////////////////////////////// #[repr(u8)] #[derive(Debug, PartialEq, Eq, Clone, Copy, StableAbi)] pub enum RTryRecvError { Empty, Disconnected, } impl RTryRecvError { pub fn is_empty(&self) -> bool { *self == RTryRecvError::Empty } pub fn is_disconnected(&self) -> bool { *self == RTryRecvError::Disconnected } } impl Display for RTryRecvError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let msg = match self { RTryRecvError::Empty { .. } => "Attempting to recv on an empty channel", RTryRecvError::Disconnected { .. } => "Attempting to recv on a disconnected channel", }; f.pad(msg) } } impl ErrorTrait for RTryRecvError {} impl_from_rust_repr! { impl From<TryRecvError> for RTryRecvError { fn(this){ match this { TryRecvError::Empty=> RTryRecvError::Empty, TryRecvError::Disconnected=> RTryRecvError::Disconnected, } } } } impl_into_rust_repr! { impl Into<TryRecvError> for RTryRecvError { fn(this){ match this { RTryRecvError::Empty=>TryRecvError::Empty, RTryRecvError::Disconnected=>TryRecvError::Disconnected, } } } } /////////////////////////////////////////////////////////////////////////////// #[repr(u8)] #[derive(PartialEq, Eq, Clone, Copy, StableAbi)] pub enum RSendTimeoutError<T> { Timeout(T), Disconnected(T), } impl<T> RSendTimeoutError<T> { pub fn into_inner(self) -> T { match self { RSendTimeoutError::Timeout(v) => v, RSendTimeoutError::Disconnected(v) => v, } } pub fn is_timeout(&self) -> bool { matches!(self, RSendTimeoutError::Timeout { .. }) } pub fn is_disconnected(&self) -> bool { matches!(self, RSendTimeoutError::Disconnected { .. }) } } impl<T> Debug for RSendTimeoutError<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let msg = match self { RSendTimeoutError::Timeout { .. } => "Timeout{..}", RSendTimeoutError::Disconnected { .. } => "Disconnected{..}", }; f.pad(msg) } } impl<T> Display for RSendTimeoutError<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let msg = match *self { RSendTimeoutError::Timeout { .. } => "Timed out while attempting to send on a channel", RSendTimeoutError::Disconnected { .. } => { "Attempting to send on a disconnected channel" } }; f.pad(msg) } } impl<T> ErrorTrait for RSendTimeoutError<T> {} impl_from_rust_repr! { impl[T] From<SendTimeoutError<T>> for RSendTimeoutError<T> { fn(this){ match this { SendTimeoutError::Timeout(v)=> RSendTimeoutError::Timeout(v), SendTimeoutError::Disconnected(v)=> RSendTimeoutError::Disconnected(v), } } } } impl_into_rust_repr! { impl[T] Into<SendTimeoutError<T>> for RSendTimeoutError<T> { fn(this){ match this { RSendTimeoutError::Timeout(v)=> SendTimeoutError::Timeout(v), RSendTimeoutError::Disconnected(v)=> SendTimeoutError::Disconnected(v), } } } } /////////////////////////////////////////////////////////////////////////////// #[repr(u8)] #[derive(Debug, PartialEq, Eq, Clone, Copy, StableAbi)] pub enum RRecvTimeoutError { Timeout, Disconnected, } impl RRecvTimeoutError { pub fn is_timeout(&self) -> bool { matches!(self, RRecvTimeoutError::Timeout { .. }) } pub fn is_disconnected(&self) -> bool { matches!(self, RRecvTimeoutError::Disconnected { .. }) } } impl Display for RRecvTimeoutError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let msg = match self { RRecvTimeoutError::Timeout { .. } => "Timed out while attempting to recv on a channel", RRecvTimeoutError::Disconnected { .. } => { "Attempting to recv on a disconnected channel" } }; f.pad(msg) } } impl ErrorTrait for RRecvTimeoutError {} impl_from_rust_repr! { impl From<RecvTimeoutError> for RRecvTimeoutError { fn(this){ match this { RecvTimeoutError::Timeout=> RRecvTimeoutError::Timeout, RecvTimeoutError::Disconnected=> RRecvTimeoutError::Disconnected, } } } } impl_into_rust_repr! { impl Into<RecvTimeoutError> for RRecvTimeoutError { fn(this){ match this { RRecvTimeoutError::Timeout=> RecvTimeoutError::Timeout, RRecvTimeoutError::Disconnected=> RecvTimeoutError::Disconnected, } } } } ///////////////////////////////////////////////////////////////////////////////
extern crate sync; extern crate postgres; extern crate time; use std::str::from_utf8; use std::io::{Acceptor, Listener}; use std::io::{TcpListener, TcpStream}; use time::Timespec; use postgres::{PostgresConnection, NoSsl}; struct SensorPacket { id: i32, value: f64, name: String, time_created: time::Timespec } fn handle_sensor(mut stream: TcpStream, db: Sender<SensorPacket>) { // let sensor_name: String = match stream.read_line() { // Ok(s) => s, // Err(e) => { // println!("Error reading name from stream {}", e); // return; // }, // }; let mut tmp = [0u8, ..1024]; stream.read(tmp); let sensor_name = from_utf8(tmp).expect("unable to parse buffer to a utf8 string").to_string(); // let firstPacket: Vec<&str> = req.split_str(":").collect(); // let sensor_name = String::from_str(firstPacket[0]); println!("New sensor with name {}", sensor_name) // let mut buffer = [0u8, ..1024]; let mut id: i32 = 0; loop { let req = stream.read_be_f64(); // let req = str::from_utf8(buffer).expect("unable to parse buffer to a utf8 string").to_owned(); match req { Ok(x) => { println!("HANDLE_SENSOR got {}", x); db.send(SensorPacket { value: x, name: sensor_name.clone(), time_created: time::get_time(), id: id}); id += 1; }, Err(e) => { println!("Error reading sensor data {}", e); break; }, } // let p: f64 = match from_str::from_str::<f64>(req.as_slice()) { // Some(x) => x, // None => 0.0 // }; } drop(stream); } // fn handle_hook(mut stream: TcpStream, receiver Receiver<(int, f64)>, sender Sender<(id, &str)>) { // let mut tmp = [0u8, ..1024]; // stream.read(tmp); // let req = str::from_utf8(tmp).expect("unable to parse buffer to a utf8 string").to_owned(); // let v: Vec<&str> = req.as_slice().split_str(":").collect(); // // let sensor_name = String::from_str(v[0]); // sender.send((TypeId::of::<int>(), v[0])); // let mut buffer = [0u8, ..1024]; // while(true) { // // let s: Packet = mainChannel.recv(); // // if s.sensor == sensor_name { // // let v: &[u8] = match s.value { // // Some(x) => format!("{:s}", x.to_string()).as_bytes(), // // None => format!("{}", s.value).as_bytes(), // // }; // // stream.write(v) // // } // let (id, data) = receiver.recv(); // stream.write(format!("{:s}", data); // } // drop(stream) // } fn main() { // let mutex1 = Arc::new(RWLock::new(Vec::new())); // let mutex2 = mutex1.clone(); // spawn(proc() { // let hook_listener = TcpListener::bind("127.0.0.1", 8079); // let mut hook = hook_listener.listen(); // // accept connections and process them, spawning a new tasks for each one // for stream in hook.incoming() { // println!("hey") // match stream { // Err(e) => { /* connection failed */ } // Ok(stream) => { // let mutex3 = mutex2.clone(); // spawn(proc() { // let mut tmp = [0u8, ..1024]; // stream.read(tmp); // let req = str::from_utf8(tmp).expect("unable to parse buffer to a utf8 string").to_owned(); // let v: Vec<&str> = req.as_slice().split_str(":").collect(); // let mut val = mutex3.write(); // // let sensor_name = String::from_str(v[0]); // val.push(SensorPacket{stream: stream, sensor_name: String::from_str(v[0])}); // let val = val.downgrade(); // // let mut buffer = [0u8, ..1024]; // // while(true) { // // // let s: Packet = mainChannel.recv(); // // // if s.sensor == sensor_name { // // // let v: &[u8] = match s.value { // // // Some(x) => format!("{:s}", x.to_string()).as_bytes(), // // // None => format!("{}", s.value).as_bytes(), // // // }; // // // stream.write(v) // // // } // // let (id, data) = receiver.recv(); // // stream.write(format!("{:s}", data); // // } // drop(stream) // // handle_hook(stream, sensorReceiver, hookSender.clone()) // }) // } // } // } // drop(hook); // }); // let value = mutex1.read(); // println!("Length {}", value.len()); // let (sensorSender, sensorReceiver): (Sender<(int, f64)>, Receiver<(int, f64)>) = channel(); // spawn(proc() { // let hook_listener = TcpListener::bind("127.0.0.1", 8079); // let mut hook = hook_listener.listen(); // // accept connections and process them, spawning a new tasks for each one // for stream in hook.incoming() { // match stream { // Err(e) => { /* connection failed */ } // Ok(stream) => spawn(proc() { // handle_hook(stream, sensorReceiver, hookSender.clone()) // }) // } // } // drop(hook); // }); // let (sender, receiver): (Sender<SensorPacket>, Receiver<SensorPacket>) = channel(); // let conn = PostgresConnection::connect("postgres://root:alphabeta@127.0.0.1:5432/local",&NoSsl).unwrap(); // let stmt = conn.prepare("SELECT id, name, time_created, value FROM sensors") // .unwrap(); // for row in stmt.query([]).unwrap() { // let data = SensorPacket { // id: row.get(0), // name: row.get(1), // time_created: row.get(2), // value: row.get(3) // }; // println!("Found {}, {}, {}, {}", data.id, data.name, data.time_created, data.value); // } let (sender, receiver): (Sender<SensorPacket>, Receiver<SensorPacket>) = channel(); spawn(proc(){ let conn = PostgresConnection::connect("postgres://root:alphabeta@127.0.0.1:5432/local",&NoSsl).unwrap(); // conn.execute("CREATE TABLE sensors ( // id SERIAL PRIMARY KEY, // name VARCHAR NOT NULL, // time_created TIMESTAMP NOT NULL, // value DOUBLE PRECISION // )", []).unwrap(); loop { let data = receiver.recv(); println!("Receiver got {} from {} at {}", data.value, data.name, data.time_created); conn.execute("INSERT INTO sensors (name, time_created, value) VALUES ($1, $2, $3)", &[&data.name, &data.time_created, &data.value]).unwrap(); } }); let sensor_listener = TcpListener::bind("127.0.0.1", 8000); let mut sensors = sensor_listener.listen(); // accept connections and process them, spawning a new tasks for each one for stream in sensors.incoming() { match stream { Err(e) => { println!("Error connecting to a sensor {}", e); break; } Ok(stream) => { println!("New connection"); let sender_copy = sender.clone(); spawn(proc() { handle_sensor(stream, sender_copy) }) } } } drop(sensors); }
use crate::{ routes::crates_io::crate_versions::CrateVersionsGenerator, source::{Source, SourceBuilder}, }; pub mod crate_versions; pub struct CratesIoSource; impl SourceBuilder for CratesIoSource { fn build_source() -> Source { Source::new("crates-io").register(CrateVersionsGenerator) } }
use super::InternalEvent; use crate::transforms::lua::v1::format_error; use metrics::{counter, gauge}; #[derive(Debug)] pub struct LuaEventProcessed; impl InternalEvent for LuaEventProcessed { fn emit_metrics(&self) { counter!("events_processed", 1, "component_kind" => "transform", "component_type" => "lua", ); } } #[derive(Debug)] pub struct LuaGcTriggered { pub used_memory: usize, } impl InternalEvent for LuaGcTriggered { fn emit_metrics(&self) { gauge!("memory_used", self.used_memory as i64, "component_kind" => "transform", "component_type" => "lua", ); } } #[derive(Debug)] pub struct LuaScriptError { pub error: rlua::Error, } impl InternalEvent for LuaScriptError { fn emit_logs(&self) { let error = format_error(&self.error); error!(message = "error in lua script; discarding event.", %error, rate_limit_secs = 30); } fn emit_metrics(&self) { counter!("processing_errors", 1, "component_kind" => "transform", "component_type" => "lua", ); } }
#[path = "is_process_alive_1/with_self.rs"] mod with_self; #[path = "is_process_alive_1/without_self.rs"] mod without_self; test_stdout!(without_pid_errors_badarg, "{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n{caught, error, badarg}\n");
#[cfg(test)] mod test; use crate::runtime::time::datetime; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; #[native_implemented::function(erlang:time/0)] pub fn result(process: &Process) -> Term { let time: [usize; 3] = datetime::local_time(); process.tuple_from_slice(&[ process.integer(time[0]), process.integer(time[1]), process.integer(time[2]), ]) }
use crate::services::{config::Config, database::DB}; use events::Handler; use lazy_static::lazy_static; use log::warn; use serenity::{ framework::standard::{ help_commands, macros::help, Args, CommandGroup, CommandResult, HelpOptions, StandardFramework, }, model::prelude::{Message, UserId}, prelude::*, utils::Colour, Client, }; use std::collections::HashSet; use std::sync::Arc; mod commands; pub mod components; pub mod embeds; mod events; mod hooks; mod loops; mod utils; lazy_static! { static ref INTENTS: GatewayIntents = GatewayIntents::DIRECT_MESSAGES .union(GatewayIntents::MESSAGE_CONTENT) .union(GatewayIntents::GUILD_MESSAGE_REACTIONS) .union(GatewayIntents::GUILD_MESSAGES) .union(GatewayIntents::GUILD_MEMBERS) .union(GatewayIntents::GUILDS); } #[help] #[command_not_found_text = "Could not find: `{}`."] #[strikethrough_commands_tip_in_dm = "~~`Strikethrough commands`~~ are unavailable because the bot is unable to run them."] #[strikethrough_commands_tip_in_guild = "~~`Strikethrough commands`~~ are unavailable because the bot is unable to run them."] #[max_levenshtein_distance(3)] #[lacking_permissions = "Hide"] #[lacking_role = "Hide"] #[wrong_channel = "Strike"] #[group_prefix = "Prefix commands"] async fn my_help( ctx: &Context, msg: &Message, args: Args, help_options: &'static HelpOptions, groups: &[&'static CommandGroup], owners: HashSet<UserId>, ) -> CommandResult { let mut ho = help_options.clone(); ho.embed_error_colour = Colour::from_rgb(255, 30, 30); ho.embed_success_colour = Colour::from(0x00adf8); let _ = help_commands::with_embeds(ctx, msg, args, &ho, groups, owners).await; Ok(()) } pub async fn start(config: Config) { let framework = StandardFramework::new() .configure(|c| { c.prefix(&config.prefix); c.allow_dm(true); c.case_insensitivity(true); c }) .on_dispatch_error(hooks::dispatch_error_hook) .group(&commands::general::COMMANDS_GROUP) .group(&commands::nasa::NASA_GROUP) .group(&commands::get::GET_GROUP) .group(&commands::config::CONFIG_GROUP) .help(&MY_HELP); let mut client = Client::builder(&config.token, *INTENTS) .framework(framework) .event_handler(Handler { run_loops: Mutex::new(true), }) .application_id(config.application_id) .await .expect("Failed to create a new client"); let db = DB::new(&config.db_uri) .await .expect("Failed to initialize database"); db.run_migrations().await.expect("Failed to run migrations"); { let mut data = client.data.write().await; data.insert::<Config>(Arc::new(config)); data.insert::<DB>(Arc::new(db)); } if let Err(e) = client.start_autosharded().await { warn!("Failed to login, is the token correct?\n{}", e); } }
use std::io; use std::io::Read; use regex::Regex; fn matches_rule(val: u16, rule: (u16, u16, u16, u16)) -> bool { (rule.0 <= val && val <= rule.1) || (rule.2 <= val && val <= rule.3) } fn main() { let mut input = String::new(); io::stdin().read_to_string(&mut input).unwrap(); let re_rule = Regex::new(r"(?m)^([a-z ]+): (\d+)-(\d+) or (\d+)-(\d+)$").unwrap(); let re_your_ticket = Regex::new(r"(?m)^your ticket:\n((?:\d+,)*\d+)$").unwrap(); let re_nearby_tickets = Regex::new(r"(?m)^nearby tickets:\n((?:\d+[,\n])*\d+)$").unwrap(); let rules: Vec<_> = re_rule.captures_iter(&input).map(|rule| {( rule[1].to_string(), (rule[2].parse().unwrap(), rule[3].parse().unwrap(), rule[4].parse().unwrap(), rule[5].parse().unwrap()), )}).collect(); let mut rules_matched = vec![false; rules.len()]; let your_ticket: Vec<u16> = re_your_ticket .captures(&input) .unwrap()[1] .split(',') .map(|x| x.parse().unwrap()) .collect(); let tickets: Vec<_> = re_nearby_tickets.captures(&input).unwrap()[1].lines().filter_map(|x| { let values: Vec<_> = x.split(',').map(|y| y.parse().unwrap()).collect(); if values.iter().all(|&y| { rules.iter().any(|&(_, z)| matches_rule(y, z)) }) { Some(values) } else { None } }).chain([&your_ticket].iter().cloned().cloned()).collect(); let mut ticket_fields: Vec<(_, Vec<_>)> = (0..your_ticket.len()).map(|x| { (None, tickets.iter().map(|y| y[x]).collect()) }).collect(); let mut product = 1; while !rules_matched.iter().enumerate().all(|(n, &x)| x || !rules[n].0.starts_with("departure")) { let new_matched: Vec<_> = ticket_fields.iter_mut().enumerate().filter_map(|(n, (matched_rules, values))| { let matched_rules: &mut Vec<_> = if let Some(matched) = matched_rules { matched } else { *matched_rules = Some(rules.iter().enumerate().filter_map(|(n, &(_, limits))| { if values.iter().all(|&y| matches_rule(y, limits)) { Some(n) } else { None } }).collect()); matched_rules.as_mut().unwrap() }; *matched_rules = matched_rules.iter().cloned().filter(|&x| !rules_matched[x]).collect(); if matched_rules.len() == 1 { let rule_index = matched_rules[0]; if rules[rule_index].0.starts_with("departure") { product *= *values.last().unwrap() as u64; } rules_matched[rule_index] = true; Some(n) } else { None } }).collect(); if new_matched.len() == 0 { panic!("Found no matches"); } for &i in new_matched.iter().rev() { ticket_fields.remove(i); } } println!("{}", product); }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::alloc::Allocator; use super::table0::Entry; type Ent<V> = Entry<[u8; 2], V>; pub struct Table1<V, A: Allocator + Clone> { pub(crate) data: Box<[Entry<[u8; 2], V>; 65536], A>, pub(crate) len: usize, } impl<V, A: Allocator + Clone> Table1<V, A> { pub fn new_in(allocator: A) -> Self { Self { data: unsafe { let mut res = Box::<[Entry<[u8; 2], V>; 65536], A>::new_zeroed_in(allocator).assume_init(); res[0].key.write([0xff, 0xff]); res }, len: 0, } } pub fn capacity(&self) -> usize { 65536 } pub fn len(&self) -> usize { self.len } pub fn heap_bytes(&self) -> usize { std::mem::size_of::<[Entry<[u8; 2], V>; 65536]>() } pub fn get(&self, key: [u8; 2]) -> Option<&Ent<V>> { let e = &self.data[key[1] as usize * 256 + key[0] as usize]; if unsafe { e.key.assume_init() } == key { Some(e) } else { None } } pub fn get_mut(&mut self, key: [u8; 2]) -> Option<&mut Ent<V>> { let e = &mut self.data[key[1] as usize * 256 + key[0] as usize]; if unsafe { e.key.assume_init() } == key { Some(e) } else { None } } /// # Safety /// /// The resulted `MaybeUninit` should be initialized immedidately. pub fn insert(&mut self, key: [u8; 2]) -> Result<&mut Ent<V>, &mut Ent<V>> { let e = &mut self.data[key[1] as usize * 256 + key[0] as usize]; if unsafe { e.key.assume_init() } == key { Err(e) } else { self.len += 1; e.key.write(key); Ok(e) } } pub fn iter(&self) -> Table1Iter<'_, V> { Table1Iter { slice: self.data.as_ref(), i: 0, } } pub fn iter_mut(&mut self) -> Table1IterMut<'_, V> { Table1IterMut { slice: self.data.as_mut(), i: 0, } } } impl<V, A: Allocator + Clone> Drop for Table1<V, A> { fn drop(&mut self) { if std::mem::needs_drop::<V>() { self.iter_mut().for_each(|e| unsafe { e.val.assume_init_drop(); }); } } } pub struct Table1Iter<'a, V> { slice: &'a [Entry<[u8; 2], V>; 65536], i: usize, } impl<'a, V> Iterator for Table1Iter<'a, V> { type Item = &'a Entry<[u8; 2], V>; fn next(&mut self) -> Option<Self::Item> { while self.i < 65536 && unsafe { u16::from_le_bytes(self.slice[self.i].key.assume_init()) as usize != self.i } { self.i += 1; } if self.i == 65536 { None } else { let res = unsafe { &*(self.slice.as_ptr().add(self.i) as *const _) }; self.i += 1; Some(res) } } } pub struct Table1IterMut<'a, V> { slice: &'a mut [Entry<[u8; 2], V>; 65536], i: usize, } impl<'a, V> Iterator for Table1IterMut<'a, V> { type Item = &'a mut Entry<[u8; 2], V>; fn next(&mut self) -> Option<Self::Item> { while self.i < 65536 && unsafe { u16::from_le_bytes(self.slice[self.i].key.assume_init()) as usize != self.i } { self.i += 1; } if self.i == 65536 { None } else { let res = unsafe { &mut *(self.slice.as_ptr().add(self.i) as *mut _) }; self.i += 1; Some(res) } } }
#[doc = "Reader of register HOSTXDESC"] pub type R = crate::R<u32, super::HOSTXDESC>; #[doc = "Reader of field `CURTXDESC`"] pub type CURTXDESC_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - Host Transmit Descriptor Address Pointer"] #[inline(always)] pub fn curtxdesc(&self) -> CURTXDESC_R { CURTXDESC_R::new((self.bits & 0xffff_ffff) as u32) } }
use crate::p2p::{MultiaddrWithPeerId, MultiaddrWithoutPeerId}; use crate::subscription::{SubscriptionFuture, SubscriptionRegistry}; use core::task::{Context, Poll}; use libp2p::core::{connection::ConnectionId, ConnectedPoint, Multiaddr, PeerId}; use libp2p::swarm::handler::DummyConnectionHandler; use libp2p::swarm::{ self, dial_opts::{DialOpts, PeerCondition}, ConnectionHandler, DialError, NetworkBehaviour, PollParameters, Swarm, }; use std::collections::{hash_map::Entry, HashMap, HashSet, VecDeque}; use std::convert::{TryFrom, TryInto}; use std::time::{Duration, Instant}; /// A description of currently active connection. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Connection { /// The connected peer along with its address. pub addr: MultiaddrWithPeerId, /// Latest ping report on any of the connections. pub rtt: Option<Duration>, } /// Disconnected will use banning to disconnect a node. Disconnecting a single peer connection is /// not supported at the moment. pub struct Disconnector { peer_id: PeerId, } impl Disconnector { pub fn disconnect<T: NetworkBehaviour>(self, swarm: &mut Swarm<T>) { Swarm::ban_peer_id(swarm, self.peer_id); Swarm::unban_peer_id(swarm, self.peer_id); } } // Currently this is swarm::NetworkBehaviourAction<Void, Void> type NetworkBehaviourAction = swarm::NetworkBehaviourAction< <<SwarmApi as NetworkBehaviour>::ConnectionHandler as ConnectionHandler>::OutEvent, <SwarmApi as NetworkBehaviour>::ConnectionHandler, >; #[derive(Debug, Default)] pub struct SwarmApi { events: VecDeque<NetworkBehaviourAction>, // FIXME: anything related to this is probably wrong, and doesn't behave as one would expect // from the method names peers: HashSet<PeerId>, connect_registry: SubscriptionRegistry<(), String>, connections: HashMap<MultiaddrWithoutPeerId, PeerId>, roundtrip_times: HashMap<PeerId, Duration>, connected_peers: HashMap<PeerId, Vec<MultiaddrWithoutPeerId>>, connected_times: HashMap<PeerId, Instant>, /// The connections which have been requested, but the swarm/network is yet to ask for /// addresses; currently filled in the order of adding, with the default size of one. pending_addresses: HashMap<PeerId, Vec<MultiaddrWithPeerId>>, /// The connections which have been requested, and the swarm/network has requested the /// addresses of. Used to keep finishing all of the subscriptions. pending_connections: HashMap<PeerId, Vec<MultiaddrWithPeerId>>, pub(crate) bootstrappers: HashSet<MultiaddrWithPeerId>, } impl SwarmApi { pub fn add_peer(&mut self, peer_id: PeerId) { self.peers.insert(peer_id); } pub fn peers(&self) -> impl Iterator<Item = &PeerId> { self.peers.iter() } pub fn remove_peer(&mut self, peer_id: &PeerId) { self.peers.remove(peer_id); } pub fn connections(&self) -> impl Iterator<Item = Connection> + '_ { self.connected_peers .iter() .filter_map(move |(peer, conns)| { let rtt = self.roundtrip_times.get(peer).cloned().or_else(|| { // If no rountrip time yet, just return time since connected. // See: https://github.com/rs-ipfs/rust-ipfs/issues/178 self.connected_times.get(peer).map(Instant::elapsed) }); conns.first().map(|any| Connection { addr: MultiaddrWithPeerId::from((any.clone(), *peer)), rtt, }) }) } pub fn set_rtt(&mut self, peer_id: &PeerId, rtt: Duration) { // NOTE: this is for any connection self.roundtrip_times.insert(*peer_id, rtt); } pub fn connect(&mut self, addr: MultiaddrWithPeerId) -> Option<SubscriptionFuture<(), String>> { let connected_already = self .connected_peers .get(&addr.peer_id) .map(|conns| conns.iter().any(|wo| wo == &addr.multiaddr)) .unwrap_or(false); if connected_already { return None; } trace!("Connecting to {:?}", addr); let subscription = self .connect_registry .create_subscription(addr.clone().into(), None); let handler = self.new_handler(); self.events.push_back(NetworkBehaviourAction::Dial { // rationale: this is sort of explicit command, perhaps the old address is no longer // valid. Always would be even better but it's bugged at the moment. opts: DialOpts::peer_id(addr.peer_id) .condition(PeerCondition::NotDialing) .build(), handler, }); // store this for returning the time since connecting started before ping is available self.connected_times.insert(addr.peer_id, Instant::now()); self.pending_addresses .entry(addr.peer_id) .or_insert_with(|| Vec::with_capacity(1)) .push(addr); Some(subscription) } pub fn disconnect(&mut self, addr: MultiaddrWithPeerId) -> Option<Disconnector> { trace!("request to disconnect {}", addr); if let Some(&peer_id) = self.connections.get(&addr.multiaddr) { Some(Disconnector { peer_id }) } else { None } } pub fn connections_to(&self, peer_id: &PeerId) -> Vec<Multiaddr> { self.connected_peers .get(peer_id) .cloned() .map(|addrs| addrs.into_iter().map(From::from).collect()) .unwrap_or_default() } } impl NetworkBehaviour for SwarmApi { type ConnectionHandler = DummyConnectionHandler; type OutEvent = void::Void; fn new_handler(&mut self) -> Self::ConnectionHandler { Default::default() } fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec<Multiaddr> { // when libp2p starts dialing, it'll collect these from all of known addresses for the peer // from the behaviour and dial them all through, ending with calls to inject_connected or // inject_addr_reach_failure. let addresses = self.pending_addresses.remove(peer_id).unwrap_or_default(); // store the "given out" addresses as we have created the subscriptions for them self.pending_connections .entry(*peer_id) .or_default() .extend(addresses.iter().cloned()); addresses.into_iter().map(|a| a.into()).collect() } fn inject_connection_established( &mut self, peer_id: &PeerId, _connection_id: &ConnectionId, endpoint: &ConnectedPoint, _failed_addresses: Option<&Vec<Multiaddr>>, _other_established: usize, ) { // TODO: could be that the connection is not yet fully established at this point trace!("inject_connection_established {} {:?}", peer_id, endpoint); let addr = connection_point_addr(endpoint); self.peers.insert(*peer_id); let connections = self.connected_peers.entry(*peer_id).or_default(); connections.push(addr.clone()); let prev = self.connections.insert(addr.clone(), *peer_id); if let Some(prev) = prev { error!( "tracked connection was replaced from {} => {}: {}", prev, peer_id, addr ); } if let ConnectedPoint::Dialer { address, role_override: _, } = endpoint { // we dialed to the `address` match self.pending_connections.entry(*peer_id) { Entry::Occupied(mut oe) => { let addresses = oe.get_mut(); let address: MultiaddrWithPeerId = address .clone() .try_into() .expect("dialed address contains peerid in libp2p 0.38"); let just_connected = addresses.iter().position(|x| *x == address); if let Some(just_connected) = just_connected { addresses.swap_remove(just_connected); if addresses.is_empty() { oe.remove(); } self.connect_registry .finish_subscription(address.into(), Ok(())); } } Entry::Vacant(_) => { // we not connecting to this peer through this api, must be libp2p_kad or // something else. } } } // we have at least one fully open connection and handler is running // // just finish all of the subscriptions that remain. trace!("inject connected {}", peer_id); let all_subs = self .pending_addresses .remove(peer_id) .unwrap_or_default() .into_iter() .chain( self.pending_connections .remove(peer_id) .unwrap_or_default() .into_iter(), ); for addr in all_subs { // fail the other than already connected subscriptions in // inject_connection_established. while the whole swarmapi is quite unclear on the // actual use cases, assume that connecting one is good enough for all outstanding // connection requests. self.connect_registry.finish_subscription( addr.into(), Err("finished connecting to another address".into()), ); } } fn inject_connection_closed( &mut self, peer_id: &PeerId, _id: &ConnectionId, endpoint: &ConnectedPoint, _handler: Self::ConnectionHandler, _remaining_established: usize, ) { trace!("inject_connection_closed {} {:?}", peer_id, endpoint); let closed_addr = connection_point_addr(endpoint); match self.connected_peers.entry(*peer_id) { Entry::Occupied(mut oe) => { let connections = oe.get_mut(); let pos = connections.iter().position(|addr| *addr == closed_addr); if let Some(pos) = pos { connections.swap_remove(pos); } if connections.is_empty() { oe.remove(); } } Entry::Vacant(_) => {} } let removed = self.connections.remove(&closed_addr); debug_assert!( removed.is_some(), "connection was not tracked but it should had been: {}", closed_addr ); self.connected_times.remove(peer_id); if let ConnectedPoint::Dialer { .. } = endpoint { let addr = MultiaddrWithPeerId::from((closed_addr, peer_id.to_owned())); match self.pending_connections.entry(*peer_id) { Entry::Occupied(mut oe) => { let connections = oe.get_mut(); let pos = connections.iter().position(|x| addr == *x); if let Some(pos) = pos { connections.swap_remove(pos); // this needs to be guarded, so that the connect test case doesn't cause a // panic following inject_connection_established, inject_connection_closed // if there's only the DummyConnectionHandler, which doesn't open a // substream and closes up immediatedly. self.connect_registry.finish_subscription( addr.into(), Err("Connection reset by peer".to_owned()), ); } if connections.is_empty() { oe.remove(); } } Entry::Vacant(_) => {} } } else { // we were not dialing to the peer, thus we cannot have a pending subscription to // finish. } } fn inject_event(&mut self, _peer_id: PeerId, _connection: ConnectionId, _event: void::Void) {} fn inject_dial_failure( &mut self, peer_id: Option<PeerId>, _handler: Self::ConnectionHandler, error: &DialError, ) { // TODO: there might be additional connections we should attempt // (i.e) a new MultiAddr was found after sending the existing ones // off to dial if let Some(peer_id) = peer_id { match self.pending_connections.entry(peer_id) { Entry::Occupied(mut oe) => { let addresses = oe.get_mut(); match error { DialError::Transport(multiaddrs) => { for (addr, error) in multiaddrs { let addr = MultiaddrWithPeerId::try_from(addr.clone()) .expect("to recieve an MultiAddrWithPeerId from DialError"); self.connect_registry.finish_subscription( addr.clone().into(), Err(error.to_string()), ); if let Some(pos) = addresses.iter().position(|a| *a == addr) { addresses.swap_remove(pos); } } } DialError::WrongPeerId { .. } => { for addr in addresses.iter() { self.connect_registry.finish_subscription( addr.clone().into(), Err(error.to_string()), ); } addresses.clear(); } error => { warn!( ?error, "unexpected DialError; some futures might never complete" ); } } if addresses.is_empty() { oe.remove(); } // FIXME from libp2p-0.43 upgrade: unclear if there could be a need for new // dial attempt if new entries to self.pending_addresses arrived. } Entry::Vacant(_) => {} } } } fn poll( &mut self, _: &mut Context, _: &mut impl PollParameters, ) -> Poll<NetworkBehaviourAction> { if let Some(event) = self.events.pop_front() { Poll::Ready(event) } else { Poll::Pending } } } fn connection_point_addr(cp: &ConnectedPoint) -> MultiaddrWithoutPeerId { match cp { ConnectedPoint::Dialer { address, role_override: _, } => MultiaddrWithPeerId::try_from(address.to_owned()) .expect("dialed address contains peerid in libp2p 0.38") .into(), ConnectedPoint::Listener { send_back_addr, .. } => send_back_addr .to_owned() .try_into() .expect("send back address does not contain peerid in libp2p 0.38"), } } #[cfg(test)] mod tests { use super::*; use crate::p2p::transport::build_transport; use futures::{ stream::{StreamExt, TryStreamExt}, TryFutureExt, }; use libp2p::identity::Keypair; use libp2p::swarm::SwarmEvent; use libp2p::{multiaddr::Protocol, multihash::Multihash, swarm::Swarm, swarm::SwarmBuilder}; use std::convert::TryInto; #[tokio::test] async fn swarm_api() { let (peer1_id, mut swarm1) = build_swarm(); let (peer2_id, mut swarm2) = build_swarm(); Swarm::listen_on(&mut swarm1, "/ip4/127.0.0.1/tcp/0".parse().unwrap()).unwrap(); loop { if let Some(SwarmEvent::NewListenAddr { .. }) = swarm1.next().await { break; } } let listeners = Swarm::listeners(&swarm1).cloned().collect::<Vec<_>>(); for mut addr in listeners { addr.push(Protocol::P2p( Multihash::from_bytes(&peer1_id.to_bytes()).unwrap(), )); let mut sub = swarm2 .behaviour_mut() .connect(addr.try_into().unwrap()) .unwrap(); loop { tokio::select! { biased; _ = (&mut swarm1).next() => {}, _ = (&mut swarm2).next() => {}, res = (&mut sub) => { // this is currently a success even though the connection is never really // established, the DummyConnectionHandler doesn't do anything nor want the // connection to be kept alive and thats it. // // it could be argued that this should be `Err("keepalive disconnected")` // or something and I'd agree, but I also agree this can be an `Ok(())`; // it's the sort of difficulty with the cli functionality in general: what // does it mean to connect to a peer? one way to look at it would be to // make the peer a "pinned peer" or "friend" and to keep the connection // alive at all costs. perhaps that is something for the next round. // another aspect would be to fail this future because there was no // `inject_connected`, only `inject_connection_established`. taking that // route would be good; it does however leave the special case of adding // another connection, which does add even more complexity than it exists // at the present. res.unwrap(); // just to confirm that there are no connections. assert_eq!(Vec::<Multiaddr>::new(), swarm1.behaviour().connections_to(&peer2_id)); break; } } } } } #[tokio::test] async fn wrong_peerid() { let (swarm1_peerid, mut swarm1) = build_swarm(); let (_, mut swarm2) = build_swarm(); let peer3_id = Keypair::generate_ed25519().public().to_peer_id(); Swarm::listen_on(&mut swarm1, "/ip4/127.0.0.1/tcp/0".parse().unwrap()).unwrap(); let addr; loop { if let Some(SwarmEvent::NewListenAddr { address, .. }) = swarm1.next().await { // wonder if there should be a timeout? addr = address; break; } } let mut fut = swarm2 .behaviour_mut() .connect( MultiaddrWithoutPeerId::try_from(addr) .unwrap() .with(peer3_id), ) .unwrap() // remove the private type wrapper .map_err(|e| e.into_inner()); loop { tokio::select! { _ = swarm1.next() => {}, _ = swarm2.next() => {}, res = &mut fut => { let err = res.unwrap_err().unwrap(); let expected_start = format!("Dial error: Unexpected peer ID {}", swarm1_peerid); assert_eq!(&err[0..expected_start.len()], expected_start); return; } } } } #[tokio::test] async fn racy_connecting_attempts() { let (peer1_id, mut swarm1) = build_swarm(); let (_, mut swarm2) = build_swarm(); Swarm::listen_on(&mut swarm1, "/ip4/127.0.0.1/tcp/0".parse().unwrap()).unwrap(); Swarm::listen_on(&mut swarm1, "/ip4/127.0.0.1/tcp/0".parse().unwrap()).unwrap(); let mut addr = Vec::with_capacity(2); while addr.len() < 2 { if let Some(SwarmEvent::NewListenAddr { address, .. }) = swarm1.next().await { addr.push(address); } } let targets = ( MultiaddrWithoutPeerId::try_from(addr[0].clone()) .unwrap() .with(peer1_id), MultiaddrWithoutPeerId::try_from(addr[1].clone()) .unwrap() .with(peer1_id), ); let mut connections = futures::stream::FuturesOrdered::new(); // these two should be attempted in parallel. since we know both of them work, and they are // given in this order, we know that in libp2p 0.34 only the first should win, however // both should always be finished. connections.push(swarm2.behaviour_mut().connect(targets.0).unwrap()); connections.push(swarm2.behaviour_mut().connect(targets.1).unwrap()); let ready = connections // turn the private error type into Option .map_err(|e| e.into_inner()) .collect::<Vec<_>>(); tokio::pin!(ready); loop { tokio::select! { _ = swarm1.next() => {} _ = swarm2.next() => {} res = &mut ready => { assert_eq!( res, vec![ Ok(()), Err(Some("finished connecting to another address".into())) ]); break; } } } } fn build_swarm() -> (PeerId, libp2p::swarm::Swarm<SwarmApi>) { let key = Keypair::generate_ed25519(); let peer_id = key.public().to_peer_id(); let transport = build_transport(key).unwrap(); let swarm = SwarmBuilder::new(transport, SwarmApi::default(), peer_id) .executor(Box::new(ThreadLocalTokio)) .build(); (peer_id, swarm) } use std::future::Future; use std::pin::Pin; // can only be used from within tokio context. this is required since otherwise libp2p-tcp will // use tokio, but from a futures-executor threadpool, which is outside of tokio context. struct ThreadLocalTokio; impl libp2p::core::Executor for ThreadLocalTokio { fn exec(&self, future: Pin<Box<dyn Future<Output = ()> + Send + 'static>>) { tokio::task::spawn(future); } } }
use super::AutoCfg; #[test] fn autocfg_version() { let ac = AutoCfg::with_dir("target").unwrap(); println!("version: {:?}", ac.rustc_version); assert!(ac.probe_rustc_version(1, 0)); } #[test] fn version_cmp() { use super::version::Version; let v123 = Version::new(1, 2, 3); assert!(Version::new(1, 0, 0) < v123); assert!(Version::new(1, 2, 2) < v123); assert!(Version::new(1, 2, 3) == v123); assert!(Version::new(1, 2, 4) > v123); assert!(Version::new(1, 10, 0) > v123); assert!(Version::new(2, 0, 0) > v123); } #[test] fn probe_add() { let ac = AutoCfg::with_dir("target").unwrap(); assert!(ac.probe_path("std::ops::Add")); assert!(ac.probe_trait("std::ops::Add")); assert!(ac.probe_trait("std::ops::Add<i32>")); assert!(ac.probe_trait("std::ops::Add<i32, Output = i32>")); assert!(ac.probe_type("std::ops::Add<i32, Output = i32>")); } #[test] fn probe_as_ref() { let ac = AutoCfg::with_dir("target").unwrap(); assert!(ac.probe_path("std::convert::AsRef")); assert!(ac.probe_trait("std::convert::AsRef<str>")); assert!(ac.probe_type("std::convert::AsRef<str>")); } #[test] fn probe_i128() { let ac = AutoCfg::with_dir("target").unwrap(); let missing = !ac.probe_rustc_version(1, 26); assert!(missing ^ ac.probe_path("std::i128")); assert!(missing ^ ac.probe_type("i128")); } #[test] fn probe_sum() { let ac = AutoCfg::with_dir("target").unwrap(); let missing = !ac.probe_rustc_version(1, 12); assert!(missing ^ ac.probe_path("std::iter::Sum")); assert!(missing ^ ac.probe_trait("std::iter::Sum")); assert!(missing ^ ac.probe_trait("std::iter::Sum<i32>")); assert!(missing ^ ac.probe_type("std::iter::Sum<i32>")); }
use serde::Serialize; macro_rules! mk_limits{ ( $($id:ident : $type:ty = $value:expr,)* ) => { #[derive(Serialize)] pub struct Limits { $( pub $id : $type, )* } pub const LIMITS : Limits = Limits { $( $id : $value, )* }; } } mk_limits! { msg_text_len: usize = 4096, msg_name_len: usize = 32, msg_subject_len: usize = 64, media_max_count: usize = 5, media_orig_name_len: usize = 128, media_content_type: [&'static str; 2] = ["image/png", "image/jpeg"], /* XXX: for some reason multipart crate accepts sizes up to * 1024*1024*10 + 8047 */ media_max_file_size: u64 = 10*1024*1024, media_max_area: &'static str = "unimplemented", }
//! Types and parsers for the `FROM` clause common to `DELETE` or `SHOW` schema statements. use crate::common::{ qualified_measurement_name, ws1, MeasurementName, OneOrMore, Parser, QualifiedMeasurementName, }; use crate::identifier::{identifier, Identifier}; use crate::internal::ParseResult; use crate::keywords::keyword; use nom::sequence::{pair, preceded}; use std::fmt; use std::fmt::{Display, Formatter}; /// Represents a `FROM` clause of a `DELETE` or `SHOW` statement. /// /// A `FROM` clause for a `DELETE` can only accept [`Identifier`] or regular expressions /// for measurements names. /// /// A `FROM` clause for a number of `SHOW` statements can accept a [`QualifiedMeasurementName`]. pub type FromMeasurementClause<U> = OneOrMore<U>; fn from_clause<T: Parser + fmt::Display>(i: &str) -> ParseResult<&str, FromMeasurementClause<T>> { preceded( pair(keyword("FROM"), ws1), FromMeasurementClause::<T>::separated_list1( "invalid FROM clause, expected identifier or regular expression", ), )(i) } impl Parser for QualifiedMeasurementName { fn parse(i: &str) -> ParseResult<&str, Self> { qualified_measurement_name(i) } } /// Represents a `FROM` clause used by various `SHOW` statements. /// /// A `FROM` clause for a `SHOW` statements differs from a `FROM` in a /// `SELECT`, as it can only contain measurement name or regular expressions. /// /// It is defined by the following EBNF notation: /// /// ```text /// from_clause ::= "FROM" qualified_measurement_name ("," qualified_measurement_name)* /// /// qualified_measurement_name ::= measurement_name | /// ( policy_name "." measurement_name ) | /// ( db_name "." policy_name? "." measurement_name ) /// /// db_name ::= identifier /// measurement_name ::= identifier | regex_lit /// policy_name ::= identifier /// ``` /// /// A minimal `FROM` clause would be a single identifier /// /// ```text /// FROM foo /// ``` /// /// A more complicated example may include a variety of fully-qualified /// identifiers and regular expressions /// /// ```text /// FROM foo, /bar/, some_database..foo, some_retention_policy.foobar /// ``` pub type ShowFromClause = FromMeasurementClause<QualifiedMeasurementName>; impl Display for ShowFromClause { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "FROM {}", self.head())?; for arg in self.tail() { write!(f, ", {arg}")?; } Ok(()) } } /// Parse a `FROM` clause for various `SHOW` statements. pub(crate) fn show_from_clause(i: &str) -> ParseResult<&str, ShowFromClause> { from_clause(i) } impl Parser for Identifier { fn parse(i: &str) -> ParseResult<&str, Self> { identifier(i) } } /// Represents a `FROM` clause for a `DELETE` statement. pub type DeleteFromClause = FromMeasurementClause<MeasurementName>; impl Display for DeleteFromClause { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "FROM {}", self.head())?; for arg in self.tail() { write!(f, ", {arg}")?; } Ok(()) } } /// Parse a `FROM` clause for a `DELETE` statement. pub(crate) fn delete_from_clause(i: &str) -> ParseResult<&str, DeleteFromClause> { from_clause(i) } #[cfg(test)] mod test { use super::*; #[test] fn test_show_from_clause() { use crate::common::MeasurementName::*; let (_, from) = show_from_clause("FROM c").unwrap(); assert_eq!( from, ShowFromClause::new(vec![QualifiedMeasurementName::new(Name("c".into()))]) ); let (_, from) = show_from_clause("FROM a..c").unwrap(); assert_eq!( from, ShowFromClause::new(vec![QualifiedMeasurementName::new_db( Name("c".into()), "a".into() )]) ); let (_, from) = show_from_clause("FROM a.b.c").unwrap(); assert_eq!( from, ShowFromClause::new(vec![QualifiedMeasurementName::new_db_rp( Name("c".into()), "a".into(), "b".into() )]) ); let (_, from) = show_from_clause("FROM /reg/").unwrap(); assert_eq!( from, ShowFromClause::new(vec![QualifiedMeasurementName::new(Regex("reg".into()))]) ); let (_, from) = show_from_clause("FROM c, /reg/").unwrap(); assert_eq!( from, ShowFromClause::new(vec![ QualifiedMeasurementName::new(Name("c".into())), QualifiedMeasurementName::new(Regex("reg".into())) ]) ); } #[test] fn test_delete_from_clause() { use crate::common::MeasurementName::*; let (_, from) = delete_from_clause("FROM c").unwrap(); assert_eq!(from, DeleteFromClause::new(vec![Name("c".into())])); let (_, from) = delete_from_clause("FROM /reg/").unwrap(); assert_eq!(from, DeleteFromClause::new(vec![Regex("reg".into())])); let (_, from) = delete_from_clause("FROM c, /reg/").unwrap(); assert_eq!( from, DeleteFromClause::new(vec![Name("c".into()), Regex("reg".into())]) ); // Demonstrate that the 3-part name is not parsed let (i, from) = delete_from_clause("FROM a.b.c").unwrap(); assert_eq!(from, DeleteFromClause::new(vec![Name("a".into())])); // The remaining input will fail in a later parser assert_eq!(i, ".b.c"); } }
use sdl2::image::{self, InitFlag}; use sdl2::keyboard::Keycode; use sdl2::mouse::MouseState; use sdl2::rect::Point; use sdl2::video::Window; use sdl2::EventPump; use std::collections::HashSet; pub struct Input { pub keys_current: HashSet<Keycode>, pub keys_down: HashSet<Keycode>, keys_up: HashSet<Keycode>, mouse_state: MouseState, } impl Input { pub fn new() -> Self { Input { keys_current: HashSet::new(), keys_down: HashSet::new(), keys_up: HashSet::new(), mouse_state: MouseState::from_sdl_state(0), } } } impl Input { pub fn get_key_down(&self, key: Keycode) -> bool { self.keys_down.contains(&key) } pub fn get_key(&self, key: Keycode) -> bool { self.keys_current.contains(&key) } pub fn get_key_up(&self, key: Keycode) -> bool { self.keys_up.contains(&key) } pub fn set_mouse_state(&mut self, events: &EventPump) { let state = events.mouse_state(); self.mouse_state = state; } pub fn set_keys(&mut self, events: &EventPump) { let keys = events .keyboard_state() .pressed_scancodes() .filter_map(Keycode::from_scancode) .collect(); let new_keys = &keys - &self.keys_current; let old_keys = &self.keys_current - &keys; self.keys_down = new_keys; self.keys_up = old_keys; self.keys_current = keys; } pub fn get_mouse_pos(&mut self) -> Point { Point::new(self.mouse_state.x(), self.mouse_state.y()) } } pub struct Config { pub width: u32, pub height: u32, pub canvas_scale: f32, pub title: String, } fn parse_config(config: Option<Config>) -> Config { match config { Some(res) => res, None => Config { width: 1200, height: 800, canvas_scale: 0.5, title: "rg2d".to_string(), }, } } pub struct Context { pub window: Window, pub input: Input, pub gl_context: sdl2::video::GLContext, } impl Context { pub fn new(config: Option<Config>) -> (Context, EventPump) { let _config = parse_config(config); let sdl = sdl2::init().unwrap(); let video_subsystem = sdl.video().unwrap(); let gl_attr = video_subsystem.gl_attr(); gl_attr.set_context_profile(sdl2::video::GLProfile::Core); gl_attr.set_context_version(4, 1); let window = video_subsystem .window("Game", _config.width, _config.height) .opengl() .resizable() .build() .unwrap(); let gl_context = window.gl_create_context().unwrap(); gl::load_with(|s| video_subsystem.gl_get_proc_address(s) as *const std::os::raw::c_void); let input = Input::new(); ( Context { window, input, gl_context, }, sdl.event_pump().unwrap(), ) } }
mod with_atom_name; use super::*; use crate::runtime::scheduler::SchedulerDependentAlloc; #[test] fn without_atom_name_errors_badarg() { run!( |arc_process| { ( Just(arc_process.clone()), strategy::term::is_not_atom(arc_process.clone()), strategy::term(arc_process.clone()), ) }, |(arc_process, name, message)| { let destination = arc_process.tuple_from_slice(&[name, erlang::node_0::result()]); prop_assert_badarg!( result(&arc_process, destination, message), format!("registered_name ({}) in {{registered_name, node}} ({}) destination is not an atom", name, destination) ); Ok(()) }, ); } #[test] fn with_local_reference_name_errors_badarg() { with_name_errors_badarg(|process| process.next_reference()); } #[test] fn with_empty_list_name_errors_badarg() { with_name_errors_badarg(|_| Term::NIL); } #[test] fn with_list_name_errors_badarg() { with_name_errors_badarg(|process| process.cons(process.integer(0), process.integer(1))); } #[test] fn with_small_integer_name_errors_badarg() { with_name_errors_badarg(|process| process.integer(0)); } #[test] fn with_big_integer_name_errors_badarg() { with_name_errors_badarg(|process| process.integer(SmallInteger::MAX_VALUE + 1)); } #[test] fn with_float_name_errors_badarg() { with_name_errors_badarg(|process| process.float(1.0)); } #[test] fn with_local_pid_name_errors_badarg() { with_name_errors_badarg(|_| Pid::make_term(0, 1).unwrap()); } #[test] fn with_external_pid_name_errors_badarg() { with_name_errors_badarg(|process| process.external_pid(external_arc_node(), 2, 3).unwrap()); } #[test] fn with_tuple_name_errors_badarg() { with_name_errors_badarg(|process| process.tuple_from_slice(&[])); } #[test] fn with_map_name_errors_badarg() { with_name_errors_badarg(|process| process.map_from_slice(&[])); } #[test] fn with_heap_binary_name_errors_badarg() { with_name_errors_badarg(|process| process.binary_from_bytes(&[])); } #[test] fn with_subbinary_name_errors_badarg() { with_name_errors_badarg(|process| bitstring!(1 :: 1, &process)); } fn with_name_errors_badarg<N>(name: N) where N: FnOnce(&Process) -> Term, { with_process(|process| { let destination = process.tuple_from_slice(&[name(process), erlang::node_0::result()]); let message = Atom::str_to_term("message"); assert_badarg!( result(process, destination, message), "destination is not an atom" ); }) }
// ***************************************************************************** // // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software // Foundation; either version 2 of the License, or (at your option) any later // version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more // details. // // You should have received a copy of the GNU General Public License along with // this program; if not, write to the Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Module authors: // Enrico Faulhaber <enrico.faulhaber@frm2.tum.de> // Georg Brandl <g.brandl@fz-juelich.de> // // ***************************************************************************** use std::collections::HashMap; use std::net::{UdpSocket, TcpStream, Ipv4Addr}; use std::time::Duration; use ads::{AmsAddr, AmsNetId, udp}; use anyhow::{anyhow, Context, Result}; use log::{debug, info, error}; use mlzutil::{self, bytes::hexdump}; use crate::forwarder::{Beckhoff, BhType}; use crate::util::{FWDER_NETID, BECKHOFF_BC_UDP_PORT, BECKHOFF_UDP_PORT, BECKHOFF_TCP_PORT}; /// Determines what to scan. pub enum Scan<'a> { Everything, Interface(&'a str), Address(Ipv4Addr), NetId(AmsNetId), } pub struct Scanner { dump: bool, if_addrs: HashMap<String, (Ipv4Addr, Ipv4Addr)>, } impl Scanner { pub fn new(dump: bool) -> Scanner { Scanner { dump, if_addrs: mlzutil::net::iface::find_ipv4_addrs() } } pub fn if_exists(&self, if_name: &str) -> bool { self.if_addrs.contains_key(if_name) } /// Scan the locally reachable network for Beckhoffs. /// /// If given a `Scan::Interface`, only IPs on that interface are scanned. /// If given a `Scan::Address`, only that IP is scanned. /// /// Returns a vector of found Beckhoffs. pub fn scan(&self, what: Scan) -> Vec<Beckhoff> { match self.scan_inner(what) { Ok(v) => v, Err(err) => { error!("during scan: {err:#}"); Vec::new() } } } fn scan_inner(&self, what: Scan) -> Result<Vec<Beckhoff>> { let broadcast = [255, 255, 255, 255].into(); match what { Scan::Address(bh_addr) => self.scan_addr([0, 0, 0, 0].into(), bh_addr, true), Scan::Interface(if_name) => self.scan_addr(self.if_addrs[if_name].0, broadcast, false), Scan::Everything => { let mut all = Vec::new(); for (if_name, &(if_addr, _)) in &self.if_addrs { debug!("scanning interface {if_name}"); all.extend(self.scan_addr(if_addr, broadcast, false)?); } Ok(all) } Scan::NetId(netid) => { // scan all interfaces until we found our NetID for (if_name, &(if_addr, _)) in &self.if_addrs { debug!("scanning interface {if_name}"); let bhs = self.scan_addr(if_addr, broadcast, false) .with_context(|| format!("scanning interface {if_name}"))?; if let Some(bh) = bhs.into_iter().find(|bh| bh.netid == netid) { return Ok(vec![bh]); } } Ok(vec![]) } } } fn scan_addr(&self, bind_addr: Ipv4Addr, send_addr: Ipv4Addr, single_reply: bool) -> Result<Vec<Beckhoff>> { let udp = UdpSocket::bind((bind_addr, 0)).context("binding UDP socket")?; udp.set_broadcast(true)?; udp.set_read_timeout(Some(Duration::from_millis(500)))?; // scan for BCs: request 3 words from 0:33 (NetID) and 10 words from 100:4 (Name) let bc_msg = [1, 0, 0, 0, 0, 0, 33, 0, 3, 0, 100, 0, 4, 0, 10, 0]; udp.send_to(&bc_msg, (send_addr, BECKHOFF_BC_UDP_PORT)) .context("sending BC scan broadcast")?; debug!("scan: sending BC UDP packet"); if self.dump { hexdump(&bc_msg); } // scan for CXs: "identify" operation in the UDP protocol let cx_msg = udp::Message::new(udp::ServiceId::Identify, AmsAddr::new(FWDER_NETID, 10000)); udp.send_to(cx_msg.as_bytes(), (send_addr, BECKHOFF_UDP_PORT)) .context("sending CX scan broadcast")?; debug!("scan: sending CX UDP packet"); if self.dump { hexdump(cx_msg.as_bytes()); } // wait for replies let mut beckhoffs = Vec::new(); let mut reply = [0; 2048]; while let Ok((len, reply_addr)) = udp.recv_from(&mut reply) { let reply = &reply[..len]; if self.dump { info!("scan: reply from {reply_addr}"); hexdump(reply); } let bh_addr = mlzutil::net::unwrap_ipv4(reply_addr.ip()); if reply_addr.port() == BECKHOFF_BC_UDP_PORT { if reply.len() == 42 && reply[0..4] == [1, 0, 0, 0x80] { let netid = AmsNetId::from_slice(&reply[10..16]).unwrap(); let name = &reply[22..32]; let name = String::from_utf8_lossy( &name[..name.iter().position(|&ch| ch == 0).unwrap_or(10)]); info!("scan: found {name} ({netid}) at {bh_addr}"); beckhoffs.push(Beckhoff { if_addr: self.find_if_addr(bh_addr), typ: BhType::BC, bh_addr, netid }); } } else if let Ok(msg) = udp::Message::parse(reply, udp::ServiceId::Identify, true) { let name = msg.get_str(udp::Tag::ComputerName).unwrap_or("<???>"); let ver = msg.get_bytes(udp::Tag::TCVersion).ok_or_else(|| anyhow!("no version info"))?; info!("scan: found {name}, TwinCat {}.{}.{} ({}) at {bh_addr}", ver[0], ver[1], ver[2] as u16 | (ver[3] as u16) << 8, msg.get_source()); beckhoffs.push(Beckhoff { if_addr: self.find_if_addr(bh_addr), typ: if ver[0] == 2 { BhType::CX2 } else { BhType::CX3 }, bh_addr, netid: msg.get_source().netid() }); } // if scanning a single address, don't wait for more replies if single_reply { break; } } Ok(beckhoffs) } /// Find the local address of the interface to connect to the given Beckhoff. fn find_if_addr(&self, bh_addr: Ipv4Addr) -> Ipv4Addr { // check for local IPs for &(if_addr, if_mask) in self.if_addrs.values() { if mlzutil::net::in_same_net(bh_addr, if_addr, if_mask) { return if_addr; } } // not a local IP, check by trying to connect using TCP match TcpStream::connect((bh_addr, BECKHOFF_TCP_PORT)).and_then(|sock| sock.local_addr()) { Ok(addr) => mlzutil::net::unwrap_ipv4(addr.ip()), _ => panic!("Did not find local address for route to Beckhoff {bh_addr}") } } }
fn main(){ proconio::input!{n:u64,a:[u64;n]} let mut m=0; let mut x=0; for &i in a.iter(){ if i<m{x+=m-i;} m=m.max(i); } println!("{}",x); }
// Original implementation Copyright 2013 The Rust Project Developers <https://github.com/rust-lang> // // Original source file: https://github.com/rust-lang/rust/blob/master/src/libstd/io/buffered.rs // // Modifications copyright 2018 Austin Bonander <austin.bonander@gmail.com> // // 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. //! Tests checking `Buffer::new_ringbuf()` and friends. //! //! Some may be adapted from rust/src/libstd/io/buffered.rs //! //! Since `SliceDeque` rounds allocations up to the page size or larger, these cannot assume //! a small capacity like `std_test` does. // TODO: add tests centered around the mirrored buf boundary use std::io::prelude::*; use std::io::{self, SeekFrom}; use {Buffer, BufReader, DEFAULT_BUF_SIZE}; use std_tests::ShortReader; macro_rules! assert_capacity { ($buf:expr, $cap:expr) => { let cap = $buf.capacity(); if cfg!(windows) { // Windows' minimum allocation size is 64K assert_eq!(cap, ::std::cmp::max(64 * 1024, cap)); } else { assert_eq!(cap, $cap); } } } #[test] fn test_buffer_new() { let buf = Buffer::new_ringbuf(); assert_capacity!(buf, DEFAULT_BUF_SIZE); assert_eq!(buf.capacity(), buf.usable_space()); } #[test] fn test_buffer_with_cap() { let buf = Buffer::with_capacity_ringbuf(4 * 1024); assert_capacity!(buf, 4 * 1024); // test rounding up to page size let buf = Buffer::with_capacity_ringbuf(64); assert_capacity!(buf, 4 * 1024); assert_eq!(buf.capacity(), buf.usable_space()); } #[test] fn test_buffered_reader() { let inner: &[u8] = &[5, 6, 7, 0, 1, 2, 3, 4]; let mut reader = BufReader::new_ringbuf(inner); let mut buf = [0, 0, 0]; let nread = reader.read(&mut buf); assert_eq!(nread.unwrap(), 3); let b: &[_] = &[5, 6, 7]; assert_eq!(buf, b); let mut buf = [0, 0]; let nread = reader.read(&mut buf); assert_eq!(nread.unwrap(), 2); let b: &[_] = &[0, 1]; assert_eq!(buf, b); let mut buf = [0]; let nread = reader.read(&mut buf); assert_eq!(nread.unwrap(), 1); let b: &[_] = &[2]; assert_eq!(buf, b); let mut buf = [0, 0, 0]; let nread = reader.read(&mut buf); assert_eq!(nread.unwrap(), 2); let b: &[_] = &[3, 4, 0]; assert_eq!(buf, b); assert_eq!(reader.read(&mut buf).unwrap(), 0); } #[test] fn test_buffered_reader_seek() { let inner: &[u8] = &[5, 6, 7, 0, 1, 2, 3, 4]; let mut reader = BufReader::new_ringbuf(io::Cursor::new(inner)); assert_eq!(reader.seek(SeekFrom::Start(3)).ok(), Some(3)); assert_eq!(reader.fill_buf().ok(), Some(&[0, 1, 2, 3, 4][..])); assert_eq!(reader.seek(SeekFrom::Current(0)).ok(), Some(3)); assert_eq!(reader.fill_buf().ok(), Some(&[0, 1, 2, 3, 4][..])); assert_eq!(reader.seek(SeekFrom::Current(1)).ok(), Some(4)); assert_eq!(reader.fill_buf().ok(), Some(&[1, 2, 3, 4][..])); reader.consume(1); assert_eq!(reader.seek(SeekFrom::Current(-2)).ok(), Some(3)); assert_eq!(reader.fill_buf().ok(), Some(&[0, 1, 2, 3, 4][..])); } #[test] fn test_buffered_reader_seek_underflow() { // gimmick reader that yields its position modulo 256 for each byte struct PositionReader { pos: u64 } impl Read for PositionReader { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let len = buf.len(); for x in buf { *x = self.pos as u8; self.pos = self.pos.wrapping_add(1); } Ok(len) } } impl Seek for PositionReader { fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { match pos { SeekFrom::Start(n) => { self.pos = n; } SeekFrom::Current(n) => { self.pos = self.pos.wrapping_add(n as u64); } SeekFrom::End(n) => { self.pos = u64::max_value().wrapping_add(n as u64); } } Ok(self.pos) } } let mut reader = BufReader::with_capacity(5, PositionReader { pos: 0 }); assert_eq!(reader.fill_buf().ok(), Some(&[0, 1, 2, 3, 4][..])); assert_eq!(reader.seek(SeekFrom::End(-5)).ok(), Some(u64::max_value()-5)); assert_eq!(reader.fill_buf().ok().map(|s| s.len()), Some(5)); // the following seek will require two underlying seeks let expected = 9223372036854775802; assert_eq!(reader.seek(SeekFrom::Current(i64::min_value())).ok(), Some(expected)); assert_eq!(reader.fill_buf().ok().map(|s| s.len()), Some(5)); // seeking to 0 should empty the buffer. assert_eq!(reader.seek(SeekFrom::Current(0)).ok(), Some(expected)); assert_eq!(reader.get_ref().pos, expected); } #[test] fn test_read_until() { let inner: &[u8] = &[0, 1, 2, 1, 0]; let mut reader = BufReader::with_capacity(2, inner); let mut v = Vec::new(); reader.read_until(0, &mut v).unwrap(); assert_eq!(v, [0]); v.truncate(0); reader.read_until(2, &mut v).unwrap(); assert_eq!(v, [1, 2]); v.truncate(0); reader.read_until(1, &mut v).unwrap(); assert_eq!(v, [1]); v.truncate(0); reader.read_until(8, &mut v).unwrap(); assert_eq!(v, [0]); v.truncate(0); reader.read_until(9, &mut v).unwrap(); assert_eq!(v, []); } #[test] fn test_read_line() { let in_buf: &[u8] = b"a\nb\nc"; let mut reader = BufReader::with_capacity(2, in_buf); let mut s = String::new(); reader.read_line(&mut s).unwrap(); assert_eq!(s, "a\n"); s.truncate(0); reader.read_line(&mut s).unwrap(); assert_eq!(s, "b\n"); s.truncate(0); reader.read_line(&mut s).unwrap(); assert_eq!(s, "c"); s.truncate(0); reader.read_line(&mut s).unwrap(); assert_eq!(s, ""); } #[test] fn test_lines() { let in_buf: &[u8] = b"a\nb\nc"; let reader = BufReader::with_capacity(2, in_buf); let mut it = reader.lines(); assert_eq!(it.next().unwrap().unwrap(), "a".to_string()); assert_eq!(it.next().unwrap().unwrap(), "b".to_string()); assert_eq!(it.next().unwrap().unwrap(), "c".to_string()); assert!(it.next().is_none()); } #[test] fn test_short_reads() { let inner = ShortReader{lengths: vec![0, 1, 2, 0, 1, 0]}; let mut reader = BufReader::new(inner); let mut buf = [0, 0]; assert_eq!(reader.read(&mut buf).unwrap(), 0); assert_eq!(reader.read(&mut buf).unwrap(), 1); assert_eq!(reader.read(&mut buf).unwrap(), 2); assert_eq!(reader.read(&mut buf).unwrap(), 0); assert_eq!(reader.read(&mut buf).unwrap(), 1); assert_eq!(reader.read(&mut buf).unwrap(), 0); assert_eq!(reader.read(&mut buf).unwrap(), 0); } #[cfg(feature = "nightly")] #[test] fn read_char_buffered() { let buf = [195, 159]; let reader = BufReader::with_capacity(1, &buf[..]); assert_eq!(reader.chars().next().unwrap().unwrap(), 'ß'); } #[cfg(feature = "nightly")] #[test] fn test_chars() { let buf = [195, 159, b'a']; let reader = BufReader::with_capacity(1, &buf[..]); let mut it = reader.chars(); assert_eq!(it.next().unwrap().unwrap(), 'ß'); assert_eq!(it.next().unwrap().unwrap(), 'a'); assert!(it.next().is_none()); } /// Test that the ringbuffer wraps as intended #[test] fn test_mirror_boundary() { // pretends the given bytes have been read struct FakeReader(usize); impl Read for FakeReader { fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(self.0) } } let mut buffer = Buffer::new_ringbuf(); let cap = buffer.capacity(); // declaring these as variables for sanity let read_amt = cap; // fill the buffer let test_slice = &[1, 2, 3, 4, 5]; let consume_amt = read_amt - 5; // leave several bytes on the head side of the mirror assert_eq!(buffer.read_from(&mut FakeReader(read_amt)).unwrap(), read_amt); assert_eq!(buffer.usable_space(), cap - read_amt); // should be 0 assert_eq!(buffer.read_from(&mut FakeReader(read_amt)).unwrap(), 0); // buffer is full buffer.consume(consume_amt); assert_eq!(buffer.usable_space(), consume_amt); assert_eq!(buffer.copy_from_slice(test_slice), test_slice.len()); // zeroes are the bytes we didn't consume assert_eq!(buffer.buf(), &[0, 0, 0, 0, 0, 1, 2, 3, 4, 5]); buffer.clear(); assert_eq!(buffer.usable_space(), cap); } #[test] fn issue_8(){ let source = vec![0u8; 4096*4]; let mut rdr = BufReader::with_capacity_ringbuf(4096, source.as_slice()); loop { let n = rdr.read_into_buf().unwrap(); if n == 0 { break; } rdr.consume(4000); // rdr.make_room(); // (only necessary with 'standard' reader) println!("{}", n); } } // `BufWriter` doesn't utilize a ringbuffer
use rocket::request::Form; use rocket_contrib::json::JsonValue; use crate::http::console::PagingParams; use crate::http::user_session; use crate::http::{session_user, Context}; use crate::models::domain::Domain; use crate::models::user::UserFlag; use crate::repo::{DomainRepo}; use crate::{conn, util}; #[derive(FromForm, Debug)] pub struct DomainEntity { pub id: i32, pub domain: String, pub user_id: i32, pub notes: String, pub state: i16, } #[post("/domain/list", data = "<p>")] pub fn domain_list(p: PagingParams, ctx: Context) -> JsonValue { let user_id: i32 = p .data .get("user_id") .expect("缺少参数:user_id") .parse() .unwrap_or(0); if !user_session::check_access(&ctx.req.cookies(), user_id) { return user_session::access_denied(); } let begin = ((p.page - 1) * p.rows) as i64; let over = begin + p.rows as i64; let (total, rows) = DomainRepo::take_domains(&conn(), user_id, begin, over); json!({"total":total,"rows":rows}) } #[post("/domain/get?<id>")] pub fn get_domain(id: i32, ctx: Context) -> JsonValue { match DomainRepo::get(&conn(), id) { Some(u) => { if !user_session::check_access(&ctx.req.cookies(), u.user_id) { return user_session::access_denied(); } json!(u) } None => json!({"err_msg":"域名不存在"}), } } #[post("/domain/save", data = "<entity>")] pub fn save_domain(ctx: Context, entity: Form<DomainEntity>) -> JsonValue { let i = UserFlag::SuperUser as i16; let u = session_user(&ctx.req.cookies()).unwrap(); if (u.flag & i != i) && u.id != entity.user_id { return json!({"code":1,"err_msg":"no such user"}); } let conn = &conn(); let mut domain: Domain; if entity.id > 0 { domain = DomainRepo::get(&conn, entity.id).expect("no such domain"); } else { domain = Domain { id: 0, user_id: entity.user_id, hash: "".to_string(), domain: String::from(""), flag: 0, state: 0, notes: String::from(""), create_time: 0, } } domain.domain = entity.domain.clone(); domain.state = entity.state; domain.notes = entity.notes.clone(); match DomainRepo::save(&conn, &domain) { Ok(_) => json!({"code":0}), Err(err) => json!({"code":1,"err_msg":err.message()}), } } #[post("/domain/stat_js?<self_host>&<hash>")] pub fn stat_js(self_host: i16, hash: String, ctx: Context) -> JsonValue { if let Some(d) = DomainRepo::get_domain(&conn(), hash.clone()) { if d.state == 0 { return json!({"code":1,"err_msg":"域名未启用,无法生成统计代码"}); } let mut js_url; if self_host == 1 { js_url = String::from("http://"); js_url.push_str(&d.domain); } else { js_url = util::self_pre_link(&ctx); } js_url.push_str("/static/domain_stat.js?"); js_url.push_str(&hash); return json!({"code":0,"url":js_url}); } json!({"code":1,"err_msg":"no such domain"}) }
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use common_meta_types::compat07; use common_meta_types::Entry; use common_meta_types::EntryPayload; use common_meta_types::LogId; use common_meta_types::Membership; use common_meta_types::Node; use common_meta_types::SeqNum; use common_meta_types::SeqV; use common_meta_types::SnapshotMeta; use common_meta_types::StoredMembership; use common_meta_types::Vote; use openraft::compat::Upgrade; use crate::SledBytesError; use crate::SledSerde; impl SledSerde for String { fn de<T: AsRef<[u8]>>(v: T) -> Result<Self, SledBytesError> where Self: Sized { let s = serde_json::from_slice(v.as_ref())?; Ok(s) } } impl<U> SledSerde for SeqV<U> where U: serde::Serialize + serde::de::DeserializeOwned { fn de<T: AsRef<[u8]>>(v: T) -> Result<Self, SledBytesError> where Self: Sized { let s = serde_json::from_slice(v.as_ref())?; Ok(s) } } impl SledSerde for SeqNum { fn de<T: AsRef<[u8]>>(v: T) -> Result<Self, SledBytesError> where Self: Sized { let s = serde_json::from_slice(v.as_ref())?; Ok(s) } } impl SledSerde for LogId { fn de<T: AsRef<[u8]>>(v: T) -> Result<Self, SledBytesError> where Self: Sized { let s: compat07::LogId = serde_json::from_slice(v.as_ref())?; Ok(s.upgrade()) } } impl SledSerde for Vote { fn de<T: AsRef<[u8]>>(v: T) -> Result<Self, SledBytesError> where Self: Sized { let s: compat07::Vote = serde_json::from_slice(v.as_ref())?; Ok(s.upgrade()) } } impl SledSerde for Membership { fn de<T: AsRef<[u8]>>(v: T) -> Result<Self, SledBytesError> where Self: Sized { let s: compat07::Membership = serde_json::from_slice(v.as_ref())?; Ok(s.upgrade()) } } impl SledSerde for StoredMembership { fn de<T: AsRef<[u8]>>(v: T) -> Result<Self, SledBytesError> where Self: Sized { let s: compat07::StoredMembership = serde_json::from_slice(v.as_ref())?; Ok(s.upgrade()) } } impl SledSerde for EntryPayload { fn de<T: AsRef<[u8]>>(v: T) -> Result<Self, SledBytesError> where Self: Sized { let s: compat07::EntryPayload = serde_json::from_slice(v.as_ref())?; Ok(s.upgrade()) } } impl SledSerde for Entry { fn de<T: AsRef<[u8]>>(v: T) -> Result<Self, SledBytesError> where Self: Sized { let s: compat07::Entry = serde_json::from_slice(v.as_ref())?; Ok(s.upgrade()) } } impl SledSerde for SnapshotMeta { fn de<T: AsRef<[u8]>>(v: T) -> Result<Self, SledBytesError> where Self: Sized { let s: compat07::SnapshotMeta = serde_json::from_slice(v.as_ref())?; Ok(s.upgrade()) } } impl SledSerde for Node { fn de<T: AsRef<[u8]>>(v: T) -> Result<Self, SledBytesError> where Self: Sized { let s = serde_json::from_slice(v.as_ref())?; Ok(s) } }
// 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 core::fmt; use std::convert::TryFrom; use common_exception::ErrorCode; use common_exception::Result; use enumflags2::bitflags; use enumflags2::BitFlags; use serde::Deserialize; use serde::Serialize; use crate::principal::AuthInfo; use crate::principal::UserGrantSet; use crate::principal::UserIdentity; use crate::principal::UserQuota; #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Default)] #[serde(default)] pub struct UserInfo { pub name: String, pub hostname: String, pub auth_info: AuthInfo, pub grants: UserGrantSet, pub quota: UserQuota, pub option: UserOption, } impl UserInfo { pub fn new(name: &str, hostname: &str, auth_info: AuthInfo) -> Self { // Default is no privileges. let grants = UserGrantSet::default(); let quota = UserQuota::no_limit(); let option = UserOption::default(); UserInfo { name: name.to_string(), hostname: hostname.to_string(), auth_info, grants, quota, option, } } pub fn new_no_auth(name: &str, hostname: &str) -> Self { UserInfo::new(name, hostname, AuthInfo::None) } pub fn identity(&self) -> UserIdentity { UserIdentity { username: self.name.clone(), hostname: self.hostname.clone(), } } pub fn has_option_flag(&self, flag: UserOptionFlag) -> bool { self.option.has_option_flag(flag) } pub fn update_auth_option(&mut self, auth: Option<AuthInfo>, option: Option<UserOption>) { if let Some(auth_info) = auth { self.auth_info = auth_info; }; if let Some(user_option) = option { self.option = user_option; }; } } impl TryFrom<Vec<u8>> for UserInfo { type Error = ErrorCode; fn try_from(value: Vec<u8>) -> Result<Self> { match serde_json::from_slice(&value) { Ok(user_info) => Ok(user_info), Err(serialize_error) => Err(ErrorCode::IllegalUserInfoFormat(format!( "Cannot deserialize user info from bytes. cause {}", serialize_error ))), } } } #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Default)] #[serde(default)] pub struct UserOption { flags: BitFlags<UserOptionFlag>, default_role: Option<String>, } impl UserOption { pub fn new(flags: BitFlags<UserOptionFlag>) -> Self { Self { flags, default_role: None, } } pub fn empty() -> Self { Default::default() } pub fn with_flags(mut self, flags: BitFlags<UserOptionFlag>) -> Self { self.flags = flags; self } pub fn with_default_role(mut self, default_role: Option<String>) -> Self { self.default_role = default_role; self } pub fn with_set_flag(mut self, flag: UserOptionFlag) -> Self { self.flags.insert(flag); self } pub fn flags(&self) -> &BitFlags<UserOptionFlag> { &self.flags } pub fn default_role(&self) -> Option<&String> { self.default_role.as_ref() } pub fn set_default_role(&mut self, default_role: Option<String>) { self.default_role = default_role; } pub fn set_all_flag(&mut self) { self.flags = BitFlags::all(); } pub fn set_option_flag(&mut self, flag: UserOptionFlag) { self.flags.insert(flag); } pub fn switch_option_flag(&mut self, flag: UserOptionFlag, on: bool) { if on { self.flags.insert(flag); } else { self.flags.remove(flag); } } pub fn unset_option_flag(&mut self, flag: UserOptionFlag) { self.flags.remove(flag); } pub fn has_option_flag(&self, flag: UserOptionFlag) -> bool { self.flags.contains(flag) } } #[bitflags] #[repr(u64)] #[derive(Serialize, Deserialize, Clone, Copy, Debug, Eq, PartialEq, num_derive::FromPrimitive)] pub enum UserOptionFlag { TenantSetting = 1 << 0, } impl std::fmt::Display for UserOptionFlag { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { UserOptionFlag::TenantSetting => write!(f, "TENANTSETTING"), } } } #[cfg(test)] mod tests { use enumflags2::BitFlags; use crate::principal::AuthInfo; use crate::principal::UserInfo; use crate::principal::UserOption; #[test] fn test_user_update_auth_option() -> anyhow::Result<()> { let mut u = UserInfo::new("a", "b", AuthInfo::None); // None does not take effect { let mut u2 = u.clone(); u2.update_auth_option(None, None); assert_eq!(u2, u); } // Some updates the corresponding fields { u.update_auth_option(Some(AuthInfo::JWT), Some(UserOption::new(BitFlags::all()))); assert_eq!(AuthInfo::JWT, u.auth_info); assert_eq!(BitFlags::all(), u.option.flags); } Ok(()) } }
use std::fs; fn main() { let result = solve_puzzle("input"); println!("And the result is {}", result); } fn solve_puzzle(file_name: &str) -> u32 { let mut layout = parse_layout(read_data(file_name)); loop { let new_layout = run_round(&layout); if new_layout == layout { break; }; layout = new_layout; } layout.iter().flatten().filter(|x| x == &&'#').count() as u32 } fn read_data(file_name: &str) -> String { fs::read_to_string(file_name).expect("Error") } fn run_round(layout: &Vec<Vec<char>>) -> Vec<Vec<char>> { let mut output: Vec<Vec<char>> = vec![]; for (row_idx, row) in layout.iter().enumerate() { let mut new_row: Vec<char> = vec![]; for (col_idx, seat) in row.iter().enumerate() { let seat_state = next_state(seat, layout, row_idx, col_idx); new_row.push(seat_state); } output.push(new_row); } output } fn next_state(seat: &char, layout: &Vec<Vec<char>>, row_idx: usize, col_idx: usize) -> char { let visible_occupied = count_visible_occupied(layout, row_idx, col_idx); match (seat, visible_occupied == 0, visible_occupied >= 5) { ('.', _, _) => '.', ('L', true, _) => '#', ('#', _, true) => 'L', (x, _, _) => *x, } } fn parse_layout(layout: String) -> Vec<Vec<char>> { layout .lines() .map(|line| line.chars().collect::<Vec<char>>()) .collect() } fn count_visible_occupied(layout: &Vec<Vec<char>>, row_idx: usize, col_idx: usize) -> u8 { let layout_cols = layout[0].len(); let layout_rows = layout.len(); let mut visible_occupied: u8 = 0; // above let mut i = 1; while row_idx >= i { match layout[row_idx - i][col_idx] { '#' => { visible_occupied += 1; break; } 'L' => break, _ => (), } i += 1; } // below i = 1; while row_idx + i < layout_rows { match layout[row_idx + i][col_idx] { '#' => { visible_occupied += 1; break; } 'L' => break, _ => (), } i += 1; } // right i = 1; while col_idx + i < layout_cols { match layout[row_idx][col_idx + i] { '#' => { visible_occupied += 1; break; } 'L' => break, _ => (), } i += 1; } // left i = 1; while col_idx >= i { match layout[row_idx][col_idx - i] { '#' => { visible_occupied += 1; break; } 'L' => break, _ => (), } i += 1; } // top left i = 1; while col_idx >= i && row_idx >= i { match layout[row_idx - i][col_idx - i] { '#' => { visible_occupied += 1; break; } 'L' => break, _ => (), } i += 1; } // top right i = 1; while col_idx + i < layout_cols && row_idx >= i { match layout[row_idx - i][col_idx + i] { '#' => { visible_occupied += 1; break; } 'L' => break, _ => (), } i += 1; } // bottom right i = 1; while col_idx + i < layout_cols && row_idx + i < layout_rows { match layout[row_idx + i][col_idx + i] { '#' => { visible_occupied += 1; break; } 'L' => break, _ => (), } i += 1; } // bottom left i = 1; while col_idx >= i && row_idx + i < layout_rows { match layout[row_idx + i][col_idx - i] { '#' => { visible_occupied += 1; break; } 'L' => break, _ => (), } i += 1; } visible_occupied } #[cfg(test)] mod test { use super::*; #[test] fn test_example() { assert_eq!(26, solve_puzzle("example_data")); } #[test] fn test_second_iteration() { let entry = parse_layout(String::from( "#.L#.L#.L#\n\ #LLLLLL.LL\n\ L.L.L..#..\n\ ##LL.LL.L#\n\ L.LL.LL.L#\n\ #.LLLLL.LL\n\ ..L.L.....\n\ LLLLLLLLL#\n\ #.LLLLL#.L\n\ #.L#LL#.L#", )); let output = parse_layout(String::from( "#.L#.L#.L#\n\ #LLLLLL.LL\n\ L.L.L..#..\n\ ##L#.#L.L#\n\ L.L#.#L.L#\n\ #.L####.LL\n\ ..#.#.....\n\ LLL###LLL#\n\ #.LLLLL#.L\n\ #.L#LL#.L#", )); assert_eq!(output, run_round(&entry)); } #[test] fn last_iteration() { let entry = parse_layout(String::from( "#.L#.L#.L#\n\ #LLLLLL.LL\n\ L.L.L..#..\n\ ##L#.#L.L#\n\ L.L#.#L.L#\n\ #.L####.LL\n\ ..#.#.....\n\ LLL###LLL#\n\ #.LLLLL#.L\n\ #.L#LL#.L#", )); let output = parse_layout(String::from( "#.L#.L#.L#\n\ #LLLLLL.LL\n\ L.L.L..#..\n\ ##L#.#L.L#\n\ L.L#.LL.L#\n\ #.LLLL#.LL\n\ ..#.L.....\n\ LLL###LLL#\n\ #.LLLLL#.L\n\ #.L#LL#.L#", )); assert_eq!(output, run_round(&entry)); } #[test] fn test_see_eight_occupied() { let layout = parse_layout(String::from( ".......#.\n\ ...#.....\n\ .#.......\n\ .........\n\ ..#L....#\n\ ....#....\n\ .........\n\ #........\n\ ...#.....", )); assert_eq!('L', next_state(&'L', &layout, 4, 3)) } #[test] fn see_no_occupied_seat() { let layout = parse_layout(String::from( ".##.##.\n\ #.#.#.#\n\ ##...##\n\ ...L...\n\ ##...##\n\ #.#.#.#\n\ .##.##.", )); assert_eq!(0, count_visible_occupied(&layout, 3, 3)) } #[test] fn no_visible_occupied_right() { let entry = parse_layout(String::from("L....L.#")); let result = count_visible_occupied(&entry, 0, 0); assert_eq!(0, result); } #[test] fn visible_occupied_right() { let entry = parse_layout(String::from("L......#")); let result = count_visible_occupied(&entry, 0, 0); assert_eq!(1, result); } #[test] fn no_visible_occupied_left() { let entry = parse_layout(String::from("#..L...L.")); let result = count_visible_occupied(&entry, 0, 7); assert_eq!(0, result); } #[test] fn visible_occupied_left() { let entry = parse_layout(String::from("#......L.")); let result = count_visible_occupied(&entry, 0, 7); assert_eq!(1, result); } #[test] fn visible_occupied_left_and_right() { let entry = parse_layout(String::from("L..#.#.L...#")); let result = count_visible_occupied(&entry, 0, 7); assert_eq!(2, result); } #[test] fn visible_occupied_below() { let entry = parse_layout(String::from( "L\n\ .\n\ .\n\ #\n\ #", )); let result = count_visible_occupied(&entry, 0, 0); assert_eq!(1, result); } #[test] fn no_visible_occupied_below() { let entry = parse_layout(String::from( "L\n\ L\n\ .\n\ #\n\ #", )); let result = count_visible_occupied(&entry, 0, 0); assert_eq!(0, result); } #[test] fn visible_occupied_above() { let entry = parse_layout(String::from( "#\n\ #\n\ .\n\ L\n\ .", )); let result = count_visible_occupied(&entry, 3, 0); assert_eq!(1, result); } #[test] fn no_visible_occupied_above() { let entry = parse_layout(String::from( "#\n\ #\n\ L\n\ L\n\ .", )); let result = count_visible_occupied(&entry, 3, 0); assert_eq!(0, result); } #[test] fn visible_occupied_above_and_below() { let entry = parse_layout(String::from( "#\n\ #\n\ .\n\ L\n\ .\n\ #", )); let result = count_visible_occupied(&entry, 3, 0); assert_eq!(2, result); } #[test] fn visible_occupied_top_right() { let entry = parse_layout(String::from( ".....#\n\ ......\n\ ...L..\n\ ......\n\ ......", )); let result = count_visible_occupied(&entry, 2, 3); assert_eq!(1, result); } #[test] fn no_visible_occupied_top_right() { let entry = parse_layout(String::from( ".....#\n\ ....L.\n\ ...L..\n\ ......\n\ ......", )); let result = count_visible_occupied(&entry, 2, 3); assert_eq!(0, result); } #[test] fn visible_occupied_bottom_left() { let entry = parse_layout(String::from( "......\n\ ......\n\ ...L..\n\ .....\n\ .#....", )); let result = count_visible_occupied(&entry, 2, 3); assert_eq!(1, result); } #[test] fn no_visible_occupied_bottom_left() { let entry = parse_layout(String::from( "......\n\ ......\n\ ...L..\n\ ..L..\n\ .#....", )); let result = count_visible_occupied(&entry, 2, 3); assert_eq!(0, result); } #[test] fn no_visible_occupied_top_left() { let entry = parse_layout(String::from( "L#L...\n\ ..L...\n\ ...L..\n\ .....\n\ ......", )); let result = count_visible_occupied(&entry, 2, 3); assert_eq!(0, result); } #[test] fn visible_occupied_top_left() { let entry = parse_layout(String::from( "L#L...\n\ ......\n\ ...L..\n\ .....\n\ ......", )); let result = count_visible_occupied(&entry, 2, 3); assert_eq!(1, result); } #[test] fn visible_occupied_bottom_right() { let entry = parse_layout(String::from( "......\n\ ......\n\ .L....\n\ .....\n\ ...#..", )); let result = count_visible_occupied(&entry, 2, 1); assert_eq!(1, result); } #[test] fn no_visible_occupied_bottom_right() { let entry = parse_layout(String::from( "......\n\ ......\n\ .L....\n\ ..L..\n\ ...#..", )); let result = count_visible_occupied(&entry, 2, 1); assert_eq!(0, result); } #[test] fn visible_nothing_nowhere() { let entry = parse_layout(String::from( ".....\n\ .....\n\ ..#..\n\ .....\n\ .....", )); let result = count_visible_occupied(&entry, 2, 2); assert_eq!(0, result); } #[test] fn count_visible_for() { let entry = parse_layout(String::from( "#.L#.##.L#\n\ #L#####.LL\n\ L.#.#..#..\n\ ##L#.##.##\n\ #.##.#L.##\n\ #.#####.#L\n\ ..#.#.....\n\ LLL####LL#\n\ #.L#####.L\n\ #.L####.L#", )); let result = count_visible_occupied(&entry, 0, 0); assert_eq!(1, result); } #[test] fn eight_visible() { let entry = parse_layout(String::from( ".......#.\n\ ...#.....\n\ .#.......\n\ .........\n\ ..#L....#\n\ ....#....\n\ .........\n\ #........\n\ ...#.....", )); let result = count_visible_occupied(&entry, 4, 3); assert_eq!(8, result); } #[test] fn eight_adjacent_visible() { let entry = parse_layout(String::from( ".....\n\ .###.\n\ .#L#.\n\ .###.\n\ .....", )); let result = count_visible_occupied(&entry, 2, 2); assert_eq!(8, result); } #[test] fn test_seat_hidden_by_empty_seat() { let entry = parse_layout(String::from( ".............\n\ .L.L.#.#.#.#.\n\ .............", )); let result = count_visible_occupied(&entry, 1, 1); assert_eq!(0, result); } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { crate::switchboard::base::*, crate::switchboard::hanging_get_handler::{HangingGetHandler, Sender}, crate::switchboard::switchboard_impl::SwitchboardImpl, failure::format_err, fidl_fuchsia_settings::*, fuchsia_async as fasync, fuchsia_syslog::fx_log_err, futures::lock::Mutex, futures::prelude::*, parking_lot::RwLock, std::sync::Arc, }; impl Sender<SystemSettings> for SystemWatchResponder { fn send_response(self, data: SystemSettings) { self.send(&mut Ok(data)).unwrap(); } } impl From<SettingResponse> for SystemSettings { fn from(response: SettingResponse) -> Self { if let SettingResponse::System(info) = response { let mut system_settings = fidl_fuchsia_settings::SystemSettings::empty(); system_settings.mode = Some(fidl_fuchsia_settings::LoginOverride::from(info.login_override_mode)); system_settings } else { panic!("incorrect value sent to system"); } } } pub fn spawn_system_fidl_handler( switchboard_handle: Arc<RwLock<SwitchboardImpl>>, mut stream: SystemRequestStream, ) { let hanging_get_handler: Arc<Mutex<HangingGetHandler<SystemSettings, SystemWatchResponder>>> = HangingGetHandler::create(switchboard_handle.clone(), SettingType::System); fasync::spawn(async move { while let Ok(Some(req)) = stream.try_next().await { #[allow(unreachable_patterns)] match req { SystemRequest::Set { settings, responder } => { if let Some(mode) = settings.mode { change_login_override( switchboard_handle.clone(), SystemLoginOverrideMode::from(mode), responder, ); } } SystemRequest::Watch { responder } => { let mut hanging_get_lock = hanging_get_handler.lock().await; hanging_get_lock.watch(responder).await; } _ => {} } } }); } /// Sets the login mode and schedules accounts to be cleared. Upon success, the /// device is scheduled to reboot so the change will take effect. fn change_login_override( switchboard: Arc<RwLock<dyn Switchboard + Send + Sync>>, mode: SystemLoginOverrideMode, responder: SystemSetResponder, ) { fasync::spawn(async move { let login_override_result = request( switchboard.clone(), SettingType::System, SettingRequest::SetLoginOverrideMode(mode), "set login override", ) .await; if login_override_result.is_err() { responder.send(&mut Err(fidl_fuchsia_settings::Error::Failed)).ok(); return; } let schedule_account_clear_result = request( switchboard.clone(), SettingType::Account, SettingRequest::ScheduleClearAccounts, "clear accounts", ) .await; if schedule_account_clear_result.is_err() { responder.send(&mut Err(fidl_fuchsia_settings::Error::Failed)).ok(); return; } let restart_result = request(switchboard.clone(), SettingType::Power, SettingRequest::Reboot, "rebooting") .await; if restart_result.is_err() { responder.send(&mut Err(fidl_fuchsia_settings::Error::Failed)).ok(); return; } responder.send(&mut Ok(())).ok(); }); } async fn request( switchboard: Arc<RwLock<dyn Switchboard + Send + Sync>>, setting_type: SettingType, setting_request: SettingRequest, description: &str, ) -> SettingResponseResult { let (response_tx, response_rx) = futures::channel::oneshot::channel::<SettingResponseResult>(); let result = switchboard.clone().write().request(setting_type, setting_request, response_tx); match result { Ok(()) => match response_rx.await { Ok(result) => { return result; } Err(error) => { fx_log_err!("request failed: {} error: {}", description, error); return Err(format_err!("request failed: {} error: {}", description, error)); } }, Err(error) => { fx_log_err!("request failed: {} error: {}", description, error); return Err(error); } } } impl From<fidl_fuchsia_settings::LoginOverride> for SystemLoginOverrideMode { fn from(item: fidl_fuchsia_settings::LoginOverride) -> Self { match item { fidl_fuchsia_settings::LoginOverride::AutologinGuest => { SystemLoginOverrideMode::AutologinGuest } fidl_fuchsia_settings::LoginOverride::AuthProvider => { SystemLoginOverrideMode::AuthProvider } fidl_fuchsia_settings::LoginOverride::None => SystemLoginOverrideMode::None, } } } impl From<SystemLoginOverrideMode> for fidl_fuchsia_settings::LoginOverride { fn from(item: SystemLoginOverrideMode) -> Self { match item { SystemLoginOverrideMode::AutologinGuest => { fidl_fuchsia_settings::LoginOverride::AutologinGuest } SystemLoginOverrideMode::AuthProvider => { fidl_fuchsia_settings::LoginOverride::AuthProvider } SystemLoginOverrideMode::None => fidl_fuchsia_settings::LoginOverride::None, } } }
use oxygengine::prelude::*; #[derive(Debug, Default)] pub struct GameState { camera: Option<Entity>, camera_ui: Option<Entity>, } impl State for GameState { fn on_enter(&mut self, world: &mut World) { // instantiate world objects from scene prefab. world .write_resource::<PrefabManager>() .instantiate_world("scene", world) .unwrap(); } fn on_process(&mut self, world: &mut World) -> StateChange { if let Some(camera) = self.camera { // check if we pressed left mouse button. let input = &world.read_resource::<InputController>(); if input.trigger_or_default("pointer-action").is_pressed() { // get mouse screen space coords. let x = input.axis_or_default("pointer-x"); let y = input.axis_or_default("pointer-y"); let point = [x, y].into(); // convert mouse coords from screen space to world space. if let Some(pos) = world .read_resource::<CompositeCameraCache>() .screen_to_world_space(camera, point) { // instantiate object from prefab and store its entity. let instance = world .write_resource::<PrefabManager>() .instantiate_world("instance", world) .unwrap()[0]; // LazyUpdate::exec() runs code after all systems are done, so it's perfect to // modify components of entities created from prefab there. // note this `move` within closure definition - since we use `pos` and `instance` // objects from outside of closure scope, rust has to be informed that we want // to move ownership of these objects to that closure scope. world.read_resource::<LazyUpdate>().exec(move |world| { // fetch CompositeTransform from instance and set its position. // note that we can fetch multiple components at once if we pack them in // tuple (up to 26 components) just like that: // ``` // let (mut t, s) = <(CompositeTransform, Speed)>::fetch(world, instance); // let pos = t.get_translation() + t.get_direction() * s.0; // t.set_translation(pos); // ``` let mut transform = <CompositeTransform>::fetch(world, instance); transform.set_translation(pos); }); } } } else { // find and store camera entity by its name. self.camera = entity_find_world("camera", world); } StateChange::None } }
// ========= use std::cmp::{max, min}; use std::collections::{HashMap, HashSet}; use std::process::exit; const MOD: usize = 1000000007; pub struct IO<R, W: std::io::Write>(R, std::io::BufWriter<W>); impl<R: std::io::Read, W: std::io::Write> IO<R, W> { pub fn new(r: R, w: W) -> IO<R, W> { IO(r, std::io::BufWriter::new(w)) } pub fn write<S: std::ops::Deref<Target = str>>(&mut self, s: S) { use std::io::Write; self.1.write(s.as_bytes()).unwrap(); } pub fn read<T: std::str::FromStr>(&mut self) -> T { use std::io::Read; let buf = self .0 .by_ref() .bytes() .map(|b| b.unwrap()) .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r' || b == b'\t') .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r' && b != b'\t') .collect::<Vec<_>>(); unsafe { std::str::from_utf8_unchecked(&buf) } .parse() .ok() .expect("Parse error.") } pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> { (0..n).map(|_| self.read()).collect() } pub fn chars(&mut self) -> Vec<char> { self.read::<String>().chars().collect() } } // ========= struct SegTree<T> { // num: 葉(元データ)の数, data: ノードの値, neutral: 単位元, merge: 区間クエリ, update_point: 点更新 num: usize, data: Vec<T>, neutral: T, merge: Box<Fn(T, T) -> T>, update_point: Box<Fn(T, T) -> T>, } impl<T: Clone + Copy + std::fmt::Debug> SegTree<T> { // v...元配列, neutral...初期値かつ単位元, merge...区間クエリ, update: fn new( v: Vec<T>, neutral: T, merge: Box<Fn(T, T) -> T>, update_point: Box<Fn(T, T) -> T>, ) -> Self { let n = v.len().checked_next_power_of_two().unwrap(); let mut data: Vec<T> = vec![neutral; 2 * n - 1]; for i in 0..v.len() { data[i + n - 1] = v[i]; } if n > 1 { for i in (0..(n - 2)).rev() { data[i] = merge(data[2 * i + 1], data[2 * i + 2]); } } SegTree { num: n, data: data, neutral: neutral, merge: merge, update_point: update_point, } } // 点更新, i番目の値をxで更新 fn update(&mut self, i: usize, x: T) { let mut i = i + self.num - 1; // 対応する葉のNodeへ self.data[i] = (self.update_point)(self.data[i], x); while i > 0 { i = (i - 1) / 2; // 親の値を更新する self.data[i] = (self.merge)(self.data[i * 2 + 1], self.data[i * 2 + 2]); } } // [a, b): クエリの区間, k: valueのNode, [l,r): k-Nodeの担当区間 // 0-indexedで来たら[a, b+1]をする fn query(&self, a: usize, b: usize, k: usize, l: usize, r: usize) -> T { if r <= a || b <= l { self.neutral // 区間がかぶらないので単位元 } else if a <= l && r <= b { self.data[k] //もろの区間なので値を返す } else { //半端な区間なので左右にqueryしてもう一回評価をする let l_val = self.query(a, b, 2 * k + 1, l, (l + r) / 2); let r_val = self.query(a, b, 2 * k + 2, (l + r) / 2, r); (self.merge)(l_val, r_val) } } } // adjl...隣接リスト, u...今の点, depth...各頂点の深さを持つ, d...深さの値, fid...各頂点がはじめて出るet上のIndex fn eulertour( adjl: &Vec<Vec<usize>>, u: usize, p: usize, et: &mut Vec<usize>, depth: &mut Vec<usize>, d: usize, fid: &mut Vec<usize>, ) { depth[u] = d; fid[u] = et.len(); et.push(u); for v in &adjl[u] { if *v != p { eulertour(adjl, *v, u, et, depth, d + 1, fid); et.push(u); } } } fn main() { let (r, w) = (std::io::stdin(), std::io::stdout()); let mut sc = IO::new(r.lock(), w.lock()); let n: usize = sc.read(); let mut adjl: Vec<Vec<usize>> = vec![vec![]; n]; for i in 0..n { let k: usize = sc.read(); for _ in 0..k { let c: usize = sc.read(); adjl[i].push(c); } } let mut et: Vec<usize> = vec![]; let mut depth: Vec<usize> = vec![std::usize::MAX; n]; let mut fid: Vec<usize> = vec![std::usize::MAX; n]; eulertour(&adjl, 0, 0, &mut et, &mut depth, 0, &mut fid); let v = et .iter() .map(|e| (*e, depth[*e])) .collect::<Vec<(usize, usize)>>(); // index, depthで持つ let mut st = SegTree::<(usize, usize)>::new( v, (std::usize::MAX, std::usize::MAX), Box::new( |l: (usize, usize), r: (usize, usize)| { if l.1 < r.1 { l } else { r } }, ), Box::new(|_old: (usize, usize), new: (usize, usize)| new), ); let q: usize = sc.read(); // query 処理 for _ in 0..q { let u: usize = sc.read(); let v: usize = sc.read(); if u == v { println!("{:?}", u); } else if fid[u] < fid[v] { println!("{:?}", st.query(fid[u], fid[v], 0, 0, st.num).0); } else { println!("{:?}", st.query(fid[v], fid[u], 0, 0, st.num).0); } } }
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] pub struct VkDebugReportCallbackCreateInfoEXT { pub sType: VkStructureType, pub pNext: *const c_void, pub flags: VkDebugReportFlagBitsEXT, pub pfnCallback: PFN_vkDebugReportCallbackEXT, pub pUserData: *mut c_void, } impl VkDebugReportCallbackCreateInfoEXT { pub fn new<T>(flags: T, callback: PFN_vkDebugReportCallbackEXT) -> Self where T: Into<VkDebugReportFlagBitsEXT>, { VkDebugReportCallbackCreateInfoEXT { sType: VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT, pNext: ptr::null(), flags: flags.into(), pfnCallback: callback, pUserData: ptr::null_mut(), } } pub fn set_user_data<'a, 'b: 'a, T>(&'a mut self, user_data: &'b mut T) { self.pUserData = user_data as *mut T as *mut c_void; } }
// Copyright 2017 Dasein Phaos aka. Luxko // // 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. //! resource barriers use super::{ResourceStates, RawResource}; use smallvec::SmallVec; use std::borrow::Borrow; /// resource barrier builder #[derive(Clone, Debug, Default)] pub struct ResourceBarriersBuilder { barriers: SmallVec<[::winapi::D3D12_RESOURCE_BARRIER; 8]>, } impl ResourceBarriersBuilder { #[inline] pub fn new() -> Self { Default::default() } #[inline] pub fn push(&mut self, barrier: ResourceBarrier) { self.barriers.push(barrier.into()) } #[inline] pub fn as_ffi_slice(&self) -> &[::winapi::D3D12_RESOURCE_BARRIER] { self.barriers.borrow() } } /// resource barriers #[derive(Copy, Clone, Debug)] pub struct ResourceBarrier{ pub flags: ResourceBarrierFlags, pub barrier_type: ResourceBarrierType, } impl ResourceBarrier { #[inline] pub fn new(barrier: ResourceBarrierType) -> ResourceBarrier { ResourceBarrier{ flags: Default::default(), barrier_type: barrier, } } #[inline] pub fn transition( resource: &RawResource, subresource: u32, before: ResourceStates, after: ResourceStates ) -> ResourceBarrier { ResourceBarrier::new( ResourceBarrierType::Transition( ResourceTransitionBarrier::new( resource, subresource, before, after ) ) ) } #[inline] pub fn aliasing(before: &mut RawResource, after: &mut RawResource) -> ResourceBarrier { ResourceBarrier::new( ResourceBarrierType::Aliasing( ResourceAliasingBarrier::new(before, after) ) ) } #[inline] pub fn uav(resource: &RawResource) -> ResourceBarrier { ResourceBarrier::new( ResourceBarrierType::Uav( ResourceUavBarrier::new(resource) ) ) } } impl From<ResourceBarrier> for ::winapi::D3D12_RESOURCE_BARRIER { #[inline] fn from(barrier: ResourceBarrier) -> Self { unsafe { let mut ret: Self = ::std::mem::uninitialized(); ret.Flags = ::std::mem::transmute(barrier.flags); match barrier.barrier_type { ResourceBarrierType::Transition(transition) => { ret.Type = ::winapi::D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; ret.u = ::std::mem::transmute_copy(&transition); }, ResourceBarrierType::Aliasing(aliasing) => { ret.Type = ::winapi::D3D12_RESOURCE_BARRIER_TYPE_ALIASING; ret.u = ::std::mem::transmute_copy(&aliasing); }, ResourceBarrierType::Uav(uav) => { ret.Type = ::winapi::D3D12_RESOURCE_BARRIER_TYPE_UAV; ret.u = ::std::mem::transmute_copy(&uav); } } ret } } } #[derive(Copy, Clone, Debug)] pub enum ResourceBarrierType { Transition(ResourceTransitionBarrier), Aliasing(ResourceAliasingBarrier), Uav(ResourceUavBarrier), } /// represents a transition of subresource between different usages #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct ResourceTransitionBarrier { resource: *mut ::winapi::ID3D12Resource, subresource: u32, before: ResourceStates, after: ResourceStates, } impl ResourceTransitionBarrier { #[inline] pub fn new( resource: &RawResource, subresource: u32, before: ResourceStates, after: ResourceStates ) -> ResourceTransitionBarrier { ResourceTransitionBarrier{ resource: resource.ptr.as_mut_ptr(), subresource, before, after, } } } /// describes the transition between usage of two different /// resources mapping into the same heap location. #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct ResourceAliasingBarrier { before: *mut ::winapi::ID3D12Resource, after: *mut ::winapi::ID3D12Resource, } impl ResourceAliasingBarrier { // TODO: global aliasing barriers, see remarks in https://msdn.microsoft.com/en-us/library/windows/desktop/dn986739(v=vs.85).aspx // TODO: safety #[inline] pub fn new(before: &mut RawResource, after: &mut RawResource) -> Self { // debug_assert_eq!( // before.get_placed_heap().ptr.as_ptr(), // after.get_placed_heap().ptr.as_ptr() // ); // debug_assert_eq!(before.get_heap_offset(), after.get_heap_offset()); // debug_assert_eq!(before.get_alloc_info(), after.get_alloc_info()); ResourceAliasingBarrier{ before: before.ptr.as_mut_ptr(), after: after.ptr.as_mut_ptr(), } } } /// describes a barrier in which all uav access to a resource must complete /// before subsequent uav accesses can begin #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct ResourceUavBarrier { resource: *mut ::winapi::ID3D12Resource, } impl ResourceUavBarrier { #[inline] pub fn new(resource: &RawResource) -> Self { ResourceUavBarrier{ resource: resource.ptr.as_mut_ptr() } } } bitflags!{ /// misc resource barrier flags. [more](https://msdn.microsoft.com/library/windows/desktop/dn986741(v=vs.85).aspx) #[repr(C)] pub struct ResourceBarrierFlags: u32 { /// The default, an atomic barrier. const NONE = 0; /// Marks the start of a transition, putting the resource in a temporary no-access condition. const BEGIN_ONLY = 0x1; /// Marks the end of a transition, restore the resource to the state after transition. const END_ONLY = 0x2; } } impl Default for ResourceBarrierFlags { #[inline] fn default() -> Self { ResourceBarrierFlags::NONE } }
use crate::extensions::context::ClientContextExt; use serenity::{ framework::standard::{macros::command, CommandResult}, model::prelude::*, prelude::*, }; #[command] async fn prefix(ctx: &Context, msg: &Message) -> CommandResult { let config = ctx.get_config().await; if let Err(why) = msg .channel_id .send_message(&ctx.http, |m| { m.embed(|e| { e.title("Prefix"); e.description(format!("My prefix is: `{}`", &config.prefix)); e.color(0xffa500) }); m }) .await { println!( "Failed to send message in #{} because\n{:?}", msg.channel_id, why ); }; Ok(()) }
/* * Given an array of integers, return indices of the two numbers such that they add up to a specific target. * You may assume that each input would have exactly one solution, and you may not use the same element twice. * * Example: * ---------- * Given nums = [2, 7, 11, 15], target = 9, * Because nums[0] + nums[1] = 2 + 7 = 9, * return [0, 1]. */ // Single pass using hashtable use std::collections::HashMap; pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { let mut res: Vec<i32> = vec![]; let mut table: HashMap<i32, usize> = HashMap::new(); let mut i = 0; for num in nums { let complement = target - num; match table.get(&complement) { None => { table.insert(num, i); } Some(v) => { // println!("num: {:?}, i: {:?}, v: {:?}, complement: {:?}, res: {:?}, table: {:?}", num, i, v, complement, res, table); if *v != i { res.push(*v as i32); res.push(i as i32); return res; } } } i += 1; } return res } #[cfg(test)] mod test { use super::two_sum; #[test] fn example1() { let nums = vec![2, 7 , 11, 15]; let target = 9; assert_eq!(two_sum(nums, target), vec![0, 1]); } #[test] fn example2() { let nums = vec![3, 2, 4]; let target = 6; assert_eq!(two_sum(nums, target), vec![1, 2]); } #[test] fn example3() { let nums = vec![3, 3]; let target = 6; assert_eq!(two_sum(nums, target), vec![0, 1]); } }
#![allow(non_snake_case)] #![cfg(test)] #[test] fn Cannot_reassign_immutable_variable() { let x = 1; //x = 3; assert_eq!(x, 1); } #[test] fn Can_reassign_mutable_variable() { let mut x = 1; x = 3; assert_eq!(x, 3); } #[test] fn Can_create_explicit_var_1() { let x: i32 = 1; } #[test] fn Can_create_explicit_var_2() { let x: &i32 = &1; } #[test] fn Can_create_explicit_var_3() { let x = 1; let expected = &3; } //Can function return reference of just created object?
//! Implementation of the standard x64 ABI. use alloc::vec::Vec; use log::trace; use regalloc::{RealReg, Reg, RegClass, Set, SpillSlot, Writable}; use std::mem; use crate::binemit::Stackmap; use crate::ir::{self, types, types::*, ArgumentExtension, StackSlot, Type}; use crate::isa::{x64::inst::*, CallConv}; use crate::machinst::*; use crate::settings; use crate::{CodegenError, CodegenResult}; use args::*; /// This is the limit for the size of argument and return-value areas on the /// stack. We place a reasonable limit here to avoid integer overflow issues /// with 32-bit arithmetic: for now, 128 MB. static STACK_ARG_RET_SIZE_LIMIT: u64 = 128 * 1024 * 1024; #[derive(Clone, Debug)] enum ABIArg { Reg(RealReg, ir::Type), Stack(i64, ir::Type), } /// X64 ABI information shared between body (callee) and caller. struct ABISig { /// Argument locations (regs or stack slots). Stack offsets are relative to /// SP on entry to function. args: Vec<ABIArg>, /// Return-value locations. Stack offsets are relative to the return-area /// pointer. rets: Vec<ABIArg>, /// Space on stack used to store arguments. stack_arg_space: i64, /// Space on stack used to store return values. stack_ret_space: i64, /// Index in `args` of the stack-return-value-area argument. stack_ret_arg: Option<usize>, /// Calling convention used. call_conv: CallConv, } pub(crate) struct X64ABIBody { sig: ABISig, /// Offsets to each stack slot. stack_slots: Vec<usize>, /// Total stack size of all the stack slots. stack_slots_size: usize, /// The register holding the return-area pointer, if needed. ret_area_ptr: Option<Writable<Reg>>, /// Clobbered registers, as indicated by regalloc. clobbered: Set<Writable<RealReg>>, /// Total number of spill slots, as indicated by regalloc. num_spill_slots: Option<usize>, /// Calculated while creating the prologue, and used when creating the epilogue. Amount by /// which RSP is adjusted downwards to allocate the spill area. frame_size_bytes: Option<usize>, call_conv: CallConv, /// The settings controlling this function's compilation. flags: settings::Flags, } fn in_int_reg(ty: types::Type) -> bool { match ty { types::I8 | types::I16 | types::I32 | types::I64 | types::B1 | types::B8 | types::B16 | types::B32 | types::B64 => true, _ => false, } } fn in_vec_reg(ty: types::Type) -> bool { match ty { types::F32 | types::F64 => true, _ => false, } } fn get_intreg_for_arg_systemv(call_conv: &CallConv, idx: usize) -> Option<Reg> { match call_conv { CallConv::Fast | CallConv::Cold | CallConv::SystemV | CallConv::BaldrdashSystemV => {} _ => panic!("int args only supported for SysV calling convention"), }; match idx { 0 => Some(regs::rdi()), 1 => Some(regs::rsi()), 2 => Some(regs::rdx()), 3 => Some(regs::rcx()), 4 => Some(regs::r8()), 5 => Some(regs::r9()), _ => None, } } fn get_fltreg_for_arg_systemv(call_conv: &CallConv, idx: usize) -> Option<Reg> { match call_conv { CallConv::Fast | CallConv::Cold | CallConv::SystemV | CallConv::BaldrdashSystemV => {} _ => panic!("float args only supported for SysV calling convention"), }; match idx { 0 => Some(regs::xmm0()), 1 => Some(regs::xmm1()), 2 => Some(regs::xmm2()), 3 => Some(regs::xmm3()), 4 => Some(regs::xmm4()), 5 => Some(regs::xmm5()), 6 => Some(regs::xmm6()), 7 => Some(regs::xmm7()), _ => None, } } fn get_intreg_for_retval_systemv(call_conv: &CallConv, idx: usize) -> Option<Reg> { match call_conv { CallConv::Fast | CallConv::Cold | CallConv::SystemV => match idx { 0 => Some(regs::rax()), 1 => Some(regs::rdx()), _ => None, }, CallConv::BaldrdashSystemV => { if idx == 0 { Some(regs::rax()) } else { None } } CallConv::WindowsFastcall | CallConv::BaldrdashWindows | CallConv::Probestack => todo!(), } } fn get_fltreg_for_retval_systemv(call_conv: &CallConv, idx: usize) -> Option<Reg> { match call_conv { CallConv::Fast | CallConv::Cold | CallConv::SystemV => match idx { 0 => Some(regs::xmm0()), 1 => Some(regs::xmm1()), _ => None, }, CallConv::BaldrdashSystemV => { if idx == 0 { Some(regs::xmm0()) } else { None } } CallConv::WindowsFastcall | CallConv::BaldrdashWindows | CallConv::Probestack => todo!(), } } fn is_callee_save_systemv(r: RealReg) -> bool { use regs::*; match r.get_class() { RegClass::I64 => match r.get_hw_encoding() as u8 { ENC_RBX | ENC_RBP | ENC_R12 | ENC_R13 | ENC_R14 | ENC_R15 => true, _ => false, }, RegClass::V128 => false, _ => unimplemented!(), } } fn is_callee_save_baldrdash(r: RealReg) -> bool { use regs::*; match r.get_class() { RegClass::I64 => { if r.get_hw_encoding() as u8 == ENC_R14 { // r14 is the WasmTlsReg and is preserved implicitly. false } else { // Defer to native for the other ones. is_callee_save_systemv(r) } } RegClass::V128 => false, _ => unimplemented!(), } } fn get_callee_saves(call_conv: &CallConv, regs: Vec<Writable<RealReg>>) -> Vec<Writable<RealReg>> { match call_conv { CallConv::BaldrdashSystemV => regs .into_iter() .filter(|r| is_callee_save_baldrdash(r.to_reg())) .collect(), CallConv::BaldrdashWindows => { todo!("baldrdash windows"); } CallConv::Fast | CallConv::Cold | CallConv::SystemV => regs .into_iter() .filter(|r| is_callee_save_systemv(r.to_reg())) .collect(), CallConv::WindowsFastcall => todo!("windows fastcall"), CallConv::Probestack => todo!("probestack?"), } } impl X64ABIBody { /// Create a new body ABI instance. pub(crate) fn new(f: &ir::Function, flags: settings::Flags) -> CodegenResult<Self> { let sig = ABISig::from_func_sig(&f.signature)?; let call_conv = f.signature.call_conv; debug_assert!( call_conv == CallConv::SystemV || call_conv.extends_baldrdash(), "unsupported or unimplemented calling convention {}", call_conv ); // Compute stackslot locations and total stackslot size. let mut stack_offset: usize = 0; let mut stack_slots = vec![]; for (stackslot, data) in f.stack_slots.iter() { let off = stack_offset; stack_offset += data.size as usize; stack_offset = (stack_offset + 7) & !7; debug_assert_eq!(stackslot.as_u32() as usize, stack_slots.len()); stack_slots.push(off); } Ok(Self { sig, stack_slots, stack_slots_size: stack_offset, ret_area_ptr: None, clobbered: Set::empty(), num_spill_slots: None, frame_size_bytes: None, call_conv: f.signature.call_conv.clone(), flags, }) } /// Returns the offset from FP to the argument area, i.e., jumping over the saved FP, return /// address, and maybe other standard elements depending on ABI (e.g. Wasm TLS reg). fn fp_to_arg_offset(&self) -> i64 { if self.call_conv.extends_baldrdash() { let num_words = self.flags.baldrdash_prologue_words() as i64; debug_assert!(num_words > 0, "baldrdash must set baldrdash_prologue_words"); num_words * 8 } else { 16 // frame pointer + return address. } } } impl ABIBody for X64ABIBody { type I = Inst; fn temp_needed(&self) -> bool { self.sig.stack_ret_arg.is_some() } fn init(&mut self, maybe_tmp: Option<Writable<Reg>>) { if self.sig.stack_ret_arg.is_some() { assert!(maybe_tmp.is_some()); self.ret_area_ptr = maybe_tmp; } } fn flags(&self) -> &settings::Flags { &self.flags } fn num_args(&self) -> usize { self.sig.args.len() } fn num_retvals(&self) -> usize { self.sig.rets.len() } fn num_stackslots(&self) -> usize { self.stack_slots.len() } fn liveins(&self) -> Set<RealReg> { let mut set: Set<RealReg> = Set::empty(); for arg in &self.sig.args { if let &ABIArg::Reg(r, _) = arg { set.insert(r); } } set } fn liveouts(&self) -> Set<RealReg> { let mut set: Set<RealReg> = Set::empty(); for ret in &self.sig.rets { if let &ABIArg::Reg(r, _) = ret { set.insert(r); } } set } fn gen_copy_arg_to_reg(&self, idx: usize, to_reg: Writable<Reg>) -> Inst { match &self.sig.args[idx] { ABIArg::Reg(from_reg, ty) => Inst::gen_move(to_reg, from_reg.to_reg(), *ty), &ABIArg::Stack(off, ty) => { assert!( self.fp_to_arg_offset() + off <= u32::max_value() as i64, "large offset nyi" ); load_stack( Amode::imm_reg((self.fp_to_arg_offset() + off) as u32, regs::rbp()), to_reg, ty, ) } } } fn gen_retval_area_setup(&self) -> Option<Inst> { if let Some(i) = self.sig.stack_ret_arg { let inst = self.gen_copy_arg_to_reg(i, self.ret_area_ptr.unwrap()); trace!( "gen_retval_area_setup: inst {:?}; ptr reg is {:?}", inst, self.ret_area_ptr.unwrap().to_reg() ); Some(inst) } else { trace!("gen_retval_area_setup: not needed"); None } } fn gen_copy_reg_to_retval( &self, idx: usize, from_reg: Writable<Reg>, ext: ArgumentExtension, ) -> Vec<Inst> { let mut ret = Vec::new(); match &self.sig.rets[idx] { &ABIArg::Reg(r, ty) => { let from_bits = ty.bits() as u8; let ext_mode = match from_bits { 1 | 8 => Some(ExtMode::BQ), 16 => Some(ExtMode::WQ), 32 => Some(ExtMode::LQ), 64 => None, _ => unreachable!(), }; let dest_reg = Writable::from_reg(r.to_reg()); match (ext, ext_mode) { (ArgumentExtension::Uext, Some(ext_mode)) => { ret.push(Inst::movzx_rm_r( ext_mode, RegMem::reg(from_reg.to_reg()), dest_reg, /* infallible load */ None, )); } (ArgumentExtension::Sext, Some(ext_mode)) => { ret.push(Inst::movsx_rm_r( ext_mode, RegMem::reg(from_reg.to_reg()), dest_reg, /* infallible load */ None, )); } _ => ret.push(Inst::gen_move(dest_reg, from_reg.to_reg(), ty)), }; } &ABIArg::Stack(off, ty) => { let from_bits = ty.bits() as u8; let ext_mode = match from_bits { 1 | 8 => Some(ExtMode::BQ), 16 => Some(ExtMode::WQ), 32 => Some(ExtMode::LQ), 64 => None, _ => unreachable!(), }; // Trash the from_reg; it should be its last use. match (ext, ext_mode) { (ArgumentExtension::Uext, Some(ext_mode)) => { ret.push(Inst::movzx_rm_r( ext_mode, RegMem::reg(from_reg.to_reg()), from_reg, /* infallible load */ None, )); } (ArgumentExtension::Sext, Some(ext_mode)) => { ret.push(Inst::movsx_rm_r( ext_mode, RegMem::reg(from_reg.to_reg()), from_reg, /* infallible load */ None, )); } _ => {} }; assert!( off < u32::max_value() as i64, "large stack return offset nyi" ); let mem = Amode::imm_reg(off as u32, self.ret_area_ptr.unwrap().to_reg()); ret.push(store_stack(mem, from_reg.to_reg(), ty)) } } ret } fn gen_ret(&self) -> Inst { Inst::ret() } fn gen_epilogue_placeholder(&self) -> Inst { Inst::epilogue_placeholder() } fn set_num_spillslots(&mut self, slots: usize) { self.num_spill_slots = Some(slots); } fn set_clobbered(&mut self, clobbered: Set<Writable<RealReg>>) { self.clobbered = clobbered; } fn stackslot_addr(&self, slot: StackSlot, offset: u32, dst: Writable<Reg>) -> Inst { let stack_off = self.stack_slots[slot.as_u32() as usize] as i64; let sp_off: i64 = stack_off + (offset as i64); Inst::lea(SyntheticAmode::nominal_sp_offset(sp_off as u32), dst) } fn load_stackslot( &self, _slot: StackSlot, _offset: u32, _ty: Type, _into_reg: Writable<Reg>, ) -> Inst { unimplemented!("load_stackslot") } fn store_stackslot(&self, _slot: StackSlot, _offset: u32, _ty: Type, _from_reg: Reg) -> Inst { unimplemented!("store_stackslot") } fn load_spillslot(&self, slot: SpillSlot, ty: Type, into_reg: Writable<Reg>) -> Inst { // Offset from beginning of spillslot area, which is at nominal-SP + stackslots_size. let islot = slot.get() as i64; let spill_off = islot * 8; let sp_off = self.stack_slots_size as i64 + spill_off; debug_assert!(sp_off <= u32::max_value() as i64, "large spill offsets NYI"); trace!("load_spillslot: slot {:?} -> sp_off {}", slot, sp_off); load_stack( SyntheticAmode::nominal_sp_offset(sp_off as u32), into_reg, ty, ) } fn store_spillslot(&self, slot: SpillSlot, ty: Type, from_reg: Reg) -> Inst { // Offset from beginning of spillslot area, which is at nominal-SP + stackslots_size. let islot = slot.get() as i64; let spill_off = islot * 8; let sp_off = self.stack_slots_size as i64 + spill_off; debug_assert!(sp_off <= u32::max_value() as i64, "large spill offsets NYI"); trace!("store_spillslot: slot {:?} -> sp_off {}", slot, sp_off); store_stack( SyntheticAmode::nominal_sp_offset(sp_off as u32), from_reg, ty, ) } fn spillslots_to_stackmap(&self, _slots: &[SpillSlot], _state: &EmitState) -> Stackmap { unimplemented!("spillslots_to_stackmap") } fn gen_prologue(&mut self) -> Vec<Inst> { let r_rsp = regs::rsp(); let mut insts = vec![]; // Baldrdash generates its own prologue sequence, so we don't have to. if !self.call_conv.extends_baldrdash() { let r_rbp = regs::rbp(); let w_rbp = Writable::from_reg(r_rbp); // The "traditional" pre-preamble // RSP before the call will be 0 % 16. So here, it is 8 % 16. insts.push(Inst::push64(RegMemImm::reg(r_rbp))); // RSP is now 0 % 16 insts.push(Inst::mov_r_r(true, r_rsp, w_rbp)); } let clobbered = get_callee_saves(&self.call_conv, self.clobbered.to_vec()); let callee_saved_used: usize = clobbered .iter() .map(|reg| match reg.to_reg().get_class() { RegClass::I64 => 8, _ => todo!(), }) .sum(); let mut total_stacksize = self.stack_slots_size + 8 * self.num_spill_slots.unwrap(); if self.call_conv.extends_baldrdash() { // Baldrdash expects the stack to take at least the number of words set in // baldrdash_prologue_words; count them here. debug_assert!( !self.flags.enable_probestack(), "baldrdash does not expect cranelift to emit stack probes" ); total_stacksize += self.flags.baldrdash_prologue_words() as usize * 8; } // Now make sure the frame stack is aligned, so RSP == 0 % 16 in the function's body. let padding = (16 - ((total_stacksize + callee_saved_used) % 16)) & 15; let frame_size = total_stacksize + padding; debug_assert!( frame_size <= u32::max_value() as usize, "gen_prologue(x86): total_stacksize >= 2G" ); debug_assert_eq!((frame_size + callee_saved_used) % 16, 0, "misaligned stack"); if !self.call_conv.extends_baldrdash() { // Explicitly allocate the frame. let w_rsp = Writable::from_reg(r_rsp); if frame_size > 0 { insts.push(Inst::alu_rmi_r( true, AluRmiROpcode::Sub, RegMemImm::imm(frame_size as u32), w_rsp, )); } } // Save callee saved registers that we trash. Keep track of how much space we've used, so // as to know what we have to do to get the base of the spill area 0 % 16. let clobbered = get_callee_saves(&self.call_conv, self.clobbered.to_vec()); for reg in clobbered { let r_reg = reg.to_reg(); match r_reg.get_class() { RegClass::I64 => { insts.push(Inst::push64(RegMemImm::reg(r_reg.to_reg()))); } _ => unimplemented!(), } } if callee_saved_used > 0 { insts.push(Inst::VirtualSPOffsetAdj { offset: callee_saved_used as i64, }); } // Stash this value. We'll need it for the epilogue. debug_assert!(self.frame_size_bytes.is_none()); self.frame_size_bytes = Some(frame_size); insts } fn gen_epilogue(&self) -> Vec<Inst> { let mut insts = vec![]; // Undo what we did in the prologue. // Restore regs. let clobbered = get_callee_saves(&self.call_conv, self.clobbered.to_vec()); for wreg in clobbered.into_iter().rev() { let rreg = wreg.to_reg(); match rreg.get_class() { RegClass::I64 => { // TODO: make these conversion sequences less cumbersome. insts.push(Inst::pop64(Writable::from_reg(rreg.to_reg()))); } _ => unimplemented!(), } } // No need to adjust the virtual sp offset here: // - this would create issues when there's a return in the middle of a function, // - and nothing in this sequence may try to access stack slots from the nominal SP. // Clear the spill area and the 16-alignment padding below it. if !self.call_conv.extends_baldrdash() { let frame_size = self.frame_size_bytes.unwrap(); if frame_size > 0 { let r_rsp = regs::rsp(); let w_rsp = Writable::from_reg(r_rsp); insts.push(Inst::alu_rmi_r( true, AluRmiROpcode::Add, RegMemImm::imm(frame_size as u32), w_rsp, )); } } // Baldrdash generates its own preamble. if !self.call_conv.extends_baldrdash() { // Undo the "traditional" pre-preamble // RSP before the call will be 0 % 16. So here, it is 8 % 16. insts.push(Inst::pop64(Writable::from_reg(regs::rbp()))); insts.push(Inst::ret()); } insts } fn frame_size(&self) -> u32 { self.frame_size_bytes .expect("frame size not computed before prologue generation") as u32 } fn stack_args_size(&self) -> u32 { unimplemented!("I need to be computed!") } fn get_spillslot_size(&self, rc: RegClass, ty: Type) -> u32 { // We allocate in terms of 8-byte slots. match (rc, ty) { (RegClass::I64, _) => 1, (RegClass::V128, F32) | (RegClass::V128, F64) => 1, (RegClass::V128, _) => 2, _ => panic!("Unexpected register class!"), } } fn gen_spill(&self, to_slot: SpillSlot, from_reg: RealReg, ty: Option<Type>) -> Inst { let ty = ty_from_ty_hint_or_reg_class(from_reg.to_reg(), ty); self.store_spillslot(to_slot, ty, from_reg.to_reg()) } fn gen_reload( &self, to_reg: Writable<RealReg>, from_slot: SpillSlot, ty: Option<Type>, ) -> Inst { let ty = ty_from_ty_hint_or_reg_class(to_reg.to_reg().to_reg(), ty); self.load_spillslot(from_slot, ty, to_reg.map(|r| r.to_reg())) } } /// Return a type either from an optional type hint, or if not, from the default /// type associated with the given register's class. This is used to generate /// loads/spills appropriately given the type of value loaded/stored (which may /// be narrower than the spillslot). We usually have the type because the /// regalloc usually provides the vreg being spilled/reloaded, and we know every /// vreg's type. However, the regalloc *can* request a spill/reload without an /// associated vreg when needed to satisfy a safepoint (which requires all /// ref-typed values, even those in real registers in the original vcode, to be /// in spillslots). fn ty_from_ty_hint_or_reg_class(r: Reg, ty: Option<Type>) -> Type { match (ty, r.get_class()) { // If the type is provided (Some(t), _) => t, // If no type is provided, this should be a register spill for a // safepoint, so we only expect I64 (integer) registers. (None, RegClass::I64) => I64, _ => panic!("Unexpected register class!"), } } fn get_caller_saves(call_conv: CallConv) -> Vec<Writable<Reg>> { let mut caller_saved = Vec::new(); // Systemv calling convention: // - GPR: all except RBX, RBP, R12 to R15 (which are callee-saved). caller_saved.push(Writable::from_reg(regs::rsi())); caller_saved.push(Writable::from_reg(regs::rdi())); caller_saved.push(Writable::from_reg(regs::rax())); caller_saved.push(Writable::from_reg(regs::rcx())); caller_saved.push(Writable::from_reg(regs::rdx())); caller_saved.push(Writable::from_reg(regs::r8())); caller_saved.push(Writable::from_reg(regs::r9())); caller_saved.push(Writable::from_reg(regs::r10())); caller_saved.push(Writable::from_reg(regs::r11())); if call_conv.extends_baldrdash() { caller_saved.push(Writable::from_reg(regs::r12())); caller_saved.push(Writable::from_reg(regs::r13())); // Not r14; implicitly preserved in the entry. caller_saved.push(Writable::from_reg(regs::r15())); caller_saved.push(Writable::from_reg(regs::rbx())); } // - XMM: all the registers! caller_saved.push(Writable::from_reg(regs::xmm0())); caller_saved.push(Writable::from_reg(regs::xmm1())); caller_saved.push(Writable::from_reg(regs::xmm2())); caller_saved.push(Writable::from_reg(regs::xmm3())); caller_saved.push(Writable::from_reg(regs::xmm4())); caller_saved.push(Writable::from_reg(regs::xmm5())); caller_saved.push(Writable::from_reg(regs::xmm6())); caller_saved.push(Writable::from_reg(regs::xmm7())); caller_saved.push(Writable::from_reg(regs::xmm8())); caller_saved.push(Writable::from_reg(regs::xmm9())); caller_saved.push(Writable::from_reg(regs::xmm10())); caller_saved.push(Writable::from_reg(regs::xmm11())); caller_saved.push(Writable::from_reg(regs::xmm12())); caller_saved.push(Writable::from_reg(regs::xmm13())); caller_saved.push(Writable::from_reg(regs::xmm14())); caller_saved.push(Writable::from_reg(regs::xmm15())); caller_saved } fn abisig_to_uses_and_defs(sig: &ABISig) -> (Vec<Reg>, Vec<Writable<Reg>>) { // Compute uses: all arg regs. let mut uses = Vec::new(); for arg in &sig.args { match arg { &ABIArg::Reg(reg, _) => uses.push(reg.to_reg()), _ => {} } } // Compute defs: all retval regs, and all caller-save (clobbered) regs. let mut defs = get_caller_saves(sig.call_conv); for ret in &sig.rets { match ret { &ABIArg::Reg(reg, _) => defs.push(Writable::from_reg(reg.to_reg())), _ => {} } } (uses, defs) } /// Try to fill a Baldrdash register, returning it if it was found. fn try_fill_baldrdash_reg(call_conv: CallConv, param: &ir::AbiParam) -> Option<ABIArg> { if call_conv.extends_baldrdash() { match &param.purpose { &ir::ArgumentPurpose::VMContext => { // This is SpiderMonkey's `WasmTlsReg`. Some(ABIArg::Reg(regs::r14().to_real_reg(), ir::types::I64)) } &ir::ArgumentPurpose::SignatureId => { // This is SpiderMonkey's `WasmTableCallSigReg`. Some(ABIArg::Reg(regs::r10().to_real_reg(), ir::types::I64)) } _ => None, } } else { None } } /// Are we computing information about arguments or return values? Much of the /// handling is factored out into common routines; this enum allows us to /// distinguish which case we're handling. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum ArgsOrRets { Args, Rets, } /// Process a list of parameters or return values and allocate them to X-regs, /// V-regs, and stack slots. /// /// Returns the list of argument locations, the stack-space used (rounded up /// to a 16-byte-aligned boundary), and if `add_ret_area_ptr` was passed, the /// index of the extra synthetic arg that was added. fn compute_arg_locs( call_conv: CallConv, params: &[ir::AbiParam], args_or_rets: ArgsOrRets, add_ret_area_ptr: bool, ) -> CodegenResult<(Vec<ABIArg>, i64, Option<usize>)> { let is_baldrdash = call_conv.extends_baldrdash(); let mut next_gpr = 0; let mut next_vreg = 0; let mut next_stack: u64 = 0; let mut ret = vec![]; for i in 0..params.len() { // Process returns backward, according to the SpiderMonkey ABI (which we // adopt internally if `is_baldrdash` is set). let param = match (args_or_rets, is_baldrdash) { (ArgsOrRets::Args, _) => &params[i], (ArgsOrRets::Rets, false) => &params[i], (ArgsOrRets::Rets, true) => &params[params.len() - 1 - i], }; // Validate "purpose". match &param.purpose { &ir::ArgumentPurpose::VMContext | &ir::ArgumentPurpose::Normal | &ir::ArgumentPurpose::StackLimit | &ir::ArgumentPurpose::SignatureId => {} _ => panic!( "Unsupported argument purpose {:?} in signature: {:?}", param.purpose, params ), } let intreg = in_int_reg(param.value_type); let vecreg = in_vec_reg(param.value_type); debug_assert!(intreg || vecreg); debug_assert!(!(intreg && vecreg)); let (next_reg, candidate) = if intreg { let candidate = match args_or_rets { ArgsOrRets::Args => get_intreg_for_arg_systemv(&call_conv, next_gpr), ArgsOrRets::Rets => get_intreg_for_retval_systemv(&call_conv, next_gpr), }; debug_assert!(candidate .map(|r| r.get_class() == RegClass::I64) .unwrap_or(true)); (&mut next_gpr, candidate) } else { let candidate = match args_or_rets { ArgsOrRets::Args => get_fltreg_for_arg_systemv(&call_conv, next_vreg), ArgsOrRets::Rets => get_fltreg_for_retval_systemv(&call_conv, next_vreg), }; debug_assert!(candidate .map(|r| r.get_class() == RegClass::V128) .unwrap_or(true)); (&mut next_vreg, candidate) }; if let Some(param) = try_fill_baldrdash_reg(call_conv, param) { assert!(intreg); ret.push(param); } else if let Some(reg) = candidate { ret.push(ABIArg::Reg(reg.to_real_reg(), param.value_type)); *next_reg += 1; } else { // Compute size. Every arg takes a minimum slot of 8 bytes. (16-byte // stack alignment happens separately after all args.) let size = (param.value_type.bits() / 8) as u64; let size = std::cmp::max(size, 8); // Align. debug_assert!(size.is_power_of_two()); next_stack = (next_stack + size - 1) & !(size - 1); ret.push(ABIArg::Stack(next_stack as i64, param.value_type)); next_stack += size; } } if args_or_rets == ArgsOrRets::Rets && is_baldrdash { ret.reverse(); } let extra_arg = if add_ret_area_ptr { debug_assert!(args_or_rets == ArgsOrRets::Args); if let Some(reg) = get_intreg_for_arg_systemv(&call_conv, next_gpr) { ret.push(ABIArg::Reg(reg.to_real_reg(), ir::types::I64)); } else { ret.push(ABIArg::Stack(next_stack as i64, ir::types::I64)); next_stack += 8; } Some(ret.len() - 1) } else { None }; next_stack = (next_stack + 15) & !15; // To avoid overflow issues, limit the arg/return size to something reasonable. if next_stack > STACK_ARG_RET_SIZE_LIMIT { return Err(CodegenError::ImplLimitExceeded); } Ok((ret, next_stack as i64, extra_arg)) } impl ABISig { fn from_func_sig(sig: &ir::Signature) -> CodegenResult<ABISig> { // Compute args and retvals from signature. Handle retvals first, // because we may need to add a return-area arg to the args. let (rets, stack_ret_space, _) = compute_arg_locs( sig.call_conv, &sig.returns, ArgsOrRets::Rets, /* extra ret-area ptr = */ false, )?; let need_stack_return_area = stack_ret_space > 0; let (args, stack_arg_space, stack_ret_arg) = compute_arg_locs( sig.call_conv, &sig.params, ArgsOrRets::Args, need_stack_return_area, )?; trace!( "ABISig: sig {:?} => args = {:?} rets = {:?} arg stack = {} ret stack = {} stack_ret_arg = {:?}", sig, args, rets, stack_arg_space, stack_ret_space, stack_ret_arg ); Ok(ABISig { args, rets, stack_arg_space, stack_ret_space, stack_ret_arg, call_conv: sig.call_conv, }) } } enum CallDest { ExtName(ir::ExternalName, RelocDistance), Reg(Reg), } fn adjust_stack<C: LowerCtx<I = Inst>>(ctx: &mut C, amount: u64, is_sub: bool) { if amount == 0 { return; } let (alu_op, sp_adjustment) = if is_sub { (AluRmiROpcode::Sub, amount as i64) } else { (AluRmiROpcode::Add, -(amount as i64)) }; ctx.emit(Inst::VirtualSPOffsetAdj { offset: sp_adjustment, }); if amount <= u32::max_value() as u64 { ctx.emit(Inst::alu_rmi_r( true, alu_op, RegMemImm::imm(amount as u32), Writable::from_reg(regs::rsp()), )); } else { // TODO will require a scratch register. unimplemented!("adjust stack with large offset"); } } fn load_stack(mem: impl Into<SyntheticAmode>, into_reg: Writable<Reg>, ty: Type) -> Inst { let (is_int, ext_mode) = match ty { types::B1 | types::B8 | types::I8 => (true, Some(ExtMode::BQ)), types::B16 | types::I16 => (true, Some(ExtMode::WQ)), types::B32 | types::I32 => (true, Some(ExtMode::LQ)), types::B64 | types::I64 => (true, None), types::F32 | types::F64 => (false, None), _ => panic!("load_stack({})", ty), }; let mem = mem.into(); if is_int { match ext_mode { Some(ext_mode) => Inst::movsx_rm_r( ext_mode, RegMem::mem(mem), into_reg, /* infallible load */ None, ), None => Inst::mov64_m_r(mem, into_reg, None /* infallible */), } } else { let sse_op = match ty { types::F32 => SseOpcode::Movss, types::F64 => SseOpcode::Movsd, _ => unreachable!(), }; Inst::xmm_mov( sse_op, RegMem::mem(mem), into_reg, None, /* infallible */ ) } } fn store_stack(mem: impl Into<SyntheticAmode>, from_reg: Reg, ty: Type) -> Inst { let (is_int, size) = match ty { types::B1 | types::B8 | types::I8 => (true, 1), types::B16 | types::I16 => (true, 2), types::B32 | types::I32 => (true, 4), types::B64 | types::I64 => (true, 8), types::F32 => (false, 4), types::F64 => (false, 8), _ => unimplemented!("store_stack({})", ty), }; let mem = mem.into(); if is_int { Inst::mov_r_m(size, from_reg, mem, /* infallible store */ None) } else { let sse_op = match size { 4 => SseOpcode::Movss, 8 => SseOpcode::Movsd, _ => unreachable!(), }; Inst::xmm_mov_r_m(sse_op, from_reg, mem, /* infallible store */ None) } } /// X64 ABI object for a function call. pub struct X64ABICall { sig: ABISig, uses: Vec<Reg>, defs: Vec<Writable<Reg>>, dest: CallDest, loc: ir::SourceLoc, opcode: ir::Opcode, } impl X64ABICall { /// Create a callsite ABI object for a call directly to the specified function. pub fn from_func( sig: &ir::Signature, extname: &ir::ExternalName, dist: RelocDistance, loc: ir::SourceLoc, ) -> CodegenResult<Self> { let sig = ABISig::from_func_sig(sig)?; let (uses, defs) = abisig_to_uses_and_defs(&sig); Ok(Self { sig, uses, defs, dest: CallDest::ExtName(extname.clone(), dist), loc, opcode: ir::Opcode::Call, }) } /// Create a callsite ABI object for a call to a function pointer with the /// given signature. pub fn from_ptr( sig: &ir::Signature, ptr: Reg, loc: ir::SourceLoc, opcode: ir::Opcode, ) -> CodegenResult<Self> { let sig = ABISig::from_func_sig(sig)?; let (uses, defs) = abisig_to_uses_and_defs(&sig); Ok(Self { sig, uses, defs, dest: CallDest::Reg(ptr), loc, opcode, }) } } impl ABICall for X64ABICall { type I = Inst; fn num_args(&self) -> usize { if self.sig.stack_ret_arg.is_some() { self.sig.args.len() - 1 } else { self.sig.args.len() } } fn emit_stack_pre_adjust<C: LowerCtx<I = Self::I>>(&self, ctx: &mut C) { let off = self.sig.stack_arg_space + self.sig.stack_ret_space; adjust_stack(ctx, off as u64, /* is_sub = */ true) } fn emit_stack_post_adjust<C: LowerCtx<I = Self::I>>(&self, ctx: &mut C) { let off = self.sig.stack_arg_space + self.sig.stack_ret_space; adjust_stack(ctx, off as u64, /* is_sub = */ false) } fn emit_copy_reg_to_arg<C: LowerCtx<I = Self::I>>( &self, ctx: &mut C, idx: usize, from_reg: Reg, ) { match &self.sig.args[idx] { &ABIArg::Reg(reg, ty) => ctx.emit(Inst::gen_move( Writable::from_reg(reg.to_reg()), from_reg, ty, )), &ABIArg::Stack(off, ty) => { debug_assert!(off <= u32::max_value() as i64); debug_assert!(off >= 0); ctx.emit(store_stack( Amode::imm_reg(off as u32, regs::rsp()), from_reg, ty, )) } } } fn emit_copy_retval_to_reg<C: LowerCtx<I = Self::I>>( &self, ctx: &mut C, idx: usize, into_reg: Writable<Reg>, ) { match &self.sig.rets[idx] { &ABIArg::Reg(reg, ty) => ctx.emit(Inst::gen_move(into_reg, reg.to_reg(), ty)), &ABIArg::Stack(off, ty) => { let ret_area_base = self.sig.stack_arg_space; let sp_offset = off + ret_area_base; // TODO handle offsets bigger than u32::max debug_assert!(sp_offset >= 0); debug_assert!(sp_offset <= u32::max_value() as i64); ctx.emit(load_stack( Amode::imm_reg(sp_offset as u32, regs::rsp()), into_reg, ty, )); } } } fn emit_call<C: LowerCtx<I = Self::I>>(&mut self, ctx: &mut C) { let (uses, defs) = ( mem::replace(&mut self.uses, Default::default()), mem::replace(&mut self.defs, Default::default()), ); if let Some(i) = self.sig.stack_ret_arg { let dst = ctx.alloc_tmp(RegClass::I64, I64); let ret_area_base = self.sig.stack_arg_space; debug_assert!( ret_area_base <= u32::max_value() as i64, "large offset for ret area NYI" ); ctx.emit(Inst::lea( Amode::imm_reg(ret_area_base as u32, regs::rsp()), dst, )); self.emit_copy_reg_to_arg(ctx, i, dst.to_reg()); } match &self.dest { &CallDest::ExtName(ref name, ref _reloc_distance) => ctx.emit(Inst::call_known( name.clone(), uses, defs, self.loc, self.opcode, )), &CallDest::Reg(reg) => ctx.emit(Inst::call_unknown( RegMem::reg(reg), uses, defs, self.loc, self.opcode, )), } } }
use crate::error::HandleError; use crate::filter::*; use http::StatusCode; use model::*; use mysql::MySqlPool; use repository::ResetScore; use warp::filters::BoxedFilter; use warp::path; use warp::{Filter, Rejection, Reply}; pub fn route(db_pool: &MySqlPool) -> BoxedFilter<(impl Reply,)> { warp::post() .and(path!("reset")) .and(with_db(db_pool)) .and(account_by_session(db_pool)) .and_then(reset_handler) .boxed() } async fn reset_handler<C: ResetScore>( mut repository: C, account: Account, ) -> Result<impl Reply, Rejection> { repository .reset_score(&account) .map_err(HandleError::from)?; Ok(StatusCode::OK) }
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #![allow(non_snake_case)] extern crate astro; use astro::*; #[test] #[allow(unused_variables)] fn time() { let eq_point1 = coords::EqPoint{ asc: 40.68021_f64.to_radians(), dec: 18.04761_f64.to_radians() }; let eq_point2 = coords::EqPoint{ asc: 41.73129_f64.to_radians(), dec: 18.44092_f64.to_radians() }; let eq_point3 = coords::EqPoint{ asc: 42.78204_f64.to_radians(), dec: 18.82742_f64.to_radians() }; let geograph_point = coords::GeographPoint{ long: 71.0833_f64.to_radians(), lat: 42.3333_f64.to_radians(), }; let Theta0 = 177.74208_f64.to_radians(); let deltaT = time::delta_t(1988, 3); let (h_rise, m_rise, s_rise) = transit::time( &transit::TransitType::Rise, &transit::TransitBody::StarOrPlanet, &geograph_point, &eq_point1, &eq_point2, &eq_point3, Theta0, deltaT, 0.0 ); assert_eq!((h_rise, m_rise), (12, 25)); let (h_transit, m_transit, s_transit) = transit::time( &transit::TransitType::Transit, &transit::TransitBody::StarOrPlanet, &geograph_point, &eq_point1, &eq_point2, &eq_point3, Theta0, deltaT, 0.0 ); assert_eq!((h_transit, m_transit), (19, 40)); let (h_set, m_set, s_set) = transit::time( &transit::TransitType::Set, &transit::TransitBody::StarOrPlanet, &geograph_point, &eq_point1, &eq_point2, &eq_point3, Theta0, deltaT, 0.0 ); assert_eq!((h_set, m_set), (2, 54)); }
use crate::domain; use near_sdk::{ json_types::U128, serde::{Deserialize, Serialize}, }; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[serde(crate = "near_sdk::serde")] pub struct BatchId(pub U128); impl From<domain::BatchId> for BatchId { fn from(value: domain::BatchId) -> Self { Self(value.0.into()) } } impl From<BatchId> for u128 { fn from(vale: BatchId) -> Self { vale.0 .0 } }
#[cfg(feature = "erasure")] use crate::erasure::{NUM_CODING, NUM_DATA}; #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)] // The Meta column family pub struct SlotMeta { // The number of slots above the root (the genesis block). The first // slot has slot 0. pub slot: u64, // The total number of consecutive blobs starting from index 0 // we have received for this slot. pub consumed: u64, // The index *plus one* of the highest blob received for this slot. Useful // for checking if the slot has received any blobs yet, and to calculate the // range where there is one or more holes: `(consumed..received)`. pub received: u64, // The index of the blob that is flagged as the last blob for this slot. pub last_index: u64, // The slot height of the block this one derives from. pub parent_slot: u64, // The list of slot heights, each of which contains a block that derives // from this one. pub next_slots: Vec<u64>, // True if this slot is full (consumed == last_index + 1) and if every // slot that is a parent of this slot is also connected. pub is_connected: bool, // True if this slot is a root pub is_root: bool, } impl SlotMeta { pub fn is_full(&self) -> bool { // last_index is std::u64::MAX when it has no information about how // many blobs will fill this slot. // Note: A full slot with zero blobs is not possible. if self.last_index == std::u64::MAX { return false; } assert!(self.consumed <= self.last_index + 1); self.consumed == self.last_index + 1 } pub fn is_parent_set(&self) -> bool { self.parent_slot != std::u64::MAX } pub(in crate::blocktree) fn new(slot: u64, parent_slot: u64) -> Self { SlotMeta { slot, consumed: 0, received: 0, parent_slot, next_slots: vec![], is_connected: slot == 0, is_root: false, last_index: std::u64::MAX, } } } #[cfg(feature = "erasure")] #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)] /// Erasure coding information pub struct ErasureMeta { /// Which erasure set in the slot this is pub set_index: u64, /// Bitfield representing presence/absence of data blobs pub data: u64, /// Bitfield representing presence/absence of coding blobs pub coding: u64, } #[cfg(feature = "erasure")] impl ErasureMeta { pub fn new(set_index: u64) -> ErasureMeta { ErasureMeta { set_index, data: 0, coding: 0, } } pub fn can_recover(&self) -> bool { let (data_missing, coding_missing) = ( NUM_DATA - self.data.count_ones() as usize, NUM_CODING - self.coding.count_ones() as usize, ); data_missing > 0 && data_missing + coding_missing <= NUM_CODING } pub fn is_coding_present(&self, index: u64) -> bool { let set_index = Self::set_index_for(index); let position = index - self.start_index(); set_index == self.set_index && self.coding & (1 << position) != 0 } pub fn set_coding_present(&mut self, index: u64) { let set_index = Self::set_index_for(index); if set_index as u64 == self.set_index { let position = index - self.start_index(); self.coding |= 1 << position; } } pub fn is_data_present(&self, index: u64) -> bool { let set_index = Self::set_index_for(index); let position = index - self.start_index(); set_index == self.set_index && self.data & (1 << position) != 0 } pub fn set_data_present(&mut self, index: u64) { let set_index = Self::set_index_for(index); if set_index as u64 == self.set_index { let position = index - self.start_index(); self.data |= 1 << position; } } pub fn set_index_for(index: u64) -> u64 { index / NUM_DATA as u64 } pub fn start_index(&self) -> u64 { self.set_index * NUM_DATA as u64 } /// returns a tuple of (data_end, coding_end) pub fn end_indexes(&self) -> (u64, u64) { let start = self.start_index(); (start + NUM_DATA as u64, start + NUM_CODING as u64) } } #[cfg(feature = "erasure")] #[test] fn test_meta_coding_present() { let set_index = 0; let mut e_meta = ErasureMeta { set_index, data: 0, coding: 0, }; for i in 0..NUM_CODING as u64 { e_meta.set_coding_present(i); assert_eq!(e_meta.is_coding_present(i), true); } for i in NUM_CODING as u64..NUM_DATA as u64 { assert_eq!(e_meta.is_coding_present(i), false); } e_meta.set_index = ErasureMeta::set_index_for((NUM_DATA * 17) as u64); for i in (NUM_DATA * 17) as u64..((NUM_DATA * 17) + NUM_CODING) as u64 { e_meta.set_coding_present(i); assert_eq!(e_meta.is_coding_present(i), true); } for i in (NUM_DATA * 17 + NUM_CODING) as u64..((NUM_DATA * 17) + NUM_DATA) as u64 { assert_eq!(e_meta.is_coding_present(i), false); } } #[cfg(feature = "erasure")] #[test] fn test_can_recover() { let set_index = 0; let mut e_meta = ErasureMeta { set_index, data: 0, coding: 0, }; assert!(!e_meta.can_recover()); e_meta.data = 0b1111_1111_1111_1111; e_meta.coding = 0x00; assert!(!e_meta.can_recover()); e_meta.coding = 0x0e; assert_eq!(0x0fu8, 0b0000_1111u8); assert!(!e_meta.can_recover()); e_meta.data = 0b0111_1111_1111_1111; assert!(e_meta.can_recover()); e_meta.data = 0b0111_1111_1111_1110; assert!(e_meta.can_recover()); e_meta.data = 0b0111_1111_1011_1110; assert!(e_meta.can_recover()); e_meta.data = 0b0111_1011_1011_1110; assert!(!e_meta.can_recover()); e_meta.data = 0b0111_1011_1011_1110; assert!(!e_meta.can_recover()); e_meta.coding = 0b0000_1110; e_meta.data = 0b1111_1111_1111_1100; assert!(e_meta.can_recover()); e_meta.data = 0b1111_1111_1111_1000; assert!(e_meta.can_recover()); }
use super::CelestialBody; use crate::codec::{Decode, Encode}; use crate::{remote_type, Quaternion, RemoteObject, Vector3}; remote_type!( /// Used to get flight telemetry for a vessel, by calling `Vessel::flight()`. All of /// the information returned by this class is given in the reference frame passed to that method. /// /// # Note /// To get orbital information, such as the apoapsis or inclination, see `Orbit`. object SpaceCenter.Flight { properties: { { GForce { /// Returns the current G force acting on the vessel in *g*. /// /// **Game Scenes**: Flight get: g_force -> f32 } } { MeanAltitude { /// Returns the altitude above sea level, in meters. Measured from the center of /// mass of the vessel. /// /// **Game Scenes**: Flight get: mean_altitude -> f64 } } { SurfaceAltitude { /// Returns the altitude above the surface of the body or sea level, whichever /// is closer, in meters. Measured from the center of mass of the vessel. /// /// **Game Scenes**: Flight get: surface_altitude -> f64 } } { BedrockAltitude { /// Returns the altitude above the surface of the body, in meters. When over water, /// this is the altitude above the sea floor. Measured from the center of mass of /// the vessel. /// /// **Game Scenes**: Flight get: bedrock_altitude -> f64 } } { Elevation { /// Returns the elevation of the terrain under the vessel, in meters. This is the /// height of the terrain above sea level, and is negative when the vessel is /// over the sea. /// /// **Game Scenes**: Flight get: elevation -> f64 } } { Latitude { /// Returns the [latitude](https://en.wikipedia.org/wiki/Latitude) of the vessel for /// the body being orbited, in degrees. /// /// **Game Scenes**: Flight get: latitude -> f64 } } { Longitude { /// Returns the [longitude](https://en.wikipedia.org/wiki/Longitude) of the vessel for /// the body being orbited, in degrees. /// /// **Game Scenes**: Flight get: longitude -> f64 } } { Velocity { /// Returns the velocity of the vessel, in the reference frame `ReferenceFrame`. /// /// **Game Scenes**: Flight /// /// # Return /// The velocity as a vector. The vector points in the direction of travel, and /// its magnitude is the speed of the vessel in meters per second. get: velocity -> Vector3 } } { Speed { /// Returns the speed of the vessel in meters per second, in the reference /// frame `ReferenceFrame`. /// /// **Game Scenes**: Flight get: speed -> f64 } } { HorizontalSpeed { /// Returns the horizontal speed of the vessel in meters per second, in the reference /// frame `ReferenceFrame`. /// /// **Game Scenes**: Flight get: horizontal_speed -> f64 } } { VerticalSpeed { /// Returns the vertical speed of the vessel in meters per second, in the reference /// frame `ReferenceFrame`. /// /// **Game Scenes**: Flight get: vertical_speed -> f64 } } { CenterOfMass { /// Returns the position of the center of mass of the vessel, in the /// reference frame `ReferenceFrame`. /// /// **Game Scenes**: Flight /// /// # Return /// The position as a vector. get: center_of_mass -> Vector3 } } { Rotation { /// Returns the rotation of the vessel, in the reference frame `ReferenceFrame` /// /// **Game Scenes**: Flight /// /// # Return /// The rotation as a quaternion of the form (*x*,*y*,*z*,*w*). get: rotation -> Quaternion } } { Direction { /// Returns the direction that the vessel is pointing in, in the /// reference frame `ReferenceFrame`. /// /// **Game Scenes**: Flight /// /// # Return /// The direction as a unit vector. get: direction -> Vector3 } } { Pitch { /// Returns the pitch of the vessel relative to the horizon, in degrees. /// A value between -90° and +90°. /// /// **Game Scenes**: Flight get: pitch -> f32 } } { Heading { /// Returns the heading of the vessel (its angle relative to north), in degrees. /// A value between 0° and 360°. /// /// **Game Scenes**: Flight get: heading -> f32 } } { Roll { /// Returns the roll of the vessel relative to the horizon, in degrees. /// A value between -180° and +180°. /// /// **Game Scenes**: Flight get: roll -> f32 } } { Prograde { /// Returns the prograde direction of the vessels orbit, in the /// reference frame `ReferenceFrame`. /// /// **Game Scenes**: Flight /// /// # Return /// The direction as a unit vector. get: prograde -> Vector3 } } { Retrograde { /// Returns the retrograde direction of the vessels orbit, in the /// reference frame `ReferenceFrame`. /// /// **Game Scenes**: Flight /// /// # Return /// The direction as a unit vector. get: retrograde -> Vector3 } } { Normal { /// Returns the normal direction of the vessels orbit, in the /// reference frame `ReferenceFrame`. /// /// **Game Scenes**: Flight /// /// # Return /// The direction as a unit vector. get: normal -> Vector3 } } { AntiNormal { /// Returns the direction opposite to the normal of the vessels orbit, in the /// reference frame `ReferenceFrame`. /// /// **Game Scenes**: Flight /// /// # Return /// The direction as a unit vector. get: anti_normal -> Vector3 } } { Radial { /// Returns the radial direction of the vessels orbit, in the /// reference frame `ReferenceFrame`. /// /// **Game Scenes**: Flight /// /// # Return /// The direction as a unit vector. get: radial -> Vector3 } } { AntiRadial { /// Returns the direction opposite to the radial of the vessels orbit, in the /// reference frame `ReferenceFrame`. /// /// **Game Scenes**: Flight /// /// # Return /// The direction as a unit vector. get: anti_radial -> Vector3 } } { AtmosphereDensity { /// Returns the current density of the atmosphere around the vessel, /// in kg/m<sup>3</sup>. /// /// **Game Scenes**: Flight get: atmosphere_density -> f32 } } { DynamicPressure { /// Returns the dynamic pressure acting on the vessel, in Pascals. This is a /// measure of the strength of the aerodynamic forces. It is equal to /// `1/2 · air density · velocity<sup>2</sup>`. It is commonly denoted Q. /// /// **Game Scenes**: Flight get: dynamic_pressure -> f32 } } { StaticPressure { /// Returns the static atmospheric pressure acting on the vessel, in Pascals. /// /// **Game Scenes**: Flight get: static_pressure -> f32 } } { StaticPressureAtMSL { /// Returns the static pressure at mean sea level, in Pascals. /// /// **Game Scenes**: Flight get: static_pressure_at_msl -> f32 } } { AerodynamicForce { /// Returns the total aerodynamic forces acting on the vessel, /// in reference frame `ReferenceFrame`. /// /// **Game Scenes**: Flight /// /// # Return /// A vector pointing in the direction that the force acts, with its magnitude /// equal to the strength of the force in Newtons. get: aerodynamic_force -> Vector3 } } { Lift { /// Returns the [aerodynamic lift](https://en.wikipedia.org/wiki/Aerodynamic_force) /// currently acting on the vessel. /// /// **Game Scenes**: Flight /// /// # Return /// A vector pointing in the direction that the force acts, with its magnitude /// equal to the strength of the force in Newtons. get: lift -> Vector3 } } { Drag { /// Returns the [aerodynamic drag](https://en.wikipedia.org/wiki/Aerodynamic_force) /// currently acting on the vessel. /// /// **Game Scenes**: Flight /// /// # Return /// A vector pointing in the direction that the force acts, with its magnitude /// equal to the strength of the force in Newtons. get: drag -> Vector3 } } { SpeedOfSound { /// Returns the speed of sound, in the atmosphere around the vessel, in m/s. /// /// **Game Scenes**: Flight get: speed_of_sound -> f32 } } { Mach { /// Returns the speed of the vessel, in multiples of the speed of sound. /// /// **Game Scenes**: Flight get: mach -> f32 } } { ReynoldsNumber { /// Returns the vessels Reynolds number. /// /// **Game Scenes**: Flight /// /// # Note /// Requires Ferram Aerospace Research. get: reynolds_number -> f32 } } { TrueAirSpeed { /// Returns the [true air speed](https://en.wikipedia.org/wiki/True_airspeed) /// of the vessel, in meters per second. /// /// **Game Scenes**: Flight get: true_air_speed -> f32 } } { EquivalentAirSpeed { /// Returns the [equivalent air speed](https://en.wikipedia.org/wiki/Equivalent_airspeed) /// of the vessel, in meters per second. /// /// **Game Scenes**: Flight get: equivalent_air_speed -> f32 } } { TerminalVelocity { /// Returns an estimate of the current terminal velocity of the vessel, /// in meters per second. This is the speed at which the drag forces cancel /// out the force of gravity. /// /// **Game Scenes**: Flight get: terminal_velocity -> f32 } } { AngleOfAttack { /// Returns the pitch angle between the orientation of the vessel and its /// velocity vector, in degrees.. /// /// **Game Scenes**: Flight get: angle_of_attack -> f32 } } { SideslipAngle { /// Returns the yaw angle between the orientation of the vessel and its /// velocity vector, in degrees. /// /// **Game Scenes**: Flight get: sideslip_angle -> f32 } } { TotalAirTemperature { /// Returns the [total air temperature](https://en.wikipedia.org/wiki/Total_air_temperature) /// of the atmosphere around the vessel, in Kelvin. This includes the /// `Flight::static_air_temperature()` and the vessel’s kinetic energy. /// /// **Game Scenes**: Flight get: total_air_temperature -> f32 } } { StaticAirTemperature { /// Returns the [static (ambient) temperature](https://en.wikipedia.org/wiki/Total_air_temperature) /// of the atmosphere around the vessel, in Kelvin. /// /// **Game Scenes**: Flight get: static_air_temperature -> f32 } } { StallFraction { /// Returns the current amount of stall, between 0 and 1. A value greater than /// 0.005 indicates a minor stall and a value greater than 0.5 indicates /// a large-scale stall. /// /// **Game Scenes**: Flight /// /// # Note /// Requires Ferram Aerospace Research. get: stall_fraction -> f32 } } { DragCoefficient { /// Returns the coefficient of drag. This is the amount of drag produced by the /// vessel. It depends on air speed, air density and wing area. /// /// **Game Scenes**: Flight /// /// # Note /// Requires Ferram Aerospace Research. get: drag_coefficient -> f32 } } { LiftCoefficient { /// Returns the coefficient of lift. This is the amount of lift produced by the /// vessel. It depends on air speed, air density and wing area. /// /// **Game Scenes**: Flight /// /// # Note /// Requires Ferram Aerospace Research. get: lift_coefficient -> f32 } } { BallisticCoefficient { /// Returns the [ballistic coefficient](https://en.wikipedia.org/wiki/Ballistic_coefficient). /// /// **Game Scenes**: Flight /// /// # Note /// Requires Ferram Aerospace Research. get: ballistic_coefficient -> f32 } } { ThrustSpecificFuelConsumption { /// Returns the efficiency of the engines, with a lower value indicating a /// more efficient vessel. This value is the number of Newtons of fuel that /// are burned, per hour, to produce one newton of thrust. /// /// **Game Scenes**: Flight /// /// # Note /// Requires Ferram Aerospace Research. get: thrust_specific_fuel_consumption -> f32 } } } methods: { { /// Simulate and return the total aerodynamic forces acting on the vessel, /// if it where to be traveling with the given velocity at the given position /// in the atmosphere of the given celestial body. /// /// **Game Scenes**: Flight /// /// # Arguments /// * `body` - The celestial body. /// * `position` - The vessel's position as a vector on the body. /// * `velocity` - The vessel's velocity as a vector on the body. /// /// # Return /// A vector pointing in the direction that the force acts, with its magnitude equal /// to the strength of the force in Newtons. fn simulate_aerodynamic_force_at(body: &CelestialBody, position: Vector3, velocity: Vector3) -> Vector3 { SimulateAerodynamicForceAt(body, position, velocity) } } } });
pub mod escape_stm;
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved // #![allow(dead_code, non_snake_case)] use std::path::Path; pub fn ASSET_PINECONE_MATTE() -> &'static Path { Path::new("../assets/pinecones/matte/Pinecone.gltf") } pub fn ASSET_PINECONE_SHINY() -> &'static Path { Path::new("../assets/pinecones/shiny/Pinecone.gltf") } pub fn ASSET_PINECONE_TINTED() -> &'static Path { Path::new("../assets/pinecones/tinted/Pinecone.gltf") } pub fn ASSET_PINECONE_VARIATIONAL() -> &'static Path { Path::new("../assets/pinecones/variational/Pinecone.gltf") } pub fn ASSET_TEAPOT_CAMO_PINK_BRONZE() -> &'static Path { Path::new("../assets/tank_teapots/teapot-camo-pink-bronze.gltf") } pub fn ASSET_TEAPOT_CAMO_PINK_SILVER() -> &'static Path { Path::new("../assets/tank_teapots/teapot-camo-pink-silver.gltf") } pub fn ASSET_TEAPOT_GREEN_PINK_BRONZE() -> &'static Path { Path::new("../assets/tank_teapots/teapot-green-pink-bronze.gltf") } pub fn ASSET_TEAPOT_GREEN_PINK_SILVER() -> &'static Path { Path::new("../assets/tank_teapots/teapot-green-pink-silver.gltf") }
use nalgebra as na; use uwb_clock_tracker::{ dwt_utils, clock_tracker, clock_tracker::ClockTracker, }; fn main() { println!("Hello, dwt: {}", na::Vector3::<f32>::x()); let tracker = ClockTracker::<clock_tracker::CONSTRUCTED>::new(1e-8, 0.18e-9); let mut tracker = tracker.init_with_matdiag(0, &na::Vector3::<f64>::x(), &na::Vector3::<f64>::zeros()); tracker.predict_mut(1); tracker.update(1); }
// Copyright © 2016-2017 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use std::fmt; use rabble::{Pid, CorrelationId, Envelope}; use msg::Msg; use vr::states::*; use super::vr_msg::VrMsg; use super::vr_ctx::VrCtx; /// Generate a state struct: `$struct_name` from a set of fields /// /// Generate `impl From<$struct_name> for VrState` macro_rules! state { ($struct_name:ident { $( $field:ident: $ty:ty),* }) => { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct $struct_name { $( pub $field: $ty ),* } impl From<$struct_name> for VrState { fn from(state: $struct_name) -> VrState { VrState::$struct_name(state) } } impl State for $struct_name { fn ctx(self) -> VrCtx { self.ctx } fn borrow_ctx(&self) -> &VrCtx { &self.ctx } } } } macro_rules! up_to_date { ($Self:ident, $From:ident, $Msg:ident, $Cid:ident, $Output:ident) => { if $Msg.epoch < $Self.ctx.epoch { return $Self.into(); } if $Msg.epoch > $Self.ctx.epoch { // Reconfiguration has already occurred since a primary in the new epoch is accepting // requests and sending Prepare messages. return StateTransfer::start_epoch($Self, $From, $Cid, $Msg.epoch, $Msg.view, $Output); } if $Msg.view < $Self.ctx.view { return $Self.into(); } if $Msg.view > $Self.ctx.view { return StateTransfer::start_view($Self, $Msg.view, $Cid, $Output); } } } /// This represents a transition from one state to another via a received message pub trait Transition { fn handle(self, msg: VrMsg, from: Pid, correlation_id: CorrelationId, output: &mut Vec<Envelope<Msg>>) -> VrState; } pub trait State: Into<VrState> { fn ctx(self) -> VrCtx; fn borrow_ctx(&self) -> &VrCtx; } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum VrState { Primary(Primary), Backup(Backup), StateTransfer(StateTransfer), StartViewChange(StartViewChange), DoViewChange(DoViewChange), StartView(StartView), Recovery(Recovery), Reconfiguration(Reconfiguration), Leaving(Leaving), Shutdown(Shutdown) } // TODO: Implement state specific display instead of just name and ctx impl fmt::Display for VrState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { VrState::Primary(_) => write!(f, "Primary {}\n", self.ctx()), VrState::Backup(_) => write!(f, "Backup {}\n", self.ctx()), VrState::StateTransfer(_) => write!(f, "StateTransfer {}\n", self.ctx()), VrState::StartViewChange(_) => write!(f, "StartViewChange {}\n", self.ctx()), VrState::DoViewChange(_) => write!(f, "DoViewChange {}\n", self.ctx()), VrState::StartView(_) => write!(f, "StartView {}\n", self.ctx()), VrState::Recovery(_) => write!(f, "Recovery {}\n", self.ctx()), VrState::Reconfiguration(_) => write!(f, "Reconfiguration {}\n", self.ctx()), VrState::Leaving(_) => write!(f, "Leaving {}\n", self.ctx()), VrState::Shutdown(_) => write!(f, "Shutdown {}\n", self.ctx()) } } } impl VrState { pub fn next(self, msg: VrMsg, from: Pid, cid: CorrelationId, output: &mut Vec<Envelope<Msg>>) -> VrState { match self { VrState::Primary(s) => s.handle(msg, from, cid, output), VrState::Backup(s) => s.handle(msg, from, cid, output), VrState::StateTransfer(s) => s.handle(msg, from, cid, output), VrState::StartViewChange(s) => s.handle(msg, from, cid, output), VrState::DoViewChange(s) => s.handle(msg, from, cid, output), VrState::StartView(s) => s.handle(msg, from, cid, output), VrState::Recovery(s) => s.handle(msg, from, cid, output), VrState::Reconfiguration(s) => s.handle(msg, from, cid, output), VrState::Leaving(s) => s.handle(msg, from, cid, output), VrState::Shutdown(s) => s.into() } } pub fn ctx(&self) -> &VrCtx { match *self { VrState::Primary(ref s) => &s.ctx, VrState::Backup(ref s) => &s.ctx, VrState::StateTransfer(ref s) => &s.ctx, VrState::StartViewChange(ref s) => &s.ctx, VrState::DoViewChange(ref s) => &s.ctx, VrState::StartView(ref s) => &s.ctx, VrState::Recovery(ref s) => &s.ctx, VrState::Reconfiguration(ref s) => &s.ctx, VrState::Leaving(ref s) => &s.ctx, VrState::Shutdown(ref s) => &s.ctx } } }
//! Implémentation d’une intelligence artificielle plaçant systématiquement aléatoirement un jeton use super::connect_four::{Interface, Area, State}; /// Intelligence artificielle aléatoire pub struct RandomBot { #[doc(hidden)] name : String } impl RandomBot { /// Initialise l’intelligence artificielle /// /// # Arguments /// /// * `name` : Le nom donné à l’intelligence artificielle. /// /// # Retour /// /// Une instance de l’intelligence artificielle pub fn new(name : &str) -> Self { Self { name: String::from(name) } } } impl Interface for RandomBot { fn play(&mut self, area: &Area, _ : State) -> usize { let available = area.get_available_columns(); const SZ : usize = std::mem::size_of::<usize>(); let mut idx_a : [u8; SZ] = [0; SZ]; getrandom::getrandom(&mut idx_a).unwrap(); let idx : usize = unsafe { std::mem::transmute::<[u8; SZ], usize>(idx_a) } % available.len(); return available[idx]; } fn name(&self) -> String { return self.name.clone(); } }
use anyhow::{anyhow, Error, Result}; use std::str::FromStr; #[derive(Debug, Clone)] enum Op { Nop(isize), Acc(i32), Jmp(isize), } impl FromStr for Op { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut s = s.trim().split(' '); let token = s.next().ok_or_else(|| anyhow!("No op token".to_owned()))?; match token { "nop" => Ok(Self::Nop( s.next() .ok_or_else(|| anyhow!("Invalid jmp offset".to_owned()))? .parse()?, )), "acc" => Ok(Self::Acc( s.next() .ok_or_else(|| anyhow!("Invalid acc argument".to_owned()))? .parse()?, )), "jmp" => Ok(Self::Jmp( s.next() .ok_or_else(|| anyhow!("Invalid jmp offset".to_owned()))? .parse()?, )), _ => Err(anyhow!("Invalid operation".to_owned())), } } } struct Machine { pc: usize, accumulator: i32, program: Vec<Op>, } impl Machine { fn new(program: impl IntoIterator<Item = Op>) -> Self { Self { pc: 0, accumulator: 0, program: program.into_iter().collect(), } } fn step(&mut self) -> Result<bool> { let op = self .program .get(self.pc) .ok_or_else(|| anyhow!("Invalid pc: {}!", self.pc))?; match op { Op::Nop(_) => { #[cfg(feature = "dbg-print")] println!("[{}] Nop", self.pc); self.pc += 1; } Op::Acc(arg) => { #[cfg(feature = "dbg-print")] println!( "[{}] Acc {}, acc = {} + {1} = {}", self.pc, arg, self.accumulator, self.accumulator + arg ); self.accumulator += arg; self.pc += 1; } Op::Jmp(offset) => { #[cfg(feature = "dbg-print")] println!( "[{}] Jmp {}, pc = {0} + {1} = {}", self.pc, offset, ((self.pc as isize) + offset) as usize ); self.pc = ((self.pc as isize) + offset) as usize; } } Ok(self.pc < self.program.len()) } fn reset(&mut self) { self.pc = 0; self.accumulator = 0; } } fn part1(program: Vec<Op>) -> Result<i32> { let mut machine = Machine::new(program); let mut visited = vec![false; machine.program.len()]; while !visited[machine.pc] { visited[machine.pc] = true; machine.step()?; } Ok(machine.accumulator) } fn part2(program: Vec<Op>) -> Result<i32> { let mut machine = Machine::new(program); let mut visited = vec![false; machine.program.len()]; let swap = |machine: &mut Machine, n: usize| { let new = match &machine.program[n] { Op::Nop(arg) => Op::Jmp(*arg), Op::Jmp(arg) => Op::Nop(*arg), _ => return false, }; machine.program[n] = new; true }; for n in 0..machine.program.len() { if !swap(&mut machine, n) { continue; } while !visited[machine.pc] { visited[machine.pc] = true; if !machine.step()? { return Ok(machine.accumulator); } } swap(&mut machine, n); for v in visited.iter_mut() { *v = false; } machine.reset() } Err(anyhow!("Loops, loops everywhere!".to_owned())) } fn main() -> Result<()> { let program: Vec<Op> = common::std_input_vec()?; println!("Part1: {}", part1(program.clone())?); println!("Part2: {}", part2(program)?); Ok(()) }
use crate::load_function_ptrs; use crate::prelude::*; use std::os::raw::c_void; load_function_ptrs!(PhysicalDeviceProperties2Functions, { vkGetPhysicalDeviceProperties2KHR( physicalDevice: VkPhysicalDevice, pProperties: *mut VkPhysicalDeviceProperties2KHR ) -> (), vkGetPhysicalDeviceFeatures2KHR( physicalDevice: VkPhysicalDevice, pFeatures: *mut VkPhysicalDeviceFeatures2KHR ) -> (), vkGetPhysicalDeviceFormatProperties2KHR( physicalDevice: VkPhysicalDevice, pFormatProperties: *mut VkFormatProperties2KHR<'_> ) -> (), vkGetPhysicalDeviceImageFormatProperties2KHR( physicalDevice: VkPhysicalDevice, pImageFormatInfo: *const VkPhysicalDeviceImageFormatInfo2KHR, pImageFormatProperties: *mut VkImageFormatProperties2KHR<'_> ) -> VkResult, vkGetPhysicalDeviceQueueFamilyProperties2KHR( physicalDevice: VkPhysicalDevice, pQueueFamilyPropertiesCount: *mut u32, pQueueFamilyProperties: *mut VkQueueFamilyProperties2KHR ) -> (), vkGetPhysicalDeviceMemoryProperties2KHR( physicalDevice: VkPhysicalDevice, pMemoryProperties: *mut VkPhysicalDeviceMemoryProperties2KHR ) -> (), vkGetPhysicalDeviceSparseImageFormatProperties2KHR( physicalDevice: VkPhysicalDevice, pFormatInfo: *const VkPhysicalDeviceSparseImageFormatInfo2KHR, pPropertyCount: *mut u32, pProperties: *mut VkSparseImageFormatProperties2KHR ) -> (), });
use crate::{error, state, types}; use mysql::{params, prelude::Queryable}; use snafu::ResultExt; pub fn check_database(config: &types::Config) -> error::Result<()> { let _ = mysql::Pool::new(&config.db_url).context(error::DbConnectionError {})?; Ok(()) } pub fn insert_subscriptions( list_name: &str, subscriptions: std::vec::Vec<types::Subscription>, request: &str, process_subscription: fn(&types::Subscription) -> error::Result<()>, ) -> error::Result<()> { let state = state::get_server_state()?; let config = state.config; let pool = mysql::Pool::new(&config.db_url).context(error::DbConnectionError {})?; let mut connection = pool.get_conn().context(error::DbConnectionError {})?; let mut transaction = connection .start_transaction(mysql::TxOpts::default()) .context(error::DbStartTransactionError {})?; let get_list_stmt = r"SELECT id FROM mailing_lists WHERE email = :email"; let prep_get_list_stmt = transaction .prep(get_list_stmt) .context(error::DbPrepareError { statement: get_list_stmt, })?; let list_id: i32 = transaction .exec_first(&prep_get_list_stmt, params! { "email" => list_name }) .context(error::DbExecuteError { statement: get_list_stmt, })? .ok_or(error::Error::DbMailingListDoesNotExist { list_name: list_name.to_string(), })?; let insert_statement = r"INSERT INTO subscriptions (uuid, list_id, email, request) VALUES (:uuid, :list_id, :email, :request)"; let insert_result = transaction.exec_batch( insert_statement, subscriptions.iter().map(|s| { params! { "uuid" => s.uuid.clone(), "list_id" => list_id, "email" => s.email.clone(), "request" => request, } }), ); if let Err(err) = insert_result { transaction .rollback() .context(error::DbRollbackTransactionError {})?; return Err(err).context(error::DbExecuteError { statement: insert_statement, }); } for subscription in subscriptions.iter() { if let Err(err) = process_subscription(&subscription) { transaction .rollback() .context(error::DbRollbackTransactionError {})?; return Err(err); } } transaction .commit() .context(error::DbCommitTransactionError {})?; Ok(()) }
//! Modules that can be implemented for specific cores. pub use self::spi::HardwareSpi; pub use self::timer::{ Timer8, Timer8Setup, ClockSource8, WaveformGenerationMode8, Timer16, Timer16Setup, ClockSource16, WaveformGenerationMode16, }; pub use self::usart::HardwareUsart; mod spi; mod timer; mod usart;
//! The module exposes the `H2Client` struct, which implements a futures-based API for performing //! HTTP/2 requests, based on Tokio. use super::{ HttpRequestHeaders, HttpRequestBody, HttpResponseHeaders, HttpResponseBody, HttpResponse }; use client::connectors::{TlsConnector, CleartextConnector, H2ConnectorParams}; use client::tokio_layer::{H2ClientTokioProto}; use std::io::{self}; use std::net::SocketAddr; use std::iter::{self, IntoIterator}; use futures::{Async, Future, Poll}; use futures::future::{self, BoxFuture}; use futures::stream::{Stream}; use futures::sync::mpsc; use tokio_core::reactor::{Handle}; use tokio_core::io::{Io}; use tokio_core::net::TcpStream; use tokio_service::{Service}; use tokio_proto::{Connect, TcpClient}; use tokio_proto::streaming::{Message, Body}; use tokio_proto::streaming::multiplex::{StreamingMultiplex}; use tokio_proto::util::client_proxy::ClientProxy; use solicit::http::{Header, StaticHeader}; /// A type alias for the request body stream. type RequestBodyStream = Body<HttpRequestBody, io::Error>; /// A type alias for the `ClientProxy` that we end up building after an `Io` is bound to a /// `H2ClientTokioTransport` by `H2ClientTokioProto`. type TokioClient = ClientProxy< Message<HttpRequestHeaders, RequestBodyStream>, Message<HttpResponseHeaders, Body<HttpResponseBody, io::Error>>, io::Error>; /// A `futures::Stream` impl that represents the body of the response. The `Future` returned /// by various `H2Client` methods returns an instance of this type, along with the response /// headers. pub struct ResponseBodyStream { /// The type simply hides away the Tokio `Body`, which will be returned by Tokio client /// Service. inner: Body<HttpResponseBody, io::Error>, } impl ResponseBodyStream { fn new(inner: Body<HttpResponseBody, io::Error>) -> ResponseBodyStream { ResponseBodyStream { inner: inner, } } } impl Stream for ResponseBodyStream { type Item = HttpResponseBody; type Error = io::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { self.inner.poll() } } /// A `Future` produced by the `H2Client`'s various `request` methods. /// (`request`, `get`, `post`, ...) pub struct FutureH2Response { /// Simply wraps a boxed future inner: BoxFuture<(HttpResponseHeaders, ResponseBodyStream), io::Error>, } impl Future for FutureH2Response { type Item = (HttpResponseHeaders, ResponseBodyStream); type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { self.inner.poll() } } impl FutureH2Response { /// Creates a new `FutureH2Response` wrapping the given boxed future. fn new(inner: BoxFuture<(HttpResponseHeaders, ResponseBodyStream), io::Error>) -> FutureH2Response { FutureH2Response { inner: inner, } } /// Consumes the `FutureH2Response` and returns a new `Future` that will resolve once the full /// body of the response has become available, with both the response headers and all the body /// bytes in a `Vec<u8>` (as an `HttpResponse` instance). pub fn into_full_body_response(self) -> BoxFuture<HttpResponse, io::Error> { let body_response = self.and_then(|(headers, body_stream)| { body_stream .fold(Vec::<u8>::new(), |mut vec, chunk| { vec.extend(chunk.body.into_iter()); future::ok::<_, io::Error>(vec) }) .map(move |body| { HttpResponse { headers: headers.headers, body: body } }) }); body_response.boxed() } } /// A struct that implements a futures-based API for an HTTP/2 client. pub struct H2Client { /// The inner ClientProxy that hooks into the whole Tokio infrastructure. inner: TokioClient, /// The authority header (nee Host). Specifies the host name that the HTTP requests will /// be directed at. This is distinct from the socket address. authority: Vec<u8>, } impl H2Client { /// Creates a new `H2Client` from the given `TokioClient`. fn new(inner: TokioClient, authority: Vec<u8>) -> H2Client { H2Client { inner: inner, authority: authority, } } /// Connect to the given socket and yield a new `H2Client` that can be used to send HTTP/2 /// requests to this socket. /// /// Returns a future that will resolve to the `H2Client`. /// /// The connection established connection will be over TLS (and http/2 has to be negotiated /// by ALPN). pub fn connect(authority: &str, socket_addr: &SocketAddr, handle: &Handle) -> H2ClientNew<TlsConnector<TcpStream>> { H2Client::with_connector( authority, socket_addr, handle, TlsConnector::<TcpStream>::new()) } /// Connect to the given socket and yield a new `H2Client` that can be used to send HTTP/2 /// requests to this socket. /// /// Returns a future that will resolve to the `H2Client`. /// /// The HTTP/2 connection will be executed in cleartext, over the raw socket. pub fn cleartext_connect(authority: &str, socket_addr: &SocketAddr, handle: &Handle) -> H2ClientNew<CleartextConnector<TcpStream>> { H2Client::with_connector( authority, socket_addr, handle, CleartextConnector::<TcpStream>::new()) } /// Connect to the given socket and yield a new `H2Client` that can be used to send HTTP/2 /// requests to this socket. /// /// Returns a future that will resolve to the `H2Client`. /// /// HTTP/2 connection negotiation needs to be performed by the provided `Connector` instance, /// which will be provided the raw socket as soon as the client has connected. pub fn with_connector<Connector>( authority: &str, socket_addr: &SocketAddr, handle: &Handle, connector: Connector) -> H2ClientNew<Connector> where Connector: Service<Request=H2ConnectorParams<TcpStream>, Error=io::Error>, Connector::Response: Io { let proto = H2ClientTokioProto { connector: connector, authority: authority.into(), }; let client = TcpClient::<StreamingMultiplex<RequestBodyStream>, _>::new(proto); let connect = client.connect(&socket_addr, &handle); H2ClientNew::new(connect, authority.as_bytes().to_vec()) } /// Issues a GET request to the server. /// /// Yields a future that resolves to an `HttpRequestHeaders` struct. This struct will carry /// both the response headers, as well as the response body. pub fn get(&mut self, path: &[u8]) -> FutureH2Response { self.request(b"GET", path, iter::empty(), None) } /// Issues a POST request, carrying the given body. pub fn post(&mut self, path: &[u8], body: Vec<u8>) -> FutureH2Response { self.request(b"POST", path, iter::empty(), Some(body)) } /// Perform a request, providing manually the request method, headers, and body. pub fn request<I>(&mut self, method: &[u8], path: &[u8], user_headers: I, body: Option<Vec<u8>>) -> FutureH2Response where I: IntoIterator<Item=StaticHeader> { let request_headers = self.prepare_headers(method, path, user_headers); let tokio_message = match body { None => Message::WithoutBody(request_headers), Some(body) => { let body_stream = Body::from(HttpRequestBody::new(body)); Message::WithBody(request_headers, body_stream) }, }; self.request_with_message(tokio_message) } /// Perform a request, where the method and path are already provided, while the body should be /// streamed out by posting body chunks (`HttpRequestBody` instances) onto the returned /// channel. pub fn streaming_request<I>(&mut self, method: &[u8], path: &[u8], user_headers: I) -> (FutureH2Response, mpsc::Sender<Result<HttpRequestBody, io::Error>>) where I: IntoIterator<Item=StaticHeader> { trace!("starting streaming request"); let headers = self.prepare_headers(method, path, user_headers); let (tx, body) = Body::pair(); (self.request_with_message(Message::WithBody(headers, body)), tx) } /// Actually performs the full request. Avoids monomorphizing the entire code, but rather only /// the bit that requires the use of the IntoIterator trait, before passing off to this. fn request_with_message(&mut self, message: Message<HttpRequestHeaders, RequestBodyStream>) -> FutureH2Response { let response_future = Service::call(&self.inner, message).map(|response| { debug!("resolved response message"); match response { Message::WithoutBody(resp @ HttpResponseHeaders { .. }) => { // If there's no body, just yield an empty body stream. (resp, ResponseBodyStream::new(Body::empty())) }, Message::WithBody(resp @ HttpResponseHeaders { .. }, body) => { (resp, ResponseBodyStream::new(body)) }, } }); FutureH2Response::new(response_future.boxed()) } /// Creates `HttpRequestHeaders` that will include appropriate pseudo-headers, as well as the /// given user-provided extra headers. fn prepare_headers<I>(&mut self, method: &[u8], path: &[u8], user_headers: I) -> HttpRequestHeaders where I: IntoIterator<Item=StaticHeader> { let mut headers = Vec::new(); headers.extend(vec![ Header::new(b":method", method.to_vec()), Header::new(b":path", path.to_vec()), Header::new(b":authority", self.authority.clone()), Header::new(b":scheme", b"http"), ].into_iter()); headers.extend(user_headers.into_iter()); HttpRequestHeaders::with_headers(headers) } } /// A simple `Future` implementation that resolves once the HTTP/2 client connection is /// established. pub struct H2ClientNew<Connector> where Connector: 'static + Service<Request=H2ConnectorParams<TcpStream>, Error=io::Error>, Connector::Response: 'static + Io { /// The future that resolves to a new Tokio ClientProxy. inner: Connect<StreamingMultiplex<RequestBodyStream>, H2ClientTokioProto<Connector>>, /// The authority that the new client will send requests to. authority: Option<Vec<u8>>, } impl<Connector> H2ClientNew<Connector> where Connector: 'static + Service<Request=H2ConnectorParams<TcpStream>, Error=io::Error>, Connector::Response: 'static + Io { fn new(connect: Connect<StreamingMultiplex<RequestBodyStream>, H2ClientTokioProto<Connector>>, authority: Vec<u8>) -> H2ClientNew<Connector> { H2ClientNew { inner: connect, authority: Some(authority), } } } impl<Connector> Future for H2ClientNew<Connector> where Connector: 'static + Service<Request=H2ConnectorParams<TcpStream>, Error=io::Error>, Connector::Response: 'static + Io { type Item = H2Client; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { trace!("waiting for client connection..."); match self.inner.poll() { Ok(Async::NotReady) => Ok(Async::NotReady), Ok(Async::Ready(client_proxy)) => { trace!("client connected"); let authority = self.authority.take().expect("H2ClientNew future polled again"); Ok(Async::Ready(H2Client::new(client_proxy, authority))) }, Err(e) => Err(e), } } }
mod hash; mod poseidon; pub use hash::{poseidon_hash, poseidon_hash_many, PoseidonHasher}; pub use poseidon::{permute, permute_comp, PoseidonState};
fn main() { windows::core::build_legacy! { Windows::ApplicationModel::Contacts::KnownContactField, }; }
use crate::{DocBase, VarType}; const DESCRIPTION: &'static str = r#" Natural logarithm of any `x > 0` is the unique `y` such that `e^y = x` "#; pub fn gen_doc() -> Vec<DocBase> { let fn_doc = DocBase { var_type: VarType::Function, name: "log", signatures: vec![], description: DESCRIPTION, example: "", returns: "The natural logarithm of x.", arguments: "", remarks: "", links: "[log10](#fun-log10)", }; vec![fn_doc] }
#[macro_use] pub mod errors; pub mod commands; pub mod http; pub mod metrics; pub mod types;
use super::country_data::CountryData; use nanoserde::DeRon; fn load_countries() -> Vec<CountryData> { let countries: Vec<CountryData> = DeRon::deserialize_ron(include_str!("../assets/Countries.ron")).unwrap(); countries } lazy_static! { pub static ref COUNTRIES: Vec<CountryData> = load_countries(); }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_exception::Result; use common_expression::types::StringType; use common_expression::DataBlock; use common_expression::DataSchemaRef; use common_expression::FromData; use common_meta_app::principal::PrincipalIdentity; use common_sql::plans::ShowGrantsPlan; use common_users::RoleCacheManager; use common_users::UserApiProvider; use crate::interpreters::Interpreter; use crate::pipelines::PipelineBuildResult; use crate::sessions::QueryContext; use crate::sessions::TableContext; pub struct ShowGrantsInterpreter { ctx: Arc<QueryContext>, plan: ShowGrantsPlan, } impl ShowGrantsInterpreter { pub fn try_create(ctx: Arc<QueryContext>, plan: ShowGrantsPlan) -> Result<Self> { Ok(ShowGrantsInterpreter { ctx, plan }) } } #[async_trait::async_trait] impl Interpreter for ShowGrantsInterpreter { fn name(&self) -> &str { "ShowGrantsInterpreter" } fn schema(&self) -> DataSchemaRef { self.plan.schema() } async fn execute2(&self) -> Result<PipelineBuildResult> { let tenant = self.ctx.get_tenant(); // TODO: add permission check on reading user grants let (identity, grant_set) = match self.plan.principal { None => { let user = self.ctx.get_current_user()?; (user.identity().to_string(), user.grants) } Some(ref principal) => match principal { PrincipalIdentity::User(user) => { let user = UserApiProvider::instance() .get_user(&tenant, user.clone()) .await?; (user.identity().to_string(), user.grants) } PrincipalIdentity::Role(role) => { let role = UserApiProvider::instance() .get_role(&tenant, role.clone()) .await?; (format!("'{}'", role.identity()), role.grants) } }, }; // TODO: display roles list instead of the inherited roles let grant_list = RoleCacheManager::instance() .find_related_roles(&tenant, &grant_set.roles()) .await? .into_iter() .map(|role| role.grants) .fold(grant_set, |a, b| a | b) .entries() .iter() .map(|e| format!("{} TO {}", e, identity).as_bytes().to_vec()) .collect::<Vec<_>>(); PipelineBuildResult::from_blocks(vec![DataBlock::new_from_columns(vec![ StringType::from_data(grant_list), ])]) } }
#[macro_use] extern crate lazy_static; use aoc; use regex::Regex; use std::cmp; use std::collections::HashMap; type HexCoord = (i32, i32, i32); type HexVec = (i32, i32, i32); type HexGrid = HashMap<HexCoord, i32>; fn add(c: HexCoord, v: HexVec) -> HexCoord { (c.0 + v.0, c.1 + v.1, c.2 + v.2) } fn count_black_adj(input: &HexGrid, pos: HexCoord) -> u32 { lazy_static! { static ref dirs: Vec<HexVec> = vec![ (1, 0, -1), (0, 1, -1), (1, -1, 0), (-1, 1, 0), (0, -1, 1), (-1, 0, 1) ]; } let mut count: u32 = 0; for d in dirs.iter() { let n = add(pos, *d); let t = input.get(&n).unwrap_or(&0); count += *t as u32; } count } fn iterate(input: &HexGrid) -> HexGrid { let mut output = input.clone(); let mut min = (0, 0, 0); let mut max = (0, 0, 0); for (p, t) in input { min.0 = cmp::min(min.0, p.0); min.1 = cmp::min(min.1, p.1); min.2 = cmp::min(min.2, p.2); max.0 = cmp::max(max.0, p.0); max.1 = cmp::max(max.1, p.1); max.2 = cmp::max(max.2, p.2); } min.0 -= 1; min.1 -= 1; min.2 -= 1; max.0 += 1; max.1 += 1; max.2 += 1; for x in min.0..=max.0 { for y in min.1..=max.1 { for z in min.2..=max.2 { let pos = (x, y, z); let t = *input.get(&pos).unwrap_or(&0); let c = count_black_adj(input, pos); let mut nv = t; // white tile, 2 black neighbors -> black if t == 0 && c == 2 { nv = 1; output.insert(pos, nv); continue; } // black tile, 0 or more than 2 black nei -> white if t == 1 && (c == 0 || c > 2) { nv = 0; output.insert(pos, nv); continue; } // output.insert(pos, nv); } } } output } fn main() { let mut grid: HexGrid = HashMap::new(); let lines = aoc::lines_from_file("input.txt"); let re: Regex = Regex::new(r"(ne|nw|se|sw|e|w)").unwrap(); for line in lines { let mut pos = (0, 0, 0); for c in re.captures_iter(&line) { let dir = c.get(1).unwrap().as_str(); let v: HexVec = match dir { "ne" => (1, 0, -1), "nw" => (0, 1, -1), "e" => (1, -1, 0), "w" => (-1, 1, 0), "se" => (0, -1, 1), "sw" => (-1, 0, 1), _ => (0, 0, 0), }; pos = add(pos, v); } let t = grid.entry(pos).or_insert(0); // toggle between white (0) and black (1) *t = (*t + 1) % 2; } let sum: i32 = grid.values().sum(); dbg!(sum); for day in 1..=100 { grid = iterate(&grid); let sum: i32 = grid.values().sum(); println!("Day {}: {}", day, sum); } }
use gl::types::*; use std::marker::PhantomData; use super::{BufferType, BufferData, BufferAcces, ReadBufferMap, WriteBufferMap, DynamicBuffer}; use crate::get_value; pub struct Buffer<T, Kind, Acces> where T: Sized + BufferData, Kind: BufferType, Acces: BufferAcces { pub(crate) id: GLuint, pub(crate) len: usize, pub(crate) data: PhantomData<T>, pub(crate) kind: PhantomData<Kind>, pub(crate) acces: PhantomData<Acces>, } impl<T, Kind, Acces> Buffer<T, Kind, Acces> where T: Sized + BufferData, Kind: BufferType, Acces: BufferAcces { pub fn new(data: &[T]) -> Buffer<T, Kind, Acces> { let id = get_value(0, |id| unsafe { gl::GenBuffers(1, id); }); let vbo = Buffer { id, len: data.len(), data: PhantomData, kind: PhantomData, acces: PhantomData, }; vbo.bind(); unsafe { gl::BufferData( Kind::value(), (data.len() * std::mem::size_of::<T>()) as gl::types::GLsizeiptr, data as *const [T] as *const GLvoid, Acces::value(), ); } vbo } pub fn id(&self) -> GLuint { self.id } pub fn bind(&self) { unsafe { gl::BindBuffer(Kind::value(), self.id); } } pub fn update(&mut self, data: &[T], offset: GLuint) { self.bind(); self.len = data.len(); unsafe { gl::BufferSubData( Kind::value(), (offset as usize * std::mem::size_of::<T>()) as isize, (data.len() * std::mem::size_of::<T>()) as gl::types::GLsizeiptr, data as *const [T] as *const GLvoid ); } } pub fn read<'a>(&self) -> ReadBufferMap<'_, T, Kind, Acces>{ let ptr = unsafe { gl::MapBuffer( Kind::value(), gl::READ_ONLY ) } as *const T; let val = unsafe { std::slice::from_raw_parts(ptr as *const T, self.len) }; ReadBufferMap { buff: self, buffer: val } } } impl<T, Kind> Buffer<T, Kind, DynamicBuffer> where T: Sized + BufferData, Kind: BufferType, { pub fn write<'a>(&mut self) -> WriteBufferMap<'_, T, Kind, DynamicBuffer>{ let ptr = unsafe { gl::MapBuffer( Kind::value(), gl::READ_WRITE ) } as *const T; let val = unsafe { std::slice::from_raw_parts_mut(ptr as *mut T, self.len) }; WriteBufferMap { buff: self, buffer: val } } } impl<T, Kind, Acces> Drop for Buffer<T, Kind, Acces> where T: Sized + BufferData, Kind: BufferType, Acces: BufferAcces { fn drop(&mut self) { unsafe { gl::DeleteBuffers(1, &self.id); } } }
// xfail-stage0 use std; use libc(); use zed(name = "std"); use bar(name = "std", ver = "0.0.1"); // FIXME: commented out since resolve doesn't know how to handle crates yet. // import std._str; // import x = std._str; mod baz { use std; use libc(); use zed(name = "std"); use bar(name = "std", ver = "0.0.1"); // import std._str; // import x = std._str; } fn main() { }
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib::object::IsA; use glib::translate::*; #[cfg(any(feature = "v2_2", feature = "dox"))] use glib::GString; use std::fmt; use webkit2_webextension_sys; glib_wrapper! { pub struct Frame(Object<webkit2_webextension_sys::WebKitFrame, webkit2_webextension_sys::WebKitFrameClass, FrameClass>); match fn { get_type => || webkit2_webextension_sys::webkit_frame_get_type(), } } pub const NONE_FRAME: Option<&Frame> = None; pub trait FrameExt: 'static { #[cfg(any(feature = "v2_26", feature = "dox"))] fn get_id(&self) -> u64; //#[cfg_attr(feature = "v2_22", deprecated)] //#[cfg(any(feature = "v2_2", feature = "dox"))] //fn get_javascript_context_for_script_world<P: IsA<ScriptWorld>>(&self, world: &P) -> /*Ignored*/Option<java_script_core::GlobalContextRef>; //#[cfg_attr(feature = "v2_22", deprecated)] //#[cfg(any(feature = "v2_2", feature = "dox"))] //fn get_javascript_global_context(&self) -> /*Ignored*/Option<java_script_core::GlobalContextRef>; //#[cfg(any(feature = "v2_22", feature = "dox"))] //fn get_js_context(&self) -> /*Ignored*/Option<java_script_core::Context>; //#[cfg(any(feature = "v2_22", feature = "dox"))] //fn get_js_context_for_script_world<P: IsA<ScriptWorld>>(&self, world: &P) -> /*Ignored*/Option<java_script_core::Context>; //#[cfg(any(feature = "v2_22", feature = "dox"))] //fn get_js_value_for_dom_object<P: IsA<DOMObject>>(&self, dom_object: &P) -> /*Ignored*/Option<java_script_core::Value>; //#[cfg(any(feature = "v2_22", feature = "dox"))] //fn get_js_value_for_dom_object_in_script_world<P: IsA<DOMObject>, Q: IsA<ScriptWorld>>(&self, dom_object: &P, world: &Q) -> /*Ignored*/Option<java_script_core::Value>; #[cfg(any(feature = "v2_2", feature = "dox"))] fn get_uri(&self) -> Option<GString>; #[cfg(any(feature = "v2_2", feature = "dox"))] fn is_main_frame(&self) -> bool; } impl<O: IsA<Frame>> FrameExt for O { #[cfg(any(feature = "v2_26", feature = "dox"))] fn get_id(&self) -> u64 { unsafe { webkit2_webextension_sys::webkit_frame_get_id(self.as_ref().to_glib_none().0) } } //#[cfg(any(feature = "v2_2", feature = "dox"))] //fn get_javascript_context_for_script_world<P: IsA<ScriptWorld>>(&self, world: &P) -> /*Ignored*/Option<java_script_core::GlobalContextRef> { // unsafe { // TODO: call webkit2_webextension_sys:webkit_frame_get_javascript_context_for_script_world() // } //} //#[cfg(any(feature = "v2_2", feature = "dox"))] //fn get_javascript_global_context(&self) -> /*Ignored*/Option<java_script_core::GlobalContextRef> { // unsafe { TODO: call webkit2_webextension_sys:webkit_frame_get_javascript_global_context() } //} //#[cfg(any(feature = "v2_22", feature = "dox"))] //fn get_js_context(&self) -> /*Ignored*/Option<java_script_core::Context> { // unsafe { TODO: call webkit2_webextension_sys:webkit_frame_get_js_context() } //} //#[cfg(any(feature = "v2_22", feature = "dox"))] //fn get_js_context_for_script_world<P: IsA<ScriptWorld>>(&self, world: &P) -> /*Ignored*/Option<java_script_core::Context> { // unsafe { TODO: call webkit2_webextension_sys:webkit_frame_get_js_context_for_script_world() } //} //#[cfg(any(feature = "v2_22", feature = "dox"))] //fn get_js_value_for_dom_object<P: IsA<DOMObject>>(&self, dom_object: &P) -> /*Ignored*/Option<java_script_core::Value> { // unsafe { TODO: call webkit2_webextension_sys:webkit_frame_get_js_value_for_dom_object() } //} //#[cfg(any(feature = "v2_22", feature = "dox"))] //fn get_js_value_for_dom_object_in_script_world<P: IsA<DOMObject>, Q: IsA<ScriptWorld>>(&self, dom_object: &P, world: &Q) -> /*Ignored*/Option<java_script_core::Value> { // unsafe { // TODO: call webkit2_webextension_sys:webkit_frame_get_js_value_for_dom_object_in_script_world() // } //} #[cfg(any(feature = "v2_2", feature = "dox"))] fn get_uri(&self) -> Option<GString> { unsafe { from_glib_none(webkit2_webextension_sys::webkit_frame_get_uri( self.as_ref().to_glib_none().0, )) } } #[cfg(any(feature = "v2_2", feature = "dox"))] fn is_main_frame(&self) -> bool { unsafe { from_glib(webkit2_webextension_sys::webkit_frame_is_main_frame( self.as_ref().to_glib_none().0, )) } } } impl fmt::Display for Frame { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Frame") } }
use std::thread; use bus::Bus; use super::Signal; impl From<usize> for Signal { fn from(sig: usize) -> Signal { match sig as libc::c_int { signal_hook::consts::SIGINT => Signal::INT, signal_hook::consts::SIGTERM => Signal::TERM, signal_hook::consts::SIGQUIT => Signal::QUIT, signal_hook::consts::SIGHUP => Signal::HUP, signal_hook::consts::SIGABRT => Signal::ABRT, signal_hook::consts::SIGALRM => Signal::ALRM, signal_hook::consts::SIGUSR1 => Signal::USR1, signal_hook::consts::SIGUSR2 => Signal::USR2, signal_hook::consts::SIGCHLD => Signal::CHLD, _ => Signal::Unknown, } } } pub fn init(mut bus: Bus<Signal>) { thread::spawn(move || { use signal_hook::iterator::Signals; let mut signals = Signals::new(&[ signal_hook::consts::SIGINT, signal_hook::consts::SIGTERM, signal_hook::consts::SIGQUIT, signal_hook::consts::SIGHUP, signal_hook::consts::SIGABRT, signal_hook::consts::SIGALRM, signal_hook::consts::SIGUSR1, signal_hook::consts::SIGUSR2, signal_hook::consts::SIGCHLD, ]) .expect("could not bind signal handlers"); for signal in signals.forever() { match Signal::from(signal as usize) { Signal::Unknown => (), sig => bus.broadcast(sig), } } }); }
mod c01_convert_hex_to_base64; use failure::Error; pub fn add_challenges(cryptochallenges: &mut Vec<fn() -> Result<(), Error>>) { cryptochallenges.push(c01_convert_hex_to_base64::run); }
struct Node { data: i32, next: Option<Box<Node>>, } impl Node { fn new(data: i32) -> Node { Node { data: data, next: None, } } fn assign_next(&mut self, next: Node) { self.next = Some(Box::new(next)); } } fn main() { let node = Node::new(1); let second_node = Node::new(2); node.assign_next(second_node); }
use cgmath::*; use num_traits::cast::NumCast; use serde::*; #[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)] pub struct Rect<T> { pub start: Point2<T>, pub end: Point2<T>, } impl<T> Rect<T> { pub fn new(start: Point2<T>, end: Point2<T>) -> Self { Self { start, end } } } impl<T: BaseNum + Ord> Rect<T> { // TODO: support this for floats /// Creates a `Rect` that is the bounding box of a set of points. pub fn from_points(points: &[Point2<T>]) -> Rect<T> { // TODO: use minmax_by_key Rect { start: Point2::from_vec(vec2( points.iter().min_by_key(|point| point.x).unwrap().x, points.iter().min_by_key(|point| point.y).unwrap().y, )), end: Point2::from_vec(vec2( points.iter().max_by_key(|point| point.x).unwrap().x, points.iter().max_by_key(|point| point.y).unwrap().y, )), } } } impl<T: BaseNum> Rect<T> { /// Returns the size of the `Rect` pub fn size(&self) -> Vector2<T> { self.end - self.start } /// Returns whether the `Rect` contains the given point. pub fn contains_point(self, point: Point2<T>) -> bool { self.start.x <= point.x && self.end.x >= point.x && self.start.y <= point.y && self.end.y >= point.y } } impl<T: NumCast + Copy> Rect<T> { pub fn cast<Res: NumCast>(&self) -> Option<Rect<Res>> { Some(Rect::new(self.start.cast()?, self.end.cast()?)) } }
use super::util; use super::writer::Writer; use crate::MkvId; const MAX_TRACK_NUMBER: u64 = 126; // Class to hold data the will be written to a block. #[derive(Debug, Clone, Eq, PartialEq)] pub struct Frame { // Id of the Additional data. add_id_: u64, // Pointer to additional data. Owned by this class. additional_: Vec<u8>, // Duration of the frame in nanoseconds. duration_: u64, // Flag indicating that |duration_| has been set. Setting duration causes the // frame to be written out as a Block with BlockDuration instead of as a // SimpleBlock. duration_set_: bool, // Pointer to the data. Owned by this class. frame_: Vec<u8>, // Flag telling if the data should set the key flag of a block. is_key_: bool, // Mkv track number the data is associated with. track_number_: u64, // Timestamp of the data in nanoseconds. timestamp_: u64, // Discard padding for the frame. discard_padding_: i64, // Reference block timestamp. reference_block_timestamp_: i64, // Flag indicating if |reference_block_timestamp_| has been set. reference_block_timestamp_set_: bool, } use std::cmp::Ordering; impl Ord for Frame { fn cmp(&self, other: &Frame) -> Ordering { self.timestamp_.cmp(&other.timestamp_) } } impl PartialOrd for Frame { fn partial_cmp(&self, other: &Frame) -> Option<Ordering> { Some(self.timestamp_.cmp(&other.timestamp_)) } } impl Frame { pub fn add_id(&self) -> u64 { self.add_id_ } pub fn additional(&self) -> &[u8] { &self.additional_ } pub fn additional_length(&self) -> u64 { self.additional_.len() as u64 } pub fn set_duration(&mut self, duration: u64) { self.duration_ = duration; self.duration_set_ = true; } pub fn duration(&self) -> u64 { self.duration_ } pub fn duration_set(&self) -> bool { self.duration_set_ } pub fn frame(&self) -> &[u8] { &self.frame_ } pub fn set_is_key(&mut self, key: bool) { self.is_key_ = key; } pub fn is_key(&self) -> bool { self.is_key_ } pub fn length(&self) -> u64 { self.frame_.len() as u64 } pub fn set_track_number(&mut self, track_number: u64) { self.track_number_ = track_number; } pub fn track_number(&self) -> u64 { self.track_number_ } pub fn set_timestamp(&mut self, timestamp: u64) { self.timestamp_ = timestamp; } pub fn timestamp(&self) -> u64 { self.timestamp_ } pub fn set_discard_padding(&mut self, discard_padding: i64) { self.discard_padding_ = discard_padding; } pub fn discard_padding(&self) -> i64 { self.discard_padding_ } pub fn set_reference_block_timestamp(&mut self, reference_block_timestamp: i64) { self.reference_block_timestamp_ = reference_block_timestamp; self.reference_block_timestamp_set_ = true; } pub fn reference_block_timestamp(&self) -> i64 { self.reference_block_timestamp_ } pub fn reference_block_timestamp_set(&self) -> bool { self.reference_block_timestamp_set_ } pub fn new() -> Frame { Frame { add_id_: 0, additional_: Vec::new(), duration_: 0, duration_set_: false, frame_: Vec::new(), is_key_: false, track_number_: 0, timestamp_: 0, discard_padding_: 0, reference_block_timestamp_: 0, reference_block_timestamp_set_: false, } } pub fn Init(&mut self, frame: &[u8]) -> bool { self.frame_ = frame.to_vec(); true } pub fn AddAdditionalData(&mut self, additional: &[u8], add_id: u64) -> bool { self.additional_ = additional.to_vec(); self.add_id_ = add_id; true } pub fn IsValid(&self) -> bool { if self.frame_.is_empty() { return false; } if !self.additional_.is_empty() { return false; } if self.track_number_ == 0 || self.track_number_ > MAX_TRACK_NUMBER { return false; } if !self.CanBeSimpleBlock() && !self.is_key_ && !self.reference_block_timestamp_set_ { return false; } return true; } pub fn CanBeSimpleBlock(&self) -> bool { self.additional_.len() == 0 && self.discard_padding_ == 0 && self.duration_ == 0 } pub fn WriteSimpleBlock(&self, writer: &mut dyn Writer, timecode: i64) -> u64 { if let Err(e) = util::WriteID(writer, MkvId::MkvSimpleBlock) { return 0; } let size = self.length() + 4; if let Err(e) = util::WriteUInt(writer, size) { return 0; } if let Err(e) = util::WriteUInt(writer, self.track_number()) { return 0; } if let Err(e) = util::SerializeInt(writer, timecode as u64, 2) { return 0; } let mut flags = 0; if self.is_key() { flags |= 0x80; } if let Err(e) = util::SerializeInt(writer, flags, 1) { return 0; } if let Err(e) = writer.write(self.frame()) { return 0; } return util::GetUIntSize(MkvId::MkvSimpleBlock as u64) as u64 + util::GetCodedUIntSize(size) as u64 + 4 + self.length(); } pub fn WriteBlock(&self, writer: &mut dyn Writer, timecode: i64, timecode_scale: u64) -> u64 { let mut block_additional_elem_size = 0; let mut block_addid_elem_size = 0; let mut block_more_payload_size = 0; let mut block_more_elem_size = 0; let mut block_additions_payload_size = 0; let mut block_additions_elem_size = 0; if !self.additional().is_empty() { block_additional_elem_size = util::EbmlElementSizeArgSlice(MkvId::MkvBlockAdditional, self.additional()); block_addid_elem_size = util::EbmlElementSizeArgU64(MkvId::MkvBlockAddID, self.add_id()); block_more_payload_size = block_addid_elem_size + block_additional_elem_size; block_more_elem_size = util::EbmlMasterElementSize(MkvId::MkvBlockMore, block_more_payload_size) + block_more_payload_size; block_additions_payload_size = block_more_elem_size; block_additions_elem_size = util::EbmlMasterElementSize(MkvId::MkvBlockAdditions, block_additions_payload_size) + block_additions_payload_size; } let mut discard_padding_elem_size = 0; if self.discard_padding() != 0 { discard_padding_elem_size = util::EbmlElementSizeArgI64(MkvId::MkvDiscardPadding, self.discard_padding()); } let reference_block_timestamp = self.reference_block_timestamp() as u64 / timecode_scale; let mut reference_block_elem_size = 0; if !self.is_key() { reference_block_elem_size = util::EbmlElementSizeArgU64(MkvId::MkvReferenceBlock, reference_block_timestamp); } let duration = self.duration() / timecode_scale; let mut block_duration_elem_size = 0; if duration > 0 { block_duration_elem_size = util::EbmlElementSizeArgU64(MkvId::MkvBlockDuration, duration); } let block_payload_size = 4 + self.length(); let block_elem_size = util::EbmlMasterElementSize(MkvId::MkvBlock, block_payload_size) + block_payload_size; let block_group_payload_size = block_elem_size + block_additions_elem_size + block_duration_elem_size + discard_padding_elem_size + reference_block_elem_size; if !util::WriteEbmlMasterElement(writer, MkvId::MkvBlockGroup, block_group_payload_size) { return 0; } if !util::WriteEbmlMasterElement(writer, MkvId::MkvBlock, block_payload_size) { return 0; } if let Err(e) = util::WriteUInt(writer, self.track_number()) { return 0; } if let Err(e) = util::SerializeInt(writer, timecode as u64, 2) { return 0; } // For a Block, flags is always 0. if let Err(e) = util::SerializeInt(writer, 0, 1) { return 0; } if let Err(e) = writer.write(self.frame()) { return 0; } if !self.additional().is_empty() { if !util::WriteEbmlMasterElement( writer, MkvId::MkvBlockAdditions, block_additions_payload_size, ) { return 0; } if !util::WriteEbmlMasterElement(writer, MkvId::MkvBlockMore, block_more_payload_size) { return 0; } if !util::WriteEbmlElementArgU64(writer, MkvId::MkvBlockAddID, self.add_id()) { return 0; } if !util::WriteEbmlElementArgSlice(writer, MkvId::MkvBlockAdditional, self.additional()) { return 0; } } if self.discard_padding() != 0 && !util::WriteEbmlElementArgI64( writer, MkvId::MkvDiscardPadding, self.discard_padding(), ) { return 0; } if !self.is_key() && !util::WriteEbmlElementArgU64( writer, MkvId::MkvReferenceBlock, reference_block_timestamp, ) { return 0; } if duration > 0 && !util::WriteEbmlElementArgU64(writer, MkvId::MkvBlockDuration, duration) { return 0; } util::EbmlMasterElementSize(MkvId::MkvBlockGroup, block_group_payload_size) + block_group_payload_size } }
//! Interactability might be important, but just sticking to regular shapes can get a bit boring. //! //! It's time for the wonderful world of images! Drawing images is almost the same as drawing //! colors, but instead of using `Background::Col` we use `Background::Img`. The big change to //! learn with images is asset loading. //! On desktop, you can make a blocking file load read, but that's not an option on web. This means //! that *all* Quicksilver asset loading is asynchronous, through the `Asset` system. //! ```no_run //! // Draw an image to the screen //! extern crate quicksilver; //! //! use quicksilver::{ //! Result, //! geom::{Shape, Vector}, //! graphics::{Background::Img, Color, Image}, // We need Image and image backgrounds //! lifecycle::{Asset, Settings, State, Window, run}, // To load anything, we need Asset //! }; //! //! struct ImageViewer { //! asset: Asset<Image>, // an image asset isn't state, but it does need to persist //! } //! //! impl State for ImageViewer { //! fn new() -> Result<ImageViewer> { //! let asset = Asset::new(Image::load("image.png")); // Start loading the asset //! Ok(ImageViewer { asset }) //! } //! //! fn draw(&mut self, window: &mut Window) -> Result<()> { //! window.clear(Color::WHITE)?; //! self.asset.execute(|image| { //! // If we've loaded the image, draw it //! window.draw(&image.area().with_center((400, 300)), Img(&image)); //! Ok(()) //! }) //! } //! } //! //! fn main() { //! run::<ImageViewer>("Image Example", Vector::new(800, 600), Settings { //! icon_path: Some("image.png"), // Set the window icon //! ..Settings::default() //! }); //! } //! ``` //! You'll notice we provided a path to `Image::load`, which was "image.png." This asset is stored //! in the `static` directory, not in the crate root. This is a current limitation of `cargo-web` //! and may be changed in the future, but for now all assets must be stored in `static.` You can //! use the [Quicksilver test //! image](https://github.com/ryanisaacg/quicksilver/blob/development/static/image.png). //! //! On the other hand, if you want to pack the Image data directly into the Rust binary, you can //! use `include_bytes!` and `Image::from_bytes`, which would look like //! `Image::from_bytes(include_bytes("path/to/my/image.png"))`. This has the advantage of allowing //! you to pack all your assets into one file, but also several disadvantages (such as needing to //! recompile the binary to edit the assets). Generally it is recommended to use the Asset system, //! but including the bytes is also an option. //! //! The asset system uses Futures, which are an asychronous programming concept. Basically, a //! Future is a computation that will complete at some point in, well, the future. For example, //! loading an image over a network is a future: the web browser doesn't have the image downloaded //! *yet* but it will (or it will produce an error.) //! //! This asset system is probably temporary, as async / await promise to be much more ergonomic //! methods of dealing with futures. However, Rust's async / await story isn't stable yet, so the //! Asset system is the most convenient way of loading things with Quicksilver. The execute //! function on an Asset runs the provided closure if loading is complete, with the actual asset //! data passed as a parameter. In the example above, the window is cleared every draw frame and //! once the image is loaded, it is drawn to the screen. //! //! Additionally, we now set the application icon path. The icon is also sourced from `static`, and //! determines the tab icon on the web and the window icon on desktop. //! //! Images can have subimages, which allows for spritesheets, texture atlases, and sprite batching: //! ```no_run //! // Draw an image to the screen //! extern crate quicksilver; //! //! use quicksilver::{ //! Future, Result, // We need the Future trait to operate on a future //! geom::{Rectangle, Shape, Vector}, //! graphics::{Background::Img, Color, Image}, //! lifecycle::{Asset, Settings, State, Window, run}, //! }; //! //! struct ImageViewer { //! asset: Asset<Image>, //! } //! //! impl State for ImageViewer { //! fn new() -> Result<ImageViewer> { //! let asset = Asset::new( //! Image::load("image.png") //! // Between the image loading and the asset being "done", take a slice from it //! .map(|image| image.subimage(Rectangle::new((0, 0), (32, 64)))) //! ); //! Ok(ImageViewer { asset }) //! } //! //! fn draw(&mut self, window: &mut Window) -> Result<()> { //! window.clear(Color::WHITE)?; //! self.asset.execute(|image| { //! // If we've loaded the image, draw it //! window.draw(&image.area().with_center((400, 300)), Img(&image)); //! Ok(()) //! }) //! } //! } //! //! fn main() { //! run::<ImageViewer>("Image Example", Vector::new(800, 600), Settings { //! icon_path: Some("image.png"), // Set the window icon //! ..Settings::default() //! }); //! } //! ``` //! Here `map` applies a transformation to the image after it is loaded; the ability to chain //! multiple assets together or apply complex operations to loading assets will be covered more in //! depth in the asset combinator tutorial.
#[doc = "Reader of register WRP1BR"] pub type R = crate::R<u32, super::WRP1BR>; #[doc = "Writer for register WRP1BR"] pub type W = crate::W<u32, super::WRP1BR>; #[doc = "Register WRP1BR `reset()`'s with value 0xff00_ff00"] impl crate::ResetValue for super::WRP1BR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0xff00_ff00 } } #[doc = "Reader of field `WRP1B_PSTRT`"] pub type WRP1B_PSTRT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WRP1B_PSTRT`"] pub struct WRP1B_PSTRT_W<'a> { w: &'a mut W, } impl<'a> WRP1B_PSTRT_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 & !0x7f) | ((value as u32) & 0x7f); self.w } } #[doc = "Reader of field `WRP1B_PEND`"] pub type WRP1B_PEND_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WRP1B_PEND`"] pub struct WRP1B_PEND_W<'a> { w: &'a mut W, } impl<'a> WRP1B_PEND_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 & !(0x7f << 16)) | (((value as u32) & 0x7f) << 16); self.w } } impl R { #[doc = "Bits 0:6 - WRP1B_PSTRT"] #[inline(always)] pub fn wrp1b_pstrt(&self) -> WRP1B_PSTRT_R { WRP1B_PSTRT_R::new((self.bits & 0x7f) as u8) } #[doc = "Bits 16:22 - WRP1B_PEND"] #[inline(always)] pub fn wrp1b_pend(&self) -> WRP1B_PEND_R { WRP1B_PEND_R::new(((self.bits >> 16) & 0x7f) as u8) } } impl W { #[doc = "Bits 0:6 - WRP1B_PSTRT"] #[inline(always)] pub fn wrp1b_pstrt(&mut self) -> WRP1B_PSTRT_W { WRP1B_PSTRT_W { w: self } } #[doc = "Bits 16:22 - WRP1B_PEND"] #[inline(always)] pub fn wrp1b_pend(&mut self) -> WRP1B_PEND_W { WRP1B_PEND_W { w: self } } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::string::String; use alloc::sync::Arc; use spin::Mutex; use alloc::collections::btree_map::BTreeMap; use alloc::string::ToString; use alloc::vec::Vec; use super::super::super::qlib::common::*; use super::super::super::qlib::path::*; use super::super::super::qlib::linux_def::*; use super::super::super::task::*; use super::super::inode::*; use super::super::mount::*; use super::util::*; use super::super::filesystems::*; pub const MAX_TRAVERSALS: u32 = 10; pub const FILESYSTEM_NAME: &str = "whitelistfs"; pub const WHITELIST_KEY: &str = "whitelist"; pub const ROOT_PATH_KEY: &str = "root"; pub const DONT_TRANSLATE_OWNERSHIP_KEY: &str = "dont_translate_ownership"; pub struct WhitelistFileSystem { pub paths: Vec<String>, } impl WhitelistFileSystem { pub fn New() -> Self { return Self { paths: Vec::new(), } } pub fn GenericMountSourceOptions(data: &str) -> BTreeMap<String, String> { let mut options = BTreeMap::new(); if data.len() == 0 { return options; } let v: Vec<&str> = data.split(',').collect(); for opt in v { if opt.len() > 0 { let res: Vec<&str> = opt.split('=').collect(); if res.len() == 2 { options.insert(res[0].to_string(), res[1].to_string()); } else { options.insert(opt.to_string(), "".to_string()); } } } return options; } pub fn InstallWhitelist(&self, task: &Task, m: &MountNs) -> Result<()> { InstallWhitelist(task, m, &self.paths) } } pub fn InstallWhitelist(task: &Task, m: &MountNs, inputPaths: &Vec<String>) -> Result<()> { if inputPaths.len() == 0 || (inputPaths.len() == 1 && inputPaths[0].as_str() == "") { return Ok(()) } let mut done = BTreeMap::new(); let root = m.Root(); let mut paths = Vec::new(); for p in inputPaths { paths.push(p.clone()) } let mut i = 0; while i < paths.len() { let p = paths[i].clone(); i += 1; if !IsAbs(&p) { return Err(Error::Common("InstallWhitelist: path should not absoluted".to_string())) } let s = p.as_bytes(); for j in 1..s.len() + 1 { if j < s.len() && s[j] != '/' as u8 { continue; } let current = String::from_utf8(s[..j].to_vec()).unwrap(); let mut remainingTraversals = MAX_TRAVERSALS; let d = m.FindLink(task, &root, None, &current, &mut remainingTraversals); let dir = match d { Err(e) => { info!("populate failed for {}, {:?}", current, e); continue; } Ok(d) => d, }; if current == p { let inode = dir.Inode(); let sattr = inode.lock().StableAttr().clone(); if sattr.IsDir() { for (name, _) in dir.ChildDenAttrs(task)? { paths.push(Join(&current, &name)) } } if sattr.IsSymlink() { match done.get(&current) { None => continue, Some(_) => (), } let s = match inode.ReadLink(task) { Err(_) => continue, Ok(s) => s, }; if IsAbs(&s) { paths.push(s) } else { let target = Join(&Dir(&current), &s); paths.push(target); } } } if !done.contains_key(&current) { done.insert(current, dir.clone()); } } } m.Freeze(); return Ok(()) } impl Filesystem for WhitelistFileSystem { fn Name(&self) -> String { return FILESYSTEM_NAME.to_string(); } fn Flags(&self) -> FilesystemFlags { return 0; } fn Mount(&mut self, task: &Task, _device: &str, flags: &MountSourceFlags, data: &str) -> Result<Inode> { let mut options = Self::GenericMountSourceOptions(data); let remove = if let Some(ref wl) = options.get(&WHITELIST_KEY.to_string()) { let v: Vec<&str> = wl.split('|').collect(); self.paths = v.iter().map(|x| x.to_string()).collect(); true } else { false }; if remove { options.remove(&WHITELIST_KEY.to_string()); } let mut rootPath = "/".to_string(); let remove = if let Some(rp) = options.get(&ROOT_PATH_KEY.to_string()) { rootPath = rp.clone(); for i in 0..self.paths.len() { let p = &self.paths[i]; let rel = Rel(&rootPath, p)?; self.paths[i] = Join(&"/".to_string(), &rel); } true } else { false }; if remove { options.remove(&ROOT_PATH_KEY.to_string()); } let (fd, writable, _) = TryOpenAt(-100, &rootPath)?; if fd < 0 { return Err(Error::SysError(-fd)) } let mut dontTranslateOwnership = false; let remove = if let Some(ref v) = options.get(&DONT_TRANSLATE_OWNERSHIP_KEY.to_string()) { let b = ParseBool(v)?; dontTranslateOwnership = b; true } else { false }; if remove { options.remove(&DONT_TRANSLATE_OWNERSHIP_KEY.to_string()); } if options.len() > 0 { return Err(Error::Common("unsupported mount options".to_string())) } let owner = task.Creds().FileOwner(); let msrc = MountSource::NewHostMountSource(&rootPath, &owner, self, flags, dontTranslateOwnership); let mut fstat = LibcStat::default(); let ret = Fstat(fd, &mut fstat); if ret < 0 { return Err(Error::SysError(-ret as i32)); } let inode = Inode::NewHostInode(&Arc::new(Mutex::new(msrc)), fd, &fstat, writable)?; return Ok(inode) } fn AllowUserMount(&self) -> bool { return false } fn AllowUserList(&self) -> bool { return true; } }
pub mod size; pub use size::*;
//! Add a bonus to the comment line or the line that can have a declaration. //! //! Ref: https://github.com/jacktasia/dumb-jump/blob/master/dumb-jump.el use crate::Score; pub type FileExtension = String; #[derive(Debug, Clone)] pub struct Language(FileExtension); impl<T: AsRef<str>> From<T> for Language { fn from(s: T) -> Self { Self(s.as_ref().into()) } } impl Language { pub fn calc_bonus(&self, bonus_text: &str, base_score: Score) -> Score { let trimmed = bonus_text.trim_start(); if dumb_analyzer::is_comment(trimmed, &self.0) { -(base_score / 5) } else { match dumb_analyzer::calculate_pattern_priority(trimmed, &self.0) { Some(priority) => base_score / priority.as_i32(), None => 0, } } } }
use super::*; #[test] fn testing_the_scaling() { let mut miniworld = World::new(); let some_entity = miniworld .spawn() .insert_bundle(( HerdSize::new_single_population(100), Susceptible(22), Infected(2), Recovered(14), )) .id(); let mut scaling_stage = SystemStage::single(repopulate_rescale_disease_compartments.system()); // dbg!(miniworld.get::<HerdSize>(some_entity)); // dbg!(miniworld.get::<Susceptible>(some_entity)); // dbg!(miniworld.get::<Infected>(some_entity)); // dbg!(miniworld.get::<Recovered>(some_entity)); scaling_stage.run(&mut miniworld); // dbg!(miniworld.components()); dbg!(miniworld.get::<HerdSize>(some_entity).map(|x| x.0).unwrap()); dbg!(miniworld .get::<Susceptible>(some_entity) .map(|x| x.0) .unwrap()); dbg!(miniworld.get::<Infected>(some_entity).map(|x| x.0).unwrap()); dbg!(miniworld .get::<Recovered>(some_entity) .map(|x| x.0) .unwrap()); }
pub struct UniverseMap {}
use super::*; use std::cell::Cell; #[allow(clippy::redundant_allocation)] fn _covariant_arc<'a: 'b, 'b, T>(foo: Arc<&'a T>) -> Arc<&'b T> { foo } fn _covariant_rarc<'a: 'b, 'b, T>(foo: RArc<&'a T>) -> RArc<&'b T> { foo } #[test] fn test_covariance() { struct F<T>(T); fn eq<'a, 'b, T>(left: &RArc<&'a T>, right: &RArc<&'b T>) -> bool where T: PartialEq, { left == right } let aaa = F(3); let bbb = F(5); let v0 = RArc::new(&aaa.0); let v1 = RArc::new(&bbb.0); assert!(!eq(&v0, &v1)); } fn refaddr<T>(ref_: &T) -> usize { ref_ as *const T as usize } #[test] fn to_from_arc() { let orig_a = Arc::new(1000); let a_addr = (&*orig_a) as *const _ as usize; let mut reprc_a = orig_a.clone().piped(RArc::from); assert_eq!(a_addr, refaddr(&*reprc_a)); assert_eq!(a_addr, reprc_a.clone().piped(|a| refaddr(&*a))); assert_eq!( a_addr, reprc_a .clone() .piped(RArc::into_arc) .piped(|a| refaddr(&*a)) ); reprc_a.set_vtable_for_testing(); assert_eq!(a_addr, refaddr(&*reprc_a)); assert_eq!(Arc::strong_count(&orig_a), 2); let back_to_a = reprc_a.piped(RArc::into_arc); assert_eq!(Arc::strong_count(&orig_a), 1); assert_ne!(a_addr, refaddr(&*back_to_a)); drop(back_to_a); assert_eq!(Arc::strong_count(&orig_a), 1); } // testing that Arc<()> is valid #[allow(clippy::unit_cmp)] #[test] fn default() { assert_eq!(*RArc::<String>::default(), ""); assert_eq!(*RArc::<()>::default(), ()); assert_eq!(*RArc::<u32>::default(), 0); assert_eq!(*RArc::<bool>::default(), false); } #[test] fn new_test() { for elem in 0..100 { assert_eq!(*RArc::new(elem), elem); } } #[test] fn into_raw() { let orig_a = Arc::new(200); let reprc_a = orig_a.clone().piped(RArc::from); let raw_a = reprc_a.into_raw(); assert_eq!(Arc::strong_count(&orig_a), 2); unsafe { Arc::from_raw(raw_a); } assert_eq!(Arc::strong_count(&orig_a), 1); } #[test] fn get_mut() { let mut conv = Arc::new(200).piped(RArc::from); { let _conv_clone = conv.clone(); assert_eq!(RArc::get_mut(&mut conv), None); } assert_eq!(RArc::get_mut(&mut conv), Some(&mut 200)); } #[test] fn make_mut() { let count = Cell::new(1); let dod = DecrementOnDrop(&count); let mut arc = Arc::new(ValueAndDod { value: 'a', _dod: dod.clone(), }) .piped(RArc::from); { assert_eq!(dod.count(), 2); let arc_clone = arc.clone(); let mutref = RArc::make_mut(&mut arc); assert_eq!(dod.count(), 3); mutref.value = 'c'; assert_eq!(arc_clone.value, 'a'); } assert_eq!(dod.count(), 2); assert_eq!(arc.value, 'c'); } ///////////////////////////////////////// #[derive(Clone)] struct ValueAndDod<'a, T> { value: T, _dod: DecrementOnDrop<'a>, } ///////////////////////////////////////// struct DecrementOnDrop<'a>(&'a Cell<u32>); impl<'a> DecrementOnDrop<'a> { fn count(&self) -> u32 { self.0.get() } } impl<'a> Clone for DecrementOnDrop<'a> { fn clone(&self) -> Self { self.0.set(self.0.get() + 1); DecrementOnDrop(self.0) } } impl<'a> Drop for DecrementOnDrop<'a> { fn drop(&mut self) { self.0.set(self.0.get() - 1); } }
//works but still a bit slow (around 40s) use projecteuler::digits; use projecteuler::primes; const SET_SIZE: usize = 5; fn main() { dbg!(digits::concat_numbers(1234, 5678)); let mut prime_generator = primes::primes_iterator() .filter(|x| match x { primes::PrimeOrFactor::Prime(_) => true, _ => false, }) .map(|x| match x { primes::PrimeOrFactor::Prime(p) => p, _ => unreachable!(), }); //drop the 2,3, and 5 //2 and 5 cannot be in a bigger prime pair set. prime_generator.next(); prime_generator.next(); prime_generator.next(); //remeber the 3 let mut prime_sets = (PrimePairTree::new(), PrimePairTree::new()); prime_sets.0.add(3); prime_sets.1.add(3); let mut smallest_sum = None; for p in prime_generator { if smallest_sum.is_some() && smallest_sum.unwrap() < p { break; } //dbg!(&prime_sets); let prime_sets = if digits::digit_sum(p) % 3 == 1 { &mut prime_sets.0 } else { &mut prime_sets.1 }; if let Some(sum) = prime_sets.add(p) { dbg!(sum); if smallest_sum.is_none() || smallest_sum.unwrap() > sum { smallest_sum = Some(sum); } } } dbg!(smallest_sum); } fn is_prime_pair(n: usize, m: usize) -> bool { primes::is_prime(digits::concat_numbers(n, m)) && primes::is_prime(digits::concat_numbers(m, n)) } struct PrimePairTree { primes: Vec<usize>, children: Vec<PrimePairTreeNode>, } struct PrimePairTreeNode { //index into prime_tree.primes prime_ind: usize, children: Vec<PrimePairTreeNode>, } impl PrimePairTree { fn new() -> Self { Self { primes: vec![], children: vec![], } } fn add(&mut self, p: usize) -> Option<usize> { //compute with which primes the new one forms a pair let pairs: Vec<bool> = self .primes .iter() .map(|old_p| is_prime_pair(*old_p, p)) .collect(); //special case the root node self.primes.push(p); let mut stack = vec![]; let mut ret = 0; for child in &mut self.children { if let Some(sum) = child.add(p, &pairs, &self.primes, &mut stack) { if ret == 0 || ret > sum { ret = sum; } } } self.children .push(PrimePairTreeNode::new(self.primes.len() - 1)); if ret != 0 { Some(ret) } else { None } } } impl PrimePairTreeNode { fn new(prime_ind: usize) -> Self { Self { prime_ind: prime_ind, children: vec![], } } fn add( &mut self, p: usize, pairs: &[bool], primes: &[usize], stack: &mut Vec<usize>, ) -> Option<usize> { if !pairs[self.prime_ind] { return None; } stack.push(primes[self.prime_ind]); //its a pair let mut ret = 0; for child in &mut self.children { if let Some(sum) = child.add(p, pairs, primes, stack) { if ret == 0 || ret > sum { ret = sum; } } } if stack.len() == SET_SIZE - 1 { let sum = stack.iter().sum::<usize>() + p; if ret == 0 || ret > sum { ret = sum; } } stack.pop(); self.children.push(PrimePairTreeNode::new(primes.len() - 1)); if ret != 0 { Some(ret) } else { None } } }
// revisions: base nll // ignore-compare-mode-nll //[nll] compile-flags: -Z borrowck=mir fn static_id<'a,'b>(t: &'a ()) -> &'static () where 'a: 'static { t } //~^ WARN unnecessary lifetime parameter `'a` fn static_id_indirect<'a,'b>(t: &'a ()) -> &'static () where 'a: 'b, 'b: 'static { t } //~^ WARN unnecessary lifetime parameter `'b` fn static_id_wrong_way<'a>(t: &'a ()) -> &'static () where 'static: 'a { t //[base]~^ ERROR E0312 //[nll]~^^ ERROR lifetime may not live long enough } fn error(u: &(), v: &()) { static_id(&u); //[base]~^ ERROR `u` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement [E0759] //[nll]~^^ ERROR borrowed data escapes outside of function [E0521] static_id_indirect(&v); //[base]~^ ERROR `v` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement [E0759] //[nll]~^^ ERROR borrowed data escapes outside of function [E0521] } fn main() {}