text
stringlengths
8
4.13M
use input_i_scanner::InputIScanner; use arithmetic_series::arithmetic_series; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { _i_i.scan::<$t>() as $t }; (($($t: ty),+); $n: expr) => { std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>() }; ($t: ty; $n: expr) => { std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>() }; } let n = scan!(u64); // 1 + 2 + 3 + ... let ans = arithmetic_series(1, (n + 1) / 2, 1).unwrap(); println!("{}", ans); }
use std::str::FromStr; use crate::Error; /// `Feet` or `FlightLevel` #[derive(Eq, PartialEq, Debug)] pub enum AltitudeUnit { Feet, FlightLevel, } impl FromStr for AltitudeUnit { type Err = Error; /// # Examples /// /// ``` /// # use std::str::FromStr; /// # use openaip::AltitudeUnit; /// # /// assert_eq!(AltitudeUnit::from_str("F").unwrap(), AltitudeUnit::Feet); /// assert_eq!(AltitudeUnit::from_str("FL").unwrap(), AltitudeUnit::FlightLevel); /// assert!(AltitudeUnit::from_str("foobar").is_err()); /// ``` fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "F" => Ok(AltitudeUnit::Feet), "FL" => Ok(AltitudeUnit::FlightLevel), _ => Err(Error::UnknownAltitudeUnit(s.to_string())), } } }
// Copyright 2020 IOTA Stiftung // // 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 crate::{Btrit, RawEncoding, RawEncodingBuf, TritBuf, Trits, Utrit}; use serde::{ de::{Error, SeqAccess, Unexpected, Visitor}, ser::SerializeSeq, Deserialize, Deserializer, Serialize, Serializer, }; use std::{convert::TryFrom, fmt, marker::PhantomData}; // Serialisation impl Serialize for Btrit { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { serializer.serialize_i8((*self).into()) } } impl Serialize for Utrit { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { serializer.serialize_i8((*self).into()) } } impl<'a, T: RawEncoding> Serialize for &'a Trits<T> where T::Trit: Serialize, T: serde::Serialize, { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { let mut seq = serializer.serialize_seq(Some(self.len()))?; for trit in self.iter() { seq.serialize_element(&trit)?; } seq.end() } } impl<T: RawEncodingBuf> Serialize for TritBuf<T> where <T::Slice as RawEncoding>::Trit: Serialize, { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { let mut seq = serializer.serialize_seq(Some(self.len()))?; for trit in self.iter() { seq.serialize_element(&trit)?; } seq.end() } } // Deserialisation struct BtritVisitor; impl<'de> Visitor<'de> for BtritVisitor { type Value = Btrit; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("a value between -1 and 1 inclusive") } fn visit_u64<E: Error>(self, trit: u64) -> Result<Self::Value, E> { i8::try_from(trit) .map_err(|_| ()) .and_then(|trit| Btrit::try_from(trit).map_err(|_| ())) .map_err(|_| E::invalid_value(Unexpected::Unsigned(trit), &self)) } fn visit_i64<E: Error>(self, trit: i64) -> Result<Self::Value, E> { i8::try_from(trit) .map_err(|_| ()) .and_then(|trit| Btrit::try_from(trit).map_err(|_| ())) .map_err(|_| E::invalid_value(Unexpected::Signed(trit), &self)) } fn visit_u8<E: Error>(self, trit: u8) -> Result<Self::Value, E> { i8::try_from(trit) .map_err(|_| ()) .and_then(|trit| Btrit::try_from(trit).map_err(|_| ())) .map_err(|_| E::invalid_value(Unexpected::Unsigned(trit as u64), &self)) } fn visit_i8<E: Error>(self, trit: i8) -> Result<Self::Value, E> { Btrit::try_from(trit).map_err(|_| E::invalid_value(Unexpected::Signed(trit as i64), &self)) } } impl<'de> Deserialize<'de> for Btrit { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { deserializer.deserialize_i8(BtritVisitor) } } struct UtritVisitor; impl<'de> Visitor<'de> for UtritVisitor { type Value = Utrit; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("a value between 0 and 2 inclusive") } fn visit_u64<E: Error>(self, trit: u64) -> Result<Self::Value, E> { u8::try_from(trit) .map_err(|_| ()) .and_then(|trit| Utrit::try_from(trit).map_err(|_| ())) .map_err(|_| E::invalid_value(Unexpected::Unsigned(trit), &self)) } fn visit_i64<E: Error>(self, trit: i64) -> Result<Self::Value, E> { i8::try_from(trit) .map_err(|_| ()) .and_then(|trit| Utrit::try_from(trit).map_err(|_| ())) .map_err(|_| E::invalid_value(Unexpected::Signed(trit), &self)) } fn visit_u8<E: Error>(self, trit: u8) -> Result<Self::Value, E> { Ok(trit) .and_then(|trit| Utrit::try_from(trit).map_err(|_| ())) .map_err(|_| E::invalid_value(Unexpected::Unsigned(trit as u64), &self)) } fn visit_i8<E: Error>(self, trit: i8) -> Result<Self::Value, E> { Utrit::try_from(trit).map_err(|_| E::invalid_value(Unexpected::Signed(trit as i64), &self)) } } impl<'de> Deserialize<'de> for Utrit { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { deserializer.deserialize_i8(UtritVisitor) } } struct TritBufVisitor<T>(PhantomData<T>); impl<'de, T: RawEncodingBuf> Visitor<'de> for TritBufVisitor<T> where <T::Slice as RawEncoding>::Trit: Deserialize<'de>, { type Value = TritBuf<T>; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("a sequence of trits") } fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> { let mut buf = TritBuf::with_capacity(seq.size_hint().unwrap_or(0)); while let Some(trit) = seq.next_element()? { buf.push(trit); } Ok(buf) } } impl<'de, T: RawEncodingBuf> Deserialize<'de> for TritBuf<T> where <T::Slice as RawEncoding>::Trit: Deserialize<'de>, { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { deserializer.deserialize_seq(TritBufVisitor::<T>(PhantomData)) } }
grass::grass_query! { let a = open("data/a.bed"); let b = open("data/b.bed"); a | subtract(b) | as_bed3() | show_all(); }
use super::*; use proptest::prop_oneof; use proptest::strategy::Strategy; #[test] fn without_non_empty_list_or_bitstring_second_returns_firsts() { run!( |arc_process| { strategy::term(arc_process.clone()) .prop_filter("Second cannot be a list or bitstring", |second| { !(second.is_non_empty_list() || second.is_bitstring()) }) }, |second| { let first = Term::NIL; prop_assert_eq!(result(first, second), first); Ok(()) }, ); } #[test] fn with_non_empty_list_or_bitstring_second_returns_second() { run!( |arc_process| { prop_oneof![ strategy::term::list::non_empty_maybe_improper(arc_process.clone()), strategy::term::is_bitstring(arc_process) ] }, |second| { let first = Term::NIL; prop_assert_eq!(result(first, second), second); Ok(()) }, ); }
#[doc = "Reader of register RIS"] pub type R = crate::R<u32, super::RIS>; #[doc = "Reader of field `INR0`"] pub type INR0_R = crate::R<bool, bool>; #[doc = "Reader of field `INR1`"] pub type INR1_R = crate::R<bool, bool>; #[doc = "Reader of field `INR2`"] pub type INR2_R = crate::R<bool, bool>; #[doc = "Reader of field `INR3`"] pub type INR3_R = crate::R<bool, bool>; #[doc = "Reader of field `DMAINR0`"] pub type DMAINR0_R = crate::R<bool, bool>; #[doc = "Reader of field `DMAINR1`"] pub type DMAINR1_R = crate::R<bool, bool>; #[doc = "Reader of field `DMAINR2`"] pub type DMAINR2_R = crate::R<bool, bool>; #[doc = "Reader of field `DMAINR3`"] pub type DMAINR3_R = crate::R<bool, bool>; #[doc = "Reader of field `INRDC`"] pub type INRDC_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - SS0 Raw Interrupt Status"] #[inline(always)] pub fn inr0(&self) -> INR0_R { INR0_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - SS1 Raw Interrupt Status"] #[inline(always)] pub fn inr1(&self) -> INR1_R { INR1_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - SS2 Raw Interrupt Status"] #[inline(always)] pub fn inr2(&self) -> INR2_R { INR2_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - SS3 Raw Interrupt Status"] #[inline(always)] pub fn inr3(&self) -> INR3_R { INR3_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 8 - SS0 DMA Raw Interrupt Status"] #[inline(always)] pub fn dmainr0(&self) -> DMAINR0_R { DMAINR0_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - SS1 DMA Raw Interrupt Status"] #[inline(always)] pub fn dmainr1(&self) -> DMAINR1_R { DMAINR1_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - SS2 DMA Raw Interrupt Status"] #[inline(always)] pub fn dmainr2(&self) -> DMAINR2_R { DMAINR2_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - SS3 DMA Raw Interrupt Status"] #[inline(always)] pub fn dmainr3(&self) -> DMAINR3_R { DMAINR3_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 16 - Digital Comparator Raw Interrupt Status"] #[inline(always)] pub fn inrdc(&self) -> INRDC_R { INRDC_R::new(((self.bits >> 16) & 0x01) != 0) } }
pub fn gcd(a: u32, b: u32) -> u32 { fn gcd_rec(m: u32, n: u32) -> u32 { assert!( m >= n, "m must be larger than or equal to n; got m={}, n={}", m, n ); if n == 0 { m } else { gcd_rec(n, m % n) } } let (m, n) = if a >= b { (a, b) } else { (b, a) }; gcd_rec(m, n) } #[cfg(test)] mod tests { use super::*; #[test] fn test_gcd() { assert_eq!(gcd(36, 63), 9); assert_eq!(gcd(63, 36), 9); assert_eq!(gcd(7, 21), 7); assert_eq!(gcd(19, 13), 1); } }
use std::{ cmp::max, fmt::{Debug, Display}, sync::Arc, }; use crate::components::{ split_or_compact::start_level_files_to_split::{merge_small_l0_chains, split_into_chains}, Components, }; use async_trait::async_trait; use data_types::{CompactionLevel, ParquetFile, Timestamp}; use itertools::Itertools; use observability_deps::tracing::debug; use crate::{error::DynError, PartitionInfo, RoundInfo}; /// Calculates information about what this compaction round does. /// When we get deeper into the compaction decision making, there /// may not be as much context information available. It may not /// be possible to reach the same conclusions about the intention /// for this compaction round. So RoundInfo must contain enough /// information carry that intention through the compactions. #[async_trait] pub trait RoundInfoSource: Debug + Display + Send + Sync { async fn calculate( &self, components: Arc<Components>, partition_info: &PartitionInfo, files: Vec<ParquetFile>, ) -> Result<(RoundInfo, Vec<Vec<ParquetFile>>, Vec<ParquetFile>), DynError>; } #[derive(Debug)] pub struct LoggingRoundInfoWrapper { inner: Arc<dyn RoundInfoSource>, } impl LoggingRoundInfoWrapper { pub fn new(inner: Arc<dyn RoundInfoSource>) -> Self { Self { inner } } } impl Display for LoggingRoundInfoWrapper { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "LoggingRoundInfoWrapper({})", self.inner) } } #[async_trait] impl RoundInfoSource for LoggingRoundInfoWrapper { async fn calculate( &self, components: Arc<Components>, partition_info: &PartitionInfo, files: Vec<ParquetFile>, ) -> Result<(RoundInfo, Vec<Vec<ParquetFile>>, Vec<ParquetFile>), DynError> { let res = self .inner .calculate(components, partition_info, files) .await; if let Ok((round_info, branches, files_later)) = &res { debug!(round_info_source=%self.inner, %round_info, branches=branches.len(), files_later=files_later.len(), "running round"); } res } } /// Computes the type of round based on the levels of the input files #[derive(Debug)] pub struct LevelBasedRoundInfo { pub max_num_files_per_plan: usize, pub max_total_file_size_per_plan: usize, } impl Display for LevelBasedRoundInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "LevelBasedRoundInfo {}", self.max_num_files_per_plan) } } impl LevelBasedRoundInfo { pub fn new(max_num_files_per_plan: usize, max_total_file_size_per_plan: usize) -> Self { Self { max_num_files_per_plan, max_total_file_size_per_plan, } } /// Returns true if the scenario looks like ManySmallFiles, but we can't group them well into branches. pub fn many_ungroupable_files( &self, files: &[ParquetFile], start_level: CompactionLevel, max_total_file_size_to_group: usize, ) -> bool { if self.too_many_small_files_to_compact(files, CompactionLevel::Initial) { let start_level_files = files .iter() .filter(|f| f.compaction_level == start_level) .collect::<Vec<_>>(); let start_count = start_level_files.len(); let mut chains = split_into_chains(start_level_files.into_iter().cloned().collect()); chains = merge_small_l0_chains(chains, max_total_file_size_to_group); if chains.len() > 1 && chains.len() > start_count / 3 { return true; } } false } /// Returns true if number of files of the given start_level and /// their overlapped files in next level is over limit, and if those /// files are sufficiently small. /// /// over the limit means that the maximum number of files that a subsequent compaction /// branch may choose to compact in a single plan would exceed `max_num_files_per_plan` pub fn too_many_small_files_to_compact( &self, files: &[ParquetFile], start_level: CompactionLevel, ) -> bool { let start_level_files = files .iter() .filter(|f| f.compaction_level == start_level) .collect::<Vec<_>>(); let num_start_level = start_level_files.len(); let size_start_level: usize = start_level_files .iter() .map(|f| f.file_size_bytes as usize) .sum(); let start_max_l0_created_at = start_level_files .iter() .map(|f| f.max_l0_created_at) .unique() .count(); let next_level_files = files .iter() .filter(|f| f.compaction_level == start_level.next()) .collect::<Vec<_>>(); // The compactor may compact all the target level and next level together in one // branch in the worst case, thus if that would result in too many files to compact in a single // plan, run a pre-phase to reduce the number of files first let num_overlapped_files = get_num_overlapped_files(start_level_files, next_level_files); if num_start_level > 1 && num_start_level + num_overlapped_files > self.max_num_files_per_plan { // This scaenario meets the simple criteria of start level files + their overlaps are lots of files. // But ManySmallFiles implies we must compact only within the start level to reduce the quantity of // start level files. There are several reasons why that might be unhelpful. // Reason 1: if all the start level files have the same max_l0_created_at, then they were split from // the same file. If we previously decided to split them, we should not undo that now. if start_max_l0_created_at == 1 { return false; } // Reason 2: Maybe its many LARGE files making reduction of file count in the start level impossible. if size_start_level / num_start_level > self.max_total_file_size_per_plan / self.max_num_files_per_plan { // Average start level file size is more than the average implied by max bytes & files per plan. // Even though there are "many files", this is not "many small files". // There isn't much (perhaps not any) file reduction to be done, attempting it can get us stuck // in a loop. return false; } // Reason 3: Maybe there are so many start level files because we did a bunch of splits. // Note that we'll do splits to ensure each start level file overlaps at most one target level file. // If the prior round did that, and now we declare this ManySmallFiles, which forces compactions // within the start level, we'll undo the splits performed in the prior round, which can get us // stuck in a loop. let chains = split_into_chains(files.to_vec()); let mut max_target_level_files: usize = 0; let mut max_chain_len: usize = 0; for chain in chains { let target_file_cnt = chain .iter() .filter(|f| f.compaction_level == start_level.next()) .count(); max_target_level_files = max(max_target_level_files, target_file_cnt); let chain_len = chain.len(); max_chain_len = max(max_chain_len, chain_len); } if max_target_level_files <= 1 && max_chain_len <= self.max_num_files_per_plan { // All of our start level files overlap with at most one target level file. If the prior round did // splits to cause this, declaring this a ManySmallFiles case can lead to an endless loop. // If we got lucky and this happened without splits, declaring this ManySmallFiles will waste // our good fortune. return false; } return true; } false } } #[async_trait] impl RoundInfoSource for LevelBasedRoundInfo { // The calculated RoundInfo is the most impactful decision for this round of compactions. // Later decisions should be just working out details to implement what RoundInfo dictates. async fn calculate( &self, components: Arc<Components>, _partition_info: &PartitionInfo, files: Vec<ParquetFile>, ) -> Result<(RoundInfo, Vec<Vec<ParquetFile>>, Vec<ParquetFile>), DynError> { // start_level is usually the lowest level we have files in, but occasionally we decide to // compact L1->L2 when L0s still exist. If this comes back as L1, we'll ignore L0s for this // round and force an early L1-L2 compaction. let start_level = get_start_level( &files, self.max_num_files_per_plan, self.max_total_file_size_per_plan, ); let round_info = if start_level == CompactionLevel::Initial && self.many_ungroupable_files(&files, start_level, self.max_num_files_per_plan) { RoundInfo::SimulatedLeadingEdge { max_num_files_to_group: self.max_num_files_per_plan, max_total_file_size_to_group: self.max_total_file_size_per_plan, } } else if start_level == CompactionLevel::Initial && self.too_many_small_files_to_compact(&files, start_level) { RoundInfo::ManySmallFiles { start_level, max_num_files_to_group: self.max_num_files_per_plan, max_total_file_size_to_group: self.max_total_file_size_per_plan, } } else { let target_level = start_level.next(); RoundInfo::TargetLevel { target_level } }; let (files_now, mut files_later) = components.round_split.split(files, round_info); let (branches, more_for_later) = components.divide_initial.divide(files_now, round_info); files_later.extend(more_for_later); Ok((round_info, branches, files_later)) } } // get_start_level decides what level to start compaction from. Often this is the lowest level // we have ParquetFiles in, but occasionally we decide to compact L1->L2 when L0s still exist. // // If we ignore the invariants (where intra-level overlaps are allowed), this would be a math problem // to optimize write amplification. // // However, allowing intra-level overlaps in L0 but not L1/L2 adds extra challenge to compacting L0s to L1. // This is especially true when there are large quantitites of overlapping L0s and L1s, potentially resulting // in many split/compact cycles to resolve the overlaps. // // Since L1 & L2 only have inter-level overlaps, they can be compacted with just a few splits to align the L1s // with the L2s. The relative ease of moving data from L1 to L2 provides additional motivation to compact the // L1s to L2s when a backlog of L0s exist. The easily solvable L1->L2 compaction can give us a clean slate in // L1, greatly simplifying the remaining L0->L1 compactions. fn get_start_level(files: &[ParquetFile], max_files: usize, max_bytes: usize) -> CompactionLevel { // panic if the files are empty assert!(!files.is_empty()); let mut l0_cnt: usize = 0; let mut l0_bytes: usize = 0; let mut l1_bytes: usize = 0; for f in files { match f.compaction_level { CompactionLevel::Initial => { l0_cnt += 1; l0_bytes += f.file_size_bytes as usize; } CompactionLevel::FileNonOverlapped => { l1_bytes += f.file_size_bytes as usize; } _ => {} } } if l1_bytes > 3 * max_bytes && (l0_cnt > max_files || l0_bytes > max_bytes) { // L1 is big enough to pose an overlap challenge compacting from L0, and there is quite a bit more coming from L0. // The criteria for this early L1->L2 compaction significanly impacts write amplification. The above values optimize // existing test cases, but may be changed as additional test cases are added. CompactionLevel::FileNonOverlapped } else if l0_bytes > 0 { CompactionLevel::Initial } else if l1_bytes > 0 { CompactionLevel::FileNonOverlapped } else { CompactionLevel::Final } } fn get_num_overlapped_files( start_level_files: Vec<&ParquetFile>, next_level_files: Vec<&ParquetFile>, ) -> usize { // min_time and max_time of files in start_level let (min_time, max_time) = start_level_files .iter() .fold((None, None), |(min_time, max_time), f| { let min_time = min_time .map(|v: Timestamp| v.min(f.min_time)) .unwrap_or(f.min_time); let max_time = max_time .map(|v: Timestamp| v.max(f.max_time)) .unwrap_or(f.max_time); (Some(min_time), Some(max_time)) }); // There must be values, otherwise panic let min_time = min_time.unwrap(); let max_time = max_time.unwrap(); // number of files in next level that overlap with files in start_level let count_overlapped = next_level_files .iter() .filter(|f| f.min_time <= max_time && f.max_time >= min_time) .count(); count_overlapped } #[cfg(test)] mod tests { use data_types::CompactionLevel; use iox_tests::ParquetFileBuilder; use crate::components::round_info_source::LevelBasedRoundInfo; #[test] fn test_too_many_small_files_to_compact() { // L0 files let f1 = ParquetFileBuilder::new(1) .with_time_range(0, 100) .with_compaction_level(CompactionLevel::Initial) .with_max_l0_created_at(0) .build(); let f2 = ParquetFileBuilder::new(2) .with_time_range(0, 100) .with_compaction_level(CompactionLevel::Initial) .with_max_l0_created_at(2) .build(); // non overlapping L1 file let f3 = ParquetFileBuilder::new(3) .with_time_range(101, 200) .with_compaction_level(CompactionLevel::FileNonOverlapped) .build(); // overlapping L1 file let f4 = ParquetFileBuilder::new(4) .with_time_range(50, 150) .with_compaction_level(CompactionLevel::FileNonOverlapped) .build(); // max 2 files per plan let round_info = LevelBasedRoundInfo { max_num_files_per_plan: 2, max_total_file_size_per_plan: 1000, }; // f1 and f2 are not over limit assert!(!round_info .too_many_small_files_to_compact(&[f1.clone(), f2.clone()], CompactionLevel::Initial)); // f1, f2 and f3 are not over limit assert!(!round_info.too_many_small_files_to_compact( &[f1.clone(), f2.clone(), f3.clone()], CompactionLevel::Initial )); // f1, f2 and f4 are over limit assert!(round_info.too_many_small_files_to_compact( &[f1.clone(), f2.clone(), f4.clone()], CompactionLevel::Initial )); // f1, f2, f3 and f4 are over limit assert!( round_info.too_many_small_files_to_compact(&[f1, f2, f3, f4], CompactionLevel::Initial) ); } }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_exception::ErrorCode; use common_exception::ToErrorCode; use common_meta_app::principal::RoleInfo; use common_meta_kvapi::kvapi; use common_meta_kvapi::kvapi::UpsertKVReq; use common_meta_types::IntoSeqV; use common_meta_types::MatchSeq; use common_meta_types::MatchSeqExt; use common_meta_types::MetaError; use common_meta_types::Operation; use common_meta_types::SeqV; use crate::role::role_api::RoleApi; static ROLE_API_KEY_PREFIX: &str = "__fd_roles"; pub struct RoleMgr { kv_api: Arc<dyn kvapi::KVApi<Error = MetaError>>, role_prefix: String, } impl RoleMgr { pub fn create( kv_api: Arc<dyn kvapi::KVApi<Error = MetaError>>, tenant: &str, ) -> Result<Self, ErrorCode> { if tenant.is_empty() { return Err(ErrorCode::TenantIsEmpty( "Tenant can not empty(while role mgr create)", )); } Ok(RoleMgr { kv_api, role_prefix: format!("{}/{}", ROLE_API_KEY_PREFIX, tenant), }) } async fn upsert_role_info( &self, role_info: &RoleInfo, seq: MatchSeq, ) -> Result<u64, ErrorCode> { let key = self.make_role_key(role_info.identity()); let value = serde_json::to_vec(&role_info)?; let kv_api = self.kv_api.clone(); let res = kv_api .upsert_kv(UpsertKVReq::new(&key, seq, Operation::Update(value), None)) .await?; match res.result { Some(SeqV { seq: s, .. }) => Ok(s), None => Err(ErrorCode::UnknownRole(format!( "unknown role, or seq not match {}", role_info.name ))), } } fn make_role_key(&self, role: &str) -> String { format!("{}/{}", self.role_prefix, role) } } #[async_trait::async_trait] impl RoleApi for RoleMgr { async fn add_role(&self, role_info: RoleInfo) -> common_exception::Result<u64> { let match_seq = MatchSeq::Exact(0); let key = self.make_role_key(role_info.identity()); let value = serde_json::to_vec(&role_info)?; let kv_api = self.kv_api.clone(); let upsert_kv = kv_api.upsert_kv(UpsertKVReq::new( &key, match_seq, Operation::Update(value), None, )); let res = upsert_kv.await?.added_or_else(|v| { ErrorCode::UserAlreadyExists(format!("Role already exists, seq [{}]", v.seq)) })?; Ok(res.seq) } async fn get_role(&self, role: &String, seq: MatchSeq) -> Result<SeqV<RoleInfo>, ErrorCode> { let key = self.make_role_key(role); let res = self.kv_api.get_kv(&key).await?; let seq_value = res.ok_or_else(|| ErrorCode::UnknownRole(format!("unknown role {}", role)))?; match seq.match_seq(&seq_value) { Ok(_) => Ok(seq_value.into_seqv()?), Err(_) => Err(ErrorCode::UnknownRole(format!("unknown role {}", role))), } } async fn get_roles(&self) -> Result<Vec<SeqV<RoleInfo>>, ErrorCode> { let role_prefix = self.role_prefix.clone(); let kv_api = self.kv_api.clone(); let values = kv_api.prefix_list_kv(role_prefix.as_str()).await?; let mut r = vec![]; for (_key, val) in values { let u = serde_json::from_slice::<RoleInfo>(&val.data) .map_err_to_code(ErrorCode::IllegalUserInfoFormat, || "")?; r.push(SeqV::new(val.seq, u)); } Ok(r) } /// General role update. /// /// It fetch the role that matches the specified seq number, update it in place, then write it back with the seq it sees. /// /// Seq number ensures there is no other write happens between get and set. async fn update_role_with<F>( &self, role: &String, seq: MatchSeq, f: F, ) -> Result<Option<u64>, ErrorCode> where F: FnOnce(&mut RoleInfo) + Send, { let SeqV { seq, data: mut role_info, .. } = self.get_role(role, seq).await?; f(&mut role_info); let seq = self .upsert_role_info(&role_info, MatchSeq::Exact(seq)) .await?; Ok(Some(seq)) } async fn drop_role(&self, role: String, seq: MatchSeq) -> Result<(), ErrorCode> { let key = self.make_role_key(&role); let kv_api = self.kv_api.clone(); let res = kv_api .upsert_kv(UpsertKVReq::new(&key, seq, Operation::Delete, None)) .await?; if res.prev.is_some() && res.result.is_none() { Ok(()) } else { Err(ErrorCode::UnknownRole(format!("unknown role {}", role))) } } }
#[doc = "Reader of register BMCR"] pub type R = crate::R<u32, super::BMCR>; #[doc = "Writer for register BMCR"] pub type W = crate::W<u32, super::BMCR>; #[doc = "Register BMCR `reset()`'s with value 0"] impl crate::ResetValue for super::BMCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `BMSTAT`"] pub type BMSTAT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `BMSTAT`"] pub struct BMSTAT_W<'a> { w: &'a mut W, } impl<'a> BMSTAT_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 } } #[doc = "Reader of field `TEBM`"] pub type TEBM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TEBM`"] pub struct TEBM_W<'a> { w: &'a mut W, } impl<'a> TEBM_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 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `TDBM`"] pub type TDBM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TDBM`"] pub struct TDBM_W<'a> { w: &'a mut W, } impl<'a> TDBM_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 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `TCBM`"] pub type TCBM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TCBM`"] pub struct TCBM_W<'a> { w: &'a mut W, } impl<'a> TCBM_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 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `TBBM`"] pub type TBBM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TBBM`"] pub struct TBBM_W<'a> { w: &'a mut W, } impl<'a> TBBM_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 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `TABM`"] pub type TABM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TABM`"] pub struct TABM_W<'a> { w: &'a mut W, } impl<'a> TABM_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 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `MTBM`"] pub type MTBM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MTBM`"] pub struct MTBM_W<'a> { w: &'a mut W, } impl<'a> MTBM_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 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `BMPREN`"] pub type BMPREN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `BMPREN`"] pub struct BMPREN_W<'a> { w: &'a mut W, } impl<'a> BMPREN_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 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `BMPRSC`"] pub type BMPRSC_R = crate::R<u8, u8>; #[doc = "Write proxy for field `BMPRSC`"] pub struct BMPRSC_W<'a> { w: &'a mut W, } impl<'a> BMPRSC_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 << 6)) | (((value as u32) & 0x0f) << 6); self.w } } #[doc = "Reader of field `BMCLK`"] pub type BMCLK_R = crate::R<u8, u8>; #[doc = "Write proxy for field `BMCLK`"] pub struct BMCLK_W<'a> { w: &'a mut W, } impl<'a> BMCLK_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 << 2)) | (((value as u32) & 0x0f) << 2); self.w } } #[doc = "Reader of field `BMOM`"] pub type BMOM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `BMOM`"] pub struct BMOM_W<'a> { w: &'a mut W, } impl<'a> BMOM_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 `BME`"] pub type BME_R = crate::R<bool, bool>; #[doc = "Write proxy for field `BME`"] pub struct BME_W<'a> { w: &'a mut W, } impl<'a> BME_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 } } impl R { #[doc = "Bit 31 - Burst Mode Status"] #[inline(always)] pub fn bmstat(&self) -> BMSTAT_R { BMSTAT_R::new(((self.bits >> 31) & 0x01) != 0) } #[doc = "Bit 21 - Timer E Burst Mode"] #[inline(always)] pub fn tebm(&self) -> TEBM_R { TEBM_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 20 - Timer D Burst Mode"] #[inline(always)] pub fn tdbm(&self) -> TDBM_R { TDBM_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 19 - Timer C Burst Mode"] #[inline(always)] pub fn tcbm(&self) -> TCBM_R { TCBM_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 18 - Timer B Burst Mode"] #[inline(always)] pub fn tbbm(&self) -> TBBM_R { TBBM_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 17 - Timer A Burst Mode"] #[inline(always)] pub fn tabm(&self) -> TABM_R { TABM_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - Master Timer Burst Mode"] #[inline(always)] pub fn mtbm(&self) -> MTBM_R { MTBM_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 10 - Burst Mode Preload Enable"] #[inline(always)] pub fn bmpren(&self) -> BMPREN_R { BMPREN_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bits 6:9 - Burst Mode Prescaler"] #[inline(always)] pub fn bmprsc(&self) -> BMPRSC_R { BMPRSC_R::new(((self.bits >> 6) & 0x0f) as u8) } #[doc = "Bits 2:5 - Burst Mode Clock source"] #[inline(always)] pub fn bmclk(&self) -> BMCLK_R { BMCLK_R::new(((self.bits >> 2) & 0x0f) as u8) } #[doc = "Bit 1 - Burst Mode operating mode"] #[inline(always)] pub fn bmom(&self) -> BMOM_R { BMOM_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - Burst Mode enable"] #[inline(always)] pub fn bme(&self) -> BME_R { BME_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 31 - Burst Mode Status"] #[inline(always)] pub fn bmstat(&mut self) -> BMSTAT_W { BMSTAT_W { w: self } } #[doc = "Bit 21 - Timer E Burst Mode"] #[inline(always)] pub fn tebm(&mut self) -> TEBM_W { TEBM_W { w: self } } #[doc = "Bit 20 - Timer D Burst Mode"] #[inline(always)] pub fn tdbm(&mut self) -> TDBM_W { TDBM_W { w: self } } #[doc = "Bit 19 - Timer C Burst Mode"] #[inline(always)] pub fn tcbm(&mut self) -> TCBM_W { TCBM_W { w: self } } #[doc = "Bit 18 - Timer B Burst Mode"] #[inline(always)] pub fn tbbm(&mut self) -> TBBM_W { TBBM_W { w: self } } #[doc = "Bit 17 - Timer A Burst Mode"] #[inline(always)] pub fn tabm(&mut self) -> TABM_W { TABM_W { w: self } } #[doc = "Bit 16 - Master Timer Burst Mode"] #[inline(always)] pub fn mtbm(&mut self) -> MTBM_W { MTBM_W { w: self } } #[doc = "Bit 10 - Burst Mode Preload Enable"] #[inline(always)] pub fn bmpren(&mut self) -> BMPREN_W { BMPREN_W { w: self } } #[doc = "Bits 6:9 - Burst Mode Prescaler"] #[inline(always)] pub fn bmprsc(&mut self) -> BMPRSC_W { BMPRSC_W { w: self } } #[doc = "Bits 2:5 - Burst Mode Clock source"] #[inline(always)] pub fn bmclk(&mut self) -> BMCLK_W { BMCLK_W { w: self } } #[doc = "Bit 1 - Burst Mode operating mode"] #[inline(always)] pub fn bmom(&mut self) -> BMOM_W { BMOM_W { w: self } } #[doc = "Bit 0 - Burst Mode enable"] #[inline(always)] pub fn bme(&mut self) -> BME_W { BME_W { w: self } } }
use std::ops::Deref; use std::sync::Arc; use vulkano::buffer::{BufferUsage, CpuAccessibleBuffer}; use vulkano::command_buffer::{AutoCommandBufferBuilder, CommandBufferUsage, DynamicState, SubpassContents}; use vulkano::descriptor::pipeline_layout::PipelineLayoutDesc; use vulkano::device::Device; use vulkano::device::DeviceExtensions; use vulkano::device::Features; use vulkano::image::{ImageUsage, SwapchainImage}; use vulkano::image::view::ImageView; use vulkano::instance::Instance; use vulkano::instance::InstanceExtensions; use vulkano::instance::PhysicalDevice; use vulkano::pipeline::GraphicsPipeline; use vulkano::pipeline::viewport::Viewport; use vulkano::render_pass::{Framebuffer, FramebufferAbstract, RenderPass, Subpass}; use vulkano::swapchain::{AcquireError, ColorSpace, FullscreenExclusive, PresentMode, SurfaceTransform, Swapchain, SwapchainCreationError}; use vulkano::sync; use vulkano::sync::{FlushError, GpuFuture}; use vulkano_win::VkSurfaceBuild; use winit::event::{Event, WindowEvent}; use winit::event_loop::{ControlFlow, EventLoop}; use winit::window::{Window, WindowBuilder}; fn main() { let instance = { let extensions = vulkano_win::required_extensions(); Instance::new(None, &extensions, None).expect("failed to create vulkan instance") }; print_devices_info(&instance); let physical = PhysicalDevice::enumerate(&instance).next().expect("no device available"); let events_loop = EventLoop::new(); let surface = WindowBuilder::new() .build_vk_surface(&events_loop, instance.clone()) .unwrap(); let queue_family = physical.queue_families() .find(|&q| { q.supports_graphics() && surface.is_supported(q).unwrap_or(false) }) .expect("couldn't find a graphical queue family"); let device_ext = vulkano::device::DeviceExtensions { khr_swapchain: true, ..vulkano::device::DeviceExtensions::none() }; let (device, mut queues) = { Device::new(physical, &Features::none(), &device_ext, [(queue_family, 0.5)].iter().cloned()) .expect("failed device creation") }; let queue = queues.next().unwrap(); // params missing from guide: 1 + true let (mut swapchain, image_views) = { let capabilities = surface.capabilities(physical).expect("failed to get surface capabilities"); let dimensions = capabilities.current_extent.unwrap_or([1280, 1024]); let alpha = capabilities.supported_composite_alpha.iter().next().unwrap(); let format = capabilities.supported_formats[0].0; let (swapchain, images) = Swapchain::start(device.clone(), surface.clone()) .num_images(capabilities.min_image_count) .format(format) .dimensions(dimensions) .usage(ImageUsage::color_attachment()) .sharing_mode(&queue) .composite_alpha(alpha) .transform(SurfaceTransform::Identity) .present_mode(PresentMode::Fifo) .fullscreen_exclusive(FullscreenExclusive::Default) .color_space(ColorSpace::SrgbNonLinear) .build() .unwrap(); let images: Vec<_> = images.into_iter().map(|img| ImageView::new(img).unwrap()).collect(); (swapchain, images) }; let vertex_buffer = { #[derive(Default, Debug, Clone)] struct Vertex { position: [f32; 2], } vulkano::impl_vertex!(Vertex, position); CpuAccessibleBuffer::from_iter( device.clone(), BufferUsage::all(), false, [ Vertex { position: [-0.5, -0.25], }, Vertex { position: [0.0, 0.5], }, Vertex { position: [0.25, -0.1], }, ] .iter() .cloned(), ) .unwrap() }; mod vs { vulkano_shaders::shader! { ty: "vertex", src: " #version 450 layout(location = 0) in vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } " } } mod fs { vulkano_shaders::shader! { ty: "fragment", src: " #version 450 layout(location = 0) out vec4 f_color; void main() { f_color = vec4(1.0, 0.0, 0.0, 1.0); } " } } let vs = vs::Shader::load(device.clone()).unwrap(); let fs = fs::Shader::load(device.clone()).unwrap(); let render_pass = Arc::new( vulkano::single_pass_renderpass!( device.clone(), attachments: { // `color` is a custom name we give to the first and only attachment. color: { // `load: Clear` means that we ask the GPU to clear the content of this // attachment at the start of the drawing. load: Clear, // `store: Store` means that we ask the GPU to store the output of the draw // in the actual image. We could also ask it to discard the result. store: Store, // `format: <ty>` indicates the type of the format of the image. This has to // be one of the types of the `vulkano::format` module (or alternatively one // of your structs that implements the `FormatDesc` trait). Here we use the // same format as the swapchain. format: swapchain.format(), // TODO: samples: 1, } }, pass: { // We use the attachment named `color` as the one and only color attachment. color: [color], // No depth-stencil attachment is indicated with empty brackets. depth_stencil: {} } ) .unwrap(), ); let pipeline = Arc::new( GraphicsPipeline::start() // We need to indicate the layout of the vertices. // The type `SingleBufferDefinition` actually contains a template parameter corresponding // to the type of each vertex. But in this code it is automatically inferred. .vertex_input_single_buffer() // A Vulkan shader can in theory contain multiple entry points, so we have to specify // which one. The `main` word of `main_entry_point` actually corresponds to the name of // the entry point. .vertex_shader(vs.main_entry_point(), ()) // The content of the vertex buffer describes a list of triangles. .triangle_list() // Use a resizable viewport set to draw over the entire window .viewports_dynamic_scissors_irrelevant(1) // See `vertex_shader`. .fragment_shader(fs.main_entry_point(), ()) // We have to indicate which subpass of which render pass this pipeline is going to be used // in. The pipeline will only be usable from this particular subpass. .render_pass(Subpass::from(render_pass.clone(), 0).unwrap()) // Now that our builder is filled, we call `build()` to obtain an actual pipeline. .build(device.clone()) .unwrap(), ); let mut dynamic_state = DynamicState { line_width: None, viewports: None, scissors: None, compare_mask: None, write_mask: None, reference: None, }; let mut framebuffers = window_size_dependent_setup(&image_views, render_pass.clone(), &mut dynamic_state); let mut recreate_swapchain = false; let mut previous_frame_end = Some(sync::now(device.clone()).boxed()); events_loop.run(move |event, _, control_flow| { match event { Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { *control_flow = ControlFlow::Exit; } Event::WindowEvent { event: WindowEvent::Resized(_), .. } => { recreate_swapchain = true; } Event::RedrawEventsCleared => { previous_frame_end.as_mut().unwrap().cleanup_finished(); // Whenever the window resizes we need to recreate everything dependent on the window size. // In this example that includes the swapchain, the framebuffers and the dynamic state viewport. if recreate_swapchain { // Get the new dimensions of the window. let dimensions: [u32; 2] = surface.window().inner_size().into(); let (new_swapchain, new_image_views) = match swapchain.recreate().dimensions(dimensions).build() { Ok((new_swapchain, new_images)) => { let new_image_views: Vec<_> = new_images.into_iter().map(|img| ImageView::new(img).unwrap()).collect(); (new_swapchain, new_image_views) } // This error tends to happen when the user is manually resizing the window. // Simply restarting the loop is the easiest way to fix this issue. Err(SwapchainCreationError::UnsupportedDimensions) => return, Err(e) => panic!("Failed to recreate swapchain: {:?}", e), }; swapchain = new_swapchain; // Because framebuffers contains an Arc on the old swapchain, we need to // recreate framebuffers as well. framebuffers = window_size_dependent_setup( &new_image_views, render_pass.clone(), &mut dynamic_state, ); recreate_swapchain = false; } let (image_num, suboptimal, acquire_future) = match vulkano::swapchain::acquire_next_image(swapchain.clone(), None) { Ok(r) => r, Err(AcquireError::OutOfDate) => { recreate_swapchain = true; return; } Err(e) => panic!("Failed to acquire next image: {:?}", e), }; if suboptimal { recreate_swapchain = true; } let clear_values = vec![[0.0, 0.0, 1.0, 1.0].into()]; let mut builder = vulkano::command_buffer::AutoCommandBufferBuilder::primary( device.clone(), queue.family(), CommandBufferUsage::OneTimeSubmit ).unwrap(); let x = builder .begin_render_pass(framebuffers[image_num].clone(), SubpassContents::Inline, clear_values) .unwrap() .draw(pipeline.clone(), &dynamic_state, vertex_buffer.clone(), (), (), vec![]) .unwrap() .end_render_pass() .unwrap(); let command_buffer = builder.build().unwrap(); let future = previous_frame_end .take() .unwrap() .join(acquire_future) .then_execute(queue.clone(), command_buffer) .unwrap() .then_swapchain_present(queue.clone(), swapchain.clone(), image_num) .then_signal_fence_and_flush(); match future { Ok(future) => { previous_frame_end = Some(future.boxed()); } Err(FlushError::OutOfDate) => { recreate_swapchain = true; previous_frame_end = Some(sync::now(device.clone()).boxed()) } Err(e) => { println!("Failed to flush future: {:?}", e); previous_frame_end = Some(sync::now(device.clone()).boxed()); } } } _ => () } }); } fn window_size_dependent_setup( image_views: &Vec<Arc<ImageView<Arc<SwapchainImage<Window>>>>>, render_pass: Arc<RenderPass>, dynamic_state: &mut DynamicState, ) -> Vec<Arc<dyn FramebufferAbstract + Send + Sync>> { let dimensions = image_views[0].image().dimensions(); let viewport = Viewport { origin: [0.0, 0.0], dimensions: [dimensions[0] as f32, dimensions[1] as f32], depth_range: 0.0..1.0, }; dynamic_state.viewports = Some(vec![viewport]); image_views .iter() .map(|image_view| { let arc_swapchain_image = image_view.clone(); let builder = Framebuffer::start(render_pass.clone()) .add(arc_swapchain_image) .unwrap(); let framebuffer = builder .build() .unwrap(); let framebuffer_abstract = Arc::new( framebuffer, ) as Arc<dyn FramebufferAbstract + Send + Sync>; framebuffer_abstract }) .collect::<Vec<_>>() } fn print_devices_info(instance: &Arc<Instance>) { for physical_device in PhysicalDevice::enumerate(&instance) { println!("found a physical device name: {}", physical_device.name()); println!("\tapi version: {}", physical_device.api_version()); println!("\tdriver_version: {}", physical_device.driver_version()); println!("\tpci_vendor_id: {}", physical_device.pci_vendor_id()); println!("\tpci_device_id: {}", physical_device.pci_device_id()); // println!("\tsupported features: {:#?}", physical_device.supported_features()); println!("\tqueue families:"); for family in physical_device.queue_families() { println!("\t\tFound a queue family with {:?} queue(s)", family.queues_count()); } println!(); } }
use crate::prelude::*; use gnudbm::GdbmOpener; use std::path::PathBuf; use serde_aux::prelude::*; use std::io; #[derive(Debug, Deserialize, Clone, Hash, PartialOrd, PartialEq, Eq)] pub struct Evr( #[serde(deserialize_with = "deserialize_number_from_string")] pub u64, pub String, pub String, ); impl FromStr for Evr { type Err = io::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut parts: Vec<_> = s.split(':').collect::<Vec<_>>(); let release = parts.pop().unwrap(); let version = parts.pop().unwrap(); let epoch = parts.pop().unwrap(); Ok(Evr( epoch.parse().unwrap(), version.to_string(), release.to_string(), )) } } #[derive(Debug, Deserialize, Clone, Hash, PartialOrd, PartialEq, Eq)] pub struct NevraId(u64, u64, u64); impl FromStr for NevraId { type Err = io::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut parts: Vec<_> = s.split(':').collect::<Vec<_>>(); let arch = parts.pop().unwrap(); let evr = parts.pop().unwrap(); let name = parts.pop().unwrap(); Ok(NevraId( name.parse().unwrap(), evr.parse().unwrap(), arch.parse().unwrap(), )) } } #[derive(Debug, Deserialize, Clone, Hash)] pub struct Package { pub name_id: u64, pub evr_id: u64, pub arch_id: u64, pub summary: Option<String>, pub desc: Option<String>, pub source_pkg_id: Option<u64>, } #[derive(Debug, Deserialize, Clone, Hash)] pub struct Cve { //id: String, } #[derive(Debug, Deserialize, Clone, Hash)] pub struct Repo { pub label: String, pub name: String, pub url: String, pub basearch: Option<String>, pub releasever: Option<String>, pub product: Option<String>, pub product_id: Option<u64>, //revision : Option<u64> } #[derive(Debug, Deserialize, Clone, Hash)] pub struct Errata {} #[derive(Debug, Deserialize, Clone)] pub struct UpdatesIndex { #[serde(flatten)] pub data: Map<u64, Vec<u64>>, } #[derive(Debug, Default)] pub struct Cache { pub name_to_id: Map<String, u64>, pub id_to_name: Map<u64, String>, pub updates: Map<u64, Vec<u64>>, pub updates_index: Map<u64, UpdatesIndex>, pub evr_to_id: Map<Evr, u64>, pub id_to_evr: Map<u64, Evr>, pub arch_to_id: Map<String, u64>, pub id_to_arch: Map<u64, String>, pub arch_compat: Map<u64, Vec<u64>>, pub pkg_details: Map<u64, Package>, pub nevra_to_pkgid: Map<NevraId, u64>, pub repo_detail: Map<u64, Repo>, pub repolabel_to_ids: Map<String, Vec<u64>>, pub productid_to_repoids: Map<u64, Vec<u64>>, pub pkgid_to_repoids: Map<u64, Vec<u64>>, pub errataid_to_name: Map<u64, String>, pub pkgid_to_errataids: Map<u64, Vec<u64>>, pub errataid_to_repoids: Map<u64, Vec<u64>>, pub cve_detail: Map<String, Cve>, pub dbchange: Map<String, String>, pub errata_detail: Map<String, Errata>, pub pkgerrata_to_module: Map<String, String>, pub modulename_to_id: Map<String, String>, pub src_pkg_id_to_pkg_ids: Map<String, Vec<u64>>, } pub fn load(name: String) -> Result<Cache, Box<dyn Error>> { let file = PathBuf::from(name); let db = GdbmOpener::new().readonly(&file).expect("Opening failed"); let mut cache = Cache::default(); for (key, data) in db.iter() { let kstr = std::str::from_utf8(key.as_bytes()).unwrap(); let (key, id) = kstr.split_at(kstr.find(':').unwrap()); let (_, id) = id.split_at(1); let data = data.as_bytes(); match key { "packagename2id" => { cache .name_to_id .insert(id.to_owned(), pickle::from_slice::<u64>(data).unwrap()); //println!("{:?} = {:?}", id, cache.name_to_id[id]) } "id2packagename" => { cache .id_to_name .insert(id.parse()?, pickle::from_slice::<String>(data)?); } "updates" => { cache.updates.insert(id.parse()?, pickle::from_slice(data)?); } "updates_index" => { cache .updates_index .insert(id.parse()?, pickle::from_slice(data)?); } "evr2id" => { cache .evr_to_id .insert(id.parse()?, pickle::from_slice(data)?); } "id2evr" => { cache .id_to_evr .insert(id.parse()?, pickle::from_slice(data)?); } "arch2id" => { cache .arch_to_id .insert(id.parse()?, pickle::from_slice(data)?); } "id2arch" => { cache .id_to_arch .insert(id.parse()?, pickle::from_slice(data)?); } "arch_compat" => { cache .arch_compat .insert(id.parse()?, pickle::from_slice(data)?); } "package_details" => { cache .pkg_details .insert(id.parse()?, pickle::from_slice(data)?); } "nevra2pkgid" => { cache .nevra_to_pkgid .insert(id.parse()?, pickle::from_slice(data)?); } "repo_detail" => { let id = id.parse()?; cache.repo_detail.insert(id, pickle::from_slice(data)?); } "repolabel2ids" => { cache .repolabel_to_ids .insert(id.parse()?, pickle::from_slice(data)?); } "productid2repoids" => { cache .productid_to_repoids .insert(id.parse()?, pickle::from_slice(data)?); } "pkgid2repoids" => { cache .pkgid_to_repoids .insert(id.parse()?, pickle::from_slice(data)?); } "errataid2name" => { cache .errataid_to_name .insert(id.parse()?, pickle::from_slice(data)?); } "pkgid2errataids" => { cache .pkgid_to_errataids .insert(id.parse()?, pickle::from_slice(data)?); } "errataid2repoids" => { cache .errataid_to_repoids .insert(id.parse()?, pickle::from_slice(data)?); } "cve_detail" => { cache .cve_detail .insert(id.parse()?, pickle::from_slice(data)?); } "dbchange" => { //cache.dbchange.insert(id.parse()?, pickle::from_slice(data)?); } "errata_detail" => { cache .errata_detail .insert(id.parse()?, pickle::from_slice(data)?); } "pkgerrata2module" => { // TODO: } "modulename2id" => { //println!("Id: {:?}", id); cache .modulename_to_id .insert(id.parse()?, pickle::from_slice(data)?); } "src_pkg_id2pkg_ids" => { cache .src_pkg_id_to_pkg_ids .insert(id.parse()?, pickle::from_slice(data)?); } other => panic!("Table {:?} not implemented", other), } } Ok(cache) }
#[doc = "Reader of register BDTEUPR"] pub type R = crate::R<u32, super::BDTEUPR>; #[doc = "Writer for register BDTEUPR"] pub type W = crate::W<u32, super::BDTEUPR>; #[doc = "Register BDTEUPR `reset()`'s with value 0"] impl crate::ResetValue for super::BDTEUPR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TIMxEEFR3`"] pub type TIMXEEFR3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxEEFR3`"] pub struct TIMXEEFR3_W<'a> { w: &'a mut W, } impl<'a> TIMXEEFR3_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 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `TIMxCR2`"] pub type TIMXCR2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxCR2`"] pub struct TIMXCR2_W<'a> { w: &'a mut W, } impl<'a> TIMXCR2_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 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `TIMxFLTR`"] pub type TIMXFLTR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxFLTR`"] pub struct TIMXFLTR_W<'a> { w: &'a mut W, } impl<'a> TIMXFLTR_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 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `TIMxOUTR`"] pub type TIMXOUTR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxOUTR`"] pub struct TIMXOUTR_W<'a> { w: &'a mut W, } impl<'a> TIMXOUTR_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 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `TIMxCHPR`"] pub type TIMXCHPR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxCHPR`"] pub struct TIMXCHPR_W<'a> { w: &'a mut W, } impl<'a> TIMXCHPR_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 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `TIMxRSTR`"] pub type TIMXRSTR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxRSTR`"] pub struct TIMXRSTR_W<'a> { w: &'a mut W, } impl<'a> TIMXRSTR_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 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `TIMxEEFR2`"] pub type TIMXEEFR2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxEEFR2`"] pub struct TIMXEEFR2_W<'a> { w: &'a mut W, } impl<'a> TIMXEEFR2_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 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `TIMxEEFR1`"] pub type TIMXEEFR1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxEEFR1`"] pub struct TIMXEEFR1_W<'a> { w: &'a mut W, } impl<'a> TIMXEEFR1_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 } } #[doc = "Reader of field `TIMxRST2R`"] pub type TIMXRST2R_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxRST2R`"] pub struct TIMXRST2R_W<'a> { w: &'a mut W, } impl<'a> TIMXRST2R_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 `TIMxSET2R`"] pub type TIMXSET2R_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxSET2R`"] pub struct TIMXSET2R_W<'a> { w: &'a mut W, } impl<'a> TIMXSET2R_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 `TIMxRST1R`"] pub type TIMXRST1R_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxRST1R`"] pub struct TIMXRST1R_W<'a> { w: &'a mut W, } impl<'a> TIMXRST1R_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 `TIMxSET1R`"] pub type TIMXSET1R_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxSET1R`"] pub struct TIMXSET1R_W<'a> { w: &'a mut W, } impl<'a> TIMXSET1R_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 `TIMx_DTxR`"] pub type TIMX_DTXR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMx_DTxR`"] pub struct TIMX_DTXR_W<'a> { w: &'a mut W, } impl<'a> TIMX_DTXR_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 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `TIMxCMP4`"] pub type TIMXCMP4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxCMP4`"] pub struct TIMXCMP4_W<'a> { w: &'a mut W, } impl<'a> TIMXCMP4_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 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `TIMxCMP3`"] pub type TIMXCMP3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxCMP3`"] pub struct TIMXCMP3_W<'a> { w: &'a mut W, } impl<'a> TIMXCMP3_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 `TIMxCMP2`"] pub type TIMXCMP2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxCMP2`"] pub struct TIMXCMP2_W<'a> { w: &'a mut W, } impl<'a> TIMXCMP2_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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `TIMxCMP1`"] pub type TIMXCMP1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxCMP1`"] pub struct TIMXCMP1_W<'a> { w: &'a mut W, } impl<'a> TIMXCMP1_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 } } #[doc = "Reader of field `TIMxREP`"] pub type TIMXREP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxREP`"] pub struct TIMXREP_W<'a> { w: &'a mut W, } impl<'a> TIMXREP_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 `TIMxPER`"] pub type TIMXPER_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxPER`"] pub struct TIMXPER_W<'a> { w: &'a mut W, } impl<'a> TIMXPER_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 `TIMxCNT`"] pub type TIMXCNT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxCNT`"] pub struct TIMXCNT_W<'a> { w: &'a mut W, } impl<'a> TIMXCNT_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 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `TIMxDIER`"] pub type TIMXDIER_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxDIER`"] pub struct TIMXDIER_W<'a> { w: &'a mut W, } impl<'a> TIMXDIER_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 `TIMxICR`"] pub type TIMXICR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxICR`"] pub struct TIMXICR_W<'a> { w: &'a mut W, } impl<'a> TIMXICR_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 `TIMxCR`"] pub type TIMXCR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TIMxCR`"] pub struct TIMXCR_W<'a> { w: &'a mut W, } impl<'a> TIMXCR_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 } } impl R { #[doc = "Bit 22 - TIMxEEFR3"] #[inline(always)] pub fn timx_eefr3(&self) -> TIMXEEFR3_R { TIMXEEFR3_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 21 - TIMxCR2"] #[inline(always)] pub fn timx_cr2(&self) -> TIMXCR2_R { TIMXCR2_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 20 - HRTIM_FLTxR register update enable"] #[inline(always)] pub fn timx_fltr(&self) -> TIMXFLTR_R { TIMXFLTR_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 19 - HRTIM_OUTxR register update enable"] #[inline(always)] pub fn timx_outr(&self) -> TIMXOUTR_R { TIMXOUTR_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 18 - HRTIM_CHPxR register update enable"] #[inline(always)] pub fn timx_chpr(&self) -> TIMXCHPR_R { TIMXCHPR_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 17 - HRTIM_RSTxR register update enable"] #[inline(always)] pub fn timx_rstr(&self) -> TIMXRSTR_R { TIMXRSTR_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - HRTIM_EEFxR2 register update enable"] #[inline(always)] pub fn timx_eefr2(&self) -> TIMXEEFR2_R { TIMXEEFR2_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 15 - HRTIM_EEFxR1 register update enable"] #[inline(always)] pub fn timx_eefr1(&self) -> TIMXEEFR1_R { TIMXEEFR1_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 14 - HRTIM_RST2xR register update enable"] #[inline(always)] pub fn timx_rst2r(&self) -> TIMXRST2R_R { TIMXRST2R_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 13 - HRTIM_SET2xR register update enable"] #[inline(always)] pub fn timx_set2r(&self) -> TIMXSET2R_R { TIMXSET2R_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 12 - HRTIM_RST1xR register update enable"] #[inline(always)] pub fn timx_rst1r(&self) -> TIMXRST1R_R { TIMXRST1R_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 11 - HRTIM_SET1xR register update enable"] #[inline(always)] pub fn timx_set1r(&self) -> TIMXSET1R_R { TIMXSET1R_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 10 - HRTIM_DTxR register update enable"] #[inline(always)] pub fn timx_dtx_r(&self) -> TIMX_DTXR_R { TIMX_DTXR_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 9 - HRTIM_CMP4xR register update enable"] #[inline(always)] pub fn timx_cmp4(&self) -> TIMXCMP4_R { TIMXCMP4_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 8 - HRTIM_CMP3xR register update enable"] #[inline(always)] pub fn timx_cmp3(&self) -> TIMXCMP3_R { TIMXCMP3_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 7 - HRTIM_CMP2xR register update enable"] #[inline(always)] pub fn timx_cmp2(&self) -> TIMXCMP2_R { TIMXCMP2_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 6 - HRTIM_CMP1xR register update enable"] #[inline(always)] pub fn timx_cmp1(&self) -> TIMXCMP1_R { TIMXCMP1_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 5 - HRTIM_REPxR register update enable"] #[inline(always)] pub fn timx_rep(&self) -> TIMXREP_R { TIMXREP_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - HRTIM_PERxR register update enable"] #[inline(always)] pub fn timx_per(&self) -> TIMXPER_R { TIMXPER_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - HRTIM_CNTxR register update enable"] #[inline(always)] pub fn timx_cnt(&self) -> TIMXCNT_R { TIMXCNT_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - HRTIM_TIMxDIER register update enable"] #[inline(always)] pub fn timx_dier(&self) -> TIMXDIER_R { TIMXDIER_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - HRTIM_TIMxICR register update enable"] #[inline(always)] pub fn timx_icr(&self) -> TIMXICR_R { TIMXICR_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - HRTIM_TIMxCR register update enable"] #[inline(always)] pub fn timx_cr(&self) -> TIMXCR_R { TIMXCR_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 22 - TIMxEEFR3"] #[inline(always)] pub fn timx_eefr3(&mut self) -> TIMXEEFR3_W { TIMXEEFR3_W { w: self } } #[doc = "Bit 21 - TIMxCR2"] #[inline(always)] pub fn timx_cr2(&mut self) -> TIMXCR2_W { TIMXCR2_W { w: self } } #[doc = "Bit 20 - HRTIM_FLTxR register update enable"] #[inline(always)] pub fn timx_fltr(&mut self) -> TIMXFLTR_W { TIMXFLTR_W { w: self } } #[doc = "Bit 19 - HRTIM_OUTxR register update enable"] #[inline(always)] pub fn timx_outr(&mut self) -> TIMXOUTR_W { TIMXOUTR_W { w: self } } #[doc = "Bit 18 - HRTIM_CHPxR register update enable"] #[inline(always)] pub fn timx_chpr(&mut self) -> TIMXCHPR_W { TIMXCHPR_W { w: self } } #[doc = "Bit 17 - HRTIM_RSTxR register update enable"] #[inline(always)] pub fn timx_rstr(&mut self) -> TIMXRSTR_W { TIMXRSTR_W { w: self } } #[doc = "Bit 16 - HRTIM_EEFxR2 register update enable"] #[inline(always)] pub fn timx_eefr2(&mut self) -> TIMXEEFR2_W { TIMXEEFR2_W { w: self } } #[doc = "Bit 15 - HRTIM_EEFxR1 register update enable"] #[inline(always)] pub fn timx_eefr1(&mut self) -> TIMXEEFR1_W { TIMXEEFR1_W { w: self } } #[doc = "Bit 14 - HRTIM_RST2xR register update enable"] #[inline(always)] pub fn timx_rst2r(&mut self) -> TIMXRST2R_W { TIMXRST2R_W { w: self } } #[doc = "Bit 13 - HRTIM_SET2xR register update enable"] #[inline(always)] pub fn timx_set2r(&mut self) -> TIMXSET2R_W { TIMXSET2R_W { w: self } } #[doc = "Bit 12 - HRTIM_RST1xR register update enable"] #[inline(always)] pub fn timx_rst1r(&mut self) -> TIMXRST1R_W { TIMXRST1R_W { w: self } } #[doc = "Bit 11 - HRTIM_SET1xR register update enable"] #[inline(always)] pub fn timx_set1r(&mut self) -> TIMXSET1R_W { TIMXSET1R_W { w: self } } #[doc = "Bit 10 - HRTIM_DTxR register update enable"] #[inline(always)] pub fn timx_dtx_r(&mut self) -> TIMX_DTXR_W { TIMX_DTXR_W { w: self } } #[doc = "Bit 9 - HRTIM_CMP4xR register update enable"] #[inline(always)] pub fn timx_cmp4(&mut self) -> TIMXCMP4_W { TIMXCMP4_W { w: self } } #[doc = "Bit 8 - HRTIM_CMP3xR register update enable"] #[inline(always)] pub fn timx_cmp3(&mut self) -> TIMXCMP3_W { TIMXCMP3_W { w: self } } #[doc = "Bit 7 - HRTIM_CMP2xR register update enable"] #[inline(always)] pub fn timx_cmp2(&mut self) -> TIMXCMP2_W { TIMXCMP2_W { w: self } } #[doc = "Bit 6 - HRTIM_CMP1xR register update enable"] #[inline(always)] pub fn timx_cmp1(&mut self) -> TIMXCMP1_W { TIMXCMP1_W { w: self } } #[doc = "Bit 5 - HRTIM_REPxR register update enable"] #[inline(always)] pub fn timx_rep(&mut self) -> TIMXREP_W { TIMXREP_W { w: self } } #[doc = "Bit 4 - HRTIM_PERxR register update enable"] #[inline(always)] pub fn timx_per(&mut self) -> TIMXPER_W { TIMXPER_W { w: self } } #[doc = "Bit 3 - HRTIM_CNTxR register update enable"] #[inline(always)] pub fn timx_cnt(&mut self) -> TIMXCNT_W { TIMXCNT_W { w: self } } #[doc = "Bit 2 - HRTIM_TIMxDIER register update enable"] #[inline(always)] pub fn timx_dier(&mut self) -> TIMXDIER_W { TIMXDIER_W { w: self } } #[doc = "Bit 1 - HRTIM_TIMxICR register update enable"] #[inline(always)] pub fn timx_icr(&mut self) -> TIMXICR_W { TIMXICR_W { w: self } } #[doc = "Bit 0 - HRTIM_TIMxCR register update enable"] #[inline(always)] pub fn timx_cr(&mut self) -> TIMXCR_W { TIMXCR_W { w: self } } }
use std::marker::PhantomData; use std::ops::{Index, IndexMut}; use std::{mem, ptr}; use device::Device; use sys::*; use BufferType; #[derive(Copy, Clone)] struct BufferAttachment { geom: RTCGeometry, buf_type: BufferType, slot: u32, } impl BufferAttachment { fn none() -> BufferAttachment { BufferAttachment { geom: ptr::null_mut(), buf_type: BufferType::VERTEX, slot: std::u32::MAX, } } fn is_attached(&self) -> bool { self.geom != ptr::null_mut() } } // TODO: To handle this nicely for sharing/re-using/changing buffer views // we basically need an API/struct for making buffer views of existing // larger buffers. pub struct Buffer<'a, T> { device: &'a Device, pub(crate) handle: RTCBuffer, // TODO: We need a list of RTCGeometry handles // that we're attached to to mark buffers as updated on // the geometries. bytes: usize, attachment: BufferAttachment, marker: PhantomData<T>, } impl<'a, T> Buffer<'a, T> { /// Allocate a buffer with some raw capacity in bytes pub fn raw(device: &'a Device, bytes: usize) -> Buffer<'a, T> { // Pad to a multiple of 16 bytes let bytes = if bytes % 16 == 0 { bytes } else { bytes + bytes / 16 }; Buffer { device: device, handle: unsafe { rtcNewBuffer(device.handle, bytes) }, bytes: bytes, attachment: BufferAttachment::none(), marker: PhantomData, } } pub fn new(device: &'a Device, len: usize) -> Buffer<'a, T> { let mut bytes = len * mem::size_of::<T>(); // Pad to a multiple of 16 bytes bytes = if bytes % 16 == 0 { bytes } else { bytes + bytes / 16 }; Buffer { device: device, handle: unsafe { rtcNewBuffer(device.handle, bytes) }, bytes: bytes, attachment: BufferAttachment::none(), marker: PhantomData, } } pub fn map(&mut self) -> MappedBuffer<'a, T> { let len = self.bytes / mem::size_of::<T>(); let slice = unsafe { rtcGetBufferData(self.handle) as *mut T }; MappedBuffer { buffer: PhantomData, attachment: self.attachment, slice: slice, len: len, } } pub(crate) fn set_attachment(&mut self, geom: RTCGeometry, buf_type: BufferType, slot: u32) { self.attachment.geom = geom; self.attachment.buf_type = buf_type; self.attachment.slot = slot; } } impl<'a, T> Drop for Buffer<'a, T> { fn drop(&mut self) { unsafe { rtcReleaseBuffer(self.handle); } } } unsafe impl<'a, T> Sync for Buffer<'a, T> {} pub struct MappedBuffer<'a, T: 'a> { buffer: PhantomData<&'a mut Buffer<'a, T>>, attachment: BufferAttachment, slice: *mut T, len: usize, } impl<'a, T: 'a> MappedBuffer<'a, T> { pub fn len(&self) -> usize { self.len } } impl<'a, T: 'a> Drop for MappedBuffer<'a, T> { fn drop(&mut self) { if self.attachment.is_attached() { // TODO: support for attaching one buffer to multiple geoms? unsafe { rtcUpdateGeometryBuffer( self.attachment.geom, self.attachment.buf_type, self.attachment.slot, ); } } } } impl<'a, T: 'a> Index<usize> for MappedBuffer<'a, T> { type Output = T; fn index(&self, index: usize) -> &T { // TODO: We should only check in debug build if index >= self.len { panic!("MappedBuffer index out of bounds"); } unsafe { &*self.slice.offset(index as isize) } } } impl<'a, T: 'a> IndexMut<usize> for MappedBuffer<'a, T> { fn index_mut(&mut self, index: usize) -> &mut T { if index >= self.len { panic!("MappedBuffer index out of bounds"); } unsafe { &mut *self.slice.offset(index as isize) } } }
use crate::structs::raw::common::SubStatPropType; use crate::structs::raw::weapon_shared::WeaponType; use serde::Deserialize; #[derive(Deserialize)] #[serde(rename_all = "PascalCase")] pub struct WeaponProp { pub prop_type: Option<SubStatPropType>, pub init_value: Option<f64>, pub r#type: String, } #[derive(Deserialize)] #[serde(rename_all = "PascalCase")] pub struct Data { pub weapon_type: WeaponType, pub rank_level: usize, pub weapon_base_exp: usize, pub skill_affix: Vec<usize>, pub weapon_prop: Vec<WeaponProp>, pub awaken_texture: String, pub awaken_light_map_texture: String, pub awaken_icon: String, pub weapon_promote_id: usize, pub story_id: Option<usize>, pub awaken_costs: Vec<usize>, pub gacha_card_name_hash_suffix: usize, pub gacha_card_name_hash_pre: usize, pub destroy_rule: Option<String>, pub destroy_return_material: Vec<usize>, pub destroy_return_material_count: Vec<usize>, pub id: usize, pub name_text_map_hash: usize, pub desc_text_map_hash: usize, pub icon: String, pub item_type: String, // Duplicate identifier breaks parsing // pub weight: usize, pub rank: usize, pub gadget_id: usize, }
#[doc = "Reader of register ISR"] pub type R = crate::R<u32, super::ISR>; #[doc = "Writer for register ISR"] pub type W = crate::W<u32, super::ISR>; #[doc = "Register ISR `reset()`'s with value 0"] impl crate::ResetValue for super::ISR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "ADC ready\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADRDY_A { #[doc = "0: ADC not yet ready to start conversion"] NOTREADY = 0, #[doc = "1: ADC ready to start conversion"] READY = 1, } impl From<ADRDY_A> for bool { #[inline(always)] fn from(variant: ADRDY_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ADRDY`"] pub type ADRDY_R = crate::R<bool, ADRDY_A>; impl ADRDY_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ADRDY_A { match self.bits { false => ADRDY_A::NOTREADY, true => ADRDY_A::READY, } } #[doc = "Checks if the value of the field is `NOTREADY`"] #[inline(always)] pub fn is_not_ready(&self) -> bool { *self == ADRDY_A::NOTREADY } #[doc = "Checks if the value of the field is `READY`"] #[inline(always)] pub fn is_ready(&self) -> bool { *self == ADRDY_A::READY } } #[doc = "ADC ready\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADRDY_AW { #[doc = "1: Clear the ADC ready flag"] CLEAR = 1, } impl From<ADRDY_AW> for bool { #[inline(always)] fn from(variant: ADRDY_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `ADRDY`"] pub struct ADRDY_W<'a> { w: &'a mut W, } impl<'a> ADRDY_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADRDY_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear the ADC ready flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(ADRDY_AW::CLEAR) } #[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 = "End of sampling flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EOSMP_A { #[doc = "0: Not at the end of the samplings phase"] NOTATEND = 0, #[doc = "1: End of sampling phase reached"] ATEND = 1, } impl From<EOSMP_A> for bool { #[inline(always)] fn from(variant: EOSMP_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `EOSMP`"] pub type EOSMP_R = crate::R<bool, EOSMP_A>; impl EOSMP_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EOSMP_A { match self.bits { false => EOSMP_A::NOTATEND, true => EOSMP_A::ATEND, } } #[doc = "Checks if the value of the field is `NOTATEND`"] #[inline(always)] pub fn is_not_at_end(&self) -> bool { *self == EOSMP_A::NOTATEND } #[doc = "Checks if the value of the field is `ATEND`"] #[inline(always)] pub fn is_at_end(&self) -> bool { *self == EOSMP_A::ATEND } } #[doc = "End of sampling flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EOSMP_AW { #[doc = "1: Clear the sampling phase flag"] CLEAR = 1, } impl From<EOSMP_AW> for bool { #[inline(always)] fn from(variant: EOSMP_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `EOSMP`"] pub struct EOSMP_W<'a> { w: &'a mut W, } impl<'a> EOSMP_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EOSMP_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear the sampling phase flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(EOSMP_AW::CLEAR) } #[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 = "End of conversion flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EOC_A { #[doc = "0: Channel conversion is not complete"] NOTCOMPLETE = 0, #[doc = "1: Channel conversion complete"] COMPLETE = 1, } impl From<EOC_A> for bool { #[inline(always)] fn from(variant: EOC_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `EOC`"] pub type EOC_R = crate::R<bool, EOC_A>; impl EOC_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EOC_A { match self.bits { false => EOC_A::NOTCOMPLETE, true => EOC_A::COMPLETE, } } #[doc = "Checks if the value of the field is `NOTCOMPLETE`"] #[inline(always)] pub fn is_not_complete(&self) -> bool { *self == EOC_A::NOTCOMPLETE } #[doc = "Checks if the value of the field is `COMPLETE`"] #[inline(always)] pub fn is_complete(&self) -> bool { *self == EOC_A::COMPLETE } } #[doc = "End of conversion flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EOC_AW { #[doc = "1: Clear the channel conversion flag"] CLEAR = 1, } impl From<EOC_AW> for bool { #[inline(always)] fn from(variant: EOC_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `EOC`"] pub struct EOC_W<'a> { w: &'a mut W, } impl<'a> EOC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EOC_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear the channel conversion flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(EOC_AW::CLEAR) } #[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 = "End of sequence flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EOS_A { #[doc = "0: Conversion sequence is not complete"] NOTCOMPLETE = 0, #[doc = "1: Conversion sequence complete"] COMPLETE = 1, } impl From<EOS_A> for bool { #[inline(always)] fn from(variant: EOS_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `EOS`"] pub type EOS_R = crate::R<bool, EOS_A>; impl EOS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EOS_A { match self.bits { false => EOS_A::NOTCOMPLETE, true => EOS_A::COMPLETE, } } #[doc = "Checks if the value of the field is `NOTCOMPLETE`"] #[inline(always)] pub fn is_not_complete(&self) -> bool { *self == EOS_A::NOTCOMPLETE } #[doc = "Checks if the value of the field is `COMPLETE`"] #[inline(always)] pub fn is_complete(&self) -> bool { *self == EOS_A::COMPLETE } } #[doc = "End of sequence flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EOS_AW { #[doc = "1: Clear the conversion sequence flag"] CLEAR = 1, } impl From<EOS_AW> for bool { #[inline(always)] fn from(variant: EOS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `EOS`"] pub struct EOS_W<'a> { w: &'a mut W, } impl<'a> EOS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EOS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear the conversion sequence flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(EOS_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "ADC overrun\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OVR_A { #[doc = "0: No overrun occurred"] NOOVERRUN = 0, #[doc = "1: Overrun occurred"] OVERRUN = 1, } impl From<OVR_A> for bool { #[inline(always)] fn from(variant: OVR_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `OVR`"] pub type OVR_R = crate::R<bool, OVR_A>; impl OVR_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OVR_A { match self.bits { false => OVR_A::NOOVERRUN, true => OVR_A::OVERRUN, } } #[doc = "Checks if the value of the field is `NOOVERRUN`"] #[inline(always)] pub fn is_no_overrun(&self) -> bool { *self == OVR_A::NOOVERRUN } #[doc = "Checks if the value of the field is `OVERRUN`"] #[inline(always)] pub fn is_overrun(&self) -> bool { *self == OVR_A::OVERRUN } } #[doc = "ADC overrun\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OVR_AW { #[doc = "1: Clear the overrun flag"] CLEAR = 1, } impl From<OVR_AW> for bool { #[inline(always)] fn from(variant: OVR_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `OVR`"] pub struct OVR_W<'a> { w: &'a mut W, } impl<'a> OVR_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: OVR_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear the overrun flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(OVR_AW::CLEAR) } #[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 = "Analog watchdog flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum AWD_A { #[doc = "0: No analog watchdog event occurred"] NOEVENT = 0, #[doc = "1: Analog watchdog event occurred"] EVENT = 1, } impl From<AWD_A> for bool { #[inline(always)] fn from(variant: AWD_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `AWD`"] pub type AWD_R = crate::R<bool, AWD_A>; impl AWD_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> AWD_A { match self.bits { false => AWD_A::NOEVENT, true => AWD_A::EVENT, } } #[doc = "Checks if the value of the field is `NOEVENT`"] #[inline(always)] pub fn is_no_event(&self) -> bool { *self == AWD_A::NOEVENT } #[doc = "Checks if the value of the field is `EVENT`"] #[inline(always)] pub fn is_event(&self) -> bool { *self == AWD_A::EVENT } } #[doc = "Analog watchdog flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum AWD_AW { #[doc = "1: Clear the analog watchdog event flag"] CLEAR = 1, } impl From<AWD_AW> for bool { #[inline(always)] fn from(variant: AWD_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `AWD`"] pub struct AWD_W<'a> { w: &'a mut W, } impl<'a> AWD_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: AWD_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear the analog watchdog event flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(AWD_AW::CLEAR) } #[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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "End Of Calibration flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EOCAL_A { #[doc = "0: Calibration is not complete"] NOTCOMPLETE = 0, #[doc = "1: Calibration complete"] COMPLETE = 1, } impl From<EOCAL_A> for bool { #[inline(always)] fn from(variant: EOCAL_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `EOCAL`"] pub type EOCAL_R = crate::R<bool, EOCAL_A>; impl EOCAL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EOCAL_A { match self.bits { false => EOCAL_A::NOTCOMPLETE, true => EOCAL_A::COMPLETE, } } #[doc = "Checks if the value of the field is `NOTCOMPLETE`"] #[inline(always)] pub fn is_not_complete(&self) -> bool { *self == EOCAL_A::NOTCOMPLETE } #[doc = "Checks if the value of the field is `COMPLETE`"] #[inline(always)] pub fn is_complete(&self) -> bool { *self == EOCAL_A::COMPLETE } } #[doc = "End Of Calibration flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EOCAL_AW { #[doc = "1: Clear the calibration flag"] CLEAR = 1, } impl From<EOCAL_AW> for bool { #[inline(always)] fn from(variant: EOCAL_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `EOCAL`"] pub struct EOCAL_W<'a> { w: &'a mut W, } impl<'a> EOCAL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EOCAL_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clear the calibration flag"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(EOCAL_AW::CLEAR) } #[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 } } impl R { #[doc = "Bit 0 - ADC ready"] #[inline(always)] pub fn adrdy(&self) -> ADRDY_R { ADRDY_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - End of sampling flag"] #[inline(always)] pub fn eosmp(&self) -> EOSMP_R { EOSMP_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - End of conversion flag"] #[inline(always)] pub fn eoc(&self) -> EOC_R { EOC_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - End of sequence flag"] #[inline(always)] pub fn eos(&self) -> EOS_R { EOS_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - ADC overrun"] #[inline(always)] pub fn ovr(&self) -> OVR_R { OVR_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 7 - Analog watchdog flag"] #[inline(always)] pub fn awd(&self) -> AWD_R { AWD_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 11 - End Of Calibration flag"] #[inline(always)] pub fn eocal(&self) -> EOCAL_R { EOCAL_R::new(((self.bits >> 11) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - ADC ready"] #[inline(always)] pub fn adrdy(&mut self) -> ADRDY_W { ADRDY_W { w: self } } #[doc = "Bit 1 - End of sampling flag"] #[inline(always)] pub fn eosmp(&mut self) -> EOSMP_W { EOSMP_W { w: self } } #[doc = "Bit 2 - End of conversion flag"] #[inline(always)] pub fn eoc(&mut self) -> EOC_W { EOC_W { w: self } } #[doc = "Bit 3 - End of sequence flag"] #[inline(always)] pub fn eos(&mut self) -> EOS_W { EOS_W { w: self } } #[doc = "Bit 4 - ADC overrun"] #[inline(always)] pub fn ovr(&mut self) -> OVR_W { OVR_W { w: self } } #[doc = "Bit 7 - Analog watchdog flag"] #[inline(always)] pub fn awd(&mut self) -> AWD_W { AWD_W { w: self } } #[doc = "Bit 11 - End Of Calibration flag"] #[inline(always)] pub fn eocal(&mut self) -> EOCAL_W { EOCAL_W { w: self } } }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::HashMap; use common_exception::ErrorCode; use common_exception::Result; use metrics_exporter_prometheus::PrometheusHandle; #[derive(Debug)] pub struct MetricSample { pub name: String, pub labels: HashMap<String, String>, pub value: MetricValue, } #[derive(Debug, PartialEq, serde::Serialize)] pub enum MetricValue { Counter(f64), Gauge(f64), Untyped(f64), Histogram(Vec<HistogramCount>), Summary(Vec<SummaryCount>), } impl MetricValue { pub fn kind(&self) -> String { match self { MetricValue::Counter(_) => "counter", MetricValue::Gauge(_) => "gauge", MetricValue::Untyped(_) => "untyped", MetricValue::Histogram(_) => "histogram", MetricValue::Summary(_) => "summary", } .to_string() } } impl From<prometheus_parse::Value> for MetricValue { fn from(value: prometheus_parse::Value) -> Self { use prometheus_parse::Value; match value { Value::Counter(v) => MetricValue::Counter(v), Value::Gauge(v) => MetricValue::Gauge(v), Value::Untyped(v) => MetricValue::Untyped(v), Value::Histogram(v) => MetricValue::Histogram( v.iter() .map(|h| HistogramCount { less_than: h.less_than, count: h.count, }) .collect(), ), Value::Summary(v) => MetricValue::Summary( v.iter() .map(|s| SummaryCount { quantile: s.quantile, count: s.count, }) .collect(), ), } } } #[derive(Debug, PartialEq, serde::Serialize)] pub struct HistogramCount { pub less_than: f64, pub count: f64, } #[derive(Debug, PartialEq, serde::Serialize)] pub struct SummaryCount { pub quantile: f64, pub count: f64, } pub fn dump_metric_samples(handle: PrometheusHandle) -> Result<Vec<MetricSample>> { let text = handle.render(); let lines = text.lines().map(|s| Ok(s.to_owned())); let mut samples = prometheus_parse::Scrape::parse(lines) .map_err(|err| ErrorCode::Internal(format!("Dump prometheus metrics failed: {:?}", err)))? .samples .into_iter() .map(|s| { let value: MetricValue = s.value.into(); MetricSample { name: s.metric, value, labels: (*s.labels).clone(), } }) .collect::<Vec<_>>(); let proc_stats = dump_proc_stats().unwrap_or_default(); samples.extend(proc_stats); Ok(samples) } #[cfg(not(target_os = "linux"))] pub fn dump_proc_stats() -> Result<Vec<MetricSample>> { Ok(vec![]) } #[cfg(target_os = "linux")] pub fn dump_proc_stats() -> procfs::ProcResult<Vec<MetricSample>> { let me = procfs::process::Process::myself()?; let io = me.io()?; // ❯ cat /proc/thread-self/io // rchar: 4092 // wchar: 8 // syscr: 8 // syscw: 1 // read_bytes: 0 // write_bytes: 0 // cancelled_write_bytes: 0 let results = vec![ MetricSample { // "Number of bytes read from disks or block devices. Doesn't include bytes read from page cache." name: "os_read_bytes".to_string(), value: MetricValue::Counter(io.read_bytes as f64), labels: HashMap::new(), }, MetricSample { // "Number of bytes written to disks or block devices. Doesn't include bytes that are in page cache dirty pages." name: "os_write_bytes".to_string(), value: MetricValue::Counter(io.write_bytes as f64), labels: HashMap::new(), }, MetricSample { name: "os_read_chars".to_string(), value: MetricValue::Counter(io.rchar as f64), labels: HashMap::new(), }, MetricSample { name: "os_write_chars".to_string(), value: MetricValue::Counter(io.wchar as f64), labels: HashMap::new(), }, ]; Ok(results) }
#[doc = "Writer for register MICR"] pub type W = crate::W<u32, super::MICR>; #[doc = "Register MICR `reset()`'s with value 0"] impl crate::ResetValue for super::MICR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Master update Interrupt flag clear\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MUPDC_AW { #[doc = "1: Clears flag in MISR register"] CLEAR = 1, } impl From<MUPDC_AW> for bool { #[inline(always)] fn from(variant: MUPDC_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `MUPDC`"] pub struct MUPDC_W<'a> { w: &'a mut W, } impl<'a> MUPDC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MUPDC_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears flag in MISR register"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(MUPDC_AW::CLEAR) } #[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 } } #[doc = "Sync Input Interrupt flag clear"] pub type SYNCC_AW = MUPDC_AW; #[doc = "Write proxy for field `SYNCC`"] pub struct SYNCC_W<'a> { w: &'a mut W, } impl<'a> SYNCC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYNCC_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears flag in MISR register"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(MUPDC_AW::CLEAR) } #[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 = "Repetition Interrupt flag clear"] pub type MREPC_AW = MUPDC_AW; #[doc = "Write proxy for field `MREPC`"] pub struct MREPC_W<'a> { w: &'a mut W, } impl<'a> MREPC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MREPC_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears flag in MISR register"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(MUPDC_AW::CLEAR) } #[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 = "Master Compare 4 Interrupt flag clear"] pub type MCMP4C_AW = MUPDC_AW; #[doc = "Write proxy for field `MCMP4C`"] pub struct MCMP4C_W<'a> { w: &'a mut W, } impl<'a> MCMP4C_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MCMP4C_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears flag in MISR register"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(MUPDC_AW::CLEAR) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Master Compare 3 Interrupt flag clear"] pub type MCMP3C_AW = MUPDC_AW; #[doc = "Write proxy for field `MCMP3C`"] pub struct MCMP3C_W<'a> { w: &'a mut W, } impl<'a> MCMP3C_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MCMP3C_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears flag in MISR register"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(MUPDC_AW::CLEAR) } #[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 = "Master Compare 2 Interrupt flag clear"] pub type MCMP2C_AW = MUPDC_AW; #[doc = "Write proxy for field `MCMP2C`"] pub struct MCMP2C_W<'a> { w: &'a mut W, } impl<'a> MCMP2C_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MCMP2C_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears flag in MISR register"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(MUPDC_AW::CLEAR) } #[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 = "Master Compare 1 Interrupt flag clear"] pub type MCMP1C_AW = MUPDC_AW; #[doc = "Write proxy for field `MCMP1C`"] pub struct MCMP1C_W<'a> { w: &'a mut W, } impl<'a> MCMP1C_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MCMP1C_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Clears flag in MISR register"] #[inline(always)] pub fn clear(self) -> &'a mut W { self.variant(MUPDC_AW::CLEAR) } #[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 } } impl W { #[doc = "Bit 6 - Master update Interrupt flag clear"] #[inline(always)] pub fn mupdc(&mut self) -> MUPDC_W { MUPDC_W { w: self } } #[doc = "Bit 5 - Sync Input Interrupt flag clear"] #[inline(always)] pub fn syncc(&mut self) -> SYNCC_W { SYNCC_W { w: self } } #[doc = "Bit 4 - Repetition Interrupt flag clear"] #[inline(always)] pub fn mrepc(&mut self) -> MREPC_W { MREPC_W { w: self } } #[doc = "Bit 3 - Master Compare 4 Interrupt flag clear"] #[inline(always)] pub fn mcmp4c(&mut self) -> MCMP4C_W { MCMP4C_W { w: self } } #[doc = "Bit 2 - Master Compare 3 Interrupt flag clear"] #[inline(always)] pub fn mcmp3c(&mut self) -> MCMP3C_W { MCMP3C_W { w: self } } #[doc = "Bit 1 - Master Compare 2 Interrupt flag clear"] #[inline(always)] pub fn mcmp2c(&mut self) -> MCMP2C_W { MCMP2C_W { w: self } } #[doc = "Bit 0 - Master Compare 1 Interrupt flag clear"] #[inline(always)] pub fn mcmp1c(&mut self) -> MCMP1C_W { MCMP1C_W { w: self } } }
use hello::ThreadPool; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::time::Duration; use std::{fs, thread}; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); let pool = ThreadPool::new(4); // // incoming 返回 TcpStream 的迭代器,stream 代表一个客户端和服务端之间打开的 connection // // connection 代表客户端连接服务端、服务端生成响应以及服务端关系连接的全部请求/响应过程 // for stream in listener.incoming() { // let stream = stream.unwrap(); // // pool.execute(|| handle_connection(stream)); // } // show case for graceful shutting down after 2 requests for stream in listener.incoming().take(2) { let stream = stream.unwrap(); pool.execute(|| handle_connection(stream)); } println!("Shutting down.") } fn handle_connection(mut stream: TcpStream) { let mut buffer = [0; 512]; stream.read(&mut buffer).unwrap(); // println!("Request: {}", String::from_utf8_lossy(&buffer[..])); // b"" 字节字符串语法将其转换为字节字符串 &str -> &[u8,] let get = b"GET / HTTP/1.1\r\n"; let sleep = b"GET /sleep HTTP/1.1\r\n"; let (status_line, filename) = if buffer.starts_with(get) { ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") } else if buffer.starts_with(sleep) { thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") } else { ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") }; let contents = fs::read_to_string(filename).unwrap(); let response = format!("{}{}", status_line, contents); stream.write(response.as_bytes()).unwrap(); stream.flush().unwrap(); } // HTTP 是一个基于文本的协议 // 一个请求有如下格式: // Method Request-URI HTTP-VERSION CRLF // headers CRLF // message-body // 第一行叫做 request line // 请求函数 统一资源标识符(URI) HTTP客户端版本 CRLF序列(代表回车和换行 carriage return line feed, \r\n) // 下面这个请求实体从 Host: 开始的都是 headers,GET请求没有 body // GET / HTTP/1.1 // Host: 127.0.0.1:7878 // Connection: keep-alive // Cache-Control: max-age=0 // Upgrade-Insecure-Requests: 1 // User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 // Sec-Fetch-Mode: navigate // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*//*//*;q=0.8,application/signed-exchange;v=b3 // Sec-Fetch-Site: cross-site // Accept-Encoding: gzip, deflate, br // Accept-Language: zh-CN,zh;q=0.9,en;q=0.8 // 缩写响应 // 一个响应有如下格式: // HTTP-Version Status-Code Reason-Phrase CRLF // headers CRLF // message-body // 第一行叫做 status line // HTTP版本 一个数字状态码 一个描述之前状态码的文本原因短语,CRLF 序列之后是任意 header,另一个 CRLF 序列,和响应的 body // HTTP/1.1 200 OK\r\n\r\n
use crate::smb2::{header, requests}; pub mod create_request; pub mod negotiate_request; pub mod query_info_request; pub mod session_setup_authenticate_request; pub mod session_setup_negotiate_request; pub mod tree_connect_request; /// Builds a sync header with the corresponding parameters. /// - The tree id will only be set after the tree connect response from the server. /// - The session id will only be set after the session setup response from the server. pub fn build_sync_header( command: header::Commands, credit_charge: u16, credit_request: u16, tree_id: Option<Vec<u8>>, session_id: Option<Vec<u8>>, message_id: u64, ) -> header::SyncHeader { let mut header = header::SyncHeader::default(); header.generic.credit_charge = credit_charge.to_le_bytes().to_vec(); header.generic.channel_sequence = vec![0; 2]; header.generic.reserved = vec![0; 2]; header.generic.command = command.unpack_byte_code(); header.generic.credit = credit_request.to_le_bytes().to_vec(); header.generic.flags = header::Flags::DfsOperations.unpack_byte_code(); header.generic.next_command = vec![0; 4]; header.generic.message_id = message_id.to_le_bytes().to_vec(); header.tree_id = match tree_id { Some(id) => id, None => vec![0; 4], }; header.session_id = match session_id { Some(id) => id, None => vec![0; 8], }; header.signature = vec![0; 16]; header } /// Creates a complete create request. pub fn build_default_echo_request() -> (Option<header::SyncHeader>, Option<requests::echo::Echo>) { ( Some(build_sync_header( header::Commands::Echo, 1, 7968, None, None, 6, )), Some(requests::echo::Echo::default()), ) } /// Creates a complete close request. pub fn build_close_request( tree_id: Vec<u8>, session_id: Vec<u8>, file_id: Vec<u8>, ) -> (Option<header::SyncHeader>, Option<requests::close::Close>) { let mut close = requests::close::Close::default(); close.file_id = file_id; ( Some(build_sync_header( header::Commands::Close, 1, 7872, Some(tree_id), Some(session_id), 7, )), Some(close), ) } #[cfg(test)] mod tests { use super::*; #[test] fn test_build_sync_header() { let result = build_sync_header( header::Commands::SessionSetup, 1, 1, Some(vec![1, 0, 0, 0]), Some(vec![1, 0, 0, 0, 0, 0, 0, 0]), 10, ); assert_eq!(vec![1, 0], result.generic.credit_charge); assert_eq!(vec![1, 0], result.generic.credit); assert_eq!(vec![1, 0], result.generic.command); assert_eq!(vec![1, 0, 0, 0], result.tree_id); assert_eq!(vec![1, 0, 0, 0, 0, 0, 0, 0], result.session_id); assert_eq!(vec![10, 0, 0, 0, 0, 0, 0, 0], result.generic.message_id); } }
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0. use std::borrow::Borrow; use std::cmp::Ordering; use std::fmt; use std::ops::{Deref, DerefMut}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)] pub struct Key(String); impl fmt::Display for Key { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } pub const LEFT_SLASH: u8 = b'/'; pub const LEFT_SLASH_STR: &str = "/"; /// ensure after clean, string is start with "/", and cleaned with the rule of "path_clean" pub fn clean<S: AsRef<str>>(s: S) -> String { let b = s.as_ref().as_bytes(); if b.is_empty() { LEFT_SLASH_STR.to_string() } else if b[0] == LEFT_SLASH { path_clean::clean(s.as_ref()) } else { let s = LEFT_SLASH_STR.to_string() + s.as_ref(); path_clean::clean(&s) } } /* A Key Namespace is like a path element. A namespace can optionally include a type (delimited by ':') > NamespaceValue("Song:PhilosopherSong") PhilosopherSong > NamespaceType("Song:PhilosopherSong") Song > NamespaceType("Music:Song:PhilosopherSong") Music:Song */ /// `namespace_type()` is the first component of a namespace. `foo` in `foo:bar` pub fn namespace_type(input: &str) -> &str { input .rfind(|f| f == ':') .map(|i| input.split_at(i).0) .unwrap_or(&"") } /// `namespace_value()` returns the last component of a namespace. `baz` in `f:b:baz` pub fn namespace_value(input: &str) -> &str { input .rfind(|f| f == ':') .map(|i| input.split_at(i + 1).1) .unwrap_or(input) } impl Key { /// constructs a key from string. it will clean the value. pub fn new<T: AsRef<str>>(s: T) -> Self { let k = clean(s); Key(k) } /// creates a new Key without safety checking the input. Use with care. pub fn from_raw<T: AsRef<str>>(s: T) -> Self { // it's safe to use &[u8] to check, due to we only check char "/" let c_str: &[u8] = s.as_ref().as_bytes(); if c_str.is_empty() { return Key(LEFT_SLASH_STR.to_string()); } // s.len() must large than 1 if c_str[0] != LEFT_SLASH || (c_str.len() > 1 && c_str[c_str.len() - 1] == LEFT_SLASH) { panic!(format!("invalid datastore key: {:}", s.as_ref())); } Key(s.as_ref().to_string()) } pub fn key_with_namespace<I: AsRef<str>, V: AsRef<[I]>>(v: V) -> Self { let v: Vec<&str> = v.as_ref().iter().map(|i| i.as_ref()).collect(); let s_ref_list: &[&str] = v.as_ref(); let s = s_ref_list.join(LEFT_SLASH_STR); Key::new(s) } /// `random_key()` returns a randomly (uuid) generated key. /// RandomKey() /// NewKey("/f98719ea086343f7b71f32ea9d9d521d") pub fn random_key() -> Self { let uuid = uuid::Uuid::new_v4(); Key::new(uuid.to_string().replace("-", "")) } pub fn clean(&mut self) { let new_k = clean(&self.0); self.0 = new_k; } /// `list()` returns the `list` representation of this Key. /// NewKey("/Comedy/MontyPython/Actor:JohnCleese").List() /// ["Comedy", "MontyPythong", "Actor:JohnCleese"] pub fn list(&self) -> Vec<&str> { // equal to strings.Split(k.string, "/")[1:], just ignore first item self.0.split(LEFT_SLASH_STR).skip(1).collect::<Vec<_>>() } pub fn split_prefix(&self) -> (Option<&str>, &str) { // key first char must be "/", skip check it let skip = 1; if let Some(i) = &self.0[skip..].find(LEFT_SLASH_STR) { let (a, b) = self.0.split_at(*i + skip); (Some(a), b) } else { (None, &self) } } /// `reverse()` returns the reverse of this Key. /// NewKey("/Comedy/MontyPython/Actor:JohnCleese").Reverse() /// NewKey("/Actor:JohnCleese/MontyPython/Comedy") pub fn reverse(&self) -> Key { let mut l = self.list(); l.reverse(); Key::key_with_namespace(l) } /// `namespace()` returns the `namespaces` making up this Key. /// NewKey("/Comedy/MontyPython/Actor:JohnCleese").Namespaces() /// ["Comedy", "MontyPython", "Actor:JohnCleese"] pub fn namespace(&self) -> Vec<&str> { self.list() } pub fn base_namespace(&self) -> &str { self.list().last().unwrap_or(&"") } /// `type_()` returns the "type" of this key (value of last namespace). /// NewKey("/Comedy/MontyPython/Actor:JohnCleese").Type() /// "Actor" pub fn type_(&self) -> &str { namespace_type(self.base_namespace()) } /// Name returns the "name" of this key (field of last namespace). /// NewKey("/Comedy/MontyPython/Actor:JohnCleese").Name() /// "JohnCleese" pub fn name(&self) -> &str { namespace_value(self.base_namespace()) } /// `instance()` returns an "instance" of this type key (appends value to namespace). /// NewKey("/Comedy/MontyPython/Actor").Instance("JohnClesse") /// NewKey("/Comedy/MontyPython/Actor:JohnCleese") pub fn instance<T: AsRef<str>>(&self, s: T) -> Key { self.clone().into_instance(s) } pub fn into_instance<T: AsRef<str>>(self, s: T) -> Key { Key::new(self.0 + ":" + s.as_ref()) } /// Path returns the "path" of this key (parent + type). /// NewKey("/Comedy/MontyPython/Actor:JohnCleese").Path() /// NewKey("/Comedy/MontyPython/Actor") pub fn path(&self) -> Key { self.clone().into_path() } pub fn into_path(self) -> Key { let k = self.parent(); let s = k.0 + LEFT_SLASH_STR + namespace_type(self.base_namespace()); Key::new(s) } /// Parent returns the `parent` Key of this Key. /// NewKey("/Comedy/MontyPython/Actor:JohnCleese").Parent() /// NewKey("/Comedy/MontyPython") pub fn parent(&self) -> Key { let l = self.list(); if l.len() == 1 { return Key::from_raw(LEFT_SLASH_STR); } Key::new(l[..l.len() - 1].join(LEFT_SLASH_STR)) } pub fn into_parent(self) -> Key { self.parent() } /// `child()` returns the `child` Key of this Key. /// NewKey("/Comedy/MontyPython").Child(NewKey("Actor:JohnCleese")) /// NewKey("/Comedy/MontyPython/Actor:JohnCleese") pub fn child<K: AsRef<Key> + Into<Key>>(&self, k2: K) -> Key { self.clone().into_child(k2) } pub fn into_child<K: AsRef<Key> + Into<Key>>(self, k2: K) -> Key { if self.as_str() == "/" { k2.into() } else if k2.as_ref().as_str() == "/" { self } else { Key::from_raw(self.0 + k2.as_ref().as_str()) } } /// `child_string()` returns the `child` Key of this Key -- string helper. /// NewKey("/Comedy/M;' /// ontyPython").ChildString("Actor:JohnCleese") /// NewKey("/Comedy/MontyPython/Actor:JohnCleese") pub fn child_string<T: AsRef<str>>(&self, s: T) -> Key { self.clone().into_child_string(s) } pub fn into_child_string<T: AsRef<str>>(self, s: T) -> Key { let src = self.0; Key::new(src + LEFT_SLASH_STR + s.as_ref()) } /// `is_ancestor_of()` returns whether this key contains another as a prefix. /// NewKey("/Comedy").IsAncestorOf("/Comedy/MontyPython") /// true pub fn is_ancestor_of<K: AsRef<str>>(&self, other: K) -> bool { if other.as_ref().starts_with(self.as_str()) { other.as_ref().as_bytes().len() > self.as_bytes().len() } else { false } } /// `is_descendant_of()` returns whether this key contains another as a prefix. /// NewKey("/Comedy/MontyPython").IsDescendantOf("/Comedy") /// true pub fn is_descendant_of<K: AsRef<str>>(&self, other: K) -> bool { if self.as_str().starts_with(other.as_ref()) { self.as_bytes().len() > other.as_ref().as_bytes().len() } else { false } } /// IsTopLevel returns whether this key has only one namespace. pub fn is_top_level(&self) -> bool { self.list().len() == 1 } } impl PartialOrd for Key { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for Key { fn cmp(&self, other: &Self) -> Ordering { let list1 = self.list(); let list2 = other.list(); list1.cmp(&list2) } } impl Into<String> for Key { fn into(self) -> String { self.0 } } impl Into<Vec<u8>> for Key { fn into(self) -> Vec<u8> { self.0.into_bytes() } } impl Into<Key> for &Key { fn into(self) -> Key { (*self).clone() } } impl From<String> for Key { fn from(s: String) -> Self { Key::new(s) } } impl From<&str> for Key { fn from(s: &str) -> Self { Key::new(s) } } impl AsRef<str> for Key { fn as_ref(&self) -> &str { self.0.as_str() } } impl AsRef<[u8]> for Key { fn as_ref(&self) -> &[u8] { self.0.as_bytes() } } impl AsRef<Key> for Key { fn as_ref(&self) -> &Key { &self } } impl AsMut<str> for Key { fn as_mut(&mut self) -> &mut str { self.0.as_mut_str() } } impl Borrow<str> for Key { fn borrow(&self) -> &str { self.0.borrow() } } impl Deref for Key { type Target = String; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Key { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
//! Support for building `explicit_bzero.c` backport for Linux w\ glibc < 2.25. #[cfg(any(feature = "linux-backport", feature = "windows"))] extern crate cc; #[cfg(any(feature = "linux-backport", feature = "windows"))] extern crate semver; fn main() { #[cfg(all(feature = "linux-backport", target_os = "linux"))] linux::build_explicit_bzero_backport(); #[cfg(all(feature = "windows", target_os = "windows"))] windows::build_explicit_bzero_shim(); } /// Support for building the `explicit_bzero.c` backport. /// Only used when the `linux-backport` cargo feature is enabled and the /// installed glibc version is < 2.25 or musl-libc version is < 1.1.20. #[cfg(all(feature = "linux-backport", target_os = "linux"))] mod linux { use super::cc; use super::semver::Version; use std::process::Command; /// First version of glibc to support `explicit_bzero()` const GLIBC_WITH_EXPLICIT_BZERO: &str = "2.25.0"; /// First version of musl-libc to support `explicit_bzero()` const MUSL_WITH_EXPLICIT_BZERO: &str = "1.1.20"; struct LddVersion { /// Whether version command was successful. success: bool, /// Standard output of the version command. stdout: String, /// Standard error of the version command, stderr: String, } enum StdLibrary { /// GNU C standard library GNU(Version), /// Musl C standard library Musl(Version), /// Unsupported standard library Unsupported, } impl StdLibrary { /// Build backports if necessary fn should_build_explicit_bzero(&self) -> Option<bool> { match self { StdLibrary::GNU(ver) => { Some(ver < &Version::parse(GLIBC_WITH_EXPLICIT_BZERO).unwrap()) } StdLibrary::Musl(ver) => { Some(ver < &Version::parse(MUSL_WITH_EXPLICIT_BZERO).unwrap()) } StdLibrary::Unsupported => None, } } } impl LddVersion { /// Initialize LddVersion with the version command output fn new() -> Self { let output = Command::new("/usr/bin/ldd") .arg("--version") .output() .unwrap(); Self { success: output.status.success(), stdout: String::from_utf8(output.stdout).unwrap(), stderr: String::from_utf8(output.stderr).unwrap(), } } /// Resolve the version of the installed C standard library fn resolve(&self) -> StdLibrary { let stdout = self.stdout.to_ascii_lowercase(); let stderr = self.stderr.to_ascii_lowercase(); // Check if this is GNU C standard library if stdout.find("glibc").is_some() || stderr.find("glibc").is_some() { return self.get_glibc_version(); } // Check if this is musl-libc if stdout.find("musl").is_some() || stderr.find("musl").is_some() { return self.get_musl_version(); } StdLibrary::Unsupported } /// Get the version of the GNU C standard library fn get_glibc_version(&self) -> StdLibrary { if !self.success { panic!( "/usr/bin/ldd --version exited with error: {:?}", self.stderr ); } let info = self.stdout.split('\n').next().unwrap(); let version = Version::parse(&(info.split(' ').last().unwrap().to_owned() + ".0")).unwrap(); StdLibrary::GNU(version) } /// Get the version of the Musl C standard library fn get_musl_version(&self) -> StdLibrary { let info = self.stderr.split('\n').collect::<Vec<&str>>()[1]; let version = Version::parse(info.split(' ').collect::<Vec<&str>>()[1]).unwrap(); StdLibrary::Musl(version) } } /// Build `src/os/linux/explicit_bzero_backport.c` using the `cc` crate pub fn build_explicit_bzero_backport() { let ldd_version = LddVersion::new(); let stdlib = ldd_version.resolve(); match stdlib.should_build_explicit_bzero() { Some(should_build) => if should_build { cc::Build::new() .file("src/os/linux/explicit_bzero_backport.c") .compile("explicit_bzero"); }, None => panic!("unsupported standard library"), } } } /// Support for `SecureZeroMemory` (a macro found in `winnt.h`) is implemented /// as a shim for the `explicit_bzero()` API. #[cfg(all(feature = "windows", target_os = "windows"))] mod windows { use super::cc; /// Build `src/os/windows/explicit_bzero_shim.c` using the `cc` crate pub fn build_explicit_bzero_shim() { cc::Build::new() .file("src/os/windows/explicit_bzero_shim.c") .compile("explicit_bzero"); } }
use super::common::Span; use std::str::Chars; pub struct Lexer<'a> { chars: Chars<'a>, input_len: usize, } impl<'a> Lexer<'a> { pub fn new(input: &'a str) -> Lexer<'a> { Lexer { chars: input.chars(), input_len: input.len(), } } fn eat_next(&mut self) -> Option<Token> { let start = self.current_pos(); let next = self.munch(); if next.is_none() { return None; } let next = next.unwrap(); let kind = match next { '[' => TokenKind::LBracket, ']' => TokenKind::RBracket, '(' => TokenKind::LParen, ')' => TokenKind::RParen, '\n' => TokenKind::Newline, '`' => self.eat_backticks(start), _ => self.eat_text(), }; let end = self.current_pos(); Some(Token { kind, span: (start, end), }) } fn eat_backticks(&mut self, first_tick_pos: usize) -> TokenKind { self.eat_while(|c| c == '`'); let count = self.current_pos() - first_tick_pos; match count { 1 => TokenKind::Backtick, 3 => TokenKind::TripleBacktick, _ => TokenKind::Text, } } fn eat_text(&mut self) -> TokenKind { self.eat_while(|c| match c { '[' | ']' | '(' | ')' | '\n' | '`' => false, _ => true, }); TokenKind::Text } fn current_pos(&self) -> usize { self.input_len - self.chars.as_str().len() } fn peek(&self) -> Option<char> { self.chars.clone().next() } fn munch(&mut self) -> Option<char> { self.chars.next() } fn eat_while<F>(&mut self, pred: F) where F: Fn(char) -> bool, { while let Some(c) = self.peek() { if !pred(c) { break; } self.munch(); } } } impl<'a> Iterator for Lexer<'a> { type Item = Token; fn next(&mut self) -> Option<Self::Item> { self.eat_next() } } #[derive(Debug, PartialEq)] pub struct Token { pub kind: TokenKind, pub span: Span, } #[derive(Debug, PartialEq)] pub enum TokenKind { Text, Newline, LBracket, RBracket, LParen, RParen, Backtick, TripleBacktick, } #[cfg(test)] mod tests { use super::*; use TokenKind::*; macro_rules! toks { ( $( ($kind:expr, $len:expr) ),* ) => { { let mut tokens = vec![]; let mut end = 0; $( end += $len; tokens.push(Token { kind: $kind, span: (end - $len, end), }); )* tokens } }; } #[test] fn lex1() { let input = "This is a test with a `couple` of [lines](http://test.com) ``` And some preformatted text ```"; assert_eq!( Lexer::new(input).collect::<Vec<Token>>(), toks![ (Text, 14), (Newline, 1), (Text, 7), (Backtick, 1), (Text, 6), (Backtick, 1), (Text, 4), (LBracket, 1), (Text, 5), (RBracket, 1), (LParen, 1), (Text, 15), (RParen, 1), (Newline, 1), (TripleBacktick, 3), (Newline, 1), (Text, 21), (Newline, 1), (Text, 4), (Newline, 1), (TripleBacktick, 3) ] ); } }
#[doc = "Reader of register CFGR2"] pub type R = crate::R<u32, super::CFGR2>; #[doc = "Writer for register CFGR2"] pub type W = crate::W<u32, super::CFGR2>; #[doc = "Register CFGR2 `reset()`'s with value 0"] impl crate::ResetValue for super::CFGR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Sampling time control trigger mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SMPTRIG_A { #[doc = "0: Sampling time control trigger mode disabled"] DISABLED = 0, #[doc = "1: Sampling time control trigger mode enabled"] ENABLED = 1, } impl From<SMPTRIG_A> for bool { #[inline(always)] fn from(variant: SMPTRIG_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `SMPTRIG`"] pub type SMPTRIG_R = crate::R<bool, SMPTRIG_A>; impl SMPTRIG_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SMPTRIG_A { match self.bits { false => SMPTRIG_A::DISABLED, true => SMPTRIG_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == SMPTRIG_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == SMPTRIG_A::ENABLED } } #[doc = "Write proxy for field `SMPTRIG`"] pub struct SMPTRIG_W<'a> { w: &'a mut W, } impl<'a> SMPTRIG_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SMPTRIG_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Sampling time control trigger mode disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(SMPTRIG_A::DISABLED) } #[doc = "Sampling time control trigger mode enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(SMPTRIG_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Bulb sampling mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum BULB_A { #[doc = "0: Bulb sampling mode disabled"] DISABLED = 0, #[doc = "1: Bulb sampling mode enabled. Immediately start sampling after last conversion finishes."] ENABLED = 1, } impl From<BULB_A> for bool { #[inline(always)] fn from(variant: BULB_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `BULB`"] pub type BULB_R = crate::R<bool, BULB_A>; impl BULB_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> BULB_A { match self.bits { false => BULB_A::DISABLED, true => BULB_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == BULB_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == BULB_A::ENABLED } } #[doc = "Write proxy for field `BULB`"] pub struct BULB_W<'a> { w: &'a mut W, } impl<'a> BULB_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BULB_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Bulb sampling mode disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(BULB_A::DISABLED) } #[doc = "Bulb sampling mode enabled. Immediately start sampling after last conversion finishes."] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(BULB_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Software trigger bit for sampling time control trigger mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SWTRIG_A { #[doc = "0: End sampling period and start conversion"] DISABLED = 0, #[doc = "1: Start sampling period"] ENABLED = 1, } impl From<SWTRIG_A> for bool { #[inline(always)] fn from(variant: SWTRIG_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `SWTRIG`"] pub type SWTRIG_R = crate::R<bool, SWTRIG_A>; impl SWTRIG_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SWTRIG_A { match self.bits { false => SWTRIG_A::DISABLED, true => SWTRIG_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == SWTRIG_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == SWTRIG_A::ENABLED } } #[doc = "Write proxy for field `SWTRIG`"] pub struct SWTRIG_W<'a> { w: &'a mut W, } impl<'a> SWTRIG_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SWTRIG_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "End sampling period and start conversion"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(SWTRIG_A::DISABLED) } #[doc = "Start sampling period"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(SWTRIG_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Gain compensation mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum GCOMP_A { #[doc = "0: Regular ADC operating mode"] DISABLED = 0, #[doc = "1: Gain compensation enabled and applies to all channels"] ENABLED = 1, } impl From<GCOMP_A> for bool { #[inline(always)] fn from(variant: GCOMP_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `GCOMP`"] pub type GCOMP_R = crate::R<bool, GCOMP_A>; impl GCOMP_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> GCOMP_A { match self.bits { false => GCOMP_A::DISABLED, true => GCOMP_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == GCOMP_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == GCOMP_A::ENABLED } } #[doc = "Write proxy for field `GCOMP`"] pub struct GCOMP_W<'a> { w: &'a mut W, } impl<'a> GCOMP_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GCOMP_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Regular ADC operating mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GCOMP_A::DISABLED) } #[doc = "Gain compensation enabled and applies to all channels"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GCOMP_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Regular Oversampling mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ROVSM_A { #[doc = "0: Oversampling is temporary stopped and continued after injection sequence"] CONTINUED = 0, #[doc = "1: Oversampling is aborted and resumed from start after injection sequence"] RESUMED = 1, } impl From<ROVSM_A> for bool { #[inline(always)] fn from(variant: ROVSM_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ROVSM`"] pub type ROVSM_R = crate::R<bool, ROVSM_A>; impl ROVSM_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ROVSM_A { match self.bits { false => ROVSM_A::CONTINUED, true => ROVSM_A::RESUMED, } } #[doc = "Checks if the value of the field is `CONTINUED`"] #[inline(always)] pub fn is_continued(&self) -> bool { *self == ROVSM_A::CONTINUED } #[doc = "Checks if the value of the field is `RESUMED`"] #[inline(always)] pub fn is_resumed(&self) -> bool { *self == ROVSM_A::RESUMED } } #[doc = "Write proxy for field `ROVSM`"] pub struct ROVSM_W<'a> { w: &'a mut W, } impl<'a> ROVSM_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ROVSM_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Oversampling is temporary stopped and continued after injection sequence"] #[inline(always)] pub fn continued(self) -> &'a mut W { self.variant(ROVSM_A::CONTINUED) } #[doc = "Oversampling is aborted and resumed from start after injection sequence"] #[inline(always)] pub fn resumed(self) -> &'a mut W { self.variant(ROVSM_A::RESUMED) } #[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 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Triggered Regular Oversampling\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TROVS_A { #[doc = "0: All oversampled conversions for a channel are run following a trigger"] AUTOMATIC = 0, #[doc = "1: Each oversampled conversion for a channel needs a new trigger"] TRIGGERED = 1, } impl From<TROVS_A> for bool { #[inline(always)] fn from(variant: TROVS_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TROVS`"] pub type TROVS_R = crate::R<bool, TROVS_A>; impl TROVS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TROVS_A { match self.bits { false => TROVS_A::AUTOMATIC, true => TROVS_A::TRIGGERED, } } #[doc = "Checks if the value of the field is `AUTOMATIC`"] #[inline(always)] pub fn is_automatic(&self) -> bool { *self == TROVS_A::AUTOMATIC } #[doc = "Checks if the value of the field is `TRIGGERED`"] #[inline(always)] pub fn is_triggered(&self) -> bool { *self == TROVS_A::TRIGGERED } } #[doc = "Write proxy for field `TROVS`"] pub struct TROVS_W<'a> { w: &'a mut W, } impl<'a> TROVS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TROVS_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "All oversampled conversions for a channel are run following a trigger"] #[inline(always)] pub fn automatic(self) -> &'a mut W { self.variant(TROVS_A::AUTOMATIC) } #[doc = "Each oversampled conversion for a channel needs a new trigger"] #[inline(always)] pub fn triggered(self) -> &'a mut W { self.variant(TROVS_A::TRIGGERED) } #[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 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Oversampling shift\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum OVSS_A { #[doc = "0: No right shift applied to oversampling result"] NOSHIFT = 0, #[doc = "1: Shift oversampling result right by 1 bit"] SHIFT1 = 1, #[doc = "2: Shift oversampling result right by 2 bits"] SHIFT2 = 2, #[doc = "3: Shift oversampling result right by 3 bits"] SHIFT3 = 3, #[doc = "4: Shift oversampling result right by 4 bits"] SHIFT4 = 4, #[doc = "5: Shift oversampling result right by 5 bits"] SHIFT5 = 5, #[doc = "6: Shift oversampling result right by 6 bits"] SHIFT6 = 6, #[doc = "7: Shift oversampling result right by 7 bits"] SHIFT7 = 7, #[doc = "8: Shift oversampling result right by 8 bits"] SHIFT8 = 8, } impl From<OVSS_A> for u8 { #[inline(always)] fn from(variant: OVSS_A) -> Self { variant as _ } } #[doc = "Reader of field `OVSS`"] pub type OVSS_R = crate::R<u8, OVSS_A>; impl OVSS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, OVSS_A> { use crate::Variant::*; match self.bits { 0 => Val(OVSS_A::NOSHIFT), 1 => Val(OVSS_A::SHIFT1), 2 => Val(OVSS_A::SHIFT2), 3 => Val(OVSS_A::SHIFT3), 4 => Val(OVSS_A::SHIFT4), 5 => Val(OVSS_A::SHIFT5), 6 => Val(OVSS_A::SHIFT6), 7 => Val(OVSS_A::SHIFT7), 8 => Val(OVSS_A::SHIFT8), i => Res(i), } } #[doc = "Checks if the value of the field is `NOSHIFT`"] #[inline(always)] pub fn is_no_shift(&self) -> bool { *self == OVSS_A::NOSHIFT } #[doc = "Checks if the value of the field is `SHIFT1`"] #[inline(always)] pub fn is_shift1(&self) -> bool { *self == OVSS_A::SHIFT1 } #[doc = "Checks if the value of the field is `SHIFT2`"] #[inline(always)] pub fn is_shift2(&self) -> bool { *self == OVSS_A::SHIFT2 } #[doc = "Checks if the value of the field is `SHIFT3`"] #[inline(always)] pub fn is_shift3(&self) -> bool { *self == OVSS_A::SHIFT3 } #[doc = "Checks if the value of the field is `SHIFT4`"] #[inline(always)] pub fn is_shift4(&self) -> bool { *self == OVSS_A::SHIFT4 } #[doc = "Checks if the value of the field is `SHIFT5`"] #[inline(always)] pub fn is_shift5(&self) -> bool { *self == OVSS_A::SHIFT5 } #[doc = "Checks if the value of the field is `SHIFT6`"] #[inline(always)] pub fn is_shift6(&self) -> bool { *self == OVSS_A::SHIFT6 } #[doc = "Checks if the value of the field is `SHIFT7`"] #[inline(always)] pub fn is_shift7(&self) -> bool { *self == OVSS_A::SHIFT7 } #[doc = "Checks if the value of the field is `SHIFT8`"] #[inline(always)] pub fn is_shift8(&self) -> bool { *self == OVSS_A::SHIFT8 } } #[doc = "Write proxy for field `OVSS`"] pub struct OVSS_W<'a> { w: &'a mut W, } impl<'a> OVSS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: OVSS_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "No right shift applied to oversampling result"] #[inline(always)] pub fn no_shift(self) -> &'a mut W { self.variant(OVSS_A::NOSHIFT) } #[doc = "Shift oversampling result right by 1 bit"] #[inline(always)] pub fn shift1(self) -> &'a mut W { self.variant(OVSS_A::SHIFT1) } #[doc = "Shift oversampling result right by 2 bits"] #[inline(always)] pub fn shift2(self) -> &'a mut W { self.variant(OVSS_A::SHIFT2) } #[doc = "Shift oversampling result right by 3 bits"] #[inline(always)] pub fn shift3(self) -> &'a mut W { self.variant(OVSS_A::SHIFT3) } #[doc = "Shift oversampling result right by 4 bits"] #[inline(always)] pub fn shift4(self) -> &'a mut W { self.variant(OVSS_A::SHIFT4) } #[doc = "Shift oversampling result right by 5 bits"] #[inline(always)] pub fn shift5(self) -> &'a mut W { self.variant(OVSS_A::SHIFT5) } #[doc = "Shift oversampling result right by 6 bits"] #[inline(always)] pub fn shift6(self) -> &'a mut W { self.variant(OVSS_A::SHIFT6) } #[doc = "Shift oversampling result right by 7 bits"] #[inline(always)] pub fn shift7(self) -> &'a mut W { self.variant(OVSS_A::SHIFT7) } #[doc = "Shift oversampling result right by 8 bits"] #[inline(always)] pub fn shift8(self) -> &'a mut W { self.variant(OVSS_A::SHIFT8) } #[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 << 5)) | (((value as u32) & 0x0f) << 5); self.w } } #[doc = "Oversampling ratio\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum OVSR_A { #[doc = "0: Oversampling ratio of 2"] OS2 = 0, #[doc = "1: Oversampling ratio of 4"] OS4 = 1, #[doc = "2: Oversampling ratio of 8"] OS8 = 2, #[doc = "3: Oversampling ratio of 16"] OS16 = 3, #[doc = "4: Oversampling ratio of 32"] OS32 = 4, #[doc = "5: Oversampling ratio of 64"] OS64 = 5, #[doc = "6: Oversampling ratio of 128"] OS128 = 6, #[doc = "7: Oversampling ratio of 256"] OS256 = 7, } impl From<OVSR_A> for u8 { #[inline(always)] fn from(variant: OVSR_A) -> Self { variant as _ } } #[doc = "Reader of field `OVSR`"] pub type OVSR_R = crate::R<u8, OVSR_A>; impl OVSR_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OVSR_A { match self.bits { 0 => OVSR_A::OS2, 1 => OVSR_A::OS4, 2 => OVSR_A::OS8, 3 => OVSR_A::OS16, 4 => OVSR_A::OS32, 5 => OVSR_A::OS64, 6 => OVSR_A::OS128, 7 => OVSR_A::OS256, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `OS2`"] #[inline(always)] pub fn is_os2(&self) -> bool { *self == OVSR_A::OS2 } #[doc = "Checks if the value of the field is `OS4`"] #[inline(always)] pub fn is_os4(&self) -> bool { *self == OVSR_A::OS4 } #[doc = "Checks if the value of the field is `OS8`"] #[inline(always)] pub fn is_os8(&self) -> bool { *self == OVSR_A::OS8 } #[doc = "Checks if the value of the field is `OS16`"] #[inline(always)] pub fn is_os16(&self) -> bool { *self == OVSR_A::OS16 } #[doc = "Checks if the value of the field is `OS32`"] #[inline(always)] pub fn is_os32(&self) -> bool { *self == OVSR_A::OS32 } #[doc = "Checks if the value of the field is `OS64`"] #[inline(always)] pub fn is_os64(&self) -> bool { *self == OVSR_A::OS64 } #[doc = "Checks if the value of the field is `OS128`"] #[inline(always)] pub fn is_os128(&self) -> bool { *self == OVSR_A::OS128 } #[doc = "Checks if the value of the field is `OS256`"] #[inline(always)] pub fn is_os256(&self) -> bool { *self == OVSR_A::OS256 } } #[doc = "Write proxy for field `OVSR`"] pub struct OVSR_W<'a> { w: &'a mut W, } impl<'a> OVSR_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: OVSR_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Oversampling ratio of 2"] #[inline(always)] pub fn os2(self) -> &'a mut W { self.variant(OVSR_A::OS2) } #[doc = "Oversampling ratio of 4"] #[inline(always)] pub fn os4(self) -> &'a mut W { self.variant(OVSR_A::OS4) } #[doc = "Oversampling ratio of 8"] #[inline(always)] pub fn os8(self) -> &'a mut W { self.variant(OVSR_A::OS8) } #[doc = "Oversampling ratio of 16"] #[inline(always)] pub fn os16(self) -> &'a mut W { self.variant(OVSR_A::OS16) } #[doc = "Oversampling ratio of 32"] #[inline(always)] pub fn os32(self) -> &'a mut W { self.variant(OVSR_A::OS32) } #[doc = "Oversampling ratio of 64"] #[inline(always)] pub fn os64(self) -> &'a mut W { self.variant(OVSR_A::OS64) } #[doc = "Oversampling ratio of 128"] #[inline(always)] pub fn os128(self) -> &'a mut W { self.variant(OVSR_A::OS128) } #[doc = "Oversampling ratio of 256"] #[inline(always)] pub fn os256(self) -> &'a mut W { self.variant(OVSR_A::OS256) } #[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 & !(0x07 << 2)) | (((value as u32) & 0x07) << 2); self.w } } #[doc = "Injected Oversampling Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum JOVSE_A { #[doc = "0: Injected oversampling disabled"] DISABLED = 0, #[doc = "1: Injected oversampling enabled"] ENABLED = 1, } impl From<JOVSE_A> for bool { #[inline(always)] fn from(variant: JOVSE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `JOVSE`"] pub type JOVSE_R = crate::R<bool, JOVSE_A>; impl JOVSE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> JOVSE_A { match self.bits { false => JOVSE_A::DISABLED, true => JOVSE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == JOVSE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == JOVSE_A::ENABLED } } #[doc = "Write proxy for field `JOVSE`"] pub struct JOVSE_W<'a> { w: &'a mut W, } impl<'a> JOVSE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: JOVSE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Injected oversampling disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(JOVSE_A::DISABLED) } #[doc = "Injected oversampling enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(JOVSE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Regular Oversampling Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ROVSE_A { #[doc = "0: Regular oversampling disabled"] DISABLED = 0, #[doc = "1: Regular oversampling enabled"] ENABLED = 1, } impl From<ROVSE_A> for bool { #[inline(always)] fn from(variant: ROVSE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ROVSE`"] pub type ROVSE_R = crate::R<bool, ROVSE_A>; impl ROVSE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ROVSE_A { match self.bits { false => ROVSE_A::DISABLED, true => ROVSE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == ROVSE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == ROVSE_A::ENABLED } } #[doc = "Write proxy for field `ROVSE`"] pub struct ROVSE_W<'a> { w: &'a mut W, } impl<'a> ROVSE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ROVSE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Regular oversampling disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(ROVSE_A::DISABLED) } #[doc = "Regular oversampling enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(ROVSE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 27 - Sampling time control trigger mode"] #[inline(always)] pub fn smptrig(&self) -> SMPTRIG_R { SMPTRIG_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 26 - Bulb sampling mode"] #[inline(always)] pub fn bulb(&self) -> BULB_R { BULB_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 25 - Software trigger bit for sampling time control trigger mode"] #[inline(always)] pub fn swtrig(&self) -> SWTRIG_R { SWTRIG_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 16 - Gain compensation mode"] #[inline(always)] pub fn gcomp(&self) -> GCOMP_R { GCOMP_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 10 - Regular Oversampling mode"] #[inline(always)] pub fn rovsm(&self) -> ROVSM_R { ROVSM_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 9 - Triggered Regular Oversampling"] #[inline(always)] pub fn trovs(&self) -> TROVS_R { TROVS_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bits 5:8 - Oversampling shift"] #[inline(always)] pub fn ovss(&self) -> OVSS_R { OVSS_R::new(((self.bits >> 5) & 0x0f) as u8) } #[doc = "Bits 2:4 - Oversampling ratio"] #[inline(always)] pub fn ovsr(&self) -> OVSR_R { OVSR_R::new(((self.bits >> 2) & 0x07) as u8) } #[doc = "Bit 1 - Injected Oversampling Enable"] #[inline(always)] pub fn jovse(&self) -> JOVSE_R { JOVSE_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - Regular Oversampling Enable"] #[inline(always)] pub fn rovse(&self) -> ROVSE_R { ROVSE_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 27 - Sampling time control trigger mode"] #[inline(always)] pub fn smptrig(&mut self) -> SMPTRIG_W { SMPTRIG_W { w: self } } #[doc = "Bit 26 - Bulb sampling mode"] #[inline(always)] pub fn bulb(&mut self) -> BULB_W { BULB_W { w: self } } #[doc = "Bit 25 - Software trigger bit for sampling time control trigger mode"] #[inline(always)] pub fn swtrig(&mut self) -> SWTRIG_W { SWTRIG_W { w: self } } #[doc = "Bit 16 - Gain compensation mode"] #[inline(always)] pub fn gcomp(&mut self) -> GCOMP_W { GCOMP_W { w: self } } #[doc = "Bit 10 - Regular Oversampling mode"] #[inline(always)] pub fn rovsm(&mut self) -> ROVSM_W { ROVSM_W { w: self } } #[doc = "Bit 9 - Triggered Regular Oversampling"] #[inline(always)] pub fn trovs(&mut self) -> TROVS_W { TROVS_W { w: self } } #[doc = "Bits 5:8 - Oversampling shift"] #[inline(always)] pub fn ovss(&mut self) -> OVSS_W { OVSS_W { w: self } } #[doc = "Bits 2:4 - Oversampling ratio"] #[inline(always)] pub fn ovsr(&mut self) -> OVSR_W { OVSR_W { w: self } } #[doc = "Bit 1 - Injected Oversampling Enable"] #[inline(always)] pub fn jovse(&mut self) -> JOVSE_W { JOVSE_W { w: self } } #[doc = "Bit 0 - Regular Oversampling Enable"] #[inline(always)] pub fn rovse(&mut self) -> ROVSE_W { ROVSE_W { w: self } } }
#![allow(non_snake_case, non_upper_case_globals, non_camel_case_types, clippy::all)] #[cfg(feature = "Win32")] pub mod Win32;
use nix::fcntl::open; use nix::unistd::{close, read, write}; use nix::fcntl::OFlag; use nix::sys::stat::Mode; fn main() { let mut buf = [0u8; 1024]; let infile = open("file.in", OFlag::O_RDONLY, Mode::S_IRUSR).unwrap(); let outfile = open("file.out", OFlag::O_WRONLY | OFlag::O_CREAT, Mode::S_IRUSR | Mode::S_IWUSR).unwrap(); loop { match read(infile, &mut buf){ Ok(nread) => { if nread > 0 { write(outfile, &buf[..nread]); } else { break; } }, Err(e) => { println!("error {:?}", e) } } } close(infile); }
use std::fs::File; use std::io::prelude::*; use std::collections::HashSet; // --- file read fn read_file(filename: &str) -> std::io::Result<String> { let mut file = File::open(filename)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } // --- model #[derive(Debug, Eq, PartialEq)] struct Group { g_answer: Vec<Vec<char>> } impl Group { fn new(input: Vec<Vec<char>>) -> Group { Group {g_answer: input} } } fn main(){ let input = read_file("./input.txt").unwrap(); let input_array:Vec<Group> = input.split("\n\n") .map(|group_answers| { Group::new(group_answers.lines() .map(|user_answer| user_answer.chars().collect::<Vec<char>>()).collect()) }).collect::<Vec<Group>>(); let mut counter = 0; for group in input_array.iter(){ let mut answer_common_group: Option<HashSet<char>> = None; for user_answer in &group.g_answer{ let mut current_answer: HashSet<char> = HashSet::<char>::new(); for ch in user_answer{ current_answer.insert(*ch); } match answer_common_group{ None => answer_common_group = Some(current_answer.clone()), Some(x)=> answer_common_group = Some(x.intersection(&current_answer).map(|c| *c).collect()), } } counter += answer_common_group.unwrap().len(); } println!("{}", counter); }
use crate::{ engine::{input::InputState, Engine}, game::components::{Input, Pawn}, math::*, particles::Particle, render::components::*, }; use hecs::{With, World}; mod debug; mod movement; mod soldier; pub use debug::*; pub use movement::*; pub use soldier::*; pub fn apply_input(world: &mut World, eng: &Engine) { for (_, mut input) in world.query::<With<Pawn, &mut Input>>().iter() { input.state = eng.input.state; } }
#[doc = "Reader of register FLTINR1"] pub type R = crate::R<u32, super::FLTINR1>; #[doc = "Writer for register FLTINR1"] pub type W = crate::W<u32, super::FLTINR1>; #[doc = "Register FLTINR1 `reset()`'s with value 0"] impl crate::ResetValue for super::FLTINR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `FLT4LCK`"] pub type FLT4LCK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT4LCK`"] pub struct FLT4LCK_W<'a> { w: &'a mut W, } impl<'a> FLT4LCK_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 } } #[doc = "Reader of field `FLT4F`"] pub type FLT4F_R = crate::R<u8, u8>; #[doc = "Write proxy for field `FLT4F`"] pub struct FLT4F_W<'a> { w: &'a mut W, } impl<'a> FLT4F_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 << 27)) | (((value as u32) & 0x0f) << 27); self.w } } #[doc = "Reader of field `FLT4SRC`"] pub type FLT4SRC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT4SRC`"] pub struct FLT4SRC_W<'a> { w: &'a mut W, } impl<'a> FLT4SRC_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 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `FLT4P`"] pub type FLT4P_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT4P`"] pub struct FLT4P_W<'a> { w: &'a mut W, } impl<'a> FLT4P_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 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Reader of field `FLT4E`"] pub type FLT4E_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT4E`"] pub struct FLT4E_W<'a> { w: &'a mut W, } impl<'a> FLT4E_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 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `FLT3LCK`"] pub type FLT3LCK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT3LCK`"] pub struct FLT3LCK_W<'a> { w: &'a mut W, } impl<'a> FLT3LCK_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 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `FLT3F`"] pub type FLT3F_R = crate::R<u8, u8>; #[doc = "Write proxy for field `FLT3F`"] pub struct FLT3F_W<'a> { w: &'a mut W, } impl<'a> FLT3F_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 << 19)) | (((value as u32) & 0x0f) << 19); self.w } } #[doc = "Reader of field `FLT3SRC`"] pub type FLT3SRC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT3SRC`"] pub struct FLT3SRC_W<'a> { w: &'a mut W, } impl<'a> FLT3SRC_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 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `FLT3P`"] pub type FLT3P_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT3P`"] pub struct FLT3P_W<'a> { w: &'a mut W, } impl<'a> FLT3P_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 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `FLT3E`"] pub type FLT3E_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT3E`"] pub struct FLT3E_W<'a> { w: &'a mut W, } impl<'a> FLT3E_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 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `FLT2LCK`"] pub type FLT2LCK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT2LCK`"] pub struct FLT2LCK_W<'a> { w: &'a mut W, } impl<'a> FLT2LCK_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 } } #[doc = "Reader of field `FLT2F`"] pub type FLT2F_R = crate::R<u8, u8>; #[doc = "Write proxy for field `FLT2F`"] pub struct FLT2F_W<'a> { w: &'a mut W, } impl<'a> FLT2F_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 << 11)) | (((value as u32) & 0x0f) << 11); self.w } } #[doc = "Reader of field `FLT2SRC`"] pub type FLT2SRC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT2SRC`"] pub struct FLT2SRC_W<'a> { w: &'a mut W, } impl<'a> FLT2SRC_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 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `FLT2P`"] pub type FLT2P_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT2P`"] pub struct FLT2P_W<'a> { w: &'a mut W, } impl<'a> FLT2P_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 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `FLT2E`"] pub type FLT2E_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT2E`"] pub struct FLT2E_W<'a> { w: &'a mut W, } impl<'a> FLT2E_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 `FLT1LCK`"] pub type FLT1LCK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT1LCK`"] pub struct FLT1LCK_W<'a> { w: &'a mut W, } impl<'a> FLT1LCK_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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `FLT1F`"] pub type FLT1F_R = crate::R<u8, u8>; #[doc = "Write proxy for field `FLT1F`"] pub struct FLT1F_W<'a> { w: &'a mut W, } impl<'a> FLT1F_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 << 3)) | (((value as u32) & 0x0f) << 3); self.w } } #[doc = "Reader of field `FLT1SRC`"] pub type FLT1SRC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT1SRC`"] pub struct FLT1SRC_W<'a> { w: &'a mut W, } impl<'a> FLT1SRC_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 `FLT1P`"] pub type FLT1P_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT1P`"] pub struct FLT1P_W<'a> { w: &'a mut W, } impl<'a> FLT1P_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 `FLT1E`"] pub type FLT1E_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLT1E`"] pub struct FLT1E_W<'a> { w: &'a mut W, } impl<'a> FLT1E_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 } } impl R { #[doc = "Bit 31 - FLT4LCK"] #[inline(always)] pub fn flt4lck(&self) -> FLT4LCK_R { FLT4LCK_R::new(((self.bits >> 31) & 0x01) != 0) } #[doc = "Bits 27:30 - FLT4F"] #[inline(always)] pub fn flt4f(&self) -> FLT4F_R { FLT4F_R::new(((self.bits >> 27) & 0x0f) as u8) } #[doc = "Bit 26 - FLT4SRC"] #[inline(always)] pub fn flt4src(&self) -> FLT4SRC_R { FLT4SRC_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 25 - FLT4P"] #[inline(always)] pub fn flt4p(&self) -> FLT4P_R { FLT4P_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 24 - FLT4E"] #[inline(always)] pub fn flt4e(&self) -> FLT4E_R { FLT4E_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 23 - FLT3LCK"] #[inline(always)] pub fn flt3lck(&self) -> FLT3LCK_R { FLT3LCK_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bits 19:22 - FLT3F"] #[inline(always)] pub fn flt3f(&self) -> FLT3F_R { FLT3F_R::new(((self.bits >> 19) & 0x0f) as u8) } #[doc = "Bit 18 - FLT3SRC"] #[inline(always)] pub fn flt3src(&self) -> FLT3SRC_R { FLT3SRC_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 17 - FLT3P"] #[inline(always)] pub fn flt3p(&self) -> FLT3P_R { FLT3P_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - FLT3E"] #[inline(always)] pub fn flt3e(&self) -> FLT3E_R { FLT3E_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 15 - FLT2LCK"] #[inline(always)] pub fn flt2lck(&self) -> FLT2LCK_R { FLT2LCK_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bits 11:14 - FLT2F"] #[inline(always)] pub fn flt2f(&self) -> FLT2F_R { FLT2F_R::new(((self.bits >> 11) & 0x0f) as u8) } #[doc = "Bit 10 - FLT2SRC"] #[inline(always)] pub fn flt2src(&self) -> FLT2SRC_R { FLT2SRC_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 9 - FLT2P"] #[inline(always)] pub fn flt2p(&self) -> FLT2P_R { FLT2P_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 8 - FLT2E"] #[inline(always)] pub fn flt2e(&self) -> FLT2E_R { FLT2E_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 7 - FLT1LCK"] #[inline(always)] pub fn flt1lck(&self) -> FLT1LCK_R { FLT1LCK_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bits 3:6 - FLT1F"] #[inline(always)] pub fn flt1f(&self) -> FLT1F_R { FLT1F_R::new(((self.bits >> 3) & 0x0f) as u8) } #[doc = "Bit 2 - FLT1SRC"] #[inline(always)] pub fn flt1src(&self) -> FLT1SRC_R { FLT1SRC_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - FLT1P"] #[inline(always)] pub fn flt1p(&self) -> FLT1P_R { FLT1P_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - FLT1E"] #[inline(always)] pub fn flt1e(&self) -> FLT1E_R { FLT1E_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 31 - FLT4LCK"] #[inline(always)] pub fn flt4lck(&mut self) -> FLT4LCK_W { FLT4LCK_W { w: self } } #[doc = "Bits 27:30 - FLT4F"] #[inline(always)] pub fn flt4f(&mut self) -> FLT4F_W { FLT4F_W { w: self } } #[doc = "Bit 26 - FLT4SRC"] #[inline(always)] pub fn flt4src(&mut self) -> FLT4SRC_W { FLT4SRC_W { w: self } } #[doc = "Bit 25 - FLT4P"] #[inline(always)] pub fn flt4p(&mut self) -> FLT4P_W { FLT4P_W { w: self } } #[doc = "Bit 24 - FLT4E"] #[inline(always)] pub fn flt4e(&mut self) -> FLT4E_W { FLT4E_W { w: self } } #[doc = "Bit 23 - FLT3LCK"] #[inline(always)] pub fn flt3lck(&mut self) -> FLT3LCK_W { FLT3LCK_W { w: self } } #[doc = "Bits 19:22 - FLT3F"] #[inline(always)] pub fn flt3f(&mut self) -> FLT3F_W { FLT3F_W { w: self } } #[doc = "Bit 18 - FLT3SRC"] #[inline(always)] pub fn flt3src(&mut self) -> FLT3SRC_W { FLT3SRC_W { w: self } } #[doc = "Bit 17 - FLT3P"] #[inline(always)] pub fn flt3p(&mut self) -> FLT3P_W { FLT3P_W { w: self } } #[doc = "Bit 16 - FLT3E"] #[inline(always)] pub fn flt3e(&mut self) -> FLT3E_W { FLT3E_W { w: self } } #[doc = "Bit 15 - FLT2LCK"] #[inline(always)] pub fn flt2lck(&mut self) -> FLT2LCK_W { FLT2LCK_W { w: self } } #[doc = "Bits 11:14 - FLT2F"] #[inline(always)] pub fn flt2f(&mut self) -> FLT2F_W { FLT2F_W { w: self } } #[doc = "Bit 10 - FLT2SRC"] #[inline(always)] pub fn flt2src(&mut self) -> FLT2SRC_W { FLT2SRC_W { w: self } } #[doc = "Bit 9 - FLT2P"] #[inline(always)] pub fn flt2p(&mut self) -> FLT2P_W { FLT2P_W { w: self } } #[doc = "Bit 8 - FLT2E"] #[inline(always)] pub fn flt2e(&mut self) -> FLT2E_W { FLT2E_W { w: self } } #[doc = "Bit 7 - FLT1LCK"] #[inline(always)] pub fn flt1lck(&mut self) -> FLT1LCK_W { FLT1LCK_W { w: self } } #[doc = "Bits 3:6 - FLT1F"] #[inline(always)] pub fn flt1f(&mut self) -> FLT1F_W { FLT1F_W { w: self } } #[doc = "Bit 2 - FLT1SRC"] #[inline(always)] pub fn flt1src(&mut self) -> FLT1SRC_W { FLT1SRC_W { w: self } } #[doc = "Bit 1 - FLT1P"] #[inline(always)] pub fn flt1p(&mut self) -> FLT1P_W { FLT1P_W { w: self } } #[doc = "Bit 0 - FLT1E"] #[inline(always)] pub fn flt1e(&mut self) -> FLT1E_W { FLT1E_W { w: self } } }
use crate::std::collections::BTreeMap; use serde::{Serialize,Deserialize}; use crate::contracts; use crate::types::TxRef; use crate::TransactionStatus; use crate::contracts::AccountIdWrapper; use crate::std::string::String; use crate::std::vec::Vec; // Logitude And Latitude type LongLati = (f64,f64); #[derive(Serialize, Deserialize, Debug, Default)] pub struct GpsLocation { data: BTreeMap<AccountIdWrapper, LongLati> } #[derive(Serialize, Deserialize, Debug)] pub enum Command { SetLocation { latitude: f64, longitude: f64, } } #[derive(Serialize, Deserialize, Debug)] pub enum Error { InvalidRequest, NotAuthorized, NoData, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum Request { GetLocation{ account: AccountIdWrapper }, } #[derive(Serialize, Deserialize, Debug)] pub enum Response{ Location{ longitude: f64, latitude: f64 }, Error(Error) } impl GpsLocation { pub fn new() -> Self{ Self{ data: BTreeMap::new() } } } impl contracts::Contract<Command, Request, Response> for GpsLocation { fn id(&self) -> contracts::ContractId { contracts::GPS_APP } fn handle_command(&mut self, account: &chain::AccountId, _txref: &TxRef, cmd: Command) -> TransactionStatus { println!("Inside Handle Command"); println!("Contract 6 details {:?} {:?}",account,cmd); match cmd { Command::SetLocation {latitude, longitude} => { let account = AccountIdWrapper(account.clone()); self.data.insert(account, (latitude, longitude)); TransactionStatus::Ok } } } fn handle_query(&mut self,account: Option<&chain::AccountId>, req: Request) -> Response{ println!("Inside Handle Query"); if let Request::GetLocation{account} = req { println!("Contract 6 Handle Query ::: \n {:?} \n {:?} \n {:?}", account.clone().to_string(), self.data.keys().map(|v| v.to_string()).collect::<Vec<String>>(), self.data.values().map(|v| v.0).collect::<Vec<f64>>(), ); let hh = self.data.get(&account); println!("Find it:::{:?}", hh); if let Some(data) = hh { println!("Found the item returning the fucking location"); return Response::Location{ latitude: data.0, longitude: data.1 } } println!("Didnt found the item so throwing error"); return Response::Error(Error::NoData); } Response::Error(Error::InvalidRequest) } }
use super::{AccDomain, AccReport}; use fnv::FnvHashMap as HashMap; use fnv::FnvHashSet as HashSet; use std::net::IpAddr; pub struct DNSAddRecord { pub dns_records: Vec<(String, IpAddr)>, } impl DNSAddRecord { pub fn new() -> DNSAddRecord { DNSAddRecord { dns_records: Vec::with_capacity(4), } } pub fn add(&mut self, ip: IpAddr, name: &String) { self.dns_records.push((name.to_string(), ip)); } } // Acc: access domain record struct AccDomainRecord { src_addrs: HashSet<IpAddr>, } impl AccDomainRecord { pub fn new() -> AccDomainRecord { AccDomainRecord { src_addrs: HashSet::default(), } } pub fn log(&mut self, dst_ip: IpAddr) { self.src_addrs.insert(dst_ip); } } // Acc: access log pub struct AccLog { domains: HashMap<IpAddr, String>, acc_domains: HashMap<String, AccDomainRecord>, } impl AccLog { pub fn new() -> AccLog { AccLog { domains: HashMap::default(), acc_domains: HashMap::default(), } } pub fn log(&mut self, v: Vec<(std::net::IpAddr, std::net::IpAddr)>) { for (src_ip, dst_ip) in v.iter() { let domain; match self.domains.get(&dst_ip) { Some(domain1) => { // use exist domain name domain = domain1.to_string(); } None => { // convert ip to domain name domain = dst_ip.to_string(); } } match self.acc_domains.get_mut(&domain) { Some(acc_domain1) => { acc_domain1.log(*src_ip); } None => { let mut acc_domain1 = AccDomainRecord::new(); acc_domain1.log(*src_ip); self.acc_domains.insert(domain, acc_domain1); } } } } pub fn domain_add(&mut self, domain: DNSAddRecord) { for dd in domain.dns_records.iter() { self.domains.insert(dd.1, dd.0.to_string()); } } pub fn clear_log(&mut self) { self.acc_domains.clear(); } pub fn dump_to_pb(&self) -> AccReport { let mut report = AccReport::default(); for (k, ad) in self.acc_domains.iter() { let mut pad = AccDomain::default(); pad.domain = k.to_string(); for ip in ad.src_addrs.iter() { match ip { IpAddr::V4(v4) => { pad.srcIP.push(u32::from_be_bytes(v4.octets())); } _ => {} } } report.domains.push(pad); } report } pub fn is_empty(&self) -> bool { self.acc_domains.is_empty() } }
use wasmer_runtime_core::Instance; // TODO: Need to implement. /// emscripten: dlopen(filename: *const c_char, flag: c_int) -> *mut c_void pub extern "C" fn _dlopen(filename: u32, flag: c_int) -> u32 { debug!("emscripten::_dlopen"); -1 } /// emscripten: dlclose(handle: *mut c_void) -> c_int pub extern "C" fn _dlclose(filename: u32) -> u32 { debug!("emscripten::_dlclose"); -1 } /// emscripten: dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void pub extern "C" fn _dlsym(filepath: u32, symbol: u32) -> u32 { debug!("emscripten::_dlerror"); -1 } /// emscripten: dlerror() -> *mut c_char pub extern "C" fn _dlerror() -> u32 { debug!("emscripten::_dlerror"); -1 }
use rnix::Error as NixError; use std::{env, fs, io::{self, Write}}; fn main() { let stdout = io::stdout(); let mut stdout = stdout.lock(); let file = match env::args().skip(1).next() { Some(file) => file, None => { eprintln!("Usage: error-report <file>"); return; } }; let content = match fs::read_to_string(&file) { Ok(content) => content, Err(err) => { eprintln!("error reading file: {}", err); return; } }; let errors = match rnix::parse(&content) { Ok(ast) => { ast.errors() .map(|node| { let (span, err) = node.error(); (*span, err.to_string()) }) .collect() }, Err(err) => match err { NixError::TokenizeError(span, err) => vec![(Some(span), err.to_string())], NixError::ParseError(span, err) => vec![(span, err.to_string())], } }; for (i, (span, err)) in errors.iter().enumerate() { if i > 0 { writeln!(stdout).unwrap(); } writeln!(stdout, "error: {}", err).unwrap(); let span = match span { Some(span) => span, None => continue }; let start = span.start as usize; let end = span.end.map(|i| i as usize).unwrap_or(start+1); let prev_line_end = content[..start].rfind('\n'); let prev_line = content[..prev_line_end.unwrap_or(0)].rfind('\n').map(|n| n+1).unwrap_or(0); let next_line = content[end..].find('\n').map(|n| n + 1 + end).unwrap_or(content.len()); let next_line_end = content[next_line..].find('\n').map(|n| n + next_line).unwrap_or(content.len()); let line = content[..start].chars().filter(|c| *c == '\n').count() + 1; let col = start - prev_line_end.map(|n| n+1).unwrap_or(0) + 1; writeln!(stdout, "At {}:{}:{}", file, line, col); writeln!(stdout).unwrap(); let mut pos = prev_line; loop { let line = content[pos..].find('\n').map(|n| n + pos).unwrap_or(content.len() - 1); writeln!(stdout, "{}", &content[pos..line]).unwrap(); if pos >= prev_line_end.map(|n| n + 1).unwrap_or(0) && line < next_line { for i in pos..line { if i >= start && i < end { stdout.write_all(&[b'^']).unwrap(); } else { stdout.write_all(&[b' ']).unwrap(); } } writeln!(stdout).unwrap(); } pos = line+1; if pos >= next_line_end { break; } } } }
extern crate futures; use futures::prelude::*; use futures::stream::iter_ok; struct Join<T, U>(T, U); impl<T: Stream, U> Stream for Join<T, U> { type Item = T::Item; type Error = T::Error; fn poll(&mut self) -> Poll<Option<T::Item>, T::Error> { self.0.poll() } } impl<T, U: Sink> Sink for Join<T, U> { type SinkItem = U::SinkItem; type SinkError = U::SinkError; fn start_send(&mut self, item: U::SinkItem) -> StartSend<U::SinkItem, U::SinkError> { self.1.start_send(item) } fn poll_complete(&mut self) -> Poll<(), U::SinkError> { self.1.poll_complete() } fn close(&mut self) -> Poll<(), U::SinkError> { self.1.close() } } #[test] fn test_split() { let mut dest = Vec::new(); { let j = Join(iter_ok(vec![10, 20, 30]), &mut dest); let (sink, stream) = j.split(); let j = sink.reunite(stream).expect("test_split: reunite error"); let (sink, stream) = j.split(); sink.send_all(stream).wait().unwrap(); } assert_eq!(dest, vec![10, 20, 30]); }
//! Day 17 use std::{ collections::{HashMap, HashSet}, iter::repeat, }; use itertools::Itertools; trait Solution { fn part_1(&self) -> usize; fn part_2(&self) -> usize; } impl Solution for str { fn part_1(&self) -> usize { let mut dimension = parsers::input(3)(self).expect("Failed to parse the input"); for _ in 0..6 { dimension.evolve(); } dimension.active_cubes.len() } fn part_2(&self) -> usize { let mut dimension = parsers::input(4)(self).expect("Failed to parse the input"); for _ in 0..6 { dimension.evolve(); } dimension.active_cubes.len() } } type Coordinate = Vec<i64>; #[derive(Debug, Clone, PartialEq)] pub struct PocketDimension { dimensions: usize, active_cubes: HashSet<Coordinate>, } impl PocketDimension { pub fn evolve(&mut self) { let mut to_deactivate = Vec::new(); let mut to_activate = HashMap::<Coordinate, usize>::new(); for coord in self.active_cubes.iter() { let neighbors = self.neighbors(coord); let n_active = neighbors .iter() .filter(|&n| self.active_cubes.contains(n)) .count(); if n_active != 2 && n_active != 3 { to_deactivate.push(coord.clone()); } for inactive in neighbors { if !self.active_cubes.contains(&inactive) { *to_activate.entry(inactive).or_default() += 1; } } } for coord in to_deactivate { self.active_cubes.remove(&coord); } for (coord, n_active) in to_activate { if n_active == 3 { self.active_cubes.insert(coord); } } } fn neighbors(&self, coord: &Coordinate) -> Vec<Coordinate> { repeat(&[-1, 0, 1]) .take(self.dimensions) .multi_cartesian_product() .map(|off| coord.iter().zip(off).map(|(c, o)| c + o).collect_vec()) .filter(|c| c != coord) .collect() } } mod parsers { use nom::error::Error; use crate::parsers::{bw_image, finished_parser}; use super::PocketDimension; pub fn input(dimensions: usize) -> impl FnMut(&str) -> Result<PocketDimension, Error<&str>> { move |s| { finished_parser(bw_image)(s).map(|cubes| PocketDimension { dimensions, active_cubes: cubes .into_iter() .enumerate() .flat_map(|(x, row)| { row.into_iter().enumerate().filter_map(move |(y, active)| { if active { let mut coord = vec![0; dimensions]; coord[0] = x as i64; coord[1] = y as i64; Some(coord) } else { None } }) }) .collect(), }) } } } #[cfg(test)] mod tests { use super::*; #[test] fn example_input() { assert_eq!( parsers::input(3)( "\ .#. ..# ###" ), Ok(PocketDimension { dimensions: 3, active_cubes: [ vec![0, 1, 0], vec![1, 2, 0], vec![2, 0, 0], vec![2, 1, 0], vec![2, 2, 0] ] .iter() .cloned() .collect() }) ); } #[test] fn example_1() { let mut dimension = parsers::input(3)( "\ .#. ..# ###", ) .unwrap(); for _ in 0..6 { dimension.evolve(); } assert_eq!(dimension.active_cubes.len(), 112); } #[test] fn part_1() { assert_eq!(include_str!("inputs/day_17").part_1(), 301); } #[test] fn example_2() { let mut dimension = parsers::input(4)( "\ .#. ..# ###", ) .unwrap(); for _ in 0..6 { dimension.evolve(); } assert_eq!(dimension.active_cubes.len(), 848); } #[test] fn part_2() { assert_eq!(include_str!("inputs/day_17").part_2(), 2424); } }
use async_std::io::{Cursor, Read, Seek, Write}; use stackpin::FromUnpinned; use crate::PinCursor; unsafe impl<T> FromUnpinned<Cursor<T>> for PinCursor<T> where T: Unpin, Cursor<T>: Write + Read + Seek { type PinData = (); unsafe fn from_unpinned(src: Cursor<T>) -> (Self, Self::PinData) { (PinCursor::wrap(src), ()) } unsafe fn on_pin(&mut self, _pin_data: Self::PinData) { // do nothing } }
use actix_web::{web, HttpResponse}; pub fn config(cfg: &mut web::ServiceConfig) { cfg.service(web::resource("/").route(web::get().to(index))) .service(web::resource("/favicon.ico").route(web::get().to(favicon_ico))) .service(web::resource("/layout.css").route(web::get().to(layout_css))) .service(web::resource("/marked.min.js").route(web::get().to(marked_min_js))) .service(web::resource("/index.js").route(web::get().to(index_js))) .service(web::resource("/tweet/").route(web::get().to(index))) .service(web::resource("/blog/").route(web::get().to(index))) .service(web::resource("/blog/{id}").route(web::get().to(index))) .service(web::resource("/login").route(web::get().to(index))) .service(web::resource("/logout").route(web::get().to(index))) .service(web::resource("/admin/").route(web::get().to(index))) .service(web::resource("/admin/tweet/").route(web::get().to(index))) .service(web::resource("/admin/blog/").route(web::get().to(index))) .service(web::resource("/admin/blog/{id}").route(web::get().to(index))); } async fn favicon_ico() -> HttpResponse { HttpResponse::Ok() .content_type("image/vnd.microsoft.icon") .body(include_bytes!("static/favicon.ico").as_ref()) } async fn index() -> HttpResponse { HttpResponse::Ok() .content_type("text/html") .body(include_str!("static/index.html")) } async fn layout_css() -> HttpResponse { HttpResponse::Ok() .content_type("text/css") .body(include_str!("static/layout.css")) } async fn marked_min_js() -> HttpResponse { HttpResponse::Ok() .content_type("application/javascript") .body(include_str!("static/marked.min.js")) } async fn index_js() -> HttpResponse { HttpResponse::Ok() .content_type("application/javascript") .body(include_str!("static/index.js")) }
//! Main module of way-cooler ipc. use std::sync::Mutex; use std::sync::mpsc::{self, Sender}; use std::thread; use dbus::tree::{Factory, ObjectPath, Tree, MTFn, MethodErr}; mod utils; mod keybindings; mod dbus_message; pub use self::dbus_message::DBusMessage; mod session; pub use self::session::DBusSession; mod interfaces; pub use self::interfaces::screen; pub use self::interfaces::layout; pub const VERSION: u32 = 1; type DBusResult<T> = Result<T, MethodErr>; type DBusObjPath = ObjectPath<MTFn<()>, ()>; type DBusFactory = Factory<MTFn<()>>; type DBusTree = Tree<MTFn<()>, ()>; lazy_static! { static ref SENDER: Mutex<Option<Sender<DBusMessage>>> = Mutex::new(None); } pub fn init() { let (send, recv) = mpsc::channel(); let _join = thread::spawn( move || { let mut session = DBusSession::create(recv); *SENDER.lock().expect("Unable to unlock") = Some(send); session.run_thread(); }); }
use anyhow::{Context, Result}; pub fn find_matches(content: &str, pattern: &str, mut writer: impl std::io::Write) -> Result<()> { for line in content.lines() { if line.contains(pattern) { writeln!(writer, "{}", line).with_context(|| "error writing mathces")?; // return Err(anyhow::Error::msg("error writing mathces")); } } Ok(()) }
#![feature(dynamic_lib)] #![allow(deprecated)] extern crate bootstrap_rs as bootstrap; extern crate winapi; extern crate kernel32; use std::dynamic_lib::DynamicLibrary; use std::path::Path; use std::mem; use std::thread; use std::fs; use std::rc::Rc; use std::cell::RefCell; use bootstrap::time::Timer; use bootstrap::window::Window; use bootstrap::windows::file::file_modified; const TARGET_FRAME_TIME_MS: f32 = 1.0 / 60.0 * 1000.0; type EngineInit = fn (Rc<RefCell<Window>>) -> Box<()>; type EngineReload = fn (&()) -> Box<()>; type EngineUpdateAndRender = fn (&mut ()); type EngineClose = fn (&()) -> bool; type EngineDrop = fn(Box<()>); type GameInit = fn(&mut ()); type GameReload = fn(&(), &()); fn update_dll(src_lib: &str, dest: &str, last_modified: &mut u64) -> bool { let modified = match file_modified(src_lib) { Ok(modified) => modified, Err(_) => return false, }; if modified > *last_modified { println!("copy result: {:?}", fs::copy(src_lib, dest)); *last_modified = modified; true } else { false } } fn load_engine_procs(lib: &DynamicLibrary) -> (EngineUpdateAndRender, EngineClose, EngineDrop) { let engine_update_and_render = unsafe { let symbol = lib.symbol("engine_update_and_render").unwrap(); mem::transmute::<*mut u8, EngineUpdateAndRender>(symbol) }; let engine_close = unsafe { let symbol = lib.symbol("engine_close").unwrap(); mem::transmute::<*mut u8, EngineClose>(symbol) }; let engine_drop = unsafe { let symbol = lib.symbol("engine_drop").unwrap(); mem::transmute::<*mut u8, EngineDrop>(symbol) }; (engine_update_and_render, engine_close, engine_drop) } /// # TODO /// /// - Keep track of the temp files made and then delete them when done running. /// - Support reloading game code. /// - Reload the windows message proc when the engine is reloaded. pub fn run_loader(src_lib: &str) { let mut counter = 0..; // Statically create a window and load the renderer for the engine. let instance = bootstrap::init(); let window = Window::new("Gunship Game", instance); let mut temp_paths: Vec<String> = Vec::new(); // Open the game as a dynamic library. let mut last_modified = 0; let (mut _lib, mut engine, mut engine_update_and_render, mut engine_close, mut engine_drop) = { let lib_path = format!("gunship_lib_{}.dll", counter.next().unwrap().to_string()); if !update_dll(src_lib, &lib_path, &mut last_modified) { panic!("Unable to find library {} for dynamic loading", src_lib); } let lib = match DynamicLibrary::open(Some(Path::new(&lib_path))) { Ok(lib) => lib, Err(error) => panic!("Unable to open DLL {} with error: {}", lib_path, error), }; temp_paths.push(lib_path); let engine_init = unsafe { let symbol = lib.symbol("engine_init").unwrap(); mem::transmute::<*mut u8, EngineInit>(symbol) }; let game_init = unsafe { let symbol = lib.symbol("game_init").unwrap(); mem::transmute::<*mut u8, GameInit>(symbol) }; let (engine_update_and_render, engine_close, engine_drop) = load_engine_procs(&lib); let mut engine = engine_init(window.clone()); game_init(&mut engine); (lib, engine, engine_update_and_render, engine_close, engine_drop) }; let timer = Timer::new(); loop { let start_time = timer.now(); // Only reload if file has changed. let lib_path = format!("gunship_lib_{}.dll", counter.next().unwrap()); if update_dll(src_lib, &lib_path, &mut last_modified) { if let Ok(lib) = DynamicLibrary::open(Some(Path::new(&lib_path))) { let engine_reload = unsafe { let symbol = lib.symbol("engine_reload").unwrap(); mem::transmute::<*mut u8, EngineReload>(symbol) }; let game_reload = unsafe { let symbol = lib.symbol("game_reload").unwrap(); mem::transmute::<*mut u8, GameReload>(symbol) }; let mut new_engine = engine_reload(&engine); game_reload(&engine, &mut new_engine); engine_drop(engine); engine = new_engine; // Load procs from the new lib. let procs = load_engine_procs(&lib); engine_update_and_render = procs.0; engine_close = procs.1; engine_drop = procs.2; // Drop the old dll and stash the new one to keep it loaded. _lib = lib; } } engine_update_and_render(&mut engine); if engine_close(&engine) { break; } // Wait for target frame time. let mut remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); while remaining_time_ms > 1.0 { thread::sleep_ms(remaining_time_ms as u32); remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); } while remaining_time_ms > 0.0 { remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); } } }
use std::fmt::{self, Display}; use std::ops::{Deref, DerefMut}; use std::str::FromStr; /// A wrapper for anything that implements FromStr to make it serde::Deserialize. Will turn /// Display to serde::Serialize. Probably should be used with Cid, PeerId and such. /// /// Monkeyd from: https://github.com/serde-rs/serde/issues/1316 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct StringSerialized<T>(pub T); impl<T> StringSerialized<T> { pub fn into_inner(self) -> T { self.0 } } impl<T> AsRef<T> for StringSerialized<T> { fn as_ref(&self) -> &T { &self.0 } } impl<T> From<T> for StringSerialized<T> { fn from(t: T) -> Self { StringSerialized(t) } } impl<T> Deref for StringSerialized<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } impl<T> DerefMut for StringSerialized<T> { fn deref_mut(&mut self) -> &mut T { &mut self.0 } } impl<T: fmt::Debug> fmt::Debug for StringSerialized<T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(fmt) } } impl<T: fmt::Display> fmt::Display for StringSerialized<T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(fmt) } } impl<T: Display> serde::Serialize for StringSerialized<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.collect_str(self) } } impl<'de, T: FromStr> serde::Deserialize<'de> for StringSerialized<T> where <T as FromStr>::Err: Display, T: Sized, { fn deserialize<D>(deserializer: D) -> Result<StringSerialized<T>, D::Error> where D: serde::Deserializer<'de>, { String::deserialize(deserializer)? .parse() .map(StringSerialized) .map_err(serde::de::Error::custom) } }
/// Syscall errors #[derive(Eq, PartialEq, Debug, Clone, Copy)] pub enum SysError { /// Index out of bound IndexOutOfBound, /// Field is missing for the target ItemMissing, /// Buffer length is not enough, error contains actual data length LengthNotEnough(usize), /// Data encoding error Encoding, /// Unknown syscall error number Unknown(u64), } impl SysError { pub(crate) fn build_syscall_result( errno: u64, load_len: usize, actual_data_len: usize, ) -> Result<usize, SysError> { use SysError::*; match errno { 0 => { if actual_data_len > load_len { return Err(LengthNotEnough(actual_data_len)); } return Ok(actual_data_len); } 1 => Err(IndexOutOfBound), 2 => Err(ItemMissing), _ => Err(Unknown(errno)), } } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type DialApp = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct DialAppLaunchResult(pub i32); impl DialAppLaunchResult { pub const Launched: Self = Self(0i32); pub const FailedToLaunch: Self = Self(1i32); pub const NotFound: Self = Self(2i32); pub const NetworkFailure: Self = Self(3i32); } impl ::core::marker::Copy for DialAppLaunchResult {} impl ::core::clone::Clone for DialAppLaunchResult { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct DialAppState(pub i32); impl DialAppState { pub const Unknown: Self = Self(0i32); pub const Stopped: Self = Self(1i32); pub const Running: Self = Self(2i32); pub const NetworkFailure: Self = Self(3i32); } impl ::core::marker::Copy for DialAppState {} impl ::core::clone::Clone for DialAppState { fn clone(&self) -> Self { *self } } pub type DialAppStateDetails = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct DialAppStopResult(pub i32); impl DialAppStopResult { pub const Stopped: Self = Self(0i32); pub const StopFailed: Self = Self(1i32); pub const OperationNotSupported: Self = Self(2i32); pub const NetworkFailure: Self = Self(3i32); } impl ::core::marker::Copy for DialAppStopResult {} impl ::core::clone::Clone for DialAppStopResult { fn clone(&self) -> Self { *self } } pub type DialDevice = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct DialDeviceDisplayStatus(pub i32); impl DialDeviceDisplayStatus { pub const None: Self = Self(0i32); pub const Connecting: Self = Self(1i32); pub const Connected: Self = Self(2i32); pub const Disconnecting: Self = Self(3i32); pub const Disconnected: Self = Self(4i32); pub const Error: Self = Self(5i32); } impl ::core::marker::Copy for DialDeviceDisplayStatus {} impl ::core::clone::Clone for DialDeviceDisplayStatus { fn clone(&self) -> Self { *self } } pub type DialDevicePicker = *mut ::core::ffi::c_void; pub type DialDevicePickerFilter = *mut ::core::ffi::c_void; pub type DialDeviceSelectedEventArgs = *mut ::core::ffi::c_void; pub type DialDisconnectButtonClickedEventArgs = *mut ::core::ffi::c_void; pub type DialReceiverApp = *mut ::core::ffi::c_void;
pub use vek; pub mod raw_volume; pub mod raw_volume_sampler; pub mod region; pub mod sampler; pub mod volume; pub mod voxel; pub mod cubic_surface_extractor; pub mod mesh; pub mod vertex;
// Copyright © 2016-2017 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use std::collections::{HashMap, HashSet}; use std::iter::FromIterator; use vr::VersionedReplicas; use rabble::{Pid, NodeId}; use namespace_msg::NamespaceId; #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct Namespaces { pub map: HashMap<NamespaceId, (VersionedReplicas, VersionedReplicas)>, pub primaries: HashMap<NamespaceId, Pid> } impl Namespaces { pub fn new() -> Namespaces { Namespaces { map: HashMap::new(), primaries: HashMap::new() } } /// Return the nodes used in all namespaces /// Note that this can be expensive with a large number of namespaces. /// However, It's only used during an actual reconfiguration. pub fn nodes(&self) -> HashSet<NodeId> { self.map.iter().flat_map(|(_, &(ref old_config, ref new_config))| { old_config.replicas.iter().chain(new_config.replicas.iter()).map(|r| { r.node.clone() }) }).collect() } pub fn insert(&mut self, namespace: NamespaceId, old: VersionedReplicas, new: VersionedReplicas) { self.map.insert(namespace, (old, new)); } pub fn exists(&self, namespace: &NamespaceId) -> bool { self.map.contains_key(namespace) } pub fn get_config(&self, namespace: &NamespaceId) -> Option<(VersionedReplicas, VersionedReplicas)> { match self.map.get(namespace) { Some(&(ref old_config, ref new_config)) => Some((old_config.clone(), new_config.clone())), None => None } } /// Save the new namespace configuration and return whether there actually was a configuration /// change as well as the new replicas that need starting. pub fn reconfigure(&mut self, namespace: &NamespaceId, old: VersionedReplicas, new: VersionedReplicas) -> (bool, Vec<Pid>) { if let Some(&mut(ref mut saved_old_config, ref mut saved_new_config)) = self.map.get_mut(namespace) { // This is an old reconfig message, nothing to start if new.epoch <= saved_new_config.epoch { return (false, Vec::new()) } let new_set = HashSet::<Pid>::from_iter(new.replicas.clone()); // We want to use the actual running nodes here because we are trying to determine which // nodes to start locally let old_set = HashSet::<Pid>::from_iter(saved_new_config.replicas.clone()); let to_start: Vec<Pid> = new_set.difference(&old_set).cloned().collect(); *saved_old_config = old; *saved_new_config = new; (true, to_start) } else { (false, Vec::new()) } } } impl Default for Namespaces { fn default() -> Self { Namespaces::new() } }
#[doc = "Reader of register ITLINE20"] pub type R = crate::R<u32, super::ITLINE20>; #[doc = "Reader of field `TIM15`"] pub type TIM15_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - TIM15"] #[inline(always)] pub fn tim15(&self) -> TIM15_R { TIM15_R::new((self.bits & 0x01) != 0) } }
use super::helpers::{ reverse_multiply_assign, reverse_multiply_c_long, reverse_multiply_c_long_assign, }; use crate::integer::Integer; use core::ops::Mul; // Mul The multiplication operator *. // ['Integer', 'Integer', 'Integer', 'Integer::multiply_assign', 'lhs', // ['ref_mut'], ['ref']] impl Mul<Integer> for Integer { type Output = Integer; fn mul(mut self, rhs: Integer) -> Self::Output { Integer::multiply_assign(&mut self, &rhs); self } } // ['Integer', '&Integer', 'Integer', 'Integer::multiply_assign', 'lhs', // ['ref_mut'], []] impl Mul<&Integer> for Integer { type Output = Integer; fn mul(mut self, rhs: &Integer) -> Self::Output { Integer::multiply_assign(&mut self, rhs); self } } // ['&Integer', 'Integer', 'Integer', 'reverse_multiply_assign', 'rhs', [], // ['ref_mut']] impl Mul<Integer> for &Integer { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_assign(self, &mut rhs); rhs } } // ['&Integer', '&Integer', 'Integer', 'Integer::multiply', 'no', [], []] impl Mul<&Integer> for &Integer { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { Integer::multiply(self, rhs) } } // ['Integer', 'i8', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], []] impl Mul<i8> for Integer { type Output = Integer; fn mul(mut self, rhs: i8) -> Self::Output { Integer::multiply_c_long_assign(&mut self, rhs); self } } // ['Integer', '&i8', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] impl Mul<&i8> for Integer { type Output = Integer; fn mul(mut self, rhs: &i8) -> Self::Output { Integer::multiply_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'i8', 'Integer', 'Integer::multiply_c_long', 'no', [], []] impl Mul<i8> for &Integer { type Output = Integer; fn mul(self, rhs: i8) -> Self::Output { Integer::multiply_c_long(self, rhs) } } // ['&Integer', '&i8', 'Integer', 'Integer::multiply_c_long', 'no', [], // ['deref']] impl Mul<&i8> for &Integer { type Output = Integer; fn mul(self, rhs: &i8) -> Self::Output { Integer::multiply_c_long(self, *rhs) } } // ['i8', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', [], // ['ref_mut']] impl Mul<Integer> for i8 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(self, &mut rhs); rhs } } // ['i8', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', [], []] impl Mul<&Integer> for i8 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(self, rhs) } } // ['&i8', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', // ['deref'], ['ref_mut']] impl Mul<Integer> for &i8 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(*self, &mut rhs); rhs } } // ['&i8', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', ['deref'], // []] impl Mul<&Integer> for &i8 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(*self, rhs) } } // ['Integer', 'u8', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], []] impl Mul<u8> for Integer { type Output = Integer; fn mul(mut self, rhs: u8) -> Self::Output { Integer::multiply_c_long_assign(&mut self, rhs); self } } // ['Integer', '&u8', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] impl Mul<&u8> for Integer { type Output = Integer; fn mul(mut self, rhs: &u8) -> Self::Output { Integer::multiply_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'u8', 'Integer', 'Integer::multiply_c_long', 'no', [], []] impl Mul<u8> for &Integer { type Output = Integer; fn mul(self, rhs: u8) -> Self::Output { Integer::multiply_c_long(self, rhs) } } // ['&Integer', '&u8', 'Integer', 'Integer::multiply_c_long', 'no', [], // ['deref']] impl Mul<&u8> for &Integer { type Output = Integer; fn mul(self, rhs: &u8) -> Self::Output { Integer::multiply_c_long(self, *rhs) } } // ['u8', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', [], // ['ref_mut']] impl Mul<Integer> for u8 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(self, &mut rhs); rhs } } // ['u8', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', [], []] impl Mul<&Integer> for u8 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(self, rhs) } } // ['&u8', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', // ['deref'], ['ref_mut']] impl Mul<Integer> for &u8 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(*self, &mut rhs); rhs } } // ['&u8', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', ['deref'], // []] impl Mul<&Integer> for &u8 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(*self, rhs) } } // ['Integer', 'i16', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], []] impl Mul<i16> for Integer { type Output = Integer; fn mul(mut self, rhs: i16) -> Self::Output { Integer::multiply_c_long_assign(&mut self, rhs); self } } // ['Integer', '&i16', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] impl Mul<&i16> for Integer { type Output = Integer; fn mul(mut self, rhs: &i16) -> Self::Output { Integer::multiply_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'i16', 'Integer', 'Integer::multiply_c_long', 'no', [], []] impl Mul<i16> for &Integer { type Output = Integer; fn mul(self, rhs: i16) -> Self::Output { Integer::multiply_c_long(self, rhs) } } // ['&Integer', '&i16', 'Integer', 'Integer::multiply_c_long', 'no', [], // ['deref']] impl Mul<&i16> for &Integer { type Output = Integer; fn mul(self, rhs: &i16) -> Self::Output { Integer::multiply_c_long(self, *rhs) } } // ['i16', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', [], // ['ref_mut']] impl Mul<Integer> for i16 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(self, &mut rhs); rhs } } // ['i16', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', [], []] impl Mul<&Integer> for i16 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(self, rhs) } } // ['&i16', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', // ['deref'], ['ref_mut']] impl Mul<Integer> for &i16 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(*self, &mut rhs); rhs } } // ['&i16', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', ['deref'], // []] impl Mul<&Integer> for &i16 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(*self, rhs) } } // ['Integer', 'u16', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], []] impl Mul<u16> for Integer { type Output = Integer; fn mul(mut self, rhs: u16) -> Self::Output { Integer::multiply_c_long_assign(&mut self, rhs); self } } // ['Integer', '&u16', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] impl Mul<&u16> for Integer { type Output = Integer; fn mul(mut self, rhs: &u16) -> Self::Output { Integer::multiply_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'u16', 'Integer', 'Integer::multiply_c_long', 'no', [], []] impl Mul<u16> for &Integer { type Output = Integer; fn mul(self, rhs: u16) -> Self::Output { Integer::multiply_c_long(self, rhs) } } // ['&Integer', '&u16', 'Integer', 'Integer::multiply_c_long', 'no', [], // ['deref']] impl Mul<&u16> for &Integer { type Output = Integer; fn mul(self, rhs: &u16) -> Self::Output { Integer::multiply_c_long(self, *rhs) } } // ['u16', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', [], // ['ref_mut']] impl Mul<Integer> for u16 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(self, &mut rhs); rhs } } // ['u16', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', [], []] impl Mul<&Integer> for u16 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(self, rhs) } } // ['&u16', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', // ['deref'], ['ref_mut']] impl Mul<Integer> for &u16 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(*self, &mut rhs); rhs } } // ['&u16', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', ['deref'], // []] impl Mul<&Integer> for &u16 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(*self, rhs) } } // ['Integer', 'i32', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], []] impl Mul<i32> for Integer { type Output = Integer; fn mul(mut self, rhs: i32) -> Self::Output { Integer::multiply_c_long_assign(&mut self, rhs); self } } // ['Integer', '&i32', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] impl Mul<&i32> for Integer { type Output = Integer; fn mul(mut self, rhs: &i32) -> Self::Output { Integer::multiply_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'i32', 'Integer', 'Integer::multiply_c_long', 'no', [], []] impl Mul<i32> for &Integer { type Output = Integer; fn mul(self, rhs: i32) -> Self::Output { Integer::multiply_c_long(self, rhs) } } // ['&Integer', '&i32', 'Integer', 'Integer::multiply_c_long', 'no', [], // ['deref']] impl Mul<&i32> for &Integer { type Output = Integer; fn mul(self, rhs: &i32) -> Self::Output { Integer::multiply_c_long(self, *rhs) } } // ['i32', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', [], // ['ref_mut']] impl Mul<Integer> for i32 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(self, &mut rhs); rhs } } // ['i32', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', [], []] impl Mul<&Integer> for i32 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(self, rhs) } } // ['&i32', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', // ['deref'], ['ref_mut']] impl Mul<Integer> for &i32 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(*self, &mut rhs); rhs } } // ['&i32', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', ['deref'], // []] impl Mul<&Integer> for &i32 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(*self, rhs) } } // ['Integer', 'u32', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<u32> for Integer { type Output = Integer; fn mul(mut self, rhs: u32) -> Self::Output { Integer::multiply_c_long_assign(&mut self, rhs); self } } // ['Integer', '&u32', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<&u32> for Integer { type Output = Integer; fn mul(mut self, rhs: &u32) -> Self::Output { Integer::multiply_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'u32', 'Integer', 'Integer::multiply_c_long', 'no', [], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<u32> for &Integer { type Output = Integer; fn mul(self, rhs: u32) -> Self::Output { Integer::multiply_c_long(self, rhs) } } // ['&Integer', '&u32', 'Integer', 'Integer::multiply_c_long', 'no', [], // ['deref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<&u32> for &Integer { type Output = Integer; fn mul(self, rhs: &u32) -> Self::Output { Integer::multiply_c_long(self, *rhs) } } // ['u32', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', [], // ['ref_mut']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<Integer> for u32 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(self, &mut rhs); rhs } } // ['u32', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', [], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<&Integer> for u32 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(self, rhs) } } // ['&u32', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', // ['deref'], ['ref_mut']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<Integer> for &u32 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(*self, &mut rhs); rhs } } // ['&u32', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', ['deref'], // []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<&Integer> for &u32 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(*self, rhs) } } // ['Integer', 'i64', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<i64> for Integer { type Output = Integer; fn mul(mut self, rhs: i64) -> Self::Output { Integer::multiply_c_long_assign(&mut self, rhs); self } } // ['Integer', '&i64', 'Integer', 'Integer::multiply_c_long_assign', 'lhs', // ['ref_mut'], ['deref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<&i64> for Integer { type Output = Integer; fn mul(mut self, rhs: &i64) -> Self::Output { Integer::multiply_c_long_assign(&mut self, *rhs); self } } // ['&Integer', 'i64', 'Integer', 'Integer::multiply_c_long', 'no', [], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<i64> for &Integer { type Output = Integer; fn mul(self, rhs: i64) -> Self::Output { Integer::multiply_c_long(self, rhs) } } // ['&Integer', '&i64', 'Integer', 'Integer::multiply_c_long', 'no', [], // ['deref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<&i64> for &Integer { type Output = Integer; fn mul(self, rhs: &i64) -> Self::Output { Integer::multiply_c_long(self, *rhs) } } // ['i64', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', [], // ['ref_mut']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<Integer> for i64 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(self, &mut rhs); rhs } } // ['i64', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', [], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<&Integer> for i64 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(self, rhs) } } // ['&i64', 'Integer', 'Integer', 'reverse_multiply_c_long_assign', 'rhs', // ['deref'], ['ref_mut']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<Integer> for &i64 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_c_long_assign(*self, &mut rhs); rhs } } // ['&i64', '&Integer', 'Integer', 'reverse_multiply_c_long', 'no', ['deref'], // []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl Mul<&Integer> for &i64 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { reverse_multiply_c_long(*self, rhs) } } // ['Integer', 'u32', 'Integer', 'Integer::multiply_assign', 'lhs', ['ref_mut'], // ['ref', {'convert': 'Integer'}]] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<u32> for Integer { type Output = Integer; fn mul(mut self, rhs: u32) -> Self::Output { Integer::multiply_assign(&mut self, &Integer::from(rhs)); self } } // ['Integer', '&u32', 'Integer', 'Integer::multiply_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<&u32> for Integer { type Output = Integer; fn mul(mut self, rhs: &u32) -> Self::Output { Integer::multiply_assign(&mut self, &Integer::from(*rhs)); self } } // ['&Integer', 'u32', 'Integer', 'let mut rhs = // Integer::from(rhs);\nreverse_multiply_assign(self, &mut rhs);\nrhs'] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<u32> for &Integer { type Output = Integer; fn mul(self, rhs: u32) -> Self::Output { let mut rhs = Integer::from(rhs); reverse_multiply_assign(self, &mut rhs); rhs } } // ['&Integer', '&u32', 'Integer', 'let mut rhs = // Integer::from(*rhs);\nreverse_multiply_assign(self, &mut rhs);\nrhs'] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<&u32> for &Integer { type Output = Integer; fn mul(self, rhs: &u32) -> Self::Output { let mut rhs = Integer::from(*rhs); reverse_multiply_assign(self, &mut rhs); rhs } } // ['u32', 'Integer', 'Integer', 'reverse_multiply_assign', 'rhs', ['ref', // {'convert': 'Integer'}], ['ref_mut']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<Integer> for u32 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_assign(&Integer::from(self), &mut rhs); rhs } } // ['u32', '&Integer', 'Integer', 'let mut lhs = // Integer::from(self);\nInteger::multiply_assign(&mut lhs, rhs);\nlhs'] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<&Integer> for u32 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { let mut lhs = Integer::from(self); Integer::multiply_assign(&mut lhs, rhs); lhs } } // ['&u32', 'Integer', 'Integer', 'reverse_multiply_assign', 'rhs', ['ref', // {'convert': 'Integer'}, 'deref'], ['ref_mut']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<Integer> for &u32 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_assign(&Integer::from(*self), &mut rhs); rhs } } // ['&u32', '&Integer', 'Integer', 'let mut lhs = // Integer::from(*self);\nInteger::multiply_assign(&mut lhs, rhs);\nlhs'] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<&Integer> for &u32 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { let mut lhs = Integer::from(*self); Integer::multiply_assign(&mut lhs, rhs); lhs } } // ['Integer', 'i64', 'Integer', 'Integer::multiply_assign', 'lhs', ['ref_mut'], // ['ref', {'convert': 'Integer'}]] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<i64> for Integer { type Output = Integer; fn mul(mut self, rhs: i64) -> Self::Output { Integer::multiply_assign(&mut self, &Integer::from(rhs)); self } } // ['Integer', '&i64', 'Integer', 'Integer::multiply_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<&i64> for Integer { type Output = Integer; fn mul(mut self, rhs: &i64) -> Self::Output { Integer::multiply_assign(&mut self, &Integer::from(*rhs)); self } } // ['&Integer', 'i64', 'Integer', 'let mut rhs = // Integer::from(rhs);\nreverse_multiply_assign(self, &mut rhs);\nrhs'] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<i64> for &Integer { type Output = Integer; fn mul(self, rhs: i64) -> Self::Output { let mut rhs = Integer::from(rhs); reverse_multiply_assign(self, &mut rhs); rhs } } // ['&Integer', '&i64', 'Integer', 'let mut rhs = // Integer::from(*rhs);\nreverse_multiply_assign(self, &mut rhs);\nrhs'] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<&i64> for &Integer { type Output = Integer; fn mul(self, rhs: &i64) -> Self::Output { let mut rhs = Integer::from(*rhs); reverse_multiply_assign(self, &mut rhs); rhs } } // ['i64', 'Integer', 'Integer', 'reverse_multiply_assign', 'rhs', ['ref', // {'convert': 'Integer'}], ['ref_mut']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<Integer> for i64 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_assign(&Integer::from(self), &mut rhs); rhs } } // ['i64', '&Integer', 'Integer', 'let mut lhs = // Integer::from(self);\nInteger::multiply_assign(&mut lhs, rhs);\nlhs'] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<&Integer> for i64 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { let mut lhs = Integer::from(self); Integer::multiply_assign(&mut lhs, rhs); lhs } } // ['&i64', 'Integer', 'Integer', 'reverse_multiply_assign', 'rhs', ['ref', // {'convert': 'Integer'}, 'deref'], ['ref_mut']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<Integer> for &i64 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_assign(&Integer::from(*self), &mut rhs); rhs } } // ['&i64', '&Integer', 'Integer', 'let mut lhs = // Integer::from(*self);\nInteger::multiply_assign(&mut lhs, rhs);\nlhs'] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl Mul<&Integer> for &i64 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { let mut lhs = Integer::from(*self); Integer::multiply_assign(&mut lhs, rhs); lhs } } // ['Integer', 'u64', 'Integer', 'Integer::multiply_assign', 'lhs', ['ref_mut'], // ['ref', {'convert': 'Integer'}]] impl Mul<u64> for Integer { type Output = Integer; fn mul(mut self, rhs: u64) -> Self::Output { Integer::multiply_assign(&mut self, &Integer::from(rhs)); self } } // ['Integer', '&u64', 'Integer', 'Integer::multiply_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Mul<&u64> for Integer { type Output = Integer; fn mul(mut self, rhs: &u64) -> Self::Output { Integer::multiply_assign(&mut self, &Integer::from(*rhs)); self } } // ['&Integer', 'u64', 'Integer', 'let mut rhs = // Integer::from(rhs);\nreverse_multiply_assign(self, &mut rhs);\nrhs'] impl Mul<u64> for &Integer { type Output = Integer; fn mul(self, rhs: u64) -> Self::Output { let mut rhs = Integer::from(rhs); reverse_multiply_assign(self, &mut rhs); rhs } } // ['&Integer', '&u64', 'Integer', 'let mut rhs = // Integer::from(*rhs);\nreverse_multiply_assign(self, &mut rhs);\nrhs'] impl Mul<&u64> for &Integer { type Output = Integer; fn mul(self, rhs: &u64) -> Self::Output { let mut rhs = Integer::from(*rhs); reverse_multiply_assign(self, &mut rhs); rhs } } // ['u64', 'Integer', 'Integer', 'reverse_multiply_assign', 'rhs', ['ref', // {'convert': 'Integer'}], ['ref_mut']] impl Mul<Integer> for u64 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_assign(&Integer::from(self), &mut rhs); rhs } } // ['u64', '&Integer', 'Integer', 'let mut lhs = // Integer::from(self);\nInteger::multiply_assign(&mut lhs, rhs);\nlhs'] impl Mul<&Integer> for u64 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { let mut lhs = Integer::from(self); Integer::multiply_assign(&mut lhs, rhs); lhs } } // ['&u64', 'Integer', 'Integer', 'reverse_multiply_assign', 'rhs', ['ref', // {'convert': 'Integer'}, 'deref'], ['ref_mut']] impl Mul<Integer> for &u64 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_assign(&Integer::from(*self), &mut rhs); rhs } } // ['&u64', '&Integer', 'Integer', 'let mut lhs = // Integer::from(*self);\nInteger::multiply_assign(&mut lhs, rhs);\nlhs'] impl Mul<&Integer> for &u64 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { let mut lhs = Integer::from(*self); Integer::multiply_assign(&mut lhs, rhs); lhs } } // ['Integer', 'i128', 'Integer', 'Integer::multiply_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Mul<i128> for Integer { type Output = Integer; fn mul(mut self, rhs: i128) -> Self::Output { Integer::multiply_assign(&mut self, &Integer::from(rhs)); self } } // ['Integer', '&i128', 'Integer', 'Integer::multiply_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Mul<&i128> for Integer { type Output = Integer; fn mul(mut self, rhs: &i128) -> Self::Output { Integer::multiply_assign(&mut self, &Integer::from(*rhs)); self } } // ['&Integer', 'i128', 'Integer', 'let mut rhs = // Integer::from(rhs);\nreverse_multiply_assign(self, &mut rhs);\nrhs'] impl Mul<i128> for &Integer { type Output = Integer; fn mul(self, rhs: i128) -> Self::Output { let mut rhs = Integer::from(rhs); reverse_multiply_assign(self, &mut rhs); rhs } } // ['&Integer', '&i128', 'Integer', 'let mut rhs = // Integer::from(*rhs);\nreverse_multiply_assign(self, &mut rhs);\nrhs'] impl Mul<&i128> for &Integer { type Output = Integer; fn mul(self, rhs: &i128) -> Self::Output { let mut rhs = Integer::from(*rhs); reverse_multiply_assign(self, &mut rhs); rhs } } // ['i128', 'Integer', 'Integer', 'reverse_multiply_assign', 'rhs', ['ref', // {'convert': 'Integer'}], ['ref_mut']] impl Mul<Integer> for i128 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_assign(&Integer::from(self), &mut rhs); rhs } } // ['i128', '&Integer', 'Integer', 'let mut lhs = // Integer::from(self);\nInteger::multiply_assign(&mut lhs, rhs);\nlhs'] impl Mul<&Integer> for i128 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { let mut lhs = Integer::from(self); Integer::multiply_assign(&mut lhs, rhs); lhs } } // ['&i128', 'Integer', 'Integer', 'reverse_multiply_assign', 'rhs', ['ref', // {'convert': 'Integer'}, 'deref'], ['ref_mut']] impl Mul<Integer> for &i128 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_assign(&Integer::from(*self), &mut rhs); rhs } } // ['&i128', '&Integer', 'Integer', 'let mut lhs = // Integer::from(*self);\nInteger::multiply_assign(&mut lhs, rhs);\nlhs'] impl Mul<&Integer> for &i128 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { let mut lhs = Integer::from(*self); Integer::multiply_assign(&mut lhs, rhs); lhs } } // ['Integer', 'u128', 'Integer', 'Integer::multiply_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Mul<u128> for Integer { type Output = Integer; fn mul(mut self, rhs: u128) -> Self::Output { Integer::multiply_assign(&mut self, &Integer::from(rhs)); self } } // ['Integer', '&u128', 'Integer', 'Integer::multiply_assign', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Mul<&u128> for Integer { type Output = Integer; fn mul(mut self, rhs: &u128) -> Self::Output { Integer::multiply_assign(&mut self, &Integer::from(*rhs)); self } } // ['&Integer', 'u128', 'Integer', 'let mut rhs = // Integer::from(rhs);\nreverse_multiply_assign(self, &mut rhs);\nrhs'] impl Mul<u128> for &Integer { type Output = Integer; fn mul(self, rhs: u128) -> Self::Output { let mut rhs = Integer::from(rhs); reverse_multiply_assign(self, &mut rhs); rhs } } // ['&Integer', '&u128', 'Integer', 'let mut rhs = // Integer::from(*rhs);\nreverse_multiply_assign(self, &mut rhs);\nrhs'] impl Mul<&u128> for &Integer { type Output = Integer; fn mul(self, rhs: &u128) -> Self::Output { let mut rhs = Integer::from(*rhs); reverse_multiply_assign(self, &mut rhs); rhs } } // ['u128', 'Integer', 'Integer', 'reverse_multiply_assign', 'rhs', ['ref', // {'convert': 'Integer'}], ['ref_mut']] impl Mul<Integer> for u128 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_assign(&Integer::from(self), &mut rhs); rhs } } // ['u128', '&Integer', 'Integer', 'let mut lhs = // Integer::from(self);\nInteger::multiply_assign(&mut lhs, rhs);\nlhs'] impl Mul<&Integer> for u128 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { let mut lhs = Integer::from(self); Integer::multiply_assign(&mut lhs, rhs); lhs } } // ['&u128', 'Integer', 'Integer', 'reverse_multiply_assign', 'rhs', ['ref', // {'convert': 'Integer'}, 'deref'], ['ref_mut']] impl Mul<Integer> for &u128 { type Output = Integer; fn mul(self, mut rhs: Integer) -> Self::Output { reverse_multiply_assign(&Integer::from(*self), &mut rhs); rhs } } // ['&u128', '&Integer', 'Integer', 'let mut lhs = // Integer::from(*self);\nInteger::multiply_assign(&mut lhs, rhs);\nlhs'] impl Mul<&Integer> for &u128 { type Output = Integer; fn mul(self, rhs: &Integer) -> Self::Output { let mut lhs = Integer::from(*self); Integer::multiply_assign(&mut lhs, rhs); lhs } }
const THE_ANSWER: u8 = 42; pub fn fast() -> u8 { THE_ANSWER } pub fn slow() -> u8 { std::thread::sleep(std::time::Duration::from_millis(1)); THE_ANSWER }
#[doc = "Reader of register CFGR2"] pub type R = crate::R<u32, super::CFGR2>; #[doc = "Writer for register CFGR2"] pub type W = crate::W<u32, super::CFGR2>; #[doc = "Register CFGR2 `reset()`'s with value 0"] impl crate::ResetValue for super::CFGR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Oversampler Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OVSE_A { #[doc = "0: Oversampler disabled"] DISABLED = 0, #[doc = "1: Oversampler enabled"] ENABLED = 1, } impl From<OVSE_A> for bool { #[inline(always)] fn from(variant: OVSE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `OVSE`"] pub type OVSE_R = crate::R<bool, OVSE_A>; impl OVSE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OVSE_A { match self.bits { false => OVSE_A::DISABLED, true => OVSE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == OVSE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == OVSE_A::ENABLED } } #[doc = "Write proxy for field `OVSE`"] pub struct OVSE_W<'a> { w: &'a mut W, } impl<'a> OVSE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: OVSE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Oversampler disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(OVSE_A::DISABLED) } #[doc = "Oversampler enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(OVSE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Oversampling ratio\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum OVSR_A { #[doc = "0: 2x"] MUL2 = 0, #[doc = "1: 4x"] MUL4 = 1, #[doc = "2: 8x"] MUL8 = 2, #[doc = "3: 16x"] MUL16 = 3, #[doc = "4: 32x"] MUL32 = 4, #[doc = "5: 64x"] MUL64 = 5, #[doc = "6: 128x"] MUL128 = 6, #[doc = "7: 256x"] MUL256 = 7, } impl From<OVSR_A> for u8 { #[inline(always)] fn from(variant: OVSR_A) -> Self { variant as _ } } #[doc = "Reader of field `OVSR`"] pub type OVSR_R = crate::R<u8, OVSR_A>; impl OVSR_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OVSR_A { match self.bits { 0 => OVSR_A::MUL2, 1 => OVSR_A::MUL4, 2 => OVSR_A::MUL8, 3 => OVSR_A::MUL16, 4 => OVSR_A::MUL32, 5 => OVSR_A::MUL64, 6 => OVSR_A::MUL128, 7 => OVSR_A::MUL256, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `MUL2`"] #[inline(always)] pub fn is_mul2(&self) -> bool { *self == OVSR_A::MUL2 } #[doc = "Checks if the value of the field is `MUL4`"] #[inline(always)] pub fn is_mul4(&self) -> bool { *self == OVSR_A::MUL4 } #[doc = "Checks if the value of the field is `MUL8`"] #[inline(always)] pub fn is_mul8(&self) -> bool { *self == OVSR_A::MUL8 } #[doc = "Checks if the value of the field is `MUL16`"] #[inline(always)] pub fn is_mul16(&self) -> bool { *self == OVSR_A::MUL16 } #[doc = "Checks if the value of the field is `MUL32`"] #[inline(always)] pub fn is_mul32(&self) -> bool { *self == OVSR_A::MUL32 } #[doc = "Checks if the value of the field is `MUL64`"] #[inline(always)] pub fn is_mul64(&self) -> bool { *self == OVSR_A::MUL64 } #[doc = "Checks if the value of the field is `MUL128`"] #[inline(always)] pub fn is_mul128(&self) -> bool { *self == OVSR_A::MUL128 } #[doc = "Checks if the value of the field is `MUL256`"] #[inline(always)] pub fn is_mul256(&self) -> bool { *self == OVSR_A::MUL256 } } #[doc = "Write proxy for field `OVSR`"] pub struct OVSR_W<'a> { w: &'a mut W, } impl<'a> OVSR_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: OVSR_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "2x"] #[inline(always)] pub fn mul2(self) -> &'a mut W { self.variant(OVSR_A::MUL2) } #[doc = "4x"] #[inline(always)] pub fn mul4(self) -> &'a mut W { self.variant(OVSR_A::MUL4) } #[doc = "8x"] #[inline(always)] pub fn mul8(self) -> &'a mut W { self.variant(OVSR_A::MUL8) } #[doc = "16x"] #[inline(always)] pub fn mul16(self) -> &'a mut W { self.variant(OVSR_A::MUL16) } #[doc = "32x"] #[inline(always)] pub fn mul32(self) -> &'a mut W { self.variant(OVSR_A::MUL32) } #[doc = "64x"] #[inline(always)] pub fn mul64(self) -> &'a mut W { self.variant(OVSR_A::MUL64) } #[doc = "128x"] #[inline(always)] pub fn mul128(self) -> &'a mut W { self.variant(OVSR_A::MUL128) } #[doc = "256x"] #[inline(always)] pub fn mul256(self) -> &'a mut W { self.variant(OVSR_A::MUL256) } #[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 & !(0x07 << 2)) | (((value as u32) & 0x07) << 2); self.w } } #[doc = "Reader of field `OVSS`"] pub type OVSS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `OVSS`"] pub struct OVSS_W<'a> { w: &'a mut W, } impl<'a> OVSS_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 << 5)) | (((value as u32) & 0x0f) << 5); self.w } } #[doc = "Triggered Oversampling\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TOVS_A { #[doc = "0: All oversampled conversions for a channel are done consecutively after a trigger"] TRIGGERALL = 0, #[doc = "1: Each oversampled conversion for a channel needs a trigger"] TRIGGEREACH = 1, } impl From<TOVS_A> for bool { #[inline(always)] fn from(variant: TOVS_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TOVS`"] pub type TOVS_R = crate::R<bool, TOVS_A>; impl TOVS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TOVS_A { match self.bits { false => TOVS_A::TRIGGERALL, true => TOVS_A::TRIGGEREACH, } } #[doc = "Checks if the value of the field is `TRIGGERALL`"] #[inline(always)] pub fn is_trigger_all(&self) -> bool { *self == TOVS_A::TRIGGERALL } #[doc = "Checks if the value of the field is `TRIGGEREACH`"] #[inline(always)] pub fn is_trigger_each(&self) -> bool { *self == TOVS_A::TRIGGEREACH } } #[doc = "Write proxy for field `TOVS`"] pub struct TOVS_W<'a> { w: &'a mut W, } impl<'a> TOVS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TOVS_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "All oversampled conversions for a channel are done consecutively after a trigger"] #[inline(always)] pub fn trigger_all(self) -> &'a mut W { self.variant(TOVS_A::TRIGGERALL) } #[doc = "Each oversampled conversion for a channel needs a trigger"] #[inline(always)] pub fn trigger_each(self) -> &'a mut W { self.variant(TOVS_A::TRIGGEREACH) } #[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 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "ADC clock mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum CKMODE_A { #[doc = "0: ADCCLK (Asynchronous clock mode)"] ADCLK = 0, #[doc = "1: PCLK/2 (Synchronous clock mode)"] PCLK_DIV2 = 1, #[doc = "2: PCLK/4 (Synchronous clock mode)"] PCLK_DIV4 = 2, #[doc = "3: PCLK (Synchronous clock mode)"] PCLK = 3, } impl From<CKMODE_A> for u8 { #[inline(always)] fn from(variant: CKMODE_A) -> Self { variant as _ } } #[doc = "Reader of field `CKMODE`"] pub type CKMODE_R = crate::R<u8, CKMODE_A>; impl CKMODE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CKMODE_A { match self.bits { 0 => CKMODE_A::ADCLK, 1 => CKMODE_A::PCLK_DIV2, 2 => CKMODE_A::PCLK_DIV4, 3 => CKMODE_A::PCLK, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `ADCLK`"] #[inline(always)] pub fn is_adclk(&self) -> bool { *self == CKMODE_A::ADCLK } #[doc = "Checks if the value of the field is `PCLK_DIV2`"] #[inline(always)] pub fn is_pclk_div2(&self) -> bool { *self == CKMODE_A::PCLK_DIV2 } #[doc = "Checks if the value of the field is `PCLK_DIV4`"] #[inline(always)] pub fn is_pclk_div4(&self) -> bool { *self == CKMODE_A::PCLK_DIV4 } #[doc = "Checks if the value of the field is `PCLK`"] #[inline(always)] pub fn is_pclk(&self) -> bool { *self == CKMODE_A::PCLK } } #[doc = "Write proxy for field `CKMODE`"] pub struct CKMODE_W<'a> { w: &'a mut W, } impl<'a> CKMODE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CKMODE_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "ADCCLK (Asynchronous clock mode)"] #[inline(always)] pub fn adclk(self) -> &'a mut W { self.variant(CKMODE_A::ADCLK) } #[doc = "PCLK/2 (Synchronous clock mode)"] #[inline(always)] pub fn pclk_div2(self) -> &'a mut W { self.variant(CKMODE_A::PCLK_DIV2) } #[doc = "PCLK/4 (Synchronous clock mode)"] #[inline(always)] pub fn pclk_div4(self) -> &'a mut W { self.variant(CKMODE_A::PCLK_DIV4) } #[doc = "PCLK (Synchronous clock mode)"] #[inline(always)] pub fn pclk(self) -> &'a mut W { self.variant(CKMODE_A::PCLK) } #[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 << 30)) | (((value as u32) & 0x03) << 30); self.w } } impl R { #[doc = "Bit 0 - Oversampler Enable"] #[inline(always)] pub fn ovse(&self) -> OVSE_R { OVSE_R::new((self.bits & 0x01) != 0) } #[doc = "Bits 2:4 - Oversampling ratio"] #[inline(always)] pub fn ovsr(&self) -> OVSR_R { OVSR_R::new(((self.bits >> 2) & 0x07) as u8) } #[doc = "Bits 5:8 - Oversampling shift"] #[inline(always)] pub fn ovss(&self) -> OVSS_R { OVSS_R::new(((self.bits >> 5) & 0x0f) as u8) } #[doc = "Bit 9 - Triggered Oversampling"] #[inline(always)] pub fn tovs(&self) -> TOVS_R { TOVS_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bits 30:31 - ADC clock mode"] #[inline(always)] pub fn ckmode(&self) -> CKMODE_R { CKMODE_R::new(((self.bits >> 30) & 0x03) as u8) } } impl W { #[doc = "Bit 0 - Oversampler Enable"] #[inline(always)] pub fn ovse(&mut self) -> OVSE_W { OVSE_W { w: self } } #[doc = "Bits 2:4 - Oversampling ratio"] #[inline(always)] pub fn ovsr(&mut self) -> OVSR_W { OVSR_W { w: self } } #[doc = "Bits 5:8 - Oversampling shift"] #[inline(always)] pub fn ovss(&mut self) -> OVSS_W { OVSS_W { w: self } } #[doc = "Bit 9 - Triggered Oversampling"] #[inline(always)] pub fn tovs(&mut self) -> TOVS_W { TOVS_W { w: self } } #[doc = "Bits 30:31 - ADC clock mode"] #[inline(always)] pub fn ckmode(&mut self) -> CKMODE_W { CKMODE_W { w: self } } }
#[doc = "Reader of register DSI_VVSACCR"] pub type R = crate::R<u32, super::DSI_VVSACCR>; #[doc = "Reader of field `VSA`"] pub type VSA_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:9 - Vertical Synchronism Active duration"] #[inline(always)] pub fn vsa(&self) -> VSA_R { VSA_R::new((self.bits & 0x03ff) as u16) } }
use std::io::{self, BufRead}; fn get_input() -> Vec<i32> { let stdin = io::stdin(); let stdin = stdin.lock(); let result : Vec<_> = stdin.lines().map(|l| l.expect("could not read stdin").parse().expect("could not parse i32")).collect(); if result.len() >= i32::max_value() as usize { panic!("input too long"); } result } fn solve1(data: &mut [i32]) -> i32 { let mut ip : i32 = 0; let mut steps = 0; while ip >= 0 && ip < data.len() as i32 { let jump = data[ip as usize]; data[ip as usize] = jump + 1; ip = ip + jump; steps = steps + 1; } steps } fn solve2(data: &mut [i32]) -> i32 { let mut ip : i32 = 0; let mut steps = 0; while ip >= 0 && ip < data.len() as i32 { let jump = data[ip as usize]; data[ip as usize] = if jump >= 3 { jump - 1 } else { jump + 1 }; ip = ip + jump; steps = steps + 1; } steps } fn main() { let mut data1 = get_input(); let mut data2 = data1.clone(); let result1 = solve1(&mut data1); println!("Solution 1: {}", result1); let result2 = solve2(&mut data2); println!("Solution 2: {}", result2); }
extern crate lit; #[cfg(test)] mod tests { use std::env::consts; #[test] fn lit() { lit::run::tests(|config| { config.add_search_path("lit/"); config.add_extension("test"); config.constants.insert("arch".to_owned(), consts::ARCH.to_owned()); config.constants.insert("os".to_owned(), consts::OS.to_owned()); }).expect("Lit tests failed"); } }
use crate::rust_info::RustTypeCaptionStrategy; use itertools::Itertools; use ritual_common::errors::{bail, Error, Result}; use ritual_common::string_utils::CaseOperations; use ritual_common::utils::MapIfOk; use serde_derive::{Deserialize, Serialize}; use std::str::FromStr; /// Rust identifier. Represented by /// a vector of name parts. First part is name of the crate, /// last part is own name of the entity, /// and intermediate names are module names. #[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub struct RustPath { /// Parts of the name pub parts: Vec<String>, } impl FromStr for RustPath { type Err = Error; fn from_str(str: &str) -> Result<Self> { let parts = str.split("::").map(String::from).collect_vec(); if parts.is_empty() { bail!("RustPath can't be empty"); } if parts.iter().any(String::is_empty) { bail!("RustPath item can't be empty"); } Ok(RustPath { parts }) } } impl PartialEq<&str> for RustPath { fn eq(&self, str: &&str) -> bool { let parts = str.split("::"); if self.parts.len() != parts.clone().count() { return false; } self.parts.iter().zip(parts).all(|(a, b)| a == b) } } impl RustPath { /// Creates new `RustPath` consisting of `parts`. pub fn from_parts(parts: Vec<String>) -> Self { if parts.is_empty() { panic!("RustPath can't be empty"); } RustPath { parts } } pub fn from_good_str(str: &str) -> Self { Self::from_str(str).unwrap() } /// Returns crate name of this name, or `None` /// if this name does not contain the crate name (e.g. it's a built-in type). pub fn crate_name(&self) -> &str { if self.parts.is_empty() { panic!("RustPath can't be empty"); } self.parts[0].as_str() } /// Returns last component of the name. pub fn last(&self) -> &str { self.parts.last().expect("RustPath can't be empty") } pub fn last_mut(&mut self) -> &mut String { self.parts.last_mut().expect("RustPath can't be empty") } pub fn join(&self, name: impl Into<String>) -> RustPath { let mut new_path = self.clone(); new_path.parts.push(name.into()); new_path } /// Returns formatted name for using within `current_crate`. /// If `current_crate` is `None`, it's assumed that the formatted name /// will be used outside of the crate it belongs to. pub fn full_name(&self, current_crate: Option<&str>) -> String { if let Some(current_crate) = current_crate { if self.crate_name() == current_crate { return format!("crate::{}", self.parts[1..].join("::")); } } format!("::{}", self.parts.join("::")) } /// Returns true if `other` is nested within `self`. pub fn includes(&self, other: &RustPath) -> bool { let extra_modules_count = other.parts.len() as isize - self.parts.len() as isize; extra_modules_count > 0 && other.parts[0..self.parts.len()] == self.parts[..] } /// Returns true if `other` is a direct child of `self`. pub fn includes_directly(&self, other: &RustPath) -> bool { let extra_modules_count = other.parts.len() as isize - self.parts.len() as isize; self.includes(other) && extra_modules_count == 1 } pub fn is_child_of(&self, parent: &RustPath) -> bool { parent.includes_directly(self) } pub fn parent(&self) -> Result<RustPath> { if self.parts.len() > 1 { let mut new_path = self.clone(); new_path.parts.pop().unwrap(); Ok(new_path) } else { bail!("failed to get parent path for {:?}", self) } } pub fn parent_parts(&self) -> Result<&[String]> { if self.parts.len() > 1 { Ok(&self.parts[..self.parts.len() - 1]) } else { bail!("failed to get parent path for {:?}", self) } } pub fn parts(&self) -> &[String] { &self.parts } } /// Conversion from public Rust API type to /// the corresponding FFI type #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub enum RustToFfiTypeConversion { /// Types are the same None, /// `&T` to `*const T` (or similar mutable types) RefToPtr { lifetime: Option<String>, }, /// `Ptr<T>` to `*const T` (or similar mutable type) UtilsPtrToPtr {}, /// `Ref<T>` to `*const T` (or similar mutable types) UtilsRefToPtr {}, /// `Option<Ref<T>>` to `*const T` (or similar mutable types) OptionUtilsRefToPtr {}, /// `QPtr<T>` to `Ptr<T>` QPtrToPtr, /// `T` to `*const T` (or similar mutable type) ValueToPtr, /// `CppBox<T>` to `*mut T` CppBoxToPtr, /// `QBox<T>` to `*mut T` QBoxToPtr, /// `qt_core::flags::Flags<T>` to `c_int` QFlagsToUInt { api_type: RustType, }, /// `()` to any type UnitToAnything, /// Primitive to another primitive using `as` AsCast { api_type: RustType, }, /// Rust public type has an additional reference (`&`) RefTo(Box<RustToFfiTypeConversion>), ImplCastInto(Box<RustToFfiTypeConversion>), ClosureToCallback(Box<RustClosureToCallbackConversion>), } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct RustClosureToCallbackConversion { pub closure_arguments: Vec<RustFinalType>, pub closure_return_type: RustFinalType, } impl RustToFfiTypeConversion { pub fn is_option_utils_ref_to_ptr(&self) -> bool { matches!(self, RustToFfiTypeConversion::OptionUtilsRefToPtr { .. }) } pub fn is_utils_ref_to_ptr(&self) -> bool { matches!(self, RustToFfiTypeConversion::UtilsRefToPtr { .. }) } pub fn as_callback_ref(&self) -> Option<&RustClosureToCallbackConversion> { if let RustToFfiTypeConversion::ClosureToCallback(x) = self { Some(x) } else { None } } } /// Information about a completely processed type /// including its variations at each processing step. #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct RustFinalType { /// Rust type used in FFI functions /// (must be exactly the same as `cpp_ffi_type`) ffi_type: RustType, /// Type used in public Rust API api_type: RustType, /// Conversion from `rust_api_type` to `rust_ffi_type` conversion: RustToFfiTypeConversion, } fn utils_ptr(ffi_type: &RustType) -> Result<RustType> { let target = ffi_type.pointer_like_to_target()?; Ok(RustType::Common(RustCommonType { path: RustPath::from_good_str("cpp_core::Ptr"), generic_arguments: Some(vec![target]), })) } fn utils_ref(ffi_type: &RustType) -> Result<RustType> { let target = ffi_type.pointer_like_to_target()?; Ok(RustType::Common(RustCommonType { path: RustPath::from_good_str("cpp_core::Ref"), generic_arguments: Some(vec![target]), })) } fn class_type_to_qt_core_crate_path(t: &RustType) -> Result<RustPath> { if let RustType::Common(t) = t { let name = if t.path.crate_name().starts_with("moqt") { "moqt_core" } else { "qt_core" }; Ok(RustPath::from_good_str(name)) } else { bail!("expected common type for QBox/QPtr conversion, got {:?}", t); } } impl RustFinalType { pub fn new(ffi_type: RustType, api_to_ffi_conversion: RustToFfiTypeConversion) -> Result<Self> { let api_type = match &api_to_ffi_conversion { RustToFfiTypeConversion::None => ffi_type.clone(), RustToFfiTypeConversion::RefToPtr { lifetime } => { if let RustType::PointerLike { target, .. } = &ffi_type { RustType::PointerLike { is_const: true, kind: RustPointerLikeTypeKind::Reference { lifetime: lifetime.clone(), }, target: target.clone(), } } else { bail!("not a pointer like type"); } } RustToFfiTypeConversion::UtilsPtrToPtr {} => utils_ptr(&ffi_type)?, RustToFfiTypeConversion::UtilsRefToPtr {} => utils_ref(&ffi_type)?, RustToFfiTypeConversion::OptionUtilsRefToPtr {} => { RustType::new_option(utils_ref(&ffi_type)?) } RustToFfiTypeConversion::ValueToPtr => ffi_type.pointer_like_to_target()?, RustToFfiTypeConversion::CppBoxToPtr => { let target = ffi_type.pointer_like_to_target()?; RustType::Common(RustCommonType { path: RustPath::from_good_str("cpp_core::CppBox"), generic_arguments: Some(vec![target]), }) } RustToFfiTypeConversion::QBoxToPtr => { let target = ffi_type.pointer_like_to_target()?; RustType::Common(RustCommonType { path: class_type_to_qt_core_crate_path(&target)?.join("QBox"), generic_arguments: Some(vec![target.clone()]), }) } RustToFfiTypeConversion::QPtrToPtr => { let target = ffi_type.pointer_like_to_target()?; RustType::Common(RustCommonType { path: class_type_to_qt_core_crate_path(&target)?.join("QPtr"), generic_arguments: Some(vec![target.clone()]), }) } RustToFfiTypeConversion::QFlagsToUInt { api_type } | RustToFfiTypeConversion::AsCast { api_type } => api_type.clone(), RustToFfiTypeConversion::UnitToAnything => RustType::unit(), RustToFfiTypeConversion::RefTo(conversion) => { let intermediate = RustFinalType::new(ffi_type.clone(), (**conversion).clone())?; RustType::new_reference(true, intermediate.api_type) } RustToFfiTypeConversion::ImplCastInto(conversion) => { let intermediate = RustFinalType::new(ffi_type.clone(), (**conversion).clone())?; let trait_type = RustCommonType { path: RustPath::from_good_str("cpp_core::CastInto"), generic_arguments: Some(vec![intermediate.api_type]), }; RustType::ImplTrait(trait_type) } RustToFfiTypeConversion::ClosureToCallback { .. } => { RustType::GenericParameter("T".into()) } }; Ok(RustFinalType { api_type, ffi_type, conversion: api_to_ffi_conversion, }) } pub fn api_type(&self) -> &RustType { &self.api_type } pub fn ffi_type(&self) -> &RustType { &self.ffi_type } pub fn conversion(&self) -> &RustToFfiTypeConversion { &self.conversion } pub fn with_lifetime(&self, lifetime: String) -> Result<Self> { if let RustToFfiTypeConversion::RefToPtr { .. } = &self.conversion { RustFinalType::new( self.ffi_type.clone(), RustToFfiTypeConversion::RefToPtr { lifetime: Some(lifetime), }, ) } else { bail!("not a RefToPtr type"); } } } #[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub enum RustPointerLikeTypeKind { // `*mut T` or `*const T` Pointer, // `&'lifetime T` or `&'lifetime mut T` Reference { lifetime: Option<String> }, } impl RustPointerLikeTypeKind { pub fn is_pointer(&self) -> bool { matches!(self, RustPointerLikeTypeKind::Pointer) } pub fn is_ref(&self) -> bool { matches!(self, RustPointerLikeTypeKind::Reference { .. }) } } #[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub struct RustCommonType { /// Full name of the base type pub path: RustPath, /// Generic arguments, if any pub generic_arguments: Option<Vec<RustType>>, } pub fn paths_can_be_same<T1, T2>(one: &T1, other: &T2) -> bool where T1: for<'a> PartialEq<&'a str> + PartialEq<T2>, T2: for<'a> PartialEq<&'a str>, { let colliding: &[(&[&str], &[&str])] = &[ ( &[ "std::os::raw::c_char", "std::os::raw::c_schar", "std::os::raw::c_short", "std::os::raw::c_int", "std::os::raw::c_long", "std::os::raw::c_longlong", ], &["u8", "u16", "u32", "u64"], ), ( &[ "std::os::raw::c_char", "std::os::raw::c_uchar", "std::os::raw::c_ushort", "std::os::raw::c_uint", "std::os::raw::c_ulong", "std::os::raw::c_ulonglong", ], &["u8", "u16", "u32", "u64"], ), ( &["std::os::raw::c_float", "std::os::raw::c_double"], &["f32", "f64"], ), ]; if one == other { return true; } for (ambiguous, concrete) in colliding { if ambiguous.iter().any(|s| one == s) && ambiguous.iter().any(|s| other == s) { return true; } if ambiguous.iter().any(|s| one == s) && concrete.iter().any(|s| other == s) { return true; } if concrete.iter().any(|s| one == s) && ambiguous.iter().any(|s| other == s) { return true; } } false } impl RustCommonType { pub fn can_be_same_as(&self, other: &RustCommonType) -> bool { let self_args = self .generic_arguments .as_ref() .into_iter() .flat_map(|vec| vec.iter()); let other_args = other .generic_arguments .as_ref() .into_iter() .flat_map(|vec| vec.iter()); if self_args.clone().count() != other_args.clone().count() { return false; } if !self_args.zip(other_args).all(|(a, b)| a.can_be_same_as(b)) { return false; } paths_can_be_same(&self.path, &other.path) } } #[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub struct RustFunctionPointerType { /// Return type of the function. pub return_type: Box<RustType>, /// Argument types of the function. pub arguments: Vec<RustType>, } /// A Rust type #[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub enum RustType { Tuple(Vec<RustType>), /// Primitive built-in type (`i32`, `str`, etc.) Primitive(String), /// A type specified by path with possible generic arguments Common(RustCommonType), /// A function pointer type. FunctionPointer(RustFunctionPointerType), PointerLike { kind: RustPointerLikeTypeKind, is_const: bool, target: Box<RustType>, }, ImplTrait(RustCommonType), GenericParameter(String), } impl RustType { /// Constructs the unit type `()`, used as the replacement of C++'s `void` type. pub fn unit() -> Self { RustType::Tuple(Vec::new()) } pub fn bool() -> Self { RustType::Primitive("bool".into()) } pub fn new_pointer(is_const: bool, target: RustType) -> Self { RustType::PointerLike { kind: RustPointerLikeTypeKind::Pointer, is_const, target: Box::new(target), } } pub fn new_reference(is_const: bool, target: RustType) -> Self { RustType::PointerLike { kind: RustPointerLikeTypeKind::Reference { lifetime: None }, is_const, target: Box::new(target), } } pub fn new_option(target: RustType) -> Self { RustType::Common(RustCommonType { path: RustPath::from_good_str("std::option::Option"), generic_arguments: Some(vec![target]), }) } pub fn is_unit(&self) -> bool { if let RustType::Tuple(types) = self { types.is_empty() } else { false } } /// Returns alphanumeric description of this type /// for purposes of name disambiguation. pub fn caption(&self, context: &RustPath, strategy: RustTypeCaptionStrategy) -> Result<String> { Ok(match self { RustType::Tuple(types) => types .iter() .map_if_ok(|t| t.caption(context, strategy))? .join("_"), RustType::Primitive(type1) | RustType::GenericParameter(type1) => type1.to_string(), RustType::PointerLike { target, .. } => { // let const_text = if *is_const { "_const" } else { "" }; // let kind_text = match *kind { // RustPointerLikeTypeKind::Pointer => "_ptr", // RustPointerLikeTypeKind::Reference { .. } => "_ref", // }; // format!( // "{}{}{}", // target.caption(context, strategy)?, // const_text, // kind_text // ) target.caption(context, strategy)? } RustType::Common(RustCommonType { path, generic_arguments, }) => { if path == &RustPath::from_good_str("cpp_core::Ptr") || path == &RustPath::from_good_str("cpp_core::Ref") || path == &RustPath::from_good_str("cpp_core::CppBox") { let arg = &generic_arguments.as_ref().unwrap()[0]; return arg.caption(context, strategy); } let mut name = if path.parts.len() == 1 { path.parts[0].to_snake_case() } else if path.crate_name() == "std" { let last = path.last(); let last = if let Some(suffix) = last.strip_prefix("c_") { suffix } else { last }; last.to_snake_case() } else if strategy == RustTypeCaptionStrategy::LastName { path.last().to_string().to_snake_case() } else { let mut remaining_context: &[String] = &context.parts; let parts: &[String] = &path.parts; let mut good_parts = Vec::new(); for part in parts { if !remaining_context.is_empty() && part == &remaining_context[0] { remaining_context = &remaining_context[1..]; } else { remaining_context = &[]; let snake_part = part.to_snake_case(); if good_parts.last() != Some(&snake_part) { good_parts.push(snake_part); } } } if good_parts.is_empty() { path.last().to_string().to_snake_case() } else { good_parts.join("_") } }; if let Some(args) = generic_arguments { name = format!( "{}_{}", name, args.iter() .map_if_ok(|x| x.caption(context, strategy))? .join("_") ); } name } RustType::FunctionPointer { .. } => "fn".to_string(), RustType::ImplTrait(trait_type) => { if trait_type.path == RustPath::from_good_str("cpp_core::CastInto") { trait_type .generic_arguments .iter() .flatten() .map_if_ok(|x| x.caption(context, strategy))? .join("_") } else { RustType::Common(trait_type.clone()).caption(context, strategy)? } } }) } /// Returns true if this type is a reference. pub fn is_ref(&self) -> bool { match self { RustType::PointerLike { kind, .. } => kind.is_ref(), _ => false, } } /// Returns a copy of this type with `new_lifetime` added, if possible. pub fn with_lifetime(&self, new_lifetime: String) -> RustType { let mut r = self.clone(); if let RustType::PointerLike { kind, .. } = &mut r { match kind { RustPointerLikeTypeKind::Pointer => {} RustPointerLikeTypeKind::Reference { lifetime } => { *lifetime = Some(new_lifetime); } } } r } /// Returns name of the lifetime of this type, /// or `None` if there isn't any lifetime in this type. #[allow(clippy::collapsible_match)] pub fn lifetime(&self) -> Option<&str> { if let RustType::PointerLike { kind, .. } = self { if let RustPointerLikeTypeKind::Reference { lifetime } = kind { return lifetime.as_ref().map(String::as_str); } } None } /// Returns true if indirection that is applied last has const qualifier. pub fn is_const_pointer_like(&self) -> Result<bool> { if let RustType::PointerLike { is_const, .. } = self { Ok(*is_const) } else { bail!("not a PointerLike type"); } } /// Sets value of `is_const` for a `PointerLike` type. pub fn set_const(&mut self, value: bool) -> Result<()> { match self { RustType::PointerLike { is_const, .. } => { *is_const = value; Ok(()) } _ => bail!("not a PointerLike type"), } } /// Returns true if function with an argument of this type /// should be assumed unsafe. Currently returns true if this type /// is or contains a raw pointer. pub fn is_unsafe_argument(&self) -> bool { match self { RustType::PointerLike { kind, target, .. } => { kind.is_pointer() || target.is_unsafe_argument() } RustType::Primitive(_) | RustType::GenericParameter(_) => false, RustType::Common(RustCommonType { generic_arguments, .. }) => { if let Some(args) = generic_arguments { if args.iter().any(RustType::is_unsafe_argument) { return true; } } false } RustType::Tuple(types) => types.iter().any(RustType::is_unsafe_argument), RustType::FunctionPointer(function) => { function.return_type.is_unsafe_argument() || function.arguments.iter().any(RustType::is_unsafe_argument) } RustType::ImplTrait(_) => true, } } pub fn pointer_like_to_target(&self) -> Result<RustType> { if let RustType::PointerLike { target, .. } = self { Ok((**target).clone()) } else { bail!("not a pointer like type"); } } pub fn ptr_to_ref(&self, is_const1: bool) -> Result<Self> { let mut r = self.clone(); if let RustType::PointerLike { is_const, kind, .. } = &mut r { if !kind.is_pointer() { bail!("not a pointer type"); } *kind = RustPointerLikeTypeKind::Reference { lifetime: None }; *is_const = is_const1; } else { bail!("not a PointerLike type"); } Ok(r) } pub fn as_common(&self) -> Result<&RustCommonType> { if let RustType::Common(r) = self { Ok(r) } else { bail!("expected common type, got {:?}", self) } } pub fn can_be_same_as(&self, other: &RustType) -> bool { match self { RustType::Tuple(self_args) => { if let RustType::Tuple(other_args) = other { self_args.len() == other_args.len() && self_args .iter() .zip(other_args) .all(|(a, b)| a.can_be_same_as(b)) } else { false } } RustType::Common(self_type) => match other { RustType::Common(other_type) => self_type.can_be_same_as(other_type), RustType::Primitive(other_type) => { self_type.generic_arguments.is_none() && paths_can_be_same(&self_type.path, &other_type.as_str()) } _ => false, }, RustType::Primitive(type1) => match other { RustType::Primitive(other_type) => type1 == other_type, RustType::Common(other_type) => { other_type.generic_arguments.is_none() && paths_can_be_same(&other_type.path, &type1.as_str()) } _ => false, }, RustType::FunctionPointer(function) => { if let RustType::FunctionPointer(other) = other { function.return_type.can_be_same_as(&other.return_type) && function.arguments.len() == other.arguments.len() && function .arguments .iter() .zip(&other.arguments) .all(|(a, b)| a.can_be_same_as(b)) } else { false } } RustType::PointerLike { kind: self_kind, is_const: self_is_const, target: self_target, } => { if let RustType::PointerLike { kind, is_const, target, } = other { self_kind == kind && self_is_const == is_const && self_target.can_be_same_as(target) } else { false } } RustType::ImplTrait(trait_type) => { if let RustType::ImplTrait(other_trait_type) = other { trait_type.can_be_same_as(other_trait_type) } else { false } } RustType::GenericParameter(_) => self == other, } } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IInstalledDesktopApp(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IInstalledDesktopApp { type Vtable = IInstalledDesktopApp_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x75eab8ed_c0bc_5364_4c28_166e0545167a); } #[repr(C)] #[doc(hidden)] pub struct IInstalledDesktopApp_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IInstalledDesktopAppStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IInstalledDesktopAppStatics { type Vtable = IInstalledDesktopAppStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x264cf74e_21cd_5f9b_6056_7866ad72489a); } #[repr(C)] #[doc(hidden)] pub struct IInstalledDesktopAppStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct InstalledDesktopApp(pub ::windows::core::IInspectable); impl InstalledDesktopApp { #[cfg(feature = "Foundation")] pub fn ToString(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<super::super::Foundation::IStringable>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Id(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Publisher(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn DisplayVersion(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetInventoryAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<InstalledDesktopApp>>> { Self::IInstalledDesktopAppStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<InstalledDesktopApp>>>(result__) }) } pub fn IInstalledDesktopAppStatics<R, F: FnOnce(&IInstalledDesktopAppStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<InstalledDesktopApp, IInstalledDesktopAppStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for InstalledDesktopApp { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.System.Inventory.InstalledDesktopApp;{75eab8ed-c0bc-5364-4c28-166e0545167a})"); } unsafe impl ::windows::core::Interface for InstalledDesktopApp { type Vtable = IInstalledDesktopApp_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x75eab8ed_c0bc_5364_4c28_166e0545167a); } impl ::windows::core::RuntimeName for InstalledDesktopApp { const NAME: &'static str = "Windows.System.Inventory.InstalledDesktopApp"; } impl ::core::convert::From<InstalledDesktopApp> for ::windows::core::IUnknown { fn from(value: InstalledDesktopApp) -> Self { value.0 .0 } } impl ::core::convert::From<&InstalledDesktopApp> for ::windows::core::IUnknown { fn from(value: &InstalledDesktopApp) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for InstalledDesktopApp { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a InstalledDesktopApp { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<InstalledDesktopApp> for ::windows::core::IInspectable { fn from(value: InstalledDesktopApp) -> Self { value.0 } } impl ::core::convert::From<&InstalledDesktopApp> for ::windows::core::IInspectable { fn from(value: &InstalledDesktopApp) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for InstalledDesktopApp { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a InstalledDesktopApp { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<InstalledDesktopApp> for super::super::Foundation::IStringable { type Error = ::windows::core::Error; fn try_from(value: InstalledDesktopApp) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&InstalledDesktopApp> for super::super::Foundation::IStringable { type Error = ::windows::core::Error; fn try_from(value: &InstalledDesktopApp) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for InstalledDesktopApp { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IStringable> for &InstalledDesktopApp { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IStringable> { ::core::convert::TryInto::<super::super::Foundation::IStringable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for InstalledDesktopApp {} unsafe impl ::core::marker::Sync for InstalledDesktopApp {}
use std::borrow::Cow; use std::collections::BTreeSet; use std::env; use std::fmt; use std::sync::atomic::{AtomicBool, Ordering}; use lazy_static::lazy_static; use crate::term::{wants_emoji, Term}; #[cfg(feature = "ansi-parsing")] use crate::ansi::{strip_ansi_codes, AnsiCodeIterator}; #[cfg(not(feature = "ansi-parsing"))] fn strip_ansi_codes(s: &str) -> &str { s } fn default_colors_enabled(out: &Term) -> bool { (out.features().colors_supported() && &env::var("CLICOLOR").unwrap_or_else(|_| "1".into()) != "0") || &env::var("CLICOLOR_FORCE").unwrap_or_else(|_| "0".into()) != "0" } lazy_static! { static ref STDOUT_COLORS: AtomicBool = AtomicBool::new(default_colors_enabled(&Term::stdout())); static ref STDERR_COLORS: AtomicBool = AtomicBool::new(default_colors_enabled(&Term::stderr())); } /// Returns `true` if colors should be enabled for stdout. /// /// This honors the [clicolors spec](http://bixense.com/clicolors/). /// /// * `CLICOLOR != 0`: ANSI colors are supported and should be used when the program isn't piped. /// * `CLICOLOR == 0`: Don't output ANSI color escape codes. /// * `CLICOLOR_FORCE != 0`: ANSI colors should be enabled no matter what. #[inline] pub fn colors_enabled() -> bool { STDOUT_COLORS.load(Ordering::Relaxed) } /// Forces colorization on or off for stdout. /// /// This overrides the default for the current process and changes the return value of the /// `colors_enabled` function. #[inline] pub fn set_colors_enabled(val: bool) { STDOUT_COLORS.store(val, Ordering::Relaxed) } /// Returns `true` if colors should be enabled for stderr. /// /// This honors the [clicolors spec](http://bixense.com/clicolors/). /// /// * `CLICOLOR != 0`: ANSI colors are supported and should be used when the program isn't piped. /// * `CLICOLOR == 0`: Don't output ANSI color escape codes. /// * `CLICOLOR_FORCE != 0`: ANSI colors should be enabled no matter what. #[inline] pub fn colors_enabled_stderr() -> bool { STDERR_COLORS.load(Ordering::Relaxed) } /// Forces colorization on or off for stderr. /// /// This overrides the default for the current process and changes the return value of the /// `colors_enabled` function. #[inline] pub fn set_colors_enabled_stderr(val: bool) { STDERR_COLORS.store(val, Ordering::Relaxed) } /// Measure the width of a string in terminal characters. pub fn measure_text_width(s: &str) -> usize { str_width(&strip_ansi_codes(s)) } /// A terminal color. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Color { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White, Color256(u8), } impl Color { #[inline] fn ansi_num(self) -> usize { match self { Color::Black => 0, Color::Red => 1, Color::Green => 2, Color::Yellow => 3, Color::Blue => 4, Color::Magenta => 5, Color::Cyan => 6, Color::White => 7, Color::Color256(x) => x as usize, } } #[inline] fn is_color256(self) -> bool { #[allow(clippy::match_like_matches_macro)] match self { Color::Color256(_) => true, _ => false, } } } /// A terminal style attribute. #[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)] pub enum Attribute { Bold, Dim, Italic, Underlined, Blink, BlinkFast, Reverse, Hidden, StrikeThrough, } impl Attribute { #[inline] fn ansi_num(self) -> usize { match self { Attribute::Bold => 1, Attribute::Dim => 2, Attribute::Italic => 3, Attribute::Underlined => 4, Attribute::Blink => 5, Attribute::BlinkFast => 6, Attribute::Reverse => 7, Attribute::Hidden => 8, Attribute::StrikeThrough => 9, } } } /// Defines the alignment for padding operations. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Alignment { Left, Center, Right, } /// A stored style that can be applied. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Style { fg: Option<Color>, bg: Option<Color>, fg_bright: bool, bg_bright: bool, attrs: BTreeSet<Attribute>, force: Option<bool>, for_stderr: bool, } impl Default for Style { fn default() -> Style { Style::new() } } impl Style { /// Returns an empty default style. pub fn new() -> Style { Style { fg: None, bg: None, fg_bright: false, bg_bright: false, attrs: BTreeSet::new(), force: None, for_stderr: false, } } /// Creates a style from a dotted string. /// /// Effectively the string is split at each dot and then the /// terms in between are applied. For instance `red.on_blue` will /// create a string that is red on blue background. `9.on_12` is /// the same, but using 256 color numbers. Unknown terms are /// ignored. pub fn from_dotted_str(s: &str) -> Style { let mut rv = Style::new(); for part in s.split('.') { rv = match part { "black" => rv.black(), "red" => rv.red(), "green" => rv.green(), "yellow" => rv.yellow(), "blue" => rv.blue(), "magenta" => rv.magenta(), "cyan" => rv.cyan(), "white" => rv.white(), "bright" => rv.bright(), "on_black" => rv.on_black(), "on_red" => rv.on_red(), "on_green" => rv.on_green(), "on_yellow" => rv.on_yellow(), "on_blue" => rv.on_blue(), "on_magenta" => rv.on_magenta(), "on_cyan" => rv.on_cyan(), "on_white" => rv.on_white(), "on_bright" => rv.on_bright(), "bold" => rv.bold(), "dim" => rv.dim(), "underlined" => rv.underlined(), "blink" => rv.blink(), "blink_fast" => rv.blink_fast(), "reverse" => rv.reverse(), "hidden" => rv.hidden(), "strikethrough" => rv.strikethrough(), on_c if on_c.starts_with("on_") => { if let Ok(n) = on_c[3..].parse::<u8>() { rv.on_color256(n) } else { continue; } } c => { if let Ok(n) = c.parse::<u8>() { rv.color256(n) } else { continue; } } }; } rv } /// Apply the style to something that can be displayed. pub fn apply_to<D>(&self, val: D) -> StyledObject<D> { StyledObject { style: self.clone(), val, } } /// Forces styling on or off. /// /// This overrides the automatic detection. #[inline] pub fn force_styling(mut self, value: bool) -> Style { self.force = Some(value); self } /// Specifies that style is applying to something being written on stderr. #[inline] pub fn for_stderr(mut self) -> Style { self.for_stderr = true; self } /// Specifies that style is applying to something being written on stdout. /// /// This is the default behaviour. #[inline] pub fn for_stdout(mut self) -> Style { self.for_stderr = false; self } /// Sets a foreground color. #[inline] pub fn fg(mut self, color: Color) -> Style { self.fg = Some(color); self } /// Sets a background color. #[inline] pub fn bg(mut self, color: Color) -> Style { self.bg = Some(color); self } /// Adds a attr. #[inline] pub fn attr(mut self, attr: Attribute) -> Style { self.attrs.insert(attr); self } #[inline] pub fn black(self) -> Style { self.fg(Color::Black) } #[inline] pub fn red(self) -> Style { self.fg(Color::Red) } #[inline] pub fn green(self) -> Style { self.fg(Color::Green) } #[inline] pub fn yellow(self) -> Style { self.fg(Color::Yellow) } #[inline] pub fn blue(self) -> Style { self.fg(Color::Blue) } #[inline] pub fn magenta(self) -> Style { self.fg(Color::Magenta) } #[inline] pub fn cyan(self) -> Style { self.fg(Color::Cyan) } #[inline] pub fn white(self) -> Style { self.fg(Color::White) } #[inline] pub fn color256(self, color: u8) -> Style { self.fg(Color::Color256(color)) } #[inline] pub fn bright(mut self) -> Style { self.fg_bright = true; self } #[inline] pub fn on_black(self) -> Style { self.bg(Color::Black) } #[inline] pub fn on_red(self) -> Style { self.bg(Color::Red) } #[inline] pub fn on_green(self) -> Style { self.bg(Color::Green) } #[inline] pub fn on_yellow(self) -> Style { self.bg(Color::Yellow) } #[inline] pub fn on_blue(self) -> Style { self.bg(Color::Blue) } #[inline] pub fn on_magenta(self) -> Style { self.bg(Color::Magenta) } #[inline] pub fn on_cyan(self) -> Style { self.bg(Color::Cyan) } #[inline] pub fn on_white(self) -> Style { self.bg(Color::White) } #[inline] pub fn on_color256(self, color: u8) -> Style { self.bg(Color::Color256(color)) } #[inline] pub fn on_bright(mut self) -> Style { self.bg_bright = true; self } #[inline] pub fn bold(self) -> Style { self.attr(Attribute::Bold) } #[inline] pub fn dim(self) -> Style { self.attr(Attribute::Dim) } #[inline] pub fn italic(self) -> Style { self.attr(Attribute::Italic) } #[inline] pub fn underlined(self) -> Style { self.attr(Attribute::Underlined) } #[inline] pub fn blink(self) -> Style { self.attr(Attribute::Blink) } #[inline] pub fn blink_fast(self) -> Style { self.attr(Attribute::BlinkFast) } #[inline] pub fn reverse(self) -> Style { self.attr(Attribute::Reverse) } #[inline] pub fn hidden(self) -> Style { self.attr(Attribute::Hidden) } #[inline] pub fn strikethrough(self) -> Style { self.attr(Attribute::StrikeThrough) } } /// Wraps an object for formatting for styling. /// /// Example: /// /// ```rust,no_run /// # use console::style; /// format!("Hello {}", style("World").cyan()); /// ``` /// /// This is a shortcut for making a new style and applying it /// to a value: /// /// ```rust,no_run /// # use console::Style; /// format!("Hello {}", Style::new().cyan().apply_to("World")); /// ``` pub fn style<D>(val: D) -> StyledObject<D> { Style::new().apply_to(val) } /// A formatting wrapper that can be styled for a terminal. #[derive(Clone)] pub struct StyledObject<D> { style: Style, val: D, } impl<D> StyledObject<D> { /// Forces styling on or off. /// /// This overrides the automatic detection. #[inline] pub fn force_styling(mut self, value: bool) -> StyledObject<D> { self.style = self.style.force_styling(value); self } /// Specifies that style is applying to something being written on stderr #[inline] pub fn for_stderr(mut self) -> StyledObject<D> { self.style = self.style.for_stderr(); self } /// Specifies that style is applying to something being written on stdout /// /// This is the default #[inline] pub fn for_stdout(mut self) -> StyledObject<D> { self.style = self.style.for_stdout(); self } /// Sets a foreground color. #[inline] pub fn fg(mut self, color: Color) -> StyledObject<D> { self.style = self.style.fg(color); self } /// Sets a background color. #[inline] pub fn bg(mut self, color: Color) -> StyledObject<D> { self.style = self.style.bg(color); self } /// Adds a attr. #[inline] pub fn attr(mut self, attr: Attribute) -> StyledObject<D> { self.style = self.style.attr(attr); self } #[inline] pub fn black(self) -> StyledObject<D> { self.fg(Color::Black) } #[inline] pub fn red(self) -> StyledObject<D> { self.fg(Color::Red) } #[inline] pub fn green(self) -> StyledObject<D> { self.fg(Color::Green) } #[inline] pub fn yellow(self) -> StyledObject<D> { self.fg(Color::Yellow) } #[inline] pub fn blue(self) -> StyledObject<D> { self.fg(Color::Blue) } #[inline] pub fn magenta(self) -> StyledObject<D> { self.fg(Color::Magenta) } #[inline] pub fn cyan(self) -> StyledObject<D> { self.fg(Color::Cyan) } #[inline] pub fn white(self) -> StyledObject<D> { self.fg(Color::White) } #[inline] pub fn color256(self, color: u8) -> StyledObject<D> { self.fg(Color::Color256(color)) } #[inline] pub fn bright(mut self) -> StyledObject<D> { self.style = self.style.bright(); self } #[inline] pub fn on_black(self) -> StyledObject<D> { self.bg(Color::Black) } #[inline] pub fn on_red(self) -> StyledObject<D> { self.bg(Color::Red) } #[inline] pub fn on_green(self) -> StyledObject<D> { self.bg(Color::Green) } #[inline] pub fn on_yellow(self) -> StyledObject<D> { self.bg(Color::Yellow) } #[inline] pub fn on_blue(self) -> StyledObject<D> { self.bg(Color::Blue) } #[inline] pub fn on_magenta(self) -> StyledObject<D> { self.bg(Color::Magenta) } #[inline] pub fn on_cyan(self) -> StyledObject<D> { self.bg(Color::Cyan) } #[inline] pub fn on_white(self) -> StyledObject<D> { self.bg(Color::White) } #[inline] pub fn on_color256(self, color: u8) -> StyledObject<D> { self.bg(Color::Color256(color)) } #[inline] pub fn on_bright(mut self) -> StyledObject<D> { self.style = self.style.on_bright(); self } #[inline] pub fn bold(self) -> StyledObject<D> { self.attr(Attribute::Bold) } #[inline] pub fn dim(self) -> StyledObject<D> { self.attr(Attribute::Dim) } #[inline] pub fn italic(self) -> StyledObject<D> { self.attr(Attribute::Italic) } #[inline] pub fn underlined(self) -> StyledObject<D> { self.attr(Attribute::Underlined) } #[inline] pub fn blink(self) -> StyledObject<D> { self.attr(Attribute::Blink) } #[inline] pub fn blink_fast(self) -> StyledObject<D> { self.attr(Attribute::BlinkFast) } #[inline] pub fn reverse(self) -> StyledObject<D> { self.attr(Attribute::Reverse) } #[inline] pub fn hidden(self) -> StyledObject<D> { self.attr(Attribute::Hidden) } #[inline] pub fn strikethrough(self) -> StyledObject<D> { self.attr(Attribute::StrikeThrough) } } macro_rules! impl_fmt { ($name:ident) => { impl<D: fmt::$name> fmt::$name for StyledObject<D> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut reset = false; if self .style .force .unwrap_or_else(|| match self.style.for_stderr { true => colors_enabled_stderr(), false => colors_enabled(), }) { if let Some(fg) = self.style.fg { if fg.is_color256() { write!(f, "\x1b[38;5;{}m", fg.ansi_num())?; } else if self.style.fg_bright { write!(f, "\x1b[38;5;{}m", fg.ansi_num() + 8)?; } else { write!(f, "\x1b[{}m", fg.ansi_num() + 30)?; } reset = true; } if let Some(bg) = self.style.bg { if bg.is_color256() { write!(f, "\x1b[48;5;{}m", bg.ansi_num())?; } else if self.style.bg_bright { write!(f, "\x1b[48;5;{}m", bg.ansi_num() + 8)?; } else { write!(f, "\x1b[{}m", bg.ansi_num() + 40)?; } reset = true; } for attr in &self.style.attrs { write!(f, "\x1b[{}m", attr.ansi_num())?; reset = true; } } fmt::$name::fmt(&self.val, f)?; if reset { write!(f, "\x1b[0m")?; } Ok(()) } } }; } impl_fmt!(Binary); impl_fmt!(Debug); impl_fmt!(Display); impl_fmt!(LowerExp); impl_fmt!(LowerHex); impl_fmt!(Octal); impl_fmt!(Pointer); impl_fmt!(UpperExp); impl_fmt!(UpperHex); /// "Intelligent" emoji formatter. /// /// This struct intelligently wraps an emoji so that it is rendered /// only on systems that want emojis and renders a fallback on others. /// /// Example: /// /// ```rust /// use console::Emoji; /// println!("[3/4] {}Downloading ...", Emoji("🚚 ", "")); /// println!("[4/4] {} Done!", Emoji("✨", ":-)")); /// ``` #[derive(Copy, Clone)] pub struct Emoji<'a, 'b>(pub &'a str, pub &'b str); impl<'a, 'b> Emoji<'a, 'b> { pub fn new(emoji: &'a str, fallback: &'b str) -> Emoji<'a, 'b> { Emoji(emoji, fallback) } } impl<'a, 'b> fmt::Display for Emoji<'a, 'b> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if wants_emoji() { write!(f, "{}", self.0) } else { write!(f, "{}", self.1) } } } fn str_width(s: &str) -> usize { #[cfg(feature = "unicode-width")] { use unicode_width::UnicodeWidthStr; s.width() } #[cfg(not(feature = "unicode-width"))] { s.chars().count() } } #[cfg(feature = "ansi-parsing")] fn char_width(c: char) -> usize { #[cfg(feature = "unicode-width")] { use unicode_width::UnicodeWidthChar; c.width().unwrap_or(0) } #[cfg(not(feature = "unicode-width"))] { let _c = c; 1 } } /// Truncates a string to a certain number of characters. /// /// This ensures that escape codes are not screwed up in the process. /// If the maximum length is hit the string will be truncated but /// escapes code will still be honored. If truncation takes place /// the tail string will be appended. pub fn truncate_str<'a>(s: &'a str, width: usize, tail: &str) -> Cow<'a, str> { #[cfg(feature = "ansi-parsing")] { use std::cmp::Ordering; let mut iter = AnsiCodeIterator::new(s); let mut length = 0; let mut rv = None; while let Some(item) = iter.next() { match item { (s, false) => { if rv.is_none() { if str_width(s) + length > width - str_width(tail) { let ts = iter.current_slice(); let mut s_byte = 0; let mut s_width = 0; let rest_width = width - str_width(tail) - length; for c in s.chars() { s_byte += c.len_utf8(); s_width += char_width(c); match s_width.cmp(&rest_width) { Ordering::Equal => break, Ordering::Greater => { s_byte -= c.len_utf8(); break; } Ordering::Less => continue, } } let idx = ts.len() - s.len() + s_byte; let mut buf = ts[..idx].to_string(); buf.push_str(tail); rv = Some(buf); } length += str_width(s); } } (s, true) => { if rv.is_some() { rv.as_mut().unwrap().push_str(s); } } } } if let Some(buf) = rv { Cow::Owned(buf) } else { Cow::Borrowed(s) } } #[cfg(not(feature = "ansi-parsing"))] { if s.len() <= width - tail.len() { Cow::Borrowed(s) } else { Cow::Owned(format!( "{}{}", s.get(..width - tail.len()).unwrap_or_default(), tail )) } } } /// Pads a string to fill a certain number of characters. /// /// This will honor ansi codes correctly and allows you to align a string /// on the left, right or centered. Additionally truncation can be enabled /// by setting `truncate` to a string that should be used as a truncation /// marker. pub fn pad_str<'a>( s: &'a str, width: usize, align: Alignment, truncate: Option<&str>, ) -> Cow<'a, str> { pad_str_with(s, width, align, truncate, ' ') } /// Pads a string with specific padding to fill a certain number of characters. /// /// This will honor ansi codes correctly and allows you to align a string /// on the left, right or centered. Additionally truncation can be enabled /// by setting `truncate` to a string that should be used as a truncation /// marker. pub fn pad_str_with<'a>( s: &'a str, width: usize, align: Alignment, truncate: Option<&str>, pad: char, ) -> Cow<'a, str> { let cols = measure_text_width(s); if cols >= width { return match truncate { None => Cow::Borrowed(s), Some(tail) => truncate_str(s, width, tail), }; } let diff = width - cols; let (left_pad, right_pad) = match align { Alignment::Left => (0, diff), Alignment::Right => (diff, 0), Alignment::Center => (diff / 2, diff - diff / 2), }; let mut rv = String::new(); for _ in 0..left_pad { rv.push(pad); } rv.push_str(s); for _ in 0..right_pad { rv.push(pad); } Cow::Owned(rv) } #[test] fn test_text_width() { let s = style("foo") .red() .on_black() .bold() .force_styling(true) .to_string(); assert_eq!( measure_text_width(&s), if cfg!(feature = "ansi-parsing") { 3 } else if cfg!(feature = "unicode-width") { 17 } else { 21 } ); } #[test] #[cfg(all(feature = "unicode-width", feature = "ansi-parsing"))] fn test_truncate_str() { let s = format!("foo {}", style("bar").red().force_styling(true)); assert_eq!( &truncate_str(&s, 5, ""), &format!("foo {}", style("b").red().force_styling(true)) ); let s = format!("foo {}", style("bar").red().force_styling(true)); assert_eq!( &truncate_str(&s, 5, "!"), &format!("foo {}", style("!").red().force_styling(true)) ); let s = format!("foo {} baz", style("bar").red().force_styling(true)); assert_eq!( &truncate_str(&s, 10, "..."), &format!("foo {}...", style("bar").red().force_styling(true)) ); let s = format!("foo {}", style("バー").red().force_styling(true)); assert_eq!( &truncate_str(&s, 5, ""), &format!("foo {}", style("").red().force_styling(true)) ); let s = format!("foo {}", style("バー").red().force_styling(true)); assert_eq!( &truncate_str(&s, 6, ""), &format!("foo {}", style("バ").red().force_styling(true)) ); } #[test] fn test_truncate_str_no_ansi() { assert_eq!(&truncate_str("foo bar", 5, ""), "foo b"); assert_eq!(&truncate_str("foo bar", 5, "!"), "foo !"); assert_eq!(&truncate_str("foo bar baz", 10, "..."), "foo bar..."); } #[test] fn test_pad_str() { assert_eq!(pad_str("foo", 7, Alignment::Center, None), " foo "); assert_eq!(pad_str("foo", 7, Alignment::Left, None), "foo "); assert_eq!(pad_str("foo", 7, Alignment::Right, None), " foo"); assert_eq!(pad_str("foo", 3, Alignment::Left, None), "foo"); assert_eq!(pad_str("foobar", 3, Alignment::Left, None), "foobar"); assert_eq!(pad_str("foobar", 3, Alignment::Left, Some("")), "foo"); assert_eq!( pad_str("foobarbaz", 6, Alignment::Left, Some("...")), "foo..." ); } #[test] fn test_pad_str_with() { assert_eq!( pad_str_with("foo", 7, Alignment::Center, None, '#'), "##foo##" ); assert_eq!( pad_str_with("foo", 7, Alignment::Left, None, '#'), "foo####" ); assert_eq!( pad_str_with("foo", 7, Alignment::Right, None, '#'), "####foo" ); assert_eq!(pad_str_with("foo", 3, Alignment::Left, None, '#'), "foo"); assert_eq!( pad_str_with("foobar", 3, Alignment::Left, None, '#'), "foobar" ); assert_eq!( pad_str_with("foobar", 3, Alignment::Left, Some(""), '#'), "foo" ); assert_eq!( pad_str_with("foobarbaz", 6, Alignment::Left, Some("..."), '#'), "foo..." ); }
use sdl2::render::Texture; use sdl2::rect::{Point, Rect}; pub struct Sprite { pub texture: Texture } pub struct Transform { pub position: Point, pub size: Rect, pub scale: u32, } impl Transform { pub fn new(size: Rect, position: Point) -> Self { Transform { size, position, scale: 2 } } }
// use crate::webassembly::Memory; pub fn align_memory(ptr: u32) -> u32 { (ptr + 15) & !15 } // pub fn static_alloc(size: u32, static_top: &mut u32, memory: &Memory) -> u32 { // let old_static_top = *static_top; // let total_memory = memory.maximum_size() * Memory::PAGE_SIZE; // // NOTE: The `4294967280` is a u32 conversion of -16 as gotten from emscripten. // *static_top = (*static_top + size + 15) & 4294967280; // assert!( // *static_top < total_memory, // "not enough memory for static allocation - increase total_memory!" // ); // old_static_top // }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - CAN Control"] pub ctl: CTL, #[doc = "0x04 - CAN Status"] pub sts: STS, #[doc = "0x08 - CAN Error Counter"] pub err: ERR, #[doc = "0x0c - CAN Bit Timing"] pub bit_: BIT, #[doc = "0x10 - CAN Interrupt"] pub int: INT, #[doc = "0x14 - CAN Test"] pub tst: TST, #[doc = "0x18 - CAN Baud Rate Prescaler Extension"] pub brpe: BRPE, _reserved7: [u8; 4usize], #[doc = "0x20 - CAN IF1 Command Request"] pub if1crq: IF1CRQ, #[doc = "0x24 - CAN IF1 Command Mask"] pub if1cmsk: IF1CMSK, #[doc = "0x28 - CAN IF1 Mask 1"] pub if1msk1: IF1MSK1, #[doc = "0x2c - CAN IF1 Mask 2"] pub if1msk2: IF1MSK2, #[doc = "0x30 - CAN IF1 Arbitration 1"] pub if1arb1: IF1ARB1, #[doc = "0x34 - CAN IF1 Arbitration 2"] pub if1arb2: IF1ARB2, #[doc = "0x38 - CAN IF1 Message Control"] pub if1mctl: IF1MCTL, #[doc = "0x3c - CAN IF1 Data A1"] pub if1da1: IF1DA1, #[doc = "0x40 - CAN IF1 Data A2"] pub if1da2: IF1DA2, #[doc = "0x44 - CAN IF1 Data B1"] pub if1db1: IF1DB1, #[doc = "0x48 - CAN IF1 Data B2"] pub if1db2: IF1DB2, _reserved18: [u8; 52usize], #[doc = "0x80 - CAN IF2 Command Request"] pub if2crq: IF2CRQ, #[doc = "0x84 - CAN IF2 Command Mask"] pub if2cmsk: IF2CMSK, #[doc = "0x88 - CAN IF2 Mask 1"] pub if2msk1: IF2MSK1, #[doc = "0x8c - CAN IF2 Mask 2"] pub if2msk2: IF2MSK2, #[doc = "0x90 - CAN IF2 Arbitration 1"] pub if2arb1: IF2ARB1, #[doc = "0x94 - CAN IF2 Arbitration 2"] pub if2arb2: IF2ARB2, #[doc = "0x98 - CAN IF2 Message Control"] pub if2mctl: IF2MCTL, #[doc = "0x9c - CAN IF2 Data A1"] pub if2da1: IF2DA1, #[doc = "0xa0 - CAN IF2 Data A2"] pub if2da2: IF2DA2, #[doc = "0xa4 - CAN IF2 Data B1"] pub if2db1: IF2DB1, #[doc = "0xa8 - CAN IF2 Data B2"] pub if2db2: IF2DB2, _reserved29: [u8; 84usize], #[doc = "0x100 - CAN Transmission Request 1"] pub txrq1: TXRQ1, #[doc = "0x104 - CAN Transmission Request 2"] pub txrq2: TXRQ2, _reserved31: [u8; 24usize], #[doc = "0x120 - CAN New Data 1"] pub nwda1: NWDA1, #[doc = "0x124 - CAN New Data 2"] pub nwda2: NWDA2, _reserved33: [u8; 24usize], #[doc = "0x140 - CAN Message 1 Interrupt Pending"] pub msg1int: MSG1INT, #[doc = "0x144 - CAN Message 2 Interrupt Pending"] pub msg2int: MSG2INT, _reserved35: [u8; 24usize], #[doc = "0x160 - CAN Message 1 Valid"] pub msg1val: MSG1VAL, #[doc = "0x164 - CAN Message 2 Valid"] pub msg2val: MSG2VAL, } #[doc = "CAN Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ctl](ctl) module"] pub type CTL = crate::Reg<u32, _CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CTL; #[doc = "`read()` method returns [ctl::R](ctl::R) reader structure"] impl crate::Readable for CTL {} #[doc = "`write(|w| ..)` method takes [ctl::W](ctl::W) writer structure"] impl crate::Writable for CTL {} #[doc = "CAN Control"] pub mod ctl; #[doc = "CAN Status\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sts](sts) module"] pub type STS = crate::Reg<u32, _STS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _STS; #[doc = "`read()` method returns [sts::R](sts::R) reader structure"] impl crate::Readable for STS {} #[doc = "`write(|w| ..)` method takes [sts::W](sts::W) writer structure"] impl crate::Writable for STS {} #[doc = "CAN Status"] pub mod sts; #[doc = "CAN Error Counter\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [err](err) module"] pub type ERR = crate::Reg<u32, _ERR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ERR; #[doc = "`read()` method returns [err::R](err::R) reader structure"] impl crate::Readable for ERR {} #[doc = "CAN Error Counter"] pub mod err; #[doc = "CAN Bit Timing\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bit_](bit_) module"] pub type BIT = crate::Reg<u32, _BIT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _BIT; #[doc = "`read()` method returns [bit_::R](bit_::R) reader structure"] impl crate::Readable for BIT {} #[doc = "`write(|w| ..)` method takes [bit_::W](bit_::W) writer structure"] impl crate::Writable for BIT {} #[doc = "CAN Bit Timing"] pub mod bit_; #[doc = "CAN Interrupt\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [int](int) module"] pub type INT = crate::Reg<u32, _INT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INT; #[doc = "`read()` method returns [int::R](int::R) reader structure"] impl crate::Readable for INT {} #[doc = "CAN Interrupt"] pub mod int; #[doc = "CAN Test\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [tst](tst) module"] pub type TST = crate::Reg<u32, _TST>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TST; #[doc = "`read()` method returns [tst::R](tst::R) reader structure"] impl crate::Readable for TST {} #[doc = "`write(|w| ..)` method takes [tst::W](tst::W) writer structure"] impl crate::Writable for TST {} #[doc = "CAN Test"] pub mod tst; #[doc = "CAN Baud Rate Prescaler Extension\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [brpe](brpe) module"] pub type BRPE = crate::Reg<u32, _BRPE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _BRPE; #[doc = "`read()` method returns [brpe::R](brpe::R) reader structure"] impl crate::Readable for BRPE {} #[doc = "`write(|w| ..)` method takes [brpe::W](brpe::W) writer structure"] impl crate::Writable for BRPE {} #[doc = "CAN Baud Rate Prescaler Extension"] pub mod brpe; #[doc = "CAN IF1 Command Request\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if1crq](if1crq) module"] pub type IF1CRQ = crate::Reg<u32, _IF1CRQ>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF1CRQ; #[doc = "`read()` method returns [if1crq::R](if1crq::R) reader structure"] impl crate::Readable for IF1CRQ {} #[doc = "`write(|w| ..)` method takes [if1crq::W](if1crq::W) writer structure"] impl crate::Writable for IF1CRQ {} #[doc = "CAN IF1 Command Request"] pub mod if1crq; #[doc = "CAN IF1 Command Mask\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if1cmsk](if1cmsk) module"] pub type IF1CMSK = crate::Reg<u32, _IF1CMSK>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF1CMSK; #[doc = "`read()` method returns [if1cmsk::R](if1cmsk::R) reader structure"] impl crate::Readable for IF1CMSK {} #[doc = "`write(|w| ..)` method takes [if1cmsk::W](if1cmsk::W) writer structure"] impl crate::Writable for IF1CMSK {} #[doc = "CAN IF1 Command Mask"] pub mod if1cmsk; #[doc = "CAN IF1 Mask 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if1msk1](if1msk1) module"] pub type IF1MSK1 = crate::Reg<u32, _IF1MSK1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF1MSK1; #[doc = "`read()` method returns [if1msk1::R](if1msk1::R) reader structure"] impl crate::Readable for IF1MSK1 {} #[doc = "`write(|w| ..)` method takes [if1msk1::W](if1msk1::W) writer structure"] impl crate::Writable for IF1MSK1 {} #[doc = "CAN IF1 Mask 1"] pub mod if1msk1; #[doc = "CAN IF1 Mask 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if1msk2](if1msk2) module"] pub type IF1MSK2 = crate::Reg<u32, _IF1MSK2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF1MSK2; #[doc = "`read()` method returns [if1msk2::R](if1msk2::R) reader structure"] impl crate::Readable for IF1MSK2 {} #[doc = "`write(|w| ..)` method takes [if1msk2::W](if1msk2::W) writer structure"] impl crate::Writable for IF1MSK2 {} #[doc = "CAN IF1 Mask 2"] pub mod if1msk2; #[doc = "CAN IF1 Arbitration 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if1arb1](if1arb1) module"] pub type IF1ARB1 = crate::Reg<u32, _IF1ARB1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF1ARB1; #[doc = "`read()` method returns [if1arb1::R](if1arb1::R) reader structure"] impl crate::Readable for IF1ARB1 {} #[doc = "`write(|w| ..)` method takes [if1arb1::W](if1arb1::W) writer structure"] impl crate::Writable for IF1ARB1 {} #[doc = "CAN IF1 Arbitration 1"] pub mod if1arb1; #[doc = "CAN IF1 Arbitration 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if1arb2](if1arb2) module"] pub type IF1ARB2 = crate::Reg<u32, _IF1ARB2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF1ARB2; #[doc = "`read()` method returns [if1arb2::R](if1arb2::R) reader structure"] impl crate::Readable for IF1ARB2 {} #[doc = "`write(|w| ..)` method takes [if1arb2::W](if1arb2::W) writer structure"] impl crate::Writable for IF1ARB2 {} #[doc = "CAN IF1 Arbitration 2"] pub mod if1arb2; #[doc = "CAN IF1 Message Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if1mctl](if1mctl) module"] pub type IF1MCTL = crate::Reg<u32, _IF1MCTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF1MCTL; #[doc = "`read()` method returns [if1mctl::R](if1mctl::R) reader structure"] impl crate::Readable for IF1MCTL {} #[doc = "`write(|w| ..)` method takes [if1mctl::W](if1mctl::W) writer structure"] impl crate::Writable for IF1MCTL {} #[doc = "CAN IF1 Message Control"] pub mod if1mctl; #[doc = "CAN IF1 Data A1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if1da1](if1da1) module"] pub type IF1DA1 = crate::Reg<u32, _IF1DA1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF1DA1; #[doc = "`read()` method returns [if1da1::R](if1da1::R) reader structure"] impl crate::Readable for IF1DA1 {} #[doc = "`write(|w| ..)` method takes [if1da1::W](if1da1::W) writer structure"] impl crate::Writable for IF1DA1 {} #[doc = "CAN IF1 Data A1"] pub mod if1da1; #[doc = "CAN IF1 Data A2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if1da2](if1da2) module"] pub type IF1DA2 = crate::Reg<u32, _IF1DA2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF1DA2; #[doc = "`read()` method returns [if1da2::R](if1da2::R) reader structure"] impl crate::Readable for IF1DA2 {} #[doc = "`write(|w| ..)` method takes [if1da2::W](if1da2::W) writer structure"] impl crate::Writable for IF1DA2 {} #[doc = "CAN IF1 Data A2"] pub mod if1da2; #[doc = "CAN IF1 Data B1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if1db1](if1db1) module"] pub type IF1DB1 = crate::Reg<u32, _IF1DB1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF1DB1; #[doc = "`read()` method returns [if1db1::R](if1db1::R) reader structure"] impl crate::Readable for IF1DB1 {} #[doc = "`write(|w| ..)` method takes [if1db1::W](if1db1::W) writer structure"] impl crate::Writable for IF1DB1 {} #[doc = "CAN IF1 Data B1"] pub mod if1db1; #[doc = "CAN IF1 Data B2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if1db2](if1db2) module"] pub type IF1DB2 = crate::Reg<u32, _IF1DB2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF1DB2; #[doc = "`read()` method returns [if1db2::R](if1db2::R) reader structure"] impl crate::Readable for IF1DB2 {} #[doc = "`write(|w| ..)` method takes [if1db2::W](if1db2::W) writer structure"] impl crate::Writable for IF1DB2 {} #[doc = "CAN IF1 Data B2"] pub mod if1db2; #[doc = "CAN IF2 Command Request\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if2crq](if2crq) module"] pub type IF2CRQ = crate::Reg<u32, _IF2CRQ>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF2CRQ; #[doc = "`read()` method returns [if2crq::R](if2crq::R) reader structure"] impl crate::Readable for IF2CRQ {} #[doc = "`write(|w| ..)` method takes [if2crq::W](if2crq::W) writer structure"] impl crate::Writable for IF2CRQ {} #[doc = "CAN IF2 Command Request"] pub mod if2crq; #[doc = "CAN IF2 Command Mask\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if2cmsk](if2cmsk) module"] pub type IF2CMSK = crate::Reg<u32, _IF2CMSK>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF2CMSK; #[doc = "`read()` method returns [if2cmsk::R](if2cmsk::R) reader structure"] impl crate::Readable for IF2CMSK {} #[doc = "`write(|w| ..)` method takes [if2cmsk::W](if2cmsk::W) writer structure"] impl crate::Writable for IF2CMSK {} #[doc = "CAN IF2 Command Mask"] pub mod if2cmsk; #[doc = "CAN IF2 Mask 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if2msk1](if2msk1) module"] pub type IF2MSK1 = crate::Reg<u32, _IF2MSK1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF2MSK1; #[doc = "`read()` method returns [if2msk1::R](if2msk1::R) reader structure"] impl crate::Readable for IF2MSK1 {} #[doc = "`write(|w| ..)` method takes [if2msk1::W](if2msk1::W) writer structure"] impl crate::Writable for IF2MSK1 {} #[doc = "CAN IF2 Mask 1"] pub mod if2msk1; #[doc = "CAN IF2 Mask 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if2msk2](if2msk2) module"] pub type IF2MSK2 = crate::Reg<u32, _IF2MSK2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF2MSK2; #[doc = "`read()` method returns [if2msk2::R](if2msk2::R) reader structure"] impl crate::Readable for IF2MSK2 {} #[doc = "`write(|w| ..)` method takes [if2msk2::W](if2msk2::W) writer structure"] impl crate::Writable for IF2MSK2 {} #[doc = "CAN IF2 Mask 2"] pub mod if2msk2; #[doc = "CAN IF2 Arbitration 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if2arb1](if2arb1) module"] pub type IF2ARB1 = crate::Reg<u32, _IF2ARB1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF2ARB1; #[doc = "`read()` method returns [if2arb1::R](if2arb1::R) reader structure"] impl crate::Readable for IF2ARB1 {} #[doc = "`write(|w| ..)` method takes [if2arb1::W](if2arb1::W) writer structure"] impl crate::Writable for IF2ARB1 {} #[doc = "CAN IF2 Arbitration 1"] pub mod if2arb1; #[doc = "CAN IF2 Arbitration 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if2arb2](if2arb2) module"] pub type IF2ARB2 = crate::Reg<u32, _IF2ARB2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF2ARB2; #[doc = "`read()` method returns [if2arb2::R](if2arb2::R) reader structure"] impl crate::Readable for IF2ARB2 {} #[doc = "`write(|w| ..)` method takes [if2arb2::W](if2arb2::W) writer structure"] impl crate::Writable for IF2ARB2 {} #[doc = "CAN IF2 Arbitration 2"] pub mod if2arb2; #[doc = "CAN IF2 Message Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if2mctl](if2mctl) module"] pub type IF2MCTL = crate::Reg<u32, _IF2MCTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF2MCTL; #[doc = "`read()` method returns [if2mctl::R](if2mctl::R) reader structure"] impl crate::Readable for IF2MCTL {} #[doc = "`write(|w| ..)` method takes [if2mctl::W](if2mctl::W) writer structure"] impl crate::Writable for IF2MCTL {} #[doc = "CAN IF2 Message Control"] pub mod if2mctl; #[doc = "CAN IF2 Data A1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if2da1](if2da1) module"] pub type IF2DA1 = crate::Reg<u32, _IF2DA1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF2DA1; #[doc = "`read()` method returns [if2da1::R](if2da1::R) reader structure"] impl crate::Readable for IF2DA1 {} #[doc = "`write(|w| ..)` method takes [if2da1::W](if2da1::W) writer structure"] impl crate::Writable for IF2DA1 {} #[doc = "CAN IF2 Data A1"] pub mod if2da1; #[doc = "CAN IF2 Data A2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if2da2](if2da2) module"] pub type IF2DA2 = crate::Reg<u32, _IF2DA2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF2DA2; #[doc = "`read()` method returns [if2da2::R](if2da2::R) reader structure"] impl crate::Readable for IF2DA2 {} #[doc = "`write(|w| ..)` method takes [if2da2::W](if2da2::W) writer structure"] impl crate::Writable for IF2DA2 {} #[doc = "CAN IF2 Data A2"] pub mod if2da2; #[doc = "CAN IF2 Data B1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if2db1](if2db1) module"] pub type IF2DB1 = crate::Reg<u32, _IF2DB1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF2DB1; #[doc = "`read()` method returns [if2db1::R](if2db1::R) reader structure"] impl crate::Readable for IF2DB1 {} #[doc = "`write(|w| ..)` method takes [if2db1::W](if2db1::W) writer structure"] impl crate::Writable for IF2DB1 {} #[doc = "CAN IF2 Data B1"] pub mod if2db1; #[doc = "CAN IF2 Data B2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [if2db2](if2db2) module"] pub type IF2DB2 = crate::Reg<u32, _IF2DB2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IF2DB2; #[doc = "`read()` method returns [if2db2::R](if2db2::R) reader structure"] impl crate::Readable for IF2DB2 {} #[doc = "`write(|w| ..)` method takes [if2db2::W](if2db2::W) writer structure"] impl crate::Writable for IF2DB2 {} #[doc = "CAN IF2 Data B2"] pub mod if2db2; #[doc = "CAN Transmission Request 1\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [txrq1](txrq1) module"] pub type TXRQ1 = crate::Reg<u32, _TXRQ1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TXRQ1; #[doc = "`read()` method returns [txrq1::R](txrq1::R) reader structure"] impl crate::Readable for TXRQ1 {} #[doc = "CAN Transmission Request 1"] pub mod txrq1; #[doc = "CAN Transmission Request 2\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [txrq2](txrq2) module"] pub type TXRQ2 = crate::Reg<u32, _TXRQ2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TXRQ2; #[doc = "`read()` method returns [txrq2::R](txrq2::R) reader structure"] impl crate::Readable for TXRQ2 {} #[doc = "CAN Transmission Request 2"] pub mod txrq2; #[doc = "CAN New Data 1\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [nwda1](nwda1) module"] pub type NWDA1 = crate::Reg<u32, _NWDA1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _NWDA1; #[doc = "`read()` method returns [nwda1::R](nwda1::R) reader structure"] impl crate::Readable for NWDA1 {} #[doc = "CAN New Data 1"] pub mod nwda1; #[doc = "CAN New Data 2\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [nwda2](nwda2) module"] pub type NWDA2 = crate::Reg<u32, _NWDA2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _NWDA2; #[doc = "`read()` method returns [nwda2::R](nwda2::R) reader structure"] impl crate::Readable for NWDA2 {} #[doc = "CAN New Data 2"] pub mod nwda2; #[doc = "CAN Message 1 Interrupt Pending\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [msg1int](msg1int) module"] pub type MSG1INT = crate::Reg<u32, _MSG1INT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MSG1INT; #[doc = "`read()` method returns [msg1int::R](msg1int::R) reader structure"] impl crate::Readable for MSG1INT {} #[doc = "CAN Message 1 Interrupt Pending"] pub mod msg1int; #[doc = "CAN Message 2 Interrupt Pending\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [msg2int](msg2int) module"] pub type MSG2INT = crate::Reg<u32, _MSG2INT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MSG2INT; #[doc = "`read()` method returns [msg2int::R](msg2int::R) reader structure"] impl crate::Readable for MSG2INT {} #[doc = "CAN Message 2 Interrupt Pending"] pub mod msg2int; #[doc = "CAN Message 1 Valid\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [msg1val](msg1val) module"] pub type MSG1VAL = crate::Reg<u32, _MSG1VAL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MSG1VAL; #[doc = "`read()` method returns [msg1val::R](msg1val::R) reader structure"] impl crate::Readable for MSG1VAL {} #[doc = "CAN Message 1 Valid"] pub mod msg1val; #[doc = "CAN Message 2 Valid\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [msg2val](msg2val) module"] pub type MSG2VAL = crate::Reg<u32, _MSG2VAL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MSG2VAL; #[doc = "`read()` method returns [msg2val::R](msg2val::R) reader structure"] impl crate::Readable for MSG2VAL {} #[doc = "CAN Message 2 Valid"] pub mod msg2val;
use piston::window::Size; use graphics::*; use gfx_graphics::GfxGraphics; use gfx::{Resources, CommandBuffer}; use errors::*; // a full screen of information laid out using standard units pub struct Screen { dimensions: [usize; 2], } impl Screen { pub fn new(size: Size) -> Self { Self { dimensions: [size.width as usize, size.height as usize] } } pub fn render<R: Resources, C: CommandBuffer<R>>( &self, c: &Context, g: &mut GfxGraphics<R, C>, ) -> Box<FnOnce(Context, &mut GfxGraphics<R, C>) -> ()> { unimplemented!(); } }
//============================================================================== // Notes //============================================================================== // mcu::spi.rs //============================================================================== // Crates and Mods //============================================================================== use core::cell::RefCell; use core::ops::DerefMut; use core::ptr; use cortex_m::interrupt::{free, Mutex}; use nrf52832_pac::spim0; use crate::config; use crate::mcu::gpio; use nrf52832_pac::p0::pin_cnf::DIR_A as DIR; use nrf52832_pac::p0::pin_cnf::PULL_A as PULL; //============================================================================== // Enums, Structs, and Types //============================================================================== pub struct SpiLine{ pub sclk_pin: u8, pub mosi_pin: u8, pub miso_pin: u8, pub frequency: spim0::frequency::FREQUENCY_A, pub order: spim0::config::ORDER_A, pub cpha: spim0::config::CPHA_A, pub cpol: spim0::config::CPOL_A } pub enum SpimError{ Handler, Receive, Transmit, } //============================================================================== // Variables //============================================================================== const SPIM_LINE: SpiLine = SpiLine { sclk_pin: config::SPI_SCLK_PIN, mosi_pin: config::SPI_MOSI_PIN, miso_pin: config::SPI_MISO_PIN, frequency: config::SPIM_FREQUENCY, order: config::SPIM_ORDER, cpha: config::SPIM_CPHA, cpol: config::SPIM_CPOL, }; static SPIM_HANDLE: Mutex<RefCell<Option<nrf52832_pac::SPIM0>>> = Mutex::new(RefCell::new(None)); //============================================================================== // Public Functions //============================================================================== pub fn init(spim0: nrf52832_pac::SPIM0) { configure(&spim0); free(|cs| SPIM_HANDLE.borrow(cs).replace(Some(spim0))); } #[allow(dead_code)] pub fn write(tx_block: &[u8]) -> Result<(), SpimError> { let rx_ptr = config::SPIM_DMA_RX_PTR; let (tx_ptr, len) = make_ram(tx_block); free(|cs| { if let Some(ref mut spim) = SPIM_HANDLE.borrow(cs).borrow_mut().deref_mut() { spim.enable.write(|w| w.enable().enabled()); // Setup the DMA transfer spim.txd.ptr.write(|w| unsafe { w.ptr().bits(tx_ptr) }); spim.txd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as u8) }); spim.rxd.ptr.write(|w| unsafe { w.ptr().bits(rx_ptr) }); spim.rxd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as u8) }); // Clear the end flag in case it wasn't properly cleared last time spim.events_end.write(|w| unsafe { w.bits(0) }); // Start SPI transaction. spim.tasks_start.write(|w| unsafe { w.bits(1) }); // Wait for END event - triggered when tx and rx are done while spim.events_end.read().bits() == 0 {} // Clear the end flag spim.events_end.write(|w| unsafe { w.bits(0) }); if spim.txd.amount.read().bits() != len { return Err(SpimError::Transmit); } if spim.rxd.amount.read().bits() != len { return Err(SpimError::Receive); } spim.enable.write(|w| w.enable().disabled()); gpio::set_pin_state(config::SPI_SCLK_PIN, gpio::PinState::PinHigh); Ok(()) } else { Err(SpimError::Handler) } }) } //============================================================================== // Private Functions //============================================================================== fn configure(spim: &nrf52832_pac::SPIM0) { spim.enable.write(|w| w.enable().disabled()); // Configure SCLK pin gpio::pin_setup(SPIM_LINE.sclk_pin, DIR::OUTPUT, gpio::PinState::PinLow, PULL::DISABLED); spim.psel.sck.write(|w| unsafe { w.bits(SPIM_LINE.sclk_pin as u32) }); // Configure MISO pin gpio::pin_setup(SPIM_LINE.miso_pin, DIR::INPUT, gpio::PinState::PinHigh, PULL::PULLUP); spim.psel.miso.write(|w| unsafe { w.bits(SPIM_LINE.miso_pin as u32) }); // Configure MOSI pin gpio::pin_setup(SPIM_LINE.mosi_pin, DIR::OUTPUT, gpio::PinState::PinLow, PULL::DISABLED); spim.psel.mosi.write(|w| unsafe { w.bits(SPIM_LINE.mosi_pin as u32) }); spim.frequency.write(|w| w.frequency().variant(SPIM_LINE.frequency)); spim.config.write(|w| w .order().variant(SPIM_LINE.order) .cpha().variant(SPIM_LINE.cpha) .cpol().variant(SPIM_LINE.cpol) ); // Ensure we are using the ArrayList structure spim.rxd.list.write(|w| w.list().variant(nrf52832_pac::spim0::rxd::list::LIST_A::ARRAYLIST)); spim.txd.list.write(|w| w.list().variant(nrf52832_pac::spim0::txd::list::LIST_A::ARRAYLIST)); } fn get_tx_ptr() -> u32 { static mut LAST_PTR: bool = true; unsafe { if LAST_PTR { LAST_PTR = false; config::SPIM_DMA_TX_PTR_A } else { LAST_PTR = false; config::SPIM_DMA_TX_PTR_B } } } fn is_block_valid(ptr: u32) -> bool { if (ptr >= config::SPIM_DMA_MIN) && (ptr < (config::SPIM_DMA_MAX - config::SPIM_DMA_SIZE)) { true } else { false } } fn make_ram(block: &[u8]) -> (u32, u32) { let len = block.len(); if !is_block_valid(block.as_ptr() as u32) { let ptr = get_tx_ptr() as usize; unsafe { for i in 0..len { ptr::write((ptr+i) as *mut u8, block[i]); } } (ptr as u32, len as u32) } else { (block.as_ptr() as u32, len as u32) } } //============================================================================== // Interrupt Handler //============================================================================== //============================================================================== // Task Handler //==============================================================================
macro_rules! heap_object_impls { ($type:ty) => { impl TryFrom<$crate::heap::object_heap::HeapObject> for $type { type Error = &'static str; fn try_from(value: $crate::heap::object_heap::HeapObject) -> Result<Self, Self::Error> { $crate::heap::object_heap::HeapData::from(value).try_into() } } impl From<$type> for $crate::heap::object_heap::HeapObject { fn from(value: $type) -> Self { *value } } impl From<$type> for $crate::heap::object_inline::InlineObject { fn from(value: $type) -> Self { (*value).into() } } }; } pub(super) use heap_object_impls;
use std::io; fn main() { let mut reader = io::stdin(); let mut input = String::new(); println!("Which number of the fibonacci sequence would you like to calculate?"); reader.read_line(&mut input).ok().expect("failed to read line"); let input_opt: Option<u32> = input.trim().parse::<u32>().ok(); let input_u = match input_opt { Some(input_u) => input_u, None => { println!("Please input a positive integer"); return; } }; println!("{}", fibonacci(input_u)); } fn fibonacci(n: u32) -> u32 { if n == 0 { return 0; } else if n == 1 { return 1; } else { fibonacci(n - 1) + fibonacci(n - 2) } }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fmt::Display; use std::fmt::Formatter; use common_exception::Result; use num_derive::FromPrimitive; use num_derive::ToPrimitive; use crate::optimizer::rule::TransformResult; use crate::optimizer::SExpr; pub type RulePtr = Box<dyn Rule>; pub trait Rule { fn id(&self) -> RuleID; fn apply(&self, s_expr: &SExpr, state: &mut TransformResult) -> Result<()>; fn pattern(&self) -> &SExpr; fn transformation(&self) -> bool { true } } // If add a new rule, please add it to the operator's corresponding `transformation_candidate_rules` // Such as `PushDownFilterAggregate` is related to `Filter` operator. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, FromPrimitive, ToPrimitive)] pub enum RuleID { // Rewrite rules NormalizeScalarFilter, NormalizeDisjunctiveFilter, PushDownFilterAggregate, PushDownFilterEvalScalar, PushDownFilterUnion, PushDownFilterJoin, PushDownFilterScan, PushDownFilterSort, PushDownLimitUnion, PushDownLimitOuterJoin, RulePushDownLimitExpression, PushDownLimitSort, PushDownLimitAggregate, PushDownLimitScan, PushDownSortScan, EliminateEvalScalar, EliminateFilter, MergeEvalScalar, MergeFilter, SplitAggregate, FoldCountAggregate, PushDownPrewhere, // Exploration rules CommuteJoin, RightAssociateJoin, LeftAssociateJoin, ExchangeJoin, CommuteJoinBaseTable, LeftExchangeJoin, RightExchangeJoin, } impl Display for RuleID { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { RuleID::PushDownFilterUnion => write!(f, "PushDownFilterUnion"), RuleID::PushDownFilterEvalScalar => write!(f, "PushDownFilterEvalScalar"), RuleID::PushDownFilterJoin => write!(f, "PushDownFilterJoin"), RuleID::PushDownFilterScan => write!(f, "PushDownFilterScan"), RuleID::PushDownFilterSort => write!(f, "PushDownFilterSort"), RuleID::PushDownLimitUnion => write!(f, "PushDownLimitUnion"), RuleID::PushDownLimitOuterJoin => write!(f, "PushDownLimitOuterJoin"), RuleID::RulePushDownLimitExpression => write!(f, "PushDownLimitExpression"), RuleID::PushDownLimitSort => write!(f, "PushDownLimitSort"), RuleID::PushDownLimitAggregate => write!(f, "PushDownLimitAggregate"), RuleID::PushDownFilterAggregate => write!(f, "PushDownFilterAggregate"), RuleID::PushDownLimitScan => write!(f, "PushDownLimitScan"), RuleID::PushDownSortScan => write!(f, "PushDownSortScan"), RuleID::EliminateEvalScalar => write!(f, "EliminateEvalScalar"), RuleID::EliminateFilter => write!(f, "EliminateFilter"), RuleID::MergeEvalScalar => write!(f, "MergeEvalScalar"), RuleID::MergeFilter => write!(f, "MergeFilter"), RuleID::NormalizeScalarFilter => write!(f, "NormalizeScalarFilter"), RuleID::SplitAggregate => write!(f, "SplitAggregate"), RuleID::NormalizeDisjunctiveFilter => write!(f, "NormalizeDisjunctiveFilter"), RuleID::FoldCountAggregate => write!(f, "FoldCountAggregate"), RuleID::PushDownPrewhere => write!(f, "PushDownPrewhere"), RuleID::CommuteJoin => write!(f, "CommuteJoin"), RuleID::CommuteJoinBaseTable => write!(f, "CommuteJoinBaseTable"), RuleID::LeftAssociateJoin => write!(f, "LeftAssociateJoin"), RuleID::RightAssociateJoin => write!(f, "RightAssociateJoin"), RuleID::LeftExchangeJoin => write!(f, "LeftExchangeJoin"), RuleID::RightExchangeJoin => write!(f, "RightExchangeJoin"), RuleID::ExchangeJoin => write!(f, "ExchangeJoin"), } } }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtGui/qinputmethod.h // dst-file: /src/gui/qinputmethod.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::super::core::qobject::*; // 771 use std::ops::Deref; use super::super::core::qrect::*; // 771 use super::super::core::qobjectdefs::*; // 771 use super::qtransform::*; // 773 use super::super::core::qvariant::*; // 771 use super::super::core::qlocale::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QInputMethod_Class_Size() -> c_int; // proto: QRectF QInputMethod::inputItemRectangle(); fn C_ZNK12QInputMethod18inputItemRectangleEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: const QMetaObject * QInputMethod::metaObject(); fn C_ZNK12QInputMethod10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QTransform QInputMethod::inputItemTransform(); fn C_ZNK12QInputMethod18inputItemTransformEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QInputMethod::hide(); fn C_ZN12QInputMethod4hideEv(qthis: u64 /* *mut c_void*/); // proto: QRectF QInputMethod::keyboardRectangle(); fn C_ZNK12QInputMethod17keyboardRectangleEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QInputMethod::show(); fn C_ZN12QInputMethod4showEv(qthis: u64 /* *mut c_void*/); // proto: bool QInputMethod::isAnimating(); fn C_ZNK12QInputMethod11isAnimatingEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QInputMethod::setVisible(bool visible); fn C_ZN12QInputMethod10setVisibleEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: void QInputMethod::setInputItemRectangle(const QRectF & rect); fn C_ZN12QInputMethod21setInputItemRectangleERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QInputMethod::commit(); fn C_ZN12QInputMethod6commitEv(qthis: u64 /* *mut c_void*/); // proto: void QInputMethod::setInputItemTransform(const QTransform & transform); fn C_ZN12QInputMethod21setInputItemTransformERK10QTransform(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QRectF QInputMethod::cursorRectangle(); fn C_ZNK12QInputMethod15cursorRectangleEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QInputMethod::isVisible(); fn C_ZNK12QInputMethod9isVisibleEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QLocale QInputMethod::locale(); fn C_ZNK12QInputMethod6localeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QInputMethod::reset(); fn C_ZN12QInputMethod5resetEv(qthis: u64 /* *mut c_void*/); fn QInputMethod_SlotProxy_connect__ZN12QInputMethod22cursorRectangleChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QInputMethod_SlotProxy_connect__ZN12QInputMethod13localeChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QInputMethod_SlotProxy_connect__ZN12QInputMethod14visibleChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QInputMethod_SlotProxy_connect__ZN12QInputMethod24keyboardRectangleChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QInputMethod_SlotProxy_connect__ZN12QInputMethod16animatingChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QInputMethod)=1 #[derive(Default)] pub struct QInputMethod { qbase: QObject, pub qclsinst: u64 /* *mut c_void*/, pub _cursorRectangleChanged: QInputMethod_cursorRectangleChanged_signal, pub _localeChanged: QInputMethod_localeChanged_signal, pub _inputDirectionChanged: QInputMethod_inputDirectionChanged_signal, pub _animatingChanged: QInputMethod_animatingChanged_signal, pub _keyboardRectangleChanged: QInputMethod_keyboardRectangleChanged_signal, pub _visibleChanged: QInputMethod_visibleChanged_signal, } impl /*struct*/ QInputMethod { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QInputMethod { return QInputMethod{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QInputMethod { type Target = QObject; fn deref(&self) -> &QObject { return & self.qbase; } } impl AsRef<QObject> for QInputMethod { fn as_ref(& self) -> & QObject { return & self.qbase; } } // proto: QRectF QInputMethod::inputItemRectangle(); impl /*struct*/ QInputMethod { pub fn inputItemRectangle<RetType, T: QInputMethod_inputItemRectangle<RetType>>(& self, overload_args: T) -> RetType { return overload_args.inputItemRectangle(self); // return 1; } } pub trait QInputMethod_inputItemRectangle<RetType> { fn inputItemRectangle(self , rsthis: & QInputMethod) -> RetType; } // proto: QRectF QInputMethod::inputItemRectangle(); impl<'a> /*trait*/ QInputMethod_inputItemRectangle<QRectF> for () { fn inputItemRectangle(self , rsthis: & QInputMethod) -> QRectF { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QInputMethod18inputItemRectangleEv()}; let mut ret = unsafe {C_ZNK12QInputMethod18inputItemRectangleEv(rsthis.qclsinst)}; let mut ret1 = QRectF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: const QMetaObject * QInputMethod::metaObject(); impl /*struct*/ QInputMethod { pub fn metaObject<RetType, T: QInputMethod_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QInputMethod_metaObject<RetType> { fn metaObject(self , rsthis: & QInputMethod) -> RetType; } // proto: const QMetaObject * QInputMethod::metaObject(); impl<'a> /*trait*/ QInputMethod_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QInputMethod) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QInputMethod10metaObjectEv()}; let mut ret = unsafe {C_ZNK12QInputMethod10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QTransform QInputMethod::inputItemTransform(); impl /*struct*/ QInputMethod { pub fn inputItemTransform<RetType, T: QInputMethod_inputItemTransform<RetType>>(& self, overload_args: T) -> RetType { return overload_args.inputItemTransform(self); // return 1; } } pub trait QInputMethod_inputItemTransform<RetType> { fn inputItemTransform(self , rsthis: & QInputMethod) -> RetType; } // proto: QTransform QInputMethod::inputItemTransform(); impl<'a> /*trait*/ QInputMethod_inputItemTransform<QTransform> for () { fn inputItemTransform(self , rsthis: & QInputMethod) -> QTransform { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QInputMethod18inputItemTransformEv()}; let mut ret = unsafe {C_ZNK12QInputMethod18inputItemTransformEv(rsthis.qclsinst)}; let mut ret1 = QTransform::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QInputMethod::hide(); impl /*struct*/ QInputMethod { pub fn hide<RetType, T: QInputMethod_hide<RetType>>(& self, overload_args: T) -> RetType { return overload_args.hide(self); // return 1; } } pub trait QInputMethod_hide<RetType> { fn hide(self , rsthis: & QInputMethod) -> RetType; } // proto: void QInputMethod::hide(); impl<'a> /*trait*/ QInputMethod_hide<()> for () { fn hide(self , rsthis: & QInputMethod) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QInputMethod4hideEv()}; unsafe {C_ZN12QInputMethod4hideEv(rsthis.qclsinst)}; // return 1; } } // proto: QRectF QInputMethod::keyboardRectangle(); impl /*struct*/ QInputMethod { pub fn keyboardRectangle<RetType, T: QInputMethod_keyboardRectangle<RetType>>(& self, overload_args: T) -> RetType { return overload_args.keyboardRectangle(self); // return 1; } } pub trait QInputMethod_keyboardRectangle<RetType> { fn keyboardRectangle(self , rsthis: & QInputMethod) -> RetType; } // proto: QRectF QInputMethod::keyboardRectangle(); impl<'a> /*trait*/ QInputMethod_keyboardRectangle<QRectF> for () { fn keyboardRectangle(self , rsthis: & QInputMethod) -> QRectF { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QInputMethod17keyboardRectangleEv()}; let mut ret = unsafe {C_ZNK12QInputMethod17keyboardRectangleEv(rsthis.qclsinst)}; let mut ret1 = QRectF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QInputMethod::show(); impl /*struct*/ QInputMethod { pub fn show<RetType, T: QInputMethod_show<RetType>>(& self, overload_args: T) -> RetType { return overload_args.show(self); // return 1; } } pub trait QInputMethod_show<RetType> { fn show(self , rsthis: & QInputMethod) -> RetType; } // proto: void QInputMethod::show(); impl<'a> /*trait*/ QInputMethod_show<()> for () { fn show(self , rsthis: & QInputMethod) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QInputMethod4showEv()}; unsafe {C_ZN12QInputMethod4showEv(rsthis.qclsinst)}; // return 1; } } // proto: bool QInputMethod::isAnimating(); impl /*struct*/ QInputMethod { pub fn isAnimating<RetType, T: QInputMethod_isAnimating<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isAnimating(self); // return 1; } } pub trait QInputMethod_isAnimating<RetType> { fn isAnimating(self , rsthis: & QInputMethod) -> RetType; } // proto: bool QInputMethod::isAnimating(); impl<'a> /*trait*/ QInputMethod_isAnimating<i8> for () { fn isAnimating(self , rsthis: & QInputMethod) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QInputMethod11isAnimatingEv()}; let mut ret = unsafe {C_ZNK12QInputMethod11isAnimatingEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QInputMethod::setVisible(bool visible); impl /*struct*/ QInputMethod { pub fn setVisible<RetType, T: QInputMethod_setVisible<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setVisible(self); // return 1; } } pub trait QInputMethod_setVisible<RetType> { fn setVisible(self , rsthis: & QInputMethod) -> RetType; } // proto: void QInputMethod::setVisible(bool visible); impl<'a> /*trait*/ QInputMethod_setVisible<()> for (i8) { fn setVisible(self , rsthis: & QInputMethod) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QInputMethod10setVisibleEb()}; let arg0 = self as c_char; unsafe {C_ZN12QInputMethod10setVisibleEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QInputMethod::setInputItemRectangle(const QRectF & rect); impl /*struct*/ QInputMethod { pub fn setInputItemRectangle<RetType, T: QInputMethod_setInputItemRectangle<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setInputItemRectangle(self); // return 1; } } pub trait QInputMethod_setInputItemRectangle<RetType> { fn setInputItemRectangle(self , rsthis: & QInputMethod) -> RetType; } // proto: void QInputMethod::setInputItemRectangle(const QRectF & rect); impl<'a> /*trait*/ QInputMethod_setInputItemRectangle<()> for (&'a QRectF) { fn setInputItemRectangle(self , rsthis: & QInputMethod) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QInputMethod21setInputItemRectangleERK6QRectF()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN12QInputMethod21setInputItemRectangleERK6QRectF(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QInputMethod::commit(); impl /*struct*/ QInputMethod { pub fn commit<RetType, T: QInputMethod_commit<RetType>>(& self, overload_args: T) -> RetType { return overload_args.commit(self); // return 1; } } pub trait QInputMethod_commit<RetType> { fn commit(self , rsthis: & QInputMethod) -> RetType; } // proto: void QInputMethod::commit(); impl<'a> /*trait*/ QInputMethod_commit<()> for () { fn commit(self , rsthis: & QInputMethod) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QInputMethod6commitEv()}; unsafe {C_ZN12QInputMethod6commitEv(rsthis.qclsinst)}; // return 1; } } // proto: void QInputMethod::setInputItemTransform(const QTransform & transform); impl /*struct*/ QInputMethod { pub fn setInputItemTransform<RetType, T: QInputMethod_setInputItemTransform<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setInputItemTransform(self); // return 1; } } pub trait QInputMethod_setInputItemTransform<RetType> { fn setInputItemTransform(self , rsthis: & QInputMethod) -> RetType; } // proto: void QInputMethod::setInputItemTransform(const QTransform & transform); impl<'a> /*trait*/ QInputMethod_setInputItemTransform<()> for (&'a QTransform) { fn setInputItemTransform(self , rsthis: & QInputMethod) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QInputMethod21setInputItemTransformERK10QTransform()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN12QInputMethod21setInputItemTransformERK10QTransform(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QRectF QInputMethod::cursorRectangle(); impl /*struct*/ QInputMethod { pub fn cursorRectangle<RetType, T: QInputMethod_cursorRectangle<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cursorRectangle(self); // return 1; } } pub trait QInputMethod_cursorRectangle<RetType> { fn cursorRectangle(self , rsthis: & QInputMethod) -> RetType; } // proto: QRectF QInputMethod::cursorRectangle(); impl<'a> /*trait*/ QInputMethod_cursorRectangle<QRectF> for () { fn cursorRectangle(self , rsthis: & QInputMethod) -> QRectF { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QInputMethod15cursorRectangleEv()}; let mut ret = unsafe {C_ZNK12QInputMethod15cursorRectangleEv(rsthis.qclsinst)}; let mut ret1 = QRectF::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QInputMethod::isVisible(); impl /*struct*/ QInputMethod { pub fn isVisible<RetType, T: QInputMethod_isVisible<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isVisible(self); // return 1; } } pub trait QInputMethod_isVisible<RetType> { fn isVisible(self , rsthis: & QInputMethod) -> RetType; } // proto: bool QInputMethod::isVisible(); impl<'a> /*trait*/ QInputMethod_isVisible<i8> for () { fn isVisible(self , rsthis: & QInputMethod) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QInputMethod9isVisibleEv()}; let mut ret = unsafe {C_ZNK12QInputMethod9isVisibleEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QLocale QInputMethod::locale(); impl /*struct*/ QInputMethod { pub fn locale<RetType, T: QInputMethod_locale<RetType>>(& self, overload_args: T) -> RetType { return overload_args.locale(self); // return 1; } } pub trait QInputMethod_locale<RetType> { fn locale(self , rsthis: & QInputMethod) -> RetType; } // proto: QLocale QInputMethod::locale(); impl<'a> /*trait*/ QInputMethod_locale<QLocale> for () { fn locale(self , rsthis: & QInputMethod) -> QLocale { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QInputMethod6localeEv()}; let mut ret = unsafe {C_ZNK12QInputMethod6localeEv(rsthis.qclsinst)}; let mut ret1 = QLocale::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QInputMethod::reset(); impl /*struct*/ QInputMethod { pub fn reset<RetType, T: QInputMethod_reset<RetType>>(& self, overload_args: T) -> RetType { return overload_args.reset(self); // return 1; } } pub trait QInputMethod_reset<RetType> { fn reset(self , rsthis: & QInputMethod) -> RetType; } // proto: void QInputMethod::reset(); impl<'a> /*trait*/ QInputMethod_reset<()> for () { fn reset(self , rsthis: & QInputMethod) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QInputMethod5resetEv()}; unsafe {C_ZN12QInputMethod5resetEv(rsthis.qclsinst)}; // return 1; } } #[derive(Default)] // for QInputMethod_cursorRectangleChanged pub struct QInputMethod_cursorRectangleChanged_signal{poi:u64} impl /* struct */ QInputMethod { pub fn cursorRectangleChanged(&self) -> QInputMethod_cursorRectangleChanged_signal { return QInputMethod_cursorRectangleChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QInputMethod_cursorRectangleChanged_signal { pub fn connect<T: QInputMethod_cursorRectangleChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QInputMethod_cursorRectangleChanged_signal_connect { fn connect(self, sigthis: QInputMethod_cursorRectangleChanged_signal); } #[derive(Default)] // for QInputMethod_localeChanged pub struct QInputMethod_localeChanged_signal{poi:u64} impl /* struct */ QInputMethod { pub fn localeChanged(&self) -> QInputMethod_localeChanged_signal { return QInputMethod_localeChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QInputMethod_localeChanged_signal { pub fn connect<T: QInputMethod_localeChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QInputMethod_localeChanged_signal_connect { fn connect(self, sigthis: QInputMethod_localeChanged_signal); } #[derive(Default)] // for QInputMethod_inputDirectionChanged pub struct QInputMethod_inputDirectionChanged_signal{poi:u64} impl /* struct */ QInputMethod { pub fn inputDirectionChanged(&self) -> QInputMethod_inputDirectionChanged_signal { return QInputMethod_inputDirectionChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QInputMethod_inputDirectionChanged_signal { pub fn connect<T: QInputMethod_inputDirectionChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QInputMethod_inputDirectionChanged_signal_connect { fn connect(self, sigthis: QInputMethod_inputDirectionChanged_signal); } #[derive(Default)] // for QInputMethod_animatingChanged pub struct QInputMethod_animatingChanged_signal{poi:u64} impl /* struct */ QInputMethod { pub fn animatingChanged(&self) -> QInputMethod_animatingChanged_signal { return QInputMethod_animatingChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QInputMethod_animatingChanged_signal { pub fn connect<T: QInputMethod_animatingChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QInputMethod_animatingChanged_signal_connect { fn connect(self, sigthis: QInputMethod_animatingChanged_signal); } #[derive(Default)] // for QInputMethod_keyboardRectangleChanged pub struct QInputMethod_keyboardRectangleChanged_signal{poi:u64} impl /* struct */ QInputMethod { pub fn keyboardRectangleChanged(&self) -> QInputMethod_keyboardRectangleChanged_signal { return QInputMethod_keyboardRectangleChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QInputMethod_keyboardRectangleChanged_signal { pub fn connect<T: QInputMethod_keyboardRectangleChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QInputMethod_keyboardRectangleChanged_signal_connect { fn connect(self, sigthis: QInputMethod_keyboardRectangleChanged_signal); } #[derive(Default)] // for QInputMethod_visibleChanged pub struct QInputMethod_visibleChanged_signal{poi:u64} impl /* struct */ QInputMethod { pub fn visibleChanged(&self) -> QInputMethod_visibleChanged_signal { return QInputMethod_visibleChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QInputMethod_visibleChanged_signal { pub fn connect<T: QInputMethod_visibleChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QInputMethod_visibleChanged_signal_connect { fn connect(self, sigthis: QInputMethod_visibleChanged_signal); } // cursorRectangleChanged() extern fn QInputMethod_cursorRectangleChanged_signal_connect_cb_0(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QInputMethod_cursorRectangleChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QInputMethod_cursorRectangleChanged_signal_connect for fn() { fn connect(self, sigthis: QInputMethod_cursorRectangleChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QInputMethod_cursorRectangleChanged_signal_connect_cb_0 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QInputMethod_SlotProxy_connect__ZN12QInputMethod22cursorRectangleChangedEv(arg0, arg1, arg2)}; } } impl /* trait */ QInputMethod_cursorRectangleChanged_signal_connect for Box<Fn()> { fn connect(self, sigthis: QInputMethod_cursorRectangleChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QInputMethod_cursorRectangleChanged_signal_connect_cb_box_0 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QInputMethod_SlotProxy_connect__ZN12QInputMethod22cursorRectangleChangedEv(arg0, arg1, arg2)}; } } // localeChanged() extern fn QInputMethod_localeChanged_signal_connect_cb_1(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QInputMethod_localeChanged_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QInputMethod_localeChanged_signal_connect for fn() { fn connect(self, sigthis: QInputMethod_localeChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QInputMethod_localeChanged_signal_connect_cb_1 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QInputMethod_SlotProxy_connect__ZN12QInputMethod13localeChangedEv(arg0, arg1, arg2)}; } } impl /* trait */ QInputMethod_localeChanged_signal_connect for Box<Fn()> { fn connect(self, sigthis: QInputMethod_localeChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QInputMethod_localeChanged_signal_connect_cb_box_1 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QInputMethod_SlotProxy_connect__ZN12QInputMethod13localeChangedEv(arg0, arg1, arg2)}; } } // visibleChanged() extern fn QInputMethod_visibleChanged_signal_connect_cb_2(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QInputMethod_visibleChanged_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QInputMethod_visibleChanged_signal_connect for fn() { fn connect(self, sigthis: QInputMethod_visibleChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QInputMethod_visibleChanged_signal_connect_cb_2 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QInputMethod_SlotProxy_connect__ZN12QInputMethod14visibleChangedEv(arg0, arg1, arg2)}; } } impl /* trait */ QInputMethod_visibleChanged_signal_connect for Box<Fn()> { fn connect(self, sigthis: QInputMethod_visibleChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QInputMethod_visibleChanged_signal_connect_cb_box_2 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QInputMethod_SlotProxy_connect__ZN12QInputMethod14visibleChangedEv(arg0, arg1, arg2)}; } } // keyboardRectangleChanged() extern fn QInputMethod_keyboardRectangleChanged_signal_connect_cb_3(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QInputMethod_keyboardRectangleChanged_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QInputMethod_keyboardRectangleChanged_signal_connect for fn() { fn connect(self, sigthis: QInputMethod_keyboardRectangleChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QInputMethod_keyboardRectangleChanged_signal_connect_cb_3 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QInputMethod_SlotProxy_connect__ZN12QInputMethod24keyboardRectangleChangedEv(arg0, arg1, arg2)}; } } impl /* trait */ QInputMethod_keyboardRectangleChanged_signal_connect for Box<Fn()> { fn connect(self, sigthis: QInputMethod_keyboardRectangleChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QInputMethod_keyboardRectangleChanged_signal_connect_cb_box_3 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QInputMethod_SlotProxy_connect__ZN12QInputMethod24keyboardRectangleChangedEv(arg0, arg1, arg2)}; } } // animatingChanged() extern fn QInputMethod_animatingChanged_signal_connect_cb_4(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QInputMethod_animatingChanged_signal_connect_cb_box_4(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QInputMethod_animatingChanged_signal_connect for fn() { fn connect(self, sigthis: QInputMethod_animatingChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QInputMethod_animatingChanged_signal_connect_cb_4 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QInputMethod_SlotProxy_connect__ZN12QInputMethod16animatingChangedEv(arg0, arg1, arg2)}; } } impl /* trait */ QInputMethod_animatingChanged_signal_connect for Box<Fn()> { fn connect(self, sigthis: QInputMethod_animatingChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QInputMethod_animatingChanged_signal_connect_cb_box_4 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QInputMethod_SlotProxy_connect__ZN12QInputMethod16animatingChangedEv(arg0, arg1, arg2)}; } } // <= body block end
use ckb_jsonrpc_types::{ BlockNumber, BlockView, CellWithStatus, EpochNumber, EpochView, HeaderView, OutPoint, TransactionWithStatus, }; use ckb_types::H256; macro_rules! jsonrpc { ( $(#[$struct_attr:meta])* pub struct $struct_name:ident {$( $(#[$attr:meta])* pub fn $method:ident(&mut $selff:ident $(, $arg_name:ident: $arg_ty:ty)*) -> $return_ty:ty; )*} ) => ( $(#[$struct_attr])* pub struct $struct_name { pub client: reqwest::Client, pub url: reqwest::Url, pub id: u64, } impl $struct_name { pub fn new(uri: &str) -> Self { let url = reqwest::Url::parse(uri).expect("ckb uri, e.g. \"http://127.0.0.1:8114\""); $struct_name { url, id: 0, client: reqwest::Client::new(), } } $( $(#[$attr])* pub fn $method(&mut $selff $(, $arg_name: $arg_ty)*) -> Result<$return_ty, failure::Error> { let method = String::from(stringify!($method)); let params = serialize_parameters!($($arg_name,)*); $selff.id += 1; let mut req_json = serde_json::Map::new(); req_json.insert("id".to_owned(), serde_json::json!($selff.id)); req_json.insert("jsonrpc".to_owned(), serde_json::json!("2.0")); req_json.insert("method".to_owned(), serde_json::json!(method)); req_json.insert("params".to_owned(), params); let mut resp = $selff.client.post($selff.url.clone()).json(&req_json).send()?; let output = resp.json::<ckb_jsonrpc_types::response::Output>()?; match output { ckb_jsonrpc_types::response::Output::Success(success) => { serde_json::from_value(success.result).map_err(Into::into) }, ckb_jsonrpc_types::response::Output::Failure(failure) => { Err(failure.error.into()) } } } )* } ) } macro_rules! serialize_parameters { () => ( serde_json::Value::Null ); ($($arg_name:ident,)+) => ( serde_json::to_value(($($arg_name,)+))?) } jsonrpc!(pub struct RawHttpRpcClient { // Chain pub fn get_block(&mut self, hash: H256) -> Option<BlockView>; pub fn get_block_by_number(&mut self, number: BlockNumber) -> Option<BlockView>; pub fn get_block_hash(&mut self, number: BlockNumber) -> Option<H256>; pub fn get_epoch_by_number(&mut self, number: EpochNumber) -> Option<EpochView>; pub fn get_header(&mut self, hash: H256) -> Option<HeaderView>; pub fn get_header_by_number(&mut self, number: BlockNumber) -> Option<HeaderView>; pub fn get_live_cell(&mut self, out_point: OutPoint, with_data: bool) -> CellWithStatus; pub fn get_tip_block_number(&mut self) -> BlockNumber; pub fn get_tip_header(&mut self) -> HeaderView; pub fn get_transaction(&mut self, hash: H256) -> Option<TransactionWithStatus>; // Pool }); pub struct HttpRpcClient { url: String, client: RawHttpRpcClient, } impl Clone for HttpRpcClient { fn clone(&self) -> HttpRpcClient { HttpRpcClient::new(self.url.clone()) } } impl HttpRpcClient { pub fn new(url: String) -> HttpRpcClient { let client = RawHttpRpcClient::new(url.as_str()); HttpRpcClient { url, client } } pub fn url(&self) -> &str { self.url.as_str() } } impl HttpRpcClient { // Chain pub fn get_block(&mut self, hash: H256) -> Result<Option<BlockView>, String> { self.client.get_block(hash).map_err(|err| err.to_string()) } pub fn get_block_by_number(&mut self, number: u64) -> Result<Option<BlockView>, String> { self.client .get_block_by_number(BlockNumber::from(number)) .map_err(|err| err.to_string()) } pub fn get_block_hash(&mut self, number: u64) -> Result<Option<H256>, String> { self.client .get_block_hash(BlockNumber::from(number)) .map_err(|err| err.to_string()) } pub fn get_epoch_by_number(&mut self, number: u64) -> Result<Option<EpochView>, String> { self.client .get_epoch_by_number(EpochNumber::from(number)) .map_err(|err| err.to_string()) } pub fn get_header(&mut self, hash: H256) -> Result<Option<HeaderView>, String> { self.client.get_header(hash).map_err(|err| err.to_string()) } pub fn get_header_by_number(&mut self, number: u64) -> Result<Option<HeaderView>, String> { self.client .get_header_by_number(BlockNumber::from(number)) .map_err(|err| err.to_string()) } pub fn get_live_cell( &mut self, out_point: OutPoint, with_data: bool, ) -> Result<CellWithStatus, String> { self.client .get_live_cell(out_point, with_data) .map_err(|err| err.to_string()) } pub fn get_tip_block_number(&mut self) -> Result<u64, String> { self.client .get_tip_block_number() .map(|number| number.value()) .map_err(|err| err.to_string()) } pub fn get_tip_header(&mut self) -> Result<HeaderView, String> { self.client.get_tip_header().map_err(|err| err.to_string()) } pub fn get_transaction(&mut self, hash: H256) -> Result<Option<TransactionWithStatus>, String> { self.client .get_transaction(hash) .map_err(|err| err.to_string()) } }
extern crate web3_rs_wasm; use web3_rs_wasm::futures::Future; fn main() { let (_eloop, http) = web3_rs_wasm::transports::Http::new("http://localhost:8545").unwrap(); let web3 = web3_rs_wasm::Web3::new(http); let accounts = web3.eth().accounts().wait().unwrap(); println!("Accounts: {:?}", accounts); }
fn main(){ proconio::input!{a:u64,b:u64}; println!("{}safe",if a<=b{"un"}else{""}) }
//! Collect [Tracy] profiles in tracing-enabled applications. //! //! Assuming the application is well instrumented, this should in practice be a very low effort way //! to gain great amounts of insight into an application performance. //! //! Note, however that Tracy is ultimately a profiling, not an observability, tool. As thus, some //! of tracing concepts cannot be represented well by Tracy. For instance, out-of-order span //! entries and exits, are not supported, and neither are spans that are entered and exited on //! different threads. This crate will attempt to mitigate the problems and retain trace validity //! at the cost of potentially invalid data. When such a mitigation occurs, trace will contain a //! message with a note about the problem. //! //! Some other caveats to keep in mind: //! //! * Only span entries and exits are recorded; //! * Events show up as messages in Tracy, however Tracy can struggle with large numbers of //! messages; //! * Some additional functionality such as plotting and memory allocation profiling is only //! available as part of the [tracy-client](tracy_client) crate. //! //! # Important note //! //! Unlike with many other subscriber implementations, simply depending on this crate is sufficient //! for tracy to be enabled at program startup, even if [`TracyLayer`](TracyLayer) is not //! registered as a subscriber. While not registering a `TracyLayer` will avoid Tracy from //! collecting spans, it still broadcasts discovery packets to the local network and exposes the //! data it collects in the background to that same network. Traces collected by Tracy may include //! source and assembly code as well. //! //! As thus, you may want make sure to only enable the `tracing-tracy` crate conditionally, via the //! `enable` feature flag provided by this crate. //! //! [Tracy]: https://github.com/wolfpld/tracy use std::{fmt::Write, collections::VecDeque, cell::RefCell}; use tracing_core::{ field::{Field, Visit}, span::Id, Event, Subscriber, }; use tracing_subscriber::{ layer::{Context, Layer}, registry, }; use tracy_client::{Span, color_message, message, finish_continuous_frame}; thread_local! { /// A stack of spans currently active on the current thread. static TRACY_SPAN_STACK: RefCell<VecDeque<(Span, u64)>> = RefCell::new(VecDeque::with_capacity(16)); } /// A tracing layer that collects data in Tracy profiling format. #[derive(Clone)] pub struct TracyLayer { stack_depth: u16, } impl TracyLayer { /// Create a new `TracyLayer`. /// /// Defaults to collecting stack traces. pub fn new() -> Self { Self { stack_depth: 64 } } /// Specify the maximum number of stack frames that will be collected. /// /// Specifying 0 frames will disable stack trace collection. pub fn with_stackdepth(mut self, stack_depth: u16) -> Self { self.stack_depth = stack_depth; self } } impl Default for TracyLayer { fn default() -> Self { Self::new() } } impl<S> Layer<S> for TracyLayer where S: Subscriber + for<'a> registry::LookupSpan<'a>, { fn on_enter(&self, id: &Id, ctx: Context<S>) { if let Some(span_data) = ctx.span(id) { let metadata = span_data.metadata(); let file = metadata.file().unwrap_or("<error: not available>"); let line = metadata.line().unwrap_or(0); TRACY_SPAN_STACK.with(|s| { s.borrow_mut().push_back(( Span::new(metadata.name(), "", file, line, self.stack_depth), id.into_u64() )); }); } } fn on_exit(&self, id: &Id, _: Context<S>) { TRACY_SPAN_STACK.with(|s| { if let Some((span, span_id)) = s.borrow_mut().pop_back() { if id.into_u64() != span_id { color_message( "Tracing spans exited out of order! \ Trace may not be accurate for this span stack.", 0xFF000000, self.stack_depth, ); } drop(span); } else { color_message( "Exiting a tracing span, but got nothing on the tracy span stack!", 0xFF000000, self.stack_depth, ); } }); } fn on_event(&self, event: &Event, _: Context<'_, S>) { let mut visitor = TracyEventFieldVisitor { dest: String::new(), first: true, frame_mark: false, }; event.record(&mut visitor); if !visitor.first { let mut max_len = usize::from(u16::max_value()) - 1; if visitor.dest.len() >= max_len { while !visitor.dest.is_char_boundary(max_len) { max_len -= 1; } message(&visitor.dest[..max_len], self.stack_depth); color_message( "Message for the previous event was too long, truncated", 0xFF000000, self.stack_depth, ); } else { message(&visitor.dest, self.stack_depth); } } if visitor.frame_mark { finish_continuous_frame!(); } } } struct TracyEventFieldVisitor { dest: String, frame_mark: bool, first: bool, } impl Visit for TracyEventFieldVisitor { fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { // FIXME: this is a very crude formatter, but we don’t have // an easy way to do anything better... if self.first { let _ = write!(&mut self.dest, "{} = {:?}", field.name(), value); self.first = false; } else { let _ = write!(&mut self.dest, ", {} = {:?}", field.name(), value); } } fn record_bool(&mut self, field: &Field, value: bool) { match (value, field.name()) { (true, "tracy.frame_mark") => self.frame_mark = true, _ => self.record_debug(field, &value), } } } #[cfg(test)] mod tests { use futures::future::join_all; use tracing_attributes::instrument; use tracing::{debug, event, info, span, info_span, Level}; use tracing_subscriber::layer::SubscriberExt; fn setup_subscriber() { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { tracing::subscriber::set_global_default( tracing_subscriber::registry().with(super::TracyLayer::new()), ) .unwrap(); }); } #[test] fn it_works() { setup_subscriber(); let span = span!(Level::TRACE, "a sec"); let _enter = span.enter(); event!(Level::INFO, "EXPLOSION!"); } #[test] fn it_works_2() { setup_subscriber(); let span = span!(Level::TRACE, "2 secs"); let _enter = span.enter(); event!( Level::INFO, message = "DOUBLE THE EXPLOSION!", tracy.frame_mark = true ); } #[test] fn multiple_entries() { setup_subscriber(); let span = span!(Level::INFO, "multiple_entries"); span.in_scope(|| {}); span.in_scope(|| {}); let span = span!(Level::INFO, "multiple_entries 2"); span.in_scope(|| { span.in_scope(|| {}) }); } #[test] fn out_of_order() { setup_subscriber(); let span1 = span!(Level::INFO, "out of order exits 1"); let span2 = span!(Level::INFO, "out of order exits 2"); let span3 = span!(Level::INFO, "out of order exits 3"); let entry1 = span1.enter(); let entry2 = span2.enter(); let entry3 = span3.enter(); drop(entry2); drop(entry3); drop(entry1); } #[test] fn exit_in_different_thread() { setup_subscriber(); let span = Box::leak(Box::new(span!(Level::INFO, "exit in different thread"))); let entry = span.enter(); let thread = std::thread::spawn(|| drop(entry)); thread.join().unwrap(); } #[instrument] async fn parent_task(subtasks: usize) { info!("spawning subtasks..."); let subtasks = (1..=subtasks) .map(|number| { debug!(message = "creating subtask;", number); subtask(number) }) .collect::<Vec<_>>(); let result = join_all(subtasks).await; debug!("all subtasks completed"); let sum: usize = result.into_iter().sum(); info!(sum); } #[instrument] async fn subtask(number: usize) -> usize { info!("sleeping in subtask {}...", number); tokio::time::delay_for(std::time::Duration::from_millis(10)).await; info!("sleeping in subtask {}...", number); tokio::time::delay_for(std::time::Duration::from_millis(number as _)).await; info!("sleeping in subtask {}...", number); tokio::time::delay_for(std::time::Duration::from_millis(10)).await; number } // Test based on the spawny_things example from the tracing repository. #[tokio::test] async fn async_futures() { setup_subscriber(); parent_task(5).await; } #[test] fn message_too_long() { setup_subscriber(); info!("{}", "a".repeat(u16::max_value().into())); } #[test] fn long_span_data() { setup_subscriber(); let data = "c".repeat(u16::max_value().into()); info_span!("some span name", "{}", data).in_scope(|| {}); } }
#![allow(clippy::std_instead_of_core)] extern crate std; use std::prelude::v1::*; use super::*; mod list; mod binary_tree; mod dyn_trait; /// This results in tree depths that are enough to cause stack overflows when /// `deep_safe_drop` is not used for a `Drop` impl. You may increase this but /// more RAM will be required. const TREE_SIZE: usize = 2_usize.pow(20); trait NewLink<Node> { fn new(node: Node) -> Self; } use list::List; use binary_tree::BinaryTree; #[allow(clippy::trait_duplication_in_bounds)] // Shouldn't be needed, if it was smarter. fn make_stretched_fan<L>(fan_degree: usize, stretch_len: usize) -> L where L: NewLink<List<L>> + NewLink<BinaryTree<L>> { let branch = || { let tail = Some(make_stretched_fan(fan_degree.saturating_sub(1), stretch_len)); L::new(List::make(stretch_len, tail)) }; if fan_degree >= 1 { let left = Some(branch()); let right = Some(branch()); let branches = Some(L::new(BinaryTree { left, right })); L::new(List::make(stretch_len, branches)) } else { L::new(BinaryTree { left: None, right: None }) } }
use super::*; use std::fmt::{self, Display, Formatter}; use std::ops::BitOr; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct fmx_DataVect { _address: u8, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct fmx_ExprEnv { _address: u8, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct fmx_RowVect { _address: u8, } #[cfg_attr(target_os = "macos", link(kind = "framework", name = "FMWrapper"))] #[cfg_attr(target_os = "windows", link(kind = "static", name = "FMWrapper"))] #[cfg_attr(target_os = "linux", link(kind = "dylib", name = "FMWrapper"))] extern "C" { fn FM_ExprEnv_Constructor1(_x: *mut fmx__fmxcpt) -> *mut fmx_ExprEnv; pub(crate) fn FM_ExprEnv_RegisterScriptStep( pluginId: *const fmx_QuadChar, scriptStepId: i16, scriptStepName: *const fmx_Text, scriptStepDefinition: *const fmx_Text, scriptStepDescription: *const fmx_Text, compatibleOnFlags: u32, funcPtr: fmx_ExtPluginType, _x: *mut fmx__fmxcpt, ) -> FMError; pub(crate) fn FM_ExprEnv_RegisterExternalFunctionEx( pluginId: *const fmx_QuadChar, functionId: i16, functionName: *const fmx_Text, functionPrototype: *const fmx_Text, functionDescription: *const fmx_Text, minArgs: i16, maxArgs: i16, compatibleOnFlags: u32, funcPtr: fmx_ExtPluginType, _x: *mut fmx__fmxcpt, ) -> FMError; pub(crate) fn FM_ExprEnv_UnRegisterExternalFunction( pluginId: *const fmx_QuadChar, functionId: i16, _x: *mut fmx__fmxcpt, ) -> FMError; fn FM_ExprEnv_ExecuteFileSQLTextResult( _self: *const fmx_ExprEnv, expression: *const fmx_Text, filename: *const fmx_Text, parameters: *const fmx_DataVect, result: *mut fmx_Data, colSep: u16, rowSep: u16, _x: *mut fmx__fmxcpt, ) -> FMError; fn FM_ExprEnv_ExecuteFileSQL( _self: *const fmx_ExprEnv, expression: *const fmx_Text, filename: *const fmx_Text, parameters: *const fmx_DataVect, result: *mut fmx_RowVect, _x: *mut fmx__fmxcpt, ) -> FMError; fn FM_ExprEnv_Delete(_self: *mut fmx_ExprEnv, _x: *mut fmx__fmxcpt); fn FM_ExprEnv_Evaluate( _self: *const fmx_ExprEnv, expression: *const fmx_Text, result: *mut fmx_Data, _x: *mut fmx__fmxcpt, ) -> FMError; fn FM_ExprEnv_EvaluateGetFunction( _self: *const fmx_ExprEnv, functionValue: GetFunction, result: *mut fmx_Data, _x: *mut fmx__fmxcpt, ) -> FMError; fn FM_ExprEnv_EvaluateConvertToFileMakerPath( _self: *const fmx_ExprEnv, inPath: *const fmx_Text, inFormat: FilePathFormat, outFMPath: *mut fmx_Text, _x: *mut fmx__fmxcpt, ) -> FMError; fn FM_ExprEnv_EvaluateConvertFromFileMakerPath( _self: *const fmx_ExprEnv, inFMPath: *const fmx_Text, inFormat: FilePathFormat, outPath: *mut fmx_Text, _x: *mut fmx__fmxcpt, ) -> FMError; #[deprecated] #[allow(dead_code)] fn FM_ExprEnv_RegisterExternalFunction( pluginId: *const fmx_QuadChar, functionId: i16, functionName: *const fmx_Text, functionPrototype: *const fmx_Text, minArgs: i16, maxArgs: i16, compatibleOnFlags: u32, funcPtr: fmx_ExtPluginType, _x: *mut fmx__fmxcpt, ) -> FMError; fn FM_ExprEnv_SessionID(_self: *const fmx_ExprEnv, _x: *mut fmx__fmxcpt) -> fmx_ptrtype; fn FM_ExprEnv_FileID(_self: *const fmx_ExprEnv, _x: *mut fmx__fmxcpt) -> fmx_ptrtype; pub(crate) fn FM_ExprEnv_UnRegisterScriptStep( pluginId: *const fmx_QuadChar, scriptStepId: i16, _x: *mut fmx__fmxcpt, ) -> FMError; fn FM_DataVect_Constructor1(_x: *mut fmx__fmxcpt) -> *mut fmx_DataVect; fn FM_DataVect_Size(_self: *const fmx_DataVect, _x: *mut fmx__fmxcpt) -> u32; fn FM_DataVect_At( _self: *const fmx_DataVect, position: u32, _x: *mut fmx__fmxcpt, ) -> *const fmx_Data; fn FM_DataVect_AtAsText( _self: *const fmx_DataVect, position: u32, _x: *mut fmx__fmxcpt, ) -> *const fmx_Text; fn FM_DataVect_AtAsNumber( _self: *const fmx_DataVect, position: u32, _x: *mut fmx__fmxcpt, ) -> *const fmx_FixPt; fn FM_DataVect_PushBack(_self: *mut fmx_DataVect, data: *const fmx_Data, _x: *mut fmx__fmxcpt); fn FM_DataVect_Delete(_self: *mut fmx_DataVect, _x: *mut fmx__fmxcpt); fn FM_DataVect_Clear(_self: *mut fmx_DataVect, _x: *mut fmx__fmxcpt); fn FM_DataVect_IsEmpty(_self: *const fmx_DataVect, _x: *mut fmx__fmxcpt) -> bool; fn FM_DataVect_PopBack(_self: *mut fmx_DataVect, _x: *mut fmx__fmxcpt) -> *mut fmx_Data; fn FM_DataVect_AtAsDate( _self: *const fmx_DataVect, position: u32, _x: *mut fmx__fmxcpt, ) -> *const fmx_DateTime; fn FM_DataVect_AtAsTime( _self: *const fmx_DataVect, position: u32, _x: *mut fmx__fmxcpt, ) -> *const fmx_DateTime; fn FM_DataVect_AtAsTimeStamp( _self: *const fmx_DataVect, position: u32, _x: *mut fmx__fmxcpt, ) -> *const fmx_DateTime; fn FM_DataVect_AtAsBoolean( _self: *const fmx_DataVect, position: u32, _x: *mut fmx__fmxcpt, ) -> bool; fn FM_DataVect_AtAsBinaryData( _self: *const fmx_DataVect, position: u32, _x: *mut fmx__fmxcpt, ) -> *const fmx_BinaryData; fn FM_RowVect_Constructor1(_x: *mut fmx__fmxcpt) -> *mut fmx_RowVect; fn FM_RowVect_Delete(_self: *mut fmx_RowVect, _x: *mut fmx__fmxcpt); fn FM_RowVect_Size(_self: *const fmx_RowVect, _x: *mut fmx__fmxcpt) -> u32; fn FM_RowVect_IsEmpty(_self: *const fmx_RowVect, _x: *mut fmx__fmxcpt) -> bool; fn FM_RowVect_At( _self: *const fmx_RowVect, position: u32, _x: *mut fmx__fmxcpt, ) -> *const fmx_DataVect; } #[repr(u32)] pub enum Compatibility { Mac = 0x00000002, Win = 0x00000004, Server = 0x00000008, IOS = 0x00000010, CustomWeb = 0x00000020, WebDirect = 0x00000040, AllDevice = 0x0000007E, Future = 0x00FF0000, } impl BitOr for Compatibility { type Output = u32; fn bitor(self, rhs: Self) -> Self::Output { self as u32 | rhs as u32 } } pub struct ExprEnv { pub(crate) ptr: *mut fmx_ExprEnv, drop: bool, } impl ExprEnv { pub fn new() -> Self { let mut _x = fmx__fmxcpt::new(); let ptr = unsafe { FM_ExprEnv_Constructor1(&mut _x) }; _x.check(); ExprEnv { ptr, drop: true } } pub fn from_ptr(ptr: *const fmx_ExprEnv) -> Self { Self { ptr: ptr as *mut fmx_ExprEnv, drop: false, } } pub fn session_id(&self) -> u64 { let mut _x = fmx__fmxcpt::new(); let session_id = unsafe { FM_ExprEnv_SessionID(self.ptr, &mut _x) }; _x.check(); session_id } pub fn file_id(&self) -> u64 { let mut _x = fmx__fmxcpt::new(); let file_id = unsafe { FM_ExprEnv_FileID(self.ptr, &mut _x) }; _x.check(); file_id } pub fn execute_file_sql_text_result<E: ToText, F: ToText>( &self, expression: E, file_name: F, parameters: DataVect, result: &mut Data, col_sep: u16, row_sep: u16, ) -> FMError { let mut _x = fmx__fmxcpt::new(); let expr = expression.to_text(); let fn_text = file_name.to_text(); let error = unsafe { FM_ExprEnv_ExecuteFileSQLTextResult( self.ptr, expr.ptr, fn_text.ptr, parameters.ptr, result.ptr, col_sep, row_sep, &mut _x, ) }; _x.check(); error } pub fn execute_file_sql<E: ToText, F: ToText>( &self, expression: E, file_name: F, parameters: DataVect, result: &mut RowVect, ) -> FMError { let mut _x = fmx__fmxcpt::new(); let expr = expression.to_text(); let fn_text = file_name.to_text(); let error = unsafe { FM_ExprEnv_ExecuteFileSQL( self.ptr, expr.ptr, fn_text.ptr, parameters.ptr, result.ptr, &mut _x, ) }; _x.check(); error } pub fn eval_get(&self, func: GetFunction) -> Data { let mut _x = fmx__fmxcpt::new(); let result = Data::new(); unsafe { FM_ExprEnv_EvaluateGetFunction(self.ptr, func, result.ptr, &mut _x) }; _x.check(); result } pub fn evaluate<T: ToText>(&self, expression: T) -> Data { let expr_txt = expression.to_text(); let mut _x = fmx__fmxcpt::new(); let result = Data::new(); unsafe { FM_ExprEnv_Evaluate(self.ptr, expr_txt.ptr, result.ptr, &mut _x) }; _x.check(); result } pub fn from_fm_path<T: ToText>(&self, path: T, format: FilePathFormat) -> Text { let mut _x = fmx__fmxcpt::new(); let text = path.to_text(); let result = Text::new(); unsafe { FM_ExprEnv_EvaluateConvertFromFileMakerPath( self.ptr, text.ptr, format, result.ptr, &mut _x, ) }; _x.check(); result } pub fn to_fm_path<T: ToText>(&self, path: T, format: FilePathFormat) -> Text { let mut _x = fmx__fmxcpt::new(); let text = path.to_text(); let result = Text::new(); unsafe { FM_ExprEnv_EvaluateConvertToFileMakerPath( self.ptr, text.ptr, format, result.ptr, &mut _x, ) }; _x.check(); result } } impl Drop for ExprEnv { fn drop(&mut self) { if self.drop { let mut _x = fmx__fmxcpt::new(); unsafe { FM_ExprEnv_Delete(self.ptr, &mut _x) }; _x.check(); } } } impl Default for ExprEnv { fn default() -> Self { Self::new() } } #[repr(i16)] pub enum GetFunction { ApplicationVersion = 1001, CurrentDate = 1002, LastError = 1003, ActiveFieldName = 1004, FileName = 1005, FileSize = 1006, FoundCount = 1007, HostName = 1008, LayoutCount = 1009, LayoutName = 1010, LayoutNumber = 1011, SystemLanguage = 1012, WindowMode = 1013, MultiUserState = 1014, PageNumber = 1015, SystemPlatform = 1016, ActivePortalRowNumber = 1017, PrinterName = 1018, TotalRecordCount = 1019, RecordNumber = 1020, ActiveRepetitionNumber = 1021, RequestCount = 1022, ScreenDepth = 1023, ScreenHeight = 1024, ScreenWidth = 1025, ScriptName = 1026, SortState = 1027, SystemVersion = 1028, CurrentTime = 1029, UserCount = 1030, UserName = 1031, AccountName = 1032, LastMessageChoice = 1033, CurrentPrivilegeSetName = 1034, ActiveModifierKeys = 1035, NetworkProtocol = 1036, RecordID = 1037, RecordModificationCount = 1038, ActiveFieldContents = 1039, FilePath = 1040, LastExternalErrorDetail = 1041, LayoutAccess = 1042, RecordAccess = 1043, HighContrastState = 1044, HighContrastColor = 1045, StatusAreaState = 1046, LayoutViewState = 1047, WindowName = 1048, WindowHeight = 1049, WindowLeft = 1050, WindowTop = 1051, WindowVisible = 1052, WindowWidth = 1053, SystemNICAddress = 1054, SystemIpAddress = 1055, ActiveFieldTableName = 1056, ActiveSelectionSize = 1057, ActiveSelectionStart = 1058, ApplicationLanguage = 1059, CurrentHostTimestamp = 1060, LayoutTableName = 1061, ScriptParameter = 1062, CurrentTimeStamp = 1063, WindowDesktopHeight = 1064, WindowDesktopWidth = 1065, WindowContentHeight = 1066, WindowContentWidth = 1067, CalculationRepetitionNumber = 1068, CurrentExtendedPrivileges = 1069, AllowAbortState = 1070, ErrorCaptureState = 1071, DesktopPath = 1072, DocumentsPath = 1073, FileMakerPath = 1074, HostIPAddress = 1075, RequestOmitState = 1076, PreferencesPath = 1077, RecordOpenCount = 1078, RecordOpenState = 1079, ScriptResult = 1080, SystemDrive = 1081, TextRulerVisible = 1082, AllowFormattingBarState = 1083, UseSystemFormatsState = 1084, WindowZoomLevel = 1085, CustomMenuSetName = 1086, ActiveLayoutObjectName = 1088, TemporaryPath = 1089, HostApplicationVersion = 1090, TriggerModifierKeys = 1091, TriggerKeystroke = 1092, DocumentsPathListing = 1093, AccountPrivilegeSet = 1094, AccountExtendedPrivileges = 1095, QuickFindText = 1096, TriggerCurrentPanel = 1097, TriggerTargetPanel = 1098, WindowStyle = 1099, InstalledFMPlugins = 1100, UUID = 1101, PersistentID = 1102, ConnectionState = 1103, CurrentTimeUTCMilliseconds = 1104, Device = 1105, WindowOrientation = 1106, TriggerGestureInfo = 1107, EncryptionState = 1108, ScriptAnimation = 1109, ModifiedFields = 1110, NetworkType = 1111, ConnectionAttributes = 1112, ScreenScaleFactor = 1113, ApplicationArchitecture = 1115, TriggerExternalEvent = 1116, TouchKeyboardState = 1117, MenubarState = 1118, RegionMonitorEvents = 1119, AccountGroupName = 1120, ActiveRecordNumber = 1121, UUIDNumber = 1122, OpenDataFileInfo = 1123, AccountType = 1124, PageCount = 1125, } pub struct RowVect { pub(crate) ptr: *mut fmx_RowVect, drop: bool, } impl RowVect { pub fn new() -> Self { let mut _x = fmx__fmxcpt::new(); let ptr = unsafe { FM_RowVect_Constructor1(&mut _x) }; _x.check(); Self { ptr, drop: true } } pub fn size(&self) -> u32 { let mut _x = fmx__fmxcpt::new(); let size = unsafe { FM_RowVect_Size(self.ptr, &mut _x) }; _x.check(); size } pub fn at(&self, position: u32) -> DataVect { let mut _x = fmx__fmxcpt::new(); let ptr = unsafe { FM_RowVect_At(self.ptr, position, &mut _x) }; _x.check(); DataVect::from_ptr(ptr) } pub fn is_empty(&self) -> bool { let mut _x = fmx__fmxcpt::new(); let empty = unsafe { FM_RowVect_IsEmpty(self.ptr, &mut _x) }; _x.check(); empty } } impl Drop for RowVect { fn drop(&mut self) { if self.drop { let mut _x = fmx__fmxcpt::new(); unsafe { FM_RowVect_Delete(self.ptr, &mut _x) }; _x.check(); } } } impl Default for RowVect { fn default() -> Self { Self::new() } } pub struct DataVect { pub(crate) ptr: *mut fmx_DataVect, drop: bool, } impl DataVect { pub fn new() -> Self { let mut _x = fmx__fmxcpt::new(); let ptr = unsafe { FM_DataVect_Constructor1(&mut _x) }; _x.check(); Self { ptr, drop: true } } pub fn from_ptr(ptr: *const fmx_DataVect) -> Self { Self { ptr: ptr as *mut fmx_DataVect, drop: false, } } pub fn size(&self) -> u32 { let mut _x = fmx__fmxcpt::new(); let size = unsafe { FM_DataVect_Size(self.ptr, &mut _x) }; _x.check(); size } pub fn at(&self, position: u32) -> Data { let mut _x = fmx__fmxcpt::new(); let data_ptr = unsafe { FM_DataVect_At(self.ptr, position, &mut _x) }; _x.check(); Data::from_ptr(data_ptr) } pub fn at_as_text(&self, position: u32) -> Text { let mut _x = fmx__fmxcpt::new(); let ptr = unsafe { FM_DataVect_AtAsText(self.ptr, position, &mut _x) }; _x.check(); Text::from_ptr(ptr) } pub fn at_as_string(&self, position: u32) -> String { let mut _x = fmx__fmxcpt::new(); let ptr = unsafe { FM_DataVect_AtAsText(self.ptr, position, &mut _x) }; _x.check(); Text::from_ptr(ptr).to_string() } pub fn at_as_number(&self, position: u32) -> FixPt { let mut _x = fmx__fmxcpt::new(); let ptr = unsafe { FM_DataVect_AtAsNumber(self.ptr, position, &mut _x) }; _x.check(); FixPt::from_ptr(ptr) } pub fn at_as_date(&self, position: u32) -> DateTime { let mut _x = fmx__fmxcpt::new(); let ptr = unsafe { FM_DataVect_AtAsDate(self.ptr, position, &mut _x) }; _x.check(); DateTime::from_ptr(ptr) } pub fn at_as_time(&self, position: u32) -> DateTime { let mut _x = fmx__fmxcpt::new(); let ptr = unsafe { FM_DataVect_AtAsTime(self.ptr, position, &mut _x) }; _x.check(); DateTime::from_ptr(ptr) } pub fn at_as_timestamp(&self, position: u32) -> DateTime { let mut _x = fmx__fmxcpt::new(); let ptr = unsafe { FM_DataVect_AtAsTimeStamp(self.ptr, position, &mut _x) }; _x.check(); DateTime::from_ptr(ptr) } pub fn at_as_binary(&self, position: u32) -> BinaryData { let mut _x = fmx__fmxcpt::new(); let ptr = unsafe { FM_DataVect_AtAsBinaryData(self.ptr, position, &mut _x) }; _x.check(); BinaryData::from_ptr(ptr) } pub fn at_as_bool(&self, position: u32) -> bool { let mut _x = fmx__fmxcpt::new(); let result = unsafe { FM_DataVect_AtAsBoolean(self.ptr, position, &mut _x) }; _x.check(); result } pub fn push(&mut self, data: Data) { let mut _x = fmx__fmxcpt::new(); unsafe { FM_DataVect_PushBack(self.ptr, data.ptr, &mut _x) }; _x.check(); } pub fn clear(&mut self) { let mut _x = fmx__fmxcpt::new(); unsafe { FM_DataVect_Clear(self.ptr, &mut _x) }; _x.check(); } pub fn is_empty(&mut self) -> bool { let mut _x = fmx__fmxcpt::new(); let empty = unsafe { FM_DataVect_IsEmpty(self.ptr, &mut _x) }; _x.check(); empty } pub fn pop(&mut self) -> Data { let mut _x = fmx__fmxcpt::new(); let result = unsafe { FM_DataVect_PopBack(self.ptr, &mut _x) }; _x.check(); Data::from_ptr(result) } } impl Drop for DataVect { fn drop(&mut self) { if self.drop { let mut _x = fmx__fmxcpt::new(); unsafe { FM_DataVect_Delete(self.ptr, &mut _x) }; _x.check(); } } } impl Default for DataVect { fn default() -> Self { Self::new() } } impl<'a> IntoIterator for &'a DataVect { type Item = Data; type IntoIter = DataVectIterator<'a>; fn into_iter(self) -> Self::IntoIter { DataVectIterator { data_vect: self, index: 0, } } } pub struct DataVectIterator<'a> { data_vect: &'a DataVect, index: usize, } impl<'a> Iterator for DataVectIterator<'a> { type Item = Data; fn next(&mut self) -> Option<Data> { let result = self.data_vect.at(self.index as u32); self.index += 1; Some(result) } } #[repr(i32)] pub enum FilePathFormat { PosixPath = 1, WinPath = 2, URLPath = 3, } #[derive(PartialEq, Debug)] #[repr(i16)] pub enum FMError { Unknown = -1, NoError = 0, UserCanceledAction = 1, MemoryError = 2, CommandUnavailable = 3, CommandUnknown = 4, CommandInvalid = 5, FileReadOnly = 6, RunningOutOfMemory = 7, EmptyResult = 8, InsufficientPrivileges = 9, RequestedDataMissing = 10, NameNotValid = 11, NameAlreadyExists = 12, FileInUse = 13, OutOfRange = 14, DivideByZero = 15, OperationFailed = 16, ConversionFailed = 17, AccountInformationMissing = 18, InvalidString = 19, CancelledByTriggeredScript = 20, FileMissing = 100, RecordMissing = 101, FieldMissing = 102, RelationshipMissing = 103, ScriptMissing = 104, LayoutMissing = 105, TableMissing = 106, IndexMissing = 107, ValueListMissing = 108, PrivilegeSetMissing = 109, RelatedTablesMissing = 110, FieldRepetitionInvalid = 111, WindowMissing = 112, FunctionMissing = 113, FileReferenceMissing = 114, MenuSetMissing = 115, LayoutObjectMissing = 116, DataSourceMissing = 117, FilesDamagedOrMissing = 130, LanguagePackMissing = 131, RecordAccessDenied = 200, FieldUnmodifiable = 201, FieldAccessDenied = 202, PrintAccessDenied = 203, SortOrderFieldAccessDenied = 204, ImportRecordCreationDenied = 205, PasswordChangeDenied = 206, DatabaseSchemaModificationDenied = 207, ShortPassword = 208, NewPasswordMatchesOld = 209, AccountInactive = 210, PasswordExpired = 211, InvalidAccountOrPassword = 212, AccountOrPasswordMissing = 213, TooManyLogins = 214, CannotDuplicateAdminPrivileges = 215, CannotDuplicateGuestAccounts = 216, InsufficientPrivilegesToModifyAdminAccount = 217, FileLocked = 300, RecordLocked = 301, TableLocked = 302, DatabaseSchemaLocked = 303, LayoutLocked = 304, RecordModificationIdMismatch = 306, FindCriteriaEmpty = 400, NoRecordsFound = 401, FieldNotLookupMatch = 402, TrialLimitExceeded = 403, SortOrderInvalid = 404, OmissionCountInvalid = 405, ReplaceCriteriaInvalid = 406, InvalidRelationships = 407, InvalidFieldDataType = 408, ImportOrderInvalid = 409, ExportOrderInvalid = 410, WrongVersionForRecovery = 412, InvalidFieldType = 413, LayoutCannotDisplayResult = 414, RelatedRecordsUnavailable = 415, DataSourcePrimaryKeyMissing = 416, OdbcUnsupported = 417, DataValidationFailed = 500, TimeValidationFailed = 501, NumberValidationFailed = 502, ValueOutOfRange = 503, ValueNotUnique = 504, ValueNotExisting = 505, ValueNotInValueList = 506, ValueFailedValidationCalc = 507, InvalidFindValue = 508, FieldValueRequired = 509, RelatedValueEmpty = 510, ValueExceedsMaxChars = 511, RecordAlreadyModified = 512, ValueRequiredForCreation = 513, PrintError = 600, HeaderAndFooterExceedPage = 601, BodyColumnSetupTooLarge = 602, PrintConnectionLost = 603, InvalidImportFileType = 700, EpsfPreviewMissing = 706, GraphicTranslatorMissing = 707, ImportFailed = 708, QuickTimeImportFailed = 709, QuickTimeUpdateFailed = 710, ImportTranslatorMissing = 711, PasswordPrivilegesInsufficent = 714, ExcelWorksheetOrRangeMissing = 715, OdbcImportQueryInvalid = 716, XmlImportExportInvalid = 717, XmlParsingError = 718, XmlTransformationError = 719, RepeatingFieldsNotSupported = 720, UnknownParserOrTransformerError = 721, ImportTargetMissingFields = 722, RecordCreationModificationDenied = 723, RecordCreationDenied = 724, RecordModificationDenied = 725, AllRecordsNotImported = 726, AllRecordsNotUpdated = 727, ImportError = 729, ExcelVersionUnsupported = 730, ImportFileEmpty = 731, FileContainsOtherFiles = 732, SelfReferentialImport = 733, FileInvalidForPictureDisplay = 734, FileInvalidForPictureDisplayInsertedAsFile = 735, DataTruncated = 736, BentoTableMissing = 737, FileCreationFailed = 800, TemporaryFileCreationFailed = 801, OpenFileFailed = 802, FileSingleUserOrHostMissing = 803, FileReadOnlyOpenFailed = 804, FileDamagedRecoveryRequired = 805, FileVersionInvalid = 806, FileNotFileMaker = 807, AccessPrivilegesDamaged = 808, DiskFull = 809, DiskLocked = 810, TemporaryFileNotFileMaker = 811, RecordSynchronizationError = 813, OpenFileLimitExceeded = 814, OpenLookupFileFailed = 815, FileConversionFailed = 816, FileBelongsToOtherSolution = 817, LocalSaveRemoteFileDenied = 819, FileClosing = 820, ForcedDisconnect = 821, FmiFilesMissing = 822, GuestsConnectedSingleUserDenied = 823, FileDamaged = 824, UnauthorizedReferenceToProtectedFile = 825, SpellingEngineError = 900, SpellingDictionaryMissing = 901, HelpSystemLaunchFailed = 902, CommandInvalidInSharedFile = 903, NoFieldSelected = 905, FileNotShared = 906, SpellingEngineInitializationFailed = 920, UserDictionaryLoadFailed = 921, UserDictionaryMissing = 922, UserDictionaryReadOnly = 923, UnexpectedError = 951, UnsupportedXmlGrammar = 954, DatabaseNameMissing = 955, DatabaseSessionMaxExceeded = 956, ConflictingCommands = 957, ParameterMissing = 958, CustomWebPublishingDisabled = 959, ParameterInvalid = 960, CalculationError = 1200, TooFewParameters = 1201, TooManyParameters = 1202, UnexpectedEndOfCalculation = 1203, UnexpectedValue = 1204, UnterminatedComment = 1205, MissingEndQuote = 1206, UnbalancedParenthesis = 1207, OperatorMissing = 1208, FieldOrLayoutNameMissing = 1209, PluginFunctionAlreadyRegistered = 1210, ListUsageNotAllowed = 1211, OperatorExpected = 1212, VariableAlreadyDefined = 1213, ExpressionFoundFieldNeeded = 1214, InvalidGetFunction = 1215, SummaryFieldsOnly = 1216, BreakFieldInvalid = 1217, NumberEvaluatationFailed = 1218, SelfReferentialFieldDefinition = 1219, WrongFieldType = 1220, InvalidDataType = 1221, CalculationCannotBeStored = 1222, UnimplementedFunction = 1223, UndefinedFunction = 1224, UnsupportedFunction = 1225, InvalidName = 1300, OdbcDriverInitializationFailed = 1400, OdbcEnvironmentAllocationFailed = 1401, OdbcEnvironmentFreeFailed = 1402, OdbcDisconnectFailed = 1403, OdbcConnectionAllocationFailed = 1404, OdbcConnectionFreeFailed = 1405, OdbcSqlCheckFailed = 1406, OdbcStatementAllocationFailed = 1407, OdbcExtendedError = 1408, OdbcError = 1409, OdbcCommunicationLinkFailed = 1413, PhpPrivilegeExtensionMissing = 1450, FileNotRemote = 1451, SmtpAuthenticationFailed = 1501, SmtpConnectionRefused = 1502, SmtpSslError = 1503, EncryptedConnectionRequired = 1504, SmtpAuthenticationUnsupported = 1505, EmailSendFailed = 1506, SmtpLoginFailed = 1507, InvalidPlugin = 1550, PluginInstallFailed = 1551, GenericPluginError1 = 1552, GenericPluginError2 = 1553, GenericPluginError3 = 1554, GenericPluginError4 = 1555, GenericPluginError5 = 1556, GenericPluginError6 = 1557, GenericPluginError7 = 1558, GenericPluginError8 = 1559, UnsupportedProtocol = 1626, AuthenticationFailed = 1627, SslError = 1628, ConnectionTimedOut = 1629, IncorrectUrlFormat = 1630, ConnectionFailed = 1631, CertificateAuthenticationFailed = 1632, CertificateError = 1633, UnsupportedCommand = 2046, BentoMissing = 2047, WrongExcelFormat = 2048, ActionCanceled = 3000, OnTimerScriptFailed = 8404, } impl Display for FMError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self) } }
//! System control //! //! Size: 4K use core::marker::PhantomData; use core::ops::{Deref, DerefMut}; use static_assertions::const_assert_eq; pub const PADDR: usize = 0x01C0_0000; register! { SRamCtrl, u32, RW, Fields [ Bits WIDTH(U32) OFFSET(U0) ] } const_assert_eq!(core::mem::size_of::<RegisterBlock>(), 0x08); #[repr(C)] pub struct RegisterBlock { pub __reserved_0: u32, // 0x00 pub sram_ctrl: SRamCtrl::Register, // 0x04 } pub struct SYSC { _marker: PhantomData<*const ()>, } unsafe impl Send for SYSC {} impl SYSC { pub unsafe fn from_paddr() -> Self { Self { _marker: PhantomData, } } pub fn as_ptr(&self) -> *const RegisterBlock { PADDR as *const _ } pub const unsafe fn ptr() -> *const RegisterBlock { PADDR as *const _ } pub fn as_mut_ptr(&mut self) -> *mut RegisterBlock { PADDR as *mut _ } pub const unsafe fn mut_ptr() -> *mut RegisterBlock { PADDR as *mut _ } } impl Deref for SYSC { type Target = RegisterBlock; fn deref(&self) -> &RegisterBlock { unsafe { &*self.as_ptr() } } } impl DerefMut for SYSC { fn deref_mut(&mut self) -> &mut RegisterBlock { unsafe { &mut *self.as_mut_ptr() } } }
use std::{ future::Future, pin::Pin, sync::Arc, task::{Context, Poll}, }; use futures::future::BoxFuture; use parking_lot::Mutex; use tokio::task::JoinHandle; /// Receiver for [`CancellationSafeFuture`] join handles if the future was rescued from cancellation. /// /// `T` is the [output type](Future::Output) of the wrapped future. #[derive(Debug, Default, Clone)] pub struct CancellationSafeFutureReceiver<T> { inner: Arc<ReceiverInner<T>>, } #[derive(Debug, Default)] struct ReceiverInner<T> { slot: Mutex<Option<JoinHandle<T>>>, } impl<T> Drop for ReceiverInner<T> { fn drop(&mut self) { let handle = self.slot.lock(); if let Some(handle) = handle.as_ref() { handle.abort(); } } } /// Wrapper around a future that cannot be cancelled. /// /// When the future is dropped/cancelled, we'll spawn a tokio task to _rescue_ it. pub struct CancellationSafeFuture<F> where F: Future + Send + 'static, F::Output: Send, { /// Mark if the inner future finished. If not, we must spawn a helper task on drop. done: bool, /// Inner future. /// /// Wrapped in an `Option` so we can extract it during drop. Inside that option however we also need a pinned /// box because once this wrapper is polled, it will be pinned in memory -- even during drop. Now the inner /// future does not necessarily implement `Unpin`, so we need a heap allocation to pin it in memory even when we /// move it out of this option. inner: Option<BoxFuture<'static, F::Output>>, /// Where to store the join handle on drop. receiver: CancellationSafeFutureReceiver<F::Output>, } impl<F> Drop for CancellationSafeFuture<F> where F: Future + Send + 'static, F::Output: Send, { fn drop(&mut self) { if !self.done { // acquire lock BEFORE checking the Arc let mut receiver = self.receiver.inner.slot.lock(); assert!(receiver.is_none()); // The Mutex is owned by the Arc and cannot be moved out of it. So after we acquired the lock we can safely // check if any external party still has access to the receiver state. If not, we assume there is no // interest in this future at all (e.g. during shutdown) and will NOT spawn it. if Arc::strong_count(&self.receiver.inner) > 1 { let inner = self.inner.take().expect("Double-drop?"); let handle = tokio::task::spawn(inner); *receiver = Some(handle); } } } } impl<F> CancellationSafeFuture<F> where F: Future + Send, F::Output: Send, { /// Create new future that is protected from cancellation. /// /// If [`CancellationSafeFuture`] is cancelled (i.e. dropped) and there is still some external receiver of the state /// left, than we will drive the payload (`f`) to completion. Otherwise `f` will be cancelled. pub fn new(fut: F, receiver: CancellationSafeFutureReceiver<F::Output>) -> Self { Self { done: false, inner: Some(Box::pin(fut)), receiver, } } } impl<F> Future for CancellationSafeFuture<F> where F: Future + Send, F::Output: Send, { type Output = F::Output; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { assert!(!self.done, "Polling future that already returned"); match self.inner.as_mut().expect("not dropped").as_mut().poll(cx) { Poll::Ready(res) => { self.done = true; Poll::Ready(res) } Poll::Pending => Poll::Pending, } } } #[cfg(test)] mod tests { use std::{ sync::atomic::{AtomicBool, Ordering}, time::Duration, }; use tokio::sync::Barrier; use super::*; #[tokio::test] async fn test_happy_path() { let done = Arc::new(AtomicBool::new(false)); let done_captured = Arc::clone(&done); let receiver = Default::default(); let fut = CancellationSafeFuture::new( async move { done_captured.store(true, Ordering::SeqCst); }, receiver, ); fut.await; assert!(done.load(Ordering::SeqCst)); } #[tokio::test] async fn test_cancel_future() { let done = Arc::new(Barrier::new(2)); let done_captured = Arc::clone(&done); let receiver = CancellationSafeFutureReceiver::default(); let fut = CancellationSafeFuture::new( async move { done_captured.wait().await; }, receiver.clone(), ); drop(fut); tokio::time::timeout(Duration::from_secs(5), done.wait()) .await .unwrap(); } #[tokio::test] async fn test_receiver_gone() { let done = Arc::new(Barrier::new(2)); let done_captured = Arc::clone(&done); let receiver = Default::default(); let fut = CancellationSafeFuture::new( async move { done_captured.wait().await; }, receiver, ); drop(fut); assert_eq!(Arc::strong_count(&done), 1); } }
use criterion::{black_box, criterion_group, criterion_main, Criterion}; pub fn criterion_benchmark(c: &mut Criterion) { c.bench_function("sieve 1000 - my optimized version using only single vec", |b| { b.iter(|| sieve::primes_up_to(black_box(1000))) }); c.bench_function("sieve 1000 - my original solution", |b| { b.iter(|| sieve::primes_up_to_retain(black_box(1000))) }); c.bench_function("sieve 1000 - vec retain from exercism", |b| { b.iter(|| sieve::primes_up_to_retain(black_box(1000))) }); c.bench_function("sieve 1000 - most starred from exercism", |b| { b.iter(|| sieve::primes_up_to_starred(black_box(1000))) }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
use instant::{Duration, Instant}; use crate::{ inertia::Inertia, render::{ render_target::RenderTarget, scene::{Drawable, Scene}, }, ship::{Land, Ship, Throttle}, }; struct IntegrationController { clock: Instant, } impl IntegrationController { fn new() -> IntegrationController { IntegrationController { clock: Instant::now(), } } fn step() -> Duration { Duration::from_millis((Inertia::step() * 1000.0) as u64) } fn integrate(&mut self, ship: &mut Ship, land: &mut Land) -> bool { let now = Instant::now(); while self.clock < now { ship.integrate(land); self.clock += Self::step(); } true } } pub struct World<T> where T: RenderTarget, { target: T, scene: T::RenderScene<Scene>, ship: Ship, land: Land, integration: IntegrationController, prev_zoom: f32, } impl<T> From<T> for World<T> where T: RenderTarget, { fn from(mut target: T) -> Self { let scene = target.new_scene(Scene::new()); World { target, scene, ship: Ship::new(), land: Land::new(), integration: IntegrationController::new(), prev_zoom: 0.0002, } } } #[cfg(feature = "wgpu_render")] impl<T: raw_window_handle::HasRawWindowHandle> From<&T> for World<crate::render::wgpu::target::WgpuRenderTarget> { fn from(window: &T) -> Self { crate::render::wgpu::target::WgpuRenderTarget::new(window).into() } } impl<T> World<T> where T: RenderTarget, { pub fn resize(&mut self, width: u32, height: u32) { self.target.resize(width, height); } pub fn redraw(&mut self) { let origin = self.ship.origin(); let ground = self.land.get(origin); let ground = ground.0 + ground.direction() * (origin - ground.0).0; let distance = (origin - ground).len() + 30.0; let zoom = (1.0 / distance).min(0.02); let zoom = zoom * 0.01 + self.prev_zoom * 0.99; self.prev_zoom = zoom; let size = self.target.get_size(); self.integration.integrate(&mut self.ship, &mut self.land); self.scene.set_camera(self.ship.origin(), zoom, size); let mut draw: [&mut dyn Drawable; 3] = [ &mut self.ship.drawable(), &mut self.ship.active_throttles(), &mut self.land.drawable(), ]; self.target.render_one(&mut self.scene, &mut draw[..]); } pub fn control(&mut self, throttle: Throttle, activate: bool) { self.ship.throttle(throttle, activate); } }
#![cfg(test)] use crate::sim::{BisectStrategy, SimulationState}; use crate::strategies::*; // there's a progress assertion in the simulator we hope won't trip here // basically, we're testing a strategy is capable of driving the confidence // to some arbitrary threshold (e.g. five nines), no matter how slowly fn run_progress_test<S: BisectStrategy>(n: usize, f: impl Fn(&SimulationState) -> S) { for buggy_commit in 0..n { for &fp_prob in &[0.0, 0.5, 0.9] { let s = SimulationState::new_with_bug_at(n, fp_prob, buggy_commit); let strat = f(&s); let res = s.simulate_til_confident(strat, 0.99999); if fp_prob == 0.0 { assert_eq!(res.suspected_buggy_commit, buggy_commit); } } } } #[test] fn test_simulate_deterministic_naive() { let logn = 6; let n = 1 << logn; for buggy_commit in 0..n { let s = SimulationState::new_with_bug_at(n, 0.0, buggy_commit); let nb = NaiveBinarySearch::new(&s, ConfusedHumanMode::ForgetEverything); let res = s.simulate_til_confident(nb, 1.0); assert_eq!(res.steps, logn); assert_eq!(res.confidence, 1.0); assert_eq!(res.suspected_buggy_commit, buggy_commit); } } #[test] fn test_linear_dumbness() { let n = 16; for buggy_commit in 0..n { println!("asdf: {}", buggy_commit); let s = SimulationState::new_with_bug_at(n, 0.0, buggy_commit); let c = LinearSearch::new(&s); let res = s.simulate_til_confident(c, 0.99); println!("asdf: steps was {}", res.steps); assert_eq!(res.suspected_buggy_commit, buggy_commit); // it searches backwards // bug @ 0 takes same steps to confirm as bug @ 1. otherwise normal let expected_steps = n - std::cmp::max(buggy_commit, 1); assert_eq!(res.steps, expected_steps); } } #[test] fn test_cdfbisect_progress() { for &bisect_point in &[0.01, 0.1, 0.5, 0.9, 0.99] { run_progress_test(16, |s| CdfBisect::new(s, bisect_point)); } } #[test] fn test_naive_progress() { run_progress_test(64, |s| NaiveBinarySearch::new(s, ConfusedHumanMode::ForgetEverything)); run_progress_test(64, |s| NaiveBinarySearch::new(s, ConfusedHumanMode::UsePreviousLow)); for &num_retries in &[1, 8, 64] { run_progress_test(64, |s| NaiveBinarySearch::new(s, ConfusedHumanMode::Mistrustful(num_retries))); } } #[test] fn test_linear_progress() { run_progress_test(64, LinearSearch::new); } #[test] fn test_entropy_progress() { run_progress_test(47, MinExpectedEntropy::new); } #[test] fn test_random_progress() { // 48 was min number to expose the 0 bug documented in assert_consistent. run_progress_test(48, |s| ChooseRandomly::new(s, RandomMode::Uniformly)); run_progress_test(32, |s| ChooseRandomly::new(s, RandomMode::WeightedByCDF)); }
use std::str; use serialize::{Decodable, json}; use request::Request; use typemap::Key; use plugin::{Phantom, Plugin, Pluggable}; // Plugin boilerplate struct JsonBodyParser; impl Key for JsonBodyParser { type Value = String; } impl<'a, 'b> Plugin<Request<'a, 'b>> for JsonBodyParser { fn eval(req: &mut Request, _: Phantom<JsonBodyParser>) -> Option<String> { if !req.origin.body.is_empty() { str::from_utf8(&*req.origin.body).ok().map(|s| s.to_string()) } else { None } } } pub trait JsonBody { fn json_as<T: Decodable>(&mut self) -> Option<T>; } impl<'a, 'b> JsonBody for Request<'a, 'b> { fn json_as<T: Decodable>(&mut self) -> Option<T> { // FIXME: // I think it would be smarter to not return Option<T> but rather // DecodeResult<T> to not swallow valuable debugging information. // I couldn't figure out how to properly do that self.get::<JsonBodyParser>().and_then(|parsed| { json::decode::<T>(&parsed[]).ok() }) } }
use crate::args_setup; use crate::object::cons_list::ConsList; use crate::object::Node; use crate::vm::VM; pub(crate) fn logic_gt(vm: &mut VM, args_list: ConsList<Node>) -> Result<Node, String> { let args = args_setup!(args_list, ">", ==, 2); let arg1 = vm.eval(args[0])?; let arg2 = vm.eval(args[1])?; Ok(Node::bool_obj(arg1 > arg2)) } pub(crate) fn logic_lt(vm: &mut VM, args_list: ConsList<Node>) -> Result<Node, String> { let args = args_setup!(args_list, "<", ==, 2); let arg1 = vm.eval(args[0])?; let arg2 = vm.eval(args[1])?; Ok(Node::bool_obj(arg1 < arg2)) } pub(crate) fn logic_eq(vm: &mut VM, args_list: ConsList<Node>) -> Result<Node, String> { let args = args_setup!(args_list, "eq", >=, 2); let evaled_arg1 = vm.eval(args[0]).unwrap_or_default(); let res = args .iter() .skip(1) .all(|x| vm.eval(&x).unwrap_or_default() == evaled_arg1); Ok(Node::bool_obj(res)) } pub(crate) fn logic_not(vm: &mut VM, args_list: ConsList<Node>) -> Result<Node, String> { let args = args_setup!(args_list, "not", ==, 1); Ok(Node::bool_obj(!vm.eval(args[0])?.is_truthy())) } pub(crate) fn logic_and(vm: &mut VM, args_list: ConsList<Node>) -> Result<Node, String> { let args = args_setup!(args_list, "and", >=, 2); let res = args .iter() .all(|x| vm.eval(&x).unwrap_or_default().is_truthy()); Ok(Node::bool_obj(res)) } pub(crate) fn logic_or(vm: &mut VM, args_list: ConsList<Node>) -> Result<Node, String> { let args = args_setup!(args_list, "or", >=, 2); let res = args .iter() .any(|x| vm.eval(&x).unwrap_or_default().is_truthy()); Ok(Node::bool_obj(res)) } pub(crate) fn logic_if(vm: &mut VM, args_list: ConsList<Node>) -> Result<Node, String> { let args = args_setup!(args_list, "if", 2, 3); let check = vm.eval(&args[0])?; if check.is_truthy() { vm.eval(&args[1]) } else if args.len() == 3 { vm.eval(&args[2]) } else { Ok(Node::Empty) } }
// See LICENSE file for copyright and license details. use std::rand::{task_rng, Rng}; use std::collections::hashmap::HashMap; use cgmath::{Vector2}; use error_context; use core::types::{Size2, MInt, UnitId, PlayerId, MapPos}; use core::conf::Config; use core::game_state::GameState; use core::fs::FileSystem; use core::map::{distance}; pub enum Command { CommandMove(UnitId, Vec<MapPos>), CommandEndTurn, CommandCreateUnit(MapPos), CommandAttackUnit(UnitId, UnitId), } #[deriving(Clone)] pub enum Event { EventMove(UnitId, Vec<MapPos>), EventEndTurn(PlayerId, PlayerId), // old_id, new_id EventCreateUnit(UnitId, MapPos, UnitTypeId, PlayerId), EventAttackUnit(UnitId, UnitId, /* killed: */ bool), } pub struct Player { pub id: PlayerId, } pub enum UnitClass { Infantry, Vehicle, } pub struct WeaponType { pub name: String, pub damage: MInt, pub ap: MInt, pub accuracy: MInt, pub max_distance: MInt, } #[deriving(Clone)] pub struct WeaponTypeId{pub id: MInt} pub struct UnitType { pub name: String, pub class: UnitClass, pub count: MInt, pub size: MInt, pub armor: MInt, pub toughness: MInt, pub weapon_skill: MInt, pub weapon_type_id: WeaponTypeId, pub move_points: MInt, } #[deriving(Clone)] pub struct UnitTypeId{pub id: MInt} pub struct Unit { pub id: UnitId, pub pos: MapPos, pub player_id: PlayerId, pub type_id: UnitTypeId, pub move_points: MInt, pub attacked: bool, } pub struct ObjectTypes { unit_types: Vec<UnitType>, weapon_types: Vec<WeaponType>, } impl ObjectTypes { pub fn new() -> ObjectTypes { let mut object_types = ObjectTypes { unit_types: vec![], weapon_types: vec![], }; object_types.get_weapon_types(); object_types.get_unit_types(); object_types } // TODO: read from json/toml config fn get_weapon_types(&mut self) { self.weapon_types.push(WeaponType { name: "cannon".to_string(), damage: 9, ap: 9, accuracy: 5, max_distance: 5, }); self.weapon_types.push(WeaponType { name: "rifle".to_string(), damage: 2, ap: 1, accuracy: 5, max_distance: 3, }); } // TODO: read from json/toml config fn get_unit_types(&mut self) { let cannon_id = self.get_weapon_type_id("cannon"); let rifle_id = self.get_weapon_type_id("rifle"); self.unit_types.push(UnitType { name: "tank".to_string(), class: Vehicle, size: 6, count: 1, armor: 11, toughness: 9, weapon_skill: 5, weapon_type_id: cannon_id, move_points: 5, }); self.unit_types.push(UnitType { name: "soldier".to_string(), class: Infantry, size: 4, count: 4, armor: 1, toughness: 2, weapon_skill: 5, weapon_type_id: rifle_id, move_points: 3, }); } fn get_unit_type_id_opt(&self, name: &str) -> Option<UnitTypeId> { for (id, unit_type) in self.unit_types.iter().enumerate() { if unit_type.name.as_slice() == name { return Some(UnitTypeId{id: id as MInt}); } } None } pub fn get_unit_type<'a>(&'a self, unit_type_id: UnitTypeId) -> &'a UnitType { &self.unit_types[unit_type_id.id as uint] } fn get_unit_type_id(&self, name: &str) -> UnitTypeId { match self.get_unit_type_id_opt(name) { Some(id) => id, None => panic!("No unit type with name: \"{}\"", name), } } fn get_weapon_type_id(&self, name: &str) -> WeaponTypeId { for (id, weapon_type) in self.weapon_types.iter().enumerate() { if weapon_type.name.as_slice() == name { return WeaponTypeId{id: id as MInt}; } } panic!("No weapon type with name \"{}\"", name); } } pub struct Core { game_state: GameState, players: Vec<Player>, current_player_id: PlayerId, core_event_list: Vec<Event>, event_lists: HashMap<PlayerId, Vec<Event>>, map_size: Size2<MInt>, object_types: ObjectTypes, } fn get_event_lists() -> HashMap<PlayerId, Vec<Event>> { let mut map = HashMap::new(); map.insert(PlayerId{id: 0}, Vec::new()); map.insert(PlayerId{id: 1}, Vec::new()); map } fn get_players_list() -> Vec<Player> { vec!( Player{id: PlayerId{id: 0}}, Player{id: PlayerId{id: 1}}, ) } impl Core { pub fn new(fs: &FileSystem) -> Core { set_error_context!("constructing Core", "-"); let config = Config::new(&fs.get(&Path::new("data/conf_core.json"))); let map_size = config.get("map_size"); let mut core = Core { game_state: GameState::new(), players: get_players_list(), current_player_id: PlayerId{id: 0}, core_event_list: Vec::new(), event_lists: get_event_lists(), map_size: map_size, object_types: ObjectTypes::new(), }; core.get_units(); core } pub fn object_types(&self) -> &ObjectTypes { &self.object_types } // TODO: Move to scenario.json fn get_units(&mut self) { let tank_id = self.object_types.get_unit_type_id("tank"); let soldier_id = self.object_types.get_unit_type_id("soldier"); self.add_unit(MapPos{v: Vector2{x: 0, y: 0}}, tank_id, PlayerId{id: 0}); self.add_unit(MapPos{v: Vector2{x: 0, y: 1}}, soldier_id, PlayerId{id: 0}); self.add_unit(MapPos{v: Vector2{x: 2, y: 0}}, tank_id, PlayerId{id: 1}); self.add_unit(MapPos{v: Vector2{x: 2, y: 2}}, soldier_id, PlayerId{id: 1}); } fn get_new_unit_id(&self) -> UnitId { let id = match self.game_state.units.keys().max_by(|&n| n) { Some(n) => n.id + 1, None => 0, }; UnitId{id: id} } fn add_unit(&mut self, pos: MapPos, type_id: UnitTypeId, player_id: PlayerId) { let event = EventCreateUnit( self.get_new_unit_id(), pos, type_id, player_id, ); self.do_core_event(event); } pub fn map_size(&self) -> Size2<MInt> { self.map_size } fn get_unit<'a>(&'a self, id: UnitId) -> &'a Unit { match self.game_state.units.find(&id) { Some(unit) => unit, None => panic!("No unit with id = {}", id.id), } } pub fn get_weapon_type(&self, weapon_type_id: WeaponTypeId) -> &WeaponType { &self.object_types.weapon_types[weapon_type_id.id as uint] } fn hit_test(&self, attacker_id: UnitId, defender_id: UnitId) -> bool { fn test(needed: MInt) -> bool { let real = task_rng().gen_range(-5i32, 5i32); let result = real < needed; println!("real:{} < needed:{} = {}", real, needed, result); result } println!(""); let attacker = self.get_unit(attacker_id); let defender = self.get_unit(defender_id); let attacker_type = self.object_types.get_unit_type(attacker.type_id); let defender_type = self.object_types.get_unit_type(defender.type_id); let weapon_type = self.get_weapon_type(attacker_type.weapon_type_id); if distance(attacker.pos, defender.pos) > weapon_type.max_distance { return false; } let hit_test_v = -15 + defender_type.size + weapon_type.accuracy + attacker_type.weapon_skill; let pierce_test_v = 5 + -defender_type.armor + weapon_type.ap; let wound_test_v = -defender_type.toughness + weapon_type.damage; println!("hit_test = {}, pierce_test = {}, wound_test_v = {}", hit_test_v, pierce_test_v, wound_test_v); print!("hit test: "); if !test(hit_test_v) { return false; } print!("pierce test: "); if !test(pierce_test_v) { return false; } print!("wound test: "); if !test(wound_test_v) { return false; } println!("HIT!"); true } pub fn player_id(&self) -> PlayerId { self.current_player_id } pub fn get_event(&mut self) -> Option<Event> { let list = self.event_lists.get_mut(&self.current_player_id); list.remove(0) } fn command_attack_unit_to_event( &self, attacker_id: UnitId, defender_id: UnitId ) -> Option<Event> { let attacker = &self.game_state.units[attacker_id]; let defender = &self.game_state.units[defender_id]; let attacker_type = self.object_types.get_unit_type(attacker.type_id); let weapon_type = self.get_weapon_type(attacker_type.weapon_type_id); if distance(attacker.pos, defender.pos) <= weapon_type.max_distance { Some(EventAttackUnit( attacker_id, defender_id, self.hit_test(attacker_id, defender_id), )) } else { None } } fn command_to_event(&self, command: Command) -> Option<Event> { match command { CommandEndTurn => { let old_id = self.current_player_id.id; let max_id = self.players.len() as MInt; let new_id = if old_id + 1 == max_id { 0 } else { old_id + 1 }; Some(EventEndTurn(PlayerId{id: old_id}, PlayerId{id: new_id})) }, CommandCreateUnit(pos) => { Some(EventCreateUnit( self.get_new_unit_id(), pos, self.object_types.get_unit_type_id("soldier"), self.current_player_id, )) }, CommandMove(unit_id, path) => { Some(EventMove(unit_id, path)) }, CommandAttackUnit(attacker_id, defender_id) => { self.command_attack_unit_to_event(attacker_id, defender_id) }, } } pub fn do_command(&mut self, command: Command) { match self.command_to_event(command) { Some(event) => self.do_core_event(event), None => {}, } } fn do_core_event(&mut self, core_event: Event) { self.core_event_list.push(core_event); self.make_events(); } fn apply_event(&mut self, event: &Event) { match *event { EventEndTurn(old_player_id, new_player_id) => { for player in self.players.iter() { if player.id == new_player_id { if self.current_player_id == old_player_id { self.current_player_id = player.id; } return; } } }, _ => {}, } } fn make_events(&mut self) { while self.core_event_list.len() != 0 { let event = self.core_event_list.pop().unwrap(); self.apply_event(&event); self.game_state.apply_event(&self.object_types, &event); for player in self.players.iter() { let event_list = self.event_lists.get_mut(&player.id); // TODO: per player event filter event_list.push(event.clone()); } } } } // vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
#![allow(clippy::comparison_chain)] #![allow(clippy::collapsible_if)] use std::cmp::Reverse; use std::cmp::{max, min}; use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; use std::fmt::Debug; use itertools::Itertools; use whiteread::parse_line; const ten97: usize = 1000_000_007; /// 2の逆元 mod ten97.割りたいときに使う const inv2ten97: u128 = 500_000_004; fn main() { let k: usize = parse_line().unwrap(); if k < 10 { println!("{}", k); return; } let mut juni = 9; let mut now: isize = 0; let mut ooo = vec![]; for i in 1..10 { ooo.push((-1, i)); } loop { let t = ooo[now as usize]; if t.1 > 0 { ooo.push((now, t.1 - 1)); juni += 1; } if juni == k { break; } ooo.push((now, t.1)); juni += 1; if juni == k { break; } if t.1 < 9 { ooo.push((now, t.1 + 1)); juni += 1; } if juni == k { break; } now += 1; } let mut ans = vec![]; let mut t = *ooo.last().unwrap(); while t.0 != -1 { let pre = t.0; ans.push(t.1.to_string().chars().last().unwrap()); t = ooo[pre as usize]; } ans.push(t.1.to_string().chars().last().unwrap()); println!("{}", ans.into_iter().rev().collect::<String>()); }
use openexr_sys as sys; use std::ffi::CString; use std::path::Path; use crate::core::{ error::Error, frame_buffer::{Frame, FrameBuffer, FrameBufferRef}, header::HeaderRef, }; type Result<T, E = Error> = std::result::Result<T, E>; #[repr(transparent)] pub struct InputFile(pub(crate) *mut sys::Imf_InputFile_t); impl InputFile { /// Open the file at path `filename` and read the header. /// /// # Errors /// * [`Error::Base`] - if the file cannot be opened /// pub fn new<P: AsRef<Path>>( filename: P, num_threads: i32, ) -> Result<InputFile> { let c_filename = CString::new( filename .as_ref() .to_str() .expect("Invalid bytes in filename"), ) .expect("Internal null bytes in filename"); let mut ptr = std::ptr::null_mut(); unsafe { sys::Imf_InputFile_ctor(&mut ptr, c_filename.as_ptr(), num_threads) .into_result()?; } Ok(InputFile(ptr)) } /// Access to the file [`Header`](crate::core::header::Header) /// pub fn header(&self) -> HeaderRef { unsafe { let mut ptr = std::ptr::null(); sys::Imf_InputFile_header(self.0, &mut ptr); if ptr.is_null() { panic!("Received null ptr from sys::Imf_InputFile_header"); } HeaderRef::new(ptr) } } /// Access to the file format version /// pub fn version(&self) -> i32 { let mut v = 0; unsafe { sys::Imf_InputFile_version(self.0, &mut v); } v } /// Set the current frame buffer -- copies the FrameBuffer /// object into the InputFile object. /// /// The current frame buffer is the destination for the pixel /// data read from the file. The current frame buffer must be /// set at least once before `read_pixels()` is called. /// The current frame buffer can be changed after each call /// to `read_pixels()`. /// /// # Errors /// * [`Error::InvalidArgument`] - if the sampling factors do not match or /// if the frame buffer does not have a sample count slice. /// pub fn set_frame_buffer( &mut self, frame_buffer: &FrameBuffer, ) -> Result<()> { unsafe { sys::Imf_InputFile_setFrameBuffer(self.0, frame_buffer.ptr) .into_result()?; } Ok(()) } /// Access to the current frame buffer /// pub fn frame_buffer(&self) -> FrameBufferRef { let mut ptr = std::ptr::null(); unsafe { sys::Imf_InputFile_frameBuffer(self.0, &mut ptr); } FrameBufferRef::new(ptr) } /// Check if all pixels in the data window are present in the input file /// pub fn is_complete(&self) -> bool { let mut v = false; unsafe { sys::Imf_InputFile_isComplete(self.0, &mut v); } v } /// Check if SSE optimization is enabled /// /// Call after `set_frame_buffer()` to query whether optimized file decoding /// is available - decode times will be faster if returns true /// /// Optimization depends on: /// * The file type (only scanline data is supported), /// * The framebuffer channels (RGB/RGBA mono or stereo) /// * The framebuffer channel types (all channels half-float format only) /// * The file channels (RGB/RGBA mono or stereo) /// * The file channel types (all channel half-float format only) /// * Whether SSE2 instruction support was detected at compile time /// /// # Errors /// * [`Error::InvalidArgument`] - if no frame buffer has been set /// pub fn is_optimization_enabled(&self) -> Result<bool> { let mut v = false; unsafe { sys::Imf_InputFile_isOptimizationEnabled(self.0, &mut v) .into_result()?; } Ok(v) } /// Read all scanlines in the range [s1, s2] and put them in the current /// frame buffer. /// /// `read_pixel_sample_counts()` must be called before calling this method. /// /// # Errors /// * [`Error::InvalidArgument`] - if no frame buffer has been set, if `s1` /// or `s2` are outside the data window, or if the sample counts have not been /// read yet /// * [`Error::Base`] - if any other error occurs /// pub fn read_pixels(&mut self, s1: i32, s2: i32) -> Result<()> { unsafe { sys::Imf_InputFile_readPixels(self.0, s1, s2).into_result()?; } Ok(()) } /// Consume this `InputFile` and convert it to an [`InputFileReader`]. /// /// The [`InputFileReader`] provides a safe API for reading data from the /// file into memory, by taking ownership of the memory and handling calculating /// [`Slice`](crate::core::frame_buffer::Slice) offsets internally. /// /// `frames` is a `Vec` of [`Frame`](crate::core::frame_buffer::Frame) objects, which /// describe the channels to load from the image, and how they are to be /// stored in memory. /// pub fn into_reader( mut self, frames: Vec<Frame>, ) -> Result<InputFileReader> { let mut frame_buffer = FrameBuffer::new(); for frame in frames { frame_buffer.insert_frame(frame)?; } self.set_frame_buffer(&frame_buffer)?; Ok(InputFileReader { inner: self.0, frame_buffer, }) } } /// `InputFileReader` provides a safe API over `InputFile` by taking ownership /// of the storage into which the channel data is to be read and handling all /// the [`Slice`](crate::core::frame_buffer::Slice) pointer offset shenanigans internally. /// pub struct InputFileReader { inner: *mut sys::Imf_InputFile_t, frame_buffer: FrameBuffer, } impl InputFileReader { /// Read all scanlines in the range [s1, s2] and put them in the current /// frame buffer. /// /// This consumes the `InputFileReader` and returns the original `InputFile` /// object and the `Vec` of the read [`Frame`](crate::core::frame_buffer::Frame)s . /// /// # Errors /// * [`Error::Base`] - if any error occurs /// pub fn read_pixels( self, s1: i32, s2: i32, ) -> Result<(InputFile, Vec<Frame>)> { unsafe { sys::Imf_InputFile_readPixels(self.inner, s1, s2).into_result()?; } let InputFileReader { inner: _, mut frame_buffer, } = self; Ok((InputFile(self.inner), frame_buffer.frames.take().unwrap())) } /// Check if SSE optimization is enabled. Decode times will be faster if /// this returns true. /// /// Optimization depends on: /// * The file type (only scanline data is supported), /// * The framebuffer channels (RGB/RGBA mono or stereo) /// * The framebuffer channel types (all channels half-float format only) /// * The file channels (RGB/RGBA mono or stereo) /// * The file channel types (all channel half-float format only) /// * Whether SSE2 instruction support was detected at compile time /// pub fn is_optimization_enabled(&self) -> bool { let mut v = false; unsafe { sys::Imf_InputFile_isOptimizationEnabled(self.inner, &mut v); } v } } #[cfg(test)] #[test] fn read_input_safe1() -> Result<()> { use crate::{core::frame_buffer::Frame, rgba::rgba::Rgba}; use std::path::PathBuf; let path = PathBuf::from( std::env::var("CARGO_MANIFEST_DIR") .expect("CARGO_MANIFEST_DIR not set"), ) .join("images") .join("window.exr"); // Open the `InputFile` and read the header let file = InputFile::new(&path, 4).unwrap(); // Get the data window from the header so we know how much storage we need // to allocate let data_window: [i32; 4] = *file.header().data_window(); // Create a `Frame` to hold the channels we want to read from the file. // `Frame` handles: // * Allocating the required memory (or it can use existing storage with the // `with_vec[_multi]()` constructors). // * Creating slices with the correct offsets into the storage for the // requested channels. Note that asking for ["R"] or ["R", "G", "B"] here // would be a runtime error as the `Pixel` trait we've implemented for `Rgba` // tells the constructor to expect 4 channels, but we could ask for ["R", "G", "B", "A", // "diff.R", "diff.G", diff.B", "Z"] and it would pack those 8 channels into // 2 `Rgba`s per pixel. let frame_rgba = Frame::new::<Rgba, _, _>(&["R", "G", "B", "A"], data_window)?; // Consume the `InputFile` into an `InputFileReader` by giving it the list // of `Frames` to read into. This internally creates the `FrameBuffer` and // gives it to the `InputFile` rather than having those as separate operations // which create lifetime dependencies between all the moving parts. // `InputFileReader` can have a safe `read_pixels()` method because it owns // all the data associated with the read operation. // `read_pixels()` consumes `InputFileReader` and returns an `InputFile` and // the completed `Frame`s. let (_file, mut frames) = file .into_reader(vec![frame_rgba])? .read_pixels(data_window[1], data_window[3])?; // Consume the `Frame` into a Vec (or we could just get a reference // to the data if we wanted) let pixels: Vec<Rgba> = frames.remove(0).into_vec(); for _rgba in pixels.iter() { // ... do something with pixels } Ok(()) } #[cfg(all(test, feature = "impl_cgmath"))] #[test] fn read_input_safe_cgmath1() -> Result<()> { use crate::{Frame, Rgba}; use std::path::PathBuf; let path = PathBuf::from( std::env::var("CARGO_MANIFEST_DIR") .expect("CARGO_MANIFEST_DIR not set"), ) .join("images") .join("window.exr"); // Use the Box2i implementation of Bound2 which we define as // struct Box2<T> { // min: cgmath::Vector2<T>, // max: cgmath::Vector2<T>, // } // when the "impl_cgmath" feature is enabled (which transitively enables the\ // "cgmath" feature in imath-traits. use cgmath::Vector2; use imath_traits::impl_cgmath::Box2i; // Open the `InputFile` and read the header let file = InputFile::new(&path, 4).unwrap(); // Get the data window from the header so we know how much storage we need // to allocate let data_window: Box2i = *file.header().data_window(); // Create a `Frame` to hold the channels we want to read from the file. // `Frame` handles: // * Allocating the required memory (or it can use existing storage with the // `with_vec[_multi]()` constructors). // * Creating slices with the correct offsets into the storage for the // requested channels. Note that asking for ["R"] or ["R", "G", "B"] here // would be a runtime error as the `Pixel` trait we've implemented for `Rgba` // tells the constructor to expect 4 channels. let frame_rgba = Frame::new::<Vector2<f32>, _, _>(&["R", "G", "B", "A"], data_window)?; // Consume the `InputFile` into an `InputFileReader` by giving it the list // of `Frames` to read into. This internally creates the `FrameBuffer` and // gives it to the `InputFile` rather than having those as separate operations // which create lifetime dependencies between all the moving parts. // `InputFileReader` can have a safe `read_pixels()` method because it owns // all the data associated with the read operation. // `read_pixels()` consumes `InputFileReader` and returns an `InputFile` and // the completed `Frame`s. let (_file, mut frames) = file .into_reader(vec![frame_rgba])? .read_pixels(data_window.min.y, data_window.max.y)?; // Consume the `Frame` into a Vec (or we could just get a reference // to the data if we wanted) let pixels: Vec<Rgba> = frames.remove(0).into_vec(); for _rgba in pixels.iter() { // ... do something with pixels } Ok(()) }
/// /// Prints to STDOUT if the log level is set to ```log_level=debug```. #[macro_export] macro_rules! debug_log { ($fmt:expr) => { if cfg!(feature = "log_level=debug") { println!($fmt); } }; ($fmt:expr, $($args:tt)*) => { if cfg!(feature = "log_level=debug") { println!($fmt, $($args)*); } }; } /// /// Prints to STDERR if the log level is set to ```log_level=error```. #[macro_export] macro_rules! error_log { ($fmt:expr) => { if cfg!(feature = "log_level=error") { eprintln!($fmt); } }; ($fmt:expr, $($args:tt)*) => { if cfg!(feature = "log_level=error") { eprintln!($fmt, $($args)*); } }; }
use super::*; pub struct Camera { pub center: Vec2<f32>, pub target_position: Vec2<f32>, pub fov: f32, pub target_fov: f32, } impl Camera { pub fn new(fov: f32) -> Self { Self { center: vec2(0.0, 0.0), fov, target_fov: fov, target_position: vec2(0.0, 0.0), } } pub fn update(&mut self, delta_time: f32) { let delta_time = delta_time * 5.0; self.fov += (self.target_fov - self.fov) * delta_time.min(1.0); self.center += (self.target_position - self.center) * delta_time.min(1.0); } fn view_matrix(&self) -> Mat4<f32> { Mat4::scale_uniform(1.0 / self.fov) * Mat4::translate(-self.center.extend(0.0)) } fn projection_matrix(&self, framebuffer_size: Vec2<f32>) -> Mat4<f32> { Mat4::scale(vec3( 2.0 * framebuffer_size.y / framebuffer_size.x, 2.0, 1.0, )) } pub fn uniforms(&self, framebuffer_size: Vec2<f32>) -> impl ugli::Uniforms { ugli::uniforms! { u_projection_matrix: self.projection_matrix(framebuffer_size), u_view_matrix: self.view_matrix(), } } pub fn world_to_screen(&self, framebuffer_size: Vec2<f32>, pos: Vec2<f32>) -> Vec2<f32> { let pos = (self.projection_matrix(framebuffer_size) * self.view_matrix()) * pos.extend(0.0).extend(1.0); vec2( (pos.x + 1.0) / 2.0 * framebuffer_size.x, (pos.y + 1.0) / 2.0 * framebuffer_size.y, ) } pub fn screen_to_world(&self, framebuffer_size: Vec2<f32>, pos: Vec2<f32>) -> Vec2<f32> { let pos = vec2( pos.x / framebuffer_size.x * 2.0 - 1.0, pos.y / framebuffer_size.y * 2.0 - 1.0, ); let pos = (self.projection_matrix(framebuffer_size) * self.view_matrix()).inverse() * pos.extend(0.0).extend(1.0); pos.xy() } }
/* An implementation of SAT solver, based on "An Extensible SAT-solver" (Niklas Een, Niklas Sörensson, SAT 2003) */ use crate::*; use std::ops::Index; #[derive(Debug, PartialEq, Eq, Clone, Copy)] enum Reason { Undet, Branch, Clause(usize), } impl Reason { fn is_clause(self) -> bool { match self { Reason::Clause(_) => true, _ => false, } } } #[derive(Debug, Clone, Copy)] pub struct SolverStats { pub n_restart: u64, pub n_conflict: u64, pub n_propagation: u64, } impl SolverStats { fn new() -> SolverStats { SolverStats { n_restart: 0, n_conflict: 0, n_propagation: 0, } } } #[derive(Debug)] pub struct Solver { assignment: Vec<Value>, clauses: Vec<Clause>, queue: Vec<Literal>, reason: Vec<Reason>, watcher_clauses: Vec<Vec<usize>>, queue_top: usize, var_activity: Activity, cla_activity: Activity, trail_boundary: Vec<usize>, level: Vec<i32>, cla_erased: Vec<bool>, learnt: Vec<usize>, stats: SolverStats, } impl Solver { pub fn new() -> Solver { Solver { assignment: vec![], clauses: vec![], queue: vec![], reason: vec![], watcher_clauses: vec![], queue_top: 0, var_activity: Activity::new(1.0f64 / 0.95f64), cla_activity: Activity::new(1.0f64 / 0.999f64), trail_boundary: vec![], level: vec![], cla_erased: vec![], learnt: vec![], stats: SolverStats::new(), } } pub fn stats(&self) -> SolverStats { self.stats } pub fn new_var(&mut self) -> Var { let id = self.assignment.len() as i32; self.assignment.push(Value::Undet); self.reason.push(Reason::Undet); // each for positive/negative literals self.watcher_clauses.push(vec![]); self.watcher_clauses.push(vec![]); self.var_activity.add_entry(); self.level.push(-1); Var(id) } pub fn num_var(&self) -> i32 { self.assignment.len() as i32 } pub fn add_clause(&mut self, mut clause: Clause) -> bool { let clause_id = self.clauses.len(); if clause.len() == 0 { return false; } if clause.len() == 1 { return self.decide_checked(clause[0], Reason::Branch /* TODO */); } // TODO: choose better watcher for learnt clauses self.watcher_clauses[(!clause[0]).watch_id()].push(clause_id); if clause.len() >= 2 { let mut max_i = 1; let mut max_level = self.level[clause[1].var_id()]; for i in 2..clause.len() { if max_level < self.level[clause[i].var_id()] { max_i = i; max_level = self.level[clause[i].var_id()]; } } if max_i != 1 { clause.swap(1, max_i); } self.watcher_clauses[(!clause[1]).watch_id()].push(clause_id); } self.clauses.push(clause); self.cla_activity.add_entry(); self.cla_activity.bump(clause_id); self.cla_erased.push(false); true } pub fn assignment(&self) -> Vec<Value> { self.assignment.clone() } pub fn solve(&mut self) -> bool { let mut confl_threshold = 100u64; let mut learnt_threshold = self.clauses.len() as u64 / 3; loop { self.stats.n_restart += 1; self.queue_top = 0; // TODO: should be verified match self.search(confl_threshold, learnt_threshold) { Value::True => return true, Value::False => return false, Value::Undet => (), } confl_threshold = (confl_threshold as f64 * 1.5f64) as u64; learnt_threshold = (learnt_threshold as f64 * 1.1f64) as u64; } } pub fn search(&mut self, confl_threshold: u64, learnt_threshold: u64) -> Value { let mut n_confl = 0; 'outer: loop { if let Some(conflict) = self.propagate() { if self.trail_boundary.len() == 0 { return Value::False; } n_confl += 1; self.stats.n_conflict += 1; // inconsistent let learnt = self.analyze(conflict); self.pop_level(); let mut enq = None; let mut max_level = 0; for &lit in &learnt { match self.get_assignment_lit(lit) { Value::True => panic!(), Value::False => { max_level = max_level.max(self.level[lit.var_id()]); }, Value::Undet => match enq { Some(_) => panic!(), None => enq = Some(lit), } } } assert!(enq.is_some()); while self.trail_boundary.len() as i32 > max_level { self.pop_level(); } self.queue_top = self.queue.len(); if learnt.len() >= 2 { self.add_clause(learnt); self.learnt.push(self.clauses.len() - 1); self.decide_checked(enq.unwrap(), Reason::Clause(self.clauses.len() - 1)); } else { assert!(self.add_clause(learnt)); } self.var_activity.decay(); self.cla_activity.decay(); } else { if n_confl > confl_threshold { while self.trail_boundary.len() > 0 { self.pop_level(); } return Value::Undet; } if self.learnt.len() as i64 - self.queue.len() as i64 > learnt_threshold as i64 { self.reduce_db(); } // branch let pivot = self.var_activity.find_undecided(self); match pivot { Some(var) => { self.assume(Literal::new(var, false)); continue 'outer; } None => { return Value::True; } } } } } pub fn get_assignment(&self, Var(v): Var) -> Value { self.assignment[v as usize] } pub fn get_assignment_lit(&self, lit: Literal) -> Value { if lit.is_negated() { !self.get_assignment(lit.var()) } else { self.get_assignment(lit.var()) } } fn assume(&mut self, lit: Literal) { self.trail_boundary.push(self.queue.len()); assert!(self.decide_checked(lit, Reason::Branch)); } fn clear(&mut self, var: Var) { let var_id = var.0 as usize; self.reason[var_id] = Reason::Undet; self.assignment[var_id] = Value::Undet; self.level[var_id] = -1; } fn pop_queue(&mut self) { // Popping beyond the trail boundary is prohibited assert!(self.trail_boundary[self.trail_boundary.len() - 1] != self.queue.len()); let var = self.queue.pop().unwrap().var(); self.clear(var); } fn pop_level(&mut self) { debug_assert!(self.trail_boundary[self.trail_boundary.len() - 1] <= self.queue.len()); for _ in 0..(self.queue.len() - self.trail_boundary[self.trail_boundary.len() - 1]) { self.pop_queue(); } self.trail_boundary.pop(); } fn decide_checked(&mut self, lit: Literal, reason: Reason) -> bool { let current = self.get_assignment_lit(lit); match current { Value::True => true, Value::False => false, Value::Undet => { let var_id = lit.var_id(); self.assignment[var_id] = lit.value(); self.reason[var_id] = reason; self.level[var_id] = self.trail_boundary.len() as i32; self.queue.push(lit); true } } } fn propagate(&mut self) -> Option<Reason> { while self.queue_top < self.queue.len() { let lit = self.queue[self.queue_top]; self.stats.n_propagation += 1; let watch_id = lit.watch_id(); let mut watchers = vec![]; std::mem::swap(&mut self.watcher_clauses[watch_id], &mut watchers); for i in 0..watchers.len() { let clause_id = watchers[i]; if self.cla_erased[clause_id] { continue; } if !self.propagate_clause(clause_id, lit) { // reinsert remaining watchers for j in (i + 1)..watchers.len() { let w = watchers[j]; if !self.cla_erased[w] { self.watcher_clauses[watch_id].push(w); } } self.queue_top = self.queue.len(); return Some(Reason::Clause(clause_id)); } } self.queue_top += 1; } None } fn analyze(&mut self, mut conflict: Reason) -> Clause { let mut p: Option<Literal> = None; let mut visited = vec![false; self.num_var() as usize]; let mut counter = 0; let mut ret = vec![Literal(0)]; while !self.queue.is_empty() { if let Some(l) = p { visited[l.var_id()] = false; } let mut reason = vec![]; { let conflict = match conflict { Reason::Clause(c) => c, _ => panic!(), }; self.cla_activity.bump(conflict); for &lit in &self.clauses[conflict] { if Some(lit) != p { debug_assert!(p.is_none() || p.unwrap().var() != lit.var()); reason.push(lit); } } } for lit in reason { let var_id = lit.var_id(); if !visited[var_id] { self.var_activity.bump(lit.var_id()); if self.level[var_id] == self.trail_boundary.len() as i32 { counter += 1; } else { ret.push(lit); } visited[var_id] = true; } } while !visited[self.queue[self.queue.len() - 1].var_id()] { self.pop_queue(); } debug_assert!(!self.queue.is_empty()); let pb = self.queue[self.queue.len() - 1]; let var_id = pb.var_id(); p = Some(pb); counter -= 1; if counter == 0 { ret[0] = !p.unwrap(); break; } debug_assert!(self.reason[self.queue[self.queue.len() - 1].var_id()] != Reason::Branch); debug_assert!(self.reason[var_id].is_clause()); conflict = self.reason[var_id]; self.pop_queue(); } ret } fn propagate_clause(&mut self, clause_id: usize, p: Literal) -> bool { if self.clauses[clause_id][0] == !p { self.clauses[clause_id].swap(0, 1); } debug_assert!(self.clauses[clause_id][1] == !p); if self.get_assignment_lit(self.clauses[clause_id][0]) == Value::True { self.watcher_clauses[p.watch_id()].push(clause_id); return true; } for i in 2..self.clauses[clause_id].len() { if self.get_assignment_lit(self.clauses[clause_id][i]) != Value::False { self.clauses[clause_id].swap(1, i); self.watcher_clauses[(!self.clauses[clause_id][1]).watch_id()].push(clause_id); return true; } } self.watcher_clauses[p.watch_id()].push(clause_id); return self.decide_checked(self.clauses[clause_id][0], Reason::Clause(clause_id)) } fn reduce_db(&mut self) { { let cla_activity = &self.cla_activity; self.learnt.sort_by(|&x, &y| { cla_activity[x].partial_cmp(&cla_activity[y]).unwrap() }); } let mut learnt_nxt = vec![]; let threshold = self.cla_activity.var_inc / self.learnt.len() as f64; for i in 0..self.learnt.len() { let c = self.learnt[i]; let is_locked = (&self.clauses[c]).into_iter().any(|lit| self.reason[lit.var_id()] == Reason::Clause(c)); if !is_locked && (i < self.learnt.len() / 2 || self.cla_activity[c] < threshold) { self.cla_erased[c] = true; } else { learnt_nxt.push(c); } } self.learnt = learnt_nxt; } } const ACTIVITY_THRESHOLD: f64 = 1e100; #[derive(Debug)] struct Activity { activity: Vec<f64>, var_inc: f64, var_decay: f64, } impl Activity { fn new(var_decay: f64) -> Activity { Activity { activity: vec![], var_inc: 1.0, var_decay, } } fn add_entry(&mut self) { self.activity.push(0.0f64); } fn bump(&mut self, i: usize) { self.activity[i] += self.var_inc; if self.activity[i] > ACTIVITY_THRESHOLD { self.rescale(); } } fn decay(&mut self) { self.var_inc *= self.var_decay; } fn rescale(&mut self) { for a in &mut self.activity { *a *= 1.0 / ACTIVITY_THRESHOLD; } self.var_inc /= ACTIVITY_THRESHOLD; } fn find_undecided(&self, solver: &Solver) -> Option<Var> { let mut best: Option<usize> = None; for i in 0..self.activity.len() { if solver.assignment[i] == Value::Undet { if match best { Some(prev) => self.activity[prev] < self.activity[i], None => true, } { best = Some(i); } } } best.map(|i| Var(i as i32)) } } impl Index<usize> for Activity { type Output = f64; fn index(&self, i: usize) -> &f64 { &self.activity[i] } }
use mailbox_rs::{ mb_channel::*, mb_std::{ async_std::task::{Context, Poll}, *, }, }; pub struct WaitEvent; impl<RA: MBPtrReader, WA: MBPtrWriter, R: MBPtrResolver<READER = RA, WRITER = WA>> MBAsyncRPC<RA, WA, R> for WaitEvent { fn poll_cmd( &self, server_name: &str, _r: &R, req: &MBReqEntry, _cx: &mut Context, ) -> Poll<Option<MBRespEntry>> { extern "C" { fn poll_event(id: u32) -> u32; } match unsafe { poll_event(req.args[1]) } { 0 => { // println!("{} waiting event num:{}!", server_name, req.args[1]); Poll::Pending } 0xffffffff => panic!("{} event num {} not support!", server_name, req.args[1]), x => { let mut resp = MBRespEntry::default(); resp.words = 1; resp.rets = x; println!( "{} event num:{} ready, resp {}!", server_name, req.args[1], x ); Poll::Ready(Some(resp)) } } } } impl<RA: MBPtrReader, WA: MBPtrWriter, R: MBPtrResolver<READER = RA, WRITER = WA>> CustomAsycRPC<RA, WA, R> for WaitEvent { fn is_me(&self, action: u32) -> bool { action == 0x8 } }
use abi_stable::{ sabi_trait::prelude::TD_Opaque, std_types::{RArc, RBox, Tuple1, Tuple2, Tuple3} }; #[abi_stable::sabi_trait] pub trait RFoo<'a, T: Copy + 'a> { fn get(&'a self) -> &'a T; } impl<'a, A: Copy + 'a> RFoo<'a, A> for Tuple1<A> { fn get(&'a self) -> &'a A { &self.0 } } impl<'a, A: 'a, B: Copy + 'a> RFoo<'a, B> for Tuple2<A, B> { fn get(&'a self) -> &'a B { &self.1 } } impl<'a, A: 'a, B: 'a, C: Copy + 'a> RFoo<'a, C> for Tuple3<A, B, C> { fn get(&'a self) -> &'a C { &self.2 } } impl<'a, T> RFoo<'a, T> for RArc<T> where T: 'a + Copy, { fn get(&'a self) -> &'a T { &**self } } fn main() { let object = &RFoo_TO::from_ptr(RBox::new(RArc::new(76)), TD_Opaque); let tuple1_object = &RFoo_TO::from_ptr(RArc::new(Tuple1(100)), TD_Opaque); let tuple2_object = &RFoo_TO::from_value(Tuple2(101u32, 202_u32), TD_Opaque); let tuple3_object = &RFoo_TO::from_value(Tuple3(11, 22, 300_u32), TD_Opaque); assert_eq!(object.get(), &76); assert_eq!(tuple1_object.get(), &100); assert_eq!(tuple2_object.get(), &202); assert_eq!(tuple3_object.get(), &300); assert_eq!(RFoo::get(object), &76); assert_eq!(RFoo::get(tuple1_object), &100); assert_eq!(RFoo::get(tuple2_object), &202); assert_eq!(RFoo::get(tuple3_object), &300); }
mod bsp_level; mod bsp_lumps; mod lightmap_packer; mod vertex; pub use bsp_level::BspLevelLoader; use bsp_lumps::BspLumps; pub use vertex::Vertex;
use std::time::Duration; use stdweb::js; use yew::prelude::*; // This is because the inbuilt TimeoutService appears buggy, copying it here makes it work fn to_ms(duration: Duration) -> u32 { let ms = duration.subsec_millis(); ms + duration.as_secs() as u32 * 1000 } pub fn create_timeout(duration: Duration, callback: Callback<()>) { let callback = move || { callback.emit(()); }; let ms = to_ms(duration); let _handle = js! { var callback = @{callback}; var action = function() { callback(); callback.drop(); }; var delay = @{ms}; return { timeout_id: setTimeout(action, delay), callback: callback, }; }; }
use futures::future::join_all; use generational_arena::{Arena, Index}; use nalgebra::Vector2; use std::env::args; use std::error::Error; use std::net::SocketAddr; use std::num::Wrapping; use std::time::Duration; use std::time::SystemTime; use tokio::net::{TcpListener, TcpStream, UdpSocket}; use tokio::prelude::*; use tokio::sync::mpsc::{channel, Sender}; use tokio::time::interval; use game; #[derive(Debug)] struct Player { player: game::Player, tcp_tx: Sender<game::TcpClientMessage>, random_bytes: [u8; game::NUM_RANDOM_BYTES], udp_addr: Option<SocketAddr>, input: Vector2<f64>, angle: f64, firing: bool, fire_counter: f64, } #[derive(Debug)] struct Bullet { bullet: game::Bullet, velocity: Vector2<f64>, lifetime: f64, } fn accept( players: &mut Arena<Player>, bullets: &Arena<Bullet>, stream: TcpStream, mut internal_tcp_tx: Sender<(Index, Option<game::TcpServerMessage>)>, tick_rate: u32, tick_zero: SystemTime, tick: game::Tick, ) { println!("connection!"); let (tx, mut rx) = channel(4); let idx = match players.try_insert(Player { player: game::Player { id: 0, // Set below. radius: 1.0, position: Vector2::new(0.0, 0.0), velocity: Vector2::new(0.0, 0.0), }, tcp_tx: tx, udp_addr: None, random_bytes: rand::random(), input: Vector2::new(0.0, 0.0), angle: 0.0, firing: false, fire_counter: 0.0, }) { Ok(idx) => idx, Err(_) => { println!("rejecting connection; too many players"); return; } }; // Set the user ID to some combinaiton of the arena index and generation. let id = idx.into_raw_parts().0 as u8; players[idx].player.id = id; // TODO(jack) Broadcast PlayerLeft messages. // Broadcast PlayerJoined messages. let mut tcp_txs: Vec<_> = players .iter() .filter(|(other_idx, _)| *other_idx != idx) .map(|(_, p)| p.tcp_tx.clone()) .collect(); let msg = game::TcpClientMessage::PlayerJoined(id); tokio::spawn(async move { let join_handles = tcp_txs.iter_mut().map(|tcp_tx| tcp_tx.send(msg.clone())); join_all(join_handles).await; }); // Start tasks to read-from / write-to the TCP socket. let (mut reader, mut writer) = stream.into_split(); tokio::spawn(async move { loop { const MAX_PACKET_SIZE_PLUS_ONE: usize = 64; let mut buf: [u8; MAX_PACKET_SIZE_PLUS_ONE] = [0; MAX_PACKET_SIZE_PLUS_ONE]; let num_bytes = match reader.read(&mut buf).await { Ok(0) => break, Ok(MAX_PACKET_SIZE_PLUS_ONE) => break, Err(err) => { eprintln!("{}", err); break; } Ok(num_bytes) => num_bytes, }; match bincode::deserialize(&buf[..num_bytes]) { Ok(msg) => match internal_tcp_tx.send((idx, Some(msg))).await { Ok(_) => (), Err(_) => break, }, Err(err) => { eprintln!("{}", err); break; } }; } // One consequence of every client publishing TCP packets to the same channel // is that we don't know when any one disconnects. // We signal it here with a `None`. internal_tcp_tx.send((idx, None)).await.ok(); }); let random_bytes = players[idx].random_bytes.clone(); let update = game::WorldUpdate { tick, players: players.iter().map(|(_, p)| p.player).collect(), bullets: bullets.iter().map(|(_, b)| b.bullet).collect(), }; tokio::spawn(async move { // Send the init packet. // For now, this will just include a random sequence of bytes. // We'll then wait for the random sequence of bytes via UDP to identify the client's external port number. let bytes = bincode::serialize(&game::TcpClientMessage::Init(game::ClientInit { id, random_bytes, update, tick_rate: tick_rate as u8, tick_zero, })) .unwrap(); if let Err(err) = writer.write_all(&bytes[..]).await { eprintln!("{}", err); return; } println!("wrote init message"); loop { match rx.recv().await { Some(msg) => { if let Err(_) = writer .write_all(bincode::serialize(&msg).unwrap().as_slice()) .await { break; } } None => break, }; } }); } fn step(players: &mut Arena<Player>, bullets: &mut Arena<Bullet>, dt: f64) { // Apply player impulse. for (_, player) in players.iter_mut() { let acceleration = 64.0; let max_velocity = 16.0; let friction = 16.0; // Acceleration ranges from `friction` to `friction + acceleration`, // and is inversely proportional to the projection of the current velocity onto the input vector. let acceleration_index = player.player.velocity.dot(&player.input) / max_velocity; let acceleration_index = if acceleration_index < 0.0 { 0.0 } else { acceleration_index.sqrt() }; let adjusted_acceleration = friction + acceleration * (1.0 - acceleration_index); player.player.velocity += adjusted_acceleration * dt * player.input; let dampened_velocity_unclamped = player.player.velocity.magnitude() - dt * friction; let dampened_velocity = if dampened_velocity_unclamped < 0.0 { 0.0 } else { dampened_velocity_unclamped }; let velocity_unit = player .player .velocity .try_normalize(0.0) .unwrap_or(Vector2::new(0.0, 0.0)); player.player.velocity = dampened_velocity * velocity_unit; player.player.position += dt * player.player.velocity; } // Remove expired bullets. let bullets_to_remove: Vec<_> = bullets .iter() .filter(|(_, b)| b.lifetime > 1.0) .map(|(idx, _)| idx) .collect(); for idx in bullets_to_remove.iter() { bullets.remove(*idx); } // Fire bullets. for (_, player) in players.iter_mut().filter(|(_, p)| p.firing) { let rof = 30.0; player.fire_counter += rof * dt; if player.fire_counter >= 1.0 { player.fire_counter %= 1.0; let idx = match bullets.try_insert(Bullet { bullet: game::Bullet { id: 0, player_id: player.player.id, position: player.player.position, angle: player.angle, radius: 0.5, }, velocity: 32.0 * Vector2::new(player.angle.cos(), player.angle.sin()), lifetime: 0.0, }) { Ok(idx) => idx, Err(_) => { eprintln!("too many bullets!"); break; } }; // Set the user ID to the arena index. let raw_parts = idx.into_raw_parts(); bullets[idx].bullet.id = ((raw_parts.0 & 10) | ((raw_parts.1 as usize) << 10)) as u16; } } // Update bullets. for (_, bullet) in bullets.iter_mut() { bullet.bullet.position += dt * bullet.velocity; bullet.lifetime += dt; } // Manage collisions. // We have to collect the idxs to avoid borrowing `players`. let idxs: Vec<_> = players.iter().map(|(idx, _)| idx).collect(); let idx_pairs = idxs .iter() .map(|a| idxs.iter().map(move |b| (a, b))) .flatten() .filter(|(a, b)| a.into_raw_parts().0 < b.into_raw_parts().0); for (a, b) in idx_pairs { let (a, b) = players.get2_mut(*a, *b); let a = a.unwrap(); let b = b.unwrap(); let distance = match a.player.position - b.player.position { v if v.x == 0.0 && v.y == 0.0 => Vector2::new(0.001, 0.001), v => v, }; let max_distance = a.player.radius + b.player.radius; if distance.magnitude_squared() >= max_distance.powi(2) { continue; // No collision. } let displacement_unit = distance.try_normalize(0.0).unwrap(); let displacement = displacement_unit * (max_distance - distance.magnitude()); a.player.position += 0.5 * displacement; b.player.position += -0.5 * displacement; let momentum = a.player.velocity.magnitude() + b.player.velocity.magnitude(); let elasticity = 2.0; a.player.velocity = 0.5 * elasticity * momentum * displacement_unit; b.player.velocity = -0.5 * elasticity * momentum * displacement_unit; } } #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { let port: u32 = match args().nth(1).and_then(|s| s.parse().ok()) { Some(port) => port, None => { eprintln!("Usage: {} PORT", args().nth(0).unwrap()); return Ok(()); } }; let mut players = Arena::with_capacity(16); let mut bullets = Arena::with_capacity(1024); let tick_rate = 60; let mut ticker = interval(Duration::from_secs(1) / tick_rate); let snapshot_rate = 10; let mut snapshot_ticker = interval(Duration::from_secs(1) / snapshot_rate); let mut tcp_listener = TcpListener::bind(format!("0.0.0.0:{}", port)).await?; let mut udp_socket = UdpSocket::bind(format!("0.0.0.0:{}", port)).await?; // tcp_rx is our global receiver for TCP events. // This means that each player holds a copy of tcp_tx which packets are passed to. let (tcp_tx, mut tcp_rx) = channel(4); let mut tick = Wrapping(0); let tick_zero = SystemTime::now(); loop { const MAX_PACKET_SIZE_PLUS_ONE: usize = 64; let mut buf: [u8; MAX_PACKET_SIZE_PLUS_ONE] = [0; MAX_PACKET_SIZE_PLUS_ONE]; // TODO(jack) Redesign this select! call to execute as little code linearly as possible. tokio::select! { _ = ticker.tick() => { // Update game state. let dt = 1.0 / tick_rate as f64; // TODO(jack) Measure actual elapsed time. step(&mut players, &mut bullets, dt); tick = tick + Wrapping(1); }, _ = snapshot_ticker.tick() => { // Broadcast. let update = game::WorldUpdate { tick: tick.0, players: players.iter().map(|(_, p)| p.player).collect(), bullets: bullets.iter().map(|(_, b)| b.bullet).collect(), }; let bytes = bincode::serialize(&game::UdpClientMessage::WorldUpdate(update)).unwrap(); for (_, player) in players.iter().filter(|(_, p)| p.udp_addr.is_some()) { udp_socket.send_to(&bytes, player.udp_addr.unwrap()).await?; } }, accept_result = tcp_listener.accept() => match accept_result { Ok((stream, _)) => accept(&mut players, &bullets, stream, tcp_tx.clone(), tick_rate, tick_zero, tick.0), Err(err) => { eprintln!("{}", err); break }, }, // TODO(jack) TCP messages from the client should end up in a channel. result = tcp_rx.recv() => match result { Some((idx, None)) => { println!("disconnection!"); let id = players[idx].player.id; // Broadcast that a player left. let mut tcp_txs: Vec<_> = players .iter() .filter(|(other_idx, _)| *other_idx != idx) .map(|(_, p)| p.tcp_tx.clone()) .collect(); tokio::spawn(async move { let msg = game::TcpClientMessage::PlayerLeft(id); let join_handles = tcp_txs .iter_mut() .map(|tcp_tx| tcp_tx.send(msg.clone())); // TODO(jack) Can we do this without allocations? join_all(join_handles).await; }); players.remove(idx); }, Some((idx, Some(msg))) => println!("{:?}: {:?}", idx, msg), None => break, }, result = udp_socket.recv_from(&mut buf) => match result { Ok((0, _)) => break, Ok((MAX_PACKET_SIZE_PLUS_ONE, _)) => break, Ok((num_bytes, socket_addr)) => { let bytes = &buf[..num_bytes]; let msg: game::UdpServerMessage = match bincode::deserialize(&bytes) { Ok(msg) => msg, Err(err) => { eprintln!("{}", err); continue }, }; match msg { game::UdpServerMessage::Init(game::ServerInit { random_bytes }) => { println!("received init message: {:?}", random_bytes); if let Some((_, player)) = players.iter_mut().find(|(_, player)| player.random_bytes == random_bytes) { player.udp_addr = Some(socket_addr); println!("{:?}", player.udp_addr); } }, game::UdpServerMessage::PlayerInput(inputs) => { let (_, player) = match players.iter_mut().find(|(_, player)| player.udp_addr.is_some() && player.udp_addr.unwrap() == socket_addr) { Some((idx, player)) => (idx, player), None => continue, }; // TODO(jack) Apply the inputs according to their tick. // Right now, we're just taking the most recent one. if inputs.len() == 0 { continue } let input = inputs.iter().last().unwrap(); player.input = Vector2::new( (input.right as i32 - input.left as i32) as f64, (input.down as i32 - input.up as i32) as f64, ).try_normalize(0.0).unwrap_or(Vector2::new(0.0, 0.0)); player.angle = input.angle; // TODO(jack) We probably just want to compose input in the player struct. if input.mouse_left { player.firing = true; } else { player.firing = false; player.fire_counter = 0.0; } }, }; }, Err(err) => { eprintln!("{}", err); break }, } } } Ok(()) }
pub fn parsing_table() -> [[&'static str; 33]; 25] { /* function that creates the parsing table */ let mut table = [["error"; 33]; 25]; /* defining non terminals of the table */ table[0][0] = "null"; table[1][0] = "S"; table[2][0] = "V"; table[3][0] = "I"; table[4][0] = "G"; table[5][0] = "N"; table[6][0] = "N`"; table[7][0] = "Q"; table[8][0] = "Q`"; table[9][0] = "M"; table[10][0] = "E"; table[11][0] = "E`"; table[12][0] = "T"; table[13][0] = "T`"; table[14][0] = "A"; table[15][0] = "A`"; table[16][0] = "B"; table[17][0] = "B`"; table[18][0] = "C"; table[19][0] = "C`"; table[20][0] = "F"; table[21][0] = "H"; table[22][0] = "D"; table[23][0] = "O"; table[24][0] = "J"; /* defining terminals of the table */ table[0][1] = "["; table[0][2] = "]"; table[0][3] = "{"; table[0][4] = "}"; table[0][5] = "ta"; table[0][6] = "agar"; table[0][7] = "^"; table[0][8] = "Ashari"; table[0][9] = "Sahih"; table[0][10] = "Harf"; table[0][11] = "("; table[0][12] = ")"; table[0][13] = "="; table[0][14] = "&BM"; table[0][15] = "&KM"; table[0][16] = "&K"; table[0][17] = "&B"; table[0][18] = "&MM"; table[0][19] = "Jam"; table[0][20] = "Kam"; table[0][21] = "Zarb"; table[0][22] = "Tagsim"; table[0][23] = "Bagimonde"; table[0][24] = "YekiBala"; table[0][25] = "YekiPain"; table[0][26] = "id"; table[0][27] = "num"; table[0][28] = "str"; table[0][29] = "Benevis"; table[0][30] = "Begir"; table[0][31] = ","; table[0][32] = "$"; /* table's rules */ table[1][1] = "[ S ]"; table[11][4] = " "; table[13][4] = " "; table[15][4] = " "; table[17][4] = " "; table[19][4] = " "; table[1][5] = "ta { E } S"; table[1][6] = "agar { E } S"; table[6][7] = " "; table[8][7] = " "; table[11][7] = " "; table[13][7] = " "; table[15][7] = " "; table[17][7] = " "; table[19][7] = " "; table[1][8] = "V ^"; table[2][8] = "I N"; table[3][8] = "Ashari"; table[1][9] = "V ^"; table[2][9] = "I N"; table[3][9] = "Sahih"; table[1][10] = "V ^"; table[2][10] = "I N"; table[3][10] = "Harf"; table[1][11] = "E ^"; table[10][11] = "T E`"; table[12][11] = "A T`"; table[14][11] = "B A`"; table[16][11] = "C B`"; table[18][11] = "F C`"; table[20][11] = "H"; table[21][11] = "( E )"; table[11][12] = " "; table[13][12] = " "; table[15][12] = " "; table[17][12] = " "; table[19][12] = " "; table[22][12] = " "; table[23][12] = " "; table[8][13] = "= E Q`"; table[11][13] = "= T E`"; table[13][13] = " "; table[15][13] = " "; table[17][13] = " "; table[19][13] = " "; table[13][14] = "&BM A T`"; table[15][14] = " "; table[17][14] = " "; table[19][14] = " "; table[13][15] = "&KM A T`"; table[15][15] = " "; table[17][15] = " "; table[19][15] = " "; table[13][16] = "&K A T`"; table[15][16] = " "; table[17][16] = " "; table[19][16] = " "; table[13][17] = "&B A T`"; table[15][17] = " "; table[17][17] = " "; table[19][17] = " "; table[13][18] = "&MM A T`"; table[15][18] = " "; table[17][18] = " "; table[19][18] = " "; table[15][19] = "Jam B A`"; table[17][19] = " "; table[19][19] = " "; table[15][20] = "Kam B A`"; table[17][20] = " "; table[19][20] = " "; table[17][21] = "Zarb C B`"; table[19][21] = " "; table[17][22] = "Tagsim C B`"; table[19][22] = " "; table[17][23] = "Bagimonde C B`"; table[19][23] = " "; table[1][24] = "E ^"; table[10][24] = "T E`"; table[12][24] = "A T`"; table[14][24] = "B A`"; table[16][24] = "C B`"; table[18][24] = "F C`"; table[19][24] = "YekiBala C`"; table[20][24] = "YekiBala F"; table[1][25] = "E ^"; table[10][25] = "T E`"; table[12][25] = "A T`"; table[14][25] = "B A`"; table[16][25] = "C B`"; table[18][25] = "F C`"; table[19][25] = "YekiPain C`"; table[20][25] = "YekiPain F"; table[1][26] = "E ^"; table[5][26] = "Q N`"; table[7][26] = "M Q`"; table[9][26] = "id"; table[10][26] = "T E`"; table[12][26] = "A T`"; table[14][26] = "B A`"; table[16][26] = "C B`"; table[18][26] = "F C`"; table[20][26] = "H"; table[21][26] = "id"; table[1][27] = "E ^"; table[10][27] = "T E`"; table[12][27] = "A T`"; table[14][27] = "B A`"; table[16][27] = "C B`"; table[18][27] = "F C`"; table[20][27] = "H"; table[21][27] = "num"; table[1][28] = "E ^"; table[10][28] = "T E`"; table[12][28] = "A T`"; table[14][28] = "B A`"; table[16][28] = "C B`"; table[18][28] = "F C`"; table[20][28] = "H"; table[21][28] = "str"; table[22][28] = "str D"; table[1][29] = "G ^"; table[4][29] = "Benevis ( D O )"; table[1][30] = "G ^"; table[4][30] = "Begir ( D O )"; table[6][31] = ", Q N`"; table[8][31] = " "; table[11][31] = " "; table[13][31] = " "; table[15][31] = " "; table[17][31] = " "; table[19][31] = " "; table[22][31] = " "; table[23][31] = ", id O"; return table; }
use sqlx::types::chrono; use sqlx::FromRow; #[derive(FromRow, Debug)] pub struct ExamModel { pub id: i32, pub name: String, pub description: String, } #[derive(FromRow, Debug)] pub struct QuestionModel { pub id: i32, pub content: String, } #[derive(FromRow, Debug)] pub struct AnswerModel { pub id: i32, pub content: String, } #[derive(FromRow, Debug)] pub struct AnswerCorretionModel { pub is_correct: bool, } #[derive(FromRow, Debug)] pub struct IdModel { pub id: i32, } #[derive(FromRow, Debug)] pub struct FinishedAtModel { pub finished_at: Option<chrono::DateTime<chrono::Utc>>, }
#[macro_use] extern crate clap; extern crate surf; extern crate serde_json; extern crate image; extern crate url; use async_std::task; use clap::App; use serde_json::Value; use std::io::Cursor; use std::str::from_utf8; use url::form_urlencoded::{byte_serialize}; fn main() -> Result<(), surf::Exception> { let yaml = load_yaml!("../cli.yml"); let matches = App::from_yaml(yaml).get_matches(); let card_name = matches.value_of("CARD").unwrap(); task::block_on(get_card(card_name)).unwrap(); Ok(()) } async fn get_card(name: &str) -> Result<(), surf::Exception> { let cardname: String = byte_serialize(name.as_bytes()).collect(); let url = format!("https://api.magicthegathering.io/v1/cards?name=\"{}\"", cardname); let body: String = surf::get(url).recv_string().await?; let json = parse_json(&body); let mut card_url = get_card_url(json); card_url.insert(4, 's'); //convert to https let image = surf::get(card_url).await?.body_bytes().await?; print_card(image); Ok(()) } fn parse_json(json: &str) -> serde_json::Value { let root: Value = match serde_json::from_str(json) { Ok(val) => val, Err(_) => serde_json::Value::Null, }; root } // Gets the `imageUrl` of the first card that has one fn get_card_url(json: Value) -> String { let cards = json["cards"].as_array().unwrap(); let c: Vec<Value> = cards.clone(); let cards_with_images: Vec<Value> = c.into_iter().filter(|card| card["imageUrl"].is_string()).collect(); // using indexes here can fail let x = match cards_with_images[0]["imageUrl"].as_str() { Some(y) => y, None => "", }; String::from(x) } // Shamelessly stolen from // https://github.com/edelsonc/asciify/blob/master/src/main.rs fn print_card(img: Vec<u8>) -> () { let image = image::io::Reader::new(Cursor::new(img)) .with_guessed_format().unwrap().decode().unwrap(); let img = image.resize_exact(94, 47, image::FilterType::Nearest); let imgbuf = img.to_luma(); let ascii_art = imgbuf.pixels() .map(|p| intensity_to_ascii(&p[0]) ) .fold( String::new(), |s, p| s + p ); // we have one long string, but we need to chunk it by line let subs = ascii_art.as_bytes() .chunks(imgbuf.width() as usize) .map(from_utf8) .collect::<Result<Vec<&str>, _>>() .unwrap(); for s in subs { println!("{}", s); } } fn intensity_to_ascii(value: &u8) -> &str { // changes an intensity into an ascii character let ascii_chars = [ " ", ".", "^", ",", ":", "_", "=", "~", "+", "O", "o", "*", "#", "&", "%", "B", "@", "$" ]; let n_chars = ascii_chars.len() as u8; let step = 255u8 / n_chars; for i in 1..(n_chars - 1) { let comp = &step * i; if value < &comp { let idx = (i - 1) as usize; return ascii_chars[idx] } } ascii_chars[ (n_chars - 1) as usize ] }
//! //! Take an AST and transform it into bytecode //! //! Inspirational code: //! <https://github.com/python/cpython/blob/main/Python/compile.c> //! <https://github.com/micropython/micropython/blob/master/py/compile.c> #![deny(clippy::cast_possible_truncation)] use crate::{ error::{CodegenError, CodegenErrorType}, ir, symboltable::{self, SymbolFlags, SymbolScope, SymbolTable}, IndexSet, }; use itertools::Itertools; use num_complex::Complex64; use num_traits::ToPrimitive; use rustpython_ast::located::{self as located_ast, Located}; use rustpython_compiler_core::{ bytecode::{self, Arg as OpArgMarker, CodeObject, ConstantData, Instruction, OpArg, OpArgType}, Mode, }; use rustpython_parser_core::source_code::{LineNumber, SourceLocation}; use std::borrow::Cow; type CompileResult<T> = Result<T, CodegenError>; #[derive(PartialEq, Eq, Clone, Copy)] enum NameUsage { Load, Store, Delete, } enum CallType { Positional { nargs: u32 }, Keyword { nargs: u32 }, Ex { has_kwargs: bool }, } fn is_forbidden_name(name: &str) -> bool { // See https://docs.python.org/3/library/constants.html#built-in-constants const BUILTIN_CONSTANTS: &[&str] = &["__debug__"]; BUILTIN_CONSTANTS.contains(&name) } /// Main structure holding the state of compilation. struct Compiler { code_stack: Vec<ir::CodeInfo>, symbol_table_stack: Vec<SymbolTable>, source_path: String, current_source_location: SourceLocation, qualified_path: Vec<String>, done_with_future_stmts: bool, future_annotations: bool, ctx: CompileContext, class_name: Option<String>, opts: CompileOpts, } #[derive(Debug, Clone, Default)] pub struct CompileOpts { /// How optimized the bytecode output should be; any optimize > 0 does /// not emit assert statements pub optimize: u8, } #[derive(Debug, Clone, Copy)] struct CompileContext { loop_data: Option<(ir::BlockIdx, ir::BlockIdx)>, in_class: bool, func: FunctionContext, } #[derive(Debug, Clone, Copy, PartialEq)] enum FunctionContext { NoFunction, Function, AsyncFunction, } impl CompileContext { fn in_func(self) -> bool { self.func != FunctionContext::NoFunction } } /// Compile an located_ast::Mod produced from rustpython_parser::parse() pub fn compile_top( ast: &located_ast::Mod, source_path: String, mode: Mode, opts: CompileOpts, ) -> CompileResult<CodeObject> { match ast { located_ast::Mod::Module(located_ast::ModModule { body, .. }) => { compile_program(body, source_path, opts) } located_ast::Mod::Interactive(located_ast::ModInteractive { body, .. }) => match mode { Mode::Single => compile_program_single(body, source_path, opts), Mode::BlockExpr => compile_block_expression(body, source_path, opts), _ => unreachable!("only Single and BlockExpr parsed to Interactive"), }, located_ast::Mod::Expression(located_ast::ModExpression { body, .. }) => { compile_expression(body, source_path, opts) } located_ast::Mod::FunctionType(_) => panic!("can't compile a FunctionType"), } } /// A helper function for the shared code of the different compile functions fn compile_impl<Ast: ?Sized>( ast: &Ast, source_path: String, opts: CompileOpts, make_symbol_table: impl FnOnce(&Ast) -> Result<SymbolTable, symboltable::SymbolTableError>, compile: impl FnOnce(&mut Compiler, &Ast, SymbolTable) -> CompileResult<()>, ) -> CompileResult<CodeObject> { let symbol_table = match make_symbol_table(ast) { Ok(x) => x, Err(e) => return Err(e.into_codegen_error(source_path)), }; let mut compiler = Compiler::new(opts, source_path, "<module>".to_owned()); compile(&mut compiler, ast, symbol_table)?; let code = compiler.pop_code_object(); trace!("Compilation completed: {:?}", code); Ok(code) } /// Compile a standard Python program to bytecode pub fn compile_program( ast: &[located_ast::Stmt], source_path: String, opts: CompileOpts, ) -> CompileResult<CodeObject> { compile_impl( ast, source_path, opts, SymbolTable::scan_program, Compiler::compile_program, ) } /// Compile a Python program to bytecode for the context of a REPL pub fn compile_program_single( ast: &[located_ast::Stmt], source_path: String, opts: CompileOpts, ) -> CompileResult<CodeObject> { compile_impl( ast, source_path, opts, SymbolTable::scan_program, Compiler::compile_program_single, ) } pub fn compile_block_expression( ast: &[located_ast::Stmt], source_path: String, opts: CompileOpts, ) -> CompileResult<CodeObject> { compile_impl( ast, source_path, opts, SymbolTable::scan_program, Compiler::compile_block_expr, ) } pub fn compile_expression( ast: &located_ast::Expr, source_path: String, opts: CompileOpts, ) -> CompileResult<CodeObject> { compile_impl( ast, source_path, opts, SymbolTable::scan_expr, Compiler::compile_eval, ) } macro_rules! emit { ($c:expr, Instruction::$op:ident { $arg:ident$(,)? }$(,)?) => { $c.emit_arg($arg, |x| Instruction::$op { $arg: x }) }; ($c:expr, Instruction::$op:ident { $arg:ident : $arg_val:expr $(,)? }$(,)?) => { $c.emit_arg($arg_val, |x| Instruction::$op { $arg: x }) }; ($c:expr, Instruction::$op:ident( $arg_val:expr $(,)? )$(,)?) => { $c.emit_arg($arg_val, Instruction::$op) }; ($c:expr, Instruction::$op:ident$(,)?) => { $c.emit_no_arg(Instruction::$op) }; } impl Compiler { fn new(opts: CompileOpts, source_path: String, code_name: String) -> Self { let module_code = ir::CodeInfo { flags: bytecode::CodeFlags::NEW_LOCALS, posonlyarg_count: 0, arg_count: 0, kwonlyarg_count: 0, source_path: source_path.clone(), first_line_number: LineNumber::MIN, obj_name: code_name, blocks: vec![ir::Block::default()], current_block: ir::BlockIdx(0), constants: IndexSet::default(), name_cache: IndexSet::default(), varname_cache: IndexSet::default(), cellvar_cache: IndexSet::default(), freevar_cache: IndexSet::default(), }; Compiler { code_stack: vec![module_code], symbol_table_stack: Vec::new(), source_path, current_source_location: SourceLocation::default(), qualified_path: Vec::new(), done_with_future_stmts: false, future_annotations: false, ctx: CompileContext { loop_data: None, in_class: false, func: FunctionContext::NoFunction, }, class_name: None, opts, } } fn error(&mut self, error: CodegenErrorType) -> CodegenError { self.error_loc(error, self.current_source_location) } fn error_loc(&mut self, error: CodegenErrorType, location: SourceLocation) -> CodegenError { CodegenError { error, location: Some(location), source_path: self.source_path.clone(), } } fn push_output( &mut self, flags: bytecode::CodeFlags, posonlyarg_count: u32, arg_count: u32, kwonlyarg_count: u32, obj_name: String, ) { let source_path = self.source_path.clone(); let first_line_number = self.get_source_line_number(); let table = self .symbol_table_stack .last_mut() .unwrap() .sub_tables .remove(0); let cellvar_cache = table .symbols .iter() .filter(|(_, s)| s.scope == SymbolScope::Cell) .map(|(var, _)| var.clone()) .collect(); let freevar_cache = table .symbols .iter() .filter(|(_, s)| { s.scope == SymbolScope::Free || s.flags.contains(SymbolFlags::FREE_CLASS) }) .map(|(var, _)| var.clone()) .collect(); self.symbol_table_stack.push(table); let info = ir::CodeInfo { flags, posonlyarg_count, arg_count, kwonlyarg_count, source_path, first_line_number, obj_name, blocks: vec![ir::Block::default()], current_block: ir::BlockIdx(0), constants: IndexSet::default(), name_cache: IndexSet::default(), varname_cache: IndexSet::default(), cellvar_cache, freevar_cache, }; self.code_stack.push(info); } fn pop_code_object(&mut self) -> CodeObject { let table = self.symbol_table_stack.pop().unwrap(); assert!(table.sub_tables.is_empty()); self.code_stack .pop() .unwrap() .finalize_code(self.opts.optimize) } // could take impl Into<Cow<str>>, but everything is borrowed from ast structs; we never // actually have a `String` to pass fn name(&mut self, name: &str) -> bytecode::NameIdx { self._name_inner(name, |i| &mut i.name_cache) } fn varname(&mut self, name: &str) -> CompileResult<bytecode::NameIdx> { if Compiler::is_forbidden_arg_name(name) { return Err(self.error(CodegenErrorType::SyntaxError(format!( "cannot assign to {name}", )))); } Ok(self._name_inner(name, |i| &mut i.varname_cache)) } fn _name_inner( &mut self, name: &str, cache: impl FnOnce(&mut ir::CodeInfo) -> &mut IndexSet<String>, ) -> bytecode::NameIdx { let name = self.mangle(name); let cache = cache(self.current_code_info()); cache .get_index_of(name.as_ref()) .unwrap_or_else(|| cache.insert_full(name.into_owned()).0) .to_u32() } fn compile_program( &mut self, body: &[located_ast::Stmt], symbol_table: SymbolTable, ) -> CompileResult<()> { let size_before = self.code_stack.len(); self.symbol_table_stack.push(symbol_table); let (doc, statements) = split_doc(body); if let Some(value) = doc { self.emit_constant(ConstantData::Str { value }); let doc = self.name("__doc__"); emit!(self, Instruction::StoreGlobal(doc)) } if Self::find_ann(statements) { emit!(self, Instruction::SetupAnnotation); } self.compile_statements(statements)?; assert_eq!(self.code_stack.len(), size_before); // Emit None at end: self.emit_constant(ConstantData::None); emit!(self, Instruction::ReturnValue); Ok(()) } fn compile_program_single( &mut self, body: &[located_ast::Stmt], symbol_table: SymbolTable, ) -> CompileResult<()> { self.symbol_table_stack.push(symbol_table); if let Some((last, body)) = body.split_last() { for statement in body { if let located_ast::Stmt::Expr(located_ast::StmtExpr { value, .. }) = &statement { self.compile_expression(value)?; emit!(self, Instruction::PrintExpr); } else { self.compile_statement(statement)?; } } if let located_ast::Stmt::Expr(located_ast::StmtExpr { value, .. }) = &last { self.compile_expression(value)?; emit!(self, Instruction::Duplicate); emit!(self, Instruction::PrintExpr); } else { self.compile_statement(last)?; self.emit_constant(ConstantData::None); } } else { self.emit_constant(ConstantData::None); }; emit!(self, Instruction::ReturnValue); Ok(()) } fn compile_block_expr( &mut self, body: &[located_ast::Stmt], symbol_table: SymbolTable, ) -> CompileResult<()> { self.symbol_table_stack.push(symbol_table); self.compile_statements(body)?; if let Some(last_statement) = body.last() { match last_statement { located_ast::Stmt::Expr(_) => { self.current_block().instructions.pop(); // pop Instruction::Pop } located_ast::Stmt::FunctionDef(_) | located_ast::Stmt::AsyncFunctionDef(_) | located_ast::Stmt::ClassDef(_) => { let store_inst = self.current_block().instructions.pop().unwrap(); // pop Instruction::Store emit!(self, Instruction::Duplicate); self.current_block().instructions.push(store_inst); } _ => self.emit_constant(ConstantData::None), } } emit!(self, Instruction::ReturnValue); Ok(()) } // Compile statement in eval mode: fn compile_eval( &mut self, expression: &located_ast::Expr, symbol_table: SymbolTable, ) -> CompileResult<()> { self.symbol_table_stack.push(symbol_table); self.compile_expression(expression)?; emit!(self, Instruction::ReturnValue); Ok(()) } fn compile_statements(&mut self, statements: &[located_ast::Stmt]) -> CompileResult<()> { for statement in statements { self.compile_statement(statement)? } Ok(()) } fn load_name(&mut self, name: &str) -> CompileResult<()> { self.compile_name(name, NameUsage::Load) } fn store_name(&mut self, name: &str) -> CompileResult<()> { self.compile_name(name, NameUsage::Store) } fn mangle<'a>(&self, name: &'a str) -> Cow<'a, str> { symboltable::mangle_name(self.class_name.as_deref(), name) } fn check_forbidden_name(&mut self, name: &str, usage: NameUsage) -> CompileResult<()> { let msg = match usage { NameUsage::Store if is_forbidden_name(name) => "cannot assign to", NameUsage::Delete if is_forbidden_name(name) => "cannot delete", _ => return Ok(()), }; Err(self.error(CodegenErrorType::SyntaxError(format!("{msg} {name}")))) } fn compile_name(&mut self, name: &str, usage: NameUsage) -> CompileResult<()> { let name = self.mangle(name); self.check_forbidden_name(&name, usage)?; let symbol_table = self.symbol_table_stack.last().unwrap(); let symbol = symbol_table.lookup(name.as_ref()).expect( "The symbol must be present in the symbol table, even when it is undefined in python.", ); let info = self.code_stack.last_mut().unwrap(); let mut cache = &mut info.name_cache; enum NameOpType { Fast, Global, Deref, Local, } let op_typ = match symbol.scope { SymbolScope::Local if self.ctx.in_func() => { cache = &mut info.varname_cache; NameOpType::Fast } SymbolScope::GlobalExplicit => NameOpType::Global, SymbolScope::GlobalImplicit | SymbolScope::Unknown if self.ctx.in_func() => { NameOpType::Global } SymbolScope::GlobalImplicit | SymbolScope::Unknown => NameOpType::Local, SymbolScope::Local => NameOpType::Local, SymbolScope::Free => { cache = &mut info.freevar_cache; NameOpType::Deref } SymbolScope::Cell => { cache = &mut info.cellvar_cache; NameOpType::Deref } // // TODO: is this right? // SymbolScope::Unknown => NameOpType::Global, }; if NameUsage::Load == usage && name == "__debug__" { self.emit_constant(ConstantData::Boolean { value: self.opts.optimize == 0, }); return Ok(()); } let mut idx = cache .get_index_of(name.as_ref()) .unwrap_or_else(|| cache.insert_full(name.into_owned()).0); if let SymbolScope::Free = symbol.scope { idx += info.cellvar_cache.len(); } let op = match op_typ { NameOpType::Fast => match usage { NameUsage::Load => Instruction::LoadFast, NameUsage::Store => Instruction::StoreFast, NameUsage::Delete => Instruction::DeleteFast, }, NameOpType::Global => match usage { NameUsage::Load => Instruction::LoadGlobal, NameUsage::Store => Instruction::StoreGlobal, NameUsage::Delete => Instruction::DeleteGlobal, }, NameOpType::Deref => match usage { NameUsage::Load if !self.ctx.in_func() && self.ctx.in_class => { Instruction::LoadClassDeref } NameUsage::Load => Instruction::LoadDeref, NameUsage::Store => Instruction::StoreDeref, NameUsage::Delete => Instruction::DeleteDeref, }, NameOpType::Local => match usage { NameUsage::Load => Instruction::LoadNameAny, NameUsage::Store => Instruction::StoreLocal, NameUsage::Delete => Instruction::DeleteLocal, }, }; self.emit_arg(idx.to_u32(), op); Ok(()) } fn compile_statement(&mut self, statement: &located_ast::Stmt) -> CompileResult<()> { use located_ast::*; trace!("Compiling {:?}", statement); self.set_source_location(statement.location()); match &statement { // we do this here because `from __future__` still executes that `from` statement at runtime, // we still need to compile the ImportFrom down below Stmt::ImportFrom(located_ast::StmtImportFrom { module, names, .. }) if module.as_ref().map(|id| id.as_str()) == Some("__future__") => { self.compile_future_features(names)? } // if we find any other statement, stop accepting future statements _ => self.done_with_future_stmts = true, } match &statement { Stmt::Import(StmtImport { names, .. }) => { // import a, b, c as d for name in names { let name = &name; self.emit_constant(ConstantData::Integer { value: num_traits::Zero::zero(), }); self.emit_constant(ConstantData::None); let idx = self.name(&name.name); emit!(self, Instruction::ImportName { idx }); if let Some(alias) = &name.asname { for part in name.name.split('.').skip(1) { let idx = self.name(part); emit!(self, Instruction::LoadAttr { idx }); } self.store_name(alias.as_str())? } else { self.store_name(name.name.split('.').next().unwrap())? } } } Stmt::ImportFrom(StmtImportFrom { level, module, names, .. }) => { let import_star = names.iter().any(|n| &n.name == "*"); let from_list = if import_star { if self.ctx.in_func() { return Err(self.error_loc( CodegenErrorType::FunctionImportStar, statement.location(), )); } vec![ConstantData::Str { value: "*".to_owned(), }] } else { names .iter() .map(|n| ConstantData::Str { value: n.name.to_string(), }) .collect() }; let module_idx = module.as_ref().map(|s| self.name(s.as_str())); // from .... import (*fromlist) self.emit_constant(ConstantData::Integer { value: level.as_ref().map_or(0, |level| level.to_u32()).into(), }); self.emit_constant(ConstantData::Tuple { elements: from_list, }); if let Some(idx) = module_idx { emit!(self, Instruction::ImportName { idx }); } else { emit!(self, Instruction::ImportNameless); } if import_star { // from .... import * emit!(self, Instruction::ImportStar); } else { // from mod import a, b as c for name in names { let name = &name; let idx = self.name(name.name.as_str()); // import symbol from module: emit!(self, Instruction::ImportFrom { idx }); // Store module under proper name: if let Some(alias) = &name.asname { self.store_name(alias.as_str())? } else { self.store_name(name.name.as_str())? } } // Pop module from stack: emit!(self, Instruction::Pop); } } Stmt::Expr(StmtExpr { value, .. }) => { self.compile_expression(value)?; // Pop result of stack, since we not use it: emit!(self, Instruction::Pop); } Stmt::Global(_) | Stmt::Nonlocal(_) => { // Handled during symbol table construction. } Stmt::If(StmtIf { test, body, orelse, .. }) => { let after_block = self.new_block(); if orelse.is_empty() { // Only if: self.compile_jump_if(test, false, after_block)?; self.compile_statements(body)?; } else { // if - else: let else_block = self.new_block(); self.compile_jump_if(test, false, else_block)?; self.compile_statements(body)?; emit!( self, Instruction::Jump { target: after_block, } ); // else: self.switch_to_block(else_block); self.compile_statements(orelse)?; } self.switch_to_block(after_block); } Stmt::While(StmtWhile { test, body, orelse, .. }) => self.compile_while(test, body, orelse)?, Stmt::With(StmtWith { items, body, .. }) => self.compile_with(items, body, false)?, Stmt::AsyncWith(StmtAsyncWith { items, body, .. }) => { self.compile_with(items, body, true)? } Stmt::For(StmtFor { target, iter, body, orelse, .. }) => self.compile_for(target, iter, body, orelse, false)?, Stmt::AsyncFor(StmtAsyncFor { target, iter, body, orelse, .. }) => self.compile_for(target, iter, body, orelse, true)?, Stmt::Match(StmtMatch { subject, cases, .. }) => self.compile_match(subject, cases)?, Stmt::Raise(StmtRaise { exc, cause, .. }) => { let kind = match exc { Some(value) => { self.compile_expression(value)?; match cause { Some(cause) => { self.compile_expression(cause)?; bytecode::RaiseKind::RaiseCause } None => bytecode::RaiseKind::Raise, } } None => bytecode::RaiseKind::Reraise, }; emit!(self, Instruction::Raise { kind }); } Stmt::Try(StmtTry { body, handlers, orelse, finalbody, .. }) => self.compile_try_statement(body, handlers, orelse, finalbody)?, Stmt::TryStar(StmtTryStar { body, handlers, orelse, finalbody, .. }) => self.compile_try_star_statement(body, handlers, orelse, finalbody)?, Stmt::FunctionDef(StmtFunctionDef { name, args, body, decorator_list, returns, .. }) => self.compile_function_def( name.as_str(), args, body, decorator_list, returns.as_deref(), false, )?, Stmt::AsyncFunctionDef(StmtAsyncFunctionDef { name, args, body, decorator_list, returns, .. }) => self.compile_function_def( name.as_str(), args, body, decorator_list, returns.as_deref(), true, )?, Stmt::ClassDef(StmtClassDef { name, body, bases, keywords, decorator_list, .. }) => self.compile_class_def(name.as_str(), body, bases, keywords, decorator_list)?, Stmt::Assert(StmtAssert { test, msg, .. }) => { // if some flag, ignore all assert statements! if self.opts.optimize == 0 { let after_block = self.new_block(); self.compile_jump_if(test, true, after_block)?; let assertion_error = self.name("AssertionError"); emit!(self, Instruction::LoadGlobal(assertion_error)); match msg { Some(e) => { self.compile_expression(e)?; emit!(self, Instruction::CallFunctionPositional { nargs: 1 }); } None => { emit!(self, Instruction::CallFunctionPositional { nargs: 0 }); } } emit!( self, Instruction::Raise { kind: bytecode::RaiseKind::Raise, } ); self.switch_to_block(after_block); } } Stmt::Break(_) => match self.ctx.loop_data { Some((_, end)) => { emit!(self, Instruction::Break { target: end }); } None => { return Err( self.error_loc(CodegenErrorType::InvalidBreak, statement.location()) ); } }, Stmt::Continue(_) => match self.ctx.loop_data { Some((start, _)) => { emit!(self, Instruction::Continue { target: start }); } None => { return Err( self.error_loc(CodegenErrorType::InvalidContinue, statement.location()) ); } }, Stmt::Return(StmtReturn { value, .. }) => { if !self.ctx.in_func() { return Err( self.error_loc(CodegenErrorType::InvalidReturn, statement.location()) ); } match value { Some(v) => { if self.ctx.func == FunctionContext::AsyncFunction && self .current_code_info() .flags .contains(bytecode::CodeFlags::IS_GENERATOR) { return Err(self.error_loc( CodegenErrorType::AsyncReturnValue, statement.location(), )); } self.compile_expression(v)?; } None => { self.emit_constant(ConstantData::None); } } emit!(self, Instruction::ReturnValue); } Stmt::Assign(StmtAssign { targets, value, .. }) => { self.compile_expression(value)?; for (i, target) in targets.iter().enumerate() { if i + 1 != targets.len() { emit!(self, Instruction::Duplicate); } self.compile_store(target)?; } } Stmt::AugAssign(StmtAugAssign { target, op, value, .. }) => self.compile_augassign(target, op, value)?, Stmt::AnnAssign(StmtAnnAssign { target, annotation, value, .. }) => self.compile_annotated_assign(target, annotation, value.as_deref())?, Stmt::Delete(StmtDelete { targets, .. }) => { for target in targets { self.compile_delete(target)?; } } Stmt::Pass(_) => { // No need to emit any code here :) } Stmt::TypeAlias(_) => {} } Ok(()) } fn compile_delete(&mut self, expression: &located_ast::Expr) -> CompileResult<()> { match &expression { located_ast::Expr::Name(located_ast::ExprName { id, .. }) => { self.compile_name(id.as_str(), NameUsage::Delete)? } located_ast::Expr::Attribute(located_ast::ExprAttribute { value, attr, .. }) => { self.check_forbidden_name(attr.as_str(), NameUsage::Delete)?; self.compile_expression(value)?; let idx = self.name(attr.as_str()); emit!(self, Instruction::DeleteAttr { idx }); } located_ast::Expr::Subscript(located_ast::ExprSubscript { value, slice, .. }) => { self.compile_expression(value)?; self.compile_expression(slice)?; emit!(self, Instruction::DeleteSubscript); } located_ast::Expr::Tuple(located_ast::ExprTuple { elts, .. }) | located_ast::Expr::List(located_ast::ExprList { elts, .. }) => { for element in elts { self.compile_delete(element)?; } } located_ast::Expr::BinOp(_) | located_ast::Expr::UnaryOp(_) => { return Err(self.error(CodegenErrorType::Delete("expression"))) } _ => return Err(self.error(CodegenErrorType::Delete(expression.python_name()))), } Ok(()) } fn enter_function( &mut self, name: &str, args: &located_ast::Arguments, ) -> CompileResult<bytecode::MakeFunctionFlags> { let defaults: Vec<_> = args.defaults().collect(); let have_defaults = !defaults.is_empty(); if have_defaults { // Construct a tuple: let size = defaults.len().to_u32(); for element in &defaults { self.compile_expression(element)?; } emit!(self, Instruction::BuildTuple { size }); } let (kw_without_defaults, kw_with_defaults) = args.split_kwonlyargs(); if !kw_with_defaults.is_empty() { let default_kw_count = kw_with_defaults.len(); for (arg, default) in kw_with_defaults.iter() { self.emit_constant(ConstantData::Str { value: arg.arg.to_string(), }); self.compile_expression(default)?; } emit!( self, Instruction::BuildMap { size: default_kw_count.to_u32(), } ); } let mut func_flags = bytecode::MakeFunctionFlags::empty(); if have_defaults { func_flags |= bytecode::MakeFunctionFlags::DEFAULTS; } if !kw_with_defaults.is_empty() { func_flags |= bytecode::MakeFunctionFlags::KW_ONLY_DEFAULTS; } self.push_output( bytecode::CodeFlags::NEW_LOCALS | bytecode::CodeFlags::IS_OPTIMIZED, args.posonlyargs.len().to_u32(), (args.posonlyargs.len() + args.args.len()).to_u32(), args.kwonlyargs.len().to_u32(), name.to_owned(), ); let args_iter = std::iter::empty() .chain(&args.posonlyargs) .chain(&args.args) .map(|arg| arg.as_arg()) .chain(kw_without_defaults) .chain(kw_with_defaults.into_iter().map(|(arg, _)| arg)); for name in args_iter { self.varname(name.arg.as_str())?; } if let Some(name) = args.vararg.as_deref() { self.current_code_info().flags |= bytecode::CodeFlags::HAS_VARARGS; self.varname(name.arg.as_str())?; } if let Some(name) = args.kwarg.as_deref() { self.current_code_info().flags |= bytecode::CodeFlags::HAS_VARKEYWORDS; self.varname(name.arg.as_str())?; } Ok(func_flags) } fn prepare_decorators(&mut self, decorator_list: &[located_ast::Expr]) -> CompileResult<()> { for decorator in decorator_list { self.compile_expression(decorator)?; } Ok(()) } fn apply_decorators(&mut self, decorator_list: &[located_ast::Expr]) { // Apply decorators: for _ in decorator_list { emit!(self, Instruction::CallFunctionPositional { nargs: 1 }); } } fn compile_try_statement( &mut self, body: &[located_ast::Stmt], handlers: &[located_ast::ExceptHandler], orelse: &[located_ast::Stmt], finalbody: &[located_ast::Stmt], ) -> CompileResult<()> { let handler_block = self.new_block(); let finally_block = self.new_block(); // Setup a finally block if we have a finally statement. if !finalbody.is_empty() { emit!( self, Instruction::SetupFinally { handler: finally_block, } ); } let else_block = self.new_block(); // try: emit!( self, Instruction::SetupExcept { handler: handler_block, } ); self.compile_statements(body)?; emit!(self, Instruction::PopBlock); emit!(self, Instruction::Jump { target: else_block }); // except handlers: self.switch_to_block(handler_block); // Exception is on top of stack now for handler in handlers { let located_ast::ExceptHandler::ExceptHandler( located_ast::ExceptHandlerExceptHandler { type_, name, body, .. }, ) = &handler; let next_handler = self.new_block(); // If we gave a typ, // check if this handler can handle the exception: if let Some(exc_type) = type_ { // Duplicate exception for test: emit!(self, Instruction::Duplicate); // Check exception type: self.compile_expression(exc_type)?; emit!( self, Instruction::TestOperation { op: bytecode::TestOperator::ExceptionMatch, } ); // We cannot handle this exception type: emit!( self, Instruction::JumpIfFalse { target: next_handler, } ); // We have a match, store in name (except x as y) if let Some(alias) = name { self.store_name(alias.as_str())? } else { // Drop exception from top of stack: emit!(self, Instruction::Pop); } } else { // Catch all! // Drop exception from top of stack: emit!(self, Instruction::Pop); } // Handler code: self.compile_statements(body)?; emit!(self, Instruction::PopException); if !finalbody.is_empty() { emit!(self, Instruction::PopBlock); // pop excepthandler block // We enter the finally block, without exception. emit!(self, Instruction::EnterFinally); } emit!( self, Instruction::Jump { target: finally_block, } ); // Emit a new label for the next handler self.switch_to_block(next_handler); } // If code flows here, we have an unhandled exception, // raise the exception again! emit!( self, Instruction::Raise { kind: bytecode::RaiseKind::Reraise, } ); // We successfully ran the try block: // else: self.switch_to_block(else_block); self.compile_statements(orelse)?; if !finalbody.is_empty() { emit!(self, Instruction::PopBlock); // pop finally block // We enter the finallyhandler block, without return / exception. emit!(self, Instruction::EnterFinally); } // finally: self.switch_to_block(finally_block); if !finalbody.is_empty() { self.compile_statements(finalbody)?; emit!(self, Instruction::EndFinally); } Ok(()) } fn compile_try_star_statement( &mut self, _body: &[located_ast::Stmt], _handlers: &[located_ast::ExceptHandler], _orelse: &[located_ast::Stmt], _finalbody: &[located_ast::Stmt], ) -> CompileResult<()> { Err(self.error(CodegenErrorType::NotImplementedYet)) } fn is_forbidden_arg_name(name: &str) -> bool { is_forbidden_name(name) } fn compile_function_def( &mut self, name: &str, args: &located_ast::Arguments, body: &[located_ast::Stmt], decorator_list: &[located_ast::Expr], returns: Option<&located_ast::Expr>, // TODO: use type hint somehow.. is_async: bool, ) -> CompileResult<()> { // Create bytecode for this function: self.prepare_decorators(decorator_list)?; let mut func_flags = self.enter_function(name, args)?; self.current_code_info() .flags .set(bytecode::CodeFlags::IS_COROUTINE, is_async); // remember to restore self.ctx.in_loop to the original after the function is compiled let prev_ctx = self.ctx; self.ctx = CompileContext { loop_data: None, in_class: prev_ctx.in_class, func: if is_async { FunctionContext::AsyncFunction } else { FunctionContext::Function }, }; self.push_qualified_path(name); let qualified_name = self.qualified_path.join("."); self.push_qualified_path("<locals>"); let (doc_str, body) = split_doc(body); self.current_code_info() .constants .insert_full(ConstantData::None); self.compile_statements(body)?; // Emit None at end: match body.last() { Some(located_ast::Stmt::Return(_)) => { // the last instruction is a ReturnValue already, we don't need to emit it } _ => { self.emit_constant(ConstantData::None); emit!(self, Instruction::ReturnValue); } } let code = self.pop_code_object(); self.qualified_path.pop(); self.qualified_path.pop(); self.ctx = prev_ctx; // Prepare type annotations: let mut num_annotations = 0; // Return annotation: if let Some(annotation) = returns { // key: self.emit_constant(ConstantData::Str { value: "return".to_owned(), }); // value: self.compile_annotation(annotation)?; num_annotations += 1; } let args_iter = std::iter::empty() .chain(&args.posonlyargs) .chain(&args.args) .chain(&args.kwonlyargs) .map(|arg| arg.as_arg()) .chain(args.vararg.as_deref()) .chain(args.kwarg.as_deref()); for arg in args_iter { if let Some(annotation) = &arg.annotation { self.emit_constant(ConstantData::Str { value: self.mangle(arg.arg.as_str()).into_owned(), }); self.compile_annotation(annotation)?; num_annotations += 1; } } if num_annotations > 0 { func_flags |= bytecode::MakeFunctionFlags::ANNOTATIONS; emit!( self, Instruction::BuildMap { size: num_annotations, } ); } if self.build_closure(&code) { func_flags |= bytecode::MakeFunctionFlags::CLOSURE; } self.emit_constant(ConstantData::Code { code: Box::new(code), }); self.emit_constant(ConstantData::Str { value: qualified_name, }); // Turn code object into function object: emit!(self, Instruction::MakeFunction(func_flags)); emit!(self, Instruction::Duplicate); self.load_docstring(doc_str); emit!(self, Instruction::Rotate2); let doc = self.name("__doc__"); emit!(self, Instruction::StoreAttr { idx: doc }); self.apply_decorators(decorator_list); self.store_name(name) } fn build_closure(&mut self, code: &CodeObject) -> bool { if code.freevars.is_empty() { return false; } for var in &*code.freevars { let table = self.symbol_table_stack.last().unwrap(); let symbol = table.lookup(var).unwrap_or_else(|| { panic!( "couldn't look up var {} in {} in {}", var, code.obj_name, self.source_path ) }); let parent_code = self.code_stack.last().unwrap(); let vars = match symbol.scope { SymbolScope::Free => &parent_code.freevar_cache, SymbolScope::Cell => &parent_code.cellvar_cache, _ if symbol.flags.contains(SymbolFlags::FREE_CLASS) => &parent_code.freevar_cache, x => unreachable!( "var {} in a {:?} should be free or cell but it's {:?}", var, table.typ, x ), }; let mut idx = vars.get_index_of(var).unwrap(); if let SymbolScope::Free = symbol.scope { idx += parent_code.cellvar_cache.len(); } emit!(self, Instruction::LoadClosure(idx.to_u32())) } emit!( self, Instruction::BuildTuple { size: code.freevars.len().to_u32(), } ); true } // Python/compile.c find_ann fn find_ann(body: &[located_ast::Stmt]) -> bool { use located_ast::*; for statement in body { let res = match &statement { Stmt::AnnAssign(_) => true, Stmt::For(StmtFor { body, orelse, .. }) => { Self::find_ann(body) || Self::find_ann(orelse) } Stmt::If(StmtIf { body, orelse, .. }) => { Self::find_ann(body) || Self::find_ann(orelse) } Stmt::While(StmtWhile { body, orelse, .. }) => { Self::find_ann(body) || Self::find_ann(orelse) } Stmt::With(StmtWith { body, .. }) => Self::find_ann(body), Stmt::Try(StmtTry { body, orelse, finalbody, .. }) => Self::find_ann(body) || Self::find_ann(orelse) || Self::find_ann(finalbody), _ => false, }; if res { return true; } } false } fn compile_class_def( &mut self, name: &str, body: &[located_ast::Stmt], bases: &[located_ast::Expr], keywords: &[located_ast::Keyword], decorator_list: &[located_ast::Expr], ) -> CompileResult<()> { self.prepare_decorators(decorator_list)?; emit!(self, Instruction::LoadBuildClass); let prev_ctx = self.ctx; self.ctx = CompileContext { func: FunctionContext::NoFunction, in_class: true, loop_data: None, }; let prev_class_name = std::mem::replace(&mut self.class_name, Some(name.to_owned())); // Check if the class is declared global let symbol_table = self.symbol_table_stack.last().unwrap(); let symbol = symbol_table.lookup(name.as_ref()).expect( "The symbol must be present in the symbol table, even when it is undefined in python.", ); let mut global_path_prefix = Vec::new(); if symbol.scope == SymbolScope::GlobalExplicit { global_path_prefix.append(&mut self.qualified_path); } self.push_qualified_path(name); let qualified_name = self.qualified_path.join("."); self.push_output(bytecode::CodeFlags::empty(), 0, 0, 0, name.to_owned()); let (doc_str, body) = split_doc(body); let dunder_name = self.name("__name__"); emit!(self, Instruction::LoadGlobal(dunder_name)); let dunder_module = self.name("__module__"); emit!(self, Instruction::StoreLocal(dunder_module)); self.emit_constant(ConstantData::Str { value: qualified_name, }); let qualname = self.name("__qualname__"); emit!(self, Instruction::StoreLocal(qualname)); self.load_docstring(doc_str); let doc = self.name("__doc__"); emit!(self, Instruction::StoreLocal(doc)); // setup annotations if Self::find_ann(body) { emit!(self, Instruction::SetupAnnotation); } self.compile_statements(body)?; let classcell_idx = self .code_stack .last_mut() .unwrap() .cellvar_cache .iter() .position(|var| *var == "__class__"); if let Some(classcell_idx) = classcell_idx { emit!(self, Instruction::LoadClosure(classcell_idx.to_u32())); emit!(self, Instruction::Duplicate); let classcell = self.name("__classcell__"); emit!(self, Instruction::StoreLocal(classcell)); } else { self.emit_constant(ConstantData::None); } emit!(self, Instruction::ReturnValue); let code = self.pop_code_object(); self.class_name = prev_class_name; self.qualified_path.pop(); self.qualified_path.append(global_path_prefix.as_mut()); self.ctx = prev_ctx; let mut func_flags = bytecode::MakeFunctionFlags::empty(); if self.build_closure(&code) { func_flags |= bytecode::MakeFunctionFlags::CLOSURE; } self.emit_constant(ConstantData::Code { code: Box::new(code), }); self.emit_constant(ConstantData::Str { value: name.to_owned(), }); // Turn code object into function object: emit!(self, Instruction::MakeFunction(func_flags)); self.emit_constant(ConstantData::Str { value: name.to_owned(), }); let call = self.compile_call_inner(2, bases, keywords)?; self.compile_normal_call(call); self.apply_decorators(decorator_list); self.store_name(name) } fn load_docstring(&mut self, doc_str: Option<String>) { // TODO: __doc__ must be default None and no bytecode unless it is Some // Duplicate top of stack (the function or class object) // Doc string value: self.emit_constant(match doc_str { Some(doc) => ConstantData::Str { value: doc }, None => ConstantData::None, // set docstring None if not declared }); } fn compile_while( &mut self, test: &located_ast::Expr, body: &[located_ast::Stmt], orelse: &[located_ast::Stmt], ) -> CompileResult<()> { let while_block = self.new_block(); let else_block = self.new_block(); let after_block = self.new_block(); emit!(self, Instruction::SetupLoop); self.switch_to_block(while_block); self.compile_jump_if(test, false, else_block)?; let was_in_loop = self.ctx.loop_data.replace((while_block, after_block)); self.compile_statements(body)?; self.ctx.loop_data = was_in_loop; emit!( self, Instruction::Jump { target: while_block, } ); self.switch_to_block(else_block); emit!(self, Instruction::PopBlock); self.compile_statements(orelse)?; self.switch_to_block(after_block); Ok(()) } fn compile_with( &mut self, items: &[located_ast::WithItem], body: &[located_ast::Stmt], is_async: bool, ) -> CompileResult<()> { let with_location = self.current_source_location; let Some((item, items)) = items.split_first() else { return Err(self.error(CodegenErrorType::EmptyWithItems)); }; let final_block = { let final_block = self.new_block(); self.compile_expression(&item.context_expr)?; self.set_source_location(with_location); if is_async { emit!(self, Instruction::BeforeAsyncWith); emit!(self, Instruction::GetAwaitable); self.emit_constant(ConstantData::None); emit!(self, Instruction::YieldFrom); emit!(self, Instruction::SetupAsyncWith { end: final_block }); } else { emit!(self, Instruction::SetupWith { end: final_block }); } match &item.optional_vars { Some(var) => { self.set_source_location(var.location()); self.compile_store(var)?; } None => { emit!(self, Instruction::Pop); } } final_block }; if items.is_empty() { if body.is_empty() { return Err(self.error(CodegenErrorType::EmptyWithBody)); } self.compile_statements(body)?; } else { self.set_source_location(with_location); self.compile_with(items, body, is_async)?; } // sort of "stack up" the layers of with blocks: // with a, b: body -> start_with(a) start_with(b) body() end_with(b) end_with(a) self.set_source_location(with_location); emit!(self, Instruction::PopBlock); emit!(self, Instruction::EnterFinally); self.switch_to_block(final_block); emit!(self, Instruction::WithCleanupStart); if is_async { emit!(self, Instruction::GetAwaitable); self.emit_constant(ConstantData::None); emit!(self, Instruction::YieldFrom); } emit!(self, Instruction::WithCleanupFinish); Ok(()) } fn compile_for( &mut self, target: &located_ast::Expr, iter: &located_ast::Expr, body: &[located_ast::Stmt], orelse: &[located_ast::Stmt], is_async: bool, ) -> CompileResult<()> { // Start loop let for_block = self.new_block(); let else_block = self.new_block(); let after_block = self.new_block(); emit!(self, Instruction::SetupLoop); // The thing iterated: self.compile_expression(iter)?; if is_async { emit!(self, Instruction::GetAIter); self.switch_to_block(for_block); emit!( self, Instruction::SetupExcept { handler: else_block, } ); emit!(self, Instruction::GetANext); self.emit_constant(ConstantData::None); emit!(self, Instruction::YieldFrom); self.compile_store(target)?; emit!(self, Instruction::PopBlock); } else { // Retrieve Iterator emit!(self, Instruction::GetIter); self.switch_to_block(for_block); emit!(self, Instruction::ForIter { target: else_block }); // Start of loop iteration, set targets: self.compile_store(target)?; }; let was_in_loop = self.ctx.loop_data.replace((for_block, after_block)); self.compile_statements(body)?; self.ctx.loop_data = was_in_loop; emit!(self, Instruction::Jump { target: for_block }); self.switch_to_block(else_block); if is_async { emit!(self, Instruction::EndAsyncFor); } emit!(self, Instruction::PopBlock); self.compile_statements(orelse)?; self.switch_to_block(after_block); Ok(()) } fn compile_match( &mut self, subject: &located_ast::Expr, cases: &[located_ast::MatchCase], ) -> CompileResult<()> { eprintln!("match subject: {subject:?}"); eprintln!("match cases: {cases:?}"); Err(self.error(CodegenErrorType::NotImplementedYet)) } fn compile_chained_comparison( &mut self, left: &located_ast::Expr, ops: &[located_ast::CmpOp], exprs: &[located_ast::Expr], ) -> CompileResult<()> { assert!(!ops.is_empty()); assert_eq!(exprs.len(), ops.len()); let (last_op, mid_ops) = ops.split_last().unwrap(); let (last_val, mid_exprs) = exprs.split_last().unwrap(); use bytecode::ComparisonOperator::*; use bytecode::TestOperator::*; let compile_cmpop = |c: &mut Self, op: &located_ast::CmpOp| match op { located_ast::CmpOp::Eq => emit!(c, Instruction::CompareOperation { op: Equal }), located_ast::CmpOp::NotEq => emit!(c, Instruction::CompareOperation { op: NotEqual }), located_ast::CmpOp::Lt => emit!(c, Instruction::CompareOperation { op: Less }), located_ast::CmpOp::LtE => emit!(c, Instruction::CompareOperation { op: LessOrEqual }), located_ast::CmpOp::Gt => emit!(c, Instruction::CompareOperation { op: Greater }), located_ast::CmpOp::GtE => { emit!(c, Instruction::CompareOperation { op: GreaterOrEqual }) } located_ast::CmpOp::In => emit!(c, Instruction::TestOperation { op: In }), located_ast::CmpOp::NotIn => emit!(c, Instruction::TestOperation { op: NotIn }), located_ast::CmpOp::Is => emit!(c, Instruction::TestOperation { op: Is }), located_ast::CmpOp::IsNot => emit!(c, Instruction::TestOperation { op: IsNot }), }; // a == b == c == d // compile into (pseudo code): // result = a == b // if result: // result = b == c // if result: // result = c == d // initialize lhs outside of loop self.compile_expression(left)?; let end_blocks = if mid_exprs.is_empty() { None } else { let break_block = self.new_block(); let after_block = self.new_block(); Some((break_block, after_block)) }; // for all comparisons except the last (as the last one doesn't need a conditional jump) for (op, val) in mid_ops.iter().zip(mid_exprs) { self.compile_expression(val)?; // store rhs for the next comparison in chain emit!(self, Instruction::Duplicate); emit!(self, Instruction::Rotate3); compile_cmpop(self, op); // if comparison result is false, we break with this value; if true, try the next one. if let Some((break_block, _)) = end_blocks { emit!( self, Instruction::JumpIfFalseOrPop { target: break_block, } ); } } // handle the last comparison self.compile_expression(last_val)?; compile_cmpop(self, last_op); if let Some((break_block, after_block)) = end_blocks { emit!( self, Instruction::Jump { target: after_block, } ); // early exit left us with stack: `rhs, comparison_result`. We need to clean up rhs. self.switch_to_block(break_block); emit!(self, Instruction::Rotate2); emit!(self, Instruction::Pop); self.switch_to_block(after_block); } Ok(()) } fn compile_annotation(&mut self, annotation: &located_ast::Expr) -> CompileResult<()> { if self.future_annotations { self.emit_constant(ConstantData::Str { value: annotation.to_string(), }); } else { self.compile_expression(annotation)?; } Ok(()) } fn compile_annotated_assign( &mut self, target: &located_ast::Expr, annotation: &located_ast::Expr, value: Option<&located_ast::Expr>, ) -> CompileResult<()> { if let Some(value) = value { self.compile_expression(value)?; self.compile_store(target)?; } // Annotations are only evaluated in a module or class. if self.ctx.in_func() { return Ok(()); } // Compile annotation: self.compile_annotation(annotation)?; if let located_ast::Expr::Name(located_ast::ExprName { id, .. }) = &target { // Store as dict entry in __annotations__ dict: let annotations = self.name("__annotations__"); emit!(self, Instruction::LoadNameAny(annotations)); self.emit_constant(ConstantData::Str { value: self.mangle(id.as_str()).into_owned(), }); emit!(self, Instruction::StoreSubscript); } else { // Drop annotation if not assigned to simple identifier. emit!(self, Instruction::Pop); } Ok(()) } fn compile_store(&mut self, target: &located_ast::Expr) -> CompileResult<()> { match &target { located_ast::Expr::Name(located_ast::ExprName { id, .. }) => { self.store_name(id.as_str())? } located_ast::Expr::Subscript(located_ast::ExprSubscript { value, slice, .. }) => { self.compile_expression(value)?; self.compile_expression(slice)?; emit!(self, Instruction::StoreSubscript); } located_ast::Expr::Attribute(located_ast::ExprAttribute { value, attr, .. }) => { self.check_forbidden_name(attr.as_str(), NameUsage::Store)?; self.compile_expression(value)?; let idx = self.name(attr.as_str()); emit!(self, Instruction::StoreAttr { idx }); } located_ast::Expr::List(located_ast::ExprList { elts, .. }) | located_ast::Expr::Tuple(located_ast::ExprTuple { elts, .. }) => { let mut seen_star = false; // Scan for star args: for (i, element) in elts.iter().enumerate() { if let located_ast::Expr::Starred(_) = &element { if seen_star { return Err(self.error(CodegenErrorType::MultipleStarArgs)); } else { seen_star = true; let before = i; let after = elts.len() - i - 1; let (before, after) = (|| Some((before.to_u8()?, after.to_u8()?)))() .ok_or_else(|| { self.error_loc( CodegenErrorType::TooManyStarUnpack, target.location(), ) })?; let args = bytecode::UnpackExArgs { before, after }; emit!(self, Instruction::UnpackEx { args }); } } } if !seen_star { emit!( self, Instruction::UnpackSequence { size: elts.len().to_u32(), } ); } for element in elts { if let located_ast::Expr::Starred(located_ast::ExprStarred { value, .. }) = &element { self.compile_store(value)?; } else { self.compile_store(element)?; } } } _ => { return Err(self.error(match target { located_ast::Expr::Starred(_) => CodegenErrorType::SyntaxError( "starred assignment target must be in a list or tuple".to_owned(), ), _ => CodegenErrorType::Assign(target.python_name()), })); } } Ok(()) } fn compile_augassign( &mut self, target: &located_ast::Expr, op: &located_ast::Operator, value: &located_ast::Expr, ) -> CompileResult<()> { enum AugAssignKind<'a> { Name { id: &'a str }, Subscript, Attr { idx: bytecode::NameIdx }, } let kind = match &target { located_ast::Expr::Name(located_ast::ExprName { id, .. }) => { let id = id.as_str(); self.compile_name(id, NameUsage::Load)?; AugAssignKind::Name { id } } located_ast::Expr::Subscript(located_ast::ExprSubscript { value, slice, .. }) => { self.compile_expression(value)?; self.compile_expression(slice)?; emit!(self, Instruction::Duplicate2); emit!(self, Instruction::Subscript); AugAssignKind::Subscript } located_ast::Expr::Attribute(located_ast::ExprAttribute { value, attr, .. }) => { let attr = attr.as_str(); self.check_forbidden_name(attr, NameUsage::Store)?; self.compile_expression(value)?; emit!(self, Instruction::Duplicate); let idx = self.name(attr); emit!(self, Instruction::LoadAttr { idx }); AugAssignKind::Attr { idx } } _ => { return Err(self.error(CodegenErrorType::Assign(target.python_name()))); } }; self.compile_expression(value)?; self.compile_op(op, true); match kind { AugAssignKind::Name { id } => { // stack: RESULT self.compile_name(id, NameUsage::Store)?; } AugAssignKind::Subscript => { // stack: CONTAINER SLICE RESULT emit!(self, Instruction::Rotate3); emit!(self, Instruction::StoreSubscript); } AugAssignKind::Attr { idx } => { // stack: CONTAINER RESULT emit!(self, Instruction::Rotate2); emit!(self, Instruction::StoreAttr { idx }); } } Ok(()) } fn compile_op(&mut self, op: &located_ast::Operator, inplace: bool) { let op = match op { located_ast::Operator::Add => bytecode::BinaryOperator::Add, located_ast::Operator::Sub => bytecode::BinaryOperator::Subtract, located_ast::Operator::Mult => bytecode::BinaryOperator::Multiply, located_ast::Operator::MatMult => bytecode::BinaryOperator::MatrixMultiply, located_ast::Operator::Div => bytecode::BinaryOperator::Divide, located_ast::Operator::FloorDiv => bytecode::BinaryOperator::FloorDivide, located_ast::Operator::Mod => bytecode::BinaryOperator::Modulo, located_ast::Operator::Pow => bytecode::BinaryOperator::Power, located_ast::Operator::LShift => bytecode::BinaryOperator::Lshift, located_ast::Operator::RShift => bytecode::BinaryOperator::Rshift, located_ast::Operator::BitOr => bytecode::BinaryOperator::Or, located_ast::Operator::BitXor => bytecode::BinaryOperator::Xor, located_ast::Operator::BitAnd => bytecode::BinaryOperator::And, }; if inplace { emit!(self, Instruction::BinaryOperationInplace { op }) } else { emit!(self, Instruction::BinaryOperation { op }) } } /// Implement boolean short circuit evaluation logic. /// https://en.wikipedia.org/wiki/Short-circuit_evaluation /// /// This means, in a boolean statement 'x and y' the variable y will /// not be evaluated when x is false. /// /// The idea is to jump to a label if the expression is either true or false /// (indicated by the condition parameter). fn compile_jump_if( &mut self, expression: &located_ast::Expr, condition: bool, target_block: ir::BlockIdx, ) -> CompileResult<()> { // Compile expression for test, and jump to label if false match &expression { located_ast::Expr::BoolOp(located_ast::ExprBoolOp { op, values, .. }) => { match op { located_ast::BoolOp::And => { if condition { // If all values are true. let end_block = self.new_block(); let (last_value, values) = values.split_last().unwrap(); // If any of the values is false, we can short-circuit. for value in values { self.compile_jump_if(value, false, end_block)?; } // It depends upon the last value now: will it be true? self.compile_jump_if(last_value, true, target_block)?; self.switch_to_block(end_block); } else { // If any value is false, the whole condition is false. for value in values { self.compile_jump_if(value, false, target_block)?; } } } located_ast::BoolOp::Or => { if condition { // If any of the values is true. for value in values { self.compile_jump_if(value, true, target_block)?; } } else { // If all of the values are false. let end_block = self.new_block(); let (last_value, values) = values.split_last().unwrap(); // If any value is true, we can short-circuit: for value in values { self.compile_jump_if(value, true, end_block)?; } // It all depends upon the last value now! self.compile_jump_if(last_value, false, target_block)?; self.switch_to_block(end_block); } } } } located_ast::Expr::UnaryOp(located_ast::ExprUnaryOp { op: located_ast::UnaryOp::Not, operand, .. }) => { self.compile_jump_if(operand, !condition, target_block)?; } _ => { // Fall back case which always will work! self.compile_expression(expression)?; if condition { emit!( self, Instruction::JumpIfTrue { target: target_block, } ); } else { emit!( self, Instruction::JumpIfFalse { target: target_block, } ); } } } Ok(()) } /// Compile a boolean operation as an expression. /// This means, that the last value remains on the stack. fn compile_bool_op( &mut self, op: &located_ast::BoolOp, values: &[located_ast::Expr], ) -> CompileResult<()> { let after_block = self.new_block(); let (last_value, values) = values.split_last().unwrap(); for value in values { self.compile_expression(value)?; match op { located_ast::BoolOp::And => { emit!( self, Instruction::JumpIfFalseOrPop { target: after_block, } ); } located_ast::BoolOp::Or => { emit!( self, Instruction::JumpIfTrueOrPop { target: after_block, } ); } } } // If all values did not qualify, take the value of the last value: self.compile_expression(last_value)?; self.switch_to_block(after_block); Ok(()) } fn compile_dict( &mut self, keys: &[Option<located_ast::Expr>], values: &[located_ast::Expr], ) -> CompileResult<()> { let mut size = 0; let (packed, unpacked): (Vec<_>, Vec<_>) = keys .iter() .zip(values.iter()) .partition(|(k, _)| k.is_some()); for (key, value) in packed { self.compile_expression(key.as_ref().unwrap())?; self.compile_expression(value)?; size += 1; } emit!(self, Instruction::BuildMap { size }); for (_, value) in unpacked { self.compile_expression(value)?; emit!(self, Instruction::DictUpdate); } Ok(()) } fn compile_expression(&mut self, expression: &located_ast::Expr) -> CompileResult<()> { use located_ast::*; trace!("Compiling {:?}", expression); let location = expression.location(); self.set_source_location(location); match &expression { Expr::Call(ExprCall { func, args, keywords, .. }) => self.compile_call(func, args, keywords)?, Expr::BoolOp(ExprBoolOp { op, values, .. }) => self.compile_bool_op(op, values)?, Expr::BinOp(ExprBinOp { left, op, right, .. }) => { self.compile_expression(left)?; self.compile_expression(right)?; // Perform operation: self.compile_op(op, false); } Expr::Subscript(ExprSubscript { value, slice, .. }) => { self.compile_expression(value)?; self.compile_expression(slice)?; emit!(self, Instruction::Subscript); } Expr::UnaryOp(ExprUnaryOp { op, operand, .. }) => { self.compile_expression(operand)?; // Perform operation: let op = match op { UnaryOp::UAdd => bytecode::UnaryOperator::Plus, UnaryOp::USub => bytecode::UnaryOperator::Minus, UnaryOp::Not => bytecode::UnaryOperator::Not, UnaryOp::Invert => bytecode::UnaryOperator::Invert, }; emit!(self, Instruction::UnaryOperation { op }); } Expr::Attribute(ExprAttribute { value, attr, .. }) => { self.compile_expression(value)?; let idx = self.name(attr.as_str()); emit!(self, Instruction::LoadAttr { idx }); } Expr::Compare(ExprCompare { left, ops, comparators, .. }) => { self.compile_chained_comparison(left, ops, comparators)?; } Expr::Constant(ExprConstant { value, .. }) => { self.emit_constant(compile_constant(value)); } Expr::List(ExprList { elts, .. }) => { let (size, unpack) = self.gather_elements(0, elts)?; if unpack { emit!(self, Instruction::BuildListUnpack { size }); } else { emit!(self, Instruction::BuildList { size }); } } Expr::Tuple(ExprTuple { elts, .. }) => { let (size, unpack) = self.gather_elements(0, elts)?; if unpack { emit!(self, Instruction::BuildTupleUnpack { size }); } else { emit!(self, Instruction::BuildTuple { size }); } } Expr::Set(ExprSet { elts, .. }) => { let (size, unpack) = self.gather_elements(0, elts)?; if unpack { emit!(self, Instruction::BuildSetUnpack { size }); } else { emit!(self, Instruction::BuildSet { size }); } } Expr::Dict(ExprDict { keys, values, .. }) => { self.compile_dict(keys, values)?; } Expr::Slice(ExprSlice { lower, upper, step, .. }) => { let mut compile_bound = |bound: Option<&located_ast::Expr>| match bound { Some(exp) => self.compile_expression(exp), None => { self.emit_constant(ConstantData::None); Ok(()) } }; compile_bound(lower.as_deref())?; compile_bound(upper.as_deref())?; if let Some(step) = step { self.compile_expression(step)?; } let step = step.is_some(); emit!(self, Instruction::BuildSlice { step }); } Expr::Yield(ExprYield { value, .. }) => { if !self.ctx.in_func() { return Err(self.error(CodegenErrorType::InvalidYield)); } self.mark_generator(); match value { Some(expression) => self.compile_expression(expression)?, Option::None => self.emit_constant(ConstantData::None), }; emit!(self, Instruction::YieldValue); } Expr::Await(ExprAwait { value, .. }) => { if self.ctx.func != FunctionContext::AsyncFunction { return Err(self.error(CodegenErrorType::InvalidAwait)); } self.compile_expression(value)?; emit!(self, Instruction::GetAwaitable); self.emit_constant(ConstantData::None); emit!(self, Instruction::YieldFrom); } Expr::YieldFrom(ExprYieldFrom { value, .. }) => { match self.ctx.func { FunctionContext::NoFunction => { return Err(self.error(CodegenErrorType::InvalidYieldFrom)); } FunctionContext::AsyncFunction => { return Err(self.error(CodegenErrorType::AsyncYieldFrom)); } FunctionContext::Function => {} } self.mark_generator(); self.compile_expression(value)?; emit!(self, Instruction::GetIter); self.emit_constant(ConstantData::None); emit!(self, Instruction::YieldFrom); } Expr::JoinedStr(ExprJoinedStr { values, .. }) => { if let Some(value) = try_get_constant_string(values) { self.emit_constant(ConstantData::Str { value }) } else { for value in values { self.compile_expression(value)?; } emit!( self, Instruction::BuildString { size: values.len().to_u32(), } ) } } Expr::FormattedValue(ExprFormattedValue { value, conversion, format_spec, .. }) => { match format_spec { Some(spec) => self.compile_expression(spec)?, None => self.emit_constant(ConstantData::Str { value: String::new(), }), }; self.compile_expression(value)?; emit!( self, Instruction::FormatValue { conversion: *conversion, }, ); } Expr::Name(located_ast::ExprName { id, .. }) => self.load_name(id.as_str())?, Expr::Lambda(located_ast::ExprLambda { args, body, .. }) => { let prev_ctx = self.ctx; let name = "<lambda>".to_owned(); let mut func_flags = self.enter_function(&name, args)?; self.ctx = CompileContext { loop_data: Option::None, in_class: prev_ctx.in_class, func: FunctionContext::Function, }; self.current_code_info() .constants .insert_full(ConstantData::None); self.compile_expression(body)?; emit!(self, Instruction::ReturnValue); let code = self.pop_code_object(); if self.build_closure(&code) { func_flags |= bytecode::MakeFunctionFlags::CLOSURE; } self.emit_constant(ConstantData::Code { code: Box::new(code), }); self.emit_constant(ConstantData::Str { value: name }); // Turn code object into function object: emit!(self, Instruction::MakeFunction(func_flags)); self.ctx = prev_ctx; } Expr::ListComp(located_ast::ExprListComp { elt, generators, .. }) => { self.compile_comprehension( "<listcomp>", Some(Instruction::BuildList { size: OpArgMarker::marker(), }), generators, &|compiler| { compiler.compile_comprehension_element(elt)?; emit!( compiler, Instruction::ListAppend { i: generators.len().to_u32(), } ); Ok(()) }, )?; } Expr::SetComp(located_ast::ExprSetComp { elt, generators, .. }) => { self.compile_comprehension( "<setcomp>", Some(Instruction::BuildSet { size: OpArgMarker::marker(), }), generators, &|compiler| { compiler.compile_comprehension_element(elt)?; emit!( compiler, Instruction::SetAdd { i: generators.len().to_u32(), } ); Ok(()) }, )?; } Expr::DictComp(located_ast::ExprDictComp { key, value, generators, .. }) => { self.compile_comprehension( "<dictcomp>", Some(Instruction::BuildMap { size: OpArgMarker::marker(), }), generators, &|compiler| { // changed evaluation order for Py38 named expression PEP 572 compiler.compile_expression(key)?; compiler.compile_expression(value)?; emit!( compiler, Instruction::MapAdd { i: generators.len().to_u32(), } ); Ok(()) }, )?; } Expr::GeneratorExp(located_ast::ExprGeneratorExp { elt, generators, .. }) => { self.compile_comprehension("<genexpr>", None, generators, &|compiler| { compiler.compile_comprehension_element(elt)?; compiler.mark_generator(); emit!(compiler, Instruction::YieldValue); emit!(compiler, Instruction::Pop); Ok(()) })?; } Expr::Starred(_) => { return Err(self.error(CodegenErrorType::InvalidStarExpr)); } Expr::IfExp(located_ast::ExprIfExp { test, body, orelse, .. }) => { let else_block = self.new_block(); let after_block = self.new_block(); self.compile_jump_if(test, false, else_block)?; // True case self.compile_expression(body)?; emit!( self, Instruction::Jump { target: after_block, } ); // False case self.switch_to_block(else_block); self.compile_expression(orelse)?; // End self.switch_to_block(after_block); } Expr::NamedExpr(located_ast::ExprNamedExpr { target, value, range: _, }) => { self.compile_expression(value)?; emit!(self, Instruction::Duplicate); self.compile_store(target)?; } } Ok(()) } fn compile_keywords(&mut self, keywords: &[located_ast::Keyword]) -> CompileResult<()> { let mut size = 0; let groupby = keywords.iter().group_by(|e| e.arg.is_none()); for (is_unpacking, sub_keywords) in &groupby { if is_unpacking { for keyword in sub_keywords { self.compile_expression(&keyword.value)?; size += 1; } } else { let mut sub_size = 0; for keyword in sub_keywords { if let Some(name) = &keyword.arg { self.emit_constant(ConstantData::Str { value: name.to_string(), }); self.compile_expression(&keyword.value)?; sub_size += 1; } } emit!(self, Instruction::BuildMap { size: sub_size }); size += 1; } } if size > 1 { emit!(self, Instruction::BuildMapForCall { size }); } Ok(()) } fn compile_call( &mut self, func: &located_ast::Expr, args: &[located_ast::Expr], keywords: &[located_ast::Keyword], ) -> CompileResult<()> { let method = if let located_ast::Expr::Attribute(located_ast::ExprAttribute { value, attr, .. }) = &func { self.compile_expression(value)?; let idx = self.name(attr.as_str()); emit!(self, Instruction::LoadMethod { idx }); true } else { self.compile_expression(func)?; false }; let call = self.compile_call_inner(0, args, keywords)?; if method { self.compile_method_call(call) } else { self.compile_normal_call(call) } Ok(()) } fn compile_normal_call(&mut self, ty: CallType) { match ty { CallType::Positional { nargs } => { emit!(self, Instruction::CallFunctionPositional { nargs }) } CallType::Keyword { nargs } => emit!(self, Instruction::CallFunctionKeyword { nargs }), CallType::Ex { has_kwargs } => emit!(self, Instruction::CallFunctionEx { has_kwargs }), } } fn compile_method_call(&mut self, ty: CallType) { match ty { CallType::Positional { nargs } => { emit!(self, Instruction::CallMethodPositional { nargs }) } CallType::Keyword { nargs } => emit!(self, Instruction::CallMethodKeyword { nargs }), CallType::Ex { has_kwargs } => emit!(self, Instruction::CallMethodEx { has_kwargs }), } } fn compile_call_inner( &mut self, additional_positional: u32, args: &[located_ast::Expr], keywords: &[located_ast::Keyword], ) -> CompileResult<CallType> { let count = (args.len() + keywords.len()).to_u32() + additional_positional; // Normal arguments: let (size, unpack) = self.gather_elements(additional_positional, args)?; let has_double_star = keywords.iter().any(|k| k.arg.is_none()); for keyword in keywords { if let Some(name) = &keyword.arg { self.check_forbidden_name(name.as_str(), NameUsage::Store)?; } } let call = if unpack || has_double_star { // Create a tuple with positional args: if unpack { emit!(self, Instruction::BuildTupleUnpack { size }); } else { emit!(self, Instruction::BuildTuple { size }); } // Create an optional map with kw-args: let has_kwargs = !keywords.is_empty(); if has_kwargs { self.compile_keywords(keywords)?; } CallType::Ex { has_kwargs } } else if !keywords.is_empty() { let mut kwarg_names = vec![]; for keyword in keywords { if let Some(name) = &keyword.arg { kwarg_names.push(ConstantData::Str { value: name.to_string(), }); } else { // This means **kwargs! panic!("name must be set"); } self.compile_expression(&keyword.value)?; } self.emit_constant(ConstantData::Tuple { elements: kwarg_names, }); CallType::Keyword { nargs: count } } else { CallType::Positional { nargs: count } }; Ok(call) } // Given a vector of expr / star expr generate code which gives either // a list of expressions on the stack, or a list of tuples. fn gather_elements( &mut self, before: u32, elements: &[located_ast::Expr], ) -> CompileResult<(u32, bool)> { // First determine if we have starred elements: let has_stars = elements .iter() .any(|e| matches!(e, located_ast::Expr::Starred(_))); let size = if has_stars { let mut size = 0; if before > 0 { emit!(self, Instruction::BuildTuple { size: before }); size += 1; } let groups = elements .iter() .map(|element| { if let located_ast::Expr::Starred(located_ast::ExprStarred { value, .. }) = &element { (true, value.as_ref()) } else { (false, element) } }) .group_by(|(starred, _)| *starred); for (starred, run) in &groups { let mut run_size = 0; for (_, value) in run { self.compile_expression(value)?; run_size += 1 } if starred { size += run_size } else { emit!(self, Instruction::BuildTuple { size: run_size }); size += 1 } } size } else { for element in elements { self.compile_expression(element)?; } before + elements.len().to_u32() }; Ok((size, has_stars)) } fn compile_comprehension_element(&mut self, element: &located_ast::Expr) -> CompileResult<()> { self.compile_expression(element).map_err(|e| { if let CodegenErrorType::InvalidStarExpr = e.error { self.error(CodegenErrorType::SyntaxError( "iterable unpacking cannot be used in comprehension".to_owned(), )) } else { e } }) } fn compile_comprehension( &mut self, name: &str, init_collection: Option<Instruction>, generators: &[located_ast::Comprehension], compile_element: &dyn Fn(&mut Self) -> CompileResult<()>, ) -> CompileResult<()> { let prev_ctx = self.ctx; self.ctx = CompileContext { loop_data: None, in_class: prev_ctx.in_class, func: FunctionContext::Function, }; // We must have at least one generator: assert!(!generators.is_empty()); // Create magnificent function <listcomp>: self.push_output( bytecode::CodeFlags::NEW_LOCALS | bytecode::CodeFlags::IS_OPTIMIZED, 1, 1, 0, name.to_owned(), ); let arg0 = self.varname(".0")?; let return_none = init_collection.is_none(); // Create empty object of proper type: if let Some(init_collection) = init_collection { self._emit(init_collection, OpArg(0), ir::BlockIdx::NULL) } let mut loop_labels = vec![]; for generator in generators { if generator.is_async { unimplemented!("async for comprehensions"); } let loop_block = self.new_block(); let after_block = self.new_block(); if loop_labels.is_empty() { // Load iterator onto stack (passed as first argument): emit!(self, Instruction::LoadFast(arg0)); } else { // Evaluate iterated item: self.compile_expression(&generator.iter)?; // Get iterator / turn item into an iterator emit!(self, Instruction::GetIter); } loop_labels.push((loop_block, after_block)); self.switch_to_block(loop_block); emit!( self, Instruction::ForIter { target: after_block, } ); self.compile_store(&generator.target)?; // Now evaluate the ifs: for if_condition in &generator.ifs { self.compile_jump_if(if_condition, false, loop_block)? } } compile_element(self)?; for (loop_block, after_block) in loop_labels.iter().rev().copied() { // Repeat: emit!(self, Instruction::Jump { target: loop_block }); // End of for loop: self.switch_to_block(after_block); } if return_none { self.emit_constant(ConstantData::None) } // Return freshly filled list: emit!(self, Instruction::ReturnValue); // Fetch code for listcomp function: let code = self.pop_code_object(); self.ctx = prev_ctx; let mut func_flags = bytecode::MakeFunctionFlags::empty(); if self.build_closure(&code) { func_flags |= bytecode::MakeFunctionFlags::CLOSURE; } // List comprehension code: self.emit_constant(ConstantData::Code { code: Box::new(code), }); // List comprehension function name: self.emit_constant(ConstantData::Str { value: name.to_owned(), }); // Turn code object into function object: emit!(self, Instruction::MakeFunction(func_flags)); // Evaluate iterated item: self.compile_expression(&generators[0].iter)?; // Get iterator / turn item into an iterator emit!(self, Instruction::GetIter); // Call just created <listcomp> function: emit!(self, Instruction::CallFunctionPositional { nargs: 1 }); Ok(()) } fn compile_future_features( &mut self, features: &[located_ast::Alias], ) -> Result<(), CodegenError> { if self.done_with_future_stmts { return Err(self.error(CodegenErrorType::InvalidFuturePlacement)); } for feature in features { match feature.name.as_str() { // Python 3 features; we've already implemented them by default "nested_scopes" | "generators" | "division" | "absolute_import" | "with_statement" | "print_function" | "unicode_literals" => {} // "generator_stop" => {} "annotations" => self.future_annotations = true, other => { return Err(self.error(CodegenErrorType::InvalidFutureFeature(other.to_owned()))) } } } Ok(()) } // Low level helper functions: fn _emit(&mut self, instr: Instruction, arg: OpArg, target: ir::BlockIdx) { let location = self.current_source_location; // TODO: insert source filename self.current_block().instructions.push(ir::InstructionInfo { instr, arg, target, location, }); } fn emit_no_arg(&mut self, ins: Instruction) { self._emit(ins, OpArg::null(), ir::BlockIdx::NULL) } fn emit_arg<A: OpArgType, T: EmitArg<A>>( &mut self, arg: T, f: impl FnOnce(OpArgMarker<A>) -> Instruction, ) { let (op, arg, target) = arg.emit(f); self._emit(op, arg, target) } // fn block_done() fn emit_constant(&mut self, constant: ConstantData) { let info = self.current_code_info(); let idx = info.constants.insert_full(constant).0.to_u32(); self.emit_arg(idx, |idx| Instruction::LoadConst { idx }) } fn current_code_info(&mut self) -> &mut ir::CodeInfo { self.code_stack.last_mut().expect("no code on stack") } fn current_block(&mut self) -> &mut ir::Block { let info = self.current_code_info(); &mut info.blocks[info.current_block] } fn new_block(&mut self) -> ir::BlockIdx { let code = self.current_code_info(); let idx = ir::BlockIdx(code.blocks.len().to_u32()); code.blocks.push(ir::Block::default()); idx } fn switch_to_block(&mut self, block: ir::BlockIdx) { let code = self.current_code_info(); let prev = code.current_block; assert_eq!( code.blocks[block].next, ir::BlockIdx::NULL, "switching to completed block" ); let prev_block = &mut code.blocks[prev.0 as usize]; assert_eq!( prev_block.next.0, u32::MAX, "switching from block that's already got a next" ); prev_block.next = block; code.current_block = block; } fn set_source_location(&mut self, location: SourceLocation) { self.current_source_location = location; } fn get_source_line_number(&mut self) -> LineNumber { let location = self.current_source_location; location.row } fn push_qualified_path(&mut self, name: &str) { self.qualified_path.push(name.to_owned()); } fn mark_generator(&mut self) { self.current_code_info().flags |= bytecode::CodeFlags::IS_GENERATOR } } trait EmitArg<Arg: OpArgType> { fn emit( self, f: impl FnOnce(OpArgMarker<Arg>) -> Instruction, ) -> (Instruction, OpArg, ir::BlockIdx); } impl<T: OpArgType> EmitArg<T> for T { fn emit( self, f: impl FnOnce(OpArgMarker<T>) -> Instruction, ) -> (Instruction, OpArg, ir::BlockIdx) { let (marker, arg) = OpArgMarker::new(self); (f(marker), arg, ir::BlockIdx::NULL) } } impl EmitArg<bytecode::Label> for ir::BlockIdx { fn emit( self, f: impl FnOnce(OpArgMarker<bytecode::Label>) -> Instruction, ) -> (Instruction, OpArg, ir::BlockIdx) { (f(OpArgMarker::marker()), OpArg::null(), self) } } fn split_doc(body: &[located_ast::Stmt]) -> (Option<String>, &[located_ast::Stmt]) { if let Some((located_ast::Stmt::Expr(expr), body_rest)) = body.split_first() { if let Some(doc) = try_get_constant_string(std::slice::from_ref(&expr.value)) { return (Some(doc), body_rest); } } (None, body) } fn try_get_constant_string(values: &[located_ast::Expr]) -> Option<String> { fn get_constant_string_inner(out_string: &mut String, value: &located_ast::Expr) -> bool { match value { located_ast::Expr::Constant(located_ast::ExprConstant { value: located_ast::Constant::Str(s), .. }) => { out_string.push_str(s); true } located_ast::Expr::JoinedStr(located_ast::ExprJoinedStr { values, .. }) => values .iter() .all(|value| get_constant_string_inner(out_string, value)), _ => false, } } let mut out_string = String::new(); if values .iter() .all(|v| get_constant_string_inner(&mut out_string, v)) { Some(out_string) } else { None } } fn compile_constant(value: &located_ast::Constant) -> ConstantData { match value { located_ast::Constant::None => ConstantData::None, located_ast::Constant::Bool(b) => ConstantData::Boolean { value: *b }, located_ast::Constant::Str(s) => ConstantData::Str { value: s.clone() }, located_ast::Constant::Bytes(b) => ConstantData::Bytes { value: b.clone() }, located_ast::Constant::Int(i) => ConstantData::Integer { value: i.clone() }, located_ast::Constant::Tuple(t) => ConstantData::Tuple { elements: t.iter().map(compile_constant).collect(), }, located_ast::Constant::Float(f) => ConstantData::Float { value: *f }, located_ast::Constant::Complex { real, imag } => ConstantData::Complex { value: Complex64::new(*real, *imag), }, located_ast::Constant::Ellipsis => ConstantData::Ellipsis, } } // Note: Not a good practice in general. Keep this trait private only for compiler trait ToU32 { fn to_u32(self) -> u32; } impl ToU32 for usize { fn to_u32(self) -> u32 { self.try_into().unwrap() } } #[cfg(test)] mod tests { use super::*; use rustpython_parser as parser; use rustpython_parser_core::source_code::LinearLocator; fn compile_exec(source: &str) -> CodeObject { let mut locator: LinearLocator = LinearLocator::new(source); use rustpython_parser::ast::fold::Fold; let mut compiler: Compiler = Compiler::new( CompileOpts::default(), "source_path".to_owned(), "<module>".to_owned(), ); let ast = parser::parse_program(source, "<test>").unwrap(); let ast = locator.fold(ast).unwrap(); let symbol_scope = SymbolTable::scan_program(&ast).unwrap(); compiler.compile_program(&ast, symbol_scope).unwrap(); compiler.pop_code_object() } macro_rules! assert_dis_snapshot { ($value:expr) => { insta::assert_snapshot!( insta::internals::AutoName, $value.display_expand_code_objects().to_string(), stringify!($value) ) }; } #[test] fn test_if_ors() { assert_dis_snapshot!(compile_exec( "\ if True or False or False: pass " )); } #[test] fn test_if_ands() { assert_dis_snapshot!(compile_exec( "\ if True and False and False: pass " )); } #[test] fn test_if_mixed() { assert_dis_snapshot!(compile_exec( "\ if (True and False) or (False and True): pass " )); } #[test] fn test_nested_double_async_with() { assert_dis_snapshot!(compile_exec( "\ for stop_exc in (StopIteration('spam'), StopAsyncIteration('ham')): with self.subTest(type=type(stop_exc)): try: async with egg(): raise stop_exc except Exception as ex: self.assertIs(ex, stop_exc) else: self.fail(f'{stop_exc} was suppressed') " )); } }
pub unsafe fn paging() { // Disable MMU asm!( "mrs x0, sctlr_el1", "bic x0, x0, 1", "msr sctlr_el1, x0", "isb", lateout("x0") _ ); }
use crate::domain::cloc::ClocSummary; use crate::domain::suggest::ModelSuggest; use core_model::coco_struct::ClassInfo; use core_model::Settings; use std::fs; use std::path::PathBuf; pub struct Suggester; impl Suggester { pub fn run(project: String) { if let Ok(model) = Suggester::load_struct(project) { let suggest: ModelSuggest = ModelSuggest::new(model); suggest.analysis_all(); } } #[allow(dead_code)] fn load_cloc(project: String) -> Result<Vec<ClocSummary>, String> { let type_dir = Settings::cloc(); let contents = Suggester::read_content(project, type_dir)?; let model: Vec<ClocSummary>; match serde_json::from_str(contents.as_str()) { Ok(m) => model = m, Err(error) => { return Err(format!("{}", error)); } } return Ok(model); } fn load_struct(project: String) -> Result<Vec<ClassInfo>, String> { let type_dir = Settings::struct_dir(); let contents = Suggester::read_content(project, type_dir)?; let model: Vec<ClassInfo>; match serde_json::from_str(contents.as_str()) { Ok(m) => model = m, Err(error) => { return Err(format!("{}", error)); } } return Ok(model); } fn read_content(project: String, type_dir: PathBuf) -> Result<String, String> { let file_name = format!("{}.json", project); let path = type_dir.join(file_name); let contents; match fs::read_to_string(path) { Ok(str) => contents = str, Err(error) => { return Err(format!("{}", error)); } } Ok(contents) } }
#[doc = "Reader of register MIS"] pub type R = crate::R<u32, super::MIS>; #[doc = "Reader of field `RORMIS`"] pub type RORMIS_R = crate::R<bool, bool>; #[doc = "Reader of field `RTMIS`"] pub type RTMIS_R = crate::R<bool, bool>; #[doc = "Reader of field `RXMIS`"] pub type RXMIS_R = crate::R<bool, bool>; #[doc = "Reader of field `TXMIS`"] pub type TXMIS_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - SSI Receive Overrun Masked Interrupt Status"] #[inline(always)] pub fn rormis(&self) -> RORMIS_R { RORMIS_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - SSI Receive Time-Out Masked Interrupt Status"] #[inline(always)] pub fn rtmis(&self) -> RTMIS_R { RTMIS_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - SSI Receive FIFO Masked Interrupt Status"] #[inline(always)] pub fn rxmis(&self) -> RXMIS_R { RXMIS_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - SSI Transmit FIFO Masked Interrupt Status"] #[inline(always)] pub fn txmis(&self) -> TXMIS_R { TXMIS_R::new(((self.bits >> 3) & 0x01) != 0) } }
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(core_intrinsics)] struct NT(str); struct DST { a: u32, b: str } fn main() { // type_name should support unsized types assert_eq!(unsafe {( // Slice std::intrinsics::type_name::<[u8]>(), // str std::intrinsics::type_name::<str>(), // Trait std::intrinsics::type_name::<Send>(), // Newtype std::intrinsics::type_name::<NT>(), // DST std::intrinsics::type_name::<DST>() )}, ("[u8]", "str", "dyn std::marker::Send", "NT", "DST")); }
pub mod prime; pub mod util;
//! This module implements the `catalog` CLI command use clap_blocks::catalog_dsn::CatalogDsnConfig; use thiserror::Error; use crate::process_info::setup_metric_registry; #[allow(clippy::enum_variant_names)] #[derive(Debug, Error)] pub enum Error { #[error("Catalog error: {0}")] Catalog(#[from] iox_catalog::interface::Error), #[error("Catalog DSN error: {0}")] CatalogDsn(#[from] clap_blocks::catalog_dsn::Error), } /// Various commands for catalog manipulation #[derive(Debug, clap::Parser)] pub struct Config { #[clap(subcommand)] command: Command, } /// Run database migrations #[derive(Debug, clap::Parser)] struct Setup { #[clap(flatten)] catalog_dsn: CatalogDsnConfig, } /// All possible subcommands for catalog #[derive(Debug, clap::Parser)] enum Command { /// Run database migrations Setup(Setup), } pub async fn command(config: Config) -> Result<(), Error> { match config.command { Command::Setup(command) => { let metrics = setup_metric_registry(); let catalog = command.catalog_dsn.get_catalog("cli", metrics).await?; catalog.setup().await?; println!("OK"); } } Ok(()) }
fn main() { println!("Hello, world!"); let stu = Student { name: String::from("hello world"), age: 10, }; let lsu = Teacher { name: String::from("lao jiang"), age: 30, subject: String::from("消费"), }; println!("学生姓名: {}, age: {}", stu.get_name(), stu.get_age()); println!("学生姓名: {}, age: {} ", lsu.get_name(), lsu.get_age()); print_information(stu); print_information(lsu); } pub trait GetInformation { fn get_name(&self) -> &String; fn get_age(&self) -> u32; } pub struct Student { pub name: String, pub age: u32, } impl GetInformation for Student { fn get_name(&self) -> &String { &self.name } fn get_age(&self) -> u32 { self.age } } pub struct Teacher { pub name: String, pub age: u32, pub subject: String, } impl GetInformation for Teacher { fn get_name(&self) -> &String { &self.name } fn get_age(&self) -> u32 { self.age } } fn print_information(item: impl GetInformation){ println!("name: {}", item.get_name()); println!("age: {}", item.get_age()); }
use graph_generator_lib::*; use osquery_generator_lib::{ generator::OSQueryGenerator, metrics::OSQueryGeneratorMetrics, }; #[tokio::main] #[tracing::instrument] async fn main() -> Result<(), Box<dyn std::error::Error>> { let (env, _guard) = grapl_config::init_grapl_env!(); let service_name = env.service_name.clone(); tracing::info!( message = "Starting generator.", name =% service_name ); run_graph_generator( env, move |cache| OSQueryGenerator::new(cache, OSQueryGeneratorMetrics::new(&service_name)), grapl_service::decoder::NdjsonDecoder::default(), ) .await; Ok(()) }