text
stringlengths
8
4.13M
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - FLASH access control register"] pub acr: ACR, _reserved_1_acr_: [u8; 0x0200], } impl RegisterBlock { #[doc = "0x04..0x204 - Cluster BANK%s, containing KEYR?, CR?, SR?, CCR?, PRAR_CUR?, PRAR_PRG?, SCAR_CUR?, SCAR_PRG?, WPSN_CUR?R, WPSN_PRG?R, CRCCR?, CRCSADD?R, CRCEADD?R, ECC_FA?R"] #[inline(always)] pub const fn bank(&self) -> &[BANK; 2] { unsafe { &*(self as *const Self).cast::<u8>().add(4usize).cast() } } #[doc = "0x04..0x104 - Cluster BANK%s, containing KEYR?, CR?, SR?, CCR?, PRAR_CUR?, PRAR_PRG?, SCAR_CUR?, SCAR_PRG?, WPSN_CUR?R, WPSN_PRG?R, CRCCR?, CRCSADD?R, CRCEADD?R, ECC_FA?R"] #[inline(always)] pub fn bank1(&self) -> &BANK { &self.bank()[0] } #[doc = "0x104..0x204 - Cluster BANK%s, containing KEYR?, CR?, SR?, CCR?, PRAR_CUR?, PRAR_PRG?, SCAR_CUR?, SCAR_PRG?, WPSN_CUR?R, WPSN_PRG?R, CRCCR?, CRCSADD?R, CRCEADD?R, ECC_FA?R"] #[inline(always)] pub fn bank2(&self) -> &BANK { &self.bank()[1] } #[doc = "0x08 - FLASH option key register"] #[inline(always)] pub const fn optkeyr(&self) -> &OPTKEYR { unsafe { &*(self as *const Self).cast::<u8>().add(8usize).cast() } } #[doc = "0x18 - FLASH option control register"] #[inline(always)] pub const fn optcr(&self) -> &OPTCR { unsafe { &*(self as *const Self).cast::<u8>().add(24usize).cast() } } #[doc = "0x1c - FLASH option status register"] #[inline(always)] pub const fn optsr_cur(&self) -> &OPTSR_CUR { unsafe { &*(self as *const Self).cast::<u8>().add(28usize).cast() } } #[doc = "0x20 - FLASH option status register"] #[inline(always)] pub const fn optsr_prg(&self) -> &OPTSR_PRG { unsafe { &*(self as *const Self).cast::<u8>().add(32usize).cast() } } #[doc = "0x24 - FLASH option clear control register"] #[inline(always)] pub const fn optccr(&self) -> &OPTCCR { unsafe { &*(self as *const Self).cast::<u8>().add(36usize).cast() } } #[doc = "0x40 - FLASH register boot address for Arm Cortex-M7 core"] #[inline(always)] pub const fn boot7_curr(&self) -> &BOOT7_CURR { unsafe { &*(self as *const Self).cast::<u8>().add(64usize).cast() } } #[doc = "0x44 - FLASH register boot address for Arm Cortex-M7 core"] #[inline(always)] pub const fn boot7_prgr(&self) -> &BOOT7_PRGR { unsafe { &*(self as *const Self).cast::<u8>().add(68usize).cast() } } #[doc = "0x48 - FLASH register boot address for Arm Cortex-M4 core"] #[inline(always)] pub const fn boot4_curr(&self) -> &BOOT4_CURR { unsafe { &*(self as *const Self).cast::<u8>().add(72usize).cast() } } #[doc = "0x4c - FLASH register boot address for Arm Cortex-M4 core"] #[inline(always)] pub const fn boot4_prgr(&self) -> &BOOT4_PRGR { unsafe { &*(self as *const Self).cast::<u8>().add(76usize).cast() } } #[doc = "0x5c - FLASH CRC data register"] #[inline(always)] pub const fn crcdatar(&self) -> &CRCDATAR { unsafe { &*(self as *const Self).cast::<u8>().add(92usize).cast() } } #[doc = "0x100 - FLASH access control register"] #[inline(always)] pub const fn acr_(&self) -> &ACR_ { unsafe { &*(self as *const Self).cast::<u8>().add(256usize).cast() } } #[doc = "0x108 - FLASH option key register"] #[inline(always)] pub const fn optkeyr_(&self) -> &OPTKEYR_ { unsafe { &*(self as *const Self).cast::<u8>().add(264usize).cast() } } #[doc = "0x118 - FLASH option control register"] #[inline(always)] pub const fn optcr_(&self) -> &OPTCR_ { unsafe { &*(self as *const Self).cast::<u8>().add(280usize).cast() } } #[doc = "0x11c - FLASH option status register"] #[inline(always)] pub const fn optsr_cur_(&self) -> &OPTSR_CUR_ { unsafe { &*(self as *const Self).cast::<u8>().add(284usize).cast() } } #[doc = "0x120 - FLASH option status register"] #[inline(always)] pub const fn optsr_prg_(&self) -> &OPTSR_PRG_ { unsafe { &*(self as *const Self).cast::<u8>().add(288usize).cast() } } #[doc = "0x124 - FLASH option clear control register"] #[inline(always)] pub const fn optccr_(&self) -> &OPTCCR_ { unsafe { &*(self as *const Self).cast::<u8>().add(292usize).cast() } } #[doc = "0x140 - FLASH register boot address for Arm Cortex-M7 core"] #[inline(always)] pub const fn boot7_curr_(&self) -> &BOOT7_CURR_ { unsafe { &*(self as *const Self).cast::<u8>().add(320usize).cast() } } #[doc = "0x144 - FLASH register boot address for Arm Cortex-M7 core"] #[inline(always)] pub const fn boot7_prgr_(&self) -> &BOOT7_PRGR_ { unsafe { &*(self as *const Self).cast::<u8>().add(324usize).cast() } } #[doc = "0x148 - FLASH register boot address for Arm Cortex-M4 core"] #[inline(always)] pub const fn boot4_curr_(&self) -> &BOOT4_CURR_ { unsafe { &*(self as *const Self).cast::<u8>().add(328usize).cast() } } #[doc = "0x14c - FLASH register boot address for Arm Cortex-M4 core"] #[inline(always)] pub const fn boot4_prgr_(&self) -> &BOOT4_PRGR_ { unsafe { &*(self as *const Self).cast::<u8>().add(332usize).cast() } } } #[doc = "ACR (rw) register accessor: FLASH access control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`acr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`acr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`acr`] module"] pub type ACR = crate::Reg<acr::ACR_SPEC>; #[doc = "FLASH access control register"] pub mod acr; #[doc = "Cluster BANK%s, containing KEYR?, CR?, SR?, CCR?, PRAR_CUR?, PRAR_PRG?, SCAR_CUR?, SCAR_PRG?, WPSN_CUR?R, WPSN_PRG?R, CRCCR?, CRCSADD?R, CRCEADD?R, ECC_FA?R"] pub use self::bank::BANK; #[doc = r"Cluster"] #[doc = "Cluster BANK%s, containing KEYR?, CR?, SR?, CCR?, PRAR_CUR?, PRAR_PRG?, SCAR_CUR?, SCAR_PRG?, WPSN_CUR?R, WPSN_PRG?R, CRCCR?, CRCSADD?R, CRCEADD?R, ECC_FA?R"] pub mod bank; #[doc = "OPTKEYR (w) register accessor: FLASH option key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`optkeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`optkeyr`] module"] pub type OPTKEYR = crate::Reg<optkeyr::OPTKEYR_SPEC>; #[doc = "FLASH option key register"] pub mod optkeyr; #[doc = "OPTCR (rw) register accessor: FLASH option control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`optcr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`optcr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`optcr`] module"] pub type OPTCR = crate::Reg<optcr::OPTCR_SPEC>; #[doc = "FLASH option control register"] pub mod optcr; #[doc = "OPTSR_CUR (rw) register accessor: FLASH option status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`optsr_cur::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`optsr_cur::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`optsr_cur`] module"] pub type OPTSR_CUR = crate::Reg<optsr_cur::OPTSR_CUR_SPEC>; #[doc = "FLASH option status register"] pub mod optsr_cur; #[doc = "OPTSR_PRG (rw) register accessor: FLASH option status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`optsr_prg::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`optsr_prg::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`optsr_prg`] module"] pub type OPTSR_PRG = crate::Reg<optsr_prg::OPTSR_PRG_SPEC>; #[doc = "FLASH option status register"] pub mod optsr_prg; #[doc = "OPTCCR (rw) register accessor: FLASH option clear control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`optccr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`optccr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`optccr`] module"] pub type OPTCCR = crate::Reg<optccr::OPTCCR_SPEC>; #[doc = "FLASH option clear control register"] pub mod optccr; #[doc = "BOOT7_CURR (rw) register accessor: FLASH register boot address for Arm Cortex-M7 core\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`boot7_curr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`boot7_curr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`boot7_curr`] module"] pub type BOOT7_CURR = crate::Reg<boot7_curr::BOOT7_CURR_SPEC>; #[doc = "FLASH register boot address for Arm Cortex-M7 core"] pub mod boot7_curr; #[doc = "BOOT7_PRGR (rw) register accessor: FLASH register boot address for Arm Cortex-M7 core\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`boot7_prgr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`boot7_prgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`boot7_prgr`] module"] pub type BOOT7_PRGR = crate::Reg<boot7_prgr::BOOT7_PRGR_SPEC>; #[doc = "FLASH register boot address for Arm Cortex-M7 core"] pub mod boot7_prgr; #[doc = "BOOT4_CURR (rw) register accessor: FLASH register boot address for Arm Cortex-M4 core\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`boot4_curr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`boot4_curr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`boot4_curr`] module"] pub type BOOT4_CURR = crate::Reg<boot4_curr::BOOT4_CURR_SPEC>; #[doc = "FLASH register boot address for Arm Cortex-M4 core"] pub mod boot4_curr; #[doc = "BOOT4_PRGR (rw) register accessor: FLASH register boot address for Arm Cortex-M4 core\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`boot4_prgr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`boot4_prgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`boot4_prgr`] module"] pub type BOOT4_PRGR = crate::Reg<boot4_prgr::BOOT4_PRGR_SPEC>; #[doc = "FLASH register boot address for Arm Cortex-M4 core"] pub mod boot4_prgr; #[doc = "CRCDATAR (rw) register accessor: FLASH CRC data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`crcdatar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`crcdatar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`crcdatar`] module"] pub type CRCDATAR = crate::Reg<crcdatar::CRCDATAR_SPEC>; #[doc = "FLASH CRC data register"] pub mod crcdatar; #[doc = "ACR_ (rw) register accessor: FLASH access control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`acr_::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`acr_::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`acr_`] module"] pub type ACR_ = crate::Reg<acr_::ACR__SPEC>; #[doc = "FLASH access control register"] pub mod acr_; #[doc = "OPTKEYR_ (w) register accessor: FLASH option key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`optkeyr_::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`optkeyr_`] module"] pub type OPTKEYR_ = crate::Reg<optkeyr_::OPTKEYR__SPEC>; #[doc = "FLASH option key register"] pub mod optkeyr_; #[doc = "OPTCR_ (rw) register accessor: FLASH option control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`optcr_::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`optcr_::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`optcr_`] module"] pub type OPTCR_ = crate::Reg<optcr_::OPTCR__SPEC>; #[doc = "FLASH option control register"] pub mod optcr_; #[doc = "OPTSR_CUR_ (rw) register accessor: FLASH option status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`optsr_cur_::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`optsr_cur_::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`optsr_cur_`] module"] pub type OPTSR_CUR_ = crate::Reg<optsr_cur_::OPTSR_CUR__SPEC>; #[doc = "FLASH option status register"] pub mod optsr_cur_; #[doc = "OPTSR_PRG_ (rw) register accessor: FLASH option status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`optsr_prg_::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`optsr_prg_::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`optsr_prg_`] module"] pub type OPTSR_PRG_ = crate::Reg<optsr_prg_::OPTSR_PRG__SPEC>; #[doc = "FLASH option status register"] pub mod optsr_prg_; #[doc = "OPTCCR_ (rw) register accessor: FLASH option clear control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`optccr_::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`optccr_::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`optccr_`] module"] pub type OPTCCR_ = crate::Reg<optccr_::OPTCCR__SPEC>; #[doc = "FLASH option clear control register"] pub mod optccr_; #[doc = "BOOT7_CURR_ (rw) register accessor: FLASH register boot address for Arm Cortex-M7 core\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`boot7_curr_::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`boot7_curr_::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`boot7_curr_`] module"] pub type BOOT7_CURR_ = crate::Reg<boot7_curr_::BOOT7_CURR__SPEC>; #[doc = "FLASH register boot address for Arm Cortex-M7 core"] pub mod boot7_curr_; #[doc = "BOOT7_PRGR_ (rw) register accessor: FLASH register boot address for Arm Cortex-M7 core\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`boot7_prgr_::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`boot7_prgr_::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`boot7_prgr_`] module"] pub type BOOT7_PRGR_ = crate::Reg<boot7_prgr_::BOOT7_PRGR__SPEC>; #[doc = "FLASH register boot address for Arm Cortex-M7 core"] pub mod boot7_prgr_; #[doc = "BOOT4_CURR_ (rw) register accessor: FLASH register boot address for Arm Cortex-M4 core\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`boot4_curr_::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`boot4_curr_::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`boot4_curr_`] module"] pub type BOOT4_CURR_ = crate::Reg<boot4_curr_::BOOT4_CURR__SPEC>; #[doc = "FLASH register boot address for Arm Cortex-M4 core"] pub mod boot4_curr_; #[doc = "BOOT4_PRGR_ (rw) register accessor: FLASH register boot address for Arm Cortex-M4 core\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`boot4_prgr_::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`boot4_prgr_::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`boot4_prgr_`] module"] pub type BOOT4_PRGR_ = crate::Reg<boot4_prgr_::BOOT4_PRGR__SPEC>; #[doc = "FLASH register boot address for Arm Cortex-M4 core"] pub mod boot4_prgr_;
pub mod server; pub fn connect() { }
use schemars::JsonSchema; use stainless_ffmpeg::order::{Filter, ParameterValue}; use std::collections::HashMap; use std::convert::TryInto; #[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)] // #[cfg_attr(feature = "python", derive(FromPyObject, IntoPyObject))] pub struct GenericFilter { pub name: String, pub label: Option<String>, pub parameters: HashMap<String, String>, } impl TryInto<Filter> for GenericFilter { type Error = crate::Error; fn try_into(self) -> Result<Filter, Self::Error> { let parameters = self .parameters .iter() .map(|(key, value)| (key.clone(), ParameterValue::String(value.clone()))) .collect(); let name = self.name.clone(); let label = self.label; Ok(Filter { name, label, parameters, inputs: None, outputs: None, }) } }
// the `std::print` macros panic on any IO error. these are non-panicking alternatives macro_rules! println_ignore_io_error { ($($tt:tt)*) => {{ use std::io::Write; let _ = writeln!(std::io::stdout(), $($tt)*); }} } macro_rules! eprintln_ignore_io_error { ($($tt:tt)*) => {{ use std::io::Write; let _ = writeln!(std::io::stderr(), $($tt)*); }} } // catch unintentional uses of `print*` macros with the test suite #[allow(unused_macros)] #[cfg(debug_assertions)] macro_rules! eprintln { ($($tt:tt)*) => { compiler_error!("do not use `eprintln!`; use the `write!` macro instead") }; } #[allow(unused_macros)] #[cfg(debug_assertions)] macro_rules! eprint { ($($tt:tt)*) => { compiler_error!("do not use `eprint!`; use the `write!` macro instead") }; } #[allow(unused_macros)] #[cfg(debug_assertions)] macro_rules! println { ($($tt:tt)*) => { compiler_error!("do not use `println!`; use the `write!` macro instead") }; } #[allow(unused_macros)] #[cfg(debug_assertions)] macro_rules! print { ($($tt:tt)*) => { compiler_error!("do not use `print!`; use the `write!` macro instead") }; }
use super::super::super::failpoints::failpoint; use super::super::commit_log::Commit; use super::super::data::{self, DataWriter}; use super::super::entry::Entry; use super::super::env::SeriesEnv; use super::super::error::Error; use super::super::file_system::{FileKind, OpenMode}; use super::super::Compression; use crate::buffering::BufferingBuilder; use std::ops::DerefMut; use std::sync::{Arc, Mutex, MutexGuard}; pub struct Interior { data_writer: DataWriter, env: Arc<SeriesEnv>, } pub struct Appender<I> where I: DerefMut<Target = Interior>, { inter: I, data_offset: u32, index_offset: u32, highest_ts: i64, } impl<I> Appender<I> where I: DerefMut<Target = Interior>, { fn create(inter: I) -> Result<Appender<I>, Error> { let commit = inter.env.commit_log().current(); Ok(Appender { inter: inter, data_offset: commit.data_offset, index_offset: commit.index_offset, highest_ts: commit.highest_ts, }) } pub fn done(mut self) -> Result<(), Error> { self.inter.data_writer.sync()?; self.inter.env.index().sync()?; self.inter.env.commit_log().commit(Commit { data_offset: self.data_offset, index_offset: self.index_offset, highest_ts: self.highest_ts, }) } fn process_entries<'a, E>(&mut self, entries: E) -> Vec<&'a Entry> where E: IntoIterator<Item = &'a Entry> + 'a, { let mut entries: Vec<&Entry> = entries .into_iter() .filter(|entry| entry.ts >= self.highest_ts) .collect(); entries.sort_by_key(|entry| entry.ts); entries } fn append_block<'a>( &mut self, block: Vec<&'a Entry>, compression: Compression, ) -> Result<(), Error> { let highest_ts = match block.last() { Some(entry) => entry.ts, _ => return Ok(()), }; #[rustfmt::skip] let index_offset = self.inter.env.index().set(self.index_offset, highest_ts, self.data_offset)?; failpoint!( self.inter.env.fp(), "series_writer::index::set", Err(Error::Io(std::io::Error::new( std::io::ErrorKind::WriteZero, "fp" ))) ); #[rustfmt::skip] let data_offset = self.inter.data_writer.write_block(self.data_offset, block, compression)?; failpoint!( self.inter.env.fp(), "series_writer::data_writer::write_block", Err(Error::Io(std::io::Error::new( std::io::ErrorKind::WriteZero, "fp" ))) ); self.data_offset = data_offset; self.index_offset = index_offset; self.highest_ts = highest_ts; Ok(()) } pub fn append<'a, E>(&mut self, entries: E) -> Result<(), Error> where E: IntoIterator<Item = &'a Entry> + 'a, { for block in self .process_entries(entries) .into_iter() .buffering::<Vec<&'a Entry>>(data::MAX_ENTRIES_PER_BLOCK) { self.append_block(block, Compression::Delta)?; } Ok(()) } } impl Interior { fn create(env: Arc<SeriesEnv>) -> Result<Interior, Error> { Ok(Interior { data_writer: DataWriter::create(env.dir().open(FileKind::Data, OpenMode::Write)?)?, env: env, }) } } #[derive(Clone)] pub struct SeriesWriter { writer: Arc<Mutex<Interior>>, } impl SeriesWriter { pub fn create(env: Arc<SeriesEnv>) -> Result<SeriesWriter, Error> { Ok(SeriesWriter { writer: Arc::new(Mutex::new(Interior::create(env)?)), }) } pub fn appender(&self) -> Result<Appender<MutexGuard<'_, Interior>>, Error> { Appender::create(self.writer.lock().unwrap()) } pub fn append<'a, I>(&self, batch: I) -> Result<(), Error> where I: IntoIterator<Item = &'a Entry> + 'a, { let mut appender = self.appender()?; appender.append(batch)?; appender.done() } pub async fn append_async(&self, batch: Vec<Entry>) -> Result<(), Error> { let writer = self.writer.clone(); tokio::task::spawn_blocking(move || { let mut appender = Appender::create(writer.lock().unwrap())?; appender.append(&batch)?; appender.done() }) .await .unwrap() } pub async fn append_with_batch_size_async( &self, size: usize, entries: Vec<Entry>, ) -> Result<(), Error> { let writer = self.writer.clone(); tokio::task::spawn_blocking(move || { let mut appender = Appender::create(writer.lock().unwrap())?; for batch in entries.into_iter().buffering::<Vec<Entry>>(size) { appender.append(&batch)?; } appender.done() }) .await .unwrap() } }
/* 3 [8, 12, 40]; 6 [382253568, 723152896, 37802240, 379425024, 404894720, 471526144] */ fn main() { let n = read(); let mut vec = read_line(); let mut cnt = std::u32::MAX; for i in 0..n as usize { let mut t_cnt = 0; while vec[i] % 2 == 0 && vec[i] != 0 { vec[i] /= 2; t_cnt += 1; } cnt = std::cmp::min(t_cnt, cnt); } println!("{}", cnt); } fn read() -> i32 { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn read_line() -> Vec<i32> { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); let v = s.trim() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect(); return v }
use crate::config::{Named, Project, Test}; use crate::docker::Verification; use crate::io::Logger; use curl::easy::{Handler, WriteError}; use serde::Deserialize; #[derive(Clone, Debug)] pub struct Verifier { pub verification: Verification, logger: Logger, } impl Verifier { pub fn new( project: &Project, test: &Test, test_type: &(&String, &String), logger: &Logger, ) -> Self { let mut logger = logger.clone(); logger.set_log_file("verifications.txt"); Self { logger, verification: Verification { framework_name: project.framework.get_name(), test_name: test.get_name(), type_name: test_type.0.clone(), warnings: vec![], errors: vec![], }, } } } impl Handler for Verifier { fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> { if let Ok(logs) = std::str::from_utf8(&data) { for line in logs.lines() { if !line.trim().is_empty() { if let Ok(warning) = serde_json::from_str::<WarningMessage>(line) { self.verification.warnings.push(warning.warning); } else if let Ok(error) = serde_json::from_str::<ErrorMessage>(line) { self.verification.errors.push(error.error); } else { self.logger.log(line.trim_end()).unwrap(); } } } } Ok(data.len()) } } #[derive(Deserialize, Clone, Debug)] pub struct Warning { pub message: String, pub short_message: String, } #[derive(Deserialize, Clone, Debug)] pub struct Error { pub message: String, pub short_message: String, } #[derive(Deserialize)] struct WarningMessage { warning: Warning, } #[derive(Deserialize)] struct ErrorMessage { error: Error, }
//! wordcountは単語を数える機能を提供します。オプションで文字、行もカウントできます。 //! 詳しくは[`count`]のドキュメント(fm.count.html)を参照してください。 #![warn(missing_docs)] use regex::Regex; use std::collections::HashMap; use std::io::BufRead; /// inputから1行ずつUTF8文字列を読み込み、頻度を数える /// /// 頻度を数える対象はオプションにより制御される /// * [`CountOption::Char`](enum.CountOption.html#variant.Char): Unicodeの1文字ごと /// * [`CountOption::Word`](enum.CountOption.html#variant.Word): 正規表現`\w+`にマッチする単語ごと /// * [`CountOption::Line`](enum.CountOption.html#variant.Line): `\n`または`\r\n`で区切られた行ごと /// /// # Panics /// /// 入力がUTF8でない場合パニックする。 pub fn count(input: impl BufRead, option: CountOption) -> HashMap<String, usize> { let re = Regex::new(r"\w+").unwrap(); let mut freqs = HashMap::new(); // HashMap<キーString,バリューusize>型 for line in input.lines() { let line = line.unwrap(); use crate::CountOption::*; match option { Char => { for c in line.chars() { *freqs.entry(c.to_string()).or_insert(0) += 1; } } Word => { // 4. その行を単語に分割する for m in re.find_iter(&line) { let word = m.as_str().to_string(); // 5. 出現した単語の頻度を数える *freqs.entry(word).or_insert(0) += 1; } } Line => *freqs.entry(line.to_string()).or_insert(0) += 1, } } freqs } // 行や文字もカウントできるようにoptionを追加する /// [`count`](fn.count.html)で使うオプション #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum CountOption { /// 文字ごとの頻度を数える Char, /// 単語ごとの頻度を数える Word, /// 行ごとの頻度を数える Line, } /// オプションのデフォルトは[`Word`](enum.CountOption.html#valiant.Word) impl Default for CountOption { fn default() -> Self { CountOption::Word } } #[test] fn word_count_works() { /// Cursorは内部にバイト列を保持してインメモリバッファを作るデータ型 use std::io::Cursor; let mut exp = HashMap::new(); exp.insert("aa".to_string(), 1); exp.insert("bb".to_string(), 2); exp.insert("cc".to_string(), 1); assert_eq!(count(Cursor::new("aa bb cc bb"), CountOption::Word), exp); } #[test] #[should_panic] fn word_count_do_not_contain_unknown_words() { use std::io::Cursor; count( Cursor::new([ b'a', // a 0xf0, 0x90, 0x80, // でたらめなバイト列 0xe3, 0x81, 0x82, // あ ]), CountOption::Word, ); } #[cfg(tet)] mod test { use super::*; use sdt::io::Cursor; // Mapの複数のkey,valueに対してassertするマクロ macro_rules! assert_map { ($expr: expr ,{$($key:expr=>$value:expr),*}) => { $(assert_eq!($expr[$key],$value));* }; } fn word_count_works_with_macro() { let freqs = count(Cursor::new("aa bb dd"), CountOption::Word); assert_eq!(freqs.len(), 3); assert_map!(freqs,{"aa" => 1,"bb" => 1,"dd"=> 1}); } }
use azure_core::AddAsHeader; use http::request::Builder; use crate::headers::{CONTENT_CRC64, CONTENT_MD5}; #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord)] pub enum Hash { MD5([u8; 16]), CRC64(u64), } impl AddAsHeader for Hash { fn add_as_header(&self, builder: Builder) -> Builder { match self { Hash::MD5(md5) => builder.header(CONTENT_MD5, base64::encode(md5)), Hash::CRC64(crc64) => builder.header(CONTENT_CRC64, &format!("{}", crc64)), } } fn add_as_header2( &self, request: &mut azure_core::Request, ) -> Result<(), azure_core::HTTPHeaderError> { let (header_name, header_value) = match self { Hash::MD5(md5) => (CONTENT_MD5, base64::encode(md5)), Hash::CRC64(crc64) => (CONTENT_CRC64, crc64.to_string()), }; request.headers_mut().append( header_name, http::header::HeaderValue::from_str(&header_value)?, ); Ok(()) } } impl From<md5::Digest> for Hash { fn from(md5: md5::Digest) -> Self { Hash::MD5(md5.0) } }
use lines; use marker; use marker::Marker; use board::Board; pub fn find_current_player(board: &Board) -> Marker { if board.get_spaces().len() % 2 == 0 { Marker::X } else { Marker::O } } pub fn is_game_over(board: &Board) -> bool { is_game_tied(board) || is_game_won(board) } pub fn is_game_tied(board: &Board) -> bool { !is_game_won(board) && board.get_available_spaces().is_empty() } fn is_game_won(board: &Board) -> bool { is_game_won_by(board, &Marker::X) || is_game_won_by(board, &Marker::O) } pub fn is_game_won_by(board: &Board, player: &Marker) -> bool { let winning_scenarios = lines::find_all_lines(board); winning_scenarios .iter() .any(|line| is_line_won_by(line, player)) } fn is_line_won_by(line: &[String], player: &Marker) -> bool { line.iter().all(|space| space == &marker::inspect(player)) } pub fn find_winner(board: &Board) -> Marker { if is_game_won_by(board, &Marker::X) { Marker::X } else if is_game_won_by(board, &Marker::O) { Marker::O } else { Marker::NA } } pub mod tests { #[cfg(test)] use super::*; #[cfg(test)] use board::tests::set_up_board; #[test] fn x_is_current_player_at_start_of_game() { let board: Board = set_up_board(3, vec![]); assert_eq!(Marker::X, find_current_player(&board)); } #[test] fn o_is_current_player_after_one_move() { let board: Board = set_up_board(3, vec![0]); assert_eq!(Marker::O, find_current_player(&board)); } #[test] fn game_not_over_when_board_is_empty() { let board: Board = set_up_board(3, vec![]); assert!(!is_game_over(&board)); } #[test] fn game_is_over_when_board_is_full() { let board: Board = set_up_board(3, vec![0, 4, 8, 2, 6, 7, 1, 3, 5]); assert!(is_game_over(&board)); } #[test] fn check_if_tied_game_is_won() { let board = set_up_board(3, vec![0, 4, 8, 2, 6, 7, 1, 3, 5]); assert!(!is_game_won(&board)); } #[test] fn check_if_game_won_by_x_is_won() { let board = set_up_board(3, vec![0, 4, 8, 2, 6, 3, 7]); assert!(is_game_won(&board)); } #[test] fn check_if_game_won_by_o_is_won() { let board = set_up_board(3, vec![0, 8, 4, 7, 2, 6]); assert!(is_game_won(&board)); } #[test] fn an_empty_game_is_not_won() { let board = set_up_board(3, vec![]); assert!(!is_game_won(&board)); } #[test] fn an_empty_game_is_not_tied() { let board = set_up_board(3, vec![]); assert!(!is_game_tied(&board)); } #[test] fn a_won_game_is_not_tied() { let board = set_up_board(3, vec![0, 8, 4, 7, 2, 6]); assert!(!is_game_tied(&board)); } #[test] fn a_won_game_with_a_full_board_is_not_tied() { let board = set_up_board(3, vec![0, 3, 1, 4, 6, 7, 5, 8, 2]); assert!(!is_game_tied(&board)); } #[test] fn a_tied_game_is_tied() { let board = set_up_board(3, vec![0, 4, 8, 2, 6, 7, 1, 3, 5]); assert!(is_game_tied(&board)); } #[test] fn check_line_won_by_x() { let line: Vec<String> = vec!["X".to_string(), "X".to_string(), "X".to_string()]; assert!(is_line_won_by(&line, &Marker::X)); } #[test] fn check_row_not_won_by_o() { let line: Vec<String> = vec!["O".to_string(), " ".to_string(), "X".to_string()]; assert!(!is_line_won_by(&line, &Marker::O)); } #[test] fn find_winner_when_nobody_has_won() { let board = set_up_board(3, vec![0, 4, 8, 2, 6, 7, 1, 3, 5]); assert_eq!(Marker::NA, find_winner(&board)); } #[test] fn find_winner_when_x_has_won() { let board = set_up_board(3, vec![0, 4, 8, 2, 6, 3, 7]); assert_eq!(Marker::X, find_winner(&board)); } #[test] fn find_winner_when_o_has_won() { let board = set_up_board(3, vec![0, 8, 4, 7, 2, 6]); assert_eq!(Marker::O, find_winner(&board)); } }
use byteorder::{LittleEndian, WriteBytesExt}; use failure::Error; use crate::{chunks::TOKEN_RESOURCE, model::owned::OwnedBuf}; #[derive(Default, Debug)] pub struct ResourcesBuf { resources: Vec<u32>, } impl ResourcesBuf { pub fn push_resource(&mut self, resource: u32) { self.resources.push(resource); } pub fn pop_resource(&mut self) -> Option<u32> { self.resources.pop() } } impl OwnedBuf for ResourcesBuf { fn get_token(&self) -> u16 { TOKEN_RESOURCE } fn get_body_data(&self) -> Result<Vec<u8>, Error> { let mut out = Vec::new(); for r in &self.resources { out.write_u32::<LittleEndian>(*r)?; } Ok(out) } } #[cfg(test)] mod tests { use super::{OwnedBuf, ResourcesBuf}; use crate::{chunks::ResourceWrapper, raw_chunks, test::compare_chunks}; #[test] fn it_can_generate_a_chunk_with_the_given_data() { let mut resources = ResourcesBuf::default(); resources.push_resource(111); resources.push_resource(222); let out = resources.to_vec().unwrap(); let wrapper = ResourceWrapper::new(&out); let expected_resources: Vec<u32> = vec![111, 222]; assert_eq!(expected_resources, wrapper.get_resources().unwrap()); } #[test] fn it_can_generate_an_empty_chunk() { let resources = ResourcesBuf::default(); let out = resources.to_vec().unwrap(); let wrapper = ResourceWrapper::new(&out); let expected_resources: Vec<u32> = vec![]; assert_eq!(expected_resources, wrapper.get_resources().unwrap()); } #[test] fn identity() { let raw = raw_chunks::EXAMPLE_RESOURCES; let wrapper = ResourceWrapper::new(&raw); let owned = wrapper.to_buffer().unwrap(); let new_raw = owned.to_vec().unwrap(); compare_chunks(&raw, &new_raw); } }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use clap::arg_enum; use fidl_fuchsia_net_stack::{self as netstack}; use structopt::StructOpt; // Same as https://docs.rs/log/0.4.8/log/enum.Level.html // but it can't be used for clap parsing here since it is external. arg_enum! { #[derive(PartialEq, Copy, Clone, Debug)] pub enum LogLevelArg { // See syslog/logger.go for numeric definitions. Trace, Debug, Info , Warn, Error, Fatal, } } impl ::std::convert::From<LogLevelArg> for netstack::LogLevelFilter { fn from(arg: LogLevelArg) -> Self { match arg { LogLevelArg::Trace => netstack::LogLevelFilter::Trace, LogLevelArg::Debug => netstack::LogLevelFilter::Debug, LogLevelArg::Info => netstack::LogLevelFilter::Info, LogLevelArg::Warn => netstack::LogLevelFilter::Warn, LogLevelArg::Error => netstack::LogLevelFilter::Error, LogLevelArg::Fatal => netstack::LogLevelFilter::Fatal, } } } #[derive(StructOpt, Debug)] pub enum Opt { #[structopt(name = "if")] /// commands for network interfaces If(IfCmd), #[structopt(name = "fwd")] /// commands for forwarding tables Fwd(FwdCmd), #[structopt(name = "route")] /// commands for routing tables Route(RouteCmd), #[structopt(name = "filter")] /// commands for packet filter Filter(FilterCmd), #[structopt(name = "log")] /// commands for logging Log(LogCmd), } #[derive(StructOpt, Clone, Debug)] pub enum IfCmd { #[structopt(name = "list")] /// lists network interfaces List { /// name substring to be matched name_pattern: Option<String>, }, #[structopt(name = "add")] /// adds a network interface by path Add { #[structopt(raw(required = "true"))] // The path must yield a handle to a fuchsia.hardware.ethernet.Device interface. // Currently this means paths under /dev/class/ethernet. /// path to the device to add path: String, }, #[structopt(name = "del")] /// removes a network interface Del { #[structopt(raw(required = "true"))] /// id of the network interface to remove id: u64, }, #[structopt(name = "get")] /// queries a network interface Get { #[structopt(raw(required = "true"))] /// id of the network interface to query id: u64, }, #[structopt(name = "enable")] /// enables a network interface Enable { #[structopt(raw(required = "true"))] /// id of the network interface to enable id: u64, }, #[structopt(name = "disable")] /// disables a network interface Disable { #[structopt(raw(required = "true"))] /// id of the network interface to disable id: u64, }, #[structopt(name = "addr")] /// commands for updating network interface addresses Addr(AddrCmd), } #[derive(StructOpt, Clone, Debug)] pub enum AddrCmd { #[structopt(name = "add")] /// adds an address to the network interface Add { #[structopt(raw(required = "true"))] /// id of the network interface id: u64, #[structopt(raw(required = "true"))] addr: String, #[structopt(raw(required = "true"))] prefix: u8, }, #[structopt(name = "del")] /// deletes an address from the network interface Del { #[structopt(raw(required = "true"))] /// id of the network interface id: u64, #[structopt(raw(required = "true"))] addr: String, }, } #[derive(StructOpt, Clone, Debug)] pub enum FwdCmd { #[structopt(name = "list")] /// lists forwarding table entries List, #[structopt(name = "add-device")] /// adds a forwarding table entry to route to a device AddDevice { #[structopt(raw(required = "true"))] /// id of the network interface to route to id: u64, #[structopt(raw(required = "true"))] /// address portion of the subnet for this forwarding rule addr: String, #[structopt(raw(required = "true"))] /// routing prefix for this forwarding rule prefix: u8, }, #[structopt(name = "add-hop")] /// adds a forwarding table entry to route to a IP address AddHop { #[structopt(raw(required = "true"))] /// IP address of the next hop to route to next_hop: String, #[structopt(raw(required = "true"))] /// address portion of the subnet for this forwarding rule addr: String, #[structopt(raw(required = "true"))] /// routing prefix for this forwarding rule prefix: u8, }, #[structopt(name = "del")] /// deletes a forwarding table entry Del { #[structopt(raw(required = "true"))] /// address portion of the subnet for this forwarding rule addr: String, #[structopt(raw(required = "true"))] /// routing prefix for this forwarding rule prefix: u8, }, } #[derive(StructOpt, Clone, Debug)] pub enum RouteCmd { #[structopt(name = "list")] List, } #[derive(StructOpt, Clone, Debug)] pub enum FilterCmd { #[structopt(name = "enable")] /// enable the packet filter Enable, #[structopt(name = "disable")] /// disable the packet filter Disable, #[structopt(name = "is_enabled")] /// is the packet filter enabled? IsEnabled, #[structopt(name = "get_rules")] /// get filter rules GetRules, #[structopt(name = "set_rules")] /// set filter rules (see the netfilter::parser library for the rules format) SetRules { rules: String }, #[structopt(name = "get_nat_rules")] /// get nat rules GetNatRules, #[structopt(name = "set_nat_rules")] /// set nat rules (see the netfilter::parser library for the NAT rules format) SetNatRules { rules: String }, #[structopt(name = "get_rdr_rules")] /// get rdr rules GetRdrRules, #[structopt(name = "set_rdr_rules")] /// set rdr rules (see the netfilter::parser library for the RDR rules format) SetRdrRules { rules: String }, } #[derive(StructOpt, Clone, Debug)] pub enum LogCmd { /// Syslog severity level / loglevel #[structopt(name = "set-level")] SetLevel { #[structopt( raw(possible_values = "&LogLevelArg::variants()"), raw(case_insensitive = "true") )] log_level: LogLevelArg, }, }
use crate::model::{Change, Changeable, Revertable, Watcher, SubWatcher, apply_pipe_to_mut_ref}; use std::fmt; #[derive(Clone, PartialEq)] struct ChangeSet<C> { name: String, changes: Vec<C>, } impl<C> ChangeSet<C> { fn new(name: String) -> ChangeSet<C> { ChangeSet { name, changes: vec![], } } } /// Allows undo and redo within a [`Changeable`](trait.Changeable.html) data model. #[derive(Clone, PartialEq)] pub struct History<T: Revertable<C>, C: Change> { pub model: T, undo_stack: Vec<ChangeSet<C>>, redo_stack: Vec<ChangeSet<C>>, } impl<T: Revertable<C> + fmt::Debug, C: Change> fmt::Debug for History<T, C> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "History({}<>{}): ", self.undo_stack.len(), self.redo_stack.len())?; self.model.fmt(f) } } impl<T: Revertable<C>, C: Change> History<T, C> { pub fn new(model: T) -> History<T, C> { History { model, undo_stack: vec![], redo_stack: vec![], } } pub fn can_undo(&self) -> bool { !self.undo_stack.is_empty() } pub fn can_redo(&self) -> bool { !self.redo_stack.is_empty() } } #[derive(Debug, Clone, PartialEq)] pub enum HistorySignal<ST> { /// This signal is for any change that touches the History's model, /// including Push/Undo/Redo, except for Reset, which must be handled /// separately. Change(ST), Reset, /// Signal for when the current transaction changes. CurrentTransaction, Push, Undo, Redo, ClearHistory, } #[derive(Debug, Clone, PartialEq)] pub enum HistoryChange<T: Revertable<C>, C: Change> { Reset(Box<T>), NewTransaction(String), Push(C), Undo, Redo, ClearHistory, //Pop, } impl<T: 'static + Revertable<C> + Send, C: Change> Change for HistoryChange<T, C> { type SignalType = HistorySignal<C::SignalType>; /*fn get_signals(&self) -> Vec<Self::SignalType> { match *self { HistoryChange::Reset(..) => { vec![HistorySignal::Reset] }, HistoryChange::NewTransaction(ref name) => { vec![HistorySignal::CurrentTransaction] }, HistoryChange::Push(ref change) => { change.get_signals().into_iter().map( |signal| HistorySignal::Change(signal) ).chain(Some(HistorySignal::Push).into_iter()).collect() }, HistoryChange::Undo => { vec![HistorySignal::Undo] }, HistoryChange::Redo => { vec![HistorySignal::Redo] }, HistoryChange::ClearHistory => { vec![HistorySignal::ClearHistory] }, } }*/ } impl<T: 'static + Revertable<C> + Send, C: Change> Changeable<HistoryChange<T, C>> for History<T, C> { fn changeable_apply(&mut self, change: HistoryChange<T, C>, watcher: &mut Watcher<HistorySignal<C::SignalType>>) { use self::HistoryChange::*; match change { Reset(newmodel) => { self.model = *newmodel; self.undo_stack.clear(); self.redo_stack.clear(); watcher.send_signal(HistorySignal::Reset); }, NewTransaction(name) => { self.undo_stack.push(ChangeSet::new(name)); self.redo_stack.clear(); watcher.send_signal(HistorySignal::CurrentTransaction); }, Push(subchange) => { let revertchange = { let mut watcher_fn = |signal| { watcher.send_signal(HistorySignal::Change(signal)); }; //self.change_queue.push(subchange.clone()); self.model.revertable_apply(subchange, &mut SubWatcher::new(&mut watcher_fn)) }; self.redo_stack.clear(); if self.undo_stack.is_empty() { // There were no transactions to add to, so just add to a // new, nameless one let mut first_changeset = ChangeSet::new("".into()); first_changeset.changes.push(revertchange); self.undo_stack.push(first_changeset); } else { if let Some(ref mut current) = self.undo_stack.last_mut() { current.changes.push(revertchange); } else { panic!("Should not be reachable"); } } watcher.send_signal(HistorySignal::Push); }, Undo => { if let Some(mut revertchangeset) = self.undo_stack.pop() { { let mut watcher_fn = |signal| { watcher.send_signal(HistorySignal::Change(signal)); }; for revertchange in &mut revertchangeset.changes.iter_mut().rev() { //self.change_queue.push(revertchange.clone()); apply_pipe_to_mut_ref(|change| self.model.revertable_apply(change, &mut SubWatcher::new(&mut watcher_fn)), revertchange); } } self.redo_stack.push(revertchangeset); watcher.send_signal(HistorySignal::Undo); watcher.send_signal(HistorySignal::CurrentTransaction); } }, Redo => { if let Some(mut reapplychangeset) = self.redo_stack.pop() { { let mut watcher_fn = |signal| { watcher.send_signal(HistorySignal::Change(signal)); }; for reapplychange in &mut reapplychangeset.changes.iter_mut() { //self.change_queue.push(reapplychange.clone()); apply_pipe_to_mut_ref(|change| self.model.revertable_apply(change, &mut SubWatcher::new(&mut watcher_fn)), reapplychange); } } self.undo_stack.push(reapplychangeset); watcher.send_signal(HistorySignal::Redo); watcher.send_signal(HistorySignal::CurrentTransaction); } }, ClearHistory => { self.undo_stack.clear(); self.redo_stack.clear(); watcher.send_signal(HistorySignal::ClearHistory); watcher.send_signal(HistorySignal::CurrentTransaction); }, } } fn reset_view_signals(&self) -> Vec<HistorySignal<C::SignalType>> { vec![HistorySignal::Reset, HistorySignal::CurrentTransaction] } } /*#[derive(Clone, Debug)] pub struct Hist<C> { undo_stack: Vec<ChangeSet<C>>, redo_stack: Vec<ChangeSet<C>>, } impl<C> Hist<C> { fn push(&mut self, revertchange: C) { self.redo_stack.clear(); if self.undo_stack.is_empty() { // There were no transactions to add to, so just add to a // new, nameless one let mut first_changeset = ChangeSet::new("".into()); first_changeset.changes.push(revertchange); self.undo_stack.push(first_changeset); } else { if let Some(ref mut current) = self.undo_stack.last_mut() { current.changes.push(revertchange); } else { panic!("Should not be reachable"); } } } fn undo<T: Revertable<C>>(&mut self, cxt: &mut ApplyContext<T, C>) { if let Some(mut revertchangeset) = self.undo_stack.pop() { for revertchange in &mut revertchangeset.changes.iter_mut().rev() { cxt.apply(revertchange); } self.redo_stack.push(revertchangeset); } } fn redo<T: Revertable<C>>(&mut self, cxt: &mut ApplyContext<T, C>) { if let Some(mut reapplychangeset) = self.redo_stack.pop() { for reapplychange in &mut reapplychangeset.changes.iter_mut().rev() { cxt.apply(reapplychange); } self.undo_stack.push(reapplychangeset); } } } #[derive(Clone, Debug)] pub struct ValWithHist<T: Revertable<C>, C> { val: T, hist: Hist<C>, } impl<T: Revertable<C>, C> ValWithHist<T, C> { fn get_hist(&mut self) -> Hist<C> { self.hist } } impl<T: Revertable<C>, C> Revertable<C> for ValWithHist<T, C> { fn revertable_apply(&mut self, change: C) -> C { let revertchange = self.val.revertable_apply(change); self.hist.push(revertchange.clone()); revertchange } }*/
use svm_types::{ReceiptLog, RuntimeError}; #[derive(Debug, PartialEq, Clone)] pub struct Failure { err: RuntimeError, logs: Vec<ReceiptLog>, } impl Failure { pub fn new(err: RuntimeError, logs: Vec<ReceiptLog>) -> Self { Self { err, logs } } pub fn take_logs(&mut self) -> Vec<ReceiptLog> { std::mem::take(&mut self.logs) } pub fn take_error(self) -> RuntimeError { self.err } } impl From<RuntimeError> for Failure { fn from(err: RuntimeError) -> Self { Failure::new(err, Vec::new()) } }
use std::any::Any; use std::any::TypeId; use std::collections::HashMap; pub struct SharedResources { resources: HashMap<TypeId, Box<Any>>, } impl SharedResources { pub fn new() -> SharedResources { SharedResources { resources: HashMap::new(), } } pub fn add<R: 'static>(&mut self, resource: R) { self.resources.insert(TypeId::of::<R>(), Box::new(resource)); } pub fn get<R: 'static>(&mut self) -> Option<&mut R> { self.resources .get_mut(&TypeId::of::<R>()) .map(|resource| resource.downcast_mut::<R>().unwrap()) } }
/// An enum to represent all characters in the IdeographicSymbolsandPunctuation block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum IdeographicSymbolsandPunctuation { /// \u{16fe0}: '𖿠' TangutIterationMark, /// \u{16fe1}: '𖿡' NushuIterationMark, /// \u{16fe2}: '𖿢' OldChineseHookMark, /// \u{16fe3}: '𖿣' OldChineseIterationMark, } impl Into<char> for IdeographicSymbolsandPunctuation { fn into(self) -> char { match self { IdeographicSymbolsandPunctuation::TangutIterationMark => '𖿠', IdeographicSymbolsandPunctuation::NushuIterationMark => '𖿡', IdeographicSymbolsandPunctuation::OldChineseHookMark => '𖿢', IdeographicSymbolsandPunctuation::OldChineseIterationMark => '𖿣', } } } impl std::convert::TryFrom<char> for IdeographicSymbolsandPunctuation { type Error = (); fn try_from(c: char) -> Result<Self, Self::Error> { match c { '𖿠' => Ok(IdeographicSymbolsandPunctuation::TangutIterationMark), '𖿡' => Ok(IdeographicSymbolsandPunctuation::NushuIterationMark), '𖿢' => Ok(IdeographicSymbolsandPunctuation::OldChineseHookMark), '𖿣' => Ok(IdeographicSymbolsandPunctuation::OldChineseIterationMark), _ => Err(()), } } } impl Into<u32> for IdeographicSymbolsandPunctuation { fn into(self) -> u32 { let c: char = self.into(); let hex = c .escape_unicode() .to_string() .replace("\\u{", "") .replace("}", ""); u32::from_str_radix(&hex, 16).unwrap() } } impl std::convert::TryFrom<u32> for IdeographicSymbolsandPunctuation { type Error = (); fn try_from(u: u32) -> Result<Self, Self::Error> { if let Ok(c) = char::try_from(u) { Self::try_from(c) } else { Err(()) } } } impl Iterator for IdeographicSymbolsandPunctuation { type Item = Self; fn next(&mut self) -> Option<Self> { let index: u32 = (*self).into(); use std::convert::TryFrom; Self::try_from(index + 1).ok() } } impl IdeographicSymbolsandPunctuation { /// The character with the lowest index in this unicode block pub fn new() -> Self { IdeographicSymbolsandPunctuation::TangutIterationMark } /// The character's name, in sentence case pub fn name(&self) -> String { let s = std::format!("IdeographicSymbolsandPunctuation{:#?}", self); string_morph::to_sentence_case(&s) } }
use clap::Clap; use euler::*; #[derive(Clap)] #[clap(version = "1.0", author = "Brian McCallister <brianm@skife.org>")] struct Args { #[clap(subcommand)] subcmd: Command, } #[derive(Clap)] enum Command { #[clap(name = "1")] One(p0001::Solution), #[clap(name = "2")] Two(p0002::Solution), #[clap(name = "3")] Three(p0003::Solution), #[clap(name = "4")] Four(p0004::Solution), #[clap(name = "5")] Five(p0005::Solution), #[clap(name = "6")] Six(p0006::Solution), } fn main() { let args: Args = Args::parse(); match args.subcmd { Command::One(sol) => println!("{}", sol.run()), Command::Two(sol) => println!("{}", sol.run()), Command::Three(sol) => println!("{}", sol.run()), Command::Four(sol) => println!("{}", sol.run()), Command::Five(sol) => println!("{}", sol.run()), Command::Six(sol) => println!("{}", sol.run()), } }
use crate::domain::admin::AdminId; #[derive(Debug, Clone)] pub enum Status { Requested, Approved { admin_id: AdminId }, Rejected { admin_id: AdminId }, Cancelled, } impl ToString for Status { fn to_string(&self) -> String { match self { Status::Requested => "requested".to_owned(), Status::Approved { .. } => "approved".to_owned(), Status::Rejected { .. } => "rejected".to_owned(), Status::Cancelled => "cancelled".to_owned(), } } }
//! Reset and Clock Control peripheral //! //! This module contains a partial abstraction over the RCC peripheral, as well as types and traits //! related to the various clocks on the chip. The usual pattern here is to mutate clock settings //! as you wish them to be, freeze the clocks, and then pass references to the `ClockContext` to //! other peripherals that need frequency information. //! //! ``` //! use stm32l0x1_hal; //! //! let d = stm32l0x1_hal::stm32l0x1::Peripherals::take().unwrap(); //! let mut flash = d.FLASH.constrain(); //! let mut pwr = d.POWER.constrain(); //! let mut rcc = d.RCC.constrain(); //! //! { //! let cfgr: &mut stm32l0x1_hal::rcc::CFGR = rcc.cfgr.config().unwrap(); // for convenience o //! //! cfgr.msi.enable(); // enable the MSI clock (it's enabled by default) //! cfgr.msi.set_freq(clocking::MsiFreq::Hz_131_072); // set it to 131 kHz //! cfgr.hsi16.enable(); // turn on the 16 MHz internal RC //! cfgr.hclk_fclk = Hertz(131_072); // the HCLK bus should not be prescaled //! cfgr.pclk1 = Hertz(131_072); // same for the APB1 clock //! cfgr.pclk2 = Hertz(131_072); // and the same for the APB2 clock //! cfgr.sysclk_src = stm32l0x1_hal::rcc::clocking::SysClkSource::MSI; //! // use the MSI to clock the CPU //! } //! //! rcc.freeze(&mut flash, &mut pwr); //! //! let clk_ctx = rcc.cfgr.context().unwrap(); // get a clk_ctx handle to pass around //! ``` use core::mem::replace; use crate::common::Constrain; use crate::flash; use crate::power; use crate::stm32l0x1::{rcc, RCC}; use crate::time::Hertz; pub mod clocking; impl Constrain<Rcc> for RCC { fn constrain(self) -> Rcc { Rcc { ahb: AHB(()), apb1: APB1(()), apb2: APB2(()), iop: IOP(()), ccipr: CCIPR(()), cr: CR(()), csr: CSR(()), icscr: ICSCR(()), cfgr: ClockConfig::Open(CFGR { hclk_fclk: Hertz(2_097_000), pclk1: Hertz(2_097_000), pclk2: Hertz(2_097_000), sysclk_src: clocking::SysClkSource::MSI, lsi: clocking::LowSpeedInternalRC::new(), msi: clocking::MediumSpeedInternalRC::new(true, clocking::MsiFreq::Hz_2_097_000), hsi16: clocking::HighSpeedInternal16RC::new(), //pll: PLL, lse: None, //hse: Option<HighSpeedExternalOSC>, }), } } } /// Returns an already-frozen default `Rcc` config /// /// This config matches the default start-up configuration of the MCU. This is an easy way to elide /// the code space necessary to support more flexible configuration capability. pub fn as_default(_rcc: RCC) -> Rcc { Rcc { ahb: AHB(()), apb1: APB1(()), apb2: APB2(()), iop: IOP(()), ccipr: CCIPR(()), cr: CR(()), csr: CSR(()), icscr: ICSCR(()), cfgr: ClockConfig::Frozen(ClockContext { sysclk: Hertz(2_097_000), /// HCLK/FCLK hclk: Hertz(2_097_000), /// PCLK1 to APB1 peripherals pclk1: Hertz(2_097_000), /// PCLK2 to APB2 peripherals pclk2: Hertz(2_097_000), /// Low-speed internal RC clock speed lsiclk: None, /// Medium-speed internal RC clock speed msiclk: Some(Hertz(2_097_000)), /// High-speed internal 16 MHz clock speed (optionally /4) hsi16clk: None, /// Low-speed external 32kHz clock speed lseclk: None, }), } } /// Struct representing the RCC peripheral pub struct Rcc { /// AMBA High-performance Bus (AHB) registers. pub ahb: AHB, /// APB1 peripheral registers. pub apb1: APB1, /// APB2 peripheral registers. pub apb2: APB2, /// GPIO port configuration pub iop: IOP, /// Peripherals independent clock configuration register pub ccipr: CCIPR, /// Clock control register pub cr: CR, /// Control/status register pub csr: CSR, /// HW clock configuration. pub cfgr: ClockConfig, /// Internal clock sources calibration register pub icscr: ICSCR, } impl Rcc { /// "Freeze" the clock configuration /// /// This is an operation upon which _most_ other operations will depend. This provides a /// `ClockContext` that provides clocking information to other peripherals, and which is used /// to calculate bus timing info. /// /// This function also manipulates the `Flash` and `Power` settings of the chip to achieve the /// requested clock speeds. /// /// Note that this `mem::replace()`s the contents of `self.cfgr`. You cannot change the clock /// configuration after this function is called, and future calls to `rcc.cfgr.config()` will /// return an `Err`. pub fn freeze<VDD, VCORE, RTC>( &mut self, flash: &mut flash::Flash, pwr: &mut power::Power<VDD, VCORE, RTC>, ) where VCORE: power::FreqLimit + flash::Latency + power::Vos, { // Enable the system configuration clock so our changes will take effect. self.apb2.enr().modify(|_, w| w.syscfgen().set_bit()); while !self.apb2.enr().read().syscfgen().bit_is_set() {} // Configure the clock to which we will switch early. We will then do some ancillary tasks // and switch to it before dealing with any other clocks. This assures that we can turn off // the current sysclk source if necessary. let sysclk = match self.cfgr.config().unwrap().sysclk_src { clocking::SysClkSource::MSI => self .cfgr .config() .unwrap() .msi .configure(&mut self.icscr, &mut self.cr), clocking::SysClkSource::HSI16 => self .cfgr .config() .unwrap() .hsi16 .configure(&mut self.icscr, &mut self.cr), //clocking::SysClkSource::HSE => ..= //clocking::SysClkSource::PLLCLK => ..= } .expect("selected SYSCLK source is not enabled!"); let max_f = VCORE::max_freq(); if sysclk > max_f { panic!("sysclk too high for vcore"); } let (hpre_bits, hpre_ratio) = match sysclk.0 / self.cfgr.config().unwrap().hclk_fclk.0 { 0 => unreachable!(), 1 => (0b0000, 1), 2 => (0b1000, 2), 3..=5 => (0b1001, 4), 6..=11 => (0b1010, 8), 12..=39 => (0b1011, 16), 40..=95 => (0b1100, 64), 96..=191 => (0b1101, 128), 192..=383 => (0b1110, 256), _ => (0b1111, 512), }; let hclk = sysclk.0 / hpre_ratio; let (ppre1_bits, ppre1_ratio) = match self.cfgr.config().unwrap().hclk_fclk.0 / self.cfgr.config().unwrap().pclk1.0 { 0 => unreachable!(), 1 => (0b000, 1), 2 => (0b100, 2), 3..=5 => (0b101, 4), 6..=11 => (0b110, 8), _ => (0b111, 16), }; let pclk1 = Hertz(hclk / ppre1_ratio); let (ppre2_bits, ppre2_ratio) = match self.cfgr.config().unwrap().hclk_fclk.0 / self.cfgr.config().unwrap().pclk2.0 { 0 => unreachable!(), 1 => (0b000, 1), 2 => (0b100, 2), 3..=5 => (0b101, 4), 6..=11 => (0b110, 8), _ => (0b111, 16), }; let pclk2 = Hertz(hclk / ppre2_ratio); let hclk = Hertz(hclk); let sw_bits = match self.cfgr.config().unwrap().sysclk_src { clocking::SysClkSource::MSI => 0b00, clocking::SysClkSource::HSI16 => 0b01, //clocking::SysClkSource::HSE => 0b10, //clocking::SysClkSource::PLLCLK => 0b11, }; // Configure the remaining clocks, including possibly turning them off. let lsiclk = self.cfgr.config().unwrap().lsi.configure(&mut self.csr); let msiclk = self .cfgr .config() .unwrap() .msi .configure(&mut self.icscr, &mut self.cr); let hsi16clk = self .cfgr .config() .unwrap() .hsi16 .configure(&mut self.icscr, &mut self.cr); let lseclk = if let Some(lse) = self.cfgr.config().unwrap().lse.as_ref() { lse.configure(&mut self.csr, pwr) } else { None }; // The following is messy and intends to encode ordering relationships between configuring // PWR, FLASH, and RCC. Specifically, the following must hold: // // 3.7.1: FLASH_ACR bit 0, LATENCY: // To increase the clock frequency, the user has to change this bit to ‘1’, then to // increase the frequency. To reduce the clock frequency, the user has to decrease the // frequency, then to change this bit to ‘0’. // // as well as // // 6.1.7: Voltage regulator and clock management when modifying the VCORE range: // • When the voltage range is above the targeted voltage range (e.g. from range 1 to 2): // a) Adapt the clock frequency to the lower voltage range that will be selected at // next step. // b) Select the required voltage range. // • When the voltage range is below the targeted voltage range (e.g. from range 3 to 1): // a) Select the required voltage range. // b) Tune the clock frequency if needed. let curr_flash_latency = flash.get_latency(); match (curr_flash_latency, VCORE::latency(sysclk)) { (flash::FlashLatency::_1_Clk, flash::FlashLatency::_0_Clk) => { // set clock, then lower latency if VCORE::range() > pwr.read_vcore_range() { // we're increasing the power, so set up power before setting the clock unsafe { pwr.enact(&mut self.apb1) }; } self.cfgr.config().unwrap().inner().write(|w| unsafe { w.ppre1() .bits(ppre1_bits) .ppre2() .bits(ppre2_bits) .hpre() .bits(hpre_bits) .sw() .bits(sw_bits) }); if VCORE::range() <= pwr.read_vcore_range() { // lower the power after decreasing the clock unsafe { pwr.enact(&mut self.apb1) }; } flash.set_latency(sysclk, pwr); } (flash::FlashLatency::_0_Clk, flash::FlashLatency::_1_Clk) => { // raise latency, then set clock flash.set_latency(sysclk, pwr); if VCORE::range() > pwr.read_vcore_range() { // increase power before raising the clock unsafe { pwr.enact(&mut self.apb1) }; } self.cfgr.config().unwrap().inner().write(|w| unsafe { w.ppre1() .bits(ppre1_bits) .ppre2() .bits(ppre2_bits) .hpre() .bits(hpre_bits) .sw() .bits(sw_bits) }); if VCORE::range() <= pwr.read_vcore_range() { // lower the power after decreasing the clock unsafe { pwr.enact(&mut self.apb1) }; } } _ => { // no change to latency, so just set clock if VCORE::range() > pwr.read_vcore_range() { // increase power before raising the clock unsafe { pwr.enact(&mut self.apb1) }; } self.cfgr.config().unwrap().inner().write(|w| unsafe { w.ppre1() .bits(ppre1_bits) .ppre2() .bits(ppre2_bits) .hpre() .bits(hpre_bits) .sw() .bits(sw_bits) }); if VCORE::range() <= pwr.read_vcore_range() { // decrease power after lowering the clock unsafe { pwr.enact(&mut self.apb1) }; } } }; self.apb2.enr().modify(|_, w| w.syscfgen().clear_bit()); while !self.apb2.enr().read().syscfgen().bit_is_clear() {} let clk_ctx = ClockContext { sysclk, hclk, pclk1, pclk2, lsiclk, msiclk, hsi16clk, lseclk, }; let _ = replace(&mut self.cfgr, ClockConfig::Frozen(clk_ctx)); } } /// "Frozen" clock context pub struct ClockContext { /// Core system clock sysclk: Hertz, /// HCLK/FCLK hclk: Hertz, /// PCLK1 to APB1 peripherals pclk1: Hertz, /// PCLK2 to APB2 peripherals pclk2: Hertz, /// Low-speed internal RC clock speed lsiclk: Option<Hertz>, /// Medium-speed internal RC clock speed msiclk: Option<Hertz>, /// High-speed internal 16 MHz clock speed (optionally /4) hsi16clk: Option<Hertz>, /// Low-speed external 32kHz clock speed lseclk: Option<Hertz>, } impl ClockContext { /// Returns the frequency of the system clock SYSCLK, also CK_PWR pub fn sysclk(&self) -> Hertz { self.sysclk } /// Returns the frequency of HCLK/FCLK pub fn hclk_fclk(&self) -> Hertz { self.hclk } /// Returns the frequency of APB1 pub fn apb1(&self) -> Hertz { self.pclk1 } /// Returns the frequency of APB2 pub fn apb2(&self) -> Hertz { self.pclk2 } /// Returns the frequency of the low speed internal RC, if turned on pub fn lsi(&self) -> Option<Hertz> { self.lsiclk } /// Returns the frequency of the medium speed internal RC, if turned on pub fn msi(&self) -> Option<Hertz> { self.msiclk } /// Returns the frequency of the high speed 16 MHz internal RC, if turned on pub fn hsi16(&self) -> Option<Hertz> { self.hsi16clk } /// Returns the frequency of the low speed external oscillator, if enabled pub fn lse(&self) -> Option<Hertz> { self.lseclk } } /// AHB 1-3 register access pub struct AHB(()); impl AHB { /// Access AHB reset register pub fn rstr(&mut self) -> &rcc::AHBRSTR { unsafe { &(*RCC::ptr()).ahbrstr } } /// Access AHB clock enable register pub fn enr(&mut self) -> &rcc::AHBENR { unsafe { &(*RCC::ptr()).ahbenr } } /// Access AHB enable clock in sleep mode register pub fn smenr(&mut self) -> &rcc::AHBSMENR { unsafe { &(*RCC::ptr()).ahbsmenr } } } /// APB1 register access pub struct APB1(()); impl APB1 { /// Access APB1RSTR1 reset register pub fn rstr(&mut self) -> &rcc::APB1RSTR { unsafe { &(*RCC::ptr()).apb1rstr } } /// Access APB1ENR reset register pub fn enr(&mut self) -> &rcc::APB1ENR { unsafe { &(*RCC::ptr()).apb1enr } } } /// APB2 register access pub struct APB2(()); impl APB2 { /// Access APB2RSTR reset register pub fn rstr(&mut self) -> &rcc::APB2RSTR { unsafe { &(*RCC::ptr()).apb2rstr } } /// Access APB2ENR reset register pub fn enr(&mut self) -> &rcc::APB2ENR { unsafe { &(*RCC::ptr()).apb2enr } } } /// I/O port register access pub struct IOP(()); impl IOP { /// Access IOPENR enable register pub fn enr(&mut self) -> &rcc::IOPENR { unsafe { &(*RCC::ptr()).iopenr } } /// Access IOPRSTR reset register pub fn rstr(&mut self) -> &rcc::IOPRSTR { unsafe { &(*RCC::ptr()).ioprstr } } /// Access IOPSMENR sleep mode register pub fn smenr(&mut self) -> &rcc::IOPSMEN { unsafe { &(*RCC::ptr()).iopsmen } } } /// Clock configuration register pub struct CCIPR(()); impl CCIPR { /// Direct access to RCC_CCIPR #[inline] pub fn inner(&mut self) -> &rcc::CCIPR { unsafe { &(*RCC::ptr()).ccipr } } } /// Clock control register pub struct CR(()); impl CR { /// Direct access to RCC_CR #[inline] pub fn inner(&mut self) -> &rcc::CR { unsafe { &(*RCC::ptr()).cr } } } /// Control/status register pub struct CSR(()); impl CSR { /// Direct access to RCC_CSR #[inline] pub fn inner(&mut self) -> &rcc::CSR { unsafe { &(*RCC::ptr()).csr } } } /// MCU clock configuration - either a configurable register or a "frozen" context pub enum ClockConfig { /// Access to configure the clocks Open(CFGR), /// Frozen clock context that cannot be changed Frozen(ClockContext), } #[derive(Debug)] /// Possible errors raised when trying to access the RCC clock configuration pub enum CfgErr { /// The clock configuration is not frozen Configurable, /// The clock configuration cannot be configured Frozen, } impl ClockConfig { /// Retrieve the configurable clock settings, if not yet frozen pub fn config(&mut self) -> Result<&mut CFGR, CfgErr> { match self { ClockConfig::Open(cfgr) => Ok(cfgr), _ => Err(CfgErr::Frozen), } } /// Retrieve the frozen clock settings, if frozen pub fn context(&self) -> Result<&ClockContext, CfgErr> { match self { ClockConfig::Frozen(ctx) => Ok(ctx), _ => Err(CfgErr::Configurable), } } } /// Clock configuration register pub struct CFGR { /// Desired HCLK/FCLK frequency pub hclk_fclk: Hertz, /// Desired peripheral clock 1 frequency pub pclk1: Hertz, /// Desired peripheral clock 2 frequency pub pclk2: Hertz, /// SYSCLK source selection pub sysclk_src: clocking::SysClkSource, /// Low-speed internal RC configuration pub lsi: clocking::LowSpeedInternalRC, /// Medium-speed internal RC configuration pub msi: clocking::MediumSpeedInternalRC, /// High-speed 16 MHz internal RC configuration pub hsi16: clocking::HighSpeedInternal16RC, /// Low-speed external oscillator configuration pub lse: Option<clocking::LowSpeedExternalOSC>, //pub pll: clocking::PLL, //pub hse: Option<clocking::HighSpeedExternalOSC>, } /// Clock configuration register impl CFGR { /// Direct access to RCC_CFGR #[inline] pub(crate) fn inner(&mut self) -> &rcc::CFGR { unsafe { &(*RCC::ptr()).cfgr } } } /// Internal clock sources calibration register pub struct ICSCR(()); impl ICSCR { /// Direct access to RCC_ICSCR #[inline] pub fn inner(&mut self) -> &rcc::ICSCR { unsafe { &(*RCC::ptr()).icscr } } }
use hasami_shogi_engine::ShogiGame; use hasami_shogi_engine::Cell; // 0 2 0 // 0 1 0 // 0 0 2 #[test] fn it_makes_the_best_move_as_cpu() { let board_state = vec![0, 2, 0, 0, 1, 0, 0, 0, 2]; let mut sg = ShogiGame::import(3,3, board_state); sg.computer_move(1); assert_eq!(sg.cell(7), Cell::Player2); } #[test] fn it_makes_the_best_move_as_cpu_2() { let board_state = vec![2, 2, 0, 0, 2, 1, 1, 0, 2]; let mut sg = ShogiGame::import(3,3, board_state); sg.computer_move(1); assert_eq!(Cell::Player2, Cell::Player2); }
use crate::lexer::Lexer; use crate::lexer::LexerError; use crate::lexer::Loc; use crate::lexer::ParserLanguage; use crate::lexer::StrLit; use crate::lexer::StrLitDecodeError; use crate::lexer::Token; use crate::lexer::TokenWithLocation; use std::fmt; #[derive(Debug)] pub enum TokenizerError { LexerError(LexerError), StrLitDecodeError(StrLitDecodeError), InternalError, IncorrectInput, // TODO: too broad UnexpectedEof, ExpectStrLit, ExpectIntLit, ExpectFloatLit, ExpectIdent, ExpectNamedIdent(String), ExpectChar(char), ExpectAnyChar(Vec<char>), } impl fmt::Display for TokenizerError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { TokenizerError::LexerError(e) => write!(f, "{}", e), TokenizerError::StrLitDecodeError(e) => write!(f, "{}", e), TokenizerError::InternalError => write!(f, "Internal tokenizer error"), TokenizerError::IncorrectInput => write!(f, "Incorrect input"), TokenizerError::UnexpectedEof => write!(f, "Unexpected EOF"), TokenizerError::ExpectStrLit => write!(f, "Expecting string literal"), TokenizerError::ExpectIntLit => write!(f, "Expecting int literal"), TokenizerError::ExpectFloatLit => write!(f, "Expecting float literal"), TokenizerError::ExpectIdent => write!(f, "Expecting identifier"), TokenizerError::ExpectNamedIdent(n) => write!(f, "Expecting identifier {}", n), TokenizerError::ExpectChar(c) => write!(f, "Expecting char {}", c), TokenizerError::ExpectAnyChar(c) => write!( f, "Expecting one of: {}", c.iter() .map(|c| format!("{}", c)) .collect::<Vec<String>>() .join(", ") ), } } } impl std::error::Error for TokenizerError {} pub type TokenizerResult<R> = Result<R, TokenizerError>; impl From<LexerError> for TokenizerError { fn from(e: LexerError) -> Self { TokenizerError::LexerError(e) } } impl From<StrLitDecodeError> for TokenizerError { fn from(e: StrLitDecodeError) -> Self { TokenizerError::StrLitDecodeError(e) } } #[derive(Clone)] pub struct Tokenizer<'a> { lexer: Lexer<'a>, next_token: Option<TokenWithLocation>, last_token_loc: Option<Loc>, } #[allow(dead_code)] impl<'a> Tokenizer<'a> { pub fn new(input: &'a str, comment_style: ParserLanguage) -> Tokenizer<'a> { Tokenizer { lexer: Lexer::new(input, comment_style), next_token: None, last_token_loc: None, } } pub fn loc(&self) -> Loc { // After lookahead return the location of the next token self.next_token .as_ref() .map(|t| t.loc) // After token consumed return the location of that token .or(self.last_token_loc) // Otherwise return the position of lexer .unwrap_or(self.lexer.loc) } pub fn lookahead_loc(&mut self) -> Loc { drop(self.lookahead()); // TODO: does not handle EOF properly self.loc() } fn lookahead(&mut self) -> TokenizerResult<Option<&Token>> { Ok(match self.next_token { Some(ref token) => Some(&token.token), None => { self.next_token = self.lexer.next_token()?; self.last_token_loc = self.next_token.as_ref().map(|t| t.loc); match self.next_token { Some(ref token) => Some(&token.token), None => None, } } }) } pub fn lookahead_some(&mut self) -> TokenizerResult<&Token> { match self.lookahead()? { Some(token) => Ok(token), None => Err(TokenizerError::UnexpectedEof), } } /// Can be called only after lookahead, otherwise it's error pub fn advance(&mut self) -> TokenizerResult<Token> { self.next_token .take() .map(|TokenWithLocation { token, .. }| token) .ok_or(TokenizerError::InternalError) } /// No more tokens pub fn syntax_eof(&mut self) -> TokenizerResult<bool> { Ok(self.lookahead()?.is_none()) } pub fn next_token_if_map<P, R>(&mut self, p: P) -> TokenizerResult<Option<R>> where P: FnOnce(&Token) -> Option<R>, { self.lookahead()?; let v = match self.next_token { Some(ref token) => match p(&token.token) { Some(v) => v, None => return Ok(None), }, _ => return Ok(None), }; self.next_token = None; Ok(Some(v)) } pub fn next_token_check_map<P, R, E>(&mut self, p: P) -> Result<R, E> where P: FnOnce(&Token) -> Result<R, E>, E: From<TokenizerError>, { self.lookahead()?; let r = match self.next_token { Some(ref token) => p(&token.token)?, None => return Err(TokenizerError::UnexpectedEof.into()), }; self.next_token = None; Ok(r) } fn next_token_if<P>(&mut self, p: P) -> TokenizerResult<Option<Token>> where P: FnOnce(&Token) -> bool, { self.next_token_if_map(|token| if p(token) { Some(token.clone()) } else { None }) } pub fn next_ident_if_in(&mut self, idents: &[&str]) -> TokenizerResult<Option<String>> { let v = match self.lookahead()? { Some(&Token::Ident(ref next)) => { if idents.iter().any(|&i| i == next) { next.clone() } else { return Ok(None); } } _ => return Ok(None), }; self.advance()?; Ok(Some(v)) } pub fn next_ident_if_eq(&mut self, word: &str) -> TokenizerResult<bool> { Ok(self.next_ident_if_in(&[word])? != None) } pub fn next_ident_expect_eq(&mut self, word: &str) -> TokenizerResult<()> { if self.next_ident_if_eq(word)? { Ok(()) } else { Err(TokenizerError::ExpectNamedIdent(word.to_owned())) } } pub fn next_ident_if_eq_error(&mut self, word: &str) -> TokenizerResult<()> { if self.clone().next_ident_if_eq(word)? { return Err(TokenizerError::IncorrectInput); } Ok(()) } pub fn next_symbol_if_eq(&mut self, symbol: char) -> TokenizerResult<bool> { Ok(self.next_token_if(|token| matches!(token, &Token::Symbol(c) if c == symbol))? != None) } pub fn next_symbol_expect_eq(&mut self, symbol: char) -> TokenizerResult<()> { if self.lookahead_is_symbol(symbol)? { self.advance()?; Ok(()) } else { Err(TokenizerError::ExpectChar(symbol)) } } pub fn lookahead_if_symbol(&mut self) -> TokenizerResult<Option<char>> { Ok(match self.lookahead()? { Some(&Token::Symbol(c)) => Some(c), _ => None, }) } pub fn lookahead_is_symbol(&mut self, symbol: char) -> TokenizerResult<bool> { Ok(self.lookahead_if_symbol()? == Some(symbol)) } pub fn lookahead_is_ident(&mut self, ident: &str) -> TokenizerResult<bool> { Ok(match self.lookahead()? { Some(Token::Ident(i)) => i == ident, _ => false, }) } pub fn next_ident(&mut self) -> TokenizerResult<String> { self.next_token_check_map(|token| match *token { Token::Ident(ref ident) => Ok(ident.clone()), _ => Err(TokenizerError::ExpectIdent), }) } pub fn next_str_lit(&mut self) -> TokenizerResult<StrLit> { self.next_token_check_map(|token| match *token { Token::StrLit(ref str_lit) => Ok(str_lit.clone()), _ => Err(TokenizerError::ExpectStrLit), }) } } #[cfg(test)] mod test { use super::*; fn tokenize<P, R>(input: &str, what: P) -> R where P: FnOnce(&mut Tokenizer) -> TokenizerResult<R>, { let mut tokenizer = Tokenizer::new(input, ParserLanguage::Proto); let r = what(&mut tokenizer).expect(&format!("parse failed at {}", tokenizer.loc())); let eof = tokenizer .syntax_eof() .expect(&format!("check eof failed at {}", tokenizer.loc())); assert!(eof, "{}", tokenizer.loc()); r } #[test] fn test_ident() { let msg = r#" aabb_c "#; let mess = tokenize(msg, |p| p.next_ident().map(|s| s.to_owned())); assert_eq!("aabb_c", mess); } #[test] fn test_str_lit() { let msg = r#" "a\nb" "#; let mess = tokenize(msg, |p| p.next_str_lit()); assert_eq!( StrLit { escaped: r#"a\nb"#.to_owned() }, mess ); } }
#![feature(box_syntax, box_patterns, or_patterns)] #![allow(dead_code)] pub mod ast; pub mod lexer; pub mod parser; mod tests; use crate::{ ast::{Expression, FloatSize, IntSize, PrimitiveType, TypeKind, AST}, lexer::{ token, token::{Keyword, Symbol, Type}, }, parser::{ParseError, ParseResult, Parser}, }; use ast::FunctionType; use std::path::PathBuf; impl Parser { fn parse_type(&mut self) -> ParseResult<PrimitiveType> { let token = self.next(); if let Some(tok) = token { match tok.sym() { Some(Symbol::Colon) => Some(PrimitiveType::Symbol(ident!(res self)?)), Some(Symbol::Unit) => Some(PrimitiveType::Unit), Some(Symbol::GoDot) => Some(PrimitiveType::Varargs), Some(Symbol::Ampersand) => capture!(res parse_type, self) .ok() .and_then(|ty| Some(PrimitiveType::Ref(box ty))), Some(Symbol::At) => capture!(res parse_type, self) .ok() .and_then(|ty| Some(PrimitiveType::Box(box ty))), Some(Symbol::LBracket) => capture!(res parse_type, self).ok().and_then(|ty| { let len = if sym!(bool Comma, self) { self.peek().and_then(|tok| tok.int()).map(|len| len as u32) } else { None }; if len.is_some() { self.next(); } sym!(RBracket, self); Some(match len { None => PrimitiveType::Slice { ty: box ty }, Some(len) => PrimitiveType::Array { ty: box ty, len }, }) }), _ => None, } .or_else(|| match tok.kw() { Some(Keyword::Bool) => Some(PrimitiveType::Bool), _ => None, }) .or_else(|| match tok.ident() { Some(tyref) => { if matches!(self.peek_symbol(Symbol::LBracket), Some(true)) { self.next(); let types = self .parse_type_list() .expect(format!("Expected type list at {}", tyref).as_str()); sym!(RBracket, self); Some(PrimitiveType::GenericTypeRef(tyref, types)) } else { Some(PrimitiveType::TypeRef(tyref)) } } None => None, }) .or_else(|| match tok.ty() { Some(Type::Str) => Some(PrimitiveType::Str), Some(Type::Char) => Some(PrimitiveType::Char), Some(Type::I8) => Some(PrimitiveType::Int(IntSize::Bits8)), Some(Type::I16) => Some(PrimitiveType::Int(IntSize::Bits16)), Some(Type::I32) => Some(PrimitiveType::Int(IntSize::Bits32)), Some(Type::I64) => Some(PrimitiveType::Int(IntSize::Bits64)), Some(Type::U8) => Some(PrimitiveType::UInt(IntSize::Bits8)), Some(Type::U16) => Some(PrimitiveType::UInt(IntSize::Bits16)), Some(Type::U32) => Some(PrimitiveType::UInt(IntSize::Bits32)), Some(Type::U64) => Some(PrimitiveType::UInt(IntSize::Bits64)), Some(Type::F32) => Some(PrimitiveType::Float(FloatSize::Bits32)), Some(Type::F64) => Some(PrimitiveType::Float(FloatSize::Bits64)), _ => None, }) } else { None } .and_then(|ty| { let mut ty = ty; while sym!(bool Star, self) { ty = PrimitiveType::Pointer(box ty); } Some(ty) }) .ok_or(ParseError::ExpectedType) } fn parse_named_type(&mut self) -> ParseResult<PrimitiveType> { let name = ident!(required self); if sym!(bool Comma, self) | sym!(bool Arrow, self) | sym!(bool LBracket, self) | sym!(bool RBracket, self) { return Err(ParseError::Continue); }; let ty = if sym!(bool Colon, self) { Some(box capture!(res parse_type, self)?) } else { None }; Ok(PrimitiveType::NamedType { name, ty }) } fn parse_attribute(&mut self) -> Option<String> { sym!(At, self); ident!(self) } fn parse_use(&mut self) -> ParseResult<AST> { kw!(Use, self); if let Some(path) = self.peek_str() { self.next(); let pb = PathBuf::from(path); Ok(AST::Import( pb.to_str().expect("ICE parse_use pb.to_str").to_string(), )) } else { Err(ParseError::ExpectedPath) } } fn parse_type_list(&mut self) -> ParseResult<Vec<PrimitiveType>> { let mut params = vec![]; loop { params.push( capture!(res parse_named_type, self) .or_else(|_| capture!(res parse_type, self)) .or(Err(ParseError::ExpectedType))?, ); if !sym!(bool Comma, self) { break; } } Ok(params) } fn parse_free_type_list(&mut self) -> ParseResult<Vec<PrimitiveType>> { let mut params = vec![]; loop { params.push(capture!(res parse_type, self).or(Err(ParseError::ExpectedType))?); if !sym!(bool Comma, self) { break; } } Ok(params) } fn parse_type_names(&mut self) -> ParseResult<Vec<String>> { let mut params = vec![]; loop { params.push(ident!(res self)?); if !sym!(bool Comma, self) { break; } } Ok(params) } fn parse_record(&mut self) -> ParseResult<AST> { kw!(Record, self); let name = ident!(required self); let type_names = if sym!(bool LBracket, self) { let type_names = self.parse_type_names()?; sym!(required RBracket, self); Some(type_names) } else { None }; let fields = if sym!(bool Unit, self) { vec![PrimitiveType::Unit] } else { sym!(required LParen, self); let fields = self .parse_type_list() .expect(format!("Expected type list at {}", name).as_str()); sym!(required RParen, self); fields }; Ok(AST::Record(name, type_names, fields)) } fn parse_const_global(&mut self) -> ParseResult<AST> { let export = kw!(bool Exp, self); let cons = kw!(bool Const, self); let glob = kw!(bool Global, self); if !cons && !glob { return Err(ParseError::Continue); } let ty = capture!(res parse_named_type, self)?; sym!(required Assign, self); let value = box capture!(self, parse_expression).ok_or(ParseError::ExpectedExpression)?; Ok(if cons { AST::Constant { ty, value, export } } else { AST::Global { ty, value, export } }) } fn parse_typedef(&mut self) -> ParseResult<AST> { kw!(Type, self); let name = ident!(res self)?; let type_names = if sym!(bool LBracket, self) { let type_names = self.parse_type_names()?; sym!(required RBracket, self); Some(type_names) } else { None }; let variants = if sym!(bool Assign, self) { let ty = capture!(res parse_type, self)?; let vars = self.parse_free_type_list().ok(); Some(if sym!(bool Pipe, self) { let mut variants = vec![]; if let PrimitiveType::TypeRef(name) = ty { self.variants.push(name.clone()); variants.push(TypeKind::Variant(name, vars)); } else { variants.push(TypeKind::Newtype(ty)); } loop { if let Ok(name) = ident!(res self) { self.variants.push(name.clone()); variants.push(TypeKind::Variant(name, self.parse_free_type_list().ok())); } else { variants.push(TypeKind::Newtype(capture!(res parse_type, self)?)); } if !sym!(bool Pipe, self) { break; } } variants } else { if vars.is_some() { if let PrimitiveType::TypeRef(name) = ty { vec![TypeKind::Variant(name, vars)] } else { return Err(ParseError::ExpectedIdent); } } else { vec![TypeKind::Newtype(ty)] } }) } else { None }; Ok(AST::Typedef { name, type_names, variants, }) } fn parse_function(&mut self) -> ParseResult<AST> { let mut attributes = vec![]; loop { match capture!(self, parse_attribute) { None => break, Some(attr) => attributes.push(attr), } } let export = kw!(bool Exp, self); let ext = kw!(bool Extern, self); kw!(Fn, self); let name = ident!(required self); let type_names = if sym!(bool LBracket, self) { let type_names = self.parse_type_names()?; sym!(required RBracket, self); type_names } else { vec![] }; let params = self .parse_type_list() .expect(format!("Expected type list at {}", name).as_str()); let ret_ty = box if sym!(bool Arrow, self) { capture!(res parse_type, self)? } else { PrimitiveType::Unit }; let mut body = None; if sym!(bool Assign, self) { body = capture!(box parse_expression, err ExpectedExpression, self); } Ok(AST::Expr(Expression::Function { name, attributes, body, type_names, export, ty: FunctionType { ext, ret_ty, params, }, })) } }
use rand::prelude::*; struct Solution { nums: Vec<i32>, rng: ThreadRng, } impl Solution { fn new(nums: Vec<i32>) -> Self { Self { nums, rng: thread_rng(), } } /** Resets the array to its original configuration and return it. */ fn reset(&self) -> Vec<i32> { self.nums.clone() } /** Returns a random shuffling of the array. */ fn shuffle(&mut self) -> Vec<i32> { let mut s = self.nums.clone(); for i in 0..s.len() { let j = self.rng.gen_range(i, s.len()); s.swap(i, j); } s } }
use crate::actix::{ Actor, SyncContext, Message, Handler }; use crate::model::Msg; use crate::schema; use actix_web::error::Error; use diesel::r2d2::{ ConnectionManager, Pool }; use diesel::PgConnection; use diesel::prelude::*; use serde_derive::Deserialize; use uuid::Uuid; use chrono::Local; pub struct DbActor(pub Pool<ConnectionManager<PgConnection>>); #[derive(Debug, Deserialize)] pub struct User { pub username: String, } #[derive(Debug, Deserialize)] pub struct Form { pub username: String, pub body: String, } impl Actor for DbActor { type Context = SyncContext<Self>; } impl Message for Form { type Result = Result<Msg, Error>; } impl Message for User { type Result = Result<Vec<Msg>, Error>; } impl Handler<User> for DbActor { type Result = Result<Vec<Msg>, Error>; fn handle(&mut self, _msg: User, _: &mut Self::Context) -> Self::Result { let conn: &PgConnection = &self.0.get().unwrap(); let msgs = schema::messages::table .order(schema::messages::ts.desc()) .limit(20) .load::<Msg>(conn) .unwrap(); Ok(msgs) } } impl Handler<Form> for DbActor { type Result = Result<Msg, Error>; fn handle(&mut self, msg: Form, _: &mut Self::Context) -> Self::Result { let conn: &PgConnection = &self.0.get().unwrap(); let new_msg = Msg { id: Uuid::new_v4(), username: msg.username, body: msg.body, ts: Local::now().naive_local(), }; let result = diesel::insert_into(schema::messages::table) .values(&new_msg) .get_result(conn) .unwrap(); Ok(result) } }
use crate::basictables::fill_tables; use crate::glyph::glifs_to_glyph; use fonttools::font; use fonttools::font::Table; use fonttools::glyf; use fonttools::gvar::GlyphVariationData; use fonttools::hmtx; use fonttools::otvar::VariationModel; use kurbo::{Affine, Point}; use norad::{Component, Contour, ContourPoint, Glyph, Layer}; use std::collections::{BTreeMap, HashSet}; use std::sync::Arc; fn decomposed_components(glyph: &Glyph, glyphset: &Layer) -> Vec<Contour> { let mut contours = Vec::new(); let mut stack: Vec<(&Component, Affine)> = Vec::new(); for component in &glyph.components { stack.push((component, component.transform.into())); while let Some((component, transform)) = stack.pop() { let new_outline = match glyphset.get_glyph(&component.base) { Some(g) => g, None => continue, }; for contour in &new_outline.contours { let mut decomposed_contour = Contour::default(); for point in &contour.points { let new_point = transform * Point::new(point.x as f64, point.y as f64); decomposed_contour.points.push(ContourPoint::new( new_point.x as f32, new_point.y as f32, point.typ.clone(), point.smooth, point.name.clone(), None, None, )) } contours.push(decomposed_contour); } for new_component in new_outline.components.iter().rev() { let new_transform: Affine = new_component.transform.into(); stack.push((new_component, transform * new_transform)); } } } contours } fn decompose_mixed_glyphs(ufo: &mut norad::Font) { let layer = ufo.default_layer_mut(); let mut decomposed: BTreeMap<String, Vec<norad::Contour>> = BTreeMap::new(); for glif in layer.iter() { decomposed.insert(glif.name.to_string(), decomposed_components(glif, layer)); } for glif in layer.iter_mut() { if glif.components.is_empty() || glif.contours.is_empty() { continue; } if let Some(contours) = decomposed.get(&glif.name.to_string()) { glif.contours.extend(contours.clone()); glif.components.clear(); log::info!("Decomposed mixed glyph {:?}", glif.name); } } } fn form_glyf_and_fix_bounds( glyphs: Vec<glyf::Glyph>, metrics: &mut Vec<hmtx::Metric>, ) -> glyf::glyf { let mut glyf_table = glyf::glyf { glyphs }; glyf_table.recalc_bounds(); // Do LSBs again for (id, glyph) in glyf_table.glyphs.iter().enumerate() { metrics[id].lsb = glyph.xMin; } glyf_table } fn get_glyph_names_and_mapping( layer: &norad::Layer, mapping: &mut BTreeMap<u32, u16>, name_to_id: &mut BTreeMap<String, u16>, subset: &Option<HashSet<String>>, ) -> Vec<String> { let mut names: Vec<String> = vec![]; for (glyph_id, glyf) in layer.iter().enumerate() { let name = glyf.name.to_string(); if subset.is_some() && !subset.as_ref().unwrap().contains(&name) { continue; } names.push(name.clone()); name_to_id.insert(name, glyph_id as u16); let cp = &glyf.codepoints; if !cp.is_empty() { mapping.insert(cp[0] as u32, glyph_id as u16); } } names } pub fn build_font(mut ufo: norad::Font, include: Option<HashSet<String>>) -> font::Font { decompose_mixed_glyphs(&mut ufo); let layer = ufo.default_layer(); let info = ufo.font_info.as_ref().unwrap(); let mut mapping: BTreeMap<u32, u16> = BTreeMap::new(); let mut name_to_id: BTreeMap<String, u16> = BTreeMap::new(); let names = get_glyph_names_and_mapping(&layer, &mut mapping, &mut name_to_id, &include); let glifs: Vec<&Arc<norad::Glyph>> = layer.iter().collect(); let (glyphs, mut metrics): (Vec<glyf::Glyph>, Vec<hmtx::Metric>) = glifs .iter() .filter(|g| include.is_none() || include.as_ref().unwrap().contains(&g.name.to_string())) .map({ |glyf| { let (glyph, _) = glifs_to_glyph(0, &name_to_id, &[Some(&glyf)], None); let lsb = glyph.xMin; let advance_width = glyf.width as u16; ( glyph, hmtx::Metric { advanceWidth: advance_width, lsb, }, ) } }) .unzip(); let glyf_table = form_glyf_and_fix_bounds(glyphs, &mut metrics); fill_tables(info, glyf_table, metrics, names, mapping) } pub fn build_fonts( default_master: usize, mut fonts: Vec<norad::Font>, variation_model: VariationModel, include: Option<HashSet<String>>, ) -> font::Font { for f in fonts.iter_mut() { decompose_mixed_glyphs(f); } let layer = fonts[default_master].default_layer(); let info = fonts[default_master].font_info.as_ref().unwrap(); let mut mapping: BTreeMap<u32, u16> = BTreeMap::new(); let mut name_to_id: BTreeMap<String, u16> = BTreeMap::new(); let names = get_glyph_names_and_mapping(&layer, &mut mapping, &mut name_to_id, &include); let glifs: Vec<&Arc<norad::Glyph>> = layer.iter().collect(); let mut glyphs: Vec<glyf::Glyph> = vec![]; let mut metrics: Vec<hmtx::Metric> = vec![]; let mut variations: Vec<Option<GlyphVariationData>> = vec![]; for glif in glifs { if include.is_some() && !include.as_ref().unwrap().contains(&glif.name.to_string()) { continue; } // Find other glyphs in designspace let mut glif_variations = vec![]; for font in &fonts { if let Some(other_glif) = font.default_layer().get_glyph(&glif.name) { glif_variations.push(Some(other_glif)); } else { glif_variations.push(None); } } let (glyph, variation) = glifs_to_glyph( default_master, &name_to_id, &glif_variations, Some(&variation_model), ); let lsb = glyph.xMin; let advance_width = glif.width as u16; glyphs.push(glyph); metrics.push(hmtx::Metric { advanceWidth: advance_width, lsb, }); variations.push(variation); } let glyf_table = form_glyf_and_fix_bounds(glyphs, &mut metrics); let mut font = fill_tables(info, glyf_table, metrics, names, mapping); let gvar_table = fonttools::gvar::gvar { variations }; font.tables .insert(*b"gvar", Table::Unknown(gvar_table.to_bytes(None))); // No optimization by default font }
use std::{env, path::PathBuf}; use anyhow::{Context, Result}; use config::{Config, File, FileFormat}; use serde::Deserialize; #[derive(Deserialize)] pub struct CliConfig { pub db_path: String, pub data_path: PathBuf, } pub fn read_config() -> Result<CliConfig> { let home = env::var("HOME") .context("Trying to get $HOME")?; let cfg_path: PathBuf = [&home, ".config", "fhmp", "config"].iter().collect(); Config::builder() .add_source( File::from(cfg_path) .format(FileFormat::Toml) .required(true)) .build()? .try_deserialize() .context("Parsing config") }
extern crate clap; extern crate futures; #[macro_use] extern crate log; extern crate rand; extern crate rdkafka; extern crate tokio; use clap::{App, Arg}; use futures::{lazy, Stream}; use rdkafka::config::ClientConfig; use rdkafka::consumer::Consumer; use rdkafka::consumer::stream_consumer::StreamConsumer; use rdkafka::Message; use rdkafka::message::OwnedMessage; use serde_json::{Error, json, Value}; use tokio::runtime::current_thread; use crate::example_utils::setup_logger; mod example_utils; fn send_log_message(message: String, client: reqwest::Client, url: &str) -> String { let response = client .post(url) .header("content-type", "application/json") .body(message.to_string()) .send(); match response { Ok(response) => { format!("Got response: {}", response.status()) } Err(e) => { format!("Got error from http request: {}", e.to_string()) } } } // Emulates an expensive, synchronous computation. fn expensive_computation<'a>(url: &str, msg: OwnedMessage) -> String { match msg.payload_view::<str>() { Some(Ok(payload)) => { let parsed: Result<Value, Error> = serde_json::from_str(payload); match parsed { Ok(parsed_json) => { let message_json = match parsed_json["@timestamp"].as_f64() { Some(timestamp) => { let dd_timestamp = (timestamp * 1000.0) as i64; let mut new_json = parsed_json.clone(); new_json["@timestamp"] = json!(dd_timestamp); Some(new_json) } None => { None } }; let result = match message_json { Some(message) => { let client = reqwest::Client::new(); send_log_message(message.to_string(), client, url) } None => { format!("Failed to convert the json payload to a string") } }; result // format!("Payload timestamp is {} for offset {}", parsedJson["@timestamp"], msg.offset()) } Err(err) => format!("Failed to parse json. Error: {}", err) } } Some(Err(_)) => "Message payload is not a string".to_owned(), None => "No payload".to_owned(), } } // Creates all the resources and runs the event loop. The event loop will: // 1) receive a stream of messages from the `StreamConsumer`. // 2) filter out eventual Kafka errors. // 3) send the message to a thread pool for processing. // Moving each message from one stage of the pipeline to next one is handled by the event loop, // that runs on a single thread. The expensive CPU-bound computation is handled by the `ThreadPool`, // without blocking the event loop. fn run_async_processor(url: &'static str, brokers: &str, group_id: &str, input_topic: &str) { // Create the `StreamConsumer`, to receive the messages from the topic in form of a `Stream`. let consumer: StreamConsumer = ClientConfig::new() .set("group.id", group_id) .set("bootstrap.servers", brokers) .set("enable.partition.eof", "false") .set("session.timeout.ms", "6000") .set("enable.auto.commit", "false") .create() .expect("Consumer creation failed"); consumer .subscribe(&[input_topic]) .expect("Can't subscribe to specified topic"); // Create the runtime where the expensive computation will be performed. let mut thread_pool = tokio::runtime::Builder::new() .name_prefix("pool-") .core_threads(4) .build() .unwrap(); // Use the current thread as IO thread to drive consumer and producer. let mut io_thread = current_thread::Runtime::new().unwrap(); // Create the outer pipeline on the message stream. let stream_processor = consumer .start() .filter_map(|result| { // Filter out errors match result { Ok(msg) => Some(msg), Err(kafka_error) => { warn!("Error while receiving from Kafka: {:?}", kafka_error); None } } }) .for_each(move |borrowed_message| { // Process each message info!("Message received: {}", borrowed_message.offset()); // Borrowed messages can't outlive the consumer they are received from, so they need to // be owned in order to be sent to a separate thread. let owned_message = borrowed_message.detach(); let message_future = lazy(move || { // The body of this closure will be executed in the thread pool. let computation_result = expensive_computation(&url, owned_message); info!("Computation result: {}", computation_result); Ok(()) }); thread_pool.spawn(message_future); Ok(()) }); info!("Starting event loop"); let _ = io_thread.block_on(stream_processor); info!("Stream processing terminated"); } fn main() { let matches = App::new("Async example") .version(option_env!("CARGO_PKG_VERSION").unwrap_or("")) .about("Asynchronous computation example") .arg( Arg::with_name("dd-api-key") .short("api") .long("api-key") .help("Datadog API key") .takes_value(true) ) .arg( Arg::with_name("brokers") .short("b") .long("brokers") .help("Broker list in kafka format") .takes_value(true) .default_value("localhost:9092"), ) .arg( Arg::with_name("group-id") .short("g") .long("group-id") .help("Consumer group id") .takes_value(true) .default_value("example_consumer_group_id"), ) .arg( Arg::with_name("log-conf") .long("log-conf") .help("Configure the logging format (example: 'rdkafka=trace')") .takes_value(true), ) .arg( Arg::with_name("input-topic") .long("input-topic") .help("Input topic") .takes_value(true) .required(true), ) .get_matches(); setup_logger(true, matches.value_of("log-conf")); let dd_api_key = matches.value_of("dd-api-key").unwrap(); let brokers = matches.value_of("brokers").unwrap(); let group_id = matches.value_of("group-id").unwrap(); let input_topic = matches.value_of("input-topic").unwrap(); let url = format!("https://http-intake.logs.datadoghq.com/v1/input/{}?ddtags=env:development", dd_api_key); // https://stackoverflow.com/questions/23975391/how-to-convert-a-string-into-a-static-str let static_url = Box::leak(url.into_boxed_str()); run_async_processor(static_url, brokers, group_id, input_topic); }
// Copyright 2020 Shift Cryptosecurity AG // // 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 futures::channel::mpsc; use std::net::SocketAddr; use tokio::runtime::Runtime; #[macro_use] extern crate log; #[cfg(target_os = "windows")] #[path = "daemon/windows.rs"] mod daemon; #[cfg(not(target_os = "windows"))] #[path = "daemon/unix.rs"] mod daemon; mod error; mod usb; mod web; use usb::UsbDevices; fn main() -> Result<(), Box<dyn std::error::Error>> { // On some platforms it is necessary to inform that you are a daemon and will run in the // background. The `start()` function returns a future that completes if the platform requests // the service to stop. let stop_request = daemon::start(); // Check if the user requested some specific log level via an env variable. Otherwise set log // level to something reasonable. if std::env::var("RUST_LOG").is_ok() { env_logger::init(); } else { env_logger::Builder::new() .filter_level(log::LevelFilter::Info) .init(); } println!("Set RUST_LOG=<filter> to enable logging. Example RUST_LOG=debug"); // Parse CLI args let matches = clap::App::new("BitBoxBridge") .version(clap::crate_version!()) .arg( clap::Arg::with_name("port") .long("port") .short("p") .default_value("8178"), ) .get_matches(); // Unwrap shouldn't happen since it has a default value let port = matches.value_of("port").unwrap(); // Create an async runtime for spawning futures on let rt = Runtime::new()?; // Create the global state that can be shared between threads let usb_devices = UsbDevices::new()?; // Create a channel with which it is possible to request a refresh of usb devices. A length of // 1 is enough since it doesn't make sense to request more refreses than the refresh task can // execute. let (mut notify_tx, notify_rx) = mpsc::channel(1); // Trigger one refresh on startup web::notify(&mut notify_tx); // Create and spawn the future that polls for USB devices let usb_poller = { let usb_devices = usb_devices.clone(); async move { if let Err(e) = usb_devices.presence_detector(notify_rx).await { error!("Stopped polling for usb devices: {}", e); } } }; let addr = SocketAddr::new("127.0.0.1".parse()?, port.parse::<u16>()?); println!("listening on http://{}", addr); let server = web::create(usb_devices, notify_tx, addr); rt.block_on(async move { tokio::select! { _ = stop_request => info!("Requested to stop by environment"), _ = server => info!("Warp returned"), _ = usb_poller => info!("Usb poller died"), } }); Ok(()) }
use crate::tcp::opaque_transport; use linkerd_app_core::{ metrics, profiles::{self, LogicalAddr}, proxy::{ api_resolve::{ConcreteAddr, Metadata}, http, resolve::map_endpoint::MapEndpoint, }, svc::{self, Param}, tls, transport::{self, OrigDstAddr, Remote, ServerAddr}, transport_header, Addr, Conditional, Error, }; use std::net::SocketAddr; use tracing::debug; #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub struct Accept<P> { pub orig_dst: OrigDstAddr, pub protocol: P, } #[derive(Clone)] pub struct Logical<P> { pub orig_dst: OrigDstAddr, pub logical_addr: Option<LogicalAddr>, pub profile: Option<profiles::Receiver>, pub protocol: P, } #[derive(Clone, Debug)] pub struct Concrete<P> { pub resolve: ConcreteAddr, pub logical: Logical<P>, } #[derive(Clone, Debug)] pub struct Endpoint<P> { pub addr: Remote<ServerAddr>, pub tls: tls::ConditionalClientTls, pub metadata: Metadata, pub logical_addr: Addr, pub protocol: P, } #[derive(Copy, Clone)] pub struct EndpointFromMetadata { pub identity_disabled: bool, } // === impl Accept === impl<P> Param<transport::labels::Key> for Accept<P> { fn param(&self) -> transport::labels::Key { const NO_TLS: tls::ConditionalServerTls = Conditional::None(tls::NoServerTls::Loopback); transport::labels::Key::accept( transport::labels::Direction::Out, NO_TLS, self.orig_dst.into(), ) } } // === impl Logical === impl<P> From<(Option<profiles::Receiver>, Accept<P>)> for Logical<P> { fn from( ( profile, Accept { orig_dst, protocol, .. }, ): (Option<profiles::Receiver>, Accept<P>), ) -> Self { let logical_addr = profile.as_ref().and_then(|p| p.borrow().addr.clone()); Self { profile, orig_dst, protocol, logical_addr, } } } /// Used for traffic split impl<P> Param<Option<profiles::Receiver>> for Logical<P> { fn param(&self) -> Option<profiles::Receiver> { self.profile.clone() } } /// Used for default traffic split impl<P> Param<profiles::LookupAddr> for Logical<P> { fn param(&self) -> profiles::LookupAddr { profiles::LookupAddr(self.addr()) } } impl<P> Logical<P> { pub fn addr(&self) -> Addr { self.logical_addr .as_ref() .map(|LogicalAddr(a)| Addr::from(a.clone())) .unwrap_or_else(|| self.orig_dst.0.into()) } } impl<P: PartialEq> PartialEq<Logical<P>> for Logical<P> { fn eq(&self, other: &Logical<P>) -> bool { self.orig_dst == other.orig_dst && self.logical_addr == other.logical_addr && self.protocol == other.protocol } } impl<P: Eq> Eq for Logical<P> {} impl<P: std::hash::Hash> std::hash::Hash for Logical<P> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.orig_dst.hash(state); self.logical_addr.hash(state); self.protocol.hash(state); } } impl<P: std::fmt::Debug> std::fmt::Debug for Logical<P> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Logical") .field("orig_dst", &self.orig_dst) .field("protocol", &self.protocol) .field( "profile", &format_args!( "{}", if self.profile.is_some() { "Some(..)" } else { "None" } ), ) .field("logical_addr", &self.logical_addr) .finish() } } impl<P> Logical<P> { pub fn or_endpoint( reason: tls::NoClientTls, ) -> impl Fn(Self) -> Result<svc::Either<Self, Endpoint<P>>, Error> + Copy { move |logical: Self| { let should_resolve = match logical.profile.as_ref() { Some(p) => { let p = p.borrow(); p.endpoint.is_none() && (p.addr.is_some() || !p.targets.is_empty()) } None => false, }; if should_resolve { Ok(svc::Either::A(logical)) } else { debug!(%reason, orig_dst = %logical.orig_dst, "Target is unresolveable"); Ok(svc::Either::B(Endpoint::from((reason, logical)))) } } } } // === impl Concrete === impl<P> From<(ConcreteAddr, Logical<P>)> for Concrete<P> { fn from((resolve, logical): (ConcreteAddr, Logical<P>)) -> Self { Self { resolve, logical } } } impl<P> Param<ConcreteAddr> for Concrete<P> { fn param(&self) -> ConcreteAddr { self.resolve.clone() } } // === impl Endpoint === impl<P> From<(tls::NoClientTls, Logical<P>)> for Endpoint<P> { fn from((reason, logical): (tls::NoClientTls, Logical<P>)) -> Self { match logical .profile .as_ref() .and_then(|p| p.borrow().endpoint.clone()) { None => Self { addr: Remote(ServerAddr(logical.orig_dst.into())), metadata: Metadata::default(), tls: Conditional::None(reason), logical_addr: logical.addr(), protocol: logical.protocol, }, Some((addr, metadata)) => Self { addr: Remote(ServerAddr(addr)), tls: EndpointFromMetadata::client_tls(&metadata, reason), metadata, logical_addr: logical.addr(), protocol: logical.protocol, }, } } } impl<P> From<(tls::NoClientTls, Accept<P>)> for Endpoint<P> { fn from((reason, accept): (tls::NoClientTls, Accept<P>)) -> Self { Self::from((reason, Logical::from((None, accept)))) } } impl<P> Param<Remote<ServerAddr>> for Endpoint<P> { fn param(&self) -> Remote<ServerAddr> { self.addr } } impl<P> Param<tls::ConditionalClientTls> for Endpoint<P> { fn param(&self) -> tls::ConditionalClientTls { self.tls.clone() } } impl<P> Param<Option<opaque_transport::PortOverride>> for Endpoint<P> { fn param(&self) -> Option<opaque_transport::PortOverride> { self.metadata .opaque_transport_port() .map(opaque_transport::PortOverride) } } impl<P> Param<Option<http::AuthorityOverride>> for Endpoint<P> { fn param(&self) -> Option<http::AuthorityOverride> { self.metadata .authority_override() .cloned() .map(http::AuthorityOverride) } } impl<P> Param<transport::labels::Key> for Endpoint<P> { fn param(&self) -> transport::labels::Key { transport::labels::Key::OutboundConnect(self.param()) } } impl<P> Param<metrics::OutboundEndpointLabels> for Endpoint<P> { fn param(&self) -> metrics::OutboundEndpointLabels { metrics::OutboundEndpointLabels { authority: Some(self.logical_addr.to_http_authority()), labels: metrics::prefix_labels("dst", self.metadata.labels().iter()), server_id: self.tls.clone(), target_addr: self.addr.into(), } } } impl<P> Param<metrics::EndpointLabels> for Endpoint<P> { fn param(&self) -> metrics::EndpointLabels { Param::<metrics::OutboundEndpointLabels>::param(self).into() } } impl<P: std::hash::Hash> std::hash::Hash for Endpoint<P> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.addr.hash(state); self.tls.hash(state); self.logical_addr.hash(state); self.protocol.hash(state); } } // === EndpointFromMetadata === impl EndpointFromMetadata { fn client_tls(metadata: &Metadata, reason: tls::NoClientTls) -> tls::ConditionalClientTls { // If we're transporting an opaque protocol OR we're communicating with // a gateway, then set an ALPN value indicating support for a transport // header. let use_transport_header = metadata.opaque_transport_port().is_some() || metadata.authority_override().is_some(); metadata .identity() .cloned() .map(move |server_id| { Conditional::Some(tls::ClientTls { server_id, alpn: if use_transport_header { Some(tls::client::AlpnProtocols(vec![ transport_header::PROTOCOL.into() ])) } else { None }, }) }) .unwrap_or(Conditional::None(reason)) } } impl<P: Copy + std::fmt::Debug> MapEndpoint<Concrete<P>, Metadata> for EndpointFromMetadata { type Out = Endpoint<P>; fn map_endpoint( &self, concrete: &Concrete<P>, addr: SocketAddr, metadata: Metadata, ) -> Self::Out { tracing::trace!(%addr, ?metadata, ?concrete, "Resolved endpoint"); let tls = if self.identity_disabled { tls::ConditionalClientTls::None(tls::NoClientTls::Disabled) } else { Self::client_tls(&metadata, tls::NoClientTls::NotProvidedByServiceDiscovery) }; Endpoint { addr: Remote(ServerAddr(addr)), tls, metadata, logical_addr: concrete.logical.addr(), protocol: concrete.logical.protocol, } } }
//! 2x2 Matrix use super::common::{Mat2, Vec2, hypot, EPSILON}; /// Creates a new identity mat2. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn create() -> Mat2 { let mut out: Mat2 = [0_f32; 4]; out[0] = 1_f32; out[3] = 1_f32; out } /// Creates a new mat2 initialized with values from an existing matrix. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn clone(a: &Mat2) -> Mat2 { let mut out: Mat2 = [0_f32; 4]; out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out } /// Copy the values from one mat2 to another. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn copy(out: &mut Mat2, a: &Mat2) -> Mat2 { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; *out } /// Set a mat2 to the identity matrix. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn identity(out: &mut Mat2) -> Mat2 { out[0] = 1_f32; out[1] = 0_f32; out[2] = 0_f32; out[3] = 1_f32; *out } /// Create a new mat2 with the given values. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn from_values(m00: f32, m01: f32, m10: f32, m11: f32) -> Mat2 { let mut out: Mat2 = [0_f32; 4]; out[0] = m00; out[1] = m01; out[2] = m10; out[3] = m11; out } /// Set the components of a mat2 to the given values. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn set(out: &mut Mat2, m00: f32, m01: f32, m10: f32, m11: f32) -> Mat2 { out[0] = m00; out[1] = m01; out[2] = m10; out[3] = m11; *out } /// Transpose the values of a mat2. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn transpose(out: &mut Mat2, a: &Mat2) -> Mat2 { // If we are transposing ourselves we can skip a few steps but have to cache // some values if out.eq(&a) { let a1 = a[1]; out[1] = a[2]; out[2] = a1; } else { out[0] = a[0]; out[1] = a[2]; out[2] = a[1]; out[3] = a[3]; } *out } /// Inverts a mat2. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn invert(out: &mut Mat2, a: &Mat2) -> Option<Mat2> { let a0 = a[0]; let a1 = a[1]; let a2 = a[2]; let a3 = a[3]; // Calculate the determinant let det = a0 * a3 - a2 * a1; // Make sure matrix is not singular if det == 0_f32 { return None; } let det = 1_f32 / det; out[0] = a3 * det; out[1] = -a1 * det; out[2] = -a2 * det; out[3] = a0 * det; Some(*out) } /// Calculates the adjugate of a mat2. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn adjoint(out: &mut Mat2, a: &Mat2) -> Mat2 { // Caching this value is nessecary if out == a let a0 = a[0]; out[0] = a[3]; out[1] = -a[1]; out[2] = -a[2]; out[3] = a0; *out } /// Calculates the determinant of a mat2. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn determinant(a: &Mat2) -> f32 { a[0] * a[3] - a[2] * a[1] } /// Multiplies two mat2's. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn multiply(out: &mut Mat2, a: &Mat2, b: &Mat2) -> Mat2 { let a0 = a[0]; let a1 = a[1]; let a2 = a[2]; let a3 = a[3]; let b0 = b[0]; let b1 = b[1]; let b2 = b[2]; let b3 = b[3]; out[0] = a0 * b0 + a2 * b1; out[1] = a1 * b0 + a3 * b1; out[2] = a0 * b2 + a2 * b3; out[3] = a1 * b2 + a3 * b3; *out } /// Rotates a mat2 by the given angle. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn rotate(out: &mut Mat2, a: &Mat2, rad: f32) -> Mat2 { let a0 = a[0]; let a1 = a[1]; let a2 = a[2]; let a3 = a[3]; let s = f32::sin(rad); let c = f32::cos(rad); out[0] = a0 * c + a2 * s; out[1] = a1 * c + a3 * s; out[2] = a0 * -s + a2 * c; out[3] = a1 * -s + a3 * c; *out } /// Scales the mat2 by the dimensions in the given vec2. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn scale(out: &mut Mat2, a: &Mat2, v: &Vec2) -> Mat2 { let a0 = a[0]; let a1 = a[1]; let a2 = a[2]; let a3 = a[3]; let v0 = v[0]; let v1 = v[1]; out[0] = a0 * v0; out[1] = a1 * v0; out[2] = a2 * v1; out[3] = a3 * v1; *out } /// Creates a matrix from a given angle. /// /// This is equivalent to (but much faster than): /// ``` /// use gl_matrix::common::*; /// use gl_matrix::mat2; /// /// let dest = &mut [0., 0., 0., 0.]; /// let rad = PI * 0.5; /// /// mat2::identity(dest); /// mat2::rotate(dest, &mat2::clone(dest), rad); /// ``` /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn from_rotation(out: &mut Mat2, rad: f32) -> Mat2 { let s = f32::sin(rad); let c = f32::cos(rad); out[0] = c; out[1] = s; out[2] = -s; out[3] = c; *out } /// Creates a matrix from a vector scaling. /// /// This is equivalent to (but much faster than): /// ``` /// use gl_matrix::common::*; /// use gl_matrix::mat2; /// /// let dest = &mut [0., 0., 0., 0.]; /// let vec: Vec2 = [2., 3.]; /// /// mat2::identity(dest); /// mat2::scale(dest, &mat2::clone(dest), &vec); /// ``` /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn from_scaling(out: &mut Mat2, v: &Vec2) -> Mat2 { out[0] = v[0]; out[1] = 0_f32; out[2] = 0_f32; out[3] = v[1]; *out } /// Returns a string representation of a mat2. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn string(a: &Mat2) -> String { let a0 = ["mat2(".to_string(), a[0].to_string()].join(""); let a1 = a[1].to_string(); let a2 = a[2].to_string(); let a3 = [a[3].to_string(), ")".to_string()].join(""); [a0, a1, a2, a3].join(", ") } /// Returns Frobenius norm of a mat2. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn frob(a: &Mat2) -> f32 { hypot(a) } /// Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn ldu(l: &mut Mat2, _d: &mut Mat2, u: &mut Mat2, a: &Mat2) -> (Mat2, Mat2, Mat2) { l[2] = a[2] / a[0]; u[0] = a[0]; u[1] = a[1]; u[3] = a[3] - l[2] * u[1]; (*l, *_d, *u) } /// Adds two mat2's. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn add(out: &mut Mat2, a: &Mat2, b: &Mat2) -> Mat2 { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; out[2] = a[2] + b[2]; out[3] = a[3] + b[3]; *out } /// Subtracts matrix b from matrix a. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn subtract(out: &mut Mat2, a: &Mat2, b: &Mat2) -> Mat2 { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; out[2] = a[2] - b[2]; out[3] = a[3] - b[3]; *out } /// Returns whether or not the matrices have exactly the same elements in the same position (when compared with ==). /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn exact_equals(a: &Mat2, b: &Mat2) -> bool { a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3] } /// Returns whether or not the matrices have approximately the same elements in the same position. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn equals(a: &Mat2, b: &Mat2) -> bool { let a0 = a[0]; let a1 = a[1]; let a2 = a[2]; let a3 = a[3]; let b0 = b[0]; let b1 = b[1]; let b2 = b[2]; let b3 = b[3]; f32::abs(a0 - b0) <= EPSILON * f32::max(1.0, f32::max(f32::abs(a0), f32::abs(b0))) && f32::abs(a1 - b1) <= EPSILON * f32::max(1.0, f32::max(f32::abs(a1), f32::abs(b1))) && f32::abs(a2 - b2) <= EPSILON * f32::max(1.0, f32::max(f32::abs(a2), f32::abs(b2))) && f32::abs(a3 - b3) <= EPSILON * f32::max(1.0, f32::max(f32::abs(a3), f32::abs(b3))) } /// Multiply each element of the matrix by a scalar. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn multiply_scalar(out: &mut Mat2, a: &Mat2, b: f32) -> Mat2 { out[0] = a[0] * b; out[1] = a[1] * b; out[2] = a[2] * b; out[3] = a[3] * b; *out } /// Adds two mat2's after multiplying each element of the second operand by a scalar value. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn multiply_scalar_and_add(out: &mut Mat2, a: &Mat2, b: &Mat2, scale: f32) -> Mat2 { out[0] = a[0] + (b[0] * scale); out[1] = a[1] + (b[1] * scale); out[2] = a[2] + (b[2] * scale); out[3] = a[3] + (b[3] * scale); *out } /// Alias for mat2::multiply. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn mul(out: &mut Mat2, a: &Mat2, b: &Mat2) -> Mat2 { multiply(out, a, b) } /// Alias for mat2::subtract. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat2.html) pub fn sub(out: &mut Mat2, a: &Mat2, b: &Mat2) -> Mat2 { subtract(out, a, b) } #[cfg(test)] mod tests { use super::*; #[test] fn create_a_mat2() { let ident: Mat2 = [1., 0., 0., 1.]; let out = create(); assert_eq!(ident, out); } #[test] fn clone_a_mat2() { let mat_a: Mat2 = [1., 2., 3., 4.]; let out = clone(&mat_a); assert_eq!(mat_a, out); } #[test] fn copy_values_from_a_mat2_to_another() { let mut out = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let result = copy(&mut out, &mat_a); assert_eq!(mat_a, out); assert_eq!(result, out); } #[test] fn set_a_mat2_to_identity() { let mut out: Mat2 = [0., 0., 0., 0.]; let ident = [1., 0., 0., 1.]; let result = identity(&mut out); assert_eq!(out, ident); assert_eq!(result, out); } #[test] fn create_mat2_from_values() { let out = from_values(1., 2., 3. ,4.); assert_eq!([1., 2., 3., 4.], out); } #[test] fn set_mat2_with_values() { let mut out: Mat2 = [0., 0., 0., 0.]; let result = set(&mut out, 1., 2., 3., 4.); assert_eq!([1., 2., 3., 4.], out); assert_eq!(result, out); } #[test] fn transpose_same_mat2() { let mut mat_a: Mat2 = [1., 2., 3., 4.]; let mat_a_copy = clone(&mat_a); let result = transpose(&mut mat_a, &mat_a_copy); assert_eq!([1., 3., 2., 4.], mat_a); assert_eq!(result, mat_a); } #[test] fn transpose_different_mat2() { let mut out: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let result = transpose(&mut out, &mat_a); assert_eq!([1., 3., 2., 4.], out); assert_eq!(result, out); } #[test] fn invert_mat2() { let mut out: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let result = invert(&mut out, &mat_a).unwrap(); assert_eq!([-2., 1., 1.5, -0.5], out); assert_eq!(result, out); } #[test] fn invert_singular_mat2() { let mut out: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [-1., 3./2., 2./3., -1.]; let result = invert(&mut out, &mat_a); assert_eq!([0., 0., 0., 0.], out); assert_eq!(None, result); } #[test] fn adjugate_mat2() { let mut out: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let result = adjoint(&mut out, &mat_a); assert_eq!([4., -2., -3., 1.], out); assert_eq!(result, out); } #[test] fn adjugate_mat2_same() { let mut mat_a: Mat2 = [1., 2., 3., 4.]; let mat_a_copy: Mat2 = [1., 2., 3., 4.]; let result = adjoint(&mut mat_a, &mat_a_copy); assert_eq!([4., -2., -3., 1.], mat_a); assert_eq!(result, mat_a); } #[test] fn get_mat2_determinant() { let mat_a: Mat2 = [1., 2., 3., 4.]; let det: f32 = determinant(&mat_a); assert_eq!(-2_f32, det); } #[test] fn multiply_two_mat2s() { let mut out: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let mat_b: Mat2 = [5., 6., 7., 8.]; let result = multiply(&mut out, &mat_a, &mat_b); assert_eq!([23., 34., 31., 46.], out); assert_eq!(result, out); } #[test] fn mul_two_mat2s() { let mut out: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let mat_b: Mat2 = [5., 6., 7., 8.]; let result = mul(&mut out, &mat_a, &mat_b); assert_eq!([23., 34., 31., 46.], out); assert_eq!(result, out); } #[test] fn mul_is_equal_to_multiply() { let mut out_a: Mat2 = [0., 0., 0., 0.]; let mut out_b: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let mat_b: Mat2 = [5., 6., 7., 8.]; multiply(&mut out_a, &mat_a, &mat_b); mul(&mut out_b, &mat_a, &mat_b); assert_eq!(out_a, out_b); } #[test] fn rotate_a_mat2() { use super::super::common::{PI}; let mut out: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let result = rotate(&mut out, &mat_a, PI * 0.5); assert!(equals(&[3., 4., -1., -2.], &out)); assert_eq!(result, out); } #[test] fn scale_mat2() { let mut out: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let vec_a: Vec2 = [2., 3.]; let result = scale(&mut out, &mat_a, &vec_a); assert_eq!([2., 4., 9., 12.], out); assert_eq!(result, out); } #[test] fn mat2_from_rotation() { use super::super::common::{PI}; let mut out = create(); let result = from_rotation(&mut out, PI * 0.5); assert!(equals(&[0., 1., -1., 0.], &out)); assert_eq!(result, out); } #[test] fn mat2_from_scaling() { let mut out: Mat2 = create(); let vec_a: Vec2 = [2., 3.]; let result = from_scaling(&mut out, &vec_a); assert_eq!([2., 0., 0., 3.], out); assert_eq!(result, out); } #[test] fn get_mat2_string() { let mat_a: Mat2 = [1., 2., 3., 4.]; let str_a = string(&mat_a); assert_eq!("mat2(1, 2, 3, 4)".to_string(), str_a); } #[test] fn calc_frob_norm_of_mat2() { let mat_a: Mat2 = [1., 2., 3., 4.]; let frob_a = frob(&mat_a); assert_eq!((1_f32.powi(2) + 2_f32.powi(2) + 3_f32.powi(2) + 4_f32.powi(2)).sqrt(), frob_a); } #[test] fn get_ldu_mat2() { let mut l: Mat2 = create(); let mut d: Mat2 = create(); let mut u: Mat2 = create(); let mut l_result: Mat2 = create(); l_result[2] = 1.5; let d_result: Mat2 = create(); let mut u_result: Mat2 = create(); u_result[0] = 4.; u_result[1] = 3.; u_result[3] = -1.5; let (l_r, d_r, u_r) = ldu(&mut l, &mut d, &mut u, &[4.,3.,6.,3.]); assert_eq!(l_result, l); assert_eq!(d_result, d); assert_eq!(u_result, u); assert_eq!(l_r, l); assert_eq!(d_r, d); assert_eq!(u_r, u); } #[test] fn add_two_mat2s() { let mut out: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let mat_b: Mat2 = [5., 6., 7., 8.]; let result = add(&mut out, &mat_a, &mat_b); assert_eq!([6., 8., 10., 12.], out); assert_eq!(result, out); } #[test] fn subtract_two_mat2s() { let mut out: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let mat_b: Mat2 = [5., 6., 7., 8.]; let result = subtract(&mut out, &mat_a, &mat_b); assert_eq!([-4., -4., -4., -4.], out); assert_eq!(result, out); } #[test] fn sub_two_mat2s() { let mut out: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let mat_b: Mat2 = [5., 6., 7., 8.]; let result = sub(&mut out, &mat_a, &mat_b); assert_eq!([-4., -4., -4., -4.], out); assert_eq!(result, out); } #[test] fn sub_is_equal_to_subtract() { let mut out_a: Mat2 = [0., 0., 0., 0.]; let mut out_b: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let mat_b: Mat2 = [5., 6., 7., 8.]; sub(&mut out_a, &mat_a, &mat_b); subtract(&mut out_b, &mat_a, &mat_b); assert_eq!(out_a, out_b); } #[test] fn mat2s_are_exact_equal() { let mat_a: Mat2 = [0., 1., 2., 3.]; let mat_b: Mat2 = [0., 1., 2., 3.]; let r0 = exact_equals(&mat_a, &mat_b); assert!(r0); } #[test] fn mat2s_are_not_exact_equal() { let mat_a: Mat2 = [0., 1., 2., 3.]; let mat_b: Mat2 = [1., 2., 3., 4.]; let r0 = exact_equals(&mat_a, &mat_b); assert!(!r0); } #[test] fn mat2s_are_equal() { let mat_a: Mat2 = [0., 1., 2., 3.]; let mat_b: Mat2 = [0., 1., 2., 3.]; let r0 = equals(&mat_a, &mat_b); assert!(r0); } #[test] fn mat2s_are_equal_enough() { let mat_a: Mat2 = [0., 1., 2., 3.]; let mat_b: Mat2 = [1_f32*10_f32.powi(-16), 1., 2., 3.]; let r0 = equals(&mat_a, &mat_b); assert!(r0); } #[test] fn mat2s_are_not_equal() { let mat_a: Mat2 = [0., 1., 2., 3.]; let mat_b: Mat2 = [1., 2., 3., 4.]; let r0 = equals(&mat_a, &mat_b); assert!(!r0); } #[test] fn multiply_mat2_by_scalar() { let mut out: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let result = multiply_scalar(&mut out, &mat_a, 2.); assert_eq!([2., 4., 6., 8.], out); assert_eq!(result, out); } #[test] fn multiply_mat2_by_scalar_and_add() { let mut out: Mat2 = [0., 0., 0., 0.]; let mat_a: Mat2 = [1., 2., 3., 4.]; let mat_b: Mat2 = [5., 6., 7., 8.]; let result = multiply_scalar_and_add(&mut out, &mat_a, &mat_b, 0.5); assert_eq!([3.5, 5., 6.5, 8.], out); assert_eq!(result, out); } }
use mongodb::bson::{document::Document, oid::ObjectId}; use serde::Serialize; use std::iter::Iterator; use super::Product; #[derive(Serialize, Clone)] pub struct Wishlist { #[serde(skip)] id: Option<ObjectId>, timestamp: Option<i32>, #[serde(skip)] product_ids: Option<Vec<ObjectId>>, products: Option<Vec<Product>>, } impl Wishlist { pub fn get_product_ids(&self) -> Option<&[ObjectId]> { self.product_ids.as_ref().map(|e| e.as_slice()) } pub fn set_products(&mut self, products: Vec<Product>) { self.products = Some(products); } } impl From<&Document> for Wishlist { fn from(doc: &Document) -> Self { Self { id: doc.get_object_id("_id").map(|id| id.clone()).ok(), timestamp: doc.get_i32("timestamp").ok(), product_ids: doc .get_array("products") .map(|list| { list.into_iter() .filter_map(|e| e.as_object_id().map(|id| id.clone())) .collect() }) .ok(), products: None, } } }
use crate::format::problem::*; use crate::format::solution::*; use crate::helpers::*; #[test] fn can_use_vehicle_with_open_end() { let problem = Problem { plan: Plan { jobs: vec![create_delivery_job("job1", vec![1., 0.])], relations: Option::None }, fleet: Fleet { vehicles: vec![create_default_vehicle_type()], profiles: create_default_matrix_profiles() }, ..create_empty_problem() }; let matrix = Matrix { profile: Some("car".to_owned()), timestamp: None, travel_times: vec![0, 1, 1, 0], distances: vec![0, 1, 1, 0], error_codes: Some(vec![0, 1, 1, 1]), }; let solution = solve_with_metaheuristic(problem, Some(vec![matrix])); assert_eq!( solution, Solution { statistic: Statistic { cost: 0., distance: 0, duration: 0, times: Timing { driving: 0, serving: 0, waiting: 0, break_time: 0 }, }, tours: vec![], unassigned: Some(vec![UnassignedJob { job_id: "job1".to_string(), reasons: vec![UnassignedJobReason { code: "REACHABLE_CONSTRAINT".to_string(), description: "location unreachable".to_string() }] }]), ..create_empty_solution() } ); }
pub mod dtos; pub mod role; pub mod user;
use super::super::super::repository::design::{find_designs}; #[test] fn test_find_designs() { let domain_designs = find_designs(1, 1); assert_eq!(1, domain_designs[0].id); }
use crate::{ fragment::{Bounds, Rect}, Fragment, }; /// Result of endorsing processes #[derive(Debug)] pub struct Endorse<T, E> { /// The result that passed the endorsed pub accepted: Vec<T>, /// The objects that didn't pass the endorsement pub rejects: Vec<E>, } impl<T, E> Endorse<T, E> { pub fn extend(&mut self, other: Self) { self.accepted.extend(other.accepted); self.rejects.extend(other.rejects); } } /// if a group of fragment can be endorse as rect, return the bounds point for the /// rectangle pub fn endorse_rect(fragments: &[&Fragment]) -> Option<Rect> { if is_rect(fragments) { let is_any_broken = fragments.iter().any(|fragment| fragment.is_broken()); let all_points = fragments.iter().fold(vec![], |mut acc, frag| { let (p1, p2) = frag.bounds(); acc.push(p1); acc.push(p2); acc }); let min = all_points.iter().min(); let max = all_points.iter().max(); if let (Some(min), Some(max)) = (min, max) { Some(Rect::new(*min, *max, false, is_any_broken)) } else { None } } else { None } } /// group of fragments can be check if they form: /// - rectangle fn is_rect(fragments: &[&Fragment]) -> bool { if fragments.len() == 4 { let parallels = parallel_aabb_group(fragments); if parallels.len() == 2 { let (a1, a2) = parallels[0]; let (b1, b2) = parallels[1]; let line_a1 = fragments[a1].as_line().expect("expecting a line"); let line_b1 = fragments[b1].as_line().expect("expecting a line"); let line_a2 = fragments[a2].as_line().expect("expecting a line"); let line_b2 = fragments[b2].as_line().expect("expecting a line"); line_a1.is_touching_aabb_perpendicular(line_b1) && line_a2.is_touching_aabb_perpendicular(line_b2) } else { false } } else { false } } /// qualifications: /// - 8 fragments /// - 2 parallel pair /// - 4 aabb right angle arc (top_left, top_right, bottom_left, bottom_right) /// - each of the right angle touches 2 lines that are aabb_perpendicular pub fn endorse_rounded_rect(fragments: &[&Fragment]) -> Option<Rect> { if let (true, arc_radius) = is_rounded_rect(fragments) { let is_any_broken = fragments.iter().any(|fragment| fragment.is_broken()); let all_points = fragments.iter().fold(vec![], |mut acc, frag| { let (p1, p2) = frag.bounds(); acc.push(p1); acc.push(p2); acc }); let min = all_points.iter().min(); let max = all_points.iter().max(); if let (Some(min), Some(max)) = (min, max) { //TODO: compute the radius from Some(Rect::rounded_new( *min, *max, false, arc_radius.expect("expecting arc radius"), is_any_broken, )) } else { None } } else { None } } fn is_rounded_rect(fragments: &[&Fragment]) -> (bool, Option<f32>) { if fragments.len() == 8 { let parallels = parallel_aabb_group(fragments); let right_arcs = right_angle_arcs(fragments); //TODO: throroughly check the arc composition to be top_left, top_right, bottom_left, //bottom_right if parallels.len() == 2 && right_arcs.len() == 4 { let first_right_arc_index = right_arcs[0]; let arc_fragment = &fragments[first_right_arc_index]; let arc_radius = arc_fragment.as_arc().expect("expecting an arc").radius; let (a1, a2) = parallels[0]; let (b1, b2) = parallels[1]; let line_a1 = fragments[a1].as_line().expect("expecting a line"); let line_b1 = fragments[b1].as_line().expect("expecting a line"); let line_a2 = fragments[a2].as_line().expect("expecting a line"); let line_b2 = fragments[b2].as_line().expect("expecting a line"); let passed = line_a1.is_aabb_perpendicular(line_b1) && line_a2.is_aabb_perpendicular(line_b2); (passed, Some(arc_radius)) } else { (false, None) } } else { (false, None) } } /// return the index of the fragments that are right angle arc fn right_angle_arcs(fragments: &[&Fragment]) -> Vec<usize> { fragments .iter() .enumerate() .filter_map(|(index, frag)| { if let Some(arc) = frag.as_arc() { if arc.is_aabb_right_angle_arc() { Some(index) } else { None } } else { None } }) .collect() } /// return the indexes of the fragments that are aabb parallel fn parallel_aabb_group(fragments: &[&Fragment]) -> Vec<(usize, usize)> { let mut parallels = vec![]; for (index1, frag1) in fragments.iter().enumerate() { for (index2, frag2) in fragments.iter().enumerate() { if index1 != index2 && !parallels.iter().any(|(pair1, pair2)| { index1 == *pair1 || index1 == *pair2 || index2 == *pair1 || index2 == *pair2 }) && frag1.is_aabb_parallel(frag2) { parallels.push((index1, index2)); } } } parallels } #[cfg(test)] mod tests { use super::*; use crate::{buffer::CellGrid, fragment::line}; #[test] fn test_parallel_grouping() { let a = CellGrid::a(); let e = CellGrid::e(); let u = CellGrid::u(); let y = CellGrid::y(); let line_ae = line(a, e); let line_uy = line(u, y); let group = parallel_aabb_group(&[&line_ae, &line_uy]); println!("group: {:#?}", group); assert_eq!(group, vec![(0, 1)]) } #[test] fn test_parallel_grouping_with4() { let a = CellGrid::a(); let e = CellGrid::e(); let u = CellGrid::u(); let y = CellGrid::y(); let line_ae = line(a, e); let line_uy = line(u, y); let line_au = line(a, u); let line_ey = line(e, y); let group = parallel_aabb_group(&[&line_ae, &line_au, &line_uy, &line_ey]); println!("group: {:#?}", group); assert_eq!(group, vec![(0, 2), (1, 3)]); let rect = endorse_rect(&[&line_ae, &line_au, &line_uy, &line_ey]); assert!(rect.is_some()); assert_eq!(rect, Some(Rect::new(a, y, false, false))); assert!(is_rect(&[&line_ae, &line_au, &line_uy, &line_ey])); } #[test] fn parallel_and_perpendicular_but_not_touching_should_not_be_rect() { let a = CellGrid::a(); let e = CellGrid::e(); let u = CellGrid::u(); let y = CellGrid::y(); let g = CellGrid::g(); let q = CellGrid::q(); let i = CellGrid::i(); let s = CellGrid::s(); let line_ae = line(a, e); let line_uy = line(u, y); let line_gq = line(g, q); let line_is = line(i, s); assert!(!is_rect(&[&line_ae, &line_uy, &line_gq, &line_is])); } }
#[macro_use] extern crate log; use bot::{commands, data, handler}; use std::{collections::HashSet, env, sync::Arc}; use dotenv::dotenv; use redis::Client as RedisClient; use serenity::{ client::bridge::gateway::GatewayIntents, framework::StandardFramework, http::Http, prelude::Mutex, Client, }; use songbird::{ driver::{Config as DriverConfig, DecodeMode}, SerenityInit, Songbird, }; #[tokio::main] async fn main() { dotenv().ok(); pretty_env_logger::init(); let token = env::var("DISCORD_BOT_TOKEN").expect("Missing DISCORD_BOT_TOKEN"); let http = Http::new_with_token(&token); let pg_url = env::var("DATABASE_URL").expect("Missing DATABASE_URL"); let redis_url = env::var("REDIS_HOST").expect("Missing REDIS_HOST"); let cert_path = env::var("GCP_SERVICE_ACCOUNT_CREDENTIAL_FILE") .expect("Missing GCP_SERVICE_ACCOUNT_CREDENTIAL_FILE"); // ** Get Owner Info ** // let (owners, user_id) = http .get_current_application_info() .await .map(|info| { let mut set = HashSet::new(); set.insert(info.owner.id); let id = info.id; (set, id) }) .unwrap(); // ** Framework Initialization ** // let framework = StandardFramework::new() .configure(|c| { c.owners(owners) .allow_dm(false) .on_mention(Some(user_id)) .prefix("z.") .delimiters(vec![" ", " "]) .case_insensitivity(true) }) .group(&commands::META_GROUP) .group(&commands::TTS_GROUP); let songbird = Songbird::serenity(); songbird.set_config(DriverConfig::default().decode_mode(DecodeMode::Decode)); // ** Setup Gateway Intents ** // let intents: GatewayIntents = GatewayIntents::GUILDS | GatewayIntents::GUILD_MEMBERS // Note: This intent is *priviledged* | GatewayIntents::GUILD_BANS | GatewayIntents::GUILD_EMOJIS | GatewayIntents::GUILD_INVITES | GatewayIntents::GUILD_VOICE_STATES | GatewayIntents::GUILD_MESSAGES | GatewayIntents::GUILD_MESSAGE_REACTIONS | GatewayIntents::DIRECT_MESSAGES; // ** Create Client ** // let mut client = Client::builder(&token) .event_handler(handler::ClientHandler::new()) .framework(framework) .intents(intents) .register_songbird_with(songbird.into()) .await .expect("Failed to create discord client"); { let mut data = client.data.write().await; let pool = data::create_pool(&pg_url).await; let redis_client = RedisClient::open(redis_url).unwrap(); let token = tts::backend::gcp::GcpToken::issue(cert_path).await.unwrap(); data.insert::<data::RedisConnection>(Arc::new(Mutex::new(redis_client))); data.insert::<data::GcpAccessToken>(Arc::new(Mutex::new(token))); data.insert::<data::DatabasePool>(pool); data.insert::<data::ShardManagerContainer>(client.shard_manager.clone()) } // ** Start Application ** // let shard_manager = client.shard_manager.clone(); tokio::spawn(async move { tokio::signal::ctrl_c() .await .expect("Failed to register CTRL + C handler"); shard_manager.lock().await.shutdown_all().await; }); info!("Application Start"); if let Err(e) = client.start().await { error!("Fatal error: {:?}", e); } }
#[macro_use] extern crate ndarray; use ndarray::{arr2, ArrayBase}; use ndarray::{Array1, Array2, Axis}; fn projection_space(space: ArrayBase<ndarray::ViewRepr<&f64>, ndarray::Dim<[usize; 2]>>, projection: Array1<f64>) -> Array1<f64> { let space_shape = space.shape(); let mut sum = Array1::<f64>::zeros(space_shape[0]); for (i, a) in space.axis_iter(Axis(0)).enumerate() { let proj = &a * &projection; let mut proj_sum = 0.; for c in 0..proj.shape()[0] { proj_sum += proj[c]; } sum[i] = proj_sum; } sum } fn normalization(vector: &mut Array1<f64>) { let norm = vector.dot(vector).sqrt(); for i in vector.iter_mut() { if norm.abs() >= 1e-8 { *i = *i / norm; } } } fn gram_schmidt(x: Array2<f64>) -> Array2<f64> { let shape = x.shape(); let mut o = Array2::<f64>::zeros((shape[0], shape[1])); for i in 0..shape[1] { let vector = x.slice(s![..,i]); let space = o.slice(s![..,..i]); let projection = vector.dot(&space); let mut v2 = &vector - &projection_space(space, projection); normalization(&mut v2); for r in 0..shape[0] { o[(r, i)] = v2[r]; } } o } fn print(vectors: &Array2<f64>) { for row in vectors.genrows() { for c in row { print!("{:>12.5}", c); } println!(); } println!(); } fn main() { let vectors = arr2( &[[1., 1., 2., 0., 1., 1.], [0., 0., 0., 1., 2., 1.], [1., 2., 3., 1., 3., 2.], [1., 0., 1., 0., 1., 1.]]); let orthonormal = gram_schmidt(vectors); println!("orthonormal:"); print(&orthonormal); println!("orthonormal.t().dot(&orthonormal):"); print(&orthonormal.t().dot(&orthonormal)); let matrix = arr2( &[[1., 1., -1.], [1., 2., 1.], [1., 3., 0.]]); println!("QR decomposition:"); let q = gram_schmidt(matrix.clone()); println!("Q:"); print(&q); let r = q.t().dot(&matrix); println!("R:"); print(&r); println!("Q dot R:"); print(&q.dot(&r)); }
use reqwest::Client; use reqwest::StatusCode; use serde::{Deserialize, Serialize}; use std::env; use std::process; use std::time::SystemTime; #[derive(Serialize, Deserialize)] struct RequestBody { time: u128, time_end: u128, is_region: bool, tags: Vec<String>, text: String, } fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 4 { println!("error: not enough arguments"); println!("usage: grafana-notifier <env> <app_name> <version>"); process::exit(1); } let env = &args[1]; let app_name = &args[2]; let version = format!("v{}", &args[3]); let resp = make_request(env, app_name, version); println!("{}", resp); } fn make_request(environ: &str, app_name: &str, version: String) -> String { let tags = vec![ format!("env:{}", environ), "release-notifier".to_string(), app_name.to_string(), ]; let now = get_current_timestamp(); let (key, url) = get_env_config(); let body = RequestBody { time: now, time_end: now, is_region: true, tags, text: format!("Deployed Service: {}\nVersion: {}", app_name, version), }; let client = Client::new(); let result = client.post(&*url).bearer_auth(&key).json(&body).send(); return match result { Ok(resp) => match resp.status() { StatusCode::OK => format!( "successfully notified release {} of {}\n", version, app_name ), s => format!("request was not successful\ncode: {:?}", s), }, Err(err) => format!("error!: {:?}", err), }; } fn get_current_timestamp() -> u128 { return match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) { Ok(n) => n.as_millis(), Err(_) => { println!("error: time before epoch"); process::exit(1); } }; } fn get_env_config() -> (String, String) { let key: String = match env::var("GRAFANA_TOKEN") { Ok(token) => token, Err(_) => { println!("error: GRAFANA_TOKEN not set"); process::exit(1); } }; let url: String = match env::var("GRAFANA_ADDR") { Ok(base_url) => format!("{}/api/annotations", base_url), Err(_) => { println!("error: GRAFANA_ADDR not set"); process::exit(1); } }; return (key, url); }
extern crate byteorder; #[macro_use] extern crate lazy_static; extern crate regex; use std::borrow::Cow; use std::cmp::min; use std::fmt; use std::io::{self, Read, Write}; use std::num::ParseIntError; mod game; pub use game::Game; pub use game::ROM_SIZE; pub mod sections; mod rom_rebuilder; pub use rom_rebuilder::ROMRebuilder; // 1048576 = 2^20 = 1MiB, there's no real good reason behind this choice pub const WRITE_CHUNK_SIZE: usize = 1048576; // 32KiB pub const DEFAULT_ALIGNMENT: u64 = 32 * 1024; pub const MIN_ALIGNMENT: u64 = 4; pub mod paths { pub const APPLOADER_PATH: &'static str = "&&systemdata/Apploader.ldr"; pub const DOL_PATH: &'static str = "&&systemdata/Start.dol"; pub const FST_PATH: &'static str = "&&systemdata/Game.toc"; pub const HEADER_PATH: &'static str = "&&systemdata/ISO.hdr"; } pub fn extract_section( mut iso: impl Read, bytes: usize, mut file: impl Write, ) -> io::Result<()> { let mut buf: [u8; WRITE_CHUNK_SIZE] = [0; WRITE_CHUNK_SIZE]; let mut bytes_left = bytes; while bytes_left > 0 { let bytes_to_read = min(bytes_left, WRITE_CHUNK_SIZE) as u64; let bytes_read = (&mut iso).take(bytes_to_read).read(&mut buf)?; if bytes_read == 0 { break } file.write_all(&buf[..bytes_read])?; bytes_left -= bytes_read; } Ok(()) } pub fn align(n: u64, m: u64) -> u64 { let extra = if n % m == 0 { 0 } else { 1 }; ((n / m) + extra) * m } #[derive(Copy, Clone)] pub enum NumberStyle { Hexadecimal, Decimal, } // This isn't very efficient because the string returned will usually // just get passed to another formatting macro, like println. // The extra string allocation here isn't ideal, but it's not a problem // at the moment. It'll need to be scrapped if this gets used in a place // where it'll be called a lot. pub fn format_u64(num: u64, style: NumberStyle) -> String { match style { NumberStyle::Hexadecimal => format!("{:#x}", num), NumberStyle::Decimal => format!("{}", num), } } pub fn format_usize(num: usize, style: NumberStyle) -> String { match style { NumberStyle::Hexadecimal => format!("{:#x}", num), NumberStyle::Decimal => format!("{}", num), } } pub fn parse_as_u64(text: &str) -> Result<u64, ParseIntError> { let is_hex = text.chars().count() > 2 && (&text[0..2] == "0x" || &text[0..2] == "0X"); if is_hex { u64::from_str_radix(&text[2..], 16) } else { u64::from_str_radix(text, 10) } } pub fn parse_as_usize(text: &str) -> Result<usize, ParseIntError> { let is_hex = text.chars().count() > 2 && (&text[0..2] == "0x" || &text[0..2] == "0X"); if is_hex { usize::from_str_radix(&text[2..], 16) } else { usize::from_str_radix(text, 10) } } pub struct AppError(Cow<'static, str>); impl AppError { pub fn new(msg: impl Into<Cow<'static, str>>) -> AppError { AppError(msg.into()) } } impl fmt::Debug for AppError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl From<io::Error> for AppError { fn from(e: io::Error) -> AppError { AppError::new(e.to_string()) } } pub type AppResult = Result<(), AppError>;
//! Named Window //! //! A widget represent a named window use std::fmt::Debug; use druid::{ widget::{Label, LabelText, LineBreaking, WidgetExt}, LifeCycle, LifeCycleCtx, }; use druid::{ BoxConstraints, Color, Data, Env, Event, EventCtx, LayoutCtx, PaintCtx, Point, Rect, RenderContext, Size, UpdateCtx, Widget, WidgetPod, }; pub struct Named<T: Data + Debug> { inner: WidgetPod<T, Box<dyn Widget<T>>>, label: Box<dyn Widget<T>>, } impl<T: Data + Debug> Widget<T> for Named<T> { fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { self.inner.lifecycle(ctx, event, data, env); self.label.lifecycle(ctx, event, data, env); } fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { self.inner.event(ctx, event, data, env); self.label.event(ctx, event, data, env); } fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { self.inner.update(ctx, data, env); self.label.update(ctx, old_data, data, env); } fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { let size = self.label.layout(ctx, &bc, data, env); self.inner.set_layout_rect(ctx, data, env, Rect::from_origin_size(Point::ORIGIN, size)); let header_offset = size.height; let child_bc = bc.shrink((0.0, header_offset)); let size = self.inner.layout(ctx, &child_bc, data, env); let origin = Point::new(0.0, header_offset); self.inner.set_layout_rect(ctx, data, env, Rect::from_origin_size(origin, size)); // relayout label for compulated width let label_bc = BoxConstraints::new(Size::ZERO, Size::new(size.width, header_offset)); self.label.layout(ctx, &label_bc, data, env); Size::new(size.width, size.height + header_offset) } fn paint(&mut self, paint_ctx: &mut PaintCtx, data: &T, env: &Env) { let size = paint_ctx.size(); paint_ctx.with_save(|paint_ctx| { let rect = Rect::from_origin_size(Point::ORIGIN, size); paint_ctx.fill(rect, &Color::rgb8(0x11, 0x93, 0x92)); }); self.inner.paint(paint_ctx, data, env); self.label.paint(paint_ctx, data, env); } } impl<T: Data + Debug> Named<T> { pub fn new(inner: impl Widget<T> + 'static, label: impl Into<LabelText<T>>) -> impl Widget<T> where T: Data + 'static, { let label = Label::new(label.into()).with_line_break_mode(LineBreaking::Clip).padding(10.0); Named { inner: WidgetPod::new(inner).boxed(), label: Box::new(label) } } }
#[doc = "Register `HASH_CSR52` reader"] pub type R = crate::R<HASH_CSR52_SPEC>; #[doc = "Register `HASH_CSR52` writer"] pub type W = crate::W<HASH_CSR52_SPEC>; #[doc = "Field `CS52` reader - CS52"] pub type CS52_R = crate::FieldReader<u32>; #[doc = "Field `CS52` writer - CS52"] pub type CS52_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>; impl R { #[doc = "Bits 0:31 - CS52"] #[inline(always)] pub fn cs52(&self) -> CS52_R { CS52_R::new(self.bits) } } impl W { #[doc = "Bits 0:31 - CS52"] #[inline(always)] #[must_use] pub fn cs52(&mut self) -> CS52_W<HASH_CSR52_SPEC, 0> { CS52_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "HASH context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hash_csr52::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`hash_csr52::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct HASH_CSR52_SPEC; impl crate::RegisterSpec for HASH_CSR52_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`hash_csr52::R`](R) reader structure"] impl crate::Readable for HASH_CSR52_SPEC {} #[doc = "`write(|w| ..)` method takes [`hash_csr52::W`](W) writer structure"] impl crate::Writable for HASH_CSR52_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets HASH_CSR52 to value 0"] impl crate::Resettable for HASH_CSR52_SPEC { const RESET_VALUE: Self::Ux = 0; }
use serde::{Deserialize, Serialize}; /// The system parameters type returned from contract calls. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SysParams { /// Block gas limit #[serde(rename = "BlockGasLimit")] pub block_gas_limit: u64, /// Transaction gas limit #[serde(rename = "TxGasLimit")] pub tx_gas_limit: u64, /// Is transaction use gas #[serde(rename = "IsTxUseGas")] pub is_tx_use_gas: bool, /// Is produce empty block #[serde(rename = "IsProduceEmptyBlock")] pub is_produce_empty_block: bool, /// Enable deploy #[serde(rename = "EnableDeploy")] pub enable_deploy: bool, }
use { ply_generator_lib::{ V3, print_ply, merge_meshes, negate_z_coord, flip_normals }, simple_tiled_wfc::grid_generation::{WfcModule, WfcContext, WfcContextBuilder}, ron::de::from_reader, crate::{ types::{ControlPoints}, wang_info::{ PTS_FILE, is_north_neighbour, is_south_neighbour, is_west_neighbour, is_east_neighbour } }, bitsetium::Bits128, std::sync::mpsc::channel }; mod wang_info; mod types; mod generators; fn main() { let points: ControlPoints = from_reader(PTS_FILE).expect("failed to deserialize RON file"); wfc_experiment(&points); } fn wfc_experiment(points: &ControlPoints) { let mut tile_indices = Vec::with_capacity(96); let mut modules = Vec::with_capacity(96); for i in 0..96 { let idx = (i as usize) % 32; let height_prev = (i as u16) / 32; let mut tile_id = wang_info::TILE_MASKS[idx] & 0b1_1111_00_00_00_00; tile_id = tile_id | if (wang_info::TILE_MASKS[idx] & wang_info::NW) != 0 { height_prev + 1 } else { height_prev } << 0u16; tile_id = tile_id | if (wang_info::TILE_MASKS[idx] & wang_info::NE) != 0 { height_prev + 1 } else { height_prev } << 2u16; tile_id = tile_id | if (wang_info::TILE_MASKS[idx] & wang_info::SW) != 0 { height_prev + 1 } else { height_prev } << 4u16; tile_id = tile_id | if (wang_info::TILE_MASKS[idx] & wang_info::SE) != 0 { height_prev + 1 } else { height_prev } << 6u16; tile_indices.push(tile_id); } let mut tile_indices_indices = (0..tile_indices.len()) .map(|it| (it, it / 32)) .collect::<Vec<_>>(); for i in (0..3).rev() { let idx = 32 * i; tile_indices_indices[idx + 30] = tile_indices_indices[idx + 15]; tile_indices_indices[idx + 29] = tile_indices_indices[idx + 15]; tile_indices_indices[idx + 28] = tile_indices_indices[idx + 15]; tile_indices_indices[idx + 26] = tile_indices_indices[idx + 15]; tile_indices_indices[idx + 25] = tile_indices_indices[idx + 15]; tile_indices_indices[idx + 24] = tile_indices_indices[idx]; tile_indices_indices[idx + 22] = tile_indices_indices[idx]; tile_indices_indices[idx + 21] = tile_indices_indices[idx]; tile_indices_indices[idx + 20] = tile_indices_indices[idx]; tile_indices_indices[idx + 18] = tile_indices_indices[idx]; tile_indices_indices[idx + 17] = tile_indices_indices[idx]; tile_indices_indices[idx + 16] = tile_indices_indices[idx]; } for i in 0..tile_indices_indices.len() { let mut module: WfcModule<Bits128> = WfcModule::new(); let tile_idx = tile_indices_indices[i].0; let tile = tile_indices[tile_idx]; for j in 0..tile_indices_indices.len() { let other_idx = tile_indices_indices[j].0; let other_rile = tile_indices[other_idx]; if is_north_neighbour(tile, other_rile) { if check_slide_indices_south_north(tile_idx, other_idx) { module.add_north_neighbour(j); } } if is_south_neighbour(tile, other_rile) { if check_slide_indices_south_north(tile_idx, other_idx) { module.add_south_neighbour(j); } } if is_west_neighbour(tile, other_rile) { if check_slide_indices_east_west(tile_idx, other_idx) { module.add_west_neighbour(j); } } if is_east_neighbour(tile, other_rile) { if check_slide_indices_east_west(tile_idx, other_idx) { module.add_east_neighbour(j); } } } modules.push(module); fn check_slide_indices_east_west(tile_idx: usize, other_idx: usize) -> bool { let is_same_idx = tile_idx == other_idx; let is_same_slide = is_same_idx && ( tile_idx == 19 || tile_idx == 31 || tile_idx == 19 + 32 || tile_idx == 31 + 32 || tile_idx == 19 + 64 || tile_idx == 31 + 64 ); let is_opposing_slide = tile_idx == 23 && other_idx == 27 || tile_idx == 27 && other_idx == 23 || tile_idx == 23 + 32 && other_idx == 27 + 32 || tile_idx == 27 + 32 && other_idx == 23 + 32 || tile_idx == 23 + 64 && other_idx == 27 + 64 || tile_idx == 27 + 64 && other_idx == 23 + 64 || tile_idx == 23 && (other_idx == 10 || other_idx == 11 || other_idx == 14) || other_idx == 23 && (tile_idx == 10 || tile_idx == 11 || tile_idx == 14) || tile_idx == 27 && (other_idx == 5 || other_idx == 7 || other_idx == 13) || other_idx == 27 && (tile_idx == 5 || tile_idx == 7 || tile_idx == 13) || tile_idx == 32 + 23 && (other_idx == 32 + 10 || other_idx == 32 + 11 || other_idx == 32 + 14) || other_idx == 32 + 23 && (tile_idx == 32 + 10 || tile_idx == 32 + 11 || tile_idx == 32 + 14) || tile_idx == 32 + 27 && (other_idx == 32 + 5 || other_idx == 32 + 7 || other_idx == 32 + 13) || other_idx == 32 + 27 && (tile_idx == 32 + 5 || tile_idx == 32 + 7 || tile_idx == 32 + 13) || tile_idx == 64 + 23 && (other_idx == 64 + 10 || other_idx == 64 + 11 || other_idx == 64 + 14) || other_idx == 64 + 23 && (tile_idx == 64 + 10 || tile_idx == 64 + 11 || tile_idx == 64 + 14) || tile_idx == 64 + 27 && (other_idx == 64 + 5 || other_idx == 64 + 7 || other_idx == 64 + 13) || other_idx == 64 + 27 && (tile_idx == 64 + 5 || tile_idx == 64 + 7 || tile_idx == 64 + 13); !is_same_slide && !is_opposing_slide } fn check_slide_indices_south_north(tile_idx: usize, other_idx: usize) -> bool { let is_same_idx = tile_idx == other_idx; let is_same_slide = is_same_idx && ( tile_idx == 23 || tile_idx == 27 || tile_idx == 23 + 32 || tile_idx == 27 + 32 || tile_idx == 23 + 64 || tile_idx == 27 + 64 ); let is_opposing_slide = tile_idx == 19 && other_idx == 31 || tile_idx == 31 && other_idx == 19 || tile_idx == 19 + 32 && other_idx == 31 + 32 || tile_idx == 31 + 32 && other_idx == 19 + 32 || tile_idx == 19 + 64 && other_idx == 31 + 64 || tile_idx == 31 + 64 && other_idx == 19 + 64 || tile_idx == 19 && (other_idx == 12 || other_idx == 13 || other_idx == 14) || other_idx == 19 && (tile_idx == 12 || tile_idx == 13 || tile_idx == 14) || tile_idx == 31 && (other_idx == 3 || other_idx == 7 || other_idx == 11) || other_idx == 31 && (tile_idx == 3 || tile_idx == 7 || tile_idx == 11) || tile_idx == 32 + 19 && (other_idx == 32 + 12 || other_idx == 32 + 13 || other_idx == 32 + 14) || other_idx == 32 + 19 && (tile_idx == 32 + 12 || tile_idx == 32 + 13 || tile_idx == 32 + 14) || tile_idx == 32 + 31 && (other_idx == 32 + 3 || other_idx == 32 + 7 || other_idx == 32 + 11) || other_idx == 32 + 31 && (tile_idx == 32 + 3 || tile_idx == 32 + 7 || tile_idx == 32 + 11) || tile_idx == 64 + 19 && (other_idx == 64 + 12 || other_idx == 64 + 13 || other_idx == 64 + 14) || other_idx == 64 + 19 && (tile_idx == 64 + 12 || tile_idx == 64 + 13 || tile_idx == 64 + 14) || tile_idx == 64 + 31 && (other_idx == 64 + 3 || other_idx == 64 + 7 || other_idx == 64 + 11) || other_idx == 64 + 31 && (tile_idx == 64 + 3 || tile_idx == 64 + 7 || tile_idx == 64 + 11); !is_same_slide && !is_opposing_slide } } let w = 36; let h = 36; let (tx, rc) = channel(); let mut wfc_context: WfcContext<Bits128> = WfcContextBuilder::new(&modules, w, h).build(); wfc_context.set_module(0, 0, 0); wfc_context.set_module(0, 35, 0); wfc_context.set_module(35, 0, 0); wfc_context.set_module(35, 35, 0); wfc_context.set_module(17, 17, modules.len()-1); wfc_context.collapse(100, tx.clone()); let wfc_result = rc.recv().unwrap(); match wfc_result { Ok(results) => { let mut meshes = Vec::with_capacity(w * h); let mut offset = 0; for result_id in results { let x = ((offset % w) * 2) as f32; let z = ((offset / w) as f32) * -2.0; let y = tile_indices_indices[result_id].1 as f32; let origin = V3 { x, y, z }; let true_id = tile_indices_indices[result_id].0; meshes.push(wang_info::TILE_DEFINITIONS[true_id % 32].gen_mesh(&points, origin, 0.87)); offset += 1; } let mut merged = merge_meshes(&meshes); negate_z_coord(&mut merged); flip_normals(&mut merged); let printed = print_ply(&merged, Some("test")); print!("{}", &printed); } Err(_) => {} } }
//! Version Output use libwgetj; include!(concat!(env!("OUT_DIR"), "/version.rs")); #[cfg(unix)] /// Generate the verbose version string. fn verbose_ver() -> String { format!("\x1b[32;1mlibwgetj {}\x1b[0m ({} {}) (built {})\ncommit-hash: {}\ncommit-date: \ {}\nbuild-date: {}\nhost: {}\nrelease: {}\n\n{}", semver(), short_sha(), commit_date(), short_now(), sha(), commit_date(), short_now(), target(), semver(), libwgetj::version(true)) } #[cfg(windows)] /// Generate the verbose version string. fn verbose_ver() -> String { format!("libwgetj {} ({} {}) (built {})\ncommit-hash: {}\ncommit-date: {}\nbuild-date: \ {}\nhost: {}\nrelease: {}\n\n{}", semver(), short_sha(), commit_date(), short_now(), sha(), commit_date(), short_now(), target(), semver(), libwgetj::version(true)) } #[cfg(unix)] /// Generate the version string. fn ver() -> String { format!("\x1b[32;1mlibwgetj {}\x1b[0m ({} {}) (built {})\n{}", semver(), short_sha(), commit_date(), short_now(), libwgetj::version(false)) } #[cfg(windows)] /// Generate the version string. fn ver() -> String { format!("libwgetj {}[0m ({} {}) (built {})\n{}", semver(), short_sha(), commit_date(), short_now(), libwgetj::version(false)) } /// Generate a verbose or more terse version string. pub fn version(verbose: bool) -> String { if verbose { verbose_ver() } else { ver() } }
// Pasts // // Copyright (c) 2019-2020 Jeron Aldaron Lau // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // https://apache.org/licenses/LICENSE-2.0>, or the Zlib License, <LICENSE-ZLIB // or http://opensource.org/licenses/Zlib>, at your option. This file may not be // copied, modified, or distributed except according to those terms. use core::{ future::Future, pin::Pin, task::{Context, Poll}, task::{RawWaker, RawWakerVTable, Waker}, }; /// An executor for `Future`s. #[allow(unsafe_code)] pub trait Executor: 'static + Send + Sync + Sized { /// Cause `wait_for_event()` to return. /// /// # Safety /// This method is marked `unsafe` because it must only be called from a /// `Waker`. This is guaranteed by the `block_on()` method. unsafe fn trigger_event(&self); /// Blocking wait until an event is triggered with `trigger_event`. This /// function should put the current thread or processor to sleep to save /// power consumption. /// /// # Safety /// This function should only be called by one executor. On the first call /// to this method, all following calls to `is_used()` should return `true`. /// This method is marked `unsafe` because only one thread and one executor /// can call it (ever!). This is guaranteed by the `block_on()` method. unsafe fn wait_for_event(&self); /// Should return true if `wait_for_event` has been called, false otherwise. fn is_used(&self) -> bool; /// Run a future to completion on the current thread. This will cause the /// current thread to block. #[allow(unsafe_code)] #[inline] fn block_on<F: Future>(&'static self, mut f: F) -> <F as Future>::Output { if self.is_used() { panic!("Can't reuse an executor!"); } // unsafe: f can't move after this, because it is shadowed let mut f = unsafe { Pin::new_unchecked(&mut f) }; // Go through the loop each time it wakes up, break when Future ready. let waker = waker(self); let context = &mut Context::from_waker(&waker); 'executor: loop { unsafe { self.wait_for_event() }; if let Poll::Ready(ret) = f.as_mut().poll(context) { break 'executor ret; } } } } // Safe wrapper around `Waker` API to get a `Waker` from an `Interrupt`. #[inline] #[allow(unsafe_code)] fn waker<E: Executor>(interrupt: *const E) -> Waker { #[inline] unsafe fn clone<E: Executor>(data: *const ()) -> RawWaker { RawWaker::new( data, &RawWakerVTable::new(clone::<E>, wake::<E>, wake::<E>, drop::<E>), ) } #[inline] unsafe fn wake<E: Executor>(data: *const ()) { E::trigger_event(&*(data as *const E)); } #[inline] unsafe fn drop<E: Executor>(_data: *const ()) {} unsafe { Waker::from_raw(RawWaker::new( interrupt as *const (), &RawWakerVTable::new(clone::<E>, wake::<E>, wake::<E>, drop::<E>), )) } }
#[cfg(unix)] use cluFlock::{ExclusiveFlock, FlockLock}; use reqwest::Client; use reqwest::header::{USER_AGENT, CONTENT_DISPOSITION}; use reqwest::Url; use std::fs::File; use std::io; use std::path::Path; #[cfg(windows)] use std::path::{Component, Prefix, PathBuf}; #[cfg(unix)] pub fn lock_process_or_wait<'a>(lock_file: &'a File) -> io::Result<FlockLock<&'a File>> { match lock_file.try_lock() { Ok(lock) => { trace!("aquired process lock."); Ok(lock) } Err(_) => { debug!("progress lock already aquired."); debug!("wait for other process to finish."); let lock = lock_file.wait_lock()?; Ok(lock) } //Err(err) => Err(err), } } #[cfg(windows)] pub fn lock_process_or_wait(_: &File) -> io::Result<()> { Ok(()) } #[cfg(windows)] fn get_path_prefix(path: &Path) -> Prefix { match path.components().next().unwrap() { Component::Prefix(prefix_component) => prefix_component.kind(), _ => panic!(), } } #[cfg(windows)] pub fn prepend_long_path_support<P:AsRef<Path>>(path:P) -> PathBuf { use std::ffi::OsString; let path = path.as_ref(); if (path.has_root() && !path.is_absolute()) || (path.is_absolute() && !get_path_prefix(path).is_verbatim()) { trace!(r#"prepend path with \\?\"#); let mut components = path.components(); let mut new_prefix = OsString::new(); let mut new_path = PathBuf::new(); new_prefix.push(r"\\?\"); new_prefix.push(components.next().unwrap()); new_path.push(new_prefix); while let Some(component) = components.next() { new_path.push(component); } new_path } else { path.to_path_buf() } } pub struct UrlUtils {} impl UrlUtils { fn get_final_file_name_from_url(url: &Url) -> io::Result<String> { let client = Client::new(); let response = client .head(url.clone()) .header(USER_AGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36") .send() .map_err(|err| { io::Error::new(io::ErrorKind::Other, err) })?; response .headers() .get(CONTENT_DISPOSITION) .and_then(|disposition| { if disposition.is_empty() { None } else { Some(disposition) } }) .and_then(|disposition| { let disposition = disposition.to_str().ok()?; trace!("disposition header value: {}", disposition); let parts = disposition.split(';'); parts .map(|s| s.trim()) .fold(None, { |filename: Option<String>, part| { if part.starts_with("filename=") { let part = part.replace("filename=", ""); let part = &part.trim_start_matches('"').trim_end_matches('"'); Some(part.to_string()) } else { filename } } }) .map(|name| { trace!("after header disposition replacement"); trace!("{}", &name); name }) }) .or_else(|| { response .url() .as_str() .rsplit('/') .next() .map(|s| s.to_string()) }) .ok_or_else(|| { io::Error::new(io::ErrorKind::InvalidData, "unable to parse final filename") }) } pub fn get_file_name_from_url(url: &Url) -> io::Result<String> { let test_path = Path::new(url.as_ref()); if test_path.extension().is_some() { url.as_str() .rsplit('/') .next() .map(|s| s.to_string()) .ok_or_else(|| { io::Error::new( io::ErrorKind::NotFound, format!("unable to read filename from url {}", url), ) }) } else { Self::get_final_file_name_from_url(url) } } } #[cfg(test)] mod tests { use super::*; use reqwest::Url; #[test] fn parse_file_name_from_url_with_file_name_part() { let url = Url::parse("https://beta.unity3d.com/download/8ea4afdbfa47/MacEditorTargetInstaller/UnitySetup-Android-Support-for-Editor-2019.3.0a8.pkg").unwrap(); assert_eq!(UrlUtils::get_file_name_from_url(&url).unwrap(), "UnitySetup-Android-Support-for-Editor-2019.3.0a8.pkg".to_string()); } #[test] fn parse_file_name_from_url_without_file_name_part_and_content_disposition() { let url = Url::parse("https://go.microsoft.com/fwlink/?linkid=2086937").unwrap(); assert!(UrlUtils::get_file_name_from_url(&url).unwrap().starts_with("visualstudioformac-")); } #[test] fn parse_file_name_from_url_without_file_name_part_and_content_disposition2() { let url = Url::parse("https://go.microsoft.com/fwlink/?linkid=2087047").unwrap(); assert!(UrlUtils::get_file_name_from_url(&url).unwrap().starts_with("monoframework-mdk-")); } #[test] fn parse_file_name_from_url_without_file_name_part_and_content_disposition3() { let url = Url::parse("https://new-translate.unity3d.jp/v1/live/54/2019.3/zh-hant").unwrap(); assert_eq!(UrlUtils::get_file_name_from_url(&url).unwrap(), "zh-hant.po".to_string()); } #[cfg(windows)] #[test] fn prepend_long_path_prefix_when_missing() { let path = Path::new(r#"c:/path/to/some/file.txt"#); let new_path = prepend_long_path_support(&path); assert!(new_path.to_string_lossy().starts_with(r#"\\?\c:\"#)); } #[cfg(windows)] #[test] fn prepend_long_path_prefix_when_missing2() { let path = Path::new(r#"/path/to/some/file.txt"#); let new_path = prepend_long_path_support(&path); assert!(new_path.to_string_lossy().starts_with(r#"\\?\"#)); } #[cfg(windows)] #[test] fn prepend_long_path_changes_path_separator() { let path = Path::new(r#"c:/path/to/some/file.txt"#); let new_path = prepend_long_path_support(&path); assert_eq!(new_path.to_string_lossy() , r#"\\?\c:\path\to\some\file.txt"#); } #[cfg(windows)] #[test] fn prepend_long_path_prefix_only_absolute_paths() { let path = Path::new(r#"./some/file.txt"#); let new_path = prepend_long_path_support(&path); assert!(!new_path.to_string_lossy().starts_with(r#"\\?\"#)); } #[cfg(windows)] #[test] fn prepend_long_path_prefix_returns_same_path_when_already_prefixed() { let path = Path::new(r#"\\?\c:/path/to/some/file.txt"#); let new_path = prepend_long_path_support(&path); assert_eq!(path.to_str(), new_path.to_str()); } }
use core::slice; use std::{collections::HashMap, time::Duration}; use futures::Future; use http::{header::AUTHORIZATION, Method, Request, StatusCode, Uri}; use hyper::{client::HttpConnector, Body, Client}; use metrics::counter; use serde::Deserialize; use tokio::{ sync::mpsc::{self, Receiver, Sender}, time::timeout, }; use tracing::{debug, info}; use super::{AckSettings, SPLUNK_HEC_CHANNEL_HEADER}; type AckId = u64; #[derive(thiserror::Error, Debug, Clone, Copy)] pub enum Error {} #[derive(Debug, Clone)] pub(crate) enum Channel { /// Variant that communicates acks to underlying AckService. Ack { id: String, tx: Sender<AckId> }, /// Variant that does no ack'ing. NoAck { id: String }, } impl Channel { pub(crate) fn id(&self) -> &str { match self { Self::Ack { ref id, .. } | Self::NoAck { ref id, .. } => id, } } pub(crate) async fn send<Fut>(&self, msg: Fut) where Fut: Future<Output = AckId>, { match self { Self::NoAck { .. } => (), Self::Ack { tx, .. } => tx .send(msg.await) .await .expect("receiver dropped unexpectedly"), } } } /// Splunk HEC channels #[derive(Debug)] pub(crate) struct Channels { channels: Vec<Channel>, } impl Channels { pub(crate) fn new(num_channels: u16) -> Self { let channels = (0..num_channels) .map(|i| Channel::NoAck { id: format!( "{}-1111-1111-1111-111111111111", 10_000_000_u32 + u32::from(i) ), }) .collect::<Vec<Channel>>(); Self { channels } } pub(crate) fn iter(&self) -> Iter<'_, Channel> { Iter(self.channels.iter()) } pub(crate) fn enable_acknowledgements( &mut self, ack_uri: Uri, token: String, ack_settings: AckSettings, ) { let client: Client<HttpConnector, Body> = Client::builder() .retry_canceled_requests(false) .set_host(false) .build_http(); let ack_service = AckService { ack_uri, token, client, ack_settings, }; for channel in &mut self.channels { match channel { Channel::Ack { .. } => unreachable!(), Channel::NoAck { id } => { let (tx, rx) = mpsc::channel::<AckId>(1_000_000); tokio::spawn(ack_service.clone().spin(id.clone(), rx)); *channel = Channel::Ack { id: id.clone(), tx }; } } } } } #[derive(Clone)] pub(crate) struct Iter<'a, V>(slice::Iter<'a, V>); impl<'a, V> Iterator for Iter<'a, V> { type Item = &'a V; fn next(&mut self) -> Option<Self::Item> { self.0.next() } } #[derive(Debug, Clone)] /// Responsible for querying /services/collector/ack /// periodically. [`AckService`] is bounded to a single Channel -- via the /// `channel_id` parameter on [`AckService::spin`] -- and is created by /// Channel. That is, this service is purely an implementation detail. struct AckService { pub(crate) ack_uri: Uri, pub(crate) token: String, pub(crate) client: Client<HttpConnector, Body>, pub(crate) ack_settings: AckSettings, } impl AckService { /// Spawn a tokio task that will continuously query /// to check on a particular Splunk channel's ack id statuses. The task /// receives new ack ids from [`super::worker::Worker`] pub(crate) async fn spin<'a>(self, channel_id: String, mut ack_rx: Receiver<AckId>) { let mut ack_ids: HashMap<AckId, u64> = HashMap::new(); let mut interval = tokio::time::interval(Duration::from_secs( self.ack_settings.ack_query_interval_seconds, )); let retries = self.ack_settings.ack_timeout_seconds / self.ack_settings.ack_query_interval_seconds; loop { tokio::select! { resp = ack_rx.recv() => { match resp { None => { info!("AckService receiver closed, shutting down"); return; } Some(ack_id) => { ack_ids.insert(ack_id, retries); } } } _ = interval.tick(), if !ack_ids.is_empty() => { if ack_ids.is_empty() { debug!("tick expired with no acks"); } else { let body = Body::from( serde_json::json!({ "acks": ack_ids.keys().collect::<Vec<&u64>>() }) .to_string(), ); let request: Request<Body> = Request::builder() .method(Method::POST) .uri(self.ack_uri.clone()) .header(AUTHORIZATION, format!("Splunk {}", self.token)) .header(SPLUNK_HEC_CHANNEL_HEADER, channel_id.clone()) .body(body) .unwrap(); let work = ack_request(self.client.clone(), request, channel_id.clone(), &mut ack_ids); if let Err(_err) = timeout(Duration::from_secs(1), work).await { counter!("ack_request_timeout", 1); } } } } } } } async fn ack_request( client: Client<HttpConnector>, request: Request<Body>, channel_id: String, ack_ids: &mut HashMap<AckId, u64>, ) { match client.request(request).await { Ok(response) => { let (parts, body) = response.into_parts(); let status = parts.status; counter!("ack_status_request_ok", 1, "channel_id" => channel_id.clone(), "status" => status.to_string()); if status == StatusCode::OK { let body = hyper::body::to_bytes(body).await.unwrap(); let ack_status = serde_json::from_slice::<HecAckStatusResponse>(&body).unwrap(); let mut ack_ids_acked: u32 = 0; // Remove successfully acked ack ids for acked_ack_id in ack_status .acks .into_iter() .filter_map(|(ack_id, acked)| if acked { Some(ack_id) } else { None }) { ack_ids.remove(&acked_ack_id); ack_ids_acked += 1; } counter!("ack_ids_acked", u64::from(ack_ids_acked), "channel_id" => channel_id.clone()); // For all remaining ack ids, decrement the retries count, // removing ack ids with no retries left let mut timed_out_ack_ids = Vec::new(); for (ack_id, retries) in ack_ids.iter_mut() { match retries.checked_sub(1) { None => timed_out_ack_ids.push(*ack_id), Some(r) => *retries = r, } } counter!("ack_ids_dropped", timed_out_ack_ids.len() as u64, "channel_id" => channel_id.clone()); for timed_out_ack_id in timed_out_ack_ids { ack_ids.remove(&timed_out_ack_id); } } } Err(err) => { counter!("ack_status_request_failure", 1, "channel_id" => channel_id.clone(), "error" => err.to_string()); } } } #[derive(Deserialize, Debug)] struct HecAckStatusResponse { acks: HashMap<AckId, bool>, }
#![deny(unsafe_code)] #![type_length_limit = "1664759"] #![feature( trait_alias, option_flattening, // Converts Option<Option<Item>> into Option<Item> TODO: Remove this once this feature becomes stable )] #[macro_use] extern crate serde_derive; #[macro_use] extern crate log; pub mod assets; pub mod clock; pub mod comp; pub mod effect; pub mod event; pub mod figure; pub mod msg; pub mod npc; pub mod ray; pub mod state; pub mod sys; pub mod terrain; pub mod util; pub mod vol; pub mod volumes; /// The networking module containing high-level wrappers of `TcpListener` and `TcpStream` (`PostOffice` and `PostBox` respectively) and data types used by both the server and client. /// # Examples /// ``` /// use std::net::SocketAddr; /// use veloren_common::net::{PostOffice, PostBox}; /// /// let listen_addr = SocketAddr::from(([0, 0, 0, 0], 12345u16)); /// let conn_addr = SocketAddr::from(([127, 0, 0, 1], 12345u16)); /// /// let mut server: PostOffice<String, String> = PostOffice::bind(listen_addr).unwrap(); /// let mut client: PostBox<String, String> = PostBox::to(conn_addr).unwrap(); /// std::thread::sleep(std::time::Duration::from_millis(100)); /// /// let mut scon = server.new_postboxes().next().unwrap(); /// std::thread::sleep(std::time::Duration::from_millis(100)); /// /// scon.send_message(String::from("foo")); /// client.send_message(String::from("bar")); /// std::thread::sleep(std::time::Duration::from_millis(100)); /// /// assert_eq!("foo", client.next_message().unwrap()); /// assert_eq!("bar", scon.next_message().unwrap()); /// ``` pub mod net; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ChatType { Broadcast, Chat, GameUpdate, Private, Tell, Say, Group, Faction, Meta, Kill, }
use std::{fs, hash::Hasher, io::Read, path::Path}; use anyhow::Result; use crate::wallpaper::Wallpaper; use crate::{cache::Cache, wallpaper::unpack}; /// Unpacks HEIF files and loads them into `Wallpaper` structs, while transparently caching them. #[derive(Debug)] pub struct WallpaperLoader { cache: Cache, } impl WallpaperLoader { pub fn new() -> Self { WallpaperLoader { cache: Cache::find("wallpapers"), } } /// Load given file into `Wallpaper` struct. /// /// Each loaded file is persistently cached and will be loaded from cache if requested again. pub fn load<P: AsRef<Path>>(&mut self, path: P) -> Wallpaper { let hash = hash_file(&path).expect("wallpaper hashing failed"); let cache_dir = self.cache.entry(&hash); if cache_dir.read_dir().unwrap().next().is_none() { unpack(&path, &cache_dir).expect("wallpaper unpacking failed"); } Wallpaper::load(&cache_dir).expect("malformed wallpaper cache") } } fn hash_file<P: AsRef<Path>>(path: P) -> Result<String> { const BUFFER_LEN: usize = 1024; let mut buffer = [0u8; BUFFER_LEN]; let mut file = fs::File::open(&path)?; let mut hasher = seahash::SeaHasher::new(); loop { let read_count = file.read(&mut buffer)?; hasher.write(&buffer[..read_count]); if read_count != BUFFER_LEN { break; } } let hash_bytes = hasher.finish(); Ok(format!("{hash_bytes:x}")) }
use std::env; use sidekiq::{Client, ClientOpts, JobOpts, Job}; use bson::ordered::{ OrderedDocument }; use r2d2_redis::{redis, RedisConnectionManager}; use r2d2_redis::r2d2::{Pool}; use std::error::Error; pub struct Notifier { client: Client } impl Notifier { pub fn new() -> Self { let client_opts = ClientOpts { namespace: None, ..Default::default() }; let redis_url = env::var("REDIS_URL_ENV").unwrap().to_string(); let url = redis::parse_redis_url(&redis_url).unwrap(); let manager = RedisConnectionManager::new(url).unwrap(); let redis_pool = Pool::new(manager).map_err(|err| err.description().to_string()); Notifier { client: Client::new(redis_pool.unwrap(), client_opts) } } pub fn connect(&self) { if let Err(err) = self.client.redis_pool.get() { panic!("Cannot create thread to RedisPool: {}", err) } } pub fn publish(&self, value: &OrderedDocument) { let job_args = json!(value); let job_options = JobOpts { queue: "notification".to_string(), ..Default::default() }; let job = Job::new("ChatNotifier".to_string(), vec![job_args], job_options); if let Err(err) = self.client.push(job) { error!("SidekiqClient push failed: {}", err); } } }
use lspower::jsonrpc::{Error, ErrorCode}; #[derive(Debug)] pub enum LspError { InternalError(String), LockNotAcquired, FileNotFound(String), InvalidArguments(Vec<serde_json::value::Value>), InvalidCommand(String), CompositionNotFound(lspower::lsp::Url), } impl From<LspError> for Error { fn from(error: LspError) -> Self { match error { LspError::InternalError(error) => Error { code: ErrorCode::InternalError, message: error, data: None, }, LspError::LockNotAcquired => Error { code: ErrorCode::InternalError, message: "Could not acquire lock".into(), data: None, }, LspError::FileNotFound(filename) => Error { code: ErrorCode::InvalidParams, message: format!("File not fiend: {}", filename), data: None, }, LspError::InvalidArguments(value) => Error { code: ErrorCode::InvalidParams, message: format!( "Invalid parameters supplied: {:?}", value ), data: None, }, LspError::InvalidCommand(command) => Error { code: ErrorCode::InvalidParams, message: format!( "Unknown command execution: {}", command ), data: None, }, LspError::CompositionNotFound(uri) => Error { code: ErrorCode::InvalidParams, message: format!( "Composition not found for uri: {}", uri ), data: None, }, } } }
//! # Logistic regression //! //! `logistic_regression` provides tools to build and run //! logistic regression models. extern crate ndarray; extern crate ndarray_linalg; use ndarray::{ Array, Array1, Array2, ArrayBase, Data, Ix1, Ix2, NdFloat, s, }; use ndarray_linalg::solve::Inverse; use crate::classification::{ Classification, ClassLabel, ClassProbability, Optimize, }; use std::error::Error; /// Basic binary classification logistic regression model /// /// A bias feature is assumed to be the first feature in /// functions where a bias exists. pub struct LogisticRegression<T: NdFloat> { pub coefficients: Array1<T>, } /// Simple function to classify based on threshold. fn convert_proba_to_class<T: NdFloat>(x: T, threshold: T) -> ClassLabel { if x > threshold { 1 } else { 0 } } impl<T: NdFloat> Classification for LogisticRegression<T> { type DataType = T; /// Predict the clas label. fn predict<S>(&self, inputs: &ArrayBase<S, Ix2>) -> Array1<ClassLabel> where S: Data<Elem = Self::DataType> { let threshold = T::from(0.5).unwrap(); let probas = self.predict_proba(inputs); let proba_slice = probas.slice(s![.., 1]); proba_slice.mapv(|a| convert_proba_to_class(a, threshold)) } } impl<T: NdFloat> ClassProbability for LogisticRegression<T> { /// Predict the probabilities for each class. fn predict_proba<S>(&self, inputs: &ArrayBase<S, Ix2>) -> Array2<T> where S: Data<Elem = T> { let one = T::from(1.0).unwrap(); let length = inputs.shape()[0]; let neglogits = -inputs.dot(&self.coefficients); let probabilities = neglogits.mapv(|a| one / (one + a.exp())); let mut results = Array2::zeros((length, 2)); results.slice_mut(s![.., 1]).assign(&probabilities); let inverse_probabilities = probabilities.mapv(|a| one - a); results.slice_mut(s![.., 0]).assign(&inverse_probabilities); results } } /// A solver using a naive implementation of Newton's method. /// /// Be very careful with this solver since results can be very unstable /// if bad initial conditions are chosen. /// This is likely an effect of the disappearing gradients problem /// for the logistic function. This will tend to drive the bias toward /// extremely large values. /// /// Currently, L2 regularization can be used. L1 regularization will also /// likely be implemented in the near future. /// /// The model makes use of directly inverting the Hessian of the log loss /// and so could be a big performance hit if large numbers of features are /// used. struct SimpleNewtonsMethodOptimizer { number_of_iterations: usize, l2_strength: f64, regularize_bias: bool, } impl Optimize for SimpleNewtonsMethodOptimizer { type ModelType = LogisticRegression<f64>; /// Optimize the model. fn optimize<S1, S2, S3>( &self, inputs: &ArrayBase<S1, Ix2>, outputs: &ArrayBase<S2, Ix1>, _weights: Option<&ArrayBase<S3, Ix1>>, model: &mut Self::ModelType, ) -> Result<(), Box<dyn Error>> where S1: Data<Elem = f64>, S2: Data<Elem = ClassLabel>, S3: Data<Elem = f64> { let float_outputs = outputs.mapv(|a| a as f64); let size = inputs.shape()[0]; let size_scale = 1.0 / (inputs.shape()[0] as f64); let mut l2_mask = self.l2_strength * Array::ones((model.coefficients.shape()[0],)); if !self.regularize_bias { l2_mask[0] = 0.0; } let l2_weight_hessian = Array::diag(&l2_mask); let ones: Array1::<f64> = Array::ones(size); // TODO: Clean up this code - probably some can be combined. for _iter in 1..self.number_of_iterations { let predictions = model.predict_proba(inputs); let predictions = predictions.slice(s![.., 1]); let diff = &float_outputs - &predictions; let gradients = - size_scale * inputs.t().dot(&diff) + &l2_mask * &model.coefficients; let inv_predictions = &ones - &predictions; let hessian_weight = &inv_predictions * &predictions; let hessian_weight = hessian_weight.into_shape((size, 1))?; let weighted_inputs = inputs * &hessian_weight; let transformed_inputs = inputs.t().dot(&weighted_inputs); // Note: Will be a bottleneck when large numbers of features are chosen let inv_hessian = (size_scale * &transformed_inputs + l2_weight_hessian).inv()?; model.coefficients = &model.coefficients - &inv_hessian.dot(&gradients); } Ok(()) } } #[cfg(test)] mod tests { extern crate netlib_src; use super::*; use ndarray::array; #[test] fn test_logistic_regression_probabilities() { let model = LogisticRegression::<f64> { coefficients: array![1.0, 2.0], }; let data = array![[0., 0.], [0., 1.], [1., 0.], [1., 1.], [0., -1.]]; let prob2 = 1. / (1. + (-2_f64).exp()); let prob3 = 1. / (1. + (-1_f64).exp()); let prob4 = 1. / (1. + (-3_f64).exp()); let prob5 = 1. / (1. + (2_f64).exp()); let expected_results = array![ [0.5, 0.5], [1. - prob2, prob2], [1. - prob3, prob3], [1. - prob4, prob4], [1. - prob5, prob5], ]; let result_probs = model.predict_proba(&data); let differences = expected_results - result_probs; let epsilon = 1e-8; let error = differences.mapv(|a| a.abs()).sum(); assert!(error < epsilon); } #[test] fn test_logistic_regression_predictions() { let model = LogisticRegression::<f64> { coefficients: array![1.0, 2.0], }; let data = array![ [0., 0.], [0., 1.], [1., 0.], [1., 1.], [0., -1.], [-1., 0.], [-1., -1.] ]; let expected_results = array![0, 1, 1, 1, 0, 0, 0]; let results = model.predict(&data); assert_eq!(expected_results, results); } #[test] fn test_newtons_method_optimization() { let mut model = LogisticRegression::<f64> { coefficients: array![0.0, 0.0], }; let data: Array2::<f64> = array![ [1.0, 0.0], [1.0, 0.0], [1.0, 0.0], [1.0, 0.0], [1.0, 0.0], [1.0, 0.25], [1.0, 0.25], [1.0, 0.25], [1.0, 0.25], [1.0, 0.25], [1.0, 0.5], [1.0, 0.5], [1.0, 0.5], [1.0, 0.5], [1.0, 0.5], [1.0, 0.75], [1.0, 0.75], [1.0, 0.75], [1.0, 0.75], [1.0, 0.75], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0], ]; let outputs: Array1::<usize> = array![ 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, ]; // Should figure out how to get the type to infer correctly let weights: Option<&Array1::<f64>> = None; let optimizer = SimpleNewtonsMethodOptimizer { number_of_iterations: 100, l2_strength: 0.02, regularize_bias: false, }; optimizer.optimize(&data, &outputs, weights, &mut model) .expect("Could not optimize!"); let expected_coefficients = array![-0.585770, 2.08941]; let epsilon = 1e-5; let differences = expected_coefficients - model.coefficients; let error = differences.mapv(|a| a.abs()).sum(); assert!(error < epsilon); } }
use std::{cell::RefCell, rc::Rc}; use apllodb_storage_engine_interface::StorageEngine; use crate::{ access_methods::{ with_db_methods_impl::WithDbMethodsImpl, with_tx_methods_impl::WithTxMethodsImpl, without_db_methods_impl::WithoutDbMethodsImpl, }, sqlite::sqlite_resource_pool::{db_pool::SqliteDatabasePool, tx_pool::SqliteTxPool}, }; /// Storage engine implementation. #[derive(Clone, Debug, Default)] pub struct ApllodbImmutableSchemaEngine { db_pool: Rc<RefCell<SqliteDatabasePool>>, tx_pool: Rc<RefCell<SqliteTxPool>>, } impl StorageEngine for ApllodbImmutableSchemaEngine { type WithoutDb = WithoutDbMethodsImpl; type WithDb = WithDbMethodsImpl; type WithTx = WithTxMethodsImpl; fn without_db(&self) -> WithoutDbMethodsImpl { WithoutDbMethodsImpl::new(self.db_pool.clone()) } fn with_db(&self) -> WithDbMethodsImpl { WithDbMethodsImpl::new(self.db_pool.clone(), self.tx_pool.clone()) } fn with_tx(&self) -> WithTxMethodsImpl { WithTxMethodsImpl::new(self.db_pool.clone(), self.tx_pool.clone()) } }
use math; pub fn runner() { let a: [u64; 2] = [13195, 600851475143]; for element in a.iter() { println!( "lpf of {} is {}", *element, calculate_lpf(*element) ); } } pub fn calculate_lpf(n: u64) -> u64 { let root = (n as f64).sqrt(); let root = math::round::ceil(root, 0) as u64; let mut counter = root; while counter >= 2 { if n % counter == 0 && is_prime(counter) == true { break; } counter -= 1; } return counter; } pub fn is_prime(n: u64) -> bool { let root = (n as f64).sqrt(); let root = math::round::floor(root, 0) as u64; let mut counter = 2; let mut flag = true; while counter <= root { if n % counter == 0 { flag = false; break; } counter += 1; } return flag; }
#[macro_use] extern crate actix_web; use std::{thread, time}; use std::{env, io}; use std::borrow::Borrow; use std::sync::mpsc; use actix_rt::System; use actix_web::{ App, error, Error, guard, HttpRequest, HttpResponse, HttpServer, middleware, Result, web, }; use actix_web::dev::Server; use actix_web::http::{header, Method, StatusCode}; use bucket::S3::{get_file_content, put_file_content}; use bytes::{Buf, Bytes, BytesMut}; use dotenv; use futures::TryStreamExt; use rusoto_core::Region; use rusoto_s3::{GetObjectRequest, S3, S3Client}; use rusoto_sqs::{CreateQueueRequest, DeleteMessageRequest, ReceiveMessageRequest, Sqs, SqsClient}; use serde::Deserialize; use serde_json::{json, Value}; use PostDocument::Post::Post; #[get("/{name}")] async fn get_doc_content(doc_name: web::Path<(String)>) -> Result<HttpResponse> { let document_name = doc_name.into_inner(); let file_content = get_file_content(document_name); Ok(HttpResponse::build(StatusCode::OK) .content_type("application/json; charset=utf-8") .body(file_content.await)) } #[post("/")] async fn create_doc(document_content: web::Json<Post>, ) -> Result<String> { let content = document_content.0; Ok(put_file_content(content).await) } fn run_app(tx: mpsc::Sender<Server>) -> std::io::Result<()> { let mut sys = System::new("server"); // srv is server controller type, `dev::Server` let srv = HttpServer::new(|| { App::new() .service(get_doc_content) .service(create_doc) .wrap(middleware::Logger::default()) }).bind("127.0.0.1:8000")? .run(); // send server controller to main thread let _ = tx.send(srv.clone()); // run future sys.block_on(srv) } #[actix_rt::main] async fn main() -> std::io::Result<()> { dotenv::dotenv().ok(); let qpath = env::var("qpath").unwrap(); env_logger::init(); let (tx, rx) = mpsc::channel(); println!("START SERVER"); thread::spawn(move || { let _ = run_app(tx); }); let sqs = SqsClient::new( Region::CaCentral1 ); let mut req = ReceiveMessageRequest::default(); req.queue_url = qpath.to_string(); loop { let response = sqs.receive_message(req.clone()).await.unwrap(); let messages = response.messages.unwrap_or_default(); if !messages.is_empty() { for (i, x) in messages.iter().enumerate() { let body = x.body.clone(); println!("{}", body.unwrap()); let mut del_req = DeleteMessageRequest::default(); del_req.queue_url = qpath.to_string(); del_req.receipt_handle = x.receipt_handle.clone().unwrap(); println!("{}", x.message_id.clone().unwrap()); sqs.delete_message(del_req); } } } }
use std::collections::{HashMap}; use super::hash::{H256}; use super::block::{Block, Header}; use super::blockchain::{BlockChain}; use std::sync::{Arc, Mutex}; use std::sync::mpsc::{self}; use std::collections::{HashSet, VecDeque}; use super::contract::interface::{Message, Handle, Answer}; use web3::types::{TransactionReceipt}; use super::contract::interface::Response as ContractResponse; use crossbeam::channel::{self, Sender}; use super::scheduler::{Token}; use super::cmtda::Block as CMTBlock; use super::cmtda::Transaction; use super::cmtda::H256 as CMTH256; use super::cmtda::{BlockHeader, HEADER_SIZE, read_codes}; use chain::decoder::{Code, Decoder, TreeDecoder, CodingErr, IncorrectCodingProof}; use chain::decoder::{Symbol}; use chain::constants::{BLOCK_SIZE, BASE_SYMBOL_SIZE, RATE}; use primitives::bytes::{Bytes}; use ser::{deserialize, serialize}; use std::net::{SocketAddr}; use rand::Rng; use std::time::{SystemTime, UNIX_EPOCH}; use merkle; use ring::digest::{Algorithm, Context, SHA256}; use merkle::{Hashable, MerkleTree, Proof}; use std::fs::File; use std::io::{BufRead, BufReader}; use crate::mempool::scheduler; #[allow(non_upper_case_globals)] static algorithm: &'static Algorithm = &SHA256; //struct Sample { //symbols: Vec<Vec<Symbols>>, //indices: Vec<Vec<u64>>, //} //impl Sample { //fn merge(&mut self, s: &Sample) { //let num_layer = self.symbols.len(); //for l in 0..num_layer { //let symbols_l = &s.symbols[l]; //let idx_l= &s.idx[l]; //let mut c_symbols = &mut self.symbols[l]; //let mut c_idx = &mut self.indices[l]; //let mut j = 0; //for i in idx { //if c_idx.contains(i) { //// //} else { //c_idx.push(*i); //c_symbols.push(symbols[j]); //} //j += 1; //} //} //} //} pub struct Mempool { transactions: VecDeque<Transaction>, block_size: usize, contract_handler: Sender<Handle>, schedule_handler: Sender<scheduler::Signal>, returned_blocks: VecDeque<Block>, symbols_by: HashMap<u64, HashMap<u64, (Vec<Vec<Symbol>>, Vec<Vec<u64>>) > >, headers_by: HashMap<u64, BlockHeader>, //block_by: HashMap<u64, CMTBlock>, addr: SocketAddr, codes_for_encoding: Vec<Code>, codes_for_decoding: Vec<Code>, } impl Mempool { pub fn new( contract_handler: Sender<Handle>, schedule_handler: Sender<scheduler::Signal>, addr: SocketAddr, codes_for_encoding: Vec<Code>, codes_for_decoding: Vec<Code>, ) -> Mempool { Mempool { transactions: VecDeque::with_capacity(200000), block_size: BLOCK_SIZE as usize, // in bytes contract_handler: contract_handler, schedule_handler: schedule_handler, returned_blocks: VecDeque::new(), symbols_by: HashMap::new(), //block_by: HashMap::new(), addr: addr, codes_for_encoding: codes_for_encoding, codes_for_decoding: codes_for_decoding, headers_by: HashMap::new(), } } pub fn transaction_size_in_bytes(&self) -> usize { let mut trans_byte = self.transactions.iter().map(Transaction::bytes).collect::<Vec<Bytes>>(); let mut total_size = 0; for tx in &trans_byte { total_size += tx.len(); } total_size } pub fn change_mempool_size(&mut self, size: usize) { self.block_size = size; } pub fn get_num_transaction(&self) -> u64 { return self.transactions.len() as u64; } // TODO change the height in the header, but leave to future when tx has meaning pub fn return_block(&mut self, block: Block) { self.returned_blocks.push_back(block); } pub fn insert_symbols( &mut self, block_id: u64, block_header: &BlockHeader, symbols_by_scale_id: HashMap<u64, (Vec<Vec<Symbol>>, Vec<Vec<u64>>)> ) { self.headers_by.insert(block_id, block_header.clone()); self.symbols_by.insert(block_id, symbols_by_scale_id); } pub fn get_cmt_sample(&mut self, block_id: u64, scale_id: u64) -> (BlockHeader, Vec<Vec<Symbol>>, Vec<Vec<u64>>) { match self.symbols_by.get(&block_id) { Some(symbols_by) => { match symbols_by.get(&scale_id) { Some((s, i)) => { let header = match self.headers_by.get(&block_id) { Some(h) => h.clone(), None => { info!("I don't have cmt header for block id {}", block_id); unreachable!(); }, }; return (header, s.clone(), i.clone()) }, None => { info!("I have cmt symbols for block id {}, but not have for scale node {}", block_id, scale_id); unreachable!(); } } }, None => { info!("I don't have cmt symbols for block id {}", block_id); unreachable!(); } } } //pub fn sample_cmt(&mut self, //block_id: u64, //sample_idx: Vec<u32>, //)-> (BlockHeader, Vec<Vec<Symbol>>, Vec<Vec<u64>>) { //match self.block_by.get(&block_id) { //None => { //info!("I don't have cmt block {}", block_id); //unreachable!(); //}, //Some(cmt_block) => { //let num = sample_idx.len(); //let (mut symbols, mut idx) = cmt_block.sample_vec(sample_idx); ////info!("{:?}, symbols {:?}", self.addr, symbols); ////info!("{:?}, idx {:?}", self.addr,idx); ////let mut decoder: TreeDecoder = TreeDecoder::new( ////self.codes_for_decoding.to_vec(), ////&cmt_block.block_header.coded_merkle_roots_hashes ////); ////info!("{:?}, test treedecoder n {} height {}", self.addr, decoder.n, decoder.height); ////match decoder.run_tree_decoder(symbols.clone(), idx.clone(), cmt_block.block_header.clone()) { ////Ok(transactions) => { ////println!("transactions {:?}", transactions); ////}, ////_ => info!("tree decoder error"), ////}; ////info!("{:?} after calling tree decoder", self.addr); //(cmt_block.block_header.clone(), symbols, idx) //} //} //} //pub fn update_block_id(&mut self, new_id: u64, old_id: u64) { //info!("update a block id from {} to {}", old_id, new_id); //warn!("consider to increase slot time, block generation too fast"); //match self.block_by.get(&old_id) { //None => panic!("cannot update block id,I don't have cmt block"), //Some(cmt_block) => { //self.block_by.insert(new_id, cmt_block.clone()); //self.block_by.remove(&old_id); //} //} //} // currently a hack, need to combine with sample_cmt //pub fn get_cmt_header(&self, block_id: u64) -> BlockHeader { //match &self.block_by.get(&block_id) { //None => panic!("I don't have cmt block"), //Some(cmt_block) => cmt_block.block_header.clone(), //} //} pub fn package_trans(&mut self, transactions: &mut Vec<Transaction>) { let tx_bytes_size = self.transaction_size_in_bytes(); if tx_bytes_size > self.block_size { let mut s = 0; for i in 0..self.transactions.len() { s += self.transactions[i].bytes().len(); if s > self.block_size { if self.transactions.len() == 0 { panic!("single transaction too large, block size is insufficient"); } break; } else { transactions.push(self.transactions[i].clone()); } } for _ in 0..transactions.len() { self.transactions.pop_front(); } } else { for tx in &self.transactions { transactions.push(tx.clone()); } self.transactions.clear(); } //let mut trans_byte = transactions.iter().map(Transaction::bytes).collect::<Vec<Bytes>>(); //let mut total_size = 0; //for tx in &trans_byte { //total_size += tx.len(); //} } pub fn prepare_transaction_block(&mut self) -> Vec<Transaction>{ let mut transactions: Vec<Transaction> = Vec::new(); self.package_trans(&mut transactions); transactions } //pub fn prepare_cmt_block(&mut self, block_id: u64) -> Option<BlockHeader> { //let mut rng = rand::thread_rng(); //// get CMT //let header = BlockHeader { //version: 1, //previous_header_hash: CMTH256::default(), //merkle_root_hash: CMTH256::default(), //time: 4u32, //bits: 5.into(), //nonce: rng.gen(), //coded_merkle_roots_hashes: vec![CMTH256::default(); 8], //}; //// CMT - propose block //// let transaction_size = Transaction::bytes(&self.transactions[0]).len(); //// info!("{:?} transaction_size {:?}", self.addr, transaction_size); //let mut transactions: Vec<Transaction> = Vec::new(); //self.package_trans(&mut transactions); //info!("num trans in block {}", transactions.len()); //let start = SystemTime::now(); //// autopad transactions //let (block, trans_len) = CMTBlock::new( //header.clone(), //&transactions, //BLOCK_SIZE as usize, //HEADER_SIZE, //&self.codes_for_encoding, //vec![true; self.codes_for_encoding.len()] //); ////PERFORMANCE_COUNTER.record_generated_transaction(); //let cmt_header = block.block_header.clone(); ////self.block_by.insert(block_id, block); //return Some(cmt_header); //} pub fn len(&self) -> usize { self.transactions.len() } pub fn remove_block(&mut self, block_id: u64) { info!("mempool remove {}", block_id); self.symbols_by.remove(&block_id); self.headers_by.remove(&block_id); } pub fn insert(&mut self, transaction: Transaction) { self.transactions.push_back(transaction); let tx_bytes_size = self.transaction_size_in_bytes(); // need to truncate if tx_bytes_size > 0 {//self.block_size { self.schedule_handler.send(scheduler::Signal::Control); } } pub fn insert_transactions(&mut self, transactions: Vec<Transaction>) { self.transactions.extend(transactions); let tx_bytes_size = self.transaction_size_in_bytes(); //info!("tx_bytes_size {} num {}", tx_bytes_size, self.transactions.len()); if tx_bytes_size > self.block_size { self.schedule_handler.send(scheduler::Signal::Control); } } pub fn estimate_gas(&mut self, transaction: Transaction) { } } //pub fn prepare_block(&mut self) -> Option<BlockHeader> { //if self.transactions.len() == 0 { //return None; //} //let transaction_size = Transaction::bytes(&self.transactions[0]).len(); //info!("{:?} transaction_size {:?}", self.addr, transaction_size); //let mut transactions: Vec<Transaction> = Vec::new(); //let mut transactions_bytes: Vec<Vec<u8>> = Vec::new(); //let tx_bytes_size = self.transaction_size_in_bytes(); //let start = SystemTime::now(); //// need to truncate //if tx_bytes_size > self.block_size { //let mut s = 0; //for i in 0..self.transactions.len() { //let trans_byte = self.transactions[i].bytes(); //s += trans_byte.len(); //if s > self.block_size { //if self.transactions.len() == 0 { //panic!("single transaction too large, block size is insufficient"); //} //break; //} else { //transactions.push(self.transactions[i].clone()); //transactions_bytes.push(trans_byte.to_vec()); //} //} //for _ in 0..transactions.len() { //self.transactions.pop_front(); //} //} else { //for tx in &self.transactions { //transactions.push(tx.clone()); //transactions_bytes.push(tx.bytes().to_vec()); //} //self.transactions.clear(); //} //let mut trans_byte = transactions.iter().map(Transaction::bytes).collect::<Vec<Bytes>>(); //info!("{:?} copied block {:?}", self.addr, start.elapsed()); //let merkle_tree = MerkleTree::from_vec(algorithm, transactions_bytes); //info!("{:?} prepared merkle_tree {:?}", self.addr, start.elapsed()); //let root_hash = merkle_tree.root_hash(); //let cmt_root_hash: CMTH256 = root_hash[..].into(); ////info!("root_hash {:?}", root_hash); ////let proof = merkle_tree.gen_proof(vec![0]).unwrap(); //let mut rng = rand::thread_rng(); //let header = BlockHeader { //version: 1, //previous_header_hash: CMTH256::default(), //merkle_root_hash: cmt_root_hash, //time: 4u32, //bits: 5.into(), //nonce: rng.gen(), //coded_merkle_roots_hashes: vec![CMTH256::default(); 32], //delimitor: vec![], //}; //// ////let f = File::open("t").expect("Unable to open file"); ////let f = BufReader::new(f); ////let mut header_hex = "".to_string(); ////for line in f.lines() { ////header_hex = line.expect("Unable to read line").to_string(); ////} ////let header_bytes = hex::decode(&header_hex).unwrap(); ////let header: BlockHeader = deserialize(&header_bytes as &[u8]).unwrap(); //let block = CMTBlock { //block_header: header.clone(), //transactions: transactions, //coded_tree: vec![], //Coded Merkle tree constructed from the transactions in the block //block_size_in_bytes: 65535, // size of transactions in the block, used to specify block size for tests //}; //self.cmt_block = Some(block); //return Some(header); //}
use crate::component_store::ComponentStore; use crate::entity_store::EntityStore; use crate::{Component, Entity}; use std::any::{Any, TypeId}; use std::collections::HashMap; const UNDEFINED: usize = 1; pub struct System { components: HashMap<TypeId, Box<Any>>, entity_store: EntityStore, } impl System { pub fn new() -> System { System { components: HashMap::new(), entity_store: EntityStore::new(), } } pub fn new_entity(&mut self) -> Entity { let new_entity: Entity = Entity { id: self.entity_store.get_new_id(), }; new_entity } pub fn count_entities(&self) -> usize { self.entity_store.count() } pub fn set<C: Component>(&mut self, entity: Entity, component: C) -> Option<C> { let type_of_c = TypeId::of::<C>(); //Check if a related typed store exists. if !self.contains_type_id(&type_of_c) { //TODO: Define id self.components .insert(type_of_c, Box::new(ComponentStore::<C>::new(UNDEFINED))); } //Insert the component into the related store. self.get_mut_store::<C>() .and_then(|store| store.set(entity.id, component)) } pub fn get_mut<C: Component>(&mut self, entity: Entity) -> Option<&mut C> { self.get_mut_store::<C>() .and_then(|store| store.borrow_mut(entity.id)) } pub fn get<C: Component>(&mut self, entity: Entity) -> Option<&C> { self.get_mut_store::<C>() .and_then(|store| store.borrow(entity.id)) } pub fn get_mut_components<C: Component>(&mut self) -> Option<&mut ComponentStore<C>> { self.get_mut_store::<C>() } pub fn get_component<C: Component>(&mut self) -> Option<&mut ComponentStore<C>> { self.get_mut_store::<C>() } pub fn remove<C: Component>(&mut self, entity: Entity) -> Option<C> { let ret = self .get_mut_store::<C>() .and_then(|store| store.remove(entity.id)); self.clean_store::<C>(); ret } pub fn remove_components<C: Component>(&mut self) { self.components.remove(&TypeId::of::<C>()); } pub fn count<C: Component>(&mut self) -> usize { //TODO: Manage error self.get_mut_store::<C>() .and_then(|store| Some(store.len())) .unwrap_or(0) } fn contains_type_id(&self, id: &TypeId) -> bool { self.components.contains_key(id) } fn get_mut_store<C: Component>(&mut self) -> Option<&mut ComponentStore<C>> { //TODO: Manage error self.components .get_mut(&TypeId::of::<C>()) .and_then(|store: &mut Box<Any>| { Some(store.downcast_mut::<ComponentStore<C>>().expect("")) }) } fn clean_store<C: Component>(&mut self) { let store = self.get_mut_store::<C>().unwrap(); if store.len() == 0 { self.components.remove(&TypeId::of::<C>()); } } } #[cfg(test)] mod system_tests { use super::*; use crate::components_lib::position::Position; use crate::components_lib::velocity::Velocity; #[test] fn should_create_system() { let sys: System = System::new(); assert_eq!(sys.count_entities(), 0); } #[test] fn should_create_entity() { let mut sys: System = System::new(); let _ent: Entity = sys.new_entity(); assert_eq!(sys.count_entities(), 1); } #[test] fn should_set_entity_component() { let mut sys: System = System::new(); let ent = sys.new_entity(); let pos = Position { x: 0, y: 0 }; let vel = Velocity { vel: 0.2 }; sys.set(ent, pos); sys.set(ent, vel); assert_eq!(sys.count_entities(), 1); } #[test] fn should_get_entity_component() { let mut sys: System = System::new(); let ent = sys.new_entity(); let pos = Position { x: 0, y: 0 }; let vel = Velocity { vel: 0.2 }; sys.set(ent, pos); sys.set(ent, vel); assert_eq!(sys.count_entities(), 1); let ret_pos = sys.get::<Position>(ent).unwrap().clone(); let ret_vel = sys.get::<Velocity>(ent).unwrap().clone(); assert_eq!(ret_pos.x, 0); assert_eq!(ret_pos.y, 0); assert_eq!(ret_vel.vel, 0.2); } #[test] fn should_delete_entity() { let mut sys: System = System::new(); let ent = sys.new_entity(); let pos = Position { x: 0, y: 0 }; let vel = Velocity { vel: 0.2 }; sys.set(ent, pos); sys.set(ent, vel); assert_eq!(sys.count_entities(), 1); assert_eq!(sys.count::<Position>(), 1); sys.remove::<Position>(ent); assert_eq!(sys.count::<Position>(), 0); } #[test] fn should_delete_components() { let mut sys: System = System::new(); let ent1 = sys.new_entity(); let ent2 = sys.new_entity(); let pos1 = Position { x: 0, y: 0 }; let pos2 = Position { x: 0, y: 0 }; sys.set(ent1, pos1); sys.set(ent2, pos2); assert_eq!(sys.count_entities(), 2); assert_eq!(sys.count::<Position>(), 2); sys.remove_components::<Position>(); assert_eq!(sys.count::<Position>(), 0); } #[test] fn should_iter_mut_on_components() { let mut sys: System = System::new(); let ent1 = sys.new_entity(); let ent2 = sys.new_entity(); let pos1 = Position { x: 0, y: 0 }; let pos2 = Position { x: 10, y: 20 }; let vel1 = Velocity { vel: 0.5678 }; sys.set(ent1, pos1); sys.set(ent1, vel1); sys.set(ent2, pos2); assert_eq!(sys.count_entities(), 2); assert_eq!(sys.count::<Position>(), 2); { //Check/Update Position components //-------------------------------------------------------------- let components = sys.get_mut_components::<Position>().unwrap(); assert_eq!(components.len(), 2); for component in components.iter_mut() { let id: &u32 = component.0; let value: &mut Position = component.1; println!("Position : {:?}:{:?}", id, value); value.x += 10; value.y += 100; } } { //Check/Update Velocity components //-------------------------------------------------------------- let components = sys.get_mut_components::<Velocity>().unwrap(); assert_eq!(components.len(), 1); for component in components.iter_mut() { let id: &u32 = component.0; let value: &mut Velocity = component.1; println!("Velocity : {:?}:{:?}", id, value); value.vel *= 2.0; } } { //Check Position components //-------------------------------------------------------------- let components = sys.get_mut_components::<Position>().unwrap(); assert_eq!(components.len(), 2); for component in components.iter() { let id: &u32 = component.0; let value: &Position = component.1; println!("Position : {:?}:{:?}", id, value); } } { //Check Velocity components //-------------------------------------------------------------- let components = sys.get_mut_components::<Velocity>().unwrap(); assert_eq!(components.len(), 1); for component in components.iter() { let id: &u32 = component.0; let value: &Velocity = component.1; println!("Velocity : {:?}:{:?}", id, value); } } } }
use crate::base::{ID, Element, ListResult, BareList}; use crate::dbbase::ConnectionProvider; use crate::rocketeer::db::listdao; use crate::rocketeer::service::list_service::{ListService}; /** * Database implementation of the list service interface. * * Note. Deceptively pretends to be database-agnostic! But * ConnectionProvider is defined in terms of Sqlite. * See dbbase for details. */ pub struct ListServiceDb { connection_provider: ConnectionProvider } impl ListServiceDb { pub fn new(connection_provider: ConnectionProvider) -> ListServiceDb { ListServiceDb { connection_provider } } } impl ListService for ListServiceDb { fn create(&self, id: &ID) -> ListResult<()> { let conn = self.connection_provider.get_connection()?; listdao::create(&conn, id) } fn get(&self, id: &ID) -> ListResult<BareList> { let conn = self.connection_provider.get_connection()?; listdao::get(&conn, id) } fn update(&self, id: &ID, list: &BareList) -> ListResult<()> { let conn = self.connection_provider.get_connection()?; listdao::update(&conn, id, list.clone()) } fn delete(&self, id: &ID) -> ListResult<()> { let conn = self.connection_provider.get_connection()?; listdao::delete(&conn, id) .map(|_| ()) } fn add_element(&self, id: &ID, element: &Element, index: usize) -> ListResult<()> { let conn = self.connection_provider.get_connection()?; listdao::add_element(&conn, id, element, index) } fn get_element(&self, id: &ID, index: usize) -> ListResult<Element> { let conn = self.connection_provider.get_connection()?; listdao::get_element(&conn, id, index) } #[allow(unused)] fn update_element(&self, id: &ID, element: &Element, index: usize) -> ListResult<()> { // TODO. URGENT. Implement me. Delegate to transactional dao function. unimplemented!() } #[allow(unused)] fn remove_element(&self, id: &ID, index: usize) -> ListResult<()> { // TODO. URGENT. Implement me. Delegate to transactional dao function. unimplemented!() } }
/*! Some helper functions. */ /// Used to coerce `&[T;N]` to `&[T]`. pub const fn coerce_slice<'a,T>(slic:&'a [T])->&'a [T]{ slic }
use crate::{check_uniq, field_indices, index_number, is_cow, is_option, variant_indices}; use crate::{Idx, lifetimes_to_constrain, is_str, is_byte_slice, encoding, Encoding}; use crate::{collect_type_params, CustomCodec, custom_codec}; use crate::find_cbor_attr; use quote::quote; use std::collections::HashSet; use syn::spanned::Spanned; /// Entry point to derive `minicbor::Decode` on structs and enums. pub fn derive_from(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let mut input = syn::parse_macro_input!(input as syn::DeriveInput); let result = match &input.data { syn::Data::Struct(_) => on_struct(&mut input), syn::Data::Enum(_) => on_enum(&mut input), syn::Data::Union(u) => { let msg = "deriving `minicbor::Decode` for a `union` is not supported"; Err(syn::Error::new(u.union_token.span(), msg)) } }; proc_macro::TokenStream::from(result.unwrap_or_else(|e| e.to_compile_error())) } /// Create a `Decode` impl for (tuple) structs. fn on_struct(inp: &mut syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> { let data = if let syn::Data::Struct(data) = &inp.data { data } else { unreachable!("`derive_from` matched against `syn::Data::Struct`") }; let name = &inp.ident; let indices = field_indices(data.fields.iter())?; check_uniq(name.span(), indices.iter().cloned())?; let (field_names, field_types, decode_fns) = fields(data.fields.iter())?; let mut lifetime = decode_lifetime()?; for l in lifetimes_to_constrain(indices.iter().zip(field_types.iter())) { lifetime.bounds.push(l.clone()) } // Collect type parameters which should not have an `Decode` bound added. let blacklist = collect_type_params(&inp.generics, data.fields.iter().zip(&decode_fns).filter_map(|(f, ff)| { if let Some(CustomCodec::Decode(_)) | Some(CustomCodec::Both(_)) = ff { Some(f) } else { None } })); add_decode_bound(&blacklist, inp.generics.type_params_mut())?; let g = add_lifetime(&inp.generics, lifetime); let (impl_generics , ..) = g.split_for_impl(); let (_, typ_generics, where_clause) = inp.generics.split_for_impl(); // If transparent, just forward the decode call to the inner type. if find_cbor_attr(inp.attrs.iter(), "transparent")?.is_some() { return make_transparent_impl(inp, data, impl_generics, typ_generics, where_clause) } let field_str = field_names.iter().map(|n| format!("{}::{}", name, n)); let encoding = inp.attrs.iter().filter_map(encoding).next().unwrap_or_default(); let statements = gen_statements(&field_names, &field_types, &indices, &decode_fns, encoding)?; let result = if let syn::Fields::Named(_) = data.fields { quote! { Ok(#name { #(#field_names : if let Some(x) = #field_names { x } else { return Err(minicbor::decode::Error::MissingValue(#indices, #field_str)) }),* }) } } else if let syn::Fields::Unit = &data.fields { quote!(Ok(#name)) } else { quote! { Ok(#name(#(if let Some(x) = #field_names { x } else { return Err(minicbor::decode::Error::MissingValue(#indices, #field_str)) }),*)) } }; Ok(quote! { impl #impl_generics minicbor::Decode<'__b777> for #name #typ_generics #where_clause { fn decode(__d777: &mut minicbor::Decoder<'__b777>) -> Result<#name #typ_generics, minicbor::decode::Error> { #statements #result } } }) } /// Create a `Decode` impl for enums. fn on_enum(inp: &mut syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> { let data = if let syn::Data::Enum(data) = &inp.data { data } else { unreachable!("`derive_from` matched against `syn::Data::Enum`") }; let name = &inp.ident; check_uniq(data.enum_token.span(), variant_indices(data.variants.iter())?)?; let enum_encoding = inp.attrs.iter().filter_map(encoding).next().unwrap_or_default(); let mut blacklist = HashSet::new(); let mut lifetime = decode_lifetime()?; let mut rows = Vec::new(); for var in data.variants.iter() { let con = &var.ident; let idx = index_number(var.ident.span(), &var.attrs)?; let indices = field_indices(var.fields.iter())?; check_uniq(con.span(), indices.iter().cloned())?; let row = if let syn::Fields::Unit = &var.fields { quote!(#idx => { __d777.skip()?; Ok(#name::#con) }) } else { let (field_names, field_types, decode_fns) = fields(var.fields.iter())?; for l in lifetimes_to_constrain(indices.iter().zip(field_types.iter())) { lifetime.bounds.push(l.clone()) } let field_str = field_names.iter().map(|n| format!("{}::{}::{}", name, con, n)); let numbers = field_indices(var.fields.iter())?; let encoding = var.attrs.iter().filter_map(encoding).next().unwrap_or(enum_encoding); // Collect type parameters which should not have an `Decode` bound added. blacklist.extend(collect_type_params(&inp.generics, var.fields.iter().zip(&decode_fns).filter_map(|(f, ff)| { if let Some(CustomCodec::Decode(_)) | Some(CustomCodec::Both(_)) = ff { Some(f) } else { None } }))); let statements = gen_statements(&field_names, &field_types, &numbers, &decode_fns, encoding)?; if let syn::Fields::Named(_) = var.fields { quote! { #idx => { #statements Ok(#name::#con { #(#field_names : if let Some(x) = #field_names { x } else { return Err(minicbor::decode::Error::MissingValue(#numbers, #field_str)) }),* }) } } } else { quote! { #idx => { #statements Ok(#name::#con(#(if let Some(x) = #field_names { x } else { return Err(minicbor::decode::Error::MissingValue(#numbers, #field_str)) }),*)) } } } }; rows.push(row) } add_decode_bound(&blacklist, inp.generics.type_params_mut())?; let g = add_lifetime(&inp.generics, lifetime); let (impl_generics , ..) = g.split_for_impl(); let (_, typ_generics, where_clause) = inp.generics.split_for_impl(); Ok(quote! { impl #impl_generics minicbor::Decode<'__b777> for #name #typ_generics #where_clause { fn decode(__d777: &mut minicbor::Decoder<'__b777>) -> Result<#name #typ_generics, minicbor::decode::Error> { if Some(2) != __d777.array()? { return Err(minicbor::decode::Error::Message("expected enum (2-element array)")) } match __d777.u32()? { #(#rows)* n => Err(minicbor::decode::Error::UnknownVariant(n)) } } } }) } /// Generate decoding statements for every item. // // For every name `n`, type `t` and index `i` we declare a local mutable // variable `n` with type `Option<t>` and set it to `None` if `t` is not // an `Option`, otherwise to `Some(None)`. [1] // // Then -- depending on the selected encoding -- we iterate over all CBOR // map or array elements and if an index `j` equal to `i` is found, we // attempt to decode the next CBOR item as a value `v` of type `t`. If // successful, we assign the result to `n` as `Some(v)`, otherwise we // error, or -- if `t` is an option and the decoding failed because an // unknown enum variant was decoded -- we skip the variant value and // continue decoding. // // -------------------------------------------------------------------- // [1]: These variables will later be deconstructed in `on_enum` and // `on_struct` and their inner value will be used to initialise a field. // If not present, an error will be produced. fn gen_statements ( names: &[syn::Ident] , types: &[syn::Type] , numbers: &[Idx] , decode_fns: &[Option<CustomCodec>] , encoding: Encoding ) -> syn::Result<proc_macro2::TokenStream> { assert_eq!(names.len(), types.len()); assert_eq!(types.len(), numbers.len()); assert_eq!(numbers.len(), decode_fns.len()); let default_decode_fn: syn::ExprPath = syn::parse_str("minicbor::Decode::decode")?; let inits = types.iter().map(|ty| { if is_option(ty, |_| true) { quote!(Some(None)) } else { quote!(None) } }); let actions = numbers.iter().zip(names.iter().zip(types.iter().zip(decode_fns))) .map(|(ix, (name, (ty, ff)))| { let decode_fn = ff.as_ref() .and_then(|ff| ff.to_decode_path()) .unwrap_or_else(|| default_decode_fn.clone()); if is_option(ty, |_| true) { return quote! { match #decode_fn(__d777) { Ok(value) => #name = Some(value), Err(minicbor::decode::Error::UnknownVariant(_)) => { __d777.skip()? } Err(e) => return Err(e) } } } if ix.is_b() && is_cow(ty, |t| is_str(t) || is_byte_slice(t)) { return quote! { match #decode_fn(__d777) { Ok(value) => #name = Some(std::borrow::Cow::Borrowed(value)), Err(minicbor::decode::Error::UnknownVariant(_)) => { __d777.skip()? } Err(e) => return Err(e) } } } quote!({ #name = Some(#decode_fn(__d777)?) }) }) .collect::<Vec<_>>(); Ok(match encoding { Encoding::Array => quote! { #(let mut #names : Option<#types> = #inits;)* if let Some(__len777) = __d777.array()? { for __i777 in 0 .. __len777 { match __i777 { #(#numbers => #actions)* _ => __d777.skip()? } } } else { let mut __i777 = 0; while minicbor::data::Type::Break != __d777.datatype()? { match __i777 { #(#numbers => #actions)* _ => __d777.skip()? } __i777 += 1 } __d777.skip()? } }, Encoding::Map => quote! { #(let mut #names : Option<#types> = #inits;)* if let Some(__len777) = __d777.map()? { for _ in 0 .. __len777 { match __d777.u32()? { #(#numbers => #actions)* _ => __d777.skip()? } } } else { while minicbor::data::Type::Break != __d777.datatype()? { match __d777.u32()? { #(#numbers => #actions)* _ => __d777.skip()? } } __d777.skip()? } } }) } /// Map fields to a list of field names and field types. fn fields<'a, I>(iter: I) -> syn::Result<(Vec<syn::Ident>, Vec<syn::Type>, Vec<Option<CustomCodec>>)> where I: Iterator<Item = &'a syn::Field> + Clone { let names = iter.clone() .enumerate() .map(|(i, f)| { match &f.ident { Some(n) => n.clone(), None => quote::format_ident!("_{}", i) } }) .collect(); let types = iter.clone() .map(|f| f.ty.clone()) .collect(); let decode_fns = iter .map(|f| { for a in &f.attrs { if let Some(ff) = custom_codec(a)? { if ff.is_decode() { return Ok(Some(ff)) } } } Ok(None) }) .collect::<syn::Result<Vec<_>>>()?; Ok((names, types, decode_fns)) } /// Generate the '__b777 lifetime. fn decode_lifetime() -> syn::Result<syn::LifetimeDef> { syn::parse_str("'__b777") } /// Add a `minicbor::Decode` bound to every type parameter. fn add_decode_bound<'a, I>(blacklist: &HashSet<syn::TypeParam>, iter: I) -> syn::Result<()> where I: Iterator<Item = &'a mut syn::TypeParam> { let bound: syn::TypeParamBound = syn::parse_str("minicbor::Decode<'__b777>")?; for t in iter.filter(|t| !blacklist.contains(t)) { t.bounds.push(bound.clone()) } Ok(()) } /// Return a modified clone of `syn::Generics` with the given lifetime /// parameter put before the other type and lifetime parameters. /// /// This will be used later when splitting the parameters so that the /// additional lifetime is only present in the `impl` parameter section. fn add_lifetime(g: &syn::Generics, l: syn::LifetimeDef) -> syn::Generics { let mut g2 = g.clone(); g2.params = Some(l.into()).into_iter().chain(g2.params).collect(); g2 } /// Forward the decoding because of a `#[cbor(transparent)]` attribute. fn make_transparent_impl ( input: &syn::DeriveInput , data: &syn::DataStruct , impl_generics: syn::ImplGenerics , typ_generics: syn::TypeGenerics , where_clause: Option<&syn::WhereClause> ) -> syn::Result<proc_macro2::TokenStream> { if data.fields.len() != 1 { let msg = "#[cbor(transparent)] requires a struct with one field"; return Err(syn::Error::new(input.ident.span(), msg)) } let field = data.fields.iter().next().expect("struct has one field"); if let Some(a) = find_cbor_attr(field.attrs.iter(), "decode_with")? { let msg = "#[cbor(decode_with)] not allowed within #[cbor(transparent)]"; return Err(syn::Error::new(a.span(), msg)) } if let Some(a) = find_cbor_attr(field.attrs.iter(), "with")? { let msg = "#[cbor(with)] not allowed within #[cbor(transparent)]"; return Err(syn::Error::new(a.span(), msg)) } let name = &input.ident; let call = if let Some(id) = &field.ident { quote! { Ok(#name { #id: minicbor::Decode::decode(__d777)? }) } } else { quote! { Ok(#name(minicbor::Decode::decode(__d777)?)) } }; Ok(quote! { impl #impl_generics minicbor::Decode<'__b777> for #name #typ_generics #where_clause { fn decode(__d777: &mut minicbor::Decoder<'__b777>) -> Result<#name #typ_generics, minicbor::decode::Error> { #call } } }) }
/// Won't you be my neighbor? /// /// A simple CRM, starting as a JSON API user management system. mod sitter; use std::env; use actix_web::{middleware, App, HttpServer}; use anyhow::Result; use dotenv::dotenv; use log::info; use sqlx::PgPool; #[actix_web::main] async fn main() -> Result<()> { dotenv().ok(); env_logger::init(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set in .env file"); let db_pool = PgPool::connect(&database_url).await?; let listener = "127.0.0.1:5335"; let server = HttpServer::new(move || { App::new() // enable logger .wrap(middleware::Logger::default()) // enable page served by header .wrap(middleware::DefaultHeaders::new().header("X-Neighbor", "0")) // pass database pool to application .data(db_pool.clone()) // pass registered hooks to application .data(sitter::register_hooks()) // @TODO: make endpoint paths easily configurable .configure(sitter::routes) }); info!("Neighbor listening at: {:?}", listener); server.bind(listener)?.run().await?; Ok(()) }
// Copyright (c) 2016, <daggerbot@gmail.com> // This software is available under the terms of the zlib license. // See COPYING.md for more information. use device::{Device, DeviceBridge}; use error::Result; use imp::PixelFormatProvider; use util::GetProvider; /// Implementation trait for `PixelFormat`. pub trait PixelFormatBridge : Clone + PartialEq { fn supports_view (&self) -> bool; fn supports_window (&self) -> bool; } /// Format for a surface's pixel buffer. #[derive(Clone, PartialEq)] pub struct PixelFormat { provider: PixelFormatProvider, } impl PixelFormat { pub fn supports_view (&self) -> bool { self.provider.supports_view() } pub fn supports_window (&self) -> bool { self.provider.supports_window() } } #[doc(hidden)] impl From<PixelFormatProvider> for PixelFormat { fn from (provider: PixelFormatProvider) -> PixelFormat { PixelFormat { provider: provider } } } #[doc(hidden)] impl GetProvider for PixelFormat { type Provider = PixelFormatProvider; fn provider (&self) -> &PixelFormatProvider { &self.provider } } #[doc(hidden)] impl PixelFormatPriv for PixelFormat { fn default (device: &Device) -> Result<PixelFormat> { Ok(PixelFormat { provider: try!(device.provider().default_pixel_format()), }) } } /// Private methods for `PixelFormat`. pub trait PixelFormatPriv : Sized { fn default (device: &Device) -> Result<Self>; }
use crate::commands::*; use std::collections::HashSet; use serenity::framework::standard::macros::group; use serenity::framework::StandardFramework; use serenity::model::event::ResumedEvent; use serenity::model::gateway::Ready; use serenity::prelude::*; struct Handler; impl EventHandler for Handler { fn ready(&self, _: Context, ready: Ready) { log::info!("Connected as {}", ready.user.name); } fn resume(&self, _: Context, _: ResumedEvent) { log::info!("Resumed"); } } #[group] #[commands(all, gossip, setguild)] struct General; /// Run the discord bot. pub fn run(token: &str, prefix: &str) -> anyhow::Result<()> { let mut client = Client::new(&token, Handler)?; let owners = match client.cache_and_http.http.get_current_application_info() { Ok(info) => { let mut set = HashSet::new(); set.insert(info.owner.id); set } Err(why) => panic!("Couldn't get application info: {:?}", why), }; client.with_framework( StandardFramework::new() .configure(|c| c.owners(owners).prefix(&prefix)) .group(&GENERAL_GROUP), ); client.start()?; Ok(()) }
// Copyright 2020 Shift Cryptosecurity AG // // 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::ffi::OsString; use std::time::Duration; use windows_service::service::{ ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, ServiceType, }; use windows_service::service_control_handler::{self, ServiceControlHandlerResult}; use windows_service::{define_windows_service, service_dispatcher}; define_windows_service!(ffi_service_main, my_service_main); /// Gets called when service is started /// Is run in a background thread fn my_service_main(args: Vec<OsString>) { if let Err(e) = run_service(args) { error!("Service control communication failed: {:?}", e); } } fn run_service(_args: Vec<OsString>) -> Result<(), windows_service::Error> { let (tx, rx) = std::sync::mpsc::channel(); let event_handler = move |control_event| -> ServiceControlHandlerResult { match control_event { ServiceControl::Stop => { // Handle stop event and return control back to the system. tx.send(()).unwrap(); ServiceControlHandlerResult::NoError } // All services must accept Interrogate even if it's a no-op. ServiceControl::Interrogate => ServiceControlHandlerResult::NoError, _ => ServiceControlHandlerResult::NotImplemented, } }; // Register system service event handler let status_handle = service_control_handler::register("bitbox-bridge", event_handler)?; // Tell the system that the service is running now status_handle.set_service_status(ServiceStatus { // Should match the one from system service registry service_type: ServiceType::OWN_PROCESS, // The new state current_state: ServiceState::Running, // Accept stop events when running controls_accepted: ServiceControlAccept::STOP, // Used to report an error when starting or stopping only, otherwise must be zero exit_code: ServiceExitCode::Win32(0), // Only used for pending states, otherwise must be zero checkpoint: 0, // Only used for pending states, otherwise must be zero wait_hint: Duration::default(), process_id: None, })?; // Poll shutdown event. rx.recv().unwrap(); // Tell the system that service has stopped. status_handle.set_service_status(ServiceStatus { service_type: ServiceType::OWN_PROCESS, current_state: ServiceState::Stopped, controls_accepted: ServiceControlAccept::empty(), exit_code: ServiceExitCode::Win32(0), checkpoint: 0, wait_hint: Duration::default(), process_id: None, })?; Ok(()) } /// start interacting as a service / daemon pub async fn start() { let (tx, rx) = futures::channel::oneshot::channel(); std::thread::spawn(move || { // Blocking call, will block until service is killed by Winows if let Err(e) = service_dispatcher::start("bitbox-bridge", ffi_service_main) { error!("Failed to register as started service: {:?}", e); tx.send(false).unwrap(); return; } tx.send(true).unwrap(); }); let res = rx.await.unwrap(); if !res { // This task will forever wait here since we coulnd't communicate with the windows service manager futures::future::pending::<()>().await; } }
mod task; use fumio_utils::park::Park; use futures_core::future::{Future, FutureObj, LocalFutureObj}; use futures_core::task::{Spawn, LocalSpawn, SpawnError}; use futures_executor::Enter; use futures_util::pin_mut; use std::rc::{Rc, Weak}; use std::task::{Context, Poll}; // Set up and run a basic single-threaded spawner loop, invoking `f` on each // turn. fn run_executor<P: Park, T, F: FnMut(&mut Context<'_>) -> Poll<T>>(park: &mut P, enter: &mut Enter, mut f: F) -> T { let waker = park.waker(); let mut cx = Context::from_waker(&waker); loop { if let Poll::Ready(t) = f(&mut cx) { return t; } park.park(enter, None); } } /// A single-threaded task pool for polling futures to completion. /// /// This executor allows you to multiplex any number of tasks onto a single /// thread. It's appropriate to poll strictly I/O-bound futures that do very /// little work in between I/O actions. /// /// To get a handle to the pool that implements /// [`Spawn`](futures_core::task::Spawn), use the /// [`spawner()`](LocalPool::spawner) method. Because the executor is /// single-threaded, it supports a special form of task spawning for non-`Send` /// futures, via [`spawn_local_obj`](futures_core::task::LocalSpawn::spawn_local_obj). #[derive(Debug)] pub struct LocalPool { task_list: Rc<task::LocalTaskList>, } impl LocalPool { /// Create a new, empty pool of tasks. pub fn new() -> Self { Self { task_list: Rc::new(task::LocalTaskList::new()), } } /// Get a clonable handle to the pool as a [`Spawn`]. pub fn spawner(&self) -> LocalSpawner { LocalSpawner { task_list: Rc::downgrade(&self.task_list) } } /// Run all tasks in the pool to completion. /// /// The function will block the calling thread until *all* tasks in the pool /// completed, including any spawned while running existing tasks. pub fn run<P: Park>(&mut self, park: &mut P, enter: &mut Enter) { run_executor(park, enter, |cx| self.poll_pool(cx)) } /// Runs all the tasks in the pool until the given future completes. /// /// The given spawner, `spawn`, is used as the default spawner for any /// *newly*-spawned tasks. You can route these additional tasks back into /// the `LocalPool` by using its spawner handle: /// /// The function will block the calling thread *only* until the future `f` /// completes; there may still be incomplete tasks in the pool, which will /// be inert after the call completes, but can continue with further use of /// one of the pool's run or poll methods. While the function is running, /// however, all tasks in the pool will try to make progress. pub fn run_until<P: Park, F: Future>(&mut self, park: &mut P, enter: &mut Enter, future: F) -> F::Output { pin_mut!(future); run_executor(park, enter, |cx| { { // if our main task is done, so are we let result = future.as_mut().poll(cx); if let Poll::Ready(output) = result { return Poll::Ready(output); } } let _ = self.poll_pool(cx); Poll::Pending }) } /// Make progress on entire pool, polling each spawend task at most once. /// /// Becomes `Ready` when all tasks are completed. pub fn poll_pool(&mut self, cx: &mut Context<'_>) -> Poll<()> { self.task_list.poll(cx) } /// Spawn future on pool pub fn spawn(&self, future: LocalFutureObj<'static, ()>) { self.task_list.add_task(future); } } impl Default for LocalPool { fn default() -> Self { Self::new() } } impl Spawn for LocalPool { fn spawn_obj( &mut self, future: FutureObj<'static, ()>, ) -> Result<(), SpawnError> { self.spawn_local_obj(future.into()) } fn status(&self) -> Result<(), SpawnError> { self.status_local() } } impl LocalSpawn for LocalPool { fn spawn_local_obj( &mut self, future: LocalFutureObj<'static, ()>, ) -> Result<(), SpawnError> { self.spawn(future); Ok(()) } fn status_local(&self) -> Result<(), SpawnError> { Ok(()) } } /// A handle to a [`LocalPool`](LocalPool) that implements [`Spawn`](futures_core::task::Spawn) and /// [`LocalSpawn`](futures_core::task::LocalSpawn). #[derive(Clone, Debug)] pub struct LocalSpawner { task_list: Weak<task::LocalTaskList>, } impl LocalSpawner { /// Enter a spawner. /// /// Clears the current spawner when `f` returns. /// /// [`current_local`](fn.current_local.html) needs this to work. /// /// A runtime (combining reactor, pool, ...) should enter a spawner handle (in /// each thread it runs tasks from the pool) so all tasks have access to the /// spawner. /// /// # Panics /// /// Panics if a spawner is already entered. pub fn enter<F, T>(self, enter: &mut Enter, f: F) -> T where F: FnOnce(&mut Enter) -> T { crate::current::enter_local(self, enter, f) } } impl Spawn for LocalSpawner { fn spawn_obj( &mut self, future: FutureObj<'static, ()>, ) -> Result<(), SpawnError> { self.spawn_local_obj(future.into()) } fn status(&self) -> Result<(), SpawnError> { self.status_local() } } impl LocalSpawn for LocalSpawner { fn spawn_local_obj( &mut self, future: LocalFutureObj<'static, ()>, ) -> Result<(), SpawnError> { if let Some(task_list) = self.task_list.upgrade() { task_list.add_task(future); Ok(()) } else { Err(SpawnError::shutdown()) } } fn status_local(&self) -> Result<(), SpawnError> { if self.task_list.upgrade().is_some() { Ok(()) } else { Err(SpawnError::shutdown()) } } }
use glfw::{Action, CursorMode, Key, WindowEvent}; use luminance::{ context::GraphicsContext, face_culling::FaceCulling, framebuffer::Framebuffer, linear::M44, pipeline::BoundTexture, pixel::Floating, render_state::RenderState, shader::program::{Program, Uniform}, texture::{Dim2, Flat}, }; use luminance_derive::UniformInterface; use luminance_glfw_custom::surface::{GlfwSurface, Surface, WindowDim, WindowOpt}; use sandbox::{ entity::{camera::Camera, player::Player, sector::SectorManager}, maths::{ matrix::{Projection, Transform}, vector::{MathVec, Vec2f, Vec3, Vec4, Vec4f}, }, resource::ResourceManager, timing::Clock, vertexattrib::Semantic, }; use std::f32::consts::PI; const VS: &'static str = include_str!("vs.glsl"); const FS: &'static str = include_str!("fs.glsl"); const BLACK: [f32; 4] = [0., 0., 0., 0.]; #[derive(UniformInterface)] struct ShaderInterface { //time: Uniform<f32>, model_mat: Uniform<M44>, view_mat: Uniform<M44>, projection_mat: Uniform<M44>, terrain_texture: Uniform<&'static BoundTexture<'static, Flat, Dim2, Floating>>, } fn main() { // Informal tests of math let v = Vec2f::new(1., 1.); println!("{} -> {}", v.mag_sq(), v.mag()); println!("{:?}", v + Vec2f::new(-1., 3.)); println!("{:?}", v - Vec2f::new(-1., 3.)); println!("{:?}", v * 5.0); println!("{:?}", -v); println!("{:?}", Vec4::<char>::from(('a', 'b', 'c', 'd'))); println!("{:?}", Into::<Vec3<i32>>::into((1, 2, 3))); let mut v2 = Vec2f::new(0., 0.); v2 += (1., 2.).into(); println!("{:?}", v2); v2 = Vec2f::new(0., 0.); v2 -= Vec2f::new(5., -5.); println!("{:?}", v2); let mut v4 = Vec4f::new(-1., 0., 1., 2.); v4 += Vec4f::new(1., 1., 1., 1.); println!("{:?}", v4); v4 = Vec4f::new(-1., 0., 1., 2.); v4 *= 3.0; println!("{:?}", v4); // Window creation let mut surface = GlfwSurface::new( WindowDim::Windowed(960, 540), "sandbox", WindowOpt::default(), ) .expect("GLFW surface creation!"); // Set the correct mouse mode surface .lib_handle_mut() .set_cursor_mode(CursorMode::Disabled); // Resource loading let res_mgr = ResourceManager::load_all(&mut surface); let terrain_tex = res_mgr.texture_mgr().terrain(); // Shader compilation let (program, _) = Program::<Semantic, (), ShaderInterface>::from_strings(None, VS, None, FS) .expect("program creation"); // Create a ``Player` let mut player = Player::at_origin(); // Camera and projection matrix let mut cam = Camera::new(); let mut proj_mat = make_proj(&surface).to_matrix(); // Create a ``SectorManager``. let mut sector_mgr = SectorManager::new(terrain_tex.info()); // Framebuffer let mut back_buffer = Framebuffer::back_buffer(surface.size()); // Track frame time and window resize let mut resized = true; let mut clock = Clock::begin(); 'game: loop { // Handle timing let dt = clock.restart_seconds(); //std::thread::sleep(Duration::from_millis(200)); // Load pending sectors sector_mgr.finalize_sectors(&mut surface); // Poll events for event in surface.poll_events() { match event { WindowEvent::Close | WindowEvent::Key(Key::Escape, _, Action::Release, _) => { break 'game } WindowEvent::Key(Key::P, _, Action::Release, _) => { println!("{}\t{}", 1. / dt, dt); } WindowEvent::FramebufferSize(width, height) => { println!("resize!"); back_buffer = Framebuffer::back_buffer([width as u32, height as u32]); resized = true; } _ => {} } } // Handle resize if resized { println!("make proj matrix!"); proj_mat = make_proj(&surface).to_matrix(); } let move_speed = 4.0 * dt as f32; // Movement if surface.lib_handle().get_key(Key::D) == Action::Press { player.move_x(move_speed); } else if surface.lib_handle().get_key(Key::A) == Action::Press { player.move_x(-move_speed); } if surface.lib_handle().get_key(Key::Space) == Action::Press { player.slide((0., move_speed, 0.)); } else if surface.lib_handle().get_key(Key::LeftShift) == Action::Press { player.slide((0., -move_speed, 0.)); } if surface.lib_handle().get_key(Key::S) == Action::Press { //player.slide((0., 0., move_speed)); player.move_z(move_speed); } else if surface.lib_handle().get_key(Key::W) == Action::Press { //player.slide((0., 0., -move_speed)); player.move_z(-move_speed); } let rot_speed = 0.012; // Pan / pitch with arrow keys if surface.lib_handle().get_key(Key::Left) == Action::Press { player.spin((0., rot_speed)); } else if surface.lib_handle().get_key(Key::Right) == Action::Press { player.spin((0., -rot_speed)); } if surface.lib_handle().get_key(Key::Up) == Action::Press { player.spin((rot_speed, 0.)); } else if surface.lib_handle().get_key(Key::Down) == Action::Press { player.spin((-rot_speed, 0.)); } // Pan / pitch with mouse let mouse_speed: f64 = 0.002; //println!("{:?}", surface.lib_handle().get_cursor_pos()); let mouse_delta = surface.lib_handle().get_cursor_pos(); surface.lib_handle_mut().set_cursor_pos(0., 0.); // swap x and y let cam_delta = ( (-mouse_delta.1 * mouse_speed) as f32, (-mouse_delta.0 * mouse_speed) as f32, ); player.spin(cam_delta); // Update camera cam.snap_to(&player); // Render frame surface .pipeline_builder() .pipeline(&back_buffer, BLACK, |pipe, shd_gate| { let bound_terrain_tex = pipe.bind_texture(terrain_tex.inner()); shd_gate.shade(&program, |rdr_gate, iface| { if resized { println!("load proj matrix!"); iface.projection_mat.update(proj_mat.0); } iface.view_mat.update(cam.to_matrix().0); iface.terrain_texture.update(&bound_terrain_tex); for (_, sector) in &sector_mgr { iface.model_mat.update(sector.translation().0); let state = RenderState::default().set_face_culling(FaceCulling::default()); if let Some(geometry) = sector.geometry() { rdr_gate.render(state, |tess_gate| { tess_gate.render(&mut surface, geometry.into()); }); } } }); }); // Show the backbuffer surface.swap_buffers(); // Reset resize flag resized = false; } } fn make_proj(surface: &impl Surface) -> Projection { let [w, h] = surface.size(); let (w, h) = (w as f32, h as f32); Projection::new(40.0 * PI / 180.0, w / h, 0.1, 1000.0) }
// Copyright 2017 rust-ipfs-api Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. // use clap::{App, Arg, ArgMatches, SubCommand}; use command::EXPECTED_API; use ipfs_api::IpfsClient; use tokio_core::reactor::Core; pub fn signature<'a, 'b>() -> App<'a, 'b> { // The clap macro does not allow hyphenated command names, // so the `set-time` command has to be manually instantiated. // let set_time_command = SubCommand::with_name("set-time") .about("Set how long to keep inactive requests in the log") .arg(Arg::with_name("TIME").required(true).index(1).help( "Time to keep inactive requests in the log", )); clap_app!( @subcommand diag => (@setting SubcommandRequiredElseHelp) (@subcommand cmds => (@setting SubcommandRequiredElseHelp) (@subcommand clear => (about: "Clear inactive requests from the log") ) (subcommand: set_time_command) ) (@subcommand sys => (about: "Print system diagnostic information") ) ) } pub fn handle(core: &mut Core, client: &IpfsClient, args: &ArgMatches) { match args.subcommand() { ("cmds", Some(args)) => { match args.subcommand() { ("clear", _) => { core.run(client.diag_cmds_clear()).expect(EXPECTED_API); println!(""); println!(" OK"); println!(""); } ("set-time", Some(args)) => { let time = args.value_of("TIME").unwrap(); core.run(client.diag_cmds_set_time(&time)).expect( EXPECTED_API, ); println!(""); println!(" OK"); println!(""); } _ => unreachable!(), } } ("sys", _) => { let sys = core.run(client.diag_sys()).expect(EXPECTED_API); println!(""); println!(" {}", sys); println!(""); } _ => unreachable!(), } }
use std::{ net::SocketAddr, time::{Duration, Instant}, }; use crate::protocol::handshake::Handshake; use crate::{SeqNumber, SocketID}; #[derive(Clone, Debug)] pub struct Connection { pub settings: ConnectionSettings, pub handshake: Handshake, } #[derive(Debug, Clone, Copy)] pub struct ConnectionSettings { /// The remote socket to send & receive to pub remote: SocketAddr, /// The socket id of the UDT entity on the other side pub remote_sockid: SocketID, /// The local UDT socket id pub local_sockid: SocketID, /// The time that this socket started at, used to develop timestamps pub socket_start_time: Instant, /// The first sequence number pub init_seq_num: SeqNumber, /// The maximum packet size pub max_packet_size: u32, /// The maxiumum flow size pub max_flow_size: u32, /// The TSBPD latency configured by the user. /// Not necessarily the actual decided on latency, which /// is the max of both side's respective latencies. pub tsbpd_latency: Duration, } impl ConnectionSettings { /// Timestamp in us pub fn get_timestamp(&self, at: Instant) -> i32 { let elapsed = at - self.socket_start_time; elapsed.as_micros() as i32 // TODO: handle overflow here } /// Timestamp in us pub fn get_timestamp_now(&self) -> i32 { self.get_timestamp(Instant::now()) } }
use List::*; enum List { Cons(u32, Box<List>), Nil, } // Here we attach methods to an enum impl List { // creates an empty list fn new() -> List { Nil } // prepends values to list fn prepend(self, elem: u32) -> List { Cons(elem, Box::new(self)) } // returns length of list fn len(&self) -> u32 { match *self { Cons(_, ref tail) => 1 + tail.len(), Nil => 0 } } fn stringify(&self) -> String { match *self { // prefer to match on concrete type, not reference. // self here is borrowed, so we can't take ownership of tail. // i'm not really sure what any of that means, but let's just // roll with it. // i guess we're actually destructuring Cons here. Cons(head, ref tail) => { format!("{}, {}", head, tail.stringify()) }, Nil => { format!("Nil") }, } } } fn main() { let mut list = List::new(); list = list.prepend(1); list = list.prepend(2); list = list.prepend(3); println!("linked list has length: {}", list.len()); println!("{}", list.stringify()); }
extern crate rand; use std::collections::HashMap; use self::rand::{thread_rng, Rng}; #[derive(Debug)] pub struct Chain { pub map: HashMap<String, Vec<String>>, pub gramcount: usize, } impl Chain { pub fn new(count: usize) -> Chain { Chain { map: HashMap::with_capacity(8_000_000), gramcount: count } } pub fn parse(&mut self, content: &str) { let mut buffer = Vec::new(); let mut word = String::new(); for character in content.chars() { if character == '\n' { buffer.push(word); if buffer.len() == self.gramcount + 1 { self.insert_pair(&buffer); } buffer = Vec::new(); word = String::new(); } else if character == ' ' { buffer.push(word); word = String::new(); if buffer.len() == self.gramcount + 1 { self.insert_pair(&buffer); buffer = buffer.iter().skip(1).map(|s| s.to_string()).collect(); word = String::new(); } } else { word.push(character); } } if buffer.len() == self.gramcount + 1 { self.insert_pair(&buffer); } } fn insert_pair(&mut self, buffer: &Vec<String>) { let key_vec = buffer .iter() .take(self.gramcount) .map(|s| s.to_string()) .collect::<Vec<String>>(); let key = key_vec.join(" "); let value = buffer.iter().nth(self.gramcount).expect("could not get last value"); self.insert(key, value.to_string()); } pub fn insert(&mut self, key: String, value: String) { if self.map.contains_key(&key) { let old_value = self.map.get_mut(&key).unwrap(); old_value.push(value); } else { self.map.insert(key, vec!(value)); } } pub fn sentence(&self) -> String { let key = self.random_key(); let values = self.map.get(key).expect("could not fetch values"); let value = random_value(values); let mut sentence = format!("{} {}", key, value); loop { let copy_sentence = sentence.clone(); let words: Vec<&str> = copy_sentence.split(" ").collect(); let key = words.iter() .skip(words.len() - self.gramcount) .map(|s| s.to_string()) .collect::<Vec<String>>() .join(" "); match self.map.get(&key) { Some(values) => { let value = random_value(values); sentence = format!("{} {}", sentence, value); } None => break } } sentence } fn random_key(&self) -> &str { let mut rng = thread_rng(); let keys = self.map.keys().collect::<Vec<&String>>(); let key = rng.choose(&keys).expect("could not get random key"); key } } fn random_value(words: &Vec<String>) -> String { let mut rng = thread_rng(); rng.choose(&words).expect("could not get random word").clone() }
#[no_mangle] pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_legendre_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, link_stiffness: f64, link_energy: f64, force: f64, temperature: f64) -> f64 { super::helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &link_stiffness, &link_energy, &force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_legendre_helmholtz_free_energy_per_link(link_length: f64, hinge_mass: f64, link_stiffness: f64, link_energy: f64, force: f64, temperature: f64) -> f64 { super::helmholtz_free_energy_per_link(&link_length, &hinge_mass, &link_stiffness, &link_energy, &force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_legendre_relative_helmholtz_free_energy(number_of_links: u8, link_length: f64, link_stiffness: f64, link_energy: f64, force: f64, temperature: f64) -> f64 { super::relative_helmholtz_free_energy(&number_of_links, &link_length, &link_stiffness, &link_energy, &force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_legendre_relative_helmholtz_free_energy_per_link(link_length: f64, link_stiffness: f64, link_energy: f64, force: f64, temperature: f64) -> f64 { super::relative_helmholtz_free_energy_per_link(&link_length, &link_stiffness, &link_energy, &force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_legendre_nondimensional_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, nondimensional_link_stiffness: f64, nondimensional_link_energy: f64, nondimensional_force: f64, temperature: f64) -> f64 { super::nondimensional_helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &nondimensional_link_stiffness, &nondimensional_link_energy, &nondimensional_force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_legendre_nondimensional_helmholtz_free_energy_per_link(link_length: f64, hinge_mass: f64, nondimensional_link_stiffness: f64, nondimensional_link_energy: f64, nondimensional_force: f64, temperature: f64) -> f64 { super::nondimensional_helmholtz_free_energy_per_link(&link_length, &hinge_mass, &nondimensional_link_stiffness, &nondimensional_link_energy, &nondimensional_force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_legendre_nondimensional_relative_helmholtz_free_energy(number_of_links: u8, nondimensional_link_stiffness: f64, nondimensional_link_energy: f64, nondimensional_force: f64) -> f64 { super::nondimensional_relative_helmholtz_free_energy(&number_of_links, &nondimensional_link_stiffness, &nondimensional_link_energy, &nondimensional_force) } #[no_mangle] pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_legendre_nondimensional_relative_helmholtz_free_energy_per_link(nondimensional_link_stiffness: f64, nondimensional_link_energy: f64, nondimensional_force: f64) -> f64 { super::nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_link_stiffness, &nondimensional_link_energy, &nondimensional_force) }
pub mod sys; pub mod error; use core::iter::FusedIterator; use std::io; /// Get an `Iterator` over all USB devices identified by your operating system. /// /// Note that the return value for this iterator is a `Result`. /// You may need to use a try operator `?` after the function call `devices()` /// if you want to iterate everything in it by using `for` statements. /// That's because a `Result` is also an `Iterator`, and its `Item` is `Devices` /// other than `Device` expected. pub fn devices<'list>() -> io::Result<DeviceList<'list>> { sys::devices().map(|inner| DeviceList { inner }) } #[derive(Debug, Clone)] pub struct DeviceList<'list> { inner: sys::DeviceList<'list> } impl<'list> DeviceList<'list> { pub fn iter<'iter>(&self) -> Devices<'iter> { Devices { inner: self.inner.iter() } } pub fn len(&self) -> usize { self.inner.len() } } /// An `Iterator` for USB devices. #[derive(Debug, Clone)] pub struct Devices<'iter> { inner: sys::Devices<'iter>, } impl<'iter> Iterator for Devices<'iter> { type Item = io::Result<Device<'iter>>; fn next(&mut self) -> Option<Self::Item> { self.inner.next().map(|res| res.map(|inner| Device { inner })) } } impl FusedIterator for Devices<'_> {} /// An owned iterator for USB devices. #[derive(Debug, Clone)] pub struct DeviceIntoIter<'iter> { inner: sys::DeviceIntoIter<'iter>, } impl<'list> IntoIterator for DeviceList<'list> { type Item = io::Result<Device<'list>>; type IntoIter = DeviceIntoIter<'list>; fn into_iter(self) -> Self::IntoIter { DeviceIntoIter { inner: self.inner.into_iter() } } } impl<'iter> Iterator for DeviceIntoIter<'iter> { type Item = io::Result<Device<'iter>>; fn next(&mut self) -> Option<Self::Item> { self.inner.next().map(|res| res.map(|inner| Device { inner })) } } /// A path struct representing a certain USB device connected to underlying OS. #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub struct Device<'device> { inner: sys::Device<'device>, } impl<'device> Device<'device> { pub fn open<'handle>(&self) -> io::Result<Handle<'handle>> { self.inner.open().map(|inner| Handle { inner }) } } /// A connection handle to the remote device. /// /// Underlying code must ensure that this handle implements `Drop` and all relevant /// resources are freed during their `drop` operations. #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub struct Handle<'handle> { inner: sys::Handle<'handle>, } impl<'handle> Handle<'handle> { pub fn device_descriptor(&self) -> io::Result<DeviceDescriptor> { self.inner.device_descriptor() } pub fn speed(&self) -> io::Result<crate::Speed> { self.inner.speed() } pub fn read_pipe(&self, pipe_index: u8, buf: &mut [u8]) -> io::Result<usize> { self.inner.read_pipe(pipe_index, buf) } pub fn write_pipe(&self, pipe_index: u8, buf: &[u8]) -> io::Result<usize> { self.inner.write_pipe(pipe_index, buf) } pub fn flush_pipe(&self, pipe_index: u8) -> io::Result<()> { self.inner.flush_pipe(pipe_index) } } /// A `DeviceDescriptor` describing what this name represents in the USB specification #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub struct DeviceDescriptor { pub length: u8, pub descriptor_type: u8, pub bcd_usb: u16, pub device_class: u8, pub device_sub_class: u8, pub device_protocol: u8, pub max_packet_size_0: u8, pub id_vendor: u16, pub id_product: u16, pub bcd_device: u16, pub manufacturer: u8, pub product: u8, pub serial_number: u8, pub num_configurations: u8, } /// An `InterfaceDescriptor` describing what this name represents in the USB specification #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub struct InterfaceDescriptor { pub length: u8, pub descriptor_type: u8, pub interface_number: u8, pub alternate_setting: u8, pub num_endpoints: u8, pub interface_class: u8, pub interface_subclass: u8, pub interface_protocol: u8, pub index_interface: u8, } #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum Speed { Unknown, Low, Full, High, Super, }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00..0x100 - DFSDM channel configuration cluster"] pub ch: [CH; 8], #[doc = "0x100..0x300 - DFSDM cluster: CR1, CR2, ISR, ICR, JCHGR, FCR, JDATAR, RDATAR, AWHTR, AWLTR, AWSR, AWCFR, EXMAX, EXMIN, CNVTIMR registers"] pub flt: [FLT; 4], } #[doc = "DFSDM channel configuration cluster"] pub use self::ch::CH; #[doc = r"Cluster"] #[doc = "DFSDM channel configuration cluster"] pub mod ch; #[doc = "DFSDM cluster: CR1, CR2, ISR, ICR, JCHGR, FCR, JDATAR, RDATAR, AWHTR, AWLTR, AWSR, AWCFR, EXMAX, EXMIN, CNVTIMR registers"] pub use self::flt::FLT; #[doc = r"Cluster"] #[doc = "DFSDM cluster: CR1, CR2, ISR, ICR, JCHGR, FCR, JDATAR, RDATAR, AWHTR, AWLTR, AWSR, AWCFR, EXMAX, EXMIN, CNVTIMR registers"] pub mod flt;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum Explain { Boost(f32), MaxTokenToTextId(f32), TermToAnchor { term_score: f32, anchor_score: f32, final_score: f32, term_id: u32, }, LevenshteinScore { score: f32, text_or_token_id: String, term_id: u32, }, OrSumOverDistinctTerms(f32), NumDistintTermsBoost { distinct_boost: u32, new_score: u32, }, }
use exonum::{ blockchain::{ExecutionError, ExecutionResult, Transaction, TransactionContext}, crypto::{PublicKey, SecretKey}, messages::{Message, RawTransaction, Signed}, }; use crate::currency::schema::Schema as CurrencySchema; use crate::lvm::{proto, runner::Runner, schema::Schema as LvmSchema, service::LVM_SERVICE_ID}; #[derive(Debug, Fail)] #[repr(u8)] pub enum Error { #[fail(display = "Contract already exists")] ContractAlreadyExists = 0, #[fail(display = "Contract not exists")] ContractNotExists = 1, #[fail(display = "Contract execution error")] ContractExecutionError = 2, } impl From<Error> for ExecutionError { fn from(value: Error) -> ExecutionError { let description = format!("{}", value); ExecutionError::with_description(value as u8, description) } } #[derive(Serialize, Deserialize, Clone, Debug, ProtobufConvert)] #[exonum(pb = "proto::CreateContract")] pub struct CreateContract { pub pub_key: PublicKey, pub code: String, } #[derive(Serialize, Deserialize, Clone, Debug, ProtobufConvert)] #[exonum(pb = "proto::CallContract")] pub struct CallContract { pub pub_key: PublicKey, pub fn_name: String, pub args: Vec<String>, } #[derive(Serialize, Deserialize, Clone, Debug, TransactionSet)] pub enum LvmTransactions { CreateContract(CreateContract), CallContract(CallContract), } impl CreateContract { #[doc(hidden)] pub fn sign( pub_key: &PublicKey, code: &str, pk: &PublicKey, sk: &SecretKey, ) -> Signed<RawTransaction> { Message::sign_transaction( Self { pub_key: *pub_key, code: code.to_string(), }, LVM_SERVICE_ID, *pk, sk, ) } } impl CallContract { #[doc(hidden)] pub fn sign( pub_key: &PublicKey, fn_name: &str, args: &Vec<String>, pk: &PublicKey, sk: &SecretKey, ) -> Signed<RawTransaction> { Message::sign_transaction( Self { pub_key: *pub_key, fn_name: fn_name.to_string(), args: args.clone(), }, LVM_SERVICE_ID, *pk, sk, ) } } impl Transaction for CreateContract { fn execute(&self, mut context: TransactionContext) -> ExecutionResult { { let mut schema = LvmSchema::new(context.fork()); match schema.contract(&self.pub_key) { None => { schema.create_contract(&self.pub_key, &self.code); } Some(_) => Err(Error::ContractAlreadyExists)?, } } { let hash = context.tx_hash(); let mut schema = CurrencySchema::new(context.fork()); if schema.wallet(&self.pub_key).is_none() { let name = format!("contract-{}", &self.pub_key); schema.create_wallet(&self.pub_key, &name, &hash); } else { Err(Error::ContractAlreadyExists)? } } Ok(()) } } impl Transaction for CallContract { fn execute(&self, mut context: TransactionContext) -> ExecutionResult { let contract = { let schema = LvmSchema::new(context.fork()); match schema.contract(&self.pub_key) { Some(c) => c, None => Err(Error::ContractNotExists)?, } }; let contract_wallet = { let schema = CurrencySchema::new(context.fork()); match schema.wallet(&self.pub_key) { Some(w) => w, None => Err(Error::ContractNotExists)?, } }; let runner = Runner { contract, contract_wallet, context: &mut context, }; match runner.exec(&self.fn_name, self.args.clone()) { Ok(contract) => { let mut schema = LvmSchema::new(context.fork()); schema.contracts_mut().put(&self.pub_key, contract); Ok(()) } Err(desc) => Err(ExecutionError::with_description( Error::ContractExecutionError as u8, desc, )), } } }
use super::*; #[test] fn test_header_marshalling() -> Result<(), Box<Error>> { let internal_header: InternalHeader = InternalHeader { typ: Typ::BWTv0, iat: 1, exp: 2, kid: [0u8; 16], nonce: [0u8; 12], base64_kid: "AAAAAAAAAAAAAAAAAAAAAA==".to_string(), }; let header: Header = Header { typ: Typ::BWTv0, iat: 1, exp: 2, kid: [0u8; 16], }; let buf: [u8; HEADER_BYTES] = internal_header.clone().into(); let internal_header_a: InternalHeader = InternalHeader::try_from(&buf[..])?; let internal_header_b: InternalHeader = InternalHeader::try_from((&header, &internal_header.nonce[..]))?; let header_a: Header = internal_header.clone().into(); assert_eq!(internal_header_a.nonce, internal_header.nonce); assert_eq!(internal_header_a.typ, internal_header.typ); assert_eq!(internal_header_a.iat, internal_header.iat); assert_eq!(internal_header_a.exp, internal_header.exp); assert_eq!(internal_header_a.kid, internal_header.kid); assert_eq!(internal_header_b.nonce, internal_header.nonce); assert_eq!(internal_header_b.typ, internal_header.typ); assert_eq!(internal_header_b.iat, internal_header.iat); assert_eq!(internal_header_b.exp, internal_header.exp); assert_eq!(internal_header_b.kid, internal_header.kid); assert_eq!(header_a.typ, header.typ); assert_eq!(header_a.iat, header.iat); assert_eq!(header_a.exp, header.exp); assert_eq!(header_a.kid, header.kid); Ok(()) } #[test] fn test_peer_public_key_map() -> Result<(), Box<Error>> { let peer_public_keys: Vec<PeerPublicKey> = vec![ PeerPublicKey { public_key: [0u8; PUBLIC_KEY_BYTES], kid: [77, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], }, PeerPublicKey { public_key: [0u8; PUBLIC_KEY_BYTES], kid: [99, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], }, ]; let PeerPublicKeyMap(public_key_map): PeerPublicKeyMap = PeerPublicKeyMap::from(&peer_public_keys[..]); assert_eq!(public_key_map.len(), 2usize); assert_eq!(public_key_map.get("QldU"), None); let base64_kid_0: String = base64_encode(&peer_public_keys[0].kid); let public_key_0: &[u8; PUBLIC_KEY_BYTES] = public_key_map.get(&base64_kid_0).unwrap(); let base64_kid_1: String = base64_encode(&peer_public_keys[1].kid); let public_key_1: &[u8; PUBLIC_KEY_BYTES] = public_key_map.get(&base64_kid_1).unwrap(); assert_eq!(*public_key_0, [0u8; PUBLIC_KEY_BYTES]); assert_eq!(*public_key_1, [0u8; PUBLIC_KEY_BYTES]); Ok(()) } #[test] fn test_concat_token() -> Result<(), Box<Error>> { let aad: Vec<u8> = vec![66]; let ciphertext: Vec<u8> = vec![87]; let tag: Vec<u8> = vec![84]; let token: String = concat_token(&aad, &ciphertext, &tag); assert_eq!(&token, "Qg==.Vw==.VA=="); Ok(()) } #[test] fn test_is_valid_header() -> Result<(), Box<Error>> { let invalid_header: Header = Header { typ: Typ::BWTv0, iat: 0, exp: 1, kid: [0u8; KID_BYTES], }; let valid_header: Header = Header { typ: Typ::BWTv0, iat: 0, exp: 9999999999999, kid: [0u8; KID_BYTES], }; assert!(!invalid_header.is_valid()); assert!(valid_header.is_valid()); Ok(()) } #[test] fn test_is_valid_internal_header() -> Result<(), Box<Error>> { let invalid_internal_header: InternalHeader = InternalHeader { typ: Typ::BWTv0, iat: 0, exp: 1, kid: [0u8; KID_BYTES], nonce: [0u8; NONCE_BYTES], base64_kid: "deadbeefdeadbeefdeadbeef".to_string(), }; let valid_internal_header: InternalHeader = InternalHeader { typ: Typ::BWTv0, iat: 0, exp: 9999999999999, kid: [0u8; KID_BYTES], nonce: [0u8; NONCE_BYTES], base64_kid: "deadbeefdeadbeefdeadbeef".to_string(), }; assert!(!invalid_internal_header.is_valid()); assert!(valid_internal_header.is_valid()); Ok(()) }
use std::convert::TryInto; fn contains_forbidden_letters(input: &str) -> bool { let vowels = ['i', 'u', 'l']; input .chars() .fold(0, |count, c| count + vowels.contains(&c) as u32) > 0 } fn contains_increasing_three_letters(input: &str) -> bool { input .as_bytes() .windows(3) .any(|chars| chars[1] - chars[0] == 1 && chars[2] - chars[1] == 1) } fn has_pair_repetition(input: &str) -> bool { input .chars() .collect::<Vec<char>>() .windows(2) .enumerate() .any(|(pos, first)| { input .chars() .skip(pos + 2) .collect::<Vec<char>>() .windows(2) .any(|second| { first[0] == first[1] && second[0] == second[1] && first[0] != second[0] }) }) } fn validate_password(input: &str) -> bool { !contains_forbidden_letters(input) && contains_increasing_three_letters(input) && has_pair_repetition(input) } fn generate_next_password(mut input: [u8; 8]) -> String { while !validate_password(std::str::from_utf8(&input).unwrap()) { input[7] += 1; for i in (0..8).rev() { if input[i] > b'z' { input[i] = b'a'; input[i - 1] += 1; } if validate_password(std::str::from_utf8(&input).unwrap()) { break; } } } std::str::from_utf8(&input).unwrap().to_string() } fn part_1(input: &str) -> String { let input: [u8; 8] = input.as_bytes().try_into().unwrap(); generate_next_password(input) } fn main() { let content = "hepxcrrq"; println!("First puzzle: {}", part_1(content)); println!("Second puzzle: {}", part_1("hepxxzaa")); } #[cfg(test)] mod day11 { use super::*; #[test] fn test_contains_increasing_three_letters() { assert_eq!(true, contains_increasing_three_letters("hijklmmn")); assert_eq!(false, contains_increasing_three_letters("abbceffg")); assert_eq!(false, contains_increasing_three_letters("abbcegjk")); assert_eq!(false, contains_increasing_three_letters("")); } #[test] fn test_contains_forbidden_letters() { assert_eq!(true, contains_forbidden_letters("hijklmmn")); assert_eq!(false, contains_forbidden_letters("abbceffg")); assert_eq!(false, contains_forbidden_letters("abbcegjk")); assert_eq!(true, contains_forbidden_letters("iol")); assert_eq!(false, contains_forbidden_letters("")); } #[test] fn test_has_pair_repetition() { assert_eq!(true, has_pair_repetition("abbceffg")); assert_eq!(false, has_pair_repetition("abbcegjk")); assert_eq!(false, has_pair_repetition("aaa")); } #[test] fn test_validate_password() { assert_eq!(true, validate_password("abcdffaa")); assert_eq!(false, validate_password("aabbcciol")); } #[test] fn test_generate_next_password() { assert_eq!( "abcdffaa", generate_next_password("abcdefgh".as_bytes().try_into().unwrap()) ); } }
mod startup; mod stop; use super::RunnableCmd; pub use startup::StartupCmd; pub use stop::StopCmd; pub fn create_server_cmd(name: Option<String>, port: u16) -> Box<dyn RunnableCmd> { match name.as_ref().map(|s| s.as_ref()) { Some("start") => Box::new(StartupCmd::new("".to_owned(), port)), Some("stop") => Box::new(StopCmd::new("".to_owned(), port)), unknown => Box::new(UnknownServerCmd::new(unknown.map(|s| s.to_owned()))), } } struct UnknownServerCmd { name: Option<String>, } impl UnknownServerCmd { fn new(name: Option<String>) -> UnknownServerCmd { UnknownServerCmd { name } } } impl RunnableCmd for UnknownServerCmd { fn run(&mut self) -> Result<(), String> { match self.name { Some(ref cmd) => eprintln!("unrecognized server cmd: {}", cmd), None => eprintln!("no server cmd specified."), }; Ok(()) } }
mod handler; use handler::promote_handler; mod server; pub use server::Server; mod auth; pub use auth::AuthTokenExtractor; mod response; use response::Response;
extern crate petgraph; #[macro_use] extern crate lazy_static; pub mod trie; pub mod powerset; pub mod score_word; pub use self::trie::Trie; pub use self::powerset::powerset; pub use self::score_word::score_word;
use image::{DynamicImage, LumaA}; use once_cell::sync::Lazy; use rusttype::{point, Font, Scale, ScaledGlyph}; use std::io::Cursor; static DEJA_VU_MONO: Lazy<Font<'static>> = Lazy::new(|| { Font::try_from_bytes(include_bytes!("../fonts/dejavu/DejaVuSansMono.ttf") as &[u8]).unwrap() }); static OPEN_SANS_ITALIC: Lazy<Font<'static>> = Lazy::new(|| { Font::try_from_bytes(include_bytes!("../fonts/opensans/OpenSans-Italic.ttf") as &[u8]).unwrap() }); static EXO2_OFT: Lazy<Font<'static>> = Lazy::new(|| Font::try_from_bytes(include_bytes!("../fonts/Exo2-Light.otf") as &[u8]).unwrap()); fn draw_luma_alpha(glyph: ScaledGlyph<'_>) -> image::GrayAlphaImage { let glyph = glyph.positioned(point(0.0, 0.0)); let bounds = glyph.pixel_bounding_box().unwrap(); let mut glyph_image = DynamicImage::new_luma_a8(bounds.width() as _, bounds.height() as _).into_luma_alpha8(); glyph.draw(|x, y, v| glyph_image.put_pixel(x, y, LumaA([128, (v * 255.0) as u8]))); glyph_image } /// Render a 600px U+2623 character require it to match the reference with /// 8-bit accuracy #[test] fn render_to_reference_big_biohazard() { let new_image = draw_luma_alpha(DEJA_VU_MONO.glyph('☣').scaled(Scale::uniform(600.0))); // save the new render for manual inspection new_image.save("../target/big_biohazard.png").unwrap(); let reference = image::load( Cursor::new(include_bytes!("reference_big_biohazard.png") as &[u8]), image::ImageFormat::Png, ) .expect("!image::load") .into_luma_alpha8(); assert_eq!(reference.dimensions(), new_image.dimensions()); for y in 0..reference.height() { for x in 0..reference.width() { assert_eq!( reference.get_pixel(x, y), new_image.get_pixel(x, y), "unexpected alpha difference at ({}, {})", x, y ); } } } /// Render a 16px 'w' character require it to match the reference with 8-bit /// accuracy #[test] fn render_to_reference_w() { let new_image = draw_luma_alpha(DEJA_VU_MONO.glyph('w').scaled(Scale::uniform(16.0))); // save the new render for manual inspection new_image.save("../target/w.png").unwrap(); let reference = image::load( Cursor::new(include_bytes!("reference_w.png") as &[u8]), image::ImageFormat::Png, ) .expect("!image::load") .into_luma_alpha8(); assert_eq!(reference.dimensions(), new_image.dimensions()); for y in 0..reference.height() { for x in 0..reference.width() { assert_eq!( reference.get_pixel(x, y), new_image.get_pixel(x, y), "unexpected alpha difference at ({}, {})", x, y ); } } } /// Render a 60px 'ΐ' character require it to match the reference with 8-bit /// accuracy #[test] fn render_to_reference_iota() { let new_image = draw_luma_alpha(OPEN_SANS_ITALIC.glyph('ΐ').scaled(Scale::uniform(60.0))); // save the new render for manual inspection new_image.save("../target/iota.png").unwrap(); let reference = image::load( Cursor::new(include_bytes!("reference_iota.png") as &[u8]), image::ImageFormat::Png, ) .expect("!image::load") .into_luma_alpha8(); assert_eq!(reference.dimensions(), new_image.dimensions()); for y in 0..reference.height() { for x in 0..reference.width() { assert_eq!( reference.get_pixel(x, y), new_image.get_pixel(x, y), "unexpected alpha difference at ({}, {})", x, y ); } } } /// Render a 300px 'ę' character that uses cubic beziers & require it to match /// the reference. #[test] fn render_to_reference_oft_tailed_e() { let new_image = draw_luma_alpha(EXO2_OFT.glyph('ę').scaled(Scale::uniform(300.0))); // save the new render for manual inspection new_image.save("../target/otf_tailed_e.png").unwrap(); let reference = image::load( Cursor::new(include_bytes!("reference_otf_tailed_e.png") as &[u8]), image::ImageFormat::Png, ) .expect("!image::load") .into_luma_alpha8(); assert_eq!(reference.dimensions(), new_image.dimensions()); for y in 0..reference.height() { for x in 0..reference.width() { assert_eq!( reference.get_pixel(x, y), new_image.get_pixel(x, y), "unexpected alpha difference at ({}, {})", x, y ); } } }
mod mappers; mod maps; mod mapsets; mod mods; use std::sync::Arc; use twilight_model::application::{ command::CommandOptionChoice, interaction::{application_command::CommandOptionValue, ApplicationCommand}, }; use crate::{ commands::{MyCommand, MyCommandOption}, core::Context, error::Error, BotResult, }; pub use self::mapsets::MapsetEntry; enum PopularCommandKind { Maps { pp: u32 }, Mapsets, Mappers, Mods, } impl PopularCommandKind { fn slash(command: &mut ApplicationCommand) -> BotResult<Self> { let option = command .data .options .pop() .ok_or(Error::InvalidCommandOptions)?; match option.value { CommandOptionValue::SubCommand(options) => match option.name.as_str() { "maps" => { let mut pp = None; for option in options { match option.value { CommandOptionValue::String(value) => match option.name.as_str() { "pp" => { let value = value .split('_') .next() .map(str::parse) .map(Result::ok) .flatten() .ok_or(Error::InvalidCommandOptions)?; pp = Some(value); } _ => return Err(Error::InvalidCommandOptions), }, _ => return Err(Error::InvalidCommandOptions), } } let pp = pp.ok_or(Error::InvalidCommandOptions)?; Ok(PopularCommandKind::Maps { pp }) } "mapsets" => Ok(PopularCommandKind::Mapsets), "mods" => Ok(PopularCommandKind::Mods), "mappers" => Ok(PopularCommandKind::Mappers), _ => Err(Error::InvalidCommandOptions), }, _ => Err(Error::InvalidCommandOptions), } } } pub async fn slash_popular(ctx: Arc<Context>, mut command: ApplicationCommand) -> BotResult<()> { match PopularCommandKind::slash(&mut command)? { PopularCommandKind::Maps { pp } => maps::maps_(ctx, command.into(), pp).await, PopularCommandKind::Mapsets => mapsets::mapsets_(ctx, command.into()).await, PopularCommandKind::Mappers => mappers::mappers_(ctx, command.into()).await, PopularCommandKind::Mods => mods::mods_(ctx, command.into()).await, } } fn subcommand_maps() -> MyCommandOption { let pp_choices = vec![ CommandOptionChoice::String { name: "100-200pp".to_owned(), value: "100_200".to_owned(), }, CommandOptionChoice::String { name: "200-300pp".to_owned(), value: "200_300".to_owned(), }, CommandOptionChoice::String { name: "300-400pp".to_owned(), value: "300_400".to_owned(), }, CommandOptionChoice::String { name: "400-500pp".to_owned(), value: "400_500".to_owned(), }, CommandOptionChoice::String { name: "500-600pp".to_owned(), value: "500_600".to_owned(), }, CommandOptionChoice::String { name: "600-700pp".to_owned(), value: "600_700".to_owned(), }, CommandOptionChoice::String { name: "700-800pp".to_owned(), value: "700_800".to_owned(), }, CommandOptionChoice::String { name: "800-900pp".to_owned(), value: "800_900".to_owned(), }, CommandOptionChoice::String { name: "900-1000pp".to_owned(), value: "900_1000".to_owned(), }, CommandOptionChoice::String { name: "1000-1100pp".to_owned(), value: "1000_1100".to_owned(), }, CommandOptionChoice::String { name: "1100-1200pp".to_owned(), value: "1100_1200".to_owned(), }, CommandOptionChoice::String { name: "1200-1300pp".to_owned(), value: "1200_1300".to_owned(), }, ]; let pp = MyCommandOption::builder("pp", "Specify a pp range").string(pp_choices, true); MyCommandOption::builder("maps", "What are the most common maps per pp range?") .subcommand(vec![pp]) } fn subcommand_mapsets() -> MyCommandOption { let description = "What mapsets appear the most in people's top100?"; MyCommandOption::builder("mapsets", description).subcommand(Vec::new()) } fn subcommand_mods() -> MyCommandOption { MyCommandOption::builder("mods", "What mods appear the most in people's top100?") .subcommand(Vec::new()) } fn subcommand_mappers() -> MyCommandOption { let description = "What mappers' mapsets appear the most in people's top100?"; MyCommandOption::builder("mappers", description).subcommand(Vec::new()) } pub fn define_popular() -> MyCommand { let help = "Check out the most popular map(set)s, mods, or mappers.\n\ All data is provided by [nzbasic](https://osu.ppy.sh/users/9008211)'s website [osutracker](https://osutracker.com/)."; let options = vec![ subcommand_maps(), subcommand_mapsets(), subcommand_mods(), subcommand_mappers(), ]; let description = "Check out the most popular map(set)s, mods, or mappers"; MyCommand::new("popular", description) .help(help) .options(options) }
use std::cmp::{max, min, Ordering}; use std::ops::Range; use std::ops::RangeInclusive; use crate::extended_time::ExtendedTime; pub fn wrapping_range_contains<T: PartialOrd>(range: &RangeInclusive<T>, elt: &T) -> bool { if range.start() <= range.end() { range.contains(elt) } else { range.start() <= elt || elt <= range.end() } } // TODO: can we gain performances by returning an iterator (requires custom implem). pub fn time_ranges_union( ranges: impl Iterator<Item = Range<ExtendedTime>>, ) -> Vec<Range<ExtendedTime>> { let mut ranges: Vec<_> = ranges.collect(); let mut output = Vec::new(); // Get ranges by increasing start ranges.sort_unstable_by_key(|range| range.start); let mut ranges = ranges.into_iter(); if let Some(mut current) = ranges.next() { for item in ranges { assert!(item.start >= current.start); if current.end >= item.start { // The two intervals intersect with each other current.end = max(current.end, item.end); } else { output.push(current); current = item; } } output.push(current); } output } pub fn range_intersection<T: Ord>(range_1: Range<T>, range_2: Range<T>) -> Option<Range<T>> { let result = max(range_1.start, range_2.start)..min(range_1.end, range_2.end); if result.start < result.end { Some(result) } else { None } } pub fn is_sorted<T: PartialOrd>(slice: &[T]) -> bool { if let Some(mut curr) = slice.first() { for x in &slice[1..] { if x >= curr { curr = x; } else { return false; } } } true } pub fn union_sorted<T: Clone + Ord>(vec_1: &[T], vec_2: &[T]) -> Vec<T> { debug_assert!(is_sorted(vec_1)); debug_assert!(is_sorted(vec_2)); match (vec_1, vec_2) { ([], vec) | (vec, []) => vec.to_vec(), ([head_1 @ .., tail_1], [head_2 @ .., tail_2]) => { let build_with = |for_head_1, for_head_2, tail| { let mut res = union_sorted(for_head_1, for_head_2); res.push(tail); res }; match tail_1.cmp(tail_2) { Ordering::Equal => build_with(head_1, head_2, tail_1.clone()), Ordering::Less => build_with(vec_1, head_2, tail_2.clone()), Ordering::Greater => build_with(head_1, vec_2, tail_1.clone()), } } } }
pub mod math_library; // mod premutations { // fn count() { } // } // mod really_big_int { // fn addition() { } // } pub mod utilities { pub fn format_milliseconds(total_milliseconds: i64) -> String { let milliseconds = total_milliseconds % 1000; let totalseconds = total_milliseconds / 1000; let seconds = totalseconds % 60; let totalminutes = totalseconds / 60; let minutes = totalminutes % 60; let hours = totalminutes / 60; let mut format_seconds = seconds.to_string(); let mut format_minutes = minutes.to_string(); let mut format_hours = hours.to_string(); let format_milliseconds: String = if milliseconds < 10 { "00".to_owned() + &milliseconds.to_string() } else if milliseconds < 100 { "0".to_owned() + &milliseconds.to_string() } else { milliseconds.to_string() }; if seconds < 10 { format_seconds = "0".to_owned() + &format_seconds; } if minutes < 10 { format_minutes = "0".to_owned() + &format_minutes; } if hours < 10 { format_hours = "0".to_owned() + &format_hours; } format_hours + ":" + &format_minutes + ":" + &format_seconds + ":" + &format_milliseconds } } pub mod problems;
use std::cmp::max; use std::any::Any; use Cursive; use align::*; use event::*; use theme::ColorStyle; use view::{Selector, TextView, View}; use view::{Button, SizedView}; use vec::{ToVec4, Vec2, Vec4}; use printer::Printer; use unicode_width::UnicodeWidthStr; #[derive(PartialEq)] enum Focus { Content, Button(usize), } /// Popup-like view with a main content, and optional buttons under it. /// /// # Examples /// /// ``` /// # use cursive::view::{Dialog,TextView}; /// let dialog = Dialog::new(TextView::new("Hello!")) /// .button("Ok", |s| s.quit()); /// ``` pub struct Dialog { title: String, content: Box<View>, buttons: Vec<SizedView<Button>>, padding: Vec4, borders: Vec4, focus: Focus, align: Align, } impl Dialog { /// Creates a new Dialog with the given content. pub fn new<V: View + 'static>(view: V) -> Self { Dialog { content: Box::new(view), buttons: Vec::new(), title: String::new(), focus: Focus::Content, padding: Vec4::new(1, 1, 0, 0), borders: Vec4::new(1, 1, 1, 1), align: Align::top_right(), } } pub fn info(text: &str) -> Self { Self::new(TextView::new(text)).dismiss_button("Ok") } /// Adds a button to the dialog with the given label and callback. /// /// Consumes and returns self for easy chaining. pub fn button<F>(mut self, label: &str, cb: F) -> Self where F: Fn(&mut Cursive) + 'static { self.buttons.push(SizedView::new(Button::new(label, cb))); self } /// Sets the horizontal alignment for the buttons, if any. /// Only works if the buttons are as a row at the bottom of the dialog. pub fn h_align(mut self, h: HAlign) -> Self { self.align.h = h; self } /// Sets the vertical alignment for the buttons, if any. /// Only works if the buttons are as a column to the right of the dialog. pub fn v_align(mut self, v: VAlign) -> Self { self.align.v = v; self } /// Shortcut method to add a button that will dismiss the dialog. pub fn dismiss_button(self, label: &str) -> Self { self.button(label, |s| s.screen_mut().pop_layer()) } /// Sets the title of the dialog. /// If not empty, it will be visible at the top. pub fn title(mut self, label: &str) -> Self { self.title = label.to_string(); self } /// Sets the padding in the dialog (around content and buttons). pub fn padding<T: ToVec4>(mut self, padding: T) -> Self { self.padding = padding.to_vec4(); self } } impl View for Dialog { fn draw(&mut self, printer: &Printer) { // This will be the buttons_height used by the buttons. let mut buttons_height = 0; // Current horizontal position of the next button we'll draw. // Sum of the sizes + len-1 for margins let width = if self.buttons.is_empty() { 0 } else { self.buttons .iter() .map(|button| button.size.x) .fold(0, |a, b| a + b) + self.buttons.len() - 1 }; let overhead = self.padding + self.borders; let mut offset = overhead.left + self.align .h .get_offset(width, printer.size.x - overhead.horizontal()); let y = printer.size.y - self.padding.bottom - self.borders.bottom - 1; for (i, button) in self.buttons.iter_mut().enumerate() { let size = button.size; // Add some special effect to the focused button button.draw(&printer.sub_printer(Vec2::new(offset, y), size, self.focus == Focus::Button(i))); // Keep 1 blank between two buttons offset += size.x + 1; // Also keep 1 blank above the buttons buttons_height = max(buttons_height, size.y + 1); } // What do we have left? let inner_size = printer.size - Vec2::new(0, buttons_height) - self.borders.combined() - self.padding.combined(); self.content .draw(&printer.sub_printer(self.borders.top_left() + self.padding.top_left(), inner_size, self.focus == Focus::Content)); printer.print_box(Vec2::new(0, 0), printer.size); if !self.title.is_empty() { let len = self.title.width(); let x = (printer.size.x - len) / 2; printer.print((x - 2, 0), "┤ "); printer.print((x + len, 0), " ├"); printer.with_color(ColorStyle::TitlePrimary, |p| p.print((x, 0), &self.title)); } } fn get_min_size(&mut self, req: Vec2) -> Vec2 { // Padding and borders are not available for kids. let nomans_land = self.padding.combined() + self.borders.combined(); // Buttons are not flexible, so their size doesn't depend on ours. let mut buttons_size = Vec2::new(0, 0); if !self.buttons.is_empty() { buttons_size.x += self.buttons.len() - 1; } for button in &mut self.buttons { let s = button.view.get_min_size(req); buttons_size.x += s.x; buttons_size.y = max(buttons_size.y, s.y + 1); } // We also remove one row for the buttons. let content_req = req - (nomans_land + Vec2::new(0, buttons_size.y)); let content_size = self.content.get_min_size(content_req); // On the Y axis, we add buttons and content. // On the X axis, we take the max. let mut inner_size = Vec2::new(max(content_size.x, buttons_size.x), content_size.y + buttons_size.y) + self.padding.combined() + self.borders.combined(); if !self.title.is_empty() { // If we have a title, we have to fit it too! inner_size.x = max(inner_size.x, self.title.width() + 6); } inner_size } fn layout(&mut self, mut size: Vec2) { // Padding and borders are taken, sorry. // TODO: handle border-less themes? size = size - (self.borders.combined() + self.padding.combined()); // Buttons are kings, we give them everything they want. let mut buttons_height = 0; for button in self.buttons.iter_mut().rev() { let size = button.get_min_size(size); buttons_height = max(buttons_height, size.y + 1); button.layout(size); } // Poor content will have to make do with what's left. self.content.layout(size - Vec2::new(0, buttons_height)); } fn on_event(&mut self, event: Event) -> EventResult { match self.focus { // If we are on the content, we can only go down. Focus::Content => { match self.content.on_event(event) { EventResult::Ignored if !self.buttons.is_empty() => { match event { Event::Key(Key::Down) | Event::Key(Key::Tab) | Event::Key(Key::ShiftTab) => { // Default to leftmost button when going down. self.focus = Focus::Button(0); EventResult::Consumed(None) } _ => EventResult::Ignored, } } res => res, } } // If we are on a button, we have more choice Focus::Button(i) => { match self.buttons[i].on_event(event) { EventResult::Ignored => { match event { // Up goes back to the content Event::Key(Key::Up) | Event::Key(Key::Tab) | Event::Key(Key::ShiftTab) => { if self.content.take_focus() { self.focus = Focus::Content; EventResult::Consumed(None) } else { EventResult::Ignored } } // Left and Right move to other buttons Event::Key(Key::Right) if i + 1 < self.buttons .len() => { self.focus = Focus::Button(i + 1); EventResult::Consumed(None) } Event::Key(Key::Left) if i > 0 => { self.focus = Focus::Button(i - 1); EventResult::Consumed(None) } _ => EventResult::Ignored, } } res => res, } } } } fn take_focus(&mut self) -> bool { // TODO: add a direction to the focus. Meanwhile, takes button first. if self.content.take_focus() { self.focus = Focus::Content; true } else if !self.buttons.is_empty() { self.focus = Focus::Button(0); true } else { false } } fn find(&mut self, selector: &Selector) -> Option<&mut Any> { self.content.find(selector) } }
use byteorder::*; use std::error::Error; use std::io::Cursor; use serde_derive::{Serialize, Deserialize}; use super::CallLoopRef; #[cfg(test)] mod tests { use super::*; #[test] fn test_sustain_not_note() { let mut first = ParameterizedCommand::new(Some(1), None, None, Command::Rest); let second = ParameterizedCommand::new(Some(1), None, None, Command::Rest); assert!(!first.set_sustain(&second)); assert!(first.sustain.is_none()); assert_eq!(1, first.duration.unwrap()); } #[test] fn test_sustain_not_followed_by_rest() { let mut first = ParameterizedCommand::new(Some(1), None, None, Command::Note(0)); let second = ParameterizedCommand::new(Some(1), None, None, Command::Tie); assert!(!first.set_sustain(&second)); assert!(first.sustain.is_none()); assert_eq!(1, first.duration.unwrap()); } #[test] fn test_sustain_half() { let mut first = ParameterizedCommand::new(Some(1), None, None, Command::Note(0)); let second = ParameterizedCommand::new(Some(1), None, None, Command::Rest); assert!(first.set_sustain(&second)); assert_eq!(4, first.sustain.unwrap()); assert_eq!(2, first.duration.unwrap()); } #[test] fn test_sustain_eighth() { let mut first = ParameterizedCommand::new(Some(1), None, None, Command::Note(0)); let second = ParameterizedCommand::new(Some(7), None, None, Command::Rest); assert!(first.set_sustain(&second)); assert_eq!(1, first.sustain.unwrap()); assert_eq!(8, first.duration.unwrap()); } #[test] fn test_sustain_five_eighths() { let mut first = ParameterizedCommand::new(Some(5), None, None, Command::Note(0)); let second = ParameterizedCommand::new(Some(3), None, None, Command::Rest); assert!(first.set_sustain(&second)); assert_eq!(5, first.sustain.unwrap()); assert_eq!(8, first.duration.unwrap()); } #[test] fn test_sustain_too_short() { let mut first = ParameterizedCommand::new(Some(1), None, None, Command::Note(0)); let second = ParameterizedCommand::new(Some(12), None, None, Command::Rest); assert!(!first.set_sustain(&second)); assert!(first.sustain.is_none()); assert_eq!(1, first.duration.unwrap()); } #[test] fn test_sustain_too_long() { let mut first = ParameterizedCommand::new(Some(12), None, None, Command::Note(0)); let second = ParameterizedCommand::new(Some(1), None, None, Command::Rest); assert!(!first.set_sustain(&second)); assert!(first.sustain.is_none()); assert_eq!(12, first.duration.unwrap()); } #[test] fn test_sustain_doesnt_divide_evenly() { let mut first = ParameterizedCommand::new(Some(5), None, None, Command::Note(0)); let second = ParameterizedCommand::new(Some(6), None, None, Command::Rest); assert!(!first.set_sustain(&second)); assert!(first.sustain.is_none()); assert_eq!(5, first.duration.unwrap()); } #[test] fn test_sustain_very_short_rest() { let mut first = ParameterizedCommand::new(Some(24), None, None, Command::Note(0)); let second = ParameterizedCommand::new(Some(1), None, None, Command::Rest); assert!(first.set_sustain(&second)); assert_eq!(7, first.sustain.unwrap()); assert_eq!(25, first.duration.unwrap()); } } #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Hash)] pub enum Command { Note(u8), Rest, Tie, SetInstrument(u8), Pan(u8), PanFade(u8, u8), Vibrato(u8, u8, u8), VibratoOff, MasterVolume(u8), MasterVolumeFade(u8, u8), Tempo(u8), TempoFade(u8, u8), GlobalTranspose(u8), ChannelTranspose(u8), Tremolo(u8, u8, u8), TremoloOff, ChannelVolume(u8), ChannelVolumeFade(u8), CallLoop(usize, u8), VibratoFade(u8), PitchEnvelopeTo(u8, u8, u8), PitchEnvelopeFrom(u8, u8, u8), PitchEnvelopeOff, Tuning(u8), EchoVolume(u8, u8, u8), EchoOff, EchoParams(u8, u8, u8), EchoVolumeFade(u8, u8, u8), PitchSlide(u8, u8, u8), PercussionPatchBase(u8), } impl Command { fn write( &self, out: &mut Cursor<Vec<u8>>, call_loops: &mut Vec<CallLoopRef>, ) -> Result<(), Box<Error>> { match *self { Command::Note(note) => { out.write_u8(note)?; } Command::Tie => { out.write_u8(0xc8)?; } Command::Rest => { out.write_u8(0xc9)?; } Command::SetInstrument(p1) => { out.write_u8(0xe0)?; out.write_u8(p1)?; } Command::Pan(p1) => { out.write_u8(0xe1)?; out.write_u8(p1)?; } Command::PanFade(p1, p2) => { out.write_u8(0xe2)?; out.write_u8(p1)?; out.write_u8(p2)?; } Command::Vibrato(p1, p2, p3) => { out.write_u8(0xe3)?; out.write_u8(p1)?; out.write_u8(p2)?; out.write_u8(p3)?; } Command::VibratoOff => { out.write_u8(0xe4)?; } Command::MasterVolume(p1) => { out.write_u8(0xe5)?; out.write_u8(p1)?; } Command::MasterVolumeFade(p1, p2) => { out.write_u8(0xe6)?; out.write_u8(p1)?; out.write_u8(p2)?; } Command::Tempo(p1) => { out.write_u8(0xe7)?; out.write_u8(p1)?; } Command::TempoFade(p1, p2) => { out.write_u8(0xe8)?; out.write_u8(p1)?; out.write_u8(p2)?; } Command::GlobalTranspose(p1) => { out.write_u8(0xe9)?; out.write_u8(p1)?; } Command::ChannelTranspose(p1) => { out.write_u8(0xea)?; out.write_u8(p1)?; } Command::Tremolo(p1, p2, p3) => { out.write_u8(0xeb)?; out.write_u8(p1)?; out.write_u8(p2)?; out.write_u8(p3)?; } Command::TremoloOff => { out.write_u8(0xec)?; } Command::ChannelVolume(p1) => { out.write_u8(0xed)?; out.write_u8(p1)?; } Command::ChannelVolumeFade(p1) => { out.write_u8(0xee)?; out.write_u8(p1)?; } Command::CallLoop(p1, p2) => { out.write_u8(0xef)?; call_loops.push(CallLoopRef { target_track: p1, ref_pos: out.position(), }); out.write_u8(0x00)?; out.write_u8(0xd0)?; out.write_u8(p2)?; } Command::VibratoFade(p1) => { out.write_u8(0xf0)?; out.write_u8(p1)?; } Command::PitchEnvelopeTo(p1, p2, p3) => { out.write_u8(0xf1)?; out.write_u8(p1)?; out.write_u8(p2)?; out.write_u8(p3)?; } Command::PitchEnvelopeFrom(p1, p2, p3) => { out.write_u8(0xf2)?; out.write_u8(p1)?; out.write_u8(p2)?; out.write_u8(p3)?; } Command::PitchEnvelopeOff => { out.write_u8(0xf3)?; } Command::Tuning(p1) => { out.write_u8(0xf4)?; out.write_u8(p1)?; } Command::EchoVolume(p1, p2, p3) => { out.write_u8(0xf5)?; out.write_u8(p1)?; out.write_u8(p2)?; out.write_u8(p3)?; } Command::EchoOff => { out.write_u8(0xf6)?; } Command::EchoParams(p1, p2, p3) => { out.write_u8(0xf7)?; out.write_u8(p1)?; out.write_u8(p2)?; out.write_u8(p3)?; } Command::EchoVolumeFade(p1, p2, p3) => { out.write_u8(0xf8)?; out.write_u8(p1)?; out.write_u8(p2)?; out.write_u8(p3)?; } Command::PitchSlide(p1, p2, p3) => { out.write_u8(0xf9)?; out.write_u8(p1)?; out.write_u8(p2)?; out.write_u8(p3)?; } Command::PercussionPatchBase(p1) => { out.write_u8(0xfa)?; out.write_u8(p1)?; } }; Ok(()) } } #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Hash)] pub struct ParameterizedCommand { duration: Option<u8>, velocity: Option<u8>, sustain: Option<u8>, command: Command, } impl ParameterizedCommand { pub fn new( duration: Option<u8>, velocity: Option<u8>, sustain: Option<u8>, command: Command, ) -> ParameterizedCommand { ParameterizedCommand { duration, velocity, sustain, command, } } pub fn write( &self, out: &mut Cursor<Vec<u8>>, prev_duration: u8, prev_velocity_sustain: Option<u8>, call_loops: &mut Vec<CallLoopRef>, ) -> Result<(u8, Option<u8>), Box<Error>> { let mut duration_out = prev_duration; let mut velocity_sustain_out = prev_velocity_sustain; let mut duration_to_write = None; if let Some(duration) = self.duration { if duration != prev_duration { duration_out = duration; if duration > 0 { duration_to_write = Some(duration); } } } let mut velocity_sustain = None; if self.velocity.is_some() || self.sustain.is_some() { let mut velocity_sustain_value = prev_velocity_sustain.unwrap_or(0x7d); let mut nonzero = false; if let Some(velocity) = self.velocity { if velocity > 0 { velocity_sustain_value = (velocity_sustain_value & 0x70) | velocity; nonzero = true; } } if let Some(sustain) = self.sustain { if sustain > 0 { velocity_sustain_value = (velocity_sustain_value & 0x0F) | (sustain << 4); nonzero = true; } } if nonzero { velocity_sustain = Some(velocity_sustain_value); } } let mut velocity_sustain_to_write = None; if let Some(velocity_sustain) = velocity_sustain { if prev_velocity_sustain.is_none() || prev_velocity_sustain.unwrap() != velocity_sustain { velocity_sustain_out = Some(velocity_sustain); velocity_sustain_to_write = Some(velocity_sustain); } } else if prev_velocity_sustain.is_none() { if let Command::Note(..) = self.command { velocity_sustain_out = Some(0x7d); velocity_sustain_to_write = Some(0x7d); } } if let Some(duration) = duration_to_write { out.write_u8(duration)?; } else if velocity_sustain_to_write.is_some() { out.write_u8(prev_duration)?; } if let Some(velocity_sustain) = velocity_sustain_to_write { out.write_u8(velocity_sustain)?; } self.command.write(out, call_loops)?; Ok((duration_out, velocity_sustain_out)) } pub fn call_loop_eligible(&self) -> bool { match self.command { Command::CallLoop(..) => false, Command::PitchSlide(..) => false, _ => true, } } pub fn set_sustain(&mut self, next_command: &ParameterizedCommand) -> bool { if let Command::Note(..) = self.command { if let Command::Rest = next_command.command { let note_duration = self.duration.unwrap() as u16; let rest_duration = next_command.duration.unwrap() as u16; let total_duration = note_duration + rest_duration; if (note_duration * 8) % total_duration == 0 || note_duration > rest_duration * 16 { let sustain = ((note_duration * 8) / total_duration) as u8; self.sustain = Some(sustain.min(7)); self.duration = Some(total_duration as u8); return true; } } } false } pub fn create_pitch_slide( &self, slide_time: u8, target_note: u8, ) -> Option<ParameterizedCommand> { match self.command { Command::Rest => None, _ => self.duration.map(|duration| ParameterizedCommand { duration: None, velocity: None, sustain: None, command: Command::PitchSlide(duration - slide_time.min(duration), slide_time, target_note), }) } } pub fn is_slide(&self) -> bool { match self.command { Command::PitchSlide(..) => true, _ => false, } } pub fn can_be_first_in_call_loop(&self) -> bool { match self.command { Command::Tie => false, _ => true, } } pub fn can_be_last_in_call_loop(&self) -> bool { match self.command { Command::PitchSlide(..) => false, _ => true, } } }
#[doc = "Register `GICV_BPR` reader"] pub type R = crate::R<GICV_BPR_SPEC>; #[doc = "Register `GICV_BPR` writer"] pub type W = crate::W<GICV_BPR_SPEC>; #[doc = "Field `BINARY_POINT` reader - BINARY_POINT"] pub type BINARY_POINT_R = crate::FieldReader; #[doc = "Field `BINARY_POINT` writer - BINARY_POINT"] pub type BINARY_POINT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; impl R { #[doc = "Bits 0:2 - BINARY_POINT"] #[inline(always)] pub fn binary_point(&self) -> BINARY_POINT_R { BINARY_POINT_R::new((self.bits & 7) as u8) } } impl W { #[doc = "Bits 0:2 - BINARY_POINT"] #[inline(always)] #[must_use] pub fn binary_point(&mut self) -> BINARY_POINT_W<GICV_BPR_SPEC, 0> { BINARY_POINT_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "GICV VM binary point register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicv_bpr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`gicv_bpr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct GICV_BPR_SPEC; impl crate::RegisterSpec for GICV_BPR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`gicv_bpr::R`](R) reader structure"] impl crate::Readable for GICV_BPR_SPEC {} #[doc = "`write(|w| ..)` method takes [`gicv_bpr::W`](W) writer structure"] impl crate::Writable for GICV_BPR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets GICV_BPR to value 0x02"] impl crate::Resettable for GICV_BPR_SPEC { const RESET_VALUE: Self::Ux = 0x02; }
#[doc = "Register `BCCR` reader"] pub type R = crate::R<BCCR_SPEC>; #[doc = "Register `BCCR` writer"] pub type W = crate::W<BCCR_SPEC>; #[doc = "Field `BCBLUE` reader - Background color blue value"] pub type BCBLUE_R = crate::FieldReader; #[doc = "Field `BCBLUE` writer - Background color blue value"] pub type BCBLUE_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 8, O>; #[doc = "Field `BCGREEN` reader - Background color green value"] pub type BCGREEN_R = crate::FieldReader; #[doc = "Field `BCGREEN` writer - Background color green value"] pub type BCGREEN_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 8, O>; #[doc = "Field `BCRED` reader - Background color red value"] pub type BCRED_R = crate::FieldReader; #[doc = "Field `BCRED` writer - Background color red value"] pub type BCRED_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 8, O>; impl R { #[doc = "Bits 0:7 - Background color blue value"] #[inline(always)] pub fn bcblue(&self) -> BCBLUE_R { BCBLUE_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 8:15 - Background color green value"] #[inline(always)] pub fn bcgreen(&self) -> BCGREEN_R { BCGREEN_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bits 16:23 - Background color red value"] #[inline(always)] pub fn bcred(&self) -> BCRED_R { BCRED_R::new(((self.bits >> 16) & 0xff) as u8) } } impl W { #[doc = "Bits 0:7 - Background color blue value"] #[inline(always)] #[must_use] pub fn bcblue(&mut self) -> BCBLUE_W<BCCR_SPEC, 0> { BCBLUE_W::new(self) } #[doc = "Bits 8:15 - Background color green value"] #[inline(always)] #[must_use] pub fn bcgreen(&mut self) -> BCGREEN_W<BCCR_SPEC, 8> { BCGREEN_W::new(self) } #[doc = "Bits 16:23 - Background color red value"] #[inline(always)] #[must_use] pub fn bcred(&mut self) -> BCRED_W<BCCR_SPEC, 16> { BCRED_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "Background Color Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bccr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`bccr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct BCCR_SPEC; impl crate::RegisterSpec for BCCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`bccr::R`](R) reader structure"] impl crate::Readable for BCCR_SPEC {} #[doc = "`write(|w| ..)` method takes [`bccr::W`](W) writer structure"] impl crate::Writable for BCCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets BCCR to value 0"] impl crate::Resettable for BCCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use parity_scale_codec::{Encode, MaxEncodedLen}; #[derive(Encode, MaxEncodedLen)] union Union { a: u8, b: u16, } fn main() {}
use std::borrow::Cow; use serde_json; use request::DoRequest; use request::RequestBuilder; use response; impl response::NamedResponse for String { fn name<'a>() -> Cow<'a, str> { "".into() } } impl<'t> DoRequest<response::ResponseStringArray> for RequestBuilder<'t, response::ResponseStringArray> { #[allow(unused_variables)] fn retrieve_obj(&self, obj: String) -> Result<response::ResponseStringArray, String> { debug!("Inside retrieve_obj() of ResponseStringArray"); debug!("Retrieveing JSON"); match self.retrieve_json() { Ok(ref s) => { debug!("Success"); debug!("Retrieving Value"); match serde_json::from_str::<response::ResponseStringArray>(s) { Ok(ob) => { debug!("Success"); Ok(ob) } Err(e) => { debug!("Failed"); Err(e.to_string()) } } } Err(e) => { debug!("Failed"); Err(e.to_string()) } } } } impl<'t> DoRequest<response::Neighbors> for RequestBuilder<'t, response::Neighbors> {}
use ark_ec::{twisted_edwards_extended::GroupProjective as TEProjective, TEModelParameters}; use ark_ff::PrimeField; use ark_r1cs_std::{ alloc::AllocVar, groups::curves::twisted_edwards::AffineVar, prelude::*, uint8::UInt8, }; use ark_relations::r1cs::{Namespace, SynthesisError}; use ark_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec}; use crate::variable_length_crh::bowe_hopwood::{ VariableLengthBoweHopwoodCompressedCRH, VariableLengthBoweHopwoodParameters, }; use crate::variable_length_crh::constraints::VariableLengthCRHGadget; use ark_r1cs_std::bits::boolean::Boolean; use ark_r1cs_std::fields::fp::FpVar; use ark_std::rand::{CryptoRng, Rng, SeedableRng}; #[derive(Default)] pub struct VariableLengthBoweHopwoodParametersVar<P: TEModelParameters> { params: VariableLengthBoweHopwoodParameters<P>, } impl<P: TEModelParameters> Clone for VariableLengthBoweHopwoodParametersVar<P> { fn clone(&self) -> Self { Self { params: self.params.clone(), } } } impl<P: TEModelParameters> VariableLengthBoweHopwoodParametersVar<P> { pub fn get_generators<RO: Rng + CryptoRng + SeedableRng>( &self, pos: usize, ) -> Vec<Vec<TEProjective<P>>> { self.params.get_generators::<RO>(pos) } } pub const WINDOW_SIZE: usize = 64; pub const CHUNK_SIZE: usize = 3; pub struct VariableLengthBoweHopwoodCompressedCRHGadget< RO: Rng + CryptoRng + SeedableRng, P: TEModelParameters, > where P::BaseField: PrimeField<BasePrimeField = P::BaseField>, { #[doc(hidden)] _rand: PhantomData<RO>, #[doc(hidden)] _params: PhantomData<P>, } impl<RO, P> VariableLengthCRHGadget<VariableLengthBoweHopwoodCompressedCRH<RO, P>, P::BaseField> for VariableLengthBoweHopwoodCompressedCRHGadget<RO, P> where RO: Rng + CryptoRng + SeedableRng, P: TEModelParameters, P::BaseField: PrimeField<BasePrimeField = P::BaseField>, { type OutputVar = FpVar<P::BaseField>; type ParametersVar = VariableLengthBoweHopwoodParametersVar<P>; fn check_evaluation_gadget( parameters: &Self::ParametersVar, input: &[UInt8<P::BaseField>], ) -> Result<Self::OutputVar, SynthesisError> { // Pad the input if it is not the current length. let mut input_in_bits: Vec<Boolean<_>> = input .iter() .flat_map(|byte| byte.to_bits_le().unwrap()) .collect(); if (input_in_bits.len()) % CHUNK_SIZE != 0 { let current_length = input_in_bits.len(); for _ in 0..(CHUNK_SIZE - current_length % CHUNK_SIZE) { input_in_bits.push(Boolean::constant(false)); } } assert!(input_in_bits.len() % CHUNK_SIZE == 0); let generators = parameters.get_generators::<RO>(input_in_bits.len() / CHUNK_SIZE); // Allocate new variable for the result. let input_in_bits = input_in_bits .chunks(WINDOW_SIZE * CHUNK_SIZE) .map(|x| x.chunks(CHUNK_SIZE).collect::<Vec<_>>()) .collect::<Vec<_>>(); let result = AffineVar::<P, FpVar<P::BaseField>>::precomputed_base_3_bit_signed_digit_scalar_mul( &generators, &input_in_bits, )?; Ok(result.x) } fn convert_output_to_field_gadgets( output: &Self::OutputVar, ) -> Result<Vec<FpVar<P::BaseField>>, SynthesisError> { Ok(vec![(*output).clone()]) } } impl<P> AllocVar<VariableLengthBoweHopwoodParameters<P>, P::BaseField> for VariableLengthBoweHopwoodParametersVar<P> where P: TEModelParameters, P::BaseField: PrimeField<BasePrimeField = P::BaseField>, { fn new_variable<T: Borrow<VariableLengthBoweHopwoodParameters<P>>>( _cs: impl Into<Namespace<P::BaseField>>, f: impl FnOnce() -> Result<T, SynthesisError>, _mode: AllocationMode, ) -> Result<Self, SynthesisError> { let params = f()?.borrow().clone(); Ok(VariableLengthBoweHopwoodParametersVar { params }) } } #[cfg(test)] mod test { use ark_std::rand::Rng; use crate::variable_length_crh::bowe_hopwood::constraints::VariableLengthBoweHopwoodCompressedCRHGadget; use crate::variable_length_crh::bowe_hopwood::VariableLengthBoweHopwoodCompressedCRH; use crate::variable_length_crh::constraints::VariableLengthCRHGadget; use crate::variable_length_crh::VariableLengthCRH; use ark_ed_on_bls12_381::{EdwardsParameters, Fq as Fr}; use ark_std::test_rng; use ark_r1cs_std::{alloc::AllocVar, uint8::UInt8, R1CSVar}; use ark_relations::r1cs::{ConstraintSystem, ConstraintSystemRef}; use rand_chacha::ChaChaRng; type TestCRH = VariableLengthBoweHopwoodCompressedCRH<ChaChaRng, EdwardsParameters>; type TestCRHGadget = VariableLengthBoweHopwoodCompressedCRHGadget<ChaChaRng, EdwardsParameters>; fn generate_input<R: Rng>( cs: ConstraintSystemRef<Fr>, rng: &mut R, ) -> ([u8; 189], Vec<UInt8<Fr>>) { let mut input = [1u8; 189]; rng.fill_bytes(&mut input); let mut input_bytes = vec![]; for byte in input.iter() { input_bytes.push(UInt8::new_witness(cs.clone(), || Ok(byte)).unwrap()); } (input, input_bytes) } #[test] fn test_native_equality() { let rng = &mut test_rng(); let cs = ConstraintSystem::<Fr>::new_ref(); let (input, input_var) = generate_input(cs.clone(), rng); println!("number of constraints for input: {}", cs.num_constraints()); let parameters = TestCRH::setup(rng).unwrap(); let primitive_result = TestCRH::evaluate(&parameters, &input).unwrap(); let parameters_var = <TestCRHGadget as VariableLengthCRHGadget<TestCRH, Fr>>::ParametersVar::new_witness( ark_relations::ns!(cs, "parameters_var"), || Ok(&parameters), ) .unwrap(); println!( "number of constraints for input + params: {}", cs.num_constraints() ); let result_var = TestCRHGadget::check_evaluation_gadget(&parameters_var, &input_var).unwrap(); println!("number of constraints total: {}", cs.num_constraints()); assert_eq!(primitive_result, result_var.value().unwrap()); assert!(cs.is_satisfied().unwrap()); } }
mod intcode; use std::collections::BTreeMap; use std::fs; use std::sync::mpsc; use std::{thread, time}; fn main() { let input = fs::read_to_string("input.txt").expect("Something went wrong reading the file"); let mut program: Vec<i64> = input.trim_end().split(",").map(|n| n.parse().unwrap()).collect(); //Memory address 0 represents the number of quarters that have been inserted; set it to 2 //to play for free. program[0] = 2; let score = run_game(program); println!("Score: {}", score); } #[derive(Debug, PartialEq)] enum TileType { Empty, Wall, Block, HorizontalPaddle, Ball, } use TileType::*; impl TileType { fn from_tile_id(tile_id: i64) -> TileType { match tile_id { 0 => Empty, 1 => Wall, 2 => Block, 3 => HorizontalPaddle, 4 => Ball, n => panic!("Unknown tile id {}", n), } } fn print(&self) -> &str { match self { Empty => ".", Wall => "▏", Block => "▀", HorizontalPaddle => "▂", Ball => "o", } } } enum Direction { Left, Right, } use Direction::*; fn run_game(program: Vec<i64>) -> i64 { let mut tiles: BTreeMap<Position, TileType> = BTreeMap::new(); // Open channel to send input from main thread to game thread let (main_output, game_input) = mpsc::channel(); // Open channel to receive output from game thread in main thread let (game_output, main_input) = mpsc::channel(); let game_thread = thread::spawn(move || { intcode::run_intcode_with_channels(program, game_input, game_output); }); let mut score = 0; let mut ball_position: Option<Position> = None; let mut paddle_position: Option<Position> = None; let mut need_to_send_initial_message = true; loop { let x = main_input.recv().unwrap(); if x == -99 { // End of program break; } let y = main_input.recv().unwrap(); if x == -1 && y == 0 { // When three output instructions specify X=-1, Y=0, the third output instruction is // not a tile; the value instead specifies the new score to show in the segment // display. For example, a sequence of output values like -1,0,12345 would show 12345 // as the player's current score. score = main_input.recv().unwrap(); println!("New score: {}", score); } else { let tile_id = main_input.recv().unwrap(); let tile_type = TileType::from_tile_id(tile_id); println!("tile type: {:?}", tile_type); let position = Position { x, y }; println!("tile position: {:?}", position); if let Ball = tile_type { if let Some(paddle_position) = paddle_position { if tiles.len() == 968 { // Move joystick toward ball's position //If the joystick is in the neutral position, provide 0. //If the joystick is tilted to the left, provide -1. //If the joystick is tilted to the right, provide 1. if position.x < paddle_position.x { main_output.send(-1).unwrap(); } else if position.x > paddle_position.x { main_output.send(1).unwrap(); } else { main_output.send(0).unwrap(); } } } ball_position = Some(position); } else if let HorizontalPaddle = tile_type { paddle_position = Some(position); } tiles.insert(position, tile_type); // 44 x 22 tile screen if tiles.len() == 968 { print_tiles(&tiles, score); if need_to_send_initial_message { need_to_send_initial_message = false; main_output.send(1).unwrap(); } } } } game_thread.join().unwrap(); return score; } fn print_tiles(tiles: &BTreeMap<Position, TileType>, score: i64) { // slow down the animation thread::sleep(time::Duration::from_millis(15)); for (position, tile_type) in tiles { // println!("printing position {:?}", position); if position.x == 0 { println!(""); } print!("{}", tile_type.print()); } println!(""); println!("SCORE: {}", score); } #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)] struct Position { y: i64, // order of fields matters here since we're deriving Ord (so (0, 1) comes before (1, 0)) x: i64, }
mod expression; mod instruction; mod lexer; mod section; mod symbol; use crate::lexer::{Lexer, Location, LocationSpan, TokType}; use crate::parser::AsmParser; use crate::symbol::Symbol; use lalrpop_util::lalrpop_mod; use std::cell::{Ref, RefCell}; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::io::{self, Read}; use std::rc::{Rc, Weak}; lalrpop_mod!(parser); type ParseError = lalrpop_util::ParseError<Location, TokType, AssemblerError>; #[derive(Debug)] pub struct Error { err: ParseError, } fn write_expected_tokens(fmt: &mut Formatter, expected: &Vec<String>) -> Result<(), fmt::Error> { let mut items = expected.iter(); write!(fmt, "{}", items.next().unwrap())?; let mut item = items.next(); while let Some(tok) = item { let next = items.next(); match next { Some(_) => write!(fmt, ", {}", tok)?, None => write!(fmt, " or {}", tok)?, } item = next; } Ok(()) } impl Display for Error { fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> { use lalrpop_util::ParseError::*; match &self.err { InvalidToken { location } => write!(fmt, "Invalid token at {}", location), UnrecognizedEOF { location, expected } => { write!(fmt, "Unexpected EOF at {}; expected ", location)?; debug_assert_ne!(expected.len(), 0); write_expected_tokens(fmt, expected) } UnrecognizedToken { token: (begin, tok_type, end), expected, } => { write!( fmt, "Unexpected {} at {}; expected ", tok_type, LocationSpan::new(begin, end) )?; debug_assert_ne!(expected.len(), 0); write_expected_tokens(fmt, expected) } ExtraToken { token: (begin, tok_type, end), } => write!( fmt, "Unexpected {} at {}; expected no more tokens", tok_type, LocationSpan::new(begin, end) ), User { error } => error.fmt(fmt), } } } impl From<ParseError> for Error { fn from(err: ParseError) -> Self { Self { err } } } impl From<AssemblerError> for Error { fn from(err: AssemblerError) -> Self { Self { err: err.into() } } } #[derive(Debug)] pub enum Warning { // } #[derive(Debug)] pub enum AssemblerError { // Lexer errors BadInterpFmt(String), CharAfterLineCont(char), GarbageChar(char), EmptyFract, EmptyGfx, EmptyHex, EmptyInterpFmt, EmptyInterpName, EmptyOct, IllegalEscape(char), IllegalEscapeEOF, IllegalInterpChar(char), LineContEOF, MultipleInterpFmt, UntermInterp, UntermString, // Logic errors AssertFailure(Option<String>), LdHLHL, LocalInMainScope(String), // Expression errors ExprNotConstant, // Symbol errors SymbolRedef, } #[derive(Debug)] pub enum Diagnostic { Warning(Warning), Error(Error), } pub type DiagCallback = dyn Fn(Diagnostic); impl Display for AssemblerError { fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> { match self { Self::BadInterpFmt(s) => write!(fmt, "Bad interpolation format \"{}\"", s), Self::CharAfterLineCont(c) => write!( fmt, "Begun line continuation, but encountered character '{}'", c ), Self::GarbageChar(c) => write!(fmt, "Garbage char '{}'", c), Self::EmptyFract => write!(fmt, "Invalid fixed-point constant, no digits after '.'"), Self::EmptyGfx => write!(fmt, "Invalid gfx constant, no digits after '`'"), Self::EmptyHex => write!(fmt, "Invalid hex constant, no digits after '$'"), Self::EmptyInterpFmt => write!(fmt, "Empty interpolation format"), Self::EmptyInterpName => write!(fmt, "Empty interpolation name"), Self::EmptyOct => write!(fmt, "Invalid octal constant, no digits after '&'"), Self::IllegalEscape(c) => write!(fmt, "Illegal character escape '{}'", c), Self::IllegalEscapeEOF => write!(fmt, "Illegal character escape at end of input"), Self::IllegalInterpChar(c) => write!(fmt, "Illegal character '{}' in interpolation", c), Self::LineContEOF => write!(fmt, "Line continuation at end of file"), Self::MultipleInterpFmt => write!(fmt, "Multiple interpolation formats"), Self::UntermInterp => write!(fmt, "Unterminated interpolation"), Self::UntermString => write!(fmt, "Unterminated string"), Self::AssertFailure(Some(s)) => write!(fmt, "Assertion failure: {}", s), Self::AssertFailure(None) => write!(fmt, "Assertion failure"), Self::LdHLHL => write!(fmt, "ld [hl], [hl] is not a valid instruction"), Self::LocalInMainScope(name) => write!(fmt, "Local symbol \"{}\" in main scope", name), Self::ExprNotConstant => write!(fmt, "Expression is not constant"), Self::SymbolRedef => write!(fmt, "Redefined symbol"), } } } #[derive(Debug)] pub enum AssertType { Warn, Error, Fatal, } pub struct Assembler<'a> { symbols: RefCell<HashMap<Rc<String>, Symbol>>, sym_scope: RefCell<Option<Weak<Symbol>>>, // Callbacks diagnose: &'a DiagCallback, } impl<'a> Assembler<'a> { // === Contructor === pub fn new(diagnose: &'a DiagCallback) -> Self { Self { symbols: RefCell::new(HashMap::new()), sym_scope: RefCell::new(None), diagnose, } } // === Main call === pub fn assemble(&mut self, mut f: impl Read) -> Result<(), io::Error> { // Init all self.symbols.borrow_mut().clear(); self.add_symbol(Symbol::new_equ("_RS".to_string(), 0)) .unwrap(); // FIXME: reading the whole file as a string sucks, using an Iterator over chars would be much better let mut s = String::new(); f.read_to_string(&mut s)?; let lexer_state = RefCell::new(Lexer::new_state()); let lexer = Lexer::new(s.chars(), &lexer_state, self.diagnose, &self); if let Err(err) = AsmParser::new().parse(self, &lexer_state, lexer) { (self.diagnose)(Diagnostic::Error(err.into())); } Ok(()) } // === Error reporting === pub fn assert( &self, assert_type: AssertType, expr: i32, msg: Option<String>, ) -> Result<(), AssemblerError> { if expr == 0 { return Ok(()); } match assert_type { AssertType::Warn => unimplemented!(), AssertType::Error => unimplemented!(), AssertType::Fatal => Err(AssemblerError::AssertFailure(msg)), } } // === Symbol management === pub fn get_symbol_scope(&self) -> Option<Rc<Symbol>> { self.sym_scope .borrow() .as_ref() .and_then(|weak| weak.upgrade()) } pub fn set_symbol_scope(&self, scope: Weak<Symbol>) { self.sym_scope.replace(Some(scope)); } pub fn expand_sym_name(&self, name: String) -> Result<String, AssemblerError> { if !name.starts_with('.') { Ok(name) } else { if let Some(scope) = self.get_symbol_scope() { Ok(format!("{}{}", scope.get_name(), name)) } else { Err(AssemblerError::LocalInMainScope(name)) } } } pub fn find_symbol(&self, name: &String) -> Option<Ref<Symbol>> { self.symbols.borrow().get(name).map(|sym| Ref::map(sym)) } pub fn add_symbol(&self, sym: Symbol) -> Result<(), AssemblerError> { if let Some(other) = self.symbols.borrow_mut().get_mut(sym.get_name()) { other.redefine(sym)?; Ok(()) } else { self.symbols .borrow_mut() .insert(Rc::clone(sym.get_name()), sym); Ok(()) } } pub(crate) fn advance_rs(&self, offset: i32) -> i32 { let rs = self .symbols .borrow_mut() .get_mut(&"_RS".to_string()) .unwrap(); let val = rs.get_value().unwrap(); rs.set_value(val + offset); val } }
pub mod rng;
macro_rules! impl_from { ($to:ident :: $constructor:ident ($from:ty)) => { impl ::std::convert::From<$from> for $to { fn from(x: $from) -> Self { $to::$constructor(::std::convert::From::from(x)) } } }; } macro_rules! impl_node { ($x:ident <$a:ident, $b:ident>) => { impl<$a, $b> ::ast::Node for $x<$a, $b> { fn line(&self) -> ::ast::LineNum { self.line } } }; ($x:ident <$a:ident>) => { impl<$a> ::ast::Node for $x<$a> { fn line(&self) -> ::ast::LineNum { self.line } } }; ($x:ty) => { impl ::ast::Node for $x { fn line(&self) -> ::ast::LineNum { self.line } } }; } pub mod clause; pub mod common; pub mod expr; pub mod form; pub mod guard; pub mod literal; pub mod pat; pub mod ty; pub type LineNum = i32; pub type Arity = u32; pub trait Node { fn line(&self) -> LineNum; } #[derive(Debug, Clone)] pub struct ModuleDecl { pub forms: Vec<form::Form>, }
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::{convert::TryInto, fmt::{self, Display, Formatter}}; use std::io::{self, Cursor, Read, Write}; pub trait Packable { type Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error>; fn pack(&self) -> Result<Vec<u8>, Self::Error> { let mut wtr = Vec::new(); self.pack_into(&mut wtr)?; Ok(wtr) } } pub trait Unpackable where Self: Sized { type Error; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error>; fn unpack<'a>(buf: &'a [u8]) -> Result<(Self, &'a [u8]), Self::Error> { let mut rdr = Cursor::new(buf); let val = Self::unpack_from(&mut rdr)?; Ok((val, &buf[rdr.position() as usize..])) } } #[derive(Debug, PartialEq)] pub enum PackError { SizeError, } impl Display for PackError { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Self::SizeError => write!(f, "buffer is too small"), } } } impl std::error::Error for PackError {} impl From<io::Error> for PackError { fn from(e: io::Error) -> Self { match e.kind() { io::ErrorKind::UnexpectedEof => Self::SizeError, _ => unreachable!(), } } } impl Packable for bool { type Error = io::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { stream.write_u8(if *self {1} else {0})?; Ok(()) } } impl Unpackable for bool { type Error = PackError; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { Ok(rdr.read_u8()? != 0) } } impl Packable for u8 { type Error = io::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { stream.write_u8(*self)?; Ok(()) } } impl Unpackable for u8 { type Error = PackError; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { Ok(rdr.read_u8()?) } } impl Packable for i8 { type Error = io::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { stream.write_i8(*self)?; Ok(()) } } impl Unpackable for i8 { type Error = PackError; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { Ok(rdr.read_i8()?) } } impl Packable for u16 { type Error = io::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { stream.write_u16::<BigEndian>(*self)?; Ok(()) } } impl Unpackable for u16 { type Error = PackError; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { Ok(rdr.read_u16::<BigEndian>()?) } } impl Packable for i16 { type Error = io::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { stream.write_i16::<BigEndian>(*self)?; Ok(()) } } impl Unpackable for i16 { type Error = PackError; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { Ok(rdr.read_i16::<BigEndian>()?) } } impl Packable for u32 { type Error = io::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { stream.write_u32::<BigEndian>(*self)?; Ok(()) } } impl Unpackable for u32 { type Error = PackError; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { Ok(rdr.read_u32::<BigEndian>()?) } } impl Packable for i32 { type Error = io::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { stream.write_i32::<BigEndian>(*self)?; Ok(()) } } impl Unpackable for i32 { type Error = PackError; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { Ok(rdr.read_i32::<BigEndian>()?) } } impl Packable for u64 { type Error = io::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { stream.write_u64::<BigEndian>(*self)?; Ok(()) } } impl Unpackable for u64 { type Error = PackError; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { Ok(rdr.read_u64::<BigEndian>()?) } } impl Packable for i64 { type Error = io::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { stream.write_i64::<BigEndian>(*self)?; Ok(()) } } impl Unpackable for i64 { type Error = PackError; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { Ok(rdr.read_i64::<BigEndian>()?) } } impl Packable for u128 { type Error = io::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { stream.write_u128::<BigEndian>(*self)?; Ok(()) } } impl Unpackable for u128 { type Error = PackError; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { Ok(rdr.read_u128::<BigEndian>()?) } } impl Packable for i128 { type Error = io::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { stream.write_i128::<BigEndian>(*self)?; Ok(()) } } impl Unpackable for i128 { type Error = PackError; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { Ok(rdr.read_i128::<BigEndian>()?) } } impl Packable for f32 { type Error = io::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { stream.write_f32::<BigEndian>(*self)?; Ok(()) } } impl Unpackable for f32 { type Error = PackError; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { Ok(rdr.read_f32::<BigEndian>()?) } } impl Packable for f64 { type Error = io::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { stream.write_f64::<BigEndian>(*self)?; Ok(()) } } impl Unpackable for f64 { type Error = PackError; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { Ok(rdr.read_f64::<BigEndian>()?) } } impl<T: Packable, const S: usize> Packable for [T; S] { type Error = T::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { for v in self { v.pack_into(stream)?; } Ok(()) } } impl<T: Unpackable, const S: usize> Unpackable for [T; S] { type Error = T::Error; fn unpack_from(rdr: &mut impl Read) -> Result<Self, Self::Error> { let mut v: Vec<T> = Vec::with_capacity(S); for _ in 0..S { v.push(unpack_from(rdr)?); } Ok(v.try_into().unwrap_or_else(|_| unreachable!())) } } impl<T: Packable> Packable for Vec<T> { type Error = T::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { for v in self { v.pack_into(stream)?; } Ok(()) } } impl<T: Packable> Packable for &T { type Error = T::Error; fn pack_into(&self, stream: &mut impl Write) -> Result<(), Self::Error> { (*self).pack_into(stream) } } pub fn unpack_from<T: Unpackable>(rdr: &mut impl Read) -> Result<T, T::Error> { T::unpack_from(rdr) } pub fn unpack<'a, T: Unpackable>(buf: &'a [u8]) -> Result<(T, &'a [u8]), T::Error> { T::unpack(buf) } pub fn pack_into<T: Packable>(wtr: &mut impl Write, value: &T) -> Result<(), T::Error> { T::pack_into(value, wtr) } pub fn pack<T: Packable>(value: &T) -> Result<Vec<u8>, T::Error> { T::pack(value) } pub trait WritePackExt: io::Write + Sized { fn pack<T: Packable>(&mut self, pack: &T) -> Result<(), T::Error>; } impl<T: Write> WritePackExt for T { fn pack<P: Packable>(&mut self, pack: &P) -> Result<(), P::Error> { pack.pack_into(self)?; Ok(()) } } pub trait ReadPackExt: io::Read { fn unpack<T: Unpackable>(&mut self) -> Result<T, T::Error>; } impl<T: Read> ReadPackExt for T { fn unpack<U: Unpackable>(&mut self) -> Result<U, U::Error> { U::unpack_from(self) } } #[cfg(test)] mod tests { use crate::*; #[test] fn test_pack_bool() { let t = true; let f = false; let tb = t.pack().unwrap(); let fb = f.pack().unwrap(); assert_eq!(tb, vec![0x01]); assert_eq!(fb, vec![0x00]); } #[test] fn test_unpack_bool() { let tb1 = []; let tb2 = [0x1]; let tb3 = [0x1, 0xff]; let tb4 = [0x20]; let tb5 = [0x20, 0xff]; let fb6 = [0]; let fb7 = [0, 0xff]; let tv1: Result<(i8, _), PackError> = unpack(&tb1); let (tv2, tv2b): (bool, _) = unpack(&tb2).unwrap(); let (tv3, tv3b): (bool, _) = unpack(&tb3).unwrap(); let (tv4, tv4b): (bool, _) = unpack(&tb4).unwrap(); let (tv5, tv5b): (bool, _) = unpack(&tb5).unwrap(); let (fv6, fvb6): (bool, _) = unpack(&fb6).unwrap(); let (fv7, fvb7): (bool, _) = unpack(&fb7).unwrap(); assert_eq!(tv1, Err(PackError::SizeError)); assert_eq!(tv2, true); assert_eq!(tv2b, &[]); assert_eq!(tv3, true); assert_eq!(tv3b, &[0xff]); assert_eq!(tv4, true); assert_eq!(tv4b, &[]); assert_eq!(tv5, true); assert_eq!(tv5b, &[0xff]); assert_eq!(fv6, false); assert_eq!(fvb6, &[]); assert_eq!(fv7, false); assert_eq!(fvb7, &[0xff]); } #[test] fn test_roundtrip_bool() { let v1 = true; let v2 = false; let i1 = v1.pack().unwrap(); let i2 = v2.pack().unwrap(); let (t1, t1b): (bool, _) = unpack(&i1).unwrap(); let (t2, t2b): (bool, _) = unpack(&i2).unwrap(); assert_eq!(t1, v1); assert_eq!(t1b, &[]); assert_eq!(t2, v2); assert_eq!(t2b, &[]); } #[test] fn test_pack_u8() { let val = 0xfu8; assert_eq!(val.pack().unwrap(), vec![val]); } #[test] fn test_unpack_u8() { let u1 = []; let u2 = [0x82]; let u3 = [0x82, 0xff]; let v1: Result<(i8, _), PackError> = unpack(&u1); let (v2, b2): (u8, _) = unpack(&u2).unwrap(); let (v3, b3): (u8, _) = unpack(&u3).unwrap(); assert_eq!(v1, Err(PackError::SizeError)); assert_eq!(v2, 0x82); assert_eq!(b2, &[]); assert_eq!(v3, 0x82); assert_eq!(b3, &[0xff]); } #[test] fn test_roundtrip_u8() { let v = 0x20; let i = v.pack().unwrap(); let (t, tb): (u8, _) = unpack(&i).unwrap(); assert_eq!(t, v); assert_eq!(tb, &[]); } #[test] fn test_pack_i8() { let val = 25i8; let val2 = -25i8; assert_eq!(val.pack().unwrap(), vec![25]); assert_eq!(val2.pack().unwrap(), vec![231]); } #[test] fn test_unpack_i8() { let i1 = []; let i2 = [25]; let i3 = [25, 0xff]; let i4 = [231]; let i5 = [231, 0xff]; let v1: Result<(i8, _), PackError> = unpack(&i1); let (v2, b2): (i8, _) = unpack(&i2).unwrap(); let (v3, b3): (i8, _) = unpack(&i3).unwrap(); let (v4, b4): (i8, _) = unpack(&i4).unwrap(); let (v5, b5): (i8, _) = unpack(&i5).unwrap(); assert_eq!(v1, Err(PackError::SizeError)); assert_eq!(v2, 25); assert_eq!(b2, &[]); assert_eq!(v3, 25); assert_eq!(b3, &[0xff]); assert_eq!(v4, -25); assert_eq!(b4, &[]); assert_eq!(v5, -25); assert_eq!(b5, &[0xff]); } #[test] fn test_roundtrip_i8() { let v1 = 25; let v2 = -25; let i1 = v1.pack().unwrap(); let i2 = v2.pack().unwrap(); let (t1, t1b): (i8, _) = unpack(&i1).unwrap(); let (t2, t2b): (i8, _) = unpack(&i2).unwrap(); assert_eq!(t1, v1); assert_eq!(t1b, &[]); assert_eq!(t2, v2); assert_eq!(t2b, &[]); } #[test] fn test_pack_u16() { let v1 = 0x1221u16; assert_eq!(v1.pack().unwrap(), vec![0x12, 0x21]); } #[test] fn test_unpack_u16() { let i1 = []; let i2 = [0x12]; let i3 = [0x12, 0x21]; let i4 = [0x12, 0x21, 0xff]; let v1: Result<(u16, _), PackError> = unpack(&i1); let v2: Result<(u16, _), PackError> = unpack(&i2); let (v3, b3): (u16, _) = unpack(&i3).unwrap(); let (v4, b4): (u16, _) = unpack(&i4).unwrap(); assert_eq!(v1, Err(PackError::SizeError)); assert_eq!(v2, Err(PackError::SizeError)); assert_eq!(v3, 0x1221); assert_eq!(b3, &[]); assert_eq!(v4, 0x1221); assert_eq!(b4, &[0xff]); } #[test] fn test_roundtrip_u16() { let v1 = 0x1221u16; let i1 = v1.pack().unwrap(); let (t1, t1b): (u16, _) = unpack(&i1).unwrap(); assert_eq!(t1, v1); assert_eq!(t1b, &[]); } #[test] fn test_pack_i16() { let v1 = 0x1221i16; let v2 = -0x1221i16; assert_eq!(v1.pack().unwrap(), vec![0x12, 0x21]); assert_eq!(v2.pack().unwrap(), vec![0xed, 0xdf]); } #[test] fn test_unpack_i16() { let i1 = [0x12]; let i2 = [0x12, 0x21]; let i3 = [0x12, 0x21, 0xff]; let i4 = [0xed, 0xdf]; let i5 = [0xed, 0xdf, 0xff]; let v1: Result<(i16, _), PackError> = unpack(&i1); let (v2, b2): (i16, _) = unpack(&i2).unwrap(); let (v3, b3): (i16, _) = unpack(&i3).unwrap(); let (v4, b4): (i16, _) = unpack(&i4).unwrap(); let (v5, b5): (i16, _) = unpack(&i5).unwrap(); assert_eq!(v1, Err(PackError::SizeError)); assert_eq!(v2, 0x1221); assert_eq!(b2, &[]); assert_eq!(v3, 0x1221); assert_eq!(b3, &[0xff]); assert_eq!(v4, -0x1221); assert_eq!(b4, &[]); assert_eq!(v5, -0x1221); assert_eq!(b5, &[0xff]); } #[test] fn test_roundtrip_i16() { let v1 = 0x1221; let v2 = -0x1221; let i1 = v1.pack().unwrap(); let i2 = v2.pack().unwrap(); let (t1, b1): (i16, _) = unpack(&i1).unwrap(); let (t2, b2): (i16, _) = unpack(&i2).unwrap(); assert_eq!(t1, v1); assert_eq!(b1, &[]); assert_eq!(t2, v2); assert_eq!(b2, &[]); } #[test] fn test_pack_u32() { let v1 = 0x12345678u32; assert_eq!(v1.pack().unwrap(), vec![0x12, 0x34, 0x56, 0x78]); } #[test] fn test_unpack_u32() { let i1 = []; let i2 = [0x12]; let i3 = [0x12, 0x34]; let i4 = [0x12, 0x34, 0x56]; let i5 = [0x12, 0x34, 0x56, 0x78]; let i6 = [0x12, 0x34, 0x56, 0x78, 0xff]; let v1: Result<(u32, _), PackError> = unpack(&i1); let v2: Result<(u32, _), PackError> = unpack(&i2); let v3: Result<(u32, _), PackError> = unpack(&i3); let v4: Result<(u32, _), PackError> = unpack(&i4); let (v5, b5): (u32, _) = unpack(&i5).unwrap(); let (v6, b6): (u32, _) = unpack(&i6).unwrap(); assert_eq!(v1, Err(PackError::SizeError)); assert_eq!(v2, Err(PackError::SizeError)); assert_eq!(v3, Err(PackError::SizeError)); assert_eq!(v4, Err(PackError::SizeError)); assert_eq!(v5, 0x12345678); assert_eq!(b5, &[]); assert_eq!(v6, 0x12345678); assert_eq!(b6, &[0xff]); } #[test] fn test_roundtrip_u32() { let v = 0x12345678u32; let i = v.pack().unwrap(); let (t1, b1): (u32, _) = unpack(&i).unwrap(); assert_eq!(t1, v); assert_eq!(b1, &[]); } #[test] fn test_pack_i32() { let v1 = 0x12345678i32; let v2 = -0x12345678i32; let i1 = v1.pack().unwrap(); let i2 = v2.pack().unwrap(); assert_eq!(i1, vec![0x12, 0x34, 0x56, 0x78]); assert_eq!(i2, vec![0xed, 0xcb, 0xa9, 0x88]); } #[test] fn test_unpack_i32() { let i1 = []; let i2 = [0x12]; let i3 = [0x12, 0x34]; let i4 = [0x12, 0x34, 0x56]; let i5 = [0x12, 0x34, 0x56, 0x78]; let i6 = [0x12, 0x34, 0x56, 0x78, 0xff]; let i7 = [0xed, 0xcb, 0xa9, 0x88]; let i8 = [0xed, 0xcb, 0xa9, 0x88, 0xff]; let v1: Result<(i32, _), PackError> = unpack(&i1); let v2: Result<(i32, _), PackError> = unpack(&i2); let v3: Result<(i32, _), PackError> = unpack(&i3); let v4: Result<(i32, _), PackError> = unpack(&i4); let (v5, b5): (i32, _) = unpack(&i5).unwrap(); let (v6, b6): (i32, _) = unpack(&i6).unwrap(); let (v7, b7): (i32, _) = unpack(&i7).unwrap(); let (v8, b8): (i32, _) = unpack(&i8).unwrap(); assert_eq!(v1, Err(PackError::SizeError)); assert_eq!(v2, Err(PackError::SizeError)); assert_eq!(v3, Err(PackError::SizeError)); assert_eq!(v4, Err(PackError::SizeError)); assert_eq!(v5, 0x12345678); assert_eq!(b5, &[]); assert_eq!(v6, 0x12345678); assert_eq!(b6, &[0xff]); assert_eq!(v7, -0x12345678); assert_eq!(b7, &[]); assert_eq!(v8, -0x12345678); assert_eq!(b8, &[0xff]); } #[test] fn test_roundtrip_i32() { let v1 = 0x12345678; let v2 = -0x12345678; let i1 = v1.pack().unwrap(); let i2 = v2.pack().unwrap(); let (t1, b1): (i32, _) = unpack(&i1).unwrap(); let (t2, b2): (i32, _) = unpack(&i2).unwrap(); assert_eq!(t1, v1); assert_eq!(b1, &[]); assert_eq!(t2, v2); assert_eq!(b2, &[]); } #[test] fn test_pack_u64() { let v1 = 0x0123456789abcdefu64; assert_eq!(v1.pack().unwrap(), vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]); } #[test] fn test_unpack_u64() { let i1 = []; let i2 = [0x01]; let i3 = [0x01, 0x23]; let i4 = [0x01, 0x23, 0x45]; let i5 = [0x01, 0x23, 0x45, 0x67]; let i6 = [0x01, 0x23, 0x45, 0x67, 0x89]; let i7 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab]; let i8 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd]; let i9 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]; let i10 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xff]; let v1: Result<(u64, _), PackError> = unpack(&i1); let v2: Result<(u64, _), PackError> = unpack(&i2); let v3: Result<(u64, _), PackError> = unpack(&i3); let v4: Result<(u64, _), PackError> = unpack(&i4); let v5: Result<(u64, _), PackError> = unpack(&i5); let v6: Result<(u64, _), PackError> = unpack(&i6); let v7: Result<(u64, _), PackError> = unpack(&i7); let v8: Result<(u64, _), PackError> = unpack(&i8); let (v9, b9): (u64, _) = unpack(&i9).unwrap(); let (v10, b10): (u64, _) = unpack(&i10).unwrap(); assert_eq!(v1, Err(PackError::SizeError)); assert_eq!(v2, Err(PackError::SizeError)); assert_eq!(v3, Err(PackError::SizeError)); assert_eq!(v4, Err(PackError::SizeError)); assert_eq!(v5, Err(PackError::SizeError)); assert_eq!(v6, Err(PackError::SizeError)); assert_eq!(v7, Err(PackError::SizeError)); assert_eq!(v8, Err(PackError::SizeError)); assert_eq!(v9, 0x0123456789abcdef); assert_eq!(b9, &[]); assert_eq!(v10, 0x0123456789abcdef); assert_eq!(b10, &[0xff]); } #[test] fn test_roundtrip_u64() { let v = 0x0123456789abcdefu64; let i = v.pack().unwrap(); let (t1, b1): (u64, _) = unpack(&i).unwrap(); assert_eq!(t1, v); assert_eq!(b1, &[]); } #[test] fn test_pack_i64() { let v1 = 0x123456789abcdefi64; let v2 = -0x123456789abcdefi64; assert_eq!(v1.pack().unwrap(), vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]); assert_eq!(v2.pack().unwrap(), vec![0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x11]); } #[test] fn test_unpack_i64() { let i1 = []; let i2 = [0x01]; let i3 = [0x01, 0x23]; let i4 = [0x01, 0x23, 0x45]; let i5 = [0x01, 0x23, 0x45, 0x67]; let i6 = [0x01, 0x23, 0x45, 0x67, 0x89]; let i7 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab]; let i8 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd]; let i9 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]; let i10 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xff]; let i11 = [0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x11]; let i12 = [0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x11, 0xff]; let v1: Result<(i64, _), PackError> = unpack(&i1); let v2: Result<(i64, _), PackError> = unpack(&i2); let v3: Result<(i64, _), PackError> = unpack(&i3); let v4: Result<(i64, _), PackError> = unpack(&i4); let v5: Result<(i64, _), PackError> = unpack(&i5); let v6: Result<(i64, _), PackError> = unpack(&i6); let v7: Result<(i64, _), PackError> = unpack(&i7); let v8: Result<(i64, _), PackError> = unpack(&i8); let (v9, b9): (i64, _) = unpack(&i9).unwrap(); let (v10, b10): (i64, _) = unpack(&i10).unwrap(); let (v11, b11): (i64, _) = unpack(&i11).unwrap(); let (v12, b12): (i64, _) = unpack(&i12).unwrap(); assert_eq!(v1, Err(PackError::SizeError)); assert_eq!(v2, Err(PackError::SizeError)); assert_eq!(v3, Err(PackError::SizeError)); assert_eq!(v4, Err(PackError::SizeError)); assert_eq!(v5, Err(PackError::SizeError)); assert_eq!(v6, Err(PackError::SizeError)); assert_eq!(v7, Err(PackError::SizeError)); assert_eq!(v8, Err(PackError::SizeError)); assert_eq!(v9, 0x0123456789abcdef); assert_eq!(b9, &[]); assert_eq!(v10, 0x0123456789abcdef); assert_eq!(b10, &[0xff]); assert_eq!(v11, -0x0123456789abcdef); assert_eq!(b11, &[]); assert_eq!(v12, -0x0123456789abcdef); assert_eq!(b12, &[0xff]); } #[test] fn test_roundtrip_i64() { let v1 = 0x123456789abcdefi64; let v2 = -0x123456789abcdefi64; let i1 = v1.pack().unwrap(); let i2 = v2.pack().unwrap(); let (t1, b1): (i64, _) = unpack(&i1).unwrap(); let (t2, b2): (i64, _) = unpack(&i2).unwrap(); assert_eq!(t1, v1); assert_eq!(b1, &[]); assert_eq!(t2, v2); assert_eq!(b2, &[]); } #[test] fn test_pack_u128() { let v1 = 0x0123456789abcdeffedcba9876543210u128; assert_eq!(v1.pack().unwrap(), vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10]); } #[test] fn test_unpack_u128() { let i1 = []; let i2 = [0x01]; let i3 = [0x01, 0x23]; let i4 = [0x01, 0x23, 0x45]; let i5 = [0x01, 0x23, 0x45, 0x67]; let i6 = [0x01, 0x23, 0x45, 0x67, 0x89]; let i7 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab]; let i8 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd]; let i9 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]; let i10 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe]; let i11 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc]; let i12 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba]; let i13 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98]; let i14 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76]; let i15 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54]; let i16 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32]; let i17 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10]; let i18 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0xff]; let v1: Result<(u128, _), PackError> = unpack(&i1); let v2: Result<(u128, _), PackError> = unpack(&i2); let v3: Result<(u128, _), PackError> = unpack(&i3); let v4: Result<(u128, _), PackError> = unpack(&i4); let v5: Result<(u128, _), PackError> = unpack(&i5); let v6: Result<(u128, _), PackError> = unpack(&i6); let v7: Result<(u128, _), PackError> = unpack(&i7); let v8: Result<(u128, _), PackError> = unpack(&i8); let v9: Result<(u128, _), PackError> = unpack(&i9); let v10: Result<(u128, _), PackError> = unpack(&i10); let v11: Result<(u128, _), PackError> = unpack(&i11); let v12: Result<(u128, _), PackError> = unpack(&i12); let v13: Result<(u128, _), PackError> = unpack(&i13); let v14: Result<(u128, _), PackError> = unpack(&i14); let v15: Result<(u128, _), PackError> = unpack(&i15); let v16: Result<(u128, _), PackError> = unpack(&i16); let (v17, b17): (u128, _) = unpack(&i17).unwrap(); let (v18, b18): (u128, _) = unpack(&i18).unwrap(); assert_eq!(v1, Err(PackError::SizeError)); assert_eq!(v2, Err(PackError::SizeError)); assert_eq!(v3, Err(PackError::SizeError)); assert_eq!(v4, Err(PackError::SizeError)); assert_eq!(v5, Err(PackError::SizeError)); assert_eq!(v6, Err(PackError::SizeError)); assert_eq!(v7, Err(PackError::SizeError)); assert_eq!(v8, Err(PackError::SizeError)); assert_eq!(v9, Err(PackError::SizeError)); assert_eq!(v10, Err(PackError::SizeError)); assert_eq!(v11, Err(PackError::SizeError)); assert_eq!(v12, Err(PackError::SizeError)); assert_eq!(v13, Err(PackError::SizeError)); assert_eq!(v14, Err(PackError::SizeError)); assert_eq!(v15, Err(PackError::SizeError)); assert_eq!(v16, Err(PackError::SizeError)); assert_eq!(v17, 0x0123456789abcdeffedcba9876543210); assert_eq!(b17, &[]); assert_eq!(v18, 0x0123456789abcdeffedcba9876543210); assert_eq!(b18, &[0xff]); } #[test] fn test_roundtrip_u128() { let v = 0x0123456789abcdeffedcba9876543210u128; let i = v.pack().unwrap(); let (t1, b1): (u128, _) = unpack(&i).unwrap(); assert_eq!(t1, v); assert_eq!(b1, &[]); } #[test] fn test_pack_i128() { let v1 = 0x0123456789abcdeffedcba9876543210i128; let v2 = -0x0123456789abcdeffedcba9876543210i128; assert_eq!(v1.pack().unwrap(), vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10]); assert_eq!(v2.pack().unwrap(), vec![0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xf0]); } #[test] fn test_unpack_i128() { let i1 = []; let i2 = [0x01]; let i3 = [0x01, 0x23]; let i4 = [0x01, 0x23, 0x45]; let i5 = [0x01, 0x23, 0x45, 0x67]; let i6 = [0x01, 0x23, 0x45, 0x67, 0x89]; let i7 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab]; let i8 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd]; let i9 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]; let i10 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe]; let i11 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc]; let i12 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba]; let i13 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98]; let i14 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76]; let i15 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54]; let i16 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32]; let i17 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10]; let i18 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0xff]; let i19 = [0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xf0]; let i20 = [0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xf0, 0xff]; let v1: Result<(i128, _), PackError> = unpack(&i1); let v2: Result<(i128, _), PackError> = unpack(&i2); let v3: Result<(i128, _), PackError> = unpack(&i3); let v4: Result<(i128, _), PackError> = unpack(&i4); let v5: Result<(i128, _), PackError> = unpack(&i5); let v6: Result<(i128, _), PackError> = unpack(&i6); let v7: Result<(i128, _), PackError> = unpack(&i7); let v8: Result<(i128, _), PackError> = unpack(&i8); let v9: Result<(i128, _), PackError> = unpack(&i9); let v10: Result<(i128, _), PackError> = unpack(&i10); let v11: Result<(i128, _), PackError> = unpack(&i11); let v12: Result<(i128, _), PackError> = unpack(&i12); let v13: Result<(i128, _), PackError> = unpack(&i13); let v14: Result<(i128, _), PackError> = unpack(&i14); let v15: Result<(i128, _), PackError> = unpack(&i15); let v16: Result<(i128, _), PackError> = unpack(&i16); let (v17, b17): (i128, _) = unpack(&i17).unwrap(); let (v18, b18): (i128, _) = unpack(&i18).unwrap(); let (v19, b19): (i128, _) = unpack(&i19).unwrap(); let (v20, b20): (i128, _) = unpack(&i20).unwrap(); assert_eq!(v1, Err(PackError::SizeError)); assert_eq!(v2, Err(PackError::SizeError)); assert_eq!(v3, Err(PackError::SizeError)); assert_eq!(v4, Err(PackError::SizeError)); assert_eq!(v5, Err(PackError::SizeError)); assert_eq!(v6, Err(PackError::SizeError)); assert_eq!(v7, Err(PackError::SizeError)); assert_eq!(v8, Err(PackError::SizeError)); assert_eq!(v9, Err(PackError::SizeError)); assert_eq!(v10, Err(PackError::SizeError)); assert_eq!(v11, Err(PackError::SizeError)); assert_eq!(v12, Err(PackError::SizeError)); assert_eq!(v13, Err(PackError::SizeError)); assert_eq!(v14, Err(PackError::SizeError)); assert_eq!(v15, Err(PackError::SizeError)); assert_eq!(v16, Err(PackError::SizeError)); assert_eq!(v17, 0x0123456789abcdeffedcba9876543210); assert_eq!(b17, &[]); assert_eq!(v18, 0x0123456789abcdeffedcba9876543210); assert_eq!(b18, &[0xff]); assert_eq!(v19, -0x0123456789abcdeffedcba9876543210); assert_eq!(b19, &[]); assert_eq!(v20, -0x0123456789abcdeffedcba9876543210); assert_eq!(b20, &[0xff]); } #[test] fn test_roundtrip_i128() { let v1 = 0x0123456789abcdeffedcba9876543210i128; let v2 = -0x0123456789abcdeffedcba9876543210i128; let i1 = v1.pack().unwrap(); let i2 = v2.pack().unwrap(); let (t1, b1): (i128, _) = unpack(&i1).unwrap(); let (t2, b2): (i128, _) = unpack(&i2).unwrap(); assert_eq!(t1, v1); assert_eq!(b1, &[]); assert_eq!(t2, v2); assert_eq!(b2, &[]); } #[test] fn test_pack_f32() { let v1 = 0.00000000000000000000000000056904566f32; let v2 = -7878801000000000000000000000.0f32; assert_eq!(v1.pack().unwrap(), &[0x12, 0x34, 0x56, 0x78]); assert_eq!(v2.pack().unwrap(), &[0xed, 0xcb, 0xa9, 0x88]); } #[test] fn test_unpack_f32() { let i1 = []; let i2 = [0x12]; let i3 = [0x12, 0x34]; let i4 = [0x12, 0x34, 0x56]; let i5 = [0x12, 0x34, 0x56, 0x78]; let i6 = [0x12, 0x34, 0x56, 0x78, 0xff]; let i7 = [0xed, 0xcb, 0xa9, 0x88]; let i8 = [0xed, 0xcb, 0xa9, 0x88, 0xff]; let v1: Result<(f32, _), PackError> = unpack(&i1); let v2: Result<(f32, _), PackError> = unpack(&i2); let v3: Result<(f32, _), PackError> = unpack(&i3); let v4: Result<(f32, _), PackError> = unpack(&i4); let (v5, b5): (f32, _) = unpack(&i5).unwrap(); let (v6, b6): (f32, _) = unpack(&i6).unwrap(); let (v7, b7): (f32, _) = unpack(&i7).unwrap(); let (v8, b8): (f32, _) = unpack(&i8).unwrap(); assert_eq!(v1, Err(PackError::SizeError)); assert_eq!(v2, Err(PackError::SizeError)); assert_eq!(v3, Err(PackError::SizeError)); assert_eq!(v4, Err(PackError::SizeError)); assert_eq!(v5, 0.00000000000000000000000000056904566); assert_eq!(b5, &[]); assert_eq!(v6, 0.00000000000000000000000000056904566); assert_eq!(b6, &[0xff]); assert_eq!(v7, -7878801000000000000000000000.0); assert_eq!(b7, &[]); assert_eq!(v8, -7878801000000000000000000000.0); assert_eq!(b8, &[0xff]); } #[test] fn test_roundtrip_f32() { let v1 = 0.00000000000000000000000000056904566f32; let v2 = -7878801000000000000000000000.0f32; let i1 = v1.pack().unwrap(); let i2 = v2.pack().unwrap(); let (t1, b1): (f32, _) = unpack(&i1).unwrap(); let (t2, b2): (f32, _) = unpack(&i2).unwrap(); assert_eq!(t1, v1); assert_eq!(b1, &[]); assert_eq!(t2, v2); assert_eq!(b2, &[]); } #[test] fn test_pack_f64() { let v1 = 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003512700564088504; let v2 = -1231330068773694700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0; assert_eq!(v1.pack().unwrap(), vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]); assert_eq!(v2.pack().unwrap(), vec![0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x11]); } #[test] fn test_unpack_f64() { let i1 = []; let i2 = [0x01]; let i3 = [0x01, 0x23]; let i4 = [0x01, 0x23, 0x45]; let i5 = [0x01, 0x23, 0x45, 0x67]; let i6 = [0x01, 0x23, 0x45, 0x67, 0x89]; let i7 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab]; let i8 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd]; let i9 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]; let i10 = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xff]; let i11 = [0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x11]; let i12 = [0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x11, 0xff]; let v1: Result<(f64, _), PackError> = unpack(&i1); let v2: Result<(f64, _), PackError> = unpack(&i2); let v3: Result<(f64, _), PackError> = unpack(&i3); let v4: Result<(f64, _), PackError> = unpack(&i4); let v5: Result<(f64, _), PackError> = unpack(&i5); let v6: Result<(f64, _), PackError> = unpack(&i6); let v7: Result<(f64, _), PackError> = unpack(&i7); let v8: Result<(f64, _), PackError> = unpack(&i8); let (v9, b9): (f64, _) = unpack(&i9).unwrap(); let (v10, b10): (f64, _) = unpack(&i10).unwrap(); let (v11, b11): (f64, _) = unpack(&i11).unwrap(); let (v12, b12): (f64, _) = unpack(&i12).unwrap(); assert_eq!(v1, Err(PackError::SizeError)); assert_eq!(v2, Err(PackError::SizeError)); assert_eq!(v3, Err(PackError::SizeError)); assert_eq!(v4, Err(PackError::SizeError)); assert_eq!(v5, Err(PackError::SizeError)); assert_eq!(v6, Err(PackError::SizeError)); assert_eq!(v7, Err(PackError::SizeError)); assert_eq!(v8, Err(PackError::SizeError)); assert_eq!(v9, 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003512700564088504); assert_eq!(b9, &[]); assert_eq!(v10, 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003512700564088504); assert_eq!(b10, &[0xff]); assert_eq!(v11, -1231330068773694700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0); assert_eq!(b11, &[]); assert_eq!(v12, -1231330068773694700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0); assert_eq!(b12, &[0xff]); } #[test] fn test_roundtrip_f64() { let v1 = 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003512700564088504; let v2 = -1231330068773694700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0; let i1 = v1.pack().unwrap(); let i2 = v2.pack().unwrap(); let (t1, b1): (f64, _) = unpack(&i1).unwrap(); let (t2, b2): (f64, _) = unpack(&i2).unwrap(); assert_eq!(t1, v1); assert_eq!(b1, &[]); assert_eq!(t2, v2); assert_eq!(b2, &[]); } #[test] fn test_pack_array() { let a1: [u8; 0] = []; let a2: [u8; 1] = [0x01]; let a3: [u8; 2] = [0x01, 0x23]; let a4: [u16; 3] = [0x01, 0x23, 0x45]; assert_eq!(a1.pack().unwrap(), &a1); assert_eq!(a2.pack().unwrap(), &a2); assert_eq!(a3.pack().unwrap(), &a3); assert_eq!(a4.pack().unwrap(), &[0x00, 0x01, 0x00, 0x23, 0x00, 0x45]); } #[test] fn test_unpack_array() { let a1 = []; let a2 = [0x01]; let a3 = [0x01, 0x23]; let a4 = [0x00, 0x01, 0x00, 0x23, 0x00]; let a5 = [0x00, 0x01, 0x00, 0x23, 0x00, 0x45]; let a6 = [0x00, 0x01, 0x00, 0x23, 0x00, 0x45, 0xff]; let a7 = [0x01, 0xff]; let (v1, b1): ([u8; 0], _) = unpack(&a1).unwrap(); let (v2, b2): ([u8; 1], _) = unpack(&a2).unwrap(); let (v3, b3): ([u8; 2], _) = unpack(&a3).unwrap(); let v4: Result<([u16; 3], _), PackError> = unpack(&a4); let (v5, b5): ([u16; 3], _) = unpack(&a5).unwrap(); let (v6, b6): ([u16; 3], _) = unpack(&a6).unwrap(); let (v7, b7): ([u8; 1], _) = unpack(&a7).unwrap(); assert_eq!(v1, []); assert_eq!(b1, &[]); assert_eq!(v2, [0x01]); assert_eq!(b2, &[]); assert_eq!(v3, [0x01, 0x23]); assert_eq!(b3, &[]); assert_eq!(v4, Err(PackError::SizeError)); assert_eq!(v5, [0x01, 0x23, 0x45]); assert_eq!(b5, &[]); assert_eq!(v6, [0x01, 0x23, 0x45]); assert_eq!(b6, &[0xff]); assert_eq!(v7, [0x01]); assert_eq!(b7, &[0xff]); } #[test] fn test_pack_vec() { let v1: Vec<u8> = vec![0x01, 0x23, 0x45]; let v2: Vec<u16> = vec![0x0123, 0x4567]; assert_eq!(v1.pack().unwrap(), [0x01, 0x23, 0x45]); assert_eq!(v2.pack().unwrap(), [0x01, 0x23, 0x45, 0x67]); } }
use std::fmt::Debug; use tokio::sync::{broadcast, mpsc}; use tokio::sync::{Mutex, RwLock}; // Notifier lets other tasks know that we're shutting down. #[derive(Debug)] pub struct Notifier { shutdown_tx: RwLock<Option<broadcast::Sender<()>>>, shutdown_complete_tx: RwLock<Option<mpsc::Sender<()>>>, shutdown_complete_rx: Mutex<mpsc::Receiver<()>>, } impl Notifier { // Creates a new Shutdown notifier pub fn new() -> Notifier { let (shutdown_tx, _) = broadcast::channel(1); let (shutdown_complete_tx, shutdown_complete_rx) = mpsc::channel(1); Notifier { shutdown_tx: RwLock::new(Some(shutdown_tx)), shutdown_complete_tx: RwLock::new(Some(shutdown_complete_tx)), shutdown_complete_rx: Mutex::new(shutdown_complete_rx), } } // Notifies shutdown listeners that shutdown is commencing. Listeners then need to gracefully // shutdown and signal that they are done by simply letting the Listener instance that they hold // go out of scope. pub async fn notify(&self) { // When the sender is dropped, all tasks which have `subscribe`d will // receive the shutdown signal and can exit drop(self.shutdown_tx.write().await.take()); // Drop final `Sender` so the `Receiver` used in linger() will complete drop(self.shutdown_complete_tx.write().await.take()) } // Waits for tasks holding shutdown listeners to finish pub async fn linger(&self) { // Wait for all active connections to finish processing. As the `Sender` // handle held by the listener has been dropped above, the only remaining // `Sender` instances are held by connection handler tasks. When those drop, // the `mpsc` channel will close and `recv()` will return `None`. let _ = self.shutdown_complete_rx.lock().await.recv().await; } pub async fn subscribe(&self) -> Listener { let sender_opt = self.shutdown_tx.read().await; let complete_sender_opt = self.shutdown_complete_tx.read().await; Listener { shutdown: sender_opt.is_none(), shutdown_rx: sender_opt.as_ref().map(|tx| tx.subscribe()), shutdown_complete_tx: complete_sender_opt.clone(), } } } // Listener listens for shutdown notifications #[derive(Debug)] #[allow(dead_code)] pub struct Listener { shutdown: bool, shutdown_rx: Option<broadcast::Receiver<()>>, shutdown_complete_tx: Option<mpsc::Sender<()>>, } impl Listener { /// Returns `true` if the shutdown signal has been received. pub(crate) fn is_shutdown(&self) -> bool { self.shutdown } /// Receive the shutdown notice, waiting if necessary. pub async fn listen(&mut self) { // If the shutdown signal has already been received, then return // immediately. if self.is_shutdown() { return; } // Cannot receive a "lag error" as only one value is ever sent. let _ = self.shutdown_rx.as_mut().unwrap().recv().await; // Remember that the signal has been received. self.shutdown = true; } }
use { num_traits::{AsPrimitive, One, PrimInt, Signed, Unsigned}, std::mem::size_of, }; pub trait ZigZag: Signed + PrimInt where Self: AsPrimitive<<Self as ZigZag>::UInt>, { type UInt: Unsigned + PrimInt + AsPrimitive<Self>; #[inline] fn encode(value: Self) -> Self::UInt { let s = (value << 1) ^ (value >> ((size_of::<Self>() * 8) - 1)); AsPrimitive::<Self::UInt>::as_(s) } #[inline] fn decode(value: Self::UInt) -> Self { let shr1 = value >> 1; let a1: Self = (value & One::one()).as_(); let neg: Self::UInt = (-a1).as_(); let or = shr1 ^ neg; or.as_() } } impl ZigZag for i128 { type UInt = u128; } impl ZigZag for i64 { type UInt = u64; } impl ZigZag for i32 { type UInt = u32; } impl ZigZag for i16 { type UInt = u16; } impl ZigZag for i8 { type UInt = u8; } #[cfg(test)] mod tests { use super::*; #[test] fn known_values() { let result = ZigZag::encode(0i32); assert_eq!(result, 0); let result = ZigZag::encode(-1i32); assert_eq!(result, 1); let result = ZigZag::encode(2147483647i32); assert_eq!(result, 4294967294); let result = ZigZag::encode(-2147483648i32); assert_eq!(result, 4294967295); } #[test] fn all_values() { for i in std::i16::MIN..=std::i16::MAX { let zig = ZigZag::encode(i); let zag = ZigZag::decode(zig); assert_eq!(i, zag); } } }
unsafe fn guessNumber(n: i32) -> i32 { let mut l = 1; let mut r = n as i64 + 1; while r - l > 1 { let mut mid = (l + r) / 2; match guess(mid as i32) { -1 => r = mid, 1 => l = mid, _ => return mid as i32 } } l as i32 }
use actix_cors::Cors; use actix_web::{middleware::Condition, web, App, HttpServer}; use anyhow::Context; use dotenv::dotenv; use drogue_cloud_admin_service::apps; use drogue_cloud_device_management_service::{ app, endpoints, service::{self, PostgresManagementServiceConfig}, Config, WebData, }; use drogue_cloud_registry_events::sender::KafkaEventSender; use drogue_cloud_service_common::{ config::ConfigFromEnv, health::HealthServer, openid::Authenticator, openid_auth, }; use futures::TryFutureExt; #[actix_web::main] async fn main() -> anyhow::Result<()> { env_logger::init(); dotenv().ok(); // Initialize config from environment variables let config = Config::from_env().unwrap(); let enable_auth = config.enable_auth; let authenticator = if enable_auth { Some(Authenticator::new().await?) } else { None }; let sender = KafkaEventSender::new(config.kafka_sender) .context("Unable to create Kafka event sender")?; let max_json_payload_size = 64 * 1024; let service = service::PostgresManagementService::new( PostgresManagementServiceConfig::from_env()?, sender, )?; let data = web::Data::new(WebData { authenticator, service: service.clone(), }); // health server let health = HealthServer::new(config.health, vec![Box::new(service.clone())]); // main server let main = HttpServer::new(move || { let auth = openid_auth!(req -> { req .app_data::<web::Data<WebData<service::PostgresManagementService<KafkaEventSender>>>>() .as_ref() .and_then(|d|d.authenticator.as_ref()) }); app!(KafkaEventSender, enable_auth, max_json_payload_size, auth) // for the management service .app_data(data.clone()) // for the admin service .app_data(web::Data::new(apps::WebData { service: service.clone(), })) }) .bind(config.bind_addr)? .run(); // run futures::try_join!(health.run(), main.err_into())?; // exiting Ok(()) }