text
stringlengths
8
4.13M
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Control register 1"] pub cr1: CR1, #[doc = "0x04 - Control register 2"] pub cr2: CR2, #[doc = "0x08 - Own address register 1"] pub oar1: OAR1, #[doc = "0x0c - Own address register 2"] pub oar2: OAR2, #[doc = "0x10 - Data register"] pub dr: DR, #[doc = "0x14 - Status register 1"] pub sr1: SR1, #[doc = "0x18 - Status register 2"] pub sr2: SR2, #[doc = "0x1c - Clock control register"] pub ccr: CCR, #[doc = "0x20 - TRISE register"] pub trise: TRISE, } #[doc = "CR1 (rw) register accessor: Control register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr1::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 [`cr1::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 [`cr1`] module"] pub type CR1 = crate::Reg<cr1::CR1_SPEC>; #[doc = "Control register 1"] pub mod cr1; #[doc = "CR2 (rw) register accessor: Control register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr2::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 [`cr2::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 [`cr2`] module"] pub type CR2 = crate::Reg<cr2::CR2_SPEC>; #[doc = "Control register 2"] pub mod cr2; #[doc = "OAR1 (rw) register accessor: Own address register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`oar1::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 [`oar1::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 [`oar1`] module"] pub type OAR1 = crate::Reg<oar1::OAR1_SPEC>; #[doc = "Own address register 1"] pub mod oar1; #[doc = "OAR2 (rw) register accessor: Own address register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`oar2::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 [`oar2::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 [`oar2`] module"] pub type OAR2 = crate::Reg<oar2::OAR2_SPEC>; #[doc = "Own address register 2"] pub mod oar2; #[doc = "DR (rw) register accessor: Data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dr::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 [`dr::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 [`dr`] module"] pub type DR = crate::Reg<dr::DR_SPEC>; #[doc = "Data register"] pub mod dr; #[doc = "SR1 (rw) register accessor: Status register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr1::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 [`sr1::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 [`sr1`] module"] pub type SR1 = crate::Reg<sr1::SR1_SPEC>; #[doc = "Status register 1"] pub mod sr1; #[doc = "SR2 (r) register accessor: Status register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr2::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sr2`] module"] pub type SR2 = crate::Reg<sr2::SR2_SPEC>; #[doc = "Status register 2"] pub mod sr2; #[doc = "CCR (rw) register accessor: Clock control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr::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 [`ccr::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 [`ccr`] module"] pub type CCR = crate::Reg<ccr::CCR_SPEC>; #[doc = "Clock control register"] pub mod ccr; #[doc = "TRISE (rw) register accessor: TRISE register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`trise::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 [`trise::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 [`trise`] module"] pub type TRISE = crate::Reg<trise::TRISE_SPEC>; #[doc = "TRISE register"] pub mod trise;
#![cfg(any(feature = "hash_md5", feauture = "hash_sha1"))] use std::convert::TryInto; use md5; use sha1::Sha1; use crate::{Layout, Node, Variant, Version, UUID}; impl Layout { fn hash_fields(hash: [u8; 16], v: Version) -> Self { Self { field_low: ((hash[0] as u32) << 24) | (hash[1] as u32) << 16 | (hash[2] as u32) << 8 | hash[3] as u32, field_mid: (hash[4] as u16) << 8 | (hash[5] as u16), field_high_and_version: ((hash[6] as u16) << 8 | (hash[7] as u16)) & 0xfff | (v as u16) << 12, clock_seq_high_and_reserved: (hash[8] & 0xf) | (Variant::RFC as u8) << 4, clock_seq_low: hash[9] as u8, node: Node([hash[10], hash[11], hash[12], hash[13], hash[14], hash[15]]), } } } impl UUID { /// New UUID version-3 using md5 algorithme #[doc(cfg(feature = "hash_md5"))] pub fn using_md5(data: &str, ns: UUID) -> Layout { let hash = md5::compute(Self::concat(data, ns)).0; Layout::hash_fields(hash, Version::MD5) } /// New UUID version-5 using sha1 algorithme #[doc(cfg(feature = "hash_sha1"))] pub fn using_sha1(data: &str, ns: UUID) -> Layout { let hash = Sha1::from(Self::concat(data, ns)).digest().bytes()[..16] .try_into() .unwrap(); Layout::hash_fields(hash, Version::SHA1) } fn concat(data: &str, ns: UUID) -> String { format!("{:x}", ns) + data } } impl ToString for Layout { fn to_string(&self) -> String { format!("{:02x}", self.as_bytes(),) } } /// `UUID` version-3 #[doc(cfg(feature = "hash_md5"))] #[macro_export] macro_rules! v3 { ($data:expr, $ns:expr) => { format!("{:x}", $crate::UUID::using_md5($data, $ns).as_bytes()) }; } /// `UUID` version-5 #[doc(cfg(feature = "hash_sha1"))] #[macro_export] macro_rules! v5 { ($data:expr, $ns:expr) => { format!("{:x}", $crate::UUID::using_sha1($data, $ns).as_bytes()) }; } #[cfg(test)] mod tests { use super::*; #[test] fn new_uuid_using_md5() { let ns = [ UUID::NAMESPACE_DNS, UUID::NAMESPACE_OID, UUID::NAMESPACE_URL, UUID::NAMESPACE_X500, ]; for s in ns.iter() { assert_eq!( UUID::using_md5("test_data", *s).get_version(), Some(Version::MD5) ); assert_eq!( UUID::using_md5("test_data", *s).get_variant(), Some(Variant::RFC) ); } } #[test] fn new_uuid_using_sha1() { let ns = [ UUID::NAMESPACE_DNS, UUID::NAMESPACE_OID, UUID::NAMESPACE_URL, UUID::NAMESPACE_X500, ]; for s in ns.iter() { assert_eq!( UUID::using_sha1("test_data", *s).get_version(), Some(Version::SHA1) ); assert_eq!( UUID::using_sha1("test_data", *s).get_variant(), Some(Variant::RFC) ); } } }
use std::process::ExitStatus; use std::os::unix::process::ExitStatusExt; pub fn clear_screen() { print!( "\x1B[2J\x1B[H" ); } pub unsafe fn disable_ctrl_c() { // TODO } pub fn get_exit_code( status: ExitStatus ) -> Option<i32> { match status.code() { Some( x ) => Some( x ), None => status.signal() } }
use std::env; use std::process; use std::fs::File; use std::io; use std::io::Read; fn get_file_string(filename: &str) -> Result<String, io::Error> { let mut file = try!(File::open(filename)); let mut s = String::new(); try!(file.read_to_string(&mut s)); Ok(s) } fn main() { let args = env::args().skip(1); for filename in args { match get_file_string(&filename) { Ok(s) => println!("{}", s), Err(msg) => panic!("Error getting file.") } } }
struct Solution; use std::collections::HashMap; impl Solution { pub fn find_itinerary(tickets: Vec<Vec<String>>) -> Vec<String> { // 转成 map,出发点是 key,终点列表是 value,并且 value 是排序了的。 let mut map = HashMap::new(); for mut ticket in tickets.into_iter() { let values = map.entry(ticket.remove(0)).or_insert(Vec::new()); values.push(ticket.remove(0)); } for (_, values) in map.iter_mut() { values.sort(); } let mut ans = Vec::new(); Self::find_itinerary_dfs("JFK".to_owned(), &mut map, &mut ans); ans.reverse(); ans } fn find_itinerary_dfs( begin: String, tickets: &mut HashMap<String, Vec<String>>, ans: &mut Vec<String>, ) { loop { match tickets.get_mut(&begin) { None => { break; } Some(values) => { if values.len() == 0 { break; } Self::find_itinerary_dfs(values.remove(0), tickets, ans); } } } ans.push(begin); } pub fn find_itinerary_failed(tickets: Vec<Vec<String>>) -> Vec<String> { // 转成 map,出发点是 key,终点列表是 value,并且 value 是排序了的。 let mut map = HashMap::new(); for mut ticket in tickets.into_iter() { let values = map.entry(ticket.remove(0)).or_insert(Vec::new()); values.push(ticket.remove(0)); } for (_, values) in map.iter_mut() { values.sort_by(|x, y| y.cmp(x)); } // 从 JFK 出发 let mut ans = vec!["JFK".to_owned()]; let mut begin = ans.last().unwrap(); loop { // 获取到终点列表。 match map.get_mut(begin) { // ERROR!! 如果获取到最后一个后不能有效的走完全部的行程,那么需要尝试其它路径。 // 获取到列表的最后一个。 Some(values) => match values.pop() { Some(end) => { ans.push(end); begin = ans.last().unwrap(); } None => break, }, None => break, } } ans } } #[cfg(test)] mod tests { use super::*; #[test] fn test_find_itinerary1() { let tickers = vec![ vec!["MUC", "LHR"], vec!["JFK", "MUC"], vec!["SFO", "SJC"], vec!["LHR", "SFO"], ] .into_iter() .map(|row| { row.into_iter() .map(|s| s.to_owned()) .collect::<Vec<String>>() }) .collect::<Vec<Vec<String>>>(); let ans = Solution::find_itinerary(tickers); let want = vec!["JFK", "MUC", "LHR", "SFO", "SJC"] .into_iter() .map(|s| s.to_owned()) .collect::<Vec<String>>(); assert_eq!(ans, want); } #[test] fn test_find_itinerary2() { let tickers = vec![ vec!["JFK", "SFO"], vec!["JFK", "ATL"], vec!["SFO", "ATL"], vec!["ATL", "JFK"], vec!["ATL", "SFO"], ] .into_iter() .map(|row| { row.into_iter() .map(|s| s.to_owned()) .collect::<Vec<String>>() }) .collect::<Vec<Vec<String>>>(); let ans = Solution::find_itinerary(tickers); let want = vec!["JFK", "ATL", "JFK", "SFO", "ATL", "SFO"] .into_iter() .map(|s| s.to_owned()) .collect::<Vec<String>>(); assert_eq!(ans, want); } #[test] fn test_find_itinerary3() { let tickers = vec![vec!["JFK", "KUL"], vec!["JFK", "NRT"], vec!["NRT", "JFK"]] .into_iter() .map(|row| { row.into_iter() .map(|s| s.to_owned()) .collect::<Vec<String>>() }) .collect::<Vec<Vec<String>>>(); let ans = Solution::find_itinerary(tickers); let want = vec!["JFK", "NRT", "JFK", "KUL"] .into_iter() .map(|s| s.to_owned()) .collect::<Vec<String>>(); assert_eq!(ans, want); } }
use crate::lib::canister_info::{CanisterInfo, CanisterInfoFactory}; use crate::lib::error::DfxResult; use std::path::{Path, PathBuf}; pub struct MotokoCanisterInfo { input_path: PathBuf, output_root: PathBuf, idl_path: PathBuf, output_wasm_path: PathBuf, output_idl_path: PathBuf, output_did_js_path: PathBuf, output_canister_js_path: PathBuf, output_assets_root: PathBuf, packtool: Option<String>, has_frontend: bool, } impl MotokoCanisterInfo { pub fn get_main_path(&self) -> &Path { self.input_path.as_path() } pub fn get_output_wasm_path(&self) -> &Path { self.output_wasm_path.as_path() } pub fn get_output_idl_path(&self) -> &Path { self.output_idl_path.as_path() } pub fn get_output_did_js_path(&self) -> &Path { self.output_did_js_path.as_path() } pub fn get_output_canister_js_path(&self) -> &Path { self.output_canister_js_path.as_path() } pub fn get_output_assets_root(&self) -> &Path { self.output_assets_root.as_path() } pub fn get_output_root(&self) -> &Path { self.output_root.as_path() } pub fn get_packtool(&self) -> &Option<String> { &self.packtool } pub fn has_frontend(&self) -> bool { self.has_frontend } } impl CanisterInfoFactory for MotokoCanisterInfo { fn supports(info: &CanisterInfo) -> bool { info.get_type() == "motoko" } fn create(info: &CanisterInfo) -> DfxResult<MotokoCanisterInfo> { let workspace_root = info.get_workspace_root(); let build_root = info.get_build_root(); let name = info.get_name(); let idl_path = build_root.join("idl/"); let main_path = info.get_extra::<PathBuf>("main")?; let input_path = workspace_root.join(&main_path); let output_root = build_root.join(name); let output_wasm_path = output_root.join(name).with_extension("wasm"); let output_idl_path = output_wasm_path.with_extension("did"); let output_did_js_path = output_wasm_path.with_extension("did.js"); let output_canister_js_path = output_wasm_path.with_extension("js"); let output_assets_root = output_root.join("assets"); Ok(MotokoCanisterInfo { input_path, output_root, idl_path, output_wasm_path, output_idl_path, output_did_js_path, output_canister_js_path, output_assets_root, packtool: info.get_packtool().clone(), has_frontend: info.get_extra_value("frontend").is_some(), }) } }
use super::*; pub async fn analyze_one_inner( analysis_id: &String, sender: &Sender<RealTimeMessage>, temp_path: &PathBuf, ) -> Option<()> { send_stage(Stage::InitializeAnalysis, StageResult::Pending, sender).ok()?; let a = match get_analysis_package(analysis_id) { Some(v) => v, None => { send_stage(Stage::InitializeAnalysis, StageResult::Failure, sender).ok()?; return None; } }; send_stage(Stage::InitializeAnalysis, StageResult::Success, sender).ok()?; send_stage(Stage::ImportInputFiles, StageResult::Pending, sender).ok()?; let imported = import_files(temp_path, &a); if !imported { send_stage(Stage::ImportInputFiles, StageResult::Failure, sender).ok()?; return None; } send_stage(Stage::ImportInputFiles, StageResult::Success, sender).ok()?; send_stage(Stage::CleanRun, StageResult::Pending, sender).ok()?; let clean_run = if a.metadata.language == LanguageType::Stata { run_stata(temp_path, sender).await } else { run_r(temp_path, sender).await }; if clean_run.is_none() { send_stage(Stage::CleanRun, StageResult::Failure, sender).ok()?; return None; } send_stage(Stage::CleanRun, StageResult::Success, sender).ok()?; send_stage(Stage::OutputFiles, StageResult::Pending, sender).ok()?; let all_files_stored = store_outputs(temp_path, &a); if !all_files_stored { send_stage(Stage::OutputFiles, StageResult::Failure, sender).ok()?; return None; } send_stage(Stage::OutputFiles, StageResult::Success, sender).ok()?; Some(()) } fn import_files(temp_path: &PathBuf, a: &AnalysisPackage) -> bool { // Script let code_file_path = temp_path.join(_FILE_NAME_MYSCRIPT); let res1 = write(code_file_path, format!("{}\r\n", &a.code)); if res1.is_err() { return false; } // Input files for input in &a.metadata.inputs { let fr_path = get_path_to_file(&input.folder_type, &input.analysis_id, &input.file_name); let to_path = temp_path.join(&input.file_name); let res2 = copy(fr_path, to_path); if res2.is_err() { return false; } } true } fn store_outputs(temp_path: &PathBuf, a: &AnalysisPackage) -> bool { let mut all_successful = true; for output in &a.metadata.outputs { let fr_path = temp_path.join(&output.file_name); if metadata(&fr_path).is_err() { all_successful = false; continue; } let to_path = PathBuf::from(_ANALYSES_FOLDER) .join(&a.id) .join(&output.file_name); if copy(fr_path, to_path).is_err() { all_successful = false; continue; } } all_successful } ///////////////////////////////////////////// ///////////////////////////////////////////// ///////////////////////////////////////////// ///////////////////////////////////////////// fn send_stage( stage: Stage, stage_result: StageResult, sender: &Sender<RealTimeMessage>, ) -> Result<(), tokio::sync::mpsc::error::TrySendError<RealTimeMessage>> { let rtm = RealTimeMessage { msg_type: MessageType::Stage, stage: Some(stage), stage_result: Some(stage_result), log: None, }; sender.try_send(rtm) }
#[doc = "Register `PLLSAICFGR` reader"] pub type R = crate::R<PLLSAICFGR_SPEC>; #[doc = "Register `PLLSAICFGR` writer"] pub type W = crate::W<PLLSAICFGR_SPEC>; #[doc = "Field `PLLSAIN` reader - PLLSAI division factor for VCO"] pub type PLLSAIN_R = crate::FieldReader<u16>; #[doc = "Field `PLLSAIN` writer - PLLSAI division factor for VCO"] pub type PLLSAIN_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 9, O, u16>; #[doc = "Field `PLLSAIQ` reader - PLLSAI division factor for SAI1 clock"] pub type PLLSAIQ_R = crate::FieldReader; #[doc = "Field `PLLSAIQ` writer - PLLSAI division factor for SAI1 clock"] pub type PLLSAIQ_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `PLLSAIR` reader - PLLSAI division factor for LCD clock"] pub type PLLSAIR_R = crate::FieldReader; #[doc = "Field `PLLSAIR` writer - PLLSAI division factor for LCD clock"] pub type PLLSAIR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; impl R { #[doc = "Bits 6:14 - PLLSAI division factor for VCO"] #[inline(always)] pub fn pllsain(&self) -> PLLSAIN_R { PLLSAIN_R::new(((self.bits >> 6) & 0x01ff) as u16) } #[doc = "Bits 24:27 - PLLSAI division factor for SAI1 clock"] #[inline(always)] pub fn pllsaiq(&self) -> PLLSAIQ_R { PLLSAIQ_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 28:30 - PLLSAI division factor for LCD clock"] #[inline(always)] pub fn pllsair(&self) -> PLLSAIR_R { PLLSAIR_R::new(((self.bits >> 28) & 7) as u8) } } impl W { #[doc = "Bits 6:14 - PLLSAI division factor for VCO"] #[inline(always)] #[must_use] pub fn pllsain(&mut self) -> PLLSAIN_W<PLLSAICFGR_SPEC, 6> { PLLSAIN_W::new(self) } #[doc = "Bits 24:27 - PLLSAI division factor for SAI1 clock"] #[inline(always)] #[must_use] pub fn pllsaiq(&mut self) -> PLLSAIQ_W<PLLSAICFGR_SPEC, 24> { PLLSAIQ_W::new(self) } #[doc = "Bits 28:30 - PLLSAI division factor for LCD clock"] #[inline(always)] #[must_use] pub fn pllsair(&mut self) -> PLLSAIR_W<PLLSAICFGR_SPEC, 28> { PLLSAIR_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 = "RCC PLL configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pllsaicfgr::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 [`pllsaicfgr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct PLLSAICFGR_SPEC; impl crate::RegisterSpec for PLLSAICFGR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`pllsaicfgr::R`](R) reader structure"] impl crate::Readable for PLLSAICFGR_SPEC {} #[doc = "`write(|w| ..)` method takes [`pllsaicfgr::W`](W) writer structure"] impl crate::Writable for PLLSAICFGR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets PLLSAICFGR to value 0x2400_3000"] impl crate::Resettable for PLLSAICFGR_SPEC { const RESET_VALUE: Self::Ux = 0x2400_3000; }
macro_rules! remove_overriden { (@remove $_self:ident, $v:ident, $a:ident.$ov:ident) => { if let Some(ref ora) = $a.$ov { vec_remove_all!($_self.$v, ora); } }; (@arg $_self:ident, $arg:ident) => { remove_overriden!(@remove $_self, required, $arg.requires); remove_overriden!(@remove $_self, blacklist, $arg.blacklist); remove_overriden!(@remove $_self, overrides, $arg.overrides); }; ($_self:ident, $name:expr) => { debugln!("macro=remove_overriden!;"); if let Some(ref o) = $_self.opts.iter().filter(|o| o.name == *$name).next() { remove_overriden!(@arg $_self, o); } else if let Some(ref f) = $_self.flags.iter().filter(|f| f.name == *$name).next() { remove_overriden!(@arg $_self, f); } else if let Some(p) = $_self.positionals.values().filter(|p| p.name == *$name).next() { remove_overriden!(@arg $_self, p); } }; } macro_rules! arg_post_processing { ($me:ident, $arg:ident, $matcher:ident) => { debugln!("macro=arg_post_processing!;"); // Handle POSIX overrides debug!("Is '{}' in overrides...", $arg.to_string()); if $me.overrides.contains(&$arg.name()) { if let Some(ref name) = $me.overriden_from($arg.name(), $matcher) { sdebugln!("Yes by {}", name); $matcher.remove(name); remove_overriden!($me, name); } } else { sdebugln!("No"); } // Add overrides debug!("Does '{}' have overrides...", $arg.to_string()); if let Some(or) = $arg.overrides() { sdebugln!("Yes"); $matcher.remove_all(or); for pa in or { remove_overriden!($me, pa); } $me.overrides.extend(or); vec_remove_all!($me.required, or); } else { sdebugln!("No"); } // Handle conflicts debug!("Does '{}' have conflicts...", $arg.to_string()); if let Some(bl) = $arg.blacklist() { sdebugln!("Yes"); $me.blacklist.extend(bl); vec_remove_all!($me.overrides, bl); vec_remove_all!($me.required, bl); } else { sdebugln!("No"); } // Add all required args which aren't already found in matcher to the master // list debug!("Does '{}' have requirements...", $arg.to_string()); if let Some(reqs) = $arg.requires() { for n in reqs { if $matcher.contains(&n) { sdebugln!("\tYes '{}' but it's already met", n); continue; } else { sdebugln!("\tYes '{}'", n); } $me.required.push(n); } } else { sdebugln!("No"); } _handle_group_reqs!($me, $arg); }; } macro_rules! _handle_group_reqs{ ($me:ident, $arg:ident) => ({ use args::AnyArg; debugln!("macro=_handle_group_reqs!;"); for grp in $me.groups.values() { let mut found = false; for name in &grp.args { if name == &$arg.name() { vec_remove!($me.required, name); if let Some(ref reqs) = grp.requires { $me.required.extend(reqs); } if let Some(ref bl) = grp.conflicts { $me.blacklist.extend(bl); } found = true; // What if arg is in more than one group with different reqs? break; } } if found { vec_remove_all!($me.required, &grp.args); $me.blacklist.extend(&grp.args); vec_remove!($me.blacklist, &$arg.name()); } } }) } macro_rules! validate_multiples { ($_self:ident, $a:ident, $m:ident) => { debugln!("macro=validate_multiples!;"); if $m.contains(&$a.name) && !$a.settings.is_set(ArgSettings::Multiple) { // Not the first time, and we don't allow multiples return Err(Error::unexpected_multiple_usage($a, &*$_self.create_current_usage($m))) } }; }
/// NotificationSubject contains the notification subject (Issue/Pull/Commit) #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct NotificationSubject { pub latest_comment_url: Option<String>, pub state: Option<String>, pub title: Option<String>, #[serde(rename = "type")] pub type_: Option<String>, pub url: Option<String>, } impl NotificationSubject { /// Create a builder for this object. #[inline] pub fn builder() -> NotificationSubjectBuilder { NotificationSubjectBuilder { body: Default::default(), } } } impl Into<NotificationSubject> for NotificationSubjectBuilder { fn into(self) -> NotificationSubject { self.body } } /// Builder for [`NotificationSubject`](./struct.NotificationSubject.html) object. #[derive(Debug, Clone)] pub struct NotificationSubjectBuilder { body: self::NotificationSubject, } impl NotificationSubjectBuilder { #[inline] pub fn latest_comment_url(mut self, value: impl Into<String>) -> Self { self.body.latest_comment_url = Some(value.into()); self } #[inline] pub fn state(mut self, value: impl Into<String>) -> Self { self.body.state = Some(value.into()); self } #[inline] pub fn title(mut self, value: impl Into<String>) -> Self { self.body.title = Some(value.into()); self } #[inline] pub fn type_(mut self, value: impl Into<String>) -> Self { self.body.type_ = Some(value.into()); self } #[inline] pub fn url(mut self, value: impl Into<String>) -> Self { self.body.url = Some(value.into()); self } }
use byteorder::{ByteOrder, NativeEndian}; use crate::{ traits::{Emitable, Parseable}, DecodeError, Field, }; const FORWARDING: Field = 0..4; const MC_FORWARDING: Field = 4..8; const PROXY_ARP: Field = 8..12; const ACCEPT_REDIRECTS: Field = 12..16; const SECURE_REDIRECTS: Field = 16..20; const SEND_REDIRECTS: Field = 20..24; const SHARED_MEDIA: Field = 24..28; const RP_FILTER: Field = 28..32; const ACCEPT_SOURCE_ROUTE: Field = 32..36; const BOOTP_RELAY: Field = 36..40; const LOG_MARTIANS: Field = 40..44; const TAG: Field = 44..48; const ARPFILTER: Field = 48..52; const MEDIUM_ID: Field = 52..56; const NOXFRM: Field = 56..60; const NOPOLICY: Field = 60..64; const FORCE_IGMP_VERSION: Field = 64..68; const ARP_ANNOUNCE: Field = 68..72; const ARP_IGNORE: Field = 72..76; const PROMOTE_SECONDARIES: Field = 76..80; const ARP_ACCEPT: Field = 80..84; const ARP_NOTIFY: Field = 84..88; const ACCEPT_LOCAL: Field = 88..92; const SRC_VMARK: Field = 92..96; const PROXY_ARP_PVLAN: Field = 96..100; const ROUTE_LOCALNET: Field = 100..104; const IGMPV2_UNSOLICITED_REPORT_INTERVAL: Field = 104..108; const IGMPV3_UNSOLICITED_REPORT_INTERVAL: Field = 108..112; const IGNORE_ROUTES_WITH_LINKDOWN: Field = 112..116; const DROP_UNICAST_IN_L2_MULTICAST: Field = 116..120; const DROP_GRATUITOUS_ARP: Field = 120..124; #[derive(Clone, Copy, Eq, PartialEq, Debug)] pub struct LinkInetDevConf { pub forwarding: i32, pub mc_forwarding: i32, pub proxy_arp: i32, pub accept_redirects: i32, pub secure_redirects: i32, pub send_redirects: i32, pub shared_media: i32, pub rp_filter: i32, pub accept_source_route: i32, pub bootp_relay: i32, pub log_martians: i32, pub tag: i32, pub arpfilter: i32, pub medium_id: i32, pub noxfrm: i32, pub nopolicy: i32, pub force_igmp_version: i32, pub arp_announce: i32, pub arp_ignore: i32, pub promote_secondaries: i32, pub arp_accept: i32, pub arp_notify: i32, pub accept_local: i32, pub src_vmark: i32, pub proxy_arp_pvlan: i32, pub route_localnet: i32, pub igmpv2_unsolicited_report_interval: i32, pub igmpv3_unsolicited_report_interval: i32, pub ignore_routes_with_linkdown: i32, pub drop_unicast_in_l2_multicast: i32, pub drop_gratuitous_arp: i32, } pub const LINK_INET_DEV_CONF_LEN: usize = DROP_GRATUITOUS_ARP.end; #[derive(Debug, PartialEq, Eq, Clone)] pub struct LinkInetDevConfBuffer<T> { buffer: T, } impl<T: AsRef<[u8]>> LinkInetDevConfBuffer<T> { pub fn new(buffer: T) -> LinkInetDevConfBuffer<T> { LinkInetDevConfBuffer { buffer } } pub fn new_checked(buffer: T) -> Result<LinkInetDevConfBuffer<T>, DecodeError> { let buf = Self::new(buffer); buf.check_buffer_length()?; Ok(buf) } fn check_buffer_length(&self) -> Result<(), DecodeError> { let len = self.buffer.as_ref().len(); if len < LINK_INET_DEV_CONF_LEN { return Err(format!( "invalid LinkInetDevConfBuffer buffer: length is {} instead of {}", len, LINK_INET_DEV_CONF_LEN ) .into()); } Ok(()) } pub fn into_inner(self) -> T { self.buffer } pub fn forwarding(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[FORWARDING]) } pub fn mc_forwarding(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[MC_FORWARDING]) } pub fn proxy_arp(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[PROXY_ARP]) } pub fn accept_redirects(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[ACCEPT_REDIRECTS]) } pub fn secure_redirects(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[SECURE_REDIRECTS]) } pub fn send_redirects(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[SEND_REDIRECTS]) } pub fn shared_media(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[SHARED_MEDIA]) } pub fn rp_filter(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[RP_FILTER]) } pub fn accept_source_route(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[ACCEPT_SOURCE_ROUTE]) } pub fn bootp_relay(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[BOOTP_RELAY]) } pub fn log_martians(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[LOG_MARTIANS]) } pub fn tag(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[TAG]) } pub fn arpfilter(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[ARPFILTER]) } pub fn medium_id(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[MEDIUM_ID]) } pub fn noxfrm(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[NOXFRM]) } pub fn nopolicy(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[NOPOLICY]) } pub fn force_igmp_version(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[FORCE_IGMP_VERSION]) } pub fn arp_announce(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[ARP_ANNOUNCE]) } pub fn arp_ignore(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[ARP_IGNORE]) } pub fn promote_secondaries(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[PROMOTE_SECONDARIES]) } pub fn arp_accept(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[ARP_ACCEPT]) } pub fn arp_notify(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[ARP_NOTIFY]) } pub fn accept_local(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[ACCEPT_LOCAL]) } pub fn src_vmark(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[SRC_VMARK]) } pub fn proxy_arp_pvlan(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[PROXY_ARP_PVLAN]) } pub fn route_localnet(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[ROUTE_LOCALNET]) } pub fn igmpv2_unsolicited_report_interval(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[IGMPV2_UNSOLICITED_REPORT_INTERVAL]) } pub fn igmpv3_unsolicited_report_interval(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[IGMPV3_UNSOLICITED_REPORT_INTERVAL]) } pub fn ignore_routes_with_linkdown(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[IGNORE_ROUTES_WITH_LINKDOWN]) } pub fn drop_unicast_in_l2_multicast(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[DROP_UNICAST_IN_L2_MULTICAST]) } pub fn drop_gratuitous_arp(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[DROP_GRATUITOUS_ARP]) } } impl<T: AsRef<[u8]> + AsMut<[u8]>> LinkInetDevConfBuffer<T> { pub fn set_forwarding(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[FORWARDING], value) } pub fn set_mc_forwarding(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[MC_FORWARDING], value) } pub fn set_proxy_arp(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[PROXY_ARP], value) } pub fn set_accept_redirects(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[ACCEPT_REDIRECTS], value) } pub fn set_secure_redirects(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[SECURE_REDIRECTS], value) } pub fn set_send_redirects(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[SEND_REDIRECTS], value) } pub fn set_shared_media(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[SHARED_MEDIA], value) } pub fn set_rp_filter(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[RP_FILTER], value) } pub fn set_accept_source_route(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[ACCEPT_SOURCE_ROUTE], value) } pub fn set_bootp_relay(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[BOOTP_RELAY], value) } pub fn set_log_martians(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[LOG_MARTIANS], value) } pub fn set_tag(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[TAG], value) } pub fn set_arpfilter(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[ARPFILTER], value) } pub fn set_medium_id(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[MEDIUM_ID], value) } pub fn set_noxfrm(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[NOXFRM], value) } pub fn set_nopolicy(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[NOPOLICY], value) } pub fn set_force_igmp_version(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[FORCE_IGMP_VERSION], value) } pub fn set_arp_announce(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[ARP_ANNOUNCE], value) } pub fn set_arp_ignore(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[ARP_IGNORE], value) } pub fn set_promote_secondaries(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[PROMOTE_SECONDARIES], value) } pub fn set_arp_accept(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[ARP_ACCEPT], value) } pub fn set_arp_notify(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[ARP_NOTIFY], value) } pub fn set_accept_local(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[ACCEPT_LOCAL], value) } pub fn set_src_vmark(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[SRC_VMARK], value) } pub fn set_proxy_arp_pvlan(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[PROXY_ARP_PVLAN], value) } pub fn set_route_localnet(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[ROUTE_LOCALNET], value) } pub fn set_igmpv2_unsolicited_report_interval(&mut self, value: i32) { NativeEndian::write_i32( &mut self.buffer.as_mut()[IGMPV2_UNSOLICITED_REPORT_INTERVAL], value, ) } pub fn set_igmpv3_unsolicited_report_interval(&mut self, value: i32) { NativeEndian::write_i32( &mut self.buffer.as_mut()[IGMPV3_UNSOLICITED_REPORT_INTERVAL], value, ) } pub fn set_ignore_routes_with_linkdown(&mut self, value: i32) { NativeEndian::write_i32( &mut self.buffer.as_mut()[IGNORE_ROUTES_WITH_LINKDOWN], value, ) } pub fn set_drop_unicast_in_l2_multicast(&mut self, value: i32) { NativeEndian::write_i32( &mut self.buffer.as_mut()[DROP_UNICAST_IN_L2_MULTICAST], value, ) } pub fn set_drop_gratuitous_arp(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[DROP_GRATUITOUS_ARP], value) } } impl<T: AsRef<[u8]>> Parseable<LinkInetDevConf> for LinkInetDevConfBuffer<T> { fn parse(&self) -> Result<LinkInetDevConf, DecodeError> { Ok(LinkInetDevConf { forwarding: self.forwarding(), mc_forwarding: self.mc_forwarding(), proxy_arp: self.proxy_arp(), accept_redirects: self.accept_redirects(), secure_redirects: self.secure_redirects(), send_redirects: self.send_redirects(), shared_media: self.shared_media(), rp_filter: self.rp_filter(), accept_source_route: self.accept_source_route(), bootp_relay: self.bootp_relay(), log_martians: self.log_martians(), tag: self.tag(), arpfilter: self.arpfilter(), medium_id: self.medium_id(), noxfrm: self.noxfrm(), nopolicy: self.nopolicy(), force_igmp_version: self.force_igmp_version(), arp_announce: self.arp_announce(), arp_ignore: self.arp_ignore(), promote_secondaries: self.promote_secondaries(), arp_accept: self.arp_accept(), arp_notify: self.arp_notify(), accept_local: self.accept_local(), src_vmark: self.src_vmark(), proxy_arp_pvlan: self.proxy_arp_pvlan(), route_localnet: self.route_localnet(), igmpv2_unsolicited_report_interval: self.igmpv2_unsolicited_report_interval(), igmpv3_unsolicited_report_interval: self.igmpv3_unsolicited_report_interval(), ignore_routes_with_linkdown: self.ignore_routes_with_linkdown(), drop_unicast_in_l2_multicast: self.drop_unicast_in_l2_multicast(), drop_gratuitous_arp: self.drop_gratuitous_arp(), }) } } impl Emitable for LinkInetDevConf { fn buffer_len(&self) -> usize { LINK_INET_DEV_CONF_LEN } fn emit(&self, buffer: &mut [u8]) { let mut buffer = LinkInetDevConfBuffer::new(buffer); buffer.set_forwarding(self.forwarding); buffer.set_mc_forwarding(self.mc_forwarding); buffer.set_proxy_arp(self.proxy_arp); buffer.set_accept_redirects(self.accept_redirects); buffer.set_secure_redirects(self.secure_redirects); buffer.set_send_redirects(self.send_redirects); buffer.set_shared_media(self.shared_media); buffer.set_rp_filter(self.rp_filter); buffer.set_accept_source_route(self.accept_source_route); buffer.set_bootp_relay(self.bootp_relay); buffer.set_log_martians(self.log_martians); buffer.set_tag(self.tag); buffer.set_arpfilter(self.arpfilter); buffer.set_medium_id(self.medium_id); buffer.set_noxfrm(self.noxfrm); buffer.set_nopolicy(self.nopolicy); buffer.set_force_igmp_version(self.force_igmp_version); buffer.set_arp_announce(self.arp_announce); buffer.set_arp_ignore(self.arp_ignore); buffer.set_promote_secondaries(self.promote_secondaries); buffer.set_arp_accept(self.arp_accept); buffer.set_arp_notify(self.arp_notify); buffer.set_accept_local(self.accept_local); buffer.set_src_vmark(self.src_vmark); buffer.set_proxy_arp_pvlan(self.proxy_arp_pvlan); buffer.set_route_localnet(self.route_localnet); buffer.set_igmpv2_unsolicited_report_interval(self.igmpv2_unsolicited_report_interval); buffer.set_igmpv3_unsolicited_report_interval(self.igmpv3_unsolicited_report_interval); buffer.set_ignore_routes_with_linkdown(self.ignore_routes_with_linkdown); buffer.set_drop_unicast_in_l2_multicast(self.drop_unicast_in_l2_multicast); buffer.set_drop_gratuitous_arp(self.drop_gratuitous_arp); } }
#![recursion_limit="1024"] // limit the recursion depth of the html! macro mod helper; mod clock; mod form; use wasm_bindgen::prelude::*; use yew::prelude::*; use yew::services::{Task, IntervalService, ConsoleService}; use helper::{hours, minutes, seconds}; use clock::Clock; use form::Form; use wasm_bindgen::__rt::core::time::Duration; /// This represents the upper layer of an interval timer. /// /// A interval timer (also known as ta-ba-ta timer) loops between `on` and `off` state until all /// cycles of a training are completed. struct Timer { link: ComponentLink<Self>, duration_on: u64, // duration of each cycle in seconds duration_off: u64, // duration of each pause in seconds cycles: u64, // total number of rounds start: u64, // seconds until the timer starts counter_s: u64, counter_c: u64, callback_tick: Callback<()>, // callback to be invoked on a `tick` callback_form: Callback<(u64, u64, u64)>, message: &'static str, state: State, // the current state of the timer saved_state: State, // Used to save the state if the timer is paused. job: Option<Box<dyn Task>>, // Currently active task } /// Messages the `Timer` can handle. /// /// # Messages /// /// * `StartTimer` - Starts the timer. /// * `StopTimer` - Stops the timer (state is preserved). /// * `ResetTimer` - Resets everything to the currently selected settings. /// * `SetTimer` - Set a new On and Off duration as well as a new number of cycles to complete. /// * `Tick` - Frequently called (each second) by an `IntervalService` if the timer is active (`On`, `Off`). enum Msg { StartTimer, StopTimer, ResetTimer, SetTimer(u64, u64, u64), Tick, } /// The different states of the `Timer`. /// /// The `Timer` starts in `Idle` state. If the user clicks the start button the `Timer` switches /// to the `Start` state and a countdown appears after which it transitions to the `On` state. /// The `Timer` toggles between `On` and `Off` until either all cycles are completed or the user /// presses the pause button. In `Pause` state the timer can either be resumed or reset. /// /// # States /// /// * `Start` - Start/ Resume the timer. /// * `On` - The state in which the user is demanded to work out. /// * `Off` - The state in which the user is granted some rest. /// * `Paused` - The timer is paused. /// * `Idle` - Do nothing. #[derive(Copy, Clone, PartialEq)] enum State { Start, On, Off, Paused, Idle, } impl Component for Timer { type Message = Msg; type Properties = (); // Root node so we have no properties /// Create a new `Timer` component. /// /// # Arguments /// /// * `_props` - Properties from the parent component (currently none - it's the root). /// * `link` - A link to register callbacks or send messages to the component. fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self { Self { callback_tick: link.callback(|_| Msg::Tick), // register new `Tick` callback. callback_form: link.callback(|tup: (u64, u64, u64)| Msg::SetTimer(tup.0, tup.1, tup.2)), link, duration_on: 20, duration_off: 10, cycles: 8, start: 5, counter_s: 20, counter_c: 0, message: "", state: State::Idle, saved_state: State::Idle, job: None, } } /// Handle incomming messages. /// /// The `update()` lifecycle method is called for each message. /// /// # Arguments /// /// * `msg` - The message to handle. fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { // Called when the timer is started or resumed. Msg::StartTimer => { // Create an new `IntervalService` instance that calls `Tick` every second. let handle = IntervalService::spawn(Duration::from_secs(1), self.callback_tick.clone()); self.job = Some(Box::new(handle)); match self.state { State::Idle => { // Start timer self.counter_s = self.duration_on; self.counter_c = 0; //self.message = "Timer started"; self.state = State::Start; }, _ => { // Resume timer //self.message = "Timer resumed"; self.state = self.saved_state; } } }, Msg::StopTimer => { // Pause the timer (state is preserved until it is started again or reset) //self.message = "Timer stoped"; self.saved_state = self.state; // Save current state self.state = State::Paused; // Switch timer into pause state self.job = None; // Remove the current interval service that calls tick }, Msg::ResetTimer => { // Reset the timer state self.counter_s = self.duration_on; self.counter_c = 0; self.start = 5; self.state = State::Idle; //self.message = "Reset"; self.job = None; }, Msg::SetTimer(on, off, rounds) => { self.duration_on = on; self.duration_off = off; self.cycles = rounds; self.link.callback(|_| Msg::ResetTimer).emit(()); }, Msg::Tick => { // Called every second to update the timer state match self.state { State::Start => { // The timer has just bee started and we're counting down. if self.start == 0 { // Countdown finished, switch to `On` state. self.start = 5; self.state = State::On; } else { self.start -= 1; } if self.start == 0 { // Play countdown sound. play_countdown("LongBeep"); } else if self.start <= 4 { // Play countdown sound. play_countdown("ShortBeep"); } }, _ => { if self.counter_s == 0 { // Counted down match self.state { State::On => self.counter_c += 1, // `On` - `Off` cycle completed. _ => {}, } if self.counter_c < self.cycles { // Not all cycles are completed. match self.state { State::On => { self.state = State::Off; self.counter_s = self.duration_off; }, State::Off => { self.state = State::On; self.counter_s = self.duration_on; }, _ => {}, // Should be impossible } } else { // All cycles completed, Nice Job ! self.state = State::Idle; //self.message = "Done, nice work!"; self.job = None; } } else { self.counter_s -= 1; // Decrement counter on every tick. } if self.counter_s == 0 { // Play countdown sound. play_countdown("LongBeep"); } else if self.counter_s <= 4 { // Play countdown sound. play_countdown("ShortBeep"); } } } }, } true } fn change(&mut self, _props: Self::Properties) -> ShouldRender { false } /// Create a (html) layout for the component. fn view(&self) -> Html { html! { <> <div class="cover-container d-flex w-100 h-100 p-3 mx-auto flex-column"> <header class="masthead mb-auto"> <div class="inner"> <h3 class="masthead-brand">{ "RustyTimer" }</h3> <nav class="nav nav-masthead justify-content-center"> <a class="nav-link" href="#" data-toggle="modal" data-target="#settingsModal">{ "Settings" }</a> <a class="nav-link" href="#" data-toggle="modal" data-target="#infoModal">{ "Info" }</a> </nav> </div> </header> <main role="main" class="inner cover"> <p class="lead">{ self.message }</p> <div class="clock-container"> <Clock progress={ self.counter_c as f64 / self.cycles as f64 } text={ if self.state == State::Start { format!("{}", self.start) } else { format!("{:02}:{:02}:{:02}", hours(self.counter_s), minutes(self.counter_s), seconds(self.counter_s)) }} darken={self.state == State::Off} color="#39c9bb" /> </div> { match self.state { State::Idle => html! { <button type="button" class="btn btn-outline-info btn-lg" onclick=self.link.callback(|_| Msg::StartTimer)>{ "Start" }</button> }, State::Paused => html! { <><button type="button" class="btn btn-outline-info btn-lg mr-3" onclick=self.link.callback(|_| Msg::StartTimer)>{ "Resume" }</button> <button type="button" class="btn btn-outline-warning btn-lg" onclick=self.link.callback(|_| Msg::ResetTimer)>{ "Reset" }</button></>}, State::Start => html! { }, _ => html! { <button type="button" class="btn btn-outline-secondary btn-lg" onclick=self.link.callback(|_| Msg::StopTimer)>{ "Stop" }</button> }, } } </main> <footer class="mastfoot mt-auto" style="padding-top: 18px;"> <div class="inner"> <div style="padding-top: 6px;">{"Copyright (c) 2020 David Sugar"}</div> </div> </footer> </div> <div class="modal fade" id="settingsModal" tabindex="-1" role="dialog" aria-labelledby="settingsModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header bg-info"> <h4 class="modal-title" id="settingsModalLabel">{ "Settings" }</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <i class="fa fa-times" aria-hidden="true" style="color: #fff;"></i> </button> </div> <div class="modal-body text-dark" id="settingsModalBody"> <Form callback={ self.callback_form.clone() } /> </div> </div> </div> </div> <div class="modal fade" id="infoModal" tabindex="-1" role="dialog" aria-labelledby="infoModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header bg-info"> <h4 class="modal-title">{ "Info" }</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <i class="fa fa-times" aria-hidden="true" style="color: #fff;"></i> </button> </div> <div class="modal-body text-dark" id="infoModalBody"> <p> {"I believe in free software that benefits people. I don't store any personal data \ nor do I wanna show you advertising. If you want to support me feel free and "} <a href="https://ko-fi.com/sug4r" target="_blank"> <img src="images/BuyMeACoffee.png" alt="Buy Me a Coffee!" style="width: 120px;" /> </a> {"."}<br/><br/>{"This site is licensed under "} <a href="https://github.com/r4gus/rustytimer/blob/main/LICENSE" style="color: black;" target="_blank"><strong>{"MIT "} </strong></a> {"and uses "}<a href="https://getbootstrap.com/" style="color: black;" target="_blank"><strong>{"Bootstrap "}</strong></a> {"and "}<a href="https://fontawesome.com/v4.7.0/" style="color: black;" target="_blank"><strong> {"FontAwesome "}</strong></a> {"for it's layout. \ It is written in "} <a href="https://www.rust-lang.org/" style="color: black;" target="_blank"><strong>{"Rust "}</strong></a> {"using the "} <a href="https://yew.rs/docs/en/" style="color: black;" target="_blank"><strong>{"Yew "}</strong></a> {"framework."}</p> </div> </div> </div> </div> </> } } } #[wasm_bindgen] extern "C" { fn play_countdown(aid: &str); } #[wasm_bindgen(start)] pub fn run_app() { App::<Timer>::new().mount_to_body(); }
extern crate opencv; use opencv::{calib3d::*, core::*, highgui::*, imgcodecs::*, prelude::*, types::*, videoio::*}; use std::{thread, time}; use crate::errors::Error; use crate::utils::*; const BOARD_VERTICES_W: u8 = 9; const BOARD_VERTICES_H: u8 = 5; const BOARD_SQUARE_LENGTH: f32 = 0.13; // in meters const REQUIRED_MARKERS: usize = 3; #[derive(Debug)] pub struct CalibrationData { pub camera_matrix: Mat, pub distortion_coeffs: Mat, } pub fn camera_calibrate(resolution: Size) -> Result<CalibrationData, Error> { let board = imread( "resources/calibration.png", IMREAD_UNCHANGED, )?; let mut cam = VideoCapture::new(0, CAP_V4L2)?; let opened = VideoCapture::is_opened(&cam)?; if !opened { panic!("Unable to open default camera"); } thread::sleep(time::Duration::from_millis(2)); // camera warm up let template_obj_points = calculate_obj_points(BOARD_SQUARE_LENGTH, BOARD_VERTICES_W, BOARD_VERTICES_H); let mut obj_points = Vec::<VectorOfPoint3f>::new(); let mut img_points = Vec::<VectorOfPoint2f>::new(); loop { let mut frame = Mat::default()?; cam.read(&mut frame)?; show_frame("calibration", &board)?; let mut corners = VectorOfPoint2f::new(); let ret = find_chessboard_corners_sb( &frame, Size::new(BOARD_VERTICES_W as i32, BOARD_VERTICES_H as i32), &mut corners, 0, )?; if ret { obj_points.push(VectorOfPoint3f::from_iter(template_obj_points.clone())); img_points.push(corners); } let key = wait_key(10)?; if key > 0 && key != 255 { break; } if img_points.len() >= REQUIRED_MARKERS { break; } } destroy_frame("calibration")?; let mut rvec = Mat::default()?; let mut tvec = Mat::default()?; let mut matrix = Mat::default()?; let mut dist_coeffs = Mat::default()?; calibrate_camera( &VectorOfVectorOfPoint3f::from_iter(obj_points), &VectorOfVectorOfPoint2f::from_iter(img_points), resolution, &mut matrix, &mut dist_coeffs, &mut rvec, &mut tvec, 0, TermCriteria::new( TermCriteria_Type::COUNT as i32 + TermCriteria_Type::EPS as i32, 30, std::f64::EPSILON, )?, )?; let c = CalibrationData { camera_matrix: matrix, distortion_coeffs: dist_coeffs, }; Ok(c) } fn calculate_obj_points(square_size: f32, width: u8, height: u8) -> Vec<Point3f> { let mut obj_points = Vec::with_capacity((width * height) as usize); for row in 0..height { for col in 0..width { obj_points.push(Point3f::new( square_size * col as f32, square_size * row as f32, 0., )); } } obj_points }
//! # Tendermock Builder API //! //! This modules holds the builder API, which can be use to create and start a mocked chain easily. //! //! It is the public API for interacting with Tendermock. use std::net::SocketAddr; use std::path::Path; use futures::future::try_join_all; use futures::try_join; use crate::config::Config; use crate::grpc; use crate::init; use crate::jrpc; use crate::logger::Log; use crate::node; use crate::store; /// Tendermock builder object. pub struct Tendermock { /// Interval between new blocks, in seconds. /// This parameter applies to all nodes in the Tendermock instance. growth_interval: u64, /// A list of interfaces for the chain, the first address for JsonRPC and the second for gRPC. interfaces: Vec<(SocketAddr, SocketAddr)>, /// The genesis block configuration. config: Config, } impl Tendermock { /// Return a new Tendermock object with default configuration: /// - Grow interval: 0 (no growth) /// - Interfaces: [] (no interfaces) /// - Config: default pub fn new() -> Self { Tendermock { growth_interval: 0, interfaces: vec![], config: Config::default(), } } /// Set the interval between two new blocks, in seconds. pub fn growth_rate(&mut self, interval: u64) -> &mut Self { self.growth_interval = interval; self } /// Add a new node interface (one JsonRPC and one gRPC address). pub fn register_node_interface(&mut self, jrpc: SocketAddr, grpc: SocketAddr) -> &mut Self { self.interfaces.push((jrpc, grpc)); self } /// Load the configuration of the genesis block. pub fn load_config<P: AsRef<Path>>(&mut self, path: P) -> &mut Self { self.config = Config::load(path); self } /// Start the Tendermock instance. /// /// This call is blocking, for running multiple nodes simultaneously threading can be used (a /// scheduler will run on each thread). pub fn start(&self) { // Initialize a node. let node = node::Node::new(&self.config); let mut node = node.shared(); init::init(&mut node, &self.config); // Build servers let mut jrpc_servers = Vec::new(); let mut grpc_servers = Vec::new(); if self.interfaces.is_empty() { log!(Log::Chain, "Warning: no interface configured"); } for (jrpc_addr, grpc_addr) in &self.interfaces { log!(Log::Grpc, "Listening on: {}", &grpc_addr); log!(Log::Jrpc, "Listening on: {}", &jrpc_addr); let jrpc_server = jrpc::serve(node.clone(), *jrpc_addr); let grpc_server = grpc::serve(node.clone(), *grpc_addr); jrpc_servers.push(jrpc_server); grpc_servers.push(grpc_server); } // Start servers tokio::runtime::Runtime::new() .unwrap() .block_on(async { try_join!( try_join_all(jrpc_servers), try_join_all(grpc_servers), schedule_growth(node, self.growth_interval) ) }) .unwrap(); } } impl Default for Tendermock { fn default() -> Self { Self::new() } } /// Push a new block on the chain every `interval` seconds. async fn schedule_growth<S: store::Storage>( node: node::SharedNode<S>, interval: u64, ) -> Result<(), std::convert::Infallible> { node.grow(); if interval == 0 { return Ok(()); } loop { tokio::time::sleep(std::time::Duration::from_secs(interval)).await; let node_ref = node.write(); node_ref.chain().grow(); drop(node_ref); } }
pub mod quadric;
extern crate gl; use std::error::Error; use std::option::NoneError; use std::fmt; use std; #[derive(Debug)] pub struct GlError(String); pub type Result<T> = std::result::Result<T, GlError>; pub fn validate_gl() -> Result<()> { if let Some(err) = get_error() { Err(GlError::new(err)) } else { Ok(()) } } fn get_error() -> Option<String> { let err = unsafe { gl::GetError() }; if err != gl::NO_ERROR { Some(err.to_string()) } else { None } } impl fmt::Display for GlError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &GlError(ref s) = self; write!(f, "{}", s) } } impl Error for GlError { fn description(&self) -> &str { let &GlError(ref s) = self; s.as_str() } } impl GlError { pub fn new(st : String) -> GlError { GlError(st) } } impl From<NoneError> for GlError { fn from(err : NoneError) -> GlError { GlError(format!("{:?}", err)) } } impl From<std::string::FromUtf8Error> for GlError { fn from(err : std::string::FromUtf8Error) -> GlError { GlError(err.description().to_string()) } } impl From<std::ffi::NulError> for GlError { fn from(err : std::ffi::NulError) -> GlError { GlError(err.description().to_string()) } }
#[doc = "Reader of register TX_EN_EXT_DELAY"] pub type R = crate::R<u32, super::TX_EN_EXT_DELAY>; #[doc = "Writer for register TX_EN_EXT_DELAY"] pub type W = crate::W<u32, super::TX_EN_EXT_DELAY>; #[doc = "Register TX_EN_EXT_DELAY `reset()`'s with value 0x1345"] impl crate::ResetValue for super::TX_EN_EXT_DELAY { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x1345 } } #[doc = "Reader of field `TXEN_EXT_DELAY`"] pub type TXEN_EXT_DELAY_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TXEN_EXT_DELAY`"] pub struct TXEN_EXT_DELAY_W<'a> { w: &'a mut W, } impl<'a> TXEN_EXT_DELAY_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `RXEN_EXT_DELAY`"] pub type RXEN_EXT_DELAY_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RXEN_EXT_DELAY`"] pub struct RXEN_EXT_DELAY_W<'a> { w: &'a mut W, } impl<'a> RXEN_EXT_DELAY_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4); self.w } } #[doc = "Reader of field `DEMOD_2M_COMP_DLY`"] pub type DEMOD_2M_COMP_DLY_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DEMOD_2M_COMP_DLY`"] pub struct DEMOD_2M_COMP_DLY_W<'a> { w: &'a mut W, } impl<'a> DEMOD_2M_COMP_DLY_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `MOD_2M_COMP_DLY`"] pub type MOD_2M_COMP_DLY_R = crate::R<u8, u8>; #[doc = "Write proxy for field `MOD_2M_COMP_DLY`"] pub struct MOD_2M_COMP_DLY_W<'a> { w: &'a mut W, } impl<'a> MOD_2M_COMP_DLY_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 12)) | (((value as u32) & 0x0f) << 12); self.w } } impl R { #[doc = "Bits 0:3 - Transmit enable extension delay. This is to extend the active state (high) of rif_tx_en signal after the last bit is sent out from LLH. The unit is in microsecond and the supported range is 00 - 31 us."] #[inline(always)] pub fn txen_ext_delay(&self) -> TXEN_EXT_DELAY_R { TXEN_EXT_DELAY_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - receiver enable extension delay. This is to extend the active state (high) of dbus_rx_en signal after the last bit is received from demod. The unit is in microsecond and the supported range is 00 - 31 us."] #[inline(always)] pub fn rxen_ext_delay(&self) -> RXEN_EXT_DELAY_R { RXEN_EXT_DELAY_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:11 - 2Mbps demod delay delta compare to 1Mbps demod delay. This data is 2's comp data."] #[inline(always)] pub fn demod_2m_comp_dly(&self) -> DEMOD_2M_COMP_DLY_R { DEMOD_2M_COMP_DLY_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 12:15 - 2Mbps modulation delay delta compare to 1Mbps demod delay. This data is 2's comp data."] #[inline(always)] pub fn mod_2m_comp_dly(&self) -> MOD_2M_COMP_DLY_R { MOD_2M_COMP_DLY_R::new(((self.bits >> 12) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - Transmit enable extension delay. This is to extend the active state (high) of rif_tx_en signal after the last bit is sent out from LLH. The unit is in microsecond and the supported range is 00 - 31 us."] #[inline(always)] pub fn txen_ext_delay(&mut self) -> TXEN_EXT_DELAY_W { TXEN_EXT_DELAY_W { w: self } } #[doc = "Bits 4:7 - receiver enable extension delay. This is to extend the active state (high) of dbus_rx_en signal after the last bit is received from demod. The unit is in microsecond and the supported range is 00 - 31 us."] #[inline(always)] pub fn rxen_ext_delay(&mut self) -> RXEN_EXT_DELAY_W { RXEN_EXT_DELAY_W { w: self } } #[doc = "Bits 8:11 - 2Mbps demod delay delta compare to 1Mbps demod delay. This data is 2's comp data."] #[inline(always)] pub fn demod_2m_comp_dly(&mut self) -> DEMOD_2M_COMP_DLY_W { DEMOD_2M_COMP_DLY_W { w: self } } #[doc = "Bits 12:15 - 2Mbps modulation delay delta compare to 1Mbps demod delay. This data is 2's comp data."] #[inline(always)] pub fn mod_2m_comp_dly(&mut self) -> MOD_2M_COMP_DLY_W { MOD_2M_COMP_DLY_W { w: self } } }
mod trig; #[cfg(test)] mod tests { use trig; #[test] fn test_sin() { assert!(trig::sin(0.0) == 0.0); } #[test] fn test_cos() { assert!(trig::cos(0.0) == 1.0); } #[test] fn test_tan() { assert!(trig::tan(0.0) == 0.0); } }
use crate::models::AccessionNumber; use crate::postgres::*; use crate::sec_entry::{FilingType, SECEntry}; use regex::Regex; use std::collections::HashSet; use xml::reader::{EventReader, XmlEvent}; use crate::errors::*; const NUM_ENTRY_ELEMENTS: usize = 4; pub fn read_rss(xml: &str, ignore: HashSet<FilingType>) -> Result<Vec<SECEntry>> { let parsed_xml = parse_xml(&xml); clean_xml(parsed_xml, ignore) //TODO replace } pub fn parse_xml(xml: &str) -> Vec<String> { let parser = EventReader::from_str(&xml); let mut entries: Vec<String> = Vec::new(); let mut entry_tag: bool = false; // Parse and aggregate information that occurs within an entry element for e in parser { match e { Ok(XmlEvent::StartElement { name, .. }) => { if name.local_name.contains("entry") { entry_tag = true; } } Ok(XmlEvent::Characters(c)) => { if entry_tag { entries.push(c); } } Ok(XmlEvent::EndElement { name }) => { if name.local_name.contains("entry") { entry_tag = false; } } _ => (), } } entries } pub fn clean_xml(xml: Vec<String>, ignore: HashSet<FilingType>) -> Result<Vec<SECEntry>> { //! This function will clean up the XML given to it, and create a vector of //! entries that describe the SEC Filings // Assumption: The form of the `Entry` XMLElement to be parsed will be as follows // A title, which has the Type of Filing, Conformed Company Name, Central Index Key (CIK) // A filing information index, which has the Accession Number, and Data of Filing // A timestamp // A Tag that is ignored let mut entries: Vec<SECEntry> = Vec::new(); assert!(xml.len() % NUM_ENTRY_ELEMENTS == 0); // Routine for every 4 entries let mut element_it = xml.iter(); for _ in xml.iter().step_by(NUM_ENTRY_ELEMENTS) { let (filing_type, conformed_name, cik) = clean_title(element_it.next()).expect("Unable to get title element"); let filing_enum = FilingType::which(filing_type).chain_err(|| "Unknown filing type given")?; /* Ignore if of certain filing type(s)*/ if ignore.contains(&filing_enum) { ignore_filing(&mut element_it); } else { let (date, acc_number) = clean_filing(element_it.next()).chain_err(|| "Unable to get filing element")?; /* CIKs are not unique, i.e. a company/individual will have the same*/ /* CIK each time it files with the SEC */ let timestamp = clean_timestamp(element_it.next()) .chain_err(|| "Unable to get timestamp element")?; element_it.next(); let entry = SECEntry::new( filing_enum, conformed_name.to_owned(), cik, acc_number, date, timestamp.to_owned(), ); if !has_accession_number(acc_number).is_some() { write_accession_number(acc_number); entries.push(entry); } } } Ok(entries) } /// This function will check to see if an accesion number is not unique, and thus /// must be ignore. The Programmer regrets this function, and will replace it with /// database query /// ^ /// It's replaced :) fn has_accession_number(acc_number: usize) -> Option<Vec<AccessionNumber>> { let conn = establish_connection(""); get_number(&conn, acc_number).and_then(|c| if c.len() == 0 { None } else { Some(c) }) } fn write_accession_number(acc_number: usize) { // -> Result<(i32, String)> { let conn = establish_connection(""); write_number(&conn, acc_number).chain_err(|| "Unable to write accession Number"); } fn delete_accession_number(acc_number: usize) -> Result<usize> { let conn = establish_connection(""); delete_number(&conn, acc_number).chain_err(|| "Unable to delete accession Number") } /// This function cleans the string received in the filing information from the xml /// <b>Filed:</b> 2018-06-29 <b>AccNo:</b> 0001140361-18-030802 <b>Size:</b> 25 KB /// Fields of interest here are the date, and accession number, both of which are between <\b> /// <b> tags /// Dates & Accession Numbers will be kept in usize format, so that we don't need any string /// overhead. /// /// Since we the data we want will have - in it with numbers on either side, we can use a regex/// to rip things out. /// ``` /// // use super::*; /// // I think doc tests are broken? /// //assert_eq!(Ok((20180629,114036118030802)),clean_filing(Some(&"<b>Filed:</b> 2018-06-29 <b>AccNo:</b> 0001140361-18-030802 <b>Size:</b> 25 KB".to_string()))); /// /// ``` pub fn clean_filing(input: Option<&String>) -> Result<(usize, usize)> { match input { Some(f) => { let re = Regex::new(r"(\d*-\d*-\d*)").unwrap(); let mut matches = re .captures_iter(&f) .map(|a| a[1].to_owned()) .collect::<Vec<String>>(); // In place manipulation, for_each is eager as opposed to map() matches .iter_mut() .for_each(|y: &mut String| y.retain(|x| x != '-')); Ok(( matches[0] .parse::<usize>() .expect("Could not convert to usize"), matches[1] .parse::<usize>() .expect("Could not convert to usize"), )) } _ => bail!("Filing title unclean"), } } pub fn clean_timestamp(input: Option<&String>) -> Result<(&String)> { match input { Some(x) => Ok(&x), None => Err("Unable to clean timestamp")?, } } /// pub fn clean_title<'a>(input: Option<&'a String>) -> Result<(&'a str, &'a str, usize)> { //! TODO: Make Errors that are helpful match input { Some(t) => { /* Get the form name, it may contain a -, which is why we take this approach */ let split_names = t.split(" - ").collect::<Vec<&str>>(); /* Get the conformed name, and accession number. The accession number is between two parens */ let re = Regex::new(r"\((\d+)\)").unwrap(); let cik = &re.captures_iter(&t).next().unwrap()[1]; let name: Vec<&'a str> = (&split_names[1]).split('(').map(&str::trim).collect(); Ok(( split_names[0], name[0], cik.parse::<usize>() .chain_err(|| "Could not convert to usize")?, )) } None => Err("No xml title found")?, } } #[inline] pub fn ignore_filing<T: Iterator>(iter: &mut T) { iter.next(); iter.next(); iter.next(); } #[cfg(test)] mod rss_tests { use super::*; use bigdecimal::BigDecimal; #[test] fn clean_title_test_s1a() { assert_eq!( clean_title(Some( &"S-1/A - Tipmefast, Inc. (0001726079) (Filer)".to_owned() )) .unwrap(), ("S-1/A", "Tipmefast, Inc.", 1726079) ); } #[test] fn clean_title_test_standard() { assert_eq!( clean_title(Some(&"4 - Wang Janet (0001655081) (Reporting)".to_owned())).unwrap(), ("4", "Wang Janet", 1655081) ); } #[test] fn clean_filing_test() { assert_eq!( (20180629, 114036118030802), clean_filing(Some( &"<b>Filed:</b> 2018-06-29 <b>AccNo:</b> 0001140361-18-030802 <b>Size:</b> 25 KB" .to_string() )) .expect("") ); } #[test] fn clean_xml_ignore0() { let test = vec![ "4/A - Wilson Andrew (0001545193) (Reporting)", "\n <b>Filed:</b> 2018-07-05 <b>AccNo:</b> 0001454387-18-000188 <b>Size:</b> 5 KB\n", "2018-07-05T20:51:01-04:00", "urn:tag:sec.gov,2008:accession-number=0001454387-18-000188"]; let vec = test.into_iter().map(String::from).collect::<Vec<String>>(); let mut ignore_set = HashSet::new(); ignore_set.insert(FilingType::Sec4A); assert_eq!(Vec::<SECEntry>::new(), clean_xml(vec, ignore_set).unwrap()); } #[test] fn clean_xml_ignore1() { let _entry = SECEntry::new( FilingType::Sec4A, String::from("Wilson Andrew"), 1545193, 145438718000188, 20180705, String::from("2018-07-05T20:51:01-04:00"), ); // Previous Test will write number back to database delete_accession_number(145438718000188); let test = vec![ "4/A - Wilson Andrew (0001545193) (Reporting)", "\n <b>Filed:</b> 2018-07-05 <b>AccNo:</b> 0001454387-18-000188 <b>Size:</b> 5 KB\n", "2018-07-05T20:51:01-04:00", "urn:tag:sec.gov,2008:accession-number=0001454387-18-000188", "4 - Wilson Andrew (0001545193) (Reporting)", "\n <b>Filed:</b> 2018-07-05 <b>AccNo:</b> 0001454387-18-000188 <b>Size:</b> 5 KB\n", "2018-07-05T20:51:01-04:00", "urn:tag:sec.gov,2008:accession-number=0001454387-18-000188", ]; let vec = test.into_iter().map(String::from).collect::<Vec<String>>(); let mut ignore_set = HashSet::new(); ignore_set.insert(FilingType::Sec4A); let entry = SECEntry::new( FilingType::Sec4, String::from("Wilson Andrew"), 1545193, 145438718000188, 20180705, String::from("2018-07-05T20:51:01-04:00"), ); assert_eq!(Some(entry), clean_xml(vec, ignore_set).unwrap().pop()); } #[test] fn clean_xml_test() { let test = vec![ "4/A - Wilson Andrew (0001545193) (Reporting)", "\n <b>Filed:</b> 2018-07-05 <b>AccNo:</b> 0001454387-18-000188 <b>Size:</b> 5 KB\n", "2018-07-05T20:51:01-04:00", "urn:tag:sec.gov,2008:accession-number=0001454387-18-000188"]; delete_accession_number(145438718000188); let vec = test.into_iter().map(str::to_owned).collect::<Vec<String>>(); let entry = SECEntry::new( FilingType::Sec4A, String::from("Wilson Andrew"), 1545193, 145438718000188, 20180705, String::from("2018-07-05T20:51:01-04:00"), ); assert_eq!(Some(entry), clean_xml(vec, HashSet::new()).unwrap().pop()); } #[test] fn clean_xml_mega_test() { let test = vec![ "4 - REDIKER DENNIS L (0001189878) (Reporting)", "\n <b>Filed:</b> 2018-09-05 <b>AccNo:</b> 0001127602-18-026760 <b>Size:</b> 4 KB\n", "2018-09-05T12:36:45-04:00", "urn:tag:sec.gov,2008:accession-number=0001127602-18-026759", "4 - MARTIN MARIETTA MATERIALS INC (0000916076) (Issuer)", "\n <b>Filed:</b> 2018-09-05 <b>AccNo:</b> 0001127602-18-026759 <b>Size:</b> 4 KB\n", "2018-09-05T12:36:45-04:00", "urn:tag:sec.gov,2008:accession-number=0001127602-18-026759", "FWP - WELLS FARGO & COMPANY/MN (0000072971) (Subject)", "\n <b>Filed:</b> 2018-09-05 <b>AccNo:</b> 0001387131-18-004493 <b>Size:</b> 108 KB\n", "2018-09-05T12:36:29-04:00", "urn:tag:sec.gov,2008:accession-number=0001387131-18-004493", ] .into_iter() .map(String::from) .collect::<Vec<String>>(); // Previous Test will write number back to database delete_accession_number(138713118004493); delete_accession_number(112760218026759); delete_accession_number(112760218026760); if let Ok(x) = clean_xml(test, HashSet::new()) { println!("{:#?}", &x); assert_eq!(x.len(), 3); } else { assert!(false); } } #[test] fn clean_xml_mega_mega_test() { let test = vec![ "497 - JACKSON NATIONAL SEPARATE ACCOUNT - I (0000927730) (Filer)", "\n <b>Filed:</b> 2018-09-05 <b>AccNo:</b> 0000927730-18-000500 <b>Size:</b> 69 KB\n", "2018-09-05T13:06:11-04:00", "urn:tag:sec.gov,2008:accession-number=0000927730-18-000500", ] .into_iter() .map(String::from) .collect::<Vec<String>>(); delete_accession_number(92773018000500); let entry = SECEntry::new( FilingType::Sec497, String::from("JACKSON NATIONAL SEPARATE ACCOUNT"), 927730, 92773018000500, 20180905, String::from("2018-09-05T13:06:11-04:00"), ); if let Ok(mut x) = clean_xml(test, HashSet::new()) { assert_eq!(x.pop().unwrap(), entry); } else { assert!(false); } } #[test] fn accession_number_test() { let x = 1337; let val = BigDecimal::from(1337); delete_accession_number(x).expect("Better Not Fail"); assert_eq!(has_accession_number(x), None); write_accession_number(x); assert_eq!( has_accession_number(x) .unwrap() .pop() .unwrap() .accession_number, val ); assert!(delete_accession_number(x).is_ok()); } }
use ferris_base; mod utils; #[test] // Baba is you: Space 6 fn blocked_by_stop() { let start = vec![ "......🦀..🦀..", "......🧱🧱🧱..", "Wa==St........", "Fe==Fa&&U ....", ]; let inputs = vec![ferris_base::core::direction::Direction::RIGHT]; let end = vec![ "........🦀....", "......🧱🧱🧱..", "Wa==St........", "Fe==Fa&&U ..🦀", ]; utils::assert_evolution(start, inputs, end); } #[test] fn blocked_by_push() { let start = vec![ "......🦀..🦀..", "......🚩🚩🚩..", "Fg==St........", "Fe==Fa&&U ....", ]; let inputs = vec![ferris_base::core::direction::Direction::RIGHT]; let end = vec![ "........🦀....", "......🚩🚩🚩..", "Fg==St........", "Fe==Fa&&U ..🦀", ]; utils::assert_evolution(start, inputs, end); } #[test] // Baba is you: Cavern 3 fn can_pull_upwards() { let start = vec![ "............", "..........🦀", "Fg==Pl....🚩", "Fe==Fa&&U ..", ]; let inputs = vec![ferris_base::core::direction::Direction::UP]; let end = vec![ "..........🦀", "..........🚩", "Fg==Pl......", "Fe==Fa&&U ..", ]; utils::assert_evolution(start, inputs, end); } #[test] // Baba is you: Space 10 fn through_defeat() { let start = vec![ "🦀💀....🦀..", "Sk==Df..🧱💀", "Wa==St......", "Fe==Fa&&U ..", ]; let inputs = vec![ ferris_base::core::direction::Direction::RIGHT, ferris_base::core::direction::Direction::RIGHT, ]; let end = vec![ "..💀........", "Sk==Df..🧱💀", "Wa==St......", "Fe==Fa&&U 🦀", ]; utils::assert_evolution(start, inputs, end); } #[test] // Baba is you: Cavern 3 // TODO understand how this works fn move_then_fall() {} #[test] // Baba is you: Space 10 fn push_then_fall() { let start = vec![ "............", "............", "Fg==Pu....🚩", "Fe==Fa&&U 🦀", ]; let inputs = vec![ferris_base::core::direction::Direction::UP]; let end = vec![ "............", "..........🚩", "Fg==Pu......", "Fe==Fa&&U 🦀", ]; utils::assert_evolution(start, inputs, end); } #[test] // Baba is you: Space 11 fn independent_of_float() { let start = vec![ "............", "..........🦀", "Wa==St....🧱", "Fe==Fa&&Fl..", ]; let inputs = vec![None]; let end = vec![ "............", "..........🦀", "Wa==St....🧱", "Fe==Fa&&Fl..", ]; utils::assert_evolution_with_pauses(start, inputs, end); } #[test] fn keeps_orientation() { let start = vec![ "..🦀..........", "..🧱🧱🧱......", "Wa==St........", "Fe==U ........", "Fe==Fa&&Mv....", ]; let inputs = vec![ Some(ferris_base::core::direction::Direction::RIGHT), None, None, ]; let end = vec![ "..............", "..🧱🧱🧱......", "Wa==St........", "Fe==U ........", "Fe==Fa&&Mv🦀..", ]; utils::assert_evolution_with_pauses(start, inputs, end); }
use crate::{callbacks, types::{self, adapter}, utils}; use super::auto::{HasInner, Abstract}; use super::container::{Container, ContainerInner, AContainer}; use super::control::{Control, AControl, ControlBase, ControlInner}; use super::member::{Member, AMember, MemberBase}; define_abstract! { Adapted: Control + Container { base: { pub adapter: Box<dyn types::Adapter>, } outer: { fn adapter(&self) -> &dyn types::Adapter; fn adapter_mut(&mut self) -> &mut dyn types::Adapter; fn len_at(&self, indexes: &[usize]) -> Option<usize> { self.adapter().len_at(indexes) } } inner: { fn on_item_change<'a>(&mut self, base: &mut MemberBase, value: adapter::Change<'a>); } } } impl<T: AdaptedInner + 'static> AAdapted<T> { #[inline] pub fn with_inner<O: Adapted>(inner: T, adapter: Box<dyn types::Adapter>, u: &mut ::std::mem::MaybeUninit<O>) -> Self { let mut t = Self { base: AdaptedBase { adapter }, inner }; let base = u as *mut _ as *mut MemberBase; t.base.adapter.on_item_change(Some(AdapterInnerCallback { target: base, on_item_change: Self::on_item_change.into(), })); t } #[inline] fn on_item_change(base: &mut MemberBase, value: adapter::Change) { let this = base.as_any_mut().downcast_mut::<AMember<AControl<AContainer<AAdapted<T>>>>>().unwrap(); let this2 = this as *mut AMember<AControl<AContainer<AAdapted<T>>>>; // bck is stupid; let inner = unsafe {&mut *this2}.inner_mut().inner_mut().inner_mut().inner_mut(); inner.on_item_change(base, value) } } impl<T: AdaptedInner + ControlInner + 'static> AMember<AControl<AContainer<AAdapted<T>>>> { #[inline] pub fn as_adapted_parts_mut(&mut self) -> (&mut MemberBase, &mut ControlBase, &mut AdaptedBase, &mut T) { let this = self as *mut Self; (&mut unsafe { &mut *this }.base, &mut unsafe { &mut *this }.inner.base, &mut unsafe { &mut *this }.inner.inner.inner.base, &mut unsafe { &mut *this }.inner.inner.inner.inner) } #[inline] pub unsafe fn adapter_base_parts_mut(base: &mut MemberBase) -> (&mut MemberBase, &mut ControlBase, &mut AdaptedBase, &mut T) { utils::base_to_impl_mut::<Self>(base).as_adapted_parts_mut() } } pub struct AdapterInnerCallback { target: *mut MemberBase, on_item_change: callbacks::OnItemChange, } impl AdapterInnerCallback { pub fn on_item_change(&mut self, value: adapter::Change) { if !self.target.is_null() { (self.on_item_change.as_mut())(unsafe {&mut *self.target}, value) } } } impl<T: AdaptedInner> Adapted for AMember<AControl<AContainer<AAdapted<T>>>> { #[inline] default fn adapter(&self) -> &dyn types::Adapter { self.inner.inner.inner.base.adapter.as_ref() } #[inline] default fn adapter_mut(&mut self) -> &mut dyn types::Adapter { self.inner.inner.inner.base.adapter.as_mut() } #[inline] default fn as_adapted(&self) -> &dyn Adapted { self } #[inline] default fn as_adapted_mut(&mut self) -> &mut dyn Adapted { self } #[inline] default fn into_adapted(self: Box<Self>) -> Box<dyn Adapted> { self } } impl<II: AdaptedInner, T: HasInner<I = II> + Abstract + 'static> AdaptedInner for T { #[inline] fn on_item_change(&mut self, base: &mut MemberBase, value: adapter::Change) { self.inner_mut().on_item_change(base, value) } }
use std::path::Path; use tera::Tera; use crate::Site; use config::Config; use errors::{bail, Error, Result}; use templates::{filters, global_fns, PEPEL_TERA}; use utils::templates::rewrite_theme_paths; pub fn load_tera(path: &Path, config: &Config) -> Result<Tera> { let tpl_glob = format!("{}/{}", path.to_string_lossy().replace("\\", "/"), "templates/**/*.{*ml,md}"); // Only parsing as we might be extending templates from themes and that would error // as we haven't loaded them yet let mut tera = Tera::parse(&tpl_glob).map_err(|e| Error::chain("Error parsing templates", e))?; if let Some(ref theme) = config.theme { // Test that the templates folder exist for that theme let theme_path = path.join("themes").join(&theme); if !theme_path.join("templates").exists() { bail!("Theme `{}` is missing a templates folder", theme); } let theme_tpl_glob = format!( "{}/{}", path.to_string_lossy().replace("\\", "/"), format!("themes/{}/templates/**/*.{{*ml,md}}", theme) ); let mut tera_theme = Tera::parse(&theme_tpl_glob) .map_err(|e| Error::chain("Error parsing templates from themes", e))?; rewrite_theme_paths(&mut tera_theme, &theme); if theme_path.join("templates").join("robots.txt").exists() { tera_theme.add_template_file(theme_path.join("templates").join("robots.txt"), None)?; } tera.extend(&tera_theme)?; } tera.extend(&PEPEL_TERA)?; tera.build_inheritance_chains()?; if path.join("templates").join("robots.txt").exists() { tera.add_template_file(path.join("templates").join("robots.txt"), Some("robots.txt"))?; } Ok(tera) } /// Adds global fns that are to be available to shortcodes while rendering markdown pub fn register_early_global_fns(site: &mut Site) { site.tera.register_filter("markdown", filters::MarkdownFilter::new(site.config.clone())); site.tera.register_function( "get_url", global_fns::GetUrl::new( site.config.clone(), site.permalinks.clone(), vec![site.static_path.clone(), site.output_path.clone(), site.content_path.clone()], ), ); site.tera .register_function("resize_image", global_fns::ResizeImage::new(site.imageproc.clone())); site.tera.register_function( "get_image_metadata", global_fns::GetImageMeta::new(site.content_path.clone()), ); site.tera.register_function("load_data", global_fns::LoadData::new(site.base_path.clone())); site.tera.register_function("trans", global_fns::Trans::new(site.config.clone())); site.tera.register_function( "get_taxonomy_url", global_fns::GetTaxonomyUrl::new( &site.config.default_language, &site.taxonomies, site.config.slugify.taxonomies, ), ); site.tera.register_function( "get_file_hash", global_fns::GetFileHash::new(vec![ site.static_path.clone(), site.output_path.clone(), site.content_path.clone(), ]), ); } /// Functions filled once we have parsed all the pages/sections only, so not available in shortcodes pub fn register_tera_global_fns(site: &mut Site) { site.tera.register_function( "get_page", global_fns::GetPage::new(site.base_path.clone(), site.library.clone()), ); site.tera.register_function( "get_section", global_fns::GetSection::new(site.base_path.clone(), site.library.clone()), ); site.tera.register_function( "get_taxonomy", global_fns::GetTaxonomy::new( &site.config.default_language, site.taxonomies.clone(), site.library.clone(), ), ); }
use nix::unistd::{getegid, geteuid, getgid, getuid, setegid, seteuid, Gid, Uid}; use std::error::Error; #[derive(Debug, Clone)] pub struct ExecutionContext { pub is_suid: bool, pub is_sgid: bool, pub uid: Uid, pub euid: Uid, pub gid: Gid, pub egid: Gid, } impl Default for ExecutionContext { fn default() -> Self { Self::new() } } impl ExecutionContext { pub fn new() -> Self { Self { is_suid: getuid() != geteuid(), is_sgid: getgid() != getegid(), uid: getuid(), euid: geteuid(), gid: getgid(), egid: getegid(), } } pub fn drop_privileges(&self) -> Result<(), nix::Error> { debug!("Dropping privileges -> {}/{}", self.uid, self.gid); if self.is_suid { seteuid(self.uid)?; } if self.is_sgid { setegid(self.gid)?; } Ok(()) } pub fn regain_privileges(&self) -> Result<(), nix::Error> { debug!("Regaining privileges -> {}/{}", self.euid, self.egid); if self.is_suid { seteuid(self.euid)?; } if self.is_sgid { setegid(self.egid)?; } Ok(()) } /// Convenience helper which brackets a closure with drop/regain privileges pub fn with_dropped_privileges<T, E, F>(&self, unprivileged: F) -> Result<T, E> where E: Error + From<nix::Error>, F: FnOnce() -> Result<T, E>, { self.drop_privileges()?; let res = unprivileged(); self.regain_privileges()?; res } }
use pretty_assertions::assert_eq; use super::*; use crate::ast::tests::Locator; #[test] fn regex_literal() { let mut p = Parser::new(r#"/.*/"#); let parsed = p.parse_file("".to_string()); let loc = Locator::new(&p.source[..]); assert_eq!( parsed, File { base: BaseNode { location: loc.get(1, 1, 1, 5), ..BaseNode::default() }, name: "".to_string(), metadata: "parser-type=rust".to_string(), package: None, imports: vec![], body: vec![Statement::Expr(Box::new(ExprStmt { base: BaseNode { location: loc.get(1, 1, 1, 5), ..BaseNode::default() }, expression: Expression::Regexp(RegexpLit { base: BaseNode { location: loc.get(1, 1, 1, 5), ..BaseNode::default() }, value: ".*".to_string() }) }))], eof: vec![], }, ) } #[test] fn regex_literal_with_escape_sequence() { let mut p = Parser::new(r#"/a\/b\\c\d/"#); let parsed = p.parse_file("".to_string()); let loc = Locator::new(&p.source[..]); assert_eq!( parsed, File { base: BaseNode { location: loc.get(1, 1, 1, 12), ..BaseNode::default() }, name: "".to_string(), metadata: "parser-type=rust".to_string(), package: None, imports: vec![], body: vec![Statement::Expr(Box::new(ExprStmt { base: BaseNode { location: loc.get(1, 1, 1, 12), ..BaseNode::default() }, expression: Expression::Regexp(RegexpLit { base: BaseNode { location: loc.get(1, 1, 1, 12), ..BaseNode::default() }, value: "a/b\\\\c\\d".to_string() }) }))], eof: vec![], }, ) } #[test] fn bad_regex_literal() { let mut p = Parser::new(r#"/*/"#); let parsed = p.parse_file("".to_string()); let loc = Locator::new(&p.source[..]); assert_eq!( parsed, File { base: BaseNode { location: loc.get(1, 1, 1, 4), ..BaseNode::default() }, name: "".to_string(), metadata: "parser-type=rust".to_string(), package: None, imports: vec![], body: vec![Statement::Expr(Box::new(ExprStmt { base: BaseNode { location: loc.get(1, 1, 1, 4), ..BaseNode::default() }, expression: Expression::Regexp(RegexpLit { base: BaseNode { location: loc.get(1, 1, 1, 4), errors: vec![ "regex parse error: * error: repetition operator missing expression" .to_string() ], ..BaseNode::default() }, value: "".to_string() }) }))], eof: vec![], }, ) } #[test] fn duration_literal_all_units() { let mut p = Parser::new(r#"dur = 1y3mo2w1d4h1m30s1ms2µs70ns"#); let parsed = p.parse_file("".to_string()); let loc = Locator::new(&p.source[..]); assert_eq!( parsed, File { base: BaseNode { location: loc.get(1, 1, 1, 34), ..BaseNode::default() }, name: "".to_string(), metadata: "parser-type=rust".to_string(), package: None, imports: vec![], body: vec![Statement::Variable(Box::new(VariableAssgn { base: BaseNode { location: loc.get(1, 1, 1, 34), ..BaseNode::default() }, id: Identifier { base: BaseNode { location: loc.get(1, 1, 1, 4), ..BaseNode::default() }, name: "dur".to_string() }, init: Expression::Duration(DurationLit { base: BaseNode { location: loc.get(1, 7, 1, 34), ..BaseNode::default() }, values: vec![ Duration { magnitude: 1, unit: "y".to_string() }, Duration { magnitude: 3, unit: "mo".to_string() }, Duration { magnitude: 2, unit: "w".to_string() }, Duration { magnitude: 1, unit: "d".to_string() }, Duration { magnitude: 4, unit: "h".to_string() }, Duration { magnitude: 1, unit: "m".to_string() }, Duration { magnitude: 30, unit: "s".to_string() }, Duration { magnitude: 1, unit: "ms".to_string() }, Duration { magnitude: 2, unit: "us".to_string() }, Duration { magnitude: 70, unit: "ns".to_string() } ] }) }))], eof: vec![], }, ) } #[test] fn duration_literal_leading_zero() { let mut p = Parser::new(r#"dur = 01y02mo03w04d05h06m07s08ms09µs010ns"#); let parsed = p.parse_file("".to_string()); let loc = Locator::new(&p.source[..]); assert_eq!( parsed, File { base: BaseNode { location: loc.get(1, 1, 1, 43), ..BaseNode::default() }, name: "".to_string(), metadata: "parser-type=rust".to_string(), package: None, imports: vec![], body: vec![Statement::Variable(Box::new(VariableAssgn { base: BaseNode { location: loc.get(1, 1, 1, 43), ..BaseNode::default() }, id: Identifier { base: BaseNode { location: loc.get(1, 1, 1, 4), ..BaseNode::default() }, name: "dur".to_string() }, init: Expression::Duration(DurationLit { base: BaseNode { location: loc.get(1, 7, 1, 43), ..BaseNode::default() }, values: vec![ Duration { magnitude: 1, unit: "y".to_string() }, Duration { magnitude: 2, unit: "mo".to_string() }, Duration { magnitude: 3, unit: "w".to_string() }, Duration { magnitude: 4, unit: "d".to_string() }, Duration { magnitude: 5, unit: "h".to_string() }, Duration { magnitude: 6, unit: "m".to_string() }, Duration { magnitude: 7, unit: "s".to_string() }, Duration { magnitude: 8, unit: "ms".to_string() }, Duration { magnitude: 9, unit: "us".to_string() }, Duration { magnitude: 10, unit: "ns".to_string() } ] }) }))], eof: vec![], }, ) } #[test] fn duration_literal_months() { let mut p = Parser::new(r#"dur = 6mo"#); let parsed = p.parse_file("".to_string()); let loc = Locator::new(&p.source[..]); assert_eq!( parsed, File { base: BaseNode { location: loc.get(1, 1, 1, 10), ..BaseNode::default() }, name: "".to_string(), metadata: "parser-type=rust".to_string(), package: None, imports: vec![], body: vec![Statement::Variable(Box::new(VariableAssgn { base: BaseNode { location: loc.get(1, 1, 1, 10), ..BaseNode::default() }, id: Identifier { base: BaseNode { location: loc.get(1, 1, 1, 4), ..BaseNode::default() }, name: "dur".to_string() }, init: Expression::Duration(DurationLit { base: BaseNode { location: loc.get(1, 7, 1, 10), ..BaseNode::default() }, values: vec![Duration { magnitude: 6, unit: "mo".to_string() }] }) }))], eof: vec![], }, ) } #[test] fn duration_literal_milliseconds() { let mut p = Parser::new(r#"dur = 500ms"#); let parsed = p.parse_file("".to_string()); let loc = Locator::new(&p.source[..]); assert_eq!( parsed, File { base: BaseNode { location: loc.get(1, 1, 1, 12), ..BaseNode::default() }, name: "".to_string(), metadata: "parser-type=rust".to_string(), package: None, imports: vec![], body: vec![Statement::Variable(Box::new(VariableAssgn { base: BaseNode { location: loc.get(1, 1, 1, 12), ..BaseNode::default() }, id: Identifier { base: BaseNode { location: loc.get(1, 1, 1, 4), ..BaseNode::default() }, name: "dur".to_string() }, init: Expression::Duration(DurationLit { base: BaseNode { location: loc.get(1, 7, 1, 12), ..BaseNode::default() }, values: vec![Duration { magnitude: 500, unit: "ms".to_string() }] }) }))], eof: vec![], }, ) } #[test] fn duration_literal_months_minutes_milliseconds() { let mut p = Parser::new(r#"dur = 6mo30m500ms"#); let parsed = p.parse_file("".to_string()); let loc = Locator::new(&p.source[..]); assert_eq!( parsed, File { base: BaseNode { location: loc.get(1, 1, 1, 18), ..BaseNode::default() }, name: "".to_string(), metadata: "parser-type=rust".to_string(), package: None, imports: vec![], body: vec![Statement::Variable(Box::new(VariableAssgn { base: BaseNode { location: loc.get(1, 1, 1, 18), ..BaseNode::default() }, id: Identifier { base: BaseNode { location: loc.get(1, 1, 1, 4), ..BaseNode::default() }, name: "dur".to_string() }, init: Expression::Duration(DurationLit { base: BaseNode { location: loc.get(1, 7, 1, 18), ..BaseNode::default() }, values: vec![ Duration { magnitude: 6, unit: "mo".to_string() }, Duration { magnitude: 30, unit: "m".to_string() }, Duration { magnitude: 500, unit: "ms".to_string() } ] }) }))], eof: vec![], }, ) } #[test] fn date_literal_in_the_default_location() { let mut p = Parser::new(r#"now = 2018-11-29"#); let parsed = p.parse_file("".to_string()); let loc = Locator::new(&p.source[..]); assert_eq!( parsed, File { base: BaseNode { location: loc.get(1, 1, 1, 17), ..BaseNode::default() }, name: "".to_string(), metadata: "parser-type=rust".to_string(), package: None, imports: vec![], body: vec![Statement::Variable(Box::new(VariableAssgn { base: BaseNode { location: loc.get(1, 1, 1, 17), ..BaseNode::default() }, id: Identifier { base: BaseNode { location: loc.get(1, 1, 1, 4), ..BaseNode::default() }, name: "now".to_string() }, init: Expression::DateTime(DateTimeLit { base: BaseNode { location: loc.get(1, 7, 1, 17), ..BaseNode::default() }, value: chrono::DateTime::parse_from_rfc3339("2018-11-29T00:00:00Z").unwrap() }) }))], eof: vec![], }, ) } #[test] fn data_time_literal_arg() { let mut p = Parser::new(r#"range(start: 2018-11-29T09:00:00)"#); let parsed = p.parse_file("".to_string()); let loc = Locator::new(&p.source[..]); assert_eq!( parsed, File { base: BaseNode { location: loc.get(1, 1, 1, 34), ..BaseNode::default() }, name: "".to_string(), metadata: "parser-type=rust".to_string(), package: None, imports: vec![], body: vec![Statement::Expr(Box::new(ExprStmt { base: BaseNode { location: loc.get(1, 1, 1, 34), ..BaseNode::default() }, expression: Expression::Call(Box::new(CallExpr { base: BaseNode { location: loc.get(1, 1, 1, 34), errors: vec!["expected RPAREN, got EOF".to_string()], ..BaseNode::default() }, arguments: vec![Expression::Object(Box::new(ObjectExpr { base: BaseNode { location: loc.get(1, 7, 1, 12), ..BaseNode::default() }, lbrace: vec![], rbrace: vec![], with: None, properties: vec![Property { base: BaseNode { location: loc.get(1, 7, 1, 12), errors: vec![ "invalid expression @1:33-1:34: )".to_string(), "missing property value".to_string(), ], ..BaseNode::default() }, key: PropertyKey::Identifier(Identifier { base: BaseNode { location: loc.get(1, 7, 1, 12), ..BaseNode::default() }, name: "start".to_string(), }), comma: vec![], separator: vec![], value: None, }], }))], callee: Expression::Identifier(Identifier { base: BaseNode { location: loc.get(1, 1, 1, 6), ..BaseNode::default() }, name: "range".to_string(), }), lparen: vec![], rparen: vec![], })) }))], eof: vec![], }, ) } #[test] fn date_time_literal() { let mut p = Parser::new(r#"now = 2018-11-29T09:00:00Z"#); let parsed = p.parse_file("".to_string()); let loc = Locator::new(&p.source[..]); assert_eq!( parsed, File { base: BaseNode { location: loc.get(1, 1, 1, 27), ..BaseNode::default() }, name: "".to_string(), metadata: "parser-type=rust".to_string(), package: None, imports: vec![], body: vec![Statement::Variable(Box::new(VariableAssgn { base: BaseNode { location: loc.get(1, 1, 1, 27), ..BaseNode::default() }, id: Identifier { base: BaseNode { location: loc.get(1, 1, 1, 4), ..BaseNode::default() }, name: "now".to_string() }, init: Expression::DateTime(DateTimeLit { base: BaseNode { location: loc.get(1, 7, 1, 27), ..BaseNode::default() }, value: chrono::DateTime::parse_from_rfc3339("2018-11-29T09:00:00Z").unwrap() }) }))], eof: vec![], }, ) } #[test] fn date_time_literal_with_fractional_seconds() { let mut p = Parser::new(r#"now = 2018-11-29T09:00:00.100000000Z"#); let parsed = p.parse_file("".to_string()); let loc = Locator::new(&p.source[..]); assert_eq!( parsed, File { base: BaseNode { location: loc.get(1, 1, 1, 37), ..BaseNode::default() }, name: "".to_string(), metadata: "parser-type=rust".to_string(), package: None, imports: vec![], body: vec![Statement::Variable(Box::new(VariableAssgn { base: BaseNode { location: loc.get(1, 1, 1, 37), ..BaseNode::default() }, id: Identifier { base: BaseNode { location: loc.get(1, 1, 1, 4), ..BaseNode::default() }, name: "now".to_string() }, init: Expression::DateTime(DateTimeLit { base: BaseNode { location: loc.get(1, 7, 1, 37), ..BaseNode::default() }, value: chrono::DateTime::parse_from_rfc3339("2018-11-29T09:00:00.100000000Z") .unwrap() }) }))], eof: vec![], }, ) } #[test] fn integer_literal_overflow() { let mut p = Parser::new(r#"100000000000000000000000000000"#); let parsed = p.parse_file("".to_string()); let loc = Locator::new(&p.source[..]); assert_eq!( parsed, File { base: BaseNode { location: loc.get(1, 1, 1, 31), .. BaseNode::default() }, name: "".to_string(), metadata: "parser-type=rust".to_string(), package: None, imports: vec![], body: vec![Statement::Expr(Box::new(ExprStmt { base: BaseNode { location: loc.get(1, 1, 1, 31), .. BaseNode::default() }, expression: Expression::Integer(IntegerLit { base: BaseNode { location: loc.get(1, 1, 1, 31), errors: vec!["invalid integer literal \"100000000000000000000000000000\": value out of range".to_string()], .. BaseNode::default() }, value: 0, }) }))], eof: vec![], }, ) }
#[doc = "Register `VOSCR` reader"] pub type R = crate::R<VOSCR_SPEC>; #[doc = "Register `VOSCR` writer"] pub type W = crate::W<VOSCR_SPEC>; #[doc = "Field `VOS` reader - voltage scaling selection according to performance These bits control the V&lt;sub>CORE&lt;/sub> voltage level and allow to obtain the best trade-off between power consumption and performance: - In bypass mode, these bits must also be set according to the external provided core voltage level and related performance. - When increasing the performance, the voltage scaling must be changed before increasing the system frequency. - When decreasing performance, the system frequency must first be decreased before changing the voltage scaling."] pub type VOS_R = crate::FieldReader; #[doc = "Field `VOS` writer - voltage scaling selection according to performance These bits control the V&lt;sub>CORE&lt;/sub> voltage level and allow to obtain the best trade-off between power consumption and performance: - In bypass mode, these bits must also be set according to the external provided core voltage level and related performance. - When increasing the performance, the voltage scaling must be changed before increasing the system frequency. - When decreasing performance, the system frequency must first be decreased before changing the voltage scaling."] pub type VOS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; impl R { #[doc = "Bits 4:5 - voltage scaling selection according to performance These bits control the V&lt;sub>CORE&lt;/sub> voltage level and allow to obtain the best trade-off between power consumption and performance: - In bypass mode, these bits must also be set according to the external provided core voltage level and related performance. - When increasing the performance, the voltage scaling must be changed before increasing the system frequency. - When decreasing performance, the system frequency must first be decreased before changing the voltage scaling."] #[inline(always)] pub fn vos(&self) -> VOS_R { VOS_R::new(((self.bits >> 4) & 3) as u8) } } impl W { #[doc = "Bits 4:5 - voltage scaling selection according to performance These bits control the V&lt;sub>CORE&lt;/sub> voltage level and allow to obtain the best trade-off between power consumption and performance: - In bypass mode, these bits must also be set according to the external provided core voltage level and related performance. - When increasing the performance, the voltage scaling must be changed before increasing the system frequency. - When decreasing performance, the system frequency must first be decreased before changing the voltage scaling."] #[inline(always)] #[must_use] pub fn vos(&mut self) -> VOS_W<VOSCR_SPEC, 4> { VOS_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 = "PWR voltage scaling control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`voscr::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 [`voscr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct VOSCR_SPEC; impl crate::RegisterSpec for VOSCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`voscr::R`](R) reader structure"] impl crate::Readable for VOSCR_SPEC {} #[doc = "`write(|w| ..)` method takes [`voscr::W`](W) writer structure"] impl crate::Writable for VOSCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets VOSCR to value 0"] impl crate::Resettable for VOSCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[doc = "Register `FDCAN_TXEFC` reader"] pub type R = crate::R<FDCAN_TXEFC_SPEC>; #[doc = "Register `FDCAN_TXEFC` writer"] pub type W = crate::W<FDCAN_TXEFC_SPEC>; #[doc = "Field `EFSA` reader - EFSA"] pub type EFSA_R = crate::FieldReader<u16>; #[doc = "Field `EFSA` writer - EFSA"] pub type EFSA_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 14, O, u16>; #[doc = "Field `EFS` reader - EFS"] pub type EFS_R = crate::FieldReader; #[doc = "Field `EFS` writer - EFS"] pub type EFS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 6, O>; #[doc = "Field `EFWM` reader - EFWM"] pub type EFWM_R = crate::FieldReader; #[doc = "Field `EFWM` writer - EFWM"] pub type EFWM_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 6, O>; impl R { #[doc = "Bits 2:15 - EFSA"] #[inline(always)] pub fn efsa(&self) -> EFSA_R { EFSA_R::new(((self.bits >> 2) & 0x3fff) as u16) } #[doc = "Bits 16:21 - EFS"] #[inline(always)] pub fn efs(&self) -> EFS_R { EFS_R::new(((self.bits >> 16) & 0x3f) as u8) } #[doc = "Bits 24:29 - EFWM"] #[inline(always)] pub fn efwm(&self) -> EFWM_R { EFWM_R::new(((self.bits >> 24) & 0x3f) as u8) } } impl W { #[doc = "Bits 2:15 - EFSA"] #[inline(always)] #[must_use] pub fn efsa(&mut self) -> EFSA_W<FDCAN_TXEFC_SPEC, 2> { EFSA_W::new(self) } #[doc = "Bits 16:21 - EFS"] #[inline(always)] #[must_use] pub fn efs(&mut self) -> EFS_W<FDCAN_TXEFC_SPEC, 16> { EFS_W::new(self) } #[doc = "Bits 24:29 - EFWM"] #[inline(always)] #[must_use] pub fn efwm(&mut self) -> EFWM_W<FDCAN_TXEFC_SPEC, 24> { EFWM_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 = "FDCAN Tx event FIFO configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fdcan_txefc::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 [`fdcan_txefc::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct FDCAN_TXEFC_SPEC; impl crate::RegisterSpec for FDCAN_TXEFC_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`fdcan_txefc::R`](R) reader structure"] impl crate::Readable for FDCAN_TXEFC_SPEC {} #[doc = "`write(|w| ..)` method takes [`fdcan_txefc::W`](W) writer structure"] impl crate::Writable for FDCAN_TXEFC_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets FDCAN_TXEFC to value 0"] impl crate::Resettable for FDCAN_TXEFC_SPEC { const RESET_VALUE: Self::Ux = 0; }
use super::super::{ program::MaskCheckProgram, webgl::{WebGlF32Vbo, WebGlI16Ibo, WebGlRenderingContext}, ModelMatrix, }; use crate::block::{self, BlockId}; use ndarray::Array2; pub struct AreaCollectionRenderer { vertexis_buffer: WebGlF32Vbo, texture_coord_buffer: WebGlF32Vbo, index_buffer: WebGlI16Ibo, mask_check_program: MaskCheckProgram, } impl AreaCollectionRenderer { pub fn new(gl: &WebGlRenderingContext) -> Self { let vertexis_buffer = gl.create_vbo_with_f32array( &[ [0.5, 0.5, 0.0], [-0.5, 0.5, 0.0], [0.5, -0.5, 0.0], [-0.5, -0.5, 0.0], ] .concat(), ); let texture_coord_buffer = gl.create_vbo_with_f32array(&[[1.0, 1.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]].concat()); let index_buffer = gl.create_ibo_with_i16array(&[0, 1, 2, 3, 2, 1]); let mask_check_program = MaskCheckProgram::new(gl); Self { vertexis_buffer, texture_coord_buffer, index_buffer, mask_check_program, } } pub fn render<'a>( &self, gl: &WebGlRenderingContext, vp_matrix: &Array2<f32>, block_field: &block::Field, areas: impl Iterator<Item = &'a BlockId>, ) { self.mask_check_program.use_program(gl); gl.set_attribute( &self.vertexis_buffer, &self.mask_check_program.a_vertex_location, 3, 0, ); gl.set_attribute( &self.texture_coord_buffer, &self.mask_check_program.a_texture_coord_location, 2, 0, ); gl.bind_buffer( web_sys::WebGlRenderingContext::ELEMENT_ARRAY_BUFFER, Some(&self.index_buffer), ); for (_, area) in block_field.listed::<block::table_object::Area>(areas.collect()) { let (model_matrix, is_rounded, size) = if let block::table_object::area::Type::Line(line_width) = area.type_() { let line_width = *line_width as f32; let o = area.org().clone(); let v = area.vec().clone(); let len = (v[0].powi(2) + v[1].powi(2) + v[2].powi(2)).sqrt(); let zr = v[1].atan2(v[0]); let mm: Array2<f32> = ModelMatrix::new() .with_scale(&[len, line_width, 0.0]) .with_z_axis_rotation(zr) .with_movement(&[o[0] + v[0] / 2.0, o[1] + v[1] / 2.0, o[2] + v[2] / 2.0]) .into(); (mm, false, [len, line_width]) } else { let o = area.org(); let v = area.vec().clone(); let len = (v[0].powi(2) + v[1].powi(2) + v[2].powi(2)).sqrt() * 2.0; let mm: Array2<f32> = ModelMatrix::new() .with_scale(&[len, len, 0.0]) .with_movement(o) .into(); (mm, true, [len, len]) }; let mvp_matrix = vp_matrix.dot(&model_matrix); let mvp_matrix = mvp_matrix.t(); gl.uniform_matrix4fv_with_f32_array( Some(&self.mask_check_program.u_translate_location), false, &[ mvp_matrix.row(0).to_vec(), mvp_matrix.row(1).to_vec(), mvp_matrix.row(2).to_vec(), mvp_matrix.row(3).to_vec(), ] .concat() .into_iter() .map(|a| a as f32) .collect::<Vec<f32>>(), ); gl.uniform4fv_with_f32_array( Some(&self.mask_check_program.u_mask_color_1_location), &area.color_1().to_f32array(), ); gl.uniform4fv_with_f32_array( Some(&self.mask_check_program.u_mask_color_2_location), &area.color_2().to_f32array(), ); gl.uniform2fv_with_f32_array( Some(&self.mask_check_program.u_mask_size_location), &size, ); gl.uniform1i( Some(&self.mask_check_program.u_flag_round_location), if is_rounded { 1 } else { 0 }, ); gl.draw_elements_with_i32( web_sys::WebGlRenderingContext::TRIANGLES, 6, web_sys::WebGlRenderingContext::UNSIGNED_SHORT, 0, ); } } }
use base64ct::{Base64Unpadded, Encoding}; fn main() { for ex in &["Mi", "Mg"] { println!("--- {} ---", ex); let a = base64::decode(ex); let b = Base64Unpadded::decode_vec(ex); println!("base64: {:?}", a); println!("base64ct: {:?}", b); } }
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![warn(clippy::default_hash_types)] #![feature(rustc_private)] extern crate rustc_data_structures; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use std::collections::{HashMap, HashSet}; fn main() { let _map: HashMap<String, String> = HashMap::default(); let _set: HashSet<String> = HashSet::default(); // test that the lint doesn't also match the Fx variants themselves 😂 let _fx_map: FxHashMap<String, String> = FxHashMap::default(); let _fx_set: FxHashSet<String> = FxHashSet::default(); }
use hyper::{Client, Response}; use tokio::runtime::Runtime; use hyper::Error; use std::convert::TryInto; use hyper::client::HttpConnector; use hyper::body::Body; use std::borrow::Borrow; use hyper::http::response::Parts; type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; pub fn new_engine() -> Engine { Engine { runtime: tokio::runtime::Builder::new_multi_thread() .enable_all() .build().unwrap(), } } async fn req_async_body_string(success: fn(Parts, String), error: fn(Error)) { let client: Client<HttpConnector, Body> = Client::builder().build_http(); let uri = "http://httpbin.org/ip".parse().unwrap(); match client.get(uri).await { Ok(ok) => { let parts = ok.into_parts(); match hyper::body::to_bytes(parts.1).await { Ok(bytes) => { success(parts.0, String::from_utf8(bytes.to_vec()).unwrap()); } Err(err) => { error(err); } }; } Err(err) => { error(err) } }; } pub struct Engine { runtime: Runtime, } impl Engine { pub fn request(&self, success: fn(Parts, String), error: fn(Error)) { self.runtime.spawn(req_async_body_string(success, error)); } }
use indoc::indoc; pub const DEFAULT_CONFIG_SETTINGS: &str = indoc!( " # The number of seconds in a break. break_duration_seconds = 600 # 10 minutes # The number of seconds in between breaks. seconds_between_breaks = 3000 # 50 minutes # Whether or not to use idle detection. # # If set to true (the default), break-time will watch X events. If it detects you # haven't typed on the keyboard or used the mouse for `idle_detection_seconds`, it # will use this time as a break, and then set the next break to occur in # `seconds_between_breaks`. # # If set to false, break-time will ignore any X idle time and just start a new break # every `seconds_between_breaks`. idle_detection_enabled = true # The number of seconds to use for a break if you've been idle. This # means that if break-time detects that you've been idle for 8 minutes, # it will use that time as a break. It will then start waiting for # another seconds_between_breaks until starting another break. idle_detection_seconds = 480 # 8 minutes [plugin.google_calendar] # A list of strings, one for each Google account you want to authenticate with. accounts = [] [plugin.x11_window_title_checker] " );
use std::collections::HashMap; use std::pin::Pin; use std::sync::Arc; use futures::{ future::{poll_fn, select}, pin_mut, FutureExt, Sink, }; use crate::{ client::{watch_for_client_state_change, Broadcast, Client, ClientTaskTracker}, error::WampError, proto::TxMessage, transport::Transport, uri::Uri, Id, SessionScope, }; async fn publish_impl<T: Transport>( task_tracker: Arc<ClientTaskTracker<T>>, topic: Uri, message: Broadcast, ) -> Result<(), WampError> { { let mut sender = task_tracker.get_sender().lock().await; poll_fn(|cx| Pin::new(&mut *sender).poll_ready(cx)) .await .map_err(|error| WampError::WaitForReadyToSendFailed { message_type: "PUBLISH", error, })?; Pin::new(&mut *sender) .start_send(TxMessage::Publish { request: Id::<SessionScope>::next(), options: HashMap::new(), topic, arguments: Some(message.arguments), arguments_kw: Some(message.arguments_kw), }) .map_err(|error| WampError::MessageSendFailed { message_type: "PUBLISH", error, })?; } { let mut sender = task_tracker.get_sender().lock().await; poll_fn(|cx| Pin::new(&mut *sender).poll_flush(cx)) .await .map_err(|error| WampError::SinkFlushFailed { message_type: "PUBLISH", error, })?; } // Note: since we're not requesting acknowledgement, the broker // will not tell us if the message request fails. Ok(()) } pub(in crate::client) async fn publish<T: Transport>( client: &Client<T>, topic: Uri, message: Broadcast, ) -> Result<(), WampError> { let wfcsc = watch_for_client_state_change(client.state.clone(), |state| state.is_established()).fuse(); let pi = publish_impl(client.task_tracker.clone(), topic, message).fuse(); pin_mut!(wfcsc, pi); select(wfcsc, pi).await.factor_first().0 }
extern crate reqwest; extern crate scraper; extern crate select; use select::document::Document; use select::predicate::{Class, Name, Predicate}; use scraper::{Html, Selector}; fn main() { println!("\n{}\n", "*. Hacker news headlines"); // assert!(hacker_news("https://news.ycombinator.com").is_ok()); // assert!(hacker_news_headlines("https://news.ycombinator.com").is_ok()); assert!(hacker_news_ranked("https://news.ycombinator.com").is_ok()); } #[tokio::main] async fn hacker_news_headlines(url: &str) -> Result<(), Box<dyn std::error::Error>> { let response = reqwest::get(url).await?; assert!(response.status().is_success()); let body = response.text().await?; let fragment = Html::parse_document(&body); let stories = Selector::parse(".storylink").unwrap(); for story in fragment.select(&stories) { let story_txt = story.text().collect::<Vec<_>>(); println!("{}", story_txt.join(" ")); } Ok(()) } #[tokio::main] async fn hacker_news(url: &str) -> Result<(), Box<dyn std::error::Error>> { let response = reqwest::get(url).await?; assert!(response.status().is_success()); let body = response.text().await?; Document::from_read(body.as_bytes()) .unwrap() .find(Name("a")) .filter_map(|n| n.attr("href")) .for_each(|x| println!("{}", x)); Ok(()) } #[tokio::main] async fn hacker_news_ranked(url: &str) -> Result<(), Box<dyn std::error::Error>> { let response = reqwest::get(url).await?; assert!(response.status().is_success()); let body = response.text().await?; let document = Document::from_read(body.as_bytes()).unwrap(); for node in document.find(Class("athing")) { let rank = node.find(Class("rank")).next().unwrap(); let story = node .find(Class("title").descendant(Name("a"))) .next() .unwrap() .text(); println!("{} {}", rank.text(), story); let subtext = node.next().ok_or("Err").unwrap(); for field in &["score", "hnuser", "age"] { let value = subtext.find(Class(*field)).next().ok_or("Err"); let value: String = if value.is_ok() { value.unwrap().text() } else { "".to_string() }; print!("{}:\t\t{}\n", field, value); } let url = node .find(Class("title").descendant(Name("a"))) .next() .unwrap(); println!("url:\t\t{}\n", url.attr("href").unwrap()); } Ok(()) }
#![deny(warnings)] use embedded_hal::can::ExtendedId; use embedded_time::Clock; use uavcan::{ session::StdVecSessionManager, time::StdClock, transfer::Transfer, transport::can::{Can, CanFrame as UavcanFrame, CanMetadata}, types::TransferId, Node, Priority, StreamingIterator, Subscription, TransferKind, }; use arrayvec::ArrayVec; use socketcan::{CANFrame, CANSocket}; fn main() { let clock = StdClock::new(); let mut session_manager = StdVecSessionManager::<CanMetadata, StdClock>::new(); session_manager .subscribe(Subscription::new( TransferKind::Message, 7509, // TODO check 7, embedded_time::duration::Milliseconds(500), )) .unwrap(); session_manager .subscribe(Subscription::new( TransferKind::Message, 100, 200, embedded_time::duration::Milliseconds(500), )) .unwrap(); let mut node = Node::<_, Can, StdClock>::new(Some(42), session_manager); let sock = CANSocket::open("vcan0").unwrap(); let mut last_publish = clock.try_now().unwrap(); let mut transfer_id: TransferId = 30; sock.set_read_timeout(std::time::Duration::from_millis(100)) .unwrap(); loop { let socketcan_frame = sock.read_frame().ok(); if let Some(socketcan_frame) = socketcan_frame { // Note that this exposes some things I *don't* like about the API // 1: we should have CanFrame::new or something // 2: I don't like how the payload is working let mut uavcan_frame = UavcanFrame { timestamp: clock.try_now().unwrap(), id: ExtendedId::new(socketcan_frame.id()).expect("not a extended CAN ID"), payload: ArrayVec::new(), }; uavcan_frame .payload .extend(socketcan_frame.data().iter().copied()); let xfer = match node.try_receive_frame(uavcan_frame) { Ok(xfer) => xfer, Err(err) => { println!("try_receive_frame error: {:?}", err); return; } }; if let Some(xfer) = xfer { match xfer.transfer_kind { TransferKind::Message => { println!("UAVCAN message received!"); print!("\tData: "); for byte in xfer.payload { print!("0x{:02x} ", byte); } println!(); } TransferKind::Request => { println!("Request Received!"); } TransferKind::Response => { println!("Response Received!"); } } } } if clock.try_now().unwrap() - last_publish > embedded_time::duration::Generic::new(500, StdClock::SCALING_FACTOR) { // Publish string let hello = "Hello Python!"; let mut str = Vec::from([hello.len() as u8, 0]); str.extend_from_slice(hello.as_bytes()); let transfer = Transfer { timestamp: clock.try_now().unwrap(), priority: Priority::Nominal, transfer_kind: TransferKind::Message, port_id: 100, remote_node_id: None, transfer_id, payload: &str, }; // unchecked_add is unstable :( // unsafe { transfer_id.unchecked_add(1); } transfer_id = (std::num::Wrapping(transfer_id) + std::num::Wrapping(1)).0; let mut frame_iter = node.transmit(&transfer).unwrap(); while let Some(frame) = frame_iter.next() { sock.write_frame( &CANFrame::new(frame.id.as_raw(), &frame.payload, false, false).unwrap(), ) .unwrap(); //print!("Can frame {}: ", i); //for byte in &frame.payload { // print!("0x{:02x} ", byte); //} //println!(""); //if let Some(in_xfer) = node.try_receive_frame(frame).unwrap() { // println!("Received xfer!"); //} } last_publish = clock.try_now().unwrap(); } } }
use super::constants::*; use super::waves::*; #[derive(Clone, Copy)] pub struct SamplingContext { pub clock: f32, pub sample_rate: f32, } pub trait Node: Send { fn sample (&self, ctx: &SamplingContext) -> f32; } pub enum WaveType { Sine, Square, Sawtooth, Triangle } pub struct WaveGenerator { pub freq: f32, pub offset: f32, pub wave_type: WaveType } impl Node for WaveGenerator { fn sample (&self, ctx: &SamplingContext) -> f32 { match self.wave_type { WaveType::Sine => sine_wave(self.freq, ctx.clock, self.offset), WaveType::Square => square_wave(self.freq, ctx.clock, self.offset), WaveType::Sawtooth => sawtooth_wave(self.freq, ctx.clock, self.offset), WaveType::Triangle => triangle_wave(self.freq, ctx.clock, self.offset) } } } pub struct Sum { pub nodes: Vec<Box<dyn Node>>, } impl Node for Sum { fn sample (&self, ctx: &SamplingContext) -> f32 { self.nodes.iter().map (|n| n.sample(ctx)).sum() } }
use reqwest::{header, Client}; use serde::Deserialize; use std::collections::HashMap; use thiserror::Error; #[derive(Error, Debug)] pub enum EmojiListError { #[error("invalid token was passed: {0}")] InvalidTokenPassed(header::InvalidHeaderValue), #[error("reqwest client couldn't be built: {0}")] ClientBuildFailed(reqwest::Error), #[error("API request failed: URL: {url}, HTTP status: {status}")] APIRequestFailed { url: String, status: String }, #[error("the response body is not in JSON format or it cannot be properly deserialized: {0}")] ResponseUndeserializable(reqwest::Error), } /// Represents a response from the Slack emoji.list Web API. /// Refer to the [API documents](https://api.slack.com/methods/emoji.list) for more details. #[derive(Deserialize, Debug)] pub struct EmojiListResponse { pub ok: bool, pub emoji: Option<HashMap<String, String>>, pub error: Option<String>, } /// Given a valid access token with `emoji:read` scope granted, try to fetch an [`EmojiListResponse`](struct.EmojiListResponse.html). /// /// # Errors /// /// This method fails whenever any error occurs while making request and getting response from the Slack Web API. pub async fn fetch(token: &str) -> Result<EmojiListResponse, EmojiListError> { let mut headers = header::HeaderMap::new(); headers.insert( header::AUTHORIZATION, header::HeaderValue::from_str(format!("Bearer {}", token).as_str()) .map_err(EmojiListError::InvalidTokenPassed)?, ); let client = Client::builder() .default_headers(headers) .build() .map_err(EmojiListError::ClientBuildFailed)?; let response = client .get("https://slack.com/api/emoji.list") .send() .await .map_err(|error| { let url = error.url().map_or_else( || "URL not found.".to_string(), |url| url.as_str().to_owned(), ); let status = error.status().map_or_else( || "No HTTP status.".to_string(), |status| status.as_str().to_owned(), ); EmojiListError::APIRequestFailed { url, status } })?; response .json::<EmojiListResponse>() .await .map_err(EmojiListError::ResponseUndeserializable) } #[cfg(test)] mod test { use super::*; #[tokio::test] async fn invalid_token_error() { let invalid_token = "invalid!\n"; let result = fetch(invalid_token).await; assert!(result.is_err()); } }
#![cfg(test)] use super::{super::EntityStorage, *}; #[test] fn test_insertion() { let mut entities = EntityStorage::with_key(); let mut storage = ComponentStorage::new(); let entity = entities.insert(()); let component = "foo"; assert_eq!(storage.insert(entity, component), None); assert!(storage.attached(entity)); assert_eq!(storage[entity], "foo"); storage.remove(entity); assert!(!storage.attached(entity)); assert_eq!(storage.get(entity), None); } #[test] #[should_panic] fn test_insertion_assert() { use std::time::Instant; let mut entities = EntityStorage::with_key(); let mut storage = ComponentStorage::new(); let entity1 = entities.insert(()); let entity2 = entities.insert(()); assert_eq!(storage.insert(entity1, Instant::now()), None); assert_eq!(storage.insert(entity2, Instant::now()), None); assert_eq!(storage.insert(entity1, Instant::now()), None); } #[test] #[should_panic] fn test_index() { let mut entities = EntityStorage::with_key(); let mut storage = ComponentStorage::new(); let entity = entities.insert(()); storage[entity] = 0; assert_eq!(storage[entity], 0); let entity = entities.insert(()); let _component = storage[entity]; } #[test] fn test_iterator() { let mut entities = EntityStorage::with_key(); let mut storage = ComponentStorage::new(); let _entities: Vec<_> = (0..100) .map(|int| { let entity = entities.insert(()); storage.insert(entity, int); entity }) .collect(); for (_, component) in storage.iter_mut() { *component += 10; } for ((_, component), value) in storage.iter().zip(10..110) { assert_eq!(*component, value); } let iterator: IntoIter<i32> = storage.into_iter(); let range: Vec<_> = iterator.map(|tuple| tuple.1).collect(); assert_eq!(range, (10..110).collect::<Vec<_>>()); }
#[macro_use] extern crate rocket; #[macro_use] extern crate lazy_static; #[macro_use] extern crate rbatis; use example::BizActivity; use rbatis::crud::{CRUD}; use rbatis::rbatis::Rbatis; //mysql driver url pub const MYSQL_URL: &'static str = "mysql://root:123456@localhost:3306/test"; // init global rbatis pool lazy_static! { static ref RB: Rbatis = Rbatis::new(); } #[get("/")] async fn hello() -> String { let v = RB.fetch_list::<BizActivity>().await.unwrap(); serde_json::json!(v).to_string() } #[rocket::main] async fn main() { //log fast_log::init_log("requests.log", 1000, log::Level::Info, None, true); //link database RB.link(MYSQL_URL).await.unwrap(); rocket::build() .mount("/", routes![hello]) .launch() .await; }
use super::*; use crate::{mock::*, Error}; use frame_support::{assert_noop, assert_ok}; #[test] fn test_create_kitty_success() { new_test_ext().execute_with(|| { System::set_block_number(10); assert_ok!(KittiesModule::create_kitty(Origin::signed(1))); }); } #[test] fn test_transfer_kitty_success() { new_test_ext().execute_with(|| { System::set_block_number(10); KittiesModule::create_kitty(Origin::signed(1)); let kittyid = <KittiesCount<Test>>::get().unwrap() - 1; assert_ok!(KittiesModule::transfer_kitty(Origin::signed(1), 2, kittyid)); assert_eq!(Owner::<Test>::get(kittyid), Some(2)); }); } #[test] fn test_transfer_kitty_failed_dueto_not_kitty_not_exist() { new_test_ext().execute_with(|| { System::set_block_number(10); assert_noop!( KittiesModule::transfer_kitty(Origin::signed(10), 2, u64::max_value()), Error::<Test>::KittyNotExist ); }); } #[test] fn test_transfer_kitty_failed_dueto_not_kitty_owner() { new_test_ext().execute_with(|| { System::set_block_number(10); KittiesModule::create_kitty(Origin::signed(1)); let next_kittyid = <KittiesCount<Test>>::get().unwrap(); assert_noop!( KittiesModule::transfer_kitty(Origin::signed(10), 2, next_kittyid - 1), Error::<Test>::NotKittyOwner ); }); } #[test] fn test_breed_kitty_success() { new_test_ext().execute_with(|| { System::set_block_number(10); let parent1 = create_kitty(1); let parent2 = create_kitty(1); assert_ok!(KittiesModule::breed_kitty( Origin::signed(1), parent1, parent2 )); }); } #[test] fn test_breed_kitty_failed_dueto_kitty_not_exist() { new_test_ext().execute_with(|| { System::set_block_number(10); assert_noop!( KittiesModule::breed_kitty(Origin::signed(1), 1, 2), Error::<Test>::KittyNotExist ); }); } #[test] fn test_breed_kitty_failed_dueto_kitty_same_parent() { new_test_ext().execute_with(|| { System::set_block_number(10); let parent1 = create_kitty(1); assert_noop!( KittiesModule::breed_kitty(Origin::signed(1), 0, 0), Error::<Test>::SameParentIndex ); }); } fn create_kitty(owner: u64) -> u64 { KittiesModule::create_kitty(Origin::signed(owner)); <KittiesCount<Test>>::get().unwrap() - 1 }
#![feature(fs, io, path)] use std::process::Command; use std::io::Write; use std::fs::{ rename, OpenOptions }; use std::path::PathBuf; use std::env; extern crate gcc; fn main() { let config = &[ format!("--target={}", env::var("TARGET").unwrap()), format!("--host={}", env::var("HOST").unwrap()), ]; let dir = env::current_dir().unwrap(); let out_dir = PathBuf::new(&env::var_os("OUT_DIR").unwrap()); let backtrace = dir.join("../../../libbacktrace"); run(Command::new("sh") .current_dir(&out_dir) .arg("-c") .arg(&format!("{} {}", backtrace.join("configure").display(), config.connect(" ")))); let config = out_dir.join("config.h"); let mut config = OpenOptions::new().append(true).write(true).open(&config).unwrap(); config.write_all("\n#undef HAVE_ATOMIC_FUNCTIONS\n#undef HAVE_SYNC_FUNCTIONS\n".as_bytes()).unwrap(); drop(config); run(Command::new("make") .current_dir(&out_dir) .arg(&format!("-j{}", env::var("NUM_JOBS").unwrap())) .arg(&format!("INCDIR={}", backtrace.display()))); rename(&out_dir.join(".libs").join("libbacktrace.a"), &out_dir.join("libbacktrace.a")).unwrap(); println!("cargo:rustc-flags=-L native={} -l static={}", out_dir.display(), "backtrace"); } fn run(cmd: &mut Command) { println!("running: {:?}", cmd); cmd.status().unwrap(); }
/// /// 回文 /// pub fn palindrome_str_low() { println!("wow this palindrome test!"); let s = String::from("daaad"); let mut _index = 0; let mut _iner_index = 0; let mut _len = s.len(); println!("str len:{}", &_len); for _index in 0..s.len() { let mut _index_str = &s[_index.._index + 1]; let mut _len_str = &s[&_len - _index - 1.._len - _index]; //println!("_index_str:{},_len_str:{}", _index_str, _len_str); if _index_str != _len_str { println!("str is not palindrome"); return; } } println!("str is palindrome"); } pub fn palindrome_str_high() { }
fn main() { let s = "15cm"; println!("{}", s.split("cm").next().unwrap()); }
use arch::io; const CONFIG_ADDRESS: u16 = 0xCF8; const CONFIG_DATA: u16 = 0xCFC; /// Read from PCI config space pub unsafe fn pci_readcfg(bus: u32, dev: u32, func: u32, offset: u32) -> u32 { let address = 0x80000000u32 | (bus << 16) | (dev << 11) | (func << 8) | (offset & 0xfc); io::outl(CONFIG_ADDRESS, address); return io::inl(CONFIG_DATA); } /// Write to PCI config space pub unsafe fn pci_writecfg(bus: u32, dev: u32, func: u32, offset: u32, value: u32) { let address = 0x80000000u32 | (bus << 16) | (dev << 11) | (func << 8) | (offset & 0xfc); io::outl(CONFIG_ADDRESS, address); io::outl(CONFIG_DATA, value); } pub struct PCIBus { busno: u32, } // https://wiki.osdev.org/PCI#The_PCI_Bus impl PCIBus { pub fn new(busno: u32) -> Self { Self { busno: busno } } /// scan the devices on the bus pub fn scan<T>(&self, attach: T) -> (usize, usize) where T: Fn(u32, u32, u32) -> bool, { let mut devcnt: usize = 0; let mut attached: usize = 0; for dev in 0..32 { let vendor = unsafe { pci_readcfg(self.busno, dev, 0, 0) } & 0xFFFF; // non-existing device if vendor == 0xFFFF { continue; } devcnt += 1; let bhlc = unsafe { pci_readcfg(self.busno, dev, 0, 0xC) }; let funcs: u32; if (bhlc >> 16) & 0xFF > 0x80 { funcs = 8; } else { funcs = 1; } for func in 0..funcs { let vendor = unsafe { pci_readcfg(self.busno, dev, func, 0) } & 0xFFFF; if vendor == 0xFFFF { continue; } if attach(self.busno, dev, func) { attached += 1; } } } (devcnt, attached) } } pub fn init() { PCIBus::new(0).scan(|busno, dev, func| { println!("Busno {} Dev {} Fn {}", busno, dev, func); let data = unsafe { pci_readcfg(busno, dev, func, 0x8) }; println!("Class {} Subclass {}", data >> 24, (data >> 16) & 0xFF); false }); }
// Copyright 2018-2020 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Substrate is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Substrate. If not, see <http://www.gnu.org/licenses/>. use parity_scale_codec::{Decode, Encode}; use std::sync::Arc; /// Consensus-related data changes tracker. #[derive(Clone, Debug, Encode, Decode)] pub(crate) struct ConsensusChanges<H, N> { pending_changes: Vec<(N, H)>, } impl<H, N> ConsensusChanges<H, N> { /// Create empty consensus changes. pub(crate) fn empty() -> Self { ConsensusChanges { pending_changes: Vec::new() } } } impl<H: Copy + PartialEq, N: Copy + Ord> ConsensusChanges<H, N> { /// Returns reference to all pending changes. pub fn pending_changes(&self) -> &[(N, H)] { &self.pending_changes } /// Note unfinalized change of consensus-related data. pub(crate) fn note_change(&mut self, at: (N, H)) { let idx = self .pending_changes .binary_search_by_key(&at.0, |change| change.0) .unwrap_or_else(|i| i); self.pending_changes.insert(idx, at); } /// Finalize all pending consensus changes that are finalized by given block. /// Returns true if there any changes were finalized. pub(crate) fn finalize<F: Fn(N) -> ::sp_blockchain::Result<Option<H>>>( &mut self, block: (N, H), canonical_at_height: F, ) -> ::sp_blockchain::Result<(bool, bool)> { let (split_idx, has_finalized_changes) = self .pending_changes .iter() .enumerate() .take_while(|(_, &(at_height, _))| at_height <= block.0) .fold((None, Ok(false)), |(_, has_finalized_changes), (idx, ref at)| { ( Some(idx), has_finalized_changes.and_then(|has_finalized_changes| { if has_finalized_changes { Ok(has_finalized_changes) } else { canonical_at_height(at.0).map(|can_hash| Some(at.1) == can_hash) } }), ) }); let altered_changes = split_idx.is_some(); if let Some(split_idx) = split_idx { self.pending_changes = self.pending_changes.split_off(split_idx + 1); } has_finalized_changes.map(|has_finalized_changes| (altered_changes, has_finalized_changes)) } } /// Thread-safe consensus changes tracker reference. pub(crate) type SharedConsensusChanges<H, N> = Arc<parking_lot::Mutex<ConsensusChanges<H, N>>>;
#[doc = "Register `CREL` reader"] pub type R = crate::R<CREL_SPEC>; #[doc = "Register `CREL` writer"] pub type W = crate::W<CREL_SPEC>; #[doc = "Field `DAY` reader - Time Stamp Day"] pub type DAY_R = crate::FieldReader; #[doc = "Field `DAY` writer - Time Stamp Day"] pub type DAY_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `MON` reader - Time Stamp Month"] pub type MON_R = crate::FieldReader; #[doc = "Field `MON` writer - Time Stamp Month"] pub type MON_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `YEAR` reader - Time Stamp Year"] pub type YEAR_R = crate::FieldReader; #[doc = "Field `YEAR` writer - Time Stamp Year"] pub type YEAR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `SUBSTEP` reader - Sub-step of Core Release"] pub type SUBSTEP_R = crate::FieldReader; #[doc = "Field `SUBSTEP` writer - Sub-step of Core Release"] pub type SUBSTEP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `STEP` reader - Step of Core Release"] pub type STEP_R = crate::FieldReader; #[doc = "Field `STEP` writer - Step of Core Release"] pub type STEP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `REL` reader - Core Release"] pub type REL_R = crate::FieldReader; #[doc = "Field `REL` writer - Core Release"] pub type REL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; impl R { #[doc = "Bits 0:7 - Time Stamp Day"] #[inline(always)] pub fn day(&self) -> DAY_R { DAY_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 8:15 - Time Stamp Month"] #[inline(always)] pub fn mon(&self) -> MON_R { MON_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bits 16:19 - Time Stamp Year"] #[inline(always)] pub fn year(&self) -> YEAR_R { YEAR_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 20:23 - Sub-step of Core Release"] #[inline(always)] pub fn substep(&self) -> SUBSTEP_R { SUBSTEP_R::new(((self.bits >> 20) & 0x0f) as u8) } #[doc = "Bits 24:27 - Step of Core Release"] #[inline(always)] pub fn step(&self) -> STEP_R { STEP_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 28:31 - Core Release"] #[inline(always)] pub fn rel(&self) -> REL_R { REL_R::new(((self.bits >> 28) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:7 - Time Stamp Day"] #[inline(always)] #[must_use] pub fn day(&mut self) -> DAY_W<CREL_SPEC, 0> { DAY_W::new(self) } #[doc = "Bits 8:15 - Time Stamp Month"] #[inline(always)] #[must_use] pub fn mon(&mut self) -> MON_W<CREL_SPEC, 8> { MON_W::new(self) } #[doc = "Bits 16:19 - Time Stamp Year"] #[inline(always)] #[must_use] pub fn year(&mut self) -> YEAR_W<CREL_SPEC, 16> { YEAR_W::new(self) } #[doc = "Bits 20:23 - Sub-step of Core Release"] #[inline(always)] #[must_use] pub fn substep(&mut self) -> SUBSTEP_W<CREL_SPEC, 20> { SUBSTEP_W::new(self) } #[doc = "Bits 24:27 - Step of Core Release"] #[inline(always)] #[must_use] pub fn step(&mut self) -> STEP_W<CREL_SPEC, 24> { STEP_W::new(self) } #[doc = "Bits 28:31 - Core Release"] #[inline(always)] #[must_use] pub fn rel(&mut self) -> REL_W<CREL_SPEC, 28> { REL_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 = "Clock Calibration Unit Core Release Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`crel::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 [`crel::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CREL_SPEC; impl crate::RegisterSpec for CREL_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`crel::R`](R) reader structure"] impl crate::Readable for CREL_SPEC {} #[doc = "`write(|w| ..)` method takes [`crel::W`](W) writer structure"] impl crate::Writable for CREL_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CREL to value 0"] impl crate::Resettable for CREL_SPEC { const RESET_VALUE: Self::Ux = 0; }
use protocol::serde_am::*; #[derive(Debug, Copy, Clone, Eq, PartialEq, Default, Hash)] #[cfg_attr(features = "serde", derive(Serialize, Deserialize))] pub struct Upgrades { pub speed: u8, pub shield: bool, pub inferno: bool, } impl Serialize for Upgrades { fn serialize(&self, ser: &mut Serializer) -> Result<(), SerError> { assert!(self.speed < 8); let val = 0 | (self.speed & 7) | (self.shield as u8) << 3 | (self.inferno as u8) << 4; ser.serialize_u8(val) } } impl<'de> Deserialize<'de> for Upgrades { fn deserialize(de: &mut Deserializer<'de>) -> Result<Self, DeError> { let val = de.deserialize_u8()?; Ok(Self { speed: val & 7, shield: (val & 8) != 0, inferno: (val & 16) != 0, }) } }
pub type c_char = i8; pub type c_schar = i8; pub type c_uchar = u8; pub type c_short = i16; pub type c_ushort = u16; pub type c_int = i32; pub type c_uint = u32; pub type c_long = i32; pub type c_ulong = u32; pub type c_float = f32; pub type c_double = f64; pub type size_t = u32; pub type ptrdiff_t = i32; pub type clock_t = i32; pub type time_t = i32; pub type wchar_t = i32; pub type uint32_t = u32;
fn main() { let mut v = vec![1, 2, 3]; v.push(4); println!("{:?}", v); // let fourth = v[3]; // let fifth = & v.get(4); // println!("{:?}",fifth); for i in &mut v { println!("{}", i); *i *= 2; } println!("{:?}", v); for c in "नमस्ते".chars() { println!("{}", c); } use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); let teams = vec![String::from("Blue"), String::from("Yellow")]; let initial_scores = vec![10, 50]; let team_scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect(); println!("{:?}", team_scores); }
use std; use std::error::Error; use std::io::Read; use hyper; use hyper::Client; use hyper::client::RequestBuilder; use hyper::client::pool::{Config, Pool}; use hyper::client::response::Response; #[cfg(feature="ssl")] use hyper::net::HttpsConnector; #[cfg(feature="ssl")] use hyper::net::Openssl; #[cfg(feature="unix")] use unix::HttpUnixConnector; #[cfg(feature="ssl")] use openssl::ssl::{SslContext, SslMethod}; #[cfg(feature="ssl")] use openssl::ssl::error::SslError; #[cfg(feature="ssl")] use openssl::x509::X509FileType; use container::{Container, ContainerInfo}; use process::{Process, Top}; use stats::StatsReader; use system::SystemInfo; use image::{Image, ImageStatus, ImageDeleteAction}; use filesystem::FilesystemChange; use version::Version; use rustc_serialize::json; enum ClientType { #[cfg(feature="unix")] Unix, Tcp, } pub struct Docker { client: Client, client_type: ClientType, client_addr: String, } impl Docker { #[cfg(feature="unix")] pub fn connect_with_unix(addr: String) -> Result<Docker, std::io::Error> { // This ensures that using a fully-qualified path -- e.g. unix://.... -- works. The unix // socket provider expects a Path, so we don't need scheme. let client_addr = addr.clone().replace("unix://", ""); let http_unix_connector = HttpUnixConnector::new(&client_addr); let connection_pool_config = Config { max_idle: 8 }; let connection_pool = Pool::with_connector(connection_pool_config, http_unix_connector); let client = Client::with_connector(connection_pool); let docker = Docker { client: client, client_type: ClientType::Unix, client_addr: client_addr }; return Ok(docker); } pub fn connect_with_http(addr: String) -> Result<Docker, std::io::Error> { let mut client_addr = addr.clone().replace("tcp://", "http://"); if !client_addr.ends_with("/") { client_addr.push_str("/"); } let docker = Docker { client: Client::new(), client_type: ClientType::Tcp, client_addr: client_addr }; return Ok(docker); } #[cfg(feature="ssl")] pub fn connect_with_ssl(addr: String, ssl_key: &Path, ssl_cert: &Path, ssl_ca: &Path) -> Result<Docker, SslError> { // This ensures that using docker-machine-esque addresses work with Hyper. let mut client_addr = addr.clone().replace("tcp://", "https://"); if !client_addr.ends_with("/") { client_addr.push_str("/"); } let mut ssl_context = try!(SslContext::new(SslMethod::Sslv23)); try!(ssl_context.set_CA_file(ssl_ca)); try!(ssl_context.set_certificate_file(ssl_cert, X509FileType::PEM)); try!(ssl_context.set_private_key_file(ssl_key, X509FileType::PEM)); let hyper_ssl_context = Openssl { context: Arc::new(ssl_context) }; let https_connector = HttpsConnector::new(hyper_ssl_context); let connection_pool_config = Config { max_idle: 8 }; let connection_pool = Pool::with_connector(connection_pool_config, https_connector); let client = Client::with_connector(connection_pool); let docker = Docker { client: client, client_type: ClientType::Tcp, client_addr: client_addr }; return Ok(docker); } fn get_url(&self, path: String) -> String { let mut base = match self.client_type { ClientType::Tcp => self.client_addr.clone(), #[cfg(feature="unix")] ClientType::Unix => { // We need a host so the HTTP headers can be generated, so we just spoof it and say // that we're talking to localhost. The hostname doesn't matter one bit. "http://localhost/".to_string() } }; let new_path; if path.starts_with("/") { new_path = path[1..].to_owned(); } else { new_path = path.clone(); } base.push_str(&*new_path); base } fn build_get_request(&self, request_url: String) -> RequestBuilder { self.client.get(&*request_url) } fn build_post_request(&self, request_url: String) -> RequestBuilder { self.client.post(&*request_url) } fn build_delete_request(&self, request_url: String) -> RequestBuilder { self.client.delete(&*request_url) } fn execute_request(&self, request: RequestBuilder) -> Result<String, hyper::error::Error> { match request.send() { Ok(mut response) => { assert!(response.status.is_success()); let mut body = String::new(); match response.read_to_string(&mut body) { Ok(_) => Ok(body), Err(e) => Err(hyper::error::Error::Io(e)) } }, Err(e) => Err(e) } } fn start_request(&self, request: RequestBuilder) -> Result<Response, hyper::error::Error> { match request.send() { Ok(response) => { assert!(response.status.is_success()); Ok(response) }, Err(e) => Err(e) } } fn arrayify(&self, s: String) -> String { let wrapped = format!("[{}]", s); wrapped.clone().replace("}\r\n{", "}{").replace("}{", "},{") } pub fn get_containers(&self, all: bool) -> std::io::Result<Vec<Container>> { let a = match all { true => "1", false => "0" }; let request_url = self.get_url(format!("/containers/json?a={}&size=1", a)); let request = self.build_get_request(request_url); match self.execute_request(request) { Ok(body) => { match json::decode::<Vec<Container>>(&body) { Ok(containers) => Ok(containers), Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e.description())) } }, Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e.description())) } } pub fn get_processes(&self, container: &Container) -> std::io::Result<Vec<Process>> { let request_url = self.get_url(format!("/containers/{}/top", container.Id)); let request = self.build_get_request(request_url); match self.execute_request(request) { Ok(body) => { match json::decode::<Top>(&body) { Ok(top) => { let mut processes: Vec<Process> = Vec::new(); let mut process_iter = top.Processes.iter(); loop { let process = match process_iter.next() { Some(process) => process, None => { break; } }; let mut p = Process{ user: String::new(), pid: String::new(), cpu: None, memory: None, vsz: None, rss: None, tty: None, stat: None, start: None, time: None, command: String::new() }; let mut value_iter = process.iter(); let mut i: usize = 0; loop { let value = match value_iter.next() { Some(value) => value, None => { break; } }; let key = &top.Titles[i]; match key.as_ref() { "UID" => { p.user = value.clone() }, "USER" => {p.user = value.clone() }, "PID" => { p.pid = value.clone() }, "%CPU" => { p.cpu = Some(value.clone()) }, "%MEM" => { p.memory = Some(value.clone()) }, "VSZ" => { p.vsz = Some(value.clone()) }, "RSS" => { p.rss = Some(value.clone()) }, "TTY" => { p.tty = Some(value.clone()) }, "STAT" => { p.stat = Some(value.clone()) }, "START" => { p.start = Some(value.clone()) }, "STIME" => { p.start = Some(value.clone()) }, "TIME" => { p.time = Some(value.clone()) }, "CMD" => { p.command = value.clone() }, "COMMAND" => { p.command = value.clone() }, _ => {} } i = i + 1; }; processes.push(p); }; Ok(processes) }, Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e.description())) } }, Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e.description())) } } pub fn get_stats(&self, container: &Container) -> std::io::Result<StatsReader> { if container.Status.contains("Up") == false { let err = std::io::Error::new(std::io::ErrorKind::InvalidInput, "The container is already stopped."); return Err(err); } let request_url = self.get_url(format!("/containers/{}/stats", container.Id)); let request = self.build_get_request(request_url); match self.start_request(request) { Ok(response) => Ok(StatsReader::new(response)), Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e.description())) } } pub fn create_image(&self, image: String, tag: String) -> std::io::Result<Vec<ImageStatus>> { let request_url = self.get_url(format!("/images/create?fromImage={}&tag={}", image, tag)); let request = self.build_post_request(request_url); match self.execute_request(request) { Ok(body) => { let fixed = self.arrayify(body); match json::decode::<Vec<ImageStatus>>(&fixed) { Ok(statuses) => Ok(statuses), Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e.description())) } }, Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e.description())) } } pub fn get_images(&self, all: bool) -> std::io::Result<Vec<Image>> { let a = match all { true => "1", false => "0" }; let request_url = self.get_url(format!("/images/json?a={}", a)); let request = self.build_get_request(request_url); match self.execute_request(request) { Ok(body) => { match json::decode::<Vec<Image>>(&body) { Ok(images) => Ok(images), Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e.description())) } }, Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e.description())) } } pub fn delete_image(&self, tag: String, force: bool, noprune: bool) -> std::io::Result<Vec<ImageDeleteAction>> { let force_str = match force { true => "1", false => "0" }; let noprune_str = match noprune { true => "1", false => "0" }; let request_url = self.get_url(format!("/images/{}?force={}&noprune={}", tag, force_str, noprune_str)); let request = self.build_delete_request(request_url); match self.execute_request(request) { Ok(body) => { match json::decode::<Vec<ImageDeleteAction>>(&body) { Ok(status) => Ok(status), Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e.description())) } }, Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e.description())) } } pub fn get_system_info(&self) -> std::io::Result<SystemInfo> { let request_url = self.get_url(format!("/info")); let request = self.build_get_request(request_url); match self.execute_request(request) { Ok(body) => { match json::decode::<SystemInfo>(&body) { Ok(info) => Ok(info), Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e.description())) } }, Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e.description())) } } pub fn get_container_info(&self, container: &Container) -> std::io::Result<ContainerInfo> { let request_url = self.get_url(format!("/containers/{}/json", container.Id)); let request = self.build_get_request(request_url); match self.execute_request(request) { Ok(body) => { match json::decode::<ContainerInfo>(&body) { Ok(info) => Ok(info), Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e.description())) } }, Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e.description())) } } pub fn get_filesystem_changes(&self, container: &Container) -> std::io::Result<Vec<FilesystemChange>> { let request_url = self.get_url(format!("/containers/{}/changes", container.Id)); let request = self.build_get_request(request_url); match self.execute_request(request) { Ok(body) => { match json::decode::<Vec<FilesystemChange>>(&body) { Ok(changes) => Ok(changes), Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e.description())) } }, Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e.description())) } } pub fn export_container(&self, container: &Container) -> std::io::Result<Response> { let request_url = self.get_url(format!("/containers/{}/export", container.Id)); let request = self.build_get_request(request_url); match self.start_request(request) { Ok(response) => Ok(response), Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e.description())) } } pub fn ping(&self) -> std::io::Result<String> { let request_url = self.get_url(format!("/_ping")); let request = self.build_get_request(request_url); match self.execute_request(request) { Ok(body) => Ok(body), Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e.description())) } } pub fn get_version(&self) -> std::io::Result<Version> { let request_url = self.get_url(format!("/version")); let request = self.build_get_request(request_url); match self.execute_request(request) { Ok(body) => { match json::decode::<Version>(&body) { Ok(version) => Ok(version), Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e.description())) } }, Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e.description())) } } }
extern crate bitcoinrs_bytes; mod sha2; mod rand; pub use self::sha2::sha256; pub use self::rand::xorshift32;
use rand::{thread_rng, RngCore}; #[repr(C)] struct Mouth {} impl Mouth { /* * Note: Currently just spouts random data * */ pub fn speak() -> Vec<u8> { let mut data = [u8; random_number(5,50) ]; // each time we don't speak same amount of things... hai na :D thread_rng().fill_bytes(&mut data); data.to_vec() } }
//! Overflow-safe utilities for tracking JSON document depth. use super::error::DepthError; use std::{ fmt::Display, ops::{Add, Deref, Sub}, }; /// Overflow-safe thin wrapper for a [`u8`] depth counter. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Depth(u8); impl Depth { /// Depth of 0. pub const ZERO: Self = Self(0); /// Depth of 1. pub const ONE: Self = Self(1); /// Add `1` to the depth, or raise an error if the maximum /// supported value is reached. pub fn increment(&mut self) -> Result<(), DepthError> { *self = (*self + 1)?; Ok(()) } /// Subtract `1` from the depth, or raise an error if the depth /// is zero. pub fn decrement(&mut self) -> Result<(), DepthError> { *self = (*self - 1)?; Ok(()) } } macro_rules! impl_add { ($t:ty) => { impl Add<u8> for $t { type Output = Result<Depth, DepthError>; #[inline] fn add(self, rhs: u8) -> Self::Output { self.0 .checked_add(rhs) .ok_or(DepthError::AboveLimit(u8::MAX as usize)) .map(Depth) } } }; } macro_rules! impl_sub { ($t:ty) => { impl Sub<u8> for $t { type Output = Result<Depth, DepthError>; #[inline] fn sub(self, rhs: u8) -> Self::Output { self.0.checked_sub(rhs).ok_or(DepthError::BelowZero).map(Depth) } } }; } impl_add!(Depth); impl_add!(&Depth); impl_add!(&mut Depth); impl_sub!(Depth); impl_sub!(&Depth); impl_sub!(&mut Depth); impl Display for Depth { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } } impl Deref for Depth { type Target = u8; fn deref(&self) -> &Self::Target { &self.0 } }
use crate::mac::Poly1305; use crate::mem::constant_time_eq; mod chacha20; use self::chacha20::Chacha20; /// ChaCha20 and Poly1305 for OpenSSH Protocols (chacha20-poly1305@openssh.com) /// /// <https://github.com/openbsd/src/blob/master/usr.bin/ssh/PROTOCOL.chacha20poly1305> #[derive(Clone)] pub struct Chacha20Poly1305 { c1: Chacha20, c2: Chacha20, } impl core::fmt::Debug for Chacha20Poly1305 { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { f.debug_struct("Chacha20Poly1305").finish() } } impl Chacha20Poly1305 { pub const KEY_LEN: usize = Chacha20::KEY_LEN * 2; // 64 bytes pub const BLOCK_LEN: usize = Chacha20::BLOCK_LEN; // 64 bytes pub const NONCE_LEN: usize = Chacha20::NONCE_LEN; // 8 bytes pub const TAG_LEN: usize = Poly1305::TAG_LEN; // 16 bytes #[cfg(target_pointer_width = "64")] pub const P_MAX: usize = 274877906880; // (2^32 - 1) * BLOCK_LEN #[cfg(target_pointer_width = "32")] pub const P_MAX: usize = usize::MAX; // 2^32 - 1 #[allow(dead_code)] #[cfg(target_pointer_width = "64")] pub const C_MAX: usize = Self::P_MAX + Self::TAG_LEN; // 274,877,906,896 #[allow(dead_code)] #[cfg(target_pointer_width = "32")] pub const C_MAX: usize = Self::P_MAX - Self::TAG_LEN; // 4294967279 pub const N_MIN: usize = Self::NONCE_LEN; pub const N_MAX: usize = Self::NONCE_LEN; pub const PKT_OCTETS_LEN: usize = 4; pub fn new(key: &[u8]) -> Self { assert_eq!(Self::KEY_LEN / 2, Poly1305::KEY_LEN); assert_eq!(key.len(), Self::KEY_LEN); // K_2 is used in conjunction with poly1305 to build an AEAD // that is used to encrypt and authenticate the entire packet. let k2 = &key[..Chacha20::KEY_LEN]; // K_1 is used only to encrypt the 4 byte packet length field. let k1 = &key[Chacha20::KEY_LEN..Self::KEY_LEN]; let c2 = Chacha20::new(k2); let c1 = Chacha20::new(k1); Self { c1, c2 } } pub fn encrypt_slice(&mut self, pkt_seq_num: u32, aead_pkt: &mut [u8]) { debug_assert!(aead_pkt.len() >= Self::TAG_LEN + Self::PKT_OCTETS_LEN); let (pkt_len, plaintext_and_tag) = aead_pkt.split_at_mut(Self::PKT_OCTETS_LEN); let plen = plaintext_and_tag.len() - Self::TAG_LEN; let (plaintext_in_ciphertext_out, tag_out) = plaintext_and_tag.split_at_mut(plen); self.encrypt_slice_detached(pkt_seq_num, pkt_len, plaintext_in_ciphertext_out, tag_out) } pub fn decrypt_slice(&mut self, pkt_seq_num: u32, aead_pkt: &mut [u8]) -> bool { debug_assert!(aead_pkt.len() >= Self::TAG_LEN + Self::PKT_OCTETS_LEN); let (pkt_len, ciphertext_and_tag) = aead_pkt.split_at_mut(Self::PKT_OCTETS_LEN); let clen = ciphertext_and_tag.len() - Self::TAG_LEN; let (ciphertext_in_plaintext_out, tag_in) = ciphertext_and_tag.split_at_mut(clen); self.decrypt_slice_detached(pkt_seq_num, pkt_len, ciphertext_in_plaintext_out, &tag_in) } pub fn encrypt_slice_detached( &mut self, pkt_seq_num: u32, pkt_len: &mut [u8], plaintext_in_ciphertext_out: &mut [u8], tag_out: &mut [u8], ) { let plen = plaintext_in_ciphertext_out.len(); let tlen = tag_out.len(); debug_assert_eq!(pkt_len.len(), Self::PKT_OCTETS_LEN); debug_assert!(plen <= Self::P_MAX); debug_assert!(tlen == Self::TAG_LEN); let mut poly1305_key = [0u8; Poly1305::KEY_LEN]; self.c2.encrypt_slice(pkt_seq_num, 0, &mut poly1305_key); // The Secure Shell (SSH) Transport Layer Protocol // 6.1. Maximum Packet Length // https://tools.ietf.org/html/rfc4253#section-6.1 // The length in bytes of the `packet_length` field in a SSH packet. self.c1.encrypt_slice(pkt_seq_num, 0, pkt_len); // Set Chacha's block counter to 1 self.c2 .encrypt_slice(pkt_seq_num, 1, plaintext_in_ciphertext_out); // calculate and append tag // void poly1305_auth(unsigned char out[POLY1305_TAGLEN], const unsigned char *m, size_t inlen, const unsigned char key[POLY1305_KEYLEN]) { // poly1305_auth(dest + aadlen + len, dest, aadlen + len, poly_key); let mut poly1305 = Poly1305::new(&poly1305_key); poly1305.update(&pkt_len); poly1305.update(&plaintext_in_ciphertext_out); let tag = poly1305.finalize(); tag_out.copy_from_slice(&tag[..Self::TAG_LEN]); } pub fn decrypt_slice_detached( &mut self, pkt_seq_num: u32, pkt_len: &mut [u8], ciphertext_in_plaintext_out: &mut [u8], tag_in: &[u8], ) -> bool { let clen = ciphertext_in_plaintext_out.len(); let tlen = tag_in.len(); debug_assert_eq!(pkt_len.len(), Self::PKT_OCTETS_LEN); debug_assert!(clen <= Self::P_MAX); debug_assert!(tlen == Self::TAG_LEN); let mut poly1305_key = [0u8; Poly1305::KEY_LEN]; self.c2.encrypt_slice(pkt_seq_num, 0, &mut poly1305_key); let mut poly1305 = Poly1305::new(&poly1305_key); poly1305.update(&pkt_len); poly1305.update(&ciphertext_in_plaintext_out); let tag = poly1305.finalize(); // Verify let is_match = constant_time_eq(tag_in, &tag[..Self::TAG_LEN]); if is_match { // The length in bytes of the `packet_length` field in a SSH packet. self.c1.decrypt_slice(pkt_seq_num, 0, pkt_len); // Set Chacha's block counter to 1 self.c2 .decrypt_slice(pkt_seq_num, 1, ciphertext_in_plaintext_out); } is_match } }
#[aoc_generator(day2, part1)] pub fn parse_program(input: &str) -> Vec<usize> { input .split(',') .map(|i| i.parse::<usize>().unwrap()) .collect() } fn run_tape(mut tape: Vec<usize>) -> Vec<usize> { let mut i = 0; loop { match tape[i] { 1 => { let out = tape[i + 3]; tape[out] = tape[tape[i + 2]] + tape[tape[i + 1]] } 2 => { let out = tape[i + 3]; tape[out] = tape[tape[i + 2]] * tape[tape[i + 1]] } 99 => break, _ => {} } i += 4; } tape } #[aoc(day2, part1)] fn solve_p1(tape: &[usize]) -> usize { let mut tape = tape.to_owned(); tape[1] = 12; tape[2] = 2; run_tape(tape)[0] } #[aoc_generator(day2, part2)] fn p2_generator(input: &str) -> Vec<usize> { parse_program(input) } #[aoc(day2, part2)] fn solve_p2(tape: &[usize]) -> usize { for noun in 1..99 { for verb in 1..99 { let mut tape = tape.to_owned(); tape[1] = noun; tape[2] = verb; if run_tape(tape)[0] == 19_690_720 { return noun * 100 + verb; } } } println!("Failed to solve Day 2 Part 2"); 0 } #[cfg(test)] mod tests { use super::*; #[test] fn sample1() { assert_eq!(run_tape(vec![1, 0, 0, 0, 99]), vec![2, 0, 0, 0, 99]); } #[test] fn sample2() { assert_eq!(run_tape(vec![2, 3, 0, 3, 99]), vec![2, 3, 0, 6, 99]); } #[test] fn sample3() { assert_eq!( run_tape(vec![2, 4, 4, 5, 99, 0]), vec![2, 4, 4, 5, 99, 9801] ); } #[test] fn sample4() { assert_eq!( run_tape(vec![1, 1, 1, 4, 99, 5, 6, 0, 99]), vec![30, 1, 1, 4, 2, 5, 6, 0, 99] ); } }
#[doc = "Register `MACMDIOAR` reader"] pub type R = crate::R<MACMDIOAR_SPEC>; #[doc = "Register `MACMDIOAR` writer"] pub type W = crate::W<MACMDIOAR_SPEC>; #[doc = "Field `MB` reader - MII Busy"] pub type MB_R = crate::BitReader; #[doc = "Field `MB` writer - MII Busy"] pub type MB_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `C45E` reader - Clause 45 PHY Enable"] pub type C45E_R = crate::BitReader; #[doc = "Field `C45E` writer - Clause 45 PHY Enable"] pub type C45E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `GOC` reader - MII Operation Command"] pub type GOC_R = crate::FieldReader; #[doc = "Field `GOC` writer - MII Operation Command"] pub type GOC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `SKAP` reader - Skip Address Packet"] pub type SKAP_R = crate::BitReader; #[doc = "Field `SKAP` writer - Skip Address Packet"] pub type SKAP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CR` reader - CSR Clock Range"] pub type CR_R = crate::FieldReader; #[doc = "Field `CR` writer - CSR Clock Range"] pub type CR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `NTC` reader - Number of Training Clocks"] pub type NTC_R = crate::FieldReader; #[doc = "Field `NTC` writer - Number of Training Clocks"] pub type NTC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; #[doc = "Field `RDA` reader - Register/Device Address"] pub type RDA_R = crate::FieldReader; #[doc = "Field `RDA` writer - Register/Device Address"] pub type RDA_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>; #[doc = "Field `PA` reader - Physical Layer Address"] pub type PA_R = crate::FieldReader; #[doc = "Field `PA` writer - Physical Layer Address"] pub type PA_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>; #[doc = "Field `BTB` reader - Back to Back transactions"] pub type BTB_R = crate::BitReader; #[doc = "Field `BTB` writer - Back to Back transactions"] pub type BTB_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PSE` reader - Preamble Suppression Enable"] pub type PSE_R = crate::BitReader; #[doc = "Field `PSE` writer - Preamble Suppression Enable"] pub type PSE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - MII Busy"] #[inline(always)] pub fn mb(&self) -> MB_R { MB_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Clause 45 PHY Enable"] #[inline(always)] pub fn c45e(&self) -> C45E_R { C45E_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bits 2:3 - MII Operation Command"] #[inline(always)] pub fn goc(&self) -> GOC_R { GOC_R::new(((self.bits >> 2) & 3) as u8) } #[doc = "Bit 4 - Skip Address Packet"] #[inline(always)] pub fn skap(&self) -> SKAP_R { SKAP_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bits 8:11 - CSR Clock Range"] #[inline(always)] pub fn cr(&self) -> CR_R { CR_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 12:14 - Number of Training Clocks"] #[inline(always)] pub fn ntc(&self) -> NTC_R { NTC_R::new(((self.bits >> 12) & 7) as u8) } #[doc = "Bits 16:20 - Register/Device Address"] #[inline(always)] pub fn rda(&self) -> RDA_R { RDA_R::new(((self.bits >> 16) & 0x1f) as u8) } #[doc = "Bits 21:25 - Physical Layer Address"] #[inline(always)] pub fn pa(&self) -> PA_R { PA_R::new(((self.bits >> 21) & 0x1f) as u8) } #[doc = "Bit 26 - Back to Back transactions"] #[inline(always)] pub fn btb(&self) -> BTB_R { BTB_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bit 27 - Preamble Suppression Enable"] #[inline(always)] pub fn pse(&self) -> PSE_R { PSE_R::new(((self.bits >> 27) & 1) != 0) } } impl W { #[doc = "Bit 0 - MII Busy"] #[inline(always)] #[must_use] pub fn mb(&mut self) -> MB_W<MACMDIOAR_SPEC, 0> { MB_W::new(self) } #[doc = "Bit 1 - Clause 45 PHY Enable"] #[inline(always)] #[must_use] pub fn c45e(&mut self) -> C45E_W<MACMDIOAR_SPEC, 1> { C45E_W::new(self) } #[doc = "Bits 2:3 - MII Operation Command"] #[inline(always)] #[must_use] pub fn goc(&mut self) -> GOC_W<MACMDIOAR_SPEC, 2> { GOC_W::new(self) } #[doc = "Bit 4 - Skip Address Packet"] #[inline(always)] #[must_use] pub fn skap(&mut self) -> SKAP_W<MACMDIOAR_SPEC, 4> { SKAP_W::new(self) } #[doc = "Bits 8:11 - CSR Clock Range"] #[inline(always)] #[must_use] pub fn cr(&mut self) -> CR_W<MACMDIOAR_SPEC, 8> { CR_W::new(self) } #[doc = "Bits 12:14 - Number of Training Clocks"] #[inline(always)] #[must_use] pub fn ntc(&mut self) -> NTC_W<MACMDIOAR_SPEC, 12> { NTC_W::new(self) } #[doc = "Bits 16:20 - Register/Device Address"] #[inline(always)] #[must_use] pub fn rda(&mut self) -> RDA_W<MACMDIOAR_SPEC, 16> { RDA_W::new(self) } #[doc = "Bits 21:25 - Physical Layer Address"] #[inline(always)] #[must_use] pub fn pa(&mut self) -> PA_W<MACMDIOAR_SPEC, 21> { PA_W::new(self) } #[doc = "Bit 26 - Back to Back transactions"] #[inline(always)] #[must_use] pub fn btb(&mut self) -> BTB_W<MACMDIOAR_SPEC, 26> { BTB_W::new(self) } #[doc = "Bit 27 - Preamble Suppression Enable"] #[inline(always)] #[must_use] pub fn pse(&mut self) -> PSE_W<MACMDIOAR_SPEC, 27> { PSE_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 = "MDIO address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`macmdioar::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 [`macmdioar::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct MACMDIOAR_SPEC; impl crate::RegisterSpec for MACMDIOAR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`macmdioar::R`](R) reader structure"] impl crate::Readable for MACMDIOAR_SPEC {} #[doc = "`write(|w| ..)` method takes [`macmdioar::W`](W) writer structure"] impl crate::Writable for MACMDIOAR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets MACMDIOAR to value 0"] impl crate::Resettable for MACMDIOAR_SPEC { const RESET_VALUE: Self::Ux = 0; }
fn main() { prost_build::compile_protos(&["src/worker/schema/dht.proto"], &["src/worker/schema"]).unwrap(); }
mod block_template; mod blockchain; mod bytes; mod cell; mod net; mod pool; mod proposal_short_id; mod trace; pub type BlockNumber = String; pub type Capacity = String; pub type Cycle = String; pub use self::block_template::{ BlockTemplate, CellbaseTemplate, TransactionTemplate, UncleTemplate, }; pub use self::blockchain::{ Block, CellInput, CellOutput, Header, OutPoint, Script, Seal, Transaction, TransactionWithStatus, TxStatus, UncleBlock, Witness, }; pub use self::bytes::JsonBytes; pub use self::cell::{CellOutputWithOutPoint, CellWithStatus}; pub use self::net::{Node, NodeAddress}; pub use self::pool::TxPoolInfo; pub use self::proposal_short_id::ProposalShortId; pub use self::trace::{Action, TxTrace}; pub use ckb_core::Version; pub use jsonrpc_core::types::{error, id, params, request, response, version};
//! Angles. use std::{f64::consts::PI, ops::*}; /// Wrapper type storing angle expressed in radians. /// /// ``` /// use veccentric::{Angle, Angular}; /// /// let half_pi: Angle = (3.14_f32 / 2.0).rad(); /// ``` #[derive(Copy, Clone, PartialEq, Default, Debug)] pub struct Angle(f64); impl Deref for Angle { type Target = f64; fn deref(&self) -> &f64 { &self.0 } } // Neg. // Owned. impl Neg for Angle { type Output = Angle; fn neg(self) -> Angle { Angle(self.0.neg()) } } // Borrowed. impl Neg for &Angle { type Output = Angle; fn neg(self) -> Angle { Angle(self.0.neg()) } } // Add. // Owned & owned. impl Add<Angle> for Angle { type Output = Angle; fn add(self, rhs: Angle) -> Self::Output { Angle(self.0.add(rhs.0)) } } // Owned & borrowed. impl Add<&Angle> for Angle { type Output = Angle; fn add(self, rhs: &Angle) -> Self::Output { Angle(self.0.add(rhs.0)) } } // Borrowed & owned. impl Add<Angle> for &Angle { type Output = Angle; fn add(self, rhs: Angle) -> Self::Output { Angle(self.0.add(rhs.0)) } } // Borrowed & borrowed. impl Add<&Angle> for &Angle { type Output = Angle; fn add(self, rhs: &Angle) -> Self::Output { Angle(self.0.add(rhs.0)) } } // Sub. // Owned & owned. impl Sub<Angle> for Angle { type Output = Angle; fn sub(self, rhs: Angle) -> Self::Output { Angle(self.0.sub(rhs.0)) } } // Owned & borrowed. impl Sub<&Angle> for Angle { type Output = Angle; fn sub(self, rhs: &Angle) -> Self::Output { Angle(self.0.sub(rhs.0)) } } // Borrowed & owned. impl Sub<Angle> for &Angle { type Output = Angle; fn sub(self, rhs: Angle) -> Self::Output { Angle(self.0.sub(rhs.0)) } } // Borrowed & borrowed. impl Sub<&Angle> for &Angle { type Output = Angle; fn sub(self, rhs: &Angle) -> Self::Output { Angle(self.0.sub(rhs.0)) } } // Mul with f64. // Owned & owned. impl Mul<f64> for Angle { type Output = Angle; fn mul(self, rhs: f64) -> Self::Output { Angle(self.0.mul(rhs)) } } // Owned & borrowed. impl Mul<&f64> for Angle { type Output = Angle; fn mul(self, rhs: &f64) -> Self::Output { Angle(self.0.mul(rhs)) } } // Borrowed & owned. impl Mul<f64> for &Angle { type Output = Angle; fn mul(self, rhs: f64) -> Self::Output { Angle(self.0.mul(rhs)) } } // Borrowed & borrowed. impl Mul<&f64> for &Angle { type Output = Angle; fn mul(self, rhs: &f64) -> Self::Output { Angle(self.0.mul(rhs)) } } // Div with f64. // Owned & owned. impl Div<f64> for Angle { type Output = Angle; fn div(self, rhs: f64) -> Self::Output { Angle(self.0.div(rhs)) } } // Owned & borrowed. impl Div<&f64> for Angle { type Output = Angle; fn div(self, rhs: &f64) -> Self::Output { Angle(self.0.div(rhs)) } } // Borrowed & owned. impl Div<f64> for &Angle { type Output = Angle; fn div(self, rhs: f64) -> Self::Output { Angle(self.0.div(rhs)) } } // Borrowed & borrowed. impl Div<&f64> for &Angle { type Output = Angle; fn div(self, rhs: &f64) -> Self::Output { Angle(self.0.div(rhs)) } } // AddAssign. // Owned. impl AddAssign<Angle> for Angle { fn add_assign(&mut self, rhs: Angle) { self.0.add_assign(rhs.0); } } // Borrowed. impl AddAssign<&Angle> for Angle { fn add_assign(&mut self, rhs: &Angle) { self.0.add_assign(rhs.0); } } // SubAssign. // Owned. impl SubAssign<Angle> for Angle { fn sub_assign(&mut self, rhs: Angle) { self.0.sub_assign(rhs.0); } } // Borrowed. impl SubAssign<&Angle> for Angle { fn sub_assign(&mut self, rhs: &Angle) { self.0.sub_assign(rhs.0); } } impl<T> From<T> for Angle where f64: From<T>, { fn from(angle: T) -> Self { Self(angle.into()) } } /// A trait exposing a convenient API to work with angles. It is implemented for /// every type implementing `Into<f64>`. /// /// ``` /// use veccentric::{Angular, Angle, Fecc}; /// /// let half_pi_rad: Angle = (3.14_f32 / 2.0).rad(); /// let half_pi_deg: Angle = 90_i32.deg(); /// let half_pi_f64: f64 = 3.14 / 2.0; /// /// let a = Fecc::new(1.0, 0.0); /// let b = a.rotate(half_pi_rad); /// let b = a.rotate(half_pi_deg); /// let b = a.rotate(half_pi_f64); /// ``` /// /// The API prevents calling [`deg()`](Angular::deg) or [`rad()`](Angular::rad) /// twice. /// /// ```compile_fail /// let pi = 180.0_f32.deg(); /// /// // Doesn't work! `pi` is of type `Angle` which has no such method. /// let not_pi = pi.deg(); /// ``` pub trait Angular { /// Interpret the value as radians. fn rad(self) -> Angle; /// Interpret the value as degrees. fn deg(self) -> Angle; } impl<T> Angular for T where T: Into<f64>, { fn rad(self) -> Angle { Angle(self.into()) } fn deg(self) -> Angle { Angle(self.into() * PI / 180.0) } }
mod cache; mod config; pub mod data_loader_wrapper; mod db; mod snapshot; mod store; mod transaction; pub use cache::StoreCache; pub use config::StoreConfig; pub use db::ChainDB; pub use snapshot::StoreSnapshot; pub use store::ChainStore; pub use transaction::StoreTransaction; use ckb_db::Col; pub const COLUMNS: u32 = 12; pub const COLUMN_INDEX: Col = "0"; pub const COLUMN_BLOCK_HEADER: Col = "1"; pub const COLUMN_BLOCK_BODY: Col = "2"; pub const COLUMN_BLOCK_UNCLE: Col = "3"; pub const COLUMN_META: Col = "4"; pub const COLUMN_TRANSACTION_INFO: Col = "5"; pub const COLUMN_BLOCK_EXT: Col = "6"; pub const COLUMN_BLOCK_PROPOSAL_IDS: Col = "7"; pub const COLUMN_BLOCK_EPOCH: Col = "8"; pub const COLUMN_EPOCH: Col = "9"; pub const COLUMN_CELL_SET: Col = "10"; pub const COLUMN_UNCLES: Col = "11"; const META_TIP_HEADER_KEY: &[u8] = b"TIP_HEADER"; const META_CURRENT_EPOCH_KEY: &[u8] = b"CURRENT_EPOCH";
#![feature(min_const_fn)] extern crate stringly_typed_rust_esosyntax; use stringly_typed_rust_esosyntax::stringly_typed; const fn to_string(n: i32) -> String { format!("{}", n) } stringly_typed!{"'N'id'String'ty'"to_string"id"69"int'call"const} fn main() { println!("N = {}!", N); }
//! The `Fuzzer` is the main struct for a fuzz campaign. use crate::{ bolts::current_time, corpus::{Corpus, CorpusScheduler, Testcase}, events::{Event, EventFirer, EventManager}, executors::{Executor, ExitKind, HasExecHooksTuple, HasObservers, HasObserversHooks}, feedbacks::Feedback, inputs::Input, mark_feature_time, observers::ObserversTuple, stages::StagesTuple, start_timer, state::{HasClientPerfStats, HasCorpus, HasExecutions, HasSolutions}, Error, }; #[cfg(feature = "introspection")] use crate::stats::PerfFeature; #[cfg(feature = "introspection")] use alloc::boxed::Box; use alloc::string::ToString; use core::{marker::PhantomData, time::Duration}; /// Send a stats update all 3 (or more) seconds const STATS_TIMEOUT_DEFAULT: Duration = Duration::from_millis(3 * 1000); /// Holds a scheduler pub trait HasCorpusScheduler<CS, I, S> where CS: CorpusScheduler<I, S>, I: Input, { /// The scheduler fn scheduler(&self) -> &CS; /// The scheduler (mut) fn scheduler_mut(&mut self) -> &mut CS; } /// Holds an feedback pub trait HasFeedback<F, I, S> where F: Feedback<I, S>, I: Input, { /// The feedback fn feedback(&self) -> &F; /// The feedback (mut) fn feedback_mut(&mut self) -> &mut F; } /// Holds an objective feedback pub trait HasObjective<I, OF, S> where OF: Feedback<I, S>, I: Input, { /// The objective feedback fn objective(&self) -> &OF; /// The objective feedback (mut) fn objective_mut(&mut self) -> &mut OF; } /// Evaluate if an input is interesting using the feedback pub trait IsInteresting<I, OT, S> where OT: ObserversTuple, I: Input, { /// Evaluate if a set of observation channels has an interesting state fn is_interesting<EM>( &mut self, state: &mut S, manager: &mut EM, input: &I, observers: &OT, exit_kind: &ExitKind, ) -> Result<bool, Error> where EM: EventFirer<I, S>; } /// Add to the state if interesting pub trait IfInteresting<I, S> { /// Adds this input to the corpus, if it's intersting, and return the index fn add_if_interesting( &mut self, state: &mut S, input: &I, is_interesting: bool, ) -> Result<Option<usize>, Error>; } /// Evaluate an input modyfing the state of the fuzzer pub trait Evaluator<E, EM, I, S> { /// Runs the input and triggers observers and feedback, /// returns if is interesting an (option) the index of the new testcase in the corpus fn evaluate_input( &mut self, state: &mut S, executor: &mut E, manager: &mut EM, input: I, ) -> Result<(bool, Option<usize>), Error>; /// Runs the input and triggers observers and feedback. /// Adds an input, to the corpus even if it's not considered `interesting` by the `feedback`. /// Returns the `index` of the new testcase in the corpus. /// Usually, you want to use [`Evaluator::evaluate_input`], unless you know what you are doing. fn add_input( &mut self, state: &mut S, executor: &mut E, manager: &mut EM, input: I, ) -> Result<usize, Error>; } /// The main fuzzer trait. pub trait Fuzzer<E, EM, I, S, ST> { /// Fuzz for a single iteration /// Returns the index of the last fuzzed corpus item /// /// If you use this fn in a restarting scenario to only run for `n` iterations, /// before exiting, make sure you call `event_mgr.on_restart(&mut state)?;`. /// This way, the state will be available in the next, respawned, iteration. fn fuzz_one( &mut self, stages: &mut ST, executor: &mut E, state: &mut S, manager: &mut EM, ) -> Result<usize, Error>; /// Fuzz forever (or until stopped) fn fuzz_loop( &mut self, stages: &mut ST, executor: &mut E, state: &mut S, manager: &mut EM, ) -> Result<usize, Error> { let mut last = current_time(); let stats_timeout = STATS_TIMEOUT_DEFAULT; loop { self.fuzz_one(stages, executor, state, manager)?; last = Self::maybe_report_stats(state, manager, last, stats_timeout)?; } } /// Fuzz for n iterations /// Returns the index of the last fuzzed corpus item /// /// If you use this fn in a restarting scenario to only run for `n` iterations, /// before exiting, make sure you call `event_mgr.on_restart(&mut state)?;`. /// This way, the state will be available in the next, respawned, iteration. fn fuzz_loop_for( &mut self, stages: &mut ST, state: &mut S, executor: &mut E, manager: &mut EM, iters: u64, ) -> Result<usize, Error> { if iters == 0 { return Err(Error::IllegalArgument( "Cannot fuzz for 0 iterations!".to_string(), )); } let mut ret = 0; let mut last = current_time(); let stats_timeout = STATS_TIMEOUT_DEFAULT; for _ in 0..iters { ret = self.fuzz_one(stages, executor, state, manager)?; last = Self::maybe_report_stats(state, manager, last, stats_timeout)?; } // If we would assume the fuzzer loop will always exit after this, we could do this here: // manager.on_restart(state)?; // But as the state may grow to a few megabytes, // for now we won' and the user has to do it (unless we find a way to do this on `Drop`). Ok(ret) } /// Given the last time, if `stats_timeout` seconds passed, send off an info/stats/heartbeat message to the broker. /// Returns the new `last` time (so the old one, unless `stats_timeout` time has passed and stats have been sent) /// Will return an [`crate::Error`], if the stats could not be sent. fn maybe_report_stats( state: &mut S, manager: &mut EM, last: Duration, stats_timeout: Duration, ) -> Result<Duration, Error>; } pub enum ExecuteInputResult { None, Interesting, Solution, } /// Your default fuzzer instance, for everyday use. #[derive(Debug)] pub struct StdFuzzer<C, CS, F, I, OF, OT, S, SC> where CS: CorpusScheduler<I, S>, F: Feedback<I, S>, I: Input, OF: Feedback<I, S>, { scheduler: CS, feedback: F, objective: OF, phantom: PhantomData<(C, I, OT, S, SC)>, } impl<C, CS, F, I, OF, OT, S, SC> HasCorpusScheduler<CS, I, S> for StdFuzzer<C, CS, F, I, OF, OT, S, SC> where CS: CorpusScheduler<I, S>, F: Feedback<I, S>, I: Input, OF: Feedback<I, S>, { fn scheduler(&self) -> &CS { &self.scheduler } fn scheduler_mut(&mut self) -> &mut CS { &mut self.scheduler } } impl<C, CS, F, I, OF, OT, S, SC> HasFeedback<F, I, S> for StdFuzzer<C, CS, F, I, OF, OT, S, SC> where CS: CorpusScheduler<I, S>, F: Feedback<I, S>, I: Input, OF: Feedback<I, S>, { fn feedback(&self) -> &F { &self.feedback } fn feedback_mut(&mut self) -> &mut F { &mut self.feedback } } impl<C, CS, F, I, OF, OT, S, SC> HasObjective<I, OF, S> for StdFuzzer<C, CS, F, I, OF, OT, S, SC> where CS: CorpusScheduler<I, S>, F: Feedback<I, S>, I: Input, OF: Feedback<I, S>, { fn objective(&self) -> &OF { &self.objective } fn objective_mut(&mut self) -> &mut OF { &mut self.objective } } impl<C, CS, F, I, OF, OT, S, SC> IsInteresting<I, OT, S> for StdFuzzer<C, CS, F, I, OF, OT, S, SC> where C: Corpus<I>, CS: CorpusScheduler<I, S>, F: Feedback<I, S>, I: Input, OF: Feedback<I, S>, OT: ObserversTuple, S: HasCorpus<C, I>, { /// Evaluate if a set of observation channels has an interesting state fn is_interesting<EM>( &mut self, state: &mut S, manager: &mut EM, input: &I, observers: &OT, exit_kind: &ExitKind, ) -> Result<bool, Error> where EM: EventFirer<I, S>, { self.feedback_mut() .is_interesting(state, manager, input, observers, exit_kind) } } impl<C, CS, F, I, OF, OT, S, SC> IfInteresting<I, S> for StdFuzzer<C, CS, F, I, OF, OT, S, SC> where C: Corpus<I>, CS: CorpusScheduler<I, S>, F: Feedback<I, S>, I: Input, OF: Feedback<I, S>, OT: ObserversTuple, S: HasCorpus<C, I>, { /// Adds this input to the corpus, if it's intersting, and return the index #[inline] fn add_if_interesting( &mut self, state: &mut S, input: &I, is_interesting: bool, ) -> Result<Option<usize>, Error> { if is_interesting { let mut testcase = Testcase::new(input.clone()); self.feedback_mut().append_metadata(state, &mut testcase)?; let idx = state.corpus_mut().add(testcase)?; self.scheduler_mut().on_add(state, idx)?; Ok(Some(idx)) } else { self.feedback_mut().discard_metadata(state, input)?; Ok(None) } } } impl<C, CS, E, EM, F, I, OF, OT, S, SC> Evaluator<E, EM, I, S> for StdFuzzer<C, CS, F, I, OF, OT, S, SC> where C: Corpus<I>, CS: CorpusScheduler<I, S>, E: Executor<EM, I, S, Self> + HasObservers<OT> + HasObserversHooks<EM, I, OT, S, Self>, OT: ObserversTuple + HasExecHooksTuple<EM, I, S, Self>, EM: EventManager<E, I, S, Self>, F: Feedback<I, S>, I: Input, OF: Feedback<I, S>, S: HasExecutions + HasCorpus<C, I> + HasSolutions<SC, I> + HasClientPerfStats, SC: Corpus<I>, { /// Process one input, adding to the respective corpuses if needed and firing the right events #[inline] fn evaluate_input( &mut self, state: &mut S, executor: &mut E, manager: &mut EM, input: I, ) -> Result<(bool, Option<usize>), Error> { let result = self.execute_input(state, executor, manager, &input)?; let observers = executor.observers(); match result { ExecuteInputResult::None => { self.feedback_mut().discard_metadata(state, &input)?; self.objective_mut().discard_metadata(state, &input)?; Ok((false, None)) } ExecuteInputResult::Interesting => { // Not a solution self.objective_mut().discard_metadata(state, &input)?; // Add the input to the main corpus let mut testcase = Testcase::new(input.clone()); self.feedback_mut().append_metadata(state, &mut testcase)?; let idx = state.corpus_mut().add(testcase)?; self.scheduler_mut().on_add(state, idx)?; let observers_buf = manager.serialize_observers(observers)?; manager.fire( state, Event::NewTestcase { input, observers_buf, corpus_size: state.corpus().count(), client_config: "TODO".into(), time: current_time(), executions: *state.executions(), }, )?; Ok((true, Some(idx))) } ExecuteInputResult::Solution => { // Not interesting self.feedback_mut().discard_metadata(state, &input)?; // The input is a solution, add it to the respective corpus let mut testcase = Testcase::new(input); self.objective_mut().append_metadata(state, &mut testcase)?; state.solutions_mut().add(testcase)?; manager.fire( state, Event::Objective { objective_size: state.solutions().count(), }, )?; Ok((false, None)) } } } /// Adds an input, even if it's not conisered `interesting` by any of the executors fn add_input( &mut self, state: &mut S, executor: &mut E, manager: &mut EM, input: I, ) -> Result<usize, Error> { let _ = self.execute_input(state, executor, manager, &input)?; let observers = executor.observers(); // Always consider this to be "interesting" // Not a solution self.objective_mut().discard_metadata(state, &input)?; // Add the input to the main corpus let mut testcase = Testcase::new(input.clone()); self.feedback_mut().append_metadata(state, &mut testcase)?; let idx = state.corpus_mut().add(testcase)?; self.scheduler_mut().on_add(state, idx)?; let observers_buf = manager.serialize_observers(observers)?; manager.fire( state, Event::NewTestcase { input, observers_buf, corpus_size: state.corpus().count(), client_config: "TODO".into(), time: current_time(), executions: *state.executions(), }, )?; Ok(idx) } } impl<C, CS, E, EM, F, I, OF, OT, S, ST, SC> Fuzzer<E, EM, I, S, ST> for StdFuzzer<C, CS, F, I, OF, OT, S, SC> where CS: CorpusScheduler<I, S>, EM: EventManager<E, I, S, Self>, F: Feedback<I, S>, I: Input, S: HasExecutions + HasClientPerfStats, OF: Feedback<I, S>, ST: StagesTuple<E, EM, S, Self>, { #[inline] fn maybe_report_stats( state: &mut S, manager: &mut EM, last: Duration, stats_timeout: Duration, ) -> Result<Duration, Error> { let cur = current_time(); if cur - last > stats_timeout { // Default no introspection implmentation #[cfg(not(feature = "introspection"))] manager.fire( state, Event::UpdateStats { executions: *state.executions(), time: cur, phantom: PhantomData, }, )?; // If performance stats are requested, fire the `UpdatePerfStats` event #[cfg(feature = "introspection")] { state .introspection_stats_mut() .set_current_time(crate::bolts::cpu::read_time_counter()); // Send the current stats over to the manager. This `.clone` shouldn't be // costly as `ClientPerfStats` impls `Copy` since it only contains `u64`s manager.fire( state, Event::UpdatePerfStats { executions: *state.executions(), time: cur, introspection_stats: Box::new(*state.introspection_stats()), phantom: PhantomData, }, )?; } Ok(cur) } else { if cur.as_millis() % 1000 == 0 {} Ok(last) } } fn fuzz_one( &mut self, stages: &mut ST, executor: &mut E, state: &mut S, manager: &mut EM, ) -> Result<usize, Error> { // Init timer for scheduler #[cfg(feature = "introspection")] state.introspection_stats_mut().start_timer(); // Get the next index from the scheduler let idx = self.scheduler.next(state)?; // Mark the elapsed time for the scheduler #[cfg(feature = "introspection")] state.introspection_stats_mut().mark_scheduler_time(); // Mark the elapsed time for the scheduler #[cfg(feature = "introspection")] state.introspection_stats_mut().reset_stage_index(); // Execute all stages stages.perform_all(self, executor, state, manager, idx)?; // Init timer for manager #[cfg(feature = "introspection")] state.introspection_stats_mut().start_timer(); // Execute the manager manager.process(self, state, executor)?; // Mark the elapsed time for the manager #[cfg(feature = "introspection")] state.introspection_stats_mut().mark_manager_time(); Ok(idx) } } impl<C, CS, F, I, OF, OT, S, SC> StdFuzzer<C, CS, F, I, OF, OT, S, SC> where CS: CorpusScheduler<I, S>, F: Feedback<I, S>, I: Input, OF: Feedback<I, S>, S: HasExecutions + HasClientPerfStats, { /// Create a new `StdFuzzer` with standard behavior. pub fn new(scheduler: CS, feedback: F, objective: OF) -> Self { Self { scheduler, feedback, objective, phantom: PhantomData, } } /// Runs the input and triggers observers and feedback pub fn execute_input<E, EM>( &mut self, state: &mut S, executor: &mut E, event_mgr: &mut EM, input: &I, ) -> Result<ExecuteInputResult, Error> where E: Executor<EM, I, S, Self> + HasObservers<OT> + HasObserversHooks<EM, I, OT, S, Self>, OT: ObserversTuple + HasExecHooksTuple<EM, I, S, Self>, EM: EventManager<E, I, S, Self>, { start_timer!(state); executor.pre_exec_observers(self, state, event_mgr, input)?; mark_feature_time!(state, PerfFeature::PreExecObservers); start_timer!(state); let exit_kind = executor.run_target(self, state, event_mgr, input)?; mark_feature_time!(state, PerfFeature::TargetExecution); *state.executions_mut() += 1; start_timer!(state); executor.post_exec_observers(self, state, event_mgr, input)?; mark_feature_time!(state, PerfFeature::PostExecObservers); let observers = executor.observers(); start_timer!(state); let is_solution = self .objective_mut() .is_interesting(state, event_mgr, input, observers, &exit_kind)?; mark_feature_time!(state, PerfFeature::GetObjectivesInterestingAll); if is_solution { return Ok(ExecuteInputResult::Solution); } #[cfg(not(feature = "introspection"))] let is_interesting = self .feedback_mut() .is_interesting(state, event_mgr, &input, observers, &exit_kind)?; #[cfg(feature = "introspection")] let is_interesting = { // Init temporary feedback stats here. We can't use the typical pattern above // since we need a `mut self` for `feedbacks_mut`, so we can't also hand a // new `mut self` to `is_interesting_with_perf`. We use this stack // variable to get the stats and then update the feedbacks directly let mut feedback_stats = [0_u64; crate::stats::NUM_FEEDBACKS]; let feedback_index = 0; let is_interesting = self.feedback_mut().is_interesting_with_perf( state, event_mgr, input, observers, &exit_kind, &mut feedback_stats, feedback_index, )?; // Update the feedback stats state .introspection_stats_mut() .update_feedbacks(feedback_stats); // Return the total fitness is_interesting }; if is_interesting { Ok(ExecuteInputResult::Interesting) } else { Ok(ExecuteInputResult::None) } } }
#[allow(unused_imports)] use super::prelude::*; type Input = Vec<((i32, i32), u32)>; pub fn input_generator(input: &str) -> Input { let mut paths = Vec::new(); for line in input.lines() { let mut current = (0i32, 0i32); let mut points = HashMap::new(); let mut distance = 0u32; for segment in line.split(',') { let delta = match segment.chars().next() { Some('R') => (1, 0), Some('L') => (-1, 0), Some('U') => (0, 1), Some('D') => (0, -1), _ => panic!("Invalid input") }; let length: usize = segment[1..].parse().expect("Cannot parse number in input"); for _ in 0..length { distance += 1; current = (current.0 + delta.0, current.1 + delta.1); points.entry(current).or_insert(distance); } } paths.push(points); } if paths.len() != 2 { panic!("Input has a wrong number of paths"); } let second_path = paths.remove(1); let first_path = paths.remove(0); first_path.into_iter() .filter_map(move |(k, v1)| second_path.get(&k).map(|v2| (k, v1 + v2))) .collect() } pub fn part1(input: &Input) -> u32 { let intersections = input; intersections.iter() .map(|((x, y), _)| (x.abs() + y.abs()) as u32) .min() .expect("There are no intersections in the paths") } pub fn part2(input: &Input) -> u32 { let intersections = input; intersections.iter() .map(|(_, v)| *v) .min() .expect("There are no intersections in the paths") }
// ANCHOR: struct #[derive(Serialize, Deserialize, Debug)] pub struct BlogPost { pub title: String, pub body: String, pub category: Option<String>, } // ANCHOR_END: struct // ANCHOR: view pub trait BlogPostsByCategory { type Collection = BlogPost; type Key = Option<String>; type Value = u32; fn map(&self, document: &Document<'_>) -> MapResult<Self::Key, Self::Value> { let post = document.contents::<BlogPost>()?; Ok(Some(document.emit_key_and_value(post.category.clone(), 1))) } fn reduce( &self, mappings: &[MappedValue<Self::Key, Self::Value>], _rereduce: bool, ) -> Result<Self::Value, Error> { Ok(mappings.iter().map(|mapping| mapping.value).sum()) } } // ANCHOR_END: view #[tokio::main] async fn main() -> Result<(), Error> { let db = Database::<BlogPost>::open_local("example.bonsaidb", &Configuration::default()).await?; // ANCHOR: query_with_docs let rust_posts = db .view::<BlogPostsByCategory>() .with_key(Some(String::from("Rust"))) .query_with_docs().await?; // ANCHOR_END: query_with_docs // ANCHOR: reduce_one_key let rust_post_count = db .view::<BlogPostsByCategory>() .with_key(Some(String::from("Rust"))) .reduce().await?; // ANCHOR_END: reduce_one_key // ANCHOR: reduce_multiple_keys let total_post_count = db .view::<BlogPostsByCategory>() .reduce().await?; // ANCHOR_END: reduce_multiple_keys Ok(()) }
use std::{ fmt::{Display, Formatter}, io::{BufWriter, ErrorKind, Read}, io, net::{SocketAddr, TcpListener, TcpStream}, sync::mpsc::{channel, Receiver, Sender, SendError, TryRecvError}, thread::{JoinHandle, sleep}, time::Duration, }; use crate::{ Direction::{Inbound, Outbound}, Direction, networked_message::NetworkedMessage, }; use crate::node::{Incoming, Outgoing}; use crate::spawn_with_name; #[derive(Debug)] pub struct Connection { addr: SocketAddr, thread: JoinHandle<io::Result<()>>, sender: Sender<NetworkedMessage>, direction: Direction, } impl Connection { fn send(&self, message: NetworkedMessage) -> Result<(), SendError<NetworkedMessage>> { self.sender.send(message) } } impl PartialEq for Connection { fn eq(&self, other: &Self) -> bool { self.addr == other.addr } } impl Display for Connection { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "({}, {})", self.addr, self.direction) } } /// Handles sending and receiving messages, but leaves the business logic to the `node`. pub struct Networking { connections: Vec<Connection>, sender: Sender<Incoming>, receiver: Receiver<Outgoing>, listener: TcpListener, } impl Networking { pub fn new( addr: SocketAddr, sender: Sender<Incoming>, receiver: Receiver<Outgoing>, ) -> Networking { let listener = TcpListener::bind(addr).unwrap(); listener.set_nonblocking(true).unwrap(); Networking { connections: vec![], sender, receiver, listener } } pub fn process(&mut self) { // Accept new connections loop { match self.accept() { Ok(addr) => self.sender.send(Incoming::ConnectionEstablished(addr)).unwrap(), Err(e) if e.kind() == ErrorKind::WouldBlock => break, Err(error) => panic!("Error when accepting listeners: {}", error), } } // Send queued messages loop { match self.receiver.try_recv() { Ok(Outgoing::Connect(addr)) => { match self.connect(addr) { Ok(addr) => self.sender.send(Incoming::ConnectionEstablished(addr)).unwrap(), Err(error) => eprintln!("Failed to connect to {}: {}", addr, error) } } Ok(Outgoing::Send(addr, message)) => self.send(addr, message), Ok(Outgoing::Forward(from, message)) => self.forward(from, message), Ok(Outgoing::Broadcast(message)) => self.broadcast(message), Err(TryRecvError::Empty) => break, Err(TryRecvError::Disconnected) => break, } } } pub fn accept(&mut self) -> Result<SocketAddr, io::Error> { let (stream, _) = self.listener.accept()?; let incoming_message_sender = self.sender.clone(); self.accept_connection(stream, incoming_message_sender, Inbound) } pub fn connect(&mut self, addr: SocketAddr) -> Result<SocketAddr, io::Error> { if self.is_connected(addr) { todo!() } eprintln!("Connecting to {}", addr); let sender = self.sender.clone(); let stream = TcpStream::connect(addr)?; self.accept_connection(stream, sender, Outbound) } fn accept_connection(&mut self, stream: TcpStream, node_sender: Sender<Incoming>, direction: Direction) -> Result<SocketAddr, io::Error> { stream.set_nonblocking(true)?; let remote_addr = stream.peer_addr()?; let local_addr = stream.local_addr()?; eprintln!("connection: them {}, us {}", remote_addr, local_addr); let (connection_sender, connection_receiver) = channel::<NetworkedMessage>(); let connection_thread = spawn_with_name("connection", move || -> io::Result<()> { let mut writer = BufWriter::new(&stream); 'main: loop { let mut buffer = vec![0; 1]; 'stream_events: loop { match Read::read(&mut (&stream), &mut buffer) { Ok(0) => { // connection closed break 'stream_events; } Ok(1) => { let message = NetworkedMessage::receive(&stream, buffer[0]).unwrap(); node_sender.send(Incoming::Message(remote_addr, message)).unwrap(); } Ok(count) => panic!("Read more bytes than the size of the buffer {}", count), Err(error) if error.kind() == ErrorKind::WouldBlock => { break 'stream_events; } Err(error) => panic!("error reading {:?}", error), } } 'channel_events: loop { match connection_receiver.try_recv() { Ok(message) => { if let Err(error) = message.send(&mut writer) { eprintln!("Connection closed {}->{}: {}", local_addr, remote_addr, error); break 'main; } } Err(TryRecvError::Empty) => break 'channel_events, Err(TryRecvError::Disconnected) => { eprintln!("Quitting connection thread {}->{}", local_addr, remote_addr); break 'main; } } } // TODO: Replace with something smarter and OS dependant sleep(Duration::from_millis(10)); } Ok(()) }); self.connections.push(Connection { addr: remote_addr, thread: connection_thread, sender: connection_sender, direction, }); Ok(remote_addr) } pub fn is_connected(&self, addr: SocketAddr) -> bool { return self.connections.iter().any(|c| c.addr == addr); } /// Sends a message to a single connection pub fn send(&mut self, to: SocketAddr, message: NetworkedMessage) { let sender = self.sender.clone(); self.connections.retain(|connection| { if connection.addr != to { return true; } if let Err(error) = connection.send(message.clone()) { eprintln!("Connection closed {}: {}", connection.addr, error); sender.send(Incoming::ConnectionClosed(connection.addr)).unwrap(); false } else { true } }); } /// Sends a message to all connections, except the original sender pub fn forward(&mut self, except: SocketAddr, message: NetworkedMessage) { let sender = self.sender.clone(); self.connections.retain(|connection| { if connection.addr == except { return true; } if let Err(error) = connection.send(message.clone()) { eprintln!("Connection closed {}: {}", connection.addr, error); sender.send(Incoming::ConnectionClosed(connection.addr)).unwrap(); false } else { true } }); } /// Sends a message to all connections pub fn broadcast(&mut self, message: NetworkedMessage) { let sender = self.sender.clone(); self.connections.retain(|connection| { if let Err(error) = connection.send(message.clone()) { eprintln!("Connection closed {}: {}", connection.addr, error); sender.send(Incoming::ConnectionClosed(connection.addr)).unwrap(); false } else { true } }); } pub fn close(&mut self) { // todo!() // let threads: Vec<JoinHandle<io::Result<()>>> = self.connections.into_iter().map(|c| c.thread).collect(); // self.connections.clear(); // for thread in threads { thread.join().unwrap(); } } }
#[doc = "Register `APB3LPENR` reader"] pub type R = crate::R<APB3LPENR_SPEC>; #[doc = "Register `APB3LPENR` writer"] pub type W = crate::W<APB3LPENR_SPEC>; #[doc = "Field `SBSLPEN` reader - SBS clock enable during sleep mode Set and reset by software."] pub type SBSLPEN_R = crate::BitReader; #[doc = "Field `SBSLPEN` writer - SBS clock enable during sleep mode Set and reset by software."] pub type SBSLPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SPI5LPEN` reader - SPI5 clock enable during Slsleepeep mode Set and reset by software."] pub type SPI5LPEN_R = crate::BitReader; #[doc = "Field `SPI5LPEN` writer - SPI5 clock enable during Slsleepeep mode Set and reset by software."] pub type SPI5LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPUART1LPEN` reader - LPUART1 clock enable during sleep mode Set and reset by software."] pub type LPUART1LPEN_R = crate::BitReader; #[doc = "Field `LPUART1LPEN` writer - LPUART1 clock enable during sleep mode Set and reset by software."] pub type LPUART1LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `I2C3LPEN` reader - I2C3 clock enable during sleep mode Set and reset by software."] pub type I2C3LPEN_R = crate::BitReader; #[doc = "Field `I2C3LPEN` writer - I2C3 clock enable during sleep mode Set and reset by software."] pub type I2C3LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `I2C4LPEN` reader - I2C4 clock enable during sleep mode Set and reset by software."] pub type I2C4LPEN_R = crate::BitReader; #[doc = "Field `I2C4LPEN` writer - I2C4 clock enable during sleep mode Set and reset by software."] pub type I2C4LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPTIM1LPEN` reader - LPTIM1 clock enable during sleep mode Set and reset by software."] pub type LPTIM1LPEN_R = crate::BitReader; #[doc = "Field `LPTIM1LPEN` writer - LPTIM1 clock enable during sleep mode Set and reset by software."] pub type LPTIM1LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPTIM3LPEN` reader - LPTIM3 clock enable during sleep mode Set and reset by software."] pub type LPTIM3LPEN_R = crate::BitReader; #[doc = "Field `LPTIM3LPEN` writer - LPTIM3 clock enable during sleep mode Set and reset by software."] pub type LPTIM3LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPTIM4LPEN` reader - LPTIM4 clock enable during sleep mode Set and reset by software."] pub type LPTIM4LPEN_R = crate::BitReader; #[doc = "Field `LPTIM4LPEN` writer - LPTIM4 clock enable during sleep mode Set and reset by software."] pub type LPTIM4LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPTIM5LPEN` reader - LPTIM5 clock enable during sleep mode Set and reset by software."] pub type LPTIM5LPEN_R = crate::BitReader; #[doc = "Field `LPTIM5LPEN` writer - LPTIM5 clock enable during sleep mode Set and reset by software."] pub type LPTIM5LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPTIM6LPEN` reader - LPTIM6 clock enable during sleep mode Set and reset by software."] pub type LPTIM6LPEN_R = crate::BitReader; #[doc = "Field `LPTIM6LPEN` writer - LPTIM6 clock enable during sleep mode Set and reset by software."] pub type LPTIM6LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `VREFLPEN` reader - VREF clock enable during sleep mode Set and reset by software."] pub type VREFLPEN_R = crate::BitReader; #[doc = "Field `VREFLPEN` writer - VREF clock enable during sleep mode Set and reset by software."] pub type VREFLPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RTCAPBLPEN` reader - RTC APB interface clock enable during sleep mode Set and reset by software."] pub type RTCAPBLPEN_R = crate::BitReader; #[doc = "Field `RTCAPBLPEN` writer - RTC APB interface clock enable during sleep mode Set and reset by software."] pub type RTCAPBLPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 1 - SBS clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn sbslpen(&self) -> SBSLPEN_R { SBSLPEN_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 5 - SPI5 clock enable during Slsleepeep mode Set and reset by software."] #[inline(always)] pub fn spi5lpen(&self) -> SPI5LPEN_R { SPI5LPEN_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - LPUART1 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn lpuart1lpen(&self) -> LPUART1LPEN_R { LPUART1LPEN_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - I2C3 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn i2c3lpen(&self) -> I2C3LPEN_R { I2C3LPEN_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - I2C4 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn i2c4lpen(&self) -> I2C4LPEN_R { I2C4LPEN_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 11 - LPTIM1 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn lptim1lpen(&self) -> LPTIM1LPEN_R { LPTIM1LPEN_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - LPTIM3 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn lptim3lpen(&self) -> LPTIM3LPEN_R { LPTIM3LPEN_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - LPTIM4 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn lptim4lpen(&self) -> LPTIM4LPEN_R { LPTIM4LPEN_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - LPTIM5 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn lptim5lpen(&self) -> LPTIM5LPEN_R { LPTIM5LPEN_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - LPTIM6 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn lptim6lpen(&self) -> LPTIM6LPEN_R { LPTIM6LPEN_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bit 20 - VREF clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn vreflpen(&self) -> VREFLPEN_R { VREFLPEN_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - RTC APB interface clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn rtcapblpen(&self) -> RTCAPBLPEN_R { RTCAPBLPEN_R::new(((self.bits >> 21) & 1) != 0) } } impl W { #[doc = "Bit 1 - SBS clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn sbslpen(&mut self) -> SBSLPEN_W<APB3LPENR_SPEC, 1> { SBSLPEN_W::new(self) } #[doc = "Bit 5 - SPI5 clock enable during Slsleepeep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn spi5lpen(&mut self) -> SPI5LPEN_W<APB3LPENR_SPEC, 5> { SPI5LPEN_W::new(self) } #[doc = "Bit 6 - LPUART1 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn lpuart1lpen(&mut self) -> LPUART1LPEN_W<APB3LPENR_SPEC, 6> { LPUART1LPEN_W::new(self) } #[doc = "Bit 7 - I2C3 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn i2c3lpen(&mut self) -> I2C3LPEN_W<APB3LPENR_SPEC, 7> { I2C3LPEN_W::new(self) } #[doc = "Bit 8 - I2C4 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn i2c4lpen(&mut self) -> I2C4LPEN_W<APB3LPENR_SPEC, 8> { I2C4LPEN_W::new(self) } #[doc = "Bit 11 - LPTIM1 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn lptim1lpen(&mut self) -> LPTIM1LPEN_W<APB3LPENR_SPEC, 11> { LPTIM1LPEN_W::new(self) } #[doc = "Bit 12 - LPTIM3 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn lptim3lpen(&mut self) -> LPTIM3LPEN_W<APB3LPENR_SPEC, 12> { LPTIM3LPEN_W::new(self) } #[doc = "Bit 13 - LPTIM4 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn lptim4lpen(&mut self) -> LPTIM4LPEN_W<APB3LPENR_SPEC, 13> { LPTIM4LPEN_W::new(self) } #[doc = "Bit 14 - LPTIM5 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn lptim5lpen(&mut self) -> LPTIM5LPEN_W<APB3LPENR_SPEC, 14> { LPTIM5LPEN_W::new(self) } #[doc = "Bit 15 - LPTIM6 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn lptim6lpen(&mut self) -> LPTIM6LPEN_W<APB3LPENR_SPEC, 15> { LPTIM6LPEN_W::new(self) } #[doc = "Bit 20 - VREF clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn vreflpen(&mut self) -> VREFLPEN_W<APB3LPENR_SPEC, 20> { VREFLPEN_W::new(self) } #[doc = "Bit 21 - RTC APB interface clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn rtcapblpen(&mut self) -> RTCAPBLPEN_W<APB3LPENR_SPEC, 21> { RTCAPBLPEN_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 = "RCC APB4 sleep clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb3lpenr::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 [`apb3lpenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct APB3LPENR_SPEC; impl crate::RegisterSpec for APB3LPENR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`apb3lpenr::R`](R) reader structure"] impl crate::Readable for APB3LPENR_SPEC {} #[doc = "`write(|w| ..)` method takes [`apb3lpenr::W`](W) writer structure"] impl crate::Writable for APB3LPENR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets APB3LPENR to value 0x0030_f9e2"] impl crate::Resettable for APB3LPENR_SPEC { const RESET_VALUE: Self::Ux = 0x0030_f9e2; }
use crate::config::dfinity::Config; use crate::lib::builders::{ BuildConfig, BuildOutput, BuilderPool, CanisterBuilder, IdlBuildOutput, WasmBuildOutput, }; use crate::lib::canister_info::CanisterInfo; use crate::lib::environment::Environment; use crate::lib::error::{BuildError, DfxError, DfxResult}; use crate::lib::models::canister_id_store::CanisterIdStore; use crate::util::{assets, check_candid_file}; use anyhow::anyhow; use ic_types::principal::Principal as CanisterId; use petgraph::graph::{DiGraph, NodeIndex}; use rand::{thread_rng, RngCore}; use slog::Logger; use std::cell::RefCell; use std::collections::BTreeMap; use std::convert::TryFrom; use std::io::Read; use std::path::Path; use std::sync::Arc; /// Represents a canister from a DFX project. It can be a virtual Canister. /// Multiple canister instances can have the same info, but would be differentiated /// by their IDs. /// Once an instance of a canister is built it is immutable. So for comparing /// two canisters one can use their ID. pub struct Canister { info: CanisterInfo, builder: Arc<dyn CanisterBuilder>, output: RefCell<Option<BuildOutput>>, } impl Canister { /// Create a new canister. /// This can only be done by a CanisterPool. pub(super) fn new(info: CanisterInfo, builder: Arc<dyn CanisterBuilder>) -> Self { Self { info, builder, output: RefCell::new(None), } } pub fn prebuild(&self, pool: &CanisterPool, build_config: &BuildConfig) -> DfxResult { self.builder.prebuild(pool, &self.info, build_config) } pub fn build( &self, pool: &CanisterPool, build_config: &BuildConfig, ) -> DfxResult<&BuildOutput> { let output = self.builder.build(pool, &self.info, build_config)?; // Ignore the old output, and return a reference. let _ = self.output.replace(Some(output)); Ok(self.get_build_output().unwrap()) } pub fn postbuild(&self, pool: &CanisterPool, build_config: &BuildConfig) -> DfxResult { self.builder.postbuild(pool, &self.info, build_config) } pub fn get_name(&self) -> &str { self.info.get_name() } pub fn canister_id(&self) -> CanisterId { self.info.get_canister_id().unwrap() } // this function is only ever used when build_config.build_mode_check is true pub fn generate_random_canister_id() -> DfxResult<CanisterId> { let mut rng = thread_rng(); let mut v: Vec<u8> = std::iter::repeat(0u8).take(8).collect(); rng.fill_bytes(v.as_mut_slice()); Ok(CanisterId::try_from(v)?) } /// Get the build output of a build process. If the output isn't known at this time, /// will return [None]. pub fn get_build_output(&self) -> Option<&BuildOutput> { unsafe { (&*self.output.as_ptr()).as_ref() } } } /// A canister pool is a list of canisters. pub struct CanisterPool { canisters: Vec<Arc<Canister>>, logger: Logger, } struct PoolConstructHelper<'a> { config: &'a Config, builder_pool: BuilderPool, canister_id_store: CanisterIdStore, generate_cid: bool, canisters_map: &'a mut Vec<Arc<Canister>>, } impl CanisterPool { fn insert(canister_name: &str, pool_helper: &mut PoolConstructHelper<'_>) -> DfxResult<()> { let canister_id = match pool_helper.canister_id_store.find(canister_name) { Some(canister_id) => Some(canister_id), None if pool_helper.generate_cid => Some(Canister::generate_random_canister_id()?), _ => None, }; let info = CanisterInfo::load(pool_helper.config, canister_name, canister_id)?; if let Some(builder) = pool_helper.builder_pool.get(&info) { pool_helper .canisters_map .insert(0, Arc::new(Canister::new(info, builder))); Ok(()) } else { Err(anyhow!( "Cannot find builder for canister '{}'.", info.get_name().to_string() )) } } pub fn load( env: &dyn Environment, generate_cid: bool, canister_names: &[String], ) -> DfxResult<Self> { let logger = env.get_logger().new(slog::o!()); let config = env .get_config() .ok_or_else(|| anyhow!("Cannot find dfx configuration file in the current working directory. Did you forget to create one?"))?; let mut canisters_map = Vec::new(); let mut pool_helper = PoolConstructHelper { config: &config, builder_pool: BuilderPool::new(env)?, canister_id_store: CanisterIdStore::for_env(env)?, generate_cid, canisters_map: &mut canisters_map, }; for canister_name in canister_names { CanisterPool::insert(canister_name, &mut pool_helper)?; } Ok(CanisterPool { canisters: canisters_map, logger, }) } pub fn get_canister(&self, canister_id: &CanisterId) -> Option<&Canister> { for c in &self.canisters { let info = &c.info; if Some(canister_id) == info.get_canister_id().ok().as_ref() { return Some(c); } } None } pub fn get_canister_list(&self) -> Vec<&Canister> { self.canisters.iter().map(|c| c.as_ref()).collect() } pub fn get_canister_info(&self, canister_id: &CanisterId) -> Option<&CanisterInfo> { self.get_canister(canister_id).map(|c| &c.info) } pub fn get_first_canister_with_name(&self, name: &str) -> Option<Arc<Canister>> { for c in &self.canisters { if c.info.get_name() == name { return Some(Arc::clone(c)); } } None } pub fn get_logger(&self) -> &Logger { &self.logger } fn build_dependencies_graph(&self) -> DfxResult<DiGraph<CanisterId, ()>> { let mut graph: DiGraph<CanisterId, ()> = DiGraph::new(); let mut id_set: BTreeMap<CanisterId, NodeIndex<u32>> = BTreeMap::new(); // Add all the canisters as nodes. for canister in &self.canisters { let canister_id = canister.info.get_canister_id()?; id_set.insert(canister_id.clone(), graph.add_node(canister_id.clone())); } // Add all the edges. for canister in &self.canisters { let canister_id = canister.canister_id(); let canister_info = &canister.info; let deps = canister.builder.get_dependencies(self, canister_info)?; if let Some(node_ix) = id_set.get(&canister_id) { for d in deps { if let Some(dep_ix) = id_set.get(&d) { graph.add_edge(*node_ix, *dep_ix, ()); } } } } // Verify the graph has no cycles. if let Err(err) = petgraph::algo::toposort(&graph, None) { let message = match graph.node_weight(err.node_id()) { Some(canister_id) => match self.get_canister_info(canister_id) { Some(info) => info.get_name().to_string(), None => format!("<{}>", canister_id.to_text()), }, None => "<Unknown>".to_string(), }; Err(DfxError::new(BuildError::DependencyError(format!( "Found circular dependency: {}", message )))) } else { Ok(graph) } } fn step_prebuild_all(&self, _build_config: &BuildConfig) -> DfxResult<()> { Ok(()) } fn step_prebuild(&self, build_config: &BuildConfig, canister: &Canister) -> DfxResult<()> { canister.prebuild(self, build_config) } fn step_build<'a>( &self, build_config: &BuildConfig, canister: &'a Canister, ) -> DfxResult<&'a BuildOutput> { canister.build(self, build_config) } fn step_postbuild( &self, build_config: &BuildConfig, canister: &Canister, build_output: &BuildOutput, ) -> DfxResult<()> { // Copy the WASM and IDL files to canisters/NAME/... let IdlBuildOutput::File(build_idl_path) = &build_output.idl; let idl_file_path = canister.info.get_build_idl_path(); if build_idl_path.ne(&idl_file_path) { std::fs::create_dir_all(idl_file_path.parent().unwrap())?; std::fs::copy(&build_idl_path, &idl_file_path) .map(|_| {}) .map_err(DfxError::from)?; let mut perms = std::fs::metadata(&idl_file_path)?.permissions(); perms.set_readonly(false); std::fs::set_permissions(&idl_file_path, perms)?; } let WasmBuildOutput::File(build_wasm_path) = &build_output.wasm; let wasm_file_path = canister.info.get_build_wasm_path(); if build_wasm_path.ne(&wasm_file_path) { std::fs::create_dir_all(wasm_file_path.parent().unwrap())?; std::fs::copy(&build_wasm_path, &wasm_file_path) .map(|_| {}) .map_err(DfxError::from)?; let mut perms = std::fs::metadata(&wasm_file_path)?.permissions(); perms.set_readonly(false); std::fs::set_permissions(&wasm_file_path, perms)?; } // And then create an canisters/IDL folder with canister DID files per canister ID. let idl_root = &build_config.idl_root; let canister_id = canister.canister_id(); let idl_file_path = idl_root.join(canister_id.to_text()).with_extension("did"); std::fs::create_dir_all(idl_file_path.parent().unwrap())?; std::fs::copy(&build_idl_path, &idl_file_path) .map(|_| {}) .map_err(DfxError::from)?; build_canister_js(&canister.canister_id(), &canister.info)?; canister.postbuild(self, build_config) } fn step_postbuild_all( &self, build_config: &BuildConfig, _order: &[CanisterId], ) -> DfxResult<()> { // We don't want to simply remove the whole directory, as in the future, // we may want to keep the IDL files downloaded from network. for canister in &self.canisters { let idl_root = &build_config.idl_root; let canister_id = canister.canister_id(); let idl_file_path = idl_root.join(canister_id.to_text()).with_extension("did"); // Ignore errors (e.g. File Not Found). let _ = std::fs::remove_file(idl_file_path); } Ok(()) } /// Build all canisters, returning a vector of results of each builds. pub fn build( &self, build_config: BuildConfig, ) -> DfxResult<Vec<Result<&BuildOutput, BuildError>>> { self.step_prebuild_all(&build_config) .map_err(|e| DfxError::new(BuildError::PreBuildAllStepFailed(Box::new(e))))?; let graph = self.build_dependencies_graph()?; let nodes = petgraph::algo::toposort(&graph, None).map_err(|cycle| { let message = match graph.node_weight(cycle.node_id()) { Some(canister_id) => match self.get_canister_info(canister_id) { Some(info) => info.get_name().to_string(), None => format!("<{}>", canister_id.to_text()), }, None => "<Unknown>".to_string(), }; BuildError::DependencyError(format!("Found circular dependency: {}", message)) })?; let order: Vec<CanisterId> = nodes .iter() .rev() // Reverse the order, as we have a dependency graph, we want to reverse indices. .map(|idx| graph.node_weight(*idx).unwrap().clone()) .collect(); let mut result = Vec::new(); for canister_id in &order { if let Some(canister) = self.get_canister(canister_id) { result.push( self.step_prebuild(&build_config, canister) .map_err(|e| { BuildError::PreBuildStepFailed(canister_id.clone(), Box::new(e)) }) .and_then(|_| { self.step_build(&build_config, canister).map_err(|e| { BuildError::BuildStepFailed(canister_id.clone(), Box::new(e)) }) }) .and_then(|o| { self.step_postbuild(&build_config, canister, o) .map_err(|e| { BuildError::PostBuildStepFailed( canister_id.clone(), Box::new(e), ) }) .map(|_| o) }), ); } } self.step_postbuild_all(&build_config, &order) .map_err(|e| DfxError::new(BuildError::PostBuildAllStepFailed(Box::new(e))))?; Ok(result) } /// Build all canisters, failing with the first that failed the build. Will return /// nothing if all succeeded. pub fn build_or_fail(&self, build_config: BuildConfig) -> DfxResult<()> { let outputs = self.build(build_config)?; for output in outputs { output.map_err(DfxError::new)?; } Ok(()) } } fn decode_path_to_str(path: &Path) -> DfxResult<&str> { path.to_str().ok_or_else(|| { DfxError::new(BuildError::JsBindGenError(format!( "Unable to convert output canister js path to a string: {:#?}", path ))) }) } /// Create a canister JavaScript DID and Actor Factory. fn build_canister_js(canister_id: &CanisterId, canister_info: &CanisterInfo) -> DfxResult { let output_did_js_path = canister_info.get_build_idl_path().with_extension("did.js"); let output_did_ts_path = canister_info.get_build_idl_path().with_extension("d.ts"); let output_canister_js_path = canister_info.get_build_idl_path().with_extension("js"); let (env, ty) = check_candid_file(&canister_info.get_build_idl_path())?; let content = candid::bindings::javascript::compile(&env, &ty); std::fs::write(output_did_js_path, content)?; let content = candid::bindings::typescript::compile(&env, &ty); std::fs::write(output_did_ts_path, content)?; let mut language_bindings = assets::language_bindings()?; for f in language_bindings.entries()? { let mut file = f?; let mut file_contents = String::new(); file.read_to_string(&mut file_contents)?; let new_file_contents = file_contents .replace("{canister_id}", &canister_id.to_text()) .replace("{canister_name}", &canister_info.get_name()); match decode_path_to_str(&file.path()?)? { "canister.js" => { std::fs::write( decode_path_to_str(&output_canister_js_path)?, new_file_contents, )?; } _ => unreachable!(), } } Ok(()) }
fn main() { let s1 = gives_ownership(); let s1_len = calculate_length(&s1); // does not take ownership of s1 println!("length of {} (s1): {}", s1, s1_len); // s1 can still be used! let s2 = String::from("hello"); let s3 = takes_and_gives_back(s2); takes_ownership(s3); // s3 was moved, ownership transferred to the scope of takes_ownership // trying to use s3 here would result in a compiler error // println!("{}", s3); // <-- compiler error let mut s4 = String::from("hello world"); let word1 = first_word(&s4[..]); // convert a string to a slice let word2 = first_word("cargo hello"); // string literals are slices! println!("first words are {}, and {}", word1, word2); // The following `s.clear()` would result in a compiler error. // If it were allowed, it would invalidate the string slice at // `word` above. // s.clear(); } fn gives_ownership() -> String { let some_string = String::from("hello"); some_string // &some_string would result in a dangling pointer, and the compiler would complain! } fn takes_and_gives_back(a_string: String) -> String { a_string } fn takes_ownership(some_string: String) { println!("{}", some_string); } // because we took ownership, some_string is deallocated once it goes out of scope // calculate length of input string without taking ownership of it fn calculate_length(s: &String) -> usize { s.len() } // Note that if first_word accepted &String instead of &str, // it would not accept string slices, and therefore would not // accept string literals fn first_word(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] }
use rand::Rng; #[cfg(feature = "parallel")] use rayon::prelude::*; use subspace_archiving::archiver::Archiver; use subspace_archiving::piece_reconstructor::{PiecesReconstructor, ReconstructorError}; use subspace_core_primitives::crypto::kzg::{embedded_kzg_settings, Kzg}; use subspace_core_primitives::objects::BlockObjectMapping; use subspace_core_primitives::{ArchivedHistorySegment, FlatPieces, Piece, RecordedHistorySegment}; fn pieces_to_option_of_pieces(pieces: &FlatPieces) -> Vec<Option<Piece>> { pieces.iter().map(Piece::from).map(Some).collect() } // Block that fits into the segment fully fn get_random_block() -> Vec<u8> { let mut block = vec![0u8; RecordedHistorySegment::SIZE]; rand::thread_rng().fill(block.as_mut_slice()); block } #[test] fn segment_reconstruction_works() { let kzg = Kzg::new(embedded_kzg_settings()); let mut archiver = Archiver::new(kzg.clone()).unwrap(); let block = get_random_block(); let archived_segments = archiver.add_block(block, BlockObjectMapping::default(), true); assert_eq!(archived_segments.len(), 1); let mut maybe_pieces = pieces_to_option_of_pieces(&archived_segments.first().unwrap().pieces); assert_eq!(maybe_pieces.len(), ArchivedHistorySegment::NUM_PIECES); // Remove some pieces from the array maybe_pieces .iter_mut() .skip(100) .take(30) .for_each(|piece| { piece.take(); }); let reconstructor = PiecesReconstructor::new(kzg).unwrap(); let flat_pieces = reconstructor.reconstruct_segment(&maybe_pieces).unwrap(); assert_eq!(flat_pieces.len(), ArchivedHistorySegment::NUM_PIECES); archived_segments .into_iter() .next() .unwrap() .pieces .iter() .zip(flat_pieces.iter()) .for_each(|(original_piece, reconstructed_piece)| { assert_eq!(original_piece, reconstructed_piece); }); } #[test] fn piece_reconstruction_works() { let kzg = Kzg::new(embedded_kzg_settings()); let mut archiver = Archiver::new(kzg.clone()).unwrap(); // Block that fits into the segment fully let block = get_random_block(); let archived_segments = archiver.add_block(block, BlockObjectMapping::default(), true); assert_eq!(archived_segments.len(), 1); let mut maybe_pieces = pieces_to_option_of_pieces(&archived_segments.first().unwrap().pieces); assert_eq!(maybe_pieces.len(), ArchivedHistorySegment::NUM_PIECES); // Remove some pieces from the vector let missing_pieces = maybe_pieces .iter_mut() .enumerate() .skip(100) .take(40) .map(|(piece_position, piece)| (piece_position, piece.take().unwrap())) .collect::<Vec<_>>(); let reconstructor = PiecesReconstructor::new(kzg).unwrap(); #[cfg(not(feature = "parallel"))] let iter = missing_pieces.iter(); #[cfg(feature = "parallel")] let iter = missing_pieces.par_iter(); let reconstructed_pieces = iter .map(|(missing_piece_position, _missing_piece)| { reconstructor .reconstruct_piece(&maybe_pieces, *missing_piece_position) .unwrap() }) .collect::<Vec<_>>(); for ((_, missing_piece), reconstructed_piece) in missing_pieces.iter().zip(&reconstructed_pieces) { assert_eq!(missing_piece, reconstructed_piece); } } #[test] fn segment_reconstruction_fails() { let kzg = Kzg::new(embedded_kzg_settings()); let reconstructor = PiecesReconstructor::new(kzg.clone()).unwrap(); let pieces = vec![None]; let result = reconstructor.reconstruct_segment(&pieces); assert!(result.is_err()); if let Err(error) = result { assert!(matches!( error, ReconstructorError::DataShardsReconstruction(..) )); } let mut archiver = Archiver::new(kzg).unwrap(); // Block that fits into the segment fully let block = get_random_block(); let archived_segments = archiver.add_block(block, BlockObjectMapping::default(), true); assert_eq!(archived_segments.len(), 1); let maybe_pieces = pieces_to_option_of_pieces(&archived_segments.first().unwrap().pieces); let result = reconstructor.reconstruct_piece(&maybe_pieces, 4000); assert!(result.is_err()); if let Err(error) = result { assert_eq!(error, ReconstructorError::IncorrectPiecePosition); } } #[test] fn piece_reconstruction_fails() { let kzg = Kzg::new(embedded_kzg_settings()); let reconstructor = PiecesReconstructor::new(kzg.clone()).unwrap(); let pieces = vec![None]; let result = reconstructor.reconstruct_piece(&pieces, 0); assert!(result.is_err()); if let Err(error) = result { assert!(matches!( error, ReconstructorError::DataShardsReconstruction(..) )); } let mut archiver = Archiver::new(kzg).unwrap(); // Block that fits into the segment fully let block = get_random_block(); let archived_segments = archiver.add_block(block, BlockObjectMapping::default(), true); assert_eq!(archived_segments.len(), 1); let maybe_pieces = pieces_to_option_of_pieces(&archived_segments.first().unwrap().pieces); let result = reconstructor.reconstruct_piece(&maybe_pieces, 4000); assert!(result.is_err()); if let Err(error) = result { assert_eq!(error, ReconstructorError::IncorrectPiecePosition); } }
//! Fearless [Concurrency] //! //! [concurrency]: https://doc.rust-lang.org/book/ch16-00-concurrency.html pub mod sec03;
use std::fs; use crate::poc::PocMap; use crate::prelude::*; use askama::Template; use structopt::StructOpt; #[derive(Debug, StructOpt, Template)] #[template(path = "new_poc.rs", escape = "none")] pub struct AddArgs { #[structopt(name = "crate", help = "target crate name")] krate: String, #[structopt( parse(try_from_str = semver::Version::parse), help = "target crate version" )] version: semver::Version, } pub fn cmd_add(args: AddArgs) -> Result<()> { let poc_map = PocMap::new()?; let new_poc_id = poc_map.next_empty_id(); let new_poc_name = format!("{}-{}", new_poc_id, args.krate); let new_poc_path = PROJECT_PATH.join(format!("poc/{}.rs", &new_poc_name)); // Create a new PoC file fs::write(&new_poc_path, args.render().unwrap()) .with_context(|| format!("Failed to write to {}", new_poc_path.display()))?; // Setup poc-debug directory let poc_map = PocMap::new()?; poc_map.prepare_poc_workspace(new_poc_id, PROJECT_PATH.join("poc-debug"))?; println!("Successfully added {}", new_poc_name); crate::cmd::update::update_readme()?; Ok(()) }
pub mod instruction; pub mod opcode;
use std::io::{self}; fn transform_input(file_content: &Vec<String>) -> Vec<usize> { let helper: Vec<usize> = file_content[0] .split(",") .collect::<Vec<_>>() .iter() .map(|x| x.parse::<usize>().unwrap()) .collect(); let mut state = vec![0; 9]; for el in helper { state[el] += 1; } state } fn do_day(state: &mut Vec<usize>) { let new_to_spawn = state[0]; for i in 1..state.len() { state[i - 1] = state[i]; } state[8] = new_to_spawn; state[6] += new_to_spawn; } fn do_n_days(state: &mut Vec<usize>, n_days: usize) { for _ in 0..n_days { do_day(state); } } fn part_1(file_content: &Vec<String>) -> usize { let mut state = transform_input(&file_content); do_n_days(&mut state, 80); state.iter().sum() } fn part_2(file_content: &Vec<String>) -> usize { let mut state = transform_input(&file_content); do_n_days(&mut state, 256); state.iter().sum() } fn main() -> io::Result<()> { let files_results = vec![ ("test.txt", 5934, 26984457539), ("input.txt", 366057, 1653559299811), ]; for (f, result_1, result_2) in files_results.into_iter() { println!("{}", f); let file_content: Vec<String> = std::fs::read_to_string(f)? .lines() .map(|x| x.to_string()) .collect(); let res_1 = part_1(&file_content); assert_eq!(res_1, result_1); let res_2 = part_2(&file_content); assert_eq!(res_2, result_2); } Ok(()) }
use std::fs; pub mod ast; pub mod text_tree; pub fn parse_file(filename: &str) -> Result<ast::Program, String> { let text = fs::read_to_string(filename).expect("failed to read file"); let parser = text_tree::ProgramParser::new(); dbg!(parser.parse(&text) .map_err(|e| e.to_string())) }
#[cfg(feature = "autoload")] pub mod autoload; pub mod sna;
#![allow(dead_code)] pub const ROUTE_RXPEN: u32 = 0x1 << 0; pub const ROUTE_TXPEN: u32 = 0x1 << 1; pub const ROUTE_CSPEN: u32 = 0x1 << 2; pub const ROUTE_CLKPEN: u32 = 0x1 << 3; pub const ROUTE_LOCATION_MASK: u32 = 0x700; pub const ROUTE_LOCATION_LOC0: u32 = 0x0 << 8; pub const ROUTE_LOCATION_LOC1: u32 = 0x1 << 8; pub const ROUTE_LOCATION_LOC2: u32 = 0x2 << 8; pub const ROUTE_LOCATION_LOC3: u32 = 0x3 << 8; pub const ROUTE_LOCATION_LOC4: u32 = 0x4 << 8; pub const ROUTE_LOCATION_LOC5: u32 = 0x5 << 8; pub const IEN_RXDATAV: u32 = 0x1 << 2; pub const IF_RXDATAV: u32 = 0x1 << 2; pub const IF_MASK: u32 = 0x00001FFF; // Usart status register pub const STATUS_RXDATAV: u32 = 0x1 << 7; pub const STATUS_TXBL: u32 = 0x1 << 6; use core::intrinsics::transmute; use core::default::Default; #[repr(C)] #[derive(Copy, Clone)] #[allow(non_snake_case)] pub struct Usart { pub CTRL: u32, pub FRAME: u32, pub TRIGCTRL: u32, pub CMD: u32, pub STATUS: u32, pub CLKDIV: u32, pub RXDATAX: u32, pub RXDATA: u32, pub RXDOUBLEX: u32, pub RXDOUBLE: u32, pub RXDATAXP: u32, pub RXDOUBLEXP: u32, pub TXDATAX: u32, pub TXDATA: u32, pub TXDOUBLEX: u32, pub TXDOUBLE: u32, pub IF: u32, pub IFS: u32, pub IFC: u32, pub IEN: u32, pub IRCTRL: u32, pub ROUTE: u32, pub INPUT: u32, pub I2SCTRL: u32, } impl Usart { #[inline] pub fn uart0() -> &'static mut Usart { unsafe { transmute(GET_UART0()) } } #[inline] pub fn uart1() -> &'static mut Usart { unsafe { transmute(GET_UART1()) } } #[inline] pub fn usart0() -> &'static mut Usart { unsafe { transmute(GET_USART0()) } } #[inline] pub fn usart1() -> &'static mut Usart { unsafe { transmute(GET_USART1()) } } #[inline] pub fn usart2() -> &'static mut Usart { unsafe { transmute(GET_USART2()) } } pub fn enable(&self, enable: Enable) { unsafe { USART_Enable(self, enable) } } pub fn init_async(&mut self, init: &InitAsync) { unsafe { USART_InitAsync(self, init) } } pub fn int_clear(&self, flags: u32) { unsafe { STATIC_INLINE_USART_IntClear(self, flags) } } pub fn int_enable(&self, flags: u32) { unsafe { STATIC_INLINE_USART_IntEnable(self, flags) } } pub fn tx(&self, val: u8) { unsafe { USART_Tx(self, val) } } pub fn rx(&self) -> u8 { unsafe { USART_Rx(self) } } } #[repr(C)] pub struct InitAsync { pub enable: Enable, pub ref_freq: u32, pub baudrate: u32, pub oversampling: OVS, pub databits: Databits, pub parity: Parity, pub stopbits: Stopbits, pub mv_dis: bool, pub prs_rx_enable: bool, pub prs_rx_ch: PrsRxCh, } impl Default for InitAsync { fn default() -> InitAsync { InitAsync { enable: Enable::Enable, ref_freq: 0, baudrate: 115200, oversampling: OVS::OVS16, databits: Databits::Databits8, parity: Parity::NoParity, stopbits: Stopbits::Stopbits1, mv_dis: false, prs_rx_enable: false, prs_rx_ch: PrsRxCh::Ch0, } } } #[repr(u8)] #[derive(Copy, Clone)] pub enum Enable { Disable = 0x0, Rx = 0x1 << 0, Tx = 0x1 << 2, Enable = (0x1 << 0) | (0x1 << 2), } #[repr(u8)] #[derive(Copy, Clone)] pub enum OVS { OVS16 = 0x0 << 5, OVS8 = 0x1 << 5, OVS6 = 0x2 << 5, OVS4 = 0x3 << 5, } #[repr(u8)] #[derive(Copy, Clone)] pub enum Databits { Databits4 = 0x1, Databits5 = 0x2, Databits6 = 0x3, Databits7 = 0x4, Databits8 = 0x5, Databits9 = 0x6, Databits10 = 0x7, Databits11 = 0x8, Databits12 = 0x9, Databits13 = 0xA, Databits14 = 0xB, Databits15 = 0xC, Databits16 = 0xD, } #[repr(u16)] #[derive(Copy, Clone)] pub enum Parity { NoParity = 0x0 << 8, EvenParity = 0x2 << 8, OddParity = 0x3 << 8, } #[repr(u16)] #[derive(Copy, Clone)] pub enum Stopbits { Stopbits0p5 = 0x0 << 12, Stopbits1 = 0x1 << 12, Stopbits1p5 = 0x2 << 12, Stopbits2 = 0x3 << 12, } #[repr(u8)] #[derive(Copy, Clone)] pub enum PrsRxCh { Ch0 = 0x0, Ch1 = 0x1, Ch2 = 0x2, Ch3 = 0x3, Ch4 = 0x4, Ch5 = 0x5, Ch6 = 0x6, Ch7 = 0x7, Ch8 = 0x8, Ch9 = 0x9, Ch10 = 0xA, Ch11 = 0xB, } #[link(name = "emlib")] extern { #[inline] fn GET_UART0() -> *mut Usart; #[inline] fn GET_UART1() -> *mut Usart; #[inline] fn GET_USART0() -> *mut Usart; #[inline] fn GET_USART1() -> *mut Usart; #[inline] fn GET_USART2() -> *mut Usart; #[inline] fn USART_InitAsync(usart: &Usart, init: &InitAsync); #[inline] fn USART_Rx(usart: &Usart) -> u8; #[inline] fn USART_Tx(usart: &Usart, data: u8); #[inline] fn USART_Enable(usart: &Usart, enable: Enable); #[inline] fn STATIC_INLINE_USART_IntClear(usart: &Usart, data: u32); #[inline] fn STATIC_INLINE_USART_IntEnable(usart: &Usart, data: u32); }
mod inventory; #[macro_use] extern crate prettytable; use std::error::Error; use std::{io, fmt}; use std::process; use std::fs::File; use serde::Deserialize; use prettytable::{Table, Cell}; use prettytable::format; use prettytable::format::Alignment; use crate::inventory::Inventory; use prettytable::{color}; use chrono::{NaiveDateTime}; use Alignment::RIGHT; use term::Attr::ForegroundColor; #[derive(Debug, Clone, Deserialize)] pub enum TradeType { BUY, SELL, DIV } impl fmt::Display for TradeType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { TradeType::BUY => write!(f, "BUY"), TradeType::SELL => write!(f, "SELL"), TradeType::DIV => write!(f, "DIV"), } } } #[derive(Debug, Clone, Deserialize)] pub struct TradingRecord { date: NaiveDateTime, #[serde(alias = "buy or sell")] buy_or_sell: TradeType, code: String, volume: u32, price: f32, fee: f32 } fn read_transactions() -> Result<(), Box<dyn Error>> { let mut inventory = Inventory::new(); let mut table = Table::new(); table.set_titles(row!["Date", "Trade", "Code", "Volume", "Price", "Fee", "Total", "Net Profit", "Fulfillment"]); let mut rdr = csv::Reader::from_reader(io::BufReader::new(File::open("trades.csv")?)); for result in rdr.deserialize() { let record: TradingRecord = result?; inventory.record_transaction(&record); } for t in inventory.consolidated_transactions().iter() { let mut row = row![t.date.format("%Y-%m-%d"), t.trade_type, t.code]; row.add_cell(Cell::new_align(&t.quantity.to_string(), RIGHT)); row.add_cell(Cell::new_align(&format!("{:.3}", t.price), RIGHT)); match t.trade_type { TradeType::BUY => { row.add_cell(Cell::new_align(&format!("{:.2}", t.fee), RIGHT)); row.add_cell(Cell::new_align(&format!("-{:.2}", t.amount_settled), RIGHT)); row.add_cell(Cell::new("")); table.add_row(row); } TradeType::SELL => { row.add_cell(Cell::new_align(&format!("{:.2}", t.fee), RIGHT)); row.add_cell(Cell::new_align(&format!("{:.2}", t.amount_settled), RIGHT)); let mut cell = Cell::new_align(&format!("{:.2}", t.net_profit), RIGHT); if t.net_profit >= 0.0 { cell = cell.with_style(ForegroundColor(color::GREEN)); } else { cell = cell.with_style(ForegroundColor(color::RED)); } row.add_cell(cell); let mut fulfill_table = Table::new(); fulfill_table.set_titles(row!["Qty", "Purchase Price", "Diff %", "Fees", "Net Profit", "Acquired Duration"]); let fulfill_table_format = format::FormatBuilder::from(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR) .separators(&[format::LinePosition::Bottom], format::LineSeparator::new('=', '=', '+', '+')).build(); fulfill_table.set_format(fulfill_table_format); for f in t.fulfillments.as_ref().unwrap() { let mut row = row![]; row.add_cell(Cell::new_align(&f.quantity.to_string(), RIGHT)); row.add_cell(Cell::new_align(&format!("{:.3}", f.purchase_price), RIGHT)); row.add_cell(Cell::new_align(&format!("{:.1}", (t.price - f.purchase_price) / f.purchase_price * 100.0), RIGHT)); row.add_cell(Cell::new_align(&format!("{:.2}", f.purchase_fee + f.selling_fee), RIGHT)); row.add_cell(Cell::new_align(&format!("{:.2}", f.profit), RIGHT)); row.add_cell(Cell::new_align(&format!("{} days", f.acquired_duration.num_days()), RIGHT)); fulfill_table.add_row(row); } row.add_cell(Cell::new(&fulfill_table.to_string())); table.add_row(row); } TradeType::DIV => { row.add_cell(Cell::new("")); row.add_cell(Cell::new_align(&format!("{:.2}", t.amount_settled), RIGHT)); row.add_cell(Cell::new_align(&format!("{:.2}", t.net_profit), RIGHT).with_style(ForegroundColor(color::GREEN))); table.add_row(row); } } } table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE); table.printstd(); for (fy, profit) in inventory.fy_profit_map { println!("{}: {:.2}", fy, profit); } Ok(()) } fn main() { if let Err(err) = read_transactions() { println!("error running example: {}", err); process::exit(1); } }
//! Strategies for merging disk-resident sorted runs of data. mod leveled; mod size_tiered; pub use self::leveled::LeveledStrategy; pub use self::size_tiered::SizeTieredStrategy; use lsm_tree::{Result, SSTable, SSTableValue}; use std::path::Path; /// An iterator for the disk-resident data. pub type CompactionIter<T, U> = Iterator<Item = Result<(T, U)>>; /// Trait for types that have compaction logic for disk-resident data. /// /// A compaction strategy should incrementally accept SSTables and handle the logic for creating /// new SSTables, deleting stale SSTables, and searching through current SSTables. pub trait CompactionStrategy<T, U> { /// Returns the path of the disk-resident data. fn get_path(&self) -> &Path; /// Returns the maximum size of the in-memory tree in bytes. fn get_max_in_memory_size(&self) -> u64; /// Returns and increments the current logical time of the compaction strategy. fn get_and_increment_logical_time(&mut self) -> Result<u64>; /// Adds a SSTable to the compaction strategy and compacts the SSTables being tracked, if /// needed. fn try_compact(&mut self, sstable: SSTable<T, U>) -> Result<()>; /// Waits until the current compaction thread, if any, terminates and updates the metadata of /// the compaction strategy. fn flush(&mut self) -> Result<()>; /// Searches through disk-resident data and returns the value associated with a particular key. /// It will return `None` if the key does not exist in the disk-resident data. fn get(&mut self, key: &T) -> Result<Option<SSTableValue<U>>>; /// Returns the approximate number of items in the disk-resident data. fn len_hint(&mut self) -> Result<usize>; /// Returns the number of items in the disk-resident data. fn len(&mut self) -> Result<usize>; /// Returns `true` if the disk-resident data is empty. fn is_empty(&mut self) -> Result<bool>; /// Clears the disk-resident data, removing all values. fn clear(&mut self) -> Result<()>; /// Returns the minimum key of the disk-resident data. Returns `None` if the disk-resident data /// is empty. fn min(&mut self) -> Result<Option<T>>; /// Returns the maximum key of the disk-resident data. Returns `None` if the disk-resident data /// is empty. fn max(&mut self) -> Result<Option<T>>; /// Returns an iterator over the disk-resident data. The iterator will yield key-value pairs /// in ascending order. fn iter(&mut self) -> Result<Box<CompactionIter<T, U>>>; }
#[macro_use] extern crate cpython; use cpython::{Python, PyResult}; /// This will generate a method named PyInit_hello which will be called when /// Python loads the library. The actual name should be PyInit_<library> /// where <library> is the library name. For example if your library is named /// lab3 then you would replace PyInit_hello with PyInit_lab3. The second /// and third arguments are the same. /// /// The py_fn! macro takes the Python object, a method, and the arguments to /// the method, and generates the glue code to allow Python to call the function. /// /// `m.add()` takes a Python object, a method name, and a function, and adds the /// function to the module. `m.add()` returns a Result and so each line ends with /// a ? to propogate errors properly. Read the Rust Book for more details. py_module_initializer!(libhello, PyInit_hello, PyInit_hello, |py, m| { m.add(py, "multiply_rs", py_fn!(py, multiply_py(a: i32, b: i32)))?; m.add(py, "hamming_rs", py_fn!(py, hamming_py(a: i32, b: i32)))?; Ok(()) }); pub fn multiply_py(_: Python, a: i32, b: i32) -> PyResult<i32> { Ok(a * b) } pub fn hamming_py(_: Python, a: i32, b: i32) -> PyResult<i32> { Ok((a ^ b).count_ones() as i32) }
use bit_field::BitField; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct VirtAddr(usize); impl VirtAddr { #[cfg(riscv32)] pub fn new(addr: usize) -> VirtAddr { VirtAddr(addr) } #[cfg(riscv64)] pub fn new(addr: usize) -> VirtAddr { if addr.get_bit(47) { assert!(addr.get_bits(48..64) == 0xFFFF, "va 48..64 is not sext"); } else { assert!(addr.get_bits(48..64) == 0x0000, "va 48..64 is not sext"); } VirtAddr(addr) } pub fn as_usize(&self) -> usize { self.0 } #[cfg(riscv64)] pub fn p4_index(&self) -> usize { self.0.get_bits(39..48) } #[cfg(riscv64)] pub fn p3_index(&self) -> usize { self.0.get_bits(30..39) } #[cfg(riscv64)] pub fn p2_index(&self) -> usize { self.0.get_bits(21..30) } #[cfg(riscv32)] pub fn p2_index(&self) -> usize { self.0.get_bits(22..32) } #[cfg(riscv64)] pub fn p1_index(&self) -> usize { return self.0.get_bits(12..21); } #[cfg(riscv32)] pub fn p1_index(&self) -> usize { return self.0.get_bits(12..22); } #[cfg(riscv64)] pub fn page_number(&self) -> usize { self.0.get_bits(12..64) } #[cfg(riscv32)] pub fn page_number(&self) -> usize { self.0.get_bits(12..32) } pub fn page_offset(&self) -> usize { self.0.get_bits(0..12) } pub fn to_4k_aligned(&self) -> Self { VirtAddr((self.0 >> 12) << 12) } #[cfg(riscv32)] pub fn from_page_table_indices(p2_index: usize, p1_index: usize, offset: usize) -> Self { assert!(p2_index.get_bits(10..32) == 0, "p2_index exceeding 10 bits"); assert!(p1_index.get_bits(10..32) == 0, "p1_index exceeding 10 bits"); assert!(offset.get_bits(12..32) == 0, "offset exceeding 12 bits"); VirtAddr::new((p2_index << 22) | (p1_index << 12) | offset) } #[cfg(riscv64)] pub fn from_page_table_indices( p4_index: usize, p3_index: usize, p2_index: usize, p1_index: usize, offset: usize, ) -> Self { assert!(p4_index.get_bits(10..32) == 0, "p4_index exceeding 9 bits"); assert!(p3_index.get_bits(10..32) == 0, "p3_index exceeding 9 bits"); assert!(p2_index.get_bits(10..32) == 0, "p2_index exceeding 9 bits"); assert!(p1_index.get_bits(10..32) == 0, "p1_index exceeding 9 bits"); assert!(offset.get_bits(12..32) == 0, "offset exceeding 12 bits"); let mut addr: usize = (p4_index << 12 << 9 << 9 << 9) | (p3_index << 12 << 9 << 9) | (p2_index << 12 << 9) | (p1_index << 12) | offset; if addr.get_bit(47) { addr.set_bits(48..64, 0xFFFF); } else { addr.set_bits(48..64, 0x0000); } VirtAddr::new(addr) } pub(crate) unsafe fn as_mut<'a, 'b, T>(&'a self) -> &'b mut T { &mut *(self.0 as *mut T) } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct PhysAddr(usize); impl PhysAddr { #[cfg(riscv32)] pub fn new(addr: usize) -> PhysAddr { PhysAddr(addr) } #[cfg(riscv64)] pub fn new(addr: usize) -> PhysAddr { assert!(addr.get_bits(32..64) == 0, "pa 32..64 not zero?"); PhysAddr(addr) } pub fn as_usize(&self) -> usize { self.0 } #[cfg(riscv64)] pub fn p4_index(&self) -> usize { self.0.get_bits(39..48) as usize } #[cfg(riscv64)] pub fn p3_index(&self) -> usize { self.0.get_bits(30..39) as usize } #[cfg(riscv64)] pub fn p2_index(&self) -> usize { self.0.get_bits(21..30) as usize } #[cfg(riscv32)] pub fn p2_index(&self) -> usize { self.0.get_bits(22..32) } #[cfg(riscv64)] pub fn p1_index(&self) -> usize { self.0.get_bits(12..21) as usize } #[cfg(riscv32)] pub fn p1_index(&self) -> usize { self.0.get_bits(12..22) } #[cfg(riscv64)] pub fn page_number(&self) -> usize { self.0.get_bits(12..64) as usize } #[cfg(riscv32)] pub fn page_number(&self) -> usize { self.0.get_bits(12..32) } pub fn page_offset(&self) -> usize { self.0.get_bits(0..12) } pub fn to_4k_aligned(&self) -> Self { PhysAddr((self.0 >> 12) << 12) } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Page(VirtAddr); impl Page { pub fn of_addr(addr: VirtAddr) -> Self { Page(addr.to_4k_aligned()) } pub fn of_vpn(vpn: usize) -> Self { Page(VirtAddr::new(vpn << 12)) } pub fn start_address(&self) -> VirtAddr { self.0.clone() } #[cfg(riscv64)] pub fn p4_index(&self) -> usize { self.0.p4_index() } #[cfg(riscv64)] pub fn p3_index(&self) -> usize { self.0.p3_index() } pub fn p2_index(&self) -> usize { self.0.p2_index() } pub fn p1_index(&self) -> usize { self.0.p1_index() } pub fn number(&self) -> usize { self.0.page_number() } #[cfg(riscv64)] pub fn from_page_table_indices( p4_index: usize, p3_index: usize, p2_index: usize, p1_index: usize, ) -> Self { let mut addr: usize = 0; addr.set_bits(39..48, p4_index); addr.set_bits(30..39, p3_index); addr.set_bits(21..30, p2_index); addr.set_bits(12..21, p1_index); if addr.get_bit(47) { addr.set_bits(48..64, 0xFFFF); } else { addr.set_bits(48..64, 0x0000); } Page::of_addr(VirtAddr::new(addr)) } #[cfg(riscv32)] pub fn from_page_table_indices(p2_index: usize, p1_index: usize) -> Self { let mut addr: usize = 0; addr.set_bits(22..32, p2_index); addr.set_bits(12..22, p1_index); Page::of_addr(VirtAddr::new(addr)) } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Frame(PhysAddr); impl Frame { pub fn of_addr(addr: PhysAddr) -> Self { Frame(addr.to_4k_aligned()) } #[inline(always)] pub fn of_ppn(ppn: usize) -> Self { Frame(PhysAddr::new(ppn << 12)) } pub fn start_address(&self) -> PhysAddr { self.0.clone() } #[cfg(riscv64)] pub fn p4_index(&self) -> usize { self.0.p4_index() } #[cfg(riscv64)] pub fn p3_index(&self) -> usize { self.0.p3_index() } pub fn p2_index(&self) -> usize { self.0.p2_index() } pub fn p1_index(&self) -> usize { self.0.p1_index() } pub fn number(&self) -> usize { self.0.page_number() } pub unsafe fn as_kernel_mut<'a, 'b, T>(&'a self, linear_offset: usize) -> &'b mut T { &mut *(((self.0).0 + linear_offset) as *mut T) } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Control"] pub ctl: CTL, _reserved1: [u8; 12usize], #[doc = "0x10 - Clock control"] pub clock_ctl: CLOCK_CTL, _reserved2: [u8; 12usize], #[doc = "0x20 - Command"] pub cmd: CMD, _reserved3: [u8; 28usize], #[doc = "0x40 - Trigger control"] pub tr_ctl: TR_CTL, _reserved4: [u8; 60usize], #[doc = "0x80 - Transmitter control"] pub tx_ctl: TX_CTL, #[doc = "0x84 - Transmitter watchdog"] pub tx_watchdog: TX_WATCHDOG, _reserved6: [u8; 24usize], #[doc = "0xa0 - Receiver control"] pub rx_ctl: RX_CTL, #[doc = "0xa4 - Receiver watchdog"] pub rx_watchdog: RX_WATCHDOG, _reserved8: [u8; 344usize], #[doc = "0x200 - TX FIFO control"] pub tx_fifo_ctl: TX_FIFO_CTL, #[doc = "0x204 - TX FIFO status"] pub tx_fifo_status: TX_FIFO_STATUS, #[doc = "0x208 - TX FIFO write"] pub tx_fifo_wr: TX_FIFO_WR, _reserved11: [u8; 244usize], #[doc = "0x300 - RX FIFO control"] pub rx_fifo_ctl: RX_FIFO_CTL, #[doc = "0x304 - RX FIFO status"] pub rx_fifo_status: RX_FIFO_STATUS, #[doc = "0x308 - RX FIFO read"] pub rx_fifo_rd: RX_FIFO_RD, #[doc = "0x30c - RX FIFO silent read"] pub rx_fifo_rd_silent: RX_FIFO_RD_SILENT, _reserved15: [u8; 3056usize], #[doc = "0xf00 - Interrupt register"] pub intr: INTR, #[doc = "0xf04 - Interrupt set register"] pub intr_set: INTR_SET, #[doc = "0xf08 - Interrupt mask register"] pub intr_mask: INTR_MASK, #[doc = "0xf0c - Interrupt masked register"] pub intr_masked: INTR_MASKED, } #[doc = "Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ctl](ctl) module"] pub type CTL = crate::Reg<u32, _CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CTL; #[doc = "`read()` method returns [ctl::R](ctl::R) reader structure"] impl crate::Readable for CTL {} #[doc = "`write(|w| ..)` method takes [ctl::W](ctl::W) writer structure"] impl crate::Writable for CTL {} #[doc = "Control"] pub mod ctl; #[doc = "Clock control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [clock_ctl](clock_ctl) module"] pub type CLOCK_CTL = crate::Reg<u32, _CLOCK_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CLOCK_CTL; #[doc = "`read()` method returns [clock_ctl::R](clock_ctl::R) reader structure"] impl crate::Readable for CLOCK_CTL {} #[doc = "`write(|w| ..)` method takes [clock_ctl::W](clock_ctl::W) writer structure"] impl crate::Writable for CLOCK_CTL {} #[doc = "Clock control"] pub mod clock_ctl; #[doc = "Command\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cmd](cmd) module"] pub type CMD = crate::Reg<u32, _CMD>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CMD; #[doc = "`read()` method returns [cmd::R](cmd::R) reader structure"] impl crate::Readable for CMD {} #[doc = "`write(|w| ..)` method takes [cmd::W](cmd::W) writer structure"] impl crate::Writable for CMD {} #[doc = "Command"] pub mod cmd; #[doc = "Trigger control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tr_ctl](tr_ctl) module"] pub type TR_CTL = crate::Reg<u32, _TR_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TR_CTL; #[doc = "`read()` method returns [tr_ctl::R](tr_ctl::R) reader structure"] impl crate::Readable for TR_CTL {} #[doc = "`write(|w| ..)` method takes [tr_ctl::W](tr_ctl::W) writer structure"] impl crate::Writable for TR_CTL {} #[doc = "Trigger control"] pub mod tr_ctl; #[doc = "Transmitter control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tx_ctl](tx_ctl) module"] pub type TX_CTL = crate::Reg<u32, _TX_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TX_CTL; #[doc = "`read()` method returns [tx_ctl::R](tx_ctl::R) reader structure"] impl crate::Readable for TX_CTL {} #[doc = "`write(|w| ..)` method takes [tx_ctl::W](tx_ctl::W) writer structure"] impl crate::Writable for TX_CTL {} #[doc = "Transmitter control"] pub mod tx_ctl; #[doc = "Transmitter watchdog\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tx_watchdog](tx_watchdog) module"] pub type TX_WATCHDOG = crate::Reg<u32, _TX_WATCHDOG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TX_WATCHDOG; #[doc = "`read()` method returns [tx_watchdog::R](tx_watchdog::R) reader structure"] impl crate::Readable for TX_WATCHDOG {} #[doc = "`write(|w| ..)` method takes [tx_watchdog::W](tx_watchdog::W) writer structure"] impl crate::Writable for TX_WATCHDOG {} #[doc = "Transmitter watchdog"] pub mod tx_watchdog; #[doc = "Receiver control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_ctl](rx_ctl) module"] pub type RX_CTL = crate::Reg<u32, _RX_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RX_CTL; #[doc = "`read()` method returns [rx_ctl::R](rx_ctl::R) reader structure"] impl crate::Readable for RX_CTL {} #[doc = "`write(|w| ..)` method takes [rx_ctl::W](rx_ctl::W) writer structure"] impl crate::Writable for RX_CTL {} #[doc = "Receiver control"] pub mod rx_ctl; #[doc = "Receiver watchdog\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_watchdog](rx_watchdog) module"] pub type RX_WATCHDOG = crate::Reg<u32, _RX_WATCHDOG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RX_WATCHDOG; #[doc = "`read()` method returns [rx_watchdog::R](rx_watchdog::R) reader structure"] impl crate::Readable for RX_WATCHDOG {} #[doc = "`write(|w| ..)` method takes [rx_watchdog::W](rx_watchdog::W) writer structure"] impl crate::Writable for RX_WATCHDOG {} #[doc = "Receiver watchdog"] pub mod rx_watchdog; #[doc = "TX FIFO control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tx_fifo_ctl](tx_fifo_ctl) module"] pub type TX_FIFO_CTL = crate::Reg<u32, _TX_FIFO_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TX_FIFO_CTL; #[doc = "`read()` method returns [tx_fifo_ctl::R](tx_fifo_ctl::R) reader structure"] impl crate::Readable for TX_FIFO_CTL {} #[doc = "`write(|w| ..)` method takes [tx_fifo_ctl::W](tx_fifo_ctl::W) writer structure"] impl crate::Writable for TX_FIFO_CTL {} #[doc = "TX FIFO control"] pub mod tx_fifo_ctl; #[doc = "TX FIFO status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tx_fifo_status](tx_fifo_status) module"] pub type TX_FIFO_STATUS = crate::Reg<u32, _TX_FIFO_STATUS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TX_FIFO_STATUS; #[doc = "`read()` method returns [tx_fifo_status::R](tx_fifo_status::R) reader structure"] impl crate::Readable for TX_FIFO_STATUS {} #[doc = "TX FIFO status"] pub mod tx_fifo_status; #[doc = "TX FIFO write\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tx_fifo_wr](tx_fifo_wr) module"] pub type TX_FIFO_WR = crate::Reg<u32, _TX_FIFO_WR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TX_FIFO_WR; #[doc = "`write(|w| ..)` method takes [tx_fifo_wr::W](tx_fifo_wr::W) writer structure"] impl crate::Writable for TX_FIFO_WR {} #[doc = "TX FIFO write"] pub mod tx_fifo_wr; #[doc = "RX FIFO control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_fifo_ctl](rx_fifo_ctl) module"] pub type RX_FIFO_CTL = crate::Reg<u32, _RX_FIFO_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RX_FIFO_CTL; #[doc = "`read()` method returns [rx_fifo_ctl::R](rx_fifo_ctl::R) reader structure"] impl crate::Readable for RX_FIFO_CTL {} #[doc = "`write(|w| ..)` method takes [rx_fifo_ctl::W](rx_fifo_ctl::W) writer structure"] impl crate::Writable for RX_FIFO_CTL {} #[doc = "RX FIFO control"] pub mod rx_fifo_ctl; #[doc = "RX FIFO status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_fifo_status](rx_fifo_status) module"] pub type RX_FIFO_STATUS = crate::Reg<u32, _RX_FIFO_STATUS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RX_FIFO_STATUS; #[doc = "`read()` method returns [rx_fifo_status::R](rx_fifo_status::R) reader structure"] impl crate::Readable for RX_FIFO_STATUS {} #[doc = "RX FIFO status"] pub mod rx_fifo_status; #[doc = "RX FIFO read\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_fifo_rd](rx_fifo_rd) module"] pub type RX_FIFO_RD = crate::Reg<u32, _RX_FIFO_RD>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RX_FIFO_RD; #[doc = "`read()` method returns [rx_fifo_rd::R](rx_fifo_rd::R) reader structure"] impl crate::Readable for RX_FIFO_RD {} #[doc = "RX FIFO read"] pub mod rx_fifo_rd; #[doc = "RX FIFO silent read\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_fifo_rd_silent](rx_fifo_rd_silent) module"] pub type RX_FIFO_RD_SILENT = crate::Reg<u32, _RX_FIFO_RD_SILENT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RX_FIFO_RD_SILENT; #[doc = "`read()` method returns [rx_fifo_rd_silent::R](rx_fifo_rd_silent::R) reader structure"] impl crate::Readable for RX_FIFO_RD_SILENT {} #[doc = "RX FIFO silent read"] pub mod rx_fifo_rd_silent; #[doc = "Interrupt register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr](intr) module"] pub type INTR = crate::Reg<u32, _INTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR; #[doc = "`read()` method returns [intr::R](intr::R) reader structure"] impl crate::Readable for INTR {} #[doc = "`write(|w| ..)` method takes [intr::W](intr::W) writer structure"] impl crate::Writable for INTR {} #[doc = "Interrupt register"] pub mod intr; #[doc = "Interrupt set register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_set](intr_set) module"] pub type INTR_SET = crate::Reg<u32, _INTR_SET>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_SET; #[doc = "`read()` method returns [intr_set::R](intr_set::R) reader structure"] impl crate::Readable for INTR_SET {} #[doc = "`write(|w| ..)` method takes [intr_set::W](intr_set::W) writer structure"] impl crate::Writable for INTR_SET {} #[doc = "Interrupt set register"] pub mod intr_set; #[doc = "Interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_mask](intr_mask) module"] pub type INTR_MASK = crate::Reg<u32, _INTR_MASK>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_MASK; #[doc = "`read()` method returns [intr_mask::R](intr_mask::R) reader structure"] impl crate::Readable for INTR_MASK {} #[doc = "`write(|w| ..)` method takes [intr_mask::W](intr_mask::W) writer structure"] impl crate::Writable for INTR_MASK {} #[doc = "Interrupt mask register"] pub mod intr_mask; #[doc = "Interrupt masked register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_masked](intr_masked) module"] pub type INTR_MASKED = crate::Reg<u32, _INTR_MASKED>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_MASKED; #[doc = "`read()` method returns [intr_masked::R](intr_masked::R) reader structure"] impl crate::Readable for INTR_MASKED {} #[doc = "Interrupt masked register"] pub mod intr_masked;
use markdown::mdast::{Node, Root}; pub(crate) trait IntoPlainText { fn plain_text(&self) -> String; } impl IntoPlainText for Node { fn plain_text(&self) -> String { fn blank() -> String { "".to_string() } fn surround_with(surround_token: &str, inner: String) -> String { format!("{}{}{}", surround_token, inner, surround_token) } match self { Node::Root(x) => x.children.plain_text(), Node::BlockQuote(x) => x.children.plain_text(), Node::FootnoteDefinition(x) => x.children.plain_text(), Node::MdxJsxFlowElement(_) => blank(), Node::List(x) => x.children.plain_text(), Node::MdxjsEsm(_) => blank(), Node::Toml(_) => blank(), Node::Yaml(_) => blank(), Node::Break(_) => blank(), Node::InlineCode(x) => x.value.to_owned(), Node::InlineMath(x) => x.value.to_owned(), Node::Delete(x) => surround_with("~", x.children.plain_text()), Node::Emphasis(x) => surround_with("*", x.children.plain_text()), Node::MdxTextExpression(_) => blank(), Node::FootnoteReference(_) => blank(), Node::Html(_) => blank(), Node::Image(_) => blank(), Node::ImageReference(_) => blank(), Node::MdxJsxTextElement(_) => blank(), Node::Link(x) => x.children.plain_text(), Node::LinkReference(_) => blank(), Node::Strong(x) => surround_with("*", x.children.plain_text()), Node::Text(x) => x.value.to_owned(), Node::Code(x) => surround_with("\n```\n", x.value.to_owned()), Node::Math(x) => x.value.to_owned(), Node::MdxFlowExpression(_) => blank(), Node::Heading(x) => x.children.plain_text(), Node::Table(x) => x.children.plain_text(), Node::ThematicBreak(_) => blank(), Node::TableRow(x) => x.children.plain_text(), Node::TableCell(x) => x.children.plain_text(), Node::ListItem(x) => x.children.iter().map(|x| x.plain_text()).collect(), Node::Definition(_) => blank(), Node::Paragraph(x) => x.children.plain_text(), } } } impl IntoPlainText for Vec<Node> { fn plain_text(&self) -> String { self.iter() .map(|x| x.plain_text()) .collect::<Vec<_>>() .join("\n") } } impl IntoPlainText for Root { fn plain_text(&self) -> String { self.children.plain_text().trim().to_owned() } } #[cfg(test)] mod test { use crate::posts::MarkdownAst; use super::*; #[test] fn simple() { let original = "Hello, world!"; let parsed = MarkdownAst::from_str(original).unwrap(); let plain = parsed.0.plain_text(); assert_eq!(plain, original); } #[test] #[ignore = "The newlines around paragraphs aren't quite right"] fn heading() { let original = "# Hello, world! This is a test. More words these are together I think # Another heading"; let parsed = MarkdownAst::from_str(original).unwrap(); let plain = parsed.0.plain_text(); assert_eq!( plain, "Hello, world! This is a test." ); } #[test] fn code() { let original = "``` let x = \"test\"; ```"; let parsed = MarkdownAst::from_str(original).unwrap(); let plain = parsed.0.plain_text(); assert_eq!( plain, "``` let x = \"test\"; ```" ); } #[test] #[ignore = "We dont add the language to the code block yet"] fn code_with_lang() { let original = "```rust let x = \"test\"; ```"; let parsed = MarkdownAst::from_str(original).unwrap(); let plain = parsed.0.plain_text(); assert_eq!( plain, "```rust let x = \"test\"; ```" ); } #[test] #[ignore = "We don't add dashes before the list items yet"] fn ul_list() { let original = "- Hello, world! - This is a test."; let parsed = MarkdownAst::from_str(original).unwrap(); dbg!(&parsed); let plain = parsed.0.plain_text(); assert_eq!(plain, original); } #[test] #[ignore = "We don't add numbers before the list items yet"] fn ol_list() { let original = "0. Hello, world! 0. This is a test."; let parsed = MarkdownAst::from_str(original).unwrap(); let plain = parsed.0.plain_text(); assert_eq!( plain, "1. Hello, world! 2. This is a test." ); } }
use std::{io, path::Path}; pub use directory::Directory; pub use directory::MmapDirectory; pub use directory::RamDirectory; use ownedbytes::OwnedBytes; use crate::util::{Ext, SetExt}; pub fn load_data_pair(directory: &Box<dyn Directory>, path: &Path) -> Result<(OwnedBytes, OwnedBytes), io::Error> { let data_path = path.set_ext(Ext::Data); let indirect_path = path.set_ext(Ext::Indirect); Ok((directory.get_file_bytes(&indirect_path)?, directory.get_file_bytes(&data_path)?)) }
//! This module contains a Margin settings of a [`Table`]. //! //! # Example //! #![cfg_attr(feature = "std", doc = "```")] #![cfg_attr(not(feature = "std"), doc = "```ignore")] //! use tabled::{settings::{Margin, Style}, Table}; //! //! let data = vec!["Hello", "World", "!"]; //! //! let mut table = Table::new(data); //! table.with(Style::markdown()).with(Margin::new(3, 3, 1, 0)); //! //! assert_eq!( //! table.to_string(), //! concat!( //! " \n", //! " | &str | \n", //! " |-------| \n", //! " | Hello | \n", //! " | World | \n", //! " | ! | ", //! ) //! ); //! ``` //! //! [`Table`]: crate::Table use crate::{ grid::{ color::StaticColor, config::{CompactConfig, CompactMultilineConfig}, config::{Indent, Sides}, }, settings::TableOption, }; #[cfg(feature = "std")] use crate::grid::{color::AnsiColor, config::ColoredConfig}; /// Margin is responsible for a left/right/top/bottom outer indent of a grid. /// #[cfg_attr(feature = "std", doc = "```")] #[cfg_attr(not(feature = "std"), doc = "```ignore")] /// # use tabled::{settings::Margin, Table}; /// # let data: Vec<&'static str> = Vec::new(); /// let table = Table::new(&data) /// .with(Margin::new(1, 1, 1, 1).fill('>', '<', 'V', '^')); /// ``` #[derive(Debug, Clone)] pub struct Margin<C = StaticColor> { indent: Sides<Indent>, colors: Option<Sides<C>>, } impl Margin { /// Construct's an Margin object. /// /// It uses space(' ') as a default fill character. /// To set a custom character you can use [`Margin::fill`] function. pub const fn new(left: usize, right: usize, top: usize, bottom: usize) -> Self { Self { indent: Sides::new( Indent::spaced(left), Indent::spaced(right), Indent::spaced(top), Indent::spaced(bottom), ), colors: None, } } } impl<Color> Margin<Color> { /// The function, sets a characters for the margin on an each side. pub const fn fill(mut self, left: char, right: char, top: char, bottom: char) -> Self { self.indent.left.fill = left; self.indent.right.fill = right; self.indent.top.fill = top; self.indent.bottom.fill = bottom; self } /// The function, sets a characters for the margin on an each side. pub fn colorize<C>(self, left: C, right: C, top: C, bottom: C) -> Margin<C> { Margin { indent: self.indent, colors: Some(Sides::new(left, right, top, bottom)), } } } #[cfg(feature = "std")] impl<R, D, C> TableOption<R, D, ColoredConfig> for Margin<C> where C: Into<AnsiColor<'static>> + Clone, { fn change(self, _: &mut R, cfg: &mut ColoredConfig, _: &mut D) { let indent = self.indent; let margin = Sides::new(indent.left, indent.right, indent.top, indent.bottom); cfg.set_margin(margin); if let Some(colors) = &self.colors { let margin = Sides::new( Some(colors.left.clone().into()), Some(colors.right.clone().into()), Some(colors.top.clone().into()), Some(colors.bottom.clone().into()), ); cfg.set_margin_color(margin); } } } impl<R, D, C> TableOption<R, D, CompactConfig> for Margin<C> where C: Into<StaticColor> + Clone, { fn change(self, _: &mut R, cfg: &mut CompactConfig, _: &mut D) { *cfg = cfg.set_margin(self.indent); if let Some(c) = self.colors { // todo: make a new method (BECAUSE INTO doesn't work) try_into(); let colors = Sides::new(c.left.into(), c.right.into(), c.top.into(), c.bottom.into()); *cfg = cfg.set_margin_color(colors); } } } impl<R, D, C> TableOption<R, D, CompactMultilineConfig> for Margin<C> where C: Into<StaticColor> + Clone, { fn change(self, records: &mut R, cfg: &mut CompactMultilineConfig, dimension: &mut D) { self.change(records, cfg.as_mut(), dimension) } }
// -*- mode:rust;mode:rust-playground -*- // snippet of code @ 2017-04-18 12:24:11 // === Rust Playground === // Execute the snippet with Ctl-Return // Remove the snippet completely with its dir and all files M-x `rust-playground-rm` fn main() { let (tx, rx) = channel(); spawn(proc () { tx.send(2u+2); tx.send(3u+5); }); println!("{}, {}", rx.recv(), rx.recv()); }
struct Rectangle { height: i32, length: i32, } impl Rectangle { fn is_square(&self) -> bool { return self.height == self.length; } }
// thread 'rustc' panicked at 'index out of bounds: the len is 1 but the index is 1' // prusti-viper/src/encoder/procedure_encoder.rs:5764:36 union Foo { a: [i32; 1], b: [i32; 1], } fn main() { let _ = Foo { a: [0] }; }
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2017 The developers of rdma-core. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. pub struct UnextendedValidWorkCompletion(UnextendedWorkCompletion); impl ValidWorkCompletion for UnextendedValidWorkCompletion { #[inline(always)] fn flags(&self) -> c_int { self.data().wc_flags } #[inline(always)] fn workRequestOperationWas(&self) -> ibv_wc_opcode { self.data().opcode } // Only relevant for UD => Unreliable datagram? // AKA source queue pair number #[inline(always)] fn receiveWorkRequestRemoteQueuePairNumber(&self) -> QueuePairNumber { self.data().src_qp } #[doc(hidden)] #[inline(always)] fn rawImmediateDataInNetworkByteOrder(&self) -> u32 { let union = (self.data()).__bindgen_anon_1; unsafe { union.imm_data } } // Only relevant for UD #[inline(always)] fn receiveWorkRequestSourceLocalIdentifier(&self) -> LocalIdentifier { self.data().slid } // Only relevant for UD #[inline(always)] fn receiveWorkRequestServiceLevel(&self) -> ServiceLevel { unsafe { transmute(self.data().sl) } } // Only relevant for UD and only then for unicast messages #[inline(always)] fn receiveWorkRequestDestinationLocalIdentifierPath(&self) -> LocalIdentifierPath { self.data().dlid_path_bits } /// The number of bytes transferred. Relevant if the Receive Queue for incoming Send or RDMA Write with immediate operations. This value doesn't include the length of the immediate data, if such exists. Relevant in the Send Queue for RDMA Read and Atomic operations. /// For the Receive Queue of a UD QP that is not associated with an SRQ or for an SRQ that is associated with a UD QP this value equals to the payload of the message plus the 40 bytes reserved for the GRH. /// The number of bytes transferred is the payload of the message plus the 40 bytes reserved for the GRH, whether or not the GRH is present #[inline(always)] fn numberOfBytesTransferred(&self) -> u32 { self.data().byte_len as u32 } #[inline(always)] fn partitionKeyIndex(&self) -> PartitionKeyIndex { self.data().pkey_index } } impl UnextendedValidWorkCompletion { #[inline(always)] fn data(&self) -> ibv_wc { (self.0).0 } }
use std::{ self, cmp::{ PartialEq, PartialOrd, Ordering }, fmt::{ self, Debug }, num::FpCategory, ops::{ Mul, Div, Rem, Neg, MulAssign, DivAssign, RemAssign }, }; #[cfg(not(feature = "double"))] use std::f32::consts; #[cfg(feature = "double")] use std::f64::consts; use cgmath::ApproxEq; use derive_more::{ Add, Sub, Mul, Div, Rem, AddAssign, SubAssign, }; use num; use num::Float as NumFloat; use num::traits::{ Bounded, Num, One, Zero, NumCast }; use num::traits::ParseFloatError; use shrinkwraprs::Shrinkwrap; use rand::Rng; use rand::distributions::{ Distribution, Standard }; macro_rules! float_define { ($prim:ident, $noisy_ty:ident, $noisy_fn:ident) => { #[macro_use] pub mod float { use noisy_float::types::{ $noisy_ty, $noisy_fn }; pub(crate) const CONV: fn(FloatPrim) -> FloatNoisy = $noisy_fn; pub type FloatNoisy = $noisy_ty; pub type FloatPrim = $prim; #[macro_export] macro_rules! float_const { ($fn:ident, $name:ident) => { #[inline(always)] pub fn $fn() -> Self { float(std::$prim::consts::$name) } }; } } }; } #[cfg(not(feature = "double"))] float_define!(f32, N32, n32); #[cfg(feature = "double")] float_define!(f64, N64, n64); pub use self::float::*; pub fn float(f: impl NumCast) -> Float { Float(CONV(num::cast::cast(f).unwrap())) } #[derive( Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Add, Sub, Mul, Div, Rem, AddAssign, SubAssign, Shrinkwrap )] #[shrinkwrap(mutable, unsafe_ignore_visibility)] pub struct Float(FloatNoisy); impl Debug for Float { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { <FloatPrim as Debug>::fmt(&self.raw(), f) } } impl Float { float_const!(pi, PI); float_const!(frac_1_pi, FRAC_1_PI); float_const!(frac_pi_2, FRAC_PI_2); float_const!(frac_pi_4, FRAC_PI_4); #[inline(always)] pub fn inv_2_pi() -> Self { const FRAC_2_PI: FloatPrim = 1.0 / (2.0 * consts::PI); float(FRAC_2_PI) } #[inline(always)] pub fn inv_4_pi() -> Self { const FRAC_4_PI: FloatPrim = 1.0 / (4.0 * consts::PI); float(FRAC_4_PI) } pub fn raw(self) -> FloatPrim { self.0.raw() } pub fn pow(self, n: i32) -> Self { self.powi(n) } pub fn lerp(self, other: Self, amount: Self) -> Self { (float(1.0) - amount) * self + float(1.0) * other } } impl Distribution<Float> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Float { float(rng.gen::<FloatPrim>()) } } impl From<FloatPrim> for Float { #[inline(always)] fn from(f: FloatPrim) -> Self { float(f) } } impl Into<FloatPrim> for Float { #[inline(always)] fn into(self) -> FloatPrim { self.raw() } } impl From<FloatNoisy> for Float { #[inline(always)] fn from(f: FloatNoisy) -> Self { Float(f) } } impl Into<FloatNoisy> for Float { #[inline(always)] fn into(self) -> FloatNoisy { self.0 } } impl ApproxEq for Float { type Epsilon = Self; #[inline(always)] fn default_epsilon() -> Self { float(<FloatPrim as ApproxEq>::default_epsilon()) } #[inline(always)] fn default_max_relative() -> Self { float(<FloatPrim as ApproxEq>::default_max_relative()) } #[inline(always)] fn default_max_ulps() -> u32 { <FloatPrim as ApproxEq>::default_max_ulps() } #[inline(always)] fn relative_eq(&self, other: &Self, epsilon: Self, max_relative: Self) -> bool { <FloatPrim as ApproxEq>::relative_eq(&self.0.raw(), &other.0.raw(), epsilon.0.raw(), max_relative.0.raw()) } #[inline(always)] fn ulps_eq(&self, other: &Self, epsilon: Self, max_ulps: u32) -> bool { <FloatPrim as ApproxEq>::ulps_eq(&self.0.raw(), &other.0.raw(), epsilon.0.raw(), max_ulps) } } impl Num for Float { type FromStrRadixErr = ParseFloatError; #[inline(always)] fn from_str_radix(src: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> { <FloatPrim as Num>::from_str_radix(src, radix) .map(float) } } impl One for Float { #[inline(always)] fn one() -> Float { float(1.0) } } impl Zero for Float { #[inline(always)] fn zero() -> Float { float(0.0) } #[inline(always)] fn is_zero(&self) -> bool { self.0.is_zero() } } impl Bounded for Float { #[inline(always)] fn min_value() -> Self { float(<FloatPrim as Bounded>::min_value()) } #[inline(always)] fn max_value() -> Self { float(<FloatPrim as Bounded>::max_value()) } } impl num::ToPrimitive for Float { #[inline(always)] fn to_i64(&self) -> Option<i64> { <FloatPrim as num::ToPrimitive>::to_i64(&self.0.raw()) } #[inline(always)] fn to_u64(&self) -> Option<u64> { <FloatPrim as num::ToPrimitive>::to_u64(&self.0.raw()) } } impl num::NumCast for Float { #[inline(always)] fn from<T: num::ToPrimitive>(n: T) -> Option<Self> { <FloatPrim as num::NumCast>::from(n).map(float) } } impl PartialEq<FloatPrim> for Float { #[inline(always)] fn eq(&self, other: &FloatPrim) -> bool { self.eq(&float(*other)) } } impl PartialOrd<FloatPrim> for Float { #[inline(always)] fn partial_cmp(&self, other: &FloatPrim) -> Option<Ordering> { self.partial_cmp(&float(*other)) } } impl Mul for Float { type Output = Self; #[inline(always)] fn mul(self, rhs: Self) -> Self { Float(self.0 * rhs.0) } } impl MulAssign for Float { #[inline(always)] fn mul_assign(&mut self, rhs: Self) { self.0 *= rhs.0; } } impl Div for Float { type Output = Self; #[inline(always)] fn div(self, rhs: Self) -> Self { Float(self.0 / rhs.0) } } impl DivAssign for Float { #[inline(always)] fn div_assign(&mut self, rhs: Self) { self.0 /= rhs.0; } } impl Rem for Float { type Output = Self; #[inline(always)] fn rem(self, rhs: Self) -> Self { Float(self.0 % rhs.0) } } impl RemAssign for Float { #[inline(always)] fn rem_assign(&mut self, rhs: Self) { self.0 %= rhs.0; } } impl Neg for Float { type Output = Self; #[inline(always)] fn neg(self) -> Self { float(-self.0.raw()) } } impl NumFloat for Float { #[inline(always)] fn nan() -> Self { float(FloatPrim::nan()) } #[inline(always)] fn infinity() -> Self { float(FloatPrim::infinity()) } #[inline(always)] fn neg_infinity() -> Self { float(FloatPrim::neg_infinity()) } #[inline(always)] fn neg_zero() -> Self { float(FloatPrim::neg_zero()) } #[inline(always)] fn min_value() -> Self { float(<FloatPrim as Bounded>::min_value()) } #[inline(always)] fn min_positive_value() -> Self { float(FloatPrim::min_positive_value()) } #[inline(always)] fn max_value() -> Self { float(<FloatPrim as Bounded>::max_value()) } #[inline(always)] fn is_nan(self) -> bool { self.0.is_nan() } #[inline(always)] fn is_infinite(self) -> bool { self.0.is_infinite() } #[inline(always)] fn is_finite(self) -> bool { self.0.is_finite() } #[inline(always)] fn is_normal(self) -> bool { self.0.is_normal() } #[inline(always)] fn classify(self) -> FpCategory { self.0.classify() } #[inline(always)] fn floor(self) -> Self { Float(self.0.floor()) } #[inline(always)] fn ceil(self) -> Self { Float(self.0.ceil()) } #[inline(always)] fn round(self) -> Self { Float(self.0.round()) } #[inline(always)] fn trunc(self) -> Self { Float(self.0.trunc()) } #[inline(always)] fn fract(self) -> Self { Float(self.0.fract()) } #[inline(always)] fn abs(self) -> Self { Float(self.0.abs()) } #[inline(always)] fn signum(self) -> Self { Float(self.0.signum()) } #[inline(always)] fn is_sign_positive(self) -> bool { self.0.is_sign_positive() } #[inline(always)] fn is_sign_negative(self) -> bool { self.0.is_sign_negative() } #[inline(always)] fn mul_add(self, a: Self, b: Self) -> Self { Float(self.0.mul_add(a.0, b.0)) } #[inline(always)] fn recip(self) -> Self { Float(self.0.recip()) } #[inline(always)] fn powi(self, n: i32) -> Self { Float(self.0.powi(n)) } #[inline(always)] fn powf(self, n: Self) -> Self { Float(self.0.powf(n.0)) } #[inline(always)] fn sqrt(self) -> Self { Float(self.0.sqrt()) } #[inline(always)] fn exp(self) -> Self { Float(self.0.exp()) } #[inline(always)] fn exp2(self) -> Self { Float(self.0.exp2()) } #[inline(always)] fn ln(self) -> Self { Float(self.0.ln()) } #[inline(always)] fn log(self, base: Self) -> Self { Float(self.0.log(base.0)) } #[inline(always)] fn log2(self) -> Self { Float(self.0.log2()) } #[inline(always)] fn log10(self) -> Self { Float(self.0.log10()) } #[inline(always)] fn max(self, other: Self) -> Self { Float(self.0.max(other.0)) } #[inline(always)] fn min(self, other: Self) -> Self { Float(self.0.min(other.0)) } #[inline(always)] fn abs_sub(self, other: Self) -> Self { Float(self.0.abs_sub(other.0)) } #[inline(always)] fn cbrt(self) -> Self { Float(self.0.cbrt()) } #[inline(always)] fn hypot(self, other: Self) -> Self { Float(self.0.hypot(other.0)) } #[inline(always)] fn sin(self) -> Self { Float(self.0.sin()) } #[inline(always)] fn cos(self) -> Self { Float(self.0.cos()) } #[inline(always)] fn tan(self) -> Self { Float(self.0.tan()) } #[inline(always)] fn asin(self) -> Self { Float(self.0.asin()) } #[inline(always)] fn acos(self) -> Self { Float(self.0.acos()) } #[inline(always)] fn atan(self) -> Self { Float(self.0.atan()) } #[inline(always)] fn atan2(self, other: Self) -> Self { Float(self.0.atan2(other.0)) } #[inline(always)] fn sin_cos(self) -> (Self, Self) { let (a, b) = self.0.sin_cos(); (Float(a), Float(b)) } #[inline(always)] fn exp_m1(self) -> Self { Float(self.0.exp_m1()) } #[inline(always)] fn ln_1p(self) -> Self { Float(self.0.ln_1p()) } #[inline(always)] fn sinh(self) -> Self { Float(self.0.sinh()) } #[inline(always)] fn cosh(self) -> Self { Float(self.0.cosh()) } #[inline(always)] fn tanh(self) -> Self { Float(self.0.tanh()) } #[inline(always)] fn asinh(self) -> Self { Float(self.0.asinh()) } #[inline(always)] fn acosh(self) -> Self { Float(self.0.acosh()) } #[inline(always)] fn atanh(self) -> Self { Float(self.0.atanh()) } #[inline(always)] fn integer_decode(self) -> (u64, i16, i8) { self.0.integer_decode() } }
extern crate itertools; extern crate rayon; extern crate hashbrown; use itertools::Itertools; use rayon::prelude::*; use hashbrown::HashMap; #[derive(Debug, Clone)] pub struct DistanceMatrix { pub size: usize, pub array: Vec<Option<u32>>, } impl DistanceMatrix { /// Creates new Distance Matrix pub fn new(n: usize, distances: Vec<u32>) -> DistanceMatrix { let new_array: Vec<Option<u32>> = distances .iter() .map(|i| match i { &0 => None, x => Some(*x), }) .collect(); let new_dist = DistanceMatrix { array: new_array, size: n, }; assert_eq!( new_dist.array.len(), new_dist.size * new_dist.size, "Array and size do not match" ); new_dist } /// Gets distance from v1 to v2 pub fn get(&self, v1: usize, v2: usize) -> Option<u32> { self.array[v2 + self.size * v1] } } fn set_to_num(set: &Vec<usize>) -> usize { let mut bin: usize = 0; for x in set { bin |= 1usize << x; } bin } /// Traveling Salesperson Problem /// /// # Examples /// /// This example comes from the wikipedia page for the /// [Held-Karp algorithm](https://en.wikipedia.org/wiki/Held%E2%80%93Karp_algorithm#Example[4]) /// /// ``` /// let distances: Vec<u32> = vec! [ /// 0, 2, 9, 10, /// 1, 0, 6, 4, /// 15, 7, 0, 8, /// 6, 3, 12, 0 /// ]; /// let dist_matrix = held_karp_rust::DistanceMatrix::new(4, distances); /// let result = held_karp_rust::travel(dist_matrix); /// assert_eq!(result.0, 21); /// assert_eq!(result.1, vec![0, 2, 3, 1, 0]); /// ``` pub fn travel(w_array: DistanceMatrix) -> (u32, Vec<usize>) { // create the hash map let mut dist_map: HashMap<usize, Vec<(usize, Option<u32>)>> = HashMap::new(); // calculate the void column let void_col: Vec<(usize, Option<u32>)> = (0..w_array.size) .map(|i: usize| (0, w_array.get(i, 0))) .collect(); // println!("[], {:?}", void_col); // add empty set column to distance map dist_map.insert(0, void_col); // for each combination size for set_len in 1..(w_array.size - 1) { // combinations of length set_len let comb_by_len = (1..w_array.size).combinations(set_len).collect_vec(); // println!("{:?}", comb_by_len); // iterate through all combinations of a given length comb_by_len .iter() .for_each(|comb| { let comb_num = set_to_num(comb); let mut dist: Vec<(usize, Option<u32>)> = vec![(0, None); w_array.size]; // for each possible value (1..w_array.size) // filter out all values if it's contained in the the combination .filter(|i| !comb.contains(i)) .for_each(|i| { // TODO: take the min from here let min_val: Option<(usize, Option<u32>)> = comb .iter() .map(|k| { let w = w_array.get(i, *k); // gets the correct column for A - Vx let d_col: usize = comb_num ^ (1usize << k); // gets the value of D[Vx][A - Vx] let d_val: Option<u32> = dist_map[&d_col][*k].1; // add the two together let val: Option<u32> = match (w, d_val) { (Some(x), Some(y)) => Some(x + y), // if both are not infinity, add them _ => None, // else (at least one is infinity, retrn none }; (*k, val) }) .filter(|i| i.1.is_some()) .min_by_key(|i| i.1); // Find the minimum value that is not None dist[i] = match min_val { None => (0, None), Some(x) => x, }; }); // println!("{:?}, {:?}", comb, dist); // dist_map.insert(comb.clone(), dist); dist_map.insert(comb_num, dist); }); } let mut comb: Vec<usize> = (1..w_array.size).collect(); let comb_num: usize = set_to_num(&comb); let last_val: (usize, Option<u32>) = comb .iter() .map(|k| { let w = w_array.get(0, *k); // gets the correct column for A - Vx let d_col: usize = comb_num ^ (1usize << k); // gets the value of D[Vx][A - Vx] let d_val: Option<u32> = dist_map[&d_col][*k].1; // add the two together let val: Option<u32> = match (w, d_val) { (Some(x), Some(y)) => Some(x + y), // if both are not infinity, add them _ => None, // else (at least one is infinity, retrn none }; (*k, val) }) .filter(|i| i.1.is_some()) .min_by_key(|i| i.1) .unwrap(); let mut trip: Vec<usize> = vec![0]; // calculate minimum trip // set next city let mut next: usize = last_val.0; trip.push(next); comb = comb.iter().filter(|i| **i != next).cloned().collect(); let mut comb_num: usize = set_to_num(&comb); while comb_num > 0 { next = dist_map[&comb_num][next].0; trip.push(next); comb_num = comb_num ^ (1 << next); } trip.push(0); // let last_comb: Vec<usize> = (1..w_array.size).collect(); // println!("{:?}: [({}, {:?})]", last_comb, last_val.0, last_val.1); // println!("Trip: {:?}", trip); // println!("Distance: {}", last_val.1.unwrap()); (last_val.1.unwrap(), trip) } /// ### Parallel Asymmetric Traveling Salesperson Problem /// /// This function impliments a parallelized version of the /// Held–Karp algorithm using the Rayon crate. /// Note that the performance benefits of using /// the parallel version compared to the sequential /// are only apparent with more than 11 cities. /// /// # Examples /// /// This example comes from the wikipedia page for the /// [Held-Karp algorithm](https://en.wikipedia.org/wiki/Held%E2%80%93Karp_algorithm#Example[4]) /// /// ``` /// let distances: Vec<u32> = vec! [ /// 0, 2, 9, 10, /// 1, 0, 6, 4, /// 15, 7, 0, 8, /// 6, 3, 12, 0 /// ]; /// let dist_matrix = held_karp_rust::DistanceMatrix::new(4, distances); /// let result = held_karp_rust::par_travel(dist_matrix); /// assert_eq!(result.0, 21); /// assert_eq!(result.1, vec![0, 2, 3, 1, 0]); /// ``` pub fn par_travel(w_array: DistanceMatrix) -> (u32, Vec<usize>) { // create the hash map let mut dist_map: HashMap<usize, Vec<(usize, Option<u32>)>> = HashMap::new(); // calculate the void column let void_col: Vec<(usize, Option<u32>)> = (0..w_array.size) .map(|i: usize| (0, w_array.get(i, 0))) .collect(); // println!("[], {:?}", void_col); // add empty set column to distance map dist_map.insert(0, void_col); // for each combination size for set_len in 1..(w_array.size - 1) { // combinations of length set_len let comb_by_len = (1..w_array.size).combinations(set_len).collect_vec(); // println!("{:?}", comb_by_len); // iterate through all combinations of a given length let new_cols: Vec<(usize, Vec<(usize, Option<u32>)>)> = comb_by_len .par_iter() .map(|comb| { let comb_num = set_to_num(comb); let mut dist: Vec<(usize, Option<u32>)> = vec![(0, None); w_array.size]; // for each possible value (1..w_array.size) // filter out all values if it's contained in the the combination .filter(|i| !comb.contains(i)) .for_each(|i| { // TODO: take the min from here let min_val: Option<(usize, Option<u32>)> = comb .iter() .map(|k| { let w = w_array.get(i, *k); // gets the correct column for A - Vx let d_col: usize = comb_num ^ (1usize << k); // gets the value of D[Vx][A - Vx] let d_val: Option<u32> = dist_map[&d_col][*k].1; // add the two together let val: Option<u32> = match (w, d_val) { (Some(x), Some(y)) => Some(x + y), // if both are not infinity, add them (_, _) => None, // else (at least one is infinity, retrn none }; (*k, val) }) .filter(|i| i.1.is_some()) .min_by_key(|i| i.1); // Find the minimum value that is not None dist[i] = match min_val { None => (0, None), Some(x) => x, }; }); // println!("{:?}, {:?}", comb, dist); // dist_map.insert(comb.clone(), dist); (comb_num, dist) }).collect(); new_cols.iter().for_each(|i| { dist_map.insert(i.0.clone(), i.1.clone()); }); } let mut comb: Vec<usize> = (1..w_array.size).collect(); let comb_num: usize = set_to_num(&comb); let last_val: (usize, Option<u32>) = comb .iter() .map(|k| { let w = w_array.get(0, *k); // gets the correct column for A - Vx let d_col: usize = comb_num ^ (1usize << k); // gets the value of D[Vx][A - Vx] let d_val: Option<u32> = dist_map[&d_col][*k].1; // add the two together let val: Option<u32> = match (w, d_val) { (Some(x), Some(y)) => Some(x + y), // if both are not infinity, add them (_, _) => None, // else (at least one is infinity, retrn none }; (*k, val) }) .filter(|i| i.1.is_some()) .min_by_key(|i| i.1) .unwrap(); let mut trip: Vec<usize> = vec![0]; // calculate minimum trip // set next city let mut next: usize = last_val.0; trip.push(next); comb = comb.iter().filter(|i| **i != next).cloned().collect(); let mut comb_num: usize = set_to_num(&comb); while comb_num > 0 { next = dist_map[&comb_num][next].0; trip.push(next); comb_num = comb_num ^ (1 << next); } trip.push(0); // let last_comb: Vec<usize> = (1..w_array.size).collect(); // println!("{:?}: [({}, {:?})]", last_comb, last_val.0, last_val.1); // println!("Trip: {:?}", trip); // println!("Distance: {}", last_val.1.unwrap()); (last_val.1.unwrap(), trip) } // Tests #[cfg(test)] mod tests { use super::*; #[test] fn four_d() { let distances: Vec<u32> = vec![ 0, 2, 9, 0, 1, 0, 6, 4, 0, 7, 0, 8, 6, 3, 0, 0 ]; let w: DistanceMatrix = DistanceMatrix::new(4, distances); let result = travel(w); assert_eq!(result.0, 21); assert_eq!(result.1, vec![0, 2, 3, 1, 0]); } #[test] fn five_d() { let distances: Vec<u32> = vec![ 0, 1, 0, 1, 5, 9, 0, 3, 2, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 3, 3, 0, 0, 0, 0, ]; let w: DistanceMatrix = DistanceMatrix::new(5, distances); let result = travel(w); assert_eq!(result.0, 14); assert_eq!(result.1, vec![0, 1, 2, 3, 4, 0]); } #[test] fn par_four_d() { let distances: Vec<u32> = vec![ 0, 2, 9, 0, 1, 0, 6, 4, 0, 7, 0, 8, 6, 3, 0, 0 ]; let w: DistanceMatrix = DistanceMatrix::new(4, distances); let result = par_travel(w); assert_eq!(result.0, 21); assert_eq!(result.1, vec![0, 2, 3, 1, 0]); } #[test] fn par_five_d() { let distances: Vec<u32> = vec![ 0, 1, 0, 1, 5, 9, 0, 3, 2, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 3, 3, 0, 0, 0, 0, ]; let w: DistanceMatrix = DistanceMatrix::new(5, distances); let result = par_travel(w); assert_eq!(result.0, 14); assert_eq!(result.1, vec![0, 1, 2, 3, 4, 0]); } #[test] #[should_panic] fn invalid_distance_matrix_1() { let d: Vec<u32> = vec![0, 1]; let _w: DistanceMatrix = DistanceMatrix::new(2, d); } #[test] #[should_panic] fn invalid_distance_get() { let d: Vec<u32> = vec![ 0, 1, 2, 0 ]; let w: DistanceMatrix = DistanceMatrix::new(2, d); let _x = w.get(2, 0); } #[test] fn vec_to_bin1() { let mut vec_set: Vec<usize> = vec![4]; let mut res = set_to_num(&vec_set); assert_eq!(16, res); vec_set = vec![1, 2, 3, 4]; res = set_to_num(&vec_set); assert_eq!(30, res); } }
use crate::{ audio, interrupts, memory::io::{Interrupt, IoRegisters, Timer}, scheduler::{EventTag, Scheduler}, Gba, }; pub fn started(idx: usize, ioregs: &mut IoRegisters, scheduler: &Scheduler) { let timer = &mut ioregs.timers[idx]; timer.origin = ioregs.time; timer.counter = timer.reload; if timer.control.count_up_timing() { return; } let event_tag = EventTag::timer(idx); let overflow_fn = match idx { 0 => overflow::<0>, 1 => overflow::<1>, 2 => overflow::<2>, 3 => overflow::<3>, _ => panic!("invalid timer"), }; let overflow_cycles = (0x10000u32 - timer.counter as u32) << timer.control.prescaler_shift(); scheduler.unschedule(event_tag); scheduler.schedule(overflow_fn, overflow_cycles, event_tag); } pub fn stopped(timer: usize, _timers: &mut [Timer; 4], scheduler: &Scheduler) { scheduler.unschedule(EventTag::timer(timer)); } pub fn reschedule(idx: usize, timers: &mut [Timer; 4], scheduler: &Scheduler) { let event_tag = EventTag::timer(idx); let timer = &mut timers[idx]; scheduler.unschedule(event_tag); if !timer.control.count_up_timing() { let overflow_fn = match idx { 0 => overflow::<0>, 1 => overflow::<1>, 2 => overflow::<2>, 3 => overflow::<3>, _ => panic!("invalid timer"), }; let overflow_cycles = (0x10000u32 - timer.counter as u32) << timer.control.prescaler_shift(); scheduler.schedule(overflow_fn, overflow_cycles, event_tag); } } pub fn flush(timer: &mut Timer, now: u64) { if !timer.control.started() || timer.control.count_up_timing() { return; } // This should NEVER overflow before the overflow function is called by the scheduler, which should reset the timer's counter. let delta = now - timer.origin; if delta >= (1 << timer.control.prescaler_shift()) { timer.counter += ((now - timer.origin) >> timer.control.prescaler_shift()) as u16; timer.origin = now; } } pub fn overflow<const TIMER: usize>(gba: &mut Gba) { let mut overflows = 1u32; { let timer = &mut gba.mem.ioregs.timers[TIMER]; timer.counter = timer.reload; timer.origin = gba.mem.ioregs.time; let overflow_cycles = (0x10000u32 - timer.counter as u32) << timer.control.prescaler_shift(); gba.scheduler .schedule(overflow::<TIMER>, overflow_cycles, EventTag::timer(TIMER)); } after_overflow(TIMER, gba); let mut idx = TIMER + 1; while overflows > 0 && idx < 4 { let timer = &mut gba.mem.ioregs.timers[idx]; if !timer.control.count_up_timing() || !timer.control.started() { break; } let mut rem = overflows; overflows = 0; while rem >= (0x10000u32 - timer.counter as u32) { overflows += 1; rem -= 0x10000u32 - timer.counter as u32; timer.counter = timer.reload; } timer.counter += rem as u16; for _ in 0..overflows { after_overflow(idx, gba); } idx += 1; } } fn after_overflow(idx: usize, gba: &mut Gba) { if gba.mem.ioregs.timers[idx].control.irq_enable() { interrupts::raise(Interrupt::timer(idx), &mut gba.mem.ioregs, &gba.scheduler); } if idx == 0 || idx == 1 { audio::check_fifo_timer_overflow(idx, gba); } }
use std::path::Path; use std::{env, fmt, fs, io, panic, thread}; use backtrace::Backtrace; pub fn setup(logging_path: &Path) -> Result<(), fern::InitError> { let level_filter = match std::env::var("XI_LOG") { Ok(level) => match level.to_lowercase().as_ref() { "trace" => log::LevelFilter::Trace, "debug" => log::LevelFilter::Debug, _ => log::LevelFilter::Info, }, // Default to info Err(_) => log::LevelFilter::Info, }; create_log_directory(logging_path)?; let fern_dispatch = fern::Dispatch::new() .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message, )) }) .level(level_filter) .chain(fern::log_file(logging_path)?); // Start fern fern_dispatch.apply()?; info!("Logging with fern is set up to level {}", level_filter); info!("Writing logs to: {}", logging_path.display()); setup_panic_handler(); Ok(()) } struct Shim(Backtrace); impl fmt::Debug for Shim { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { if env::var("RUST_BACKTRACE").is_ok() { write!(fmt, "\n{:?}", self.0) } else { Ok(()) } } } fn setup_panic_handler() { panic::set_hook(Box::new(|info| { let backtrace = Backtrace::new(); let thread = thread::current(); let thread = thread.name().unwrap_or("unnamed"); let msg = match info.payload().downcast_ref::<&'static str>() { Some(s) => *s, None => match info.payload().downcast_ref::<String>() { Some(s) => &**s, None => "Box<Any>", }, }; match info.location() { Some(location) => { error!( target: "panic", "thread '{}' panicked at '{}': {}:{}{:?}", thread, msg, location.file(), location.line(), Shim(backtrace) ); } None => error!( target: "panic", "thread '{}' panicked at '{}'{:?}", thread, msg, Shim(backtrace) ), } })); } /// This function tries to create the parent directories for a file /// /// It wraps around the `parent()` function of `Path` which returns an `Option<&Path>` and /// `fs::create_dir_all` which returns an `io::Result<()>`. /// /// This allows you to use `?`/`try!()` to create the dir and you recive the additional custom error for when `parent()` /// returns nothing. /// /// # Errors /// This can return an `io::Error` if `fs::create_dir_all` fails or if `parent()` returns `None`. /// See `Path`'s `parent()` function for more details. /// # Examples /// ``` /// use std::path::Path; /// use std::ffi::OsStr; /// /// let path_with_file = Path::new("/some/directory/then/file"); /// assert_eq!(Some(OsStr::new("file")), path_with_file.file_name()); /// assert_eq!(create_log_directory(path_with_file).is_ok(), true); /// /// let path_with_other_file = Path::new("/other_file"); /// assert_eq!(Some(OsStr::new("other_file")), path_with_other_file.file_name()); /// assert_eq!(create_log_directory(path_with_file).is_ok(), true); /// /// // Path that is just the root or prefix: /// let path_without_file = Path::new("/"); /// assert_eq!(None, path_without_file.file_name()); /// assert_eq!(create_log_directory(path_without_file).is_ok(), false); /// ``` fn create_log_directory(path_with_file: &Path) -> io::Result<()> { let log_dir = path_with_file.parent().ok_or_else(|| io::Error::new( io::ErrorKind::InvalidInput, format!( "Unable to get the parent of the following Path: {}, Your path should contain a file name", path_with_file.display(), ), ))?; fs::create_dir_all(log_dir)?; Ok(()) }
use util::*; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut nums = input::lines::<usize>(&std::env::args().nth(1).unwrap()); nums.sort(); let mut hi = nums.len() - 1; let mut lo = 0; while nums[lo] + nums[hi] != 2020 { if nums[lo] + nums[hi] > 2020 { hi -= 1; } else { lo += 1; } } println!("{}", nums[hi] * nums[lo]); Ok(()) }
pub(crate) use self::{ stream::Stream, transport::ClickhouseTransport, }; mod read_to_end; pub(crate) mod transport; pub(crate) mod stream;
#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(dead_code)] #![cfg_attr(feature = "cargo-clippy", allow(expl_impl_clone_on_copy))] include!("bindings.rs"); #[cfg(node8)] mod node8; #[cfg(node8)] pub use self::node8::Status; #[cfg(node9)] mod node9; #[cfg(node9)] pub use self::node9::Status;
use std::fs::create_dir_all; use std::path::{Path, PathBuf}; use once_cell::sync::Lazy; pub static CALTRAIND_PATH: Lazy<PathBuf> = Lazy::new(|| { let p = PathBuf::from("/tmp/caltraind"); create_dir_all(&p).expect("error creating /tmp/caltraind"); p }); pub static PID_PATH: Lazy<PathBuf> = Lazy::new(|| Path::new(CALTRAIND_PATH.as_os_str()).join("pid")); pub static SOCKET_PATH: Lazy<PathBuf> = Lazy::new(|| Path::new(CALTRAIND_PATH.as_os_str()).join("socket")); pub static STDOUT_PATH: Lazy<PathBuf> = Lazy::new(|| Path::new(CALTRAIND_PATH.as_os_str()).join("out.log")); pub static STDERR_PATH: Lazy<PathBuf> = Lazy::new(|| Path::new(CALTRAIND_PATH.as_os_str()).join("err.log"));
use core::sync::atomic::{AtomicBool, Ordering::SeqCst}; use embedded_graphics::{geometry::Size, pixelcolor::Rgb565, prelude::RgbColor}; pub const WIDTH: u16 = 240; pub const HEIGHT: u16 = 240; pub const VERT_LINES: u16 = 320; pub const SIZE: Size = Size::new(WIDTH as u32, HEIGHT as u32); pub type PixelFormat = Rgb565; pub const BACKGROUND_COLOR: PixelFormat = PixelFormat::BLACK; #[derive(Debug)] #[repr(transparent)] pub struct AtomicDisplayAwakeState(AtomicBool); impl AtomicDisplayAwakeState { pub const fn new(initial_state: bool) -> Self { AtomicDisplayAwakeState(AtomicBool::new(initial_state)) } pub fn awaken(&self) { self.0.store(true, SeqCst); } pub fn is_awake(&self) -> bool { self.0.load(SeqCst) } pub fn get_and_clear(&self) -> bool { self.0.swap(false, SeqCst) } }
pub struct Register { val: u8, } pub struct Core { ix: Register, iy: Register, y: Register, a: Register, b: Register, c: Register, d: Register, e: Register, h: Register, l: Register, } impl Register { pub fn new() -> Register { Register { val: 0, } } pub fn set(&mut self, val: u8) { self.val = val; } pub fn get(&self) -> u8 { self.val } } impl Core { pub fn new() -> Core { Core { ix: Register::new(), iy: Register::new(), y: Register::new(), a: Register::new(), b: Register::new(), c: Register::new(), d: Register::new(), e: Register::new(), h: Register::new(), l: Register::new(), } } pub fn print_status(&self) { println!("CORE STATUS"); println!("-----------"); println!("Registers"); println!("ix:\t{}", self.ix.get()); println!("iy:\t{}", self.iy.get()); println!("y:\t{}", self.y.get()); println!("a:\t{}", self.a.get()); println!("b:\t{}", self.b.get()); println!("c:\t{}", self.c.get()); println!("d:\t{}", self.d.get()); println!("e:\t{}", self.e.get()); println!("h:\t{}", self.h.get()); println!("l:\t{}", self.l.get()); } pub fn ld0(&self, r: &mut Register, rp: &Register) { r.set(rp.get()); } pub fn ld1(&self, r: &mut Register, n: u8) { r.set(n); } pub fn inc0(&self, r: &mut Register) { r.set(r.get() + 1); } pub fn add0(&mut self, r: &Register) { self.a.set(self.a.get() + r.get()); } } #[cfg(test)] mod tests { use super::*; #[test] fn test_ld0() { let core = Core::new(); let mut r = Register::new(); let mut rp = Register::new(); r.set(0); rp.set(1); core.ld0(&mut r, &rp); assert_eq!(r.get(), 1); assert_eq!(rp.get(), 1); } #[test] fn test_1d1() { let core = Core::new(); let mut r = Register::new(); r.set(0); core.ld1(&mut r, 1); assert_eq!(r.get(), 1); } #[test] fn test_inc0() { let core = Core::new(); let mut r = Register::new(); r.set(0); core.inc0(&mut r); assert_eq!(r.get(), 1); } #[test] fn test_add0() { let mut core = Core::new(); let mut r = Register::new(); r.set(1); core.add0(&r); assert_eq!(core.a.get(), 1); } }
use crate::redis_wrapper::init::{self, read_hashmap_key, write_hashmap_key}; use redis::Connection; pub fn get_topics_list(con: &mut Connection) { let hm = read_hashmap_key(con, &("topics".to_string())); println!("hm = {:?}", hm); }
use thiserror::Error; use serde::Deserialize; use crate::{ web::scraping::Html, util::bytes, }; // The bitrate and size fields come from the same element. It's not practical to handle // them as separate results. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize)] pub struct Data { pub bitrate: u16, pub size: usize } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)] pub enum Error { #[error("missing bitrate")] MissingBitrate, #[error("invalid bitrate")] InvalidBitrate, #[error("missing size")] MissingSize, #[error("invalid size")] InvalidSize, } pub fn scrap(page: &str) -> Result<Data, Error> { let doc = Html::parse_fragment(page); log::trace!("scraping html: {:#?}", doc); let mut texts = doc .root_element() .text(); let bitrate_text = texts .nth(1) .ok_or(Error::MissingBitrate)?; let bitrate: u16 = bitrate_text .trim_start() .splitn(2, ' ') .next() .expect("split should always yield at least one item") .parse() .ok() .filter( |&bitrate| bitrate > 0 ) .ok_or(Error::InvalidBitrate)?; let size_text = texts .nth(1) .ok_or(Error::MissingSize)?; let size = size_text .parse::<bytes::Mb>() .or(Err(Error::InvalidSize))? .into(); Ok( Data { bitrate, size } ) } #[cfg(test)] mod tests { use super::*; #[test] fn test_scrap() { // <b>Bitrate:</b> 320 kbps <br><b>File Size:</b> 21.16 mb assert_eq!( scrap("<b>Bitrate:</b> 320 kbps <br><b>File Size:</b> 21.16 mb"), Ok( Data { bitrate: 320, size: 22187868 } ) ) } }
// TODO: This file is utter mess, should be refactored #[macro_use] extern crate glium; #[macro_use] extern crate itertools; extern crate nalgebra as na; extern crate cam; extern crate vecmath; extern crate rand; extern crate time; mod marching_cubes_data; mod linspace; use glium::Surface; use glium::backend::glutin::Display; use linspace::linspace; use glium::texture::buffer_texture::BufferTexture; use glium::texture::buffer_texture::BufferTextureType; use glium::glutin::{Event, WindowEvent, dpi::{LogicalSize, LogicalPosition}, KeyboardInput}; use glium::glutin::ElementState; use glium::glutin::VirtualKeyCode; use cam::{Camera, CameraPerspective}; use glium::texture::texture2d::Texture2d; use glium::texture::RawImage2d; use rand::{SeedableRng, XorShiftRng, Rng}; use std::cmp; const MAX_METABALLS_SIZE: usize = 64; #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 3], } implement_vertex!(Vertex, position); impl Default for Vertex { fn default() -> Self { Vertex { position: [0.0f32, 0.0, 0.0] } } } #[derive(Copy, Clone)] struct BorderVertex { position: [f32; 3], tex_coord: [f32; 2], } implement_vertex!(BorderVertex, position, tex_coord); impl BorderVertex { fn new(pos: [f32; 3], tex: [f32; 2]) -> BorderVertex { BorderVertex { position: pos, tex_coord: tex, } } } fn create_tri_table_texture(display: &Display) -> BufferTexture<(i8, i8, i8, i8)> { BufferTexture::immutable(display, &marching_cubes_data::tri_table(), BufferTextureType::Integral) .expect("could not create triangle table buffer") } fn load_shaders(display: &Display) -> (glium::Program, glium::Program) { let vertex_shader_src = include_str!("Shaders/metaball_vertex.glsl"); let geometry_shader_src = include_str!("Shaders/metaball_geometry.glsl"); let fragment_shader_src = include_str!("Shaders/metaball_fragment.glsl"); let metaball_program = glium::Program::from_source(display, vertex_shader_src, fragment_shader_src, Some(geometry_shader_src)) .expect("couldn't create border program"); let border_vertex_shader = include_str!("Shaders/border_vertex.glsl"); let border_fragment_shader = include_str!("Shaders/border_fragment.glsl"); let border_program = glium::Program::from_source(display, border_vertex_shader, border_fragment_shader, None) .expect("couldn't create border program"); (metaball_program, border_program) } fn get_grid(a: f32, b: f32, resolution: usize) -> Vec<Vertex> { iproduct!(linspace(a, b, resolution), linspace(a, b, resolution), linspace(a, b, resolution)) .map(|(x, y, z)| Vertex { position: [x, y, z] }) .collect() } fn get_border_vertices(start: f32, end: f32) -> Vec<BorderVertex> { let mut res = Vec::with_capacity(36); let v = [(start, start, start), (end, start, start), (end, end, start), (start, end, start), (start, start, end), (end, start, end), (end, end, end), (start, end, end)]; for face in 0..6 { let _00 = match face { 0 => v[0], 1 => v[1], 2 => v[5], 3 => v[4], 4 => v[4], 5 => v[3], _ => unreachable!(), }; let _01 = match face { 0 => v[1], 1 => v[5], 2 => v[4], 3 => v[0], 4 => v[5], 5 => v[2], _ => unreachable!(), }; let _10 = match face { 0 => v[3], 1 => v[2], 2 => v[6], 3 => v[7], 4 => v[0], 5 => v[7], _ => unreachable!(), }; let _11 = match face { 0 => v[2], 1 => v[6], 2 => v[7], 3 => v[3], 4 => v[1], 5 => v[6], _ => unreachable!(), }; res.push(BorderVertex::new([_00.0, _00.1, _00.2], [0.0, 0.0])); res.push(BorderVertex::new([_10.0, _10.1, _10.2], [50.0, 0.0])); res.push(BorderVertex::new([_01.0, _01.1, _01.2], [0.0, 50.0])); res.push(BorderVertex::new([_10.0, _10.1, _10.2], [50.0, 0.0])); res.push(BorderVertex::new([_11.0, _11.1, _11.2], [50.0, 50.0])); res.push(BorderVertex::new([_01.0, _01.1, _01.2], [0.0, 50.0])); } res } fn get_border_texture(display: &Display) -> Texture2d { let (dim_x, dim_y) = (32, 32); let mut data = Vec::with_capacity(dim_x * dim_y); for y in 0..dim_y { for x in 0..dim_x { if x < dim_x / 16 || y < dim_y / 16 { data.push(0u8); data.push(0); data.push(0); data.push(255); } else { data.push(0); data.push(0); data.push(0); data.push(0); } } } let raw_tex = RawImage2d::from_raw_rgba(data, (dim_x as u32, dim_y as u32)); Texture2d::new(display, raw_tex).expect("couldn't create border texture") } fn update_metaball_positions(metaballs: &mut [(f32, f32, f32, f32)], t: f32) { let mut rng: XorShiftRng = SeedableRng::from_seed([1, 3, 3, 7]); for i in 0..MAX_METABALLS_SIZE { let xtmul = rng.gen::<f32>(); let xoff = rng.gen::<f32>(); let xmul = (rng.gen::<f32>() - 0.5) * 3.5; let ytmul = rng.gen::<f32>(); let yoff = rng.gen::<f32>(); let ymul = (rng.gen::<f32>() - 0.5) * 3.5; let ztmul = rng.gen::<f32>(); let zoff = rng.gen::<f32>(); let zmul = (rng.gen::<f32>() - 0.5) * 3.5; metaballs[i].0 = (t * xtmul + xoff).sin() * xmul; metaballs[i].1 = (t * ytmul + yoff).sin() * ymul; metaballs[i].2 = (t * ztmul + zoff).sin() * zmul; } } fn change_resolution(display: &Display, space_start: f32, space_end: f32, resolution: usize) -> glium::VertexBuffer<Vertex> { let shape = get_grid(space_start, space_end, resolution); glium::VertexBuffer::new(display, &shape) .expect("could not create the vertex buffer with the get_grid") } fn recalculate_step(space_start: f32, space_end: f32, resolution: usize) -> f32 { ((space_end - space_start) / ((resolution - 1) as f32)).abs() } fn main() { let mut events_loop = glium::glutin::EventsLoop::new(); let window = glium::glutin::WindowBuilder::new(); let context = glium::glutin::ContextBuilder::new().with_depth_buffer(24); let display = glium::Display::new(window, context, &events_loop).unwrap(); let mut resolution = 100usize; let space_start = -2.0f32; let space_end = 2.0f32; let mut step = recalculate_step(space_start, space_end, resolution); println!("step: {}", step); let mut vertex_buffer = change_resolution(&display, space_start, space_end, resolution); let indices = glium::index::NoIndices(glium::index::PrimitiveType::Points); let border_texture = get_border_texture(&display); let border_texture = border_texture.sampled() .wrap_function(glium::uniforms::SamplerWrapFunction::Repeat) .minify_filter(glium::uniforms::MinifySamplerFilter::LinearMipmapLinear) .magnify_filter(glium::uniforms::MagnifySamplerFilter::Linear) .anisotropy(16); let border = get_border_vertices(space_start, space_end); let border_vertex_buf = glium::VertexBuffer::new(&display, &border) .expect("could not create vertex buffer with borders"); let border_indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList); let tri_table = create_tri_table_texture(&display); let (program, border_program) = load_shaders(&display); let mut metaballs = [(0.0f32, 0.0f32, 0.0f32, 0.0f32); MAX_METABALLS_SIZE]; let mut metaballs_size = 0usize; let mut metaballs_buffer: BufferTexture<(f32, f32, f32, f32)> = BufferTexture::dynamic(&display, &metaballs, BufferTextureType::Float) .expect("couldn't create metaballs buffer"); let dimens = display.get_framebuffer_dimensions(); let mut camera = Camera::new([0.0f32, 0.0, 4.0]); let mut camera_perspective = CameraPerspective { fov: 45.0, near_clip: 0.2, far_clip: 1024.0, aspect_ratio: dimens.0 as f32 / dimens.1 as f32, }; let mut t = 0.5f32; let mut dt = 0.0f32; let mut ctrl_down = false; let mut rmb_down = false; let (mut mouse_x, mut mouse_y) = (0, 0); let mut directionwise_move_factor = 0.0f32; let mut sidewise_move_factor = 0.0f32; let mut upwards_move_factor = 0.0f32; let mut pitch = 0.0f32; let mut yaw = 0.0f32; let mut now: f64; let mut previous = 0.0f64; let mut r_down = false; let mut running = true; while running { now = time::precise_time_s(); let delta = (now - previous) as f32; t += dt * delta; let cam_pos = camera.position; let cam_pos: na::Vector3<_> = cam_pos.into(); let cam_dir = camera.forward; let cam_dir: na::Vector3<_> = cam_dir.into(); let sideways = camera.right; let sideways: na::Vector3<_> = sideways.into(); let upwards = camera.up; let upwards: na::Vector3<_> = upwards.into(); let new_cam_pos = cam_pos + cam_dir * directionwise_move_factor * delta * 2.0; let new_cam_pos = new_cam_pos + sideways * sidewise_move_factor * delta * 2.0; let new_cam_pos = new_cam_pos + upwards * upwards_move_factor * delta * 2.0; camera.position = *new_cam_pos.as_ref(); update_metaball_positions(&mut metaballs, t); let mut target = display.draw(); target.clear_color_and_depth((0.1, 0.1, 0.4, 1.0), 1.0); let border_uniforms = uniform! { tex: border_texture, persp: camera_perspective.projection(), view: camera.orthogonal() }; let border_params = glium::DrawParameters { blend: glium::Blend { alpha: glium::BlendingFunction::Addition { source: glium::LinearBlendingFactor::SourceAlpha, destination: glium::LinearBlendingFactor::OneMinusSourceAlpha, }, color: glium::BlendingFunction::Addition { source: glium::LinearBlendingFactor::SourceAlpha, destination: glium::LinearBlendingFactor::OneMinusSourceAlpha, }, ..Default::default() }, backface_culling: glium::draw_parameters::BackfaceCullingMode::CullCounterClockwise, ..Default::default() }; target.draw(&border_vertex_buf, &border_indices, &border_program, &border_uniforms, &border_params) .unwrap(); // this scope is important, since we don't want the metaballs_buffer to be borrowed // for the rest of the loop { let uniforms = uniform! { perspective: camera_perspective.projection(), metaballs: &metaballs_buffer, metaballsLength: metaballs_size as i32, view: camera.orthogonal(), triTableTex: &tri_table, cubeSideLength: step, isolevel: 0.5f32, light: (-1.0f32, 1.0f32, 1.0f32), eye: (new_cam_pos.x, new_cam_pos.y, new_cam_pos.z), }; let params = glium::DrawParameters { depth: glium::Depth { test: glium::draw_parameters::DepthTest::IfLess, write: true, ..Default::default() }, backface_culling: glium::draw_parameters::BackfaceCullingMode::CullClockwise, ..Default::default() }; target.draw(&vertex_buffer, &indices, &program, &uniforms, &params) .unwrap(); target.finish().unwrap(); } macro_rules! kbd { (pressed $key:ident) => { WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::$key), .. }, .. } }; (released $key:ident) => { WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Released, virtual_keycode: Some(VirtualKeyCode::$key), .. }, .. } }; } events_loop.poll_events(|ev| { match ev { Event::WindowEvent { event, .. } => match event { WindowEvent::CloseRequested | WindowEvent::Destroyed => running = false, WindowEvent::Resized(LogicalSize { width, height }) => camera_perspective.aspect_ratio = width as f32 / height as f32, kbd!(pressed LControl) => ctrl_down = true, kbd!(released LControl) => ctrl_down = false, kbd!(pressed R) => r_down = true, kbd!(released R) => r_down = false, kbd!(pressed W) => directionwise_move_factor = -1.0, kbd!(released W) => directionwise_move_factor = 0.0, kbd!(pressed S) => directionwise_move_factor = 1.0, kbd!(released S) => directionwise_move_factor = 0.0, kbd!(pressed D) => sidewise_move_factor = 1.0, kbd!(released D) => sidewise_move_factor = 0.0, kbd!(pressed A) => sidewise_move_factor = -1.0, kbd!(released A) => sidewise_move_factor = 0.0, kbd!(pressed Space) => upwards_move_factor = 1.0, kbd!(released Space) => upwards_move_factor = 0.0, kbd!(pressed LShift) => upwards_move_factor = -1.0, kbd!(released LShift) => upwards_move_factor = 0.0, kbd!(released Q) => add_random_metaball(&mut metaballs, &mut metaballs_size), kbd!(released E) => remove_random_metaball(&mut metaballs_size), WindowEvent::MouseWheel { delta, .. } if r_down => { let amt = match delta { glium::glutin::MouseScrollDelta::LineDelta(_, y) => y, glium::glutin::MouseScrollDelta::PixelDelta(LogicalPosition { y, .. }) => y as f32, }; println!("amt: {}", amt); resolution = cmp::max( cmp::min( resolution as i32 + amt as i32 * if resolution < 20 { 1 } else { 10 }, 200, ), 2, ) as usize; vertex_buffer = change_resolution(&display, space_start, space_end, resolution); step = recalculate_step(space_start, space_end, resolution); println!("grid resolution: {}", resolution); } WindowEvent::MouseWheel { delta, .. } if ctrl_down => { let amt = match delta { glium::glutin::MouseScrollDelta::LineDelta(_, y) => y, glium::glutin::MouseScrollDelta::PixelDelta(LogicalPosition { y, .. }) => y as f32, }; let fov = camera_perspective.fov; camera_perspective.fov = (fov + amt).min(120.0).max(10.0); println!("fov: {}", (fov + amt).min(120.0).max(10.0)); } WindowEvent::MouseWheel { delta, .. } => { let amt = match delta { glium::glutin::MouseScrollDelta::LineDelta(_, y) => y, glium::glutin::MouseScrollDelta::PixelDelta(LogicalPosition { y, .. }) => y as f32, }; dt += amt; } WindowEvent::MouseInput { state: ElementState::Pressed, button: glium::glutin::MouseButton::Right, .. } => rmb_down = true, WindowEvent::MouseInput { state: ElementState::Released, button: glium::glutin::MouseButton::Right, .. } => rmb_down = false, WindowEvent::CursorMoved { position: LogicalPosition { x, y }, .. } if rmb_down => { let x = x as i32; let y = y as i32; pitch = pitch - (y - mouse_y) as f32 / 1000.0; pitch = pitch.min(90.0f32.to_radians()).max(-90.0f32.to_radians()); yaw = yaw + (x - mouse_x) as f32 / 1000.0; camera.set_yaw_pitch(yaw, pitch); mouse_x = x; mouse_y = y; } WindowEvent::CursorMoved { position: LogicalPosition { x, y }, .. } => { mouse_x = x as i32; mouse_y = y as i32; } _ => (), }, _ => (), } }); update_metaballs(&mut metaballs, &mut metaballs_buffer); previous = now; } } fn update_metaballs(metaballs: &mut [(f32, f32, f32, f32)], metaballs_buffer: &mut BufferTexture<(f32, f32, f32, f32)>) { metaballs_buffer.write(&metaballs); } fn add_random_metaball(metaballs: &mut [(f32, f32, f32, f32)], metaballs_size: &mut usize) { if *metaballs_size == MAX_METABALLS_SIZE { return; } metaballs[*metaballs_size].3 = if rand::random::<f32>() > 0.1 { 0.4 + rand::random::<f32>() * 0.4 } else { -0.2 - rand::random::<f32>() * 0.4 }; *metaballs_size += 1; println!("metaballs: {}", *metaballs_size); } fn remove_random_metaball(metaballs_size: &mut usize) { if *metaballs_size == 0 { return; } *metaballs_size -= 1; println!("metaballs: {}", *metaballs_size); }