text
stringlengths
8
4.13M
use crate::crusty_graph::{CrustyGraph, NodeIndex}; use crate::CrustyError; pub use logical_op::*; use serde_json::{json, Value}; use std::collections::HashMap; mod logical_op; use std::default::Default; use std::fmt; /// OpIndex is used to identify nodes in the LogicalPlan. pub type OpIndex = NodeIndex; /// Graph where nodes represent logical operations and edges represent the flow of data. pub struct LogicalPlan { /// Graph of the logical plan. dataflow: CrustyGraph<LogicalOp>, /// The root represents final output operation. Root does not work if the graph contains any unconnected components. root: Option<OpIndex>, } impl Default for LogicalPlan { fn default() -> Self { Self::new() } } impl LogicalPlan { /// Creates an empty logical plan. pub fn new() -> Self { Self { dataflow: CrustyGraph::new(), root: None, } } /// Adds a node with an associated LogicalOp to the logical plan and returns the index of the added node. /// /// # Arguments /// /// * `operator` - Operator to add to the logical plan. pub fn add_node(&mut self, operator: LogicalOp) -> OpIndex { let index = self.dataflow.add_node(operator); if self.root.is_none() { self.root = Some(index) } index } /// Adds from source to target. /// /// In the logical plan representation data flows from target to source. /// /// # Arguments /// /// * `source` - Data producer. /// * `target` - Data consumer. pub fn add_edge(&mut self, source: OpIndex, target: OpIndex) { if let Some(index) = self.root { if index == target { self.root = Some(source); } } self.dataflow.add_edge(source, target); } /// Returns an iterator over all nodes that 'from' has an edge to. /// /// # Arguments /// /// * `from` - Node to get the edges of. pub fn edges<'a>(&'a self, from: OpIndex) -> impl Iterator<Item = NodeIndex> + 'a { self.dataflow.edges(from) } /// Gets the index of the root node, if such a node is present. /// /// The root node represents the final output operation in the logical plan. pub fn root(&self) -> Option<OpIndex> { self.root } /// Returns the LogicalOperation associated with a node. /// /// # Arguments /// /// * `index` - Index of the node to get the logical operation of. pub fn get_operator(&self, index: OpIndex) -> Option<&LogicalOp> { self.dataflow.node_data(index) } /// Returns the total number of nodes present in the graph. pub fn node_count(&self) -> usize { self.dataflow.node_count() } /// Returns the total number of edges present in the graph. pub fn edge_count(&self) -> usize { self.dataflow.edge_count() } /// Serializes the Logical Plan as json. pub fn to_json(&self) -> serde_json::Value { let mut node_map = HashMap::new(); let mut edge_map = HashMap::new(); for (i, node) in self.dataflow.node_references() { node_map.insert(i, node.data()); } for (_, edge) in self.dataflow.edge_references().enumerate() { let source = edge.source(); let targets = edge_map.entry(source).or_insert_with(Vec::new); targets.push(edge.target().to_string()); } return json!({"nodes":node_map, "edges":edge_map, "root":self.root.map(|i| i.to_string())}); } fn map_crusty_err<T>( result: serde_json::Result<T>, err: CrustyError, ) -> Result<T, CrustyError> { match result { Ok(res) => Ok(res), _ => Err(err), } } /// De-Serializes a json representation of the Logical Plan created in to_json pub fn from_json(json: &str) -> Result<Self, CrustyError> { let malformed_err = CrustyError::CrustyError(String::from("Malformatted logical plan json")); let v: Value = LogicalPlan::map_crusty_err(serde_json::from_str(json), malformed_err.clone())?; let nodes: HashMap<String, LogicalOp> = LogicalPlan::map_crusty_err( serde_json::from_value(v["nodes"].clone()), malformed_err.clone(), )?; let edges: HashMap<String, Vec<String>> = LogicalPlan::map_crusty_err( serde_json::from_value(v["edges"].clone()), malformed_err.clone(), )?; let root: Option<String> = LogicalPlan::map_crusty_err( serde_json::from_value(v["root"].clone()), malformed_err.clone(), )?; let mut graph_map = HashMap::new(); let mut plan = LogicalPlan::new(); for (i, val) in nodes.iter() { let node = plan.dataflow.add_node(val.clone()); graph_map.insert(i, node); } if let Some(i) = root { let root_node = graph_map.get(&i).ok_or_else(|| malformed_err.clone())?; plan.root = Some(*root_node); } for (source, targets) in edges.iter() { let source_node = graph_map.get(source).ok_or_else(|| malformed_err.clone())?; for target in targets { let target_node = graph_map .get(&target.to_string()) .ok_or_else(|| malformed_err.clone())?; plan.dataflow.add_edge(*source_node, *target_node); } } Ok(plan) } } impl fmt::Display for LogicalPlan { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.to_json()) } } #[cfg(test)] mod test { use super::*; #[test] fn test_new() { let lp = LogicalPlan::new(); assert_eq!(lp.node_count(), 0); assert_eq!(lp.edge_count(), 0); assert_eq!(lp.root, None); } #[test] fn test_add_node() { let count = 10; let mut lp = LogicalPlan::new(); for i in 0..count { lp.add_node(LogicalOp::Scan(ScanNode { alias: i.to_string(), })); } assert_eq!(lp.node_count(), count); } #[test] fn test_add_edge() { let count = 10; let mut lp = LogicalPlan::new(); let mut prev = lp.add_node(LogicalOp::Scan(ScanNode { alias: 0.to_string(), })); for i in 0..count { let curr = lp.add_node(LogicalOp::Scan(ScanNode { alias: i.to_string(), })); lp.add_edge(curr, prev); prev = curr; } assert_eq!(lp.root, Some(prev)); assert_eq!(lp.edge_count(), count); } #[test] fn test_add_two_edges() { let mut lp = LogicalPlan::new(); let parent = lp.add_node(LogicalOp::Scan(ScanNode { alias: String::from("parent"), })); let child1 = lp.add_node(LogicalOp::Scan(ScanNode { alias: String::from("child1"), })); let child2 = lp.add_node(LogicalOp::Scan(ScanNode { alias: String::from("child2"), })); lp.add_edge(parent, child1); lp.add_edge(parent, child2); assert_eq!(lp.edge_count(), 2); } #[test] fn test_edges() { let mut lp = LogicalPlan::new(); let parent = lp.add_node(LogicalOp::Scan(ScanNode { alias: String::from("parent"), })); let child1 = lp.add_node(LogicalOp::Scan(ScanNode { alias: String::from("child1"), })); let child2 = lp.add_node(LogicalOp::Scan(ScanNode { alias: String::from("child2"), })); lp.add_edge(parent, child1); lp.add_edge(parent, child2); let mut edges = lp.edges(parent); assert_eq!(edges.next(), Some(child2)); assert_eq!(edges.next(), Some(child1)); } #[test] fn test_get_operator() { let count = 5; let mut nodes = Vec::new(); let mut lp = LogicalPlan::new(); for i in 0..count { let index = lp.add_node(LogicalOp::Scan(ScanNode { alias: i.to_string(), })); nodes.push(index); } for i in 0..count { let expected = i.to_string(); match lp.get_operator(nodes[i]) { Some(LogicalOp::Scan(s)) => { assert_eq!(expected, s.alias); } _ => panic!("Incorrect operator"), } } } #[test] fn test_json() { let mut lp = LogicalPlan::new(); let scan = lp.add_node(LogicalOp::Scan(ScanNode { alias: String::from("Table"), })); let project = lp.add_node(LogicalOp::Project(ProjectNode { identifiers: ProjectIdentifiers::Wildcard, })); lp.add_edge(project, scan); let json = lp.to_json(); let new_lp = LogicalPlan::from_json(&json.to_string()).unwrap(); assert_eq!(lp.dataflow.node_count(), new_lp.dataflow.node_count()); assert_eq!(lp.dataflow.edge_count(), new_lp.dataflow.edge_count()); let original_root = lp.dataflow.node_data(lp.root.unwrap()).unwrap(); let new_root = lp.dataflow.node_data(lp.root.unwrap()).unwrap(); match (original_root, new_root) { (LogicalOp::Project(_), LogicalOp::Project(_)) => (), _ => panic!("Incorrect root"), } } }
use common::event::EventPublisher; use common::result::Result; use crate::domain::interaction::{InteractionRepository, InteractionService}; use crate::domain::publication::{PublicationId, PublicationRepository}; use crate::domain::reader::{ReaderId, ReaderRepository}; pub struct DeleteReview<'a> { event_pub: &'a dyn EventPublisher, publication_repo: &'a dyn PublicationRepository, reader_repo: &'a dyn ReaderRepository, interaction_serv: &'a InteractionService, } impl<'a> DeleteReview<'a> { pub fn new( event_pub: &'a dyn EventPublisher, publication_repo: &'a dyn PublicationRepository, reader_repo: &'a dyn ReaderRepository, interaction_serv: &'a InteractionService, ) -> Self { DeleteReview { event_pub, publication_repo, reader_repo, interaction_serv, } } pub async fn exec(&self, reader_id: String, publication_id: String) -> Result<()> { let publication_id = PublicationId::new(publication_id)?; let mut publication = self.publication_repo.find_by_id(&publication_id).await?; let reader_id = ReaderId::new(reader_id)?; let reader = self.reader_repo.find_by_id(&reader_id).await?; self.interaction_serv .delete_review(&reader, &mut publication) .await?; self.publication_repo.save(&mut publication).await?; self.event_pub .publish_all(publication.base().events()?) .await?; Ok(()) } }
use crate::BenchStr; /// a non-optimized naive implementation just using `String` from the std-lib. #[derive(Clone)] pub struct StdLibStringOnly(String); impl BenchStr for StdLibStringOnly { fn from_str(slice: &str) -> Self { Self(String::from(slice)) } fn from_static(slice: &'static str) -> Self { Self(String::from(slice)) } fn from_bin_iter(iter: impl Iterator<Item = u8>) -> Option<Self> where Self: Sized, { let vec: Vec<u8> = iter.collect(); if let Ok(string) = String::from_utf8(vec) { Some(Self(string)) } else { None } } fn from_multiple(iter: impl Iterator<Item = Self>) -> Self where Self: Sized, { let string: String = iter.map(|item| item.0).collect(); Self(string) } fn as_slice(&self) -> &str { self.0.as_str() } fn slice(&self, start: usize, end: usize) -> Option<Self> where Self: Sized, { if let Some(slice) = self.0.get(start..end) { Some(Self(slice.to_owned())) } else { None } } fn into_string(self) -> String { self.0 } }
use crate::decimal::DecimalNumber; use std::{iter::Peekable, str::Chars}; use crate::token::Token; struct Scanner<'a> { characters: Peekable<Chars<'a>>, } impl<'a> Scanner<'_> { fn new(input: &'a str) -> Scanner<'a> { let characters = input.chars().peekable(); Scanner { characters } } fn next(&mut self) -> Option<char> { self.characters.next() } fn peek(&mut self) -> Option<char> { self.characters.peek().copied() } } pub struct Lexer { tokens: Vec<Token>, } impl Lexer { pub fn new(input: &str) -> Lexer { let mut scanner = Scanner::new(input); let mut opt_c: Option<char>; let mut c: char; let mut tokens: Vec<Token> = Vec::new(); loop { opt_c = scanner.peek(); match opt_c { Some(val) => { c = val; scanner.next(); } None => { tokens.push(Token::Eof); //EOF - termination point break; } }; let opt_token: Option<Token> = match c { '+' => Some(Token::Add), '-' => Some(Token::Minus), '*' => Some(Token::Mul), '/' => Some(Token::Div), '±' => Some(Token::PlusMinus), 'e' => Some(Token::EulersNum), 'π' => Some(Token::Pi), '(' => Some(Token::LeftParen), ')' => Some(Token::RightParen), '0'..='9' => Some(Lexer::parse_number(c, false, &mut scanner)), '.' => Some(Lexer::parse_number(c, true, &mut scanner)), ' ' | '\t' | '\n' => continue, //whitespace _ => panic!("Unexpected character: \'{}\'", c), }; match opt_token { Some(t) => tokens.push(t), None => {} } } tokens.reverse(); Lexer { tokens } } pub fn next(&mut self) -> Token { self.tokens.pop().unwrap_or(Token::Eof) } pub fn peek(&mut self) -> Token { self.tokens.last().cloned().unwrap_or(Token::Eof) } fn parse_number(init_c: char, mut found_period: bool, scanner: &mut Scanner) -> Token { let mut number_str = String::from(""); let mut opt_c: Option<char>; let mut c: char; //Add the initial digit (as a character) to the string number_str.push(init_c); //Incrementally read and build the numeric string //as long as there are valid characters loop { opt_c = scanner.peek(); match opt_c { Some(val) => { c = val; } None => break, //STOP: reached EOF }; match c { '0'..='9' => { number_str.push(c); } '.' => { if found_period { //STOP break; } else { found_period = true; number_str.push(c); } } _ => break, //STOP } scanner.next(); } match number_str.chars().last() { Some(val) => { if val == '.' { panic!("Error: numeric literal cannot end in a period. Problematic literal: \"{}\"", number_str); } } None => (), }; let number = DecimalNumber::new(number_str.as_str()); Token::PosNum(number) } } #[cfg(test)] mod tests { use super::*; use crate::token::Token; fn num_eq(_x: &str, _y: Token) { let x = DecimalNumber::new(_x); let y = match _y { Token::PosNum(val) => val, _ => DecimalNumber::new("0"), }; assert_eq!(x, y) } #[test] fn test_simple_number() { let mut lex = Lexer::new("12"); let token = lex.next(); num_eq("12", token); assert_eq!(Token::Eof, lex.next()); } #[test] fn test_simple_addition() { let mut lex = Lexer::new("2 + 3"); num_eq("2", lex.next()); assert_eq!(Token::Add, lex.next()); num_eq("3", lex.next()); assert_eq!(Token::Eof, lex.next()); } #[test] fn test_simple_plus_minus() { let mut lex = Lexer::new("2.3 ± 3.3"); num_eq("2.3", lex.next()); assert_eq!(Token::PlusMinus, lex.next()); num_eq("3.3", lex.next()); assert_eq!(Token::Eof, lex.next()); } #[test] fn test_parenthesis() { let mut lex = Lexer::new("(2 + 3) - 5"); assert_eq!(Token::LeftParen, lex.next()); num_eq("2", lex.next()); assert_eq!(Token::Add, lex.next()); num_eq("3", lex.next()); assert_eq!(Token::RightParen, lex.next()); assert_eq!(Token::Minus, lex.next()); num_eq("5", lex.next()); assert_eq!(Token::Eof, lex.next()); } #[test] fn test_float_1() { let mut lex = Lexer::new("13.095"); num_eq("13.095", lex.next()); assert_eq!(Token::Eof, lex.next()); } #[test] fn test_float_2() { let mut lex = Lexer::new("0.095"); num_eq("0.095", lex.next()); assert_eq!(Token::Eof, lex.next()); } #[test] fn test_float_3() { let mut lex = Lexer::new(".095"); num_eq("0.095", lex.next()); assert_eq!(Token::Eof, lex.next()); } #[test] #[should_panic] fn test_float_4() { Lexer::new("23."); } #[test] #[should_panic] fn test_float_5() { Lexer::new("."); } #[test] #[should_panic] fn test_float_6() { Lexer::new("2 + 5 - 33."); } #[test] fn test_eulers_num() { let mut lex = Lexer::new("e"); assert_eq!(Token::EulersNum, lex.next()); assert_eq!(Token::Eof, lex.next()); } #[test] fn test_pi() { let mut lex = Lexer::new("π"); assert_eq!(Token::Pi, lex.next()); assert_eq!(Token::Eof, lex.next()); } #[test] fn test_eof() { let mut lex = Lexer::new(""); assert_eq!(Token::Eof, lex.next()); } }
pub mod app; pub mod button_state_image; pub mod color_rect; pub mod content; pub mod image_button; pub mod title_bar;
#[doc = "Reader of register CONN_CONFIG"] pub type R = crate::R<u32, super::CONN_CONFIG>; #[doc = "Writer for register CONN_CONFIG"] pub type W = crate::W<u32, super::CONN_CONFIG>; #[doc = "Register CONN_CONFIG `reset()`'s with value 0xe11f"] impl crate::ResetValue for super::CONN_CONFIG { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0xe11f } } #[doc = "Reader of field `RX_PKT_LIMIT`"] pub type RX_PKT_LIMIT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RX_PKT_LIMIT`"] pub struct RX_PKT_LIMIT_W<'a> { w: &'a mut W, } impl<'a> RX_PKT_LIMIT_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 `RX_INTR_THRESHOLD`"] pub type RX_INTR_THRESHOLD_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RX_INTR_THRESHOLD`"] pub struct RX_INTR_THRESHOLD_W<'a> { w: &'a mut W, } impl<'a> RX_INTR_THRESHOLD_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 `MD_BIT_CLEAR`"] pub type MD_BIT_CLEAR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MD_BIT_CLEAR`"] pub struct MD_BIT_CLEAR_W<'a> { w: &'a mut W, } impl<'a> MD_BIT_CLEAR_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `DSM_SLOT_VARIANCE`"] pub type DSM_SLOT_VARIANCE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DSM_SLOT_VARIANCE`"] pub struct DSM_SLOT_VARIANCE_W<'a> { w: &'a mut W, } impl<'a> DSM_SLOT_VARIANCE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `SLV_MD_CONFIG`"] pub type SLV_MD_CONFIG_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SLV_MD_CONFIG`"] pub struct SLV_MD_CONFIG_W<'a> { w: &'a mut W, } impl<'a> SLV_MD_CONFIG_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `EXTEND_CU_TX_WIN`"] pub type EXTEND_CU_TX_WIN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EXTEND_CU_TX_WIN`"] pub struct EXTEND_CU_TX_WIN_W<'a> { w: &'a mut W, } impl<'a> EXTEND_CU_TX_WIN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `MASK_SUTO_AT_UPDT`"] pub type MASK_SUTO_AT_UPDT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MASK_SUTO_AT_UPDT`"] pub struct MASK_SUTO_AT_UPDT_W<'a> { w: &'a mut W, } impl<'a> MASK_SUTO_AT_UPDT_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `CONN_REQ_1SLOT_EARLY`"] pub type CONN_REQ_1SLOT_EARLY_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CONN_REQ_1SLOT_EARLY`"] pub struct CONN_REQ_1SLOT_EARLY_W<'a> { w: &'a mut W, } impl<'a> CONN_REQ_1SLOT_EARLY_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } impl R { #[doc = "Bits 0:3 - Defines a limit for the number of Rx packets that can be re-ceived by the LLH. Default maximum value is 0xF.Minimum value shall be '1' or no packet will be stored in the Rx FIFO."] #[inline(always)] pub fn rx_pkt_limit(&self) -> RX_PKT_LIMIT_R { RX_PKT_LIMIT_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - This register field allows setting a threshold for the packet received interrupt to the firmware. For example if the value programmed is 0x2 - then HW will generate interrupt only on receiving the second packet. In any case if the received number of packets in a conn event is less than the threshold or there are still packets (less than threshold) pending in the Rx FIFO, HW will generate the interrupt at the ce_close. Min value possible is 1. Max value depends on the Rx FIFO capacity."] #[inline(always)] pub fn rx_intr_threshold(&self) -> RX_INTR_THRESHOLD_R { RX_INTR_THRESHOLD_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bit 8 - This register field indicates whether the MD (More Data) bit needs to be controlled by 'software' or, 'hardware and soft-ware logic combined'. 1 - MD bit is exclusively controlled by software, ie based on status of CE_CNFG_STS_REGISTER\\[6\\] - md bit. 0 - MD Bit in the transmitted pdu is controlled by software and hardware logic. MD bit is set in transmitted packet, only if the software has set the md bit in CE_CNFG_STS_REGISTER\\[6\\] and either of the following conditions is true, a) If there are packets queued for transmission. b) If there is an acknowledgement awaited from the remote side for the packet transmitted."] #[inline(always)] pub fn md_bit_clear(&self) -> MD_BIT_CLEAR_R { MD_BIT_CLEAR_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 11 - This bit configures the DSM slot counting mode. 0 - The DSM slot count variance with respect to actual time is less than 1 slot 1 - The DSM slot count variance with respect to actual time is more than 1 slot &less that 2 slots"] #[inline(always)] pub fn dsm_slot_variance(&self) -> DSM_SLOT_VARIANCE_R { DSM_SLOT_VARIANCE_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - This bit is set to configure the MD bit control when IUT is in slave role. 1 - MD bit will be decided on packet pending status 0 - MD bit will be decided on packet queued in next buffer status This bit has effect only when 'CONN_CONFIG.md_bit_ctr' bit is not set ."] #[inline(always)] pub fn slv_md_config(&self) -> SLV_MD_CONFIG_R { SLV_MD_CONFIG_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - This bit is used to enable/disable extending the additional rx window on slave side during connection update in event of packet miss at the update instant. 1 - Enable 0 - Disable"] #[inline(always)] pub fn extend_cu_tx_win(&self) -> EXTEND_CU_TX_WIN_R { EXTEND_CU_TX_WIN_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - This bit is used to enable/disable masking of internal hardware supervision timeout trigger when switching from old connection parameters to new parameters. 1 - Enable 0 - Disable"] #[inline(always)] pub fn mask_suto_at_updt(&self) -> MASK_SUTO_AT_UPDT_R { MASK_SUTO_AT_UPDT_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - This bit is used to enable extension of the Conn Request to arbiter to 1 slot early. When enabled the request length is 2 slots. 1 - Enable 0 - Disable"] #[inline(always)] pub fn conn_req_1slot_early(&self) -> CONN_REQ_1SLOT_EARLY_R { CONN_REQ_1SLOT_EARLY_R::new(((self.bits >> 15) & 0x01) != 0) } } impl W { #[doc = "Bits 0:3 - Defines a limit for the number of Rx packets that can be re-ceived by the LLH. Default maximum value is 0xF.Minimum value shall be '1' or no packet will be stored in the Rx FIFO."] #[inline(always)] pub fn rx_pkt_limit(&mut self) -> RX_PKT_LIMIT_W { RX_PKT_LIMIT_W { w: self } } #[doc = "Bits 4:7 - This register field allows setting a threshold for the packet received interrupt to the firmware. For example if the value programmed is 0x2 - then HW will generate interrupt only on receiving the second packet. In any case if the received number of packets in a conn event is less than the threshold or there are still packets (less than threshold) pending in the Rx FIFO, HW will generate the interrupt at the ce_close. Min value possible is 1. Max value depends on the Rx FIFO capacity."] #[inline(always)] pub fn rx_intr_threshold(&mut self) -> RX_INTR_THRESHOLD_W { RX_INTR_THRESHOLD_W { w: self } } #[doc = "Bit 8 - This register field indicates whether the MD (More Data) bit needs to be controlled by 'software' or, 'hardware and soft-ware logic combined'. 1 - MD bit is exclusively controlled by software, ie based on status of CE_CNFG_STS_REGISTER\\[6\\] - md bit. 0 - MD Bit in the transmitted pdu is controlled by software and hardware logic. MD bit is set in transmitted packet, only if the software has set the md bit in CE_CNFG_STS_REGISTER\\[6\\] and either of the following conditions is true, a) If there are packets queued for transmission. b) If there is an acknowledgement awaited from the remote side for the packet transmitted."] #[inline(always)] pub fn md_bit_clear(&mut self) -> MD_BIT_CLEAR_W { MD_BIT_CLEAR_W { w: self } } #[doc = "Bit 11 - This bit configures the DSM slot counting mode. 0 - The DSM slot count variance with respect to actual time is less than 1 slot 1 - The DSM slot count variance with respect to actual time is more than 1 slot &less that 2 slots"] #[inline(always)] pub fn dsm_slot_variance(&mut self) -> DSM_SLOT_VARIANCE_W { DSM_SLOT_VARIANCE_W { w: self } } #[doc = "Bit 12 - This bit is set to configure the MD bit control when IUT is in slave role. 1 - MD bit will be decided on packet pending status 0 - MD bit will be decided on packet queued in next buffer status This bit has effect only when 'CONN_CONFIG.md_bit_ctr' bit is not set ."] #[inline(always)] pub fn slv_md_config(&mut self) -> SLV_MD_CONFIG_W { SLV_MD_CONFIG_W { w: self } } #[doc = "Bit 13 - This bit is used to enable/disable extending the additional rx window on slave side during connection update in event of packet miss at the update instant. 1 - Enable 0 - Disable"] #[inline(always)] pub fn extend_cu_tx_win(&mut self) -> EXTEND_CU_TX_WIN_W { EXTEND_CU_TX_WIN_W { w: self } } #[doc = "Bit 14 - This bit is used to enable/disable masking of internal hardware supervision timeout trigger when switching from old connection parameters to new parameters. 1 - Enable 0 - Disable"] #[inline(always)] pub fn mask_suto_at_updt(&mut self) -> MASK_SUTO_AT_UPDT_W { MASK_SUTO_AT_UPDT_W { w: self } } #[doc = "Bit 15 - This bit is used to enable extension of the Conn Request to arbiter to 1 slot early. When enabled the request length is 2 slots. 1 - Enable 0 - Disable"] #[inline(always)] pub fn conn_req_1slot_early(&mut self) -> CONN_REQ_1SLOT_EARLY_W { CONN_REQ_1SLOT_EARLY_W { w: self } } }
use std::io::{self, Read}; use std::iter; fn main() -> io::Result<()> { let mut raw_input = String::new(); io::stdin().read_to_string(&mut raw_input)?; let input: Vec<i32> = raw_input .lines() .map(|line| line.parse().unwrap()) .collect(); println!("Part 1: {}", part1(&input)?); println!("Part 2: {}", part2(&input)?); Ok(()) } fn part1(input: &Vec<i32>) -> io::Result<i32> { Ok(input.iter().map(|&w| calculate_fuel(w)).sum()) } fn part2(input: &Vec<i32>) -> io::Result<i32> { Ok(input .iter() .map(|&w| calculate_fuel(w)) .flat_map(|w| { iter::successors(Some(w), |&w| { if w == 0 { None } else { Some(calculate_fuel(w)) } }) }) .sum()) } fn calculate_fuel(mass: i32) -> i32 { ((mass / 3) - 2).max(0) } #[cfg(test)] mod tests { use super::*; #[test] fn fuel_calculated_correctly() { assert_eq!(calculate_fuel(12), 2); assert_eq!(calculate_fuel(14), 2); assert_eq!(calculate_fuel(1969), 654); assert_eq!(calculate_fuel(100756), 33583); } }
use specs::*; use server::component::channel::*; use server::component::event::PlayerLeave; use server::systems::handlers::packet::OnCloseHandler; use server::*; use CTFGameMode; use BLUE_TEAM; use RED_TEAM; pub struct UpdateGameModeOnPlayerLeave { reader: Option<OnPlayerLeaveReader>, } #[derive(SystemData)] pub struct UpdateGameModeOnPlayerLeaveData<'a> { pub gamemode: GameModeWriter<'a, CTFGameMode>, pub channel: Read<'a, OnPlayerLeave>, pub teams: ReadStorage<'a, Team>, } impl<'a> System<'a> for UpdateGameModeOnPlayerLeave { type SystemData = UpdateGameModeOnPlayerLeaveData<'a>; fn setup(&mut self, res: &mut Resources) { Self::SystemData::setup(res); self.reader = Some(res.fetch_mut::<OnPlayerLeave>().register_reader()); } fn run(&mut self, mut data: Self::SystemData) { for PlayerLeave(ent) in data.channel.read(self.reader.as_mut().unwrap()) { let team = data.teams.get(*ent).unwrap(); if *team == RED_TEAM { data.gamemode.redteam -= 1; } else if *team == BLUE_TEAM { data.gamemode.blueteam -= 1; } else { unimplemented!(); } } } } impl SystemInfo for UpdateGameModeOnPlayerLeave { type Dependencies = OnCloseHandler; fn name() -> &'static str { concat!(module_path!(), "::", line!()) } fn new() -> Self { Self { reader: None } } }
use crate::const_generics::PartiallyInitialized; use crate::BigArray; use core::ops::{Deref, DerefMut, Index, IndexMut}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// An array newtype usable for nested structures /// /// In most cases, using the [`BigArray`] trait /// is more convenient, so you should use that one. /// /// In nesting scenarios however, the trick of using /// `#[serde(with = ...)]` comes to its limits. For /// these cases, we offer the `Array` struct. /// /// [`BigArray`]: crate::BigArray /// /// ```Rust /// # use serde_derive::{Serialize, Deserialize}; /// #[derive(Serialize, Deserialize)] /// struct S { /// arr: Box<Array<u8, 64>>, /// } /// ``` #[repr(transparent)] #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone, Debug)] pub struct Array<T, const N: usize>(pub [T; N]); impl<'de, T: Deserialize<'de>, const N: usize> Deserialize<'de> for Array<T, N> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { Ok(Self(<[T; N] as BigArray<T>>::deserialize(deserializer)?)) } } impl<T: Default, const N: usize> Default for Array<T, N> { fn default() -> Self { // TODO use array::from_fn once the MSRV allows stuff from 1.63.0 let arr = { let mut arr = PartiallyInitialized::<T, N>::new(); unsafe { { let p = arr.0.as_mut().unwrap(); for i in 0..N { let p = (p.as_mut_ptr() as *mut T).wrapping_add(i); core::ptr::write(p, Default::default()); arr.1 += 1; } } let initialized = arr.0.take().unwrap().assume_init(); initialized } }; Self(arr) } } impl<T: Serialize, const N: usize> Serialize for Array<T, N> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { <[T; N] as BigArray<T>>::serialize(&self.0, serializer) } } impl<T, const N: usize> Deref for Array<T, N> { type Target = [T; N]; fn deref(&self) -> &Self::Target { &self.0 } } impl<T, const N: usize> DerefMut for Array<T, N> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<T, I, const N: usize> Index<I> for Array<T, N> where [T]: Index<I>, { type Output = <[T] as Index<I>>::Output; #[inline] fn index(&self, index: I) -> &Self::Output { Index::index(&self.0 as &[T], index) } } impl<T, I, const N: usize> IndexMut<I> for Array<T, N> where [T]: IndexMut<I>, { #[inline] fn index_mut(&mut self, index: I) -> &mut Self::Output { IndexMut::index_mut(&mut self.0 as &mut [T], index) } }
use std::cmp; fn main() { let x = binomial_coefficient_dp(32, 12); println!("x: {}", x); let y = binomial_coefficient_dac(32, 12); println!("y: {}", y); } // Dynamic Programming Version fn binomial_coefficient_dp(n: usize, k: usize) -> usize { let mut b = vec![0; k]; for i in 0..n { let d = cmp::min(i + 1, k); for j in (0..d).rev() { if j == 0 || j == i { b[j] = 1; } else { b[j] = b[j - 1] + b[j] } } println!("b: {:?}", &b); } b[k - 1] } // Divide and Conquer Version fn binomial_coefficient_dac(n: usize, k: usize) -> usize { if k == 1 || k == n { return 1; } binomial_coefficient_dac(n - 1, k - 1) + binomial_coefficient_dac(n - 1, k) }
use std::fs; use std::collections::HashMap; const P1_REQUIRED: [&str; 7] = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]; const HEX_VALID: [char; 16] = ['a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; const EYE_COLOR: [&str; 7] = ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]; const PID_CHARS: [char; 10] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; fn is_valid_hex(c: &char) -> bool { HEX_VALID.iter().any(|x| x == c) } fn validate(input: &HashMap<String, String>) -> bool { for field in P1_REQUIRED.iter() { if !input.contains_key(*field) { return false; } } true } fn validate2(input: &HashMap<String, String>) -> bool { fn check_byr(byr: &String) -> bool { let b = byr.parse::<i32>().unwrap(); byr.len() == 4 && b >= 1920 && b <= 2002 } fn check_iyr(iyr: &String) -> bool { let i = iyr.parse::<i32>().unwrap(); iyr.len() == 4 && i >= 2010 && i <= 2020 } fn check_eyr(eyr: &String) -> bool { let i = eyr.parse::<i32>().unwrap(); eyr.len() == 4 && i >= 2020 && i <= 2030 } fn check_hgt(hgt: &String) -> bool { let len = hgt.len(); if len < 3 { return false } let n = hgt[..(len-2)].parse::<i32>().unwrap(); match &hgt[(len-2)..] { "in" => 59 <= n && n <= 76, "cm" => 150 <= n && n <= 193, _ => false } } fn check_hcl(hcl: &String) -> bool { if hcl.chars().nth(0).unwrap() != '#' { return false; } hcl[1..].chars().all(|x| is_valid_hex(&x)) } fn check_ecl(ecl: &String) -> bool { EYE_COLOR.iter().any(|x| x == ecl) } fn check_pid(pid: &String) -> bool { pid.len() == 9 && pid.chars().all(|x| PID_CHARS.iter().any(|y| y == &x)) } // validate fields for (key, val) in input.iter() { let valid = match key.as_str() { "byr" => check_byr(val), "iyr" => check_iyr(val), "eyr" => check_eyr(val), "hgt" => check_hgt(val), "hcl" => check_hcl(val), "ecl" => check_ecl(val), "pid" => check_pid(val), "cid" => true, _ => false }; if !valid { println!("Invalidated value {} {}", key, val); return false; } } true } fn parse(content: String) -> Vec<HashMap<String, String>> { let mut vec: Vec<HashMap<String, String>> = Vec::new(); let it = content .split("\n\n"); for i in it { let w = i .replace("\n", " "); let ss = w.split(" ").filter(|&x| x.len() > 0) .collect::<Vec<&str>>(); // I don't know why I had to split it into 2 variables let mut hm: HashMap<String, String> = HashMap::new(); for v in ss { let h: Vec<&str> = v.split(":").collect(); hm.insert(String::from(h[0]), String::from(h[1])); } vec.push(hm); } vec } fn main() { let contents_test = fs::read_to_string("input_example.txt") .expect("error loading file"); let pass_test = parse(contents_test); let result_test = pass_test.iter().filter(|&x| validate(x)).count(); println!("test result 1 = {}", result_test); // PART 1 let contents = fs::read_to_string("input.txt") .expect("error loading file"); let pass = parse(contents); let result1 = pass.iter().filter(|&x| validate(x)).count(); println!("result 1 = {}", result1); // PART 2 let result2 = pass.iter().filter(|&x| validate(x) && validate2(x)).count(); println!("result 2 = {}", result2); }
//! Legacy Ethereum-like ABI generator #![warn(missing_docs)] mod util; mod log; mod stream; mod sink; mod common; #[cfg(test)] mod tests; pub use self::log::AsLog; pub use self::stream::Stream; pub use self::sink::Sink; use super::types; /// Error for decoding rust types from stream #[derive(Debug, PartialEq, Eq)] pub enum Error { /// Invalid bool for provided input InvalidBool, /// Invalid u32 for provided input InvalidU32, /// Invalid u64 for provided input InvalidU64, /// Unexpected end of the stream UnexpectedEof, /// Invalid padding for fixed type InvalidPadding, /// Other error Other, } /// Abi type trait pub trait AbiType : Sized { /// Insantiate type from data stream /// Should never be called manually! Use stream.pop() fn decode(stream: &mut Stream) -> Result<Self, Error>; /// Push type to data sink /// Should never be called manually! Use sink.push(val) fn encode(self, sink: &mut Sink); /// Whether type has fixed length or not const IS_FIXED: bool; } /// Endpoint interface for contracts pub trait EndpointInterface { /// Dispatch payload for regular method fn dispatch(&mut self, payload: &[u8]) -> ::lib::Vec<u8>; /// Dispatch constructor payload fn dispatch_ctor(&mut self, payload: &[u8]); }
//! examples/plain.rs //! Blinks an LED //! //! This assumes that a LED is connected to pc13 as is the case on the blue pill board. //! //! Note: Without additional hardware, PC13 should not be used to drive an LED, see page 5.1.2 of //! the reference manaual for an explanation. This is not an issue on the blue pill. #![deny(unsafe_code)] #![no_std] #![no_main] #[allow(unused_imports)] use panic_semihosting; use cortex_m_rt::entry; use cortex_m_semihosting::hprintln; use stm32f1xx_hal::delay::Delay; use stm32f1xx_hal::gpio::State; use stm32f1xx_hal::gpio::State::High; use stm32f1xx_hal::qei::Qei; use stm32f1xx_hal::{pac, prelude::*, timer::Timer}; #[entry] fn main() -> ! { // Get access to the core peripherals from the cortex-m crate let cp = cortex_m::Peripherals::take().unwrap(); // Get access to the device specific peripherals from the peripheral access crate let dp = pac::Peripherals::take().unwrap(); // Take ownership over the raw flash and rcc devices and convert them into the corresponding // HAL structs let mut flash = dp.FLASH.constrain(); let mut rcc = dp.RCC.constrain(); // Freeze the configuration of all the clocks in the system and store the frozen frequencies in // `clocks` let clocks = rcc .cfgr .use_hse(8.mhz()) .sysclk(72.mhz()) .pclk1(36.mhz()) .freeze(&mut flash.acr); let mut afio = dp.AFIO.constrain(&mut rcc.apb2); // Acquire the GPIO peripherals let mut gpioa = dp.GPIOA.split(&mut rcc.apb2); let mut gpiob = dp.GPIOB.split(&mut rcc.apb2); let mut gpioc = dp.GPIOC.split(&mut rcc.apb2); // Declare GPIOs let mut led_hs_en_l = gpioa .pa2 .into_push_pull_output_with_state(&mut gpioa.crl, High); let mut led_hs_a0 = gpioa.pa3.into_push_pull_output(&mut gpioa.crl); let mut led_hs_a1 = gpioa.pa4.into_push_pull_output(&mut gpioa.crl); let mut led_hs_a2 = gpioa.pa5.into_push_pull_output(&mut gpioa.crl); let mut led_ls_en_l = gpiob .pb12 .into_push_pull_output_with_state(&mut gpiob.crh, High); let mut led_ls_dai = gpiob.pb15.into_push_pull_output(&mut gpiob.crh); let mut led_ls_dck = gpiob.pb14.into_push_pull_output(&mut gpiob.crh); let mut led_ls_lat = gpiob.pb13.into_push_pull_output(&mut gpiob.crh); let mut enc_a0 = gpioc.pc0.into_push_pull_output(&mut gpioc.crl); let mut enc_a1 = gpioc.pc1.into_push_pull_output(&mut gpioc.crl); let mut enc_a2 = gpioc.pc2.into_push_pull_output(&mut gpioc.crl); let mut enc_out_a = gpioa.pa1; let mut enc_out_b = gpioa.pa0; // Delay let mut delay = Delay::new(cp.SYST, clocks); // Encoder let qei = Qei::tim2( dp.TIM2, (enc_out_b, enc_out_a), &mut afio.mapr, &mut rcc.apb1, ); loop { let before = qei.count(); delay.delay_ms(1_000_u16); let after = qei.count(); let elapsed = after.wrapping_sub(before) as i16; hprintln!("{}", elapsed).unwrap(); } // LEDs /* let d: u8 = 1_u8; //let mut shift: i32 = 1; //let mut bank: i8 = 0; delay.delay_us(d); // reset DMCs for j in 0..31 { led_ls_dai.set_low(); delay.delay_us(d); led_ls_dck.set_high(); delay.delay_us(d); led_ls_dck.set_low(); } delay.delay_us(d); led_ls_lat.set_high(); delay.delay_us(d); led_ls_lat.set_low(); let mut bank: i8 = 0; let mut shift: u32 = 0; //parallel loop { led_hs_en_l.set_high(); delay.delay_us(d); shift = match bank { 0 => 0xaaaaaaaa, 1 => 0x55555555, 2 => 0xaa55aa55, 3 => 0x55aa55aa, 4 => 0x5a5a5a5a, 5 => 0xa5a5a5a5, 6 => 0x55555555, 7 => 0xaaaaaaaa, _ => 0x0, }; if bank & 1 << 0 == 0 { led_hs_a0.set_low(); } else { led_hs_a0.set_high(); } if bank & 1 << 1 == 0 { led_hs_a1.set_low(); } else { led_hs_a1.set_high(); } if bank & 1 << 2 == 0 { led_hs_a2.set_low(); } else { led_hs_a2.set_high(); } for i in 0..32 { if shift & (1 << i) == 0 { led_ls_dai.set_low(); } else { led_ls_dai.set_high(); } delay.delay_us(d); led_ls_dck.set_high(); delay.delay_us(d); led_ls_dck.set_low(); } delay.delay_us(d); led_ls_lat.set_high(); delay.delay_us(d); led_ls_lat.set_low(); delay.delay_us(d); led_ls_en_l.set_low(); led_hs_en_l.set_low(); delay.delay_us(1_u8); led_hs_en_l.set_low(); delay.delay_us(100_u16); bank += 1; if bank == 8 { bank = 0; } } */ /* // sequentiell loop { led_hs_en_l.set_high(); delay.delay_us(d); if bank & 1 << 0 == 0 { led_hs_a0.set_low(); } else { led_hs_a0.set_high(); } if bank & 1 << 1 == 0 { led_hs_a1.set_low(); } else { led_hs_a1.set_high(); } if bank & 1 << 2 == 0 { led_hs_a2.set_low(); } else { led_hs_a2.set_high(); } for i in 0..32 { if shift & (1 << i) == 0 { led_ls_dai.set_low(); } else { led_ls_dai.set_high(); } delay.delay_us(d); led_ls_dck.set_high(); delay.delay_us(d); led_ls_dck.set_low(); } delay.delay_us(d); led_ls_lat.set_high(); delay.delay_us(d); led_ls_lat.set_low(); delay.delay_us(d); led_ls_en_l.set_low(); led_hs_en_l.set_low(); delay.delay_ms(1_u8); for i in 0..25 { led_hs_en_l.set_low(); delay.delay_ms(2_u8); led_hs_en_l.set_high(); delay.delay_ms(2_u8); } shift = shift << 1; if shift == 0 { shift = 1; bank += 1; if bank == 8 { bank = 0; } } } */ }
//! This example demonstrates using the [`col!`] and [`row!`] macros to easily //! organize multiple tables together into a single, new [`Table`] display. //! //! * 🚩 This example requires the `macros` feature. //! //! * Note how both macros can be used in combination to layer //! several table arrangements together. //! //! * Note how [`col!`] and [`row!`] support idiomatic argument duplication //! with the familiar `[T; N]` syntax. use tabled::{ col, row, settings::{Alignment, Style}, Table, Tabled, }; #[derive(Tabled)] struct Person { name: String, age: u8, is_validated: bool, } impl Person { fn new(name: &str, age: u8, is_validated: bool) -> Self { Self { name: name.into(), age, is_validated, } } } fn main() { let validated = [Person::new("Sam", 31, true), Person::new("Sarah", 26, true)]; let not_validated = [ Person::new("Jack Black", 51, false), Person::new("Michelle Goldstein", 44, true), ]; let unsure = [ Person::new("Jon Doe", 255, false), Person::new("Mark Nelson", 13, true), Person::new("Terminal Monitor", 0, false), Person::new("Adam Blend", 17, true), ]; let table_a = Table::new(&validated).with(Style::ascii()).to_string(); let table_b = Table::new(&not_validated).with(Style::modern()).to_string(); let table_c = Table::new(&unsure).with(Style::ascii_rounded()).to_string(); let row_table = row![table_c, table_b]; let col_table = col![table_c; 3]; let mut row_col_table = col![row![table_a, table_b].with(Style::empty()), table_c]; row_col_table.with(Alignment::center()); println!("{row_table}\n{col_table}\n{row_col_table}",); }
use std::collections::HashMap; use std::collections::VecDeque; #[aoc_generator(day9)] pub fn input_generator(input: &str) -> Vec<Vec<i32>> { input .lines() .map(|l| l.trim().chars().map(|c| c as i32 - 0x30).collect()) .collect() } pub fn get_low_points(input: &Vec<Vec<i32>>) -> Vec<(usize, usize)> { let mut low_points: Vec<(usize, usize)> = vec![]; let neighbours: [(i32, i32); 4] = [(0, 1), (-1, 0), (1, 0), (0, -1)]; let rows = input.len(); let cols = input[0].len(); for r in 0..rows { for c in 0..cols { let mut higher = 0; for (n_r, n_c) in neighbours { let row = r as i32 + n_r; let col = c as i32 + n_c; // edge node if row < 0 || row > rows as i32 - 1 || col < 0 || col > cols as i32 - 1 { higher += 1; } else if input[r][c] < input[row as usize][col as usize] { higher += 1; } else { continue; } } if higher == 4 { low_points.push((r, c)); } } } return low_points; } pub fn is_valid( cave_map: &Vec<Vec<i32>>, next: &(i32, i32), dimensions: &(usize, usize), visited: &HashMap<(usize, usize), bool>, ) -> bool { if next.0 < 0 || next.0 >= dimensions.0 as i32 || next.1 < 0 || next.1 >= dimensions.1 as i32 { return false; } let next_pos = (next.0 as usize, next.1 as usize); if let Some(_) = visited.get(&next_pos) { return false; } let next_value = cave_map[next.0 as usize][next.1 as usize]; if next_value == 9 { return false; } return true; } pub fn get_basin(cave_map: Vec<Vec<i32>>, low_point: (usize, usize)) -> i32 { let neighbours: [(i32, i32); 4] = [(0, 1), (-1, 0), (1, 0), (0, -1)]; let dimensions = (cave_map.len(), cave_map[0].len()); let mut visited: HashMap<(usize, usize), bool> = HashMap::new(); let mut queue: VecDeque<(usize, usize)> = VecDeque::new(); let mut basin: Vec<(i32, i32)> = Vec::new(); basin.push((low_point.0 as i32, low_point.1 as i32)); visited.insert(low_point, true); queue.push_back(low_point); while !queue.is_empty() { if let Some(current) = queue.pop_front() { for neighbour in neighbours { let new_point: (i32, i32) = ( current.0 as i32 + neighbour.0, current.1 as i32 + neighbour.1, ); if is_valid(&cave_map.clone(), &new_point, &dimensions, &visited) { basin.push(new_point.clone()); queue.push_back((new_point.0 as usize, new_point.1 as usize)); } if new_point.0 >= 0 && new_point.1 >= 0 { visited.insert((new_point.0 as usize, new_point.1 as usize), true); } } } } return basin.len() as i32; } #[aoc(day9, part1)] pub fn solve_part1(input: &Vec<Vec<i32>>) -> i32 { let low_points = get_low_points(input); low_points .iter() .map(|&(lp_r, lp_c)| input[lp_r][lp_c] + 1) .sum() } #[aoc(day9, part2)] pub fn solve_part2(input: &Vec<Vec<i32>>) -> i32 { let low_points = get_low_points(input); let mut basins: Vec<i32> = Vec::new(); for low_point in low_points { basins.push(get_basin(input.clone(), low_point.clone())); } let mut res = 1; basins.sort(); for _ in 0..3 { if let Some(last) = basins.pop() { res *= last; } } return res; } #[cfg(test)] mod tests { use super::*; const INPUT: &str = r#"2199943210 3987894921 9856789892 8767896789 9899965678"#; const INPUT2: &str = r#"9199943210 3987894921 9856789892 8767896789 9899965678"#; #[test] fn example1() { assert_eq!(solve_part1(&input_generator(INPUT)), 15); } #[test] fn example2() { assert_eq!(solve_part2(&input_generator(INPUT)), 1134); } #[test] fn example3() { assert_eq!(solve_part2(&input_generator(INPUT2)), 1134); } }
#[doc = "Reader of register AMUX_SPLIT_CTL[%s]"] pub type R = crate::R<u32, super::AMUX_SPLIT_CTL>; #[doc = "Writer for register AMUX_SPLIT_CTL[%s]"] pub type W = crate::W<u32, super::AMUX_SPLIT_CTL>; #[doc = "Register AMUX_SPLIT_CTL[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::AMUX_SPLIT_CTL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `SWITCH_AA_SL`"] pub type SWITCH_AA_SL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SWITCH_AA_SL`"] pub struct SWITCH_AA_SL_W<'a> { w: &'a mut W, } impl<'a> SWITCH_AA_SL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `SWITCH_AA_SR`"] pub type SWITCH_AA_SR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SWITCH_AA_SR`"] pub struct SWITCH_AA_SR_W<'a> { w: &'a mut W, } impl<'a> SWITCH_AA_SR_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `SWITCH_AA_S0`"] pub type SWITCH_AA_S0_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SWITCH_AA_S0`"] pub struct SWITCH_AA_S0_W<'a> { w: &'a mut W, } impl<'a> SWITCH_AA_S0_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `SWITCH_BB_SL`"] pub type SWITCH_BB_SL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SWITCH_BB_SL`"] pub struct SWITCH_BB_SL_W<'a> { w: &'a mut W, } impl<'a> SWITCH_BB_SL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `SWITCH_BB_SR`"] pub type SWITCH_BB_SR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SWITCH_BB_SR`"] pub struct SWITCH_BB_SR_W<'a> { w: &'a mut W, } impl<'a> SWITCH_BB_SR_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `SWITCH_BB_S0`"] pub type SWITCH_BB_S0_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SWITCH_BB_S0`"] pub struct SWITCH_BB_S0_W<'a> { w: &'a mut W, } impl<'a> SWITCH_BB_S0_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } impl R { #[doc = "Bit 0 - T-switch control for Left AMUXBUSA switch: '0': switch open. '1': switch closed."] #[inline(always)] pub fn switch_aa_sl(&self) -> SWITCH_AA_SL_R { SWITCH_AA_SL_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - T-switch control for Right AMUXBUSA switch: '0': switch open. '1': switch closed."] #[inline(always)] pub fn switch_aa_sr(&self) -> SWITCH_AA_SR_R { SWITCH_AA_SR_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - T-switch control for AMUXBUSA vssa/ground switch: '0': switch open. '1': switch closed."] #[inline(always)] pub fn switch_aa_s0(&self) -> SWITCH_AA_S0_R { SWITCH_AA_S0_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 4 - T-switch control for Left AMUXBUSB switch."] #[inline(always)] pub fn switch_bb_sl(&self) -> SWITCH_BB_SL_R { SWITCH_BB_SL_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - T-switch control for Right AMUXBUSB switch."] #[inline(always)] pub fn switch_bb_sr(&self) -> SWITCH_BB_SR_R { SWITCH_BB_SR_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - T-switch control for AMUXBUSB vssa/ground switch."] #[inline(always)] pub fn switch_bb_s0(&self) -> SWITCH_BB_S0_R { SWITCH_BB_S0_R::new(((self.bits >> 6) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - T-switch control for Left AMUXBUSA switch: '0': switch open. '1': switch closed."] #[inline(always)] pub fn switch_aa_sl(&mut self) -> SWITCH_AA_SL_W { SWITCH_AA_SL_W { w: self } } #[doc = "Bit 1 - T-switch control for Right AMUXBUSA switch: '0': switch open. '1': switch closed."] #[inline(always)] pub fn switch_aa_sr(&mut self) -> SWITCH_AA_SR_W { SWITCH_AA_SR_W { w: self } } #[doc = "Bit 2 - T-switch control for AMUXBUSA vssa/ground switch: '0': switch open. '1': switch closed."] #[inline(always)] pub fn switch_aa_s0(&mut self) -> SWITCH_AA_S0_W { SWITCH_AA_S0_W { w: self } } #[doc = "Bit 4 - T-switch control for Left AMUXBUSB switch."] #[inline(always)] pub fn switch_bb_sl(&mut self) -> SWITCH_BB_SL_W { SWITCH_BB_SL_W { w: self } } #[doc = "Bit 5 - T-switch control for Right AMUXBUSB switch."] #[inline(always)] pub fn switch_bb_sr(&mut self) -> SWITCH_BB_SR_W { SWITCH_BB_SR_W { w: self } } #[doc = "Bit 6 - T-switch control for AMUXBUSB vssa/ground switch."] #[inline(always)] pub fn switch_bb_s0(&mut self) -> SWITCH_BB_S0_W { SWITCH_BB_S0_W { w: self } } }
use bellman::{ gadgets::{ boolean::{AllocatedBit, Boolean}, multipack, num, Assignment, }, groth16, Circuit, ConstraintSystem, SynthesisError, }; use bls12_381::Bls12; use bls12_381::Scalar; use ff::{Field, PrimeField}; use group::Curve; use rand::rngs::OsRng; use std::ops::{Neg, SubAssign}; pub const CRH_IVK_PERSONALIZATION: &[u8; 8] = b"Zcashivk"; struct MyCircuit { quantity: Option<bls12_381::Scalar>, multiplier: Option<bls12_381::Scalar>, entry_price: Option<bls12_381::Scalar>, exit_price: Option<bls12_381::Scalar>, } impl Circuit<bls12_381::Scalar> for MyCircuit { fn synthesize<CS: ConstraintSystem<bls12_381::Scalar>>( self, cs: &mut CS, ) -> Result<(), SynthesisError> { // Witness variables let quantity = num::AllocatedNum::alloc(cs.namespace(|| "conditional anchor"), || { Ok(*self.quantity.get()?) })?; let multiplier = num::AllocatedNum::alloc(cs.namespace(|| "conditional anchor"), || { Ok(*self.multiplier.get()?) })?; let entry_price = num::AllocatedNum::alloc(cs.namespace(|| "conditional anchor"), || { Ok(*self.entry_price.get()?) })?; let exit_price = num::AllocatedNum::alloc(cs.namespace(|| "conditional anchor"), || { Ok(*self.exit_price.get()?) })?; // P = mN (1 - 1/R) // = mN - mN/R // = mN - mN * S_0 * S_T^-1 // initial_margin = mN let initial_margin = multiplier.mul(cs.namespace(|| "initial margin"), &quantity)?; // S_T_inv = S_T^-1 let exit_price_inv = num::AllocatedNum::alloc(cs.namespace(|| "exit price inverse"), || { let tmp = *exit_price.get_value().get()?; if tmp.is_zero() { Err(SynthesisError::DivisionByZero) } else { let inv = tmp.invert().unwrap(); Ok(inv) } })?; // assert S_T * S_T_inv = 1 cs.enforce( || "constraint inverse exit price", |lc| lc + exit_price.get_variable(), |lc| lc + exit_price_inv.get_variable(), |lc| lc + CS::one(), ); // ungained = initial_margin * S_0 * S_T_inv let ungained = initial_margin.mul(cs.namespace(|| "ungained 1"), &entry_price)?; let ungained = ungained.mul(cs.namespace(|| "ungained 2"), &exit_price_inv)?; // pnl = initial_margin - ungained let pnl = num::AllocatedNum::alloc(cs.namespace(|| "exit price inverse"), || { let mut tmp = *initial_margin.get_value().get()?; tmp.sub_assign(ungained.get_value().get()?); Ok(tmp) })?; cs.enforce( || "constraint pnl calc", |lc| lc + initial_margin.get_variable() - ungained.get_variable(), |lc| lc + CS::one(), |lc| lc + pnl.get_variable(), ); // Apply clamp: // // if pnl < -initial_margin: // pnl = -initial_margin // if pnl > initial_margin: // pnl = initial_margin Ok(()) } } fn main() { let x = Scalar::from(2); println!("{:?}", x.invert().unwrap()); use std::time::Instant; let start = Instant::now(); // Create parameters for our circuit. In a production deployment these would // be generated securely using a multiparty computation. let params = { let c = MyCircuit { quantity: None, multiplier: None, entry_price: None, exit_price: None, }; groth16::generate_random_parameters::<Bls12, _, _>(c, &mut OsRng).unwrap() }; println!("Setup: [{:?}]", start.elapsed()); // Prepare the verification key (for proof verification). let pvk = groth16::prepare_verifying_key(&params.vk); // Pick a preimage and compute its hash. let quantity = bls12_381::Scalar::from(1); let multiplier = bls12_381::Scalar::from(1); let entry_price = bls12_381::Scalar::from(100); let exit_price = bls12_381::Scalar::from(200); // Create an instance of our circuit (with the preimage as a witness). let c = MyCircuit { quantity: Some(quantity), multiplier: Some(multiplier), entry_price: Some(entry_price), exit_price: Some(exit_price), }; let start = Instant::now(); // Create a Groth16 proof with our parameters. let proof = groth16::create_random_proof(c, &params, &mut OsRng).unwrap(); println!("Prove: [{:?}]", start.elapsed()); let start = Instant::now(); let mut public_input = [bls12_381::Scalar::zero(); 0]; let start = Instant::now(); // Check the proof! assert!(groth16::verify_proof(&pvk, &proof, &public_input).is_ok()); println!("Verify: [{:?}]", start.elapsed()); }
#[doc = "Register `ADC_CR` reader"] pub type R = crate::R<ADC_CR_SPEC>; #[doc = "Register `ADC_CR` writer"] pub type W = crate::W<ADC_CR_SPEC>; #[doc = "Field `ADEN` reader - ADEN"] pub type ADEN_R = crate::BitReader; #[doc = "Field `ADEN` writer - ADEN"] pub type ADEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ADDIS` reader - ADDIS"] pub type ADDIS_R = crate::BitReader; #[doc = "Field `ADDIS` writer - ADDIS"] pub type ADDIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ADSTART` reader - ADSTART"] pub type ADSTART_R = crate::BitReader; #[doc = "Field `ADSTART` writer - ADSTART"] pub type ADSTART_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `JADSTART` reader - JADSTART"] pub type JADSTART_R = crate::BitReader; #[doc = "Field `JADSTART` writer - JADSTART"] pub type JADSTART_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ADSTP` reader - ADSTP"] pub type ADSTP_R = crate::BitReader; #[doc = "Field `ADSTP` writer - ADSTP"] pub type ADSTP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `JADSTP` reader - JADSTP"] pub type JADSTP_R = crate::BitReader; #[doc = "Field `JADSTP` writer - JADSTP"] pub type JADSTP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BOOST` reader - BOOST"] pub type BOOST_R = crate::BitReader; #[doc = "Field `BOOST` writer - BOOST"] pub type BOOST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ADCALLIN` reader - ADCALLIN"] pub type ADCALLIN_R = crate::BitReader; #[doc = "Field `ADCALLIN` writer - ADCALLIN"] pub type ADCALLIN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LINCALRDYW1` reader - LINCALRDYW1"] pub type LINCALRDYW1_R = crate::BitReader; #[doc = "Field `LINCALRDYW1` writer - LINCALRDYW1"] pub type LINCALRDYW1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LINCALRDYW2` reader - LINCALRDYW2"] pub type LINCALRDYW2_R = crate::BitReader; #[doc = "Field `LINCALRDYW2` writer - LINCALRDYW2"] pub type LINCALRDYW2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LINCALRDYW3` reader - LINCALRDYW3"] pub type LINCALRDYW3_R = crate::BitReader; #[doc = "Field `LINCALRDYW3` writer - LINCALRDYW3"] pub type LINCALRDYW3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LINCALRDYW4` reader - LINCALRDYW4"] pub type LINCALRDYW4_R = crate::BitReader; #[doc = "Field `LINCALRDYW4` writer - LINCALRDYW4"] pub type LINCALRDYW4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LINCALRDYW5` reader - LINCALRDYW5"] pub type LINCALRDYW5_R = crate::BitReader; #[doc = "Field `LINCALRDYW5` writer - LINCALRDYW5"] pub type LINCALRDYW5_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LINCALRDYW6` reader - LINCALRDYW6"] pub type LINCALRDYW6_R = crate::BitReader; #[doc = "Field `LINCALRDYW6` writer - LINCALRDYW6"] pub type LINCALRDYW6_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ADVREGEN` reader - ADVREGEN"] pub type ADVREGEN_R = crate::BitReader; #[doc = "Field `ADVREGEN` writer - ADVREGEN"] pub type ADVREGEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DEEPPWD` reader - DEEPPWD"] pub type DEEPPWD_R = crate::BitReader; #[doc = "Field `DEEPPWD` writer - DEEPPWD"] pub type DEEPPWD_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ADCALDIF` reader - ADCALDIF"] pub type ADCALDIF_R = crate::BitReader; #[doc = "Field `ADCALDIF` writer - ADCALDIF"] pub type ADCALDIF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ADCAL` reader - ADCAL"] pub type ADCAL_R = crate::BitReader; #[doc = "Field `ADCAL` writer - ADCAL"] pub type ADCAL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - ADEN"] #[inline(always)] pub fn aden(&self) -> ADEN_R { ADEN_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - ADDIS"] #[inline(always)] pub fn addis(&self) -> ADDIS_R { ADDIS_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - ADSTART"] #[inline(always)] pub fn adstart(&self) -> ADSTART_R { ADSTART_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - JADSTART"] #[inline(always)] pub fn jadstart(&self) -> JADSTART_R { JADSTART_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - ADSTP"] #[inline(always)] pub fn adstp(&self) -> ADSTP_R { ADSTP_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - JADSTP"] #[inline(always)] pub fn jadstp(&self) -> JADSTP_R { JADSTP_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 8 - BOOST"] #[inline(always)] pub fn boost(&self) -> BOOST_R { BOOST_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 16 - ADCALLIN"] #[inline(always)] pub fn adcallin(&self) -> ADCALLIN_R { ADCALLIN_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 22 - LINCALRDYW1"] #[inline(always)] pub fn lincalrdyw1(&self) -> LINCALRDYW1_R { LINCALRDYW1_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - LINCALRDYW2"] #[inline(always)] pub fn lincalrdyw2(&self) -> LINCALRDYW2_R { LINCALRDYW2_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bit 24 - LINCALRDYW3"] #[inline(always)] pub fn lincalrdyw3(&self) -> LINCALRDYW3_R { LINCALRDYW3_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - LINCALRDYW4"] #[inline(always)] pub fn lincalrdyw4(&self) -> LINCALRDYW4_R { LINCALRDYW4_R::new(((self.bits >> 25) & 1) != 0) } #[doc = "Bit 26 - LINCALRDYW5"] #[inline(always)] pub fn lincalrdyw5(&self) -> LINCALRDYW5_R { LINCALRDYW5_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bit 27 - LINCALRDYW6"] #[inline(always)] pub fn lincalrdyw6(&self) -> LINCALRDYW6_R { LINCALRDYW6_R::new(((self.bits >> 27) & 1) != 0) } #[doc = "Bit 28 - ADVREGEN"] #[inline(always)] pub fn advregen(&self) -> ADVREGEN_R { ADVREGEN_R::new(((self.bits >> 28) & 1) != 0) } #[doc = "Bit 29 - DEEPPWD"] #[inline(always)] pub fn deeppwd(&self) -> DEEPPWD_R { DEEPPWD_R::new(((self.bits >> 29) & 1) != 0) } #[doc = "Bit 30 - ADCALDIF"] #[inline(always)] pub fn adcaldif(&self) -> ADCALDIF_R { ADCALDIF_R::new(((self.bits >> 30) & 1) != 0) } #[doc = "Bit 31 - ADCAL"] #[inline(always)] pub fn adcal(&self) -> ADCAL_R { ADCAL_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bit 0 - ADEN"] #[inline(always)] #[must_use] pub fn aden(&mut self) -> ADEN_W<ADC_CR_SPEC, 0> { ADEN_W::new(self) } #[doc = "Bit 1 - ADDIS"] #[inline(always)] #[must_use] pub fn addis(&mut self) -> ADDIS_W<ADC_CR_SPEC, 1> { ADDIS_W::new(self) } #[doc = "Bit 2 - ADSTART"] #[inline(always)] #[must_use] pub fn adstart(&mut self) -> ADSTART_W<ADC_CR_SPEC, 2> { ADSTART_W::new(self) } #[doc = "Bit 3 - JADSTART"] #[inline(always)] #[must_use] pub fn jadstart(&mut self) -> JADSTART_W<ADC_CR_SPEC, 3> { JADSTART_W::new(self) } #[doc = "Bit 4 - ADSTP"] #[inline(always)] #[must_use] pub fn adstp(&mut self) -> ADSTP_W<ADC_CR_SPEC, 4> { ADSTP_W::new(self) } #[doc = "Bit 5 - JADSTP"] #[inline(always)] #[must_use] pub fn jadstp(&mut self) -> JADSTP_W<ADC_CR_SPEC, 5> { JADSTP_W::new(self) } #[doc = "Bit 8 - BOOST"] #[inline(always)] #[must_use] pub fn boost(&mut self) -> BOOST_W<ADC_CR_SPEC, 8> { BOOST_W::new(self) } #[doc = "Bit 16 - ADCALLIN"] #[inline(always)] #[must_use] pub fn adcallin(&mut self) -> ADCALLIN_W<ADC_CR_SPEC, 16> { ADCALLIN_W::new(self) } #[doc = "Bit 22 - LINCALRDYW1"] #[inline(always)] #[must_use] pub fn lincalrdyw1(&mut self) -> LINCALRDYW1_W<ADC_CR_SPEC, 22> { LINCALRDYW1_W::new(self) } #[doc = "Bit 23 - LINCALRDYW2"] #[inline(always)] #[must_use] pub fn lincalrdyw2(&mut self) -> LINCALRDYW2_W<ADC_CR_SPEC, 23> { LINCALRDYW2_W::new(self) } #[doc = "Bit 24 - LINCALRDYW3"] #[inline(always)] #[must_use] pub fn lincalrdyw3(&mut self) -> LINCALRDYW3_W<ADC_CR_SPEC, 24> { LINCALRDYW3_W::new(self) } #[doc = "Bit 25 - LINCALRDYW4"] #[inline(always)] #[must_use] pub fn lincalrdyw4(&mut self) -> LINCALRDYW4_W<ADC_CR_SPEC, 25> { LINCALRDYW4_W::new(self) } #[doc = "Bit 26 - LINCALRDYW5"] #[inline(always)] #[must_use] pub fn lincalrdyw5(&mut self) -> LINCALRDYW5_W<ADC_CR_SPEC, 26> { LINCALRDYW5_W::new(self) } #[doc = "Bit 27 - LINCALRDYW6"] #[inline(always)] #[must_use] pub fn lincalrdyw6(&mut self) -> LINCALRDYW6_W<ADC_CR_SPEC, 27> { LINCALRDYW6_W::new(self) } #[doc = "Bit 28 - ADVREGEN"] #[inline(always)] #[must_use] pub fn advregen(&mut self) -> ADVREGEN_W<ADC_CR_SPEC, 28> { ADVREGEN_W::new(self) } #[doc = "Bit 29 - DEEPPWD"] #[inline(always)] #[must_use] pub fn deeppwd(&mut self) -> DEEPPWD_W<ADC_CR_SPEC, 29> { DEEPPWD_W::new(self) } #[doc = "Bit 30 - ADCALDIF"] #[inline(always)] #[must_use] pub fn adcaldif(&mut self) -> ADCALDIF_W<ADC_CR_SPEC, 30> { ADCALDIF_W::new(self) } #[doc = "Bit 31 - ADCAL"] #[inline(always)] #[must_use] pub fn adcal(&mut self) -> ADCAL_W<ADC_CR_SPEC, 31> { ADCAL_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 = "ADC control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`adc_cr::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 [`adc_cr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ADC_CR_SPEC; impl crate::RegisterSpec for ADC_CR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`adc_cr::R`](R) reader structure"] impl crate::Readable for ADC_CR_SPEC {} #[doc = "`write(|w| ..)` method takes [`adc_cr::W`](W) writer structure"] impl crate::Writable for ADC_CR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets ADC_CR to value 0x2000_0000"] impl crate::Resettable for ADC_CR_SPEC { const RESET_VALUE: Self::Ux = 0x2000_0000; }
pub type Duration = u64; pub enum CacheOp { Read, Write, } pub trait Storage { fn access(&mut self, address: u64, op: CacheOp) -> Duration; fn output_stats(&self) { // default: do nothing } fn stats(&self) -> StorageStats; } #[derive(Default, Debug, Clone, Copy)] pub struct StorageStats { pub num_access: u64, pub num_miss: u64, pub time: Duration, } #[derive(Debug, Clone, Copy)] pub struct CacheConfig { pub name: &'static str, pub write_through: bool, pub write_allocate: bool, pub capacity: u64, pub associativity: u64, pub line_size: u64, pub latency: Duration, } #[derive(Default, Debug, Clone, Copy)] struct CacheLine { is_valid: bool, is_dirty: bool, last_visit: u64, tag: u64, address: u64, } #[derive(Default, Debug, Clone)] struct CacheLines { last_visit: u64, lines: Vec<CacheLine>, } pub struct Cache { stats: StorageStats, config: CacheConfig, lower: Box<dyn Storage>, line_mask: u64, tag_mask: u64, lines: Vec<CacheLines>, } #[derive(Debug, Clone, Copy)] pub struct Dram { latency: Duration, stats: StorageStats, } pub fn new_1_levels(config: CacheConfig) -> Box<dyn Storage> { let dram = Box::new(Dram::new(10)); Box::new(Cache::new(config, dram)) } pub fn new_3_levels() -> Box<dyn Storage> { let dram = Box::new(Dram::new(19)); let llc = Box::new(Cache::new( CacheConfig { name: "LLC", write_through: false, write_allocate: true, capacity: 8 * 1024 * 1024, associativity: 8, line_size: 64, latency: 4, }, dram )); let l2 = Box::new(Cache::new( CacheConfig { name: "L2", write_through: false, write_allocate: true, capacity: 256 * 1024, associativity: 8, line_size: 64, latency: 2, }, llc )); let l1 = Box::new(Cache::new( CacheConfig { name: "L1", write_through: false, write_allocate: true, capacity: 32 * 1024, associativity: 8, line_size: 64, latency: 1, }, l2 )); l1 } impl CacheLines { fn new(size: usize) -> CacheLines { CacheLines { last_visit: 0, lines: vec![CacheLine::default(); size], } } fn find(&mut self, tag: u64) -> Option<&mut CacheLine> { self.last_visit += 1; let mut result = self.lines.iter_mut() .filter(|x| x.is_valid) .find(|x| x.tag == tag); if let Some(mut line) = result.as_mut() { line.last_visit = self.last_visit; } result } // return the address of the victim fn insert(&mut self, tag: u64, address: u64) -> Option<u64> { assert!(self.find(tag).is_none()); self.last_visit += 1; let mut line = (match self.lines.iter_mut().find(|x| !x.is_valid) { Some(x) => x, None => match self.lines.iter_mut().min_by_key(|x| x.last_visit) { Some(x) => x, None => panic!("eviction failed"), }, }); let result = if line.is_dirty { Some(line.address) } else { None }; *line = CacheLine { is_valid: true, is_dirty: false, last_visit: self.last_visit, tag, address, }; result } } impl Cache { pub fn new(config: CacheConfig, lower: Box<dyn Storage>) -> Self { assert_eq!(config.capacity % config.line_size, 0); let num_lines = config.capacity / config.line_size; Self { stats: Default::default(), config, lower, line_mask: ((num_lines / config.associativity) - 1) * config.line_size, tag_mask: !(config.capacity / config.associativity - 1), lines: vec![CacheLines::new(config.associativity as usize); num_lines as usize], } } fn read(&mut self, address: u64) -> Duration { let lines = &mut self.lines[((address & self.line_mask) / self.config.line_size) as usize]; let tag = address & self.tag_mask; match lines.find(tag) { Some(line) => self.config.latency, None => { self.stats.num_miss += 1; let eviction_time = match lines.insert(tag, address) { Some(lower_address) => self.lower.access(lower_address, CacheOp::Write), None => 0, }; self.config.latency + self.lower.access(address, CacheOp::Read) + eviction_time }, } } fn write(&mut self, address: u64) -> Duration { let lines = &mut self.lines[((address & self.line_mask) / self.config.line_size) as usize]; let tag = address & self.tag_mask; match lines.find(tag) { Some(line) => if self.config.write_through { self.config.latency + self.lower.access(address, CacheOp::Write) } else { line.is_dirty = true; self.config.latency }, None => { self.stats.num_miss += 1; if self.config.write_allocate { let eviction_time = match lines.insert(tag, address) { Some(lower_address) => self.lower.access(lower_address, CacheOp::Write), None => 0, }; let result = self.config.latency + self.lower.access(address, CacheOp::Read) + eviction_time; match lines.find(tag) { Some(line) => line.is_dirty = true, None => panic!("Internal error"), } result } else { self.config.latency + self.lower.access(address, CacheOp::Write) } } } } } #[test] fn test001() { let llc = Box::new(Cache::new( CacheConfig { name: "test", write_through: false, write_allocate: true, capacity: 8 * 1024 * 1024, associativity: 8, line_size: 64, latency: 4, }, Box::new(Dram::new(13)) )); assert_eq!(llc.line_mask, 0xfffc0); assert_eq!(llc.tag_mask, !0xfffff); } impl Storage for Cache { fn access(&mut self, address: u64, op: CacheOp) -> Duration { let result = match op { CacheOp::Read => self.read(address), CacheOp::Write => self.write(address), }; self.stats.num_access += 1; self.stats.time += result; result } fn output_stats(&self) { println!("{}:", self.config.name); println!(" {:?}", self.stats); println!(" miss rate: {}", self.stats.num_miss as f32 / self.stats.num_access as f32); self.lower.output_stats(); } fn stats(&self) -> StorageStats { let StorageStats { num_miss, .. } = self.lower.stats(); StorageStats { num_miss: num_miss + self.stats.num_miss, num_access: self.stats.num_access, time: self.stats.time, } } } impl Dram { fn new(latency: Duration) -> Self { Self { latency, stats: Default::default(), } } } impl Storage for Dram { fn access(&mut self, _address: u64, _op: CacheOp) -> Duration { self.latency } fn stats(&self) -> StorageStats { self.stats } }
extern crate heliometer; use heliometer::*; fn main() { use std::io::Read; let args: Vec<_> = std::env::args().collect(); if args.len() != 2 { eprintln!("Usage: {} <file.bf>", args[0]); std::process::exit(1); } let mut file = std::fs::File::open(&args[1]).unwrap(); let mut input = String::new(); file.read_to_string(&mut input).unwrap(); execute(&input, &mut std::io::stdin(), &mut std::io::stdout()).unwrap(); }
#![feature(macro_rules)] extern crate libc; use std::c_str::CString; use std::default::Default; use std::fmt::Show; #[repr(C)] type uuid_t = [libc::c_char, ..16]; #[repr(C)] type r_uuid_t = [libc::c_char, ..37]; #[deriving(PartialEq)] pub struct Uuid(uuid_t); fn uuid_t() -> uuid_t { [0, ..16] } fn r_uuid_t() -> r_uuid_t { [0, ..37] } impl Show for Uuid { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { let &Uuid(uuid) = self; try!(write!(fmt, "Uuid(")); for c in uuid.iter() { try!(write!(fmt, "{:02x}", c.clone() as u8)); } try!(write!(fmt, ")")); Ok(()) } } impl Default for Uuid { fn default() -> Uuid { Uuid(uuid_t()) } } impl Clone for Uuid { fn clone(&self) -> Uuid { let mut uuid = uuid_t(); let &Uuid(old) = self; for i in range(0, 16) { uuid[i] = old[i]; } Uuid(uuid) } fn clone_from(&mut self, source: &Uuid) { let &Uuid(old) = source; let &Uuid(ref mut new) = self; for i in range(0, 16) { new[i] = old[i]; } } } mod c { use super::libc::{c_char, c_int}; #[link(name = "uuid")] extern { pub fn uuid_generate(out: *mut c_char); pub fn uuid_generate_random(out: *mut c_char); pub fn uuid_generate_time(out: *mut c_char); pub fn uuid_generate_time_safe(out: *mut c_char) -> c_int; pub fn uuid_parse(inp: *const c_char, out: *mut c_char) -> c_int; pub fn uuid_unparse(uu: *const c_char, out: *mut c_char); pub fn uuid_unparse_lower(uu: *const c_char, out: *mut c_char); pub fn uuid_unparse_upper(uu: *const c_char, out: *mut c_char); } } macro_rules! gen ( ($f:ident) => ( pub fn $f() -> Uuid { let mut out = uuid_t(); unsafe { c::$f(out.as_mut_ptr()) }; Uuid(out) } ) ) macro_rules! unparse ( ($f:ident) => ( pub fn $f(s: Uuid) -> String { let mut out = r_uuid_t(); let Uuid(inp) = s; unsafe { c::$f(inp.as_ptr(), out.as_mut_ptr()); } String::from_str(unsafe{ CString::new(out.as_ptr(), false).as_str().unwrap() }) } ) ) gen!(uuid_generate) gen!(uuid_generate_random) gen!(uuid_generate_time) pub fn uuid_generate_time_safe() -> (Uuid, bool) { let mut out = uuid_t(); let res = unsafe { c::uuid_generate_time_safe(out.as_mut_ptr()) }; (Uuid(out), (res == 0)) } pub fn uuid_parse(s: &str) -> Option<Uuid> { let mut out = uuid_t(); match unsafe {c::uuid_parse(s.as_ptr() as *const libc::c_char, out.as_mut_ptr())} { 0 => Some(Uuid(out)), _ => None, } } unparse!(uuid_unparse) unparse!(uuid_unparse_lower) unparse!(uuid_unparse_upper) #[cfg(test)] mod test { use super::{uuid_generate, uuid_generate_random, uuid_generate_time, uuid_generate_time_safe}; use super::{uuid_parse, uuid_unparse, uuid_unparse_lower, uuid_unparse_upper}; use std::ascii::OwnedAsciiExt; #[test] fn test_gen() { let uuid1 = uuid_generate(); let uuid2 = uuid_generate(); assert!(uuid1 != uuid2); let uuid3 = uuid1.clone(); assert_eq!(uuid1, uuid3); let uuid4 = uuid_generate_random(); assert!(uuid4 != uuid1); let uuid5 = uuid_generate_time(); assert!(uuid5 != uuid4); let (uuid6, _) = uuid_generate_time_safe(); assert!(uuid6 != uuid4); } #[test] fn test_parse() { let uuid = uuid_generate(); let u1 = uuid_unparse(uuid); assert_eq!(uuid_parse(u1.as_slice()).unwrap(), uuid); let u2 = uuid_unparse_lower(uuid); assert_eq!(uuid_parse(u2.as_slice()).unwrap(), uuid); let u1_copy = u1.clone(); assert_eq!(u1_copy.into_ascii_lower(), u2.into_ascii_lower()); let u3 = uuid_unparse_upper(uuid); assert_eq!(uuid_parse(u3.as_slice()).unwrap(), uuid); assert_eq!(u1.into_ascii_lower(), u3.into_ascii_lower()); } }
//! Serves to accept syscalls. use super::gdt::{USER_32BIT_CODE_SEGMENT, KERNEL_CODE_SEGMENT, TSS}; use syscalls::syscall_handler; use x86_64::registers::flags::Flags; use x86_64::registers::msr::{wrmsr, IA32_FMASK, IA32_KERNEL_GS_BASE, IA32_LSTAR, IA32_STAR}; /// Initializes the system to be able to accept syscalls. pub fn init() { let sysret_cs = USER_32BIT_CODE_SEGMENT.0 as u64; let syscall_cs = KERNEL_CODE_SEGMENT.0 as u64; let star_value = sysret_cs << 48 | syscall_cs << 32; let lstar_value = syscall_entry as u64; let fmask_value = Flags::IF.bits() as u64; let gs_base_value = unsafe { &TSS.privilege_stack_table[0] as *const _ as u64 }; unsafe { wrmsr(IA32_LSTAR, lstar_value); wrmsr(IA32_STAR, star_value); wrmsr(IA32_FMASK, fmask_value); wrmsr(IA32_KERNEL_GS_BASE, gs_base_value); } } /// The entry point for all syscalls. #[naked] extern "C" fn syscall_entry() { extern "C" fn syscall_inner() -> isize { let num; let arg1; let arg2; let arg3; let arg4; let arg5; let arg6; unsafe { asm!("" : "={rax}"(num), "={rdi}"(arg1), "={rsi}"(arg2), "={rdx}"(arg3), "={r10}"(arg4), "={r8}"(arg5), "={r9}"(arg6) : : : "intel", "volatile"); } syscall_handler(num, arg1, arg2, arg3, arg4, arg5, arg6) } unsafe { asm!("// Load the gs base to point to the stack pointer. swapgs // Save the old stack pointer. mov r12, rsp // Load the new stack pointer. mov rsp, gs:[0] // Restore the gs base. swapgs // Now that the stack pointer is a kernel stack pointer, enable interrupts. sti // Save some context. push r12 //The old stack pointer push r11 //The flags register push rcx //The program counter // Call the actual handler. call $0 // Restore the context. pop rcx pop r11 pop r12 // Restore the old stack pointer. cli mov rsp, r12 sysret" : : "i"(syscall_inner as extern "C" fn() -> isize) : : "intel", "volatile"); } }
use super::{definitions::Granularity, JsonAny}; use crate::serialization::default_for_null; use crate::serialization::tagged_or_untagged; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Deserialize, Serialize, Debug)] pub struct DruidListResponse<T: DeserializeOwned> { pub timestamp: String, #[serde(bound (deserialize = ""))] pub result: Vec<T>, } #[derive(Deserialize, Serialize, Debug)] pub struct MetadataResponse<T: DeserializeOwned> { pub timestamp: String, #[serde(bound (deserialize = ""))] pub result: T, } pub type TopNResponse<T> = DruidListResponse<T>; #[derive(Deserialize, Serialize, Debug)] pub struct GroupByResponse<T: DeserializeOwned> { pub timestamp: String, #[serde(bound (deserialize = ""))] pub event: T, } #[derive(Deserialize, Serialize, Debug)] pub struct DimValue { pub dimension: String, pub value: JsonAny, pub count: usize, } pub type SearchResponse = DruidListResponse<DimValue>; #[serde(rename_all = "camelCase")] #[derive(Deserialize, Serialize, Debug)] pub struct ScanResponse<T: DeserializeOwned> { segment_id: String, columns: Vec<String>, #[serde(bound (deserialize = ""))] events: Vec<T>, } #[derive(Deserialize, Serialize, Debug)] #[serde(rename_all = "camelCase")] pub struct MinMaxTime { pub max_time: Option<String>, pub min_time: Option<String>, } #[derive(Deserialize, Serialize, Debug)] pub struct TimeBoundaryResponse { timestamp: String, result: MinMaxTime, } #[derive(Deserialize, Serialize, Debug)] #[serde(rename_all = "camelCase")] pub struct ColumnDefinition { #[serde(rename(deserialize = "type"))] column_type: String, has_multiple_values: bool, size: usize, cardinality: Option<f32>, min_value: Option<JsonAny>, max_value: Option<JsonAny>, error_message: Option<String>, } #[derive(Deserialize, Serialize, Debug)] #[serde(rename_all = "camelCase")] pub struct AggregatorDefinition { #[serde(rename(deserialize = "type"))] aggr_type: String, name: String, field_name: String, expression: Option<String>, } #[derive(Deserialize, Serialize, Debug)] #[serde(rename_all = "camelCase")] pub struct TimestampSpec { column: String, format: String, missing_value: Option<String>, } #[derive(Deserialize, Serialize, Debug)] #[serde(rename_all = "camelCase")] pub struct SegmentMetadataResponse { id: String, #[serde(default, deserialize_with = "default_for_null")] intervals: Vec<String>, columns: HashMap<String, ColumnDefinition>, #[serde(deserialize_with = "tagged_or_untagged")] query_granularity: Granularity, rollup: Option<bool>, size: Option<usize>, num_rows: Option<usize>, timestamp_spec: TimestampSpec, #[serde(default, deserialize_with = "default_for_null")] aggregators: HashMap<String, AggregatorDefinition>, } #[derive(Deserialize, Serialize, Debug)] #[serde(rename_all = "camelCase")] pub struct TimeseriesResponse<T: DeserializeOwned> { timestamp: Option<String>, #[serde(bound (deserialize = ""))] result: T, }
extern crate peroxide; use peroxide::*; fn main() { let x = 0f64; let o1 = ODE { f: test_fun }; (o1.f)(x).print(); // Now, o1.f becomes f64 -> f64 let f = o1.f; f(1f64).print(); let o2 = ODE { f: test_fun }; let g = o2.f; g(Dual::new(2, 1)).print(); // Now o2.f becomes Dual -> Dual o1.eval_f64(1f64).print(); o1.eval_dual(Dual::new(2, 1)).print(); o2.eval_f64(1f64).print(); o2.eval_dual(Dual::new(2, 1)).print(); } struct ODE<T: Real> { f: fn(T) -> T, } fn test_fun<T: Real>(x: T) -> T { x + 1f64 } impl<T: Real> ODE<T> { fn eval_f64(&self, x: f64) -> f64 { (self.f)(T::from_f64(x)).to_f64() } fn eval_dual(&self, x: Dual) -> Dual { (self.f)(T::from_dual(x)).to_dual() } }
use gfx; use io::xdma; #[repr(align(16))] struct AlignedBuf([u8; 0x400]); fn make_data() -> AlignedBuf { let mut data = AlignedBuf([0u8; 0x400]); let mut ctr = 0; for byte in data.0.iter_mut() { *byte = ctr as u8; ctr += 5; } data } pub fn main() { gfx::clear_screen(0xFF, 0xFF, 0xFF); print!("Starting mem->mem XDMA... "); let buf0 = make_data(); let mut buf1 = AlignedBuf([0u8; 0x400]); xdma::mem_transfer( xdma::XdmaSrc::LinearBuf(buf0.0.as_ptr(), buf0.0.len()), xdma::XdmaDst::LinearBuf(buf1.0.as_mut_ptr(), buf1.0.len()) ); assert_eq!(&buf0.0[..], &buf1.0[..]); log!("SUCCESS!"); }
#[doc = "Reader of register CSDCMP"] pub type R = crate::R<u32, super::CSDCMP>; #[doc = "Writer for register CSDCMP"] pub type W = crate::W<u32, super::CSDCMP>; #[doc = "Register CSDCMP `reset()`'s with value 0"] impl crate::ResetValue for super::CSDCMP { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "CSD Comparator Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CSDCMP_EN_A { #[doc = "0: Disable comparator, output is zero"] OFF, #[doc = "1: On, regular operation. Note that CONFIG.LP_MODE determines the power mode level"] ON, } impl From<CSDCMP_EN_A> for bool { #[inline(always)] fn from(variant: CSDCMP_EN_A) -> Self { match variant { CSDCMP_EN_A::OFF => false, CSDCMP_EN_A::ON => true, } } } #[doc = "Reader of field `CSDCMP_EN`"] pub type CSDCMP_EN_R = crate::R<bool, CSDCMP_EN_A>; impl CSDCMP_EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CSDCMP_EN_A { match self.bits { false => CSDCMP_EN_A::OFF, true => CSDCMP_EN_A::ON, } } #[doc = "Checks if the value of the field is `OFF`"] #[inline(always)] pub fn is_off(&self) -> bool { *self == CSDCMP_EN_A::OFF } #[doc = "Checks if the value of the field is `ON`"] #[inline(always)] pub fn is_on(&self) -> bool { *self == CSDCMP_EN_A::ON } } #[doc = "Write proxy for field `CSDCMP_EN`"] pub struct CSDCMP_EN_W<'a> { w: &'a mut W, } impl<'a> CSDCMP_EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CSDCMP_EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Disable comparator, output is zero"] #[inline(always)] pub fn off(self) -> &'a mut W { self.variant(CSDCMP_EN_A::OFF) } #[doc = "On, regular operation. Note that CONFIG.LP_MODE determines the power mode level"] #[inline(always)] pub fn on(self) -> &'a mut W { self.variant(CSDCMP_EN_A::ON) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Select which IDAC polarity to use to detect CSDCMP triggering\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum POLARITY_SEL_A { #[doc = "0: Use idaca_pol (firmware setting with CSX and optionally DSI mixed in) to determine the direction, this is the most common use-case, used for normal CSD and normal CSX"] IDACA_POL, #[doc = "1: Use idacb_pol (firmware setting with optional DSI mixed in) to determine the direction, this is only used for normal CSD if IDACB is used i.s.o. IDACA (not common)"] IDACB_POL, #[doc = "2: Use the expression (csd_sense ? idaca_pol : idacb_pol) to determine the direction, this is only useful for the CSX with DUAL_IDAC use-case"] DUAL_POL, } impl From<POLARITY_SEL_A> for u8 { #[inline(always)] fn from(variant: POLARITY_SEL_A) -> Self { match variant { POLARITY_SEL_A::IDACA_POL => 0, POLARITY_SEL_A::IDACB_POL => 1, POLARITY_SEL_A::DUAL_POL => 2, } } } #[doc = "Reader of field `POLARITY_SEL`"] pub type POLARITY_SEL_R = crate::R<u8, POLARITY_SEL_A>; impl POLARITY_SEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, POLARITY_SEL_A> { use crate::Variant::*; match self.bits { 0 => Val(POLARITY_SEL_A::IDACA_POL), 1 => Val(POLARITY_SEL_A::IDACB_POL), 2 => Val(POLARITY_SEL_A::DUAL_POL), i => Res(i), } } #[doc = "Checks if the value of the field is `IDACA_POL`"] #[inline(always)] pub fn is_idaca_pol(&self) -> bool { *self == POLARITY_SEL_A::IDACA_POL } #[doc = "Checks if the value of the field is `IDACB_POL`"] #[inline(always)] pub fn is_idacb_pol(&self) -> bool { *self == POLARITY_SEL_A::IDACB_POL } #[doc = "Checks if the value of the field is `DUAL_POL`"] #[inline(always)] pub fn is_dual_pol(&self) -> bool { *self == POLARITY_SEL_A::DUAL_POL } } #[doc = "Write proxy for field `POLARITY_SEL`"] pub struct POLARITY_SEL_W<'a> { w: &'a mut W, } impl<'a> POLARITY_SEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: POLARITY_SEL_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Use idaca_pol (firmware setting with CSX and optionally DSI mixed in) to determine the direction, this is the most common use-case, used for normal CSD and normal CSX"] #[inline(always)] pub fn idaca_pol(self) -> &'a mut W { self.variant(POLARITY_SEL_A::IDACA_POL) } #[doc = "Use idacb_pol (firmware setting with optional DSI mixed in) to determine the direction, this is only used for normal CSD if IDACB is used i.s.o. IDACA (not common)"] #[inline(always)] pub fn idacb_pol(self) -> &'a mut W { self.variant(POLARITY_SEL_A::IDACB_POL) } #[doc = "Use the expression (csd_sense ? idaca_pol : idacb_pol) to determine the direction, this is only useful for the CSX with DUAL_IDAC use-case"] #[inline(always)] pub fn dual_pol(self) -> &'a mut W { self.variant(POLARITY_SEL_A::DUAL_POL) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4); self.w } } #[doc = "Select in what phase(s) the comparator is active, typically set to match the BAL_MODE of the used IDAC. Note, this also determines when a bad conversion is detected, namely at the beginning and end of the comparator active phase (also taking into account FILTER_DELAY and non-overlap).\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CMP_PHASE_A { #[doc = "0: Comparator is active from start of Phi2 and kept active into Phi1. Intended usage: legacy CSD for balancing over a full csd_sense period (non-overlap should be turned off)"] FULL, #[doc = "1: Comparator is active during Phi1 only. Currently no known use-case."] PHI1, #[doc = "2: Comparator is active during Phi2 only. Intended usage: CSD Low EMI."] PHI2, #[doc = "3: Comparator is activated at the start of both Phi1 and Phi2 (non-overlap should be enabled). Intended usage: CSX, or Full-Wave."] PHI1_2, } impl From<CMP_PHASE_A> for u8 { #[inline(always)] fn from(variant: CMP_PHASE_A) -> Self { match variant { CMP_PHASE_A::FULL => 0, CMP_PHASE_A::PHI1 => 1, CMP_PHASE_A::PHI2 => 2, CMP_PHASE_A::PHI1_2 => 3, } } } #[doc = "Reader of field `CMP_PHASE`"] pub type CMP_PHASE_R = crate::R<u8, CMP_PHASE_A>; impl CMP_PHASE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CMP_PHASE_A { match self.bits { 0 => CMP_PHASE_A::FULL, 1 => CMP_PHASE_A::PHI1, 2 => CMP_PHASE_A::PHI2, 3 => CMP_PHASE_A::PHI1_2, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `FULL`"] #[inline(always)] pub fn is_full(&self) -> bool { *self == CMP_PHASE_A::FULL } #[doc = "Checks if the value of the field is `PHI1`"] #[inline(always)] pub fn is_phi1(&self) -> bool { *self == CMP_PHASE_A::PHI1 } #[doc = "Checks if the value of the field is `PHI2`"] #[inline(always)] pub fn is_phi2(&self) -> bool { *self == CMP_PHASE_A::PHI2 } #[doc = "Checks if the value of the field is `PHI1_2`"] #[inline(always)] pub fn is_phi1_2(&self) -> bool { *self == CMP_PHASE_A::PHI1_2 } } #[doc = "Write proxy for field `CMP_PHASE`"] pub struct CMP_PHASE_W<'a> { w: &'a mut W, } impl<'a> CMP_PHASE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CMP_PHASE_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Comparator is active from start of Phi2 and kept active into Phi1. Intended usage: legacy CSD for balancing over a full csd_sense period (non-overlap should be turned off)"] #[inline(always)] pub fn full(self) -> &'a mut W { self.variant(CMP_PHASE_A::FULL) } #[doc = "Comparator is active during Phi1 only. Currently no known use-case."] #[inline(always)] pub fn phi1(self) -> &'a mut W { self.variant(CMP_PHASE_A::PHI1) } #[doc = "Comparator is active during Phi2 only. Intended usage: CSD Low EMI."] #[inline(always)] pub fn phi2(self) -> &'a mut W { self.variant(CMP_PHASE_A::PHI2) } #[doc = "Comparator is activated at the start of both Phi1 and Phi2 (non-overlap should be enabled). Intended usage: CSX, or Full-Wave."] #[inline(always)] pub fn phi1_2(self) -> &'a mut W { self.variant(CMP_PHASE_A::PHI1_2) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8); self.w } } #[doc = "Select which signal to output on dsi_sample_out.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CMP_MODE_A { #[doc = "0: CSD mode: output the filtered sample signal on dsi_sample_out"] CSD, #[doc = "1: General Purpose mode: output the unfiltered sample unfiltered comparator output, either asynchronous or flopped."] GP, } impl From<CMP_MODE_A> for bool { #[inline(always)] fn from(variant: CMP_MODE_A) -> Self { match variant { CMP_MODE_A::CSD => false, CMP_MODE_A::GP => true, } } } #[doc = "Reader of field `CMP_MODE`"] pub type CMP_MODE_R = crate::R<bool, CMP_MODE_A>; impl CMP_MODE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CMP_MODE_A { match self.bits { false => CMP_MODE_A::CSD, true => CMP_MODE_A::GP, } } #[doc = "Checks if the value of the field is `CSD`"] #[inline(always)] pub fn is_csd(&self) -> bool { *self == CMP_MODE_A::CSD } #[doc = "Checks if the value of the field is `GP`"] #[inline(always)] pub fn is_gp(&self) -> bool { *self == CMP_MODE_A::GP } } #[doc = "Write proxy for field `CMP_MODE`"] pub struct CMP_MODE_W<'a> { w: &'a mut W, } impl<'a> CMP_MODE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CMP_MODE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "CSD mode: output the filtered sample signal on dsi_sample_out"] #[inline(always)] pub fn csd(self) -> &'a mut W { self.variant(CMP_MODE_A::CSD) } #[doc = "General Purpose mode: output the unfiltered sample unfiltered comparator output, either asynchronous or flopped."] #[inline(always)] pub fn gp(self) -> &'a mut W { self.variant(CMP_MODE_A::GP) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "This bit controls whether the output directly from the comparator (csdcmp_out) or the flopped version (csdcmp_out_ff) is used. For CSD operation, the selected signal controls the IDAC(s), in GP mode the signal goes out on dsi_sample_out.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FEEDBACK_MODE_A { #[doc = "0: Use feedback from sampling flip-flop (used in most modes)."] FLOP, #[doc = "1: Use feedback from comparator directly (used in single Cmod mutual cap sensing only)"] COMP, } impl From<FEEDBACK_MODE_A> for bool { #[inline(always)] fn from(variant: FEEDBACK_MODE_A) -> Self { match variant { FEEDBACK_MODE_A::FLOP => false, FEEDBACK_MODE_A::COMP => true, } } } #[doc = "Reader of field `FEEDBACK_MODE`"] pub type FEEDBACK_MODE_R = crate::R<bool, FEEDBACK_MODE_A>; impl FEEDBACK_MODE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FEEDBACK_MODE_A { match self.bits { false => FEEDBACK_MODE_A::FLOP, true => FEEDBACK_MODE_A::COMP, } } #[doc = "Checks if the value of the field is `FLOP`"] #[inline(always)] pub fn is_flop(&self) -> bool { *self == FEEDBACK_MODE_A::FLOP } #[doc = "Checks if the value of the field is `COMP`"] #[inline(always)] pub fn is_comp(&self) -> bool { *self == FEEDBACK_MODE_A::COMP } } #[doc = "Write proxy for field `FEEDBACK_MODE`"] pub struct FEEDBACK_MODE_W<'a> { w: &'a mut W, } impl<'a> FEEDBACK_MODE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FEEDBACK_MODE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Use feedback from sampling flip-flop (used in most modes)."] #[inline(always)] pub fn flop(self) -> &'a mut W { self.variant(FEEDBACK_MODE_A::FLOP) } #[doc = "Use feedback from comparator directly (used in single Cmod mutual cap sensing only)"] #[inline(always)] pub fn comp(self) -> &'a mut W { self.variant(FEEDBACK_MODE_A::COMP) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `AZ_EN`"] pub type AZ_EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AZ_EN`"] pub struct AZ_EN_W<'a> { w: &'a mut W, } impl<'a> AZ_EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bit 0 - CSD Comparator Enable"] #[inline(always)] pub fn csdcmp_en(&self) -> CSDCMP_EN_R { CSDCMP_EN_R::new((self.bits & 0x01) != 0) } #[doc = "Bits 4:5 - Select which IDAC polarity to use to detect CSDCMP triggering"] #[inline(always)] pub fn polarity_sel(&self) -> POLARITY_SEL_R { POLARITY_SEL_R::new(((self.bits >> 4) & 0x03) as u8) } #[doc = "Bits 8:9 - Select in what phase(s) the comparator is active, typically set to match the BAL_MODE of the used IDAC. Note, this also determines when a bad conversion is detected, namely at the beginning and end of the comparator active phase (also taking into account FILTER_DELAY and non-overlap)."] #[inline(always)] pub fn cmp_phase(&self) -> CMP_PHASE_R { CMP_PHASE_R::new(((self.bits >> 8) & 0x03) as u8) } #[doc = "Bit 28 - Select which signal to output on dsi_sample_out."] #[inline(always)] pub fn cmp_mode(&self) -> CMP_MODE_R { CMP_MODE_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - This bit controls whether the output directly from the comparator (csdcmp_out) or the flopped version (csdcmp_out_ff) is used. For CSD operation, the selected signal controls the IDAC(s), in GP mode the signal goes out on dsi_sample_out."] #[inline(always)] pub fn feedback_mode(&self) -> FEEDBACK_MODE_R { FEEDBACK_MODE_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 31 - Auto-Zero enable, allow the Sequencer to Auto-Zero this component"] #[inline(always)] pub fn az_en(&self) -> AZ_EN_R { AZ_EN_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - CSD Comparator Enable"] #[inline(always)] pub fn csdcmp_en(&mut self) -> CSDCMP_EN_W { CSDCMP_EN_W { w: self } } #[doc = "Bits 4:5 - Select which IDAC polarity to use to detect CSDCMP triggering"] #[inline(always)] pub fn polarity_sel(&mut self) -> POLARITY_SEL_W { POLARITY_SEL_W { w: self } } #[doc = "Bits 8:9 - Select in what phase(s) the comparator is active, typically set to match the BAL_MODE of the used IDAC. Note, this also determines when a bad conversion is detected, namely at the beginning and end of the comparator active phase (also taking into account FILTER_DELAY and non-overlap)."] #[inline(always)] pub fn cmp_phase(&mut self) -> CMP_PHASE_W { CMP_PHASE_W { w: self } } #[doc = "Bit 28 - Select which signal to output on dsi_sample_out."] #[inline(always)] pub fn cmp_mode(&mut self) -> CMP_MODE_W { CMP_MODE_W { w: self } } #[doc = "Bit 29 - This bit controls whether the output directly from the comparator (csdcmp_out) or the flopped version (csdcmp_out_ff) is used. For CSD operation, the selected signal controls the IDAC(s), in GP mode the signal goes out on dsi_sample_out."] #[inline(always)] pub fn feedback_mode(&mut self) -> FEEDBACK_MODE_W { FEEDBACK_MODE_W { w: self } } #[doc = "Bit 31 - Auto-Zero enable, allow the Sequencer to Auto-Zero this component"] #[inline(always)] pub fn az_en(&mut self) -> AZ_EN_W { AZ_EN_W { w: self } } }
pub fn hello(possible_name: Option<&str>) -> String { format!("Hello, {}!", possible_name.unwrap_or("World")) }
use super::interface::*; use smol::Async; use std::{ hash, net::{SocketAddr, TcpListener, TcpStream}, }; use yggy_core::{dev::*, types::PeerURI}; /// /// TODO look into https://github.com/wzhd/ustcp #[derive(Debug)] pub struct TCPListener { addr: SocketAddr, listener: Async<TcpListener>, } impl TCPListener { #[inline] pub fn bind(addr: SocketAddr) -> Result<Self, Error> { let listener = Async::<TcpListener>::bind(&addr).map_err(ConnError::Interface)?; Ok(Self { addr, listener }) } #[inline] pub async fn accept(&self) -> Result<TCPStream, Error> { let (stream, addr) = self.listener.accept().await.map_err(ConnError::Interface)?; Ok(TCPStream { stream, addr }) } #[inline] pub fn local_addr(&self) -> &SocketAddr { &self.addr } } impl Eq for TCPListener {} impl PartialEq for TCPListener { fn eq(&self, other: &Self) -> bool { self.addr == other.addr } } impl hash::Hash for TCPListener { #[inline] fn hash<H: hash::Hasher>(&self, state: &mut H) { self.addr.hash(state); } } #[derive(Debug)] pub struct TCPStream { addr: SocketAddr, stream: Async<TcpStream>, } impl TCPStream { #[inline] pub async fn connect(addr: SocketAddr) -> Result<Self, Error> { let stream = Async::<TcpStream>::connect(&addr) .await .map_err(ConnError::Interface)?; Ok(Self { addr, stream }) } #[inline] pub fn split(self) -> (LinkReader, LinkWriter) { let (r, w) = io::AsyncReadExt::split(self); ( LinkReaderInner::TCP(r).into(), LinkWriterInner::TCP(w).into(), ) } #[inline] pub fn remote_addr(&self) -> &SocketAddr { &self.addr } } impl AsyncRead for TCPStream { #[inline] fn poll_read( mut self: Pin<&mut Self>, cx: &mut task::Context, buf: &mut [u8], ) -> task::Poll<Result<usize, io::Error>> { // let reader = self.stream; // futures::pin_mut!(reader); // reader.poll_read(cx, buf) unimplemented!() } } impl AsyncWrite for TCPStream { #[inline] fn poll_write( mut self: Pin<&mut Self>, cx: &mut task::Context, buf: &[u8], ) -> task::Poll<Result<usize, io::Error>> { // let writer = &mut self.writer; // futures::pin_mut!(writer); // writer.poll_write(cx, buf) unimplemented!() } #[inline] fn poll_flush( mut self: Pin<&mut Self>, cx: &mut task::Context, ) -> task::Poll<Result<(), io::Error>> { // let writer = &mut self.writer; // futures::pin_mut!(writer); // writer.poll_flush(cx) unimplemented!() } #[inline] fn poll_close( mut self: Pin<&mut Self>, cx: &mut task::Context, ) -> task::Poll<Result<(), io::Error>> { // let writer = &mut self.writer; // futures::pin_mut!(writer); // writer.poll_close(cx) unimplemented!() } }
/* Simple getopt alternative. Construct a vector of options, either by using * reqopt, optopt, and optflag or by building them from components yourself, * and pass them to getopts, along with a vector of actual arguments (not * including argv[0]). You'll either get a failure code back, or a match. * You'll have to verify whether the amount of 'free' arguments in the match * is what you expect. Use opt_* accessors (bottom of the file) to get * argument values out of the match object. */ import option::{some, none}; export opt; export reqopt; export optopt; export optflag; export optflagopt; export optmulti; export getopts; export result; export success; export failure; export match; export fail_; export fail_str; export opt_present; export opt_str; export opt_strs; export opt_maybe_str; export opt_default; tag name { long(str); short(char); } tag hasarg { yes; no; maybe; } tag occur { req; optional; multi; } type opt = {name: name, hasarg: hasarg, occur: occur}; fn mkname(nm: str) -> name { ret if str::char_len(nm) == 1u { short(str::char_at(nm, 0u)) } else { long(nm) }; } fn reqopt(name: str) -> opt { ret {name: mkname(name), hasarg: yes, occur: req}; } fn optopt(name: str) -> opt { ret {name: mkname(name), hasarg: yes, occur: optional}; } fn optflag(name: str) -> opt { ret {name: mkname(name), hasarg: no, occur: optional}; } fn optflagopt(name: str) -> opt { ret {name: mkname(name), hasarg: maybe, occur: optional}; } fn optmulti(name: str) -> opt { ret {name: mkname(name), hasarg: yes, occur: multi}; } tag optval { val(str); given; } type match = {opts: [opt], vals: [mutable [optval]], free: [str]}; fn is_arg(arg: str) -> bool { ret str::byte_len(arg) > 1u && arg[0] == '-' as u8; } fn name_str(nm: name) -> str { ret alt nm { short(ch) { str::from_char(ch) } long(s) { s } }; } fn find_opt(opts: [opt], nm: name) -> option::t<uint> { let i = 0u; let l = vec::len::<opt>(opts); while i < l { if opts[i].name == nm { ret some::<uint>(i); } i += 1u; } ret none::<uint>; } tag fail_ { argument_missing(str); unrecognized_option(str); option_missing(str); option_duplicated(str); unexpected_argument(str); } fn fail_str(f: fail_) -> str { ret alt f { argument_missing(nm) { "Argument to option '" + nm + "' missing." } unrecognized_option(nm) { "Unrecognized option: '" + nm + "'." } option_missing(nm) { "Required option '" + nm + "' missing." } option_duplicated(nm) { "Option '" + nm + "' given more than once." } unexpected_argument(nm) { "Option " + nm + " does not take an argument." } }; } tag result { success(match); failure(fail_); } fn getopts(args: [str], opts: [opt]) -> result { let n_opts = vec::len::<opt>(opts); fn f(_x: uint) -> [optval] { ret []; } let vals = vec::init_fn_mut::<[optval]>(f, n_opts); let free: [str] = []; let l = vec::len(args); let i = 0u; while i < l { let cur = args[i]; let curlen = str::byte_len(cur); if !is_arg(cur) { free += [cur]; } else if str::eq(cur, "--") { let j = i + 1u; while j < l { free += [args[j]]; j += 1u; } break; } else { let names; let i_arg = option::none::<str>; if cur[1] == '-' as u8 { let tail = str::slice(cur, 2u, curlen); let eq = str::index(tail, '=' as u8); if eq == -1 { names = [long(tail)]; } else { names = [long(str::slice(tail, 0u, eq as uint))]; i_arg = option::some::<str>(str::slice(tail, (eq as uint) + 1u, curlen - 2u)); } } else { let j = 1u; names = []; while j < curlen { let range = str::char_range_at(cur, j); names += [short(range.ch)]; j = range.next; } } let name_pos = 0u; for nm: name in names { name_pos += 1u; let optid; alt find_opt(opts, nm) { some(id) { optid = id; } none. { ret failure(unrecognized_option(name_str(nm))); } } alt opts[optid].hasarg { no. { if !option::is_none::<str>(i_arg) { ret failure(unexpected_argument(name_str(nm))); } vals[optid] += [given]; } maybe. { if !option::is_none::<str>(i_arg) { vals[optid] += [val(option::get(i_arg))]; } else if name_pos < vec::len::<name>(names) || i + 1u == l || is_arg(args[i + 1u]) { vals[optid] += [given]; } else { i += 1u; vals[optid] += [val(args[i])]; } } yes. { if !option::is_none::<str>(i_arg) { vals[optid] += [val(option::get::<str>(i_arg))]; } else if i + 1u == l { ret failure(argument_missing(name_str(nm))); } else { i += 1u; vals[optid] += [val(args[i])]; } } } } } i += 1u; } i = 0u; while i < n_opts { let n = vec::len::<optval>(vals[i]); let occ = opts[i].occur; if occ == req { if n == 0u { ret failure(option_missing(name_str(opts[i].name))); } } if occ != multi { if n > 1u { ret failure(option_duplicated(name_str(opts[i].name))); } } i += 1u; } ret success({opts: opts, vals: vals, free: free}); } fn opt_vals(m: match, nm: str) -> [optval] { ret alt find_opt(m.opts, mkname(nm)) { some(id) { m.vals[id] } none. { log_err "No option '" + nm + "' defined."; fail } }; } fn opt_val(m: match, nm: str) -> optval { ret opt_vals(m, nm)[0]; } fn opt_present(m: match, nm: str) -> bool { ret vec::len::<optval>(opt_vals(m, nm)) > 0u; } fn opt_str(m: match, nm: str) -> str { ret alt opt_val(m, nm) { val(s) { s } _ { fail } }; } fn opt_strs(m: match, nm: str) -> [str] { let acc: [str] = []; for v: optval in opt_vals(m, nm) { alt v { val(s) { acc += [s]; } _ { } } } ret acc; } fn opt_maybe_str(m: match, nm: str) -> option::t<str> { let vals = opt_vals(m, nm); if vec::len::<optval>(vals) == 0u { ret none::<str>; } ret alt vals[0] { val(s) { some::<str>(s) } _ { none::<str> } }; } /// Returns none if the option was not present, `def` if the option was /// present but no argument was provided, and the argument if the option was /// present and an argument was provided. fn opt_default(m: match, nm: str, def: str) -> option::t<str> { let vals = opt_vals(m, nm); if vec::len::<optval>(vals) == 0u { ret none::<str>; } ret alt vals[0] { val(s) { some::<str>(s) } _ { some::<str>(def) } } } // Local Variables: // mode: rust; // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'"; // End:
extern crate messengerdep; pub struct Messenger { message: String, } impl Messenger { pub fn new(message: &str) -> Messenger { Messenger { message: message.to_string(), } } pub fn deliver(&self) { println!("I have a message to deliver to you: {}", &self.message); messengerdep::handler(); } }
pub trait MyTrait {} dyn_clone::clone_trait_object!(MyTrait); fn main() {}
use std::{cmp::Ordering, iter}; use crate::{ commands::osu::RankData, embeds::Author, util::{ numbers::{with_comma_float, with_comma_int}, osu::{approx_more_pp, pp_missing, ExtractablePp, PpListUtil}, }, }; use rosu_v2::model::score::Score; pub struct RankEmbed { description: String, title: String, thumbnail: String, author: Author, } impl RankEmbed { pub fn new(data: RankData, scores: Option<Vec<Score>>, each: Option<f32>) -> Self { let (title, description) = match &data { RankData::Sub10k { user, rank, country, rank_holder, } => { let user_pp = user.statistics.as_ref().unwrap().pp; let rank_holder_pp = rank_holder.statistics.as_ref().unwrap().pp; let country = country.as_ref().map(|code| code.as_str()).unwrap_or("#"); let title = format!( "How many pp is {name} missing to reach rank {country}{rank}?", name = user.username, ); let description = if user.user_id == rank_holder.user_id { format!("{} is already at rank #{rank}.", user.username) } else if user_pp > rank_holder_pp { format!( "Rank {country}{rank} is currently held by {holder_name} with \ **{holder_pp}pp**, so {name} is already above that with **{pp}pp**.", holder_name = rank_holder.username, holder_pp = with_comma_float(rank_holder_pp), name = user.username, pp = with_comma_float(user_pp) ) } else if let Some(scores) = scores { match (scores.last().and_then(|s| s.pp), each) { (Some(last_pp), Some(each)) if each < last_pp => { format!( "Rank {country}{rank} is currently held by {holder_name} with \ **{holder_pp}pp**, so {name} is missing **{missing}** raw pp.\n\ A new top100 score requires at least **{last_pp}pp** \ so {holder_pp} total pp can't be reached with {each}pp scores.", holder_name = rank_holder.username, holder_pp = with_comma_float(rank_holder_pp), name = user.username, missing = with_comma_float(rank_holder_pp - user_pp), last_pp = with_comma_float(last_pp), each = with_comma_float(each), ) } (_, Some(each)) => { let mut pps = scores.extract_pp(); let (required, idx) = if scores.len() == 100 { approx_more_pp(&mut pps, 50); pp_missing(user_pp, rank_holder_pp, pps.as_slice()) } else { pp_missing(user_pp, rank_holder_pp, scores.as_slice()) }; if required < each { format!( "Rank {country}{rank} is currently held by {holder_name} with \ **{holder_pp}pp**, so {name} is missing **{missing}** raw pp.\n\ To reach {holder_pp}pp with one additional score, {name} needs to \ perform a **{required}pp** score which would be the top {approx}#{idx}", holder_name = rank_holder.username, holder_pp = with_comma_float(rank_holder_pp), name = user.username, missing = with_comma_float(rank_holder_pp - user_pp), required = with_comma_float(required), approx = if idx >= 100 { "~" } else { "" }, idx = idx + 1, ) } else { let idx = pps .iter() .position(|&pp| pp < each) .unwrap_or_else(|| pps.len()); let mut iter = pps .iter() .copied() .zip(0..) .map(|(pp, i)| pp * 0.95_f32.powi(i)); let mut top: f32 = (&mut iter).take(idx).sum(); let bot: f32 = iter.sum(); let bonus_pp = (user_pp - (top + bot)).max(0.0); top += bonus_pp; let len = pps.len(); let mut n_each = len; for i in idx..len { let bot = pps[idx..] .iter() .copied() .zip(i as i32 + 1..) .fold(0.0, |sum, (pp, i)| sum + pp * 0.95_f32.powi(i)); let factor = 0.95_f32.powi(i as i32); if top + factor * each + bot >= rank_holder_pp { // requires n_each many new scores of `each` many pp and one additional score n_each = i - idx; break; } top += factor * each; } if n_each == len { format!( "Rank {country}{rank} is currently held by {holder_name} with \ **{holder_pp}pp**, so {name} is missing **{missing}** raw pp.\n\ Filling up {name}'{genitiv} top scores with {amount} new \ {each}pp score{plural} would only lead to {approx}**{top}pp** which \ is still less than {holder_pp}pp.", holder_name = rank_holder.username, holder_pp = with_comma_float(rank_holder_pp), amount = len - idx, each = with_comma_float(each), missing = with_comma_float(rank_holder_pp - user_pp), plural = if len - idx != 1 { "s" } else { "" }, genitiv = if idx != 1 { "s" } else { "" }, approx = if idx >= 100 { "roughly " } else { "" }, top = with_comma_float(top), name = user.username, ) } else { pps.extend(iter::repeat(each).take(n_each)); pps.sort_unstable_by(|a, b| { b.partial_cmp(a).unwrap_or(Ordering::Equal) }); let accum = pps.accum_weighted(); // Calculate the pp of the missing score after adding `n_each` many `each` pp scores let total = accum + bonus_pp; let (required, _) = pp_missing(total, rank_holder_pp, pps.as_slice()); format!( "Rank {country}{rank} is currently held by {holder_name} with \ **{holder_pp}pp**, so {name} is missing **{missing}** raw pp.\n\ To reach {holder_pp}pp, {name} needs to perform **{n_each}** \ more {each}pp score{plural} and one **{required}pp** score.", holder_name = rank_holder.username, holder_pp = with_comma_float(rank_holder_pp), missing = with_comma_float(rank_holder_pp - user_pp), each = with_comma_float(each), plural = if n_each != 1 { "s" } else { "" }, name = user.username, required = with_comma_float(required), ) } } } _ => { let (required, idx) = if scores.len() == 100 { let mut pps = scores.extract_pp(); approx_more_pp(&mut pps, 50); pp_missing(user_pp, rank_holder_pp, pps.as_slice()) } else { pp_missing(user_pp, rank_holder_pp, scores.as_slice()) }; format!( "Rank {country}{rank} is currently held by {holder_name} with \ **{holder_pp}pp**, so {name} is missing **{missing}** raw pp, achievable \ with a single score worth **{pp}pp** which would be the top {approx}#{idx}.", holder_name = rank_holder.username, holder_pp = with_comma_float(rank_holder_pp), name = user.username, missing = with_comma_float(rank_holder_pp - user_pp), pp = with_comma_float(required), approx = if idx >= 100 { "~" } else { "" }, idx = idx + 1, ) } } } else { format!( "Rank {country}{rank} is currently held by {holder_name} with \ **{holder_pp}pp**, so {name} is missing **{holder_pp}** raw pp, \ achievable with a single score worth **{holder_pp}pp**.", holder_name = rank_holder.username, holder_pp = with_comma_float(rank_holder_pp), name = user.username, ) }; (title, description) } RankData::Over10k { user, rank, required_pp, } => { let user_pp = user.statistics.as_ref().unwrap().pp; let title = format!( "How many pp is {name} missing to reach rank #{rank}?", name = user.username, rank = with_comma_int(*rank), ); let description = if user_pp > *required_pp { format!( "Rank #{rank} currently requires **{required_pp}pp**, \ so {name} is already above that with **{pp}pp**.", rank = with_comma_int(*rank), required_pp = with_comma_float(*required_pp), name = user.username, pp = with_comma_float(user_pp) ) } else if let Some(scores) = scores { match (scores.last().and_then(|s| s.pp), each) { (Some(last_pp), Some(each)) if each < last_pp => { format!( "Rank #{rank} currently requires **{required_pp}pp**, \ so {name} is missing **{missing}** raw pp.\n\ A new top100 score requires at least **{last_pp}pp** \ so {required_pp} total pp can't be reached with {each}pp scores.", required_pp = with_comma_float(*required_pp), name = user.username, missing = with_comma_float(required_pp - user_pp), last_pp = with_comma_float(last_pp), each = with_comma_float(each), ) } (_, Some(each)) => { let mut pps = scores.extract_pp(); let (required, idx) = if scores.len() == 100 { approx_more_pp(&mut pps, 50); pp_missing(user_pp, *required_pp, pps.as_slice()) } else { pp_missing(user_pp, *required_pp, scores.as_slice()) }; if required < each { format!( "Rank #{rank} currently requires **{required_pp}pp**, \ so {name} is missing **{missing}** raw pp.\n\ To reach {required_pp}pp with one additional score, {name} needs to \ perform a **{required}pp** score which would be the top {approx}#{idx}", name = user.username, required_pp = with_comma_float(*required_pp), missing = with_comma_float(required_pp - user_pp), required = with_comma_float(required), approx = if idx >= 100 { "~" } else { "" }, idx = idx + 1, ) } else { let idx = pps .iter() .position(|&pp| pp < each) .unwrap_or_else(|| pps.len()); let mut iter = pps .iter() .copied() .zip(0..) .map(|(pp, i)| pp * 0.95_f32.powi(i)); let mut top: f32 = (&mut iter).take(idx).sum(); let bot: f32 = iter.sum(); let bonus_pp = (user_pp - (top + bot)).max(0.0); top += bonus_pp; let len = pps.len(); let mut n_each = len; for i in idx..len { let bot = pps[idx..] .iter() .copied() .zip(i as i32 + 1..) .fold(0.0, |sum, (pp, i)| sum + pp * 0.95_f32.powi(i)); let factor = 0.95_f32.powi(i as i32); if top + factor * each + bot >= *required_pp { // requires n_each many new scores of `each` many pp and one additional score n_each = i - idx; break; } top += factor * each; } if n_each == len { format!( "Rank #{rank} currently requires **{required_pp}pp**, \ so {name} is missing **{missing}** raw pp.\n\ Filling up {name}'{genitiv} top100 with {amount} new \ {each}pp score{plural} would only lead to {approx}**{top}pp** which \ is still less than {required_pp}pp.", required_pp = with_comma_float(*required_pp), amount = len - idx, each = with_comma_float(each), missing = with_comma_float(required_pp - user_pp), plural = if len - idx != 1 { "s" } else { "" }, genitiv = if idx != 1 { "s" } else { "" }, approx = if idx >= 100 { "roughly " } else { "" }, top = with_comma_float(top), name = user.username, ) } else { pps.extend(iter::repeat(each).take(n_each)); pps.sort_unstable_by(|a, b| { b.partial_cmp(a).unwrap_or(Ordering::Equal) }); let accum = pps.accum_weighted(); // Calculate the pp of the missing score after adding `n_each` many `each` pp scores let total = accum + bonus_pp; let (required, _) = pp_missing(total, *required_pp, pps.as_slice()); format!( "Rank #{rank} currently requires **{required_pp}pp**, \ so {name} is missing **{missing}** raw pp.\n\ To reach {required_pp}pp, {name} needs to perform **{n_each}** \ more {each}pp score{plural} and one **{required}pp** score.", required_pp = with_comma_float(*required_pp), missing = with_comma_float(required_pp - user_pp), each = with_comma_float(each), plural = if n_each != 1 { "s" } else { "" }, name = user.username, required = with_comma_float(required), ) } } } _ => { let (required, idx) = if scores.len() == 100 { let mut pps = scores.extract_pp(); approx_more_pp(&mut pps, 50); pp_missing(user_pp, *required_pp, pps.as_slice()) } else { pp_missing(user_pp, *required_pp, scores.as_slice()) }; format!( "Rank #{rank} currently requires **{required_pp}pp**, so \ {name} is missing **{missing}** raw pp, achievable with a \ single score worth **{pp}pp** which would be the top {approx}#{idx}.", rank = with_comma_int(*rank), required_pp = with_comma_float(*required_pp), name = user.username, missing = with_comma_float(required_pp - user_pp), pp = with_comma_float(required), approx = if idx >= 100 { "~" } else { "" }, idx = idx + 1, ) } } } else { format!( "Rank #{rank} currently requires **{required_pp}pp**, \ so {name} is missing **{required_pp}** raw pp, \ achievable with a single score worth **{required_pp}pp**.", rank = with_comma_int(*rank), required_pp = with_comma_float(*required_pp), name = user.username, ) }; (title, description) } }; let user = data.user(); Self { title, description, author: author!(user), thumbnail: user.avatar_url, } } } impl_builder!(RankEmbed { author, description, thumbnail, title, });
use serde::Deserialize; use std::collections::HashMap; use std::path::PathBuf; #[derive(Clone, Debug, Deserialize)] pub struct Config { pub process: Process, pub root: Root, pub hostname: String, #[serde(default)] pub mount_label: String, #[serde(default)] pub root_propagation: u64, #[serde(default)] pub mounts: Vec<Mount>, #[serde(default)] pub linux: Linux, #[serde(default)] pub limits: Limits, } #[derive(Clone, Debug, Default, Deserialize)] pub struct Process { #[serde(default)] pub user: User, #[serde(default)] pub env: Vec<String>, #[serde(default)] pub cwd: Option<PathBuf>, pub capabilities: Option<Capabilities>, #[serde(default)] pub rlimits: Vec<Rlimit>, #[serde(alias = "noNewPrivileges")] pub no_new_privileges: bool, } #[derive(Clone, Debug, Default, Deserialize)] pub struct User { // uid inside container pub uid: libc::uid_t, // gid inside container pub gid: libc::gid_t, #[serde(default)] pub umask: Option<u32>, } #[derive(Clone, Debug, Default, Deserialize)] pub struct Capabilities { #[serde(default)] pub bounding: Vec<String>, #[serde(default)] pub effective: Vec<String>, #[serde(default)] pub inheritable: Vec<String>, #[serde(default)] pub permitted: Vec<String>, #[serde(default)] pub ambient: Vec<String>, } #[derive(Clone, Debug, Default, Deserialize)] pub struct Rlimit { #[serde(alias = "type")] pub kind: String, pub hard: u64, pub soft: u64, } #[derive(Clone, Debug, Default, Deserialize)] pub struct Root { pub path: PathBuf, pub readonly: bool, } #[derive(Clone, Debug, Default, Deserialize)] pub struct Mount { pub destination: PathBuf, #[serde(alias = "type")] pub kind: String, pub source: String, #[serde(default)] pub options: Vec<String>, } #[derive(Clone, Debug, Default, Deserialize)] pub struct Linux { #[serde(default, alias = "uidMappings")] pub uid_mappings: Vec<IDMap>, #[serde(default, alias = "gidMappings")] pub gid_mappings: Vec<IDMap>, #[serde(default)] pub devices: Vec<Device>, #[serde(default)] pub seccomp: Option<Seccomp>, #[serde(default)] pub namespaces: Vec<Namespace>, #[serde(default)] pub masked_paths: Vec<PathBuf>, #[serde(default)] pub readonly_paths: Vec<PathBuf>, #[serde(alias = "cgroupsPath")] pub cgroups_path: Option<String>, #[serde(default)] pub resources: Option<Resources>, } #[derive(Clone, Debug, Default, Deserialize)] pub struct IDMap { /// First uid/gid inside guest user namespace. #[serde(alias = "containerID")] pub container_id: u64, /// First uid/gid in host. #[serde(alias = "hostID")] pub host_id: u64, /// Number of uid/gids that this entry maps from host into guest user namespace. pub size: u64, } #[derive(Clone, Debug, Default, Deserialize)] pub struct Device { #[serde(alias = "type")] pub kind: String, pub path: PathBuf, #[serde(default)] pub major: u64, #[serde(default)] pub minor: u64, #[serde(alias = "fileMode")] pub file_mode: u32, #[serde(default)] pub uid: libc::uid_t, #[serde(default)] pub gid: libc::gid_t, } #[derive(Clone, Debug, Default, Deserialize)] pub struct Seccomp { #[serde(alias = "defaultAction")] pub default_action: String, pub architectures: Vec<String>, pub syscalls: Vec<Syscall>, } #[derive(Clone, Debug, Default, Deserialize)] pub struct Syscall { pub names: Option<Vec<String>>, pub nr: Option<usize>, pub action: String, #[serde(default, alias = "errnoRet")] pub errno_ret: i64, #[serde(default)] pub args: Vec<SyscallArg>, } #[derive(Clone, Debug, Default, Deserialize)] pub struct SyscallArg { pub index: u32, pub value: u64, #[serde(default, alias = "valueTwo")] pub value_two: Option<u64>, pub op: String, } #[derive(Clone, Debug, Default, Deserialize)] pub struct Namespace { #[serde(alias = "type")] pub kind: String, pub path: Option<String>, } #[derive(Clone, Debug, Default, Deserialize)] pub struct Resources { pub memory: Option<MemoryResources>, pub cpu: Option<CPUResources>, pub pids: Option<PIDResources>, #[serde(default)] pub devices: Vec<DeviceResource>, pub unified: Option<HashMap<String, String>>, } #[derive(Clone, Debug, Default, Deserialize)] pub struct MemoryResources { pub limit: Option<i64>, pub reservation: Option<i64>, pub swap: Option<i64>, pub kernel: Option<i64>, #[serde(alias = "kernelTCP")] pub kernel_tcp: Option<i64>, pub swappiness: Option<u64>, #[serde(default, alias = "disableOOMKiller")] pub disable_oom_killer: bool, #[serde(default, alias = "useHierarchy")] pub use_hierarchy: bool, } #[derive(Clone, Debug, Default, Deserialize)] pub struct CPUResources { pub shares: Option<u64>, pub quota: Option<i64>, pub period: Option<u64>, #[serde(alias = "realtimeRuntime")] pub realtime_runtime: Option<i64>, #[serde(alias = "realtimePeriod")] pub realtime_period: Option<u64>, pub cpus: Option<String>, pub mems: Option<String>, } #[derive(Clone, Debug, Default, Deserialize)] pub struct PIDResources { pub limit: Option<i64>, } /// An enum holding the different types of devices that can be manipulated using this controller. #[derive(Clone, Debug, Deserialize)] pub enum DeviceType { /// The rule applies to all devices. #[serde(rename = "a")] All, /// The rule only applies to character devices. #[serde(rename = "c")] Char, /// The rule only applies to block devices. #[serde(rename = "b")] Block, } #[derive(Clone, Debug, Deserialize)] pub struct DeviceResource { /// If true, access to the device is allowed, otherwise it's denied. pub allow: bool, /// `'c'` for character device, `'b'` for block device; or `'a'` for all devices. #[serde(alias = "type")] pub kind: DeviceType, /// The major number of the device. pub major: Option<i64>, /// The minor number of the device. pub minor: Option<i64>, /// Sequence of `'r'`, `'w'` or `'m'`, each denoting read, write or mknod permissions. pub access: Option<String>, } #[derive(Clone, Debug, Default, Deserialize)] pub struct Limits { pub wall_limit: Option<f64>, pub cpu_limit: Option<f64>, }
use std::env::current_exe; fn main() { if let Ok(path) = current_exe() { let mut a = path.clone(); a.push(".."); println!("{:?}", a); println!("{:?}", (&*path).parent().unwrap()); } }
use crate::command_class::CommandClass; use bytes::{ Bytes, Buf, BytesMut, BufMut }; #[derive(Debug, PartialEq, Clone)] pub struct ApplicationCommandHandlerRequest { pub status : u8, pub node_id : u8, pub data : CommandClass, } impl ApplicationCommandHandlerRequest { pub fn encode(&self, dst: &mut BytesMut) { dst.put_u8(self.status); dst.put_u8(self.node_id); dst.put_u8(0x0); self.data.encode(dst); } pub fn decode(src: &mut Bytes) -> ApplicationCommandHandlerRequest { let status = src.get_u8(); let node_id = src.get_u8(); src.advance(1); // skip ApplicationCommandHandlerRequest { status, node_id, data: CommandClass::decode(src) } } }
mod fragmentation; mod misc; mod socket; mod spi; pub(crate) use fragmentation::{Joiner, Splitter, MIN_MTU}; pub(crate) use socket::DuplexSocket; pub use spi::*;
use std::collections::HashMap; use std::io; use std::iter::{Extend, FromIterator}; use std::mem; use std::ptr::null_mut; use bincode; use libc::c_void; use bw; use send_pointer::SendPtr; quick_error! { #[derive(Debug)] pub enum SaveError { BwIo { display("Broodwar I/O error") } Serialize(err: bincode::Error) { display("Serialization error: {}", err) from() } Io(err: io::Error) { display("I/O error: {}", err) from() } SizeLimit(amt: u64) { display("Too large chunk: {}", amt) } InvalidPointer { display("Internal error: Invalid pointer") } InvalidGrpPointer { display("Internal error: Invalid grp pointer") } InvalidRemapPalette { display("Internal error: Invalid remap palette") } InvalidUnitAi(ai: u8) { display("Internal error: Invalid unit ai type {}", ai) } } } quick_error! { #[derive(Debug)] pub enum LoadError { BwIo { display("Broodwar I/O error") } Serialize(err: bincode::Error) { display("Deserialization error: {}", err) from() } SizeLimit { display("Too large chunk") } WrongMagic(m: u16) { display("Incorrect magic: 0x{:x}", m) } Version(ver: u32) { display("Unsupported (newer?) version {}", ver) } Corrupted(info: String) { display("Invalid save data ({})", info) } } } pub unsafe fn fread_num<T>(file: *mut c_void) -> Result<T, LoadError> { let mut val = mem::MaybeUninit::<T>::uninit(); let ok = bw::fread(val.as_mut_ptr() as *mut c_void, mem::size_of::<T>() as u32, 1, file); if ok != 1 { Err(LoadError::BwIo) } else { Ok(val.assume_init()) } } pub unsafe fn fread(file: *mut c_void, size: u32) -> Result<Vec<u8>, LoadError> { let mut buf = Vec::with_capacity(size as usize); let ok = bw::fread(buf.as_mut_ptr() as *mut c_void, size, 1, file); if ok != 1 { Err(LoadError::BwIo) } else { buf.set_len(size as usize); Ok(buf) } } pub unsafe fn fwrite_num<T>(file: *mut c_void, value: T) -> Result<(), SaveError> { let amount = bw::fwrite(&value as *const T as *const c_void, mem::size_of::<T>() as u32, 1, file); if amount != 1 { Err(SaveError::BwIo) } else { Ok(()) } } pub unsafe fn fwrite(file: *mut c_void, buf: &[u8]) -> Result<(), SaveError> { let amount = bw::fwrite(buf.as_ptr() as *const c_void, buf.len() as u32, 1, file); if amount != 1 { Err(SaveError::BwIo) } else { Ok(()) } } pub unsafe fn print_text(msg: &str) { let mut buf: Vec<u8> = msg.as_bytes().into(); buf.push(0); bw::print_text(buf.as_ptr(), 0, 8); } pub struct SaveMapping<T>(pub HashMap<SendPtr<T>, u32>); impl<T> SaveMapping<T> { pub fn new() -> SaveMapping<T> { SaveMapping(HashMap::new()) } pub fn id(&self, val: *mut T) -> Result<u32, SaveError> { if val == null_mut() { Ok(0) } else { self.0.get(&val.into()).cloned().ok_or(SaveError::InvalidPointer) } } pub fn len(&self) -> usize { self.0.len() } } impl<T> FromIterator<(*mut T, u32)> for SaveMapping<T> { fn from_iter<I: IntoIterator<Item=(*mut T, u32)>>(iter: I) -> SaveMapping<T> { SaveMapping(iter.into_iter().map(|(x, y)| (x.into(), y)).collect()) } } pub struct LoadMapping<T>(pub Vec<SendPtr<T>>); impl<T> LoadMapping<T> { pub fn new() -> LoadMapping<T> { LoadMapping(Vec::new()) } pub fn pointer(&self, id: u32) -> Result<*mut T, LoadError> { if id == 0 { Ok(null_mut()) } else { self.0.get(id as usize - 1).map(|&SendPtr(x)| x).ok_or_else(|| { LoadError::Corrupted(format!("Invalid id 0x{:x}", id)) }) } } } impl<T> Extend<*mut T> for LoadMapping<T> { fn extend<I: IntoIterator<Item=*mut T>>(&mut self, iter: I) { self.0.extend(iter.into_iter().map(|x| SendPtr(x))) } } impl<T> Default for LoadMapping<T> { fn default() -> LoadMapping<T> { LoadMapping(vec![]) } }
// Copyright (C) 2019 Boyu Yang // // 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. use jsonrpc_core::error::Error as CoreError; use reqwest::Error as ReqwestError; #[derive(Debug)] pub enum Error { OptionNone, Custom(String), Core(CoreError), Serde(String), Reqwest(ReqwestError), } impl ::std::fmt::Display for Error { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "{:?}", self) } } impl ::std::error::Error for Error {} pub type Result<T> = ::std::result::Result<T, Error>; impl Error { pub fn none() -> Self { Error::OptionNone } pub fn custom(msg: &str) -> Self { Error::Custom(msg.to_owned()) } pub fn serde(msg: &str) -> Self { Error::Serde(msg.to_owned()) } } impl From<CoreError> for Error { fn from(err: CoreError) -> Self { Error::Core(err) } } impl From<ReqwestError> for Error { fn from(err: ReqwestError) -> Self { Error::Reqwest(err) } }
use std::sync::{ atomic::{AtomicU32, Ordering}, Arc, }; use crate::{ cmap::{establish::ConnectionEstablisher, options::ConnectionPoolOptions, ConnectionPool}, options::{ClientOptions, ServerAddress}, sdam::TopologyUpdater, }; /// Contains the state for a given server in the topology. #[derive(Debug)] pub(crate) struct Server { pub(crate) address: ServerAddress, /// The connection pool for the server. pub(crate) pool: ConnectionPool, /// Number of operations currently using this server. operation_count: AtomicU32, } impl Server { #[cfg(test)] pub(crate) fn new_mocked(address: ServerAddress, operation_count: u32) -> Self { Self { address: address.clone(), pool: ConnectionPool::new_mocked(address), operation_count: AtomicU32::new(operation_count), } } /// Create a new reference counted `Server`, including its connection pool. pub(crate) fn new( address: ServerAddress, options: ClientOptions, connection_establisher: ConnectionEstablisher, topology_updater: TopologyUpdater, topology_id: bson::oid::ObjectId, ) -> Arc<Server> { Arc::new(Self { pool: ConnectionPool::new( address.clone(), connection_establisher, topology_updater, topology_id, Some(ConnectionPoolOptions::from_client_options(&options)), ), address, operation_count: AtomicU32::new(0), }) } pub(crate) fn increment_operation_count(&self) { self.operation_count.fetch_add(1, Ordering::SeqCst); } pub(crate) fn decrement_operation_count(&self) { self.operation_count.fetch_sub(1, Ordering::SeqCst); } pub(crate) fn operation_count(&self) -> u32 { self.operation_count.load(Ordering::SeqCst) } }
#![feature(test)] extern crate test; extern crate sat; use test::Bencher; use sat::watch::Solver; mod benches; #[bench] fn bench_sat(b: &mut Bencher) { b.iter(|| benches::bench_sat::<Solver>()) } #[bench] fn bench_unsat(b: &mut Bencher) { b.iter(|| benches::bench_unsat::<Solver>()) }
pub use self::arch::*; pub use self::unix::*; pub use self::redox::*; // Unix compatible pub mod unix; // Redox special pub mod redox; #[cfg(target_arch = "x86")] #[path="x86.rs"] pub mod arch; #[cfg(target_arch = "x86_64")] #[path="x86_64.rs"] pub mod arch;
#![feature(proc_macro_hygiene)] extern crate wasm_bindgen_test; extern crate web_sys; use std::cell::Cell; use std::rc::Rc; use wasm_bindgen::JsCast; use wasm_bindgen_test::*; use web_sys::{Element, Event, EventTarget, MouseEvent}; use virtual_dom_rs::prelude::*; wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] fn nested_divs() { let vdiv = html! { <div> <div> <div></div> </div> </div> }; let div: Element = vdiv.create_dom_node().node.unchecked_into(); assert_eq!(&div.inner_html(), "<div><div></div></div>"); } #[wasm_bindgen_test] fn div_with_attributes() { let vdiv = html! { <div id="id-here" class="two classes"></div> }; let div: Element = vdiv.create_dom_node().node.unchecked_into(); assert_eq!(&div.id(), "id-here"); assert!(div.class_list().contains("two"));; assert!(div.class_list().contains("classes"));; assert_eq!(div.class_list().length(), 2); } #[wasm_bindgen_test] fn click_event() { let clicked = Rc::new(Cell::new(false)); let clicked_clone = Rc::clone(&clicked); let div = html! { <div onclick=move |_ev: MouseEvent| { clicked_clone.set(true); } > </div> }; let click_event = Event::new("click").unwrap(); let div = div.create_dom_node().node; (EventTarget::from(div)) .dispatch_event(&click_event) .unwrap(); assert_eq!(*clicked, Cell::new(true)); }
use std::slice; use std::mem; pub unsafe trait Primitive {} unsafe impl Primitive for i8 {} unsafe impl Primitive for u8 {} unsafe impl Primitive for i16 {} unsafe impl Primitive for u16 {} unsafe impl Primitive for i32 {} unsafe impl Primitive for u32 {} unsafe impl Primitive for i64 {} unsafe impl Primitive for u64 {} unsafe impl Primitive for f32 {} unsafe impl Primitive for f64 {} #[inline(always)] pub fn as_bytes< T: Primitive >( slice: &[T] ) -> &[u8] { unsafe { slice::from_raw_parts( slice.as_ptr() as *const u8, slice.len() * mem::size_of::< T >() ) } } #[inline(always)] pub fn as_bytes_mut< T: Primitive >( slice: &mut [T] ) -> &mut [u8] { unsafe { slice::from_raw_parts_mut( slice.as_mut_ptr() as *mut u8, slice.len() * mem::size_of::< T >() ) } }
mod async_context_test; mod corpus_test; mod github_issue_test; mod helpers; mod highlight_test; mod language_test; mod node_test; mod parser_hang_test; mod parser_test; mod pathological_test; mod query_test; mod tags_test; mod test_highlight_test; mod test_tags_test; mod text_provider_test; mod tree_test;
use std::env; use std::path::PathBuf; use std::process::Command; fn main() { let chip_name = env::vars_os() .map(|(a, _)| a.to_string_lossy().to_string()) .find(|x| x.starts_with("CARGO_FEATURE_STM32")) .expect("No stm32xx Cargo feature enabled") .strip_prefix("CARGO_FEATURE_") .unwrap() .to_ascii_uppercase(); let out_dir = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); let out_file = out_dir.join("generated.rs").to_string_lossy().to_string(); let exit_code = Command::new("python3") .args(&["gen.py", &chip_name, &out_file]) .status() .expect("failed to execute gen.py"); if !exit_code.success() { panic!("gen.py exited with {:?}", exit_code) } stm32_metapac::peripheral_versions!( ($peri:ident, $version:ident) => { println!("cargo:rustc-cfg={}", stringify!($peri)); println!("cargo:rustc-cfg={}_{}", stringify!($peri), stringify!($version)); }; ); println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=gen.py"); }
use serde::Deserialize; use serde::Serialize; use serde_json::Value; #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Album { pub arrangers: Vec<Arranger>, pub barcode: Option<String>, pub catalog: String, pub categories: Vec<String>, pub category: String, pub classification: String, pub composers: Vec<Composer>, pub covers: Vec<Cover>, pub discs: Vec<Disc>, pub distributor: Option<Distributor>, pub link: Option<String>, pub lyricists: Vec<Value>, #[serde(rename = "media_format")] pub media_format: String, pub meta: Meta, pub name: String, pub names: Names, pub notes: String, pub organizations: Vec<Organization>, pub performers: Vec<Value>, #[serde(rename = "picture_full")] pub picture_full: String, #[serde(rename = "picture_small")] pub picture_small: String, #[serde(rename = "picture_thumb")] pub picture_thumb: String, pub platforms: Option<Vec<String>>, pub products: Vec<Product>, #[serde(rename = "publish_format")] pub publish_format: String, pub publisher: Publisher, pub related: Vec<Related>, #[serde(rename = "release_date")] pub release_date: String, #[serde(rename = "release_events")] pub release_events: Vec<Value>, #[serde(rename = "release_price")] pub release_price: ReleasePrice, pub reprints: Vec<Value>, #[serde(rename = "vgmdb_link")] pub vgmdb_link: String, pub votes: i64, } #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Arranger { pub link: Option<String>, pub names: Names, } #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Composer { pub link: Option<String>, pub names: Names, } #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Cover { pub full: String, pub medium: String, pub name: String, pub thumb: String, } #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Disc { #[serde(rename = "disc_length")] pub disc_length: String, pub name: String, pub tracks: Vec<Track>, } #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Track { pub names: Names, #[serde(rename = "track_length")] pub track_length: String, } #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Distributor { pub link: Option<String>, pub names: Names, pub role: String, } #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Meta { #[serde(rename = "added_date")] pub added_date: String, #[serde(rename = "edited_date")] pub edited_date: String, #[serde(rename = "fetched_date")] pub fetched_date: String, } #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Organization { pub link: Option<String>, pub names: Names, pub role: String, } #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Product { pub link: Option<String>, pub names: Names, } #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Publisher { pub link: Option<String>, pub names: Names, pub role: String, } #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Related { pub catalog: String, pub date: Option<String>, pub link: Option<String>, pub names: Names, #[serde(rename = "type")] pub type_field: String, } // Manually fixed types #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(untagged, rename_all = "camelCase")] pub enum ReleasePrice { NormalPrice(NormalPrice), SpecialPrice(SpecialPrice), #[default] None, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct NormalPrice { pub currency: String, pub price: f64, } #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SpecialPrice { pub price: String, } #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Names { #[serde(alias = "English", alias = "en", alias = "English (Revival Disc)")] pub english: Option<String>, #[serde(alias = "Japanese", alias = "jp")] pub japenese: Option<String>, #[serde(alias = "ja-latn", alias = "Romaji")] pub japenese_latin: Option<String>, #[serde(alias = "Latin")] pub latin: Option<String>, }
fn main() { let n = 15; let r = &n; println!("{} {} {}", n, *r, r); }
use proc_macro2::TokenStream; use quote::quote; use syn::{parse2, Path, Type}; fn to_path(tokens: TokenStream) -> Path { parse2(tokens).unwrap() } fn to_type(tokens: TokenStream) -> Box<Type> { parse2(tokens).unwrap() } pub fn default_data_type() -> Box<Type> { to_type(quote! { serenity_framework::DefaultData }) } pub fn default_error_type() -> Box<Type> { to_type(quote! { serenity_framework::DefaultError }) } pub fn command_type(data: &Type, error: &Type) -> Path { to_path(quote! { serenity_framework::command::Command<#data, #error> }) } pub fn command_builder_type() -> Path { to_path(quote! { serenity_framework::command::CommandBuilder }) } pub fn hook_macro() -> Path { to_path(quote! { serenity_framework::prelude::hook }) } pub fn argument_segments_type() -> Path { to_path(quote! { serenity_framework::utils::ArgumentSegments }) } pub fn required_argument_from_str_func() -> Path { to_path(quote! { serenity_framework::argument::required_argument_from_str }) } pub fn required_argument_parse_func() -> Path { to_path(quote! { serenity_framework::argument::required_argument_parse }) } pub fn optional_argument_from_str_func() -> Path { to_path(quote! { serenity_framework::argument::optional_argument_from_str }) } pub fn optional_argument_parse_func() -> Path { to_path(quote! { serenity_framework::argument::optional_argument_parse }) } pub fn variadic_arguments_from_str_func() -> Path { to_path(quote! { serenity_framework::argument::variadic_arguments_from_str }) } pub fn variadic_arguments_parse_func() -> Path { to_path(quote! { serenity_framework::argument::variadic_arguments_parse }) } pub fn rest_argument_from_str_func() -> Path { to_path(quote! { serenity_framework::argument::rest_argument_from_str }) } pub fn rest_argument_parse_func() -> Path { to_path(quote! { serenity_framework::argument::rest_argument_parse }) } pub fn check_type(data: &Type, error: &Type) -> Path { to_path(quote! { serenity_framework::check::Check<#data, #error> }) } pub fn check_builder_type() -> Path { to_path(quote! { serenity_framework::check::CheckBuilder }) }
//uferdig //06.08 - Push pga -> Debian struct Graph{ v:u32, adj: Vec<Node>, } struct Node{ data:u32, link:Vec<u32> } impl Node{ fn new(d:u32) -> Node{ Node{ data:d, link:Vec::new() } } } impl Graph{ fn new(_V:u32)-> Graph{ println!("{}",_V); let mut nodes:Vec<Node> = Vec::with_capacity(_V as usize); for i in 0.._V { nodes.push(Node::new(i as u32)); println!("{}",i); } Graph{ v:_V, adj: nodes } } fn add_edge(&mut self,from:u32,to:u32){ println!("Added edge: {}-{}",from,&to); self.adj[from as usize].link.push(to); } fn topo_rec(&mut self,v:u32,vis: &mut Vec<bool>,stakk:&mut Vec<u32>) { vis[v as usize] = true; let mut temp = &self.adj[v as usize].link; for x in &temp{ if !vis[*x as usize]{ self.topo_rec(v,vis,stakk); } } stakk.push(v); } } fn main(){ let mut graf = Graph::new(6); Graph::add_edge(&mut graf,5,2); Graph::add_edge(&mut graf,5,0); Graph::add_edge(&mut graf,4,0); Graph::add_edge(&mut graf,4,1); Graph::add_edge(&mut graf,3,1); }
extern crate byteorder; use std; use std::io::Write; use self::byteorder::NativeEndian; use self::byteorder::WriteBytesExt; /// Represents a value in the scalar set. /// The values must be able to store booking information /// for managing the contents of the set. These requirements /// are captured in this trait. pub trait Value { /// Gets the index of the bucket for this value. fn get_bucket_index( &self, buckets: &Self ) -> usize; /// Gets a zero. fn zero() -> Self; /// Gets the integer value as a size. fn as_index( &self ) -> usize; /// Converts the number of buckets into the value type. fn from_bucket_count( bucket_count: &usize ) -> Self; /// Converts the number of set members into the value type. fn from_member_count( member_count: usize ) -> Self; /// Converts the given index into the value type. fn from_index( index: usize ) -> Self; /// Decrements the value by one. fn decrement( &self ) -> Self; /// Serializes the value. fn serialize( &self, &mut Write ) -> Result<(), std::io::Error>; } /// Implements Value trait for i32 impl Value for i32 { /// Gets the index of the bucket for this value. fn get_bucket_index( &self, buckets: &i32 ) -> usize { return ( self.clone() as usize ) % ( buckets.clone() as usize ) ; } /// Gets a zero. fn zero() -> i32 { return 0; } /// Gets the integer value as a size. fn as_index( &self ) -> usize { return self.clone() as usize; } /// Converts the specified value to a value that can be stored in the container. fn from_bucket_count( bucket_count: &usize ) -> i32 { return bucket_count.clone() as i32; } /// Converts the number of set members into the value type. fn from_member_count( member_count: usize ) -> i32 { return member_count as i32; } /// Converts the given value to index. fn from_index( index: usize ) -> i32 { return index as i32; } /// Decrements the value by one. fn decrement( &self ) -> i32 { return self - 1; } /// Serializes the value. fn serialize( &self, writer: &mut Write ) -> Result<(), std::io::Error> { writer.write_i32::<NativeEndian>( *self )?; Ok(()) } } /// The index of the number of members in the set. const SIZE_INDEX: usize = 1; /// The index of the first bucket. const FIRST_BUCKET_INDEX: usize = 2; /// Defines how the data is stored in the scalar set. enum Storage<'a, TA, TB> where TB: 'a { /// The data is stored as a vector. Vector { data: Vec<TA> }, /// The data is stored as a slice. Slice { data: &'a[TB] } } /// Scalar set cabable of storing values with Value trait. pub struct RoScalarSet<'a, T> where T: std::cmp::Ord + std::clone::Clone + Value + 'a { _storage: Storage<'a, T, T> } impl<'a, T> RoScalarSet<'a, T> where T: std::cmp::Ord + std::clone::Clone + Value + 'a { /// Returns a new integer hash set holding the specified values. /// /// # ArgumentRoScalarSets /// /// * 'values' Holds the values stored in the hash set. pub fn new<'b, 'c> ( values: &'c[T] ) -> RoScalarSet<'b,T> { // Determine the number of buckets. We introduce a 5% overhead. let bucket_count: usize = ( values.len() as f64 * 0.05 ).ceil() as usize; let mut storage: Vec<T> = vec!( T::zero(); ( FIRST_BUCKET_INDEX + bucket_count + 1 + values.len() ) ); // Store the number of buckets. let buckets = T::from_bucket_count( &bucket_count ); storage[ 0 ] = buckets.clone(); // Store the number of members. storage[ SIZE_INDEX ] = T::from_member_count( values.len() ); // Count the values required for each bucket. let mut values_in_buckets: Vec<i32> = vec!( 0; bucket_count ); for v in values { let bucket = v.get_bucket_index( &buckets ); values_in_buckets[ bucket ] += 1; } // Set bucket pointers to point the end of each bucket. // They will be decrements one-by-one when the buckets are filled. let first_bucket: usize = FIRST_BUCKET_INDEX; let data_start: usize = FIRST_BUCKET_INDEX + bucket_count + 1; let mut previous_bucket_end = data_start; for b in 0..bucket_count { // The end of the previous bucket is the start of the previous bucket. let index = previous_bucket_end + values_in_buckets[ b ].as_index(); storage[ b + first_bucket ] = T::from_index( index ); previous_bucket_end = index; } // Fix the end of the last bucket. storage[ first_bucket + bucket_count ] = T::from_index( storage.len() ); // Put values into buckets. for v in values { // Determine bucket for the value. let bucket_id = v.get_bucket_index( &buckets ); // Make room for the new value. storage[ bucket_id + first_bucket ] = storage[ bucket_id + first_bucket ].decrement(); let value_index: usize = storage[ bucket_id + first_bucket ].as_index(); storage[ value_index ] = v.clone(); } // Sort each bucket to enable binary search. for b in 0..bucket_count { // Determine the location of the bucket. let begin: usize = storage[ b + first_bucket ].as_index(); let end: usize = storage[ b + first_bucket + 1 ].as_index(); if end < begin { panic!( "Invalid bucket: {}", b ); } // Get a splice for sorting. let ( _, remainder ) = storage.split_at_mut( begin ); let ( bucket, _ ) = remainder.split_at_mut( end - begin ); bucket.sort(); } let storage: Storage<'b, T, T> = Storage::Vector { data: storage }; return RoScalarSet { _storage: storage }; } /// Attaches an integer hash set to a slice holding the values. /// /// # ArgumentRoScalarSets /// /// * 'values' Holds the values stored in the hash set. pub fn attach<'b> ( buffer: &'b[T] ) -> Result< ( RoScalarSet<'b, T>, &'b[T] ), &str > { // Determine the length of this scalar set. if buffer.len() < 4 { return Err( "The buffer is to small" ); } let buckets = buffer[0].as_index(); let values = buffer[SIZE_INDEX].as_index(); let total_size = FIRST_BUCKET_INDEX + ( buckets + 1 ) + values; // Attach. let ( set, remainder ) = buffer.split_at( total_size ); let storage: Storage<T, T> = Storage::Slice { data: set }; return Ok( ( RoScalarSet { _storage: storage }, remainder ) ); } /// Checks whether the given value exists in the set or not. pub fn contains( &self, value: T ) -> bool { // Get the bucket associated with the value. let bucket = self.get_bucket( &value ); // Locate the value. match bucket.binary_search( &value ) { Ok( _ ) => return true, Err(_) => return false, } } /// Gets the number of members in the set. pub fn size( &self ) -> usize { let storage = self.borrow_storage(); return storage[ SIZE_INDEX ].as_index(); } /// Gets the number of buckets. pub fn bucket_count( &self ) -> usize { let storage = self.borrow_storage(); return storage[ 0 ].as_index(); } /// Serializes the scalar set into the given writer. pub fn serialize<W>( &self, writer: &mut W ) -> Result<(), std::io::Error> where W: Write { // Write our intern let storage = self.borrow_storage(); for v in storage { v.serialize( writer )?; } Ok(()) } /// Gets a read-only slice containing the values of a bucket. fn get_bucket( &self, value: &T ) -> &[T] { // Determine the bucket. let storage = self.borrow_storage(); let bucket_id: usize = value.get_bucket_index( &storage[ 0 ] ); let bucket_index = bucket_id + FIRST_BUCKET_INDEX; let begin: usize = storage[ bucket_index ].as_index(); let end: usize = storage[ ( bucket_index + 1 ) ].as_index(); let ( _, remainder ) = storage.split_at( begin ); let ( bucket, _ ) = remainder.split_at( end - begin ); return bucket; } /// Borrows the storage for accessing the values. fn borrow_storage( &'a self ) -> &'a [T] { let s: &'a [T] = match &self._storage { &Storage::Vector { ref data } => data.as_slice(), &Storage::Slice { ref data } => data, }; return s; } }
mod find_usages; pub use self::find_usages::{ definitions_and_references, definitions_and_references_lines, find_occurrence_matches_by_ext, get_comments_by_ext, get_language_by_ext, DefinitionRules, MatchKind, };
#[cfg(test)] use std::time::Duration; #[cfg(test)] use chrono::prelude::*; #[cfg(test)] use time::get_start_delay_from_next; #[test] fn test_start_delay_next_hour_16_45_hour15() { let cur_time = Local .datetime_from_str("2019-09-02T16:45:00", "%Y-%m-%dT%H:%M:%S") .unwrap(); match get_start_delay_from_next(cur_time, "hour+15") { Ok(delay) => assert_eq!(delay, Duration::from_secs(1800)), Err(e) => panic!(e), } } #[test] fn test_start_delay_next_hour_22_45_hour15() { let cur_time = Local .datetime_from_str("2019-09-02T22:45:00", "%Y-%m-%dT%H:%M:%S") .unwrap(); match get_start_delay_from_next(cur_time, "hour+15") { Ok(delay) => assert_eq!(delay, Duration::from_secs(1800)), Err(e) => panic!(e), } } #[test] fn test_start_delay_next_hour_23_01_hour() { let cur_time = Local .datetime_from_str("2019-09-02T23:01:00", "%Y-%m-%dT%H:%M:%S") .unwrap(); match get_start_delay_from_next(cur_time, "hour") { Ok(delay) => assert_eq!(delay, Duration::from_secs(3540)), Err(e) => panic!(e), } } #[test] fn test_start_delay_next_hour_23_45_hour20() { let cur_time = Local .datetime_from_str("2019-09-02T23:45:00", "%Y-%m-%dT%H:%M:%S") .unwrap(); match get_start_delay_from_next(cur_time, "hour+20") { Ok(delay) => assert_eq!(delay, Duration::from_secs(2100)), Err(e) => panic!(e), } } #[test] fn test_start_delay_next_hour_23_45_hour() { let cur_time = Local .datetime_from_str("2019-09-02T23:45:00", "%Y-%m-%dT%H:%M:%S") .unwrap(); match get_start_delay_from_next(cur_time, "hour") { Ok(delay) => assert_eq!(delay, Duration::from_secs(900)), Err(e) => panic!(e), } }
use core::fmt::{self, Debug, Formatter}; use binread::{BinRead, BinReaderExt}; use modular_bitfield::prelude::*; use crate::axis::*; /// Type of controller connected (Disconnected, Normal, or Wavebird) #[derive(BitfieldSpecifier, Debug)] pub enum ControllerType { Disconnected = 0, Normal = 1, Wavebird = 2, Invalid = 3, } impl Default for ControllerType { fn default() -> Self { Self::Disconnected } } /// Status of controller for the given port #[bitfield] #[derive(BinRead, Debug, Default, Copy, Clone, PartialEq)] #[br(map = Self::from_bytes)] pub struct ControllerStatus { pub unk: bool, pub unk2: bool, pub has_rumble: bool, pub unk3: bool, pub controller_type: ControllerType, padding: B2 } /// A collection of which buttons are pressed /// /// **Note:** `right_trigger` and `left_trigger` refer to the buttons (i.e. the click when you hold /// them all the way down). For the analog part of the triggers, see /// [`Controller::triggers`](Controller::triggers). #[bitfield] #[derive(BinRead, Debug, Default)] #[br(map = Self::from_bytes)] pub struct Buttons { pub a: bool, pub b: bool, pub x: bool, pub y: bool, pub dpad_left: bool, pub dpad_right: bool, pub dpad_down: bool, pub dpad_up: bool, pub start: bool, pub z: bool, pub right_trigger: bool, pub left_trigger: bool, pub padding: B4, } /// An analog control stick. Can represent either the left or right stick. #[derive(BinRead, Debug, Default)] pub struct Stick { pub x: SignedAxis, pub y: SignedAxis, } impl Stick { /// Gets the raw stick values, where ~127.5 is center. pub fn raw(&self) -> (u8, u8) { (self.x.raw(), self.y.raw()) } /// Gets the stick position as a normalized 2d vector. For higher accuracy, use /// [`coords_centered`](Stick::coords_centered) as it allows you to specifiy the pub fn coords(&self) -> (f32, f32) { (self.x.float(), self.y.float()) } /// Gets the stick position as a normalized 2d vector. The provided center should be obtained /// using the [`raw`](Stick::raw) method. pub fn coords_centered(&self, center: (u8, u8)) -> (f32, f32) { (self.x.float_centered(center.0), self.y.float_centered(center.1)) } } /// The two analog triggers. For the digital portion, see [`Buttons::right_trigger`] and /// [`Buttons::left_trigger`]. #[derive(BinRead, Debug, Default)] pub struct Triggers { pub left: UnsignedAxis, pub right: UnsignedAxis, } /// A controller port: either disconnected or otherwise. #[derive(BinRead, Default)] pub struct Controller { pub status: ControllerStatus, pub buttons: Buttons, pub left_stick: Stick, pub right_stick: Stick, pub triggers: Triggers, } impl Controller { /// Check if the given controller is connected pub fn connected(&self) -> bool { match self.status.controller_type() { ControllerType::Normal | ControllerType::Wavebird => true, ControllerType::Disconnected | ControllerType::Invalid => false, } } } impl Debug for Controller { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.connected() { f.debug_struct("Controller") .field("status", &self.status) .field("buttons", &self.buttons) .field("left_stick", &self.left_stick) .field("right_stick", &self.right_stick) .field("triggers", &self.triggers) .finish() } else { f.write_str("Controller(Disconnected)") } } } /// A Gamecube Controller adapter USB payload #[derive(BinRead, Debug)] pub enum Packet { #[br(magic = 0x21u8)] ControllerInfo { ports: [Controller; 4], }, Unknown(u8), } impl Packet { /// Parse a packet from a 37 byte buffer pub fn parse(buffer: [u8; 37]) -> Self { let mut reader = binread::io::Cursor::new(&buffer[..]); let packet: Packet = reader.read_ne().unwrap(); packet } }
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 extern crate alloc; pub mod raw; #[cfg(any(feature = "testing", test))] pub mod testing;
#[doc = "Register `EGR` writer"] pub type W = crate::W<EGR_SPEC>; #[doc = "Field `UG` writer - Update generation This bit can be set by software, it is automatically cleared by hardware."] pub type UG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CC1G` writer - Capture/Compare 1 generation This bit is set by software in order to generate an event, it is automatically cleared by hardware. If channel CC1 is configured as output: CC1IF flag is set, Corresponding interrupt or DMA request is sent if enabled. If channel CC1 is configured as input: The current value of the counter is captured in TIMx_CCR1 register. The CC1IF flag is set, the corresponding interrupt or DMA request is sent if enabled. The CC1OF flag is set if the CC1IF flag was already high."] pub type CC1G_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `COMG` writer - Capture/Compare control update generation This bit can be set by software, it is automatically cleared by hardware. Note: This bit acts only on channels that have a complementary output."] pub type COMG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BG` writer - Break generation This bit is set by software in order to generate an event, it is automatically cleared by hardware."] pub type BG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl W { #[doc = "Bit 0 - Update generation This bit can be set by software, it is automatically cleared by hardware."] #[inline(always)] #[must_use] pub fn ug(&mut self) -> UG_W<EGR_SPEC, 0> { UG_W::new(self) } #[doc = "Bit 1 - Capture/Compare 1 generation This bit is set by software in order to generate an event, it is automatically cleared by hardware. If channel CC1 is configured as output: CC1IF flag is set, Corresponding interrupt or DMA request is sent if enabled. If channel CC1 is configured as input: The current value of the counter is captured in TIMx_CCR1 register. The CC1IF flag is set, the corresponding interrupt or DMA request is sent if enabled. The CC1OF flag is set if the CC1IF flag was already high."] #[inline(always)] #[must_use] pub fn cc1g(&mut self) -> CC1G_W<EGR_SPEC, 1> { CC1G_W::new(self) } #[doc = "Bit 5 - Capture/Compare control update generation This bit can be set by software, it is automatically cleared by hardware. Note: This bit acts only on channels that have a complementary output."] #[inline(always)] #[must_use] pub fn comg(&mut self) -> COMG_W<EGR_SPEC, 5> { COMG_W::new(self) } #[doc = "Bit 7 - Break generation This bit is set by software in order to generate an event, it is automatically cleared by hardware."] #[inline(always)] #[must_use] pub fn bg(&mut self) -> BG_W<EGR_SPEC, 7> { BG_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { self.bits = bits; self } } #[doc = "TIM16 event generation register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`egr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct EGR_SPEC; impl crate::RegisterSpec for EGR_SPEC { type Ux = u16; } #[doc = "`write(|w| ..)` method takes [`egr::W`](W) writer structure"] impl crate::Writable for EGR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets EGR to value 0"] impl crate::Resettable for EGR_SPEC { const RESET_VALUE: Self::Ux = 0; }
//! blcic /// Isolate lowest clear bit pub trait Blcic { /// Sets the least significant bit of `self` and clears all other bits.w /// /// If there is no zero bit in `self`, it returns zero. /// /// # Intrinsic (when available TBM) /// /// - [`BLCIC`](http://support.amd.com/TechDocs/24594.pdf): /// - Description: Isolate lowest clear bit. /// - Architecture: x86. /// - Instruction set: TBM. /// - Registers: 32/64 bit. /// /// # Example /// /// ``` /// # use bitintr::*; /// assert_eq!(0b0101_0001u8.blcic(), 0b0000_0010u8); /// assert_eq!(0b1111_1111u8.blcic(), 0b0000_0000u8); /// ``` fn blcic(self) -> Self; } macro_rules! impl_blcic { ($id:ident) => { impl Blcic for $id { #[inline] fn blcic(self) -> Self { !self & (self.wrapping_add(1)) } } }; } impl_all!(impl_blcic: u8, u16, u32, u64, i8, i16, i32, i64);
// let list1 = vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]; // let list2 = vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; println!("sum: {}", list1.iter().sum()); // sum: 1 println!("sum: {}", list2.iter().sum()); // sum: 0
#[macro_use] extern crate log; extern crate pretty_env_logger; extern crate hyper; extern crate futures; extern crate trust_dns_resolver; extern crate tokio_core; extern crate regex; use regex::Regex; use trust_dns_resolver::AsyncResolver; use trust_dns_resolver::lookup::TxtLookup; use trust_dns_resolver::config::*; use futures::{future, Future}; use hyper::{Body, Response, Request, StatusCode, Server}; use hyper::header::{HOST}; use hyper::service::service_fn; use std::env; const NOTFOUND: &str = "404 Not found"; fn parse_rewrite(url: &str, parts: Vec<&str>) -> String { info!("Parsing rewrite command"); if parts.len() < 3 || parts.len() > 4 { return parts.join(" "); } let re = match Regex::new(parts[1]) { Ok(x) => x, Err(_) => return parts.join(" "), }; re.replace(url, parts[2]).into() } fn parse_return(_url: &str, parts: Vec<&str>) -> String { parts.join(" ") } fn get_return_url(url: &str, line: &str) -> String { let parts: Vec<&str> = line.split_whitespace().collect(); if parts.len() == 0 { return line.to_string(); } match parts[0] { "rewrite" => parse_rewrite(url, parts), "return" => parse_return(url, parts), _ => line.to_string() } } fn redirector_response(req: Request<Body>, client: &AsyncResolver) -> Box<Future<Item=Response<Body>, Error=hyper::Error> + Send> { let host = match req.headers().get(HOST) { None => return Box::new(futures::future::ok(Response::builder().status(StatusCode::BAD_REQUEST).body(Body::from("No Host header")).unwrap())), Some(x) => x, }; let name = format!("_redirect.{}", host.to_str().unwrap()); let failure = format!("{} => Not found", host.to_str().unwrap()); let path = req.uri().path().to_string(); Box::new(client.txt_lookup(name.clone()).map(move |txt: TxtLookup| { let line = txt.iter().next().and_then(|txts| { let mut acc = Vec::new(); for value in txts.txt_data() { acc.extend_from_slice(value); } String::from_utf8(acc).ok() }); match line { None => Response::builder().status(StatusCode::NOT_FOUND).body(Body::from(NOTFOUND)).unwrap(), Some(x) => { let newurl = get_return_url(&path, &x); info!("{} => {}", name, newurl); Response::builder().header("Location", newurl).status(StatusCode::MOVED_PERMANENTLY).body(Body::from("")).unwrap() }, } }).or_else(move |_err| { info!("{}", failure); futures::future::ok(Response::builder().status(StatusCode::NOT_FOUND).body(Body::from(NOTFOUND)).unwrap()) })) } fn main() { pretty_env_logger::init(); let addr_str = match env::var("LISTEN_ADDR") { Err(_) => { eprintln!("You must supply the LISTEN_ADDR environment variable"); return; }, Ok(x) => x, }; let addr4 = match addr_str.parse() { Err(_) => { eprintln!("Unable to parse LISTEN_ADDR "); return; }, Ok(x) => x, }; let addr6 = match env::var("LISTEN_ADDR_6") { Err(_) => None, Ok(x) => x.parse().ok(), }; hyper::rt::run(future::lazy(move || { let (client4, background) = AsyncResolver::new(ResolverConfig::default(), ResolverOpts::default()); let client6 = client4.clone(); hyper::rt::spawn(background); let service4 = move || { let client = client4.clone(); service_fn(move |req| { redirector_response(req, &client) }) }; let server4 = Server::bind(&addr4) .serve(service4) .map_err(|e| eprintln!("server error {}", e)); hyper::rt::spawn(server4); println!("Listening on http://{}", addr4); if let Some(addr6) = addr6 { let service6 = move || { let client = client6.clone(); service_fn(move |req| { redirector_response(req, &client) }) }; let server6 = Server::bind(&addr6) .serve(service6) .map_err(|e| eprintln!("server error {}", e)); hyper::rt::spawn(server6); println!("Listening on http://{}", addr6) }; Ok(()) })); }
fn main() { data_server::server().launch(); }
use std::env; use std::fs::File; use std::io::{BufReader, Read}; use std::path::Path; pub fn main() { let mut args = env::args(); let (len, _) = args.size_hint(); let prog = args.next().unwrap(); if len == 1 { println!("Usage: {} [list of files]", prog); return; } for f in args { let mut crc: u64 = 0; let file = File::open(&Path::new(&f)).unwrap(); let mut reader = BufReader::new(file); let mut error = false; loop { let mut buf = [0; 100]; match reader.read(&mut buf) { Err(e) => { error = true; print!("error reading '{}': {}", f, e); break; } Ok(0) => break, Ok(nread) => crc = crc64::crc64(crc, &buf[..nread]), } } if !error { println!("{:x} {}", crc, f); } } }
#[derive(Debug, Copy, Clone)] pub struct VoltageQ(pub f32); #[derive(Debug, Copy, Clone)] pub struct VoltageD(pub f32); #[derive(Debug, Copy, Clone)] pub struct VoltageLimit(pub f32); #[derive(Debug, Copy, Clone)] pub struct PhaseVoltage(pub f32, pub f32, pub f32); #[derive(Debug, Copy, Clone)] pub struct PhaseCurrents(pub f32, pub f32, pub f32); #[derive(Debug, Copy, Clone)] pub struct DqFrame (pub f32, pub f32); #[derive(Debug, Copy, Clone)] pub struct AlphaBetaFrame(pub f32, pub f32); #[derive(Debug, Copy, Clone)] pub struct Amperes (pub f32); #[derive(Debug, Copy, Clone)] pub struct Volts(pub f32); #[derive(Debug, Copy, Clone)] pub struct ShaftTicks(pub f32); #[derive(Debug, Copy, Clone)] pub struct RotorAngleRadians(pub f32); #[derive(Debug, Copy, Clone)] pub struct PolePairs(pub f32);
use serde::de::{Deserialize}; use serde_json; use serde_json::error::{Error}; pub fn deserialise<'de, D: Deserialize<'de>>(string: &'de str) -> Result<D, Error> { serde_json::from_str::<'de>(string) }
use std::cmp::{max, min}; use theme::ColorStyle; use vec::Vec2; use printer::Printer; /// Provide scrolling functionalities to a view. #[derive(Default)] pub struct ScrollBase { pub start_line: usize, pub content_height: usize, pub view_height: usize, pub scrollbar_padding: usize, } impl ScrollBase { pub fn new() -> Self { ScrollBase { start_line: 0, content_height: 0, view_height: 0, scrollbar_padding: 0, } } pub fn bar_padding(mut self, padding: usize) -> Self { self.scrollbar_padding = padding; self } /// Call this method whem the content or the view changes. pub fn set_heights(&mut self, view_height: usize, content_height: usize) { self.view_height = view_height; self.content_height = content_height; if self.scrollable() { self.start_line = min(self.start_line, self.content_height - self.view_height); } else { self.start_line = 0; } } /// Returns `TRUE` if the view needs to scroll. pub fn scrollable(&self) -> bool { self.view_height < self.content_height } /// Returns `TRUE` unless we are at the top. pub fn can_scroll_up(&self) -> bool { self.start_line > 0 } /// Returns `TRUE` unless we are at the bottom. pub fn can_scroll_down(&self) -> bool { self.start_line + self.view_height < self.content_height } /// Scroll to the top of the view. pub fn scroll_top(&mut self) { self.start_line = 0; } /// Makes sure that the given line is visible, scrolling if needed. pub fn scroll_to(&mut self, y: usize) { if y >= self.start_line + self.view_height { self.start_line = 1 + y - self.view_height; } else if y < self.start_line { self.start_line = y; } } /// Scroll to the bottom of the view. pub fn scroll_bottom(&mut self) { self.start_line = self.content_height - self.view_height; } /// Scroll down by the given number of line, never going further than the bottom of the view. pub fn scroll_down(&mut self, n: usize) { self.start_line = min(self.start_line + n, self.content_height - self.view_height); } /// Scroll up by the given number of lines, never going above the top of the view. pub fn scroll_up(&mut self, n: usize) { self.start_line -= min(self.start_line, n); } /// Draws the scroll bar and the content using the given drawer. /// /// `line_drawer` will be called once for each line that needs to be drawn. /// It will be given the absolute ID of the item to draw.. /// It will also be given a printer with the correct offset, /// so it should only print on the first line. /// /// # Examples /// /// ``` /// # use cursive::view::ScrollBase; /// # use cursive::printer::Printer; /// # use cursive::theme; /// # let scrollbase = ScrollBase::new(); /// # let printer = Printer::new((5,1), theme::load_default()); /// # let printer = &printer; /// let lines = ["Line 1", "Line number 2"]; /// scrollbase.draw(printer, |printer, i| { /// printer.print((0,0), lines[i]); /// }); /// ``` pub fn draw<F>(&self, printer: &Printer, line_drawer: F) where F: Fn(&Printer, usize) { // Print the content in a sub_printer let max_y = min(self.view_height, self.content_height - self.start_line); let w = if self.scrollable() { printer.size.x - 1 // TODO: 2 } else { printer.size.x }; for y in 0..max_y { // Y is the actual coordinate of the line. // The item ID is then Y + self.start_line line_drawer(&printer.sub_printer(Vec2::new(0, y), Vec2::new(w, 1), true), y + self.start_line); } // And draw the scrollbar if needed if self.view_height < self.content_height { // We directly compute the size of the scrollbar (this allow use to avoid using floats). // (ratio) * max_height // Where ratio is ({start or end} / content.height) let height = max(1, self.view_height * self.view_height / self.content_height); // Number of different possible positions let steps = self.view_height - height + 1; // Now let start = steps * self.start_line / (1 + self.content_height - self.view_height); let color = if printer.focused { ColorStyle::Highlight } else { ColorStyle::HighlightInactive }; // TODO: use 1 instead of 2 let scrollbar_x = printer.size.x - 1 - self.scrollbar_padding; printer.print_vline((scrollbar_x, 0), printer.size.y, "|"); printer.with_color(color, |printer| { printer.print_vline((scrollbar_x, start), height, " "); }); } } }
pub fn min_patches(nums: Vec<i32>, n: i32) -> i32 { let mut counter = 0; let mut current_max = 0; let mut j = 0; while current_max < n as i64 { if j < nums.len() && nums[j] as i64 <= current_max + 1 { current_max += nums[j] as i64; j += 1; } else { counter += 1; current_max = current_max * 2 + 1; } } counter as i32 }
#[macro_use] pub(crate) mod feature_cfg;
use crate::app::{App, CommandRunner}; use crate::config::AppFont; use crate::config::Config; use crate::input::{Cmd, Command, Input, InputState, KeyInput}; use crate::line_cache::{count_utf16, Annotation, Line, LineCache, Style}; use crate::popup::Popup; use crate::rpc::Core; use cairo::{FontFace, FontOptions, FontSlant, FontWeight, Matrix, ScaledFont}; use druid::shell::keyboard::{KeyCode, KeyEvent, KeyModifiers}; use druid::shell::platform::IdleHandle; use druid::shell::window::{MouseEvent, WinCtx, WinHandler, WindowHandle}; use druid::shell::{kurbo, piet, runloop, WindowBuilder}; use druid::{PaintCtx, TimerToken}; use kurbo::{Affine, Point, Rect, Size, Vec2}; use piet::{ Color, FontBuilder, LinearGradient, Piet, RenderContext, Text, TextLayout, TextLayoutBuilder, UnitPoint, }; use serde_json::{json, Value}; use std::collections::HashMap; use std::sync::{Arc, Mutex, Weak}; use std::thread; use uuid::Uuid; use xi_core_lib::word_boundaries::{get_word_property, WordProperty}; pub enum EditViewCommands { ViewId(String), ApplyUpdate(Value), ScrollTo(usize), Core(Weak<Mutex<Core>>), Undo, Redo, UpperCase, LowerCase, Transpose, AddCursorAbove, AddCursorBelow, SingleSelection, SelectAll, } struct EditorState { view: Option<View>, input: Input, gutter_padding: f64, col: usize, line: usize, } #[derive(WidgetBase, Clone)] pub struct Editor { widget_state: Arc<Mutex<WidgetState>>, state: Arc<Mutex<EditorState>>, app: App, } impl Editor { pub fn new(app: App) -> Editor { Editor { widget_state: Arc::new(Mutex::new(WidgetState::new())), state: Arc::new(Mutex::new(EditorState { view: None, input: Input::new(), gutter_padding: 10.0, col: 0, line: 0, })), app, } } pub fn load_view(&self, view: View) { self.state.lock().unwrap().view = Some(view); } pub fn view(&self) -> View { self.state.lock().unwrap().view.clone().unwrap() } pub fn line(&self) -> usize { self.state.lock().unwrap().line } pub fn col(&self) -> usize { self.state.lock().unwrap().col } pub fn get_completion_pos(&self) -> (usize, usize, String) { let view = self.state.lock().unwrap().view.clone(); match view { Some(view) => { match view.line_cache.lock().unwrap().get_line(self.line()) { Some(line) => { let col = self.col(); let chars: Vec<char> = line.text()[..col].to_string().chars().collect(); if chars.len() == 0 { (0, 0, "".to_string()) } else { let mut i = chars.len() - 1; while let Some(ch) = chars.get(i) { if get_word_property(ch.clone()) != WordProperty::Other { break; } if i == 0 { break; } i -= 1; } ( i + 1, self.line(), line.text()[i + 1..self.col()].to_string(), ) } } None => (0, 0, "".to_string()), } } None => (0, 0, "".to_string()), } } fn get_view_width(&self) -> f64 { let view = self.state.lock().unwrap().view.clone(); match view { Some(view) => view.state.lock().unwrap().width, None => 0.0, } } fn get_view_height(&self) -> f64 { let view = self.state.lock().unwrap().view.clone(); match view { Some(view) => view.state.lock().unwrap().height, None => 0.0, } } fn gutter_len(&self) -> usize { let view = self.state.lock().unwrap().view.clone(); match view { Some(view) => { format!("{}", view.line_cache.lock().unwrap().height()).len() } None => 0, } } fn gutter_width(&self) -> f64 { let app_font = self.app.config.font.lock().unwrap().width; let gutter_padding = self.state.lock().unwrap().gutter_padding; 2.0 * gutter_padding + app_font * self.gutter_len() as f64 } pub fn move_popup(&self) { let popup = self .app .state .lock() .unwrap() .popup .clone() .unwrap() .clone(); let rect = self.get_rect(); let col = popup.col(); let line = popup.line(); let horizontal_scroll = self.horizontal_scroll(); let vertical_scroll = self.vertical_scroll(); let gutter_width = self.gutter_width(); let app_font = self.app.config.font.lock().unwrap().clone(); let x = rect.x0 + gutter_width + col as f64 * app_font.width - horizontal_scroll; let y = rect.y0 + (line + 1) as f64 * app_font.lineheight() - vertical_scroll; popup.set_pos(x, y); } fn layout(&self) {} fn paint(&self, paint_ctx: &mut PaintCtx) { let view = self.state.lock().unwrap().view.clone(); if view.is_none() { return; } let current_line = self.state.lock().unwrap().line; let is_active = self.app.state.lock().unwrap().active_editor.clone() == self.id(); let bg = self.app.config.theme.lock().unwrap().background.unwrap(); let rect = Rect::from_origin_size( Point::ORIGIN, self.widget_state.lock().unwrap().size(), ); paint_ctx.fill(rect, &Color::rgba8(bg.r, bg.g, bg.b, bg.a)); let line_cache = self .state .lock() .unwrap() .view .as_ref() .unwrap() .line_cache .clone(); let horizontal_scroll = self.widget_state.lock().unwrap().horizontal_scroll(); let vertical_scroll = self.widget_state.lock().unwrap().vertical_scroll(); let width = self.widget_state.lock().unwrap().size().width; let height = self.widget_state.lock().unwrap().size().height; let lineheight = self.app.config.font.lock().unwrap().lineheight(); let start = (vertical_scroll / lineheight) as usize; let line_count = (height / lineheight) as usize + 2; let total_lines = line_cache.lock().unwrap().height(); let end = if start + line_count > total_lines { total_lines } else { start + line_count }; let gutter_width = self.paint_gutter(paint_ctx, start, end); self.paint_scroll(paint_ctx); paint_ctx.save(); paint_ctx.clip(Rect::from_origin_size( Point::new(gutter_width, 0.0), Size::new(width - gutter_width, height), )); paint_ctx.transform(Affine::translate(Vec2::new( -horizontal_scroll + gutter_width, -vertical_scroll, ))); let annotations = line_cache.lock().unwrap().annotations(); for i in start..end { if let Some(line) = line_cache.lock().unwrap().get_line(i).clone() { self.paint_line( i, paint_ctx, line, &annotations, current_line == i, is_active, ); } } paint_ctx.restore(); } fn paint_gutter( &self, paint_ctx: &mut PaintCtx, start: usize, end: usize, ) -> f64 { let vertical_scroll = self.widget_state.lock().unwrap().vertical_scroll(); let app_font = self.app.config.font.lock().unwrap(); let fg = self.app.config.theme.lock().unwrap().foreground.unwrap(); let fg_color = Color::rgba8(fg.r, fg.g, fg.b, 100); let gutter_len = self.gutter_len(); let gutter_padding = self.state.lock().unwrap().gutter_padding; let font = paint_ctx .text() .new_font_by_name("Cascadia Code", 13.0) .unwrap() .build() .unwrap(); for i in start..end { let text = format!("{}", i); let layout = paint_ctx .text() .new_text_layout(&font, &format!("{}", i)) .unwrap() .build() .unwrap(); let x = gutter_padding + app_font.width * (if gutter_len >= text.len() { gutter_len - text.len() } else { 0 }) as f64; paint_ctx.draw_text( &layout, Point::new( x, app_font.lineheight() * i as f64 + app_font.ascent + app_font.linespace / 2.0 - vertical_scroll, ), &fg_color, ); } 2.0 * gutter_padding + app_font.width * gutter_len as f64 } fn paint_line( &self, i: usize, paint_ctx: &mut PaintCtx, line: &Line, annotations: &Vec<Annotation>, is_current: bool, is_active: bool, ) { let mut text = line.text().to_string(); // text.pop(); let text_len = count_utf16(&text); let app_font = self.app.config.font.lock().unwrap(); let fg = self.app.config.theme.lock().unwrap().foreground.unwrap(); let input_state = self.state.lock().unwrap().input.state.clone(); let visual_line = self.state.lock().unwrap().input.visual_line.clone(); let width = self.widget_state.lock().unwrap().size().width; let view_width = self.get_view_width(); for annotation in annotations { if let Some((start, end)) = annotation.check_line(i, line) { if input_state == InputState::Visual { let point = if visual_line { Point::new(0.0, app_font.lineheight() * i as f64) } else { Point::new( app_font.width * start as f64, app_font.lineheight() * i as f64, ) }; let size = if visual_line { Size::new( app_font.width * text_len as f64, app_font.lineheight(), ) } else { Size::new( app_font.width * (end - start + 1) as f64, app_font.lineheight(), ) }; let rect = Rect::from_origin_size(point, size); let selection_color = Color::rgba8(fg.r, fg.g, fg.b, 50); paint_ctx.fill(rect, &selection_color); } } } if input_state != InputState::Visual && is_current { let point = Point::new(0.0, app_font.lineheight() * i as f64); let size = Size::new( if view_width > width { view_width } else { width }, app_font.lineheight(), ); let rect = Rect::from_origin_size(point, size); let current_line_color = Color::rgba8(fg.r, fg.g, fg.b, 20); paint_ctx.fill(rect, &current_line_color); } if is_active { let cursor_color = Color::rgba8(fg.r, fg.g, fg.b, 160); for cursor in line.cursor() { let point = Point::new( match input_state { InputState::Insert => { if *cursor == 0 { 0.0 } else { app_font.width * *cursor as f64 - 1.0 } } _ => app_font.width * *cursor as f64, }, app_font.lineheight() * i as f64, ); let rect = Rect::from_origin_size( point, Size::new( match input_state { InputState::Insert => 2.0, _ => app_font.width, }, app_font.lineheight(), ), ); paint_ctx.fill(rect, &cursor_color); } } let font = paint_ctx .text() .new_font_by_name("Cascadia Code", 13.0) .unwrap() .build() .unwrap(); for style in line.styles() { let range = &style.range; let mut end = range.end; if end == text_len { if &text[end - 1..end] == "\n" { end -= 1; } } let layout = paint_ctx .text() .new_text_layout(&font, &text[range.start..end]) .unwrap() .build() .unwrap(); let x = paint_ctx .text() .new_text_layout(&font, &text[..range.start]) .unwrap() .build() .unwrap() .width(); if let Some(style) = self.app.config.styles.lock().unwrap().get(&style.style_id) { if let Some(fg_color) = style.fg_color { paint_ctx.draw_text( &layout, Point::new( x, app_font.lineheight() * i as f64 + app_font.ascent + app_font.linespace / 2.0, ), &Color::from_rgba32_u32(fg_color), ); } } } } fn paint_scroll(&self, paint_ctx: &mut PaintCtx) { let gutter_width = self.gutter_width(); let scroll_thickness = 9.0; let view_width = self.get_view_width(); let view_height = self.get_view_height(); let fg = self.app.config.theme.lock().unwrap().foreground.unwrap(); let color = Color::rgba8(fg.r, fg.g, fg.b, 40); let size = self.widget_state.lock().unwrap().size(); let width = size.width - gutter_width; let height = size.height; let horizontal_scroll = self.widget_state.lock().unwrap().horizontal_scroll(); let vertical_scroll = self.widget_state.lock().unwrap().vertical_scroll(); if view_width > width { let point = Point::new( gutter_width + horizontal_scroll / view_width * width, height - scroll_thickness, ); let rect = Rect::from_origin_size( point, Size::new(width / view_width * width, scroll_thickness), ); paint_ctx.fill(rect, &color); } if view_height > height { let point = Point::new( width + gutter_width - scroll_thickness, vertical_scroll / view_height * height, ); let rect = Rect::from_origin_size( point, Size::new(scroll_thickness, height / view_height * height), ); paint_ctx.fill(rect, &color); } } fn mouse_down(&self, event: &MouseEvent, ctx: &mut dyn WinCtx) { let gutter_width = self.gutter_width(); self.app.set_active_editor(&self); if self.state.lock().unwrap().view.is_none() { return; } let font = self.app.config.font.lock().unwrap(); let view_id = self .state .lock() .unwrap() .view .as_ref() .unwrap() .id() .clone(); let horizontal_scroll = self.widget_state.lock().unwrap().horizontal_scroll(); let vertical_scroll = self.widget_state.lock().unwrap().vertical_scroll(); let line = ((event.pos.y as f64 + vertical_scroll) / font.lineheight()) as u32; let col = ((event.pos.x as f64 + horizontal_scroll - gutter_width) / font.width) as u32; self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "gesture", "params": { "col":col, "line":line, "ty": "point_select" }, }), ); } fn set_cursor(&self, col: usize, line: usize) { self.state.lock().unwrap().col = col; self.state.lock().unwrap().line = line; } fn ensure_visble(&self, rect: Rect, margin_x: f64, margin_y: f64) { let mut scroll_x = 0.0; let mut scroll_y = 0.0; let gutter_width = self.gutter_width(); let size = self.widget_state.lock().unwrap().size(); let horizontal_scroll = self.widget_state.lock().unwrap().horizontal_scroll(); let vertical_scroll = self.widget_state.lock().unwrap().vertical_scroll(); let right_limit = size.width - gutter_width + horizontal_scroll - margin_x; let left_limit = horizontal_scroll + margin_x; if rect.x1 > right_limit { scroll_x = rect.x1 - right_limit; } else if rect.x0 < left_limit { scroll_x = rect.x0 - left_limit; } let bottom_limit = size.height + vertical_scroll - margin_y; let top_limit = vertical_scroll + margin_y; if rect.y1 > bottom_limit { scroll_y = rect.y1 - bottom_limit; } else if rect.y0 < top_limit { scroll_y = rect.y0 - top_limit; } self.scroll(Vec2::new(scroll_x, scroll_y)); } fn scroll(&self, delta: Vec2) { if delta.x == 0.0 && delta.y == 0.0 { return; } self.send_scroll(); let view_width = self.get_view_width(); let view_height = self.get_view_height(); let size = self.widget_state.lock().unwrap().size(); let width = size.width - self.gutter_width(); let height = size.height; let mut horizontal_scroll = self.widget_state.lock().unwrap().horizontal_scroll(); let mut vertical_scroll = self.widget_state.lock().unwrap().vertical_scroll(); horizontal_scroll += delta.x; if horizontal_scroll > view_width - width { horizontal_scroll = view_width - width; } if horizontal_scroll < 0.0 { horizontal_scroll = 0.0; } vertical_scroll += delta.y; if vertical_scroll > view_height - height { vertical_scroll = view_height - height; } if vertical_scroll < 0.0 { vertical_scroll = 0.0; } self.widget_state .lock() .unwrap() .set_scroll(horizontal_scroll, vertical_scroll); self.invalidate(); } fn exchange(&self) { let parent = self.widget_state.lock().unwrap().parent().unwrap(); let id = self.id(); let ids = parent.child_ids(); if ids.len() <= 1 { return; } let index = ids.iter().position(|c| c == &id).unwrap(); let new_index = match index { i if i < ids.len() - 1 => i + 1, i => i - 1, }; let new_id = ids.get(new_index).unwrap(); let editor = self.clone(); let new_editor = self .app .editors .lock() .unwrap() .get(new_id.as_str()) .unwrap() .clone(); parent.replace_child(index, Box::new(new_editor.clone())); parent.replace_child(new_index, Box::new(editor.clone())); new_editor.set_active(); self.app.state.lock().unwrap().active_editor = new_editor.id(); let view_id = new_editor .state .lock() .unwrap() .view .as_ref() .unwrap() .id() .clone(); let col = new_editor.state.lock().unwrap().col; let line = new_editor.state.lock().unwrap().line; self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "gesture", "params": { "col":col, "line":line, "ty": "point_select" }, }), ); self.app.main_flex.invalidate(); } fn move_curosr(&self, vertical: i64) { let parent = self.parent().unwrap(); let id = self.id(); let ids = parent.child_ids(); let index = ids.iter().position(|c| c == &id).unwrap(); let new_index = match index as i64 + vertical { i if i < 0 => 0, i if i >= ids.len() as i64 => ids.len() - 1, i => i as usize, }; if new_index == index { return; } let new_id = ids.get(new_index).unwrap(); let new_editor = self .app .editors .lock() .unwrap() .get(new_id.as_str()) .unwrap() .clone(); new_editor.set_active(); self.app.state.lock().unwrap().active_editor = new_editor.id(); let view_id = new_editor .state .lock() .unwrap() .view .as_ref() .unwrap() .id() .clone(); let col = new_editor.state.lock().unwrap().col; let line = new_editor.state.lock().unwrap().line; self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "gesture", "params": { "col":col, "line":line, "ty": "point_select" }, }), ); self.invalidate(); new_editor.invalidate(); } pub fn load_file(&self, file_path: String) { if let Some(view) = self.app.path_views.lock().unwrap().get(&file_path).clone() { self.load_view(view.to_owned()); self.invalidate(); return; } let params = json!({ "file_path": file_path.clone(), }); let editor = self.clone(); self.app .core .send_request("new_view", &params, move |value| { let view_id = value.as_str().unwrap().to_string(); let view = View::new(view_id.clone(), editor.app.clone()); editor .app .views .lock() .unwrap() .insert(view_id.clone(), view.clone()); editor .app .path_views .lock() .unwrap() .insert(file_path.clone(), view.clone()); editor.load_view(view); editor.invalidate(); }); } fn send_scroll(&self) { let view = self.state.lock().unwrap().view.clone(); if view.is_none() { return; } let view_id = view.as_ref().unwrap().id().clone(); let lineheight = self.app.config.font.lock().unwrap().lineheight(); let horizontal_scroll = self.widget_state.lock().unwrap().horizontal_scroll(); let vertical_scroll = self.widget_state.lock().unwrap().vertical_scroll(); let size = self.widget_state.lock().unwrap().size(); let start = match (vertical_scroll / lineheight) as usize { s if s > 0 => s - 1, 0 => 0, _ => 0, }; let line_count = (size.height / lineheight) as usize + 2; let core = self.app.core.clone(); thread::spawn(move || { core.send_notification( "edit", &json!({ "view_id": view_id, "method": "scroll", "params": [start, start+line_count], }), ); }); } fn wheel(&self, delta: Vec2, mods: KeyModifiers, ctx: &mut dyn WinCtx) { self.scroll(delta); } fn key_down(&self, event: KeyEvent, ctx: &mut dyn WinCtx) -> bool { let app = self.app.clone(); let key_input = KeyInput::from_keyevent(&event); thread::spawn(move || { app.handle_key_down(key_input); }); true } pub fn get_state(&self) -> InputState { self.state.lock().unwrap().input.state.clone() } } impl CommandRunner for Editor { fn run(&self, cmd: Cmd, key_input: KeyInput) { if self.state.lock().unwrap().view.is_none() { return; } let view_id = self .state .lock() .unwrap() .view .as_ref() .unwrap() .id() .clone(); let mut count = self.state.lock().unwrap().input.count; if count == 0 { count = 1; } let input_state = self.state.lock().unwrap().input.state.clone(); let line_selection = self.state.lock().unwrap().input.visual_line.clone(); let caret = match input_state { InputState::Insert => true, _ => false, }; let is_selection = match input_state { InputState::Visual => true, _ => false, }; match cmd.clone().cmd.unwrap() { Command::CommandPalette => { let palette = self.app.state.lock().unwrap().palette.clone().unwrap(); palette.run(); } Command::Insert => { self.state.lock().unwrap().input.state = InputState::Insert; self.app.core.no_move(&view_id, true, true, true); self.app.get_active_editor().invalidate(); } Command::Visual => { self.state.lock().unwrap().input.visual_line = false; if input_state == InputState::Visual { if line_selection { self.app.core.no_move(&view_id, true, false, false); } else { self.state.lock().unwrap().input.state = InputState::Normal; self.app.core.no_move(&view_id, false, false, false); } } else { self.state.lock().unwrap().input.state = InputState::Visual; self.app.core.no_move(&view_id, true, false, false); } self.app.get_active_editor().invalidate(); } Command::VisualLine => { if input_state == InputState::Visual { if !line_selection { self.state.lock().unwrap().input.visual_line = true; self.app.core.no_move(&view_id, true, true, false); } else { self.state.lock().unwrap().input.visual_line = false; self.state.lock().unwrap().input.state = InputState::Normal; self.app.core.no_move(&view_id, false, false, false); } } else { self.state.lock().unwrap().input.state = InputState::Visual; self.state.lock().unwrap().input.visual_line = true; self.app.core.no_move(&view_id, true, true, false); } self.app.get_active_editor().invalidate(); } Command::Escape => { self.state.lock().unwrap().input.state = InputState::Normal; self.state.lock().unwrap().input.count = 0; self.state.lock().unwrap().input.visual_line = false; self.app.core.no_move(&view_id, false, false, false); self.app.state.lock().unwrap().popup.clone().unwrap().hide(); self.app.get_active_editor().invalidate(); } Command::Undo => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "undo", }), ); self.app.get_active_editor().invalidate(); } Command::Redo => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "redo", }), ); self.app.get_active_editor().invalidate(); } Command::NewLineBelow => { self.state.lock().unwrap().input.state = InputState::Insert; self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "insert_newline_below", }), ); } Command::NewLineAbove => { self.state.lock().unwrap().input.state = InputState::Insert; self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "insert_newline_above", }), ); } Command::InsertNewLine => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "insert_newline", }), ); } Command::InsertTab => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "insert_tab", }), ); } Command::MoveStartOfLine => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "move_to_left_end_of_line", }), ); } Command::MoveEndOfLine => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "move_to_right_end_of_line", }), ); } Command::InsertStartOfLine => { self.state.lock().unwrap().input.state = InputState::Insert; self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "move_to_left_end_of_line", }), ); } Command::AppendRight => { self.state.lock().unwrap().input.state = InputState::Insert; self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "move_right", "params": {"count": count, "is_selection": false, "line_selection": false, "caret": true}, }), ); } Command::AppendEndOfLine => { self.state.lock().unwrap().input.state = InputState::Insert; self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "move_to_right_end_of_line", }), ); } Command::DeleteForwardInsert => { self.state.lock().unwrap().input.state = InputState::Insert; self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "delete_forward", }), ); } Command::DeleteForward => { if input_state == InputState::Visual { self.state.lock().unwrap().input.state = InputState::Normal; } self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "delete_forward", }), ); } Command::DeleteBackward => { if input_state == InputState::Visual { self.state.lock().unwrap().input.state = InputState::Normal; } self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "delete_backward", }), ); if input_state == InputState::Insert { let popup = self .app .state .lock() .unwrap() .popup .clone() .unwrap() .clone(); let (_col, _line, filter) = self.get_completion_pos(); if !popup.is_hidden() { if filter == "" { popup.hide(); } else { popup.filter_items( filter[..filter.len() - 1].to_string(), ); } popup.invalidate(); } else { if filter != "" { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "request_completion", "params": {"request_id": 123}, }), ); } } } } Command::DeleteWordBackward => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "delete_word_backward", }), ); } Command::DeleteToBeginningOfLine => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "delete_to_beginning_of_line", }), ); } Command::ScrollPageUp => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "scroll_page_up", }), ); } Command::ScrollPageDown => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "scroll_page_down", }), ); } Command::MoveToTop => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "move_to_beginning_of_document", }), ); } Command::MoveToBottom => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "move_to_end_of_document", }), ); } Command::MoveUp => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "move_up", "params": {"count": count, "is_selection": is_selection, "line_selection": line_selection, "caret": caret}, }), ); } Command::MoveDown => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "move_down", "params": {"count": count, "is_selection": is_selection, "line_selection": line_selection, "caret": caret}, }), ); } Command::Hover => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "request_hover", "params": {"request_id": 123}, }), ); } Command::MoveLeft => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "move_left", "params": {"count": count, "is_selection": is_selection, "line_selection": line_selection, "caret": caret}, }), ); } Command::MoveRight => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "move_right", "params": {"count": count, "is_selection": is_selection, "line_selection": line_selection, "caret": caret}, }), ); } Command::MoveWordLeft => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "move_word_left", "params": {"count": count, "is_selection": is_selection, "line_selection": line_selection, "caret": caret}, }), ); } Command::MoveWordRight => { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "move_word_right", "params": {"count": count, "is_selection": is_selection, "line_selection": line_selection, "caret": caret}, }), ); } Command::MoveCursorToWindowAbove => {} Command::MoveCursorToWindowBelow => {} Command::MoveCursorToWindowLeft => { let editor = self.clone(); thread::spawn(move || { editor.move_curosr(-1); }); } Command::MoveCursorToWindowRight => { let editor = self.clone(); thread::spawn(move || { editor.move_curosr(1); }); } Command::ExchangeWindow => { let editor = self.clone(); thread::spawn(move || { editor.exchange(); }); } Command::SplitHorizontal => {} Command::SplitClose => { println!("now remove child {}", self.id()); let parent = self.parent().unwrap(); let id = self.id(); let ids = parent.child_ids(); if ids.len() == 1 { return; } let index = ids.iter().position(|c| c == &id).unwrap(); match index { i if i + 1 < ids.len() => self.move_curosr(1), i => self.move_curosr(-1), }; self.app.main_flex.remove_child(self.id()); self.app.main_flex.invalidate(); } Command::SplitVertical => { let view = self.state.lock().unwrap().view.as_ref().unwrap().clone(); let editor = Editor::new(self.app.clone()); self.app .editors .lock() .unwrap() .insert(editor.id().clone(), editor.clone()); editor.state.lock().unwrap().col = self.col(); editor.state.lock().unwrap().line = self.line(); editor.set_scroll( self.horizontal_scroll(), self.vertical_scroll(), ); editor.load_view(view); self.app.main_flex.add_child(Box::new(editor)); self.app.main_flex.invalidate(); } Command::Unknown => { if input_state == InputState::Insert && key_input.text != "" && !key_input.mods.ctrl && !key_input.mods.alt && !key_input.mods.meta { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "insert", "params": {"chars": key_input.text}, }), ); let popup = self .app .state .lock() .unwrap() .popup .clone() .unwrap() .clone(); if key_input.text.len() == 1 { let ch = key_input.text.chars().next().unwrap(); let prop = get_word_property(ch); match prop { WordProperty::Other => { if popup.is_hidden() { if get_word_property(ch) == WordProperty::Other { self.app.core.send_notification( "edit", &json!({ "view_id": view_id, "method": "request_completion", "params": {"request_id": 123}, }), ); } } else { let (_col, _line, filter) = self.get_completion_pos(); popup.filter_items(format!( "{}{}", filter, key_input.text )); popup.invalidate(); } } _ => { popup.hide(); popup.invalidate(); } }; } } } _ => {} } if input_state == InputState::Normal { match cmd.cmd.unwrap() { Command::Unknown => { if let Ok(n) = key_input.text.parse::<u64>() { let count = self.state.lock().unwrap().input.count; self.state.lock().unwrap().input.count = count * 10 + n; } else { self.state.lock().unwrap().input.count = 0; } } _ => self.state.lock().unwrap().input.count = 0, }; } } } struct ViewState { width: f64, height: f64, } #[derive(Clone)] pub struct View { id: String, app: App, state: Arc<Mutex<ViewState>>, pub line_cache: Arc<Mutex<LineCache>>, } impl View { pub fn new(view_id: String, app: App) -> View { View { id: view_id, app, line_cache: Arc::new(Mutex::new(LineCache::new())), state: Arc::new(Mutex::new(ViewState { width: 0.0, height: 0.0, })), } } pub fn id(&self) -> String { self.id.clone() } pub fn apply_update(&self, update: &Value) { let (start, end) = self.line_cache.lock().unwrap().apply_update(update); let lineheight = self.app.config.font.lock().unwrap().lineheight(); let font_width = self.app.config.font.lock().unwrap().width; self.state.lock().unwrap().height = self.line_cache.lock().unwrap().height() as f64 * lineheight; let mut width = 0.0; let line_count = self.line_cache.lock().unwrap().height(); for i in 0..line_count { if let Some(line) = self.line_cache.lock().unwrap().get_line(i) { let current_width = count_utf16(line.text()) as f64 * font_width; if current_width > width { width = current_width; } } } self.state.lock().unwrap().width = width; // println!("finish apply update"); for (_, editor) in self.app.editors.lock().unwrap().iter() { let view = editor.state.lock().unwrap().view.clone(); match view { Some(view) => { if view.id() == self.id { let old_ln = editor.state.lock().unwrap().line; match view .line_cache .lock() .unwrap() .get_old_line(old_ln) .clone() { Some(old_line) => { editor.state.lock().unwrap().line = old_line.new_ln(); } None => (), } let gutter_width = editor.gutter_width(); let vertical_scroll = editor .widget_state .lock() .unwrap() .vertical_scroll(); let x = editor.gutter_width(); let y = start as f64 * lineheight - vertical_scroll; let width = editor.widget_state.lock().unwrap().size().width - gutter_width; let height = (end - start + 1) as f64 * lineheight; let rect = Rect::from_origin_size( Point::new(x, y), Size::new(width, height), ); editor.invalidate_rect(rect); } } None => (), } } // if let Some(editor) = self.get_active_editor() { // editor.invalidate(); // } } fn get_active_editor(&self) -> Option<Editor> { let editor = self.app.get_active_editor(); if editor.state.lock().unwrap().view.clone().unwrap().id == self.id { return Some(editor); } None } pub fn scroll_to(&self, col: usize, line: usize) { if let Some(editor) = self.get_active_editor() { let (font_width, line_height) = { let font = self.app.config.font.lock().unwrap(); let font_width = font.width; let line_height = font.lineheight(); (font_width, line_height) }; let rect = Rect::from_origin_size( Point::new(col as f64 * font_width, line as f64 * line_height), Size::new(font_width, line_height), ); let editor = editor.clone(); thread::spawn(move || { editor.set_cursor(col, line); editor.ensure_visble(rect, font_width, line_height); }); } } }
use std::fmt; use std::marker::PhantomData; use std::ptr; use std::sync::atomic::{AtomicPtr, Ordering}; pub struct AtomicBox<T> { ptr: AtomicPtr<T>, _marker: PhantomData<Option<Box<T>>>, } unsafe impl<T: Send> Send for AtomicBox<T> {} unsafe impl<T: Send> Sync for AtomicBox<T> {} impl<T> Drop for AtomicBox<T> { fn drop(&mut self) { let _ = self.take(Ordering::Acquire); } } impl<T> AtomicBox<T> { /// Creates a new empty `AtomicBox`. #[cfg(not(nightly))] pub fn empty() -> Self { AtomicBox { ptr: AtomicPtr::new(ptr::null_mut()), _marker: PhantomData, } } /// Creates a new empty `AtomicBox`. #[cfg(nightly)] pub const fn empty() -> Self { AtomicBox { ptr: AtomicPtr::new(ptr::null_mut()), _marker: PhantomData, } } /// Creates a new `AtomicBox` containing the specified value. pub fn new(value: Box<T>) -> Self { AtomicBox { ptr: AtomicPtr::new(Box::into_raw(value)), _marker: PhantomData, } } /// Returns a reference to the underlying `AtomicPtr`. /// /// # Safety /// /// Using the returned reference to load and use the contained value could /// result in data races and use after free errors. pub unsafe fn as_raw(&self) -> &AtomicPtr<T> { &self.ptr } /// Loads and returns a pointer to the contained value. /// /// # Safety /// /// Dereferencing the returned pointer could result in data races and use after free errors. pub unsafe fn as_ptr(&self, order: Ordering) -> *const T { self.ptr.load(order) } /// Loads and returns a mutable pointer to the contained value. /// /// # Safety /// /// Dereferencing the returned pointer could result in data races and use after free errors. pub unsafe fn as_mut_ptr(&self, order: Ordering) -> *mut T { self.ptr.load(order) } /// Replaces the contained value with the empty value and returns the old value. pub fn take(&self, order: Ordering) -> Option<Box<T>> { self.swap(None, order) } /// Replaces the contained value with the specified value and returns the old value. pub fn swap(&self, new: Option<Box<T>>, order: Ordering) -> Option<Box<T>> { let new = new.map_or(ptr::null_mut(), Box::into_raw); unsafe { self.ptr.swap(new, order).as_mut().map(|x| Box::from_raw(x)) } } } impl<T> Default for AtomicBox<T> { fn default() -> Self { AtomicBox::empty() } } impl<T> From<Option<Box<T>>> for AtomicBox<T> { fn from(value: Option<Box<T>>) -> Self { value.map_or(AtomicBox::empty(), AtomicBox::new) } } impl<T> fmt::Debug for AtomicBox<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.ptr.fmt(f) } }
pub mod next_larger_nodes; pub mod num_of_subarrays; pub mod two_sum; pub mod reverse_integer;
#[doc = "Register `APB1SMENR` reader"] pub type R = crate::R<APB1SMENR_SPEC>; #[doc = "Register `APB1SMENR` writer"] pub type W = crate::W<APB1SMENR_SPEC>; #[doc = "Field `TIM2SMEN` reader - Timer2 clock enable during sleep mode bit"] pub type TIM2SMEN_R = crate::BitReader<TIM2SMEN_A>; #[doc = "Timer2 clock enable during sleep mode bit\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TIM2SMEN_A { #[doc = "0: Clock disabled"] Disabled = 0, #[doc = "1: Clock enabled"] Enabled = 1, } impl From<TIM2SMEN_A> for bool { #[inline(always)] fn from(variant: TIM2SMEN_A) -> Self { variant as u8 != 0 } } impl TIM2SMEN_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIM2SMEN_A { match self.bits { false => TIM2SMEN_A::Disabled, true => TIM2SMEN_A::Enabled, } } #[doc = "Clock disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == TIM2SMEN_A::Disabled } #[doc = "Clock enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == TIM2SMEN_A::Enabled } } #[doc = "Field `TIM2SMEN` writer - Timer2 clock enable during sleep mode bit"] pub type TIM2SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TIM2SMEN_A>; impl<'a, REG, const O: u8> TIM2SMEN_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clock disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(TIM2SMEN_A::Disabled) } #[doc = "Clock enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(TIM2SMEN_A::Enabled) } } #[doc = "Field `TIM3SMEN` reader - Timer 3 clock enable during sleep mode bit"] pub use TIM2SMEN_R as TIM3SMEN_R; #[doc = "Field `TIM6SMEN` reader - Timer 6 clock enable during sleep mode bit"] pub use TIM2SMEN_R as TIM6SMEN_R; #[doc = "Field `TIM7SMEN` reader - Timer 7 clock enable during sleep mode bit"] pub use TIM2SMEN_R as TIM7SMEN_R; #[doc = "Field `WWDGSMEN` reader - Window watchdog clock enable during sleep mode bit"] pub use TIM2SMEN_R as WWDGSMEN_R; #[doc = "Field `SPI2SMEN` reader - SPI2 clock enable during sleep mode bit"] pub use TIM2SMEN_R as SPI2SMEN_R; #[doc = "Field `USART2SMEN` reader - UART2 clock enable during sleep mode bit"] pub use TIM2SMEN_R as USART2SMEN_R; #[doc = "Field `LPUART1SMEN` reader - LPUART1 clock enable during sleep mode bit"] pub use TIM2SMEN_R as LPUART1SMEN_R; #[doc = "Field `USART4SMEN` reader - USART4 clock enabe during sleep mode bit"] pub use TIM2SMEN_R as USART4SMEN_R; #[doc = "Field `USART5SMEN` reader - USART5 clock enable during sleep mode bit"] pub use TIM2SMEN_R as USART5SMEN_R; #[doc = "Field `I2C1SMEN` reader - I2C1 clock enable during sleep mode bit"] pub use TIM2SMEN_R as I2C1SMEN_R; #[doc = "Field `I2C2SMEN` reader - I2C2 clock enable during sleep mode bit"] pub use TIM2SMEN_R as I2C2SMEN_R; #[doc = "Field `CRSSMEN` reader - Clock recovery system clock enable during sleep mode bit"] pub use TIM2SMEN_R as CRSSMEN_R; #[doc = "Field `PWRSMEN` reader - Power interface clock enable during sleep mode bit"] pub use TIM2SMEN_R as PWRSMEN_R; #[doc = "Field `I2C3SMEN` reader - I2C3 clock enable during sleep mode bit"] pub use TIM2SMEN_R as I2C3SMEN_R; #[doc = "Field `LPTIM1SMEN` reader - Low power timer clock enable during sleep mode bit"] pub use TIM2SMEN_R as LPTIM1SMEN_R; #[doc = "Field `TIM3SMEN` writer - Timer 3 clock enable during sleep mode bit"] pub use TIM2SMEN_W as TIM3SMEN_W; #[doc = "Field `TIM6SMEN` writer - Timer 6 clock enable during sleep mode bit"] pub use TIM2SMEN_W as TIM6SMEN_W; #[doc = "Field `TIM7SMEN` writer - Timer 7 clock enable during sleep mode bit"] pub use TIM2SMEN_W as TIM7SMEN_W; #[doc = "Field `WWDGSMEN` writer - Window watchdog clock enable during sleep mode bit"] pub use TIM2SMEN_W as WWDGSMEN_W; #[doc = "Field `SPI2SMEN` writer - SPI2 clock enable during sleep mode bit"] pub use TIM2SMEN_W as SPI2SMEN_W; #[doc = "Field `USART2SMEN` writer - UART2 clock enable during sleep mode bit"] pub use TIM2SMEN_W as USART2SMEN_W; #[doc = "Field `LPUART1SMEN` writer - LPUART1 clock enable during sleep mode bit"] pub use TIM2SMEN_W as LPUART1SMEN_W; #[doc = "Field `USART4SMEN` writer - USART4 clock enabe during sleep mode bit"] pub use TIM2SMEN_W as USART4SMEN_W; #[doc = "Field `USART5SMEN` writer - USART5 clock enable during sleep mode bit"] pub use TIM2SMEN_W as USART5SMEN_W; #[doc = "Field `I2C1SMEN` writer - I2C1 clock enable during sleep mode bit"] pub use TIM2SMEN_W as I2C1SMEN_W; #[doc = "Field `I2C2SMEN` writer - I2C2 clock enable during sleep mode bit"] pub use TIM2SMEN_W as I2C2SMEN_W; #[doc = "Field `CRSSMEN` writer - Clock recovery system clock enable during sleep mode bit"] pub use TIM2SMEN_W as CRSSMEN_W; #[doc = "Field `PWRSMEN` writer - Power interface clock enable during sleep mode bit"] pub use TIM2SMEN_W as PWRSMEN_W; #[doc = "Field `I2C3SMEN` writer - I2C3 clock enable during sleep mode bit"] pub use TIM2SMEN_W as I2C3SMEN_W; #[doc = "Field `LPTIM1SMEN` writer - Low power timer clock enable during sleep mode bit"] pub use TIM2SMEN_W as LPTIM1SMEN_W; impl R { #[doc = "Bit 0 - Timer2 clock enable during sleep mode bit"] #[inline(always)] pub fn tim2smen(&self) -> TIM2SMEN_R { TIM2SMEN_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Timer 3 clock enable during sleep mode bit"] #[inline(always)] pub fn tim3smen(&self) -> TIM3SMEN_R { TIM3SMEN_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 4 - Timer 6 clock enable during sleep mode bit"] #[inline(always)] pub fn tim6smen(&self) -> TIM6SMEN_R { TIM6SMEN_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Timer 7 clock enable during sleep mode bit"] #[inline(always)] pub fn tim7smen(&self) -> TIM7SMEN_R { TIM7SMEN_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 11 - Window watchdog clock enable during sleep mode bit"] #[inline(always)] pub fn wwdgsmen(&self) -> WWDGSMEN_R { WWDGSMEN_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 14 - SPI2 clock enable during sleep mode bit"] #[inline(always)] pub fn spi2smen(&self) -> SPI2SMEN_R { SPI2SMEN_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 17 - UART2 clock enable during sleep mode bit"] #[inline(always)] pub fn usart2smen(&self) -> USART2SMEN_R { USART2SMEN_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - LPUART1 clock enable during sleep mode bit"] #[inline(always)] pub fn lpuart1smen(&self) -> LPUART1SMEN_R { LPUART1SMEN_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - USART4 clock enabe during sleep mode bit"] #[inline(always)] pub fn usart4smen(&self) -> USART4SMEN_R { USART4SMEN_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - USART5 clock enable during sleep mode bit"] #[inline(always)] pub fn usart5smen(&self) -> USART5SMEN_R { USART5SMEN_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - I2C1 clock enable during sleep mode bit"] #[inline(always)] pub fn i2c1smen(&self) -> I2C1SMEN_R { I2C1SMEN_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - I2C2 clock enable during sleep mode bit"] #[inline(always)] pub fn i2c2smen(&self) -> I2C2SMEN_R { I2C2SMEN_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 27 - Clock recovery system clock enable during sleep mode bit"] #[inline(always)] pub fn crssmen(&self) -> CRSSMEN_R { CRSSMEN_R::new(((self.bits >> 27) & 1) != 0) } #[doc = "Bit 28 - Power interface clock enable during sleep mode bit"] #[inline(always)] pub fn pwrsmen(&self) -> PWRSMEN_R { PWRSMEN_R::new(((self.bits >> 28) & 1) != 0) } #[doc = "Bit 30 - I2C3 clock enable during sleep mode bit"] #[inline(always)] pub fn i2c3smen(&self) -> I2C3SMEN_R { I2C3SMEN_R::new(((self.bits >> 30) & 1) != 0) } #[doc = "Bit 31 - Low power timer clock enable during sleep mode bit"] #[inline(always)] pub fn lptim1smen(&self) -> LPTIM1SMEN_R { LPTIM1SMEN_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bit 0 - Timer2 clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn tim2smen(&mut self) -> TIM2SMEN_W<APB1SMENR_SPEC, 0> { TIM2SMEN_W::new(self) } #[doc = "Bit 1 - Timer 3 clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn tim3smen(&mut self) -> TIM3SMEN_W<APB1SMENR_SPEC, 1> { TIM3SMEN_W::new(self) } #[doc = "Bit 4 - Timer 6 clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn tim6smen(&mut self) -> TIM6SMEN_W<APB1SMENR_SPEC, 4> { TIM6SMEN_W::new(self) } #[doc = "Bit 5 - Timer 7 clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn tim7smen(&mut self) -> TIM7SMEN_W<APB1SMENR_SPEC, 5> { TIM7SMEN_W::new(self) } #[doc = "Bit 11 - Window watchdog clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn wwdgsmen(&mut self) -> WWDGSMEN_W<APB1SMENR_SPEC, 11> { WWDGSMEN_W::new(self) } #[doc = "Bit 14 - SPI2 clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn spi2smen(&mut self) -> SPI2SMEN_W<APB1SMENR_SPEC, 14> { SPI2SMEN_W::new(self) } #[doc = "Bit 17 - UART2 clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn usart2smen(&mut self) -> USART2SMEN_W<APB1SMENR_SPEC, 17> { USART2SMEN_W::new(self) } #[doc = "Bit 18 - LPUART1 clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn lpuart1smen(&mut self) -> LPUART1SMEN_W<APB1SMENR_SPEC, 18> { LPUART1SMEN_W::new(self) } #[doc = "Bit 19 - USART4 clock enabe during sleep mode bit"] #[inline(always)] #[must_use] pub fn usart4smen(&mut self) -> USART4SMEN_W<APB1SMENR_SPEC, 19> { USART4SMEN_W::new(self) } #[doc = "Bit 20 - USART5 clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn usart5smen(&mut self) -> USART5SMEN_W<APB1SMENR_SPEC, 20> { USART5SMEN_W::new(self) } #[doc = "Bit 21 - I2C1 clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn i2c1smen(&mut self) -> I2C1SMEN_W<APB1SMENR_SPEC, 21> { I2C1SMEN_W::new(self) } #[doc = "Bit 22 - I2C2 clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn i2c2smen(&mut self) -> I2C2SMEN_W<APB1SMENR_SPEC, 22> { I2C2SMEN_W::new(self) } #[doc = "Bit 27 - Clock recovery system clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn crssmen(&mut self) -> CRSSMEN_W<APB1SMENR_SPEC, 27> { CRSSMEN_W::new(self) } #[doc = "Bit 28 - Power interface clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn pwrsmen(&mut self) -> PWRSMEN_W<APB1SMENR_SPEC, 28> { PWRSMEN_W::new(self) } #[doc = "Bit 30 - I2C3 clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn i2c3smen(&mut self) -> I2C3SMEN_W<APB1SMENR_SPEC, 30> { I2C3SMEN_W::new(self) } #[doc = "Bit 31 - Low power timer clock enable during sleep mode bit"] #[inline(always)] #[must_use] pub fn lptim1smen(&mut self) -> LPTIM1SMEN_W<APB1SMENR_SPEC, 31> { LPTIM1SMEN_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 = "APB1 peripheral clock enable in sleep mode register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1smenr::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 [`apb1smenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct APB1SMENR_SPEC; impl crate::RegisterSpec for APB1SMENR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`apb1smenr::R`](R) reader structure"] impl crate::Readable for APB1SMENR_SPEC {} #[doc = "`write(|w| ..)` method takes [`apb1smenr::W`](W) writer structure"] impl crate::Writable for APB1SMENR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets APB1SMENR to value 0xb8e6_4a11"] impl crate::Resettable for APB1SMENR_SPEC { const RESET_VALUE: Self::Ux = 0xb8e6_4a11; }
use rand::Rng; struct Heap { data: Vec<i64>, size: usize, } impl Heap { fn new() -> Heap { return Heap { data: Vec::new(), size: 0, }; } // get index relative to another // fn get_left_child_index(&self, parent_index: usize) -> usize{ return 2 * parent_index + 1; } fn get_right_child_index(&self, parent_index: usize) -> usize{ return 2 * parent_index + 2; } fn get_parent_index(&self, child_index: usize) -> usize { if child_index == 0 { return 0; } else { return (child_index - 1) / 2; } } // check if relative index exists // fn has_left_child(&self, index: usize) -> bool { return self.get_left_child_index(index) < self.data.len(); } fn has_right_child(&self, index: usize) -> bool { return self.get_right_child_index(index) < self.data.len(); } fn has_parent(&self, index: usize) -> bool { return self.get_parent_index(index) >= 0; } // get relative index value // fn get_left_child(&self, index: usize) -> i64 { return self.data[ self.get_left_child_index(index) ]; } fn get_right_child(&self, index: usize) -> i64 { return self.data[ self.get_right_child_index(index) ]; } fn get_parent(&self, index: usize) -> i64 { return self.data[ self.get_parent_index(index) ]; } // swap two value in the heap // fn swap(&mut self, index_one: usize, index_two: usize) { let tmp: i64 = self.data[index_one]; self.data[index_one] = self.data[index_two]; self.data[index_two] = tmp; } // get min value // fn peek(&self) -> i64 { return self.data[0]; } // ensure values are correctly placed in heap in a bottom up fashion fn heapify_up(&mut self) { let mut index: usize = self.data.len() - 1; while( self.has_parent(index) && self.get_parent(index) > self.data[index] ) { self.swap(self.get_parent_index(index), index); index = self.get_parent_index(index); } } // ensure values are correctly placed in heap in a top down fashion fn heapify_down(&mut self) { let mut index: usize = 0; // root node while( self.has_left_child(index) ) { let mut smaller_child_index = self.get_left_child_index(index); if self.has_right_child(index) && self.get_right_child(index) < self.get_left_child(index) { smaller_child_index = self.get_right_child_index(index); } if self.data[index] < self.data[smaller_child_index] { break; } else { self.swap(index, smaller_child_index); } index = smaller_child_index; } } // pop min value while maintaining heap structure fn poll(&mut self) -> i64 { let value: i64 = self.data[0]; // put last item at the top, and find its correct place self.data[0] = self.data[self.data.len()-1]; self.heapify_down(); return value; } // add value to heap while maintaining structure fn add(&mut self, new_value: i64){ self.data.push(new_value); self.heapify_up(); } } fn main(){ println!("Heap demo"); let mut array: [i64; 32] = [0;32]; for i in 0..32 { array[i] = rand::thread_rng().gen_range(1, 10) } let mut my_heap: Heap = Heap::new(); // add random numbers to heap for i in 0..32 { my_heap.add(array[i]) } println!("\nSorted array:"); for i in 0..32 { print!("{} ", my_heap.poll()); } println!(""); }
fn main() -> anyhow::Result<()> { flexi_logger::Logger::try_with_env_or_str("warn")?.start()?; let settings = config::Config::builder() .add_source(config::File::with_name("KosemClient.toml")) .build()?; let config = settings.try_deserialize()?; kosem_gui::start_gtk(config)?; Ok(()) }
//! Benchmarking for `pallet-domains`. use super::*; use crate::domain_registry::DomainConfig; use crate::staking::{do_reward_operators, OperatorConfig, OperatorStatus, Withdraw}; use crate::staking_epoch::{do_finalize_domain_current_epoch, do_finalize_domain_staking}; use crate::Pallet as Domains; use frame_benchmarking::v2::*; use frame_support::assert_ok; use frame_support::traits::fungible::Mutate; use frame_support::traits::Hooks; use frame_support::weights::Weight; use frame_system::{Pallet as System, RawOrigin}; use sp_core::crypto::UncheckedFrom; use sp_domains::{ dummy_opaque_bundle, DomainId, ExecutionReceipt, OperatorId, OperatorPublicKey, RuntimeType, }; use sp_runtime::traits::{BlockNumberProvider, CheckedAdd, One, SaturatedConversion}; const SEED: u32 = 0; #[benchmarks] mod benchmarks { use super::*; /// Benchmark `submit_bundle` extrinsic with the worst possible conditions: /// - The bundle is the first bundle of the consensus block /// - The bundle contains receipt that will prune the block tree #[benchmark] fn submit_bundle() { let block_tree_pruning_depth = T::BlockTreePruningDepth::get().saturated_into::<u32>(); let domain_id = register_domain::<T>(); let (_, operator_id) = register_helper_operator::<T>(domain_id, T::Currency::minimum_balance()); let mut receipt = BlockTree::<T>::get::<_, T::DomainNumber>(domain_id, Zero::zero()) .first() .and_then(DomainBlocks::<T>::get) .expect("genesis receipt must exist") .execution_receipt; for i in 1..=(block_tree_pruning_depth + 1) { let consensus_block_number = i.into(); let domain_block_number = i.into(); // Run to `block_number` run_to_block::<T>( consensus_block_number, frame_system::Pallet::<T>::block_hash(consensus_block_number - One::one()), ); // Submit a bundle with the receipt of the last block let bundle = dummy_opaque_bundle(domain_id, operator_id, receipt); assert_ok!(Domains::<T>::submit_bundle(RawOrigin::None.into(), bundle)); // Create ER for the above bundle let head_receipt_number = HeadReceiptNumber::<T>::get(domain_id); let parent_domain_block_receipt = BlockTree::<T>::get(domain_id, head_receipt_number) .first() .cloned() .expect("parent receipt must exist"); receipt = ExecutionReceipt::dummy( consensus_block_number, frame_system::Pallet::<T>::block_hash(consensus_block_number), domain_block_number, parent_domain_block_receipt, ); } assert_eq!( Domains::<T>::head_receipt_number(domain_id), (block_tree_pruning_depth).into() ); // Construct bundle that will prune the block tree let block_number = (block_tree_pruning_depth + 2).into(); run_to_block::<T>( block_number, frame_system::Pallet::<T>::block_hash(block_number - One::one()), ); let bundle = dummy_opaque_bundle(domain_id, operator_id, receipt); #[extrinsic_call] submit_bundle(RawOrigin::None, bundle); assert_eq!( Domains::<T>::head_receipt_number(domain_id), (block_tree_pruning_depth + 1).into() ); assert_eq!(Domains::<T>::oldest_receipt_number(domain_id), 1u32.into()); } /// Benchmark pending staking operation with the worst possible conditions: /// - There are `MaxPendingStakingOperation` number of pending staking operation /// - All pending staking operation are withdrawal that withdraw partial stake #[benchmark] fn pending_staking_operation() { let max_pending_staking_op = T::MaxPendingStakingOperation::get(); let epoch_duration = T::StakeEpochDuration::get(); let minimum_nominator_stake = T::Currency::minimum_balance(); let withdraw_amount = T::MinOperatorStake::get(); let domain_id = register_domain::<T>(); let (_, operator_id) = register_helper_operator::<T>(domain_id, minimum_nominator_stake); do_finalize_domain_current_epoch::<T>(domain_id, 0u32.into()) .expect("finalize domain staking should success"); for i in 0..max_pending_staking_op { let nominator = account("nominator", i, SEED); T::Currency::set_balance( &nominator, withdraw_amount * 2u32.into() + T::Currency::minimum_balance(), ); assert_ok!(Domains::<T>::nominate_operator( RawOrigin::Signed(nominator).into(), operator_id, withdraw_amount * 2u32.into(), )); } do_finalize_domain_current_epoch::<T>(domain_id, epoch_duration) .expect("finalize domain staking should success"); assert_eq!(PendingStakingOperationCount::<T>::get(domain_id), 0); for i in 0..max_pending_staking_op { let nominator = account("nominator", i, SEED); assert_ok!(Domains::<T>::withdraw_stake( RawOrigin::Signed(nominator).into(), operator_id, Withdraw::Some(withdraw_amount), )); } assert_eq!( PendingStakingOperationCount::<T>::get(domain_id) as u32, max_pending_staking_op ); assert_eq!( PendingWithdrawals::<T>::iter_prefix_values(operator_id).count() as u32, max_pending_staking_op ); #[block] { do_reward_operators::<T>( domain_id, vec![operator_id].into_iter(), T::DomainBlockReward::get(), ) .expect("reward operator should success"); do_finalize_domain_current_epoch::<T>(domain_id, epoch_duration * 2u32.into()) .expect("finalize domain staking should success"); } assert_eq!(PendingStakingOperationCount::<T>::get(domain_id), 0); assert_eq!( PendingWithdrawals::<T>::iter_prefix_values(operator_id).count(), 0 ); } #[benchmark] fn register_domain_runtime() { let runtime_blob = include_bytes!("../res/evm_domain_test_runtime.compact.compressed.wasm").to_vec(); let runtime_id = NextRuntimeId::<T>::get(); let runtime_hash = T::Hashing::hash(&runtime_blob); #[extrinsic_call] _( RawOrigin::Root, b"evm-domain".to_vec(), RuntimeType::Evm, runtime_blob, ); let runtime_obj = RuntimeRegistry::<T>::get(runtime_id).expect("runtime object must exist"); assert_eq!(runtime_obj.runtime_name, b"evm-domain".to_vec()); assert_eq!(runtime_obj.runtime_type, RuntimeType::Evm); assert_eq!(runtime_obj.hash, runtime_hash); assert_eq!(NextRuntimeId::<T>::get(), runtime_id + 1); } #[benchmark] fn upgrade_domain_runtime() { let runtime_blob = include_bytes!("../res/evm_domain_test_runtime.compact.compressed.wasm").to_vec(); let runtime_id = NextRuntimeId::<T>::get(); // The `runtime_blob` have `spec_version = 1` thus we need to modify the runtime object // version to 0 to bypass the `can_upgrade_code` check when calling `upgrade_domain_runtime` assert_ok!(Domains::<T>::register_domain_runtime( RawOrigin::Root.into(), b"evm-domain".to_vec(), RuntimeType::Evm, runtime_blob.clone() )); RuntimeRegistry::<T>::mutate(runtime_id, |maybe_runtime_object| { let runtime_obj = maybe_runtime_object .as_mut() .expect("Runtime object must exist"); runtime_obj.version.spec_version = 0; }); #[extrinsic_call] _(RawOrigin::Root, runtime_id, runtime_blob.clone()); let scheduled_at = frame_system::Pallet::<T>::current_block_number() .checked_add(&T::DomainRuntimeUpgradeDelay::get()) .expect("must not overflow"); let scheduled_upgrade = ScheduledRuntimeUpgrades::<T>::get(scheduled_at, runtime_id) .expect("scheduled upgrade must exist"); assert_eq!(scheduled_upgrade.version.spec_version, 1); assert_eq!(scheduled_upgrade.code, runtime_blob); } #[benchmark] fn instantiate_domain() { let creator = account("creator", 1, SEED); T::Currency::set_balance( &creator, T::DomainInstantiationDeposit::get() + T::Currency::minimum_balance(), ); let runtime_id = register_runtime::<T>(); let domain_id = NextDomainId::<T>::get(); let domain_config = DomainConfig { domain_name: b"evm-domain".to_vec(), runtime_id, max_block_size: 1024, max_block_weight: Weight::from_parts(1, 0), bundle_slot_probability: (1, 1), target_bundles_per_block: 10, }; #[extrinsic_call] _(RawOrigin::Signed(creator.clone()), domain_config.clone()); let domain_obj = DomainRegistry::<T>::get(domain_id).expect("domain object must exist"); assert_eq!(domain_obj.domain_config, domain_config); assert_eq!(domain_obj.owner_account_id, creator); assert!(DomainStakingSummary::<T>::get(domain_id).is_some()); assert_eq!( BlockTree::<T>::get::<_, T::DomainNumber>(domain_id, Zero::zero()).len(), 1 ); assert_eq!(NextDomainId::<T>::get(), domain_id + 1.into()); } #[benchmark] fn register_operator() { let operator_account = account("operator", 1, SEED); T::Currency::set_balance( &operator_account, T::MinOperatorStake::get() + T::Currency::minimum_balance(), ); let domain_id = register_domain::<T>(); let operator_id = NextOperatorId::<T>::get(); let operator_config = OperatorConfig { signing_key: OperatorPublicKey::unchecked_from([1u8; 32]), minimum_nominator_stake: T::Currency::minimum_balance(), nomination_tax: Default::default(), }; #[extrinsic_call] _( RawOrigin::Signed(operator_account.clone()), domain_id, T::MinOperatorStake::get(), operator_config.clone(), ); assert_eq!(NextOperatorId::<T>::get(), operator_id + 1); assert_eq!( OperatorIdOwner::<T>::get(operator_id), Some(operator_account.clone()) ); let operator = Operators::<T>::get(operator_id).expect("operator must exist"); assert_eq!(operator.signing_key, operator_config.signing_key); let staking_summary = DomainStakingSummary::<T>::get(domain_id).expect("staking summary must exist"); assert!(staking_summary.next_operators.contains(&operator_id)); assert_eq!( PendingDeposits::<T>::get(operator_id, operator_account), Some(T::MinOperatorStake::get()) ); } /// Benchmark `nominate_operator` extrinsic with the worst possible conditions: /// - There is already a pending deposit of the nominator #[benchmark] fn nominate_operator() { let nominator = account("nominator", 1, SEED); let minimum_nominator_stake = T::Currency::minimum_balance(); T::Currency::set_balance( &nominator, minimum_nominator_stake * 2u32.into() + T::Currency::minimum_balance(), ); let domain_id = register_domain::<T>(); let (_, operator_id) = register_helper_operator::<T>(domain_id, minimum_nominator_stake); // Add one more pending deposit assert_ok!(Domains::<T>::nominate_operator( RawOrigin::Signed(nominator.clone()).into(), operator_id, minimum_nominator_stake, )); #[extrinsic_call] _( RawOrigin::Signed(nominator.clone()), operator_id, minimum_nominator_stake, ); assert_eq!( PendingDeposits::<T>::get(operator_id, nominator), Some(minimum_nominator_stake * 2u32.into()) ); } #[benchmark] fn switch_domain() { let domain1_id = register_domain::<T>(); let domain2_id = register_domain::<T>(); let (operator_owner, operator_id) = register_helper_operator::<T>(domain1_id, T::Currency::minimum_balance()); #[extrinsic_call] _( RawOrigin::Signed(operator_owner.clone()), operator_id, domain2_id, ); let operator = Operators::<T>::get(operator_id).expect("operator must exist"); assert_eq!(operator.next_domain_id, domain2_id); let pending_switch = PendingOperatorSwitches::<T>::get(domain1_id).expect("pending switch must exist"); assert!(pending_switch.contains(&operator_id)); } #[benchmark] fn deregister_operator() { let domain_id = register_domain::<T>(); let (operator_owner, operator_id) = register_helper_operator::<T>(domain_id, T::Currency::minimum_balance()); #[extrinsic_call] _(RawOrigin::Signed(operator_owner.clone()), operator_id); let operator = Operators::<T>::get(operator_id).expect("operator must exist"); assert_eq!(operator.status, OperatorStatus::Deregistered); let pending_deregistration = PendingOperatorDeregistrations::<T>::get(domain_id) .expect("pending deregistration must exist"); assert!(pending_deregistration.contains(&operator_id)); } /// Benchmark `withdraw_stake` extrinsic with the worst possible conditions: /// - There is unmint reward of the nominator /// - There is already a pending withdrawal of the nominator /// - Only withdraw partial of the nominator's stake #[benchmark] fn withdraw_stake() { let nominator = account("nominator", 1, SEED); let minimum_nominator_stake = T::Currency::minimum_balance(); let withdraw_amount = T::MinOperatorStake::get(); T::Currency::set_balance( &nominator, withdraw_amount * 3u32.into() + T::Currency::minimum_balance(), ); let domain_id = register_domain::<T>(); let (_, operator_id) = register_helper_operator::<T>(domain_id, minimum_nominator_stake); assert_ok!(Domains::<T>::nominate_operator( RawOrigin::Signed(nominator.clone()).into(), operator_id, withdraw_amount * 3u32.into(), )); do_finalize_domain_staking::<T>(domain_id, 1u32.into()) .expect("finalize domain staking should success"); // Add reward to the operator let _ = DomainStakingSummary::<T>::try_mutate(domain_id, |maybe_stake_summary| { let stake_summary = maybe_stake_summary .as_mut() .expect("staking summary must exist"); stake_summary .current_epoch_rewards .insert(operator_id, T::MinOperatorStake::get()); Ok::<_, ()>(()) }); // Add one more withdraw assert_ok!(Domains::<T>::withdraw_stake( RawOrigin::Signed(nominator.clone()).into(), operator_id, Withdraw::Some(withdraw_amount), )); #[extrinsic_call] _( RawOrigin::Signed(nominator.clone()), operator_id, Withdraw::Some(withdraw_amount), ); assert_eq!( PendingWithdrawals::<T>::get(operator_id, nominator), Some(Withdraw::Some(withdraw_amount * 2u32.into())) ); } #[benchmark] fn auto_stake_block_rewards() { let nominator = account("nominator", 1, SEED); let minimum_nominator_stake = T::Currency::minimum_balance(); T::Currency::set_balance( &nominator, minimum_nominator_stake + T::Currency::minimum_balance(), ); let domain_id = register_domain::<T>(); let (_, operator_id) = register_helper_operator::<T>(domain_id, minimum_nominator_stake); assert_ok!(Domains::<T>::nominate_operator( RawOrigin::Signed(nominator.clone()).into(), operator_id, minimum_nominator_stake, )); do_finalize_domain_staking::<T>(domain_id, 1u32.into()) .expect("finalize domain staking should success"); #[extrinsic_call] _(RawOrigin::Signed(nominator.clone()), operator_id); assert_eq!(PreferredOperator::<T>::get(nominator), Some(operator_id)); } fn register_runtime<T: Config>() -> RuntimeId { let runtime_blob = include_bytes!("../res/evm_domain_test_runtime.compact.compressed.wasm").to_vec(); let runtime_id = NextRuntimeId::<T>::get(); let runtime_hash = T::Hashing::hash(&runtime_blob); assert_ok!(Domains::<T>::register_domain_runtime( RawOrigin::Root.into(), b"evm-domain".to_vec(), RuntimeType::Evm, runtime_blob, )); let runtime_obj = RuntimeRegistry::<T>::get(runtime_id).expect("runtime object must exist"); assert_eq!(runtime_obj.hash, runtime_hash); assert_eq!(NextRuntimeId::<T>::get(), runtime_id + 1); runtime_id } fn register_domain<T: Config>() -> DomainId { let creator = account("creator", 1, SEED); T::Currency::set_balance( &creator, T::DomainInstantiationDeposit::get() + T::Currency::minimum_balance(), ); let runtime_id = register_runtime::<T>(); let domain_id = NextDomainId::<T>::get(); let domain_config = DomainConfig { domain_name: b"evm-domain".to_vec(), runtime_id, max_block_size: 1024, max_block_weight: Weight::from_parts(1, 0), bundle_slot_probability: (1, 1), target_bundles_per_block: 10, }; assert_ok!(Domains::<T>::instantiate_domain( RawOrigin::Signed(creator.clone()).into(), domain_config.clone() )); let domain_obj = DomainRegistry::<T>::get(domain_id).expect("domain object must exist"); assert_eq!(domain_obj.domain_config, domain_config); assert_eq!(domain_obj.owner_account_id, creator); domain_id } fn register_helper_operator<T: Config>( domain_id: DomainId, minimum_nominator_stake: BalanceOf<T>, ) -> (T::AccountId, OperatorId) { let operator_account = account("operator", 1, SEED); T::Currency::set_balance( &operator_account, T::MinOperatorStake::get() + T::Currency::minimum_balance(), ); let operator_id = NextOperatorId::<T>::get(); let operator_config = OperatorConfig { signing_key: OperatorPublicKey::unchecked_from([1u8; 32]), minimum_nominator_stake, nomination_tax: Default::default(), }; assert_ok!(Domains::<T>::register_operator( RawOrigin::Signed(operator_account.clone()).into(), domain_id, T::MinOperatorStake::get(), operator_config.clone(), )); assert_eq!( OperatorIdOwner::<T>::get(operator_id), Some(operator_account.clone()) ); let operator = Operators::<T>::get(operator_id).expect("operator must exist"); assert_eq!(operator.signing_key, operator_config.signing_key); (operator_account, operator_id) } fn run_to_block<T: Config>(block_number: T::BlockNumber, parent_hash: T::Hash) { System::<T>::set_block_number(block_number); System::<T>::initialize(&block_number, &parent_hash, &Default::default()); <Domains<T> as Hooks<T::BlockNumber>>::on_initialize(block_number); System::<T>::finalize(); } // TODO: currently benchmark tests are running in one single function within the same `TExternalities` // (thus the storage state may be polluted by previously test) instead of one function per bench case, // wait for https://github.com/paritytech/substrate/issues/13738 to resolve this issue. impl_benchmark_test_suite!( Domains, crate::tests::new_test_ext_with_extensions(), crate::tests::Test ); }
use super::{User, DateTime}; #[derive(Debug)] pub struct IncomingMessage { pub text: String, pub time: DateTime, pub from: User } #[derive(Debug)] pub struct OutgoingMessage { pub text: String } impl OutgoingMessage { pub fn with_text(text: String) -> OutgoingMessage { OutgoingMessage { text: text } } }
use actix_web::{http::StatusCode, FromRequest, HttpResponse, Path}; use bigneon_api::controllers::orders; use bigneon_api::models::PathParameters; use bigneon_db::models::{DisplayOrder, OrderStatus, Roles}; use bigneon_db::schema; use chrono::prelude::*; use diesel; use diesel::prelude::*; use serde_json; use support; use support::database::TestDatabase; use support::test_request::TestRequest; use uuid::Uuid; #[test] pub fn show() { let database = TestDatabase::new(); let user = database.create_user().finish(); let mut order = database.create_order().for_user(&user).finish(); order .add_external_payment("test".to_string(), user.id, 1500, &database.connection) .unwrap(); assert_eq!(order.status, OrderStatus::Paid.to_string()); let test_request = TestRequest::create(); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = order.id; let auth_user = support::create_auth_user_from_user(&user, Roles::User, None, &database); let response: HttpResponse = orders::show((database.connection.into(), path, auth_user)).into(); assert_eq!(response.status(), StatusCode::OK); let body = support::unwrap_body_to_string(&response).unwrap(); let found_order: DisplayOrder = serde_json::from_str(&body).unwrap(); assert_eq!(found_order.id, order.id); } #[test] pub fn show_for_draft_returns_forbidden() { let database = TestDatabase::new(); let user = database.create_user().finish(); let order = database.create_order().for_user(&user).finish(); assert_eq!(order.status, OrderStatus::Draft.to_string()); let test_request = TestRequest::create(); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = order.id; let auth_user = support::create_auth_user_from_user(&user, Roles::User, None, &database); let response: HttpResponse = orders::show((database.connection.into(), path, auth_user)).into(); support::expects_forbidden(&response, Some("You do not have access to this order")); } #[test] pub fn index() { let database = TestDatabase::new(); let user = database.create_user().finish(); let mut order1 = database.create_order().for_user(&user).finish(); let date1 = NaiveDate::from_ymd(2017, 7, 8).and_hms(9, 10, 11); let date2 = NaiveDate::from_ymd(2017, 7, 9).and_hms(9, 10, 11); order1 .add_external_payment("test".to_string(), user.id, 1500, &database.connection) .unwrap(); order1 = diesel::update(&order1) .set(schema::orders::order_date.eq(date1)) .get_result(&*database.connection) .unwrap(); let mut order2 = database.create_order().for_user(&user).finish(); order2 .add_external_payment("test".to_string(), user.id, 500, &database.connection) .unwrap(); order2 = diesel::update(&order2) .set(schema::orders::order_date.eq(date2)) .get_result(&*database.connection) .unwrap(); let order3 = database.create_order().for_user(&user).finish(); assert_eq!(order1.status, OrderStatus::Paid.to_string()); assert_eq!(order2.status, OrderStatus::PartiallyPaid.to_string()); assert_eq!(order3.status, OrderStatus::Draft.to_string()); let auth_user = support::create_auth_user_from_user(&user, Roles::User, None, &database); let response: HttpResponse = orders::index((database.connection.clone().into(), auth_user)).into(); assert_eq!(response.status(), StatusCode::OK); let body = support::unwrap_body_to_string(&response).unwrap(); let orders: Vec<DisplayOrder> = serde_json::from_str(&body).unwrap(); assert_eq!(orders.len(), 2); let order_ids: Vec<Uuid> = orders.iter().map(|o| o.id).collect(); assert_eq!(order_ids, vec![order2.id, order1.id]); }
use std::fmt::{self, Debug}; use std::ops::RangeInclusive; use crate::std_ext::*; use crate::RangeInclusiveMap; #[derive(Clone)] /// A set whose items are stored as ranges bounded /// inclusively below and above `(start..=end)`. /// /// See [`RangeInclusiveMap`]'s documentation for more details. /// /// [`RangeInclusiveMap`]: struct.RangeInclusiveMap.html pub struct RangeInclusiveSet<T, StepFnsT = T> { rm: RangeInclusiveMap<T, (), StepFnsT>, } impl<T> Default for RangeInclusiveSet<T, T> where T: Ord + Clone + StepLite, { fn default() -> Self { Self::new() } } impl<T> RangeInclusiveSet<T, T> where T: Ord + Clone + StepLite, { /// Makes a new empty `RangeInclusiveSet`. pub fn new() -> Self { Self::new_with_step_fns() } } impl<T, StepFnsT> RangeInclusiveSet<T, StepFnsT> where T: Ord + Clone, StepFnsT: StepFns<T>, { /// Makes a new empty `RangeInclusiveSet`, specifying successor and /// predecessor functions defined separately from `T` itself. /// /// This is useful as a workaround for Rust's "orphan rules", /// which prevent you from implementing `StepLite` for `T` if `T` /// is a foreign type. /// /// **NOTE:** This will likely be deprecated and then eventually /// removed once the standard library's [Step](std::iter::Step) /// trait is stabilised, as most crates will then likely implement [Step](std::iter::Step) /// for their types where appropriate. /// /// See [this issue](https://github.com/rust-lang/rust/issues/42168) /// for details about that stabilization process. pub fn new_with_step_fns() -> Self { Self { rm: RangeInclusiveMap::new_with_step_fns(), } } /// Returns a reference to the range covering the given key, if any. pub fn get(&self, value: &T) -> Option<&RangeInclusive<T>> { self.rm.get_key_value(value).map(|(range, _)| range) } /// Returns `true` if any range in the set covers the specified value. pub fn contains(&self, value: &T) -> bool { self.rm.contains_key(value) } /// Gets an ordered iterator over all ranges, /// ordered by range. pub fn iter(&self) -> impl Iterator<Item = &RangeInclusive<T>> { self.rm.iter().map(|(range, _v)| range) } /// Insert a range into the set. /// /// If the inserted range either overlaps or is immediately adjacent /// any existing range, then the ranges will be coalesced into /// a single contiguous range. /// /// # Panics /// /// Panics if range `start > end`. pub fn insert(&mut self, range: RangeInclusive<T>) { self.rm.insert(range, ()); } /// Removes a range from the set, if all or any of it was present. /// /// If the range to be removed _partially_ overlaps any ranges /// in the set, then those ranges will be contracted to no /// longer cover the removed range. /// /// # Panics /// /// Panics if range `start > end`. pub fn remove(&mut self, range: RangeInclusive<T>) { self.rm.remove(range); } /// Gets an iterator over all the maximally-sized ranges /// contained in `outer_range` that are not covered by /// any range stored in the set. /// /// The iterator element type is `RangeInclusive<T>`. /// /// NOTE: Calling `gaps` eagerly finds the first gap, /// even if the iterator is never consumed. pub fn gaps<'a>(&'a self, outer_range: &'a RangeInclusive<T>) -> Gaps<'a, T, StepFnsT> { Gaps { inner: self.rm.gaps(outer_range), } } } // We can't just derive this automatically, because that would // expose irrelevant (and private) implementation details. // Instead implement it in the same way that the underlying BTreeSet does. impl<T: Debug> Debug for RangeInclusiveSet<T> where T: Ord + Clone + StepLite, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_set().entries(self.iter()).finish() } } pub struct Gaps<'a, T, StepFnsT> { inner: crate::inclusive_map::Gaps<'a, T, (), StepFnsT>, } // `Gaps` is always fused. (See definition of `next` below.) impl<'a, T, StepFnsT> std::iter::FusedIterator for Gaps<'a, T, StepFnsT> where T: Ord + Clone, StepFnsT: StepFns<T>, { } impl<'a, T, StepFnsT> Iterator for Gaps<'a, T, StepFnsT> where T: Ord + Clone, StepFnsT: StepFns<T>, { type Item = RangeInclusive<T>; fn next(&mut self) -> Option<Self::Item> { self.inner.next() } } #[cfg(test)] mod tests { use super::*; trait RangeInclusiveSetExt<T> { fn to_vec(&self) -> Vec<RangeInclusive<T>>; } impl<T> RangeInclusiveSetExt<T> for RangeInclusiveSet<T> where T: Ord + Clone + StepLite, { fn to_vec(&self) -> Vec<RangeInclusive<T>> { self.iter().cloned().collect() } } #[test] fn empty_set_is_empty() { let range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new(); assert_eq!(range_set.to_vec(), vec![]); } #[test] fn insert_into_empty_map() { let mut range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new(); range_set.insert(0..=50); assert_eq!(range_set.to_vec(), vec![0..=50]); } #[test] fn remove_partially_overlapping() { let mut range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new(); range_set.insert(0..=50); range_set.remove(25..=75); assert_eq!(range_set.to_vec(), vec![0..=24]); } #[test] fn gaps_between_items_floating_inside_outer_range() { let mut range_set: RangeInclusiveSet<u32> = RangeInclusiveSet::new(); // 0 1 2 3 4 5 6 7 8 9 // ◌ ◌ ◌ ◌ ◌ ●-● ◌ ◌ ◌ range_set.insert(5..=6); // 0 1 2 3 4 5 6 7 8 9 // ◌ ◌ ●-● ◌ ◌ ◌ ◌ ◌ ◌ range_set.insert(2..=3); // 0 1 2 3 4 5 6 7 8 9 // ◌ ◆-------------◆ ◌ let outer_range = 1..=8; let mut gaps = range_set.gaps(&outer_range); // Should yield gaps at start, between items, // and at end. assert_eq!(gaps.next(), Some(1..=1)); assert_eq!(gaps.next(), Some(4..=4)); assert_eq!(gaps.next(), Some(7..=8)); assert_eq!(gaps.next(), None); // Gaps iterator should be fused. assert_eq!(gaps.next(), None); assert_eq!(gaps.next(), None); } /// /// impl Debug /// #[test] fn set_debug_repr_looks_right() { let mut set: RangeInclusiveSet<u32> = RangeInclusiveSet::new(); // Empty assert_eq!(format!("{:?}", set), "{}"); // One entry set.insert(2..=5); assert_eq!(format!("{:?}", set), "{2..=5}"); // Many entries set.insert(7..=8); set.insert(10..=11); assert_eq!(format!("{:?}", set), "{2..=5, 7..=8, 10..=11}"); } }
mod app; mod input; pub mod image; pub mod ui; pub use app::{App, Focus, Route}; pub use input::Input;
//! ITP1_7_Cの回答 //! [https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_7_C](https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_7_C) use std::io::BufRead; #[allow(dead_code)] pub fn main() { loop { if let Some(result) = read_result(std::io::stdin().lock()) { for row in result.rows { for (i, n) in row.iter().enumerate() { print_number(i, *n); } println!(); } for (i, n) in result.totals.iter().enumerate() { print_number(i, *n); } println!(); continue; } return; } } fn print_number(i: usize, n: i32) { if i > 0 { print!(" "); } print!("{}", n); } /// 回答。 #[derive(Debug, Eq, PartialEq)] struct ResultSet { rows: Vec<Vec<i32>>, totals: Vec<i32>, } impl ResultSet { fn new(row_count: usize, col_count: usize) -> Self { let rows = vec![vec![0; col_count + 1]; row_count]; ResultSet { rows, totals: vec![0; col_count + 1] } } fn set_row(&mut self, row_index: usize, v: &Vec<i32>) { let mut sum = 0; for i in 0..v.len() { let v_i = v[i]; sum += v_i; self.totals[i] += v_i; self.rows[row_index][i] = v_i; } self.totals[v.len()] += sum; self.rows[row_index][v.len()] = sum; } } fn read_result<T: BufRead>(mut reader: T) -> Option<ResultSet> { if let Some((row_count, col_count)) = read_size(&mut reader) { let mut result = ResultSet::new(row_count, col_count); for row_index in 0..row_count { let row = read_row(&mut reader); result.set_row(row_index, &row); } return Some(result); } None } fn read_row<T: BufRead>(mut reader: T) -> Vec<i32> { let mut line = String::new(); if let Ok(_) = reader.read_line(&mut line) { return line.trim().split(' ').map(|x| x.parse().unwrap()).collect(); } return vec![0; 0]; } fn read_size<T: BufRead>(mut reader: T) -> Option<(usize, usize)> { let mut line = String::new(); if let Err(_) = reader.read_line(&mut line) { return None; } let fields = line.trim().split(' ').map(|x| x.parse::<usize>()); let mut numbers = Vec::new(); for field in fields { let n = match field { Ok(n) => n, Err(_) => return None }; numbers.push(n); } if numbers.len() != 2 { return None; } Some((numbers[0], numbers[1])) } #[cfg(test)] mod test { use std::io::Cursor; use super::*; #[test] fn test_result_set_new() { let r = ResultSet::new(4, 5); assert_eq!(4, r.rows.len()); assert_eq!(6, r.totals.len()); assert!(r.rows.iter().all(|x| x.len() == 6)); } #[test] fn test_result_set_add_row() { let mut rs = ResultSet::new(2, 3); rs.set_row(0, &vec![1, 2, 3]); rs.set_row(1, &vec![4, 5, 6]); assert_eq!(vec![1, 2, 3, 6], rs.rows[0]); assert_eq!(vec![4, 5, 6, 15], rs.rows[1]); assert_eq!(vec![5, 7, 9, 21], rs.totals); } #[test] fn test_read_result() { let input = Cursor::new(b"4 5\n1 1 3 4 5\n2 2 2 4 5\n3 3 0 1 1\n2 3 4 4 6\n"); let result = read_result(input); assert_ne!(None, result); let rs = result.unwrap(); assert_eq!(vec![1, 1, 3, 4, 5, 14], rs.rows[0]); assert_eq!(vec![2, 2, 2, 4, 5, 15], rs.rows[1]); assert_eq!(vec![3, 3, 0, 1, 1, 8], rs.rows[2]); assert_eq!(vec![2, 3, 4, 4, 6, 19], rs.rows[3]); assert_eq!(vec![8, 9, 9, 13, 17, 56], rs.totals); } }
use arkecosystem_client::api::models::shared::Meta; use serde_json::Value; pub fn assert_meta(actual: Meta, expected: &Value) { if actual.count.is_some() { assert_eq!( actual.count.unwrap(), expected["count"].as_u64().unwrap() as u32 ); } if actual.page_count.is_some() { assert_eq!( actual.page_count.unwrap(), expected["pageCount"].as_u64().unwrap() as u32 ); } if actual.total_count.is_some() { assert_eq!( actual.total_count.unwrap(), expected["totalCount"].as_u64().unwrap() as u32 ); } if actual.next.is_some() { assert_eq!(actual.next.unwrap(), expected["next"].as_str().unwrap()); } if actual.previous.is_some() { assert_eq!( actual.previous.unwrap(), expected["previous"].as_str().unwrap() ); } if actual.self_url.is_some() { assert_eq!(actual.self_url.unwrap(), expected["self"].as_str().unwrap()); } if actual.first.is_some() { assert_eq!(actual.first.unwrap(), expected["first"].as_str().unwrap()); } if actual.last.is_some() { assert_eq!(actual.last.unwrap(), expected["last"].as_str().unwrap()); } if actual.days.is_some() { assert_eq!( actual.days.unwrap(), expected["days"].as_u64().unwrap() as u32 ); } }
use std::fmt; type Result<T> = std::result::Result<T, String>; #[derive(Debug)] struct Stack<T>(Vec<T>); impl<T> Stack<T> { fn new() -> Self { Self(Vec::new()) } fn is_empty(&self) -> bool { self.0.is_empty() } fn len(&self) -> usize { self.0.len() } fn pop(&mut self) -> Option<T> { self.0.pop() } fn push(&mut self, value: T) { self.0.push(value) } } #[derive(Clone, Debug, PartialEq)] enum Value { Boolean(bool), Integer(i32), NativeFn(fn(Vec<Value>) -> Result<Value>), Null, } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Boolean(false) => write!(f, "#f"), Self::Boolean(true) => write!(f, "#t"), Self::Integer(value) => write!(f, "{}", value), Self::NativeFn(_) => write!(f, "#<native function>"), Self::Null => write!(f, "'()"), } } } impl Value { const FALSE: Self = Self::Boolean(false); const NULL: Self = Self::Null; const TRUE: Self = Self::Boolean(true); fn is_falsy(&self) -> bool { match self { Value::Boolean(false) => true, _ => false, } } fn is_null(&self) -> bool { match self { Value::Null => true, _ => false, } } fn is_truthy(&self) -> bool { match self { Value::Boolean(false) => false, _ => true, } } } impl From<bool> for Value { fn from(boolean: bool) -> Self { if boolean { Self::TRUE } else { Self::FALSE } } } #[derive(Debug)] struct StackFrame { base_ptr: usize, return_address: usize, } impl StackFrame { fn new(base_ptr: usize, return_address: usize) -> Self { Self { base_ptr, return_address, } } } enum Bytecode { Call(usize), Boolean(bool), Div, Eq, Gt, If(usize), Integer(i32), Lt, Mul, Neg, Null, Rem, Return, Sub, } #[derive(Debug)] struct Vm { instruction_ptr: usize, call_stack: Stack<StackFrame>, operand_stack: Stack<Value>, } impl Vm { fn new() -> Self { Self { instruction_ptr: 0, call_stack: Stack::new(), operand_stack: Stack::new(), } } fn execute(&mut self, bytecodes: Vec<Bytecode>) -> Result<()> { loop { dbg!(&self); match bytecodes[self.instruction_ptr] { Bytecode::Boolean(immediate) => self.operand_stack.push(immediate.into()), Bytecode::Call(addr) => { let frame = StackFrame::new(self.operand_stack.len(), self.instruction_ptr + 1); self.call_stack.push(frame); self.instruction_ptr = addr; continue; } Bytecode::Div => { let lhs = match self.operand_stack.pop() { Some(Value::Integer(lhs)) => lhs, Some(value) => return Err(format!("Div: invalid first operand on the stack: expected integer, found {}", value)), None => return Err("Div: invalid first operand on the stack: expected integer, found empty stack".to_owned()), }; let rhs = match self.operand_stack.pop() { Some(Value::Integer(rhs)) => rhs, Some(value) => return Err(format!("Div: invalid second operand on the stack: expected integer, found {}", value)), None => return Err("Div: invalid second operand on the stack: expected integer, found empty stack".to_owned()), }; if rhs != 0 { self.operand_stack.push(Value::Integer(lhs / rhs)); } else { return Err("Div: division by zero".to_owned()); } } Bytecode::Eq => { let lhs = match self.operand_stack.pop() { Some(Value::Integer(lhs)) => lhs, Some(value) => return Err(format!("Eq: invalid first operand on the stack: expected integer, found {}", value)), None => return Err("Eq: invalid first operand on the stack: expected integer, found empty stack".to_owned()), }; let rhs = match self.operand_stack.pop() { Some(Value::Integer(rhs)) => rhs, Some(value) => return Err(format!("Eq: invalid second operand on the stack: expected integer, found {}", value)), None => return Err("Eq: invalid second operand on the stack: expected integer, found empty stack".to_owned()), }; self.operand_stack.push(Value::Boolean(lhs == rhs)); } Bytecode::Gt => { let lhs = match self.operand_stack.pop() { Some(Value::Integer(lhs)) => lhs, Some(value) => return Err(format!("Gt: invalid first operand on the stack: expected integer, found {}", value)), None => return Err("Gt: invalid first operand on the stack: expected integer, found empty stack".to_owned()), }; let rhs = match self.operand_stack.pop() { Some(Value::Integer(rhs)) => rhs, Some(value) => return Err(format!("Gt: invalid second operand on the stack: expected integer, found {}", value)), None => return Err("Gt: invalid second operand on the stack: expected integer, found empty stack".to_owned()), }; self.operand_stack.push(Value::Boolean(lhs > rhs)); } Bytecode::If(offset) => match self.operand_stack.pop() { Some(value) => { if value.is_falsy() { self.instruction_ptr += offset; continue; } } None => return Err("If: expected 1 operand on the stack, found 0".to_owned()), }, Bytecode::Integer(immediate) => self.operand_stack.push(Value::Integer(immediate)), Bytecode::Lt => { let lhs = match self.operand_stack.pop() { Some(Value::Integer(lhs)) => lhs, Some(value) => return Err(format!("Lt: invalid first operand on the stack: expected integer, found {}", value)), None => return Err("Lt: invalid first operand on the stack: expected integer, found empty stack".to_owned()), }; let rhs = match self.operand_stack.pop() { Some(Value::Integer(rhs)) => rhs, Some(value) => return Err(format!("Lt: invalid second operand on the stack: expected integer, found {}", value)), None => return Err("Lt: invalid second operand on the stack: expected integer, found empty stack".to_owned()), }; self.operand_stack.push(Value::Boolean(lhs < rhs)); } Bytecode::Mul => { let lhs = match self.operand_stack.pop() { Some(Value::Integer(lhs)) => lhs, Some(value) => return Err(format!("Mul: invalid first operand on the stack: expected integer, found {}", value)), None => return Err("Mul: invalid first operand on the stack: expected integer, found empty stack".to_owned()), }; let rhs = match self.operand_stack.pop() { Some(Value::Integer(rhs)) => rhs, Some(value) => return Err(format!("Mul: invalid second operand on the stack: expected integer, found {}", value)), None => return Err("Mul: invalid second operand on the stack: expected integer, found empty stack".to_owned()), }; self.operand_stack.push(Value::Integer(lhs * rhs)); } Bytecode::Neg => match self.operand_stack.pop() { Some(Value::Integer(n)) => self.operand_stack.push(Value::Integer(-n)), Some(value) => { return Err(format!( "Neg: invalid operand on the stack: expected integer, found {}", value )) } None => return Err( "Neg: invalid operand on the stack: expected integer, found empty stack" .to_owned(), ), }, Bytecode::Null => self.operand_stack.push(Value::Null), Bytecode::Rem => { let lhs = match self.operand_stack.pop() { Some(Value::Integer(lhs)) => lhs, Some(value) => return Err(format!("Mod: invalid first operand on the stack: expected integer, found {}", value)), None => return Err("Mod: invalid first operand on the stack: expected integer, found empty stack".to_owned()), }; let rhs = match self.operand_stack.pop() { Some(Value::Integer(rhs)) => rhs, Some(value) => return Err(format!("Mod: invalid second operand on the stack: expected integer, found {}", value)), None => return Err("Mod: invalid second operand on the stack: expected integer, found empty stack".to_owned()), }; if rhs != 0 { self.operand_stack.push(Value::Integer(lhs % rhs)); } else { return Err("Rem: division by zero".to_owned()); } } Bytecode::Return => match self.call_stack.pop() { Some(frame) => { self.instruction_ptr = frame.return_address; continue; } None => return Ok(()), }, Bytecode::Sub => { let lhs = match self.operand_stack.pop() { Some(Value::Integer(lhs)) => lhs, Some(value) => return Err(format!("Sub: invalid first operand on the stack: expected integer, found {}", value)), None => return Err("Sub: invalid first operand on the stack: expected integer, found empty stack".to_owned()), }; let rhs = match self.operand_stack.pop() { Some(Value::Integer(rhs)) => rhs, Some(value) => return Err(format!("Sub: invalid second operand on the stack: expected integer, found {}", value)), None => return Err("Sub: invalid second operand on the stack: expected integer, found empty stack".to_owned()), }; self.operand_stack.push(Value::Integer(lhs - rhs)); } } self.instruction_ptr += 1; } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_return() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 0); assert!(vm.call_stack.is_empty()); assert!(vm.operand_stack.is_empty()); } #[test] fn test_integer() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(0), Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 1); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(0))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(1), Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 1); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(1))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(-1), Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 1); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(-1))); assert!(vm.operand_stack.is_empty()); } #[test] fn test_boolean() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Boolean(false), Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 1); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Boolean(false))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Boolean(true), Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 1); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Boolean(true))); assert!(vm.operand_stack.is_empty()); } #[test] fn test_null() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Null, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 1); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::NULL)); assert!(vm.operand_stack.is_empty()); } #[test] fn test_call() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Call(2), Bytecode::Return, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 1); assert!(vm.call_stack.is_empty()); assert!(vm.operand_stack.is_empty()); } #[test] fn test_div() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(2), Bytecode::Integer(4), Bytecode::Div, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(2))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(0), Bytecode::Integer(1), Bytecode::Div, Bytecode::Return, ]).unwrap_err(); assert_eq!(vm.instruction_ptr, 2); assert!(vm.call_stack.is_empty()); assert!(vm.operand_stack.is_empty()); } #[test] fn test_eq() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(1), Bytecode::Integer(1), Bytecode::Eq, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Boolean(true))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(0), Bytecode::Integer(1), Bytecode::Eq, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Boolean(false))); assert!(vm.operand_stack.is_empty()); } #[test] fn test_gt() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(0), Bytecode::Integer(1), Bytecode::Gt, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Boolean(true))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(1), Bytecode::Integer(1), Bytecode::Gt, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Boolean(false))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(1), Bytecode::Integer(0), Bytecode::Gt, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Boolean(false))); assert!(vm.operand_stack.is_empty()); } #[test] fn test_if() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Boolean(true), Bytecode::If(3), Bytecode::Boolean(true), Bytecode::Return, Bytecode::Boolean(false), Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Boolean(true))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Boolean(false), Bytecode::If(3), Bytecode::Boolean(true), Bytecode::Return, Bytecode::Boolean(false), Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 5); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Boolean(false))); assert!(vm.operand_stack.is_empty()); } #[test] fn test_lt() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(0), Bytecode::Integer(1), Bytecode::Lt, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Boolean(false))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(1), Bytecode::Integer(1), Bytecode::Lt, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Boolean(false))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(1), Bytecode::Integer(0), Bytecode::Lt, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Boolean(true))); assert!(vm.operand_stack.is_empty()); } #[test] fn test_mul() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(2), Bytecode::Integer(4), Bytecode::Mul, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(8))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(0), Bytecode::Integer(1), Bytecode::Mul, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(0))); assert!(vm.operand_stack.is_empty()); } #[test] fn test_neg() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(0), Bytecode::Neg, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 2); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(0))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(1), Bytecode::Neg, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 2); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(-1))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(-1), Bytecode::Neg, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 2); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(1))); assert!(vm.operand_stack.is_empty()); } #[test] fn test_rem() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(3), Bytecode::Integer(10), Bytecode::Rem, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(1))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(-3), Bytecode::Integer(10), Bytecode::Rem, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(1))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(3), Bytecode::Integer(-10), Bytecode::Rem, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(-1))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(-3), Bytecode::Integer(-10), Bytecode::Rem, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(-1))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(0), Bytecode::Integer(1), Bytecode::Rem, Bytecode::Return, ]).unwrap_err(); assert_eq!(vm.instruction_ptr, 2); assert!(vm.call_stack.is_empty()); assert!(vm.operand_stack.is_empty()); } #[test] fn test_sub() { let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(2), Bytecode::Integer(4), Bytecode::Sub, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(2))); assert!(vm.operand_stack.is_empty()); let mut vm = Vm::new(); #[rustfmt::skip] vm.execute(vec![ Bytecode::Integer(0), Bytecode::Integer(1), Bytecode::Sub, Bytecode::Return, ]).unwrap(); assert_eq!(vm.instruction_ptr, 3); assert!(vm.call_stack.is_empty()); assert_eq!(vm.operand_stack.pop(), Some(Value::Integer(1))); assert!(vm.operand_stack.is_empty()); } }
#[macro_use] mod macros; mod float; mod int;
pub use math::aabb::Aabb; pub use math::camera::Camera; pub use math::int_aabb::IntAabb; pub use math::rot::Rot; pub mod aabb; pub mod camera; pub mod int_aabb; pub mod matrices; pub mod raw; pub mod rot;
// Detect AES in ECB mode // In this file (8.txt) are a bunch of hex-encoded ciphertexts. // One of them has been encrypted with ECB. // Detect it. // Remember that the problem with ECB is that it is stateless and // deterministic; the same 16 byte plaintext block will always // produce the same 16 byte ciphertext. use std::collections::HashSet; #[cfg(not(test))] use std::env; #[cfg(not(test))] use std::io::BufReader; #[cfg(not(test))] use std::fs::File; #[cfg(not(test))] use std::path::Path; #[cfg(not(test))] use std::io::prelude::*; #[cfg(not(test))] fn main() { println!("Finding ECB..."); if env::args().count() < 2 { panic!("Must pass a file to detect") } let arg = match env::args().nth(1) { Some(s) => s, None => panic!("No input argument given") }; let path = Path::new(&arg); let file = BufReader::new(File::open(&path).unwrap()); let lines: Vec<String> = file.lines() .map(|x| x.unwrap().trim().to_string()) .collect(); for line in lines { let duplicates = detect_ecb_in_line(&line); if duplicates.len() > 0 { for block in duplicates { println!("duplicate block: {:?}", block); } println!("in line: {:?}", line); } } } fn detect_ecb_in_line(line: &str) -> Vec<String> { let blocks = line.len() / 32; let mut block_set = HashSet::new(); let mut duplicates = vec!(); for index in 0..blocks - 1 { let block = line[index * 32..(index + 1) * 32].to_string(); if block_set.contains(&block) { duplicates.push(block); } else { block_set.insert(block); } } duplicates } #[cfg(test)] mod set1challenge8 { #[test] fn detect_ecb_in_line() { let line = "d880619740a8a19b7840a8a31c810a3d08649af70dc06f4fd5d2d69c744cd283e2dd052f6b641dbf9d11b0348542bb5708649af70dc06f4fd5d2d69c744cd2839475c9dfdbc1d46597949d9c7e82bf5a08649af70dc06f4fd5d2d69c744cd28397a93eab8d6aecd566489154789a6b0308649af70dc06f4fd5d2d69c744cd283d403180c98c8f6db1f2a3f9c4040deb0ab51b29933f2c123c58386b06fba186a"; let duplicates = super::detect_ecb_in_line(&line); assert_eq!(duplicates.len(), 3); assert_eq!(duplicates[0], "08649af70dc06f4fd5d2d69c744cd283"); assert_eq!(duplicates[1], "08649af70dc06f4fd5d2d69c744cd283"); assert_eq!(duplicates[2], "08649af70dc06f4fd5d2d69c744cd283"); } #[test] fn dont_detect_ecb_in_line() { let line = "b148a13d9a04ba6ef17afb0e25a6c91a454ec0eded513a567a9824dd3cd16770f4c1dae48854c2cf557139640c1cd121cac974f74f7001aa4927f6bdb4e0fa73676855df520e2af6ac785a420e43e829fa4e77e5de386d58404d42aa57bf56467f98322275df9f1a72fbb03fa8ea8b84356bbcd7159c59ef283a1aec240ef5d25df6e2aaaea36826beb03b0826d4abc8f22837812dafe6c9623517471fc653b9"; let duplicates = super::detect_ecb_in_line(&line); assert_eq!(duplicates.len(), 0); } }
let (mut a, mut b) = (1, 2); std::mem::swap(&mut a, &mut b); println!("{:?}", (a, b));
extern crate graphics; extern crate piston_window; extern crate image; extern crate opengl_graphics; extern crate piston; extern crate squish; extern crate xnb; use graphics::Image; use image::RgbaImage; use opengl_graphics::{GlGraphics, OpenGL, Texture, TextureSettings, Filter, ImageSize}; use piston_window::{PistonWindow, WindowSettings, OpenGL as PistonOpenGL}; use piston::input::*; use std::collections::HashMap; use std::env; use std::fs::File; use std::path::Path; use squish::{decompress_image, CompressType}; use xnb::{XNB, SurfaceFormat, Texture2d, Dictionary}; use xnb::tide::{TileSheet, Layer, Map, PropertyValue, PropertyParse}; const SCALE: f64 = 1.5; type SVMap = Map<MapProps, TilesetProps, LayerProps, TileProps>; struct LayerProps; impl PropertyParse for LayerProps { fn parse(_props: Vec<(String, PropertyValue)>) -> Self { LayerProps } } struct MapProps; impl PropertyParse for MapProps { fn parse(_props: Vec<(String, PropertyValue)>) -> Self { MapProps } } struct TileProps { passable: Option<bool>, } impl PropertyParse for TileProps { fn parse(props: Vec<(String, PropertyValue)>) -> Self { let mut passable = None; for (k, v) in props { match (k.as_ref(), v) { ("Passable", PropertyValue::String(b)) => { println!("passable is {:?}", b); passable = Some(b == "T") } ("Passable", v) => println!("passable: {:?}", v), (k, v) => println!("tile: {} = {:?}", k, v), } } Self { passable: passable } } } enum TileType { Grass, Stone, Dirt, Wood, } struct TilesetProps { passable: Vec<(u32, bool)>, water: Vec<(u32, bool)>, types: Vec<(u32, TileType)>, } impl TilesetProps { fn tile_is_passable(&self, idx: u32) -> Option<bool> { self.passable.iter().find(|&&(i, _v)| i == idx).map(|&(_, v)| v) } } impl PropertyParse for TilesetProps { fn parse(_props: Vec<(String, PropertyValue)>) -> Self { let mut passable = vec![]; let mut water = vec![]; let mut types = vec![]; for (k, v) in _props { let mut parts = k.split('@'); let _ = parts.next(); let category = parts.next().unwrap(); if category != "TileIndex" { continue; } let idx = parts.next().unwrap().parse().unwrap(); let name = parts.next().unwrap(); match (name, v) { ("Spawnable", _) => (), ("Diggable", _) => (), ("PathType", _) => (), ("Shadow", _) => (), ("Passable", PropertyValue::String(ref s)) => passable.push((idx, s == "T")), ("Water", PropertyValue::String(ref s)) => water.push((idx, s == "T")), ("Type", PropertyValue::String(ref s)) => types.push((idx, match s.as_ref() { "Dirt" => TileType::Dirt, "Stone" => TileType::Stone, "Grass" => TileType::Grass, "Wood" => TileType::Wood, s => panic!("unexpected tile type: {}", s), })), (s, v) => panic!("unexpected property {}: {:?}", s, v), } } TilesetProps { passable: passable, water: water, types: types, } } } struct ResolvedTile<'a> { texture: &'a Texture, tilesheet: &'a TileSheet<TilesetProps>, } struct Character { _name: String, texture: TextureTileInfo, _index: u32, x: i32, y: i32, offset_x: f64, offset_y: f64, dir: PlayerDir, } pub struct App { gl: GlGraphics, view_x: i32, view_y: i32, view_w: u32, view_h: u32, ticks: u32, d_pressed: bool, a_pressed: bool, w_pressed: bool, s_pressed: bool, update_last_move: bool, } struct Tile<'a> { sheet: &'a TileSheet<TilesetProps>, index: u32, } fn image_for_tile(tile: &Tile, pos: (i32, i32), view: (i32, i32)) -> Image { let num_h_tiles = tile.sheet.sheet_size.0; let tile_w = tile.sheet.tile_size.0; let tile_h = tile.sheet.tile_size.1; image_for_tile_reference(num_h_tiles, (tile_w, tile_h), tile.index, 0, pos, (0, 0), view, false) } #[derive(Copy, Clone, PartialEq)] enum PlayerDir { Down = 0, Right = 1, Up = 2, Left = 3, } fn image_for_texture(texture: &TextureTileInfo, pos: (i32, i32), view: (i32, i32), offset: (i32, i32), anim: Option<(u32, u32)>, dir: PlayerDir) -> Image { let num_h_tiles = texture.0.get_width() / (texture.2).0; let offset = ((texture.3).0 + offset.0, (texture.3).1 + offset.1); let base = texture.4[dir as usize].unwrap_or(0); let flip = dir == PlayerDir::Left && texture.4[PlayerDir::Left as usize] == texture.4[PlayerDir::Right as usize]; let anim_idx = anim.map_or(0, |a| a.0 / 150 % a.1); image_for_tile_reference(num_h_tiles, texture.2.clone(), texture.1 + anim_idx, base, pos, offset, view, flip) } fn image_for_tile_reference(num_h_tiles: u32, (tile_w, tile_h): (u32, u32), index: u32, index_y_offset: u32, (x, y): (i32, i32), (off_x, off_y): (i32, i32), (view_x, view_y): (i32, i32), flip_h: bool) -> Image { let src_x = index % num_h_tiles * tile_w; let src_y = (index / num_h_tiles + index_y_offset) * tile_h; let src_rect = if flip_h { [src_x as i32 + tile_w as i32, src_y as i32, -(tile_w as i32), tile_h as i32] } else { [src_x as i32, src_y as i32, tile_w as i32, tile_h as i32] }; Image::new() .src_rect([src_rect[0] as f64, src_rect[1] as f64, src_rect[2] as f64, src_rect[3] as f64]) .rect([(x as i32 * 16) as f64 + off_x as f64 - view_x as f64, (y as i32 * 16) as f64 + off_y as f64 - view_y as f64, tile_w as f64, tile_h as f64]) } type TextureTileInfo = (Texture, u32, (u32, u32), (i32, i32), [Option<u32>; 4]); struct Player { base: TextureTileInfo, bottom: TextureTileInfo, arms: TextureTileInfo, pants: TextureTileInfo, hairstyle: TextureTileInfo, hat: Option<TextureTileInfo>, shirt: TextureTileInfo, accessory: TextureTileInfo, x: i32, y: i32, offset_x: f64, offset_y: f64, last_move_start: Option<u32>, dir: PlayerDir, } impl Player { fn adjusted_pos(&self, delta_x: f64, delta_y: f64) -> (i32, i32) { let x = self.x + (if delta_x < 0. && self.offset_x + delta_x < -8. { -1 } else if delta_x > 0. && self.offset_x + delta_x > 8. { 1 } else { 0 }); let y = self.y + (if delta_y < 0. && self.offset_y + delta_y < -8. { -1 } else if delta_y > 0. && self.offset_y + delta_y > 8. { 1 } else { 0 }); (x, y) } fn move_horiz(&mut self, delta: f64, clamp_to_current_pos: bool) { self.offset_x += delta; if delta < 0. && self.offset_x < -8. { if clamp_to_current_pos { self.offset_x = -7.99; } else { self.offset_x = 8.; self.x -= 1; } } else if delta > 0. && self.offset_x > 8. { if clamp_to_current_pos { self.offset_x = 7.99; } else { self.offset_x = -8.; self.x += 1; } } } fn move_vert(&mut self, delta: f64, clamp_to_current_pos: bool) { self.offset_y += delta; if delta < 0. && self.offset_y < -8. { if clamp_to_current_pos { self.offset_y = -7.99; } else { self.offset_y = 8.; self.y -= 1; } } else if delta > 0. && self.offset_y > 8. { if clamp_to_current_pos { self.offset_y = 7.99; } else { self.offset_y = -8.; self.y += 1; } } } } impl App { fn render(&mut self, args: &RenderArgs, player: &Player, characters: &[Character], layers: &[Layer<LayerProps, TileProps>], resolved_layers: &[Vec<ResolvedTile>]) { use graphics::*; const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0]; let view_x = self.view_x; let view_y = self.view_y; self.view_w = args.viewport().window_size[0]; self.view_h = args.viewport().window_size[1]; let view_w = args.viewport().window_size[0] as i32 / 16 + view_x / 16; let view_h = args.viewport().window_size[1] as i32 / 16 + view_y / 16; let ticks = self.ticks; fn draw_character(character: &Character, transform: [[f64; 3]; 2], gl: &mut GlGraphics, (view_x, view_y): (i32, i32), (_view_w, _view_h): (i32, i32)) { if character.x < 0 || character.y < 0 { return; } let image = image_for_texture(&character.texture, (character.x, character.y), (view_x, view_y), (character.offset_x as i32, character.offset_y as i32), None, character.dir); image.draw(&character.texture.0, &Default::default(), transform, gl); } fn draw_layer(layer: &Layer<LayerProps, TileProps>, resolved_tiles: &[ResolvedTile], transform: [[f64; 3]; 2], gl: &mut GlGraphics, ticks: u32, (view_x, view_y): (i32, i32), (view_w, view_h): (i32, i32), player: Option<&Player>) { if !layer.visible || layer.id == "Paths" { return; } let mut last_pos = None; for (base_tile, resolved) in layer.tiles.iter().zip(resolved_tiles) { let tile = Tile { sheet: resolved.tilesheet, index: base_tile.get_index(ticks), }; let (x, y) = base_tile.get_pos(); let (x, y) = (x as i32, y as i32); if let Some(player) = player { if y == player.y + 1 && x >= player.x && last_pos.map_or(false, |(tx, _)| tx < player.x) { draw_player(player, gl, transform.clone(), (view_x, view_y), ticks); } } last_pos = Some((x, y)); if x < view_x / 16 || x > view_w || y < view_y / 16 || y > view_h { continue; } let image = image_for_tile(&tile, (x, y), (view_x, view_y)); image.draw(resolved.texture, &Default::default(), transform, gl); } } fn draw_player( player: &Player, gl: &mut GlGraphics, transform: [[f64; 3]; 2], view: (i32, i32), ticks: u32, ) { let pos = (player.x as i32, player.y as i32); let offset = (player.offset_x as i32, player.offset_y as i32); let player_ticks = match player.last_move_start { Some(start) => ticks - start, None => 0, }; let three_frame = Some((player_ticks, 3)); // Body let image = image_for_texture(&player.base, pos, view, offset, three_frame, player.dir); image.draw(&player.base.0, &Default::default(), transform, gl); let image = image_for_texture(&player.bottom, pos, view, offset, three_frame, player.dir); image.draw(&player.bottom.0, &Default::default(), transform, gl); // Hair let image = image_for_texture(&player.hairstyle, pos, view, offset, None, player.dir); image.draw(&player.hairstyle.0, &Default::default(), transform, gl); // Hat if let Some(ref hat) = player.hat { let image = image_for_texture(hat, pos, view, offset, None, player.dir); image.draw(&hat.0, &Default::default(), transform, gl); } // Arms let image = image_for_texture(&player.arms, pos, view, offset, three_frame, player.dir); image.draw(&player.arms.0, &Default::default(), transform, gl); // Pants let image = image_for_texture(&player.pants, pos, view, offset, three_frame, player.dir); image.draw(&player.pants.0, &Default::default(), transform, gl); // Shirt let image = image_for_texture(&player.shirt, pos, view, offset, None, player.dir); image.draw(&player.shirt.0, &Default::default(), transform, gl); // Facial accessory if player.dir != PlayerDir::Up { let image = image_for_texture(&player.accessory, pos, view, offset, None, player.dir); image.draw(&player.accessory.0, &Default::default(), transform, gl); } } self.gl.draw(args.viewport(), |c, gl| { // Clear the screen. clear(BLACK, gl); let transform = c.transform.zoom(SCALE); for (i, (layer, resolved)) in layers.iter().zip(resolved_layers).enumerate() { if i == layers.len() - 1 { break; } let player = if i == 1 { Some(player) } else { None }; draw_layer(layer, resolved, transform, gl, ticks, (view_x, view_y), (view_w, view_h), player); } for character in characters { draw_character(character, transform, gl, (view_x, view_y), (view_w, view_h)); } draw_layer(layers.last().unwrap(), resolved_layers.last().unwrap(), transform, gl, ticks, (view_x, view_y), (view_w, view_h), None); }); } fn key_released(&mut self, key: Key) { match key { Key::A => self.a_pressed = false, Key::D => self.d_pressed = false, Key::W => self.w_pressed = false, Key::S => self.s_pressed = false, _ => {} } self.update_last_move = true; } fn key_pressed(&mut self, key: Key) { if key == Key::W && !self.w_pressed || key == Key::S && !self.s_pressed || key == Key::A && !self.a_pressed || key == Key::D && !self.d_pressed { self.update_last_move = true } match key { Key::A => self.a_pressed = true, Key::D => self.d_pressed = true, Key::S => self.s_pressed = true, Key::W => self.w_pressed = true, _ => {} } } fn update(&mut self, args: &UpdateArgs, player: &mut Player, map: &SVMap) { self.ticks += (args.dt * 1000.) as u32; if self.update_last_move { self.update_last_move = false; if self.a_pressed || self.d_pressed || self.s_pressed || self.w_pressed { if self.w_pressed { player.dir = PlayerDir::Up; } if self.s_pressed { player.dir = PlayerDir::Down; } if self.a_pressed { player.dir = PlayerDir::Left; } if self.d_pressed { player.dir = PlayerDir::Right; } player.last_move_start = Some(self.ticks); } else { player.last_move_start = None; } } const MOVE_AMOUNT: f64 = 100.0; let delta_x = if self.a_pressed { -MOVE_AMOUNT * args.dt } else if self.d_pressed { MOVE_AMOUNT * args.dt } else { 0. }; let delta_y = if self.w_pressed { -MOVE_AMOUNT * args.dt } else if self.s_pressed { MOVE_AMOUNT * args.dt } else { 0. }; let (adjusted_x, adjusted_y) = player.adjusted_pos(delta_x, delta_y); let layer = map.layers.iter().find(|l| l.id == "Buildings").expect("no buildings?"); let mut clamp_to_current_pos = false; for tile in &layer.tiles { let (tx, ty) = tile.get_pos(); if (tx as i32, ty as i32) == (adjusted_x, adjusted_y + 1) { let tilesheet = map.tilesheet(tile.get_tilesheet()).unwrap(); let passable = tilesheet.properties.tile_is_passable(tile.get_index(0)).unwrap_or(false); clamp_to_current_pos = !passable; break; } } player.move_horiz(delta_x, clamp_to_current_pos); player.move_vert(delta_y, clamp_to_current_pos); let player_x = player.x * 16 + player.offset_x as i32; let player_y = player.y * 16 + player.offset_y as i32; let (view_w, view_h) = ((self.view_w as f64 / SCALE) as i32, (self.view_h as f64 / SCALE) as i32); let adjusted_x = if player_x - self.view_x < view_w / 3 { player_x - view_w / 3 } else if player_x - self.view_x > view_w / 3 * 2 { player_x - view_w / 3 * 2 } else { self.view_x }; let adjusted_y = if player_y - self.view_y < view_h / 3 { player_y - view_h / 3 } else if player_y - self.view_y > view_h / 3 * 2 { player_y - view_h / 3 * 2 } else { self.view_y }; let max_x = (map.layers[0].size.0 as i32 - view_w / 16) * 16; let max_y = (map.layers[0].size.1 as i32 - view_h / 16) * 16; self.view_x = adjusted_x.max(0).min(max_x); self.view_y = adjusted_y.max(0).min(max_y); } } struct ScriptedCharacter { name: String, pos: (i32, i32), dir: u8, } enum Command { Pause(u32), Emote(String, u8), Move(String, (i32, i32), u8), Speak(String, String), GlobalFade, Viewport(i32, i32), Warp(String, (i32, i32)), FaceDirection(String, u8), ShowFrame(String, u32), Speed(String, u8), PlaySound(String), Shake(String, u32), Jump(String), TextAboveHead(String, String), AddQuest(u32), Message(String), Animate(String, bool, bool, u32, Vec<u32>), StopAnimation(String), Mail(String), Friendship(String, i32), PlayMusic(String), SpecificTemporarySprite(String), ChangeLocation(String), ChangeToTemporaryMap(String), Question(String, String), Fork(String), AmbientLight(u32, u32, u32), PositionOffset(String, i32, i32), } enum Trigger { } #[allow(dead_code)] enum End { WarpOut, Dialogue(String, String), Position((u32, u32)), End, } struct ScriptedEvent { _id: String, _music: String, viewport: (i32, i32), characters: Vec<ScriptedCharacter>, _skippable: bool, _commands: Vec<Command>, _end: End, _triggers: Vec<Trigger>, _forks: Vec<ScriptedEvent>, } fn parse_script(id: String, s: String) -> ScriptedEvent { let mut forks = s.split('\n'); let mut parts = forks.next().unwrap().split('/'); let music = parts.next().unwrap().to_owned(); let viewport_str = parts.next().unwrap(); let mut viewport_str = viewport_str.split(' '); let viewport = (viewport_str.next().unwrap().parse().unwrap(), viewport_str.next().unwrap().parse().unwrap()); let mut character_parts = parts.next().unwrap().split(' ').peekable(); let mut characters = vec![]; while character_parts.peek().is_some() { let character = ScriptedCharacter { name: character_parts.next().unwrap().to_owned(), pos: (character_parts.next().unwrap().parse().unwrap(), character_parts.next().unwrap().parse().unwrap()), dir: character_parts.next().unwrap().parse().unwrap(), }; characters.push(character); } let mut peekable = parts.peekable(); let skippable = match peekable.peek() { Some(&"skippable") => { let _ = peekable.next(); true } Some(_) | None => false, }; let mut commands = vec![]; for command_str in peekable { let args: Vec<_> = command_str.split(' ').collect(); let command = match args[0] { "pause" => Command::Pause(args[1].parse().unwrap()), "emote" => Command::Emote(args[1].to_owned(), args[2].parse().unwrap()), "move" => Command::Move(args[1].to_owned(), (args[2].parse().unwrap(), args[3].parse().unwrap()), args[4].parse().unwrap()), "speak" => Command::Speak(args[1].to_owned(), args[2].to_owned()), "globalFade" => Command::GlobalFade, "viewport" => Command::Viewport(args[1].parse().unwrap(), args[2].parse().unwrap()), "warp" => Command::Warp(args[1].to_owned(), (args[2].parse().unwrap(), args[3].parse().unwrap())), "faceDirection" => Command::FaceDirection(args[1].to_owned(), args[2].parse().unwrap()), "showFrame" => Command::ShowFrame(args[1].to_owned(), args[2].parse().unwrap()), "speed" => Command::Speed(args[1].to_owned(), args[2].parse().unwrap()), "playSound" => Command::PlaySound(args[1].to_owned()), "shake" => Command::Shake(args[1].to_owned(), args[2].parse().unwrap()), "jump" => Command::Jump(args[1].to_owned()), "textAboveHead" => Command::TextAboveHead(args[1].to_owned(), args[2].to_owned()), "addQuest" => Command::AddQuest(args[1].parse().unwrap()), "message" => Command::Message(args[1].to_owned()), "animate" => Command::Animate(args[1].to_owned(), args[2] == "t", args[3] == "t", args[4].parse().unwrap(), args[5..].iter().map(|s| s.parse().unwrap()).collect()), "stopAnimation" => Command::StopAnimation(args[1].to_owned()), "mail" => Command::Mail(args[1].to_owned()), "friendship" => Command::Friendship(args[1].to_owned(), args[2].parse().unwrap()), "playMusic" => Command::PlayMusic(args[1].to_owned()), "specificTemporarySprite" => Command::SpecificTemporarySprite(args[1].to_owned()), "changeLocation" => Command::ChangeLocation(args[1].to_owned()), "changeToTemporaryMap" => Command::ChangeToTemporaryMap(args[1].to_owned()), "question" => Command::Question(args[1].to_owned(), args[2].to_owned()), "fork" => Command::Fork(args[1].to_owned()), "ambientLight" => Command::AmbientLight(args[1].parse().unwrap(), args[2].parse().unwrap(), args[3].parse().unwrap()), "positionOffset" => Command::PositionOffset(args[1].to_owned(), args[2].parse().unwrap(), args[3].parse().unwrap()), "end" => continue, "" => continue, s => panic!("unknown command {}", s), }; commands.push(command); } ScriptedEvent { _id: id, _music: music, viewport: viewport, characters: characters, _skippable: skippable, _commands: commands, _end: End::End, //XXXjdm _triggers: vec![], _forks: vec![], } } fn characters_for_event(event: &ScriptedEvent, path: &Path) -> Vec<Character> { let mut characters = vec![]; for character in &event.characters { if character.name == "farmer" { continue; } let texture = load_texture(path, &format!("{}.xnb", character.name)); let info = (texture, 0, (16, 32), (0, 0), [Some(0), Some(1), Some(2), Some(3)]); characters.push(Character { texture: info, _name: character.name.clone(), x: character.pos.0, y: character.pos.1, offset_x: 0., offset_y: 0., _index: 0, dir: match character.dir { 0 => PlayerDir::Up, 1 => PlayerDir::Right, 2 => PlayerDir::Down, 3 => PlayerDir::Left, _ => unreachable!(), }, }); } characters } fn load_texture(base: &Path, filename: &str) -> Texture { let mut f = File::open(base.join(filename)).unwrap(); let xnb = XNB::<Texture2d>::from_buffer(&mut f).unwrap(); let mut texture = xnb.primary; let data = texture.mip_data.remove(0); let data = match texture.format { SurfaceFormat::Dxt3 => { decompress_image(texture.width as i32, texture.height as i32, data.as_ptr() as *const _, CompressType::Dxt3) } _ => data, }; let img = RgbaImage::from_raw(texture.width as u32, texture.height as u32, data).unwrap(); let mut settings = TextureSettings::new(); settings.set_filter(Filter::Nearest); Texture::from_image(&img, &settings) } fn main() { // Create an Glutin window. const WINDOW_DIMENSIONS: (u32, u32) = (800, 600); let mut window: PistonWindow = WindowSettings::new( "spinning-square", [WINDOW_DIMENSIONS.0, WINDOW_DIMENSIONS.1] ) .opengl(PistonOpenGL::V3_2) .exit_on_esc(true) .vsync(true) .build() .unwrap(); let mut args = env::args(); let _self = args.next(); let map_name = args.next().unwrap_or("Town.xnb".into()); let event_id = args.next(); let mut view_x = args.next().and_then(|s| s.parse().ok()).unwrap_or(0); let mut view_y = args.next().and_then(|s| s.parse().ok()).unwrap_or(0); let base = Path::new("../xnb/uncompressed"); let mut f = File::open(base.join("Maps").join(&map_name)).unwrap(); let xnb = XNB::<SVMap>::from_buffer(&mut f).unwrap(); let mut map = xnb.primary; for layer in &mut map.layers { layer.tiles.sort_by(|t1, t2| { let (t1_x, t1_y) = t1.get_pos(); let (t2_x, t2_y) = t2.get_pos(); t1_y.cmp(&t2_y).then_with(|| t1_x.cmp(&t2_x)) }); } let event = event_id.and_then(|id| { let f = File::open(base.join("Data/Events").join(&map_name)).ok(); let event = f.and_then(|mut f| { let xnb = XNB::<Dictionary<String, String>>::from_buffer(&mut f).unwrap(); for (k, v) in &xnb.primary.map { if k.split('/').next() == Some(&id) { return Some(v.clone()); } } None }); if let Some(ref event) = event { println!("got event source:\n{}", event); } event.map(|e| parse_script(id, e)) }); let mut tilesheets = HashMap::new(); for ts in &map.tilesheets { let texture = load_texture(base, &format!("{}.xnb", ts.image_source)); println!("storing texture for {}", ts.id); tilesheets.insert(ts.id.clone(), texture); } println!("loaded {} tilesheets", tilesheets.len()); let mut resolved_layers = vec![]; for layer in &map.layers { let layer_tiles = layer.tiles.iter().map(|t| { let name = t.get_tilesheet(); ResolvedTile { texture: tilesheets.get(name).expect("missing texture"), tilesheet: map.tilesheets.iter().find(|s| s.id == name).expect("missing tilesheet"), } }).collect(); resolved_layers.push(layer_tiles); } let character_path = Path::new("../xnb/uncompressed/Characters"); let path = character_path.join("Farmer"); let base = load_texture(&path, "farmer_base.xnb"); let bottom = load_texture(&path, "farmer_base.xnb"); let arms = load_texture(&path, "farmer_base.xnb"); let pants = load_texture(&path, "farmer_base.xnb"); let hairstyle = load_texture(&path, "hairstyles.xnb"); //let hat = load_texture(&path, "hats.xnb"); let shirt = load_texture(&path, "shirts.xnb"); let accessory = load_texture(&path, "accessories.xnb"); let base_dir_info = [Some(0), Some(2), Some(4), Some(2)]; let mut player = Player { base: (base, 0, (16, 16), (0, 0), base_dir_info), bottom: (bottom, 24, (16, 16), (0, 16), base_dir_info), arms: (arms, 30, (16, 16), (0, 16), base_dir_info), hairstyle: (hairstyle, 0, (16, 16), (0, 0), base_dir_info), //hat: (hat, 2, (20, 20), (-2, -2), [Some(0), Some(1), Some(3), Some(2)]), hat: None, pants: (pants, 42, (16, 16), (0, 16), base_dir_info), shirt: (shirt, 0, (8, 8), (4, 15), [Some(0), Some(1), Some(3), Some(2)]), accessory: (accessory, 0, (16, 16), (0, 3), [Some(0), Some(1), None, Some(1)]), x: 10, y: 15, offset_x: 0., offset_y: 0., last_move_start: None, dir: PlayerDir::Down, }; let characters = match event { Some(ref ev) => characters_for_event(ev, &character_path), None => vec![], }; if let Some(ref event) = event { view_x = event.viewport.0; view_y = event.viewport.1; } // Create a new game and run it. let mut app = App { gl: GlGraphics::new(OpenGL::V3_2), view_x: view_x * map.tilesheets[0].tile_size.0 as i32, view_y: view_y * map.tilesheets[0].tile_size.1 as i32, view_w: WINDOW_DIMENSIONS.0, view_h: WINDOW_DIMENSIONS.1, ticks: 0, a_pressed: false, d_pressed: false, w_pressed: false, s_pressed: false, update_last_move: false, }; while let Some(e) = window.next() { if let Some(Button::Keyboard(k)) = e.press_args() { match k { Key::Left if app.view_x > 0 => app.view_x -= 1, Key::Right => app.view_x += 1, Key::Up if app.view_y > 0 => app.view_y -= 1, Key::Down => app.view_y += 1, k => app.key_pressed(k), } } if let Some(Button::Keyboard(k)) = e.release_args() { app.key_released(k); } if let Some(r) = e.render_args() { app.render(&r, &player, &characters, &map.layers, &resolved_layers); } if let Some(u) = e.update_args() { app.update(&u, &mut player, &map); } } }
use crate::game; /* * Commands * * ? : ShowHelp * r : Retire * n : DrawFromStock * q : Quit * k : WasteToFoundation * a : AutoFinish * k[1-7] : WasteToPile [pile 0-6] * [1-7] : PileToFoundation [pile 0-6] * [1-7][1-7] : PileToPile [pile 0-6][pile 0-6] * h[1-7] : FoundationToPile[found: 0-3][pile 0-6] * d[1-7] : FoundationToPile[found: 0-3][pile 0-6] * s[1-7] : FoundationToPile[found: 0-3][pile 0-6] * c[1-7] : FoundationToPile[found: 0-3][pile 0-6] */ // TODO: Stats, StatsReset pub enum Command { ShowHelp, Retire, Quit, DrawFromStock, WasteToFoundation, AutoFinish, WasteToPile{pile_index: u8}, PileToFoundation{pile_index: u8}, PileToPile{src_pile: u8, dest_pile: u8}, FoundationToPile{foundation_index: u8, pile_index: u8}, } impl Command { pub fn from_string(cmd_str: &str) -> Option<Command> { let s = cmd_str.trim().to_lowercase(); if s.is_empty() { None } else if s.len() == 1 { let opt1 = s.parse::<u8>(); match opt1 { Ok(num) => { if num >= 1 && num <= 7 { Some(Command::PileToFoundation{pile_index: num}) } else { None } } _ => { if s == "?" { Some(Command::ShowHelp) } else if s == "r" { Some(Command::Retire) } else if s == "a" { Some(Command::AutoFinish) } else if s == "n" { Some(Command::DrawFromStock) } else if s == "q" { Some(Command::Quit) } else if s == "k" { Some(Command::WasteToFoundation) } else { None } } } } else if s.len() == 2 { let(s1, s2) = s.split_at(1); let opt1 = s1.parse::<u8>(); match opt1 { Ok(num1) => { let opt2 = s2.parse::<u8>(); match opt2 { Ok(num2) => { if num1 >= 1 && num1 <= 7 && num2 >= 1 && num2 <= 7 { Some(Command::PileToPile{src_pile: num1, dest_pile: num2}) } else { None } }, _ => None } }, _ => { if s1 == "k" || s1 == "h" || s1 == "d" || s1 == "s" || s1 == "c" { let opt2 = s2.parse::<u8>(); match opt2 { Ok(num2) => { if num2 >= 1 && num2 <= 7 { match s1 { "h" => Some(Command::FoundationToPile{foundation_index: game::HEART_FD, pile_index: num2}), "d" => Some(Command::FoundationToPile{foundation_index: game::DIAMOND_FD, pile_index: num2}), "s" => Some(Command::FoundationToPile{foundation_index: game::SPADE_FD, pile_index: num2}), "c" => Some(Command::FoundationToPile{foundation_index: game::CLUB_FD, pile_index: num2}), "k" => Some(Command::WasteToPile{pile_index: num2}), _ => None, } } else { None } }, _ => None, } } else { None } } } } else { None } } } #[cfg(test)] mod tests { use crate::command::Command; use hamcrest2::prelude::*; fn enum_type(opt_cmd: &Option<Command>) -> String { match opt_cmd { Some(cmd) => { #[allow(unused_variables)] match cmd { Command::ShowHelp => String::from("ShowHelp"), Command::Retire => String::from("Retire"), Command::Quit => String::from("Quit"), Command::DrawFromStock => String::from("DrawFromStock"), Command::WasteToFoundation => String::from("WasteToFoundation"), Command::AutoFinish => String::from("AutoFinish"), Command::WasteToPile{pile_index} => String::from("WasteToPile"), Command::PileToFoundation{pile_index} => String::from("PileToFoundation"), Command::PileToPile{src_pile, dest_pile} => String::from("PileToPile"), Command::FoundationToPile{foundation_index, pile_index} => String::from("FoundationToPile"), } }, None => String::from("") } } #[test] fn test_cmd_type() { let cmd = Command::from_string("?"); assert_that!(enum_type(&cmd), eq("ShowHelp")); let cmd = Command::from_string("r"); assert_that!(enum_type(&cmd), eq("Retire")); let cmd = Command::from_string("n"); assert_that!(enum_type(&cmd), eq("DrawFromStock")); let cmd = Command::from_string("q"); assert_that!(enum_type(&cmd), eq("Quit")); let cmd = Command::from_string("k"); assert_that!(enum_type(&cmd), eq("WasteToFoundation")); let cmd = Command::from_string("a"); assert_that!(enum_type(&cmd), eq("AutoFinish")); let cmd = Command::from_string("k1"); assert_that!(enum_type(&cmd), eq("WasteToPile")); let cmd = Command::from_string("2"); assert_that!(enum_type(&cmd), eq("PileToFoundation")); let cmd = Command::from_string("21"); assert_that!(enum_type(&cmd), eq("PileToPile")); let cmd = Command::from_string("i"); assert_that!(enum_type(&cmd), eq("")); } #[test] fn test_waste_to_pile() { let cmd = Command::from_string("k0"); assert_that!(cmd.is_none(), is(true)); let cmd = Command::from_string("k1"); assert_that!(cmd.is_none(), is(false)); match cmd.unwrap() { Command::WasteToPile{pile_index} => assert_that!(pile_index, eq(1)), _ => panic!(), } let cmd = Command::from_string("k7"); assert_that!(cmd.is_none(), is(false)); match cmd.unwrap() { Command::WasteToPile{pile_index} => assert_that!(pile_index, eq(7)), _ => panic!(), } let cmd = Command::from_string("k8"); assert_that!(cmd.is_none(), is(true)); let cmd = Command::from_string("k9"); assert_that!(cmd.is_none(), is(true)); } #[test] fn test_pile_to_foundation() { let cmd = Command::from_string("0"); assert_that!(cmd.is_none(), is(true)); let cmd = Command::from_string("1"); assert_that!(cmd.is_none(), is(false)); match cmd.unwrap() { Command::PileToFoundation{pile_index} => assert_that!(pile_index, eq(1)), _ => panic!(), } let cmd = Command::from_string("7"); assert_that!(cmd.is_none(), is(false)); match cmd.unwrap() { Command::PileToFoundation{pile_index} => assert_that!(pile_index, eq(7)), _ => panic!(), } let cmd = Command::from_string("8"); assert_that!(cmd.is_none(), is(true)); let cmd = Command::from_string("9"); assert_that!(cmd.is_none(), is(true)); } #[test] fn test_pile_to_pile() { let cmd = Command::from_string("01"); assert_that!(cmd.is_none(), is(true)); let cmd = Command::from_string("10"); assert_that!(cmd.is_none(), is(true)); let cmd = Command::from_string("82"); assert_that!(cmd.is_none(), is(true)); let cmd = Command::from_string("78"); assert_that!(cmd.is_none(), is(true)); let cmd = Command::from_string("79"); assert_that!(cmd.is_none(), is(true)); let cmd = Command::from_string("15"); assert_that!(cmd.is_none(), is(false)); match cmd.unwrap() { Command::PileToPile{src_pile, dest_pile} => { assert_that!(src_pile, eq(1)); assert_that!(dest_pile, eq(5)); }, _ => panic!(), } let cmd = Command::from_string("73"); assert_that!(cmd.is_none(), is(false)); match cmd.unwrap() { Command::PileToPile{src_pile, dest_pile} => { assert_that!(src_pile, eq(7)); assert_that!(dest_pile, eq(3)); }, _ => panic!(), } let cmd = Command::from_string("41"); assert_that!(cmd.is_none(), is(false)); match cmd.unwrap() { Command::PileToPile{src_pile, dest_pile} => { assert_that!(src_pile, eq(4)); assert_that!(dest_pile, eq(1)); }, _ => panic!(), } let cmd = Command::from_string("67"); assert_that!(cmd.is_none(), is(false)); match cmd.unwrap() { Command::PileToPile{src_pile, dest_pile} => { assert_that!(src_pile, eq(6)); assert_that!(dest_pile, eq(7)); }, _ => panic!(), } } }
use crate::config; use crate::neatns::network::activation; use crate::neatns::network::connection; use crate::neatns::network::innovation::InnovationLog; use crate::neatns::network::innovation::InnovationTime; use crate::neatns::network::link::Link; use crate::neatns::network::node::Node; use crate::neatns::network::node::NodeRef; use crate::neatns::network::order; use rand::seq::SliceRandom; use rand::Rng; use std::collections::HashMap; #[derive(Clone)] pub struct Genome { pub inputs: HashMap<NodeRef, Node>, pub hidden_nodes: HashMap<NodeRef, Node>, pub outputs: HashMap<NodeRef, Node>, pub links: HashMap<(NodeRef, NodeRef), Link>, // Links between nodes pub order: order::Order<NodeRef>, // Actions to perform when evaluating pub connections: connection::Connections<NodeRef>, // Fast connection lookup } impl Genome { pub fn empty() -> Genome { Genome { inputs: HashMap::new(), outputs: HashMap::new(), hidden_nodes: HashMap::new(), links: HashMap::new(), order: order::Order::<NodeRef>::new(), connections: connection::Connections::<NodeRef>::new(), } } /// Generate genome with default activation and no connections pub fn new(inputs: usize, outputs: usize) -> Genome { let inputs: HashMap<NodeRef, Node> = (0..inputs as u64) .map(|i| (NodeRef::Input(i), Node::new(NodeRef::Input(i)))) .collect(); let outputs: HashMap<NodeRef, Node> = (0..outputs as u64) .map(|i| (NodeRef::Output(i), Node::new(NodeRef::Output(i)))) .collect(); let order = order::Order::<NodeRef>::from_nodes( inputs.keys().cloned().collect(), vec![], outputs.keys().cloned().collect(), ); Genome { inputs, outputs, hidden_nodes: HashMap::new(), links: HashMap::new(), order, connections: connection::Connections::<NodeRef>::new(), } } fn split_link(&mut self, link: Link, new_node_id: u64, innovation_number: u64) { { // Disable link let link = self .links .get_mut(&(link.from, link.to)) .expect("Unable to split nonexistent link"); assert!(link.enabled); link.enabled = false; link.split = true; } let new_node_ref = NodeRef::Hidden(new_node_id); // Might have inherited that the connection is not split, but also the nodes splitting it if self.hidden_nodes.contains_key(&new_node_ref) { return; } // Disable connection self.connections.disable(link.from, link.to); // Add and remvoe actions self.order.split_link(link.from, link.to, new_node_ref); self.hidden_nodes .insert(new_node_ref, Node::new(NodeRef::Hidden(new_node_id))); let link1 = Link::new(link.from, new_node_ref, 1.0, innovation_number); let link2 = Link::new(new_node_ref, link.to, link.weight, innovation_number + 1); assert!(!self.links.contains_key(&(link1.from, link1.to))); self.insert_link(link1, false); assert!(!self.links.contains_key(&(link2.from, link2.to))); self.insert_link(link2, false); } fn insert_link(&mut self, link: Link, add_action: bool) { // Add link self.links.insert((link.from, link.to), link); // Add connections self.connections.add(link.from, link.to, link.enabled); // Add action if link.enabled && add_action { // When adding many links at the same time, it is faster to sort // topologically at the end than adding every connection independently // When 'add_action' is false, 'sort_topologically' must be called on // self.actions when all links are inserted. // Except when the link is added by split, then self.action should // perform the split internally. self.order.add_link(link.from, link.to, &self.connections); } } pub fn crossover(&self, other: &Self, is_fitter: bool) -> Genome { // Let parent1 be the fitter parent let (parent1, parent2) = if is_fitter { (self, other) } else { (other, self) }; let mut genome = Genome::empty(); // Copy links only in fitter parent, perform crossover if in both parents for (link_ref, link) in parent1.links.iter() { if !genome.connections.creates_cycle(link.from, link.to) { if let Some(link2) = parent2.links.get(link_ref) { genome.insert_link(link.crossover(link2), false); } else { genome.insert_link(*link, false); } } } // Copy nodes only in fitter parent, perform crossover if in both parents for (node_ref, node) in parent1.inputs.iter() { if let Some(node2) = parent2.inputs.get(node_ref) { genome.inputs.insert(*node_ref, node.crossover(node2)); } else { genome.inputs.insert(*node_ref, *node); } genome.order.add_input(*node_ref); } for (node_ref, node) in parent1.hidden_nodes.iter() { if let Some(node2) = parent2.hidden_nodes.get(node_ref) { genome.hidden_nodes.insert(*node_ref, node.crossover(node2)); } else { genome.hidden_nodes.insert(*node_ref, *node); } genome.order.add_hidden(*node_ref); } for (node_ref, node) in parent1.outputs.iter() { if let Some(node2) = parent2.outputs.get(node_ref) { genome.outputs.insert(*node_ref, node.crossover(node2)); } else { genome.outputs.insert(*node_ref, *node); } genome.order.add_output(*node_ref); } // Topologically sort actions of child, as this is not done when inserting links and nodes genome.order.sort_topologically(&genome.connections); return genome; } pub fn mutate(&mut self, log: &mut InnovationLog, global_innovation: &mut InnovationTime) { let mut rng = rand::thread_rng(); if rng.gen::<f64>() < config::NEAT.add_node_probability { self.mutation_add_node(log, global_innovation); } if rng.gen::<f64>() < config::NEAT.add_connection_probability { self.mutation_add_connection(log, global_innovation); } if rng.gen::<f64>() < config::NEAT.disable_connection_probability { self.mutation_disable_connection(); } if rng.gen::<f64>() < config::NEAT.mutate_link_weight_probability { self.mutate_link_weight(); } if rng.gen::<f64>() < config::NEAT.mutate_hidden_bias_probability { self.mutate_hidden_bias(); } if rng.gen::<f64>() < config::NEAT.mutate_hidden_activation_probability { self.mutate_hidden_activation(); } if rng.gen::<f64>() < config::NEAT.mutate_output_bias_probability { self.mutate_output_bias(); } if rng.gen::<f64>() < config::NEAT.mutate_output_activation_probability { self.mutate_output_activation(); } } fn mutate_link_weight(&mut self) { let mut rng = rand::thread_rng(); // Mutate single link /*if !self.links.is_empty() { let link_index = rng.gen_range(0, self.links.len()); if let Some(link) = self.links.values_mut().skip(link_index).next() { link.weight += (rng.gen::<f64>() - 0.5) * 2.0 * config::NEAT.mutate_link_weight_size; } }*/ for link in self.links.values_mut() { link.weight += (rng.gen::<f64>() - 0.5) * 2.0 * config::NEAT.mutate_link_weight_size; } } fn mutate_hidden_bias(&mut self) { let mut rng = rand::thread_rng(); if !self.hidden_nodes.is_empty() { let link_index = rng.gen_range(0, self.hidden_nodes.len()); if let Some(node) = self.hidden_nodes.values_mut().skip(link_index).next() { node.bias += (rng.gen::<f64>() - 0.5) * 2.0 * config::NEAT.mutate_hidden_bias_size; } } } fn mutate_hidden_activation(&mut self) { let mut rng = rand::thread_rng(); if !self.hidden_nodes.is_empty() { let link_index = rng.gen_range(0, self.hidden_nodes.len()); if let Some(node) = self.hidden_nodes.values_mut().skip(link_index).next() { node.activation = config::NEAT.hidden_activations.random(); } } } fn mutate_output_bias(&mut self) { let mut rng = rand::thread_rng(); if !self.outputs.is_empty() { let link_index = rng.gen_range(0, self.outputs.len()); if let Some(node) = self.outputs.values_mut().skip(link_index).next() { node.bias += (rng.gen::<f64>() - 0.5) * 2.0 * config::NEAT.mutate_output_bias_size; } } } fn mutate_output_activation(&mut self) { let mut rng = rand::thread_rng(); if !self.outputs.is_empty() { let link_index = rng.gen_range(0, self.outputs.len()); if let Some(node) = self.outputs.values_mut().skip(link_index).next() { node.activation = config::NEAT.output_activations.random(); } } } fn mutation_add_node( &mut self, log: &mut InnovationLog, global_innovation: &mut InnovationTime, ) { // Select random enabled link if let Some(index) = self .links .iter() .filter(|(_, link)| !link.split && link.enabled) .map(|(i, _)| *i) .collect::<Vec<(NodeRef, NodeRef)>>() .choose(&mut rand::thread_rng()) { assert!(self.order.contains(&order::Action::Link(index.0, index.1))); if let Some(&link) = self.links.get(index) { // Check if this link has been split by another individual if let Some(addition) = log.node_additions.get(&link.innovation) { // Split the link self.split_link(link, addition.node_number, addition.innovation_number); } else { // Split the link self.split_link( link, global_innovation.node_number, global_innovation.innovation_number, ); // Add this mutation to log log.node_additions.insert( link.innovation, InnovationTime { node_number: global_innovation.node_number, innovation_number: global_innovation.innovation_number, }, ); // Increase global node count and innovation number global_innovation.node_number += 1; global_innovation.innovation_number += 2; } } } } // TODO: avoid retries fn mutation_add_connection( &mut self, log: &mut InnovationLog, global_innovation: &mut InnovationTime, ) { let mut rng = rand::thread_rng(); // Retry 50 times for _ in 0..50 { // Select random source and target nodes for new link let from_index = rng.gen_range(0, self.inputs.len() + self.hidden_nodes.len()); let to_index = rng.gen_range(0, self.hidden_nodes.len() + self.outputs.len()); let from_option = if from_index < self.inputs.len() { self.inputs.keys().skip(from_index).next() } else { self.hidden_nodes .keys() .skip(from_index - self.inputs.len()) .next() }; let to_option = if to_index < self.outputs.len() { self.outputs.keys().skip(to_index).next() } else { self.hidden_nodes .keys() .skip(to_index - self.outputs.len()) .next() }; if let (Some(&from), Some(&to)) = (from_option, to_option) { // If connection does not exist and its addition does not create cycle if !self.links.contains_key(&(from, to)) && !self.connections.creates_cycle(from, to) { // Check if this link has been added by another individual let innovation = match log.edge_additions.get(&(from, to)) { Some(innovation_number) => *innovation_number, None => { log.edge_additions .insert((from, to), global_innovation.innovation_number); global_innovation.innovation_number += 1; global_innovation.innovation_number - 1 } }; self.insert_link( Link::new( from, to, (rng.gen::<f64>() - 0.5) * 2.0 * config::NEAT.initial_link_weight_size, innovation, ), true, ); break; } } else { break; } } } fn mutation_disable_connection(&mut self) { if let Some(&connection_ref) = self .links .iter() .filter(|(_, link)| link.enabled) .map(|(i, _)| i) .collect::<Vec<&(NodeRef, NodeRef)>>() .choose(&mut rand::thread_rng()) { let connection_ref = *connection_ref; self.connections.disable(connection_ref.0, connection_ref.1); self.order.remove_link(connection_ref.0, connection_ref.1); if let Some(link) = self.links.get_mut(&connection_ref) { link.enabled = false; } } } // Genetic distance between two genomes pub fn distance(&self, other: &Self) -> f64 { let mut link_differences: u64 = 0; // Number of links present in only one of the genomes let mut link_distance: f64 = 0.0; // Total distance between links present in both genomes let mut link_count = self.links.len() as u64; // Number of unique links between the two genomes for link_ref in other.links.keys() { if !self.links.contains_key(link_ref) { link_differences += 1; } } link_count += link_differences; // Count is number of links in A + links in B that are not in A for (link_ref, link) in self.links.iter() { if let Some(link2) = other.links.get(link_ref) { link_distance += link.distance(link2); // Distance normalized between 0 and 1 } else { link_differences += 1; } } return if link_count == 0 { 0.0 } else { ((link_differences as f64) + link_distance) / (link_count as f64) }; } pub fn get_activation(&self, node_ref: &NodeRef) -> activation::Activation { match node_ref { NodeRef::Input(_) => self.inputs.get(node_ref).unwrap().activation, NodeRef::Hidden(_) => self.hidden_nodes.get(node_ref).unwrap().activation, NodeRef::Output(_) => self.outputs.get(node_ref).unwrap().activation, } } pub fn get_bias(&self, node_ref: &NodeRef) -> f64 { match node_ref { NodeRef::Input(_) => self.inputs.get(node_ref).unwrap().bias, NodeRef::Hidden(_) => self.hidden_nodes.get(node_ref).unwrap().bias, NodeRef::Output(_) => self.outputs.get(node_ref).unwrap().bias, } } }
use anyhow::{anyhow, Result}; #[derive(Debug, Copy, Clone)] enum Instruction { Add(Parameter, Parameter, Parameter), Multiply(Parameter, Parameter, Parameter), Input(Parameter), Output(Parameter), JumpIfTrue(Parameter, Parameter), JumpIfFalse(Parameter, Parameter), LessThan(Parameter, Parameter, Parameter), Equals(Parameter, Parameter, Parameter), AdjustRelativeBase(Parameter), Halt, } #[derive(Debug, Copy, Clone)] enum Parameter { Immediate(i64), Indexed(IndexedParameter), } #[derive(Debug, Copy, Clone)] pub enum IndexedParameter { Positional(usize), Relative(usize), } #[derive(Debug, Clone)] pub struct Computer { memory: Vec<i64>, pointer: usize, relative_base: usize, } #[derive(Debug, Copy, Clone)] enum ExecutionResult { Running(Option<i64>), Stopped(StoppedResult), } #[derive(Debug, Copy, Clone)] pub enum StoppedResult { Blocked, Halted, } impl Computer { pub fn new(initial_memory: &Vec<i64>) -> Computer { let mut internal_memory = initial_memory.clone(); internal_memory.resize(4096, 0); Computer { memory: internal_memory, pointer: 0, relative_base: 0, } } pub fn new_from_str(serialized_memory: &str) -> Result<Computer> { let initial_memory = serialized_memory .trim() .split(',') .map(|x| x.parse::<i64>()) .collect::<Result<Vec<_>, _>>()?; Ok(Self::new(&initial_memory)) } pub fn run(&mut self, input: Vec<i64>) -> Result<Vec<i64>> { let (result, output) = self.run_until_stopped(input)?; match result { StoppedResult::Blocked => Err(anyhow!("Blocked on input")), StoppedResult::Halted => Ok(output), } } pub fn run_until_stopped(&mut self, input: Vec<i64>) -> Result<(StoppedResult, Vec<i64>)> { let mut input_stream = input.into_iter(); let mut output = vec![]; loop { let instruction = self.get_instruction()?; let result = self.do_instruction(instruction, &mut input_stream); match result { ExecutionResult::Running(None) => {} ExecutionResult::Running(Some(val)) => { output.push(val); } ExecutionResult::Stopped(stopped_result) => { return Ok((stopped_result, output)); } } } } pub fn get_memory_value(&self, idx: usize) -> i64 { self.memory[idx] } pub fn set_value(&mut self, param: IndexedParameter, value: i64) { match param { IndexedParameter::Positional(idx) => { self.set_memory_value(idx, value); } IndexedParameter::Relative(offset) => { let idx = self.relative_base.wrapping_add(offset); self.set_memory_value(idx, value); } } } fn do_instruction( &mut self, instruction: Instruction, mut input_stream: impl Iterator<Item = i64>, ) -> ExecutionResult { match instruction { Instruction::Add(a, b, Parameter::Indexed(p)) => { self.set_value(p, self.get_param_value(a) + self.get_param_value(b)); self.pointer += 4; ExecutionResult::Running(None) } Instruction::Multiply(a, b, Parameter::Indexed(p)) => { self.set_value(p, self.get_param_value(a) * self.get_param_value(b)); self.pointer += 4; ExecutionResult::Running(None) } Instruction::Input(Parameter::Indexed(p)) => match input_stream.next() { Some(input) => { self.set_value(p, input); self.pointer += 2; ExecutionResult::Running(None) } None => ExecutionResult::Stopped(StoppedResult::Blocked), }, Instruction::Output(a) => { let output = self.get_param_value(a); self.pointer += 2; ExecutionResult::Running(Some(output)) } Instruction::JumpIfTrue(a, b) => { if self.get_param_value(a) != 0 { self.pointer = self.get_param_value(b) as usize; } else { self.pointer += 3; } ExecutionResult::Running(None) } Instruction::JumpIfFalse(a, b) => { if self.get_param_value(a) == 0 { self.pointer = self.get_param_value(b) as usize; } else { self.pointer += 3; } ExecutionResult::Running(None) } Instruction::LessThan(a, b, Parameter::Indexed(p)) => { let value = match self.get_param_value(a) < self.get_param_value(b) { true => 1, false => 0, }; self.set_value(p, value); self.pointer += 4; ExecutionResult::Running(None) } Instruction::Equals(a, b, Parameter::Indexed(p)) => { let value = match self.get_param_value(a) == self.get_param_value(b) { true => 1, false => 0, }; self.set_value(p, value); self.pointer += 4; ExecutionResult::Running(None) } Instruction::AdjustRelativeBase(a) => { self.relative_base = self .relative_base .wrapping_add(self.get_param_value(a) as usize); self.pointer += 2; ExecutionResult::Running(None) } Instruction::Halt => ExecutionResult::Stopped(StoppedResult::Halted), _ => unreachable!(), } } fn get_instruction(&self) -> Result<Instruction> { let compact_opcode = self.get_memory_value(self.pointer) % 100; match compact_opcode { 1 => Ok(Instruction::Add( self.get_param(0)?, self.get_param(1)?, self.get_param(2)?, )), 2 => Ok(Instruction::Multiply( self.get_param(0)?, self.get_param(1)?, self.get_param(2)?, )), 3 => Ok(Instruction::Input(self.get_param(0)?)), 4 => Ok(Instruction::Output(self.get_param(0)?)), 5 => Ok(Instruction::JumpIfTrue( self.get_param(0)?, self.get_param(1)?, )), 6 => Ok(Instruction::JumpIfFalse( self.get_param(0)?, self.get_param(1)?, )), 7 => Ok(Instruction::LessThan( self.get_param(0)?, self.get_param(1)?, self.get_param(2)?, )), 8 => Ok(Instruction::Equals( self.get_param(0)?, self.get_param(1)?, self.get_param(2)?, )), 9 => Ok(Instruction::AdjustRelativeBase(self.get_param(0)?)), 99 => Ok(Instruction::Halt), _ => Err(anyhow!("Unrecognized opcode {}", compact_opcode)), } } fn get_param(&self, offset: usize) -> Result<Parameter> { let compact_instruction = self.get_memory_value(self.pointer); let flag = (compact_instruction / (10i64.pow(offset as u32 + 2))) % 10; let data = self.get_memory_value(self.pointer + offset + 1); match flag { 0 => Ok(Parameter::Indexed(IndexedParameter::Positional( data as usize, ))), 1 => Ok(Parameter::Immediate(data)), 2 => Ok(Parameter::Indexed(IndexedParameter::Relative( data as usize, ))), _ => Err(anyhow!("Unrecognized parameter flag {}", flag)), } } fn get_param_value(&self, param: Parameter) -> i64 { match param { Parameter::Indexed(IndexedParameter::Positional(idx)) => self.get_memory_value(idx), Parameter::Immediate(data) => data, Parameter::Indexed(IndexedParameter::Relative(offset)) => { self.get_memory_value(self.relative_base.wrapping_add(offset)) } } } fn set_memory_value(&mut self, idx: usize, value: i64) { self.memory[idx] = value; } }
use alloc::sync::Arc; use alloc::collections::BTreeMap; use crate::uses::*; use crate::util::{Futex, FutexGuard}; use crate::cap::{CapId, CapFlags, Capability, CapObject, CapObjectType, Map}; use super::*; use super::phys_alloc::{zm, Allocation}; use super::virt_alloc::{AllocType, PageMappingFlags, VirtLayout, VirtLayoutElement}; #[derive(Debug)] pub struct SharedMem { mem: Allocation, cap_data: Futex<BTreeMap<CapId, VirtRange>>, } impl SharedMem { pub fn new(size: usize, flags: CapFlags) -> Option<Capability<Self>> { let allocation = zm.alloc(size)?; let arc = Arc::new(SharedMem { mem: allocation, cap_data: Futex::new(BTreeMap::new()), }); Some(Capability::new(arc, flags)) } } impl CapObject for SharedMem { fn cap_object_type() -> CapObjectType { CapObjectType::SMem } fn inc_ref(&self) {} fn dec_ref(&self) {} } impl Map for SharedMem { type Lock<'a> = FutexGuard<'a, BTreeMap<CapId, VirtRange>>; fn virt_layout(&self, flags: CapFlags) -> VirtLayout { let elem = VirtLayoutElement::from_range( self.mem.into(), PageMappingFlags::from_cap_flags(flags), ); VirtLayout::from(vec![elem], self.alloc_type()) } fn alloc_type(&self) -> AllocType { AllocType::Shared } fn cap_map_data(&self, id: CapId) -> (Option<VirtRange>, Self::Lock<'_>) { let lock = self.cap_data.lock(); let out = lock.get(&id).map(|vr| *vr); (out, lock) } fn set_cap_map_data(&self, id: CapId, data: Option<VirtRange>, mut lock: Self::Lock<'_>) { match data { Some(virt_range) => lock.insert(id, virt_range), None => lock.remove(&id), }; } }
/*! # CRC Any To compute CRC values by providing the length of bits, expression, reflection, an initial value and a final xor value. It has many built-in CRC functions. ## Usage You can use `create_crc` associated function to create a CRC instance by providing the length of bits, expression, reflection, an initial value and a final xor value. For example, if you want to compute a CRC-24 value. ```rust use crc_any::CRC; let mut crc24 = CRC::create_crc(0x0000000000864CFB, 24, 0x0000000000B704CE, 0x0000000000000000, false); crc24.digest(b"hello"); */ #![cfg_attr( feature = "alloc", doc = " assert_eq!([71, 245, 138].to_vec(), crc24.get_crc_vec_be()); assert_eq!(\"0x47F58A\", &crc24.to_string()); " )] /*! ``` */ /*! To simplify the usage, there are several common versions of CRC whose computing functions are already built-in. * crc3gsm * crc4itu * crc4interlaken * crc5epc * crc5itu * crc5usb * crc6cdma2000_a * crc6cdma2000_b * crc6darc * crc6gsm * crc6itu * crc7 * crc7umts * crc8 * crc8cdma2000 * crc8darc * crc8dvb_s2 * crc8ebu * crc8icode * crc8itu * crc8maxim * crc8rohc * crc8wcdma * crc10 * crc10cdma2000 * crc10gsm * crc11 * crc12 * crc12cdma2000 * crc12gsm * crc13bbc * crc14darc * crc14gsm * crc15can * crc15mpt1327 * crc16 * crc16ccitt_false * crc16aug_ccitt * crc16buypass * crc16cdma2000 * crc16dds_110 * crc16dect_r * crc16dect_x * crc16dnp * crc16en_13757 * crc16genibus * crc16maxim * crc16mcrf4cc * crc16riello * crc16t10_dif * crc16teledisk * crc16tms13157 * crc16usb * crc_a * crc16kermit * crc16modbus * crc16_x25 * crc16xmodem * crc17can * crc21can * crc24 * crc24ble * crc24flexray_a * crc24flexray_b * crc24lte_a * crc24lte_b * crc24os9 * crc30cdma * crc32 * It also called `crc32b` in `mhash`. * crc32mhash * `mhash` is a common library which has two weird versions of CRC32 called `crc32` and `crc32b`. `crc32` and `crc32mhash` in this module are `crc32b` and `crc32` in mhash respectively. * crc32bzip2 * crc32c * crc32d * crc32mpeg2 * crc32posix * crc32q * crc32jamcrc * crc32xfer * crc40gsm * crc64 * crc64iso * crc64we * crc64jones For instance, ```rust use crc_any::CRC; let mut crc64 = CRC::crc64(); crc64.digest(b"hello"); */ #![cfg_attr( feature = "alloc", doc = " assert_eq!([64, 84, 74, 48, 97, 55, 182, 236].to_vec(), crc64.get_crc_vec_be()); assert_eq!(\"0x40544A306137B6EC\", &crc64.to_string()); " )] /*! ``` */ /*! After getting a CRC value, you can still use the `digest` method to continue computing the next CRC values. ## Heapless Support To make sure this crate will not use heap memory allocation, you can disable the default features. ```toml [dependencies.crc-any] version = "*" default-features = false ``` After doing that, the `get_crc_vec_be` and `get_crc_vec_le` methods can not be used. But if you still need this crate to return a `Vec` without dynamic allocation, you can enable the `heapless` feature to make the `get_crc_heapless_vec_be` and `get_crc_heapless_vec_le` methods available. ```toml [dependencies.crc-any] version = "*" default-features = false features = ["heapless"] ``` */ #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "alloc")] #[macro_use] extern crate alloc; #[cfg(feature = "alloc")] use alloc::fmt::{self, Display, Formatter}; #[cfg(feature = "alloc")] use alloc::vec::Vec; #[cfg(feature = "heapless")] use heapless::Vec as HeaplessVec; mod constants; mod crc_u16; mod crc_u32; mod crc_u64; mod crc_u8; mod lookup_table; pub use crc_u16::CRCu16; pub use crc_u32::CRCu32; pub use crc_u64::CRCu64; pub use crc_u8::CRCu8; #[allow(clippy::upper_case_acronyms, clippy::large_enum_variant)] /// This struct can help you compute a CRC value. #[cfg_attr(feature = "alloc", derive(Debug))] pub enum CRC { CRCu8(CRCu8), CRCu16(CRCu16), CRCu32(CRCu32), CRCu64(CRCu64), } #[cfg(feature = "alloc")] impl Display for CRC { #[inline] fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { match self { CRC::CRCu8(crc) => Display::fmt(crc, f), CRC::CRCu16(crc) => Display::fmt(crc, f), CRC::CRCu32(crc) => Display::fmt(crc, f), CRC::CRCu64(crc) => Display::fmt(crc, f), } } } impl CRC { /// Create a CRC instance by providing the length of bits, expression, reflection, an initial value and a final xor value. #[inline] pub fn create_crc(poly: u64, bits: u8, initial: u64, final_xor: u64, reflect: bool) -> CRC { if bits <= 8 { Self::create_crc_u8(poly as u8, bits, initial as u8, final_xor as u8, reflect) } else if bits <= 16 { Self::create_crc_u16(poly as u16, bits, initial as u16, final_xor as u16, reflect) } else if bits <= 32 { Self::create_crc_u32(poly as u32, bits, initial as u32, final_xor as u32, reflect) } else if bits <= 64 { Self::create_crc_u64(poly, bits, initial, final_xor, reflect) } else { unimplemented!() } } /// Create a CRC instance by providing the length of bits, expression, reflection, an initial value and a final xor value. #[inline] pub fn create_crc_u8(poly: u8, bits: u8, initial: u8, final_xor: u8, reflect: bool) -> CRC { let crc = CRCu8::create_crc(poly, bits, initial, final_xor, reflect); CRC::CRCu8(crc) } /// Create a CRC instance by providing the length of bits, expression, reflection, an initial value and a final xor value. #[inline] pub fn create_crc_u16(poly: u16, bits: u8, initial: u16, final_xor: u16, reflect: bool) -> CRC { let crc = CRCu16::create_crc(poly, bits, initial, final_xor, reflect); CRC::CRCu16(crc) } /// Create a CRC instance by providing the length of bits, expression, reflection, an initial value and a final xor value. #[inline] pub fn create_crc_u32(poly: u32, bits: u8, initial: u32, final_xor: u32, reflect: bool) -> CRC { let crc = CRCu32::create_crc(poly, bits, initial, final_xor, reflect); CRC::CRCu32(crc) } /// Create a CRC instance by providing the length of bits, expression, reflection, an initial value and a final xor value. #[inline] pub fn create_crc_u64(poly: u64, bits: u8, initial: u64, final_xor: u64, reflect: bool) -> CRC { let crc = CRCu64::create_crc(poly, bits, initial, final_xor, reflect); CRC::CRCu64(crc) } /// Digest some data. #[inline] pub fn digest<T: ?Sized + AsRef<[u8]>>(&mut self, data: &T) { match self { CRC::CRCu8(crc) => crc.digest(data), CRC::CRCu16(crc) => crc.digest(data), CRC::CRCu32(crc) => crc.digest(data), CRC::CRCu64(crc) => crc.digest(data), } } /// Reset the sum. #[inline] pub fn reset(&mut self) { match self { CRC::CRCu8(crc) => crc.reset(), CRC::CRCu16(crc) => crc.reset(), CRC::CRCu32(crc) => crc.reset(), CRC::CRCu64(crc) => crc.reset(), } } /// Get the current CRC value (it always returns a `u64` value). You can continue calling `digest` method even after getting a CRC value. #[inline] pub fn get_crc(&mut self) -> u64 { match self { CRC::CRCu8(crc) => u64::from(crc.get_crc()), CRC::CRCu16(crc) => u64::from(crc.get_crc()), CRC::CRCu32(crc) => u64::from(crc.get_crc()), CRC::CRCu64(crc) => crc.get_crc(), } } } #[cfg(feature = "alloc")] impl CRC { /// Get the current CRC value (it always returns a vec instance with a length corresponding to the CRC bits). You can continue calling `digest` method even after getting a CRC value. #[inline] pub fn get_crc_vec_le(&mut self) -> Vec<u8> { match self { CRC::CRCu8(crc) => vec![crc.get_crc()], CRC::CRCu16(crc) => crc.get_crc_vec_le(), CRC::CRCu32(crc) => crc.get_crc_vec_le(), CRC::CRCu64(crc) => crc.get_crc_vec_le(), } } /// Get the current CRC value (it always returns a vec instance with a length corresponding to the CRC bits). You can continue calling `digest` method even after getting a CRC value. #[inline] pub fn get_crc_vec_be(&mut self) -> Vec<u8> { match self { CRC::CRCu8(crc) => vec![crc.get_crc()], CRC::CRCu16(crc) => crc.get_crc_vec_be(), CRC::CRCu32(crc) => crc.get_crc_vec_be(), CRC::CRCu64(crc) => crc.get_crc_vec_be(), } } } #[cfg(feature = "heapless")] impl CRC { /// Get the current CRC value (it always returns a vec instance with a length corresponding to the CRC bits). You can continue calling `digest` method even after getting a CRC value. pub fn get_crc_heapless_vec_le(&mut self) -> HeaplessVec<u8, 8> { let mut vec = HeaplessVec::new(); let bits = match self { CRC::CRCu8(crc) => f64::from(crc.bits), CRC::CRCu16(crc) => f64::from(crc.bits), CRC::CRCu32(crc) => f64::from(crc.bits), CRC::CRCu64(crc) => f64::from(crc.bits), }; let e = ((bits + 7f64) / 8f64) as u64; let e_dec = e - 1; let o = e_dec * 8; let crc = self.get_crc(); for i in 0..e { vec.push((crc << ((e_dec - i) * 8) >> o) as u8).unwrap(); } vec } /// Get the current CRC value (it always returns a vec instance with a length corresponding to the CRC bits). You can continue calling `digest` method even after getting a CRC value. pub fn get_crc_heapless_vec_be(&mut self) -> HeaplessVec<u8, 8> { let mut vec = HeaplessVec::new(); let bits = match self { CRC::CRCu8(crc) => f64::from(crc.bits), CRC::CRCu16(crc) => f64::from(crc.bits), CRC::CRCu32(crc) => f64::from(crc.bits), CRC::CRCu64(crc) => f64::from(crc.bits), }; let e = ((bits + 7f64) / 8f64) as u64; let e_dec = e - 1; let o = e_dec * 8; let crc = self.get_crc(); for i in 0..e { vec.push((crc << (i * 8) >> o) as u8).unwrap(); } vec } } impl CRC { // TODO: CRC-3 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x4|0x3|0x0|false|0x7| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc3gsm(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x4\", &crc.to_string());")] /// ``` pub fn crc3gsm() -> CRC { CRC::CRCu8(CRCu8::crc3gsm()) } // TODO: CRC-4 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x7|0x3 (rev: 0xC)|0x0|true|0x0| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc4itu(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x7\", &crc.to_string());")] /// ``` pub fn crc4itu() -> CRC { CRC::CRCu8(CRCu8::crc4itu()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xB|0x3|0xF|false|0xF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc4interlaken(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xB\", &crc.to_string());")] /// ``` pub fn crc4interlaken() -> CRC { CRC::CRCu8(CRCu8::crc4interlaken()) } // TODO: CRC-5 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x00|0x09|0x09|false|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc5epc(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x00\", &crc.to_string());")] /// ``` pub fn crc5epc() -> CRC { CRC::CRCu8(CRCu8::crc5epc()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x07|0x15 (rev: 0x15)|0x00|true|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc5itu(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x07\", &crc.to_string());")] /// ``` pub fn crc5itu() -> CRC { CRC::CRCu8(CRCu8::crc5itu()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x19|0x05 (rev: 0x14)|0x1F|true|0x1F| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc5usb(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x19\", &crc.to_string());")] /// ``` pub fn crc5usb() -> CRC { CRC::CRCu8(CRCu8::crc5usb()) } // TODO: CRC-6 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x0D|0x27|0x3F|false|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc6cdma2000_a(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x0D\", &crc.to_string());")] /// ``` #[inline] pub fn crc6cdma2000_a() -> CRC { CRC::CRCu8(CRCu8::crc6cdma2000_a()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x3B|0x07|0x3F|false|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc6cdma2000_b(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x3B\", &crc.to_string());")] /// ``` #[inline] pub fn crc6cdma2000_b() -> CRC { CRC::CRCu8(CRCu8::crc6cdma2000_b()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x26|0x19 (rev: 0x26)|0x00|true|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc6darc(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x26\", &crc.to_string());")] /// ``` #[inline] pub fn crc6darc() -> CRC { CRC::CRCu8(CRCu8::crc6darc()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x13|0x2F|0x00|false|0x3F| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc6gsm(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x13\", &crc.to_string());")] /// ``` #[inline] pub fn crc6gsm() -> CRC { CRC::CRCu8(CRCu8::crc6gsm()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x06|0x03 (rev: 0x30)|0x00|true|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc6itu(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x06\", &crc.to_string());")] /// ``` #[inline] pub fn crc6itu() -> CRC { CRC::CRCu8(CRCu8::crc6itu()) } // TODO: CRC-7 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x75|0x09|0x00|false|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc7(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x75\", &crc.to_string());")] /// ``` #[inline] pub fn crc7() -> CRC { CRC::CRCu8(CRCu8::crc7()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x61|0x45|0x00|false|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc7umts(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x61\", &crc.to_string());")] /// ``` #[inline] pub fn crc7umts() -> CRC { CRC::CRCu8(CRCu8::crc7umts()) } // TODO: CRC-8 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xF4|0x07|0x00|false|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc8(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xF4\", &crc.to_string());")] /// ``` #[inline] pub fn crc8() -> CRC { CRC::CRCu8(CRCu8::crc8()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xDA|0x9B|0xFF|false|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc8cdma2000(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xDA\", &crc.to_string());")] /// ``` #[inline] pub fn crc8cdma2000() -> CRC { CRC::CRCu8(CRCu8::crc8cdma2000()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xDA|0x39 (rev: 0x9C)|0x00|true|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc8darc(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x15\", &crc.to_string());")] /// ``` #[inline] pub fn crc8darc() -> CRC { CRC::CRCu8(CRCu8::crc8darc()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xBC|0xD5|0x00|false|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc8dvb_s2(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xBC\", &crc.to_string());")] /// ``` #[inline] pub fn crc8dvb_s2() -> CRC { CRC::CRCu8(CRCu8::crc8dvb_s2()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x97|0x1D (rev: 0xB8)|0xFF|true|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc8ebu(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x97\", &crc.to_string());")] /// ``` #[inline] pub fn crc8ebu() -> CRC { CRC::CRCu8(CRCu8::crc8ebu()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x7E|0x1D|0xFD|false|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc8icode(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x7E\", &crc.to_string());")] /// ``` #[inline] pub fn crc8icode() -> CRC { CRC::CRCu8(CRCu8::crc8icode()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xA1|0x07|0x00|false|0x55| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc8itu(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xA1\", &crc.to_string());")] /// ``` #[inline] pub fn crc8itu() -> CRC { CRC::CRCu8(CRCu8::crc8itu()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xA1|0x31 (rev: 0x8C)|0x00|true|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc8maxim(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xA1\", &crc.to_string());")] /// ``` #[inline] pub fn crc8maxim() -> CRC { CRC::CRCu8(CRCu8::crc8maxim()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xD0|0x07 (rev: 0xE0)|0xFF|true|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc8rohc(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xD0\", &crc.to_string());")] /// ``` #[inline] pub fn crc8rohc() -> CRC { CRC::CRCu8(CRCu8::crc8rohc()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x25|0x9B (rev: 0xD9)|0x00|true|0x00| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc8wcdma(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x25\", &crc.to_string());")] /// ``` #[inline] pub fn crc8wcdma() -> CRC { CRC::CRCu8(CRCu8::crc8wcdma()) } // TODO: CRC-10 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x199|0x233|0x000|false|0x000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc10(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x199\", &crc.to_string());")] /// ``` #[inline] pub fn crc10() -> CRC { CRC::CRCu16(CRCu16::crc10()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x233|0x3D9|0x3FF|false|0x000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc10cdma2000(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x233\", &crc.to_string());")] /// ``` #[inline] pub fn crc10cdma2000() -> CRC { CRC::CRCu16(CRCu16::crc10cdma2000()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x12A|0x175|0x000|false|0x3FF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc10gsm(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x12A\", &crc.to_string());")] /// ``` #[inline] pub fn crc10gsm() -> CRC { CRC::CRCu16(CRCu16::crc10gsm()) } // TODO: CRC-11 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x5A3|0x385|0x01a|false|0x000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc11(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x5A3\", &crc.to_string());")] /// ``` #[inline] pub fn crc11() -> CRC { CRC::CRCu16(CRCu16::crc11()) } // TODO: CRC-12 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xF5B|0x080F|0x0000|false|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc12(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xF5B\", &crc.to_string());")] /// ``` #[inline] pub fn crc12() -> CRC { CRC::CRCu16(CRCu16::crc12()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xD4D|0x0F13|0x0FFF|false|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc12cdma2000(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xD4D\", &crc.to_string());")] /// ``` #[inline] pub fn crc12cdma2000() -> CRC { CRC::CRCu16(CRCu16::crc12cdma2000()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xB34|0x0D31|0x0000|false|0x0FFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc12gsm(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xB34\", &crc.to_string());")] /// ``` #[inline] pub fn crc12gsm() -> CRC { CRC::CRCu16(CRCu16::crc12gsm()) } // TODO: CRC-13 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x04FA|0x1CF5|0x0000|false|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc13bbc(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x04FA\", &crc.to_string());")] /// ``` #[inline] pub fn crc13bbc() -> CRC { CRC::CRCu16(CRCu16::crc13bbc()) } // TODO: CRC-14 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x082D|0x0805 (rev: 0x2804)|0x0000|true|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc14darc(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x082D\", &crc.to_string());")] /// ``` #[inline] pub fn crc14darc() -> CRC { CRC::CRCu16(CRCu16::crc14darc()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x30AE|0x202D|0x0000|false|0x3FFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc14gsm(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x30AE\", &crc.to_string());")] /// ``` #[inline] pub fn crc14gsm() -> CRC { CRC::CRCu16(CRCu16::crc14gsm()) } // TODO: CRC-15 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x059E|0x4599|0x0000|false|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc15can(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x059E\", &crc.to_string());")] /// ``` #[inline] pub fn crc15can() -> CRC { CRC::CRCu16(CRCu16::crc15can()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x2566|0x6815|0x0000|false|0x0001| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc15mpt1327(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x2566\", &crc.to_string());")] /// ``` #[inline] pub fn crc15mpt1327() -> CRC { CRC::CRCu16(CRCu16::crc15mpt1327()) } // TODO: CRC-16 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xBB3D|0x8005 (rev: 0xA001)|0x0000|true|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xBB3D\", &crc.to_string());")] /// ``` #[inline] pub fn crc16() -> CRC { CRC::CRCu16(CRCu16::crc16()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x29B1|0x1021|0xFFFF|false|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16ccitt_false(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x29B1\", &crc.to_string());")] /// ``` #[inline] pub fn crc16ccitt_false() -> CRC { CRC::CRCu16(CRCu16::crc16ccitt_false()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xE5CC|0x1021|0x1D0F|false|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16aug_ccitt(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xE5CC\", &crc.to_string());")] /// ``` #[inline] pub fn crc16aug_ccitt() -> CRC { CRC::CRCu16(CRCu16::crc16aug_ccitt()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xFEE8|0x8005|0x0000|false|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16buypass(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xFEE8\", &crc.to_string());")] /// ``` #[inline] pub fn crc16buypass() -> CRC { CRC::CRCu16(CRCu16::crc16buypass()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x4C06|0xC867|0xFFFF|false|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16cdma2000(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x4C06\", &crc.to_string());")] /// ``` #[inline] pub fn crc16cdma2000() -> CRC { CRC::CRCu16(CRCu16::crc16cdma2000()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x9ECF|0x8005|0x800D|false|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16dds_110(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x9ECF\", &crc.to_string());")] /// ``` #[inline] pub fn crc16dds_110() -> CRC { CRC::CRCu16(CRCu16::crc16dds_110()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x007E|0x0589|0x0000|false|0x0001| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16dect_r(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x007E\", &crc.to_string());")] /// ``` #[inline] pub fn crc16dect_r() -> CRC { CRC::CRCu16(CRCu16::crc16dect_r()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x007F|0x0589|0x0000|false|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16dect_r(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x007E\", &crc.to_string());")] /// ``` #[inline] pub fn crc16dect_x() -> CRC { CRC::CRCu16(CRCu16::crc16dect_x()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xEA82|0x3D65 (rev: 0xA6BC)|0x0000|true|0xFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16dnp(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xEA82\", &crc.to_string());")] /// ``` #[inline] pub fn crc16dnp() -> CRC { CRC::CRCu16(CRCu16::crc16dnp()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xC2B7|0x3D65|0x0000|false|0xFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16en_13757(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xC2B7\", &crc.to_string());")] /// ``` #[inline] pub fn crc16en_13757() -> CRC { CRC::CRCu16(CRCu16::crc16en_13757()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xD64E|0x1021|0xFFFF|false|0xFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16genibus(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xD64E\", &crc.to_string());")] /// ``` #[inline] pub fn crc16genibus() -> CRC { CRC::CRCu16(CRCu16::crc16genibus()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x44C2|0x8005 (rev: 0xA001)|0xFFFF|true|0xFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16maxim(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x44C2\", &crc.to_string());")] /// ``` #[inline] pub fn crc16maxim() -> CRC { CRC::CRCu16(CRCu16::crc16maxim()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x6F91|0x1021 (rev: 0x8408)|0xFFFF|true|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16mcrf4cc(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x6F91\", &crc.to_string());")] /// ``` #[inline] pub fn crc16mcrf4cc() -> CRC { CRC::CRCu16(CRCu16::crc16mcrf4cc()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x63D0|0x1021 (rev: 0x8408)|0xB2AA|true|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16riello(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x63D0\", &crc.to_string());")] /// ``` #[inline] pub fn crc16riello() -> CRC { CRC::CRCu16(CRCu16::crc16riello()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xD0DB|0x8BB7|0x0000|false|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16t10_dif(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xD0DB\", &crc.to_string());")] /// ``` #[inline] pub fn crc16t10_dif() -> CRC { CRC::CRCu16(CRCu16::crc16t10_dif()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x0FB3|0xA097|0x0000|false|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16teledisk(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x0FB3\", &crc.to_string());")] /// ``` #[inline] pub fn crc16teledisk() -> CRC { CRC::CRCu16(CRCu16::crc16teledisk()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x26B1|0x1021 (rev: 0x8408)|0x89EC|true|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16tms13157(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x26B1\", &crc.to_string());")] /// ``` #[inline] pub fn crc16tms13157() -> CRC { CRC::CRCu16(CRCu16::crc16tms13157()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xB4C8|0x8005 (rev: 0xA001)|0xFFFF|true|0xFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16usb(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xB4C8\", &crc.to_string());")] /// ``` #[inline] pub fn crc16usb() -> CRC { CRC::CRCu16(CRCu16::crc16usb()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xBF05|0x1021 (rev: 0x8408)|0xC6C6|true|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc_a(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xBF05\", &crc.to_string());")] /// ``` #[inline] pub fn crc_a() -> CRC { CRC::CRCu16(CRCu16::crc_a()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x2189|0x1021 (rev: 0x8408)|0x0000|true|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16kermit(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x2189\", &crc.to_string());")] /// ``` #[inline] pub fn crc16kermit() -> CRC { CRC::CRCu16(CRCu16::crc16kermit()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x4B37|0x8005 (rev: 0xA001)|0xFFFF|true|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16modbus(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x4B37\", &crc.to_string());")] /// ``` #[inline] pub fn crc16modbus() -> CRC { CRC::CRCu16(CRCu16::crc16modbus()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x906E|0x8005 (rev: 0xA001)|0xFFFF|true|0xFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16_x25(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x906E\", &crc.to_string());")] /// ``` #[inline] pub fn crc16_x25() -> CRC { CRC::CRCu16(CRCu16::crc16_x25()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x31C3|0x1021|0x0000|false|0x0000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc16xmodem(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x31C3\", &crc.to_string());")] /// ``` #[inline] pub fn crc16xmodem() -> CRC { CRC::CRCu16(CRCu16::crc16xmodem()) } // TODO: CRC-17 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x04F03|0x1685B|0x00000|false|0x00000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc17can(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x04F03\", &crc.to_string());")] /// ``` #[inline] pub fn crc17can() -> CRC { CRC::CRCu32(CRCu32::crc17can()) } // TODO: CRC-21 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x0ED841|0x102899|0x000000|false|0x000000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc21can(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x0ED841\", &crc.to_string());")] /// ``` #[inline] pub fn crc21can() -> CRC { CRC::CRCu32(CRCu32::crc21can()) } // TODO: CRC-24 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x21CF02|0x864CFB|0xB704CE|false|0x000000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc24(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x21CF02\", &crc.to_string());")] /// ``` #[inline] pub fn crc24() -> CRC { CRC::CRCu32(CRCu32::crc24()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xC25A56|0x00065B (rev: 0xDA6000)|0x555555|true|0x000000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc24ble(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xC25A56\", &crc.to_string());")] /// ``` #[inline] pub fn crc24ble() -> CRC { CRC::CRCu32(CRCu32::crc24ble()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x7979BD|0x5D6DCB|0xFEDCBA|false|0x000000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc24flexray_a(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x7979BD\", &crc.to_string());")] /// ``` #[inline] pub fn crc24flexray_a() -> CRC { CRC::CRCu32(CRCu32::crc24flexray_a()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x1F23B8|0x5D6DCB|0xABCDEF|false|0x000000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc24flexray_b(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x1F23B8\", &crc.to_string());")] /// ``` #[inline] pub fn crc24flexray_b() -> CRC { CRC::CRCu32(CRCu32::crc24flexray_b()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xCDE703|0x864CFB|0x000000|false|0x000000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc24lte_a(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xCDE703\", &crc.to_string());")] /// ``` #[inline] pub fn crc24lte_a() -> CRC { CRC::CRCu32(CRCu32::crc24lte_a()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x23EF52|0x800063|0x000000|false|0x000000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc24lte_b(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x23EF52\", &crc.to_string());")] /// ``` #[inline] pub fn crc24lte_b() -> CRC { CRC::CRCu32(CRCu32::crc24lte_b()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x200FA5|0x800063|0xFFFFFF|false|0xFFFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc24os9(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x200FA5\", &crc.to_string());")] /// ``` #[inline] pub fn crc24os9() -> CRC { CRC::CRCu32(CRCu32::crc24os9()) } // TODO: CRC-30 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x04C34ABF|0x2030B9C7|0x3FFFFFFF|false|0x3FFFFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc30cdma(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x04C34ABF\", &crc.to_string());")] /// ``` #[inline] pub fn crc30cdma() -> CRC { CRC::CRCu32(CRCu32::crc30cdma()) } // TODO: CRC-32 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xCBF43926|0x04C11DB7 (rev: 0xEDB88320)|0xFFFFFFFF|true|0xFFFFFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc32(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xCBF43926\", &crc.to_string());")] /// ``` #[inline] pub fn crc32() -> CRC { CRC::CRCu32(CRCu32::crc32()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x181989FC|0x04C11DB7|0xFFFFFFFF|false|0xFFFFFFFF| /// /// **Output will be reversed by bytes.** /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc32mhash(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x181989FC\", &crc.to_string());")] /// ``` #[inline] pub fn crc32mhash() -> CRC { CRC::CRCu32(CRCu32::crc32mhash()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xFC891918|0x04C11DB7|0xFFFFFFFF|false|0xFFFFFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc32bzip2(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xFC891918\", &crc.to_string());")] /// ``` #[inline] pub fn crc32bzip2() -> CRC { CRC::CRCu32(CRCu32::crc32bzip2()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xE3069283|0x1EDC6F41 (rev: 0x82F63B78)|0xFFFFFFFF|true|0xFFFFFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc32c(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xE3069283\", &crc.to_string());")] /// ``` #[inline] pub fn crc32c() -> CRC { CRC::CRCu32(CRCu32::crc32c()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x87315576|0xA833982B (rev: 0xD419CC15)|0xFFFFFFFF|true|0xFFFFFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc32d(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x87315576\", &crc.to_string());")] /// ``` #[inline] pub fn crc32d() -> CRC { CRC::CRCu32(CRCu32::crc32d()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x0376E6E7|0x04C11DB7|0xFFFFFFFF|false|0x00000000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc32mpeg2(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x0376E6E7\", &crc.to_string());")] /// ``` #[inline] pub fn crc32mpeg2() -> CRC { CRC::CRCu32(CRCu32::crc32mpeg2()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x765E7680|0x04C11DB7|0x00000000|false|0xFFFFFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc32posix(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x765E7680\", &crc.to_string());")] /// ``` #[inline] pub fn crc32posix() -> CRC { CRC::CRCu32(CRCu32::crc32posix()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x3010BF7F|0x814141AB|0x00000000|false|0x00000000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc32q(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x3010BF7F\", &crc.to_string());")] /// ``` #[inline] pub fn crc32q() -> CRC { CRC::CRCu32(CRCu32::crc32q()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x340BC6D9|0x04C11DB7 (rev: 0xEDB88320)|0x00000000|true|0x00000000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc32jamcrc(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x340BC6D9\", &crc.to_string());")] /// ``` #[inline] pub fn crc32jamcrc() -> CRC { CRC::CRCu32(CRCu32::crc32jamcrc()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xBD0BE338|0x000000AF|0x00000000|false|0x00000000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc32xfer(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xBD0BE338\", &crc.to_string());")] /// ``` #[inline] pub fn crc32xfer() -> CRC { CRC::CRCu32(CRCu32::crc32xfer()) } // TODO: CRC-40 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xD4164FC646|0x0004820009|0x0000000000|false|0xFFFFFFFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc40gsm(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xD4164FC646\", &crc.to_string());")] /// ``` #[inline] pub fn crc40gsm() -> CRC { CRC::CRCu64(CRCu64::crc40gsm()) } // TODO: CRC-64 /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x6C40DF5F0B497347|0x42F0E1EBA9EA3693|0x0000000000000000|false|0x0000000000000000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc64(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x6C40DF5F0B497347\", &crc.to_string());")] /// ``` #[inline] pub fn crc64() -> CRC { CRC::CRCu64(CRCu64::crc64()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xB90956C775A41001|0x000000000000001B (rev: 0xD800000000000000)|0xFFFFFFFFFFFFFFFF|true|0xFFFFFFFFFFFFFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc64iso(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xB90956C775A41001\", &crc.to_string());")] /// ``` #[inline] pub fn crc64iso() -> CRC { CRC::CRCu64(CRCu64::crc64iso()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0x62EC59E3F1A4F00A|0x42F0E1EBA9EA3693|0xFFFFFFFFFFFFFFFF|false|0xFFFFFFFFFFFFFFFF| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc64we(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0x62EC59E3F1A4F00A\", &crc.to_string());")] /// ``` #[inline] pub fn crc64we() -> CRC { CRC::CRCu64(CRCu64::crc64we()) } /// |Check|Poly|Init|Ref|XorOut| /// |---|---|---|---|---| /// |0xE9C6D914C4B8D9CA|0xAD93D23594C935A9 (rev: 0x95AC9329AC4BC9B5)|0x0000000000000000|true|0x0000000000000000| /// /// ``` /// # use crc_any::CRC; /// let mut crc = CRC::crc64jones(); /// crc.digest(b"123456789"); #[cfg_attr(feature = "alloc", doc = "assert_eq!(\"0xE9C6D914C4B8D9CA\", &crc.to_string());")] /// ``` #[inline] pub fn crc64jones() -> CRC { CRC::CRCu64(CRCu64::crc64jones()) } }
use std::path::PathBuf; #[derive(Clone)] pub struct Context { pub current_dir: PathBuf, }
#[doc = "Register `ITLINE21` reader"] pub type R = crate::R<ITLINE21_SPEC>; #[doc = "Field `TIM16` reader - TIM16"] pub type TIM16_R = crate::BitReader; impl R { #[doc = "Bit 0 - TIM16"] #[inline(always)] pub fn tim16(&self) -> TIM16_R { TIM16_R::new((self.bits & 1) != 0) } } #[doc = "interrupt line 21 status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`itline21::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ITLINE21_SPEC; impl crate::RegisterSpec for ITLINE21_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`itline21::R`](R) reader structure"] impl crate::Readable for ITLINE21_SPEC {} #[doc = "`reset()` method sets ITLINE21 to value 0"] impl crate::Resettable for ITLINE21_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::{ fmt::{Debug, Display, Formatter}, string::FromUtf8Error, {io, net}, }; use crate::error::RconError::{AddressParse, UTFEncoding, IO}; /// A common error enum that is returned by all public functions describing different forms of failures that can occur within this library. #[derive(Debug)] pub enum RconError { /// There is an error in the passed address field AddressParse(net::AddrParseError), /// There was a network issue during connection or exec IO(io::Error), /// The command provided is longer than 1014 characters. CommandTooLong, /// The server did not respond with proper UTF-8 UTFEncoding(FromUtf8Error), /// The server sent a packet with a type we were not expecting. UnexpectedPacket, /// The pass field is incorrect PasswordIncorrect, /// Returned by [`ReConnection::exec`](struct.ReConnection.html#method.exec) when [`ReConnection`](struct.ReConnection.html) is busy reconnecting. BusyReconnecting(String), } impl ::std::error::Error for RconError { fn source(&self) -> Option<&(dyn ::std::error::Error + 'static)> { match self { IO(e) => Some(e), AddressParse(e) => Some(e), UTFEncoding(e) => Some(e), _ => None, } } } impl Display for RconError { fn fmt(&self, f: &mut Formatter) -> Result<(), ::std::fmt::Error> { (self as &dyn Debug).fmt(f) } } impl From<io::Error> for RconError { fn from(e: io::Error) -> Self { IO(e) } } impl From<net::AddrParseError> for RconError { fn from(e: net::AddrParseError) -> Self { AddressParse(e) } } impl From<FromUtf8Error> for RconError { fn from(e: FromUtf8Error) -> Self { UTFEncoding(e) } }
use std::str::FromStr; use crate::error::{LookoutError, Result}; #[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct ASn(pub u16); impl FromStr for ASn { type Err = LookoutError; fn from_str(s: &str) -> Result<ASn> { if s.len() > 2 && (s.starts_with("AS") || s.starts_with("as")) { Ok(ASn(s[2..].parse()?)) } else { Ok(ASn(s.parse()?)) } } } impl From<u16> for ASn { fn from(asn: u16) -> ASn { ASn(asn) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_asn() { assert_eq!("123".parse::<ASn>().unwrap(), ASn(123)); assert_eq!("AS123".parse::<ASn>().unwrap(), ASn(123)); assert_eq!("as123".parse::<ASn>().unwrap(), ASn(123)); assert!("AS".parse::<ASn>().is_err()); assert!("As123".parse::<ASn>().is_err()); assert!("".parse::<ASn>().is_err()); } }
// Added as part the code review and testing // by ChainSafe Systems Aug 2021 use super::*; use frame_benchmarking::{benchmarks, impl_benchmark_test_suite}; use frame_system::RawOrigin; // all methods in XXEconomics are basic admin get/set of variables // so the benchmarks are trivial benchmarks!{ set_inflation_params { }: _(RawOrigin::Root, Default::default()) set_interest_points { }: _(RawOrigin::Root, Default::default()) set_liquidity_rewards_stake { }: _(RawOrigin::Root, Default::default()) set_liquidity_rewards_balance { }: _(RawOrigin::Root, Default::default()) } impl_benchmark_test_suite!( XXEconomics, crate::mock::ExtBuilder::default() .build(), crate::mock::Test, );
/** * 型ポインタ 型のエイリアス的な? * 変数は値に値に付く別名だから、関数に変数をつける。これが関数ポインタ */ fn double(n:i32) -> i32 { n + n } fn abs(n:i32) -> i32 { if n > 0 {n} else {-n} } fn main() { let mut f: fn(i32) -> i32 = double; assert_eq!(f(-42), -84); f = abs; assert_eq!(f(-42), 42); // fのサイズ8byte println!("std: {:?}", std::mem::size_of_val(&f)); println!("std: {:?}", std::mem::size_of::<usize>()); assert_eq!(std::mem::size_of_val(&f), std::mem::size_of::<usize>()); }
// Copyright 2018-2019 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. use std::{fmt, io, path::PathBuf}; use bincode::Error as BincodeError; use crate::{backend::traits::BackendError, error::StoreError}; #[derive(Debug)] pub enum ErrorImpl { KeyValuePairNotFound, EnvPoisonError, DbsFull, DbsIllegalOpen, DbNotFoundError, DbIsForeignError, UnsuitableEnvironmentPath(PathBuf), IoError(io::Error), BincodeError(BincodeError), } impl BackendError for ErrorImpl {} impl fmt::Display for ErrorImpl { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { ErrorImpl::KeyValuePairNotFound => write!(fmt, "KeyValuePairNotFound (safe mode)"), ErrorImpl::EnvPoisonError => write!(fmt, "EnvPoisonError (safe mode)"), ErrorImpl::DbsFull => write!(fmt, "DbsFull (safe mode)"), ErrorImpl::DbsIllegalOpen => write!(fmt, "DbIllegalOpen (safe mode)"), ErrorImpl::DbNotFoundError => write!(fmt, "DbNotFoundError (safe mode)"), ErrorImpl::DbIsForeignError => write!(fmt, "DbIsForeignError (safe mode)"), ErrorImpl::UnsuitableEnvironmentPath(_) => { write!(fmt, "UnsuitableEnvironmentPath (safe mode)") } ErrorImpl::IoError(e) => e.fmt(fmt), ErrorImpl::BincodeError(e) => e.fmt(fmt), } } } impl Into<StoreError> for ErrorImpl { fn into(self) -> StoreError { // The `StoreError::KeyValuePairBadSize` error is unused, because this // backend supports keys and values of arbitrary sizes. // The `StoreError::MapFull` and `StoreError::ReadersFull` are // unimplemented yet, but they should be in the future. match self { ErrorImpl::KeyValuePairNotFound => StoreError::KeyValuePairNotFound, ErrorImpl::BincodeError(_) => StoreError::FileInvalid, ErrorImpl::DbsFull => StoreError::DbsFull, ErrorImpl::UnsuitableEnvironmentPath(path) => { StoreError::UnsuitableEnvironmentPath(path) } ErrorImpl::IoError(error) => StoreError::IoError(error), _ => StoreError::SafeModeError(self), } } } impl From<io::Error> for ErrorImpl { fn from(e: io::Error) -> ErrorImpl { ErrorImpl::IoError(e) } } impl From<BincodeError> for ErrorImpl { fn from(e: BincodeError) -> ErrorImpl { ErrorImpl::BincodeError(e) } }
#[macro_use] extern crate log; #[macro_use] extern crate s_structured_log; extern crate serde_json; use s_structured_log::{JsonLogger, LoggerOutput, q}; fn main() { JsonLogger::init(LoggerOutput::Stdout, log::LogLevelFilter::Info); s_trace!(json_object! { "trace_key1" => 1, "trace_key2" => "value2" }); s_debug!(json_object! { "debug_key1" => 1, "debug_key2" => "value2" }); s_info!(json_object! { "info_key1" => 1, "info_key2" => "value2" }); s_warn!(json_object! { "warn_key1" => 1, "warn_key2" => "value2" }); s_error!(json_object! { "error_key1" => 1, "error_key2" => "value2" }); trace!("{:?}", json_object! { "trace_key1" => 1, "trace_key2" => "value2" }); error!("{}", json_format! { "error_key1" => 1, "error_key2" => q("value2"), "error_key3" => json_format![q("value3"),4] }); }
mod part_2_types_and_variables; mod part_3_control_flow; mod part_4_data_structures; mod part_5_standard_collections; fn main() { println!("+++++ PART 2 TYPES AND VARIABLES +++++"); part_2_types_and_variables::core_datatypes::run(); part_2_types_and_variables::operators::run(); part_2_types_and_variables::constants::run(); part_2_types_and_variables::scope::run(); part_2_types_and_variables::stuck_and_heap::run(); println!("+++++ PART 3 CONTROL FLOW +++++"); part_3_control_flow::if_statement::run(); part_3_control_flow::loops::run(); part_3_control_flow::match_statement::run(); // part_3_control_flow::combination_lock::run(); println!("+++++ PART 4 DATA STRUCTURES +++++"); part_4_data_structures::structs::run(); part_4_data_structures::enums::run(); part_4_data_structures::unions::run(); part_4_data_structures::option_if_let_while_let::run(); part_4_data_structures::arrays::run(); part_4_data_structures::tuples::run(); part_4_data_structures::pattern_matching::run(); part_4_data_structures::generics::run(); println!("+++++ PART 5 Standard Collections +++++"); part_5_standard_collections::overview::run(); part_5_standard_collections::vector::run(); // input::run(); }
extern crate msgpackio; extern crate argparse; use argparse::{ArgumentParser, StoreTrue, Store}; use std::fs::{File}; fn main() { let mut file_path = String::new(); { // this block limits scope of borrows by ap.refer() method let mut ap = ArgumentParser::new(); ap.set_description("MsgPack Dump Utility"); ap.refer(&mut file_path).add_argument("file_path", Store, "MsgPack File"); ap.parse_args_or_exit(); } if file_path.is_empty() { println!("No filename given"); return; } let mut f = File::open(file_path).unwrap(); let mut mpi = msgpackio::read::MsgPackIterator { reader: &mut f}; for v in mpi { println!("{:?}", v); } }
//! Errors from the crate. use thiserror::Error; /// Error from writting while saving files (data or plot scripts). #[derive(Error, Debug)] pub enum PreexplorerError { #[error("Saving error.")] Saving(#[from] std::io::Error), #[error("Plotting error.")] Plotting(std::io::Error), }