text
stringlengths
8
4.13M
#[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::STAT { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = "Possible values of the field `MSTPENDING`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSTPENDINGR { #[doc = "No service needed. The Master function does not currently need service."] NO_SERVICE_NEEDED_T, #[doc = "Service needed. The Master function needs service. Information on what is needed can be found in the adjacent MSTSTATE field."] SERVICE_NEEDED_THE_, } impl MSTPENDINGR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { MSTPENDINGR::NO_SERVICE_NEEDED_T => false, MSTPENDINGR::SERVICE_NEEDED_THE_ => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> MSTPENDINGR { match value { false => MSTPENDINGR::NO_SERVICE_NEEDED_T, true => MSTPENDINGR::SERVICE_NEEDED_THE_, } } #[doc = "Checks if the value of the field is `NO_SERVICE_NEEDED_T`"] #[inline] pub fn is_no_service_needed_t(&self) -> bool { *self == MSTPENDINGR::NO_SERVICE_NEEDED_T } #[doc = "Checks if the value of the field is `SERVICE_NEEDED_THE_`"] #[inline] pub fn is_service_needed_the_(&self) -> bool { *self == MSTPENDINGR::SERVICE_NEEDED_THE_ } } #[doc = "Possible values of the field `MSTSTATE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSTSTATER { #[doc = "Idle. The Master function is available to be used for a new transaction."] IDLE_THE_MASTER_FUN, #[doc = "Receive ready. Received data available (Master Receiver mode). Address plus Read was previously sent and Acknowledged by slave."] RECEIVE_READY_RECEI, #[doc = "Transmit ready. Data can be transmitted (Master Transmitter mode). Address plus Write was previously sent and Acknowledged by slave."] TRANSMIT_READY_DATA, #[doc = "Address. Slave Nacked address."] ADDRESS_SLAVE_NACKE, #[doc = "Data. Slave Nacked transmitted data."] DATA_SLAVE_NACKED_T, #[doc = r" Reserved"] _Reserved(u8), } impl MSTSTATER { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { MSTSTATER::IDLE_THE_MASTER_FUN => 0, MSTSTATER::RECEIVE_READY_RECEI => 1, MSTSTATER::TRANSMIT_READY_DATA => 2, MSTSTATER::ADDRESS_SLAVE_NACKE => 3, MSTSTATER::DATA_SLAVE_NACKED_T => 4, MSTSTATER::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> MSTSTATER { match value { 0 => MSTSTATER::IDLE_THE_MASTER_FUN, 1 => MSTSTATER::RECEIVE_READY_RECEI, 2 => MSTSTATER::TRANSMIT_READY_DATA, 3 => MSTSTATER::ADDRESS_SLAVE_NACKE, 4 => MSTSTATER::DATA_SLAVE_NACKED_T, i => MSTSTATER::_Reserved(i), } } #[doc = "Checks if the value of the field is `IDLE_THE_MASTER_FUN`"] #[inline] pub fn is_idle_the_master_fun(&self) -> bool { *self == MSTSTATER::IDLE_THE_MASTER_FUN } #[doc = "Checks if the value of the field is `RECEIVE_READY_RECEI`"] #[inline] pub fn is_receive_ready_recei(&self) -> bool { *self == MSTSTATER::RECEIVE_READY_RECEI } #[doc = "Checks if the value of the field is `TRANSMIT_READY_DATA`"] #[inline] pub fn is_transmit_ready_data(&self) -> bool { *self == MSTSTATER::TRANSMIT_READY_DATA } #[doc = "Checks if the value of the field is `ADDRESS_SLAVE_NACKE`"] #[inline] pub fn is_address_slave_nacke(&self) -> bool { *self == MSTSTATER::ADDRESS_SLAVE_NACKE } #[doc = "Checks if the value of the field is `DATA_SLAVE_NACKED_T`"] #[inline] pub fn is_data_slave_nacked_t(&self) -> bool { *self == MSTSTATER::DATA_SLAVE_NACKED_T } } #[doc = "Possible values of the field `MSTARBLOSS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSTARBLOSSR { #[doc = "No loss. No Arbitration Loss has occurred."] NO_LOSS_NO_ARBITRAT, #[doc = "Arbitration loss. The Master function has experienced an Arbitration Loss. At this point, the Master function has already stopped driving the bus and gone to an idle state. Software can respond by doing nothing, or by sending a Start in order to attempt to gain control of the bus when it next becomes idle."] ARBITRATION_LOSS_TH, } impl MSTARBLOSSR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { MSTARBLOSSR::NO_LOSS_NO_ARBITRAT => false, MSTARBLOSSR::ARBITRATION_LOSS_TH => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> MSTARBLOSSR { match value { false => MSTARBLOSSR::NO_LOSS_NO_ARBITRAT, true => MSTARBLOSSR::ARBITRATION_LOSS_TH, } } #[doc = "Checks if the value of the field is `NO_LOSS_NO_ARBITRAT`"] #[inline] pub fn is_no_loss_no_arbitrat(&self) -> bool { *self == MSTARBLOSSR::NO_LOSS_NO_ARBITRAT } #[doc = "Checks if the value of the field is `ARBITRATION_LOSS_TH`"] #[inline] pub fn is_arbitration_loss_th(&self) -> bool { *self == MSTARBLOSSR::ARBITRATION_LOSS_TH } } #[doc = "Possible values of the field `MSTSTSTPERR`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSTSTSTPERRR { #[doc = "No Start/Stop Error has occurred."] NO_STARTSTOP_ERROR_, #[doc = "Start/stop error has occurred. The Master function has experienced a Start/Stop Error. A Start or Stop was detected at a time when it is not allowed by the I2C specification. The Master interface has stopped driving the bus and gone to an idle state, no action is required. A request for a Start could be made, or software could attempt to insure that the bus has not stalled."] STARTSTOP_ERROR_HAS, } impl MSTSTSTPERRR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { MSTSTSTPERRR::NO_STARTSTOP_ERROR_ => false, MSTSTSTPERRR::STARTSTOP_ERROR_HAS => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> MSTSTSTPERRR { match value { false => MSTSTSTPERRR::NO_STARTSTOP_ERROR_, true => MSTSTSTPERRR::STARTSTOP_ERROR_HAS, } } #[doc = "Checks if the value of the field is `NO_STARTSTOP_ERROR_`"] #[inline] pub fn is_no_startstop_error_(&self) -> bool { *self == MSTSTSTPERRR::NO_STARTSTOP_ERROR_ } #[doc = "Checks if the value of the field is `STARTSTOP_ERROR_HAS`"] #[inline] pub fn is_startstop_error_has(&self) -> bool { *self == MSTSTSTPERRR::STARTSTOP_ERROR_HAS } } #[doc = "Possible values of the field `SLVPENDING`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SLVPENDINGR { #[doc = "No service needed. The Slave function does not currently need service."] NO_SERVICE_NEEDED_T, #[doc = "Service needed. The Slave function needs service. Information on what is needed can be found in the adjacent SLVSTATE field."] SERVICE_NEEDED_THE_, } impl SLVPENDINGR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { SLVPENDINGR::NO_SERVICE_NEEDED_T => false, SLVPENDINGR::SERVICE_NEEDED_THE_ => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SLVPENDINGR { match value { false => SLVPENDINGR::NO_SERVICE_NEEDED_T, true => SLVPENDINGR::SERVICE_NEEDED_THE_, } } #[doc = "Checks if the value of the field is `NO_SERVICE_NEEDED_T`"] #[inline] pub fn is_no_service_needed_t(&self) -> bool { *self == SLVPENDINGR::NO_SERVICE_NEEDED_T } #[doc = "Checks if the value of the field is `SERVICE_NEEDED_THE_`"] #[inline] pub fn is_service_needed_the_(&self) -> bool { *self == SLVPENDINGR::SERVICE_NEEDED_THE_ } } #[doc = "Possible values of the field `SLVSTATE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SLVSTATER { #[doc = "Received. Address plus R/W received. At least one of the four slave addresses has been matched by hardware."] RECEIVED_ADDRESS_PL, #[doc = "Data available. Received data is available (Slave Receiver mode)."] DATA_AVAILABLE_RECE, #[doc = "Data ready for transmit. Data can be transmitted (Slave Transmitter mode)."] DATA_READY_FOR_TRANS, #[doc = "Reserved."] RESERVED_, } impl SLVSTATER { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { SLVSTATER::RECEIVED_ADDRESS_PL => 0, SLVSTATER::DATA_AVAILABLE_RECE => 1, SLVSTATER::DATA_READY_FOR_TRANS => 2, SLVSTATER::RESERVED_ => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> SLVSTATER { match value { 0 => SLVSTATER::RECEIVED_ADDRESS_PL, 1 => SLVSTATER::DATA_AVAILABLE_RECE, 2 => SLVSTATER::DATA_READY_FOR_TRANS, 3 => SLVSTATER::RESERVED_, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `RECEIVED_ADDRESS_PL`"] #[inline] pub fn is_received_address_pl(&self) -> bool { *self == SLVSTATER::RECEIVED_ADDRESS_PL } #[doc = "Checks if the value of the field is `DATA_AVAILABLE_RECE`"] #[inline] pub fn is_data_available_rece(&self) -> bool { *self == SLVSTATER::DATA_AVAILABLE_RECE } #[doc = "Checks if the value of the field is `DATA_READY_FOR_TRANS`"] #[inline] pub fn is_data_ready_for_trans(&self) -> bool { *self == SLVSTATER::DATA_READY_FOR_TRANS } #[doc = "Checks if the value of the field is `RESERVED_`"] #[inline] pub fn is_reserved_(&self) -> bool { *self == SLVSTATER::RESERVED_ } } #[doc = "Possible values of the field `SLVNOTSTR`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SLVNOTSTRR { #[doc = "Stretching. The slave function is currently stretching the I2C bus clock. Deep-Sleep or Power-down mode cannot be entered at this time."] STRETCHING_THE_SLAV, #[doc = "Not stretching. The slave function is not currently stretching the I 2C bus clock. Deep-sleep or Power-down mode could be entered at this time."] NOT_STRETCHING_THE_, } impl SLVNOTSTRR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { SLVNOTSTRR::STRETCHING_THE_SLAV => false, SLVNOTSTRR::NOT_STRETCHING_THE_ => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SLVNOTSTRR { match value { false => SLVNOTSTRR::STRETCHING_THE_SLAV, true => SLVNOTSTRR::NOT_STRETCHING_THE_, } } #[doc = "Checks if the value of the field is `STRETCHING_THE_SLAV`"] #[inline] pub fn is_stretching_the_slav(&self) -> bool { *self == SLVNOTSTRR::STRETCHING_THE_SLAV } #[doc = "Checks if the value of the field is `NOT_STRETCHING_THE_`"] #[inline] pub fn is_not_stretching_the_(&self) -> bool { *self == SLVNOTSTRR::NOT_STRETCHING_THE_ } } #[doc = "Possible values of the field `SLVIDX`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SLVIDXR { #[doc = "Slave address 0 was matched."] SLAVE_ADDRESS_0_WAS_, #[doc = "Slave address 1 was matched."] SLAVE_ADDRESS_1_WAS_, #[doc = "Slave address 2 was matched."] SLAVE_ADDRESS_2_WAS_, #[doc = "Slave address 3 was matched."] SLAVE_ADDRESS_3_WAS_, } impl SLVIDXR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { SLVIDXR::SLAVE_ADDRESS_0_WAS_ => 0, SLVIDXR::SLAVE_ADDRESS_1_WAS_ => 1, SLVIDXR::SLAVE_ADDRESS_2_WAS_ => 2, SLVIDXR::SLAVE_ADDRESS_3_WAS_ => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> SLVIDXR { match value { 0 => SLVIDXR::SLAVE_ADDRESS_0_WAS_, 1 => SLVIDXR::SLAVE_ADDRESS_1_WAS_, 2 => SLVIDXR::SLAVE_ADDRESS_2_WAS_, 3 => SLVIDXR::SLAVE_ADDRESS_3_WAS_, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `SLAVE_ADDRESS_0_WAS_`"] #[inline] pub fn is_slave_address_0_was_(&self) -> bool { *self == SLVIDXR::SLAVE_ADDRESS_0_WAS_ } #[doc = "Checks if the value of the field is `SLAVE_ADDRESS_1_WAS_`"] #[inline] pub fn is_slave_address_1_was_(&self) -> bool { *self == SLVIDXR::SLAVE_ADDRESS_1_WAS_ } #[doc = "Checks if the value of the field is `SLAVE_ADDRESS_2_WAS_`"] #[inline] pub fn is_slave_address_2_was_(&self) -> bool { *self == SLVIDXR::SLAVE_ADDRESS_2_WAS_ } #[doc = "Checks if the value of the field is `SLAVE_ADDRESS_3_WAS_`"] #[inline] pub fn is_slave_address_3_was_(&self) -> bool { *self == SLVIDXR::SLAVE_ADDRESS_3_WAS_ } } #[doc = "Possible values of the field `SLVSEL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SLVSELR { #[doc = "Not selected. The Slave function is not currently selected."] NOT_SELECTED_THE_SL, #[doc = "Selected. The Slave function is currently selected."] SELECTED_THE_SLAVE_, } impl SLVSELR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { SLVSELR::NOT_SELECTED_THE_SL => false, SLVSELR::SELECTED_THE_SLAVE_ => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SLVSELR { match value { false => SLVSELR::NOT_SELECTED_THE_SL, true => SLVSELR::SELECTED_THE_SLAVE_, } } #[doc = "Checks if the value of the field is `NOT_SELECTED_THE_SL`"] #[inline] pub fn is_not_selected_the_sl(&self) -> bool { *self == SLVSELR::NOT_SELECTED_THE_SL } #[doc = "Checks if the value of the field is `SELECTED_THE_SLAVE_`"] #[inline] pub fn is_selected_the_slave_(&self) -> bool { *self == SLVSELR::SELECTED_THE_SLAVE_ } } #[doc = "Possible values of the field `SLVDESEL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SLVDESELR { #[doc = "Not deselected. The Slave function has not become deselected. This does not mean that it is currently selected. That information can be found in the SLVSEL flag."] NOT_DESELECTED_THE_, #[doc = "Deselected. The Slave function has become deselected. This is specifically caused by the SLVSEL flag changing from 1 to 0. See the description of SLVSEL for details on when that event occurs."] DESELECTED_THE_SLAV, } impl SLVDESELR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { SLVDESELR::NOT_DESELECTED_THE_ => false, SLVDESELR::DESELECTED_THE_SLAV => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SLVDESELR { match value { false => SLVDESELR::NOT_DESELECTED_THE_, true => SLVDESELR::DESELECTED_THE_SLAV, } } #[doc = "Checks if the value of the field is `NOT_DESELECTED_THE_`"] #[inline] pub fn is_not_deselected_the_(&self) -> bool { *self == SLVDESELR::NOT_DESELECTED_THE_ } #[doc = "Checks if the value of the field is `DESELECTED_THE_SLAV`"] #[inline] pub fn is_deselected_the_slav(&self) -> bool { *self == SLVDESELR::DESELECTED_THE_SLAV } } #[doc = "Possible values of the field `MONRDY`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MONRDYR { #[doc = "No data. The Monitor function does not currently have data available."] NO_DATA_THE_MONITOR, #[doc = "Data waiting. The Monitor function has data waiting to be read."] DATA_WAITING_THE_MO, } impl MONRDYR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { MONRDYR::NO_DATA_THE_MONITOR => false, MONRDYR::DATA_WAITING_THE_MO => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> MONRDYR { match value { false => MONRDYR::NO_DATA_THE_MONITOR, true => MONRDYR::DATA_WAITING_THE_MO, } } #[doc = "Checks if the value of the field is `NO_DATA_THE_MONITOR`"] #[inline] pub fn is_no_data_the_monitor(&self) -> bool { *self == MONRDYR::NO_DATA_THE_MONITOR } #[doc = "Checks if the value of the field is `DATA_WAITING_THE_MO`"] #[inline] pub fn is_data_waiting_the_mo(&self) -> bool { *self == MONRDYR::DATA_WAITING_THE_MO } } #[doc = "Possible values of the field `MONOV`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MONOVR { #[doc = "No overrun. Monitor data has not overrun."] NO_OVERRUN_MONITOR_, #[doc = "Overrun. A Monitor data overrun has occurred. This can only happen when Monitor clock stretching not enabled via the MONCLKSTR bit in the CFG register. Writing 1 to this bit clears the flag."] OVERRUN_A_MONITOR_D, } impl MONOVR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { MONOVR::NO_OVERRUN_MONITOR_ => false, MONOVR::OVERRUN_A_MONITOR_D => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> MONOVR { match value { false => MONOVR::NO_OVERRUN_MONITOR_, true => MONOVR::OVERRUN_A_MONITOR_D, } } #[doc = "Checks if the value of the field is `NO_OVERRUN_MONITOR_`"] #[inline] pub fn is_no_overrun_monitor_(&self) -> bool { *self == MONOVR::NO_OVERRUN_MONITOR_ } #[doc = "Checks if the value of the field is `OVERRUN_A_MONITOR_D`"] #[inline] pub fn is_overrun_a_monitor_d(&self) -> bool { *self == MONOVR::OVERRUN_A_MONITOR_D } } #[doc = "Possible values of the field `MONACTIVE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MONACTIVER { #[doc = "Inactive. The Monitor function considers the I2C bus to be inactive."] INACTIVE_THE_MONITO, #[doc = "Active. The Monitor function considers the I2C bus to be active."] ACTIVE_THE_MONITOR_, } impl MONACTIVER { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { MONACTIVER::INACTIVE_THE_MONITO => false, MONACTIVER::ACTIVE_THE_MONITOR_ => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> MONACTIVER { match value { false => MONACTIVER::INACTIVE_THE_MONITO, true => MONACTIVER::ACTIVE_THE_MONITOR_, } } #[doc = "Checks if the value of the field is `INACTIVE_THE_MONITO`"] #[inline] pub fn is_inactive_the_monito(&self) -> bool { *self == MONACTIVER::INACTIVE_THE_MONITO } #[doc = "Checks if the value of the field is `ACTIVE_THE_MONITOR_`"] #[inline] pub fn is_active_the_monitor_(&self) -> bool { *self == MONACTIVER::ACTIVE_THE_MONITOR_ } } #[doc = "Possible values of the field `MONIDLE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MONIDLER { #[doc = "Not idle. The I2C bus is not idle, or this flag has been cleared by software."] NOT_IDLE_THE_I2C_BU, #[doc = "Idle. The I2C bus has gone idle at least once since the last time this flag was cleared by software."] IDLE_THE_I2C_BUS_HA, } impl MONIDLER { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { MONIDLER::NOT_IDLE_THE_I2C_BU => false, MONIDLER::IDLE_THE_I2C_BUS_HA => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> MONIDLER { match value { false => MONIDLER::NOT_IDLE_THE_I2C_BU, true => MONIDLER::IDLE_THE_I2C_BUS_HA, } } #[doc = "Checks if the value of the field is `NOT_IDLE_THE_I2C_BU`"] #[inline] pub fn is_not_idle_the_i2c_bu(&self) -> bool { *self == MONIDLER::NOT_IDLE_THE_I2C_BU } #[doc = "Checks if the value of the field is `IDLE_THE_I2C_BUS_HA`"] #[inline] pub fn is_idle_the_i2c_bus_ha(&self) -> bool { *self == MONIDLER::IDLE_THE_I2C_BUS_HA } } #[doc = "Possible values of the field `EVENTTIMEOUT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EVENTTIMEOUTR { #[doc = "No time-out. I2C bus events have not caused a timeout."] NO_TIME_OUT_I2C_BUS, #[doc = "Event time-out. The time between I2C bus events has been longer than the time specified by the I2C Timeout register."] EVENT_TIME_OUT_THE_, } impl EVENTTIMEOUTR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { EVENTTIMEOUTR::NO_TIME_OUT_I2C_BUS => false, EVENTTIMEOUTR::EVENT_TIME_OUT_THE_ => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> EVENTTIMEOUTR { match value { false => EVENTTIMEOUTR::NO_TIME_OUT_I2C_BUS, true => EVENTTIMEOUTR::EVENT_TIME_OUT_THE_, } } #[doc = "Checks if the value of the field is `NO_TIME_OUT_I2C_BUS`"] #[inline] pub fn is_no_time_out_i2c_bus(&self) -> bool { *self == EVENTTIMEOUTR::NO_TIME_OUT_I2C_BUS } #[doc = "Checks if the value of the field is `EVENT_TIME_OUT_THE_`"] #[inline] pub fn is_event_time_out_the_(&self) -> bool { *self == EVENTTIMEOUTR::EVENT_TIME_OUT_THE_ } } #[doc = "Possible values of the field `SCLTIMEOUT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SCLTIMEOUTR { #[doc = "No time-out. SCL low time has not caused a timeout."] NO_TIME_OUT_SCL_LOW, #[doc = "Time-out. SCL low time has caused a timeout."] TIME_OUT_SCL_LOW_TI, } impl SCLTIMEOUTR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { SCLTIMEOUTR::NO_TIME_OUT_SCL_LOW => false, SCLTIMEOUTR::TIME_OUT_SCL_LOW_TI => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SCLTIMEOUTR { match value { false => SCLTIMEOUTR::NO_TIME_OUT_SCL_LOW, true => SCLTIMEOUTR::TIME_OUT_SCL_LOW_TI, } } #[doc = "Checks if the value of the field is `NO_TIME_OUT_SCL_LOW`"] #[inline] pub fn is_no_time_out_scl_low(&self) -> bool { *self == SCLTIMEOUTR::NO_TIME_OUT_SCL_LOW } #[doc = "Checks if the value of the field is `TIME_OUT_SCL_LOW_TI`"] #[inline] pub fn is_time_out_scl_low_ti(&self) -> bool { *self == SCLTIMEOUTR::TIME_OUT_SCL_LOW_TI } } #[doc = "Values that can be written to the field `MSTPENDING`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSTPENDINGW { #[doc = "No service needed. The Master function does not currently need service."] NO_SERVICE_NEEDED_T, #[doc = "Service needed. The Master function needs service. Information on what is needed can be found in the adjacent MSTSTATE field."] SERVICE_NEEDED_THE_, } impl MSTPENDINGW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { MSTPENDINGW::NO_SERVICE_NEEDED_T => false, MSTPENDINGW::SERVICE_NEEDED_THE_ => true, } } } #[doc = r" Proxy"] pub struct _MSTPENDINGW<'a> { w: &'a mut W, } impl<'a> _MSTPENDINGW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: MSTPENDINGW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No service needed. The Master function does not currently need service."] #[inline] pub fn no_service_needed_t(self) -> &'a mut W { self.variant(MSTPENDINGW::NO_SERVICE_NEEDED_T) } #[doc = "Service needed. The Master function needs service. Information on what is needed can be found in the adjacent MSTSTATE field."] #[inline] pub fn service_needed_the_(self) -> &'a mut W { self.variant(MSTPENDINGW::SERVICE_NEEDED_THE_) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `MSTSTATE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSTSTATEW { #[doc = "Idle. The Master function is available to be used for a new transaction."] IDLE_THE_MASTER_FUN, #[doc = "Receive ready. Received data available (Master Receiver mode). Address plus Read was previously sent and Acknowledged by slave."] RECEIVE_READY_RECEI, #[doc = "Transmit ready. Data can be transmitted (Master Transmitter mode). Address plus Write was previously sent and Acknowledged by slave."] TRANSMIT_READY_DATA, #[doc = "Address. Slave Nacked address."] ADDRESS_SLAVE_NACKE, #[doc = "Data. Slave Nacked transmitted data."] DATA_SLAVE_NACKED_T, } impl MSTSTATEW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { MSTSTATEW::IDLE_THE_MASTER_FUN => 0, MSTSTATEW::RECEIVE_READY_RECEI => 1, MSTSTATEW::TRANSMIT_READY_DATA => 2, MSTSTATEW::ADDRESS_SLAVE_NACKE => 3, MSTSTATEW::DATA_SLAVE_NACKED_T => 4, } } } #[doc = r" Proxy"] pub struct _MSTSTATEW<'a> { w: &'a mut W, } impl<'a> _MSTSTATEW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: MSTSTATEW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Idle. The Master function is available to be used for a new transaction."] #[inline] pub fn idle_the_master_fun(self) -> &'a mut W { self.variant(MSTSTATEW::IDLE_THE_MASTER_FUN) } #[doc = "Receive ready. Received data available (Master Receiver mode). Address plus Read was previously sent and Acknowledged by slave."] #[inline] pub fn receive_ready_recei(self) -> &'a mut W { self.variant(MSTSTATEW::RECEIVE_READY_RECEI) } #[doc = "Transmit ready. Data can be transmitted (Master Transmitter mode). Address plus Write was previously sent and Acknowledged by slave."] #[inline] pub fn transmit_ready_data(self) -> &'a mut W { self.variant(MSTSTATEW::TRANSMIT_READY_DATA) } #[doc = "Address. Slave Nacked address."] #[inline] pub fn address_slave_nacke(self) -> &'a mut W { self.variant(MSTSTATEW::ADDRESS_SLAVE_NACKE) } #[doc = "Data. Slave Nacked transmitted data."] #[inline] pub fn data_slave_nacked_t(self) -> &'a mut W { self.variant(MSTSTATEW::DATA_SLAVE_NACKED_T) } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 7; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `MSTARBLOSS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSTARBLOSSW { #[doc = "No loss. No Arbitration Loss has occurred."] NO_LOSS_NO_ARBITRAT, #[doc = "Arbitration loss. The Master function has experienced an Arbitration Loss. At this point, the Master function has already stopped driving the bus and gone to an idle state. Software can respond by doing nothing, or by sending a Start in order to attempt to gain control of the bus when it next becomes idle."] ARBITRATION_LOSS_TH, } impl MSTARBLOSSW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { MSTARBLOSSW::NO_LOSS_NO_ARBITRAT => false, MSTARBLOSSW::ARBITRATION_LOSS_TH => true, } } } #[doc = r" Proxy"] pub struct _MSTARBLOSSW<'a> { w: &'a mut W, } impl<'a> _MSTARBLOSSW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: MSTARBLOSSW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No loss. No Arbitration Loss has occurred."] #[inline] pub fn no_loss_no_arbitrat(self) -> &'a mut W { self.variant(MSTARBLOSSW::NO_LOSS_NO_ARBITRAT) } #[doc = "Arbitration loss. The Master function has experienced an Arbitration Loss. At this point, the Master function has already stopped driving the bus and gone to an idle state. Software can respond by doing nothing, or by sending a Start in order to attempt to gain control of the bus when it next becomes idle."] #[inline] pub fn arbitration_loss_th(self) -> &'a mut W { self.variant(MSTARBLOSSW::ARBITRATION_LOSS_TH) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 4; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `MSTSTSTPERR`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSTSTSTPERRW { #[doc = "No Start/Stop Error has occurred."] NO_STARTSTOP_ERROR_, #[doc = "Start/stop error has occurred. The Master function has experienced a Start/Stop Error. A Start or Stop was detected at a time when it is not allowed by the I2C specification. The Master interface has stopped driving the bus and gone to an idle state, no action is required. A request for a Start could be made, or software could attempt to insure that the bus has not stalled."] STARTSTOP_ERROR_HAS, } impl MSTSTSTPERRW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { MSTSTSTPERRW::NO_STARTSTOP_ERROR_ => false, MSTSTSTPERRW::STARTSTOP_ERROR_HAS => true, } } } #[doc = r" Proxy"] pub struct _MSTSTSTPERRW<'a> { w: &'a mut W, } impl<'a> _MSTSTSTPERRW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: MSTSTSTPERRW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No Start/Stop Error has occurred."] #[inline] pub fn no_startstop_error_(self) -> &'a mut W { self.variant(MSTSTSTPERRW::NO_STARTSTOP_ERROR_) } #[doc = "Start/stop error has occurred. The Master function has experienced a Start/Stop Error. A Start or Stop was detected at a time when it is not allowed by the I2C specification. The Master interface has stopped driving the bus and gone to an idle state, no action is required. A request for a Start could be made, or software could attempt to insure that the bus has not stalled."] #[inline] pub fn startstop_error_has(self) -> &'a mut W { self.variant(MSTSTSTPERRW::STARTSTOP_ERROR_HAS) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 6; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SLVPENDING`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SLVPENDINGW { #[doc = "No service needed. The Slave function does not currently need service."] NO_SERVICE_NEEDED_T, #[doc = "Service needed. The Slave function needs service. Information on what is needed can be found in the adjacent SLVSTATE field."] SERVICE_NEEDED_THE_, } impl SLVPENDINGW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SLVPENDINGW::NO_SERVICE_NEEDED_T => false, SLVPENDINGW::SERVICE_NEEDED_THE_ => true, } } } #[doc = r" Proxy"] pub struct _SLVPENDINGW<'a> { w: &'a mut W, } impl<'a> _SLVPENDINGW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SLVPENDINGW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No service needed. The Slave function does not currently need service."] #[inline] pub fn no_service_needed_t(self) -> &'a mut W { self.variant(SLVPENDINGW::NO_SERVICE_NEEDED_T) } #[doc = "Service needed. The Slave function needs service. Information on what is needed can be found in the adjacent SLVSTATE field."] #[inline] pub fn service_needed_the_(self) -> &'a mut W { self.variant(SLVPENDINGW::SERVICE_NEEDED_THE_) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SLVSTATE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SLVSTATEW { #[doc = "Received. Address plus R/W received. At least one of the four slave addresses has been matched by hardware."] RECEIVED_ADDRESS_PL, #[doc = "Data available. Received data is available (Slave Receiver mode)."] DATA_AVAILABLE_RECE, #[doc = "Data ready for transmit. Data can be transmitted (Slave Transmitter mode)."] DATA_READY_FOR_TRANS, #[doc = "Reserved."] RESERVED_, } impl SLVSTATEW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { SLVSTATEW::RECEIVED_ADDRESS_PL => 0, SLVSTATEW::DATA_AVAILABLE_RECE => 1, SLVSTATEW::DATA_READY_FOR_TRANS => 2, SLVSTATEW::RESERVED_ => 3, } } } #[doc = r" Proxy"] pub struct _SLVSTATEW<'a> { w: &'a mut W, } impl<'a> _SLVSTATEW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SLVSTATEW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Received. Address plus R/W received. At least one of the four slave addresses has been matched by hardware."] #[inline] pub fn received_address_pl(self) -> &'a mut W { self.variant(SLVSTATEW::RECEIVED_ADDRESS_PL) } #[doc = "Data available. Received data is available (Slave Receiver mode)."] #[inline] pub fn data_available_rece(self) -> &'a mut W { self.variant(SLVSTATEW::DATA_AVAILABLE_RECE) } #[doc = "Data ready for transmit. Data can be transmitted (Slave Transmitter mode)."] #[inline] pub fn data_ready_for_trans(self) -> &'a mut W { self.variant(SLVSTATEW::DATA_READY_FOR_TRANS) } #[doc = "Reserved."] #[inline] pub fn reserved_(self) -> &'a mut W { self.variant(SLVSTATEW::RESERVED_) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 9; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SLVNOTSTR`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SLVNOTSTRW { #[doc = "Stretching. The slave function is currently stretching the I2C bus clock. Deep-Sleep or Power-down mode cannot be entered at this time."] STRETCHING_THE_SLAV, #[doc = "Not stretching. The slave function is not currently stretching the I 2C bus clock. Deep-sleep or Power-down mode could be entered at this time."] NOT_STRETCHING_THE_, } impl SLVNOTSTRW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SLVNOTSTRW::STRETCHING_THE_SLAV => false, SLVNOTSTRW::NOT_STRETCHING_THE_ => true, } } } #[doc = r" Proxy"] pub struct _SLVNOTSTRW<'a> { w: &'a mut W, } impl<'a> _SLVNOTSTRW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SLVNOTSTRW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Stretching. The slave function is currently stretching the I2C bus clock. Deep-Sleep or Power-down mode cannot be entered at this time."] #[inline] pub fn stretching_the_slav(self) -> &'a mut W { self.variant(SLVNOTSTRW::STRETCHING_THE_SLAV) } #[doc = "Not stretching. The slave function is not currently stretching the I 2C bus clock. Deep-sleep or Power-down mode could be entered at this time."] #[inline] pub fn not_stretching_the_(self) -> &'a mut W { self.variant(SLVNOTSTRW::NOT_STRETCHING_THE_) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 11; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SLVIDX`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SLVIDXW { #[doc = "Slave address 0 was matched."] SLAVE_ADDRESS_0_WAS_, #[doc = "Slave address 1 was matched."] SLAVE_ADDRESS_1_WAS_, #[doc = "Slave address 2 was matched."] SLAVE_ADDRESS_2_WAS_, #[doc = "Slave address 3 was matched."] SLAVE_ADDRESS_3_WAS_, } impl SLVIDXW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { SLVIDXW::SLAVE_ADDRESS_0_WAS_ => 0, SLVIDXW::SLAVE_ADDRESS_1_WAS_ => 1, SLVIDXW::SLAVE_ADDRESS_2_WAS_ => 2, SLVIDXW::SLAVE_ADDRESS_3_WAS_ => 3, } } } #[doc = r" Proxy"] pub struct _SLVIDXW<'a> { w: &'a mut W, } impl<'a> _SLVIDXW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SLVIDXW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Slave address 0 was matched."] #[inline] pub fn slave_address_0_was_(self) -> &'a mut W { self.variant(SLVIDXW::SLAVE_ADDRESS_0_WAS_) } #[doc = "Slave address 1 was matched."] #[inline] pub fn slave_address_1_was_(self) -> &'a mut W { self.variant(SLVIDXW::SLAVE_ADDRESS_1_WAS_) } #[doc = "Slave address 2 was matched."] #[inline] pub fn slave_address_2_was_(self) -> &'a mut W { self.variant(SLVIDXW::SLAVE_ADDRESS_2_WAS_) } #[doc = "Slave address 3 was matched."] #[inline] pub fn slave_address_3_was_(self) -> &'a mut W { self.variant(SLVIDXW::SLAVE_ADDRESS_3_WAS_) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 12; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SLVSEL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SLVSELW { #[doc = "Not selected. The Slave function is not currently selected."] NOT_SELECTED_THE_SL, #[doc = "Selected. The Slave function is currently selected."] SELECTED_THE_SLAVE_, } impl SLVSELW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SLVSELW::NOT_SELECTED_THE_SL => false, SLVSELW::SELECTED_THE_SLAVE_ => true, } } } #[doc = r" Proxy"] pub struct _SLVSELW<'a> { w: &'a mut W, } impl<'a> _SLVSELW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SLVSELW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Not selected. The Slave function is not currently selected."] #[inline] pub fn not_selected_the_sl(self) -> &'a mut W { self.variant(SLVSELW::NOT_SELECTED_THE_SL) } #[doc = "Selected. The Slave function is currently selected."] #[inline] pub fn selected_the_slave_(self) -> &'a mut W { self.variant(SLVSELW::SELECTED_THE_SLAVE_) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 14; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SLVDESEL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SLVDESELW { #[doc = "Not deselected. The Slave function has not become deselected. This does not mean that it is currently selected. That information can be found in the SLVSEL flag."] NOT_DESELECTED_THE_, #[doc = "Deselected. The Slave function has become deselected. This is specifically caused by the SLVSEL flag changing from 1 to 0. See the description of SLVSEL for details on when that event occurs."] DESELECTED_THE_SLAV, } impl SLVDESELW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SLVDESELW::NOT_DESELECTED_THE_ => false, SLVDESELW::DESELECTED_THE_SLAV => true, } } } #[doc = r" Proxy"] pub struct _SLVDESELW<'a> { w: &'a mut W, } impl<'a> _SLVDESELW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SLVDESELW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Not deselected. The Slave function has not become deselected. This does not mean that it is currently selected. That information can be found in the SLVSEL flag."] #[inline] pub fn not_deselected_the_(self) -> &'a mut W { self.variant(SLVDESELW::NOT_DESELECTED_THE_) } #[doc = "Deselected. The Slave function has become deselected. This is specifically caused by the SLVSEL flag changing from 1 to 0. See the description of SLVSEL for details on when that event occurs."] #[inline] pub fn deselected_the_slav(self) -> &'a mut W { self.variant(SLVDESELW::DESELECTED_THE_SLAV) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 15; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `MONRDY`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MONRDYW { #[doc = "No data. The Monitor function does not currently have data available."] NO_DATA_THE_MONITOR, #[doc = "Data waiting. The Monitor function has data waiting to be read."] DATA_WAITING_THE_MO, } impl MONRDYW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { MONRDYW::NO_DATA_THE_MONITOR => false, MONRDYW::DATA_WAITING_THE_MO => true, } } } #[doc = r" Proxy"] pub struct _MONRDYW<'a> { w: &'a mut W, } impl<'a> _MONRDYW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: MONRDYW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No data. The Monitor function does not currently have data available."] #[inline] pub fn no_data_the_monitor(self) -> &'a mut W { self.variant(MONRDYW::NO_DATA_THE_MONITOR) } #[doc = "Data waiting. The Monitor function has data waiting to be read."] #[inline] pub fn data_waiting_the_mo(self) -> &'a mut W { self.variant(MONRDYW::DATA_WAITING_THE_MO) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `MONOV`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MONOVW { #[doc = "No overrun. Monitor data has not overrun."] NO_OVERRUN_MONITOR_, #[doc = "Overrun. A Monitor data overrun has occurred. This can only happen when Monitor clock stretching not enabled via the MONCLKSTR bit in the CFG register. Writing 1 to this bit clears the flag."] OVERRUN_A_MONITOR_D, } impl MONOVW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { MONOVW::NO_OVERRUN_MONITOR_ => false, MONOVW::OVERRUN_A_MONITOR_D => true, } } } #[doc = r" Proxy"] pub struct _MONOVW<'a> { w: &'a mut W, } impl<'a> _MONOVW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: MONOVW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No overrun. Monitor data has not overrun."] #[inline] pub fn no_overrun_monitor_(self) -> &'a mut W { self.variant(MONOVW::NO_OVERRUN_MONITOR_) } #[doc = "Overrun. A Monitor data overrun has occurred. This can only happen when Monitor clock stretching not enabled via the MONCLKSTR bit in the CFG register. Writing 1 to this bit clears the flag."] #[inline] pub fn overrun_a_monitor_d(self) -> &'a mut W { self.variant(MONOVW::OVERRUN_A_MONITOR_D) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 17; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `MONACTIVE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MONACTIVEW { #[doc = "Inactive. The Monitor function considers the I2C bus to be inactive."] INACTIVE_THE_MONITO, #[doc = "Active. The Monitor function considers the I2C bus to be active."] ACTIVE_THE_MONITOR_, } impl MONACTIVEW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { MONACTIVEW::INACTIVE_THE_MONITO => false, MONACTIVEW::ACTIVE_THE_MONITOR_ => true, } } } #[doc = r" Proxy"] pub struct _MONACTIVEW<'a> { w: &'a mut W, } impl<'a> _MONACTIVEW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: MONACTIVEW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Inactive. The Monitor function considers the I2C bus to be inactive."] #[inline] pub fn inactive_the_monito(self) -> &'a mut W { self.variant(MONACTIVEW::INACTIVE_THE_MONITO) } #[doc = "Active. The Monitor function considers the I2C bus to be active."] #[inline] pub fn active_the_monitor_(self) -> &'a mut W { self.variant(MONACTIVEW::ACTIVE_THE_MONITOR_) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 18; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `MONIDLE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MONIDLEW { #[doc = "Not idle. The I2C bus is not idle, or this flag has been cleared by software."] NOT_IDLE_THE_I2C_BU, #[doc = "Idle. The I2C bus has gone idle at least once since the last time this flag was cleared by software."] IDLE_THE_I2C_BUS_HA, } impl MONIDLEW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { MONIDLEW::NOT_IDLE_THE_I2C_BU => false, MONIDLEW::IDLE_THE_I2C_BUS_HA => true, } } } #[doc = r" Proxy"] pub struct _MONIDLEW<'a> { w: &'a mut W, } impl<'a> _MONIDLEW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: MONIDLEW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Not idle. The I2C bus is not idle, or this flag has been cleared by software."] #[inline] pub fn not_idle_the_i2c_bu(self) -> &'a mut W { self.variant(MONIDLEW::NOT_IDLE_THE_I2C_BU) } #[doc = "Idle. The I2C bus has gone idle at least once since the last time this flag was cleared by software."] #[inline] pub fn idle_the_i2c_bus_ha(self) -> &'a mut W { self.variant(MONIDLEW::IDLE_THE_I2C_BUS_HA) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 19; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `EVENTTIMEOUT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EVENTTIMEOUTW { #[doc = "No time-out. I2C bus events have not caused a timeout."] NO_TIME_OUT_I2C_BUS, #[doc = "Event time-out. The time between I2C bus events has been longer than the time specified by the I2C Timeout register."] EVENT_TIME_OUT_THE_, } impl EVENTTIMEOUTW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { EVENTTIMEOUTW::NO_TIME_OUT_I2C_BUS => false, EVENTTIMEOUTW::EVENT_TIME_OUT_THE_ => true, } } } #[doc = r" Proxy"] pub struct _EVENTTIMEOUTW<'a> { w: &'a mut W, } impl<'a> _EVENTTIMEOUTW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: EVENTTIMEOUTW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No time-out. I2C bus events have not caused a timeout."] #[inline] pub fn no_time_out_i2c_bus(self) -> &'a mut W { self.variant(EVENTTIMEOUTW::NO_TIME_OUT_I2C_BUS) } #[doc = "Event time-out. The time between I2C bus events has been longer than the time specified by the I2C Timeout register."] #[inline] pub fn event_time_out_the_(self) -> &'a mut W { self.variant(EVENTTIMEOUTW::EVENT_TIME_OUT_THE_) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SCLTIMEOUT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SCLTIMEOUTW { #[doc = "No time-out. SCL low time has not caused a timeout."] NO_TIME_OUT_SCL_LOW, #[doc = "Time-out. SCL low time has caused a timeout."] TIME_OUT_SCL_LOW_TI, } impl SCLTIMEOUTW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SCLTIMEOUTW::NO_TIME_OUT_SCL_LOW => false, SCLTIMEOUTW::TIME_OUT_SCL_LOW_TI => true, } } } #[doc = r" Proxy"] pub struct _SCLTIMEOUTW<'a> { w: &'a mut W, } impl<'a> _SCLTIMEOUTW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SCLTIMEOUTW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No time-out. SCL low time has not caused a timeout."] #[inline] pub fn no_time_out_scl_low(self) -> &'a mut W { self.variant(SCLTIMEOUTW::NO_TIME_OUT_SCL_LOW) } #[doc = "Time-out. SCL low time has caused a timeout."] #[inline] pub fn time_out_scl_low_ti(self) -> &'a mut W { self.variant(SCLTIMEOUTW::TIME_OUT_SCL_LOW_TI) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 25; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Master Pending. Indicates whether the Master function needs software service. This flag will cause an interrupt when set if enabled via the INTENSET register. The MSTPENDING flag is automatically cleared when a 1 is written to the MSTCONTINUE bit in the MSTCTL register."] #[inline] pub fn mstpending(&self) -> MSTPENDINGR { MSTPENDINGR::_from({ const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 1:3 - Master State code. Each value of this field indicates a specific required service for the Master function. All other values are reserved."] #[inline] pub fn mststate(&self) -> MSTSTATER { MSTSTATER::_from({ const MASK: u8 = 7; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 4 - Master Arbitration Loss flag. This flag can be cleared by software writing a 1 to this bit. It is also cleared automatically a 1 is written to MSTCONTINUE."] #[inline] pub fn mstarbloss(&self) -> MSTARBLOSSR { MSTARBLOSSR::_from({ const MASK: bool = true; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 6 - Master Start/Stop Error flag. This flag can be cleared by software writing a 1 to this bit. It is also cleared automatically a 1 is written to MstContinue."] #[inline] pub fn mstststperr(&self) -> MSTSTSTPERRR { MSTSTSTPERRR::_from({ const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 8 - Slave Pending. Indicates whether the Slave function needs software service. This flag will cause an interrupt when set if enabled via INTENSET. The SLVPENDING flag is read-only and is automatically cleared when a 1 is written to the SLVCONTINUE bit in the MSTCTL register."] #[inline] pub fn slvpending(&self) -> SLVPENDINGR { SLVPENDINGR::_from({ const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 9:10 - Slave State code. Each value of this field indicates a specific required service for the Slave function. All other values are reserved."] #[inline] pub fn slvstate(&self) -> SLVSTATER { SLVSTATER::_from({ const MASK: u8 = 3; const OFFSET: u8 = 9; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 11 - Slave Not Stretching. Indicates when the slave function is stretching the I2C clock. This is needed in order to gracefully invoke Deep Sleep or Power-down modes during slave operation. This read-only flag reflects the slave function status in real time."] #[inline] pub fn slvnotstr(&self) -> SLVNOTSTRR { SLVNOTSTRR::_from({ const MASK: bool = true; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 12:13 - Slave address match Index. This field is valid when the I2C slave function has been selected by receiving an address that matches one of the slave addresses defined by any enabled slave address registers, and provides an identification of the address that was matched. It is possible that more than one address could be matched, but only one match can be reported here."] #[inline] pub fn slvidx(&self) -> SLVIDXR { SLVIDXR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 14 - Slave selected flag. SLVSEL is set after an address match when software tells the Slave function to acknowledge the address. It is cleared when another address cycle presents an address that does not match an enabled address on the Slave function, when slave software decides to Nack a matched address, or when there is a Stop detected on the bus. SLVSEL is not cleared if software Nacks data."] #[inline] pub fn slvsel(&self) -> SLVSELR { SLVSELR::_from({ const MASK: bool = true; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 15 - Slave Deselected flag. This flag will cause an interrupt when set if enabled via INTENSET. This flag can be cleared by writing a 1 to this bit."] #[inline] pub fn slvdesel(&self) -> SLVDESELR { SLVDESELR::_from({ const MASK: bool = true; const OFFSET: u8 = 15; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 16 - Monitor Ready. This flag is cleared when the MONRXDAT register is read."] #[inline] pub fn monrdy(&self) -> MONRDYR { MONRDYR::_from({ const MASK: bool = true; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 17 - Monitor Overflow flag."] #[inline] pub fn monov(&self) -> MONOVR { MONOVR::_from({ const MASK: bool = true; const OFFSET: u8 = 17; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 18 - Monitor Active flag. This flag indicates when the Monitor function considers the I2C bus to be active. Active is defined here as when some Master is on the bus: a bus Start has occurred more recently than a bus Stop."] #[inline] pub fn monactive(&self) -> MONACTIVER { MONACTIVER::_from({ const MASK: bool = true; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 19 - Monitor Idle flag. This flag is set when the Monitor function sees the I2C bus change from active to inactive. This can be used by software to decide when to process data accumulated by the Monitor function. This flag will cause an interrupt when set if enabled via the INTENSET register . The flag can be cleared by writing a 1 to this bit."] #[inline] pub fn monidle(&self) -> MONIDLER { MONIDLER::_from({ const MASK: bool = true; const OFFSET: u8 = 19; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 24 - Event Time-out Interrupt flag. Indicates when the time between events has been longer than the time specified by the TIMEOUT register. Events include Start, Stop, and clock edges. The case of SCL remaining low longer than TIMEOUT is not reported by this flag, it is reported in by the SCL Time-out flag. The flag is cleared by writing a 1 to this bit."] #[inline] pub fn eventtimeout(&self) -> EVENTTIMEOUTR { EVENTTIMEOUTR::_from({ const MASK: bool = true; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 25 - SCL Time-out Interrupt flag. Indicates when SCL has remained low longer than the time specific by the TIMEOUT register. The flag is cleared by writing a 1 to this bit."] #[inline] pub fn scltimeout(&self) -> SCLTIMEOUTR { SCLTIMEOUTR::_from({ const MASK: bool = true; const OFFSET: u8 = 25; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 2049 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Master Pending. Indicates whether the Master function needs software service. This flag will cause an interrupt when set if enabled via the INTENSET register. The MSTPENDING flag is automatically cleared when a 1 is written to the MSTCONTINUE bit in the MSTCTL register."] #[inline] pub fn mstpending(&mut self) -> _MSTPENDINGW { _MSTPENDINGW { w: self } } #[doc = "Bits 1:3 - Master State code. Each value of this field indicates a specific required service for the Master function. All other values are reserved."] #[inline] pub fn mststate(&mut self) -> _MSTSTATEW { _MSTSTATEW { w: self } } #[doc = "Bit 4 - Master Arbitration Loss flag. This flag can be cleared by software writing a 1 to this bit. It is also cleared automatically a 1 is written to MSTCONTINUE."] #[inline] pub fn mstarbloss(&mut self) -> _MSTARBLOSSW { _MSTARBLOSSW { w: self } } #[doc = "Bit 6 - Master Start/Stop Error flag. This flag can be cleared by software writing a 1 to this bit. It is also cleared automatically a 1 is written to MstContinue."] #[inline] pub fn mstststperr(&mut self) -> _MSTSTSTPERRW { _MSTSTSTPERRW { w: self } } #[doc = "Bit 8 - Slave Pending. Indicates whether the Slave function needs software service. This flag will cause an interrupt when set if enabled via INTENSET. The SLVPENDING flag is read-only and is automatically cleared when a 1 is written to the SLVCONTINUE bit in the MSTCTL register."] #[inline] pub fn slvpending(&mut self) -> _SLVPENDINGW { _SLVPENDINGW { w: self } } #[doc = "Bits 9:10 - Slave State code. Each value of this field indicates a specific required service for the Slave function. All other values are reserved."] #[inline] pub fn slvstate(&mut self) -> _SLVSTATEW { _SLVSTATEW { w: self } } #[doc = "Bit 11 - Slave Not Stretching. Indicates when the slave function is stretching the I2C clock. This is needed in order to gracefully invoke Deep Sleep or Power-down modes during slave operation. This read-only flag reflects the slave function status in real time."] #[inline] pub fn slvnotstr(&mut self) -> _SLVNOTSTRW { _SLVNOTSTRW { w: self } } #[doc = "Bits 12:13 - Slave address match Index. This field is valid when the I2C slave function has been selected by receiving an address that matches one of the slave addresses defined by any enabled slave address registers, and provides an identification of the address that was matched. It is possible that more than one address could be matched, but only one match can be reported here."] #[inline] pub fn slvidx(&mut self) -> _SLVIDXW { _SLVIDXW { w: self } } #[doc = "Bit 14 - Slave selected flag. SLVSEL is set after an address match when software tells the Slave function to acknowledge the address. It is cleared when another address cycle presents an address that does not match an enabled address on the Slave function, when slave software decides to Nack a matched address, or when there is a Stop detected on the bus. SLVSEL is not cleared if software Nacks data."] #[inline] pub fn slvsel(&mut self) -> _SLVSELW { _SLVSELW { w: self } } #[doc = "Bit 15 - Slave Deselected flag. This flag will cause an interrupt when set if enabled via INTENSET. This flag can be cleared by writing a 1 to this bit."] #[inline] pub fn slvdesel(&mut self) -> _SLVDESELW { _SLVDESELW { w: self } } #[doc = "Bit 16 - Monitor Ready. This flag is cleared when the MONRXDAT register is read."] #[inline] pub fn monrdy(&mut self) -> _MONRDYW { _MONRDYW { w: self } } #[doc = "Bit 17 - Monitor Overflow flag."] #[inline] pub fn monov(&mut self) -> _MONOVW { _MONOVW { w: self } } #[doc = "Bit 18 - Monitor Active flag. This flag indicates when the Monitor function considers the I2C bus to be active. Active is defined here as when some Master is on the bus: a bus Start has occurred more recently than a bus Stop."] #[inline] pub fn monactive(&mut self) -> _MONACTIVEW { _MONACTIVEW { w: self } } #[doc = "Bit 19 - Monitor Idle flag. This flag is set when the Monitor function sees the I2C bus change from active to inactive. This can be used by software to decide when to process data accumulated by the Monitor function. This flag will cause an interrupt when set if enabled via the INTENSET register . The flag can be cleared by writing a 1 to this bit."] #[inline] pub fn monidle(&mut self) -> _MONIDLEW { _MONIDLEW { w: self } } #[doc = "Bit 24 - Event Time-out Interrupt flag. Indicates when the time between events has been longer than the time specified by the TIMEOUT register. Events include Start, Stop, and clock edges. The case of SCL remaining low longer than TIMEOUT is not reported by this flag, it is reported in by the SCL Time-out flag. The flag is cleared by writing a 1 to this bit."] #[inline] pub fn eventtimeout(&mut self) -> _EVENTTIMEOUTW { _EVENTTIMEOUTW { w: self } } #[doc = "Bit 25 - SCL Time-out Interrupt flag. Indicates when SCL has remained low longer than the time specific by the TIMEOUT register. The flag is cleared by writing a 1 to this bit."] #[inline] pub fn scltimeout(&mut self) -> _SCLTIMEOUTW { _SCLTIMEOUTW { w: self } } }
use ::json_to_final_ast; use ::spec_type_to_final_ast; use super::super::size_of::generate_size_of; fn test_size_of(spec: &str) { let ir = spec_type_to_final_ast(spec).unwrap(); let size_of = generate_size_of(ir).unwrap(); println!("{:?}", size_of); } #[test] fn simple_scalar() { test_size_of(r#" def_type("test") => u8; "#); } #[test] fn container() { test_size_of(r#" def_type("test") => container { field("woo") => u8; }; "#); test_size_of(r#" def_type("test") => container(virtual: "true") { field("woo") => u8; }; "#); test_size_of(r#" def_type("test") => container { virtual_field("len", ref: "arr", prop: "length") => u8; field("arr") => array(ref: "../len") => u8; }; "#); }
#![allow(clippy::vec_box)] use spdk_sys::spdk_bdev_module; use crate::bdev::nexus::{nexus_bdev::Nexus, nexus_fn_table::NexusFnTable}; /// Allocate C string and return pointer to it. /// NOTE: The resulting string must be freed explicitly after use! macro_rules! c_str { ($lit:expr) => { std::ffi::CString::new($lit).unwrap().into_raw(); }; } pub mod nexus_bdev; pub mod nexus_bdev_children; pub mod nexus_bdev_rebuild; pub mod nexus_bdev_snapshot; mod nexus_channel; pub(crate) mod nexus_child; pub(crate) mod nexus_child_error_store; pub mod nexus_child_status_config; mod nexus_config; pub mod nexus_fn_table; pub mod nexus_io; pub mod nexus_label; pub mod nexus_metadata; pub mod nexus_metadata_content; pub mod nexus_module; pub mod nexus_nbd; pub mod nexus_share; /// public function which simply calls register module pub fn register_module() { nexus_module::register_module() } /// get a reference to the module pub fn module() -> Option<*mut spdk_bdev_module> { if let Some(m) = nexus_module::NexusModule::current() { Some(m.as_ptr()) } else { None } } /// get a static ref to the fn table of the nexus module pub fn fn_table() -> Option<&'static spdk_sys::spdk_bdev_fn_table> { Some(NexusFnTable::table()) } /// get a reference to the global nexuses pub fn instances() -> &'static mut Vec<Box<Nexus>> { nexus_module::NexusModule::get_instances() } /// function used to create a new nexus when parsing a config file pub fn nexus_instance_new(name: String, size: u64, children: Vec<String>) { let list = instances(); list.push(Nexus::new(&name, size, None, Some(&children))); } /// called during shutdown so that all nexus children are in Destroying state /// so that a possible remove event from SPDK also results in bdev removal pub async fn nexus_children_to_destroying_state() { info!("setting all nexus children to destroying state..."); for nexus in instances() { for child in nexus.children.iter() { child.set_state(nexus_child::ChildState::Destroying); } } info!("set all nexus children to destroying state"); }
use std::io::prelude::*; use std::io::Result; use std::fs::File; use std::env; fn read_all(path : String) -> Result<String> { let mut buffer = String::new(); return File::open(path) .and_then(|mut f| f.read_to_string(&mut buffer)) .map(|_| buffer); } fn main() { for path in env::args().skip(1) { match read_all(path) { Ok(content) => { print!("{}", content) } Err(why) => { println!("ERR: {}", why.to_string()) } } } }
mod r#trait; pub(crate) use r#trait::*; #[cfg(test)] pub(crate) mod mock;
pub mod atom; pub mod color; pub mod comment; pub mod error; pub mod func_call; pub mod input; pub mod name; pub mod num; pub mod op; pub mod stat_expr; pub mod stat_expr_types; pub mod state; pub mod string; pub mod syntax_type; pub mod trans; pub mod utils;
#[doc = "Reader of register SYNC"] pub type R = crate::R<u32, super::SYNC>; #[doc = "Writer for register SYNC"] pub type W = crate::W<u32, super::SYNC>; #[doc = "Register SYNC `reset()`'s with value 0"] impl crate::ResetValue for super::SYNC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Synchronize GPTM Timer 0\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SYNCT0_A { #[doc = "0: GPTM0 is not affected"] NONE = 0, #[doc = "1: A timeout event for Timer A of GPTM0 is triggered"] TA = 1, #[doc = "2: A timeout event for Timer B of GPTM0 is triggered"] TB = 2, #[doc = "3: A timeout event for both Timer A and Timer B of GPTM0 is triggered"] TATB = 3, } impl From<SYNCT0_A> for u8 { #[inline(always)] fn from(variant: SYNCT0_A) -> Self { variant as _ } } #[doc = "Reader of field `SYNCT0`"] pub type SYNCT0_R = crate::R<u8, SYNCT0_A>; impl SYNCT0_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYNCT0_A { match self.bits { 0 => SYNCT0_A::NONE, 1 => SYNCT0_A::TA, 2 => SYNCT0_A::TB, 3 => SYNCT0_A::TATB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == SYNCT0_A::NONE } #[doc = "Checks if the value of the field is `TA`"] #[inline(always)] pub fn is_ta(&self) -> bool { *self == SYNCT0_A::TA } #[doc = "Checks if the value of the field is `TB`"] #[inline(always)] pub fn is_tb(&self) -> bool { *self == SYNCT0_A::TB } #[doc = "Checks if the value of the field is `TATB`"] #[inline(always)] pub fn is_tatb(&self) -> bool { *self == SYNCT0_A::TATB } } #[doc = "Write proxy for field `SYNCT0`"] pub struct SYNCT0_W<'a> { w: &'a mut W, } impl<'a> SYNCT0_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYNCT0_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "GPTM0 is not affected"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(SYNCT0_A::NONE) } #[doc = "A timeout event for Timer A of GPTM0 is triggered"] #[inline(always)] pub fn ta(self) -> &'a mut W { self.variant(SYNCT0_A::TA) } #[doc = "A timeout event for Timer B of GPTM0 is triggered"] #[inline(always)] pub fn tb(self) -> &'a mut W { self.variant(SYNCT0_A::TB) } #[doc = "A timeout event for both Timer A and Timer B of GPTM0 is triggered"] #[inline(always)] pub fn tatb(self) -> &'a mut W { self.variant(SYNCT0_A::TATB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03); self.w } } #[doc = "Synchronize GPTM Timer 1\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SYNCT1_A { #[doc = "0: GPTM1 is not affected"] NONE = 0, #[doc = "1: A timeout event for Timer A of GPTM1 is triggered"] TA = 1, #[doc = "2: A timeout event for Timer B of GPTM1 is triggered"] TB = 2, #[doc = "3: A timeout event for both Timer A and Timer B of GPTM1 is triggered"] TATB = 3, } impl From<SYNCT1_A> for u8 { #[inline(always)] fn from(variant: SYNCT1_A) -> Self { variant as _ } } #[doc = "Reader of field `SYNCT1`"] pub type SYNCT1_R = crate::R<u8, SYNCT1_A>; impl SYNCT1_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYNCT1_A { match self.bits { 0 => SYNCT1_A::NONE, 1 => SYNCT1_A::TA, 2 => SYNCT1_A::TB, 3 => SYNCT1_A::TATB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == SYNCT1_A::NONE } #[doc = "Checks if the value of the field is `TA`"] #[inline(always)] pub fn is_ta(&self) -> bool { *self == SYNCT1_A::TA } #[doc = "Checks if the value of the field is `TB`"] #[inline(always)] pub fn is_tb(&self) -> bool { *self == SYNCT1_A::TB } #[doc = "Checks if the value of the field is `TATB`"] #[inline(always)] pub fn is_tatb(&self) -> bool { *self == SYNCT1_A::TATB } } #[doc = "Write proxy for field `SYNCT1`"] pub struct SYNCT1_W<'a> { w: &'a mut W, } impl<'a> SYNCT1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYNCT1_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "GPTM1 is not affected"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(SYNCT1_A::NONE) } #[doc = "A timeout event for Timer A of GPTM1 is triggered"] #[inline(always)] pub fn ta(self) -> &'a mut W { self.variant(SYNCT1_A::TA) } #[doc = "A timeout event for Timer B of GPTM1 is triggered"] #[inline(always)] pub fn tb(self) -> &'a mut W { self.variant(SYNCT1_A::TB) } #[doc = "A timeout event for both Timer A and Timer B of GPTM1 is triggered"] #[inline(always)] pub fn tatb(self) -> &'a mut W { self.variant(SYNCT1_A::TATB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 2)) | (((value as u32) & 0x03) << 2); self.w } } #[doc = "Synchronize GPTM Timer 2\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SYNCT2_A { #[doc = "0: GPTM2 is not affected"] NONE = 0, #[doc = "1: A timeout event for Timer A of GPTM2 is triggered"] TA = 1, #[doc = "2: A timeout event for Timer B of GPTM2 is triggered"] TB = 2, #[doc = "3: A timeout event for both Timer A and Timer B of GPTM2 is triggered"] TATB = 3, } impl From<SYNCT2_A> for u8 { #[inline(always)] fn from(variant: SYNCT2_A) -> Self { variant as _ } } #[doc = "Reader of field `SYNCT2`"] pub type SYNCT2_R = crate::R<u8, SYNCT2_A>; impl SYNCT2_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYNCT2_A { match self.bits { 0 => SYNCT2_A::NONE, 1 => SYNCT2_A::TA, 2 => SYNCT2_A::TB, 3 => SYNCT2_A::TATB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == SYNCT2_A::NONE } #[doc = "Checks if the value of the field is `TA`"] #[inline(always)] pub fn is_ta(&self) -> bool { *self == SYNCT2_A::TA } #[doc = "Checks if the value of the field is `TB`"] #[inline(always)] pub fn is_tb(&self) -> bool { *self == SYNCT2_A::TB } #[doc = "Checks if the value of the field is `TATB`"] #[inline(always)] pub fn is_tatb(&self) -> bool { *self == SYNCT2_A::TATB } } #[doc = "Write proxy for field `SYNCT2`"] pub struct SYNCT2_W<'a> { w: &'a mut W, } impl<'a> SYNCT2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYNCT2_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "GPTM2 is not affected"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(SYNCT2_A::NONE) } #[doc = "A timeout event for Timer A of GPTM2 is triggered"] #[inline(always)] pub fn ta(self) -> &'a mut W { self.variant(SYNCT2_A::TA) } #[doc = "A timeout event for Timer B of GPTM2 is triggered"] #[inline(always)] pub fn tb(self) -> &'a mut W { self.variant(SYNCT2_A::TB) } #[doc = "A timeout event for both Timer A and Timer B of GPTM2 is triggered"] #[inline(always)] pub fn tatb(self) -> &'a mut W { self.variant(SYNCT2_A::TATB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4); self.w } } #[doc = "Synchronize GPTM Timer 3\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SYNCT3_A { #[doc = "0: GPTM3 is not affected"] NONE = 0, #[doc = "1: A timeout event for Timer A of GPTM3 is triggered"] TA = 1, #[doc = "2: A timeout event for Timer B of GPTM3 is triggered"] TB = 2, #[doc = "3: A timeout event for both Timer A and Timer B of GPTM3 is triggered"] TATB = 3, } impl From<SYNCT3_A> for u8 { #[inline(always)] fn from(variant: SYNCT3_A) -> Self { variant as _ } } #[doc = "Reader of field `SYNCT3`"] pub type SYNCT3_R = crate::R<u8, SYNCT3_A>; impl SYNCT3_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYNCT3_A { match self.bits { 0 => SYNCT3_A::NONE, 1 => SYNCT3_A::TA, 2 => SYNCT3_A::TB, 3 => SYNCT3_A::TATB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == SYNCT3_A::NONE } #[doc = "Checks if the value of the field is `TA`"] #[inline(always)] pub fn is_ta(&self) -> bool { *self == SYNCT3_A::TA } #[doc = "Checks if the value of the field is `TB`"] #[inline(always)] pub fn is_tb(&self) -> bool { *self == SYNCT3_A::TB } #[doc = "Checks if the value of the field is `TATB`"] #[inline(always)] pub fn is_tatb(&self) -> bool { *self == SYNCT3_A::TATB } } #[doc = "Write proxy for field `SYNCT3`"] pub struct SYNCT3_W<'a> { w: &'a mut W, } impl<'a> SYNCT3_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYNCT3_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "GPTM3 is not affected"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(SYNCT3_A::NONE) } #[doc = "A timeout event for Timer A of GPTM3 is triggered"] #[inline(always)] pub fn ta(self) -> &'a mut W { self.variant(SYNCT3_A::TA) } #[doc = "A timeout event for Timer B of GPTM3 is triggered"] #[inline(always)] pub fn tb(self) -> &'a mut W { self.variant(SYNCT3_A::TB) } #[doc = "A timeout event for both Timer A and Timer B of GPTM3 is triggered"] #[inline(always)] pub fn tatb(self) -> &'a mut W { self.variant(SYNCT3_A::TATB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 6)) | (((value as u32) & 0x03) << 6); self.w } } #[doc = "Synchronize GPTM Timer 4\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SYNCT4_A { #[doc = "0: GPTM4 is not affected"] NONE = 0, #[doc = "1: A timeout event for Timer A of GPTM4 is triggered"] TA = 1, #[doc = "2: A timeout event for Timer B of GPTM4 is triggered"] TB = 2, #[doc = "3: A timeout event for both Timer A and Timer B of GPTM4 is triggered"] TATB = 3, } impl From<SYNCT4_A> for u8 { #[inline(always)] fn from(variant: SYNCT4_A) -> Self { variant as _ } } #[doc = "Reader of field `SYNCT4`"] pub type SYNCT4_R = crate::R<u8, SYNCT4_A>; impl SYNCT4_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYNCT4_A { match self.bits { 0 => SYNCT4_A::NONE, 1 => SYNCT4_A::TA, 2 => SYNCT4_A::TB, 3 => SYNCT4_A::TATB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == SYNCT4_A::NONE } #[doc = "Checks if the value of the field is `TA`"] #[inline(always)] pub fn is_ta(&self) -> bool { *self == SYNCT4_A::TA } #[doc = "Checks if the value of the field is `TB`"] #[inline(always)] pub fn is_tb(&self) -> bool { *self == SYNCT4_A::TB } #[doc = "Checks if the value of the field is `TATB`"] #[inline(always)] pub fn is_tatb(&self) -> bool { *self == SYNCT4_A::TATB } } #[doc = "Write proxy for field `SYNCT4`"] pub struct SYNCT4_W<'a> { w: &'a mut W, } impl<'a> SYNCT4_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYNCT4_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "GPTM4 is not affected"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(SYNCT4_A::NONE) } #[doc = "A timeout event for Timer A of GPTM4 is triggered"] #[inline(always)] pub fn ta(self) -> &'a mut W { self.variant(SYNCT4_A::TA) } #[doc = "A timeout event for Timer B of GPTM4 is triggered"] #[inline(always)] pub fn tb(self) -> &'a mut W { self.variant(SYNCT4_A::TB) } #[doc = "A timeout event for both Timer A and Timer B of GPTM4 is triggered"] #[inline(always)] pub fn tatb(self) -> &'a mut W { self.variant(SYNCT4_A::TATB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8); self.w } } #[doc = "Synchronize GPTM Timer 5\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SYNCT5_A { #[doc = "0: GPTM5 is not affected"] NONE = 0, #[doc = "1: A timeout event for Timer A of GPTM5 is triggered"] TA = 1, #[doc = "2: A timeout event for Timer B of GPTM5 is triggered"] TB = 2, #[doc = "3: A timeout event for both Timer A and Timer B of GPTM5 is triggered"] TATB = 3, } impl From<SYNCT5_A> for u8 { #[inline(always)] fn from(variant: SYNCT5_A) -> Self { variant as _ } } #[doc = "Reader of field `SYNCT5`"] pub type SYNCT5_R = crate::R<u8, SYNCT5_A>; impl SYNCT5_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYNCT5_A { match self.bits { 0 => SYNCT5_A::NONE, 1 => SYNCT5_A::TA, 2 => SYNCT5_A::TB, 3 => SYNCT5_A::TATB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == SYNCT5_A::NONE } #[doc = "Checks if the value of the field is `TA`"] #[inline(always)] pub fn is_ta(&self) -> bool { *self == SYNCT5_A::TA } #[doc = "Checks if the value of the field is `TB`"] #[inline(always)] pub fn is_tb(&self) -> bool { *self == SYNCT5_A::TB } #[doc = "Checks if the value of the field is `TATB`"] #[inline(always)] pub fn is_tatb(&self) -> bool { *self == SYNCT5_A::TATB } } #[doc = "Write proxy for field `SYNCT5`"] pub struct SYNCT5_W<'a> { w: &'a mut W, } impl<'a> SYNCT5_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYNCT5_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "GPTM5 is not affected"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(SYNCT5_A::NONE) } #[doc = "A timeout event for Timer A of GPTM5 is triggered"] #[inline(always)] pub fn ta(self) -> &'a mut W { self.variant(SYNCT5_A::TA) } #[doc = "A timeout event for Timer B of GPTM5 is triggered"] #[inline(always)] pub fn tb(self) -> &'a mut W { self.variant(SYNCT5_A::TB) } #[doc = "A timeout event for both Timer A and Timer B of GPTM5 is triggered"] #[inline(always)] pub fn tatb(self) -> &'a mut W { self.variant(SYNCT5_A::TATB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 10)) | (((value as u32) & 0x03) << 10); self.w } } #[doc = "Synchronize GPTM 32/64-Bit Timer 0\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SYNCWT0_A { #[doc = "0: GPTM 32/64-Bit Timer 0 is not affected"] NONE = 0, #[doc = "1: A timeout event for Timer A of GPTM 32/64-Bit Timer 0 is triggered"] TA = 1, #[doc = "2: A timeout event for Timer B of GPTM 32/64-Bit Timer 0 is triggered"] TB = 2, #[doc = "3: A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 0 is triggered"] TATB = 3, } impl From<SYNCWT0_A> for u8 { #[inline(always)] fn from(variant: SYNCWT0_A) -> Self { variant as _ } } #[doc = "Reader of field `SYNCWT0`"] pub type SYNCWT0_R = crate::R<u8, SYNCWT0_A>; impl SYNCWT0_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYNCWT0_A { match self.bits { 0 => SYNCWT0_A::NONE, 1 => SYNCWT0_A::TA, 2 => SYNCWT0_A::TB, 3 => SYNCWT0_A::TATB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == SYNCWT0_A::NONE } #[doc = "Checks if the value of the field is `TA`"] #[inline(always)] pub fn is_ta(&self) -> bool { *self == SYNCWT0_A::TA } #[doc = "Checks if the value of the field is `TB`"] #[inline(always)] pub fn is_tb(&self) -> bool { *self == SYNCWT0_A::TB } #[doc = "Checks if the value of the field is `TATB`"] #[inline(always)] pub fn is_tatb(&self) -> bool { *self == SYNCWT0_A::TATB } } #[doc = "Write proxy for field `SYNCWT0`"] pub struct SYNCWT0_W<'a> { w: &'a mut W, } impl<'a> SYNCWT0_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYNCWT0_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "GPTM 32/64-Bit Timer 0 is not affected"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(SYNCWT0_A::NONE) } #[doc = "A timeout event for Timer A of GPTM 32/64-Bit Timer 0 is triggered"] #[inline(always)] pub fn ta(self) -> &'a mut W { self.variant(SYNCWT0_A::TA) } #[doc = "A timeout event for Timer B of GPTM 32/64-Bit Timer 0 is triggered"] #[inline(always)] pub fn tb(self) -> &'a mut W { self.variant(SYNCWT0_A::TB) } #[doc = "A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 0 is triggered"] #[inline(always)] pub fn tatb(self) -> &'a mut W { self.variant(SYNCWT0_A::TATB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 12)) | (((value as u32) & 0x03) << 12); self.w } } #[doc = "Synchronize GPTM 32/64-Bit Timer 1\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SYNCWT1_A { #[doc = "0: GPTM 32/64-Bit Timer 1 is not affected"] NONE = 0, #[doc = "1: A timeout event for Timer A of GPTM 32/64-Bit Timer 1 is triggered"] TA = 1, #[doc = "2: A timeout event for Timer B of GPTM 32/64-Bit Timer 1 is triggered"] TB = 2, #[doc = "3: A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 1 is triggered"] TATB = 3, } impl From<SYNCWT1_A> for u8 { #[inline(always)] fn from(variant: SYNCWT1_A) -> Self { variant as _ } } #[doc = "Reader of field `SYNCWT1`"] pub type SYNCWT1_R = crate::R<u8, SYNCWT1_A>; impl SYNCWT1_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYNCWT1_A { match self.bits { 0 => SYNCWT1_A::NONE, 1 => SYNCWT1_A::TA, 2 => SYNCWT1_A::TB, 3 => SYNCWT1_A::TATB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == SYNCWT1_A::NONE } #[doc = "Checks if the value of the field is `TA`"] #[inline(always)] pub fn is_ta(&self) -> bool { *self == SYNCWT1_A::TA } #[doc = "Checks if the value of the field is `TB`"] #[inline(always)] pub fn is_tb(&self) -> bool { *self == SYNCWT1_A::TB } #[doc = "Checks if the value of the field is `TATB`"] #[inline(always)] pub fn is_tatb(&self) -> bool { *self == SYNCWT1_A::TATB } } #[doc = "Write proxy for field `SYNCWT1`"] pub struct SYNCWT1_W<'a> { w: &'a mut W, } impl<'a> SYNCWT1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYNCWT1_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "GPTM 32/64-Bit Timer 1 is not affected"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(SYNCWT1_A::NONE) } #[doc = "A timeout event for Timer A of GPTM 32/64-Bit Timer 1 is triggered"] #[inline(always)] pub fn ta(self) -> &'a mut W { self.variant(SYNCWT1_A::TA) } #[doc = "A timeout event for Timer B of GPTM 32/64-Bit Timer 1 is triggered"] #[inline(always)] pub fn tb(self) -> &'a mut W { self.variant(SYNCWT1_A::TB) } #[doc = "A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 1 is triggered"] #[inline(always)] pub fn tatb(self) -> &'a mut W { self.variant(SYNCWT1_A::TATB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 14)) | (((value as u32) & 0x03) << 14); self.w } } #[doc = "Synchronize GPTM 32/64-Bit Timer 2\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SYNCWT2_A { #[doc = "0: GPTM 32/64-Bit Timer 2 is not affected"] NONE = 0, #[doc = "1: A timeout event for Timer A of GPTM 32/64-Bit Timer 2 is triggered"] TA = 1, #[doc = "2: A timeout event for Timer B of GPTM 32/64-Bit Timer 2 is triggered"] TB = 2, #[doc = "3: A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 2 is triggered"] TATB = 3, } impl From<SYNCWT2_A> for u8 { #[inline(always)] fn from(variant: SYNCWT2_A) -> Self { variant as _ } } #[doc = "Reader of field `SYNCWT2`"] pub type SYNCWT2_R = crate::R<u8, SYNCWT2_A>; impl SYNCWT2_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYNCWT2_A { match self.bits { 0 => SYNCWT2_A::NONE, 1 => SYNCWT2_A::TA, 2 => SYNCWT2_A::TB, 3 => SYNCWT2_A::TATB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == SYNCWT2_A::NONE } #[doc = "Checks if the value of the field is `TA`"] #[inline(always)] pub fn is_ta(&self) -> bool { *self == SYNCWT2_A::TA } #[doc = "Checks if the value of the field is `TB`"] #[inline(always)] pub fn is_tb(&self) -> bool { *self == SYNCWT2_A::TB } #[doc = "Checks if the value of the field is `TATB`"] #[inline(always)] pub fn is_tatb(&self) -> bool { *self == SYNCWT2_A::TATB } } #[doc = "Write proxy for field `SYNCWT2`"] pub struct SYNCWT2_W<'a> { w: &'a mut W, } impl<'a> SYNCWT2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYNCWT2_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "GPTM 32/64-Bit Timer 2 is not affected"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(SYNCWT2_A::NONE) } #[doc = "A timeout event for Timer A of GPTM 32/64-Bit Timer 2 is triggered"] #[inline(always)] pub fn ta(self) -> &'a mut W { self.variant(SYNCWT2_A::TA) } #[doc = "A timeout event for Timer B of GPTM 32/64-Bit Timer 2 is triggered"] #[inline(always)] pub fn tb(self) -> &'a mut W { self.variant(SYNCWT2_A::TB) } #[doc = "A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 2 is triggered"] #[inline(always)] pub fn tatb(self) -> &'a mut W { self.variant(SYNCWT2_A::TATB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16); self.w } } #[doc = "Synchronize GPTM 32/64-Bit Timer 3\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SYNCWT3_A { #[doc = "0: GPTM 32/64-Bit Timer 3 is not affected"] NONE = 0, #[doc = "1: A timeout event for Timer A of GPTM 32/64-Bit Timer 3 is triggered"] TA = 1, #[doc = "2: A timeout event for Timer B of GPTM 32/64-Bit Timer 3 is triggered"] TB = 2, #[doc = "3: A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 3 is triggered"] TATB = 3, } impl From<SYNCWT3_A> for u8 { #[inline(always)] fn from(variant: SYNCWT3_A) -> Self { variant as _ } } #[doc = "Reader of field `SYNCWT3`"] pub type SYNCWT3_R = crate::R<u8, SYNCWT3_A>; impl SYNCWT3_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYNCWT3_A { match self.bits { 0 => SYNCWT3_A::NONE, 1 => SYNCWT3_A::TA, 2 => SYNCWT3_A::TB, 3 => SYNCWT3_A::TATB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == SYNCWT3_A::NONE } #[doc = "Checks if the value of the field is `TA`"] #[inline(always)] pub fn is_ta(&self) -> bool { *self == SYNCWT3_A::TA } #[doc = "Checks if the value of the field is `TB`"] #[inline(always)] pub fn is_tb(&self) -> bool { *self == SYNCWT3_A::TB } #[doc = "Checks if the value of the field is `TATB`"] #[inline(always)] pub fn is_tatb(&self) -> bool { *self == SYNCWT3_A::TATB } } #[doc = "Write proxy for field `SYNCWT3`"] pub struct SYNCWT3_W<'a> { w: &'a mut W, } impl<'a> SYNCWT3_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYNCWT3_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "GPTM 32/64-Bit Timer 3 is not affected"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(SYNCWT3_A::NONE) } #[doc = "A timeout event for Timer A of GPTM 32/64-Bit Timer 3 is triggered"] #[inline(always)] pub fn ta(self) -> &'a mut W { self.variant(SYNCWT3_A::TA) } #[doc = "A timeout event for Timer B of GPTM 32/64-Bit Timer 3 is triggered"] #[inline(always)] pub fn tb(self) -> &'a mut W { self.variant(SYNCWT3_A::TB) } #[doc = "A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 3 is triggered"] #[inline(always)] pub fn tatb(self) -> &'a mut W { self.variant(SYNCWT3_A::TATB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 18)) | (((value as u32) & 0x03) << 18); self.w } } #[doc = "Synchronize GPTM 32/64-Bit Timer 4\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SYNCWT4_A { #[doc = "0: GPTM 32/64-Bit Timer 4 is not affected"] NONE = 0, #[doc = "1: A timeout event for Timer A of GPTM 32/64-Bit Timer 4 is triggered"] TA = 1, #[doc = "2: A timeout event for Timer B of GPTM 32/64-Bit Timer 4 is triggered"] TB = 2, #[doc = "3: A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 4 is triggered"] TATB = 3, } impl From<SYNCWT4_A> for u8 { #[inline(always)] fn from(variant: SYNCWT4_A) -> Self { variant as _ } } #[doc = "Reader of field `SYNCWT4`"] pub type SYNCWT4_R = crate::R<u8, SYNCWT4_A>; impl SYNCWT4_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYNCWT4_A { match self.bits { 0 => SYNCWT4_A::NONE, 1 => SYNCWT4_A::TA, 2 => SYNCWT4_A::TB, 3 => SYNCWT4_A::TATB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == SYNCWT4_A::NONE } #[doc = "Checks if the value of the field is `TA`"] #[inline(always)] pub fn is_ta(&self) -> bool { *self == SYNCWT4_A::TA } #[doc = "Checks if the value of the field is `TB`"] #[inline(always)] pub fn is_tb(&self) -> bool { *self == SYNCWT4_A::TB } #[doc = "Checks if the value of the field is `TATB`"] #[inline(always)] pub fn is_tatb(&self) -> bool { *self == SYNCWT4_A::TATB } } #[doc = "Write proxy for field `SYNCWT4`"] pub struct SYNCWT4_W<'a> { w: &'a mut W, } impl<'a> SYNCWT4_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYNCWT4_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "GPTM 32/64-Bit Timer 4 is not affected"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(SYNCWT4_A::NONE) } #[doc = "A timeout event for Timer A of GPTM 32/64-Bit Timer 4 is triggered"] #[inline(always)] pub fn ta(self) -> &'a mut W { self.variant(SYNCWT4_A::TA) } #[doc = "A timeout event for Timer B of GPTM 32/64-Bit Timer 4 is triggered"] #[inline(always)] pub fn tb(self) -> &'a mut W { self.variant(SYNCWT4_A::TB) } #[doc = "A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 4 is triggered"] #[inline(always)] pub fn tatb(self) -> &'a mut W { self.variant(SYNCWT4_A::TATB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 20)) | (((value as u32) & 0x03) << 20); self.w } } #[doc = "Synchronize GPTM 32/64-Bit Timer 5\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum SYNCWT5_A { #[doc = "0: GPTM 32/64-Bit Timer 5 is not affected"] NONE = 0, #[doc = "1: A timeout event for Timer A of GPTM 32/64-Bit Timer 5 is triggered"] TA = 1, #[doc = "2: A timeout event for Timer B of GPTM 32/64-Bit Timer 5 is triggered"] TB = 2, #[doc = "3: A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 5 is triggered"] TATB = 3, } impl From<SYNCWT5_A> for u8 { #[inline(always)] fn from(variant: SYNCWT5_A) -> Self { variant as _ } } #[doc = "Reader of field `SYNCWT5`"] pub type SYNCWT5_R = crate::R<u8, SYNCWT5_A>; impl SYNCWT5_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYNCWT5_A { match self.bits { 0 => SYNCWT5_A::NONE, 1 => SYNCWT5_A::TA, 2 => SYNCWT5_A::TB, 3 => SYNCWT5_A::TATB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { *self == SYNCWT5_A::NONE } #[doc = "Checks if the value of the field is `TA`"] #[inline(always)] pub fn is_ta(&self) -> bool { *self == SYNCWT5_A::TA } #[doc = "Checks if the value of the field is `TB`"] #[inline(always)] pub fn is_tb(&self) -> bool { *self == SYNCWT5_A::TB } #[doc = "Checks if the value of the field is `TATB`"] #[inline(always)] pub fn is_tatb(&self) -> bool { *self == SYNCWT5_A::TATB } } #[doc = "Write proxy for field `SYNCWT5`"] pub struct SYNCWT5_W<'a> { w: &'a mut W, } impl<'a> SYNCWT5_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYNCWT5_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "GPTM 32/64-Bit Timer 5 is not affected"] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(SYNCWT5_A::NONE) } #[doc = "A timeout event for Timer A of GPTM 32/64-Bit Timer 5 is triggered"] #[inline(always)] pub fn ta(self) -> &'a mut W { self.variant(SYNCWT5_A::TA) } #[doc = "A timeout event for Timer B of GPTM 32/64-Bit Timer 5 is triggered"] #[inline(always)] pub fn tb(self) -> &'a mut W { self.variant(SYNCWT5_A::TB) } #[doc = "A timeout event for both Timer A and Timer B of GPTM 32/64-Bit Timer 5 is triggered"] #[inline(always)] pub fn tatb(self) -> &'a mut W { self.variant(SYNCWT5_A::TATB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 22)) | (((value as u32) & 0x03) << 22); self.w } } impl R { #[doc = "Bits 0:1 - Synchronize GPTM Timer 0"] #[inline(always)] pub fn synct0(&self) -> SYNCT0_R { SYNCT0_R::new((self.bits & 0x03) as u8) } #[doc = "Bits 2:3 - Synchronize GPTM Timer 1"] #[inline(always)] pub fn synct1(&self) -> SYNCT1_R { SYNCT1_R::new(((self.bits >> 2) & 0x03) as u8) } #[doc = "Bits 4:5 - Synchronize GPTM Timer 2"] #[inline(always)] pub fn synct2(&self) -> SYNCT2_R { SYNCT2_R::new(((self.bits >> 4) & 0x03) as u8) } #[doc = "Bits 6:7 - Synchronize GPTM Timer 3"] #[inline(always)] pub fn synct3(&self) -> SYNCT3_R { SYNCT3_R::new(((self.bits >> 6) & 0x03) as u8) } #[doc = "Bits 8:9 - Synchronize GPTM Timer 4"] #[inline(always)] pub fn synct4(&self) -> SYNCT4_R { SYNCT4_R::new(((self.bits >> 8) & 0x03) as u8) } #[doc = "Bits 10:11 - Synchronize GPTM Timer 5"] #[inline(always)] pub fn synct5(&self) -> SYNCT5_R { SYNCT5_R::new(((self.bits >> 10) & 0x03) as u8) } #[doc = "Bits 12:13 - Synchronize GPTM 32/64-Bit Timer 0"] #[inline(always)] pub fn syncwt0(&self) -> SYNCWT0_R { SYNCWT0_R::new(((self.bits >> 12) & 0x03) as u8) } #[doc = "Bits 14:15 - Synchronize GPTM 32/64-Bit Timer 1"] #[inline(always)] pub fn syncwt1(&self) -> SYNCWT1_R { SYNCWT1_R::new(((self.bits >> 14) & 0x03) as u8) } #[doc = "Bits 16:17 - Synchronize GPTM 32/64-Bit Timer 2"] #[inline(always)] pub fn syncwt2(&self) -> SYNCWT2_R { SYNCWT2_R::new(((self.bits >> 16) & 0x03) as u8) } #[doc = "Bits 18:19 - Synchronize GPTM 32/64-Bit Timer 3"] #[inline(always)] pub fn syncwt3(&self) -> SYNCWT3_R { SYNCWT3_R::new(((self.bits >> 18) & 0x03) as u8) } #[doc = "Bits 20:21 - Synchronize GPTM 32/64-Bit Timer 4"] #[inline(always)] pub fn syncwt4(&self) -> SYNCWT4_R { SYNCWT4_R::new(((self.bits >> 20) & 0x03) as u8) } #[doc = "Bits 22:23 - Synchronize GPTM 32/64-Bit Timer 5"] #[inline(always)] pub fn syncwt5(&self) -> SYNCWT5_R { SYNCWT5_R::new(((self.bits >> 22) & 0x03) as u8) } } impl W { #[doc = "Bits 0:1 - Synchronize GPTM Timer 0"] #[inline(always)] pub fn synct0(&mut self) -> SYNCT0_W { SYNCT0_W { w: self } } #[doc = "Bits 2:3 - Synchronize GPTM Timer 1"] #[inline(always)] pub fn synct1(&mut self) -> SYNCT1_W { SYNCT1_W { w: self } } #[doc = "Bits 4:5 - Synchronize GPTM Timer 2"] #[inline(always)] pub fn synct2(&mut self) -> SYNCT2_W { SYNCT2_W { w: self } } #[doc = "Bits 6:7 - Synchronize GPTM Timer 3"] #[inline(always)] pub fn synct3(&mut self) -> SYNCT3_W { SYNCT3_W { w: self } } #[doc = "Bits 8:9 - Synchronize GPTM Timer 4"] #[inline(always)] pub fn synct4(&mut self) -> SYNCT4_W { SYNCT4_W { w: self } } #[doc = "Bits 10:11 - Synchronize GPTM Timer 5"] #[inline(always)] pub fn synct5(&mut self) -> SYNCT5_W { SYNCT5_W { w: self } } #[doc = "Bits 12:13 - Synchronize GPTM 32/64-Bit Timer 0"] #[inline(always)] pub fn syncwt0(&mut self) -> SYNCWT0_W { SYNCWT0_W { w: self } } #[doc = "Bits 14:15 - Synchronize GPTM 32/64-Bit Timer 1"] #[inline(always)] pub fn syncwt1(&mut self) -> SYNCWT1_W { SYNCWT1_W { w: self } } #[doc = "Bits 16:17 - Synchronize GPTM 32/64-Bit Timer 2"] #[inline(always)] pub fn syncwt2(&mut self) -> SYNCWT2_W { SYNCWT2_W { w: self } } #[doc = "Bits 18:19 - Synchronize GPTM 32/64-Bit Timer 3"] #[inline(always)] pub fn syncwt3(&mut self) -> SYNCWT3_W { SYNCWT3_W { w: self } } #[doc = "Bits 20:21 - Synchronize GPTM 32/64-Bit Timer 4"] #[inline(always)] pub fn syncwt4(&mut self) -> SYNCWT4_W { SYNCWT4_W { w: self } } #[doc = "Bits 22:23 - Synchronize GPTM 32/64-Bit Timer 5"] #[inline(always)] pub fn syncwt5(&mut self) -> SYNCWT5_W { SYNCWT5_W { w: self } } }
use geometry::Vertex; pub fn from_fractal_plant(s: String) -> Vec<Vertex> { // Example 7, wikipedia. const ANGLE_SIZE: f32 = 0.43; // about 25 degrees in rads. const STEP_SIZE: f32 = 0.05; #[derive(Copy, Clone)] struct State { pub x: f32, pub y: f32, pub theta: f32, }; let mut current = State { x: -1.0, y: -1.0, theta: 45.0, }; let mut stack = vec![]; let mut verts = vec![]; for c in s.chars() { match c { 'X' => (), // partial evaluation 'F' => { let future = State { x: current.x + STEP_SIZE * current.theta.cos(), y: current.y + STEP_SIZE * current.theta.sin(), theta: current.theta, }; verts.push(Vertex::new(current.x, current.y)); verts.push(Vertex::new(future.x, future.y)); current = future; } '-' => (current.theta -= ANGLE_SIZE), '+' => (current.theta += ANGLE_SIZE), '[' => (stack.push(current)), ']' => (current = stack.pop().unwrap()), _ => { println!("c: {}", c); assert!(false) } }; } verts }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} #[repr(C)] pub struct BackgroundDownloadProgress { pub BytesReceived: u64, pub TotalBytesToReceive: u64, pub Status: BackgroundTransferStatus, pub HasResponseChanged: bool, pub HasRestarted: bool, } impl ::core::marker::Copy for BackgroundDownloadProgress {} impl ::core::clone::Clone for BackgroundDownloadProgress { fn clone(&self) -> Self { *self } } pub type BackgroundDownloader = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct BackgroundTransferBehavior(pub i32); impl BackgroundTransferBehavior { pub const Parallel: Self = Self(0i32); pub const Serialized: Self = Self(1i32); } impl ::core::marker::Copy for BackgroundTransferBehavior {} impl ::core::clone::Clone for BackgroundTransferBehavior { fn clone(&self) -> Self { *self } } pub type BackgroundTransferCompletionGroup = *mut ::core::ffi::c_void; pub type BackgroundTransferCompletionGroupTriggerDetails = *mut ::core::ffi::c_void; pub type BackgroundTransferContentPart = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct BackgroundTransferCostPolicy(pub i32); impl BackgroundTransferCostPolicy { pub const Default: Self = Self(0i32); pub const UnrestrictedOnly: Self = Self(1i32); pub const Always: Self = Self(2i32); } impl ::core::marker::Copy for BackgroundTransferCostPolicy {} impl ::core::clone::Clone for BackgroundTransferCostPolicy { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct BackgroundTransferFileRange { pub Offset: u64, pub Length: u64, } impl ::core::marker::Copy for BackgroundTransferFileRange {} impl ::core::clone::Clone for BackgroundTransferFileRange { fn clone(&self) -> Self { *self } } pub type BackgroundTransferGroup = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct BackgroundTransferPriority(pub i32); impl BackgroundTransferPriority { pub const Default: Self = Self(0i32); pub const High: Self = Self(1i32); pub const Low: Self = Self(2i32); } impl ::core::marker::Copy for BackgroundTransferPriority {} impl ::core::clone::Clone for BackgroundTransferPriority { fn clone(&self) -> Self { *self } } pub type BackgroundTransferRangesDownloadedEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct BackgroundTransferStatus(pub i32); impl BackgroundTransferStatus { pub const Idle: Self = Self(0i32); pub const Running: Self = Self(1i32); pub const PausedByApplication: Self = Self(2i32); pub const PausedCostedNetwork: Self = Self(3i32); pub const PausedNoNetwork: Self = Self(4i32); pub const Completed: Self = Self(5i32); pub const Canceled: Self = Self(6i32); pub const Error: Self = Self(7i32); pub const PausedRecoverableWebErrorStatus: Self = Self(8i32); pub const PausedSystemPolicy: Self = Self(32i32); } impl ::core::marker::Copy for BackgroundTransferStatus {} impl ::core::clone::Clone for BackgroundTransferStatus { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct BackgroundUploadProgress { pub BytesReceived: u64, pub BytesSent: u64, pub TotalBytesToReceive: u64, pub TotalBytesToSend: u64, pub Status: BackgroundTransferStatus, pub HasResponseChanged: bool, pub HasRestarted: bool, } impl ::core::marker::Copy for BackgroundUploadProgress {} impl ::core::clone::Clone for BackgroundUploadProgress { fn clone(&self) -> Self { *self } } pub type BackgroundUploader = *mut ::core::ffi::c_void; pub type DownloadOperation = *mut ::core::ffi::c_void; pub type IBackgroundTransferBase = *mut ::core::ffi::c_void; pub type IBackgroundTransferContentPartFactory = *mut ::core::ffi::c_void; pub type IBackgroundTransferOperation = *mut ::core::ffi::c_void; pub type IBackgroundTransferOperationPriority = *mut ::core::ffi::c_void; pub type ResponseInformation = *mut ::core::ffi::c_void; pub type UnconstrainedTransferRequestResult = *mut ::core::ffi::c_void; pub type UploadOperation = *mut ::core::ffi::c_void;
fn main() { println!("Hello, able!"); }
use base64; use failure::Error; use serde::ser::Serialize; use serde_derive::{Deserialize, Serialize}; use serde_json::Value; #[derive(Debug, Deserialize, Serialize, PartialEq, Clone)] #[serde(untagged)] /// Possible data values pub enum Data { /// Represents a string or binary value. As a binary value is base64 encoded, /// it is impossible to determine if the value is a string or a binary value. /// It is up to the client to determine the data type, and do the required processing /// of the [`String`] value. /// /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html StringOrBinary(String), /// Represents a JSON [`Value`]. /// /// [`Value`]: https://docs.serde.rs/serde_json/value/enum.Value.html Object(Value), } impl Data { /// Create a [`Data`] from a [`Into<String>`]. /// /// # Example /// /// ``` /// use cloudevents::Data; /// /// let value = Data::from_string("value"); /// assert_eq!(value, Data::StringOrBinary("value".to_owned())); /// ``` /// /// [`Into<String>`]: https://doc.rust-lang.org/std/convert/trait.Into.html /// [`Data`]: enum.Data.html pub fn from_string<S>(s: S) -> Self where S: Into<String>, { Data::StringOrBinary(s.into()) } /// Create a [`Data`] from a [`AsRef<[u8]>`]. /// /// # Example /// /// ``` /// use cloudevents::Data; /// /// let value = Data::from_binary(b"value"); /// assert_eq!(value, Data::StringOrBinary("dmFsdWU=".to_owned())); /// ``` /// /// [`AsRef<[u8]>`]: https://doc.rust-lang.org/std/convert/trait.AsRef.html /// [`Data`]: enum.Data.html pub fn from_binary<I>(i: I) -> Self where I: AsRef<[u8]>, { Data::StringOrBinary(base64::encode(&i)) } /// Create a [`Data`] from a [`Serialize`] object. /// /// # Example /// /// ``` /// use cloudevents::Data; /// use serde_json::Value; /// use std::error::Error; /// /// fn main() -> Result<(), Box<Error>> { /// let value = Data::from_serializable("value")?; /// assert_eq!(value, Data::Object(Value::String("value".to_owned()))); /// Ok(()) /// } /// ``` /// /// [`Serialize`]: https://docs.serde.rs/serde/ser/trait.Serialize.html /// [`Data`]: enum.Data.html pub fn from_serializable<T>(v: T) -> Result<Self, Error> where T: Serialize, { Ok(Data::Object(serde_json::to_value(v)?)) } }
//! Types for handling information about C++ types. use crate::cpp_data::CppPath; use ritual_common::errors::{bail, Result}; use serde_derive::{Deserialize, Serialize}; use std::hash::{Hash, Hasher}; #[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)] pub enum CppPointerLikeTypeKind { Pointer, Reference, RValueReference, } /// Available built-in C++ numeric types. /// All these types have corresponding /// `clang::TypeKind` values (except for `CharS` and `CharU` /// which map to `CppBuiltInNumericType::Char`) #[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)] pub enum CppBuiltInNumericType { Bool, Char, SChar, UChar, WChar, Char16, Char32, Short, UShort, Int, UInt, Long, ULong, LongLong, ULongLong, Int128, UInt128, Float, Double, LongDouble, } /// Information about a fixed-size primitive type #[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)] pub enum CppSpecificNumericTypeKind { Integer { is_signed: bool }, FloatingPoint, } /// Information about a C++ function pointer type #[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)] pub struct CppFunctionPointerType { /// Return type of the function pub return_type: Box<CppType>, /// Arguments of the function pub arguments: Vec<CppType>, /// Whether arguments are terminated with "..." pub allows_variadic_arguments: bool, } /// Information about a numeric C++ type that is /// guaranteed to be the same on all platforms, /// e.g. `uint32_t`. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CppSpecificNumericType { /// Type identifier (most likely a typedef name) pub path: CppPath, /// Size of type in bits pub bits: usize, /// Information about the type (float or integer, /// signed or unsigned) pub kind: CppSpecificNumericTypeKind, } #[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)] pub struct CppTemplateParameter { /// Template instantiation level. For example, /// if there is a template class and a template method in it, /// the class's template parameters will have level = 0 and /// the method's template parameters will have level = 1. /// If only the class or only the method is a template, /// the level will be 0. pub nested_level: usize, /// Index of the parameter. In `QHash<K, V>` `"K"` has `index = 0` /// and `"V"` has `index = 1`. pub index: usize, /// Declared name of this template parameter pub name: String, } /// Base C++ type. `CppType` can add indirection /// and constness to `CppTypeBase`, but otherwise /// this enum lists all supported types. #[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)] pub enum CppType { /// Void Void, /// Built-in C++ primitive type, like int BuiltInNumeric(CppBuiltInNumericType), /// Fixed-size primitive type, like qint64 or int64_t /// (may be translated to Rust's i64) SpecificNumeric(CppSpecificNumericType), /// Pointer sized integer, like qintptr /// (may be translated to Rust's isize) PointerSizedInteger { path: CppPath, is_signed: bool }, /// Enum type Enum { /// Name, including namespaces and nested classes path: CppPath, }, /// Class type Class(CppPath), /// Template parameter, like `"T"` anywhere inside /// `QVector<T>` declaration TemplateParameter(CppTemplateParameter), /// Function pointer type FunctionPointer(CppFunctionPointerType), PointerLike { kind: CppPointerLikeTypeKind, is_const: bool, target: Box<CppType>, }, } impl CppBuiltInNumericType { /// Returns C++ code representing this type. pub fn to_cpp_code(&self) -> &'static str { use self::CppBuiltInNumericType::*; match *self { Bool => "bool", Char => "char", SChar => "signed char", UChar => "unsigned char", WChar => "wchar_t", Char16 => "char16_t", Char32 => "char32_t", Short => "short", UShort => "unsigned short", Int => "int", UInt => "unsigned int", Long => "long", ULong => "unsigned long", LongLong => "long long", ULongLong => "unsigned long long", Int128 => "__int128_t", UInt128 => "__uint128_t", Float => "float", Double => "double", LongDouble => "long double", } } /// Returns true if this type is some sort of floating point type. pub fn is_float(&self) -> bool { use self::CppBuiltInNumericType::*; matches!(self, Float | Double | LongDouble) } /// Returns true if this type is a signed integer. pub fn is_signed_integer(&self) -> bool { use self::CppBuiltInNumericType::*; matches!(self, SChar | Short | Int | Long | LongLong | Int128) } /// Returns true if this type is an unsigned integer. pub fn is_unsigned_integer(&self) -> bool { use self::CppBuiltInNumericType::*; matches!( self, UChar | Char16 | Char32 | UShort | UInt | ULong | ULongLong | UInt128 ) } /// Returns true if this type is integer but may be signed or /// unsigned, depending on the platform. pub fn is_integer_with_undefined_signedness(&self) -> bool { use self::CppBuiltInNumericType::*; matches!(self, Char | WChar) } /// Returns all supported types. pub fn all() -> &'static [CppBuiltInNumericType] { use self::CppBuiltInNumericType::*; &[ Bool, Char, SChar, UChar, WChar, Char16, Char32, Short, UShort, Int, UInt, Long, ULong, LongLong, ULongLong, Int128, UInt128, Float, Double, LongDouble, ] } } impl CppType { pub fn new_pointer(is_const: bool, target: CppType) -> Self { CppType::PointerLike { kind: CppPointerLikeTypeKind::Pointer, is_const, target: Box::new(target), } } pub fn new_reference(is_const: bool, target: CppType) -> Self { CppType::PointerLike { kind: CppPointerLikeTypeKind::Reference, is_const, target: Box::new(target), } } /// Returns true if this is `void` type. pub fn is_void(&self) -> bool { matches!(self, CppType::Void) } /// Returns true if this is a class type. pub fn is_class(&self) -> bool { matches!(self, CppType::Class(..)) } /// Returns true if this is a template parameter. pub fn is_template_parameter(&self) -> bool { matches!(self, CppType::TemplateParameter { .. }) } /// Returns true if this is a function pointer. pub fn is_function_pointer(&self) -> bool { matches!(self, CppType::FunctionPointer(..)) } pub fn is_pointer(&self) -> bool { match self { CppType::PointerLike { kind, .. } => *kind == CppPointerLikeTypeKind::Pointer, _ => false, } } /// Returns true if this is a template parameter or a type that /// contains any template parameters. pub fn is_or_contains_template_parameter(&self) -> bool { match self { CppType::TemplateParameter { .. } => true, CppType::PointerLike { target, .. } => target.is_or_contains_template_parameter(), CppType::FunctionPointer(type1) => { type1.return_type.is_or_contains_template_parameter() || type1 .arguments .iter() .any(CppType::is_or_contains_template_parameter) } CppType::Class(path) => path.items().iter().any(|item| { if let Some(template_arguments) = &item.template_arguments { template_arguments .iter() .any(CppType::is_or_contains_template_parameter) } else { false } }), _ => false, } } pub fn contains_template_parameter(&self, param: &CppTemplateParameter) -> bool { match self { CppType::TemplateParameter(self_params) => { self_params.nested_level == param.nested_level && self_params.index == param.index } CppType::PointerLike { target, .. } => target.contains_template_parameter(param), CppType::FunctionPointer(type1) => { type1.return_type.contains_template_parameter(param) || type1 .arguments .iter() .any(|t| t.contains_template_parameter(param)) } CppType::Class(path) => path.items().iter().any(|item| { if let Some(template_arguments) = &item.template_arguments { template_arguments .iter() .any(|t| t.contains_template_parameter(param)) } else { false } }), _ => false, } } /// Returns C++ code representing this type. pub fn to_cpp_code(&self, function_pointer_inner_text: Option<&str>) -> Result<String> { if !self.is_function_pointer() && function_pointer_inner_text.is_some() { bail!("unexpected function_pointer_inner_text"); } match self { CppType::Void => Ok("void".to_string()), CppType::BuiltInNumeric(t) => Ok(t.to_cpp_code().to_string()), CppType::Enum { path } | CppType::SpecificNumeric(CppSpecificNumericType { path, .. }) | CppType::PointerSizedInteger { path, .. } => path.to_cpp_code(), CppType::Class(path) => path.to_cpp_code(), CppType::TemplateParameter { .. } => { bail!("template parameters are not allowed in C++ code generator"); } CppType::FunctionPointer(CppFunctionPointerType { return_type, arguments, allows_variadic_arguments, }) => { if *allows_variadic_arguments { bail!("function pointers with variadic arguments are not supported"); } let mut arg_texts = Vec::new(); for arg in arguments { arg_texts.push(arg.to_cpp_code(None)?); } if let Some(function_pointer_inner_text) = function_pointer_inner_text { Ok(format!( "{} (*{})({})", return_type.as_ref().to_cpp_code(None)?, function_pointer_inner_text, arg_texts.join(", ") )) } else { bail!("function_pointer_inner_text argument is missing"); } } CppType::PointerLike { kind, is_const, target, } => Ok(format!( "{}{} {}", target.to_cpp_code(function_pointer_inner_text)?, if *is_const { " const" } else { "" }, match *kind { CppPointerLikeTypeKind::Pointer => "*", CppPointerLikeTypeKind::Reference => "&", CppPointerLikeTypeKind::RValueReference => "&&", } )), } } /// Generates string representation of this type /// for debugging output. pub fn to_cpp_pseudo_code(&self) -> String { match self { CppType::TemplateParameter(param) => { return param.name.to_string(); } CppType::Class(base) => return base.to_cpp_pseudo_code(), CppType::FunctionPointer(..) => { return self .to_cpp_code(Some(&"FN_PTR".to_string())) .unwrap_or_else(|_| "[?]".to_string()); } CppType::PointerLike { kind, is_const, target, } => { return format!( "{}{}{}", if *is_const { "const " } else { "" }, target.to_cpp_pseudo_code(), match *kind { CppPointerLikeTypeKind::Pointer => "*", CppPointerLikeTypeKind::Reference => "&", CppPointerLikeTypeKind::RValueReference => "&&", } ); } _ => {} }; self.to_cpp_code(None).unwrap_or_else(|_| "[?]".to_string()) } pub fn ascii_caption(&self) -> String { match self { CppType::Void | CppType::BuiltInNumeric(_) => { self.to_cpp_code(None).unwrap().replace(' ', "_") } CppType::SpecificNumeric(data) => data.path.ascii_caption(), CppType::PointerSizedInteger { path, .. } | CppType::Enum { path } | CppType::Class(path) => path.ascii_caption(), CppType::TemplateParameter(param) => param.name.to_string(), CppType::FunctionPointer(_) => "fn".into(), CppType::PointerLike { kind, is_const, target, } => format!( "{}{}{}", target.ascii_caption(), if *is_const { "_const" } else { "" }, match *kind { CppPointerLikeTypeKind::Pointer => "_ptr", CppPointerLikeTypeKind::Reference => "_ref", CppPointerLikeTypeKind::RValueReference => "_rref", }, ), } } pub fn pointer_like_to_target(&self) -> Result<&CppType> { if let CppType::PointerLike { target, .. } = self { Ok(target) } else { bail!("not a pointer like type"); } } pub fn pointer_like_is_const(&self) -> Result<bool> { if let CppType::PointerLike { is_const, .. } = self { Ok(*is_const) } else { bail!("not a pointer like type"); } } pub fn as_function_pointer(&self) -> Option<&CppFunctionPointerType> { if let CppType::FunctionPointer(t) = self { Some(t) } else { None } } } /// Context of usage for a C++ type #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CppTypeRole { /// This type is used as a function's return type ReturnType, /// This type is not used as a function's return type NotReturnType, } pub fn is_qflags(path: &CppPath) -> bool { path.last().name == "QFlags" && !path.has_parent() && path .last() .template_arguments .as_ref() .map_or(false, |args| args.len() == 1) } impl CppType { pub fn contains_reference(&self) -> bool { if let CppType::PointerLike { kind, target, .. } = self { match *kind { CppPointerLikeTypeKind::Pointer => target.contains_reference(), CppPointerLikeTypeKind::Reference | CppPointerLikeTypeKind::RValueReference => true, } } else { false } } /// Attempts to replace template types at `nested_level` /// within this type with `template_arguments1`. #[allow(clippy::if_not_else)] pub fn instantiate( &self, nested_level: usize, template_arguments1: &[CppType], ) -> Result<CppType> { match self { CppType::TemplateParameter(param) => { if param.nested_level == nested_level { if param.index >= template_arguments1.len() { bail!("not enough template arguments"); } Ok(template_arguments1[param.index].clone()) } else { Ok(self.clone()) } } CppType::Class(type1) => Ok(CppType::Class( type1.instantiate(nested_level, template_arguments1)?, )), CppType::PointerLike { kind, is_const, target, } => Ok(CppType::PointerLike { kind: kind.clone(), is_const: *is_const, target: Box::new(target.instantiate(nested_level, template_arguments1)?), }), _ => Ok(self.clone()), } } } impl PartialEq for CppSpecificNumericType { fn eq(&self, other: &CppSpecificNumericType) -> bool { // name field is ignored self.bits == other.bits && self.kind == other.kind } } impl Eq for CppSpecificNumericType {} impl Hash for CppSpecificNumericType { fn hash<H: Hasher>(&self, state: &mut H) { self.bits.hash(state); self.kind.hash(state); } }
use crate::APool; use actix_web::{post, web, HttpResponse}; use serde::Deserialize; use crate::dump; use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header}; use crate::error::{ customer_error, ApiError::{self, *}, }; #[derive(Deserialize)] pub struct Reg { pub username: String, pub password: String, } #[derive(sqlx::FromRow, Debug, serde::Serialize)] struct SqlGetUserByName { pub id: u64, pub username: String, #[serde(skip)] pub password: String, } #[derive(serde::Serialize)] struct UserInfo<'a> { pub id: u64, pub username: &'a str, #[serde(skip)] pub password: &'a str, } #[post("/reg")] pub async fn reg(pool: web::Data<APool>, reg: web::Json<Reg>) -> Result<HttpResponse, ApiError> { let row: sqlx::Result<(u64,)> = sqlx::query_as(r#"select id from users where username=?"#) .bind(&reg.username) .fetch_one(&**pool) .await; match row { Ok(_e) => Err(customer_error(40002, "user already exists")), Err(sqlx::Error::RowNotFound) => { let password = bcrypt::hash(&reg.password, 4)?; let id = sqlx::query(r#"insert into users (username,password) values(?,?)"#) .bind(&reg.username) .bind(&password) .execute(&**pool) .await? .last_insert_id(); let u = UserInfo { id, username: &reg.username, password: &password, }; Ok(HttpResponse::Created().json(&u)) } _e => { let _ = dump!(_e); Err(UnknowError) } } } #[post("/login")] pub async fn login( pool: web::Data<APool>, login: web::Json<Reg>, ) -> Result<HttpResponse, ApiError> { let row: SqlGetUserByName = sqlx::query_as(r#"select id,username,password from users where username=?"#) .bind(&login.username) .fetch_one(&**pool) .await .map_err(|e| match e { sqlx::Error::RowNotFound => customer_error(40004, "username note exists"), _e => { let _ = dump!(_e); UnknowError } })?; if bcrypt::verify(&login.password, &row.password).map_err(|_e| { let _ = dump!(_e); UnknowError })? { let key = EncodingKey::from_secret("123".as_bytes()); let alg = Algorithm::HS256; let headers = Header::new(alg); let token = encode(&headers, &row, &key).map_err(|_e| { let _ = dump!(_e); customer_error(50001, "jwt error") })?; Ok(HttpResponse::Created().json(&token)) } else { Err(customer_error(1, "login failed")) } }
use crate::{ lens::Lens, math::{Size, Vector2}, Backend, BoxConstraints, }; use super::{TypedWidget, Widget}; pub struct LensWrap<T, U, L: Lens<T, U>, W: TypedWidget<U, B>, B: Backend> { lens: L, widget: W, _t: std::marker::PhantomData<T>, _u: std::marker::PhantomData<U>, _b: std::marker::PhantomData<B>, } impl<T, U, L: Lens<T, U>, W: TypedWidget<U, B>, B: Backend> std::ops::Deref for LensWrap<T, U, L, W, B> { type Target = W; fn deref(&self) -> &Self::Target { &self.widget } } impl<T, U, L: Lens<T, U>, W: TypedWidget<U, B>, B: Backend> std::ops::DerefMut for LensWrap<T, U, L, W, B> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.widget } } impl<T, U, L: Lens<T, U>, W: TypedWidget<U, B>, B: Backend> LensWrap<T, U, L, W, B> { pub fn new(widget: W, lens: L) -> Self { LensWrap { lens, widget, _t: std::marker::PhantomData, _u: std::marker::PhantomData, _b: std::marker::PhantomData, } } } impl<T, U, L: Lens<T, U>, W: TypedWidget<U, B>, B: Backend> Widget<T> for LensWrap<T, U, L, W, B> { type Primitive = B::Primitive; type Context = B; type Event = B::Event; type Reaction = B::EventReaction; fn layout(&mut self, bc: &BoxConstraints, context: &Self::Context, data: &T) -> Size { let widget = &mut self.widget; self.lens.with(data, |data| { TypedWidget::<U, B>::layout(widget, bc, context, data) }) } fn draw(&self, origin: Vector2, size: Size, data: &T) -> Self::Primitive { self.lens.with(data, |data| { TypedWidget::<U, B>::draw(&self.widget, origin, size, data) }) } fn event( &mut self, origin: Vector2, size: Size, data: &mut T, event: Self::Event, ) -> Option<Self::Reaction> { let widget = &mut self.widget; self.lens.with_mut(data, |data| { TypedWidget::<U, B>::event(widget, origin, size, data, event) }) } }
//! TODO docs #![no_std] #![deny( clippy::correctness, clippy::indexing_slicing, clippy::option_unwrap_used, clippy::result_unwrap_used, clippy::unimplemented, clippy::wrong_pub_self_convention, clippy::wrong_self_convention )] #![warn( clippy::complexity, clippy::pedantic, clippy::nursery, clippy::style, clippy::perf, clippy::cargo, clippy::dbg_macro, clippy::else_if_without_else, clippy::float_cmp_const, clippy::mem_forget, clippy::use_debug )] #![allow( clippy::missing_docs_in_private_items, clippy::module_name_repetitions, clippy::trivially_copy_pass_by_ref )] #![cfg_attr( test, allow(clippy::option_unwrap_used, clippy::result_unwrap_used) )] #[macro_use] extern crate alloc; #[cfg(test)] #[macro_use] extern crate std; pub use eosio_macros::{action, n, s, table}; mod abi; pub use self::abi::*; mod account; pub use self::account::AccountName; mod action; pub use self::action::{ Action, ActionFn, ActionName, PermissionLevel, PermissionName, }; mod asset; pub use self::asset::{Asset, ExtendedAsset}; mod binary_extension; pub use self::binary_extension::BinaryExtension; mod block; pub use self::block::*; mod blockchain_parameters; pub use self::blockchain_parameters::*; mod bytes; pub use self::bytes::{ DataStream, NumBytes, Read, ReadError, Write, WriteError, }; mod crypto; pub use self::crypto::{ Checksum160, Checksum256, Checksum512, PrivateKey, PublicKey, Signature, }; #[macro_use] mod name; pub use self::name::Name; pub use eosio_numstr::{ParseNameError, NAME_CHARS, NAME_MAX_LEN}; mod ops; pub use self::ops::{ CheckedAdd, CheckedDiv, CheckedMul, CheckedRem, CheckedSub, }; mod producer_schedule; pub use self::producer_schedule::*; mod resources; pub use self::resources::{CpuWeight, NetWeight, RamBytes}; mod symbol; pub use self::symbol::{ExtendedSymbol, Symbol, SymbolCode}; pub use eosio_numstr::{ ParseSymbolCodeError, ParseSymbolError, SYMBOL_CODE_CHARS, SYMBOL_CODE_MAX_LEN, }; mod table; pub use self::table::{ PrimaryTableIndex, ScopeName, SecondaryKey, SecondaryKeys, SecondaryTableIndex, SecondaryTableName, Table, TableName, }; mod time; pub use self::time::{BlockTimestamp, TimePoint, TimePointSec}; mod transaction; pub use self::transaction::{ Transaction, TransactionExtension, TransactionHeader, TransactionId, }; mod varint; pub use self::varint::{SignedInt, UnsignedInt};
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // pretty-expanded FIXME #23616 mod a { pub enum Enum<T> { A(T), } pub trait X { fn dummy(&self) { } } impl X for isize {} pub struct Z<'a>(Enum<&'a (X+'a)>); fn foo() { let x: isize = 42; let z = Z(Enum::A(&x as &X)); let _ = z; } } mod b { trait X { fn dummy(&self) { } } impl X for isize {} struct Y<'a>{ x:Option<&'a (X+'a)>, } fn bar() { let x: isize = 42; let _y = Y { x: Some(&x as &X) }; } } mod c { pub trait X { fn f(&self); } impl X for isize { fn f(&self) {} } pub struct Z<'a>(Option<&'a (X+'a)>); fn main() { let x: isize = 42; let z = Z(Some(&x as &X)); let _ = z; } } pub fn main() {}
use opengl_graphics::{Texture, GlGraphics}; use graphics::Context; use super::renderable::Renderable; use super::camera::CameraDependentObject; use super::config; pub struct Background { background_texture: Texture, foreground_texture: Texture, pub x: f64, y: f64, repeat: i8, width: f64, pub left: bool, pub right: bool, pub combined_width: f64 } impl Background { pub fn new(background_texture: Texture, foreground_texture: Texture, repeat: i8, width: f64) -> Background { Background { background_texture, foreground_texture, x: 0.0, y: 0.0, width, left: false, right: false, repeat, combined_width: width * repeat as f64 } } } impl Renderable for Background { fn render(&mut self, ctx: &Context, gl: &mut GlGraphics) { use graphics::*; for i in -1..self.repeat + 1 { let transform = ctx.transform.trans(self.x * config::BACKGROUND_PARRALAX_FACTOR + (self.width * i as f64), self.y); image(&self.background_texture, transform, gl); } for i in -1..self.repeat + 1 { let transform = ctx.transform.trans(self.x + (self.width * i as f64), self.y); image(&self.foreground_texture, transform, gl); } } } impl CameraDependentObject for Background { fn move_object(&mut self, x: f64, y: f64){ self.x += x; self.y += y; } }
// todo: encapsule use tokio::prelude::*; use tokio::net::TcpListener; #[allow(unused)] fn main() { // Bind the server's socket. let addr = "127.0.0.1:12345".parse().unwrap(); let listener = TcpListener::bind(&addr) .expect("unable to bind TCP listener"); // Pull out a stream of sockets for incoming connections let server = listener.incoming() .map_err(|e| eprintln!("accept failed = {:?}", e)) .for_each(|sock| { drop(sock); tokio::spawn(future::ok(())) }); // Start the Tokio runtime tokio::run(server); }
// 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. //! Raw resource use winapi::ID3D12Resource; use comptr::ComPtr; use error::WinError; use super::*; use format::Box3u; /// a raw resource #[derive(Clone, Debug)] pub struct RawResource { pub(crate) ptr: ComPtr<ID3D12Resource>, } impl RawResource { /// get resource description #[inline] pub fn get_desc(&mut self) -> ResourceDesc { unsafe { let mut ret = ::std::mem::uninitialized(); self.ptr.GetDesc(&mut ret); ::std::mem::transmute(ret) } } /// get the GPU virtual address for a buffer resource, `0` for texture resources #[inline] pub fn get_gpu_vaddress(&mut self) -> GpuVAddress { unsafe { GpuVAddress{ptr: self.ptr.GetGPUVirtualAddress()}} } /// attempt to get the attached heap's info. This method would only work /// on committed or placed resources, not on reserved ones. #[inline] pub fn get_heap_info(&mut self) -> Result<(HeapProperties, HeapFlags), WinError> { unsafe { let mut hp = ::std::mem::uninitialized(); let mut hf = ::std::mem::uninitialized(); let hr = self.ptr.GetHeapProperties(&mut hp, &mut hf); WinError::from_hresult_or_ok(hr, || ( ::std::mem::transmute(hp), ::std::mem::transmute(hf) )) } } /// get a CPU pointer to the specified subresource. [more info](https://msdn.microsoft.com/library/windows/desktop/dn788712(v=vs.85).aspx) pub unsafe fn map( &mut self, subresource: u32, range: Option<(usize, usize)> ) -> Result<*mut u8, WinError> { let mut d3drange: ::winapi::D3D12_RANGE = ::std::mem::uninitialized(); let prange = if let Some(range) = range { // assert!(range.0<=range.1); d3drange.Begin = range.0 as _; d3drange.End = range.1 as _; &d3drange as *const _ } else { ::std::ptr::null() }; let mut ret = ::std::mem::uninitialized(); let hr = self.ptr.Map(subresource, prange, &mut ret); WinError::from_hresult_or_ok(hr, || ret as *mut u8) } /// invalidates the CPU pointer to the specified subresource pub unsafe fn unmap( &mut self, subresource: u32, range: Option<(usize, usize)> ) { let mut d3drange: ::winapi::D3D12_RANGE = ::std::mem::uninitialized(); let prange = if let Some(range) = range { // assert!(range.0<=range.1); d3drange.Begin = range.0 as _; d3drange.End = range.1 as _; &d3drange as *const _ } else { ::std::ptr::null() }; self.ptr.Unmap(subresource, prange); } /// use CPU to copy data from a subresource pub unsafe fn read_from_subresource( &mut self, dst_desc: ResourceChunkDesc, src_subresource: u32, src_box: Option<&Box3u> ) -> Result<(), WinError> { let pbox = if let Some(src_box) = src_box { src_box as *const _ as *const ::winapi::D3D12_BOX } else { ::std::ptr::null() }; WinError::from_hresult( self.ptr.ReadFromSubresource( dst_desc.data as *mut u8 as *mut _, dst_desc.row_pitch, dst_desc.depth_pitch, src_subresource, pbox ) ) } /// use CPU to copy data into a subresource. [more info](https://msdn.microsoft.com/library/windows/desktop/dn914416(v=vs.85).aspx) pub unsafe fn write_to_subresource( &mut self, dst_subresource: u32, dst_box: Option<&Box3u>, src_desc: ResourceChunkDesc ) -> Result<(), WinError> { let pbox = if let Some(dst_box) = dst_box { dst_box as *const _ as *const ::winapi::D3D12_BOX } else { ::std::ptr::null() }; WinError::from_hresult( self.ptr.WriteToSubresource( dst_subresource, pbox, src_desc.data as *const u8 as *const _, src_desc.row_pitch, src_desc.depth_pitch ) ) } } /// describes a chunk of resource #[derive(Copy, Clone, Debug)] pub struct ResourceChunkDesc { /// pointer to the head of data pub data: *mut u8, /// distance from one row of data to the next pub row_pitch: u32, /// distance from one depth slice of data to the next pub depth_pitch: u32, } /// GPU virtual device #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct GpuVAddress { pub(crate) ptr: u64, } impl From<GpuVAddress> for ::winapi::D3D12_GPU_VIRTUAL_ADDRESS { #[inline] fn from(addr: GpuVAddress) -> Self { unsafe {::std::mem::transmute(addr)} } }
use eval::eval; use expr::Expr; use sample::signal::Signal; #[derive(Clone)] pub struct ExprSignal { pub time: i32, expression: Expr, } impl From<Expr> for ExprSignal { fn from(expr: Expr) -> ExprSignal { ExprSignal { time: 0, expression: expr, } } } impl Signal for ExprSignal { type Frame = [i8; 1]; fn next(&mut self) -> Self::Frame { if let Ok(x) = eval(self.time, &self.expression) { self.time +=1; [x as i8] } else { self.time += 1; [0] } } }
use crate::result::{KvsError, Result}; use crate::storage::{BatchStore, Store}; use sled::{Db, Tree}; use std::fmt::Display; /// Wrapper of `sled::Db` #[derive(Clone)] pub struct SledStore(Db); impl SledStore { /// Creates a `SledKvsEngine` from `sled::Db`. pub fn open(db: Db) -> Self { SledStore(db) } } impl Display for SledStore { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "sledstore") } } impl Store for SledStore { #[inline] fn get(&self, key: impl AsRef<[u8]>) -> Result<Option<Vec<u8>>> { let tree: &Tree = &self.0; let key = key.as_ref().to_owned(); if key.is_empty() { return Err(KvsError::EmptyKey); } Ok(tree.get(key)?.map(|i_vec| AsRef::<[u8]>::as_ref(&i_vec).to_vec())) } #[inline] fn set(&mut self, key: impl AsRef<[u8]>, value: impl AsRef<[u8]>) -> Result<()> { let tree: &Tree = &self.0; let key = key.as_ref().to_owned(); if key.is_empty() { return Err(KvsError::EmptyKey); } tree.insert(key, value.as_ref())?; tree.flush()?; Ok(()) } #[inline] fn remove(&mut self, key: impl AsRef<[u8]>) -> Result<()> { let tree: &Tree = &self.0; let key = key.as_ref().to_owned(); if key.is_empty() { return Err(KvsError::EmptyKey); } tree.remove(key)?; tree.flush()?; Ok(()) } #[inline] fn contains(&mut self, key: impl AsRef<[u8]>) -> Result<bool> { let tree: &Tree = &self.0; let key = key.as_ref().to_owned(); if key.is_empty() { return Err(KvsError::EmptyKey); } Ok(tree.contains_key(key)?) } } impl BatchStore for SledStore { #[inline] fn get_batch(&self, keys: impl AsRef<[Vec<u8>]>) -> Result<Vec<Option<Vec<u8>>>> { let tree: &Tree = &self.0; let keys = keys.as_ref().to_owned(); let values = keys .into_iter() .map(|key| tree.get(&key).ok()?.map(|i_vec| AsRef::<[u8]>::as_ref(&i_vec).to_vec())) .collect(); Ok(values) } #[inline] fn set_batch( &mut self, keys: impl AsRef<[Vec<u8>]>, values: impl AsRef<[Vec<u8>]>, ) -> Result<()> { let tree: &Tree = &self.0; let keys = keys.as_ref().to_owned(); let values = values.as_ref().to_owned(); if keys.len() != values.len() { return Err(KvsError::InvalidData( "The number of keys does not match the number of values".to_string(), )); } for i in 0..keys.len() { let key = keys[i].to_vec(); let value = values[i].to_vec(); tree.insert(key, value)?; } Ok(()) } #[inline] fn remove_batch(&mut self, keys: impl AsRef<[Vec<u8>]>) -> Result<()> { let tree: &Tree = &self.0; let keys = keys.as_ref().to_owned(); for key in keys { tree.remove(&key)?; } Ok(()) } }
fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let k: usize = rd.get(); let s: Vec<char> = rd.get_chars(); let t: Vec<char> = rd.get_chars(); let s: Vec<usize> = s[..4].iter().map(|&c| c as usize - '0' as usize).collect(); let t: Vec<usize> = t[..4].iter().map(|&c| c as usize - '0' as usize).collect(); let mut freq = vec![k; 10]; // freq[0] = 0; // for &x in &s { freq[x] -= 1; } for &x in &t { freq[x] -= 1; } fn calc(c: &[usize]) -> usize { assert_eq!(c.len(), 10); (1..=9).map(|i| i * 10usize.pow(c[i] as u32)).sum::<usize>() } let judge = |s5: usize, t5: usize| -> bool { let mut cs = vec![0; 10]; let mut ct = vec![0; 10]; for &x in &s { cs[x] += 1; } for &x in &t { ct[x] += 1; } cs[s5] += 1; ct[t5] += 1; calc(&cs) > calc(&ct) }; let mut ans = 0; for a in 1..=9 { if freq[a] == 0 { continue; } let choose_a = freq[a]; freq[a] -= 1; for b in 1..=9 { if freq[b] == 0 { continue; } let choose_b = freq[b]; freq[b] -= 1; if judge(a, b) { ans += choose_a * choose_b; } freq[b] += 1; } freq[a] += 1; } let denom = (k * 9 - 8) * (k * 9 - 9); let ans = ans as f64 / denom as f64; println!("{}", ans); } pub struct ProconReader<R> { r: R, l: String, i: usize, } impl<R: std::io::BufRead> ProconReader<R> { pub fn new(reader: R) -> Self { Self { r: reader, l: String::new(), i: 0, } } pub fn get<T>(&mut self) -> T where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug, { self.skip_blanks(); assert!(self.i < self.l.len()); // remain some character assert_ne!(&self.l[self.i..=self.i], " "); let rest = &self.l[self.i..]; let len = rest.find(' ').unwrap_or_else(|| rest.len()); // parse self.l[self.i..(self.i + len)] let val = rest[..len] .parse() .unwrap_or_else(|e| panic!("{:?}, attempt to read `{}`", e, rest)); self.i += len; val } fn skip_blanks(&mut self) { loop { match self.l[self.i..].find(|ch| ch != ' ') { Some(j) => { self.i += j; break; } None => { let mut buf = String::new(); let num_bytes = self .r .read_line(&mut buf) .unwrap_or_else(|_| panic!("invalid UTF-8")); assert!(num_bytes > 0, "reached EOF :("); self.l = buf .trim_end_matches('\n') .trim_end_matches('\r') .to_string(); self.i = 0; } } } } pub fn get_vec<T>(&mut self, n: usize) -> Vec<T> where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug, { (0..n).map(|_| self.get()).collect() } pub fn get_chars(&mut self) -> Vec<char> { self.get::<String>().chars().collect() } }
use crate::ui::screens::{menu::hook::*, notifications::*}; use oxygengine::{prelude::*, user_interface::raui::core::widget::WidgetId}; #[derive(Debug, Default)] pub struct GameState { camera: Option<Entity>, player: Option<Entity>, menu: Option<WidgetId>, notifications: Option<WidgetId>, change: Scalar, } impl State for GameState { fn on_enter(&mut self, world: &mut World) { // instantiate world objects from scene prefab. let camera = world .write_resource::<PrefabManager>() .instantiate_world("new-bark-town", world) .unwrap()[0]; self.camera = Some(camera); // instantiate player from prefab. let player = world .write_resource::<PrefabManager>() .instantiate_world("player", world) .unwrap()[0]; self.player = Some(player); // setup created player instance. world.read_resource::<LazyUpdate>().exec(move |world| { let mut transform = <CompositeTransform>::fetch(world, player); let pos = Vec2::new(16.0 * 12.0, 16.0 * 11.0); transform.set_translation(pos); }); } fn on_process(&mut self, world: &mut World) -> StateChange { if let (Some(player), Some(camera)) = (self.player, self.camera) { let mut transforms = world.write_storage::<CompositeTransform>(); // NOTE: REMEMBER THAT PREFABS ARE INSTANTIATED IN NEXT FRAME, SO THEY MIGHT NOT EXIST // AT FIRST SO HANDLE THAT. if let Some(player_transform) = transforms.get(player) { let player_position = player_transform.get_translation(); if let Some(camera_transform) = transforms.get_mut(camera) { camera_transform.set_translation(player_position); } } } let mut ui = world.write_resource::<UserInterfaceRes>(); if let Some(app) = ui.application_mut("") { for (caller, msg) in app.consume_signals() { if let Some(msg) = msg.as_any().downcast_ref::<NotificationSignal>() { match msg { NotificationSignal::Register => self.notifications = Some(caller), NotificationSignal::Unregister => { if let Some(id) = &self.notifications { if &caller == id { self.notifications = None; } } } _ => {} } } else if let Some(msg) = msg.as_any().downcast_ref::<MenuSignal>() { match msg { MenuSignal::Register => self.menu = Some(caller), MenuSignal::Unregister => { if let Some(id) = &self.menu { if &caller == id { self.menu = None; } } } _ => {} } } } let input = world.read_resource::<InputController>(); if input.trigger_or_default("escape") == TriggerState::Pressed { if let Some(id) = &self.menu { app.send_message(id, MenuSignal::Show); } } self.change -= world.read_resource::<AppLifeCycle>().delta_time_seconds(); if self.change <= 0.0 { self.change = 2.0 + rand::random::<Scalar>() * 10.0; if let Some(id) = &self.notifications { if rand::random() { app.send_message( id, NotificationSignal::Show(NotificationShow { text: "There is a fog somewhere in Wild Area".to_owned(), ..Default::default() }), ); } else { app.send_message( id, NotificationSignal::Show(NotificationShow { text: "Thanks for using RAUI".to_owned(), side: true, ..Default::default() }), ); } } } } StateChange::None } }
use crate::ray::Ray; use crate::{ rtweekend::degrees_to_radians, vec3::{random_in_unit_disk, Point3, Vec3}, }; #[derive(Clone, Copy, Debug)] pub struct Camera { origin: Point3, lower_left_corner: Point3, horizontal: Vec3, vertical: Vec3, u: Vec3, v: Vec3, w: Vec3, lens_radius: f64, } impl Camera { pub fn new( lookfrom: Point3, lookat: Point3, vup: Vec3, vfov: f64, aspect_ratio: f64, aperture: f64, focus_dist: f64, ) -> Self { let theta = degrees_to_radians(vfov); let h = (theta / 2.0).tan(); let viewport_height = 2.0 * h; let viewport_width = aspect_ratio * viewport_height; let ww = (lookfrom - lookat).unit(); let uu = vup.cross(ww).unit(); let vv = ww.cross(uu); Self { origin: lookfrom, horizontal: uu * viewport_width * focus_dist, vertical: vv * viewport_height * focus_dist, lower_left_corner: lookfrom - uu / 2.0 * viewport_width * focus_dist - vv / 2.0 * viewport_height * focus_dist - ww * focus_dist, u: uu, v: vv, w: ww, lens_radius: aperture / 2.0, } } pub fn get_ray(&self, s: f64, t: f64) -> Ray { let rd = random_in_unit_disk() * self.lens_radius; let offset = self.u * rd.x + self.v * rd.y; Ray { orig: self.origin + offset, dir: self.lower_left_corner + self.horizontal * s + self.vertical * t - self.origin - offset, } } }
#![warn(clippy::all)] #![warn(clippy::pedantic)] use std::collections::HashMap; fn main() { run(); } fn run() { let start = std::time::Instant::now(); // code goes here let mut collatz = Collatz::default(); let res = (1..1_000_000) .enumerate() .map(|(i, v)| (i, collatz.find(v))) .max_by_key(|p| p.1) .unwrap() .0 as u64 + 1; let span = start.elapsed().as_nanos(); println!("{} {}", res, span); } struct Collatz { memo: HashMap<u64, u64>, } impl Default for Collatz { fn default() -> Self { let mut hm = HashMap::new(); hm.insert(1, 1); Self { memo: hm } } } impl Collatz { fn find(&mut self, key: u64) -> u64 { if self.memo.contains_key(&key) { return *self.memo.get(&key).unwrap(); } let next = if key % 2 == 0 { key / 2 } else { 3 * key + 1 }; let val = 1 + self.find(next); self.memo.insert(key, val); val } }
pub fn hamming_distance(s1: &str, s2: &str) -> Result<usize, ()> { if s1.len() != s2.len() { return Err(()); } Ok(s1.chars() .zip(s2.chars()) .filter(|&(c1, c2)| c1 != c2) .count()) }
use std::fmt::Display; pub trait Drawable { fn update(&mut self); fn pause(&mut self); fn draw(&mut self); } pub trait Window: Drawable + Display {} impl <T: Drawable + Display> Window for T {}
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IPdfDocument(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPdfDocument { type Vtable = IPdfDocument_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xac7ebedd_80fa_4089_846e_81b77ff5a86c); } #[repr(C)] #[doc(hidden)] pub struct IPdfDocument_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pageindex: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPdfDocumentStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPdfDocumentStatics { type Vtable = IPdfDocumentStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x433a0b5f_c007_4788_90f2_08143d922599); } #[repr(C)] #[doc(hidden)] pub struct IPdfDocumentStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, file: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Storage")))] usize, #[cfg(all(feature = "Foundation", feature = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, file: ::windows::core::RawPtr, password: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Storage")))] usize, #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inputstream: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize, #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inputstream: ::windows::core::RawPtr, password: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPdfPage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPdfPage { type Vtable = IPdfPage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9db4b0c8_5320_4cfc_ad76_493fdad0e594); } #[repr(C)] #[doc(hidden)] pub struct IPdfPage_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, outputstream: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize, #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, outputstream: ::windows::core::RawPtr, options: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Size) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PdfPageRotation) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPdfPageDimensions(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPdfPageDimensions { type Vtable = IPdfPageDimensions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x22170471_313e_44e8_835d_63a3e7624a10); } #[repr(C)] #[doc(hidden)] pub struct IPdfPageDimensions_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Rect) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Rect) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Rect) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Rect) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Rect) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPdfPageRenderOptions(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPdfPageRenderOptions { type Vtable = IPdfPageRenderOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c98056f_b7cf_4c29_9a04_52d90267f425); } #[repr(C)] #[doc(hidden)] pub struct IPdfPageRenderOptions_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Rect) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Foundation::Rect) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::windows::core::HRESULT, #[cfg(feature = "UI")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::UI::Color) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI"))] usize, #[cfg(feature = "UI")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::UI::Color) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::GUID) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PdfDocument(pub ::windows::core::IInspectable); impl PdfDocument { pub fn GetPage(&self, pageindex: u32) -> ::windows::core::Result<PdfPage> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), pageindex, &mut result__).from_abi::<PdfPage>(result__) } } pub fn PageCount(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn IsPasswordProtected(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(all(feature = "Foundation", feature = "Storage"))] pub fn LoadFromFileAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::IStorageFile>>(file: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PdfDocument>> { Self::IPdfDocumentStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), file.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PdfDocument>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "Storage"))] pub fn LoadFromFileWithPasswordAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::IStorageFile>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(file: Param0, password: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PdfDocument>> { Self::IPdfDocumentStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), file.into_param().abi(), password.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PdfDocument>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub fn LoadFromStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IRandomAccessStream>>(inputstream: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PdfDocument>> { Self::IPdfDocumentStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), inputstream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PdfDocument>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub fn LoadFromStreamWithPasswordAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IRandomAccessStream>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(inputstream: Param0, password: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PdfDocument>> { Self::IPdfDocumentStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), inputstream.into_param().abi(), password.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PdfDocument>>(result__) }) } pub fn IPdfDocumentStatics<R, F: FnOnce(&IPdfDocumentStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PdfDocument, IPdfDocumentStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PdfDocument { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Data.Pdf.PdfDocument;{ac7ebedd-80fa-4089-846e-81b77ff5a86c})"); } unsafe impl ::windows::core::Interface for PdfDocument { type Vtable = IPdfDocument_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xac7ebedd_80fa_4089_846e_81b77ff5a86c); } impl ::windows::core::RuntimeName for PdfDocument { const NAME: &'static str = "Windows.Data.Pdf.PdfDocument"; } impl ::core::convert::From<PdfDocument> for ::windows::core::IUnknown { fn from(value: PdfDocument) -> Self { value.0 .0 } } impl ::core::convert::From<&PdfDocument> for ::windows::core::IUnknown { fn from(value: &PdfDocument) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PdfDocument { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PdfDocument { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PdfDocument> for ::windows::core::IInspectable { fn from(value: PdfDocument) -> Self { value.0 } } impl ::core::convert::From<&PdfDocument> for ::windows::core::IInspectable { fn from(value: &PdfDocument) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PdfDocument { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PdfDocument { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PdfDocument {} unsafe impl ::core::marker::Sync for PdfDocument {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PdfPage(pub ::windows::core::IInspectable); impl PdfPage { #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub fn RenderToStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IRandomAccessStream>>(&self, outputstream: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), outputstream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub fn RenderWithOptionsToStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IRandomAccessStream>, Param1: ::windows::core::IntoParam<'a, PdfPageRenderOptions>>(&self, outputstream: Param0, options: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), outputstream.into_param().abi(), options.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "Foundation")] pub fn PreparePageAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } pub fn Index(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } #[cfg(feature = "Foundation")] pub fn Size(&self) -> ::windows::core::Result<super::super::Foundation::Size> { let this = self; unsafe { let mut result__: super::super::Foundation::Size = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Size>(result__) } } pub fn Dimensions(&self) -> ::windows::core::Result<PdfPageDimensions> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PdfPageDimensions>(result__) } } pub fn Rotation(&self) -> ::windows::core::Result<PdfPageRotation> { let this = self; unsafe { let mut result__: PdfPageRotation = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PdfPageRotation>(result__) } } pub fn PreferredZoom(&self) -> ::windows::core::Result<f32> { let this = self; unsafe { let mut result__: f32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f32>(result__) } } #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } } unsafe impl ::windows::core::RuntimeType for PdfPage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Data.Pdf.PdfPage;{9db4b0c8-5320-4cfc-ad76-493fdad0e594})"); } unsafe impl ::windows::core::Interface for PdfPage { type Vtable = IPdfPage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9db4b0c8_5320_4cfc_ad76_493fdad0e594); } impl ::windows::core::RuntimeName for PdfPage { const NAME: &'static str = "Windows.Data.Pdf.PdfPage"; } impl ::core::convert::From<PdfPage> for ::windows::core::IUnknown { fn from(value: PdfPage) -> Self { value.0 .0 } } impl ::core::convert::From<&PdfPage> for ::windows::core::IUnknown { fn from(value: &PdfPage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PdfPage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PdfPage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PdfPage> for ::windows::core::IInspectable { fn from(value: PdfPage) -> Self { value.0 } } impl ::core::convert::From<&PdfPage> for ::windows::core::IInspectable { fn from(value: &PdfPage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PdfPage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PdfPage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<PdfPage> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: PdfPage) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&PdfPage> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &PdfPage) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for PdfPage { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &PdfPage { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for PdfPage {} unsafe impl ::core::marker::Sync for PdfPage {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PdfPageDimensions(pub ::windows::core::IInspectable); impl PdfPageDimensions { #[cfg(feature = "Foundation")] pub fn MediaBox(&self) -> ::windows::core::Result<super::super::Foundation::Rect> { let this = self; unsafe { let mut result__: super::super::Foundation::Rect = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Rect>(result__) } } #[cfg(feature = "Foundation")] pub fn CropBox(&self) -> ::windows::core::Result<super::super::Foundation::Rect> { let this = self; unsafe { let mut result__: super::super::Foundation::Rect = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Rect>(result__) } } #[cfg(feature = "Foundation")] pub fn BleedBox(&self) -> ::windows::core::Result<super::super::Foundation::Rect> { let this = self; unsafe { let mut result__: super::super::Foundation::Rect = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Rect>(result__) } } #[cfg(feature = "Foundation")] pub fn TrimBox(&self) -> ::windows::core::Result<super::super::Foundation::Rect> { let this = self; unsafe { let mut result__: super::super::Foundation::Rect = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Rect>(result__) } } #[cfg(feature = "Foundation")] pub fn ArtBox(&self) -> ::windows::core::Result<super::super::Foundation::Rect> { let this = self; unsafe { let mut result__: super::super::Foundation::Rect = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Rect>(result__) } } } unsafe impl ::windows::core::RuntimeType for PdfPageDimensions { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Data.Pdf.PdfPageDimensions;{22170471-313e-44e8-835d-63a3e7624a10})"); } unsafe impl ::windows::core::Interface for PdfPageDimensions { type Vtable = IPdfPageDimensions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x22170471_313e_44e8_835d_63a3e7624a10); } impl ::windows::core::RuntimeName for PdfPageDimensions { const NAME: &'static str = "Windows.Data.Pdf.PdfPageDimensions"; } impl ::core::convert::From<PdfPageDimensions> for ::windows::core::IUnknown { fn from(value: PdfPageDimensions) -> Self { value.0 .0 } } impl ::core::convert::From<&PdfPageDimensions> for ::windows::core::IUnknown { fn from(value: &PdfPageDimensions) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PdfPageDimensions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PdfPageDimensions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PdfPageDimensions> for ::windows::core::IInspectable { fn from(value: PdfPageDimensions) -> Self { value.0 } } impl ::core::convert::From<&PdfPageDimensions> for ::windows::core::IInspectable { fn from(value: &PdfPageDimensions) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PdfPageDimensions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PdfPageDimensions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PdfPageDimensions {} unsafe impl ::core::marker::Sync for PdfPageDimensions {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PdfPageRenderOptions(pub ::windows::core::IInspectable); impl PdfPageRenderOptions { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PdfPageRenderOptions, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn SourceRect(&self) -> ::windows::core::Result<super::super::Foundation::Rect> { let this = self; unsafe { let mut result__: super::super::Foundation::Rect = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Rect>(result__) } } #[cfg(feature = "Foundation")] pub fn SetSourceRect<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn DestinationWidth(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn SetDestinationWidth(&self, value: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() } } pub fn DestinationHeight(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn SetDestinationHeight(&self, value: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "UI")] pub fn BackgroundColor(&self) -> ::windows::core::Result<super::super::UI::Color> { let this = self; unsafe { let mut result__: super::super::UI::Color = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::UI::Color>(result__) } } #[cfg(feature = "UI")] pub fn SetBackgroundColor<'a, Param0: ::windows::core::IntoParam<'a, super::super::UI::Color>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn IsIgnoringHighContrast(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetIsIgnoringHighContrast(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() } } pub fn BitmapEncoderId(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = self; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn SetBitmapEncoderId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for PdfPageRenderOptions { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Data.Pdf.PdfPageRenderOptions;{3c98056f-b7cf-4c29-9a04-52d90267f425})"); } unsafe impl ::windows::core::Interface for PdfPageRenderOptions { type Vtable = IPdfPageRenderOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c98056f_b7cf_4c29_9a04_52d90267f425); } impl ::windows::core::RuntimeName for PdfPageRenderOptions { const NAME: &'static str = "Windows.Data.Pdf.PdfPageRenderOptions"; } impl ::core::convert::From<PdfPageRenderOptions> for ::windows::core::IUnknown { fn from(value: PdfPageRenderOptions) -> Self { value.0 .0 } } impl ::core::convert::From<&PdfPageRenderOptions> for ::windows::core::IUnknown { fn from(value: &PdfPageRenderOptions) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PdfPageRenderOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PdfPageRenderOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PdfPageRenderOptions> for ::windows::core::IInspectable { fn from(value: PdfPageRenderOptions) -> Self { value.0 } } impl ::core::convert::From<&PdfPageRenderOptions> for ::windows::core::IInspectable { fn from(value: &PdfPageRenderOptions) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PdfPageRenderOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PdfPageRenderOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PdfPageRenderOptions {} unsafe impl ::core::marker::Sync for PdfPageRenderOptions {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PdfPageRotation(pub i32); impl PdfPageRotation { pub const Normal: PdfPageRotation = PdfPageRotation(0i32); pub const Rotate90: PdfPageRotation = PdfPageRotation(1i32); pub const Rotate180: PdfPageRotation = PdfPageRotation(2i32); pub const Rotate270: PdfPageRotation = PdfPageRotation(3i32); } impl ::core::convert::From<i32> for PdfPageRotation { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PdfPageRotation { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PdfPageRotation { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Data.Pdf.PdfPageRotation;i4)"); } impl ::windows::core::DefaultType for PdfPageRotation { type DefaultType = Self; }
//! Provides the input struct. use shape::coord::Coord; use shape::polygon::Polygon; /// The input for deserialization. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Input { /// The start of the path. pub start: Coord, /// The end of the path. pub end: Coord, /// Points that must be passed in order from start to end. #[serde(default = "Vec::new")] pub route: Vec<Coord>, /// The polygons that block the path. #[serde(rename = "polygon", default = "Vec::new")] pub polygons: Vec<Polygon>, }
use mode_map::ModeMap; use op::{NormalOp, PendingOp, InsertOp}; use typeahead::{Parse, RemapType, Typeahead}; use client; use xrl; pub struct State<K> where K: Ord, K: Copy, K: Parse, { pub typeahead: Typeahead<K>, pub normal_mode_map: ModeMap<K, NormalOp>, pub pending_mode_map: ModeMap<K, PendingOp>, pub insert_mode_map: ModeMap<K, InsertOp>, pub count: i32, // Used when an op is to be performed [count] times. pub view_id: xrl::ViewId, pub client: Box<client::Client>, } impl<K> State<K> where K: Ord, K: Copy, K: Parse, { pub fn new( client: Box<client::Client>, normal_map: ModeMap<K, NormalOp>, pending_map: ModeMap<K, PendingOp>, insert_map: ModeMap<K, InsertOp>, ) -> Self { State { typeahead: Typeahead::<K>::new(), normal_mode_map: normal_map, pending_mode_map: pending_map, insert_mode_map: insert_map, count: 1, view_id: xrl::ViewId(0), // TODO pass this in client: client, } } /// Add a key to the typeahead buffer for processing. pub fn put(&mut self, key: K, remap_type: RemapType) { self.typeahead.push_back(key, remap_type); } /// Clear state variables. Used when an `<Esc>` is encountered. pub fn cancel(&mut self) { self.count = 1; self.typeahead.clear(); } }
//! Provides the Polygon struct. use shape::coord::Coord; use shape::segment::Segment; /// Represents a polygon. #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Hash)] pub struct Polygon { /// The set a points that make up the polygon, ordered counterclockwise. #[serde(rename = "point")] pub points: Vec<Coord>, } impl Polygon { /// Returns a vector of the segments that make up the polygon. pub fn segments(&self) -> Vec<Segment> { let cycleiter = self.points.iter().chain(self.points.iter().take(1)); let cycleiter2 = self.points.iter().chain(self.points.iter().take(2)).skip(1); let edges = cycleiter .zip(cycleiter2) .map(|(&a, &b)| Segment::from_coords(a, b)); edges.collect::<Vec<_>>() } }
use colour::BLACK; use point::Point; use image::Rgb; use complex::Complex; const MAX_ITERS: u32 = 512; use image::Luma; use image::Pixel; use std::u8; enum MandelbrotResult { ProbablyInSet, NotInSet(u32) } fn assess_mandelbrot_membership(c: Complex) -> MandelbrotResult { let mut z = c; for iteration in 0..MAX_ITERS { // TODO further research on this part if (z.re * z.re) + (z.im * z.im) > 4.0 { // If |z| > 2, but without expensive sqrt return MandelbrotResult::NotInSet(iteration); } z = (z * z) + c; } return MandelbrotResult::ProbablyInSet; } pub fn paint_mandelbrot(p: Point) -> Rgb<u8> { match assess_mandelbrot_membership(Complex::new(p.x, p.y)) { MandelbrotResult::ProbablyInSet => BLACK, MandelbrotResult::NotInSet(iterations) => { Luma::<u8>([u8::MAX - (iterations * u8::MAX as u32 / MAX_ITERS) as u8]).to_rgb() } } }
use crate::marker_type::NonOwningPhantom; use std::fmt::{self,Debug}; /// Type-level equivalent of the `Option::None` variant. #[derive(Debug,Copy,Clone)] pub struct None_; pub struct Some_<T>(NonOwningPhantom<T>); /////////////////////////////////////////////////////////////// impl None_{ pub const NEW:Self=None_; pub const fn new()->Self{ Self::NEW } } /////////////////////////////////////////////////////////////// /// Type-level equivalent of the `Option::Some` variant. impl<T> Some_<T>{ pub const NEW:Self=Some_(NonOwningPhantom::NEW); pub const fn new()->Self{ Self::NEW } } impl<T> Default for Some_<T>{ fn default()->Self{ Self::NEW } } impl<T> Debug for Some_<T>{ fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ Debug::fmt("Some_",f) } } impl<T> Copy for Some_<T>{} impl<T> Clone for Some_<T>{ fn clone(&self)->Self{ Self::NEW } } /////////////////////////////////////////////////////////////// mod sealed { use super::*; pub trait Sealed {} impl Sealed for None_{} impl<T> Sealed for Some_<T>{} } use self::sealed::Sealed; /////////////////////////////////////////////////////////////// /// Type-level equivalent of `Option`. /// /// This trait is sealed and can only be implemente in the abi_stable crate. pub trait OptionType:Sealed{} impl OptionType for None_{} impl<T> OptionType for Some_<T>{} /////////////////////////////////////////////////////////////// /// To require `None_` in generic contexts. pub trait NoneTrait:OptionType{} /// To require `Some_<_>` in generic contexts. pub trait SomeTrait:OptionType{ type Value; } impl NoneTrait for None_{} impl<T> SomeTrait for Some_<T>{ type Value=T; } ////////////////////////////////////////////////////////////// /// Type-level equivalent of `Option::unwrap_or`. pub trait UnwrapOr_<Default_>:OptionType{ type Output; } /// Type-level equivalent of `Option::unwrap_or`. pub type UnwrapOr<This,Default_>= <This as UnwrapOr_<Default_>>::Output; impl<Default_> UnwrapOr_<Default_> for None_{ type Output=Default_; } impl<T,Default_> UnwrapOr_<Default_> for Some_<T>{ type Output=T; } //////////////////////////////////////////////////////////////
// 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::Debug; use core::ops::Bound; use core::ops::Range; use std::collections::BTreeMap; use super::range_map_key::RangeMapKey; #[derive(Clone, Debug, Default)] pub struct RangeMap<RV, ID, V> { pub(crate) map: BTreeMap<RangeMapKey<RV, ID>, V>, } impl<RV, ID, V> RangeMap<RV, ID, V> where RV: Ord + Clone + Debug, ID: Ord + Clone + Debug + Default, { pub fn new() -> Self { RangeMap { map: BTreeMap::new(), } } pub fn insert(&mut self, range: Range<RV>, id: ID, val: V) { assert!(range.start <= range.end); let range_key: RangeMapKey<RV, ID> = RangeMapKey::new(range, id); self.map.insert(range_key, val); } // Return a vector of `RangeKey` which contain the point in the [start, end). // If we have range [1,5],[2,4],[2,6], then: // 1. `get_by_point(1)` return [1,5] // 2. `get_by_point(2)` return [1,5],[2,4],[2,6] // 3. `get_by_point(5)` return [2,4],[2,6] // Use the default key when construct `RangeKey::key` for search. pub fn get_by_point(&self, point: &RV) -> Vec<(&RangeMapKey<RV, ID>, &V)> { let key = point.clone(); let range_key = RangeMapKey::new(key.clone()..key.clone(), ID::default()); self.map .range((Bound::Included(range_key), Bound::Unbounded)) .filter(|e| e.0.range.start <= key) .collect() } pub fn remove(&mut self, range: Range<RV>, id: ID) { self.map.remove(&RangeMapKey::new(range, id)); } pub fn remove_by_key(&mut self, key: &RangeMapKey<RV, ID>) { self.map.remove(key); } /// Returns an iterator of all keys. /// /// A RangeMapKey includes the range and the identity. pub fn keys(&self) -> impl Iterator<Item = &RangeMapKey<RV, ID>> { self.map.keys() } /// Returns an iterator of all values. pub fn values(&self) -> impl Iterator<Item = &V> { self.map.values() } /// Returns an iterator of all key-values. pub fn iter(&self) -> impl Iterator<Item = (&RangeMapKey<RV, ID>, &V)> { self.map.iter() } } #[cfg(test)] mod tests { use crate::rangemap::RangeMap; use crate::rangemap::RangeMapKey; #[test] fn test_range_set() { // test get_by_point for i32 { let mut a = RangeMap::new(); let r11 = (&RangeMapKey::new(1..1, 11), &11); let r15 = (&RangeMapKey::new(1..5, 15), &15); let r24 = (&RangeMapKey::new(2..4, 24), &24); let r26 = (&RangeMapKey::new(2..6, 26), &26); a.insert(1..1, 11, 11); a.insert(1..5, 15, 15); a.insert(2..4, 24, 24); a.insert(2..6, 26, 26); assert_eq!(a.get_by_point(&1), vec![r11, r15]); assert_eq!(a.get_by_point(&2), vec![r24, r15, r26]); assert_eq!(a.get_by_point(&5), vec![r26]); a.remove(1..5, 15); assert_eq!(a.get_by_point(&1), vec![r11]); assert_eq!(a.get_by_point(&2), vec![r24, r26]); } // test get_by_point for String { let mut a = RangeMap::new(); let a1 = "1".to_string(); let a2 = "2".to_string(); let a4 = "4".to_string(); let a5 = "5".to_string(); let a6 = "6".to_string(); let r11 = (&RangeMapKey::new(a1.clone()..a1.clone(), 11), &11); let r15 = (&RangeMapKey::new(a1.clone()..a5.clone(), 15), &15); let r24 = (&RangeMapKey::new(a2.clone()..a4.clone(), 24), &24); let r26 = (&RangeMapKey::new(a2.clone()..a6.clone(), 26), &26); a.insert(a1.clone()..a1.clone(), 11, 11); a.insert(a1.clone()..a5.clone(), 15, 15); a.insert(a2.clone()..a4, 24, 24); a.insert(a2.clone()..a6, 26, 26); assert_eq!(a.get_by_point(&a1), vec![r11, r15]); assert_eq!(a.get_by_point(&a2), vec![r24, r15, r26]); assert_eq!(a.get_by_point(&a5), vec![r26]); a.remove(a1.clone()..a5, 15); assert_eq!(a.get_by_point(&a1), vec![r11]); assert_eq!(a.get_by_point(&a2), vec![r24, r26]); } // test get_by_point for string prefix { let mut a = RangeMap::new(); let a1 = "11".to_string(); let a2 = "12".to_string(); a.insert(a1..a2, 11, 11); assert!(!a.get_by_point(&"11".to_string()).is_empty()); assert!(!a.get_by_point(&"111".to_string()).is_empty()); assert!(!a.get_by_point(&"11z".to_string()).is_empty()); assert!(!a.get_by_point(&"11/".to_string()).is_empty()); assert!(!a.get_by_point(&"11*".to_string()).is_empty()); assert!(a.get_by_point(&"12".to_string()).is_empty()); } // test get_by_point for char upbound limit string prefix { let mut a = RangeMap::new(); let a1 = format!("{}", 255 as char); let a2 = format!("{}{}", 255 as char, 255 as char); a.insert(a1..a2, 11, 11); assert!(!a.get_by_point(&format!("{}", 255 as char)).is_empty()); assert!(!a.get_by_point(&format!("{}z", 255 as char)).is_empty()); assert!(!a.get_by_point(&format!("{}/", 255 as char)).is_empty()); assert!(!a.get_by_point(&format!("{}*", 255 as char)).is_empty()); } // test get_by_point for char upbound limit string prefix { let mut a = RangeMap::new(); let a1 = "1".to_string(); let a2 = format!("{}{}", a1, 255 as char); a.insert(a1.clone()..a2, 11, 11); assert!(!a.get_by_point(&a1).is_empty()); assert!(!a.get_by_point(&format!("{}z", a1)).is_empty()); assert!(!a.get_by_point(&format!("{}*", a1)).is_empty()); assert!(!a.get_by_point(&format!("{}/", a1)).is_empty()); } } #[test] fn test_range_iter() { let mut a = RangeMap::new(); a.insert(1..1, 11, 11); a.insert(1..5, 15, 15); a.insert(2..4, 24, 24); a.insert(2..6, 26, 26); let r1 = RangeMapKey::new(1..1, 11); let r2 = RangeMapKey::new(2..4, 24); let r3 = RangeMapKey::new(1..5, 15); let r4 = RangeMapKey::new(2..6, 26); // keys() { let got = a.keys().collect::<Vec<_>>(); let want = vec![&r1, &r2, &r3, &r4]; assert_eq!(want, got); } // values() { let got = a.values().collect::<Vec<_>>(); let want = vec![&11, &24, &15, &26]; assert_eq!(want, got); } // iter() { let got = a.iter().collect::<Vec<_>>(); let want = vec![(&r1, &11), (&r2, &24), (&r3, &15), (&r4, &26)]; assert_eq!(want, got); } } }
use std::ops::Drop; use std::os::raw::{c_int, c_void}; pub type LamePtr = *mut c_void; #[link(name = "mp3lame")] extern "C" { pub fn lame_init() -> LamePtr; pub fn lame_close(ptr: LamePtr) -> c_int; pub fn lame_set_in_samplerate(ptr: LamePtr, in_samplerate: c_int) -> c_int; pub fn lame_get_in_samplerate(ptr: LamePtr) -> c_int; pub fn lame_set_out_samplerate(ptr: LamePtr, out_samplerate: c_int) -> c_int; pub fn lame_get_out_samplerate(ptr: LamePtr) -> c_int; pub fn lame_set_num_channels(ptr: LamePtr, channels: c_int) -> c_int; pub fn lame_get_num_channels(ptr: LamePtr) -> c_int; pub fn lame_set_quality(ptr: LamePtr, quality: c_int) -> c_int; pub fn lame_get_quality(ptr: LamePtr) -> c_int; pub fn lame_set_brate(ptr: LamePtr, brate: c_int) -> c_int; pub fn lame_get_brate(ptr: LamePtr) -> c_int; pub fn lame_init_params(ptr: LamePtr) -> c_int; pub fn lame_encode_buffer( ptr: LamePtr, leftpcm: *const i16, rightpcm: *const i16, num_samples: c_int, mp3buffer: *mut u8, mp3buffer_size: c_int, ) -> c_int; } #[derive(Debug)] pub enum Error { GenericError, NoMem, BadBitRate, BadSampleFreq, InternalError, Unknown(c_int), } fn int_to_result(ret: c_int) -> Result<(), Error> { match ret { 0 => Ok(()), -1 => Err(Error::GenericError), -10 => Err(Error::NoMem), -11 => Err(Error::BadBitRate), -12 => Err(Error::BadSampleFreq), -13 => Err(Error::InternalError), err => Err(Error::Unknown(err)), } } pub struct Lame { ptr: LamePtr, } impl Lame { pub fn init() -> Result<Lame, Error> { let ctx = unsafe { lame_init() }; if ctx.is_null() { panic!("lame_init() returned null"); } int_to_result(unsafe { lame_init_params(ctx) })?; Ok(Lame { ptr: ctx }) } pub fn samplerate_in(&self) -> i32 { unsafe { lame_get_in_samplerate(self.ptr) as i32 } } pub fn set_samplerate_in(&mut self, sample_rate: i32) -> Result<(), Error> { int_to_result(unsafe { lame_set_in_samplerate(self.ptr, sample_rate as c_int) }) } pub fn samplerate_out(&self) -> i32 { unsafe { lame_get_out_samplerate(self.ptr) as i32 } } pub fn set_samplerate_out(&mut self, sample_rate: i32) -> Result<(), Error> { int_to_result(unsafe { lame_set_out_samplerate(self.ptr, sample_rate as c_int) }) } pub fn set_samplerate(&mut self, sample_rate: i32) -> Result<(), Error> { self.set_samplerate_in(sample_rate) .and_then(|_| self.set_samplerate_out(sample_rate)) } pub fn channels(&self) -> i32 { unsafe { lame_get_num_channels(self.ptr) as i32 } } pub fn set_channels(&mut self, channels: u8) -> Result<(), Error> { int_to_result(unsafe { lame_set_num_channels(self.ptr, channels as c_int) }) } pub fn quality(&self) -> i32 { unsafe { lame_get_quality(self.ptr) as i32 } } pub fn set_quality(&mut self, quality: i32) -> Result<(), Error> { int_to_result(unsafe { lame_set_quality(self.ptr, quality as c_int) }) } pub fn kilobitrate(&self) -> i32 { unsafe { lame_get_brate(self.ptr) as i32 } } pub fn set_kilobitrate(&mut self, quality: i32) -> Result<(), Error> { int_to_result(unsafe { lame_set_brate(self.ptr, quality as c_int) }) } pub fn encode(&mut self, pcm_left: &[i16], pcm_right: &[i16]) -> Result<Vec<u8>, i32> { if pcm_left.len() != pcm_right.len() { panic!( "The number of left and right channel must be same\n left: {}\n right: {}", pcm_left.len(), pcm_right.len() ); } let mut mp3_buffer = Vec::new(); mp3_buffer.resize(pcm_left.len(), 0); let ret = unsafe { lame_encode_buffer( self.ptr, pcm_left.as_ptr(), pcm_right.as_ptr(), pcm_left.len() as c_int, mp3_buffer.as_mut_ptr(), mp3_buffer.len() as c_int, ) }; match ret { size if size >= 0 => { mp3_buffer.resize(size as usize, 0); Ok(mp3_buffer) } err => Err(err as i32), } } pub fn encode_mono(&mut self, pcm: &[i16]) -> Result<Vec<u8>, i32> { self.encode(pcm, pcm) } } impl Drop for Lame { fn drop(&mut self) { unsafe { lame_close(self.ptr) }; } }
use std::cmp::Reverse; use std::collections::{BinaryHeap, HashMap}; use std::mem::size_of; use std::ops::{Index, IndexMut}; use std::{f64, usize}; use crate::env::{Direction, Vec2D, HAZARD_DAMAGE}; use crate::util::OrdPair; #[derive(Clone, Copy, PartialEq, Eq)] #[repr(u8)] pub enum CellT { Free, Food, Owned, } /// Represents a single tile of the board #[derive(Clone, Copy, PartialEq, Eq)] pub struct Cell { pub t: CellT, pub hazard: bool, } const _: () = assert!(size_of::<Cell>() == 2); impl Cell { pub const fn new(t: CellT, hazard: bool) -> Self { Self { t, hazard } } } impl std::fmt::Debug for Cell { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use owo_colors::{OwoColorize, Style}; let style = if self.hazard { Style::new().on_bright_black() } else { Style::new() }; match self.t { CellT::Free => write!(f, "{}", "X".blue().style(style)), CellT::Food => write!(f, "{}", "o".red().style(style)), CellT::Owned => write!(f, "{}", ".".style(style)), } } } /// The board representation as grid of free and occupied cells. /// /// This is allows fast access to specific positions on the grid and /// if they are occupied by enemies or food. #[derive(Clone)] pub struct Grid { pub width: usize, pub height: usize, pub cells: Vec<Cell>, } impl Grid { /// Creates a new grid with the provided dimensions. #[must_use] pub fn new(width: usize, height: usize) -> Self { Self { width, height, cells: vec![Cell::new(CellT::Free, false); width * height], } } /// Creates a grid from a `cells` buffer. /// If the buffer is not dividable by `height` the buffer is truncated /// accordingly. #[must_use] pub fn from(mut cells: Vec<Cell>, height: usize) -> Self { let width = cells.len() / height; cells.truncate(width * height); Self { width, height, cells, } } /// Clears the grid. pub fn clear(&mut self) { for c in &mut self.cells { *c = Cell::new(CellT::Food, false); } } /// Adds the snakes as obstacles to the grid. pub fn add_snake(&mut self, body: impl Iterator<Item = Vec2D>) { for p in body { if self.has(p) { self[p].t = CellT::Owned; } } } /// Adds the provided food to the grid. pub fn add_food(&mut self, food: &[Vec2D]) { for &p in food { if self.has(p) { self[p].t = CellT::Food; } } } /// Adds the provided hazards to the grid. pub fn add_hazards(&mut self, hazards: &[Vec2D]) { for &p in hazards { if self.has(p) { self[p].hazard = true; } } } /// Returns if the cell is hazardous. pub fn is_hazardous(&self, p: Vec2D) -> bool { self.has(p) && self[p].hazard } /// Returns if `p` is within the boundaries of this grid. #[inline] pub fn has(&self, p: Vec2D) -> bool { p.within(self.width, self.height) } /// Performes an A* search that applies the `first_move_heuristic` as /// additional costs for the first move. #[must_use] pub fn a_star( &self, start: Vec2D, target: Vec2D, first_move_heuristic: &[f64; 4], ) -> Option<Vec<Vec2D>> { fn make_path(data: &HashMap<Vec2D, (Vec2D, f64)>, target: Vec2D) -> Vec<Vec2D> { let mut path = Vec::new(); let mut p = target; while p.x >= 0 { path.push(p); p = data.get(&p).unwrap().0; } path.reverse(); path } let mut queue = BinaryHeap::new(); let mut data: HashMap<Vec2D, (Vec2D, f64)> = HashMap::new(); data.insert(start, (Vec2D::new(-1, -1), 0.0)); queue.push(OrdPair(Reverse(0), start)); while let Some(OrdPair(_, front)) = queue.pop() { let cost = data.get(&front).unwrap().1; if front == target { return Some(make_path(&data, target)); } for d in Direction::iter() { let neighbor = front.apply(d); let mut neighbor_cost = cost + 1.0; if self.is_hazardous(neighbor) { neighbor_cost += HAZARD_DAMAGE as f64; } if front == start { neighbor_cost += first_move_heuristic[d as usize]; } if self.has(neighbor) && self[neighbor].t != CellT::Owned { let cost_so_far = data.get(&neighbor).map_or(f64::MAX, |(_, c)| *c); if neighbor_cost < cost_so_far { data.insert(neighbor, (front, neighbor_cost)); // queue does not accept float let estimated_cost = neighbor_cost + (neighbor - start).manhattan() as f64; queue.push(OrdPair(Reverse((estimated_cost * 10.0) as usize), neighbor)); } } } } None } } impl Index<Vec2D> for Grid { type Output = Cell; fn index(&self, p: Vec2D) -> &Self::Output { assert!(0 <= p.x && p.x < self.width as _); assert!(0 <= p.y && p.y < self.height as _); &self.cells[(p.x as usize + p.y as usize * self.width) as usize] } } impl IndexMut<Vec2D> for Grid { fn index_mut(&mut self, p: Vec2D) -> &mut Self::Output { assert!(0 <= p.x && p.x < self.width as _); assert!(0 <= p.y && p.y < self.height as _); &mut self.cells[(p.x as usize + p.y as usize * self.width) as usize] } } impl std::fmt::Debug for Grid { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!(f, "Grid {{")?; for y in (0..self.height as i16).rev() { write!(f, " ")?; for x in 0..self.width as i16 { write!(f, "{:?} ", self[Vec2D::new(x, y)])?; } writeln!(f)?; } write!(f, "}}")?; Ok(()) } } #[cfg(test)] mod test { use crate::logging; use log::info; #[test] fn grid_a_star() { use super::*; logging(); let grid = Grid::new(11, 11); let path = grid .a_star(Vec2D::new(0, 0), Vec2D::new(1, 1), &[1.0, 0.0, 0.0, 0.0]) .unwrap(); info!("{:?}", path); assert_eq!(path.len(), 3); assert_eq!(path[0], Vec2D::new(0, 0)); assert_eq!(path[2], Vec2D::new(1, 1)); } #[test] fn grid_a_star_hazards() { use super::*; logging(); let mut grid = Grid::new(5, 5); grid.add_hazards(&[ Vec2D::new(2, 0), Vec2D::new(2, 1), Vec2D::new(2, 2), Vec2D::new(2, 3), ]); let path = grid .a_star(Vec2D::new(0, 2), Vec2D::new(4, 2), &[1.0, 1.0, 1.0, 1.0]) .unwrap(); info!("{:?}", path); assert_eq!(path.len(), 9); assert_eq!(path[0], Vec2D::new(0, 2)); assert_eq!(path[path.len() - 1], Vec2D::new(4, 2)); } }
//! Binary format for varisat proofs. use std::io::{self, BufRead, Write}; use anyhow::Error; use varisat_formula::{Lit, Var}; use crate::vli_enc::{read_u64, write_u64}; use super::{ClauseHash, DeleteClauseProof, ProofStep}; macro_rules! step_codes { ($counter:expr, $name:ident, ) => { const $name: u64 = $counter; }; ($counter:expr, $name:ident, $($names:ident),* ,) => { const $name: u64 = $counter; step_codes!($counter + 1, $($names),* ,); }; } step_codes!( 0, CODE_SOLVER_VAR_NAME_UPDATE, CODE_SOLVER_VAR_NAME_REMOVE, CODE_USER_VAR_NAME_UPDATE, CODE_USER_VAR_NAME_REMOVE, CODE_DELETE_VAR, CODE_CHANGE_SAMPLING_MODE_SAMPLE, CODE_CHANGE_SAMPLING_MODE_WITNESS, CODE_AT_CLAUSE_RED, CODE_AT_CLAUSE_IRRED, CODE_UNIT_CLAUSES, CODE_DELETE_CLAUSE_REDUNDANT, CODE_DELETE_CLAUSE_SIMPLIFIED, CODE_DELETE_CLAUSE_SATISFIED, CODE_CHANGE_HASH_BITS, CODE_MODEL, CODE_ADD_CLAUSE, CODE_ASSUMPTIONS, CODE_FAILED_ASSUMPTIONS, ); // Using a random value here makes it unlikely that a corrupted proof will be silently truncated and // accepted const CODE_END: u64 = 0x9ac3391f4294c211; /// Writes a proof step in the varisat format pub fn write_step<'s>(target: &mut impl Write, step: &'s ProofStep<'s>) -> io::Result<()> { match *step { ProofStep::SolverVarName { global, solver } => { if let Some(solver) = solver { write_u64(&mut *target, CODE_SOLVER_VAR_NAME_UPDATE)?; write_u64(&mut *target, global.index() as u64)?; write_u64(&mut *target, solver.index() as u64)?; } else { write_u64(&mut *target, CODE_SOLVER_VAR_NAME_REMOVE)?; write_u64(&mut *target, global.index() as u64)?; } } ProofStep::UserVarName { global, user } => { if let Some(user) = user { write_u64(&mut *target, CODE_USER_VAR_NAME_UPDATE)?; write_u64(&mut *target, global.index() as u64)?; write_u64(&mut *target, user.index() as u64)?; } else { write_u64(&mut *target, CODE_USER_VAR_NAME_REMOVE)?; write_u64(&mut *target, global.index() as u64)?; } } ProofStep::DeleteVar { var } => { write_u64(&mut *target, CODE_DELETE_VAR)?; write_u64(&mut *target, var.index() as u64)?; } ProofStep::ChangeSamplingMode { var, sample } => { if sample { write_u64(&mut *target, CODE_CHANGE_SAMPLING_MODE_SAMPLE)?; } else { write_u64(&mut *target, CODE_CHANGE_SAMPLING_MODE_WITNESS)?; } write_u64(&mut *target, var.index() as u64)?; } ProofStep::AddClause { clause } => { write_u64(&mut *target, CODE_ADD_CLAUSE)?; write_literals(&mut *target, clause)?; } ProofStep::AtClause { redundant, clause, propagation_hashes, } => { if redundant { write_u64(&mut *target, CODE_AT_CLAUSE_RED)?; } else { write_u64(&mut *target, CODE_AT_CLAUSE_IRRED)?; } write_literals(&mut *target, clause)?; write_hashes(&mut *target, propagation_hashes)?; } ProofStep::UnitClauses { units } => { write_u64(&mut *target, CODE_UNIT_CLAUSES)?; write_unit_clauses(&mut *target, units)?; } ProofStep::DeleteClause { clause, proof } => { match proof { DeleteClauseProof::Redundant => { write_u64(&mut *target, CODE_DELETE_CLAUSE_REDUNDANT)?; } DeleteClauseProof::Simplified => { write_u64(&mut *target, CODE_DELETE_CLAUSE_SIMPLIFIED)?; } DeleteClauseProof::Satisfied => { write_u64(&mut *target, CODE_DELETE_CLAUSE_SATISFIED)?; } } write_literals(&mut *target, clause)?; } ProofStep::ChangeHashBits { bits } => { write_u64(&mut *target, CODE_CHANGE_HASH_BITS)?; write_u64(&mut *target, bits as u64)?; } ProofStep::Model { assignment } => { write_u64(&mut *target, CODE_MODEL)?; write_literals(&mut *target, assignment)?; } ProofStep::Assumptions { assumptions } => { write_u64(&mut *target, CODE_ASSUMPTIONS)?; write_literals(&mut *target, assumptions)?; } ProofStep::FailedAssumptions { failed_core, propagation_hashes, } => { write_u64(&mut *target, CODE_FAILED_ASSUMPTIONS)?; write_literals(&mut *target, failed_core)?; write_hashes(&mut *target, propagation_hashes)?; } ProofStep::End => { write_u64(&mut *target, CODE_END)?; } } Ok(()) } #[derive(Default)] pub struct Parser { lit_buf: Vec<Lit>, hash_buf: Vec<ClauseHash>, unit_buf: Vec<(Lit, ClauseHash)>, } impl Parser { pub fn parse_step<'a>(&'a mut self, source: &mut impl BufRead) -> Result<ProofStep<'a>, Error> { let code = read_u64(&mut *source)?; match code { CODE_SOLVER_VAR_NAME_UPDATE => { let global = Var::from_index(read_u64(&mut *source)? as usize); let solver = Some(Var::from_index(read_u64(&mut *source)? as usize)); Ok(ProofStep::SolverVarName { global, solver }) } CODE_SOLVER_VAR_NAME_REMOVE => { let global = Var::from_index(read_u64(&mut *source)? as usize); Ok(ProofStep::SolverVarName { global, solver: None, }) } CODE_USER_VAR_NAME_UPDATE => { let global = Var::from_index(read_u64(&mut *source)? as usize); let user = Some(Var::from_index(read_u64(&mut *source)? as usize)); Ok(ProofStep::UserVarName { global, user }) } CODE_USER_VAR_NAME_REMOVE => { let global = Var::from_index(read_u64(&mut *source)? as usize); Ok(ProofStep::UserVarName { global, user: None }) } CODE_DELETE_VAR => { let var = Var::from_index(read_u64(&mut *source)? as usize); Ok(ProofStep::DeleteVar { var }) } CODE_CHANGE_SAMPLING_MODE_SAMPLE | CODE_CHANGE_SAMPLING_MODE_WITNESS => { let var = Var::from_index(read_u64(&mut *source)? as usize); Ok(ProofStep::ChangeSamplingMode { var, sample: code == CODE_CHANGE_SAMPLING_MODE_SAMPLE, }) } CODE_ADD_CLAUSE => { read_literals(&mut *source, &mut self.lit_buf)?; Ok(ProofStep::AddClause { clause: &self.lit_buf, }) } CODE_AT_CLAUSE_IRRED | CODE_AT_CLAUSE_RED => { read_literals(&mut *source, &mut self.lit_buf)?; read_hashes(&mut *source, &mut self.hash_buf)?; Ok(ProofStep::AtClause { redundant: code == CODE_AT_CLAUSE_RED, clause: &self.lit_buf, propagation_hashes: &self.hash_buf, }) } CODE_UNIT_CLAUSES => { read_unit_clauses(&mut *source, &mut self.unit_buf)?; Ok(ProofStep::UnitClauses { units: &self.unit_buf, }) } CODE_DELETE_CLAUSE_REDUNDANT | CODE_DELETE_CLAUSE_SIMPLIFIED | CODE_DELETE_CLAUSE_SATISFIED => { let proof = match code { CODE_DELETE_CLAUSE_REDUNDANT => DeleteClauseProof::Redundant, CODE_DELETE_CLAUSE_SIMPLIFIED => DeleteClauseProof::Simplified, CODE_DELETE_CLAUSE_SATISFIED => DeleteClauseProof::Satisfied, _ => unreachable!(), }; read_literals(&mut *source, &mut self.lit_buf)?; Ok(ProofStep::DeleteClause { clause: &self.lit_buf, proof, }) } CODE_CHANGE_HASH_BITS => { let bits = read_u64(&mut *source)? as u32; Ok(ProofStep::ChangeHashBits { bits }) } CODE_MODEL => { read_literals(&mut *source, &mut self.lit_buf)?; Ok(ProofStep::Model { assignment: &self.lit_buf, }) } CODE_ASSUMPTIONS => { read_literals(&mut *source, &mut self.lit_buf)?; Ok(ProofStep::Assumptions { assumptions: &self.lit_buf, }) } CODE_FAILED_ASSUMPTIONS => { read_literals(&mut *source, &mut self.lit_buf)?; read_hashes(&mut *source, &mut self.hash_buf)?; Ok(ProofStep::FailedAssumptions { failed_core: &self.lit_buf, propagation_hashes: &self.hash_buf, }) } CODE_END => Ok(ProofStep::End), _ => anyhow::bail!("parse error"), } } } /// Writes a slice of literals for a varisat proof fn write_literals(target: &mut impl Write, literals: &[Lit]) -> io::Result<()> { write_u64(&mut *target, literals.len() as u64)?; for &lit in literals { write_u64(&mut *target, lit.code() as u64)?; } Ok(()) } /// Read a slice of literals from a varisat proof fn read_literals(source: &mut impl BufRead, literals: &mut Vec<Lit>) -> Result<(), io::Error> { literals.clear(); let len = read_u64(&mut *source)? as usize; literals.reserve(len); for _ in 0..len { literals.push(Lit::from_code(read_u64(&mut *source)? as usize)); } Ok(()) } /// Writes a slice of clause hashes for a varisat proof fn write_hashes(target: &mut impl Write, hashes: &[ClauseHash]) -> io::Result<()> { write_u64(&mut *target, hashes.len() as u64)?; for &hash in hashes { write_u64(&mut *target, hash as u64)?; } Ok(()) } /// Read a slice of clause hashes from a varisat proof fn read_hashes(source: &mut impl BufRead, hashes: &mut Vec<ClauseHash>) -> Result<(), io::Error> { hashes.clear(); let len = read_u64(&mut *source)? as usize; hashes.reserve(len); for _ in 0..len { hashes.push(read_u64(&mut *source)? as ClauseHash); } Ok(()) } /// Writes a slice of unit clauses for a varisat proof fn write_unit_clauses(target: &mut impl Write, units: &[(Lit, ClauseHash)]) -> io::Result<()> { write_u64(&mut *target, units.len() as u64)?; for &(lit, hash) in units { write_u64(&mut *target, lit.code() as u64)?; write_u64(&mut *target, hash as u64)?; } Ok(()) } /// Read a slice of unit clauses from a varisat proof fn read_unit_clauses( source: &mut impl BufRead, units: &mut Vec<(Lit, ClauseHash)>, ) -> Result<(), io::Error> { units.clear(); let len = read_u64(&mut *source)? as usize; units.reserve(len); for _ in 0..len { let lit = Lit::from_code(read_u64(&mut *source)? as usize); let hash = read_u64(&mut *source)? as ClauseHash; units.push((lit, hash)); } Ok(()) }
// Copyright 2020-2021, The Tremor Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![cfg(not(tarpaulin_include))] use crate::errors::Result; use crate::source::prelude::*; //NOTE: This is required for StreamHandlers stream use async_std::future::timeout; use futures::{future, StreamExt}; use halfbrown::HashMap; use log::Level::Debug; use rdkafka::{ client::ClientContext, config::ClientConfig, consumer::{ stream_consumer::{self, StreamConsumer}, CommitMode, Consumer, ConsumerContext, Rebalance, }, error::{KafkaError, KafkaResult}, message::{BorrowedMessage, Headers}, util::AsyncRuntime, Message, Offset, TopicPartitionList, }; use std::collections::{BTreeMap, HashMap as StdMap}; use std::future::Future; use std::mem; use std::time::{Duration, Instant}; pub struct SmolRuntime; impl AsyncRuntime for SmolRuntime { type Delay = future::Map<smol::Timer, fn(Instant)>; fn spawn<T>(task: T) where T: Future<Output = ()> + Send + 'static, { // This needs to be smol::spawn we can't use async_std::task::spawn smol::spawn(task).detach(); } fn delay_for(duration: Duration) -> Self::Delay { // This needs to be smol::Timer we can't use async_io::Timer futures::FutureExt::map(smol::Timer::after(duration), |_| ()) } } #[derive(Deserialize, Debug, Clone)] pub struct Config { /// kafka group ID to register with pub group_id: String, /// List of topics to subscribe to pub topics: Vec<String>, /// List of bootstrap brokers pub brokers: Vec<String>, /// This config determines the behaviour of this source /// if `enable.auto.commit` is set to false in `rdkafka_options`: /// /// if set to true this source will reset the consumer offset to a /// failed message, so it will effectively retry those messages. /// /// If set to `false` this source will only commit the consumer offset /// if the message has been successfully acknowledged. /// /// This might lead to events being sent multiple times. /// This should not be used when you expect persistent errors (e.g. if the message content is malformed and will lead to repeated errors) #[serde(default = "default_retry_failed_events")] pub retry_failed_events: bool, /// Optional rdkafka configuration /// /// Default settings: /// * `client.id` - `"tremor-<hostname>-<thread id>"` /// * `bootstrap.servers` - `brokers` from the config concatenated by `,` /// * `enable.partition.eof` - `"false"` /// * `session.timeout.ms` - `"6000"` /// * `enable.auto.commit` - `"true"` /// * `auto.commit.interval.ms"` - `"5000"` /// * `enable.auto.offset.store` - `"true"` pub rdkafka_options: Option<HashMap<String, String>>, } /// defaults to `true` to keep backwards compatibility fn default_retry_failed_events() -> bool { true } impl ConfigImpl for Config {} pub struct Kafka { pub config: Config, onramp_id: TremorUrl, } #[derive(Debug)] struct MsgOffset { topic: String, partition: i32, offset: Offset, } impl<'consumer> From<BorrowedMessage<'consumer>> for MsgOffset { fn from(m: BorrowedMessage) -> Self { Self { topic: m.topic().into(), partition: m.partition(), offset: Offset::Offset(m.offset()), } } } pub struct StreamAndMsgs<'consumer> { pub stream: stream_consumer::MessageStream<'consumer, LoggingConsumerContext, SmolRuntime>, } impl<'consumer> StreamAndMsgs<'consumer> { fn new( stream: stream_consumer::MessageStream<'consumer, LoggingConsumerContext, SmolRuntime>, ) -> Self { Self { stream } } } rental! { pub mod rentals { use super::{StreamAndMsgs, LoggingConsumer}; #[rental(covariant)] pub struct MessageStream { consumer: Box<LoggingConsumer>, stream: StreamAndMsgs<'consumer> } } } // ALLOW: https://github.com/tremor-rs/tremor-runtime/issues/1023 #[allow(clippy::transmute_ptr_to_ptr)] impl rentals::MessageStream { // ALLOW: https://github.com/tremor-rs/tremor-runtime/issues/1023 #[allow(mutable_transmutes, clippy::mut_from_ref)] unsafe fn mut_suffix( &mut self, ) -> &mut stream_consumer::MessageStream<'_, LoggingConsumerContext, SmolRuntime> { // ALLOW: https://github.com/tremor-rs/tremor-runtime/issues/1023 mem::transmute(&self.suffix().stream) } unsafe fn consumer(&mut self) -> &mut LoggingConsumer { struct MessageStream { consumer: Box<LoggingConsumer>, _stream: StreamAndMsgs<'static>, } // ALLOW: https://github.com/tremor-rs/tremor-runtime/issues/1023 let s: &mut MessageStream = mem::transmute(self); &mut s.consumer } fn commit(&mut self, map: &StdMap<(String, i32), Offset>, mode: CommitMode) -> Result<()> { let offsets = TopicPartitionList::from_topic_map(map)?; unsafe { self.consumer().commit(&offsets, mode)?; }; Ok(()) } fn seek(&mut self, map: &StdMap<(String, i32), Offset>) -> Result<()> { let consumer = unsafe { self.consumer() }; for ((t, p), o) in map.iter() { consumer.seek(t, *p, *o, Duration::from_millis(100))?; } Ok(()) } } pub struct Int { uid: u64, config: Config, onramp_id: TremorUrl, stream: Option<rentals::MessageStream>, origin_uri: EventOriginUri, auto_commit: bool, messages: BTreeMap<u64, MsgOffset>, } impl std::fmt::Debug for Int { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Kafka") } } impl Int { /// get a map aggregating the highest offsets for each topic and partition /// for which we have messages stored up to and including the id of this message fn get_topic_map_for_id(&mut self, id: u64) -> StdMap<(String, i32), Offset> { let mut split = self.messages.split_off(&(id + 1)); mem::swap(&mut split, &mut self.messages); // split now contains all messages up to and including `id` let mut tm = StdMap::with_capacity(split.len()); for ( _, MsgOffset { topic, partition, offset, }, ) in split { if let Offset::Offset(msg_offset) = offset { // we need to commit the message offset + 1, dont ask // The `KafkaConsumer` javadocs say: // // Note: The committed offset should always be the offset of the next message that your application will read. Thus, when calling commitSync(offsets) you should add one to the offset of the last message processed. // // See: https://kafka.apache.org/10/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html // let commit_offset = Offset::Offset(msg_offset + 1); let this_offset = tm.entry((topic, partition)).or_insert(commit_offset); if let (Offset::Offset(old), Offset::Offset(new)) = (this_offset, commit_offset) { *old = (*old).max(new); } } } tm } fn from_config(uid: u64, onramp_id: TremorUrl, config: &Config) -> Self { let origin_uri = EventOriginUri { uid, scheme: "tremor-kafka".to_string(), host: "not-connected".to_string(), port: None, path: vec![], }; let auto_commit = config .rdkafka_options .as_ref() .and_then(|m| m.get("enable.auto.commit")) .map_or(true, |v| v == "true"); Self { uid, config: config.clone(), onramp_id, stream: None, origin_uri, auto_commit, messages: BTreeMap::new(), } } } impl onramp::Impl for Kafka { fn from_config(id: &TremorUrl, config: &Option<YamlValue>) -> Result<Box<dyn Onramp>> { if let Some(config) = config { let config: Config = Config::new(config)?; Ok(Box::new(Self { config, onramp_id: id.clone(), })) } else { Err(format!("[Source::{}] Missing config for kafka onramp.", id).into()) } } } // A simple context to customize the consumer behavior and print a log line every time // offsets are committed pub struct LoggingConsumerContext { onramp_id: TremorUrl, } impl ClientContext for LoggingConsumerContext {} impl ConsumerContext for LoggingConsumerContext { fn post_rebalance(&self, rebalance: &Rebalance) { match rebalance { Rebalance::Assign(tpl) => { let offset_strings: Vec<String> = tpl .elements() .iter() .map(|elem| { format!( "[Topic: {}, Partition: {}, Offset: {:?}]", elem.topic(), elem.partition(), elem.offset() ) }) .collect(); info!( "[Source::{}] Offsets: {}", self.onramp_id, offset_strings.join(" ") ); } Rebalance::Revoke => { info!("[Source::{}] ALL partitions are REVOKED", self.onramp_id); } Rebalance::Error(err_info) => { warn!( "[Source::{}] Post Rebalance error {}", self.onramp_id, err_info ); } } } fn commit_callback(&self, result: KafkaResult<()>, offsets: &rdkafka::TopicPartitionList) { match result { Ok(_) => { if offsets.count() > 0 { debug!( "[Source::{}] Offsets committed successfully", self.onramp_id ); if log_enabled!(Debug) { let offset_strings: Vec<String> = offsets .elements() .iter() .map(|elem| { format!( "[Topic: {}, Partition: {}, Offset: {:?}]", elem.topic(), elem.partition(), elem.offset() ) }) .collect(); debug!( "[Source::{}] Offsets: {}", self.onramp_id, offset_strings.join(" ") ); } } } // this is actually not an error - we just didnt have any offset to commit Err(KafkaError::ConsumerCommit(rdkafka_sys::RDKafkaErrorCode::NoOffset)) => {} Err(e) => warn!( "[Source::{}] Error while committing offsets: {}", self.onramp_id, e ), }; } } pub type LoggingConsumer = StreamConsumer<LoggingConsumerContext, SmolRuntime>; /// ensure a zero poll timeout to have a non-blocking call #[async_trait::async_trait()] impl Source for Int { fn is_transactional(&self) -> bool { !self.auto_commit } fn id(&self) -> &TremorUrl { &self.onramp_id } async fn pull_event(&mut self, id: u64) -> Result<SourceReply> { if let Self { stream: Some(stream), onramp_id, origin_uri, auto_commit, messages, .. } = &mut self { let r = { let s = unsafe { stream.mut_suffix() }; timeout(Duration::from_millis(100), s.next()).await }; let r = match r { Ok(r) => r, Err(_) => return Ok(SourceReply::Empty(0)), }; if let Some(Ok(m)) = r { debug!( "[Source::{}] EventId: {} Offset: {}", onramp_id, id, m.offset() ); if let Some(Ok(data)) = m.payload_view::<[u8]>() { let mut origin_uri = origin_uri.clone(); origin_uri.path = vec![ m.topic().to_string(), m.partition().to_string(), m.offset().to_string(), ]; let data = data.to_vec(); let mut kafka_meta_data = Value::object_with_capacity(1); let mut meta_key = None; if let Some(key) = m.key() { meta_key = Some(key); } let mut meta_headers = None; if let Some(headers) = m.headers() { let mut key_val = Value::object_with_capacity(headers.count()); for i in 0..headers.count() { if let Some(header) = headers.get(i) { let key = String::from(header.0); let val = Value::Bytes(Vec::from(header.1).into()); key_val.insert(key, val)?; } } meta_headers = Some(key_val); } let mut meta_data = Value::object_with_capacity(6); if let Some(meta_key) = meta_key { meta_data.insert("key", Value::Bytes(Vec::from(meta_key).into()))?; } if let Some(meta_headers) = meta_headers { meta_data.insert("headers", meta_headers)?; } meta_data.insert("topic", m.topic().to_string())?; meta_data.insert("offset", m.offset())?; meta_data.insert("partition", m.partition())?; if let Some(t) = m.timestamp().to_millis() { meta_data.insert("timestamp", t)?; } kafka_meta_data.insert("kafka", meta_data)?; if !*auto_commit { messages.insert(id, MsgOffset::from(m)); } Ok(SourceReply::Data { origin_uri, data, meta: Some(kafka_meta_data), codec_override: None, stream: 0, }) } else { error!( "[Source::{}] Failed to fetch kafka message.", self.onramp_id ); Ok(SourceReply::Empty(0)) } } else { Ok(SourceReply::Empty(0)) } } else { Ok(SourceReply::StateChange(SourceState::Disconnected)) } } #[allow(clippy::too_many_lines)] async fn init(&mut self) -> Result<SourceState> { let context = LoggingConsumerContext { onramp_id: self.onramp_id.clone(), }; let mut client_config = ClientConfig::new(); let tid = task::current().id(); // Get the correct origin url let first_broker: Vec<&str> = if let Some(broker) = self.config.brokers.first() { broker.split(':').collect() } else { return Err(format!("[Source::{}] No brokers provided.", self.onramp_id).into()); }; // picking the first host for these let (host, port) = match first_broker.as_slice() { [host] => ((*host).to_string(), None), [host, port] => ((*host).to_string(), Some(port.parse()?)), _ => { return Err(format!( "[Source::{}] Invalid broker config: {}", self.onramp_id, first_broker.join(":") ) .into()) } }; self.origin_uri = EventOriginUri { uid: self.uid, scheme: "tremor-kafka".to_string(), host, port, path: vec![], }; info!("[Source::{}] Starting kafka onramp", self.onramp_id); // Setting up the configuration with default and then overwriting // them with custom settings. // // ENABLE LIBRDKAFKA DEBUGGING: // - set librdkafka logger to debug in logger.yaml // - configure: debug: "all" for this onramp client_config .set("group.id", &self.config.group_id) .set( "client.id", &format!("tremor-{}-{}-{:?}", hostname(), self.onramp_id, tid), ) .set("bootstrap.servers", &self.config.brokers.join(",")) .set("enable.partition.eof", "false") .set("session.timeout.ms", "6000") // Commit automatically every 5 seconds. .set("enable.auto.commit", "true") .set("auto.commit.interval.ms", "5000") // but only commit the offsets explicitly stored via `consumer.store_offset`. .set("enable.auto.offset.store", "true"); self.config .rdkafka_options .iter() .flat_map(halfbrown::HashMap::iter) .for_each(|(k, v)| { client_config.set(k, v); }); debug!( "[Source::{}] Consuming from Kafka with config: {:?}", self.onramp_id, &client_config ); // Set up the the consumer let consumer: LoggingConsumer = client_config.create_with_context(context)?; // Handle topics let topics: Vec<&str> = self .config .topics .iter() .map(std::string::String::as_str) .collect(); info!("[Source::{}] Subscribing to: {:?}", self.onramp_id, topics); // This is terribly ugly, thank you rdkafka! // We need to do this because: // - subscribing to a topic that does not exist will brick the whole consumer // - subscribing to a topic that does not exist will claim to succeed // - getting the metadata of a topic that does not exist will claim to succeed // - The only indication of it missing is in the metadata, in the topics list // in the errors ... // // This is terrible :/ let mut good_topics = Vec::new(); for topic in topics { match consumer.fetch_metadata(Some(topic), Duration::from_secs(1)) { Ok(m) => { let errors: Vec<_> = m .topics() .iter() .map(rdkafka::metadata::MetadataTopic::error) .collect(); match errors.as_slice() { [None] => good_topics.push(topic), [Some(e)] => error!( "[Source::{}] Kafka error for topic '{}': {:?}. Not subscribing!", self.onramp_id, topic, e ), _ => error!( "[Source::{}] Unknown kafka error for topic '{}'. Not subscribing!", self.onramp_id, topic ), } } Err(e) => error!( "[Source::{}] Kafka error for topic '{}': {}. Not subscribing!", self.onramp_id, topic, e ), }; } // bail out if there is no topic left to subscribe to if good_topics.len() < self.config.topics.len() { return Err(format!( "[Source::{}] Unable to subscribe to all configured topics: {}", self.onramp_id, self.config.topics.join(", ") ) .into()); } match consumer.subscribe(&good_topics) { Ok(()) => info!( "[Source::{}] Subscribed to topics: {:?}", self.onramp_id, good_topics ), Err(e) => { error!( "[Source::{}] Kafka error for topics '{:?}': {}", self.onramp_id, good_topics, e ); return Err(e.into()); } }; let stream = rentals::MessageStream::new(Box::new(consumer), |c| StreamAndMsgs::new(c.stream())); self.stream = Some(stream); Ok(SourceState::Connected) } fn trigger_breaker(&mut self) {} fn restore_breaker(&mut self) {} // If we fail a message we seek back to this failed // message to replay data from here. // // This might seek over multiple topics but since we internally only keep // track of a singular stream this is OK. // // If this is undesirable, multiple onramps with an onramp per topic // should be used. fn fail(&mut self, id: u64) { trace!("[Source::{}] Fail {}", self.onramp_id, id); if !self.auto_commit && self.config.retry_failed_events { let tm = self.get_topic_map_for_id(id); if let Some(consumer) = self.stream.as_mut() { if let Err(e) = consumer.seek(&tm) { error!("[Source::{}] failed to seek message: {}", self.onramp_id, e); } } } } fn ack(&mut self, id: u64) { trace!("[Source::{}] Ack {}", self.onramp_id, id); if !self.auto_commit { let tm = self.get_topic_map_for_id(id); if !tm.is_empty() { if let Some(consumer) = self.stream.as_mut() { if let Err(e) = consumer.commit(&tm, CommitMode::Async) { error!( "[Source::{}] failed to commit message: {}", self.onramp_id, e ); } } } } } } #[async_trait::async_trait] impl Onramp for Kafka { async fn start(&mut self, config: OnrampConfig<'_>) -> Result<onramp::Addr> { let source = Int::from_config(config.onramp_uid, self.onramp_id.clone(), &self.config); SourceManager::start(source, config).await } fn default_codec(&self) -> &str { "json" } }
#![allow(dead_code)] extern crate paste; extern crate terminus; use std::rc::Rc; use terminus::devices::bus::TerminusBus; use terminus::devices::clint::*; use terminus::global::*; use terminus::memory::{region::*, MemInfo}; use terminus::processor::Processor; use terminus::processor::ProcessorCfg; mod bus; use bus::{CoreBus, ExtBus}; struct Cluster { processors: Vec<Processor>, sys_bus: Option<Rc<TerminusBus>>, } static mut CLUSTER: Cluster = Cluster { processors: vec![], sys_bus: None, }; #[no_mangle] extern "C" fn cluster_init(num_cores: u32) { let configs = vec![ ProcessorCfg { xlen: XLen::X32, enable_dirty: true, extensions: vec!['m', 'a', 'c'].into_boxed_slice(), freq: 1000000000, }; num_cores as usize ]; let sys_bus = Rc::new(TerminusBus::new()); let clint = Rc::new(Timer::new(100000000)); let ext_bus = Box::new(ExtBus { name: "global".to_string(), id: 0x1000, base: 0x80000000, size: 0x80000000, }); sys_bus .space_mut() .add_region( "ext_bus", &Region::remap(ext_bus.base, &Region::io(0, ext_bus.size, ext_bus)), ) .unwrap(); sys_bus .space_mut() .add_region( "clint", &Region::remap(0x02000000, &Region::io(0, 0x000c0000, Box::new(Clint::new(&clint)))), ) .unwrap(); for cfg in configs { let core_bus = Rc::new(CoreBus::new( &sys_bus, format!("core{}",unsafe { CLUSTER.processors.len() }), unsafe { CLUSTER.processors.len() } as u32, MemInfo { base: 0, size: 4096, }, MemInfo { base: 4096, size: 4096 * 4, }, )); let p = Processor::new( unsafe { CLUSTER.processors.len() }, cfg, &core_bus, Some(clint.alloc_irq()), None, ); unsafe { CLUSTER.processors.push(p) } } unsafe { CLUSTER.sys_bus = Some(sys_bus); }; } #[no_mangle] extern "C" fn cluster_reset_core(hartid: u32, boot_addr: u64) { unsafe { CLUSTER.processors[hartid as usize] .reset(boot_addr) .expect(format!("reset core {} to {:#x} fail!", hartid, boot_addr).as_str()); } println!("reset core to {:#x}!", boot_addr); } #[no_mangle] extern "C" fn cluster_run() -> ! { extern "C" { fn cluster_step(); } unsafe { loop { for p in &mut CLUSTER.processors { p.step(1); } cluster_step(); } } } #[no_mangle] extern "C" fn cluster_run_1step() { unsafe { for p in &mut CLUSTER.processors { p.step(1); } } } #[no_mangle] extern "C" fn cluster_statics() { unsafe { for p in &CLUSTER.processors { println!("{}", p.state().to_string()) } } }
struct User { username: String, email: String, sign_in_count: i64, active: bool, } #[derive(Debug)] struct Rect { width: i32, height: i32, } impl Rect { fn new(width: i32, height: i32) -> Rect { Rect { width, height } } fn area(&self) -> i32 { self.height * self.width } fn can_hold(&self, other: &Rect) -> bool { self.height > other.height && self.width > other.width } } impl User { fn new(username: String, email: String) -> User { User { username, email, sign_in_count: 1, active: true, } } fn print(&self) { println!( "Hello, {} ({}), signed in: {} and active: {}", self.username, self.email, self.sign_in_count, self.active ); } } struct Point(i32, i32, i32); struct FPoint(f32, f32, f32); fn test_tuple_struct() { let p1 = Point(1, 2, 3); let fp2 = FPoint(1.0, 2.0, 3.0); println!("{}, {}", p1.0, fp2.0); } fn main() { let mut new_user = User::new(String::from("Adam"), String::from("adamlabbe@gmail.com")); new_user.sign_in_count = 2; new_user.print(); test_tuple_struct(); let rect = Rect::new(10, 2); println!("{:?} area: {}", rect, rect.area()); let big_rect = Rect::new(20, 3); println!("can hold?: {}", big_rect.can_hold(&rect)) }
use crate::client::Client; use crate::partial::Progress; use crate::utils::queue::Queue; use crate::utils::serialize_bytes; use byteorder::{BigEndian, ReadBytesExt}; use serde::{Deserialize, Serialize}; use serde_bytes::ByteBuf; use std::collections::VecDeque; use std::io::Cursor; use std::sync::Arc; use std::time::Duration; use tokio::sync::{broadcast, Mutex}; #[derive(Serialize, Deserialize, Debug)] struct TrackerResponse { pub interval: u64, pub peers: ByteBuf, } pub struct Peerlist { progress: Arc<Mutex<Progress>>, interval: u64, announce: String, info_hash: Vec<u8>, peer_id: Vec<u8>, port: u16, list: Queue<String>, } fn parse_peerlist(buf: &[u8]) -> VecDeque<String> { if buf.len() % 6 != 0 { panic!("Peer list not correct length!"); } let n = buf.len() / 6; let mut cx = Cursor::new(buf); let mut res = VecDeque::new(); for _ in 0..n { let mut s = String::new(); for _ in 0..4 { s.push_str(&format!("{}.", cx.read_u8().unwrap())); } s.pop(); s.push(':'); s.push_str(&format!("{}", cx.read_u16::<BigEndian>().unwrap())); res.push_back(s); } res } impl Peerlist { pub fn from(c: &Client) -> Peerlist { Peerlist { list: c.peer_list.clone(), progress: Arc::clone(&c.partial.progress), interval: 0, port: c.port, info_hash: c.torrent.info_hash.clone(), peer_id: c.torrent.peer_id.clone(), announce: c.torrent.announce.clone(), } } pub async fn poll_peerlist(&mut self, mut erx: broadcast::Receiver<()>) { loop { println!("Getting peerlist"); self.get_peerlist().await; println!("Got peerlist"); tokio::select! { _ = tokio::time::delay_for(Duration::from_secs(self.interval)) => { }, Ok(()) = erx.recv() => { break } } } println!("Peerlist stopping"); } async fn get_peerlist(&mut self) { // manually encode bytes let url = format!( "{}?info_hash={}&peer_id={}", self.announce, serialize_bytes(&self.info_hash), serialize_bytes(&self.peer_id) ); let mut params = vec![("port", self.port as u64), ("compact", 1)]; { let p = self.progress.lock().await; params.extend(vec![ ("uploaded", p.uploaded as u64), ("downloaded", p.downloaded as u64), ("left", p.left as u64), ]); } let client = reqwest::Client::new(); let res = client .get(url.as_str()) .query(&params) .send() .await .expect("Could not parse tracker response!") .bytes() .await .expect("Could not parse tracker response!"); let res: TrackerResponse = serde_bencode::de::from_bytes(&res).expect("Could not parse tracker response!"); self.list .replace(parse_peerlist(res.peers.as_slice())) .await; // hack for own tracker self.list.push(format!("localhost:{}", 4444).to_string()).await; self.interval = res.interval; } }
//! Functions and types related to the layout checking. use std::{cmp::Ordering, fmt, mem}; #[allow(unused_imports)] use core_extensions::{matches, SelfOps}; use std::{ borrow::Borrow, cell::Cell, collections::hash_map::{Entry, HashMap}, }; use crate::{ abi_stability::{ extra_checks::{ ExtraChecksBox, ExtraChecksError, ExtraChecksRef, TypeChecker, TypeCheckerMut, }, ConstGeneric, }, prefix_type::{FieldAccessibility, FieldConditionality}, sabi_types::{CmpIgnored, ParseVersionError, VersionStrings}, std_types::{RArc, RBox, RBoxError, RErr, RNone, ROk, RResult, RSome, RStr, RVec, UTypeId}, traits::IntoReprC, type_layout::{ tagging::TagErrors, FmtFullType, IncompatibleWithNonExhaustive, IsExhaustive, ReprAttr, TLData, TLDataDiscriminant, TLDiscriminant, TLEnum, TLField, TLFieldOrFunction, TLFunction, TLNonExhaustive, TLPrimitive, TypeLayout, }, type_level::downcasting::TD_Opaque, utils::{max_by, min_max_by}, }; mod errors; pub use self::errors::{ AbiInstability, AbiInstability as AI, AbiInstabilityError, AbiInstabilityErrors, ExtraCheckError, }; //////////////////////////////////////////////////////////////////////////////// /// What is AbiChecker::check_fields being called with. #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)] #[repr(C)] enum FieldContext { Fields, Subfields, PhantomFields, } ////// #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)] #[repr(C)] struct CheckingUTypeId { type_id: UTypeId, } impl CheckingUTypeId { fn new(this: &'static TypeLayout) -> Self { Self { type_id: this.get_utypeid(), } } } ////// #[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash)] pub enum CheckingState { Checking { layer: u32 }, Compatible, Error, } ////// /// Represents an error where a value was expected,but another value was found. #[derive(Debug, PartialEq, Eq, Clone)] #[repr(C)] pub struct ExpectedFound<T> { pub expected: T, pub found: T, } #[allow(clippy::missing_const_for_fn)] impl<T> ExpectedFound<T> { pub fn new<O, F>(this: O, other: O, mut field_getter: F) -> ExpectedFound<T> where F: FnMut(O) -> T, { ExpectedFound { expected: field_getter(this), found: field_getter(other), } } pub fn as_ref(&self) -> ExpectedFound<&T> { ExpectedFound { expected: &self.expected, found: &self.found, } } pub fn map<F, U>(self, mut f: F) -> ExpectedFound<U> where F: FnMut(T) -> U, { ExpectedFound { expected: f(self.expected), found: f(self.found), } } pub fn display_str(&self) -> Option<ExpectedFound<String>> where T: fmt::Display, { Some(self.as_ref().map(|x| format!("{:#}", x))) } pub fn debug_str(&self) -> Option<ExpectedFound<String>> where T: fmt::Debug, { Some(self.as_ref().map(|x| format!("{:#?}", x))) } } /////////////////////////////////////////////// #[derive(Debug)] #[repr(C)] pub struct CheckedPrefixTypes { this: &'static TypeLayout, this_prefix: __PrefixTypeMetadata, other: &'static TypeLayout, other_prefix: __PrefixTypeMetadata, } #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct NonExhaustiveEnumWithContext { layout: &'static TypeLayout, enum_: TLEnum, nonexhaustive: &'static TLNonExhaustive, } #[derive(Debug, Clone)] #[repr(C)] pub struct ExtraChecksBoxWithContext { t_lay: &'static TypeLayout, o_lay: &'static TypeLayout, extra_checks: ExtraChecksBox, } #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct CheckedNonExhaustiveEnums { this: NonExhaustiveEnumWithContext, other: NonExhaustiveEnumWithContext, } /////////////////////////////////////////////// struct AbiChecker { stack_trace: RVec<ExpectedFound<TLFieldOrFunction>>, checked_prefix_types: RVec<CheckedPrefixTypes>, checked_nonexhaustive_enums: RVec<CheckedNonExhaustiveEnums>, checked_extra_checks: RVec<ExtraChecksBoxWithContext>, visited: HashMap<(CheckingUTypeId, CheckingUTypeId), CheckingState>, errors: RVec<AbiInstabilityError>, /// Layer 0 is checking a type layout, /// /// Layer 1 is checking the type layout /// of a const parameter/ExtraCheck, /// /// Layer 2 is checking the type layout /// of a const parameter/ExtraCheck /// of a const parameter/ExtraCheck, /// /// It is an error to attempt to check the layout of types that are /// in the middle of being checked in outer layers. current_layer: u32, error_index: usize, } /////////////////////////////////////////////// impl AbiChecker { fn new() -> Self { Self { stack_trace: RVec::new(), checked_prefix_types: RVec::new(), checked_nonexhaustive_enums: RVec::new(), checked_extra_checks: RVec::new(), visited: HashMap::default(), errors: RVec::new(), current_layer: 0, error_index: 0, } } #[inline] fn check_fields<I, F>( &mut self, errs: &mut RVec<AbiInstability>, t_lay: &'static TypeLayout, o_lay: &'static TypeLayout, ctx: FieldContext, t_fields: I, o_fields: I, ) where I: ExactSizeIterator<Item = F>, F: Borrow<TLField>, { if t_fields.len() == 0 && o_fields.len() == 0 { return; } let t_data = t_lay.data(); let is_prefix = match &t_data { TLData::PrefixType { .. } => true, TLData::Enum(enum_) => !enum_.exhaustiveness.is_exhaustive(), _ => false, }; match (t_fields.len().cmp(&o_fields.len()), is_prefix) { (Ordering::Greater, _) | (Ordering::Less, false) => { push_err( errs, &t_fields, &o_fields, |x| x.len(), AI::FieldCountMismatch, ); } (Ordering::Equal, _) | (Ordering::Less, true) => {} } let acc_fields: Option<(FieldAccessibility, FieldAccessibility)> = match (&t_data, &o_lay.data()) { (TLData::PrefixType(t_prefix), TLData::PrefixType(o_prefix)) => { Some((t_prefix.accessible_fields, o_prefix.accessible_fields)) } _ => None, }; for (field_i, (this_f, other_f)) in t_fields.zip(o_fields).enumerate() { let this_f = this_f.borrow(); let other_f = other_f.borrow(); if this_f.name() != other_f.name() { push_err(errs, this_f, other_f, |x| *x, AI::UnexpectedField); continue; } let t_field_abi = this_f.layout(); let o_field_abi = other_f.layout(); let is_accessible = match (ctx, acc_fields) { (FieldContext::Fields, Some((l, r))) => { l.at(field_i).is_accessible() && r.at(field_i).is_accessible() } _ => true, }; if is_accessible { if this_f.lifetime_indices() != other_f.lifetime_indices() { push_err(errs, this_f, other_f, |x| *x, AI::FieldLifetimeMismatch); } self.stack_trace.push(ExpectedFound { expected: (*this_f).into(), found: (*other_f).into(), }); let sf_ctx = FieldContext::Subfields; let func_ranges = this_f.function_range().iter().zip(other_f.function_range()); for (t_func, o_func) in func_ranges { self.error_index += 1; let errs_index = self.error_index; let mut errs_ = RVec::<AbiInstability>::new(); let errs = &mut errs_; self.stack_trace.push(ExpectedFound { expected: t_func.into(), found: o_func.into(), }); if t_func.paramret_lifetime_indices != o_func.paramret_lifetime_indices { push_err(errs, t_func, o_func, |x| x, AI::FnLifetimeMismatch); } if t_func.qualifiers() != o_func.qualifiers() { push_err(errs, t_func, o_func, |x| x, AI::FnQualifierMismatch); } self.check_fields( errs, t_lay, o_lay, sf_ctx, t_func.get_params_ret_iter(), o_func.get_params_ret_iter(), ); if !errs_.is_empty() { self.errors.push(AbiInstabilityError { stack_trace: self.stack_trace.clone(), errs: errs_, index: errs_index, _priv: (), }); } self.stack_trace.pop(); } let _ = self.check_inner(t_field_abi, o_field_abi); self.stack_trace.pop(); } else { self.stack_trace.push(ExpectedFound { expected: (*this_f).into(), found: (*other_f).into(), }); let t_field_layout = &t_field_abi; let o_field_layout = &o_field_abi; if t_field_layout.size() != o_field_layout.size() { push_err(errs, t_field_layout, o_field_layout, |x| x.size(), AI::Size); } if t_field_layout.alignment() != o_field_layout.alignment() { push_err( errs, t_field_layout, o_field_layout, |x| x.alignment(), AI::Alignment, ); } self.stack_trace.pop(); } } } fn check_inner( &mut self, this: &'static TypeLayout, other: &'static TypeLayout, ) -> Result<(), ()> { let t_cuti = CheckingUTypeId::new(this); let o_cuti = CheckingUTypeId::new(other); let cuti_pair = (t_cuti, o_cuti); self.error_index += 1; let errs_index = self.error_index; let mut errs_ = RVec::<AbiInstability>::new(); let mut top_level_errs_ = RVec::<AbiInstabilityError>::new(); let t_lay = &this; let o_lay = &other; let start_errors = self.errors.len(); match self.visited.entry(cuti_pair) { Entry::Occupied(mut entry) => match entry.get_mut() { CheckingState::Checking { layer } if self.current_layer == *layer => return Ok(()), cs @ CheckingState::Checking { .. } => { *cs = CheckingState::Error; self.errors.push(AbiInstabilityError { stack_trace: self.stack_trace.clone(), errs: rvec![AbiInstability::CyclicTypeChecking { interface: this, implementation: other, }], index: errs_index, _priv: (), }); return Err(()); } CheckingState::Compatible => { return Ok(()); } CheckingState::Error => { return Err(()); } }, Entry::Vacant(entry) => { entry.insert(CheckingState::Checking { layer: self.current_layer, }); } } (|| { let errs = &mut errs_; let top_level_errs = &mut top_level_errs_; if t_lay.name() != o_lay.name() { push_err(errs, t_lay, o_lay, |x| x.full_type(), AI::Name); return; } let (t_package, t_ver_str) = t_lay.package_and_version(); let (o_package, o_ver_str) = o_lay.package_and_version(); if t_package != o_package { push_err(errs, t_lay, o_lay, |x| x.package(), AI::Package); return; } if this.is_nonzero() != other.is_nonzero() { push_err(errs, this, other, |x| x.is_nonzero(), AI::NonZeroness); } if t_lay.repr_attr() != o_lay.repr_attr() { push_err(errs, t_lay, o_lay, |x| x.repr_attr(), AI::ReprAttr); } { let x = (|| { let l = t_ver_str.parsed()?; let r = o_ver_str.parsed()?; Ok(l.is_loosely_compatible(r)) })(); match x { Ok(false) => { push_err( errs, t_lay, o_lay, |x| x.package_version(), AI::PackageVersion, ); } Ok(true) => {} Err(parse_error) => { errs.push(AI::PackageVersionParseError(parse_error)); return; } } } { let t_gens = t_lay.generics(); let o_gens = o_lay.generics(); let t_consts = t_gens.const_params(); let o_consts = o_gens.const_params(); if t_gens.lifetime_count() != o_gens.lifetime_count() || t_gens.const_params().len() != o_gens.const_params().len() { push_err(errs, t_lay, o_lay, |x| x.full_type(), AI::GenericParamCount); } let mut ty_checker = TypeCheckerMut::from_ptr(&mut *self, TD_Opaque); for (l, r) in t_consts.iter().zip(o_consts.iter()) { match l.is_equal(r, ty_checker.sabi_reborrow_mut()) { Ok(false) | Err(_) => { push_err(errs, l, r, |x| *x, AI::MismatchedConstParam); } Ok(true) => {} } } } // Checking phantom fields self.check_fields( errs, this, other, FieldContext::PhantomFields, this.phantom_fields().iter(), other.phantom_fields().iter(), ); match (t_lay.size().cmp(&o_lay.size()), this.is_prefix_kind()) { (Ordering::Greater, _) | (Ordering::Less, false) => { push_err(errs, t_lay, o_lay, |x| x.size(), AI::Size); } (Ordering::Equal, _) | (Ordering::Less, true) => {} } if t_lay.alignment() != o_lay.alignment() { push_err(errs, t_lay, o_lay, |x| x.alignment(), AI::Alignment); } let t_discr = t_lay.data_discriminant(); let o_discr = o_lay.data_discriminant(); if t_discr != o_discr { errs.push(AI::TLDataDiscriminant(ExpectedFound { expected: t_discr, found: o_discr, })); } let t_tag = t_lay.tag().to_checkable(); let o_tag = o_lay.tag().to_checkable(); if let Err(tag_err) = t_tag.check_compatible(&o_tag) { errs.push(AI::TagError { err: tag_err }); } match (t_lay.extra_checks(), o_lay.extra_checks()) { (None, _) => {} (Some(_), None) => { errs.push(AI::NoneExtraChecks); } (Some(t_extra_checks), Some(o_extra_checks)) => { let mut ty_checker = TypeCheckerMut::from_ptr(&mut *self, TD_Opaque); let res = handle_extra_checks_ret( t_extra_checks.clone(), o_extra_checks.clone(), errs, top_level_errs, move || { let ty_checker_ = ty_checker.sabi_reborrow_mut(); rtry!(t_extra_checks.check_compatibility(t_lay, o_lay, ty_checker_)); let ty_checker_ = ty_checker.sabi_reborrow_mut(); let opt = rtry!(t_extra_checks.combine(o_extra_checks, ty_checker_)); opt.map(|combined| ExtraChecksBoxWithContext { t_lay, o_lay, extra_checks: combined, }) .piped(ROk) }, ); if let Ok(RSome(x)) = res { self.checked_extra_checks.push(x); } } } match (t_lay.data(), o_lay.data()) { (TLData::Opaque { .. }, _) => { // No checks are necessary } (TLData::Primitive(t_prim), TLData::Primitive(o_prim)) => { if t_prim != o_prim { errs.push(AI::MismatchedPrimitive(ExpectedFound { expected: t_prim, found: o_prim, })); } } (TLData::Primitive { .. }, _) => {} (TLData::Struct { fields: t_fields }, TLData::Struct { fields: o_fields }) => { self.check_fields( errs, this, other, FieldContext::Fields, t_fields.iter(), o_fields.iter(), ); } (TLData::Struct { .. }, _) => {} (TLData::Union { fields: t_fields }, TLData::Union { fields: o_fields }) => { self.check_fields( errs, this, other, FieldContext::Fields, t_fields.iter(), o_fields.iter(), ); } (TLData::Union { .. }, _) => {} (TLData::Enum(t_enum), TLData::Enum(o_enum)) => { self.check_enum(errs, this, other, t_enum, o_enum); let t_as_ne = t_enum.exhaustiveness.as_nonexhaustive(); let o_as_ne = o_enum.exhaustiveness.as_nonexhaustive(); if let (Some(this_ne), Some(other_ne)) = (t_as_ne, o_as_ne) { self.checked_nonexhaustive_enums .push(CheckedNonExhaustiveEnums { this: NonExhaustiveEnumWithContext { layout: this, enum_: t_enum, nonexhaustive: this_ne, }, other: NonExhaustiveEnumWithContext { layout: other, enum_: o_enum, nonexhaustive: other_ne, }, }); } } (TLData::Enum { .. }, _) => {} (TLData::PrefixType(t_prefix), TLData::PrefixType(o_prefix)) => { let this_prefix = __PrefixTypeMetadata::with_prefix_layout(t_prefix, t_lay); let other_prefix = __PrefixTypeMetadata::with_prefix_layout(o_prefix, o_lay); self.check_prefix_types(errs, &this_prefix, &other_prefix); self.checked_prefix_types.push(CheckedPrefixTypes { this, this_prefix, other, other_prefix, }) } (TLData::PrefixType { .. }, _) => {} } })(); self.errors.extend(top_level_errs_); let check_st = self.visited.get_mut(&cuti_pair).unwrap(); if errs_.is_empty() && self.errors.len() == start_errors && *check_st != CheckingState::Error { *check_st = CheckingState::Compatible; Ok(()) } else { *check_st = CheckingState::Error; self.errors.push(AbiInstabilityError { stack_trace: self.stack_trace.clone(), errs: errs_, index: errs_index, _priv: (), }); Err(()) } } fn check_enum( &mut self, errs: &mut RVec<AbiInstability>, this: &'static TypeLayout, other: &'static TypeLayout, t_enum: TLEnum, o_enum: TLEnum, ) { let TLEnum { fields: t_fields, .. } = t_enum; let TLEnum { fields: o_fields, .. } = o_enum; let t_fcount = t_enum.field_count.as_slice(); let o_fcount = o_enum.field_count.as_slice(); let t_exhaus = t_enum.exhaustiveness; let o_exhaus = o_enum.exhaustiveness; match (t_exhaus.as_nonexhaustive(), o_exhaus.as_nonexhaustive()) { (Some(this_ne), Some(other_ne)) => { if let Err(e) = this_ne.check_compatible(this) { errs.push(AI::IncompatibleWithNonExhaustive(e)) } if let Err(e) = other_ne.check_compatible(other) { errs.push(AI::IncompatibleWithNonExhaustive(e)) } } (Some(_), None) | (None, Some(_)) => { push_err( errs, t_enum, o_enum, |x| x.exhaustiveness, AI::MismatchedExhaustiveness, ); } (None, None) => {} } if t_exhaus.is_exhaustive() && t_fcount.len() != o_fcount.len() || t_exhaus.is_nonexhaustive() && t_fcount.len() > o_fcount.len() { push_err(errs, t_fcount, o_fcount, |x| x.len(), AI::TooManyVariants); } if let Err(d_errs) = t_enum.discriminants.compare(&o_enum.discriminants) { errs.extend(d_errs); } let mut t_names = t_enum.variant_names.as_str().split(';'); let mut o_names = o_enum.variant_names.as_str().split(';'); let mut total_field_count = 0; for (t_field_count, o_field_count) in t_fcount.iter().zip(o_fcount) { let t_name = t_names.next().unwrap_or("<this unavailable>"); let o_name = o_names.next().unwrap_or("<other unavailable>"); total_field_count += usize::from(*t_field_count); if t_field_count != o_field_count { push_err( errs, *t_field_count, *o_field_count, |x| x as usize, AI::FieldCountMismatch, ); } if t_name != o_name { push_err(errs, t_name, o_name, RStr::from_str, AI::UnexpectedVariant); continue; } } let min_field_count = t_fields.len().min(o_fields.len()); if total_field_count != min_field_count { push_err( errs, total_field_count, min_field_count, |x| x, AI::FieldCountMismatch, ); } self.check_fields( errs, this, other, FieldContext::Fields, t_fields.iter(), o_fields.iter(), ); } fn check_prefix_types( &mut self, errs: &mut RVec<AbiInstability>, this: &__PrefixTypeMetadata, other: &__PrefixTypeMetadata, ) { if this.prefix_field_count != other.prefix_field_count { push_err( errs, this, other, |x| x.prefix_field_count, AI::MismatchedPrefixSize, ); } if this.conditional_prefix_fields != other.conditional_prefix_fields { push_err( errs, this, other, |x| x.conditional_prefix_fields, AI::MismatchedPrefixConditionality, ); } self.check_fields( errs, this.layout, other.layout, FieldContext::Fields, this.fields.iter(), other.fields.iter(), ); } /// Combines the prefix types into a global map of prefix types. fn final_prefix_type_checks( &mut self, globals: &CheckingGlobals, ) -> Result<(), AbiInstabilityError> { self.error_index += 1; let mut errs_ = RVec::<AbiInstability>::new(); let errs = &mut errs_; let mut prefix_type_map = globals.prefix_type_map.lock().unwrap(); for pair in mem::take(&mut self.checked_prefix_types) { // let t_lay=pair.this_prefix; let errors_before = self.errors.len(); let t_utid = pair.this.get_utypeid(); let o_utid = pair.other.get_utypeid(); // let t_fields=pair.this_prefix.fields; // let o_fields=pair.other_prefix.fields; let t_index = prefix_type_map.get_index(&t_utid); let mut o_index = prefix_type_map.get_index(&o_utid); if t_index == o_index { o_index = None; } let (min_prefix, mut max_prefix) = pair.this_prefix.min_max(pair.other_prefix); match (t_index, o_index) { (None, None) => { max_prefix.combine_fields_from(&min_prefix); let i = prefix_type_map .get_or_insert(t_utid, max_prefix) .into_inner() .index; prefix_type_map.associate_key(o_utid, i); } (Some(im_index), None) | (None, Some(im_index)) => { max_prefix.combine_fields_from(&min_prefix); let im_prefix = prefix_type_map.get_mut_with_index(im_index).unwrap(); let im_prefix_addr = im_prefix as *const _ as usize; let (min_prefix, max_prefix) = min_max_by(im_prefix, &mut max_prefix, |x| x.fields.len()); self.check_prefix_types(errs, min_prefix, max_prefix); if !errs.is_empty() || errors_before != self.errors.len() { break; } max_prefix.combine_fields_from(&*min_prefix); if im_prefix_addr != (max_prefix as *mut _ as usize) { mem::swap(min_prefix, max_prefix); } prefix_type_map.associate_key(t_utid, im_index); prefix_type_map.associate_key(o_utid, im_index); } (Some(l_index), Some(r_index)) => { let (l_prefix, r_prefix) = prefix_type_map.get2_mut_with_index(l_index, r_index); let l_prefix = l_prefix.unwrap(); let r_prefix = r_prefix.unwrap(); let (replace, with) = if l_prefix.fields.len() < r_prefix.fields.len() { (l_index, r_index) } else { (r_index, l_index) }; let (min_prefix, max_prefix) = min_max_by(l_prefix, r_prefix, |x| x.fields.len()); self.check_prefix_types(errs, min_prefix, max_prefix); if !errs.is_empty() || errors_before != self.errors.len() { break; } max_prefix.combine_fields_from(&*min_prefix); prefix_type_map.replace_with_index(replace, with); } } } if errs_.is_empty() { Ok(()) } else { Err(AbiInstabilityError { stack_trace: self.stack_trace.clone(), errs: errs_, index: self.error_index, _priv: (), }) } } /// Combines the nonexhaustive enums into a global map of nonexhaustive enums. fn final_non_exhaustive_enum_checks( &mut self, globals: &CheckingGlobals, ) -> Result<(), AbiInstabilityError> { self.error_index += 1; let mut errs_ = RVec::<AbiInstability>::new(); let errs = &mut errs_; let mut nonexhaustive_map = globals.nonexhaustive_map.lock().unwrap(); for pair in mem::take(&mut self.checked_nonexhaustive_enums) { let CheckedNonExhaustiveEnums { this, other } = pair; let errors_before = self.errors.len(); let t_utid = this.layout.get_utypeid(); let o_utid = other.layout.get_utypeid(); let t_index = nonexhaustive_map.get_index(&t_utid); let mut o_index = nonexhaustive_map.get_index(&o_utid); if t_index == o_index { o_index = None; } let mut max_ = max_by(this, other, |x| x.enum_.variant_count()); match (t_index, o_index) { (None, None) => { let i = nonexhaustive_map .get_or_insert(t_utid, max_) .into_inner() .index; nonexhaustive_map.associate_key(o_utid, i); } (Some(im_index), None) | (None, Some(im_index)) => { let im_nonexh = nonexhaustive_map.get_mut_with_index(im_index).unwrap(); let im_nonexh_addr = im_nonexh as *const _ as usize; let (min_nonexh, max_nonexh) = min_max_by(im_nonexh, &mut max_, |x| x.enum_.variant_count()); self.check_enum( errs, min_nonexh.layout, max_nonexh.layout, min_nonexh.enum_, max_nonexh.enum_, ); if !errs.is_empty() || errors_before != self.errors.len() { break; } if im_nonexh_addr != (max_nonexh as *mut _ as usize) { mem::swap(min_nonexh, max_nonexh); } nonexhaustive_map.associate_key(t_utid, im_index); nonexhaustive_map.associate_key(o_utid, im_index); } (Some(l_index), Some(r_index)) => { let (l_nonexh, r_nonexh) = nonexhaustive_map.get2_mut_with_index(l_index, r_index); let l_nonexh = l_nonexh.unwrap(); let r_nonexh = r_nonexh.unwrap(); let (replace, with) = if l_nonexh.enum_.variant_count() < r_nonexh.enum_.variant_count() { (l_index, r_index) } else { (r_index, l_index) }; let (min_nonexh, max_nonexh) = min_max_by(l_nonexh, r_nonexh, |x| x.enum_.variant_count()); self.check_enum( errs, min_nonexh.layout, max_nonexh.layout, min_nonexh.enum_, max_nonexh.enum_, ); if !errs.is_empty() || errors_before != self.errors.len() { break; } nonexhaustive_map.replace_with_index(replace, with); } } } if errs_.is_empty() { Ok(()) } else { Err(AbiInstabilityError { stack_trace: self.stack_trace.clone(), errs: errs_, index: self.error_index, _priv: (), }) } } /// Combines the ExtraChecksBox into a global map. fn final_extra_checks( &mut self, globals: &CheckingGlobals, ) -> Result<(), RVec<AbiInstabilityError>> { self.error_index += 1; let mut top_level_errs_ = RVec::<AbiInstabilityError>::new(); let mut errs_ = RVec::<AbiInstability>::new(); let errs = &mut errs_; let top_level_errs = &mut top_level_errs_; let mut extra_checker_map = globals.extra_checker_map.lock().unwrap(); for with_context in mem::take(&mut self.checked_extra_checks) { let ExtraChecksBoxWithContext { t_lay, o_lay, extra_checks, } = with_context; let errors_before = self.errors.len(); let type_checker = TypeCheckerMut::from_ptr(&mut *self, TD_Opaque); let t_utid = t_lay.get_utypeid(); let o_utid = o_lay.get_utypeid(); let t_index = extra_checker_map.get_index(&t_utid); let mut o_index = extra_checker_map.get_index(&o_utid); if t_index == o_index { o_index = None; } match (t_index, o_index) { (None, None) => { let i = extra_checker_map .get_or_insert(t_utid, extra_checks) .into_inner() .index; extra_checker_map.associate_key(o_utid, i); } (Some(im_index), None) | (None, Some(im_index)) => { let other_checks = extra_checker_map.get_mut_with_index(im_index).unwrap(); combine_extra_checks( errs, top_level_errs, type_checker, other_checks, &[extra_checks.sabi_reborrow()], ); if !errs.is_empty() || errors_before != self.errors.len() { break; } extra_checker_map.associate_key(t_utid, im_index); extra_checker_map.associate_key(o_utid, im_index); } (Some(l_index), Some(r_index)) => { let (l_extra_checks, r_extra_checks) = extra_checker_map.get2_mut_with_index(l_index, r_index); let l_extra_checks = l_extra_checks.unwrap(); let r_extra_checks = r_extra_checks.unwrap(); combine_extra_checks( errs, top_level_errs, type_checker, l_extra_checks, &[r_extra_checks.sabi_reborrow(), extra_checks.sabi_reborrow()], ); if !errs.is_empty() || errors_before != self.errors.len() { break; } extra_checker_map.replace_with_index(r_index, l_index); } } } if errs_.is_empty() { Ok(()) } else { top_level_errs.push(AbiInstabilityError { stack_trace: self.stack_trace.clone(), errs: errs_, index: self.error_index, _priv: (), }); Err(top_level_errs_) } } } /// Checks that the layout of `interface` is compatible with `implementation`. /// /// # Warning /// /// This function is not symmetric, /// the first parameter must be the expected layout, /// and the second must be actual layout. /// pub fn check_layout_compatibility( interface: &'static TypeLayout, implementation: &'static TypeLayout, ) -> Result<(), AbiInstabilityErrors> { check_layout_compatibility_with_globals(interface, implementation, get_checking_globals()) } #[inline(never)] pub fn check_layout_compatibility_with_globals( interface: &'static TypeLayout, implementation: &'static TypeLayout, globals: &CheckingGlobals, ) -> Result<(), AbiInstabilityErrors> { let mut errors: RVec<AbiInstabilityError>; if interface.is_prefix_kind() || implementation.is_prefix_kind() { let mut errs = RVec::with_capacity(1); push_err( &mut errs, interface, implementation, |x| x.data_discriminant(), AI::TLDataDiscriminant, ); errors = vec![AbiInstabilityError { stack_trace: vec![].into(), errs, index: 0, _priv: (), }] .into(); } else { let mut checker = AbiChecker::new(); let _ = checker.check_inner(interface, implementation); if checker.errors.is_empty() { if let Err(e) = checker.final_prefix_type_checks(globals) { checker.errors.push(e); } if let Err(e) = checker.final_non_exhaustive_enum_checks(globals) { checker.errors.push(e); } if let Err(e) = checker.final_extra_checks(globals) { checker.errors.extend(e); } } errors = checker.errors; } if errors.is_empty() { Ok(()) } else { errors.sort_by_key(|x| x.index); Err(AbiInstabilityErrors { interface, implementation, errors, _priv: (), }) } } /// Checks that the layout of `interface` is compatible with `implementation`, pub(crate) extern "C" fn check_layout_compatibility_for_ffi( interface: &'static TypeLayout, implementation: &'static TypeLayout, ) -> RResult<(), RBoxError> { extern_fn_panic_handling! { let mut is_already_inside=false; INSIDE_LAYOUT_CHECKER.with(|inside|{ is_already_inside=inside.get(); inside.set(true); }); let _guard=LayoutCheckerGuard; if is_already_inside { let errors = vec![AbiInstabilityError { stack_trace: vec![].into(), errs:vec![AbiInstability::ReentrantLayoutCheckingCall].into(), index: 0, _priv:(), }].into_c(); Err(AbiInstabilityErrors{ interface, implementation, errors, _priv:() }) }else{ check_layout_compatibility(interface,implementation) }.map_err(RBoxError::new) .into_c() } } /// Checks that the layout of `interface` is compatible with `implementation`, /// /// If this function is called within a dynamic library, /// it must be called during or after the function that exports its root module is called. /// /// **DO NOT** call this in the static initializer of a dynamic library, /// since this library relies on setting up its global state before /// calling the root module loader. /// /// # Warning /// /// This function is not symmetric, /// the first parameter must be the expected layout, /// and the second must be actual layout. /// /// pub extern "C" fn exported_check_layout_compatibility( interface: &'static TypeLayout, implementation: &'static TypeLayout, ) -> RResult<(), RBoxError> { extern_fn_panic_handling! { (crate::globals::initialized_globals().layout_checking) (interface,implementation) } } impl AbiChecker { fn check_compatibility_inner( &mut self, interface: &'static TypeLayout, implementation: &'static TypeLayout, ) -> RResult<(), ()> { let error_count_before = self.errors.len(); self.current_layer += 1; let res = self.check_inner(interface, implementation); self.current_layer -= 1; if error_count_before == self.errors.len() && res.is_ok() { ROk(()) } else { RErr(()) } } } unsafe impl TypeChecker for AbiChecker { fn check_compatibility( &mut self, interface: &'static TypeLayout, implementation: &'static TypeLayout, ) -> RResult<(), ExtraChecksError> { self.check_compatibility_inner(interface, implementation) .map_err(|_| ExtraChecksError::TypeChecker) } fn local_check_compatibility( &mut self, interface: &'static TypeLayout, implementation: &'static TypeLayout, ) -> RResult<(), ExtraChecksError> { let error_count_before = self.errors.len(); dbg!(error_count_before); println!( "interface:{} implementation:{}", interface.full_type(), implementation.full_type() ); self.check_compatibility_inner(interface, implementation) .map_err(|_| { AbiInstabilityErrors { interface, implementation, errors: self.errors.drain(error_count_before..).collect(), _priv: (), } .piped(RBoxError::new) .piped(ExtraChecksError::TypeCheckerErrors) }) } } /////////////////////////////////////////////// thread_local! { static INSIDE_LAYOUT_CHECKER:Cell<bool>=Cell::new(false); } struct LayoutCheckerGuard; impl Drop for LayoutCheckerGuard { fn drop(&mut self) { INSIDE_LAYOUT_CHECKER.with(|inside| { inside.set(false); }); } } /////////////////////////////////////////////// use std::sync::Mutex; use crate::{ multikey_map::MultiKeyMap, prefix_type::__PrefixTypeMetadata, sabi_types::LateStaticRef, utils::leak_value, }; #[derive(Debug)] pub struct CheckingGlobals { pub prefix_type_map: Mutex<MultiKeyMap<UTypeId, __PrefixTypeMetadata>>, pub nonexhaustive_map: Mutex<MultiKeyMap<UTypeId, NonExhaustiveEnumWithContext>>, pub extra_checker_map: Mutex<MultiKeyMap<UTypeId, ExtraChecksBox>>, } #[allow(clippy::new_without_default)] impl CheckingGlobals { pub fn new() -> Self { CheckingGlobals { prefix_type_map: MultiKeyMap::new().piped(Mutex::new), nonexhaustive_map: MultiKeyMap::new().piped(Mutex::new), extra_checker_map: MultiKeyMap::new().piped(Mutex::new), } } } static CHECKING_GLOBALS: LateStaticRef<&CheckingGlobals> = LateStaticRef::new(); pub fn get_checking_globals() -> &'static CheckingGlobals { CHECKING_GLOBALS.init(|| CheckingGlobals::new().piped(leak_value)) } /////////////////////////////////////////////// pub(crate) fn push_err<O, U, FG, VC>( errs: &mut RVec<AbiInstability>, this: O, other: O, field_getter: FG, mut variant_constructor: VC, ) where FG: FnMut(O) -> U, VC: FnMut(ExpectedFound<U>) -> AbiInstability, { let x = ExpectedFound::new(this, other, field_getter); let x = variant_constructor(x); errs.push(x); } fn handle_extra_checks_ret<F, R>( expected_extra_checks: ExtraChecksRef<'_>, found_extra_checks: ExtraChecksRef<'_>, errs: &mut RVec<AbiInstability>, top_level_errs: &mut RVec<AbiInstabilityError>, f: F, ) -> Result<R, ()> where F: FnOnce() -> RResult<R, ExtraChecksError>, { let make_extra_check_error = move |e: RBoxError| -> AbiInstability { ExtraCheckError { err: RArc::new(e), expected_err: ExpectedFound { expected: expected_extra_checks .piped_ref(RBoxError::from_fmt) .piped(RArc::new), found: found_extra_checks .piped_ref(RBoxError::from_fmt) .piped(RArc::new), }, } .piped(CmpIgnored::new) .piped(AI::ExtraCheckError) }; match f() { ROk(x) => Ok(x), RErr(ExtraChecksError::TypeChecker) => Err(()), RErr(ExtraChecksError::TypeCheckerErrors(e)) => { match e.downcast::<AbiInstabilityErrors>() { Ok(e) => top_level_errs.extend(RBox::into_inner(e).errors), Err(e) => errs.push(make_extra_check_error(e)), } Err(()) } RErr(ExtraChecksError::NoneExtraChecks) => { errs.push(AI::NoneExtraChecks); Err(()) } RErr(ExtraChecksError::ExtraChecks(e)) => { errs.push(make_extra_check_error(e)); Err(()) } } } fn combine_extra_checks( errs: &mut RVec<AbiInstability>, top_level_errs: &mut RVec<AbiInstabilityError>, mut ty_checker: TypeCheckerMut<'_>, extra_checks: &mut ExtraChecksBox, slic: &[ExtraChecksRef<'_>], ) { for other in slic { let other_ref = other.sabi_reborrow(); let ty_checker = ty_checker.sabi_reborrow_mut(); let opt_ret = handle_extra_checks_ret( extra_checks.sabi_reborrow(), other.sabi_reborrow(), errs, top_level_errs, || extra_checks.sabi_reborrow().combine(other_ref, ty_checker), ); match opt_ret { Ok(RSome(new)) => { *extra_checks = new; } Ok(RNone) => {} Err(_) => break, } } }
use crate::assets::prefab::PrefabManager; use crate::assets::Handle; use crate::core::animation::AnimationController; use crate::core::colors; use crate::core::random::RandomGenerator; use crate::core::timer::Timer; use crate::core::transform::Transform; use crate::event::GameEvent; use crate::gameplay::bullet::{spawn_enemy_bullet, spawn_missile, BulletType}; use crate::gameplay::collision::CollisionLayer; use crate::gameplay::explosion::{ExplosionDetails, ExplosionType}; use crate::gameplay::health::HitDetails; use crate::gameplay::physics::DynamicBody; use crate::gameplay::player::{get_player, Player}; use crate::gameplay::steering::behavior::{ avoid_obstacles, follow_player, follow_player_bis, follow_random_path, }; use crate::render::path::debug; use crate::resources::Resources; use hecs::World; use log::{debug, trace}; use luminance_glfw::GlfwSurface; use rand::Rng; use serde_derive::{Deserialize, Serialize}; use shrev::EventChannel; use std::time::Duration; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Enemy { pub enemy_type: EnemyType, /// amount of scrap to give to the player. pub scrap_drop: (u32, u32), /// % of chance to drop a pickup. pub pickup_drop_percent: u8, pub movement: MovementBehavior, } impl Default for Enemy { fn default() -> Self { Self { enemy_type: EnemyType::FollowPlayer(Timer::of_seconds(4.0)), pickup_drop_percent: 0, scrap_drop: (10, 50), movement: MovementBehavior::Follow, } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum MovementBehavior { /// Move toward the player. Avoid basic obstacles Follow, /// Move towards player. Avoid nothing. Very blunt. GoToPlayer, /// Follow a path. Each point will be randomly generated. RandomPath(glam::Vec2, bool), /// Do not move. Nothing, } impl Default for MovementBehavior { fn default() -> Self { Self::Follow } } impl MovementBehavior { pub fn apply( &mut self, e: hecs::Entity, t: &mut Transform, body: &mut DynamicBody, maybe_player: Option<glam::Vec2>, resources: &Resources, ) { let ignore_mask = CollisionLayer::ENEMY_BULLET | CollisionLayer::PLAYER_BULLET | CollisionLayer::PICKUP | CollisionLayer::MINE; match self { Self::Nothing => (), Self::GoToPlayer => { follow_player_bis(t, body, maybe_player, resources); avoid_obstacles(e, t, body, resources, ignore_mask | CollisionLayer::PLAYER); } Self::Follow => { follow_player(t, body, maybe_player, resources); avoid_obstacles(e, t, body, resources, ignore_mask); } Self::RandomPath(ref mut target, ref mut is_init) => { follow_random_path(target, is_init, t, body, resources); avoid_obstacles(e, t, body, resources, ignore_mask); } } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum EnemyType { FollowPlayer(Timer), Satellite(Satellite), Boss1(Boss1), Carrier { time_between_deploy: Timer, nb_of_spaceships: usize, }, /// Drop some mines like an asshole. MineLander(Timer), /// Move randomly like mine lander, but shoots instead Wanderer(Timer), /// Move randomly like mine lander, but shoots instead Spammer(Spammer), /// Will explode when player comes near, Mine { /// Distance from the player below which the mine will be triggered trigger_distance: f32, /// Time from when the mine is triggered until the mine explode. explosion_timer: Timer, }, /// Go straight towards the player and explode on contact. Kamikaze, /// last boss. Is a real a**hole LastBoss(LastBoss), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Boss1 { /// Time between shots pub shoot_timer: Timer, /// nb of time to shoot during a salve pub nb_shot: usize, /// nb of shots during current salve. pub current_shot: usize, /// timeout between salves. pub salve_timer: Timer, } impl Boss1 { fn should_shoot(&mut self) -> bool { self.nb_shot != self.current_shot } fn prepare_to_shoot(&mut self) { self.shoot_timer.reset(); self.shoot_timer.start(); self.salve_timer.reset(); self.salve_timer.stop(); self.current_shot = 0; } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct LastBoss { /// Time between shots pub shoot_timer: Timer, /// nb of time to shoot during a salve pub nb_shot: usize, /// nb of shots during current salve. pub current_shot: usize, /// timeout between salves. pub salve_timer: Timer, } impl LastBoss { fn should_shoot(&mut self) -> bool { self.nb_shot != self.current_shot } fn prepare_to_shoot(&mut self) { self.shoot_timer.reset(); self.shoot_timer.start(); self.salve_timer.reset(); self.salve_timer.stop(); self.current_shot = 0; } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Spammer { /// Time between shots pub shoot_timer: Timer, /// nb of time to shoot during a salve pub nb_shot: usize, /// nb of shots during current salve. pub current_shot: usize, /// timeout between salves. pub salve_timer: Timer, } impl Spammer { fn should_shoot(&mut self) -> bool { self.nb_shot != self.current_shot } fn prepare_to_shoot(&mut self) { self.shoot_timer.reset(); self.shoot_timer.start(); self.salve_timer.reset(); self.salve_timer.stop(); self.current_shot = 0; } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Satellite { /// Time between missiles pub shoot_timer: Timer, /// Detection distance for player pub shoot_distance: f32, } impl Default for Satellite { fn default() -> Self { Self { shoot_distance: 500.0, shoot_timer: Timer::of_seconds(5.0), } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Route { pub path: Vec<glam::Vec2>, #[serde(default)] pub current: usize, } impl Route { pub fn get_current(&self) -> Option<glam::Vec2> { self.path.get(self.current).map(|v| *v) } pub fn go_to_next(&mut self) { self.current = (self.current + 1) % self.path.len() } pub fn debug_draw(&self, resources: &Resources) { if self.path.len() == 0 { return; } // for i in 0..self.path.len() - 1 { let p1 = self.path[i]; let p2 = self.path[i + 1]; debug::stroke_line(resources, p1, p2, colors::GREEN); } } } pub fn update_enemies(world: &mut World, resources: &Resources, dt: Duration) { trace!("update_enemies"); let maybe_player = get_player(world); if let None = maybe_player { return; } let player = maybe_player.unwrap(); let mut ev_channel = resources.fetch_mut::<EventChannel<GameEvent>>().unwrap(); // prefabs to spawn. let mut to_spawn: Vec<(String, glam::Vec2)> = vec![]; let mut spaceship_to_spawn = vec![]; let mut bullets = vec![]; let mut to_remove = vec![]; let mut missiles = vec![]; let maybe_player = world .query::<(&Player, &Transform)>() .iter() .map(|(_, (_, t))| t.translation) .next(); for (e, (t, enemy, body, animation)) in world .query::<( &mut Transform, &mut Enemy, &mut DynamicBody, Option<&mut AnimationController>, )>() .iter() { enemy.movement.apply(e, t, body, maybe_player, resources); //follow_player(t, body, maybe_player, resources); //avoid_obstacles(e, t, body, resources); // Basic movement. if let Some(player_position) = maybe_player { let dir = player_position - t.translation; match enemy.enemy_type { EnemyType::Kamikaze => { if (t.translation - player_position).length() < 60.0 { to_remove.push(GameEvent::Delete(e)); to_remove.push(GameEvent::Explosion( e, ExplosionDetails { radius: 100.0, ty: ExplosionType::First, }, t.translation, )); to_remove.push(GameEvent::EnemyDied( e, t.translation, enemy.scrap_drop, enemy.pickup_drop_percent, )); } } EnemyType::Carrier { nb_of_spaceships, ref mut time_between_deploy, } => { time_between_deploy.tick(dt); if time_between_deploy.finished() { time_between_deploy.reset(); spaceship_to_spawn.push((e, t.translation, nb_of_spaceships)); } } EnemyType::LastBoss(ref mut boss) => { if boss.should_shoot() { boss.shoot_timer.tick(dt); if boss.shoot_timer.finished() { boss.shoot_timer.reset(); // shoot. let d = dir.normalize(); for i in 0..12 { bullets.push(( t.translation, glam::Mat2::from_angle( i as f32 * std::f32::consts::PI / 6.0 + boss.current_shot as f32 * std::f32::consts::PI / 24.0, ) * d, BulletType::Fast, )); } ev_channel.single_write(GameEvent::PlaySound( "sounds/scifi_kit/Laser/Laser_04.wav".to_string(), )); boss.current_shot += 1; } } else { // if here, boss1 needs to wait before it is able to shoot again. boss.salve_timer.tick(dt); if boss.salve_timer.finished() { boss.prepare_to_shoot(); } } } EnemyType::Spammer(ref mut spammer) => { if spammer.should_shoot() { spammer.shoot_timer.tick(dt); if spammer.shoot_timer.finished() { spammer.shoot_timer.reset(); // shoot. let d = dir.normalize(); bullets.push((t.translation, d, BulletType::Round1)); bullets.push(( t.translation, glam::Mat2::from_angle(std::f32::consts::FRAC_PI_4) * d, BulletType::Round1, )); bullets.push(( t.translation, glam::Mat2::from_angle(-std::f32::consts::FRAC_PI_4) * d, BulletType::Round1, )); bullets.push(( t.translation, glam::Mat2::from_angle(-std::f32::consts::FRAC_PI_3) * d, BulletType::Round1, )); bullets.push(( t.translation, glam::Mat2::from_angle(std::f32::consts::FRAC_PI_3) * d, BulletType::Round1, )); ev_channel.single_write(GameEvent::PlaySound( "sounds/scifi_kit/Laser/Laser_04.wav".to_string(), )); spammer.current_shot += 1; } } else { // if here, boss1 needs to wait before it is able to shoot again. spammer.salve_timer.tick(dt); if spammer.salve_timer.finished() { spammer.prepare_to_shoot(); } } } EnemyType::Boss1(ref mut boss1) => { if boss1.should_shoot() { boss1.shoot_timer.tick(dt); if boss1.shoot_timer.finished() { boss1.shoot_timer.reset(); // shoot. let to_spawn = (t.translation, dir.normalize(), BulletType::Round2); bullets.push(to_spawn); ev_channel.single_write(GameEvent::PlaySound( "sounds/scifi_kit/Laser/Laser_03.wav".to_string(), )); boss1.current_shot += 1; } } else { // if here, boss1 needs to wait before it is able to shoot again. boss1.salve_timer.tick(dt); if boss1.salve_timer.finished() { boss1.prepare_to_shoot(); } } } EnemyType::Satellite(ref mut sat) => { // If the player is really close, will shoot some missiles. sat.shoot_timer.tick(dt); if dir.length() < sat.shoot_distance { if sat.shoot_timer.finished() { sat.shoot_timer.reset(); let norm_dir = dir.normalize(); missiles.push(( t.translation + norm_dir * t.scale.x * 2.0, // TODO better spawn points norm_dir, player, )); } } } EnemyType::FollowPlayer(ref mut shoot_timer) => { // shoot if it's time. shoot_timer.tick(dt); if (player_position - t.translation).length() < 1000.0 { if shoot_timer.finished() { shoot_timer.reset(); let to_spawn = (t.translation, dir.normalize(), BulletType::Round2); ev_channel.single_write(GameEvent::PlaySound( "sounds/scifi_kit/Laser/Laser_04.wav".to_string(), )); bullets.push(to_spawn); } } // Draw stuff to the screen. debug::stroke_circle(resources, t.translation, 1500.0, colors::RED); } EnemyType::Wanderer(ref mut timer) => { timer.tick(dt); if timer.finished() { timer.reset(); let d = dir.normalize(); bullets.push((t.translation, d, BulletType::Round1)); bullets.push(( t.translation, glam::Mat2::from_angle(std::f32::consts::FRAC_PI_2) * d, BulletType::Round1, )); bullets.push(( t.translation, glam::Mat2::from_angle(2.0 * std::f32::consts::FRAC_PI_2) * d, BulletType::Round1, )); bullets.push(( t.translation, glam::Mat2::from_angle(3.0 * std::f32::consts::FRAC_PI_2) * d, BulletType::Round1, )); ev_channel.single_write(GameEvent::PlaySound( "sounds/scifi_kit/Laser/Laser_04.wav".to_string(), )); } } EnemyType::MineLander(ref mut timer) => { timer.tick(dt); if timer.finished() { timer.reset(); to_spawn.push(("mine".to_string(), t.translation)); } } EnemyType::Mine { trigger_distance, ref mut explosion_timer, } => { if explosion_timer.enabled { if let Some(anim) = animation { if anim.current_animation.is_none() { anim.current_animation = Some("boum".to_string()); } t.scale = trigger_distance * glam::Vec2::one(); } explosion_timer.tick(dt); if explosion_timer.finished() { // badaboum to_remove.push(GameEvent::Delete(e)); to_remove.push(GameEvent::Explosion( e, ExplosionDetails { radius: trigger_distance, ty: ExplosionType::First, }, t.translation, )); } debug::stroke_circle( resources, t.translation, trigger_distance, colors::GREEN, ); } else { if (player_position - t.translation).length() < trigger_distance { // BOOM explosion_timer.reset(); explosion_timer.start(); } debug::stroke_circle( resources, t.translation, trigger_distance, colors::RED, ); } } } } } { let prefab_manager = resources.fetch_mut::<PrefabManager<GlfwSurface>>().unwrap(); for (prefab, pos) in to_spawn { if let Some(prefab) = prefab_manager.get(&Handle(prefab)) { prefab.execute(|prefab| { prefab.spawn_at_pos(world, pos); }); } } } for (pos, dir, bullet) in bullets { debug!("Will spawn bullet at position ={:?}", pos); spawn_enemy_bullet( world, pos, dir, bullet, HitDetails { hit_points: 1.0, is_crit: false, }, ); } for (pos, dir, entity) in missiles { spawn_missile( world, pos, dir, entity, CollisionLayer::PLAYER | CollisionLayer::PLAYER_BULLET, ); } { let prefab_manager = resources.fetch_mut::<PrefabManager<GlfwSurface>>().unwrap(); let mut random = resources.fetch_mut::<RandomGenerator>().unwrap(); for (_e, pos, nb) in spaceship_to_spawn { if let Some(asset) = prefab_manager.get(&Handle("kamikaze".to_string())) { for _ in 0..nb { asset.execute(|prefab| { let e = prefab.spawn_at_pos(world, pos); if let Ok(mut body) = world.get_mut::<DynamicBody>(e) { let angle = random.rng().gen_range(0.0, std::f32::consts::PI * 2.0); let impulse = 500.0 * glam::Mat2::from_angle(angle) * glam::Vec2::unit_y(); body.add_impulse(impulse); } }); } } } } ev_channel.drain_vec_write(&mut to_remove); trace!("Finished update_enemies") }
//! Config program use log::*; use morgan_interface::account::KeyedAccount; use morgan_interface::instruction::InstructionError; use morgan_interface::pubkey::Pubkey; use morgan_helper::logHelper::*; pub fn process_instruction( _program_id: &Pubkey, keyed_accounts: &mut [KeyedAccount], data: &[u8], _tick_height: u64, ) -> Result<(), InstructionError> { if keyed_accounts[0].signer_key().is_none() { // error!("{}", Error(format!("account[0].signer_key().is_none()").to_string())); println!( "{}", Error( format!("account[0].signer_key().is_none()").to_string(), module_path!().to_string() ) ); Err(InstructionError::MissingRequiredSignature)?; } if keyed_accounts[0].account.data.len() < data.len() { // error!("{}", Error(format!("instruction data too large").to_string())); println!( "{}", Error( format!("instruction data too large").to_string(), module_path!().to_string() ) ); Err(InstructionError::InvalidInstructionData)?; } keyed_accounts[0].account.data[0..data.len()].copy_from_slice(data); Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::{config_instruction, id, ConfigState}; use bincode::{deserialize, serialized_size}; use serde_derive::{Deserialize, Serialize}; use morgan_runtime::bank::Bank; use morgan_runtime::bank_client::BankClient; use morgan_interface::client::SyncClient; use morgan_interface::genesis_block::create_genesis_block; use morgan_interface::message::Message; use morgan_interface::signature::{Keypair, KeypairUtil}; use morgan_interface::system_instruction; #[derive(Serialize, Deserialize, Default, Debug, PartialEq)] struct MyConfig { pub item: u64, } impl MyConfig { pub fn new(item: u64) -> Self { Self { item } } pub fn deserialize(input: &[u8]) -> Option<Self> { deserialize(input).ok() } } impl ConfigState for MyConfig { fn max_space() -> u64 { serialized_size(&Self::default()).unwrap() } } fn create_bank(difs: u64) -> (Bank, Keypair) { let (genesis_block, mint_keypair) = create_genesis_block(difs); let mut bank = Bank::new(&genesis_block); bank.add_instruction_processor(id(), process_instruction); (bank, mint_keypair) } fn create_config_account(bank: Bank, mint_keypair: &Keypair) -> (BankClient, Keypair) { let config_keypair = Keypair::new(); let config_pubkey = config_keypair.pubkey(); let bank_client = BankClient::new(bank); bank_client .send_instruction( mint_keypair, config_instruction::create_account::<MyConfig>( &mint_keypair.pubkey(), &config_pubkey, 1, ), ) .expect("new_account"); (bank_client, config_keypair) } #[test] fn test_process_create_ok() { morgan_logger::setup(); let (bank, mint_keypair) = create_bank(10_000); let (bank_client, config_keypair) = create_config_account(bank, &mint_keypair); let config_account_data = bank_client .get_account_data(&config_keypair.pubkey()) .unwrap() .unwrap(); assert_eq!( MyConfig::default(), MyConfig::deserialize(&config_account_data).unwrap() ); } #[test] fn test_process_store_ok() { morgan_logger::setup(); let (bank, mint_keypair) = create_bank(10_000); let (bank_client, config_keypair) = create_config_account(bank, &mint_keypair); let config_pubkey = config_keypair.pubkey(); let my_config = MyConfig::new(42); let instruction = config_instruction::store(&config_pubkey, &my_config); let message = Message::new_with_payer(vec![instruction], Some(&mint_keypair.pubkey())); bank_client .send_message(&[&mint_keypair, &config_keypair], message) .unwrap(); let config_account_data = bank_client .get_account_data(&config_pubkey) .unwrap() .unwrap(); assert_eq!( my_config, MyConfig::deserialize(&config_account_data).unwrap() ); } #[test] fn test_process_store_fail_instruction_data_too_large() { morgan_logger::setup(); let (bank, mint_keypair) = create_bank(10_000); let (bank_client, config_keypair) = create_config_account(bank, &mint_keypair); let config_pubkey = config_keypair.pubkey(); let my_config = MyConfig::new(42); let mut instruction = config_instruction::store(&config_pubkey, &my_config); instruction.data = vec![0; 123]; // <-- Replace data with a vector that's too large let message = Message::new(vec![instruction]); bank_client .send_message(&[&config_keypair], message) .unwrap_err(); } #[test] fn test_process_store_fail_account0_not_signer() { morgan_logger::setup(); let (bank, mint_keypair) = create_bank(10_000); let system_keypair = Keypair::new(); let system_pubkey = system_keypair.pubkey(); bank.transfer(42, &mint_keypair, &system_pubkey).unwrap(); let (bank_client, config_keypair) = create_config_account(bank, &mint_keypair); let config_pubkey = config_keypair.pubkey(); let transfer_instruction = system_instruction::transfer(&system_pubkey, &Pubkey::new_rand(), 42); let my_config = MyConfig::new(42); let mut store_instruction = config_instruction::store(&config_pubkey, &my_config); store_instruction.accounts[0].is_signer = false; // <----- not a signer let message = Message::new(vec![transfer_instruction, store_instruction]); bank_client .send_message(&[&system_keypair], message) .unwrap_err(); } }
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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. //! Core Foundation byte buffers. pub use core_foundation_sys::data::*; use core_foundation_sys::base::CFIndex; use core_foundation_sys::base::{kCFAllocatorDefault}; use std::ops::Deref; use std::slice; use base::{CFIndexConvertible, TCFType}; declare_TCFType!{ /// A byte buffer. CFData, CFDataRef } impl_TCFType!(CFData, CFDataRef, CFDataGetTypeID); impl_CFTypeDescription!(CFData); impl CFData { pub fn from_buffer(buffer: &[u8]) -> CFData { unsafe { let data_ref = CFDataCreate(kCFAllocatorDefault, buffer.as_ptr(), buffer.len().to_CFIndex()); TCFType::wrap_under_create_rule(data_ref) } } /// Returns a pointer to the underlying bytes in this data. Note that this byte buffer is /// read-only. #[inline] pub fn bytes<'a>(&'a self) -> &'a [u8] { unsafe { slice::from_raw_parts(CFDataGetBytePtr(self.0), self.len() as usize) } } /// Returns the length of this byte buffer. #[inline] pub fn len(&self) -> CFIndex { unsafe { CFDataGetLength(self.0) } } } impl Deref for CFData { type Target = [u8]; #[inline] fn deref(&self) -> &[u8] { self.bytes() } }
// 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. //! Schedule pings when they need to be scheduled, provide an estimation of round trip time use std::collections::{HashMap, VecDeque}; use std::time::{Duration, Instant}; const MIN_PING_SPACING: Duration = Duration::from_millis(100); const MAX_PING_SPACING: Duration = Duration::from_secs(20); const MAX_SAMPLE_AGE: Duration = Duration::from_secs(2 * 60); const MAX_PING_AGE: Duration = Duration::from_secs(15); /// A pong record includes an id and the amount of time taken to schedule the pong #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Pong { /// The requestors ping id pub id: u64, /// The queue time (in microseconds) before responding pub queue_time: u64, } /// Structure returning actions that need to be scheduled in response to a PingTracker operation #[must_use = "This result may contain actions that users need to act upon"] #[derive(Debug, PartialEq)] pub struct PingTrackerResult { pub sched_timeout: Option<Duration>, pub sched_send: bool, pub new_round_trip_time: bool, } #[derive(Debug)] struct Sample { when: Instant, rtt_us: i64, } /// Schedule pings when they need to be scheduled, provide an estimation of round trip time #[derive(Debug)] pub struct PingTracker { samples: VecDeque<Sample>, mean: i64, variance: i64, sent_ping_map: HashMap<u64, Instant>, sent_ping_list: VecDeque<(u64, Instant)>, ping_spacing: Duration, used_ping_spacing: bool, last_ping_sent: Option<Instant>, scheduled_timeout: Option<Instant>, scheduled_send: bool, next_ping_id: u64, published_mean: i64, } fn square(a: i64) -> Option<i64> { a.checked_mul(a) } impl PingTracker { /// Setup a new (empty) PingTracker pub fn new() -> (PingTracker, PingTrackerResult) { let tracker = PingTracker { samples: VecDeque::new(), mean: 0, variance: 0, sent_ping_map: HashMap::new(), sent_ping_list: VecDeque::new(), ping_spacing: Duration::from_millis(100), used_ping_spacing: true, last_ping_sent: None, scheduled_send: true, scheduled_timeout: None, next_ping_id: 1, published_mean: 0, }; let ptres = PingTrackerResult { sched_send: true, sched_timeout: None, new_round_trip_time: false }; (tracker, ptres) } /// Query current round trip time pub fn round_trip_time(&self) -> Option<Duration> { if self.mean > 0 { Some(Duration::from_micros(self.mean as u64)) } else { None } } fn send_ping(&mut self, now: Instant) -> Option<u64> { self.last_ping_sent = Some(now); let id = self.next_ping_id; self.next_ping_id += 1; self.sent_ping_map.insert(id, now); self.sent_ping_list.push_back((id, now)); Some(id) } /// Returns a ping id if a ping needs to be sent, updating tracking to indicate that the ping /// was sent. pub fn maybe_send_ping( &mut self, now: Instant, empty_packet: bool, ) -> (Option<u64>, PingTrackerResult) { self.mutate(now, |this| { log::trace!( "MAYBE SEND PING: empty_packet:{} last_ping_sent:{:?} ping_spacing:{:?} now:{:?}", empty_packet, this.last_ping_sent, this.ping_spacing, now ); if empty_packet { this.scheduled_send = false; } if let Some(last_ping_sent) = this.last_ping_sent { if now >= last_ping_sent + this.ping_spacing { this.send_ping(now) } else { None } } else { this.send_ping(now) } }) } /// Upon timeout: check whether that timeout causes a ping to need to be scheduled pub fn on_timeout(&mut self, now: Instant) -> PingTrackerResult { self.mutate(now, |this| { log::trace!( "TIMEOUT: now:{:?} samples:{:?} sent_ping_list:{:?} sent_ping_map:{:?}", now, this.samples, this.sent_ping_list, this.sent_ping_map ); this.scheduled_timeout = None; let epoch = now - MAX_SAMPLE_AGE; while this.samples.len() > 3 && this.samples[0].when < epoch { this.samples.pop_front(); } let epoch = now - MAX_PING_AGE; while this.sent_ping_list.len() > 1 && this.sent_ping_list[0].1 < epoch { this.sent_ping_map.remove(&this.sent_ping_list.pop_front().unwrap().0); } }) .1 } /// Upon receiving a pong: return a set of operations that need to be scheduled pub fn got_pong(&mut self, now: Instant, pong: Pong) -> PingTrackerResult { self.mutate(now, |this| { log::trace!( "GOT_PONG: {:?} now:{:?} sent_ping_map:{:?}", pong, now, this.sent_ping_map ); if let Some(send_time) = this.sent_ping_map.remove(&pong.id) { this.samples .push_back(Sample { when: now, rtt_us: (now - send_time).as_micros() as i64 }); } }) .1 } fn mutate<R>( &mut self, now: Instant, f: impl FnOnce(&mut Self) -> R, ) -> (R, PingTrackerResult) { log::trace!("BEGIN MUTATE"); let variance_before = self.variance; let r = f(self); if let Err(e) = self.recalculate_stats() { log::trace!("Failed to recalculate statistics: {}", e); self.mean = 0; self.variance = 0; } let variance_after = self.variance; log::trace!("END MUTATE: variance:{}->{} ping_spacing:{:?} mean:{} scheduled_send:{} scheduled_timeout:{:?}", variance_before, variance_after, self.ping_spacing, self.mean, self.scheduled_send, self.scheduled_timeout); if self.used_ping_spacing { if variance_after > variance_before { self.ping_spacing /= 2; if self.ping_spacing < MIN_PING_SPACING { self.ping_spacing = MIN_PING_SPACING; self.used_ping_spacing = false; } } else if variance_after < variance_before { self.ping_spacing = self.ping_spacing * 5 / 4; if self.ping_spacing > MAX_PING_SPACING { self.ping_spacing = MAX_PING_SPACING; self.used_ping_spacing = false; } } } let new_round_trip_time = self.mean > 0 && (self.published_mean <= 0 || (self.published_mean - self.mean).abs() > self.published_mean / 100); let mut sched_send = !self.scheduled_send && self.last_ping_sent.map_or(true, |tm| now >= tm + self.ping_spacing); let want_timeout = self.last_ping_sent.unwrap_or(now) + 2 * self.ping_spacing; let sched_timeout = if self.scheduled_timeout.map_or(true, |tm| tm > want_timeout) { self.scheduled_timeout = Some(want_timeout); if want_timeout > now { Some(want_timeout - now) } else { sched_send = true; None } } else { None }; if sched_send { self.scheduled_send = true; } (r, PingTrackerResult { sched_send, sched_timeout, new_round_trip_time }) } fn recalculate_stats(&mut self) -> Result<(), &'static str> { log::trace!( "RECALCSTATS: {:?}", self.samples.iter().map(|x| x.rtt_us).collect::<Vec<i64>>() ); let mut total = 0i64; let n = self.samples.len() as i64; if n == 0 { self.mean = 0; self.variance = 0; return Ok(()); } for Sample { rtt_us, .. } in self.samples.iter() { total = total.checked_add(*rtt_us).ok_or("Overflow calculating mean")?; } let mean = total / n; self.mean = mean; if n == 1 { self.variance = 0; return Ok(()); } let mut numer = 0; for Sample { rtt_us, .. } in self.samples.iter() { numer += square(rtt_us - mean).ok_or("Overflow calculating variance")?; } let variance = numer / (n - 1); self.variance = variance; Ok(()) } } /// Track which pings need pongs to be sent #[derive(Debug)] pub struct PongTracker { pong: Option<(u64, Instant)>, } impl PongTracker { /// Setup a new pong tracker pub fn new() -> PongTracker { PongTracker { pong: None } } /// Returns a Pong structure if a pong needs to be sent, updating tracking to indicate that the /// pong was sent. pub fn maybe_send_pong(&mut self) -> Option<Pong> { self.pong.take().map(|(id, received)| Pong { id, queue_time: (Instant::now() - received).as_micros() as u64, }) } /// Register that a ping was received, and return true if a pong should be sent at the next /// available opportunity pub fn got_ping(&mut self, id: u64) -> bool { self.pong.replace((id, Instant::now())).is_none() } } #[cfg(test)] mod test { use super::*; #[test] fn create() { assert_eq!( PingTracker::new().1, PingTrackerResult { sched_send: true, new_round_trip_time: false, sched_timeout: None } ); } }
pub mod errors; pub use errors::*; pub mod title; pub use title::*; pub mod author; pub use author::*; pub mod category; pub use category::*; pub mod description; pub use description::*; pub mod content_type; pub use content_type::*; pub mod question_type; pub use question_type::*;
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // https://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Wrappers / adapters forming RNGs #[cfg(feature="std")] #[doc(hidden)] pub mod read; mod reseeding; #[cfg(feature="std")] pub use self::read::ReadRng; pub use self::reseeding::ReseedingRng;
use std::os::raw::c_char; #[macro_export] macro_rules! cstr { ($s:expr) => { concat!($s, "\0") as *const str as *const [::std::os::raw::c_char] as *const ::std::os::raw::c_char }; } /// Metamod interface version. /// Declaration copy of META_INTERFACE_VERSION. /// Description copied from metamod-p sources: /// ``` /// Version consists of "major:minor", two separate integer numbers. /// Version 1 original /// Version 2 added plugin_info_t **pinfo /// Version 3 init split into query and attach, added detach /// Version 4 added (PLUG_LOADTIME now) to attach /// Version 5 changed mm ifvers int* to string, moved pl ifvers to info /// Version 5:1 added link support for entity "adminmod_timer" (adminmod) /// Version 5:2 added gamedll_funcs to meta_attach() [v1.0-rc2] /// Version 5:3 added mutil_funcs to meta_query() [v1.05] /// Version 5:4 added centersay utility functions [v1.06] /// Version 5:5 added Meta_Init to plugin API [v1.08] /// Version 5:6 added CallGameEntity utility function [v1.09] /// Version 5:7 added GetUserMsgID, GetUserMsgName util funcs [v1.11] /// Version 5:8 added GetPluginPath [v1.11] /// Version 5:9 added GetGameInfo [v1.14] /// Version 5:10 added GINFO_REALDLL_FULLPATH for GetGameInfo [v1.17] /// Version 5:11 added plugin loading and unloading API [v1.18] /// Version 5:12 added IS_QUERYING_CLIENT_CVAR to mutils [v1.18] /// Version 5:13 added MAKE_REQUESTID and GET_HOOK_TABLES to mutils [v1.19] /// ``` pub const METAMOD_INTERFACE_VERSION: *const c_char = cstr!("5:13"); /// Specifies when metamod plugin should be started /// This enum is a representation of PLUG_LOADTIME from metamod/plinfo.h #[repr(C)] pub enum PluginLoadTime { Never = 0, /// should only be loaded/unloaded at initial hlds execution Startup, /// can be loaded/unloaded between maps ChangeLevel, /// can be loaded/unloaded at any time AnyTime, /// can be loaded/unloaded at any time, and can be "paused" during a map AnyPause, } /// Metamod plugin info structure /// This struct is a representation of metamod/plinfo.h #[repr(C)] pub struct PluginInfo { /// metamod binary interface version. /// MetaRust only supports [METAMOD_INTERFACE_VERSION] pub interface_version: *const c_char, /// full name of plugin pub name: *const c_char, /// version in free format pub version: *const c_char, /// compilation date in free format pub date: *const c_char, /// author name/email pub author: *const c_char, /// plugin URL pub url: *const c_char, /// log message prefix (unused right now) pub logtag: *const c_char, /// when plugin is allowed to be loaded and attached pub loadable: PluginLoadTime, /// when plugin is allowed to be unloaded and detached pub unloadable: PluginLoadTime, }
use zoon::*; use crate::{router::Route, theme::Theme}; pub fn root() -> impl Element { Column::new() .s(Height::fill().min_screen()) .on_viewport_size_change(super::on_viewport_size_change) .item(header()) .item_signal(super::page_id().signal().map(page)) } fn header() -> impl Element { Row::with_tag(Tag::Nav) .s(Height::new(64)) .s(Background::new().color(Theme::Background1)) .s(Font::new().color(Theme::Font1)) .item(logo()) .item_signal(super::wide_screen().map_true(|| { Row::new().s(Height::fill()).items(menu_links(false)) })) .item_signal(super::saving().signal().map_true(|| "Saving...")) .item_signal(super::wide_screen().map_true(auth_controls)) .item_signal(super::wide_screen().map_false(hamburger)) .element_below(El::new().child_signal(super::show_menu_panel().map_true(menu_panel))) } fn logo() -> impl Element { Link::new() .s(Height::fill()) .s(Font::new().weight(NamedWeight::Bold).size(32)) .s(Padding::new().x(12)) .to(Route::Root) .label(Row::new().s(Height::fill()).item("TT")) } fn hamburger() -> impl Element { let (hovered, hovered_signal) = Mutable::new_and_signal(false); Button::new() .s(Height::fill()) .s(Align::new().right()) .s(Background::new().color_signal(hovered_signal.map_bool( || Theme::Background1Highlighted, || Theme::Transparent, ))) .s(Font::new().size(25)) .s(Padding::new().bottom(4)) .s(Width::new(64)) .on_press(super::toggle_menu) .on_hovered_change(move |is_hovered| hovered.set_neq(is_hovered)) .label( Row::new() .s(Height::fill()) .item_signal(super::menu_opened().signal().map_bool(|| "✕", || "☰")) ) .class_id(super::set_hamburger_class_id) } fn menu_panel() -> impl Element { Column::new() .s(Background::new().color(Theme::Background0)) .s(Font::new().color(Theme::Font0)) .s(Height::new(250)) .s(Align::new().right()) .s(Padding::all(15)) .s(Shadows::new(vec![ Shadow::new().y(8).blur(16).color(Theme::Shadow) ])) .s(RoundedCorners::new().bottom(10)) .on_click_outside( super::close_menu, Some(super::hamburger_class_id().get_cloned()) ) .after_remove(|_| super::close_menu()) .items(menu_links(true)) .item(El::new().s(Height::new(10))) .item(auth_controls()) } fn menu_links(in_menu_panel: bool) -> Vec<impl Element> { vec![ menu_link(Route::TimeTracker, "Time Tracker", super::PageId::TimeTracker, in_menu_panel), menu_link(Route::ClientsAndProjects, "Clients & Projects", super::PageId::ClientsAndProjects, in_menu_panel), menu_link(Route::TimeBlocks, "Time Blocks", super::PageId::TimeBlocks, in_menu_panel), ] } fn menu_link(route: Route, label: &str, page_id: super::PageId, in_menu_panel: bool) -> impl Element { let (hovered, hovered_signal) = Mutable::new_and_signal(false); let hovered_or_selected = map_ref! { let hovered = hovered_signal, let current_page_id = super::page_id().signal() => move { *hovered || *current_page_id == page_id } }; Link::new() .s(Height::fill()) .s(Padding::new().x(12)) .s(Background::new().color_signal(hovered_or_selected.map_bool( move || if in_menu_panel { Theme::Background2Highlighted } else { Theme::Background1Highlighted }, || Theme::Transparent, ))) .on_hovered_change(move |is_hovered| hovered.set_neq(is_hovered)) .to(route) .label(Row::new().s(Height::fill()).item(label)) } fn auth_controls() -> impl Element { Row::new() .s(Align::new().right()) .s(Padding::new().x(12)) .item_signal(super::is_user_logged_signal().map_false(login_button)) .item_signal(super::is_user_logged_signal().map_true(logout_button)) } fn login_button() -> impl Element { let (hovered, hovered_signal) = Mutable::new_and_signal(false); Link::new() .s(Background::new().color_signal(hovered_signal.map_bool( || Theme::Background3Highlighted, || Theme::Background3, ))) .s(Font::new().color(Theme::Font3).weight(NamedWeight::Bold)) .s(Padding::new().x(15).y(10)) .s(RoundedCorners::all(4)) .on_hovered_change(move |is_hovered| hovered.set_neq(is_hovered)) .to(Route::Login) .label("Log in") } fn logout_button() -> impl Element { let (hovered, hovered_signal) = Mutable::new_and_signal(false); Button::new() .s(Background::new().color_signal(hovered_signal.map_bool( || Theme::Background2Highlighted, || Theme::Background2, ))) .s(Font::new().color(Theme::Font2)) .s(Padding::new().x(15).y(10)) .s(RoundedCorners::all(4)) .on_hovered_change(move |is_hovered| hovered.set_neq(is_hovered)) .on_press(super::log_out) .label( Row::new() .item(El::new().s(Font::new().weight(NamedWeight::SemiBold)).child("Log out ")) .item(super::logged_user_name()) ) } fn page(page_id: super::PageId) -> impl Element { match page_id { super::PageId::Login => crate::login_page::view(), super::PageId::ClientsAndProjects => crate::clients_and_projects_page::view(), super::PageId::TimeTracker => crate::time_tracker_page::view(), super::PageId::TimeBlocks => crate::time_blocks_page::view(), super::PageId::Home => crate::home_page::view(), super::PageId::Unknown => El::new().child(404).into_raw_element(), } }
use std::prelude::v1::*; use super::address::{self, CryptoType}; use super::json_key; use crate::errors::{Error, ErrorKind, Result}; use crate::hdwallet::{rand as wallet_rand, Language}; use crate::sign::ecdsa::EcdsaKeyPair; use crate::sign::ecdsa::KeyPair; use num_integer::Integer; use num_traits::Num; use std::ops::{AddAssign, SubAssign}; use std::fs::File; use std::io::prelude::*; use std::path::PathBuf; #[derive(Debug)] pub struct ECDSAAccount { entropy: Vec<u8>, mnemonic: String, json_private_key: String, json_public_key: String, address: String, } /// From: https://golang.org/src/crypto/elliptic/p256.go const P256_N: &str = "115792089210356248762697446949407573529996955224135760342422259061068512044369"; /// safe check /// 1. overflow check, range is [0, n) fn get_safe_seed(seed: &[u8]) -> Result<Vec<u8>> { let big_one: num_bigint::BigInt = num_traits::One::one(); let big_n = num_bigint::BigInt::from_str_radix(P256_N, 10) .map_err(|_| Error::from(ErrorKind::ParseError))?; let mut big_n_sub_1 = big_n.clone(); // N - 1 big_n_sub_1.sub_assign(&big_one); let big_seed = num_bigint::BigInt::from_bytes_be(num_bigint::Sign::Plus, seed); // mod = big_seed^1 % (N - 1) let mut big_seed = big_seed.mod_floor(&big_n_sub_1); // mod + 1 -> [0, N) big_seed.add_assign(&big_one); Ok(big_seed.to_bytes_be().1) } pub fn generate_account_by_mnemonic(mnemonic: &String, lang: Language) -> Result<ECDSAAccount> { get_crypto_byte_from_mnemonic(mnemonic, lang)?; let password = "jingbo is handsome!".to_string(); let alg = &crate::sign::ecdsa::ECDSA_P256_SHA256_ASN1_SIGNING; //TODO should not hard code the bitsize let seed_raw = wallet_rand::generate_seed_with_error_check(mnemonic, &password, 40, lang)?; let seed = get_safe_seed(&seed_raw)?; let private_key = crate::sign::ecdsa::EcdsaKeyPair::from_seed_unchecked(alg, untrusted::Input::from(&seed))?; // TO JSON // TODO 这里不符合规范,最好是pcks8格式 let json_sk = json_key::get_ecdsa_private_key_json_format(&private_key)?; let json_pk = json_key::get_ecdsa_public_key_json_format(&private_key)?; let alg = &crate::sign::ecdsa::ECDSA_P256_SHA256_ASN1; let public_key = crate::sign::ecdsa::UnparsedPublicKey::new(alg, private_key.public_key()); let address = address::get_address_from_public_key(&public_key)?; Ok(ECDSAAccount { entropy: seed_raw, mnemonic: mnemonic.to_string(), json_public_key: json_pk, json_private_key: json_sk, address: address, }) } fn to_tag_byte(cryptography: u8) -> u8 { (cryptography & 15) << 4 } fn from_tag_byte(tag_byte: u8) -> u8 { (tag_byte >> 4) & 15 } pub fn get_crypto_byte_from_mnemonic(mnemonic: &String, lang: Language) -> Result<CryptoType> { let entropy = wallet_rand::get_entropy_from_mnemonic(mnemonic, lang)?; let tag_byte = entropy[entropy.len() - 1]; // 8bits let cryptography_int = from_tag_byte(tag_byte); CryptoType::from_u8(cryptography_int) } pub fn create_new_account_with_mnemonic( lang: Language, strength: wallet_rand::KeyStrength, crypto: CryptoType, ) -> Result<ECDSAAccount> { let strength = wallet_rand::get_bits_len(strength); let mut entropybytes = wallet_rand::generate_entropy(strength)?; let tag_byte = to_tag_byte(CryptoType::to_u8(crypto)); entropybytes.push(tag_byte); let mnemonic = wallet_rand::generate_mnemonic(&entropybytes, lang)?; generate_account_by_mnemonic(&mnemonic, lang) } pub fn export_new_account_with_mnenomic( base_path: &str, lang: Language, strength: wallet_rand::KeyStrength, cryptography: CryptoType, ) -> Result<()> { let acc = create_new_account_with_mnemonic(lang, strength, cryptography)?; let path: PathBuf = [base_path, "mnenomic"].iter().collect(); let mut file = File::create(path)?; file.write_all(acc.mnemonic.as_bytes())?; let path: PathBuf = [base_path, "private.key"].iter().collect(); let mut file = File::create(path)?; file.write_all(acc.json_private_key.as_bytes())?; let path: PathBuf = [base_path, "public.key"].iter().collect(); let mut file = File::create(path)?; file.write_all(acc.json_public_key.as_bytes())?; let path: PathBuf = [base_path, "address"].iter().collect(); let mut file = File::create(path)?; file.write_all(acc.address.as_bytes())?; Ok(()) } pub fn export_new_account(base_path: &str, private_key: &EcdsaKeyPair) -> Result<()> { let json_sk = json_key::get_ecdsa_private_key_json_format(private_key)?; let json_pk = json_key::get_ecdsa_public_key_json_format(private_key)?; let alg = &crate::sign::ecdsa::ECDSA_P256_SHA256_ASN1; let public_key = crate::sign::ecdsa::UnparsedPublicKey::new(alg, private_key.public_key()); let address = address::get_address_from_public_key(&public_key)?; let path: PathBuf = [base_path, "private.key"].iter().collect(); let mut file = File::create(path)?; file.write_all(json_sk.as_bytes())?; let path: PathBuf = [base_path, "public.key"].iter().collect(); let mut file = File::create(path)?; file.write_all(json_pk.as_bytes())?; let path: PathBuf = [base_path, "address"].iter().collect(); let mut file = File::create(path)?; file.write_all(address.as_bytes())?; Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_create_account() { let res = create_new_account_with_mnemonic( Language::ChineseSimplified, wallet_rand::KeyStrength::HARD, CryptoType::NIST, ); assert_eq!(res.is_ok(), true); } #[test] fn test_check_account() { let mnemonic = String::from("呈 仓 冯 滚 刚 伙 此 丈 锅 语 揭 弃 精 塘 界 戴 玩 爬 奶 滩 哀 极 样 费"); let acc = generate_account_by_mnemonic(&mnemonic, Language::ChineseSimplified); assert_eq!(acc.is_ok(), true); let acc = acc.unwrap(); assert_eq!("nYA6bVyhzv38g85ejxr4aqeKPcbG8mSWC", &acc.address); } #[test] fn test_open_and_save_account() { let res = export_new_account_with_mnenomic( "/tmp/", Language::ChineseSimplified, wallet_rand::KeyStrength::HARD, CryptoType::NIST, ); assert_eq!(res.is_ok(), true); //open get_ecdsa_private_key_from_file let res = super::json_key::get_ecdsa_private_key_from_file("/tmp/private.key"); assert_eq!(res.is_ok(), true); let sk = res.unwrap(); let res = export_new_account("/tmp", &sk); assert_eq!(res.is_ok(), true); } }
mod zmq_helper; use std::env; use std::io::Result; use std::pin::Pin; use aesm_client::AesmClient; use enclave_runner::usercalls::{AsyncStream, UsercallExtension}; use enclave_runner::EnclaveBuilder; use futures::future::{Future, FutureExt}; use log::{error, info}; use sgxs_loaders::isgx::Device as IsgxDevice; use self::zmq_helper::ZmqHelper; #[derive(Debug)] struct ZmqService { pub connection_str: String, } impl UsercallExtension for ZmqService { fn connect_stream<'a>( &'a self, addr: &'a str, _local_addr: Option<&'a mut String>, _peer_addr: Option<&'a mut String>, ) -> Pin<Box<dyn Future<Output = Result<Option<Box<dyn AsyncStream>>>> + 'a>> { async move { match &*addr { "zmq" => { info!("enclave helper: connecting to zmq"); let stream = ZmqHelper::new(&self.connection_str); let boxed_stream: Box<dyn AsyncStream> = Box::new(stream); let option: Option<Box<dyn AsyncStream>> = Some(boxed_stream); Ok(option) } _ => Ok(None), } } .boxed_local() } } fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 3 { error!("Please provide: <ENCLAVE_PATH> <ZMQ_CONN_STR> ENCLAVE_PATH: the path to *.sgxs file (note signature file be with it) ZMQ_CONN_STR: the ZMQ connection string (e.g. \"ipc://enclave.ipc\" or \"tcp://127.0.0.1:25933\") of the tx-validation server (now in chain-abci) "); std::process::exit(1); } let mut device = IsgxDevice::new() .expect("sgx device was not found") .einittoken_provider(AesmClient::new()) .build(); let mut enclave_builder = EnclaveBuilder::new(args[1].as_ref()); // can use `enclave_builder.dummy_signature()` in testing enclave_builder .coresident_signature() .expect("enclave signature file not found"); enclave_builder.usercall_extension(ZmqService { connection_str: args[2].clone(), }); let enclave = enclave_builder .build(&mut device) .expect("failed to build an enclave"); enclave.run().expect("failed to start an enclave"); }
use conrod::color::{self, Color}; #[doc = "Configuration for the GUI. Check source for what the defaults are. **Note**: ALWAYS add `..Default::default()` when creating a Config since I may add more configuration options and I will consider it a non breaking change."] pub struct Config { #[doc = "Background color"] pub canvas_color: Color, #[doc = "Input color"] pub input_color: Color, #[doc = "Color of unselected options in the menu"] pub unselected_color: Color, #[doc = "Color of selected option in the menu"] pub selected_color: Color, #[doc = "Size of border around input"] pub input_border: f64, #[doc = "Color of border around input"] pub input_border_color: Color, #[doc = "Size of input box"] pub input_size: [f64; 2], #[doc = "Size of the output list"] pub output_size: [f64; 2], #[doc = "Padding above input"] pub input_top_padding: f64, #[doc = "Padding between input and output"] pub output_top_padding: f64, #[doc = "Path to a .ttf file with the font to use"] pub font: String, #[doc = "Disable escape to exit the menu - because it crashes on i3-gaps"] pub disable_esc: bool, } impl Default for Config { fn default() -> Config { Config { canvas_color: color::BLACK, input_color: color::BLUE, unselected_color: color::WHITE, selected_color: color::RED, input_border: 1.0, input_border_color: color::BLACK, input_size: [200.0, 25.0], output_size: [200.0, 1000.0], input_top_padding: 0.0, output_top_padding: 0.0, font: "/usr/share/fonts/TTF/Ubuntu-M.ttf".into(), disable_esc: false, } } }
use std::{fs, path}; use crate::fs::{LllDirEntry, LllMetadata}; use crate::sort; use crate::window::LllPageState; #[derive(Debug)] pub struct LllDirList { pub index: Option<usize>, path: path::PathBuf, outdated: bool, pub metadata: LllMetadata, pub contents: Vec<LllDirEntry>, pub pagestate: LllPageState, } impl LllDirList { pub fn new(path: path::PathBuf, sort_option: &sort::SortOption) -> std::io::Result<Self> { let mut contents = read_dir_list(path.as_path(), sort_option)?; contents.sort_by(&sort_option.compare_func()); let index = if contents.is_empty() { None } else { Some(0) }; let metadata = LllMetadata::from(&path)?; let pagestate = LllPageState::default(); Ok(LllDirList { index, path, outdated: false, metadata, contents, pagestate, }) } pub fn depreciate(&mut self) { self.outdated = true; } pub fn need_update(&self) -> bool { self.outdated } pub fn file_path(&self) -> &path::PathBuf { &self.path } pub fn update_contents(&mut self, sort_option: &sort::SortOption) -> std::io::Result<()> { let sort_func = sort_option.compare_func(); let mut contents = read_dir_list(&self.path, sort_option)?; contents.sort_by(&sort_func); let contents_len = contents.len(); if contents_len == 0 { self.index = None; } else { self.index = match self.index { Some(index) => { if index >= contents_len { Some(contents_len - 1) } else { self.index } } None => Some(0), }; } let metadata = LllMetadata::from(&self.path)?; self.metadata = metadata; self.contents = contents; self.outdated = false; Ok(()) } pub fn selected_entries(&self) -> impl Iterator<Item = &LllDirEntry> { self.contents.iter().filter(|entry| entry.is_selected()) } pub fn get_selected_paths(&self) -> Vec<&path::PathBuf> { let vec: Vec<&path::PathBuf> = self.selected_entries().map(|e| e.file_path()).collect(); if vec.is_empty() { match self.get_curr_ref() { Some(s) => vec![s.file_path()], _ => vec![], } } else { vec } } pub fn get_curr_ref(&self) -> Option<&LllDirEntry> { self.get_curr_ref_(self.index?) } pub fn get_curr_mut(&mut self) -> Option<&mut LllDirEntry> { self.get_curr_mut_(self.index?) } fn get_curr_mut_(&mut self, index: usize) -> Option<&mut LllDirEntry> { if index < self.contents.len() { Some(&mut self.contents[index]) } else { None } } fn get_curr_ref_(&self, index: usize) -> Option<&LllDirEntry> { if index < self.contents.len() { Some(&self.contents[index]) } else { None } } } fn read_dir_list( path: &path::Path, sort_option: &sort::SortOption, ) -> std::io::Result<Vec<LllDirEntry>> { let filter_func = sort_option.filter_func(); let results: Vec<LllDirEntry> = fs::read_dir(path)? .filter(filter_func) .filter_map(map_entry_default) .collect(); Ok(results) } fn map_entry_default(result: std::io::Result<fs::DirEntry>) -> Option<LllDirEntry> { match result { Ok(direntry) => match LllDirEntry::from(&direntry) { Ok(s) => Some(s), Err(_) => None, }, Err(_) => None, } }
use futures::executor::block_on; use std::collections::HashMap; use std::io::Write; use reqwest::redirect::Policy; use reqwest::{StatusCode, Response}; use std::process::exit; use std::time::SystemTime; use std::thread::Thread; use reqwest::header::HeaderMap; const samf_ticket_url: &'static str = "https://billettsalg.samfundet.no/pay"; fn main() { abc() } fn get_input(display_str: &str) -> String { let mut inp_line = String::new(); print!("{}", display_str); std::io::stdout().flush(); std::io::stdin().read_line(&mut inp_line); return inp_line.trim().to_string(); } fn poll_for_keys(base_url: &String) -> (String, String) { let mut member_key: Option<String> = Option::None;//"price_9302_count".to_string(); let mut non_member_key: Option<String> = Option::None;//"price_9303_count".to_string(); let mut max_itr = 2000; let mut curr_itr = 0; let opt_resp: Option<reqwest::blocking::Response> = loop { print!("poll nmr {} for key \t", curr_itr); let response = reqwest::blocking::get(base_url).unwrap(); match { response.status() } { StatusCode::NOT_FOUND => { println!("Miss"); std::thread::sleep(std::time::Duration::from_millis(100)) } _ => { println!("Hit!"); break Option::Some(response); } } if max_itr < curr_itr { break Option::None; } curr_itr += 1; }; let response = opt_resp.unwrap(); let resp_text = response.text().unwrap(); let split_text = resp_text.split("\n"); for line in split_text { if (line.contains("<tr data-price-group=\"")) { let target_num = line .split("data-price-group=\"") .skip(1) .next() .unwrap() .split("\"").next().unwrap(); if member_key.is_none() { member_key = Option::Some(target_num.to_string()) } else { non_member_key = Option::Some(target_num.to_string()) } // println!("{}", target_num) } } // println!("{}", response.status()); // println!("{}", response.text().unwrap()); return (format!("price_{}_count", member_key.unwrap()), format!("price_{}_count", non_member_key.unwrap())); // return (( member_key.unwrap()), non_member_key.unwrap()); } fn abc() { let mut form_vals: HashMap<String, String> = HashMap::new(); // let mut email: String = "moxiv51007@rebation.com".to_string();//get_input("Ticket email: "); // let mut card_nmr: String = "4925000000000004".to_string();// get_input("card nmr: "); // let mut exp_m: String = "09".to_string();//get_input("card exp month (write 01 not 1 if 1 in 01/83): "); // let mut exp_y: String = "21".to_string();//get_input("card exp year :"); // let mut cvc2: String = "123".to_string();//get_input("cvc 2:"); let mut email: String = get_input("Ticket email: "); let mut card_nmr: String = get_input("card nmr: "); let mut exp_m: String = get_input("card exp month (write 01 not 1 if 1 in 01/83): "); let mut exp_y: String = get_input("card exp year :"); let mut cvc2: String = get_input("cvc 2:"); form_vals.insert("wheelchair-total".to_string(), "0".to_string()); form_vals.insert("ticket-type".to_string(), "on".to_string()); form_vals.insert("membercard".to_string(),"".to_string()); form_vals.insert("email".to_string(), email); form_vals.insert("ccno".to_string(), card_nmr); form_vals.insert("exp_month".to_string(), exp_m); form_vals.insert("exp_year".to_string(), exp_y); form_vals.insert("cvc2".to_string(), cvc2); println!("\ncopy the target url in this one the target url shold look somthing like this"); println!("https://www.uka.no/program/658-bli-stor-pa-some-mmaria-stavang/758"); println!("So that is: https://www.uka.no/program/<number somthing>-<name somthing>/<som other number>"); let target_url = get_input("target url: ");//"https://www.uka.no/program/658-bli-stor-pa-some-mmaria-stavang/758".to_string(); // let target_url = "https://www.uka.no/program/658-bli-stor-pa-some-mmaria-stavang/758".to_string(); println!("\nGo here to find the epoch time https://www.epochconverter.com/"); open::that("https://www.epochconverter.com/"); let target_time_string = get_input("target time in unix epoc:").trim().to_string(); let target_epoch_time = target_time_string.parse::<u64>().unwrap(); let wait_time = target_epoch_time - std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(); let sleep_time = std::time::Duration::from_secs(wait_time - 2); println!("The system is primed and will wait for the launch point in {} seconds", sleep_time.as_secs()); std::thread::sleep(sleep_time); println!("Starting preemptive polling for keys"); let (member_key, non_member_key) = poll_for_keys(&(target_url + "/billetter")); println!("Member key value \t{}", member_key); println!("Non member key value \t{}", non_member_key); form_vals.insert(member_key, "1".to_string()); form_vals.insert(non_member_key, "0".to_string()); let no_redirect_client = reqwest::blocking::ClientBuilder::new().redirect(Policy::none()).build().unwrap(); println!("posting form to samf's shitty slow website"); let mut spoof_headers = HeaderMap::new(); spoof_headers.insert("Origin", "https://www.uka.no".parse().unwrap()); spoof_headers.insert("Host", "billettsalg.samfundet.no".parse().unwrap()); spoof_headers.insert("Referer", "https://www.uka.no/".parse().unwrap()); spoof_headers.insert("Sec-GPC", "1".parse().unwrap()); spoof_headers.insert("Sec-Fetch-User", "?1".parse().unwrap()); spoof_headers.insert("Sec-Fetch-Dest", "document".parse().unwrap()); spoof_headers.insert("Sec-Fetch-Mode", "navigate".parse().unwrap()); spoof_headers.insert("Sec-Fetch-Site", "cross-site".parse().unwrap()); spoof_headers.insert("Content-Type", "application/x-www-form-urlencoded".parse().unwrap()); spoof_headers.insert("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0".parse().unwrap()); let resp = no_redirect_client .post(samf_ticket_url) .form(&form_vals) .headers(spoof_headers) .send() .unwrap(); match resp.status() { StatusCode::SEE_OTHER => { println!("Success maybe. this is the part i hav not tested so idk realy") } _ => {} } // for (key,val) in form_vals.iter(){ // println!("key <{}> val<{}>", key, val); // } resp.headers().iter().for_each(|(name, value)| { // println!("{}-{}", name, value.to_str().unwrap()); if name == "location" { println!("\nlocation hit:\n{}\n", value.to_str().unwrap()); open::that(value.to_str().unwrap()); } }); // println!("resp {}", resp.text().unwrap()); }
#[macro_use] extern crate hcl_parser; #[macro_use] extern crate pretty_assertions; use hcl_parser::hcl2::ast::*; use hcl_parser::hcl2::parser::*; macro_rules! test_productions { ($testname:ident, $func:ident, $cases:expr) => { #[test] fn $testname() { for (text, expected) in $cases { try_parse_to!($func, text, expected); } } }; } test_productions!( test_comment, comment, vec![ ( "# This is a single line comment\r\n", Comment::from(" This is a single line comment"), ), ( "// This is a single line comment\r\n", Comment::from(" This is a single line comment"), ), ( "// This is a single line comment\n", Comment::from(" This is a single line comment"), ), ( "// This is a single line comment", Comment::from(" This is a single line comment"), ), ( "/* This is a multi\n line\r\n comment */", Comment::from(" This is a multi\n line\r\n comment "), ), ] ); test_productions!( test_identifier, identifier, vec![ ("ident", Identifier::from("ident")), ("kebab-case", Identifier::from("kebab-case")), ("snake_case", Identifier::from("snake_case")), ( "SCREAMING_SNAKE_CASE", Identifier::from("SCREAMING_SNAKE_CASE"), ), ("CamelCase", Identifier::from("CamelCase")), ("Irate_Camel_Case", Identifier::from("Irate_Camel_Case"),), ("I", Identifier::from("I")), ("i", Identifier::from("i")), ("_underprefix", Identifier::from("_underprefix")), ("__underunderprefix", Identifier::from("__underunderprefix"),), (" left-whitespace", Identifier::from("left-whitespace"),), ("right-whitespace ", Identifier::from("right-whitespace"),), (" both-whitespace ", Identifier::from("both-whitespace"),), ] ); test_productions!( test_numericlit, numericlit, vec![ ("1", NumericLit(1_f64)), ("1.1", NumericLit(1.1_f64)), (" 1.1", NumericLit(1.1_f64)), ("1.1 ", NumericLit(1.1_f64)), (" 1.1 ", NumericLit(1.1_f64)), ("1.1e5", NumericLit(1.1e5_f64)), ] ); test_productions!( test_blocklabels, blocklabels, vec![ ("", BlockLabels::new()), ("ident1", vec![BlockLabel::Identifier("ident1".into())]), ( "ident1 ident2 ident3", vec![ BlockLabel::Identifier("ident1".into()), BlockLabel::Identifier("ident2".into()), BlockLabel::Identifier("ident3".into()), ], ), ( r#"ident "stringlit""#, vec![ BlockLabel::Identifier("ident".into()), BlockLabel::StringLit("stringlit".into()), ], ), ] ); test_productions!( test_attribute, attribute, vec![ ( "foo = \"bar\"\n", Attribute { ident: "foo".into(), expr: Expression::ExprTerm(ExprTerm::TemplateExpr(TemplateExpr::from("bar"))) }, ), ( "obj = {hello = \"world\"}\n", Attribute { ident: "obj".into(), expr: Expression::ExprTerm( CollectionValue::Object(vec![ObjectElem { key: ObjectKey::Identifier("hello".into()), value: Expression::ExprTerm(ExprTerm::TemplateExpr(TemplateExpr::from( "world" ))) }]) .into() ) }, ) ] ); test_productions!( test_block, block, vec![ ( "nullaryblock {\n blockitem = true\n}\n", Block { ident: "nullaryblock".into(), labels: vec![], body: Body(vec![Attribute { ident: "blockitem".into(), expr: Expression::ExprTerm(true.into()) } .into()]) } ), ( "unaryblock \"stringlit\" {\n blockitem = true\n}\n", Block { ident: "unaryblock".into(), labels: vec![BlockLabel::StringLit("stringlit".into())], body: Body(vec![Attribute { ident: "blockitem".into(), expr: Expression::ExprTerm(true.into()) } .into()]) } ), ( "binaryblock \"stringlit\" ident1 {\n blockitem = true\n}\n", Block { ident: "binaryblock".into(), labels: vec![ BlockLabel::StringLit("stringlit".into()), BlockLabel::Identifier("ident1".into()) ], body: Body(vec![Attribute { ident: "blockitem".into(), expr: Expression::ExprTerm(true.into()) } .into()]) } ), ] ); test_productions!( test_exprterm, exprterm, vec![ ( "{foo = true, bar = false}", CollectionValue::Object(vec![ ObjectElem { key: ObjectKey::Identifier("foo".into()), value: Expression::ExprTerm(true.into()), }, ObjectElem { key: ObjectKey::Identifier("bar".into()), value: Expression::ExprTerm(false.into()), }, ]) .into(), ), ( "i-am-a-variable", ExprTerm::VariableExpr("i-am-a-variable".into()), ), ( " left-whitespace", ExprTerm::VariableExpr("left-whitespace".into()), ), ( "right-whitespace ", ExprTerm::VariableExpr("right-whitespace".into()), ), ( "func(true)", ExprTerm::FunctionCall(FunctionCall { ident: "func".into(), arguments: vec![Expression::ExprTerm(true.into()),], }) ) ] ); test_productions!( test_literalvalue, literalvalue, vec![ ("true", true.into()), ("false", false.into()), ("null", LiteralValue::Null), ("3.1", 3.1.into()) ] ); test_productions!( test_tuple, tuple, vec![ ("[]", Tuple::new()), ("[true]", vec![Expression::ExprTerm(true.into())],), ( "[true, false, null, 3.1]", vec![ Expression::ExprTerm(true.into()), Expression::ExprTerm(false.into()), Expression::ExprTerm(LiteralValue::Null.into()), Expression::ExprTerm(3.1.into()) ], ), ] ); test_productions!( test_object, object, vec![ ("{}", Object::new()), ( "{foo = true, bar = false}", vec![ ObjectElem { key: ObjectKey::Identifier("foo".into()), value: Expression::ExprTerm(true.into()), }, ObjectElem { key: ObjectKey::Identifier("bar".into()), value: Expression::ExprTerm(false.into()), }, ], ), ( "{foo = true\nbar = false}", vec![ ObjectElem { key: ObjectKey::Identifier("foo".into()), value: Expression::ExprTerm(true.into()), }, ObjectElem { key: ObjectKey::Identifier("bar".into()), value: Expression::ExprTerm(false.into()), }, ], ), ( "{\nfoo = true, bar = false\n}", vec![ ObjectElem { key: ObjectKey::Identifier("foo".into()), value: Expression::ExprTerm(true.into()), }, ObjectElem { key: ObjectKey::Identifier("bar".into()), value: Expression::ExprTerm(false.into()), }, ], ), ( "{\n foo = true,\n bar = false\n}", vec![ ObjectElem { key: ObjectKey::Identifier("foo".into()), value: Expression::ExprTerm(true.into()), }, ObjectElem { key: ObjectKey::Identifier("bar".into()), value: Expression::ExprTerm(false.into()), }, ], ), ] ); test_productions!( test_collectionvalue, collectionvalue, vec![ ("[]", CollectionValue::Tuple(Tuple::new())), ("{}", CollectionValue::Object(Object::new())), ( "[true, false]", CollectionValue::Tuple(vec![ Expression::ExprTerm(true.into()), Expression::ExprTerm(false.into()), ]), ), ( "{foo = true, bar = false}", CollectionValue::Object(vec![ ObjectElem { key: ObjectKey::Identifier("foo".into()), value: Expression::ExprTerm(true.into()), }, ObjectElem { key: ObjectKey::Identifier("bar".into()), value: Expression::ExprTerm(false.into()), }, ]), ), ] ); test_productions!( test_functioncall, functioncall, vec![ ( "nullary()", FunctionCall { ident: "nullary".into(), arguments: vec![], }, ), ( "unary(true)", FunctionCall { ident: "unary".into(), arguments: vec![Expression::ExprTerm(true.into()),], }, ), ( "binary(true, false)", FunctionCall { ident: "binary".into(), arguments: vec![ Expression::ExprTerm(true.into()), Expression::ExprTerm(false.into()), ], }, ), ( "ternary(true, false, null)", FunctionCall { ident: "ternary".into(), arguments: vec![ Expression::ExprTerm(true.into()), Expression::ExprTerm(false.into()), Expression::ExprTerm(LiteralValue::Null.into()), ], }, ), ] ); test_productions!( test_for_cond, for_cond, vec![ ( "if true", ForCond(Box::new(Expression::ExprTerm(true.into()))) ), ( "if false", ForCond(Box::new(Expression::ExprTerm(false.into()))) ), ] ); test_productions!( test_for_intro, for_intro, vec![( "for item in [1, 2, 3]:", ForIntro { idents: ("item".into(), None), expr: Box::new(Expression::ExprTerm( CollectionValue::Tuple(vec![ Expression::ExprTerm(1.0_f64.into()), Expression::ExprTerm(2.0_f64.into()), Expression::ExprTerm(3.0_f64.into()), ]) .into() )) } )] ); test_productions!( test_for_tuple_expr, for_tuple_expr, vec![ ( "[for item in [1, 2, 3]: item]", ForTupleExpr { intro: ForIntro { idents: ("item".into(), None), expr: Box::new(Expression::ExprTerm( CollectionValue::Tuple(vec![ Expression::ExprTerm(1.0_f64.into()), Expression::ExprTerm(2.0_f64.into()), Expression::ExprTerm(3.0_f64.into()), ]) .into() )) }, expr: Box::new(Expression::ExprTerm(ExprTerm::VariableExpr("item".into()))), cond: None, } ), ( "[for item in [1, 2, 3]: item if true]", ForTupleExpr { intro: ForIntro { idents: ("item".into(), None), expr: Box::new(Expression::ExprTerm( CollectionValue::Tuple(vec![ Expression::ExprTerm(1.0_f64.into()), Expression::ExprTerm(2.0_f64.into()), Expression::ExprTerm(3.0_f64.into()), ]) .into() )) }, expr: Box::new(Expression::ExprTerm(ExprTerm::VariableExpr("item".into()))), cond: Some(ForCond(Box::new(Expression::ExprTerm( ExprTerm::LiteralValue(true.into(),) )))), } ) ] ); test_productions!( test_for_object_expr, for_object_expr, vec![ ( r#"{for k, v in injective: v => k}"#, ForObjectExpr { intro: ForIntro { idents: ("k".into(), Some("v".into())), expr: Box::new(Expression::ExprTerm(ExprTerm::VariableExpr( "injective".into() ))) }, k_expr: Box::new(Expression::ExprTerm(ExprTerm::VariableExpr("v".into()))), v_expr: Box::new(Expression::ExprTerm(ExprTerm::VariableExpr("k".into()))), group: false, cond: None, } ), ( r#"{for k, v in {}: v => k}"#, ForObjectExpr { intro: ForIntro { idents: ("k".into(), Some("v".into())), expr: Box::new(Expression::ExprTerm(CollectionValue::Object(vec![]).into())) }, k_expr: Box::new(Expression::ExprTerm(ExprTerm::VariableExpr("v".into()))), v_expr: Box::new(Expression::ExprTerm(ExprTerm::VariableExpr("k".into()))), group: false, cond: None, } ) ] ); test_productions!( test_for_expr, for_expr, vec![ ( r#"{for k, v in injective: v => k}"#, ForExpr::ForObjectExpr(ForObjectExpr { intro: ForIntro { idents: ("k".into(), Some("v".into())), expr: Box::new(Expression::ExprTerm(ExprTerm::VariableExpr(VariableExpr( "injective".to_string() )))) }, k_expr: Box::new(Expression::ExprTerm(ExprTerm::VariableExpr("v".into()))), v_expr: Box::new(Expression::ExprTerm(ExprTerm::VariableExpr("k".into()))), group: false, cond: None, }) ), ( "[for item in [1, 2, 3]: item]", ForExpr::ForTupleExpr(ForTupleExpr { intro: ForIntro { idents: ("item".into(), None), expr: Box::new(Expression::ExprTerm( CollectionValue::Tuple(vec![ Expression::ExprTerm(1.0_f64.into()), Expression::ExprTerm(2.0_f64.into()), Expression::ExprTerm(3.0_f64.into()), ]) .into() )) }, expr: Box::new(Expression::ExprTerm(ExprTerm::VariableExpr("item".into()))), cond: None, }) ), ] ); test_productions!( test_body, body, vec![ ( "attr = true\n\nblock {\n blockitem = null\n}\n", Body(vec![ Attribute { ident: "attr".into(), expr: Expression::ExprTerm(true.into()) } .into(), Block { ident: "block".into(), labels: vec![], body: Body(vec![Attribute { ident: "blockitem".into(), expr: Expression::ExprTerm(LiteralValue::Null.into()) } .into()]) } .into() ]) ), ( "attr = true\n\nblock \"stringlit1\" {\n blockitem = null\n}\n", Body(vec![ Attribute { ident: "attr".into(), expr: Expression::ExprTerm(true.into()) } .into(), Block { ident: "block".into(), labels: vec![BlockLabel::StringLit("stringlit1".into(),)], body: Body(vec![Attribute { ident: "blockitem".into(), expr: Expression::ExprTerm(LiteralValue::Null.into()) } .into()]) } .into() ]) ), ( "attr = true\n\nblock ident1 \"stringlit1\" {\n blockitem = null\n}\n", Body(vec![ Attribute { ident: "attr".into(), expr: Expression::ExprTerm(true.into(),) } .into(), Block { ident: "block".into(), labels: vec![ BlockLabel::Identifier("ident1".into()), BlockLabel::StringLit("stringlit1".into(),) ], body: Body(vec![Attribute { ident: Identifier("blockitem".to_string()), expr: Expression::ExprTerm(LiteralValue::Null.into()) } .into()]) } .into() ]) ), ( "attr1 = true\nattr2 = false\nattr3 = null\n", Body(vec![ Attribute { ident: "attr1".into(), expr: Expression::ExprTerm(true.into(),) } .into(), Attribute { ident: "attr2".into(), expr: Expression::ExprTerm(false.into(),) } .into(), Attribute { ident: "attr3".into(), expr: Expression::ExprTerm(LiteralValue::Null.into()) } .into(), ]) ), ( "attr1 = true\n\n\nattr2 = false\n\n\n", Body(vec![ Attribute { ident: "attr1".into(), expr: Expression::ExprTerm(true.into(),) } .into(), Attribute { ident: "attr2".into(), expr: Expression::ExprTerm(false.into(),) } .into(), ]) ), ( "foo \"baz\" {\n key = 7\n foo = \"bar\"\n}\n", Body(vec![Block { ident: Identifier("foo".to_string()), labels: vec![BlockLabel::StringLit("baz".into()),], body: Body(vec![ Attribute { ident: Identifier("key".to_string()), expr: Expression::ExprTerm(7.0_f64.into()) } .into(), Attribute { ident: Identifier("foo".to_string()), expr: Expression::ExprTerm(ExprTerm::TemplateExpr(TemplateExpr::from( "bar" ))) } .into() ]) } .into()]) ), ( "attr =<<EOD\nhello, world!\nEOD\n", Body(vec![Attribute { ident: "attr".into(), expr: Expression::ExprTerm(ExprTerm::TemplateExpr(TemplateExpr::from( "hello, world!\n" ))) } .into(),]) ) ] ); test_productions!( test_templateexpr_heredoc, template_expr, vec![ ( "<<EOD\nhello, world!\nEOD", TemplateExpr("hello, world!\n".into()) ), ( "<<EOD\n hello,\n world!\nEOD", TemplateExpr(" hello,\n world!\n".into()) ), ( "<<-EOD\n hello,\n world!\nEOD", TemplateExpr("hello,\n world!\n".into()) ), ( "<<-OVERLY_DESCRIPTIVE_TERMINATOR\n hello,\n world!\nOVERLY_DESCRIPTIVE_TERMINATOR", TemplateExpr("hello,\n world!\n".into()) ) ] ); test_productions!( test_template_interpolation, template_interpolation, vec![ ( r#"${"trivial"}"#, TemplateRegion::TemplateInterpolation(Expression::ExprTerm(ExprTerm::TemplateExpr( TemplateExpr::from("trivial") ))) ), ( r#"${[true, false]}"#, TemplateRegion::TemplateInterpolation(Expression::ExprTerm( CollectionValue::Tuple(vec![ Expression::ExprTerm(ExprTerm::from(true)), Expression::ExprTerm(ExprTerm::from(false)), ]) .into() )) ) ] );
#[doc = "Reader of register RTSR2"] pub type R = crate::R<u32, super::RTSR2>; #[doc = "Writer for register RTSR2"] pub type W = crate::W<u32, super::RTSR2>; #[doc = "Register RTSR2 `reset()`'s with value 0"] impl crate::ResetValue for super::RTSR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Rising trigger event configuration bit of line 35\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RT35_A { #[doc = "0: Rising edge trigger is disabled"] DISABLED = 0, #[doc = "1: Rising edge trigger is enabled"] ENABLED = 1, } impl From<RT35_A> for bool { #[inline(always)] fn from(variant: RT35_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `RT35`"] pub type RT35_R = crate::R<bool, RT35_A>; impl RT35_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RT35_A { match self.bits { false => RT35_A::DISABLED, true => RT35_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == RT35_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == RT35_A::ENABLED } } #[doc = "Write proxy for field `RT35`"] pub struct RT35_W<'a> { w: &'a mut W, } impl<'a> RT35_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RT35_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Rising edge trigger is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(RT35_A::DISABLED) } #[doc = "Rising edge trigger is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(RT35_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Rising trigger event configuration bit of line 36"] pub type RT36_A = RT35_A; #[doc = "Reader of field `RT36`"] pub type RT36_R = crate::R<bool, RT35_A>; #[doc = "Write proxy for field `RT36`"] pub struct RT36_W<'a> { w: &'a mut W, } impl<'a> RT36_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RT36_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Rising edge trigger is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(RT35_A::DISABLED) } #[doc = "Rising edge trigger is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(RT35_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Rising trigger event configuration bit of line 37"] pub type RT37_A = RT35_A; #[doc = "Reader of field `RT37`"] pub type RT37_R = crate::R<bool, RT35_A>; #[doc = "Write proxy for field `RT37`"] pub struct RT37_W<'a> { w: &'a mut W, } impl<'a> RT37_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RT37_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Rising edge trigger is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(RT35_A::DISABLED) } #[doc = "Rising edge trigger is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(RT35_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Rising trigger event configuration bit of line 38"] pub type RT38_A = RT35_A; #[doc = "Reader of field `RT38`"] pub type RT38_R = crate::R<bool, RT35_A>; #[doc = "Write proxy for field `RT38`"] pub struct RT38_W<'a> { w: &'a mut W, } impl<'a> RT38_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RT38_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Rising edge trigger is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(RT35_A::DISABLED) } #[doc = "Rising edge trigger is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(RT35_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } impl R { #[doc = "Bit 3 - Rising trigger event configuration bit of line 35"] #[inline(always)] pub fn rt35(&self) -> RT35_R { RT35_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Rising trigger event configuration bit of line 36"] #[inline(always)] pub fn rt36(&self) -> RT36_R { RT36_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - Rising trigger event configuration bit of line 37"] #[inline(always)] pub fn rt37(&self) -> RT37_R { RT37_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - Rising trigger event configuration bit of line 38"] #[inline(always)] pub fn rt38(&self) -> RT38_R { RT38_R::new(((self.bits >> 6) & 0x01) != 0) } } impl W { #[doc = "Bit 3 - Rising trigger event configuration bit of line 35"] #[inline(always)] pub fn rt35(&mut self) -> RT35_W { RT35_W { w: self } } #[doc = "Bit 4 - Rising trigger event configuration bit of line 36"] #[inline(always)] pub fn rt36(&mut self) -> RT36_W { RT36_W { w: self } } #[doc = "Bit 5 - Rising trigger event configuration bit of line 37"] #[inline(always)] pub fn rt37(&mut self) -> RT37_W { RT37_W { w: self } } #[doc = "Bit 6 - Rising trigger event configuration bit of line 38"] #[inline(always)] pub fn rt38(&mut self) -> RT38_W { RT38_W { w: self } } }
extern crate serde_json; use std::fs::File; use std::io::BufReader; use super::data_set_sli_manifest::DataSetSLIManifest; #[derive(Debug, Serialize, Deserialize)] pub struct Manifest { #[serde(rename = "dataSetSLIManifest")] pub manifest: Option<DataSetSLIManifest> } impl Manifest { pub fn from_file(path: &str) -> Manifest { let br = BufReader::new(File::open(path).unwrap()); let manifest: Manifest = serde_json::from_reader(br).unwrap(); manifest } }
// 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. //! A networking stack. #![deny(missing_docs)] #![deny(unreachable_patterns)] #![recursion_limit = "256"] // TODO(joshlf): Remove this once the old packet crate has been deleted and the // new one's name has been changed back to `packet`. extern crate packet_new as packet; mod devices; mod eventloop; mod fidl_worker; use crate::eventloop::EventLoop; fn main() -> Result<(), failure::Error> { fuchsia_syslog::init()?; // Severity is set to debug during development. fuchsia_syslog::set_severity(-1); let mut executor = fuchsia_async::Executor::new()?; let eventloop = EventLoop::new(); executor.run_singlethreaded(eventloop.run()) }
use crate::mechanics::damage::Damage; use crate::types::MonsterType; pub struct Attack { monster_type: MonsterType, base_damage: Damage, } impl Attack { pub fn new(base_damage: Damage, monster_type: MonsterType) -> Self { Attack { base_damage, monster_type, } } pub fn monster_type(&self) -> &MonsterType { &self.monster_type } pub fn base_damage(&self) -> &Damage { &self.base_damage } }
// Reconstruct Original Digits from English // https://leetcode.com/explore/challenge/card/march-leetcoding-challenge-2021/591/week-4-march-22nd-march-28th/3687/ pub struct Solution; impl Solution { pub fn original_digits(s: String) -> String { let mut counts = [0; (b'z' - b'e') as usize + 1]; for b in s.as_bytes() { counts[(b - b'e') as usize] += 1; } let count = |b| counts[(b - b'e') as usize]; let mut res = String::with_capacity(s.len() / 3); (0..count(b'z')).for_each(|_| res.push('0')); let count_1 = count(b'o') - count(b'z') - count(b'w') - count(b'u'); (0..count_1).for_each(|_| res.push('1')); (0..count(b'w')).for_each(|_| res.push('2')); (0..count(b'h') - count(b'g')).for_each(|_| res.push('3')); (0..count(b'u')).for_each(|_| res.push('4')); (0..count(b'f') - count(b'u')).for_each(|_| res.push('5')); (0..count(b'x')).for_each(|_| res.push('6')); let count_7 = count(b's') - count(b'x'); (0..count_7).for_each(|_| res.push('7')); (0..count(b'g')).for_each(|_| res.push('8')); let count_9 = (count(b'n') - count_1 - count_7) / 2; (0..count_9).for_each(|_| res.push('9')); res } } #[cfg(test)] mod tests { use super::*; #[test] fn example1() { assert_eq!(Solution::original_digits("owoztneoer".into()), "012"); } #[test] fn example2() { assert_eq!(Solution::original_digits("fviefuro".into()), "45"); } #[test] fn test_all_once() { assert_eq!( Solution::original_digits( "zeroonetwothreefourfivesixseveneightnine".into() ), "0123456789" ); } }
use rand::rngs::SmallRng; use rand::{Rng, SeedableRng}; use std::f32::consts::PI; #[derive(PartialEq, Copy, Clone, Debug)] pub enum WaveType { Square, Sawtooth, Sine, Noise, Triangle, } pub struct Oscillator { wave_type: WaveType, rng: SmallRng, period: u32, phase: u32, noise_buffer: [f32; 32], square_duty: f32, square_slide: f32, fperiod: f64, fmaxperiod: f64, fslide: f64, fdslide: f64, vib_phase: f64, vib_speed: f64, vib_amp: f64, arp_time: i32, arp_limit: i32, arp_mod: f64, } pub trait Filter { fn filter(&mut self, sample: f32) -> f32; } pub struct FilterIterator<'a> { iter: &'a mut dyn Iterator<Item = f32>, filter: &'a mut dyn Filter, } pub trait Filterable<'a> { fn chain_filter(&'a mut self, filter: &'a mut dyn Filter) -> FilterIterator<'a>; } impl<'a, T: Iterator<Item = f32>> Filterable<'a> for T { fn chain_filter(&'a mut self, filter: &'a mut dyn Filter) -> FilterIterator<'a> { FilterIterator { iter: self, filter } } } impl<'a> Iterator for FilterIterator<'a> { type Item = f32; fn next(&mut self) -> Option<f32> { match self.iter.next() { Some(v) => Some(self.filter.filter(v)), None => None, } } } enum EnvelopeStage { Attack, Sustain, Decay, End, } pub struct Envelope { stage: EnvelopeStage, stage_left: u32, attack: u32, sustain: u32, decay: u32, punch: f32, } pub struct HighLowPassFilter { fltp: f32, fltdp: f32, fltw: f32, fltw_d: f32, fltdmp: f32, fltphp: f32, flthp: f32, flthp_d: f32, } pub struct Phaser { ipp: usize, fphase: f32, fdphase: f32, buffer: [f32; 1024], } impl Oscillator { pub fn new(wave_type: WaveType) -> Oscillator { Oscillator { wave_type, square_duty: 0.5, period: 8, phase: 0, fperiod: 0.0, fmaxperiod: 0.0, fslide: 0.0, fdslide: 0.0, square_slide: 0.0, noise_buffer: [0.0; 32], vib_phase: 0.0, vib_speed: 0.0, vib_amp: 0.0, arp_time: 0, arp_limit: 0, arp_mod: 0.0, rng: SmallRng::seed_from_u64(0), } } pub fn reset_noise(&mut self) { for v in self.noise_buffer.iter_mut() { *v = self.rng.gen::<f32>() * 2.0 - 1.0; } } pub fn reset_phase(&mut self) { self.phase = 0; } pub fn reset_vibrato(&mut self, vib_speed: f64, vib_strength: f64) { self.vib_phase = 0.0; self.vib_speed = vib_speed.powi(2) * 0.01; self.vib_amp = vib_strength * 0.5; } pub fn reset( &mut self, wave_type: WaveType, base_freq: f64, freq_limit: f64, freq_ramp: f64, freq_dramp: f64, duty: f32, duty_ramp: f32, arp_speed: f32, arp_mod: f64, ) { self.wave_type = wave_type; self.fperiod = 100.0 / (base_freq.powi(2) + 0.001); self.fmaxperiod = 100.0 / (freq_limit.powi(2) + 0.001); self.fslide = 1.0 - freq_ramp.powi(3) * 0.01; self.fdslide = -freq_dramp.powi(3) * 0.000001; self.square_duty = 0.5 - duty * 0.5; self.square_slide = -duty_ramp * 0.00005; self.arp_mod = if arp_mod >= 0.0 { 1.0 - arp_mod.powf(2.0) * 0.9 } else { 1.0 - arp_mod.powf(2.0) * 10.0 }; self.arp_time = 0; self.arp_limit = ((1.0 - arp_speed).powi(2) * 20000.0 + 32.0) as i32; if (arp_speed - 1.0).abs() < f32::EPSILON { self.arp_limit = 0; } } pub fn advance(&mut self) { self.arp_time += 1; if self.arp_limit != 0 && self.arp_time >= self.arp_limit { self.arp_limit = 0; self.fperiod *= self.arp_mod as f64; } self.fslide += self.fdslide; self.fperiod = (self.fperiod * self.fslide).min(self.fmaxperiod); self.vib_phase += self.vib_speed; let vibrato = 1.0 + self.vib_phase.sin() * self.vib_amp; self.period = ((vibrato * self.fperiod) as u32).max(8); self.square_duty = (self.square_duty + self.square_slide).min(0.5).max(0.0); } } impl Iterator for Oscillator { type Item = f32; fn next(&mut self) -> Option<f32> { self.phase += 1; if self.phase >= self.period { self.phase %= self.period; if self.wave_type == WaveType::Noise { self.reset_noise(); } } let fp = self.phase as f32 / self.period as f32; let sample = match self.wave_type { WaveType::Square => { if fp < self.square_duty { 0.5 } else { -0.5 } } WaveType::Triangle => 1.0 - fp * 2.0, WaveType::Sawtooth => { if fp < self.square_duty { -1.0 + 2.0 * fp / self.square_duty } else { 1.0 - 2.0 * (fp - self.square_duty) / (1.0 - self.square_duty) } } WaveType::Sine => (fp * 2.0 * PI).sin(), WaveType::Noise => self.noise_buffer[(fp * 32.0) as usize], }; Some(sample) } } impl Envelope { pub fn new() -> Envelope { Envelope { stage: EnvelopeStage::Attack, stage_left: 0, attack: 0, sustain: 0, decay: 0, punch: 0.0, } } pub fn reset(&mut self, attack: f32, sustain: f32, decay: f32, punch: f32) { self.attack = (attack.powi(2) * 100_000.0) as u32; self.sustain = (sustain.powi(2) * 100_000.0) as u32; self.decay = (decay.powi(2) * 100_000.0) as u32; self.punch = punch; self.stage = EnvelopeStage::Attack; self.stage_left = self.current_stage_length(); } pub fn advance(&mut self) { if self.stage_left > 1 { self.stage_left -= 1; } else { self.stage = match self.stage { EnvelopeStage::Attack => EnvelopeStage::Sustain, EnvelopeStage::Sustain => EnvelopeStage::Decay, EnvelopeStage::Decay => EnvelopeStage::End, EnvelopeStage::End => EnvelopeStage::End, }; self.stage_left = self.current_stage_length(); } } fn current_stage_length(&self) -> u32 { match self.stage { EnvelopeStage::Attack => self.attack, EnvelopeStage::Sustain => self.sustain, EnvelopeStage::Decay => self.decay, EnvelopeStage::End => 0, } } fn volume(&self) -> f32 { let dt = self.stage_left as f32 / self.current_stage_length() as f32; match self.stage { EnvelopeStage::Attack => 1.0 - dt, EnvelopeStage::Sustain => 1.0 + dt * 2.0 * self.punch, EnvelopeStage::Decay => dt, EnvelopeStage::End => 0.0, } } } impl Filter for Envelope { fn filter(&mut self, sample: f32) -> f32 { sample * self.volume() } } impl HighLowPassFilter { pub fn new() -> HighLowPassFilter { HighLowPassFilter { fltp: 0.0, fltdp: 0.0, fltw: 0.0, fltw_d: 0.0, fltdmp: 0.0, fltphp: 0.0, flthp: 0.0, flthp_d: 0.0, } } pub fn reset( &mut self, lpf_resonance: f32, lpf_freq: f32, lpf_ramp: f32, hpf_freq: f32, hpf_ramp: f32, ) { self.fltp = 0.0; self.fltdp = 0.0; self.fltw = lpf_freq.powi(3) * 0.1; self.fltw_d = 1.0 + lpf_ramp * 0.0001; self.fltdmp = 5.0 / (1.0 + lpf_resonance.powi(2) * 20.0) * (0.01 + self.fltw); if self.fltdmp > 0.8 { self.fltdmp = 0.8; } self.fltphp = 0.0; self.flthp = hpf_freq.powi(2) * 0.1; self.flthp_d = 1.0 + hpf_ramp * 0.0003; } } impl Filter for HighLowPassFilter { fn filter(&mut self, sample: f32) -> f32 { let pp = self.fltp; if self.fltw > 0.0 { self.fltw = (self.fltw * self.fltw_d).min(0.1).max(0.0); self.fltdp += (sample - self.fltp) * self.fltw; self.fltdp -= self.fltdp * self.fltdmp; } else { self.fltp = sample; self.fltdp = 0.0; } self.fltp += self.fltdp; // High pass filter self.flthp = (self.flthp * self.flthp_d).min(0.1).max(0.00001); self.fltphp += self.fltp - pp; self.fltphp -= self.fltphp * self.flthp; self.fltphp } } impl Phaser { pub fn new() -> Phaser { Phaser { ipp: 0, fphase: 0.0, fdphase: 0.0, buffer: [0.0; 1024], } } pub fn reset(&mut self, pha_offset: f32, pha_ramp: f32) { self.fphase = pha_offset.powi(2) * 1020.0; if pha_offset < 0.0 { self.fphase = -self.fphase } self.fdphase = pha_ramp.powi(2) * 1.0; if pha_ramp < 0.0 { self.fdphase = -self.fdphase; } } pub fn advance(&mut self) { self.fphase += self.fdphase; } } impl Filter for Phaser { fn filter(&mut self, sample: f32) -> f32 { let p_len = self.buffer.len(); self.buffer[self.ipp % p_len] = sample; let iphase = (self.fphase.abs() as i32).min(p_len as i32 - 1); let result = sample + self.buffer[(self.ipp + p_len - iphase as usize) % p_len]; self.ipp = (self.ipp + 1) % p_len; result } }
use async_trait::async_trait; use data_types::{NamespaceName, NamespaceSchema}; use hashbrown::HashMap; use iox_time::{SystemProvider, TimeProvider}; use mutable_batch::MutableBatch; use observability_deps::tracing::*; use std::sync::Arc; use thiserror::Error; use trace::ctx::SpanContext; use super::DmlHandler; /// Errors emitted during retention validation. #[derive(Debug, Error)] pub enum RetentionError { /// Time is outside the retention period. #[error( "data in table {table_name} is outside of the retention period: minimum \ acceptable timestamp is {min_acceptable_ts}, but observed timestamp \ {observed_ts} is older." )] OutsideRetention { /// The minimum row timestamp that will be considered within the /// retention period. min_acceptable_ts: iox_time::Time, /// The timestamp in the write that exceeds the retention minimum. observed_ts: iox_time::Time, /// The table name in which the observed timestamp was found. table_name: String, }, } /// A [`DmlHandler`] implementation that validates that the write is within the /// retention period of the namespace. /// /// Each row of data being wrote is inspected, and if any "time" column /// timestamp lays outside of the configured namespace retention period, the /// entire write is rejected. #[derive(Debug, Default)] pub struct RetentionValidator<P = SystemProvider> { time_provider: P, } impl RetentionValidator { /// Initialise a new [`RetentionValidator`], rejecting time outside retention period pub fn new() -> Self { Self::default() } } #[async_trait] impl<P> DmlHandler for RetentionValidator<P> where P: TimeProvider, { type WriteError = RetentionError; type WriteInput = HashMap<String, MutableBatch>; type WriteOutput = Self::WriteInput; /// Partition the per-table [`MutableBatch`]. async fn write( &self, _namespace: &NamespaceName<'static>, namespace_schema: Arc<NamespaceSchema>, batch: Self::WriteInput, _span_ctx: Option<SpanContext>, ) -> Result<Self::WriteOutput, Self::WriteError> { // retention is not infinte, validate all lines of a write are within the retention period if let Some(retention_period_ns) = namespace_schema.retention_period_ns { let min_retention = self.time_provider.now().timestamp_nanos() - retention_period_ns; // batch is a HashMap<tring, MutableBatch> for (table_name, batch) in &batch { if let Some(min) = batch.timestamp_summary().and_then(|v| v.stats.min) { if min < min_retention { return Err(RetentionError::OutsideRetention { table_name: table_name.clone(), min_acceptable_ts: iox_time::Time::from_timestamp_nanos(min_retention), observed_ts: iox_time::Time::from_timestamp_nanos(min), }); } } } }; Ok(batch) } } #[cfg(test)] mod tests { use std::sync::Arc; use assert_matches::assert_matches; use iox_tests::{TestCatalog, TestNamespace}; use iox_time::MockProvider; use once_cell::sync::Lazy; use super::*; static NAMESPACE: Lazy<NamespaceName<'static>> = Lazy::new(|| "bananas".try_into().unwrap()); #[tokio::test] async fn test_time_inside_retention_period() { let namespace = test_setup().await; // Create the table so that there is a known ID that must be returned. let _want_id = namespace.create_table("bananas").await.table.id; // Create the validator whose retention period is 1 hour let handler = RetentionValidator::new(); // Make time now to be inside the retention period let now = SystemProvider::default() .now() .timestamp_nanos() .to_string(); let line = "bananas,tag1=A,tag2=B val=42i ".to_string() + &now; let writes = lp_to_writes(&line); let _result = handler .write(&NAMESPACE, namespace.schema().await.into(), writes, None) .await .unwrap(); } #[tokio::test] async fn test_time_outside_retention_period() { let namespace = test_setup().await; // Create the table so that there is a known ID that must be returned. let _want_id = namespace.create_table("bananas").await.table.id; let mock_now = iox_time::Time::from_rfc3339("2023-05-23T09:59:06+00:00").unwrap(); let mock_time = MockProvider::new(mock_now); // Create the validator whse retention period is 1 hour let handler = RetentionValidator { time_provider: mock_time.clone(), }; // Make time outside the retention period let two_hours_ago = (mock_now.timestamp_nanos() - 2 * 3_600 * 1_000_000_000).to_string(); let line = "bananas,tag1=A,tag2=B val=42i ".to_string() + &two_hours_ago; let writes = lp_to_writes(&line); let result = handler .write(&NAMESPACE, namespace.schema().await.into(), writes, None) .await; // error means the time is outside the retention period assert_matches!(result, Err(e) => { assert_eq!( e.to_string(), "data in table bananas is outside of the retention period: \ minimum acceptable timestamp is 2023-05-23T08:59:06+00:00, but \ observed timestamp 2023-05-23T07:59:06+00:00 is older." ) }); } #[tokio::test] async fn test_time_partial_inside_retention_period() { let namespace = test_setup().await; // Create the table so that there is a known ID that must be returned. let _want_id = namespace.create_table("bananas").await.table.id; let mock_now = iox_time::Time::from_rfc3339("2023-05-23T09:59:06+00:00").unwrap(); let mock_time = MockProvider::new(mock_now); // Create the validator whse retention period is 1 hour let handler = RetentionValidator { time_provider: mock_time.clone(), }; // Make time now to be inside the retention period let now = mock_now.timestamp_nanos().to_string(); let line1 = "bananas,tag1=A,tag2=B val=42i ".to_string() + &now; // Make time outside the retention period let two_hours_ago = (mock_now.timestamp_nanos() - 2 * 3_600 * 1_000_000_000).to_string(); let line2 = "bananas,tag1=AA,tag2=BB val=422i ".to_string() + &two_hours_ago; // a lp with 2 lines, one inside and one outside retention period let lp = format!("{line1}\n{line2}"); let writes = lp_to_writes(&lp); let result = handler .write(&NAMESPACE, namespace.schema().await.into(), writes, None) .await; // error means the time is outside the retention period assert_matches!(result, Err(e) => { assert_eq!( e.to_string(), "data in table bananas is outside of the retention period: \ minimum acceptable timestamp is 2023-05-23T08:59:06+00:00, but \ observed timestamp 2023-05-23T07:59:06+00:00 is older." ) }); } #[tokio::test] async fn test_one_table_inside_one_table_outside_retention_period() { let namespace = test_setup().await; // Create the table so that there is a known ID that must be returned. let _want_id = namespace.create_table("bananas").await.table.id; let mock_now = iox_time::Time::from_rfc3339("2023-05-23T09:59:06+00:00").unwrap(); let mock_time = MockProvider::new(mock_now); // Create the validator whse retention period is 1 hour let handler = RetentionValidator { time_provider: mock_time.clone(), }; // Make time now to be inside the retention period let now = mock_now.timestamp_nanos().to_string(); let line1 = "bananas,tag1=A,tag2=B val=42i ".to_string() + &now; // Make time outside the retention period let two_hours_ago = (mock_now.timestamp_nanos() - 2 * 3_600 * 1_000_000_000).to_string(); let line2 = "apple,tag1=AA,tag2=BB val=422i ".to_string() + &two_hours_ago; // a lp with 2 lines, one inside and one outside retention period let lp = format!("{line1}\n{line2}"); let writes = lp_to_writes(&lp); let result = handler .write(&NAMESPACE, namespace.schema().await.into(), writes, None) .await; // error means the time is outside the retention period assert_matches!(result, Err(e) => { assert_eq!( e.to_string(), "data in table apple is outside of the retention period: minimum \ acceptable timestamp is 2023-05-23T08:59:06+00:00, but observed \ timestamp 2023-05-23T07:59:06+00:00 is older.") }); } // Parse `lp` into a table-keyed MutableBatch map. fn lp_to_writes(lp: &str) -> HashMap<String, MutableBatch> { let (writes, _) = mutable_batch_lp::lines_to_batches_stats(lp, 42) .expect("failed to build test writes from LP"); writes } /// Initialise an in-memory [`MemCatalog`] and create a single namespace /// named [`NAMESPACE`]. async fn test_setup() -> Arc<TestNamespace> { let catalog = TestCatalog::new(); catalog.create_namespace_1hr_retention(&NAMESPACE).await } }
use otspec::types::*; use otspec::{deserialize_visitor, read_field}; use otspec_macros::tables; use serde::de::SeqAccess; use serde::de::Visitor; use serde::Deserializer; use serde::{Deserialize, Serialize}; tables!( maxp05 { uint16 numGlyphs } maxp10 { uint16 numGlyphs uint16 maxPoints uint16 maxContours uint16 maxCompositePoints uint16 maxCompositeContours uint16 maxZones uint16 maxTwilightPoints uint16 maxStorage uint16 maxFunctionDefs uint16 maxInstructionDefs uint16 maxStackElements uint16 maxSizeOfInstructions uint16 maxComponentElements uint16 maxComponentDepth }); /// Which maxp table is contained within the object. /// /// The `maxp` table comes in two versions, 0.5 and 1.0, which have /// different fields. The enum allows a single maxp object to represent /// both versions. #[derive(Debug, Serialize, Deserialize, PartialEq)] pub enum MaxpVariant { /// This table is a maxp version 0.5 Maxp05(maxp05), /// This table is a maxp version 1.0 Maxp10(maxp10), } /// A maxp table, regardless of version. #[derive(Debug, Serialize, PartialEq)] pub struct maxp { /// The version number as a fixed U16F16 value (for ease of serialization) #[serde(with = "Version16Dot16")] pub version: U16F16, /// Either a maxp 0.5 table or a maxp 1.0 table #[serde(flatten)] pub table: MaxpVariant, } impl maxp { /// Creates a new `maxp` table with version=0.5, given a number of glyphs pub fn new05(num_glyphs: u16) -> maxp { maxp { version: U16F16::from_num(0.5), table: MaxpVariant::Maxp05(maxp05 { numGlyphs: num_glyphs, }), } } pub fn new10( numGlyphs: u16, maxPoints: u16, maxContours: u16, maxCompositePoints: u16, maxCompositeContours: u16, maxComponentElements: u16, maxComponentDepth: u16, ) -> maxp { maxp { version: U16F16::from_num(1.0), table: MaxpVariant::Maxp10(maxp10 { numGlyphs, maxPoints, maxContours, maxCompositePoints, maxCompositeContours, maxZones: 2, maxTwilightPoints: 0, maxStorage: 0, maxFunctionDefs: 0, maxInstructionDefs: 0, maxStackElements: 0, maxSizeOfInstructions: 0, maxComponentElements, maxComponentDepth, }), } } pub fn num_glyphs(&self) -> u16 { match &self.table { MaxpVariant::Maxp05(s) => s.numGlyphs, MaxpVariant::Maxp10(s) => s.numGlyphs, } } pub fn set_num_glyphs(&mut self, num: u16) { match &mut self.table { MaxpVariant::Maxp05(s) => s.numGlyphs = num, MaxpVariant::Maxp10(s) => s.numGlyphs = num, } } } deserialize_visitor!( maxp, MaxpVisitor, fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> { let version = read_field!(seq, i32, "a maxp version"); if version == 0x00005000 { return Ok(maxp { version: U16F16::from_num(0.5), table: MaxpVariant::Maxp05(read_field!(seq, maxp05, "a maxp05 table")), }); } if version == 0x00010000 { return Ok(maxp { version: U16F16::from_num(1.0), table: MaxpVariant::Maxp10(read_field!(seq, maxp10, "a maxp05 table")), }); } Err(serde::de::Error::custom("Unknown maxp version")) } ); #[cfg(test)] mod tests { use crate::maxp; use otspec::ser; use otspec::types::U16F16; #[test] fn maxp_ser_v05() { let v = maxp::maxp { version: U16F16::from_num(0.5), table: maxp::MaxpVariant::Maxp05(maxp::maxp05 { numGlyphs: 935 }), }; let binary_maxp = ser::to_bytes(&v).unwrap(); let maxp_expectation = vec![0x00, 0x00, 0x50, 0x00, 0x03, 0xa7]; assert_eq!(binary_maxp, maxp_expectation); // let deserialized: maxp::maxp = otspec::de::from_bytes(&binary_maxp).unwrap(); // assert_eq!(deserialized, v); } #[test] fn maxp_ser_v10() { let v = maxp::maxp { version: U16F16::from_num(1.0), table: maxp::MaxpVariant::Maxp10(maxp::maxp10 { numGlyphs: 1117, maxPoints: 98, maxContours: 7, maxCompositePoints: 0, maxCompositeContours: 0, maxZones: 2, maxTwilightPoints: 0, maxStorage: 0, maxFunctionDefs: 0, maxInstructionDefs: 0, maxStackElements: 0, maxSizeOfInstructions: 0, maxComponentElements: 0, maxComponentDepth: 0, }), }; let binary_maxp = ser::to_bytes(&v).unwrap(); let maxp_expectation = vec![ 0x00, 0x01, 0x00, 0x00, 0x04, 0x5d, 0x00, 0x62, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; assert_eq!(binary_maxp, maxp_expectation); } #[test] fn maxp_de_v05() { let v = maxp::maxp { version: U16F16::from_num(0.5), table: maxp::MaxpVariant::Maxp05(maxp::maxp05 { numGlyphs: 935 }), }; let binary_maxp = vec![0x00, 0x00, 0x50, 0x00, 0x03, 0xa7]; let deserialized: maxp::maxp = otspec::de::from_bytes(&binary_maxp).unwrap(); assert_eq!(deserialized, v); } }
#[doc = "Reader of register DOUTR"] pub type R = crate::R<u32, super::DOUTR>; #[doc = "Reader of field `DOUTR`"] pub type DOUTR_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - Data output"] #[inline(always)] pub fn doutr(&self) -> DOUTR_R { DOUTR_R::new((self.bits & 0xffff_ffff) as u32) } }
use std::io::{self, Write}; use ast::*; use ast::{Expr::*, Statement::*}; // Convert a PizzaML function name to an SML one. pub fn translate_function_call(func_name: &str) -> &str { match func_name { "print" => "TextIO.print", s => s, } } // Convert a PizzaML operator into an SML one. fn translate_op(operator: &str) -> &str { match operator { "==" => "=", "||" => "orelse", "&&" => "andalso", op => op } } pub fn translate_expression<W: Write>(e: &Expr, o: &mut W) -> io::Result<()> { match *e { Id(ref ident) => write!(o, "{}", ident)?, Op(ref lhs, op, ref rhs) => { translate_expression(lhs, o)?; write!(o, " {} ", translate_op(op))?; translate_expression(rhs, o)?; } FnCall { ref function, ref args } => { write!(o, "{}", translate_function_call(function))?; for arg in args { write!(o, " ")?; translate_expression(arg, o)?; } } Unit => write!(o, "()")?, // FIXME: HACK printing the debug representation of the string! StringLit(ref s) => write!(o, "{:?}", s)?, IntLit(ref x) => write!(o, "{}", x)?, BoolLit(x) => write!(o, "{}", x)?, Block(ref stmts, ref terminal) => { if !stmts.is_empty() { write!(o, "let\n")?; for stmt in stmts { translate_statement(stmt, o)?; } write!(o, "in ")?; } match terminal { Some(e) => translate_expression(e, o)?, None => translate_expression(&Unit, o)?, } if !stmts.is_empty() { write!(o, "\nend")?; } } If(ref cond, ref e1, ref e2) => { write!(o, "if ")?; translate_expression(cond, o)?; write!(o, "\nthen\n")?; translate_expression(e1, o)?; write!(o, "\nelse\n")?; translate_expression(e2, o)?; } } Ok(()) } pub fn translate_expression_to_str(e: &Expr) -> Result<String, io::Error> { let mut buffer = Vec::new(); translate_expression(e, &mut buffer)?; let result = String::from_utf8(buffer).expect("translated ML should be valid utf-8"); Ok(result) } pub fn translate_statement<W: Write>(s: &Statement, o: &mut W) -> io::Result<()> { match *s { SLet(ref ident, ref body) => { write!(o, "val {} = (", ident)?; translate_expression(body, o)?; write!(o, ");\n")?; } SExpr(ref expr) => { write!(o, "val _ = (")?; translate_expression(expr, o)?; write!(o, ");\n")?; } } Ok(()) } // TODO: polymorphic types pub fn translate_function<W: Write>(f: &Function, o: &mut W) -> io::Result<()> { write!(o, "fun {} ", f.name)?; if !f.argument_list.is_empty() { for &(ref name, ref ty) in &f.argument_list { write!(o, "({}: {}) ", name, ty)?; } } else { write!(o, "() ")?; } write!(o, "= ")?; translate_expression(&f.body, o)?; write!(o, ";")?; Ok(()) } pub fn translate_function_to_str(f: &Function) -> Result<String, io::Error> { let mut buffer = Vec::new(); translate_function(f, &mut buffer)?; let result = String::from_utf8(buffer).expect("translated ML should be valid utf-8"); Ok(result) } #[cfg(test)] mod test { use super::*; use combine::Parser; use parser::*; #[test] fn simple_block() { let e = expr().parse("{ e1; e2; e3 }").unwrap().0; let translated = translate_expression_to_str(&e).unwrap(); assert_eq!( translated, r##" let val _ = (e1); val _ = (e2); in e3 end "##.trim() ); } #[test] fn function_fn_call() { let f = Function { name: "foo".into(), argument_list: vec![("x".into(), "Int".into())], body: FnCall { function: "bar".into(), args: vec![Unit, Unit, Unit] }, }; let ml_func = translate_function_to_str(&f).unwrap(); assert_eq!(&ml_func, "fun foo (x: Int) = bar () () ();"); } }
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(box_syntax)] struct pair<A,B> { a: A, b: B } trait Invokable<A> { fn f(&self) -> (A, u16); } struct Invoker<A> { a: A, b: u16, } impl<A:Clone> Invokable<A> for Invoker<A> { fn f(&self) -> (A, u16) { (self.a.clone(), self.b) } } fn f<A:Clone + 'static>(a: A, b: u16) -> Box<Invokable<A>+'static> { box Invoker { a: a, b: b, } as (Box<Invokable<A>+'static>) } pub fn main() { let (a, b) = f(22_u64, 44u16).f(); println!("a={} b={}", a, b); assert_eq!(a, 22u64); assert_eq!(b, 44u16); }
use std::io::{self, copy, BufRead, Write}; use std::sync::{Arc, RwLock}; use std::thread; use chainerror::*; use serde_json::{from_slice, from_value, to_string}; use varlink::{ Call, Connection, ErrorKind, GetInterfaceDescriptionArgs, Reply, Request, VarlinkStream, }; use varlink_stdinterfaces::org_varlink_resolver::{VarlinkClient, VarlinkClientInterface}; use crate::Result; pub fn handle<R, W>(resolver: &str, mut client_reader: R, mut client_writer: W) -> Result<bool> where R: BufRead + Send + Sync + 'static, W: Write + Send + Sync + 'static, { let conn = Connection::new(resolver) .map_err(mstrerr!("Failed to connect to resolver '{}'", resolver))?; let mut resolver = VarlinkClient::new(conn); let mut upgraded = false; let mut last_iface = String::new(); let mut last_service_stream: Option<VarlinkStream> = None; let mut address = String::new(); loop { if !upgraded { let mut buf = Vec::new(); match client_reader.read_until(b'\0', &mut buf) { Ok(0) => break, Err(_e) => break, _ => {} } // pop the last zero byte buf.pop(); let mut req: Request = from_slice(&buf).map_err(mstrerr!("Error from slice"))?; if req.method == "org.varlink.service.GetInfo" { req.method = "org.varlink.resolver.GetInfo".into(); } let n: usize = match req.method.rfind('.') { None => { let method: String = String::from(req.method.as_ref()); let mut call = Call::new(&mut client_writer, &req); call.reply_interface_not_found(Some(method))?; return Ok(false); } Some(x) => x, }; let iface = { if req.method == "org.varlink.service.GetInterfaceDescription" { let val = req.parameters.clone().unwrap_or_default(); let args: GetInterfaceDescriptionArgs = from_value(val)?; args.interface.into() } else { String::from(&req.method[..n]) } }; if iface != last_iface { if iface.eq("org.varlink.resolver") { address = String::from("unix:/run/org.varlink.resolver"); } else { address = match resolver.resolve(iface.clone()).call() { Ok(r) => r.address, _ => { let mut call = Call::new(&mut client_writer, &req); call.reply_interface_not_found(Some(iface))?; return Ok(false); } }; } last_iface = iface.clone(); } let mut stream = match VarlinkStream::connect(&address) { Ok((a, _)) => a, _ => { let mut call = Call::new(&mut client_writer, &req); call.reply_interface_not_found(Some(iface))?; return Ok(false); } }; let (service_reader, mut service_writer) = stream.split()?; last_service_stream = Some(stream); let mut service_bufreader = ::std::io::BufReader::new(service_reader); { let b = to_string(&req)? + "\0"; service_writer.write_all(b.as_bytes())?; service_writer.flush()?; } if req.oneway.unwrap_or(false) { continue; } upgraded = req.upgrade.unwrap_or(false); loop { let mut buf = Vec::new(); if service_bufreader.read_until(0, &mut buf)? == 0 { break; } if buf.is_empty() { return Err(strerr!("Connection Closed").into()); } client_writer.write_all(&buf)?; client_writer.flush()?; buf.pop(); let reply: Reply = from_slice(&buf)?; if upgraded || (!reply.continues.unwrap_or(false)) { break; } } } else if let Some(ref mut service_stream) = last_service_stream { // Should copy back and forth, until someone disconnects. let (mut service_reader, mut service_writer) = service_stream.split()?; { let copy1 = thread::spawn(move || copy(&mut client_reader, &mut service_writer)); let copy2 = thread::spawn(move || copy(&mut service_reader, &mut client_writer)); let r = copy1.join(); r.unwrap_or_else(|_| Err(io::Error::from(io::ErrorKind::ConnectionAborted)))?; let r = copy2.join(); r.unwrap_or_else(|_| Err(io::Error::from(io::ErrorKind::ConnectionAborted)))?; } return Ok(true); } } Ok(upgraded) } pub fn handle_connect<R, W>( connection: Arc<RwLock<Connection>>, mut client_reader: R, mut client_writer: W, ) -> Result<bool> where R: BufRead + Send + Sync + 'static, W: Write + Send + Sync + 'static, { let mut upgraded = false; let mut last_iface = String::new(); let mut conn = connection.write().unwrap(); loop { if !upgraded { if conn.reader.is_none() || conn.writer.is_none() { return Err(ErrorKind::ConnectionBusy.into()); } let (mut service_reader, mut service_writer) = (conn.reader.take().unwrap(), conn.writer.take().unwrap()); let mut buf = Vec::new(); match client_reader.read_until(b'\0', &mut buf) { Ok(0) => break, Err(_e) => break, _ => {} } // pop the last zero byte buf.pop(); let req: Request = from_slice(&buf)?; let n: usize = match req.method.rfind('.') { None => { let method: String = String::from(req.method.as_ref()); let mut call = Call::new(&mut client_writer, &req); call.reply_interface_not_found(Some(method))?; return Ok(false); } Some(x) => x, }; let iface = String::from(&req.method[..n]); if iface != last_iface { last_iface = iface.clone(); } { let b = to_string(&req)? + "\0"; service_writer.write_all(b.as_bytes())?; service_writer.flush()?; } if req.oneway.unwrap_or(false) { continue; } upgraded = req.upgrade.unwrap_or(false); loop { let mut buf = Vec::new(); if service_reader.read_until(0, &mut buf)? == 0 { break; } if buf.is_empty() { return Err(strerr!("Connection Closed!").into()); } client_writer.write_all(&buf)?; client_writer.flush()?; buf.pop(); let reply: Reply = from_slice(&buf)?; if upgraded || !reply.continues.unwrap_or(false) { break; } } conn.reader = Some(service_reader); conn.writer = Some(service_writer) } else { if conn.reader.is_none() || conn.writer.is_none() { return Err(ErrorKind::ConnectionBusy.into()); } let (mut service_reader, mut service_writer) = (conn.reader.take().unwrap(), conn.writer.take().unwrap()); // Should copy back and forth, until someone disconnects. { let copy1 = thread::spawn(move || copy(&mut client_reader, &mut service_writer)); let copy2 = thread::spawn(move || copy(&mut service_reader, &mut client_writer)); let r = copy1.join(); r.unwrap_or_else(|_| Err(io::Error::from(io::ErrorKind::ConnectionAborted)))?; let r = copy2.join(); r.unwrap_or_else(|_| Err(io::Error::from(io::ErrorKind::ConnectionAborted)))?; } return Ok(true); } } Ok(upgraded) }
#![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: [u8; 32]| { let constified = stark_hash::Felt::from_be_bytes(data); let orig = stark_hash::Felt::from_be_bytes_orig(data); assert_eq!(constified, orig); });
use actix_http::Method; use actix_web::{dev::Service, guard, test, web, web::Data, App}; use async_graphql::*; use serde_json::json; use test_utils::*; mod test_utils; #[actix_rt::test] async fn test_playground() { let srv = test::init_service( App::new().service( web::resource("/") .guard(guard::Get()) .to(test_utils::gql_playgound), ), ) .await; let req = test::TestRequest::with_uri("/").to_request(); let response = srv.call(req).await.unwrap(); assert!(response.status().is_success()); let body = response.into_body(); assert!( std::str::from_utf8(&actix_web::body::to_bytes(body).await.unwrap()) .unwrap() .contains("graphql") ); } #[actix_rt::test] async fn test_add() { let srv = test::init_service( App::new() .app_data(Data::new(Schema::new( AddQueryRoot, EmptyMutation, EmptySubscription, ))) .service( web::resource("/") .guard(guard::Post()) .to(gql_handle_schema::<AddQueryRoot, EmptyMutation, EmptySubscription>), ), ) .await; let response = srv .call( test::TestRequest::with_uri("/") .method(Method::POST) .set_payload(r#"{"query":"{ add(a: 10, b: 20) }"}"#) .to_request(), ) .await .unwrap(); assert!(response.status().is_success()); let body = response.into_body(); assert_eq!( actix_web::body::to_bytes(body).await.unwrap(), json!({"data": {"add": 30}}).to_string().into_bytes() ); } #[actix_rt::test] async fn test_hello() { let srv = test::init_service( App::new() .app_data(Data::new(Schema::new( HelloQueryRoot, EmptyMutation, EmptySubscription, ))) .service( web::resource("/") .guard(guard::Post()) .to(gql_handle_schema::<HelloQueryRoot, EmptyMutation, EmptySubscription>), ), ) .await; let response = srv .call( test::TestRequest::with_uri("/") .method(Method::POST) .set_payload(r#"{"query":"{ hello }"}"#) .to_request(), ) .await .unwrap(); assert!(response.status().is_success()); let body = response.into_body(); assert_eq!( actix_web::body::to_bytes(body).await.unwrap(), json!({"data": {"hello": "Hello, world!"}}) .to_string() .into_bytes() ); } #[actix_rt::test] async fn test_hello_header() { let srv = test::init_service( App::new() .app_data(Data::new(Schema::new( HelloQueryRoot, EmptyMutation, EmptySubscription, ))) .service( web::resource("/") .guard(guard::Post()) .to(gql_handle_schema_with_header::<HelloQueryRoot>), ), ) .await; let response = srv .call( test::TestRequest::with_uri("/") .method(Method::POST) .insert_header(("Name", "Foo")) .set_payload(r#"{"query":"{ hello }"}"#) .to_request(), ) .await .unwrap(); assert!(response.status().is_success()); let body = response.into_body(); assert_eq!( actix_web::body::to_bytes(body).await.unwrap(), json!({"data": {"hello": "Hello, Foo!"}}) .to_string() .into_bytes() ); } #[actix_rt::test] async fn test_count() { let srv = test::init_service( App::new() .app_data(Data::new( Schema::build(CountQueryRoot, CountMutation, EmptySubscription) .data(Count::default()) .finish(), )) .service( web::resource("/") .guard(guard::Post()) .to(gql_handle_schema::<CountQueryRoot, CountMutation, EmptySubscription>), ), ) .await; let response = srv .call( test::TestRequest::with_uri("/") .method(Method::POST) .set_payload(r#"{"query":"{ count }"}"#) .to_request(), ) .await .unwrap(); assert!(response.status().is_success()); let body = response.into_body(); assert_eq!( actix_web::body::to_bytes(body).await.unwrap(), json!({"data": {"count": 0}}).to_string().into_bytes() ); let response = srv .call( test::TestRequest::with_uri("/") .method(Method::POST) .set_payload(r#"{"query":"mutation{ addCount(count: 10) }"}"#) .to_request(), ) .await .unwrap(); assert!(response.status().is_success()); let body = response.into_body(); assert_eq!( actix_web::body::to_bytes(body).await.unwrap(), json!({"data": {"addCount": 10}}).to_string().into_bytes(), ); let response = srv .call( test::TestRequest::with_uri("/") .method(Method::POST) .set_payload(r#"{"query":"mutation{ subtractCount(count: 2) }"}"#) .to_request(), ) .await .unwrap(); assert!(response.status().is_success()); let body = response.into_body(); assert_eq!( actix_web::body::to_bytes(body).await.unwrap(), json!({"data": {"subtractCount": 8}}) .to_string() .into_bytes() ); let response = srv .call( test::TestRequest::with_uri("/") .method(Method::POST) .set_payload(r#"{"query":"mutation{ subtractCount(count: 2) }"}"#) .to_request(), ) .await .unwrap(); assert!(response.status().is_success()); let body = response.into_body(); assert_eq!( actix_web::body::to_bytes(body).await.unwrap(), json!({"data": {"subtractCount": 6}}) .to_string() .into_bytes() ); } #[cfg(feature = "cbor")] #[actix_rt::test] async fn test_cbor() { let srv = test::init_service( App::new() .app_data(Data::new(Schema::new( AddQueryRoot, EmptyMutation, EmptySubscription, ))) .service( web::resource("/") .guard(guard::Post()) .to(gql_handle_schema::<AddQueryRoot, EmptyMutation, EmptySubscription>), ), ) .await; let response = srv .call( test::TestRequest::with_uri("/") .method(Method::POST) .set_payload(r#"{"query":"{ add(a: 10, b: 20) }"}"#) .insert_header((actix_http::header::ACCEPT, "application/cbor")) .to_request(), ) .await .unwrap(); assert!(response.status().is_success()); #[derive(Debug, serde::Deserialize, PartialEq)] struct Response { data: ResponseInner, } #[derive(Debug, serde::Deserialize, PartialEq)] struct ResponseInner { add: i32, } let body = actix_web::body::to_bytes(response.into_body()) .await .unwrap(); let response: Response = serde_cbor::from_slice(&body).unwrap(); assert_eq!( response, Response { data: ResponseInner { add: 30 } } ); }
use proconio::input; fn main() { input! { n: usize, _a: [u32; n], }; if n % 2 == 0 { println!("Second"); } else { println!("First"); } }
use crate::error::{EncryptionErrorType, QuocoError}; use crate::object::{Key, CHUNK_LENGTH, ENCRYPTED_CHUNK_LENGTH}; use crate::Result; use libsodium_sys::{ crypto_secretstream_xchacha20poly1305_HEADERBYTES, crypto_secretstream_xchacha20poly1305_TAG_FINAL, crypto_secretstream_xchacha20poly1305_init_pull, crypto_secretstream_xchacha20poly1305_pull, crypto_secretstream_xchacha20poly1305_state, }; use std::io::{BufRead, Read}; use std::mem::MaybeUninit; use std::ptr::null; use std::{cmp, io}; pub struct DecryptReader<R: Read> { inner: R, in_buf: [u8; ENCRYPTED_CHUNK_LENGTH], out_buf: [u8; CHUNK_LENGTH], // pos, cap method based on BufReader implementation pos: usize, cap: usize, crypto_state: Option<crypto_secretstream_xchacha20poly1305_state>, key: Key, final_tag: bool, } impl<R: Read> DecryptReader<R> { pub fn new(reader: R, key: &Key) -> Self { #[allow(clippy::uninit_assumed_init)] DecryptReader { inner: reader, // TODO: Should I be using zeroed memory here instead? Clippy absolutely hates this. in_buf: unsafe { MaybeUninit::<[u8; ENCRYPTED_CHUNK_LENGTH]>::uninit().assume_init() }, out_buf: unsafe { MaybeUninit::<[u8; CHUNK_LENGTH]>::uninit().assume_init() }, pos: 0, cap: 0, crypto_state: None, key: *key, final_tag: false, } } fn init_crypto(&mut self) -> Result<()> { let mut state = MaybeUninit::<crypto_secretstream_xchacha20poly1305_state>::uninit(); #[allow(clippy::uninit_assumed_init)] let mut header = unsafe { MaybeUninit::<[u8; crypto_secretstream_xchacha20poly1305_HEADERBYTES as usize]>::uninit( ) .assume_init() }; self.inner.read_exact(&mut header)?; unsafe { if crypto_secretstream_xchacha20poly1305_init_pull( state.as_mut_ptr(), header.as_mut_ptr() as *mut u8, self.key.as_ptr(), ) != 0 { return Err(QuocoError::DecryptionError(EncryptionErrorType::Header)); } } self.crypto_state = Some(unsafe { state.assume_init() }); Ok(()) } fn read_next_chunk(&mut self) -> Result<usize> { // TODO: Once the encoder supports this, handle multiple compressed/encrypted blocks in one // file with a header index. // What this write function will need to do is decode the input in chunks, filling the input // buffer until it reaches the beginning of a new block, then decoding the filled buffer and // flushing it. if self.crypto_state.is_none() { self.init_crypto()?; } let mut out_len: u64 = 0; let mut tag: u8 = 0; let bytes_read = self.inner.read(&mut self.in_buf)?; if bytes_read == 0 { return Ok(bytes_read); } if self.final_tag { return Err(QuocoError::EncryptionError(EncryptionErrorType::Other( "Unexpected final tag during decryption.", ))); } // TODO: See if we're making any bad assumptions here unsafe { if crypto_secretstream_xchacha20poly1305_pull( self.crypto_state.as_mut().unwrap(), self.out_buf.as_mut_ptr(), &mut out_len as *mut u64, &mut tag as *mut u8, self.in_buf[..bytes_read].as_ptr(), bytes_read as u64, null(), 0, ) != 0 { return Err(QuocoError::DecryptionError(EncryptionErrorType::Body)); } } // TODO: Figure out how to check whether we've gotten a final tag too soon. // It doesn't work to just check that this chunk is less than ENCRYPTED_CHUNK_LENGTH bytes // because the last chunk could fit perfectly into that size. We need a way to determine if if tag == crypto_secretstream_xchacha20poly1305_TAG_FINAL as u8 { self.final_tag = true; } Ok(out_len as usize) } pub fn into_inner(self) -> R { self.inner } } /// Based on BufReader's implementation impl<R: Read> BufRead for DecryptReader<R> { fn fill_buf(&mut self) -> io::Result<&[u8]> { if self.pos >= self.cap { debug_assert!(self.pos == self.cap); self.cap = self.read_next_chunk()?; self.pos = 0; } Ok(&self.out_buf[self.pos..self.cap]) } fn consume(&mut self, amt: usize) { self.pos = cmp::min(self.pos + amt, self.cap); } } impl<R: Read> Read for DecryptReader<R> { /// Based on BufReader's implementation fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { // TODO: For now each read call can only fill as much data as the internal buffer can // contain. Would it be worth it to do the extra lifting to figure out how to loop to fill // larger buffers? Probably not to me (vinhowe) right now. let nread = { let mut rem = self.fill_buf()?; rem.read(buf)? }; self.consume(nread); Ok(nread) } }
use itertools::Itertools; use std::fs; use std::str; pub fn run() { // F,L -> 0, B,R -> 1 let content: std::string::String = fs::read_to_string("src/day_5/input.txt") .unwrap() .chars() .map(|x| match x { 'F' => '0', 'L' => '0', 'B' => '1', 'R' => '1', _ => x, }) .collect(); let seat_ids: Vec<isize> = content .lines() .map(|x| { x.as_bytes() .chunks(7) .map(str::from_utf8) .map(|a| isize::from_str_radix(a.unwrap(), 2)) .collect::<Result<Vec<isize>, _>>() .unwrap() }) .map(|x| x[0] * 8 + x[1]) .collect::<Vec<isize>>() .into_iter() .sorted() .collect(); let mut previous_seat: isize = 0; for &seat_id in seat_ids.iter() { if seat_id - previous_seat == 2 { println!("My seat ID is {}.", seat_id - 1); } previous_seat = seat_id; } }
extern crate clap; extern crate serde_bencode; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use serde_bencode::de::from_bytes; use serde_bencode::value::Value; #[derive(Eq, PartialEq)] enum StrValue { Dict(HashMap<String, StrValue>), List(Vec<StrValue>), Str(String), Int(i64), } impl ::std::fmt::Debug for StrValue { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { StrValue::Dict(ref map) => write!(f, "{:?}", map), StrValue::List(ref vec) => write!(f, "{:?}", vec), StrValue::Str(ref s) => write!(f, "{:?}", s), StrValue::Int(ref i) => write!(f, "{:?}", i), } } } impl ::std::convert::From<Value> for StrValue { fn from(input: Value) -> StrValue { match input { Value::Dict(map) => { let mut m = HashMap::new(); for (key, val) in map { let key = String::from_utf8_lossy(&key[..]).into_owned(); let val = val.into(); m.insert(key, val); } StrValue::Dict(m) } Value::List(v) => StrValue::List(v.into_iter().map(|x| x.into()).collect()), Value::Bytes(b) => { let length = b.len(); let s = String::from_utf8(b).unwrap_or(format!("<bin:{}>", length)); StrValue::Str(s) } Value::Int(i) => StrValue::Int(i), } } } fn main() { let mut b = vec![]; let opts = clap::App::new("bparse") .about("Parses bencode files into a readable json-like format") .author("J. Cliff Dyer <jcd@sdf.org>") .arg(clap::Arg::with_name("file").required(true).index(1)) .get_matches(); let filename = opts.value_of("file").unwrap(); // let filename = "data/These Systems Are Failing.torrent"; //let filename = "data/archlinux-2017.12.01-x86_64.iso.torrent"; let mut f = File::open(&filename).unwrap(); f.read_to_end(&mut b).unwrap(); let v: Value = from_bytes(&b).unwrap(); let str_value: StrValue = v.into(); println!("{:?}", str_value); // Uncomment the following to see the reserialized file //assert!(false, "Success!"); }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::HashMap; use std::collections::HashSet; use std::fmt; use std::fmt::Formatter; use std::sync::Arc; use common_datavalues::DataSchema; use crate::MetaVersion; #[derive(serde::Serialize, serde::Deserialize, Debug, Default, Clone, PartialEq)] pub struct Table { pub table_id: u64, /// name of this table pub table_name: String, /// identity of the database which this table belongs to pub database_id: u64, /// snapshot of the database name which this table is being created pub db_name: String, /// serialized schema pub schema: Vec<u8>, /// table engine pub table_engine: String, /// table options pub table_options: HashMap<String, String>, /// name of parts that belong to this table. pub parts: HashSet<String>, } impl fmt::Display for Table { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "table id: {}", self.table_id) } } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Eq, PartialEq)] pub struct TableInfo { pub database_id: u64, pub table_id: u64, /// version of this table snapshot. /// /// Any change to a table causes the version to increment, e.g. insert or delete rows, update schema etc. /// But renaming a table should not affect the version, since the table itself does not change. /// The tuple (database_id, table_id, version) identifies a unique and consistent table snapshot. /// /// A version is not guaranteed to be consecutive. /// pub version: MetaVersion, pub db: String, pub name: String, pub schema: Arc<DataSchema>, pub engine: String, pub options: HashMap<String, String>, } impl TableInfo { /// Create a TableInfo with only db, table, schema pub fn simple(db: &str, table: &str, schema: Arc<DataSchema>) -> TableInfo { TableInfo { db: db.to_string(), name: table.to_string(), schema, ..Default::default() } } pub fn schema(mut self, schema: Arc<DataSchema>) -> TableInfo { self.schema = schema; self } } impl Default for TableInfo { fn default() -> Self { TableInfo { database_id: 0, table_id: 0, version: 0, db: "".to_string(), name: "".to_string(), schema: Arc::new(DataSchema::empty()), engine: "".to_string(), options: HashMap::new(), } } }
use krnl::gdt; use krnl::idt; use krnl::port::Port; use krnl::port; use spin::Mutex; extern "C" { fn irq_handler0(); fn irq_handler1(); fn irq_handler2(); fn irq_handler3(); fn irq_handler4(); fn irq_handler5(); fn irq_handler6(); fn irq_handler7(); fn irq_handler8(); fn irq_handler9(); fn irq_handler10(); fn irq_handler11(); fn irq_handler12(); fn irq_handler13(); fn irq_handler14(); fn irq_handler15(); } const IRQ_VECTOR_OFFSET: u8 = 32; const MAX_ENTRIES: usize = 16; const PORT_MASTER_PIC_CMD: Port = Port::new(0x20); const PORT_MASTER_PIC_DAT: Port = Port::new(0x21); const PORT_SLAVE_PIC_CMD: Port = Port::new(0xa0); const PORT_SLAVE_PIC_DAT: Port = Port::new(0xa1); pub struct IrqContext { gs: u32, fs: u32, es: u32, ds: u32, edi: u32, esi: u32, ebp: u32, esp: u32, ebx: u32, edx: u32, ecx: u32, eax: u32, irq_index: u32, eip: u32, cs: u32, eflags: u32, } type IrqFn = fn(&IrqContext) -> (); pub struct Irq { entries: ([Option<IrqFn>; MAX_ENTRIES]), } pub static IRQ: Mutex<Irq> = Mutex::new(Irq { entries: [None; MAX_ENTRIES], }); impl Irq { // install an IRQ handler. pub fn install(&mut self, index: usize, handler: IrqFn) { if self.entries[index].is_some() { printf!( "[irq::install] IRQ{} handler already exists, overwritten.\n", index ); } self.entries[index] = Some(handler) } // uninstall an IRQ handler. pub fn uninstall(&mut self, index: usize) { if self.entries[index].is_none() { printf!("[irq::uninstall] IRQ{} handler not exists.\n", index); } self.entries[index] = None } unsafe fn set_mask(index: i32, set: bool) { let (port, n_index) = if index < 8 { (PORT_MASTER_PIC_DAT, index) } else { (PORT_SLAVE_PIC_DAT, index - 8) }; let value = port::inb(port); if set { port::outb(port, value | (1 << n_index)) } else { port::outb(port, value & !(1 << n_index)) } } // disable an IRQ by setting mask. pub unsafe fn disable(index: i32) { Self::set_mask(index, true) } // enable an IRQ by clearing mask. pub unsafe fn enable(index: i32) { Self::set_mask(index, false) } } #[no_mangle] pub extern "C" fn irq_dispatcher(ctx: IrqContext) { let irq_index = ctx.irq_index as usize; let irq_fn = IRQ.lock().entries[irq_index]; if irq_fn.is_none() { printf!("[IRQ dispatcher] Unhandled IRQ {}.\n", irq_index); } else { irq_fn.unwrap()(&ctx); } // send an EOI (end of interrupt) to indicate that we are done. unsafe { if irq_index >= 8 { port::outb(PORT_SLAVE_PIC_CMD, 0x20); } port::outb(PORT_MASTER_PIC_CMD, 0x20); } } pub fn initialize() { unsafe { // remap IRQ to proper IDT entries (32 ~ 47). port::outb(PORT_MASTER_PIC_CMD, 0x11); port::outb(PORT_SLAVE_PIC_CMD, 0x11); port::outb(PORT_MASTER_PIC_DAT, IRQ_VECTOR_OFFSET); // vector offset for master PIC is 32 port::outb(PORT_SLAVE_PIC_DAT, IRQ_VECTOR_OFFSET + 8); // vector offset for slave PIC is 40 port::outb(PORT_MASTER_PIC_DAT, 0x4); // tell master PIC that there is a slave PIC at IRQ2 port::outb(PORT_SLAVE_PIC_DAT, 0x2); // tell slave PIC its cascade identity port::outb(PORT_MASTER_PIC_DAT, 0x1); port::outb(PORT_SLAVE_PIC_DAT, 0x1); // disable all IRQs by default. port::outb(PORT_MASTER_PIC_DAT, 0xff); port::outb(PORT_SLAVE_PIC_DAT, 0xff); } // initialize IRQ to correct entries in the IDT. let mut idt = idt::IDT.lock(); macro_rules! set_irq { ($id:expr, $fun:ident) => { idt.set_gate( ($id + IRQ_VECTOR_OFFSET) as usize, $fun as *const () as u32, gdt::KRNL_CODE_SEL, 0x8e ); }; } set_irq!(0, irq_handler0); set_irq!(1, irq_handler1); set_irq!(2, irq_handler2); set_irq!(3, irq_handler3); set_irq!(4, irq_handler4); set_irq!(5, irq_handler5); set_irq!(6, irq_handler6); set_irq!(7, irq_handler7); set_irq!(8, irq_handler8); set_irq!(9, irq_handler9); set_irq!(10, irq_handler10); set_irq!(11, irq_handler11); set_irq!(12, irq_handler12); set_irq!(13, irq_handler13); set_irq!(14, irq_handler14); set_irq!(15, irq_handler15); }
//! [SPARQL](https://www.w3.org/TR/sparql11-overview/) implementation. mod algebra; mod eval; mod json_results; mod model; mod parser; mod plan; mod plan_builder; mod xml_results; use crate::sparql::algebra::QueryVariants; use crate::sparql::eval::SimpleEvaluator; use crate::sparql::parser::read_sparql_query; use crate::sparql::plan::TripleTemplate; use crate::sparql::plan::{DatasetView, PlanNode}; use crate::sparql::plan_builder::PlanBuilder; use crate::store::StoreConnection; use crate::Result; use std::fmt; pub use crate::sparql::model::BindingsIterator; pub use crate::sparql::model::QueryResult; pub use crate::sparql::model::QueryResultSyntax; pub use crate::sparql::model::Variable; /// A prepared [SPARQL query](https://www.w3.org/TR/sparql11-query/) pub trait PreparedQuery { /// Evaluates the query and returns its results fn exec(&self) -> Result<QueryResult>; } /// An implementation of `PreparedQuery` for internal use pub struct SimplePreparedQuery<S: StoreConnection>(SimplePreparedQueryOptions<S>); enum SimplePreparedQueryOptions<S: StoreConnection> { Select { plan: PlanNode, variables: Vec<Variable>, evaluator: SimpleEvaluator<S>, }, Ask { plan: PlanNode, evaluator: SimpleEvaluator<S>, }, Construct { plan: PlanNode, construct: Vec<TripleTemplate>, evaluator: SimpleEvaluator<S>, }, Describe { plan: PlanNode, evaluator: SimpleEvaluator<S>, }, } impl<S: StoreConnection> SimplePreparedQuery<S> { pub(crate) fn new(connection: S, query: &str, base_iri: Option<&str>) -> Result<Self> { let dataset = DatasetView::new(connection); //TODO avoid inserting terms in the Repository StringStore Ok(Self(match read_sparql_query(query, base_iri)? { QueryVariants::Select { algebra, dataset: _, base_iri, } => { let (plan, variables) = PlanBuilder::build(dataset.encoder(), &algebra)?; SimplePreparedQueryOptions::Select { plan, variables, evaluator: SimpleEvaluator::new(dataset, base_iri), } } QueryVariants::Ask { algebra, dataset: _, base_iri, } => { let (plan, _) = PlanBuilder::build(dataset.encoder(), &algebra)?; SimplePreparedQueryOptions::Ask { plan, evaluator: SimpleEvaluator::new(dataset, base_iri), } } QueryVariants::Construct { construct, algebra, dataset: _, base_iri, } => { let (plan, variables) = PlanBuilder::build(dataset.encoder(), &algebra)?; SimplePreparedQueryOptions::Construct { plan, construct: PlanBuilder::build_graph_template( dataset.encoder(), &construct, variables, )?, evaluator: SimpleEvaluator::new(dataset, base_iri), } } QueryVariants::Describe { algebra, dataset: _, base_iri, } => { let (plan, _) = PlanBuilder::build(dataset.encoder(), &algebra)?; SimplePreparedQueryOptions::Describe { plan, evaluator: SimpleEvaluator::new(dataset, base_iri), } } })) } } impl<S: StoreConnection> PreparedQuery for SimplePreparedQuery<S> { fn exec(&self) -> Result<QueryResult<'_>> { match &self.0 { SimplePreparedQueryOptions::Select { plan, variables, evaluator, } => evaluator.evaluate_select_plan(&plan, &variables), SimplePreparedQueryOptions::Ask { plan, evaluator } => { evaluator.evaluate_ask_plan(&plan) } SimplePreparedQueryOptions::Construct { plan, construct, evaluator, } => evaluator.evaluate_construct_plan(&plan, &construct), SimplePreparedQueryOptions::Describe { plan, evaluator } => { evaluator.evaluate_describe_plan(&plan) } } } } /// A parsed [SPARQL query](https://www.w3.org/TR/sparql11-query/) #[derive(Eq, PartialEq, Debug, Clone, Hash)] pub struct Query(QueryVariants); impl fmt::Display for Query { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } impl Query { /// Parses a SPARQL query pub fn parse(query: &str, base_iri: Option<&str>) -> Result<Self> { Ok(Query(read_sparql_query(query, base_iri)?)) } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[cfg(feature = "Win32_Foundation")] pub fn ChooseColorA(param0: *mut CHOOSECOLORA) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn ChooseColorW(param0: *mut CHOOSECOLORW) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn ChooseFontA(param0: *mut CHOOSEFONTA) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn ChooseFontW(param0: *mut CHOOSEFONTW) -> super::super::super::Foundation::BOOL; pub fn CommDlgExtendedError() -> COMMON_DLG_ERRORS; #[cfg(feature = "Win32_Foundation")] pub fn FindTextA(param0: *mut FINDREPLACEA) -> super::super::super::Foundation::HWND; #[cfg(feature = "Win32_Foundation")] pub fn FindTextW(param0: *mut FINDREPLACEW) -> super::super::super::Foundation::HWND; #[cfg(feature = "Win32_Foundation")] pub fn GetFileTitleA(param0: super::super::super::Foundation::PSTR, buf: super::super::super::Foundation::PSTR, cchsize: u16) -> i16; #[cfg(feature = "Win32_Foundation")] pub fn GetFileTitleW(param0: super::super::super::Foundation::PWSTR, buf: super::super::super::Foundation::PWSTR, cchsize: u16) -> i16; #[cfg(feature = "Win32_Foundation")] pub fn GetOpenFileNameA(param0: *mut OPENFILENAMEA) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn GetOpenFileNameW(param0: *mut OPENFILENAMEW) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn GetSaveFileNameA(param0: *mut OPENFILENAMEA) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn GetSaveFileNameW(param0: *mut OPENFILENAMEW) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn PageSetupDlgA(param0: *mut PAGESETUPDLGA) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn PageSetupDlgW(param0: *mut PAGESETUPDLGW) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn PrintDlgA(ppd: *mut PRINTDLGA) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn PrintDlgExA(ppd: *mut PRINTDLGEXA) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn PrintDlgExW(ppd: *mut PRINTDLGEXW) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn PrintDlgW(ppd: *mut PRINTDLGW) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub fn ReplaceTextA(param0: *mut FINDREPLACEA) -> super::super::super::Foundation::HWND; #[cfg(feature = "Win32_Foundation")] pub fn ReplaceTextW(param0: *mut FINDREPLACEW) -> super::super::super::Foundation::HWND; } pub const CDM_FIRST: u32 = 1124u32; pub const CDM_GETFILEPATH: u32 = 1125u32; pub const CDM_GETFOLDERIDLIST: u32 = 1127u32; pub const CDM_GETFOLDERPATH: u32 = 1126u32; pub const CDM_GETSPEC: u32 = 1124u32; pub const CDM_HIDECONTROL: u32 = 1129u32; pub const CDM_LAST: u32 = 1224u32; pub const CDM_SETCONTROLTEXT: u32 = 1128u32; pub const CDM_SETDEFEXT: u32 = 1130u32; pub const CD_LBSELADD: u32 = 2u32; pub const CD_LBSELCHANGE: u32 = 0u32; pub const CD_LBSELNOITEMS: i32 = -1i32; pub const CD_LBSELSUB: u32 = 1u32; #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct CHOOSECOLORA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HWND, pub rgbResult: u32, pub lpCustColors: *mut u32, pub Flags: u32, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPCCHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PSTR, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for CHOOSECOLORA {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for CHOOSECOLORA { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct CHOOSECOLORA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HWND, pub rgbResult: u32, pub lpCustColors: *mut u32, pub Flags: u32, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPCCHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PSTR, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for CHOOSECOLORA {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for CHOOSECOLORA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct CHOOSECOLORW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HWND, pub rgbResult: u32, pub lpCustColors: *mut u32, pub Flags: u32, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPCCHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PWSTR, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for CHOOSECOLORW {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for CHOOSECOLORW { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct CHOOSECOLORW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HWND, pub rgbResult: u32, pub lpCustColors: *mut u32, pub Flags: u32, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPCCHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PWSTR, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for CHOOSECOLORW {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for CHOOSECOLORW { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct CHOOSEFONTA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDC: super::super::super::Graphics::Gdi::HDC, pub lpLogFont: *mut super::super::super::Graphics::Gdi::LOGFONTA, pub iPointSize: i32, pub Flags: CHOOSEFONT_FLAGS, pub rgbColors: u32, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPCFHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PSTR, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpszStyle: super::super::super::Foundation::PSTR, pub nFontType: CHOOSEFONT_FONT_TYPE, pub ___MISSING_ALIGNMENT__: u16, pub nSizeMin: i32, pub nSizeMax: i32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for CHOOSEFONTA {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for CHOOSEFONTA { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct CHOOSEFONTA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDC: super::super::super::Graphics::Gdi::HDC, pub lpLogFont: *mut super::super::super::Graphics::Gdi::LOGFONTA, pub iPointSize: i32, pub Flags: CHOOSEFONT_FLAGS, pub rgbColors: u32, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPCFHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PSTR, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpszStyle: super::super::super::Foundation::PSTR, pub nFontType: CHOOSEFONT_FONT_TYPE, pub ___MISSING_ALIGNMENT__: u16, pub nSizeMin: i32, pub nSizeMax: i32, } #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for CHOOSEFONTA {} #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for CHOOSEFONTA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct CHOOSEFONTW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDC: super::super::super::Graphics::Gdi::HDC, pub lpLogFont: *mut super::super::super::Graphics::Gdi::LOGFONTW, pub iPointSize: i32, pub Flags: CHOOSEFONT_FLAGS, pub rgbColors: u32, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPCFHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PWSTR, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpszStyle: super::super::super::Foundation::PWSTR, pub nFontType: CHOOSEFONT_FONT_TYPE, pub ___MISSING_ALIGNMENT__: u16, pub nSizeMin: i32, pub nSizeMax: i32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for CHOOSEFONTW {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for CHOOSEFONTW { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct CHOOSEFONTW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDC: super::super::super::Graphics::Gdi::HDC, pub lpLogFont: *mut super::super::super::Graphics::Gdi::LOGFONTW, pub iPointSize: i32, pub Flags: CHOOSEFONT_FLAGS, pub rgbColors: u32, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPCFHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PWSTR, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpszStyle: super::super::super::Foundation::PWSTR, pub nFontType: CHOOSEFONT_FONT_TYPE, pub ___MISSING_ALIGNMENT__: u16, pub nSizeMin: i32, pub nSizeMax: i32, } #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for CHOOSEFONTW {} #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for CHOOSEFONTW { fn clone(&self) -> Self { *self } } pub type CHOOSEFONT_FLAGS = u32; pub const CF_APPLY: CHOOSEFONT_FLAGS = 512u32; pub const CF_ANSIONLY: CHOOSEFONT_FLAGS = 1024u32; pub const CF_BOTH: CHOOSEFONT_FLAGS = 3u32; pub const CF_EFFECTS: CHOOSEFONT_FLAGS = 256u32; pub const CF_ENABLEHOOK: CHOOSEFONT_FLAGS = 8u32; pub const CF_ENABLETEMPLATE: CHOOSEFONT_FLAGS = 16u32; pub const CF_ENABLETEMPLATEHANDLE: CHOOSEFONT_FLAGS = 32u32; pub const CF_FIXEDPITCHONLY: CHOOSEFONT_FLAGS = 16384u32; pub const CF_FORCEFONTEXIST: CHOOSEFONT_FLAGS = 65536u32; pub const CF_INACTIVEFONTS: CHOOSEFONT_FLAGS = 33554432u32; pub const CF_INITTOLOGFONTSTRUCT: CHOOSEFONT_FLAGS = 64u32; pub const CF_LIMITSIZE: CHOOSEFONT_FLAGS = 8192u32; pub const CF_NOOEMFONTS: CHOOSEFONT_FLAGS = 2048u32; pub const CF_NOFACESEL: CHOOSEFONT_FLAGS = 524288u32; pub const CF_NOSCRIPTSEL: CHOOSEFONT_FLAGS = 8388608u32; pub const CF_NOSIMULATIONS: CHOOSEFONT_FLAGS = 4096u32; pub const CF_NOSIZESEL: CHOOSEFONT_FLAGS = 2097152u32; pub const CF_NOSTYLESEL: CHOOSEFONT_FLAGS = 1048576u32; pub const CF_NOVECTORFONTS: CHOOSEFONT_FLAGS = 2048u32; pub const CF_NOVERTFONTS: CHOOSEFONT_FLAGS = 16777216u32; pub const CF_PRINTERFONTS: CHOOSEFONT_FLAGS = 2u32; pub const CF_SCALABLEONLY: CHOOSEFONT_FLAGS = 131072u32; pub const CF_SCREENFONTS: CHOOSEFONT_FLAGS = 1u32; pub const CF_SCRIPTSONLY: CHOOSEFONT_FLAGS = 1024u32; pub const CF_SELECTSCRIPT: CHOOSEFONT_FLAGS = 4194304u32; pub const CF_SHOWHELP: CHOOSEFONT_FLAGS = 4u32; pub const CF_TTONLY: CHOOSEFONT_FLAGS = 262144u32; pub const CF_USESTYLE: CHOOSEFONT_FLAGS = 128u32; pub const CF_WYSIWYG: CHOOSEFONT_FLAGS = 32768u32; pub type CHOOSEFONT_FONT_TYPE = u16; pub const BOLD_FONTTYPE: CHOOSEFONT_FONT_TYPE = 256u16; pub const ITALIC_FONTTYPE: CHOOSEFONT_FONT_TYPE = 512u16; pub const PRINTER_FONTTYPE: CHOOSEFONT_FONT_TYPE = 16384u16; pub const REGULAR_FONTTYPE: CHOOSEFONT_FONT_TYPE = 1024u16; pub const SCREEN_FONTTYPE: CHOOSEFONT_FONT_TYPE = 8192u16; pub const SIMULATED_FONTTYPE: CHOOSEFONT_FONT_TYPE = 32768u16; pub const COLOR_ADD: u32 = 712u32; pub const COLOR_BLUE: u32 = 708u32; pub const COLOR_BLUEACCEL: u32 = 728u32; pub const COLOR_BOX1: u32 = 720u32; pub const COLOR_CURRENT: u32 = 709u32; pub const COLOR_CUSTOM1: u32 = 721u32; pub const COLOR_ELEMENT: u32 = 716u32; pub const COLOR_GREEN: u32 = 707u32; pub const COLOR_GREENACCEL: u32 = 727u32; pub const COLOR_HUE: u32 = 703u32; pub const COLOR_HUEACCEL: u32 = 723u32; pub const COLOR_HUESCROLL: u32 = 700u32; pub const COLOR_LUM: u32 = 705u32; pub const COLOR_LUMACCEL: u32 = 725u32; pub const COLOR_LUMSCROLL: u32 = 702u32; pub const COLOR_MIX: u32 = 719u32; pub const COLOR_PALETTE: u32 = 718u32; pub const COLOR_RAINBOW: u32 = 710u32; pub const COLOR_RED: u32 = 706u32; pub const COLOR_REDACCEL: u32 = 726u32; pub const COLOR_SAMPLES: u32 = 717u32; pub const COLOR_SAT: u32 = 704u32; pub const COLOR_SATACCEL: u32 = 724u32; pub const COLOR_SATSCROLL: u32 = 701u32; pub const COLOR_SAVE: u32 = 711u32; pub const COLOR_SCHEMES: u32 = 715u32; pub const COLOR_SOLID: u32 = 713u32; pub const COLOR_SOLID_LEFT: u32 = 730u32; pub const COLOR_SOLID_RIGHT: u32 = 731u32; pub const COLOR_TUNE: u32 = 714u32; pub type COMMON_DLG_ERRORS = u32; pub const CDERR_DIALOGFAILURE: COMMON_DLG_ERRORS = 65535u32; pub const CDERR_GENERALCODES: COMMON_DLG_ERRORS = 0u32; pub const CDERR_STRUCTSIZE: COMMON_DLG_ERRORS = 1u32; pub const CDERR_INITIALIZATION: COMMON_DLG_ERRORS = 2u32; pub const CDERR_NOTEMPLATE: COMMON_DLG_ERRORS = 3u32; pub const CDERR_NOHINSTANCE: COMMON_DLG_ERRORS = 4u32; pub const CDERR_LOADSTRFAILURE: COMMON_DLG_ERRORS = 5u32; pub const CDERR_FINDRESFAILURE: COMMON_DLG_ERRORS = 6u32; pub const CDERR_LOADRESFAILURE: COMMON_DLG_ERRORS = 7u32; pub const CDERR_LOCKRESFAILURE: COMMON_DLG_ERRORS = 8u32; pub const CDERR_MEMALLOCFAILURE: COMMON_DLG_ERRORS = 9u32; pub const CDERR_MEMLOCKFAILURE: COMMON_DLG_ERRORS = 10u32; pub const CDERR_NOHOOK: COMMON_DLG_ERRORS = 11u32; pub const CDERR_REGISTERMSGFAIL: COMMON_DLG_ERRORS = 12u32; pub const PDERR_PRINTERCODES: COMMON_DLG_ERRORS = 4096u32; pub const PDERR_SETUPFAILURE: COMMON_DLG_ERRORS = 4097u32; pub const PDERR_PARSEFAILURE: COMMON_DLG_ERRORS = 4098u32; pub const PDERR_RETDEFFAILURE: COMMON_DLG_ERRORS = 4099u32; pub const PDERR_LOADDRVFAILURE: COMMON_DLG_ERRORS = 4100u32; pub const PDERR_GETDEVMODEFAIL: COMMON_DLG_ERRORS = 4101u32; pub const PDERR_INITFAILURE: COMMON_DLG_ERRORS = 4102u32; pub const PDERR_NODEVICES: COMMON_DLG_ERRORS = 4103u32; pub const PDERR_NODEFAULTPRN: COMMON_DLG_ERRORS = 4104u32; pub const PDERR_DNDMMISMATCH: COMMON_DLG_ERRORS = 4105u32; pub const PDERR_CREATEICFAILURE: COMMON_DLG_ERRORS = 4106u32; pub const PDERR_PRINTERNOTFOUND: COMMON_DLG_ERRORS = 4107u32; pub const PDERR_DEFAULTDIFFERENT: COMMON_DLG_ERRORS = 4108u32; pub const CFERR_CHOOSEFONTCODES: COMMON_DLG_ERRORS = 8192u32; pub const CFERR_NOFONTS: COMMON_DLG_ERRORS = 8193u32; pub const CFERR_MAXLESSTHANMIN: COMMON_DLG_ERRORS = 8194u32; pub const FNERR_FILENAMECODES: COMMON_DLG_ERRORS = 12288u32; pub const FNERR_SUBCLASSFAILURE: COMMON_DLG_ERRORS = 12289u32; pub const FNERR_INVALIDFILENAME: COMMON_DLG_ERRORS = 12290u32; pub const FNERR_BUFFERTOOSMALL: COMMON_DLG_ERRORS = 12291u32; pub const FRERR_FINDREPLACECODES: COMMON_DLG_ERRORS = 16384u32; pub const FRERR_BUFFERLENGTHZERO: COMMON_DLG_ERRORS = 16385u32; pub const CCERR_CHOOSECOLORCODES: COMMON_DLG_ERRORS = 20480u32; #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct DEVNAMES { pub wDriverOffset: u16, pub wDeviceOffset: u16, pub wOutputOffset: u16, pub wDefault: u16, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::marker::Copy for DEVNAMES {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::clone::Clone for DEVNAMES { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] pub struct DEVNAMES { pub wDriverOffset: u16, pub wDeviceOffset: u16, pub wOutputOffset: u16, pub wDefault: u16, } #[cfg(any(target_arch = "x86",))] impl ::core::marker::Copy for DEVNAMES {} #[cfg(any(target_arch = "x86",))] impl ::core::clone::Clone for DEVNAMES { fn clone(&self) -> Self { *self } } pub const DLG_COLOR: u32 = 10u32; pub const DN_DEFAULTPRN: u32 = 1u32; #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct FINDREPLACEA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HINSTANCE, pub Flags: FINDREPLACE_FLAGS, pub lpstrFindWhat: super::super::super::Foundation::PSTR, pub lpstrReplaceWith: super::super::super::Foundation::PSTR, pub wFindWhatLen: u16, pub wReplaceWithLen: u16, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPFRHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PSTR, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for FINDREPLACEA {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for FINDREPLACEA { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct FINDREPLACEA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HINSTANCE, pub Flags: FINDREPLACE_FLAGS, pub lpstrFindWhat: super::super::super::Foundation::PSTR, pub lpstrReplaceWith: super::super::super::Foundation::PSTR, pub wFindWhatLen: u16, pub wReplaceWithLen: u16, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPFRHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PSTR, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for FINDREPLACEA {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for FINDREPLACEA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct FINDREPLACEW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HINSTANCE, pub Flags: FINDREPLACE_FLAGS, pub lpstrFindWhat: super::super::super::Foundation::PWSTR, pub lpstrReplaceWith: super::super::super::Foundation::PWSTR, pub wFindWhatLen: u16, pub wReplaceWithLen: u16, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPFRHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PWSTR, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for FINDREPLACEW {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for FINDREPLACEW { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct FINDREPLACEW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HINSTANCE, pub Flags: FINDREPLACE_FLAGS, pub lpstrFindWhat: super::super::super::Foundation::PWSTR, pub lpstrReplaceWith: super::super::super::Foundation::PWSTR, pub wFindWhatLen: u16, pub wReplaceWithLen: u16, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPFRHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PWSTR, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for FINDREPLACEW {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for FINDREPLACEW { fn clone(&self) -> Self { *self } } pub type FINDREPLACE_FLAGS = u32; pub const FR_DIALOGTERM: FINDREPLACE_FLAGS = 64u32; pub const FR_DOWN: FINDREPLACE_FLAGS = 1u32; pub const FR_ENABLEHOOK: FINDREPLACE_FLAGS = 256u32; pub const FR_ENABLETEMPLATE: FINDREPLACE_FLAGS = 512u32; pub const FR_ENABLETEMPLATEHANDLE: FINDREPLACE_FLAGS = 8192u32; pub const FR_FINDNEXT: FINDREPLACE_FLAGS = 8u32; pub const FR_HIDEUPDOWN: FINDREPLACE_FLAGS = 16384u32; pub const FR_HIDEMATCHCASE: FINDREPLACE_FLAGS = 32768u32; pub const FR_HIDEWHOLEWORD: FINDREPLACE_FLAGS = 65536u32; pub const FR_MATCHCASE: FINDREPLACE_FLAGS = 4u32; pub const FR_NOMATCHCASE: FINDREPLACE_FLAGS = 2048u32; pub const FR_NOUPDOWN: FINDREPLACE_FLAGS = 1024u32; pub const FR_NOWHOLEWORD: FINDREPLACE_FLAGS = 4096u32; pub const FR_REPLACE: FINDREPLACE_FLAGS = 16u32; pub const FR_REPLACEALL: FINDREPLACE_FLAGS = 32u32; pub const FR_SHOWHELP: FINDREPLACE_FLAGS = 128u32; pub const FR_WHOLEWORD: FINDREPLACE_FLAGS = 2u32; pub const FRM_FIRST: u32 = 1124u32; pub const FRM_LAST: u32 = 1224u32; pub const FRM_SETOPERATIONRESULT: u32 = 1124u32; pub const FRM_SETOPERATIONRESULTTEXT: u32 = 1125u32; pub const FR_NOWRAPAROUND: u32 = 524288u32; pub const FR_RAW: u32 = 131072u32; pub const FR_SHOWWRAPAROUND: u32 = 262144u32; pub const FR_WRAPAROUND: u32 = 1048576u32; pub type IPrintDialogCallback = *mut ::core::ffi::c_void; pub type IPrintDialogServices = *mut ::core::ffi::c_void; #[cfg(feature = "Win32_Foundation")] pub type LPCCHOOKPROC = ::core::option::Option<unsafe extern "system" fn(param0: super::super::super::Foundation::HWND, param1: u32, param2: super::super::super::Foundation::WPARAM, param3: super::super::super::Foundation::LPARAM) -> usize>; #[cfg(feature = "Win32_Foundation")] pub type LPCFHOOKPROC = ::core::option::Option<unsafe extern "system" fn(param0: super::super::super::Foundation::HWND, param1: u32, param2: super::super::super::Foundation::WPARAM, param3: super::super::super::Foundation::LPARAM) -> usize>; #[cfg(feature = "Win32_Foundation")] pub type LPFRHOOKPROC = ::core::option::Option<unsafe extern "system" fn(param0: super::super::super::Foundation::HWND, param1: u32, param2: super::super::super::Foundation::WPARAM, param3: super::super::super::Foundation::LPARAM) -> usize>; #[cfg(feature = "Win32_Foundation")] pub type LPOFNHOOKPROC = ::core::option::Option<unsafe extern "system" fn(param0: super::super::super::Foundation::HWND, param1: u32, param2: super::super::super::Foundation::WPARAM, param3: super::super::super::Foundation::LPARAM) -> usize>; #[cfg(feature = "Win32_Foundation")] pub type LPPAGEPAINTHOOK = ::core::option::Option<unsafe extern "system" fn(param0: super::super::super::Foundation::HWND, param1: u32, param2: super::super::super::Foundation::WPARAM, param3: super::super::super::Foundation::LPARAM) -> usize>; #[cfg(feature = "Win32_Foundation")] pub type LPPAGESETUPHOOK = ::core::option::Option<unsafe extern "system" fn(param0: super::super::super::Foundation::HWND, param1: u32, param2: super::super::super::Foundation::WPARAM, param3: super::super::super::Foundation::LPARAM) -> usize>; #[cfg(feature = "Win32_Foundation")] pub type LPPRINTHOOKPROC = ::core::option::Option<unsafe extern "system" fn(param0: super::super::super::Foundation::HWND, param1: u32, param2: super::super::super::Foundation::WPARAM, param3: super::super::super::Foundation::LPARAM) -> usize>; #[cfg(feature = "Win32_Foundation")] pub type LPSETUPHOOKPROC = ::core::option::Option<unsafe extern "system" fn(param0: super::super::super::Foundation::HWND, param1: u32, param2: super::super::super::Foundation::WPARAM, param3: super::super::super::Foundation::LPARAM) -> usize>; pub const NUM_BASIC_COLORS: u32 = 48u32; pub const NUM_CUSTOM_COLORS: u32 = 16u32; #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct OFNOTIFYA { pub hdr: super::NMHDR, pub lpOFN: *mut OPENFILENAMEA, pub pszFile: super::super::super::Foundation::PSTR, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OFNOTIFYA {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OFNOTIFYA { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct OFNOTIFYA { pub hdr: super::NMHDR, pub lpOFN: *mut OPENFILENAMEA, pub pszFile: super::super::super::Foundation::PSTR, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OFNOTIFYA {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OFNOTIFYA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct OFNOTIFYEXA { pub hdr: super::NMHDR, pub lpOFN: *mut OPENFILENAMEA, pub psf: *mut ::core::ffi::c_void, pub pidl: *mut ::core::ffi::c_void, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OFNOTIFYEXA {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OFNOTIFYEXA { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct OFNOTIFYEXA { pub hdr: super::NMHDR, pub lpOFN: *mut OPENFILENAMEA, pub psf: *mut ::core::ffi::c_void, pub pidl: *mut ::core::ffi::c_void, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OFNOTIFYEXA {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OFNOTIFYEXA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct OFNOTIFYEXW { pub hdr: super::NMHDR, pub lpOFN: *mut OPENFILENAMEW, pub psf: *mut ::core::ffi::c_void, pub pidl: *mut ::core::ffi::c_void, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OFNOTIFYEXW {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OFNOTIFYEXW { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct OFNOTIFYEXW { pub hdr: super::NMHDR, pub lpOFN: *mut OPENFILENAMEW, pub psf: *mut ::core::ffi::c_void, pub pidl: *mut ::core::ffi::c_void, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OFNOTIFYEXW {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OFNOTIFYEXW { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct OFNOTIFYW { pub hdr: super::NMHDR, pub lpOFN: *mut OPENFILENAMEW, pub pszFile: super::super::super::Foundation::PWSTR, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OFNOTIFYW {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OFNOTIFYW { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct OFNOTIFYW { pub hdr: super::NMHDR, pub lpOFN: *mut OPENFILENAMEW, pub pszFile: super::super::super::Foundation::PWSTR, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OFNOTIFYW {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OFNOTIFYW { fn clone(&self) -> Self { *self } } pub const OFN_SHAREFALLTHROUGH: u32 = 2u32; pub const OFN_SHARENOWARN: u32 = 1u32; pub const OFN_SHAREWARN: u32 = 0u32; #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct OPENFILENAMEA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpstrFilter: super::super::super::Foundation::PSTR, pub lpstrCustomFilter: super::super::super::Foundation::PSTR, pub nMaxCustFilter: u32, pub nFilterIndex: u32, pub lpstrFile: super::super::super::Foundation::PSTR, pub nMaxFile: u32, pub lpstrFileTitle: super::super::super::Foundation::PSTR, pub nMaxFileTitle: u32, pub lpstrInitialDir: super::super::super::Foundation::PSTR, pub lpstrTitle: super::super::super::Foundation::PSTR, pub Flags: OPEN_FILENAME_FLAGS, pub nFileOffset: u16, pub nFileExtension: u16, pub lpstrDefExt: super::super::super::Foundation::PSTR, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPOFNHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PSTR, pub pvReserved: *mut ::core::ffi::c_void, pub dwReserved: u32, pub FlagsEx: OPEN_FILENAME_FLAGS_EX, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OPENFILENAMEA {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OPENFILENAMEA { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct OPENFILENAMEA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpstrFilter: super::super::super::Foundation::PSTR, pub lpstrCustomFilter: super::super::super::Foundation::PSTR, pub nMaxCustFilter: u32, pub nFilterIndex: u32, pub lpstrFile: super::super::super::Foundation::PSTR, pub nMaxFile: u32, pub lpstrFileTitle: super::super::super::Foundation::PSTR, pub nMaxFileTitle: u32, pub lpstrInitialDir: super::super::super::Foundation::PSTR, pub lpstrTitle: super::super::super::Foundation::PSTR, pub Flags: OPEN_FILENAME_FLAGS, pub nFileOffset: u16, pub nFileExtension: u16, pub lpstrDefExt: super::super::super::Foundation::PSTR, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPOFNHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PSTR, pub pvReserved: *mut ::core::ffi::c_void, pub dwReserved: u32, pub FlagsEx: OPEN_FILENAME_FLAGS_EX, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OPENFILENAMEA {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OPENFILENAMEA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct OPENFILENAMEW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpstrFilter: super::super::super::Foundation::PWSTR, pub lpstrCustomFilter: super::super::super::Foundation::PWSTR, pub nMaxCustFilter: u32, pub nFilterIndex: u32, pub lpstrFile: super::super::super::Foundation::PWSTR, pub nMaxFile: u32, pub lpstrFileTitle: super::super::super::Foundation::PWSTR, pub nMaxFileTitle: u32, pub lpstrInitialDir: super::super::super::Foundation::PWSTR, pub lpstrTitle: super::super::super::Foundation::PWSTR, pub Flags: OPEN_FILENAME_FLAGS, pub nFileOffset: u16, pub nFileExtension: u16, pub lpstrDefExt: super::super::super::Foundation::PWSTR, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPOFNHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PWSTR, pub pvReserved: *mut ::core::ffi::c_void, pub dwReserved: u32, pub FlagsEx: OPEN_FILENAME_FLAGS_EX, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OPENFILENAMEW {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OPENFILENAMEW { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct OPENFILENAMEW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpstrFilter: super::super::super::Foundation::PWSTR, pub lpstrCustomFilter: super::super::super::Foundation::PWSTR, pub nMaxCustFilter: u32, pub nFilterIndex: u32, pub lpstrFile: super::super::super::Foundation::PWSTR, pub nMaxFile: u32, pub lpstrFileTitle: super::super::super::Foundation::PWSTR, pub nMaxFileTitle: u32, pub lpstrInitialDir: super::super::super::Foundation::PWSTR, pub lpstrTitle: super::super::super::Foundation::PWSTR, pub Flags: OPEN_FILENAME_FLAGS, pub nFileOffset: u16, pub nFileExtension: u16, pub lpstrDefExt: super::super::super::Foundation::PWSTR, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPOFNHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PWSTR, pub pvReserved: *mut ::core::ffi::c_void, pub dwReserved: u32, pub FlagsEx: OPEN_FILENAME_FLAGS_EX, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OPENFILENAMEW {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OPENFILENAMEW { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct OPENFILENAME_NT4A { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpstrFilter: super::super::super::Foundation::PSTR, pub lpstrCustomFilter: super::super::super::Foundation::PSTR, pub nMaxCustFilter: u32, pub nFilterIndex: u32, pub lpstrFile: super::super::super::Foundation::PSTR, pub nMaxFile: u32, pub lpstrFileTitle: super::super::super::Foundation::PSTR, pub nMaxFileTitle: u32, pub lpstrInitialDir: super::super::super::Foundation::PSTR, pub lpstrTitle: super::super::super::Foundation::PSTR, pub Flags: u32, pub nFileOffset: u16, pub nFileExtension: u16, pub lpstrDefExt: super::super::super::Foundation::PSTR, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPOFNHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PSTR, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OPENFILENAME_NT4A {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OPENFILENAME_NT4A { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct OPENFILENAME_NT4A { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpstrFilter: super::super::super::Foundation::PSTR, pub lpstrCustomFilter: super::super::super::Foundation::PSTR, pub nMaxCustFilter: u32, pub nFilterIndex: u32, pub lpstrFile: super::super::super::Foundation::PSTR, pub nMaxFile: u32, pub lpstrFileTitle: super::super::super::Foundation::PSTR, pub nMaxFileTitle: u32, pub lpstrInitialDir: super::super::super::Foundation::PSTR, pub lpstrTitle: super::super::super::Foundation::PSTR, pub Flags: u32, pub nFileOffset: u16, pub nFileExtension: u16, pub lpstrDefExt: super::super::super::Foundation::PSTR, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPOFNHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PSTR, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OPENFILENAME_NT4A {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OPENFILENAME_NT4A { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct OPENFILENAME_NT4W { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpstrFilter: super::super::super::Foundation::PWSTR, pub lpstrCustomFilter: super::super::super::Foundation::PWSTR, pub nMaxCustFilter: u32, pub nFilterIndex: u32, pub lpstrFile: super::super::super::Foundation::PWSTR, pub nMaxFile: u32, pub lpstrFileTitle: super::super::super::Foundation::PWSTR, pub nMaxFileTitle: u32, pub lpstrInitialDir: super::super::super::Foundation::PWSTR, pub lpstrTitle: super::super::super::Foundation::PWSTR, pub Flags: u32, pub nFileOffset: u16, pub nFileExtension: u16, pub lpstrDefExt: super::super::super::Foundation::PWSTR, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPOFNHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PWSTR, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OPENFILENAME_NT4W {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OPENFILENAME_NT4W { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct OPENFILENAME_NT4W { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpstrFilter: super::super::super::Foundation::PWSTR, pub lpstrCustomFilter: super::super::super::Foundation::PWSTR, pub nMaxCustFilter: u32, pub nFilterIndex: u32, pub lpstrFile: super::super::super::Foundation::PWSTR, pub nMaxFile: u32, pub lpstrFileTitle: super::super::super::Foundation::PWSTR, pub nMaxFileTitle: u32, pub lpstrInitialDir: super::super::super::Foundation::PWSTR, pub lpstrTitle: super::super::super::Foundation::PWSTR, pub Flags: u32, pub nFileOffset: u16, pub nFileExtension: u16, pub lpstrDefExt: super::super::super::Foundation::PWSTR, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnHook: LPOFNHOOKPROC, pub lpTemplateName: super::super::super::Foundation::PWSTR, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for OPENFILENAME_NT4W {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for OPENFILENAME_NT4W { fn clone(&self) -> Self { *self } } pub type OPEN_FILENAME_FLAGS = u32; pub const OFN_READONLY: OPEN_FILENAME_FLAGS = 1u32; pub const OFN_OVERWRITEPROMPT: OPEN_FILENAME_FLAGS = 2u32; pub const OFN_HIDEREADONLY: OPEN_FILENAME_FLAGS = 4u32; pub const OFN_NOCHANGEDIR: OPEN_FILENAME_FLAGS = 8u32; pub const OFN_SHOWHELP: OPEN_FILENAME_FLAGS = 16u32; pub const OFN_ENABLEHOOK: OPEN_FILENAME_FLAGS = 32u32; pub const OFN_ENABLETEMPLATE: OPEN_FILENAME_FLAGS = 64u32; pub const OFN_ENABLETEMPLATEHANDLE: OPEN_FILENAME_FLAGS = 128u32; pub const OFN_NOVALIDATE: OPEN_FILENAME_FLAGS = 256u32; pub const OFN_ALLOWMULTISELECT: OPEN_FILENAME_FLAGS = 512u32; pub const OFN_EXTENSIONDIFFERENT: OPEN_FILENAME_FLAGS = 1024u32; pub const OFN_PATHMUSTEXIST: OPEN_FILENAME_FLAGS = 2048u32; pub const OFN_FILEMUSTEXIST: OPEN_FILENAME_FLAGS = 4096u32; pub const OFN_CREATEPROMPT: OPEN_FILENAME_FLAGS = 8192u32; pub const OFN_SHAREAWARE: OPEN_FILENAME_FLAGS = 16384u32; pub const OFN_NOREADONLYRETURN: OPEN_FILENAME_FLAGS = 32768u32; pub const OFN_NOTESTFILECREATE: OPEN_FILENAME_FLAGS = 65536u32; pub const OFN_NONETWORKBUTTON: OPEN_FILENAME_FLAGS = 131072u32; pub const OFN_NOLONGNAMES: OPEN_FILENAME_FLAGS = 262144u32; pub const OFN_EXPLORER: OPEN_FILENAME_FLAGS = 524288u32; pub const OFN_NODEREFERENCELINKS: OPEN_FILENAME_FLAGS = 1048576u32; pub const OFN_LONGNAMES: OPEN_FILENAME_FLAGS = 2097152u32; pub const OFN_ENABLEINCLUDENOTIFY: OPEN_FILENAME_FLAGS = 4194304u32; pub const OFN_ENABLESIZING: OPEN_FILENAME_FLAGS = 8388608u32; pub const OFN_DONTADDTORECENT: OPEN_FILENAME_FLAGS = 33554432u32; pub const OFN_FORCESHOWHIDDEN: OPEN_FILENAME_FLAGS = 268435456u32; pub type OPEN_FILENAME_FLAGS_EX = u32; pub const OFN_EX_NONE: OPEN_FILENAME_FLAGS_EX = 0u32; pub const OFN_EX_NOPLACESBAR: OPEN_FILENAME_FLAGS_EX = 1u32; #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct PAGESETUPDLGA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDevMode: isize, pub hDevNames: isize, pub Flags: PAGESETUPDLG_FLAGS, pub ptPaperSize: super::super::super::Foundation::POINT, pub rtMinMargin: super::super::super::Foundation::RECT, pub rtMargin: super::super::super::Foundation::RECT, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnPageSetupHook: LPPAGESETUPHOOK, pub lpfnPagePaintHook: LPPAGEPAINTHOOK, pub lpPageSetupTemplateName: super::super::super::Foundation::PSTR, pub hPageSetupTemplate: isize, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for PAGESETUPDLGA {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for PAGESETUPDLGA { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct PAGESETUPDLGA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDevMode: isize, pub hDevNames: isize, pub Flags: PAGESETUPDLG_FLAGS, pub ptPaperSize: super::super::super::Foundation::POINT, pub rtMinMargin: super::super::super::Foundation::RECT, pub rtMargin: super::super::super::Foundation::RECT, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnPageSetupHook: LPPAGESETUPHOOK, pub lpfnPagePaintHook: LPPAGEPAINTHOOK, pub lpPageSetupTemplateName: super::super::super::Foundation::PSTR, pub hPageSetupTemplate: isize, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for PAGESETUPDLGA {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for PAGESETUPDLGA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct PAGESETUPDLGW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDevMode: isize, pub hDevNames: isize, pub Flags: PAGESETUPDLG_FLAGS, pub ptPaperSize: super::super::super::Foundation::POINT, pub rtMinMargin: super::super::super::Foundation::RECT, pub rtMargin: super::super::super::Foundation::RECT, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnPageSetupHook: LPPAGESETUPHOOK, pub lpfnPagePaintHook: LPPAGEPAINTHOOK, pub lpPageSetupTemplateName: super::super::super::Foundation::PWSTR, pub hPageSetupTemplate: isize, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for PAGESETUPDLGW {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for PAGESETUPDLGW { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct PAGESETUPDLGW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDevMode: isize, pub hDevNames: isize, pub Flags: PAGESETUPDLG_FLAGS, pub ptPaperSize: super::super::super::Foundation::POINT, pub rtMinMargin: super::super::super::Foundation::RECT, pub rtMargin: super::super::super::Foundation::RECT, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnPageSetupHook: LPPAGESETUPHOOK, pub lpfnPagePaintHook: LPPAGEPAINTHOOK, pub lpPageSetupTemplateName: super::super::super::Foundation::PWSTR, pub hPageSetupTemplate: isize, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for PAGESETUPDLGW {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for PAGESETUPDLGW { fn clone(&self) -> Self { *self } } pub type PAGESETUPDLG_FLAGS = u32; pub const PSD_DEFAULTMINMARGINS: PAGESETUPDLG_FLAGS = 0u32; pub const PSD_DISABLEMARGINS: PAGESETUPDLG_FLAGS = 16u32; pub const PSD_DISABLEORIENTATION: PAGESETUPDLG_FLAGS = 256u32; pub const PSD_DISABLEPAGEPAINTING: PAGESETUPDLG_FLAGS = 524288u32; pub const PSD_DISABLEPAPER: PAGESETUPDLG_FLAGS = 512u32; pub const PSD_DISABLEPRINTER: PAGESETUPDLG_FLAGS = 32u32; pub const PSD_ENABLEPAGEPAINTHOOK: PAGESETUPDLG_FLAGS = 262144u32; pub const PSD_ENABLEPAGESETUPHOOK: PAGESETUPDLG_FLAGS = 8192u32; pub const PSD_ENABLEPAGESETUPTEMPLATE: PAGESETUPDLG_FLAGS = 32768u32; pub const PSD_ENABLEPAGESETUPTEMPLATEHANDLE: PAGESETUPDLG_FLAGS = 131072u32; pub const PSD_INHUNDREDTHSOFMILLIMETERS: PAGESETUPDLG_FLAGS = 8u32; pub const PSD_INTHOUSANDTHSOFINCHES: PAGESETUPDLG_FLAGS = 4u32; pub const PSD_INWININIINTLMEASURE: PAGESETUPDLG_FLAGS = 0u32; pub const PSD_MARGINS: PAGESETUPDLG_FLAGS = 2u32; pub const PSD_MINMARGINS: PAGESETUPDLG_FLAGS = 1u32; pub const PSD_NONETWORKBUTTON: PAGESETUPDLG_FLAGS = 2097152u32; pub const PSD_NOWARNING: PAGESETUPDLG_FLAGS = 128u32; pub const PSD_RETURNDEFAULT: PAGESETUPDLG_FLAGS = 1024u32; pub const PSD_SHOWHELP: PAGESETUPDLG_FLAGS = 2048u32; pub const PD_RESULT_APPLY: u32 = 2u32; pub const PD_RESULT_CANCEL: u32 = 0u32; pub const PD_RESULT_PRINT: u32 = 1u32; #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct PRINTDLGA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDevMode: isize, pub hDevNames: isize, pub hDC: super::super::super::Graphics::Gdi::HDC, pub Flags: PRINTDLGEX_FLAGS, pub nFromPage: u16, pub nToPage: u16, pub nMinPage: u16, pub nMaxPage: u16, pub nCopies: u16, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnPrintHook: LPPRINTHOOKPROC, pub lpfnSetupHook: LPSETUPHOOKPROC, pub lpPrintTemplateName: super::super::super::Foundation::PSTR, pub lpSetupTemplateName: super::super::super::Foundation::PSTR, pub hPrintTemplate: isize, pub hSetupTemplate: isize, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for PRINTDLGA {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for PRINTDLGA { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct PRINTDLGA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDevMode: isize, pub hDevNames: isize, pub hDC: super::super::super::Graphics::Gdi::HDC, pub Flags: PRINTDLGEX_FLAGS, pub nFromPage: u16, pub nToPage: u16, pub nMinPage: u16, pub nMaxPage: u16, pub nCopies: u16, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnPrintHook: LPPRINTHOOKPROC, pub lpfnSetupHook: LPSETUPHOOKPROC, pub lpPrintTemplateName: super::super::super::Foundation::PSTR, pub lpSetupTemplateName: super::super::super::Foundation::PSTR, pub hPrintTemplate: isize, pub hSetupTemplate: isize, } #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for PRINTDLGA {} #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for PRINTDLGA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct PRINTDLGEXA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDevMode: isize, pub hDevNames: isize, pub hDC: super::super::super::Graphics::Gdi::HDC, pub Flags: PRINTDLGEX_FLAGS, pub Flags2: u32, pub ExclusionFlags: u32, pub nPageRanges: u32, pub nMaxPageRanges: u32, pub lpPageRanges: *mut PRINTPAGERANGE, pub nMinPage: u32, pub nMaxPage: u32, pub nCopies: u32, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpPrintTemplateName: super::super::super::Foundation::PSTR, pub lpCallback: ::windows_sys::core::IUnknown, pub nPropertyPages: u32, pub lphPropertyPages: *mut super::HPROPSHEETPAGE, pub nStartPage: u32, pub dwResultAction: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for PRINTDLGEXA {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for PRINTDLGEXA { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct PRINTDLGEXA { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDevMode: isize, pub hDevNames: isize, pub hDC: super::super::super::Graphics::Gdi::HDC, pub Flags: PRINTDLGEX_FLAGS, pub Flags2: u32, pub ExclusionFlags: u32, pub nPageRanges: u32, pub nMaxPageRanges: u32, pub lpPageRanges: *mut PRINTPAGERANGE, pub nMinPage: u32, pub nMaxPage: u32, pub nCopies: u32, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpPrintTemplateName: super::super::super::Foundation::PSTR, pub lpCallback: ::windows_sys::core::IUnknown, pub nPropertyPages: u32, pub lphPropertyPages: *mut super::HPROPSHEETPAGE, pub nStartPage: u32, pub dwResultAction: u32, } #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for PRINTDLGEXA {} #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for PRINTDLGEXA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct PRINTDLGEXW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDevMode: isize, pub hDevNames: isize, pub hDC: super::super::super::Graphics::Gdi::HDC, pub Flags: PRINTDLGEX_FLAGS, pub Flags2: u32, pub ExclusionFlags: u32, pub nPageRanges: u32, pub nMaxPageRanges: u32, pub lpPageRanges: *mut PRINTPAGERANGE, pub nMinPage: u32, pub nMaxPage: u32, pub nCopies: u32, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpPrintTemplateName: super::super::super::Foundation::PWSTR, pub lpCallback: ::windows_sys::core::IUnknown, pub nPropertyPages: u32, pub lphPropertyPages: *mut super::HPROPSHEETPAGE, pub nStartPage: u32, pub dwResultAction: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for PRINTDLGEXW {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for PRINTDLGEXW { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct PRINTDLGEXW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDevMode: isize, pub hDevNames: isize, pub hDC: super::super::super::Graphics::Gdi::HDC, pub Flags: PRINTDLGEX_FLAGS, pub Flags2: u32, pub ExclusionFlags: u32, pub nPageRanges: u32, pub nMaxPageRanges: u32, pub lpPageRanges: *mut PRINTPAGERANGE, pub nMinPage: u32, pub nMaxPage: u32, pub nCopies: u32, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lpPrintTemplateName: super::super::super::Foundation::PWSTR, pub lpCallback: ::windows_sys::core::IUnknown, pub nPropertyPages: u32, pub lphPropertyPages: *mut super::HPROPSHEETPAGE, pub nStartPage: u32, pub dwResultAction: u32, } #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for PRINTDLGEXW {} #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for PRINTDLGEXW { fn clone(&self) -> Self { *self } } pub type PRINTDLGEX_FLAGS = u32; pub const PD_ALLPAGES: PRINTDLGEX_FLAGS = 0u32; pub const PD_COLLATE: PRINTDLGEX_FLAGS = 16u32; pub const PD_CURRENTPAGE: PRINTDLGEX_FLAGS = 4194304u32; pub const PD_DISABLEPRINTTOFILE: PRINTDLGEX_FLAGS = 524288u32; pub const PD_ENABLEPRINTTEMPLATE: PRINTDLGEX_FLAGS = 16384u32; pub const PD_ENABLEPRINTTEMPLATEHANDLE: PRINTDLGEX_FLAGS = 65536u32; pub const PD_EXCLUSIONFLAGS: PRINTDLGEX_FLAGS = 16777216u32; pub const PD_HIDEPRINTTOFILE: PRINTDLGEX_FLAGS = 1048576u32; pub const PD_NOCURRENTPAGE: PRINTDLGEX_FLAGS = 8388608u32; pub const PD_NOPAGENUMS: PRINTDLGEX_FLAGS = 8u32; pub const PD_NOSELECTION: PRINTDLGEX_FLAGS = 4u32; pub const PD_NOWARNING: PRINTDLGEX_FLAGS = 128u32; pub const PD_PAGENUMS: PRINTDLGEX_FLAGS = 2u32; pub const PD_PRINTTOFILE: PRINTDLGEX_FLAGS = 32u32; pub const PD_RETURNDC: PRINTDLGEX_FLAGS = 256u32; pub const PD_RETURNDEFAULT: PRINTDLGEX_FLAGS = 1024u32; pub const PD_RETURNIC: PRINTDLGEX_FLAGS = 512u32; pub const PD_SELECTION: PRINTDLGEX_FLAGS = 1u32; pub const PD_USEDEVMODECOPIES: PRINTDLGEX_FLAGS = 262144u32; pub const PD_USEDEVMODECOPIESANDCOLLATE: PRINTDLGEX_FLAGS = 262144u32; pub const PD_USELARGETEMPLATE: PRINTDLGEX_FLAGS = 268435456u32; pub const PD_ENABLEPRINTHOOK: PRINTDLGEX_FLAGS = 4096u32; pub const PD_ENABLESETUPHOOK: PRINTDLGEX_FLAGS = 8192u32; pub const PD_ENABLESETUPTEMPLATE: PRINTDLGEX_FLAGS = 32768u32; pub const PD_ENABLESETUPTEMPLATEHANDLE: PRINTDLGEX_FLAGS = 131072u32; pub const PD_NONETWORKBUTTON: PRINTDLGEX_FLAGS = 2097152u32; pub const PD_PRINTSETUP: PRINTDLGEX_FLAGS = 64u32; pub const PD_SHOWHELP: PRINTDLGEX_FLAGS = 2048u32; #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct PRINTDLGW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDevMode: isize, pub hDevNames: isize, pub hDC: super::super::super::Graphics::Gdi::HDC, pub Flags: PRINTDLGEX_FLAGS, pub nFromPage: u16, pub nToPage: u16, pub nMinPage: u16, pub nMaxPage: u16, pub nCopies: u16, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnPrintHook: LPPRINTHOOKPROC, pub lpfnSetupHook: LPSETUPHOOKPROC, pub lpPrintTemplateName: super::super::super::Foundation::PWSTR, pub lpSetupTemplateName: super::super::super::Foundation::PWSTR, pub hPrintTemplate: isize, pub hSetupTemplate: isize, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for PRINTDLGW {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for PRINTDLGW { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub struct PRINTDLGW { pub lStructSize: u32, pub hwndOwner: super::super::super::Foundation::HWND, pub hDevMode: isize, pub hDevNames: isize, pub hDC: super::super::super::Graphics::Gdi::HDC, pub Flags: PRINTDLGEX_FLAGS, pub nFromPage: u16, pub nToPage: u16, pub nMinPage: u16, pub nMaxPage: u16, pub nCopies: u16, pub hInstance: super::super::super::Foundation::HINSTANCE, pub lCustData: super::super::super::Foundation::LPARAM, pub lpfnPrintHook: LPPRINTHOOKPROC, pub lpfnSetupHook: LPSETUPHOOKPROC, pub lpPrintTemplateName: super::super::super::Foundation::PWSTR, pub lpSetupTemplateName: super::super::super::Foundation::PWSTR, pub hPrintTemplate: isize, pub hSetupTemplate: isize, } #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::marker::Copy for PRINTDLGW {} #[cfg(any(target_arch = "x86",))] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] impl ::core::clone::Clone for PRINTDLGW { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct PRINTPAGERANGE { pub nFromPage: u32, pub nToPage: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::marker::Copy for PRINTPAGERANGE {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::clone::Clone for PRINTPAGERANGE { fn clone(&self) -> Self { *self } } #[repr(C, packed(1))] #[cfg(any(target_arch = "x86",))] pub struct PRINTPAGERANGE { pub nFromPage: u32, pub nToPage: u32, } #[cfg(any(target_arch = "x86",))] impl ::core::marker::Copy for PRINTPAGERANGE {} #[cfg(any(target_arch = "x86",))] impl ::core::clone::Clone for PRINTPAGERANGE { fn clone(&self) -> Self { *self } } pub const PS_OPENTYPE_FONTTYPE: u32 = 65536u32; pub const START_PAGE_GENERAL: u32 = 4294967295u32; pub const SYMBOL_FONTTYPE: u32 = 524288u32; pub const TT_OPENTYPE_FONTTYPE: u32 = 131072u32; pub const TYPE1_FONTTYPE: u32 = 262144u32; pub const WM_CHOOSEFONT_GETLOGFONT: u32 = 1025u32; pub const WM_CHOOSEFONT_SETFLAGS: u32 = 1126u32; pub const WM_CHOOSEFONT_SETLOGFONT: u32 = 1125u32; pub const WM_PSD_ENVSTAMPRECT: u32 = 1029u32; pub const WM_PSD_FULLPAGERECT: u32 = 1025u32; pub const WM_PSD_GREEKTEXTRECT: u32 = 1028u32; pub const WM_PSD_MARGINRECT: u32 = 1027u32; pub const WM_PSD_MINMARGINRECT: u32 = 1026u32; pub const WM_PSD_YAFULLPAGERECT: u32 = 1030u32;
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtCore/qurlquery.h // dst-file: /src/core/qurlquery.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use std::ops::Deref; use super::qstring::*; // 773 use super::qchar::*; // 773 use super::qurl::*; // 773 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QUrlQuery_Class_Size() -> c_int; // proto: void QUrlQuery::QUrlQuery(const QString & queryString); fn C_ZN9QUrlQueryC2ERK7QString(arg0: *mut c_void) -> u64; // proto: void QUrlQuery::clear(); fn C_ZN9QUrlQuery5clearEv(qthis: u64 /* *mut c_void*/); // proto: void QUrlQuery::setQuery(const QString & queryString); fn C_ZN9QUrlQuery8setQueryERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QChar QUrlQuery::queryValueDelimiter(); fn C_ZNK9QUrlQuery19queryValueDelimiterEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QChar QUrlQuery::queryPairDelimiter(); fn C_ZNK9QUrlQuery18queryPairDelimiterEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: static QChar QUrlQuery::defaultQueryValueDelimiter(); fn C_ZN9QUrlQuery26defaultQueryValueDelimiterEv() -> *mut c_void; // proto: void QUrlQuery::swap(QUrlQuery & other); fn C_ZN9QUrlQuery4swapERS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: bool QUrlQuery::isDetached(); fn C_ZNK9QUrlQuery10isDetachedEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QUrlQuery::QUrlQuery(); fn C_ZN9QUrlQueryC2Ev() -> u64; // proto: void QUrlQuery::setQueryDelimiters(QChar valueDelimiter, QChar pairDelimiter); fn C_ZN9QUrlQuery18setQueryDelimitersE5QCharS0_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void); // proto: void QUrlQuery::~QUrlQuery(); fn C_ZN9QUrlQueryD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QUrlQuery::removeAllQueryItems(const QString & key); fn C_ZN9QUrlQuery19removeAllQueryItemsERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: bool QUrlQuery::isEmpty(); fn C_ZNK9QUrlQuery7isEmptyEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QUrlQuery::removeQueryItem(const QString & key); fn C_ZN9QUrlQuery15removeQueryItemERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: static QChar QUrlQuery::defaultQueryPairDelimiter(); fn C_ZN9QUrlQuery25defaultQueryPairDelimiterEv() -> *mut c_void; // proto: void QUrlQuery::QUrlQuery(const QUrl & url); fn C_ZN9QUrlQueryC2ERK4QUrl(arg0: *mut c_void) -> u64; // proto: void QUrlQuery::addQueryItem(const QString & key, const QString & value); fn C_ZN9QUrlQuery12addQueryItemERK7QStringS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void); // proto: void QUrlQuery::QUrlQuery(const QUrlQuery & other); fn C_ZN9QUrlQueryC2ERKS_(arg0: *mut c_void) -> u64; // proto: bool QUrlQuery::hasQueryItem(const QString & key); fn C_ZNK9QUrlQuery12hasQueryItemERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char; } // <= ext block end // body block begin => // class sizeof(QUrlQuery)=1 #[derive(Default)] pub struct QUrlQuery { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QUrlQuery { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QUrlQuery { return QUrlQuery{qclsinst: qthis, ..Default::default()}; } } // proto: void QUrlQuery::QUrlQuery(const QString & queryString); impl /*struct*/ QUrlQuery { pub fn new<T: QUrlQuery_new>(value: T) -> QUrlQuery { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QUrlQuery_new { fn new(self) -> QUrlQuery; } // proto: void QUrlQuery::QUrlQuery(const QString & queryString); impl<'a> /*trait*/ QUrlQuery_new for (&'a QString) { fn new(self) -> QUrlQuery { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQueryC2ERK7QString()}; let ctysz: c_int = unsafe{QUrlQuery_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN9QUrlQueryC2ERK7QString(arg0)}; let rsthis = QUrlQuery{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QUrlQuery::clear(); impl /*struct*/ QUrlQuery { pub fn clear<RetType, T: QUrlQuery_clear<RetType>>(& self, overload_args: T) -> RetType { return overload_args.clear(self); // return 1; } } pub trait QUrlQuery_clear<RetType> { fn clear(self , rsthis: & QUrlQuery) -> RetType; } // proto: void QUrlQuery::clear(); impl<'a> /*trait*/ QUrlQuery_clear<()> for () { fn clear(self , rsthis: & QUrlQuery) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQuery5clearEv()}; unsafe {C_ZN9QUrlQuery5clearEv(rsthis.qclsinst)}; // return 1; } } // proto: void QUrlQuery::setQuery(const QString & queryString); impl /*struct*/ QUrlQuery { pub fn setQuery<RetType, T: QUrlQuery_setQuery<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setQuery(self); // return 1; } } pub trait QUrlQuery_setQuery<RetType> { fn setQuery(self , rsthis: & QUrlQuery) -> RetType; } // proto: void QUrlQuery::setQuery(const QString & queryString); impl<'a> /*trait*/ QUrlQuery_setQuery<()> for (&'a QString) { fn setQuery(self , rsthis: & QUrlQuery) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQuery8setQueryERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QUrlQuery8setQueryERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QChar QUrlQuery::queryValueDelimiter(); impl /*struct*/ QUrlQuery { pub fn queryValueDelimiter<RetType, T: QUrlQuery_queryValueDelimiter<RetType>>(& self, overload_args: T) -> RetType { return overload_args.queryValueDelimiter(self); // return 1; } } pub trait QUrlQuery_queryValueDelimiter<RetType> { fn queryValueDelimiter(self , rsthis: & QUrlQuery) -> RetType; } // proto: QChar QUrlQuery::queryValueDelimiter(); impl<'a> /*trait*/ QUrlQuery_queryValueDelimiter<QChar> for () { fn queryValueDelimiter(self , rsthis: & QUrlQuery) -> QChar { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QUrlQuery19queryValueDelimiterEv()}; let mut ret = unsafe {C_ZNK9QUrlQuery19queryValueDelimiterEv(rsthis.qclsinst)}; let mut ret1 = QChar::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QChar QUrlQuery::queryPairDelimiter(); impl /*struct*/ QUrlQuery { pub fn queryPairDelimiter<RetType, T: QUrlQuery_queryPairDelimiter<RetType>>(& self, overload_args: T) -> RetType { return overload_args.queryPairDelimiter(self); // return 1; } } pub trait QUrlQuery_queryPairDelimiter<RetType> { fn queryPairDelimiter(self , rsthis: & QUrlQuery) -> RetType; } // proto: QChar QUrlQuery::queryPairDelimiter(); impl<'a> /*trait*/ QUrlQuery_queryPairDelimiter<QChar> for () { fn queryPairDelimiter(self , rsthis: & QUrlQuery) -> QChar { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QUrlQuery18queryPairDelimiterEv()}; let mut ret = unsafe {C_ZNK9QUrlQuery18queryPairDelimiterEv(rsthis.qclsinst)}; let mut ret1 = QChar::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: static QChar QUrlQuery::defaultQueryValueDelimiter(); impl /*struct*/ QUrlQuery { pub fn defaultQueryValueDelimiter_s<RetType, T: QUrlQuery_defaultQueryValueDelimiter_s<RetType>>( overload_args: T) -> RetType { return overload_args.defaultQueryValueDelimiter_s(); // return 1; } } pub trait QUrlQuery_defaultQueryValueDelimiter_s<RetType> { fn defaultQueryValueDelimiter_s(self ) -> RetType; } // proto: static QChar QUrlQuery::defaultQueryValueDelimiter(); impl<'a> /*trait*/ QUrlQuery_defaultQueryValueDelimiter_s<QChar> for () { fn defaultQueryValueDelimiter_s(self ) -> QChar { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQuery26defaultQueryValueDelimiterEv()}; let mut ret = unsafe {C_ZN9QUrlQuery26defaultQueryValueDelimiterEv()}; let mut ret1 = QChar::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QUrlQuery::swap(QUrlQuery & other); impl /*struct*/ QUrlQuery { pub fn swap<RetType, T: QUrlQuery_swap<RetType>>(& self, overload_args: T) -> RetType { return overload_args.swap(self); // return 1; } } pub trait QUrlQuery_swap<RetType> { fn swap(self , rsthis: & QUrlQuery) -> RetType; } // proto: void QUrlQuery::swap(QUrlQuery & other); impl<'a> /*trait*/ QUrlQuery_swap<()> for (&'a QUrlQuery) { fn swap(self , rsthis: & QUrlQuery) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQuery4swapERS_()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QUrlQuery4swapERS_(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QUrlQuery::isDetached(); impl /*struct*/ QUrlQuery { pub fn isDetached<RetType, T: QUrlQuery_isDetached<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isDetached(self); // return 1; } } pub trait QUrlQuery_isDetached<RetType> { fn isDetached(self , rsthis: & QUrlQuery) -> RetType; } // proto: bool QUrlQuery::isDetached(); impl<'a> /*trait*/ QUrlQuery_isDetached<i8> for () { fn isDetached(self , rsthis: & QUrlQuery) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QUrlQuery10isDetachedEv()}; let mut ret = unsafe {C_ZNK9QUrlQuery10isDetachedEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QUrlQuery::QUrlQuery(); impl<'a> /*trait*/ QUrlQuery_new for () { fn new(self) -> QUrlQuery { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQueryC2Ev()}; let ctysz: c_int = unsafe{QUrlQuery_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let qthis: u64 = unsafe {C_ZN9QUrlQueryC2Ev()}; let rsthis = QUrlQuery{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QUrlQuery::setQueryDelimiters(QChar valueDelimiter, QChar pairDelimiter); impl /*struct*/ QUrlQuery { pub fn setQueryDelimiters<RetType, T: QUrlQuery_setQueryDelimiters<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setQueryDelimiters(self); // return 1; } } pub trait QUrlQuery_setQueryDelimiters<RetType> { fn setQueryDelimiters(self , rsthis: & QUrlQuery) -> RetType; } // proto: void QUrlQuery::setQueryDelimiters(QChar valueDelimiter, QChar pairDelimiter); impl<'a> /*trait*/ QUrlQuery_setQueryDelimiters<()> for (QChar, QChar) { fn setQueryDelimiters(self , rsthis: & QUrlQuery) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQuery18setQueryDelimitersE5QCharS0_()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZN9QUrlQuery18setQueryDelimitersE5QCharS0_(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QUrlQuery::~QUrlQuery(); impl /*struct*/ QUrlQuery { pub fn free<RetType, T: QUrlQuery_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QUrlQuery_free<RetType> { fn free(self , rsthis: & QUrlQuery) -> RetType; } // proto: void QUrlQuery::~QUrlQuery(); impl<'a> /*trait*/ QUrlQuery_free<()> for () { fn free(self , rsthis: & QUrlQuery) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQueryD2Ev()}; unsafe {C_ZN9QUrlQueryD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QUrlQuery::removeAllQueryItems(const QString & key); impl /*struct*/ QUrlQuery { pub fn removeAllQueryItems<RetType, T: QUrlQuery_removeAllQueryItems<RetType>>(& self, overload_args: T) -> RetType { return overload_args.removeAllQueryItems(self); // return 1; } } pub trait QUrlQuery_removeAllQueryItems<RetType> { fn removeAllQueryItems(self , rsthis: & QUrlQuery) -> RetType; } // proto: void QUrlQuery::removeAllQueryItems(const QString & key); impl<'a> /*trait*/ QUrlQuery_removeAllQueryItems<()> for (&'a QString) { fn removeAllQueryItems(self , rsthis: & QUrlQuery) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQuery19removeAllQueryItemsERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QUrlQuery19removeAllQueryItemsERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QUrlQuery::isEmpty(); impl /*struct*/ QUrlQuery { pub fn isEmpty<RetType, T: QUrlQuery_isEmpty<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isEmpty(self); // return 1; } } pub trait QUrlQuery_isEmpty<RetType> { fn isEmpty(self , rsthis: & QUrlQuery) -> RetType; } // proto: bool QUrlQuery::isEmpty(); impl<'a> /*trait*/ QUrlQuery_isEmpty<i8> for () { fn isEmpty(self , rsthis: & QUrlQuery) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QUrlQuery7isEmptyEv()}; let mut ret = unsafe {C_ZNK9QUrlQuery7isEmptyEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QUrlQuery::removeQueryItem(const QString & key); impl /*struct*/ QUrlQuery { pub fn removeQueryItem<RetType, T: QUrlQuery_removeQueryItem<RetType>>(& self, overload_args: T) -> RetType { return overload_args.removeQueryItem(self); // return 1; } } pub trait QUrlQuery_removeQueryItem<RetType> { fn removeQueryItem(self , rsthis: & QUrlQuery) -> RetType; } // proto: void QUrlQuery::removeQueryItem(const QString & key); impl<'a> /*trait*/ QUrlQuery_removeQueryItem<()> for (&'a QString) { fn removeQueryItem(self , rsthis: & QUrlQuery) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQuery15removeQueryItemERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN9QUrlQuery15removeQueryItemERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: static QChar QUrlQuery::defaultQueryPairDelimiter(); impl /*struct*/ QUrlQuery { pub fn defaultQueryPairDelimiter_s<RetType, T: QUrlQuery_defaultQueryPairDelimiter_s<RetType>>( overload_args: T) -> RetType { return overload_args.defaultQueryPairDelimiter_s(); // return 1; } } pub trait QUrlQuery_defaultQueryPairDelimiter_s<RetType> { fn defaultQueryPairDelimiter_s(self ) -> RetType; } // proto: static QChar QUrlQuery::defaultQueryPairDelimiter(); impl<'a> /*trait*/ QUrlQuery_defaultQueryPairDelimiter_s<QChar> for () { fn defaultQueryPairDelimiter_s(self ) -> QChar { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQuery25defaultQueryPairDelimiterEv()}; let mut ret = unsafe {C_ZN9QUrlQuery25defaultQueryPairDelimiterEv()}; let mut ret1 = QChar::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QUrlQuery::QUrlQuery(const QUrl & url); impl<'a> /*trait*/ QUrlQuery_new for (&'a QUrl) { fn new(self) -> QUrlQuery { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQueryC2ERK4QUrl()}; let ctysz: c_int = unsafe{QUrlQuery_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN9QUrlQueryC2ERK4QUrl(arg0)}; let rsthis = QUrlQuery{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QUrlQuery::addQueryItem(const QString & key, const QString & value); impl /*struct*/ QUrlQuery { pub fn addQueryItem<RetType, T: QUrlQuery_addQueryItem<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addQueryItem(self); // return 1; } } pub trait QUrlQuery_addQueryItem<RetType> { fn addQueryItem(self , rsthis: & QUrlQuery) -> RetType; } // proto: void QUrlQuery::addQueryItem(const QString & key, const QString & value); impl<'a> /*trait*/ QUrlQuery_addQueryItem<()> for (&'a QString, &'a QString) { fn addQueryItem(self , rsthis: & QUrlQuery) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQuery12addQueryItemERK7QStringS2_()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZN9QUrlQuery12addQueryItemERK7QStringS2_(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QUrlQuery::QUrlQuery(const QUrlQuery & other); impl<'a> /*trait*/ QUrlQuery_new for (&'a QUrlQuery) { fn new(self) -> QUrlQuery { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN9QUrlQueryC2ERKS_()}; let ctysz: c_int = unsafe{QUrlQuery_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN9QUrlQueryC2ERKS_(arg0)}; let rsthis = QUrlQuery{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: bool QUrlQuery::hasQueryItem(const QString & key); impl /*struct*/ QUrlQuery { pub fn hasQueryItem<RetType, T: QUrlQuery_hasQueryItem<RetType>>(& self, overload_args: T) -> RetType { return overload_args.hasQueryItem(self); // return 1; } } pub trait QUrlQuery_hasQueryItem<RetType> { fn hasQueryItem(self , rsthis: & QUrlQuery) -> RetType; } // proto: bool QUrlQuery::hasQueryItem(const QString & key); impl<'a> /*trait*/ QUrlQuery_hasQueryItem<i8> for (&'a QString) { fn hasQueryItem(self , rsthis: & QUrlQuery) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK9QUrlQuery12hasQueryItemERK7QString()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK9QUrlQuery12hasQueryItemERK7QString(rsthis.qclsinst, arg0)}; return ret as i8; // 1 // return 1; } } // <= body block end
#![feature(macro_rules)] #[deriving(Show, PartialEq)] enum Fart<T> { Butt(T), Turd, } macro_rules! test { ($($fart:expr),+) => ( { $( println!("{} = {}", stringify!($fart), $fart); )+ } ) } fn main() { test!(1i + 1, 0i + 10, "a" == "b"); let f1 = Butt(1i); let f2 = Butt("braap!"); let f3: Fart<Option<u8>> = Turd; let f4 = Butt(12i); let f5 = Butt(12i); test!(f1, f2, f3); test!(f1 == f4, f4 == f5); }
use crate::context::RpcContext; use crate::v04::types::TransactionWithHash; use crate::v02::method::get_transaction_by_hash as v02_get_transaction_by_hash; crate::error::generate_rpc_error_subset!(GetTransactionByHashError: TxnHashNotFoundV04); pub async fn get_transaction_by_hash( context: RpcContext, input: v02_get_transaction_by_hash::GetTransactionByHashInput, ) -> Result<TransactionWithHash, GetTransactionByHashError> { v02_get_transaction_by_hash::get_transaction_by_hash_impl(context, input) .await? .map(|x| { let common_tx = pathfinder_common::transaction::Transaction::from(x); common_tx.into() }) .ok_or(GetTransactionByHashError::TxnHashNotFoundV04) }
use std::{ fs::File, io::{Read, Write}, path::PathBuf, }; pub fn read_file(path: PathBuf) { let mut file = File::open(path).unwrap(); let mut name_len: [u8; 4] = [0; 4]; file.read_exact(&mut name_len).unwrap(); let name_len = u32::from_le_bytes(name_len) as usize; let mut name: Vec<u8> = vec![0; name_len]; file.read_exact(&mut name).unwrap(); let name = String::from_utf8_lossy(&name); println!("name: {}", name); let mut data_len: [u8; 4] = [0; 4]; file.read_exact(&mut data_len).unwrap(); let data_len = u32::from_le_bytes(data_len) as usize; println!("data_len: {}", &data_len); let mut data: Vec<u8> = vec![0; data_len]; file.read_exact(&mut data).unwrap(); println!("data: {:?}", &data); let data = zstd::stream::decode_all(data.as_slice()).unwrap(); let mut decode_data = File::create("decode.data").unwrap(); decode_data.write(&data).unwrap(); }
fn main() { let s = "パタトクカシーー"; let res: String = odd_ch(s); println!("{}", res); } fn odd_ch(s: &str) -> String { s.chars().step_by(2).collect() }
use proconio::{input, marker::Chars}; fn main() { input! { h: usize, w: usize, s: [Chars; h], t: [Chars; h], }; let mut s_cols = Vec::new(); let mut t_cols = Vec::new(); for j in 0..w { let mut s_col = Vec::new(); let mut t_col = Vec::new(); for i in 0..h { s_col.push(s[i][j]); t_col.push(t[i][j]); } s_cols.push(s_col); t_cols.push(t_col); } s_cols.sort(); t_cols.sort(); if s_cols == t_cols { println!("Yes"); } else { println!("No"); } }
#![cfg(feature = "integration")] use grapl_observe::metric_reporter::MetricReporter; use sqs_executor::cache::Cache; #[tokio::test] async fn redis_cache() { const LRU_SIZE: usize = 5; const TOTAL_SIZE: usize = 10; // Create a set of cacheables that we'll store in the cache let all_cacheables: Vec<String> = (0..TOTAL_SIZE) .map(|i| format!("sqs-executor::tests::redis_cache-{}", i)) .collect(); let all_cacheables = all_cacheables.as_slice(); let (stored, not_stored) = all_cacheables.split_at(LRU_SIZE); let redis_endpoint = std::env::var("REDIS_ENDPOINT").expect("REDIS_ENDPOINT"); let mut cache = sqs_executor::redis_cache::RedisCache::with_lru_capacity( LRU_SIZE, redis_endpoint, MetricReporter::<std::io::Stdout>::new("redis_cache"), ) .await .expect("redis client"); cache.store_all(stored).await.unwrap(); // When calling `filter_cached` on what we've stored, we expect an empty response. assert_eq!(cache.filter_cached(stored).await, Vec::new() as Vec<String>); assert_eq!(cache.filter_cached(not_stored).await, not_stored); assert_eq!(cache.filter_cached(all_cacheables).await, not_stored); assert!(cache.all_exist(stored).await); assert!(!cache.all_exist(not_stored).await); assert!(!cache.all_exist(all_cacheables).await); assert!(!cache.all_exist(&["non-existent-key"]).await); }
use super::rocket; use rocket::http::Status; use rocket::local::Client; #[test] fn test_get_events() { let client = Client::new(rocket()).unwrap(); // Test default response let mut response = client.get("/events").dispatch(); let mut expected_body = r#"{"events":{"1":{"id":1,"title":"First Event"},"2":{"id":2,"title":"Second Event"},"3":{"id":3,"title":"Third Event"}},"page":1}"#.to_string(); assert_eq!(response.status(), Status::Ok); assert_eq!(response.body_string(), Some(expected_body)); // Test response for existing page // TODO This test currently only checks if the page parameter is correctly parsed, update expected_body when paging is implemented response = client.get("/events?page=2").dispatch(); expected_body = r#"{"events":{"1":{"id":1,"title":"First Event"},"2":{"id":2,"title":"Second Event"},"3":{"id":3,"title":"Third Event"}},"page":2}"#.to_string(); assert_eq!(response.status(), Status::Ok); assert_eq!(response.body_string(), Some(expected_body)); // Test response for non existing page // response = client.get("/events?page=3").dispatch(); // expected_body = r#"{"events":{"1":{"id":1,"title":"First Event"},"2":{"id":2,"title":"Second Event"},"3":{"id":3,"title":"Third Event"}},"page":3}"#.to_string(); // assert_eq!(response.status(), Status::Ok); // assert_eq!(response.body_string(), Some(expected_body)); // Test response for invalid page value response = client.get("/events?page=test").dispatch(); expected_body = r#"{"events":{"1":{"id":1,"title":"First Event"},"2":{"id":2,"title":"Second Event"},"3":{"id":3,"title":"Third Event"}},"page":1}"#.to_string(); assert_eq!(response.status(), Status::Ok); assert_eq!(response.body_string(), Some(expected_body)); } #[test] fn test_get_event() { let client = Client::new(rocket()).unwrap(); // Test existing event response let mut response = client.get("/events/1").dispatch(); let expected_body = r#"{"id":1,"title":"First Event"}"#.to_string(); assert_eq!(response.status(), Status::Ok); assert_eq!(response.body_string(), Some(expected_body)); // Test non existing event response response = client.get("/events/10").dispatch(); assert_eq!(response.status(), Status::NotFound); // Test invalid event response response = client.get("/events/test").dispatch(); assert_eq!(response.status(), Status::NotFound); } #[test] fn test_delete_event() { let client = Client::new(rocket()).unwrap(); // Test existing event delete let mut response = client.delete("/events/1").dispatch(); assert_eq!(response.status(), Status::NoContent); // Test if the event is actually removed response = client.get("/events/1").dispatch(); assert_eq!(response.status(), Status::NotFound); // Test non existing event delete response = client.get("/events/10").dispatch(); assert_eq!(response.status(), Status::NotFound); // Test invalid event delete response = client.get("/events/test").dispatch(); assert_eq!(response.status(), Status::NotFound); } #[test] fn test_new_event() { let client = Client::new(rocket()).unwrap(); // Test new event let response = client.post("/events") .body(r#"{"title":"Fourth Event"}"#) .dispatch() ; let expected_body = "/events/4"; assert_eq!(response.status(), Status::Created); assert_eq!(response.headers().get_one("Location"), Some(expected_body)); // Test if the event is actually created let location = response.headers().get_one("Location").unwrap(); let mut response = client.get(location).dispatch(); let expected_body = r#"{"id":4,"title":"Fourth Event"}"#.to_string(); assert_eq!(response.status(), Status::Ok); assert_eq!(response.body_string(), Some(expected_body)); } #[test] fn test_update_event() { let client = Client::new(rocket()).unwrap(); let response = client.put("/events/10") .body(r#"{"id":10,"title":"Test Event"}"#) .dispatch() ; assert_eq!(response.status(), Status::Ok); }
extern crate succinct; use succinct::bit; use succinct::bit::*; extern crate rand; use rand::Rng; const CNT: usize = 10; const CAP: usize = 64 << 20; // const CAP: usize = 100_000; #[test] fn test_bits_poppy() { let mut rng = rand::thread_rng(); let num = rng.gen::<u64>(); let len = CAP * rng.gen_range(0, 2) + 32 * rng.gen_range(1, 10); let pop = bit::Poppy::from_bits(&vec![num; len][..]); println!("{:?}", pop); assert_eq!(pop.pop_count(), pop.rank1(pop.size())); assert_eq!(pop.rank0(pop.size()) + pop.rank1(pop.size()), pop.size()); for _ in 0..CNT { let i = rng.gen_range::<usize>(0, pop.pop_count() - 1); let r = pop.rank1(pop.select1(i)); assert_eq!(i, r); } }
use procon_reader::ProconReader; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let k: u64 = rd.get(); let ab: Vec<(u64, u64)> = (0..n) .map(|_| { let a: u64 = rd.get(); let b: u64 = rd.get(); (a, b) }) .collect(); let mut ab = ab; ab.sort(); use std::collections::VecDeque; let mut q: VecDeque<(u64, u64)> = ab.into_iter().collect(); let mut i = 0; let mut k = k; while let Some((a, b)) = q.pop_front() { if i + k < a { println!("{}", i + k); return; } else { k -= a - i; k += b; i = a; } } let ans = i + k; println!("{}", ans); }
use std::mem::{align_of, size_of}; use std::str::FromStr; use debugid::DebugId; use uuid::Uuid; #[test] fn test_is_nil() { assert!(DebugId::default().is_nil()); } #[test] fn test_parse_zero() { assert_eq!( DebugId::from_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75").unwrap(), DebugId::from_parts( Uuid::parse_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75").unwrap(), 0, ) ); } #[test] fn test_parse_short() { assert_eq!( DebugId::from_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75-a").unwrap(), DebugId::from_parts( Uuid::parse_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75").unwrap(), 0xa, ) ); } #[test] fn test_parse_long() { assert_eq!( DebugId::from_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75-feedface").unwrap(), DebugId::from_parts( Uuid::parse_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75").unwrap(), 0xfeed_face, ) ); } #[test] fn test_parse_compact() { assert_eq!( DebugId::from_str("dfb8e43af2423d73a453aeb6a777ef75feedface").unwrap(), DebugId::from_parts( Uuid::parse_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75").unwrap(), 0xfeed_face, ) ); } #[test] fn test_parse_upper() { assert_eq!( DebugId::from_str("DFB8E43A-F242-3D73-A453-AEB6A777EF75-FEEDFACE").unwrap(), DebugId::from_parts( Uuid::parse_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75").unwrap(), 0xfeed_face, ) ); } #[test] fn test_parse_ignores_tail() { assert_eq!( DebugId::from_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75-feedface-1-2-3").unwrap(), DebugId::from_parts( Uuid::parse_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75").unwrap(), 0xfeed_face, ) ); } #[test] fn test_to_string_zero() { let id = DebugId::from_parts( Uuid::parse_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75").unwrap(), 0, ); assert_eq!(id.to_string(), "dfb8e43a-f242-3d73-a453-aeb6a777ef75"); } #[test] fn test_to_string_short() { let id = DebugId::from_parts( Uuid::parse_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75").unwrap(), 10, ); assert_eq!(id.to_string(), "dfb8e43a-f242-3d73-a453-aeb6a777ef75-a"); } #[test] fn test_to_string_long() { let id = DebugId::from_parts( Uuid::parse_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75").unwrap(), 0xfeed_face, ); assert_eq!( id.to_string(), "dfb8e43a-f242-3d73-a453-aeb6a777ef75-feedface" ); } #[test] fn test_parse_error_short() { assert!(DebugId::from_str("dfb8e43a-f242-3d73-a453-aeb6a777ef7").is_err()); } #[test] fn test_parse_error_trailing_dash() { assert!(DebugId::from_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75-").is_err()); } #[test] fn test_parse_error_unicode() { assert!(DebugId::from_str("아이쿱 조합원 앱카드").is_err()); } #[test] fn test_from_guid_age() { let guid = [ 0x98, 0xd1, 0xef, 0xe8, 0x6e, 0xf8, 0xfe, 0x45, 0x9d, 0xdb, 0xe1, 0x13, 0x82, 0xb5, 0xd1, 0xc9, ]; assert_eq!( DebugId::from_guid_age(&guid[..], 1).unwrap(), DebugId::from_str("e8efd198-f86e-45fe-9ddb-e11382b5d1c9-1").unwrap() ) } #[test] fn test_parse_breakpad_zero() { assert_eq!( DebugId::from_breakpad("DFB8E43AF2423D73A453AEB6A777EF750").unwrap(), DebugId::from_parts( Uuid::parse_str("DFB8E43AF2423D73A453AEB6A777EF75").unwrap(), 0, ) ); } #[test] fn test_parse_breakpad_short() { assert_eq!( DebugId::from_breakpad("DFB8E43AF2423D73A453AEB6A777EF75a").unwrap(), DebugId::from_parts( Uuid::parse_str("DFB8E43AF2423D73A453AEB6A777EF75").unwrap(), 10, ) ); } #[test] fn test_parse_breakpad_long() { assert_eq!( DebugId::from_breakpad("DFB8E43AF2423D73A453AEB6A777EF75feedface").unwrap(), DebugId::from_parts( Uuid::parse_str("DFB8E43AF2423D73A453AEB6A777EF75").unwrap(), 0xfeed_face, ) ); } #[test] fn test_parse_breakpad_error_tail() { assert!(DebugId::from_breakpad("DFB8E43AF2423D73A453AEB6A777EF75feedface123").is_err()); } #[test] fn test_parse_breakpad_error_missing_age() { assert!(DebugId::from_breakpad("DFB8E43AF2423D73A453AEB6A777EF75").is_err()); } #[test] fn test_parse_breakpad_error_short() { assert!(DebugId::from_breakpad("DFB8E43AF2423D73A453AEB6A777EF7").is_err()); } #[test] fn test_parse_breakpad_error_dashes() { assert!(DebugId::from_breakpad("e8efd198-f86e-45fe-9ddb-e11382b5d1c9-1").is_err()); } #[test] fn test_to_string_breakpad_zero() { let id = DebugId::from_parts( Uuid::parse_str("DFB8E43AF2423D73A453AEB6A777EF75").unwrap(), 0, ); assert_eq!( id.breakpad().to_string(), "DFB8E43AF2423D73A453AEB6A777EF750" ); } #[test] fn test_to_string_breakpad_short() { let id = DebugId::from_parts( Uuid::parse_str("DFB8E43AF2423D73A453AEB6A777EF75").unwrap(), 10, ); assert_eq!( id.breakpad().to_string(), "DFB8E43AF2423D73A453AEB6A777EF75a" ); } #[test] fn test_to_string_breakpad_long() { let id = DebugId::from_parts( Uuid::parse_str("DFB8E43AF2423D73A453AEB6A777EF75").unwrap(), 0xfeed_face, ); assert_eq!( id.breakpad().to_string(), "DFB8E43AF2423D73A453AEB6A777EF75feedface" ); } #[test] fn test_debug_id_debug() { let id = DebugId::from_parts( Uuid::parse_str("DFB8E43AF2423D73A453AEB6A777EF75").unwrap(), 10, ); assert_eq!( format!("{:?}", id), "DebugId { uuid: \"dfb8e43a-f242-3d73-a453-aeb6a777ef75\", appendix: 10 }" ); } #[test] #[cfg(feature = "with_serde")] fn test_serde_serialize() { let id = DebugId::from_parts( Uuid::parse_str("DFB8E43AF2423D73A453AEB6A777EF75").unwrap(), 10, ); assert_eq!( serde_json::to_string(&id).expect("could not serialize"), "\"dfb8e43a-f242-3d73-a453-aeb6a777ef75-a\"" ) } #[test] #[cfg(feature = "with_serde")] fn test_serde_deserialize() { let id: DebugId = serde_json::from_str("\"dfb8e43a-f242-3d73-a453-aeb6a777ef75-a\"") .expect("could not deserialize"); assert_eq!( id, DebugId::from_parts( Uuid::parse_str("DFB8E43AF2423D73A453AEB6A777EF75").unwrap(), 10, ) ); } #[test] fn test_pdb20() { let timestamp: u32 = 0x418e89c3; let age: u32 = 1; let debug_id = DebugId::from_pdb20(timestamp, age); assert!(debug_id.is_pdb20()); assert_eq!( debug_id.uuid(), Uuid::parse_str("418e89c3-0000-0000-0000-000000000000").unwrap() ); } #[test] fn test_pdb20_format() { let timestamp: u32 = 0x418e89c3; let age: u32 = 1; let debug_id = DebugId::from_pdb20(timestamp, age); assert_eq!(debug_id.to_string(), "418E89C3-1".to_string()); assert_eq!(debug_id.breakpad().to_string(), "418E89C31"); } #[test] fn test_pdb20_parse() { let timestamp: u32 = 0x418e89c3; let age: u32 = 1; let debug_id = DebugId::from_pdb20(timestamp, age); let s = "418E89C3-1"; let parsed = DebugId::from_str(s).unwrap(); assert_eq!(parsed, debug_id); let s = "418E89C31"; let parsed = DebugId::from_str(s).unwrap(); assert_eq!(parsed, debug_id); let s = "418E89C31"; let parsed = DebugId::from_breakpad(s).unwrap(); assert_eq!(parsed, debug_id); let s = "418E89C3-1"; assert!(DebugId::from_breakpad(s).is_err()); } /// The version of `DebugId` up to 0.7.2. #[repr(C, packed)] struct OldDebugId { uuid: Uuid, appendix: u32, _padding: [u8; 12], } #[test] fn test_mem() { // The size of this struct needs to be exactly aligned and can not change for backwards // compatibility. assert_eq!(size_of::<OldDebugId>(), 32); assert_eq!(size_of::<OldDebugId>(), size_of::<DebugId>()); assert_eq!(align_of::<DebugId>(), 1); } #[test] fn test_to_from_raw() { let debug_id = DebugId::from_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75-a").unwrap(); // Create &[u8] from DebugId. let slice = &[debug_id]; let ptr = slice.as_ptr() as *const u8; let len = std::mem::size_of_val(slice); let buf: &[u8] = unsafe { std::slice::from_raw_parts(ptr, len) }; // Copy bytes to new location. let mut new_buf: Vec<u8> = Vec::new(); std::io::copy(&mut std::io::Cursor::new(buf), &mut new_buf).unwrap(); // Create DebugId from &[u8]. let ptr = new_buf.as_ptr() as *const DebugId; let new_debug_id = unsafe { &*ptr }; assert_eq!(*new_debug_id, debug_id); } #[test] fn test_from_old_raw() { // Ensures we can still read previous in-memory representations into the new format. let debug_id = DebugId::from_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75-a").unwrap(); let old_debug_id = OldDebugId { uuid: debug_id.uuid(), appendix: debug_id.appendix(), _padding: [0; 12], }; // Create &[u8] from OldDebugId. let slice = &[old_debug_id]; let ptr = slice.as_ptr() as *const u8; let len = std::mem::size_of_val(slice); let buf: &[u8] = unsafe { std::slice::from_raw_parts(ptr, len) }; // Copy bytes to new location. let mut new_buf: Vec<u8> = Vec::new(); std::io::copy(&mut std::io::Cursor::new(buf), &mut new_buf).unwrap(); // Create DebugId from &[u8]. let ptr = new_buf.as_ptr() as *const DebugId; let new_debug_id = unsafe { &*ptr }; assert_eq!(*new_debug_id, debug_id); } #[test] fn test_default() { let debug_id = DebugId::default(); assert_eq!(debug_id.uuid(), Uuid::nil()); assert_eq!(debug_id.appendix(), 0); }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type ISpiControllerProvider = *mut ::core::ffi::c_void; pub type ISpiDeviceProvider = *mut ::core::ffi::c_void; pub type ISpiProvider = *mut ::core::ffi::c_void; pub type ProviderSpiConnectionSettings = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ProviderSpiMode(pub i32); impl ProviderSpiMode { pub const Mode0: Self = Self(0i32); pub const Mode1: Self = Self(1i32); pub const Mode2: Self = Self(2i32); pub const Mode3: Self = Self(3i32); } impl ::core::marker::Copy for ProviderSpiMode {} impl ::core::clone::Clone for ProviderSpiMode { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ProviderSpiSharingMode(pub i32); impl ProviderSpiSharingMode { pub const Exclusive: Self = Self(0i32); pub const Shared: Self = Self(1i32); } impl ::core::marker::Copy for ProviderSpiSharingMode {} impl ::core::clone::Clone for ProviderSpiSharingMode { fn clone(&self) -> Self { *self } }
//! Provides utility functions to manipulate [chrono](https://github.com/chronotope/chrono/) dates. //! Only [NaiveDate](https://docs.rs/chrono/0.4.11/chrono/naive/struct.NaiveDate.html) is //! supported as of now. Support for naive and timezone aware DateTime coming soon. //! //! The crate provides the following: //! //! **Transition APIs** //! Transition a chrono struct into a future or previous date using standardised methods //! like `start_of_pred_iso8601_week()` which provides the date on which the previous week //! starts. Such functions are provided for week, month and year. extern crate chrono; extern crate time as oldtime; pub mod naive; #[cfg(test)] mod tests { use chrono::NaiveDate; use crate::naive::DateTransitions; #[test] fn test_api_interface() { let d1 = NaiveDate::from_ymd(1996, 2, 23); // Month assert_eq!(d1.end_of_month().unwrap(), NaiveDate::from_ymd(1996, 2, 29)); assert_eq!(d1.start_of_month().unwrap(), NaiveDate::from_ymd(1996, 2, 1)); assert_eq!(d1.end_of_pred_month().unwrap(), NaiveDate::from_ymd(1996, 1, 31)); assert_eq!(d1.start_of_pred_month().unwrap(), NaiveDate::from_ymd(1996, 1, 1)); assert_eq!(d1.end_of_succ_month().unwrap(), NaiveDate::from_ymd(1996, 3, 31)); assert_eq!(d1.start_of_succ_month().unwrap(), NaiveDate::from_ymd(1996, 3, 1)); // Year assert_eq!(d1.end_of_year().unwrap(), NaiveDate::from_ymd(1996, 12, 31)); assert_eq!(d1.start_of_year().unwrap(), NaiveDate::from_ymd(1996, 1, 1)); assert_eq!(d1.end_of_pred_year().unwrap(), NaiveDate::from_ymd(1995, 12, 31)); assert_eq!(d1.start_of_pred_year().unwrap(), NaiveDate::from_ymd(1995, 1, 1)); assert_eq!(d1.end_of_succ_year().unwrap(), NaiveDate::from_ymd(1997, 12, 31)); assert_eq!(d1.start_of_succ_year().unwrap(), NaiveDate::from_ymd(1997, 1, 1)); // ISO 8601 Week assert_eq!(d1.end_of_iso8601_week().unwrap(), NaiveDate::from_ymd(1996, 2, 25)); assert_eq!(d1.start_of_iso8601_week().unwrap(), NaiveDate::from_ymd(1996, 2, 19)); assert_eq!(d1.end_of_pred_iso8601_week().unwrap(), NaiveDate::from_ymd(1996, 2, 18)); assert_eq!(d1.start_of_pred_iso8601_week().unwrap(), NaiveDate::from_ymd(1996, 2, 12)); assert_eq!(d1.end_of_succ_iso8601_week().unwrap(), NaiveDate::from_ymd(1996, 3, 3)); assert_eq!(d1.start_of_succ_iso8601_week().unwrap(), NaiveDate::from_ymd(1996, 2, 26)); // Leap year assert_eq!(d1.is_leap_year(), true); let d2 = NaiveDate::from_ymd(1900, 7, 4); assert_eq!(d2.is_leap_year(), false); } }
use crate::Vertex; use wgpu::util::DeviceExt; #[derive(Debug)] pub struct Mesh { pub vertex_buffer: wgpu::Buffer, pub index_buffer: wgpu::Buffer, pub material: usize, pub num_indices: u32, } impl Mesh { pub fn new(device: &wgpu::Device, mesh: &tobj::Mesh, name: &str) -> Self { let vertices = Vertex::from_tobj(mesh); let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(format!("{} vertex buffer", name).as_str()), contents: bytemuck::cast_slice(&vertices), usage: wgpu::BufferUsage::VERTEX, }); let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(format!("{} index buffer", name).as_str()), contents: bytemuck::cast_slice(&mesh.indices), usage: wgpu::BufferUsage::INDEX, }); let num_indices = mesh.indices.len() as u32; Self { vertex_buffer, index_buffer, material: mesh.material_id.unwrap_or(0), num_indices, } } } #[derive(Debug)] pub struct Model { pub mesh: Mesh, pub name: String, } impl Model { pub fn new(device: &wgpu::Device, model: &tobj::Model) -> Self { let name = model.name.as_str().to_string(); let mesh = Mesh::new(device, &model.mesh, &name.as_str()); Self { mesh, name } } }
use std::fs; use color_eyre::eyre::WrapErr; use color_eyre::Result; use serde::Deserialize; use crate::workflow::Workflow; #[derive(Deserialize, Debug)] pub(crate) struct Config { /// The list of defined workflows that are selectable pub(crate) workflows: Vec<Workflow>, /// Optional configuration for Jira pub(crate) jira: Option<Jira>, /// Optional configuration to talk to GitHub pub(crate) github: Option<GitHub>, } impl Config { /// Create a Config from a TOML file. /// /// ## Errors /// 1. Provided path is not found /// 2. Cannot parse file contents into a Config pub(crate) fn load(path: &str) -> Result<Self> { let contents = fs::read_to_string(path).wrap_err("Could not find config file.")?; toml::from_str(&contents).wrap_err("Failed to parse config file.") } } /// Config required for steps that interact with Jira. #[derive(Debug, Default, Deserialize)] pub(crate) struct Jira { /// The URL to your Atlassian instance running Jira pub(crate) url: String, /// The key of the Jira project to filter on (the prefix of all issues) pub(crate) project: String, } /// Details needed to use steps that interact with GitHub. #[derive(Debug, Default, Deserialize)] pub(crate) struct GitHub { /// The user or organization that owns the `repo`. pub(crate) owner: String, /// The name of the repository in GitHub that this project is utilizing pub(crate) repo: String, }
use super::downcast::downcast_ref; use super::error::RuntimeErr; use super::pine_ref::PineRef; use super::ref_data::RefData; use crate::runtime::Ctx; use std::fmt; use std::hash::{Hash, Hasher}; #[derive(Debug, PartialEq)] pub enum SecondType { Simple, Array, Series, } #[derive(Debug, PartialEq)] pub enum DataType { Float, Int, Bool, Color, String, Line, Label, NA, PineVar, Tuple, Callable, // The callable function defined by the library CallableFactory, Function, // The function defined by the script Object, // Simple callable-object is like callable-object, but don't copy the parameters. SimpleCallableObject, CallableObject, Evaluate, // The variable need lazy evaluate. EvaluateFactory, CallableEvaluate, // variable and object CallableObjectEvaluate, // function + object + variable } #[derive(Debug, PartialEq)] pub enum Category { Simple, Complex, } pub trait PineStaticType { fn static_type() -> (DataType, SecondType); } pub trait PineType<'a> { fn get_type(&self) -> (DataType, SecondType); fn category(&self) -> Category { Category::Simple } fn copy(&self) -> PineRef<'a>; } impl<'a> fmt::Debug for dyn PineType<'a> + 'a { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use super::{Bool, Color, Float, Int, Series, Tuple}; match self.get_type() { (DataType::Int, SecondType::Simple) => downcast_ref::<Int>(self).unwrap().fmt(f), (DataType::Float, SecondType::Simple) => downcast_ref::<Float>(self).unwrap().fmt(f), (DataType::Bool, SecondType::Simple) => downcast_ref::<Bool>(self).unwrap().fmt(f), (DataType::NA, SecondType::Simple) => write!(f, "NA"), (DataType::String, SecondType::Simple) => downcast_ref::<String>(self).unwrap().fmt(f), (DataType::Color, SecondType::Simple) => downcast_ref::<Color>(self).unwrap().fmt(f), (DataType::Int, SecondType::Series) => { downcast_ref::<Series<Int>>(self).unwrap().fmt(f) } (DataType::Float, SecondType::Series) => { downcast_ref::<Series<Float>>(self).unwrap().fmt(f) } (DataType::Bool, SecondType::Series) => { downcast_ref::<Series<Bool>>(self).unwrap().fmt(f) } (DataType::NA, SecondType::Series) => write!(f, "series(NA)"), (DataType::String, SecondType::Series) => { downcast_ref::<Series<String>>(self).unwrap().fmt(f) } (DataType::Color, SecondType::Series) => { downcast_ref::<Series<Color>>(self).unwrap().fmt(f) } (DataType::Tuple, SecondType::Simple) => downcast_ref::<Tuple>(self).unwrap().fmt(f), (DataType::Int, SecondType::Array) => downcast_ref::<Vec<Int>>(self).unwrap().fmt(f), (DataType::Float, SecondType::Array) => { downcast_ref::<Vec<Float>>(self).unwrap().fmt(f) } _ => write!(f, "Unkown type"), } } } impl<'a> PartialEq for dyn PineType<'a> + 'a { fn eq(&self, other: &(dyn PineType<'a> + 'a)) -> bool { use super::{Bool, Color, Float, Int, Series, NA}; match self.get_type() { (DataType::Int, SecondType::Simple) => downcast_ref::<Int>(self) .unwrap() .eq(downcast_ref::<Int>(other).unwrap()), (DataType::Float, SecondType::Simple) => downcast_ref::<Float>(self) .unwrap() .eq(downcast_ref::<Float>(other).unwrap()), (DataType::Bool, SecondType::Simple) => downcast_ref::<Bool>(self) .unwrap() .eq(downcast_ref::<Bool>(other).unwrap()), (DataType::NA, SecondType::Simple) => downcast_ref::<NA>(self) .unwrap() .eq(downcast_ref::<NA>(other).unwrap()), (DataType::String, SecondType::Simple) => downcast_ref::<String>(self) .unwrap() .eq(downcast_ref::<String>(other).unwrap()), (DataType::Color, SecondType::Simple) => downcast_ref::<Color>(self) .unwrap() .eq(downcast_ref::<Color>(other).unwrap()), (DataType::Int, SecondType::Series) => downcast_ref::<Series<Int>>(self) .unwrap() .eq(downcast_ref::<Series<Int>>(other).unwrap()), (DataType::Float, SecondType::Series) => downcast_ref::<Series<Float>>(self) .unwrap() .eq(downcast_ref::<Series<Float>>(other).unwrap()), (DataType::Bool, SecondType::Series) => downcast_ref::<Series<Bool>>(self) .unwrap() .eq(downcast_ref::<Series<Bool>>(other).unwrap()), (DataType::NA, SecondType::Series) => downcast_ref::<Series<NA>>(self) .unwrap() .eq(downcast_ref::<Series<NA>>(other).unwrap()), (DataType::String, SecondType::Series) => downcast_ref::<Series<String>>(self) .unwrap() .eq(downcast_ref::<Series<String>>(other).unwrap()), (DataType::Color, SecondType::Series) => downcast_ref::<Series<Color>>(self) .unwrap() .eq(downcast_ref::<Series<Color>>(other).unwrap()), _ => false, } } } pub trait PineClass<'a> { fn custom_type(&self) -> &str; fn get(&self, context: &mut dyn Ctx<'a>, name: &str) -> Result<PineRef<'a>, RuntimeErr>; fn set(&self, _name: &str, _property: PineRef<'a>) -> Result<(), RuntimeErr> { Err(RuntimeErr::NotSupportOperator) } fn copy(&self) -> Box<dyn PineClass<'a> + 'a>; } impl<'a> fmt::Debug for dyn PineClass<'a> + 'a { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Pine Class {}", self.custom_type()) } } impl<'a> PartialEq for dyn PineClass<'a> + 'a { fn eq(&self, other: &(dyn PineClass<'a> + 'a)) -> bool { if self.custom_type() == other.custom_type() { true } else { false } } } pub trait PineFrom<'a, D: 'a + PartialEq + fmt::Debug> { // The user force type cast fn explicity_from(t: PineRef<'a>) -> Result<RefData<D>, RuntimeErr> { Self::implicity_from(t) } // Create this type from the source type for auto cast fn implicity_from(_t: PineRef<'a>) -> Result<RefData<D>, RuntimeErr> { unimplemented!() } } pub trait Negative<D> { fn negative(self) -> D; } pub trait Arithmetic { fn add(self, other: Self) -> Self; fn minus(self, other: Self) -> Self; fn mul(self, other: Self) -> Self; fn div(self, other: Self) -> Self; fn rem(self, other: Self) -> Self; } pub trait Comparator { fn gt(self, other: Self) -> bool; fn ge(self, other: Self) -> bool; fn lt(self, other: Self) -> bool; fn le(self, other: Self) -> bool; } pub trait SimpleType {} pub trait ComplexType {}
//! Helper functions // Limit float resolution down to 3 decimal places pub(crate) fn format_floats<T: std::fmt::Display>(floats: Vec<T>) -> Vec<String> { floats.iter() .map(|float| format!("{:.5}", float.to_string())) .collect() } // Convert coords to iiif parameter string pub(crate) fn join_coords<T: ToString>(x: T, y: T, w: T, h: T) -> String { [x, y, w, h].iter() .map(|s| s.to_string()) .collect::<Vec<String>>() .join(",") }
#[derive(Debug, Eq, PartialEq)] enum OpCode { Nop, } impl From<&&str> for OpCode { fn from(s: &&str) -> Self { match *s { "nop" => OpCode::Nop, _ => panic!("uknown string for opcode"), } } } fn string_to_op_pair(input: &str) -> (OpCode, i64) { let string_list = input.split_whitespace().collect::<Vec<&str>>(); ( string_list.first().unwrap().into(), string_list.last().unwrap().parse::<i64>().unwrap(), ) } #[cfg(test)] mod test { use super::*; #[test] fn test_string_to_op_pair() { assert_eq!(string_to_op_pair("nop +0"), (OpCode::Nop, 0)) } }
use std::fs; fn main() { let content = fs::read_to_string("input.txt").expect("Error reading file"); let values: Vec<u32> = content .split(',') .map(|x| x.parse::<u32>().unwrap()) .collect(); match zero_value_of_intcode(&values, 12, 3) { Ok(v) => println!("{}", v), Err(e) => panic!(e), }; let magic_number = 19_690_720; match noun_verb_for(&values, magic_number) { Ok(v) => println!("{}", v), Err(e) => panic!(e), }; } // expensive: clones values fn zero_value_of_intcode(values: &[u32], noun: u32, verb: u32) -> Result<u32, &'static str> { let mut cloned_values = values.to_owned(); cloned_values[1] = noun; cloned_values[2] = verb; intcode(&mut cloned_values)?; Ok(cloned_values[0]) } fn intcode(values: &mut [u32]) -> Result<(), &'static str> { let mut halt = false; let mut base_index = 0; while !halt { halt = op_code_instruction(base_index, values)?; base_index += 4; } Ok(()) } fn op_code_instruction(base_index: usize, values: &mut [u32]) -> Result<bool, &'static str> { let op_code = values[base_index]; match op_code { 1 => { let (op1, op2, position) = intcode_ops(&values, base_index); values[position] = op1 + op2 } 2 => { let (op1, op2, position) = intcode_ops(&values, base_index); values[position] = op1 * op2 } 99 => return Ok(true), _ => return Err("invalid op-code"), } Ok(false) } fn intcode_ops(values: &[u32], base_index: usize) -> (u32, u32, usize) { let position1 = values[base_index + 1] as usize; let position2 = values[base_index + 2] as usize; ( values[position1], values[position2], values[base_index + 3] as usize, ) } fn noun_verb_for(values: &[u32], magic_number: u32) -> Result<u32, &'static str> { for noun in 0..=99 { for verb in 0..=99 { let zero_value = zero_value_of_intcode(values, noun, verb)?; if zero_value == magic_number { return Ok(100 * noun + verb); } } } Err("Failed to find noun & verb combination") } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples_part1() { let test_cases = vec![ (vec![1, 0, 0, 0, 99], vec![2, 0, 0, 0, 99]), (vec![2, 3, 0, 3, 99], vec![2, 3, 0, 6, 99]), (vec![2, 4, 4, 5, 99, 0], vec![2, 4, 4, 5, 99, 9801]), ( vec![1, 1, 1, 4, 99, 5, 6, 0, 99], vec![30, 1, 1, 4, 2, 5, 6, 0, 99], ), ( vec![1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50], vec![3500, 9, 10, 70, 2, 3, 11, 0, 99, 30, 40, 50], ), ]; for test_case in test_cases { let mut input = test_case.0; let want = test_case.1; intcode(&mut input); assert_eq!(input, want) } } }
pub mod menu; use hexacore::grid::Coords; use hexacore::ui::gridview; use ggez::*; use ggez::graphics::*; use ggez::nalgebra::Point2; pub mod mesh { use super::*; use std::borrow::Borrow; pub fn hexagons<C: Coords, T: Borrow<C>>( view: &gridview::State<C>, mesh: &mut MeshBuilder, it: impl Iterator<Item=T>, mode: DrawMode, color: Color, ) -> GameResult<()> { for t in it { if let Some(hex) = view.grid().get(*t.borrow()) { let hex_bounds = view.grid().schema().bounds(hex); if view.viewport().intersects(&hex_bounds) { mesh.polygon(mode, hex.corners(), color)?; } } } Ok(()) } } pub mod image { use super::*; use hexacore::geo::{ Hexagon, Schema, VAlign }; // use nalgebra::Point2; /// Draw an centered image into a hexagon. pub fn draw_into( ctx: &mut Context, img: &Image, hex: &Hexagon, schema: &Schema, origin: Point2<f32> ) -> GameResult<()> { let (img_w, img_h) = (img.width() as f32, img.height() as f32); let img_pos = schema.valign(&hex, img_w, img_h, VAlign::Middle); let img_dest = origin + img_pos.coords; img.draw(ctx, DrawParam::default().dest(img_dest)) } } pub mod text { use super::*; use hexacore::geo::{ Hexagon, Schema, VAlign }; /// Queue a hexagon label for rendering. pub fn queue_label( ctx: &mut Context, schema: &Schema, hex: &Hexagon, label: String, valign: VAlign, color: Color, scale: Scale ) { let txt = Text::new(TextFragment::new(label).scale(scale)); let (w, h) = (txt.width(ctx) as f32, txt.height(ctx) as f32); let pos = schema.valign(hex, w, h, valign); graphics::queue_text(ctx, &txt, pos, Some(color)); } } pub mod animation { use super::*; use std::borrow::Borrow; use ggez::nalgebra::Point2; use hexacore::grid::Grid; pub struct PathIter { edges: Vec<(Point2<f32>, Point2<f32>)>, edge_i: usize, step_dx: f32, step_dy: f32, step_i: usize, steps_per_hex: usize, } impl PathIter { fn new(edges: Vec<(Point2<f32>, Point2<f32>)>, steps_per_hex: usize) -> PathIter { let mut iter = PathIter { edges, steps_per_hex, edge_i: 0, step_i: 0, step_dx: 0.0, step_dy: 0.0, }; iter.calc_dxy(); iter } fn calc_dxy(&mut self) { let (center_a, center_b) = self.edges[self.edge_i]; let dx = center_b.x - center_a.x; let dy = center_b.y - center_a.y; self.step_dx = dx / self.steps_per_hex as f32; self.step_dy = dy / self.steps_per_hex as f32; } } impl Iterator for PathIter { type Item = Point2<f32>; fn next(&mut self) -> Option<Self::Item> { let next_edge_i = self.edge_i + 1; let max_steps = self.steps_per_hex; if self.step_i == max_steps { if next_edge_i >= self.edges.len() { None } else { self.edge_i = next_edge_i; self.step_i = 0; self.calc_dxy(); self.next() } } else { let center_a = self.edges[self.edge_i].0; let i = self.step_i as f32; let next = Point2::new(center_a.x + i * self.step_dx, center_a.y + i * self.step_dy); self.step_i += 1; Some(next) } } } // search::Path::to_pixel ? pub fn path<C, T>(ups: u16, secs: f32, grid: &Grid<C>, path: &[T]) -> PathIter where C: Coords, T: Borrow<C> { let steps_per_hex = (ups as f32 * secs).round() as usize; let edges = path.windows(2).map(|win| { let (c1, c2) = (*win[0].borrow(), *win[1].borrow()); (grid.to_pixel(c1), grid.to_pixel(c2)) }).collect::<Vec<_>>(); PathIter::new(edges, steps_per_hex) } }
extern crate iron; extern crate mount; extern crate time; extern crate rustc_serialize; use std::io::{Read, Write}; use std::sync::RwLock; use std::collections::{HashMap, BTreeMap}; use rustc_serialize::json::{self, Json, ToJson}; use time::precise_time_ns; use iron::status; use iron::headers::{self, ContentType}; use iron::prelude::{ Chain, Iron, IronResult, IronError, Request, Response, Set, }; use iron::typemap::Key; use iron::middleware::{AfterMiddleware, BeforeMiddleware, Handler}; use iron::method::Method; use mount::Mount; macro_rules! unwrap_opt_return_val( ($e:expr, $r:expr) => {{ match $e { Some(v) => v, None => return $r, } }} ); fn service_unavailable() -> IronResult<Response> { let mut response = Response::new(); response.set_mut(status::InternalServerError); response.headers.set(ContentType("text/plain".parse().unwrap())); response.set_mut("Sorry, we are down for maintenance!"); Ok(response) } fn json_wrap(key: &str, json: Json) -> Json { let mut doc = BTreeMap::new(); doc.insert(key.to_string(), json); Json::Object(doc) } struct BoardInfo { // e.g. ``prog`` id: String, // e.g. ``Programming`` title: String, } impl BoardInfo { pub fn new(id: &str, title: &str) -> BoardInfo { BoardInfo { id: id.to_string(), title: title.to_string(), } } } #[derive(RustcDecodable, RustcEncodable, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Debug)] struct PostId(pub u64); impl ToJson for PostId { fn to_json(&self) -> Json { Json::U64(self.0) } } struct Thread { id: PostId, posts: Vec<PostId>, } impl Thread { fn new(op: PostId) -> Thread { Thread { id: op, posts: vec![op], } } fn add_post(&mut self, post: &Post) { self.posts.push(post.id); } } #[derive(RustcDecodable)] struct PostReplyRequest { message: String, } #[derive(RustcDecodable)] struct PostNewThreadRequest { message: String, } #[derive(RustcEncodable, Debug)] struct Post { id: PostId, message: String, } impl Post { fn from_reply(id: PostId, request: PostReplyRequest) -> Post { Post { id: id, message: request.message, } } fn from_new_thread(id: PostId, request: PostNewThreadRequest) -> Post { Post { id: id, message: request.message, } } } impl ToJson for Post { fn to_json(&self) -> Json { let mut doc = BTreeMap::new(); doc.insert("id".to_string(), self.id.to_json()); doc.insert("message".to_string(), self.message.to_json()); Json::Object(doc) } } struct Board { min_post_id: PostId, board: BoardInfo, // thread_order: BTreeMap<SteadyTime, PostId>, threads: HashMap<PostId, Thread>, posts: HashMap<PostId, Post>, } enum ReplyError { NoThread, } enum NewThreadError {} impl Board { fn new(board: BoardInfo) -> Board { Board { min_post_id: PostId(0), board: board, threads: HashMap::new(), posts: HashMap::new(), } } fn allocate_post_id(&mut self) -> PostId { self.min_post_id.0 += 1; self.min_post_id } fn post_reply(&mut self, thread_id: PostId, request: PostReplyRequest) -> Result<(), ReplyError> { let new_post = Post::from_reply(self.allocate_post_id(), request); let thread = unwrap_opt_return_val!(self.threads.get_mut(&thread_id), Err(ReplyError::NoThread)); thread.add_post(&new_post); self.posts.insert(new_post.id, new_post); Ok(()) } fn post_new_thread(&mut self, request: PostNewThreadRequest) -> Result<(), NewThreadError> { let new_post = Post::from_new_thread(self.allocate_post_id(), request); self.threads.insert(new_post.id, Thread::new(new_post.id)); self.posts.insert(new_post.id, new_post); Ok(()) } fn threads(&self) -> Json { let mut posts: Vec<Json> = Vec::new(); for thread in self.threads.values() { if let Some(ref op_post) = self.posts.get(&thread.id) { posts.push(op_post.to_json()); } } Json::Array(posts) } fn thread(&self, thread_id: PostId) -> Json { let mut posts: Vec<Json> = Vec::new(); if let Some(ref thread_posts) = self.threads.get(&thread_id).and_then(|th| Some(&th.posts)) { for post in thread_posts.iter() { if let Some(ref post) = self.posts.get(post) { posts.push(post.to_json()); } } } Json::Array(posts) } } // PostReplyRequest // PostNewThreadRequest struct BoardHandler { board: RwLock<Board>, } impl BoardHandler { fn new(board: Board) -> BoardHandler { BoardHandler { board: RwLock::new(board) } } fn handle_get(&self, thread_id: PostId, req: &mut Request) -> IronResult<Response> { let threads_json = match self.board.read() { Ok(read_guard) => json_wrap("posts", read_guard.thread(thread_id)), Err(_) => return service_unavailable(), }; let reader = format!("{}", threads_json.pretty()).into_bytes(); let mut response = Response::new(); response.set_mut(status::Ok); response.headers.set(ContentType("application/json".parse().unwrap())); response.set_mut(reader); Ok(response) } fn handle_collection_get(&self, req: &mut Request) -> IronResult<Response> { let threads_json = match self.board.read() { Ok(read_guard) => json_wrap("threads", read_guard.threads()), Err(_) => return service_unavailable(), }; let reader = format!("{}", threads_json.pretty()).into_bytes(); let mut response = Response::new(); response.set_mut(status::Ok); response.headers.set(ContentType("application/json".parse().unwrap())); response.set_mut(reader); Ok(response) } fn handle_put(&self, thread_id: PostId, req: &mut Request) -> IronResult<Response> { let mut body_buf = String::new(); if let Err(_) = req.body.read_to_string(&mut body_buf) { return service_unavailable(); } let new_thread_request = match json::decode(&body_buf) { Ok(new_thread_request) => new_thread_request, Err(_) => return service_unavailable(), }; let post_result = match self.board.write() { Ok(mut write_guard) => write_guard.post_reply(thread_id, new_thread_request), Err(_) => return service_unavailable(), }; if let Err(_) = post_result { return service_unavailable() } let mut response = Response::new(); response.set_mut(status::Ok); response.headers.set(ContentType("text/plain".parse().unwrap())); response.set_mut("Posted!"); Ok(response) } fn handle_collection_put(&self, req: &mut Request) -> IronResult<Response> { let mut body_buf = String::new(); if let Err(_) = req.body.read_to_string(&mut body_buf) { return service_unavailable(); } let new_thread_request = match json::decode(&body_buf) { Ok(new_thread_request) => new_thread_request, Err(_) => return service_unavailable(), }; let post_result = match self.board.write() { Ok(mut write_guard) => write_guard.post_new_thread(new_thread_request), Err(_) => return service_unavailable(), }; if let Err(_) = post_result { return service_unavailable() } let mut response = Response::new(); response.set_mut(status::Ok); response.headers.set(ContentType("text/plain".parse().unwrap())); response.set_mut("Posted!"); Ok(response) } } impl Handler for BoardHandler { fn handle(&self, req: &mut Request) -> IronResult<Response> { let mut thread_id: Option<PostId> = None; if req.url.path.len() > 0 { thread_id = req.url.path[0].parse().ok().and_then(|id| Some(PostId(id))); } match (req.method.clone(), thread_id) { (Method::Get, Some(thread_id)) => self.handle_get(thread_id, req), (Method::Get, None) => self.handle_collection_get(req), (Method::Put, Some(thread_id)) => self.handle_put(thread_id, req), (Method::Put, None) => self.handle_collection_put(req), _ => Ok(Response::with((status::MethodNotAllowed, "Method not allowed"))), } } } struct ResponseTime; impl Key for ResponseTime { type Value = u64; } impl BeforeMiddleware for ResponseTime { fn before(&self, req: &mut Request) -> IronResult<()> { // Set the current time for retrieval later. req.extensions.insert::<ResponseTime>(precise_time_ns()); Ok(()) } fn catch(&self, req: &mut Request, err: IronError) -> IronResult<()> { // On an error just do the same thing. let _ = self.before(req); Err(err) } } impl AfterMiddleware for ResponseTime { fn after(&self, req: &mut Request, res: Response) -> IronResult<Response> { // Get the time we set earlier, compare it to now. let delta = precise_time_ns() - *req.extensions.find::<ResponseTime>().unwrap(); println!("Request took: {} ms", (delta as f64) / 1000000.0); Ok(res) } fn catch(&self, req: &mut Request, err: IronError) -> IronResult<Response> { let delta = precise_time_ns() - *req.extensions.find::<ResponseTime>().unwrap(); // Print something different on errors. println!("Request errored, and took: {} ms", (delta as f64) / 1000000.0); Err(err) } } fn main() { // let prog = Board::new(BoardInfo::new("prog", "Programming")); let mut prog = Mount::new(); prog.mount("prog", BoardHandler::new(Board::new(BoardInfo::new("prog", "Programming")))); let mut root = Mount::new(); root.mount("boards", prog); let mut chain = Chain::new(root); chain.link((ResponseTime, ResponseTime)); Iron::new(chain).http("localhost:3000").unwrap(); }
use Body; use flush::Flush; use futures::{Future, Poll}; use h2::client::Connection; use tokio_connect::Connect; /// Task that performs background tasks for a client. /// /// This is not used directly by a user of this library. pub struct Background<C, S> where C: Connect, S: Body, { task: Task<C, S>, } /// The specific task to execute enum Task<C, S> where C: Connect, S: Body, { Connection(Connection<C::Connected, S::Data>), Flush(Flush<S>), } // ===== impl Background ===== impl<C, S> Background<C, S> where C: Connect, S: Body, { pub(crate) fn connection( connection: Connection<C::Connected, S::Data>) -> Self { let task = Task::Connection(connection); Background { task } } pub(crate) fn flush(flush: Flush<S>) -> Self { let task = Task::Flush(flush); Background { task } } } impl<C, S> Future for Background<C, S> where C: Connect, S: Body, { type Item = (); type Error = (); fn poll(&mut self) -> Poll<Self::Item, Self::Error> { use self::Task::*; match self.task { // TODO: Log error? Connection(ref mut f) => f.poll().map_err(|_| ()), Flush(ref mut f) => f.poll(), } } }