text stringlengths 8 4.13M |
|---|
#[cfg(test)]
mod offset_tests {
use ds::SeqOffset;
use rand::prelude::*;
use std::collections::HashMap;
#[test]
fn test_offset() {
//test_seq_offset_one(1, 128, 32);
//test_seq_offset_one(8, 1024, 32);
test_seq_offset_one(64, 1024, 32);
}
// 一共生成num个offset,每interval次insert检查一次
fn test_seq_offset_one(cap: usize, num: usize, interval: usize) {
let offset = SeqOffset::with_capacity(cap);
let seqs = gen(num);
let mut cmp = 0;
let mut cached = HashMap::with_capacity(cap * 2);
let mut rng = rand::thread_rng();
for (i, &(start, end)) in seqs.iter().enumerate() {
let id = rng.next_u32() as usize % cap;
offset.insert(id, start, end);
cached.insert(start, end);
if i % interval == 0 {
while let Some(end) = cached.remove(&cmp) {
cmp = end;
}
assert_eq!(cmp, offset.load());
}
}
while let Some(end) = cached.remove(&cmp) {
cmp = end;
}
assert_eq!(cmp, offset.load());
assert_eq!(cached.len(), 0);
}
// 动态生成num个 (start, end)对
fn gen(num: usize) -> Vec<(usize, usize)> {
let max_len = 1024 * 1024u32;
let mut rng = rand::thread_rng();
let nums: Vec<usize> = (0..num)
.map(|_| 1.max(rng.next_u32() & (max_len - 1)) as usize)
.collect();
let mut offsets = Vec::with_capacity(num);
let mut offset = 0;
for len in nums[0..nums.len() - 1].iter() {
offsets.push((offset, offset + len));
offset += len;
}
let splits = 3;
for i in 0..splits {
let start = i * num / splits;
let end = (start + num / splits).min(num);
let slice = &mut offsets[start..end];
slice.shuffle(&mut rng);
}
// 分为三段,三段内部分别打乱顺序
offsets
}
}
|
#[doc = "Register `PRIVCFGR3` reader"]
pub type R = crate::R<PRIVCFGR3_SPEC>;
#[doc = "Register `PRIVCFGR3` writer"]
pub type W = crate::W<PRIVCFGR3_SPEC>;
#[doc = "Field `LPTIM6PRIV` reader - privileged access mode for LPTIM6"]
pub type LPTIM6PRIV_R = crate::BitReader;
#[doc = "Field `LPTIM6PRIV` writer - privileged access mode for LPTIM6"]
pub type LPTIM6PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `VREFBUFPRIV` reader - privileged access mode for VREFBUF"]
pub type VREFBUFPRIV_R = crate::BitReader;
#[doc = "Field `VREFBUFPRIV` writer - privileged access mode for VREFBUF"]
pub type VREFBUFPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CRCPRIV` reader - privileged access mode for CRC"]
pub type CRCPRIV_R = crate::BitReader;
#[doc = "Field `CRCPRIV` writer - privileged access mode for CRC"]
pub type CRCPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CORDICPRIV` reader - privileged access mode for CORDIC"]
pub type CORDICPRIV_R = crate::BitReader;
#[doc = "Field `CORDICPRIV` writer - privileged access mode for CORDIC"]
pub type CORDICPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FMACPRIV` reader - privileged access mode for FMAC"]
pub type FMACPRIV_R = crate::BitReader;
#[doc = "Field `FMACPRIV` writer - privileged access mode for FMAC"]
pub type FMACPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ETHPRIV` reader - privileged access mode for register of ETH"]
pub type ETHPRIV_R = crate::BitReader;
#[doc = "Field `ETHPRIV` writer - privileged access mode for register of ETH"]
pub type ETHPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ICACHEPRIV` reader - privileged access mode for ICACHE"]
pub type ICACHEPRIV_R = crate::BitReader;
#[doc = "Field `ICACHEPRIV` writer - privileged access mode for ICACHE"]
pub type ICACHEPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DCACHEPRIV` reader - privileged access mode for DCACHE"]
pub type DCACHEPRIV_R = crate::BitReader;
#[doc = "Field `DCACHEPRIV` writer - privileged access mode for DCACHE"]
pub type DCACHEPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ADC12PRIV` reader - privileged access mode for ADC1 and ADC2"]
pub type ADC12PRIV_R = crate::BitReader;
#[doc = "Field `ADC12PRIV` writer - privileged access mode for ADC1 and ADC2"]
pub type ADC12PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DCMIPRIV` reader - privileged access mode for DCMI"]
pub type DCMIPRIV_R = crate::BitReader;
#[doc = "Field `DCMIPRIV` writer - privileged access mode for DCMI"]
pub type DCMIPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AESPRIV` reader - privileged access mode for AES"]
pub type AESPRIV_R = crate::BitReader;
#[doc = "Field `AESPRIV` writer - privileged access mode for AES"]
pub type AESPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HASHPRIV` reader - privileged access mode for HASH"]
pub type HASHPRIV_R = crate::BitReader;
#[doc = "Field `HASHPRIV` writer - privileged access mode for HASH"]
pub type HASHPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RNGPRIV` reader - privileged access mode for RNG"]
pub type RNGPRIV_R = crate::BitReader;
#[doc = "Field `RNGPRIV` writer - privileged access mode for RNG"]
pub type RNGPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SAESPRIV` reader - privileged access mode for SAES"]
pub type SAESPRIV_R = crate::BitReader;
#[doc = "Field `SAESPRIV` writer - privileged access mode for SAES"]
pub type SAESPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PKAPRIV` reader - privileged access mode for PKA"]
pub type PKAPRIV_R = crate::BitReader;
#[doc = "Field `PKAPRIV` writer - privileged access mode for PKA"]
pub type PKAPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SDMMC2PRIV` reader - privileged access mode for SDMMC2"]
pub type SDMMC2PRIV_R = crate::BitReader;
#[doc = "Field `SDMMC2PRIV` writer - privileged access mode for SDMMC2"]
pub type SDMMC2PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SDMMC1PRIV` reader - privileged access mode for SDMMC1"]
pub type SDMMC1PRIV_R = crate::BitReader;
#[doc = "Field `SDMMC1PRIV` writer - privileged access mode for SDMMC1"]
pub type SDMMC1PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FMCPRIV` reader - privileged access mode for FMC"]
pub type FMCPRIV_R = crate::BitReader;
#[doc = "Field `FMCPRIV` writer - privileged access mode for FMC"]
pub type FMCPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OCTOSPI1PRIV` reader - privileged access mode for OCTOSPI1"]
pub type OCTOSPI1PRIV_R = crate::BitReader;
#[doc = "Field `OCTOSPI1PRIV` writer - privileged access mode for OCTOSPI1"]
pub type OCTOSPI1PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RAMCFGPRIV` reader - privileged access mode for RAMSCFG"]
pub type RAMCFGPRIV_R = crate::BitReader;
#[doc = "Field `RAMCFGPRIV` writer - privileged access mode for RAMSCFG"]
pub type RAMCFGPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - privileged access mode for LPTIM6"]
#[inline(always)]
pub fn lptim6priv(&self) -> LPTIM6PRIV_R {
LPTIM6PRIV_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - privileged access mode for VREFBUF"]
#[inline(always)]
pub fn vrefbufpriv(&self) -> VREFBUFPRIV_R {
VREFBUFPRIV_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 8 - privileged access mode for CRC"]
#[inline(always)]
pub fn crcpriv(&self) -> CRCPRIV_R {
CRCPRIV_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - privileged access mode for CORDIC"]
#[inline(always)]
pub fn cordicpriv(&self) -> CORDICPRIV_R {
CORDICPRIV_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - privileged access mode for FMAC"]
#[inline(always)]
pub fn fmacpriv(&self) -> FMACPRIV_R {
FMACPRIV_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - privileged access mode for register of ETH"]
#[inline(always)]
pub fn ethpriv(&self) -> ETHPRIV_R {
ETHPRIV_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - privileged access mode for ICACHE"]
#[inline(always)]
pub fn icachepriv(&self) -> ICACHEPRIV_R {
ICACHEPRIV_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - privileged access mode for DCACHE"]
#[inline(always)]
pub fn dcachepriv(&self) -> DCACHEPRIV_R {
DCACHEPRIV_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - privileged access mode for ADC1 and ADC2"]
#[inline(always)]
pub fn adc12priv(&self) -> ADC12PRIV_R {
ADC12PRIV_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - privileged access mode for DCMI"]
#[inline(always)]
pub fn dcmipriv(&self) -> DCMIPRIV_R {
DCMIPRIV_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - privileged access mode for AES"]
#[inline(always)]
pub fn aespriv(&self) -> AESPRIV_R {
AESPRIV_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - privileged access mode for HASH"]
#[inline(always)]
pub fn hashpriv(&self) -> HASHPRIV_R {
HASHPRIV_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - privileged access mode for RNG"]
#[inline(always)]
pub fn rngpriv(&self) -> RNGPRIV_R {
RNGPRIV_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - privileged access mode for SAES"]
#[inline(always)]
pub fn saespriv(&self) -> SAESPRIV_R {
SAESPRIV_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - privileged access mode for PKA"]
#[inline(always)]
pub fn pkapriv(&self) -> PKAPRIV_R {
PKAPRIV_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - privileged access mode for SDMMC2"]
#[inline(always)]
pub fn sdmmc2priv(&self) -> SDMMC2PRIV_R {
SDMMC2PRIV_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - privileged access mode for SDMMC1"]
#[inline(always)]
pub fn sdmmc1priv(&self) -> SDMMC1PRIV_R {
SDMMC1PRIV_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - privileged access mode for FMC"]
#[inline(always)]
pub fn fmcpriv(&self) -> FMCPRIV_R {
FMCPRIV_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - privileged access mode for OCTOSPI1"]
#[inline(always)]
pub fn octospi1priv(&self) -> OCTOSPI1PRIV_R {
OCTOSPI1PRIV_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 26 - privileged access mode for RAMSCFG"]
#[inline(always)]
pub fn ramcfgpriv(&self) -> RAMCFGPRIV_R {
RAMCFGPRIV_R::new(((self.bits >> 26) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - privileged access mode for LPTIM6"]
#[inline(always)]
#[must_use]
pub fn lptim6priv(&mut self) -> LPTIM6PRIV_W<PRIVCFGR3_SPEC, 0> {
LPTIM6PRIV_W::new(self)
}
#[doc = "Bit 1 - privileged access mode for VREFBUF"]
#[inline(always)]
#[must_use]
pub fn vrefbufpriv(&mut self) -> VREFBUFPRIV_W<PRIVCFGR3_SPEC, 1> {
VREFBUFPRIV_W::new(self)
}
#[doc = "Bit 8 - privileged access mode for CRC"]
#[inline(always)]
#[must_use]
pub fn crcpriv(&mut self) -> CRCPRIV_W<PRIVCFGR3_SPEC, 8> {
CRCPRIV_W::new(self)
}
#[doc = "Bit 9 - privileged access mode for CORDIC"]
#[inline(always)]
#[must_use]
pub fn cordicpriv(&mut self) -> CORDICPRIV_W<PRIVCFGR3_SPEC, 9> {
CORDICPRIV_W::new(self)
}
#[doc = "Bit 10 - privileged access mode for FMAC"]
#[inline(always)]
#[must_use]
pub fn fmacpriv(&mut self) -> FMACPRIV_W<PRIVCFGR3_SPEC, 10> {
FMACPRIV_W::new(self)
}
#[doc = "Bit 11 - privileged access mode for register of ETH"]
#[inline(always)]
#[must_use]
pub fn ethpriv(&mut self) -> ETHPRIV_W<PRIVCFGR3_SPEC, 11> {
ETHPRIV_W::new(self)
}
#[doc = "Bit 12 - privileged access mode for ICACHE"]
#[inline(always)]
#[must_use]
pub fn icachepriv(&mut self) -> ICACHEPRIV_W<PRIVCFGR3_SPEC, 12> {
ICACHEPRIV_W::new(self)
}
#[doc = "Bit 13 - privileged access mode for DCACHE"]
#[inline(always)]
#[must_use]
pub fn dcachepriv(&mut self) -> DCACHEPRIV_W<PRIVCFGR3_SPEC, 13> {
DCACHEPRIV_W::new(self)
}
#[doc = "Bit 14 - privileged access mode for ADC1 and ADC2"]
#[inline(always)]
#[must_use]
pub fn adc12priv(&mut self) -> ADC12PRIV_W<PRIVCFGR3_SPEC, 14> {
ADC12PRIV_W::new(self)
}
#[doc = "Bit 15 - privileged access mode for DCMI"]
#[inline(always)]
#[must_use]
pub fn dcmipriv(&mut self) -> DCMIPRIV_W<PRIVCFGR3_SPEC, 15> {
DCMIPRIV_W::new(self)
}
#[doc = "Bit 16 - privileged access mode for AES"]
#[inline(always)]
#[must_use]
pub fn aespriv(&mut self) -> AESPRIV_W<PRIVCFGR3_SPEC, 16> {
AESPRIV_W::new(self)
}
#[doc = "Bit 17 - privileged access mode for HASH"]
#[inline(always)]
#[must_use]
pub fn hashpriv(&mut self) -> HASHPRIV_W<PRIVCFGR3_SPEC, 17> {
HASHPRIV_W::new(self)
}
#[doc = "Bit 18 - privileged access mode for RNG"]
#[inline(always)]
#[must_use]
pub fn rngpriv(&mut self) -> RNGPRIV_W<PRIVCFGR3_SPEC, 18> {
RNGPRIV_W::new(self)
}
#[doc = "Bit 19 - privileged access mode for SAES"]
#[inline(always)]
#[must_use]
pub fn saespriv(&mut self) -> SAESPRIV_W<PRIVCFGR3_SPEC, 19> {
SAESPRIV_W::new(self)
}
#[doc = "Bit 20 - privileged access mode for PKA"]
#[inline(always)]
#[must_use]
pub fn pkapriv(&mut self) -> PKAPRIV_W<PRIVCFGR3_SPEC, 20> {
PKAPRIV_W::new(self)
}
#[doc = "Bit 21 - privileged access mode for SDMMC2"]
#[inline(always)]
#[must_use]
pub fn sdmmc2priv(&mut self) -> SDMMC2PRIV_W<PRIVCFGR3_SPEC, 21> {
SDMMC2PRIV_W::new(self)
}
#[doc = "Bit 22 - privileged access mode for SDMMC1"]
#[inline(always)]
#[must_use]
pub fn sdmmc1priv(&mut self) -> SDMMC1PRIV_W<PRIVCFGR3_SPEC, 22> {
SDMMC1PRIV_W::new(self)
}
#[doc = "Bit 23 - privileged access mode for FMC"]
#[inline(always)]
#[must_use]
pub fn fmcpriv(&mut self) -> FMCPRIV_W<PRIVCFGR3_SPEC, 23> {
FMCPRIV_W::new(self)
}
#[doc = "Bit 24 - privileged access mode for OCTOSPI1"]
#[inline(always)]
#[must_use]
pub fn octospi1priv(&mut self) -> OCTOSPI1PRIV_W<PRIVCFGR3_SPEC, 24> {
OCTOSPI1PRIV_W::new(self)
}
#[doc = "Bit 26 - privileged access mode for RAMSCFG"]
#[inline(always)]
#[must_use]
pub fn ramcfgpriv(&mut self) -> RAMCFGPRIV_W<PRIVCFGR3_SPEC, 26> {
RAMCFGPRIV_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "GTZC1 TZSC privilege configuration register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privcfgr3::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`privcfgr3::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PRIVCFGR3_SPEC;
impl crate::RegisterSpec for PRIVCFGR3_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`privcfgr3::R`](R) reader structure"]
impl crate::Readable for PRIVCFGR3_SPEC {}
#[doc = "`write(|w| ..)` method takes [`privcfgr3::W`](W) writer structure"]
impl crate::Writable for PRIVCFGR3_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets PRIVCFGR3 to value 0"]
impl crate::Resettable for PRIVCFGR3_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ServerVersion {
#[serde(rename = "5.7")]
N5_7,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SslEnforcement {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum InfrastructureEncryption {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PublicNetworkAccess {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum HaEnabled {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DelegatedSubnetArguments {
#[serde(rename = "subnetArmResourceId", default, skip_serializing_if = "Option::is_none")]
pub subnet_arm_resource_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateDnsZoneArguments {
#[serde(rename = "privateDnsZoneArmResourceId", default, skip_serializing_if = "Option::is_none")]
pub private_dns_zone_arm_resource_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MaintenanceWindow {
#[serde(rename = "customWindow", default, skip_serializing_if = "Option::is_none")]
pub custom_window: Option<String>,
#[serde(rename = "startHour", default, skip_serializing_if = "Option::is_none")]
pub start_hour: Option<i32>,
#[serde(rename = "startMinute", default, skip_serializing_if = "Option::is_none")]
pub start_minute: Option<i32>,
#[serde(rename = "dayOfWeek", default, skip_serializing_if = "Option::is_none")]
pub day_of_week: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageProfile {
#[serde(rename = "backupRetentionDays", default, skip_serializing_if = "Option::is_none")]
pub backup_retention_days: Option<i32>,
#[serde(rename = "storageMB", default, skip_serializing_if = "Option::is_none")]
pub storage_mb: Option<i32>,
#[serde(rename = "storageIops", default, skip_serializing_if = "Option::is_none")]
pub storage_iops: Option<i32>,
#[serde(rename = "storageAutogrow", default, skip_serializing_if = "Option::is_none")]
pub storage_autogrow: Option<storage_profile::StorageAutogrow>,
#[serde(rename = "fileStorageSkuName", default, skip_serializing_if = "Option::is_none")]
pub file_storage_sku_name: Option<String>,
}
pub mod storage_profile {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum StorageAutogrow {
Enabled,
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Sku {
pub name: String,
pub tier: sku::Tier,
}
pub mod sku {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Tier {
Burstable,
GeneralPurpose,
MemoryOptimized,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerProperties {
#[serde(rename = "administratorLogin", default, skip_serializing_if = "Option::is_none")]
pub administrator_login: Option<String>,
#[serde(rename = "administratorLoginPassword", default, skip_serializing_if = "Option::is_none")]
pub administrator_login_password: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<ServerVersion>,
#[serde(rename = "sslEnforcement", default, skip_serializing_if = "Option::is_none")]
pub ssl_enforcement: Option<SslEnforcement>,
#[serde(rename = "infrastructureEncryption", default, skip_serializing_if = "Option::is_none")]
pub infrastructure_encryption: Option<InfrastructureEncryption>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<server_properties::State>,
#[serde(rename = "haState", default, skip_serializing_if = "Option::is_none")]
pub ha_state: Option<server_properties::HaState>,
#[serde(rename = "haEnabled", default, skip_serializing_if = "Option::is_none")]
pub ha_enabled: Option<HaEnabled>,
#[serde(rename = "fullyQualifiedDomainName", default, skip_serializing_if = "Option::is_none")]
pub fully_qualified_domain_name: Option<String>,
#[serde(rename = "earliestRestoreDate", default, skip_serializing_if = "Option::is_none")]
pub earliest_restore_date: Option<String>,
#[serde(rename = "storageProfile", default, skip_serializing_if = "Option::is_none")]
pub storage_profile: Option<StorageProfile>,
#[serde(rename = "replicationRole", default, skip_serializing_if = "Option::is_none")]
pub replication_role: Option<String>,
#[serde(rename = "replicaCapacity", default, skip_serializing_if = "Option::is_none")]
pub replica_capacity: Option<i32>,
#[serde(rename = "publicNetworkAccess", default, skip_serializing_if = "Option::is_none")]
pub public_network_access: Option<PublicNetworkAccess>,
#[serde(rename = "maintenanceWindow", default, skip_serializing_if = "Option::is_none")]
pub maintenance_window: Option<MaintenanceWindow>,
#[serde(rename = "sourceServerId", default, skip_serializing_if = "Option::is_none")]
pub source_server_id: Option<String>,
#[serde(rename = "restorePointInTime", default, skip_serializing_if = "Option::is_none")]
pub restore_point_in_time: Option<String>,
#[serde(rename = "availabilityZone", default, skip_serializing_if = "Option::is_none")]
pub availability_zone: Option<String>,
#[serde(rename = "standbyAvailabilityZone", default, skip_serializing_if = "Option::is_none")]
pub standby_availability_zone: Option<String>,
#[serde(rename = "byokEnforcement", default, skip_serializing_if = "Option::is_none")]
pub byok_enforcement: Option<String>,
#[serde(rename = "delegatedSubnetArguments", default, skip_serializing_if = "Option::is_none")]
pub delegated_subnet_arguments: Option<DelegatedSubnetArguments>,
#[serde(rename = "privateDnsZoneArguments", default, skip_serializing_if = "Option::is_none")]
pub private_dns_zone_arguments: Option<PrivateDnsZoneArguments>,
#[serde(rename = "createMode", default, skip_serializing_if = "Option::is_none")]
pub create_mode: Option<server_properties::CreateMode>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
pub mod server_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum State {
Ready,
Dropping,
Disabled,
Starting,
Stopping,
Stopped,
Updating,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum HaState {
NotEnabled,
CreatingStandby,
ReplicatingData,
FailingOver,
Healthy,
RemovingStandby,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CreateMode {
Default,
PointInTimeRestore,
Replica,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Server {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<Identity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ServerProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerPropertiesForUpdate {
#[serde(rename = "storageProfile", default, skip_serializing_if = "Option::is_none")]
pub storage_profile: Option<StorageProfile>,
#[serde(rename = "administratorLoginPassword", default, skip_serializing_if = "Option::is_none")]
pub administrator_login_password: Option<String>,
#[serde(rename = "sslEnforcement", default, skip_serializing_if = "Option::is_none")]
pub ssl_enforcement: Option<SslEnforcement>,
#[serde(rename = "delegatedSubnetArguments", default, skip_serializing_if = "Option::is_none")]
pub delegated_subnet_arguments: Option<DelegatedSubnetArguments>,
#[serde(rename = "haEnabled", default, skip_serializing_if = "Option::is_none")]
pub ha_enabled: Option<HaEnabled>,
#[serde(rename = "maintenanceWindow", default, skip_serializing_if = "Option::is_none")]
pub maintenance_window: Option<MaintenanceWindow>,
#[serde(rename = "replicationRole", default, skip_serializing_if = "Option::is_none")]
pub replication_role: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerForUpdate {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ServerPropertiesForUpdate>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Server>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerKeyProperties {
#[serde(rename = "serverKeyType")]
pub server_key_type: server_key_properties::ServerKeyType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub uri: Option<String>,
#[serde(rename = "creationDate", default, skip_serializing_if = "Option::is_none")]
pub creation_date: Option<String>,
}
pub mod server_key_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ServerKeyType {
AzureKeyVault,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerKey {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ServerKeyProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerKeyListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ServerKey>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FirewallRuleProperties {
#[serde(rename = "startIpAddress")]
pub start_ip_address: String,
#[serde(rename = "endIpAddress")]
pub end_ip_address: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FirewallRule {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
pub properties: FirewallRuleProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FirewallRuleListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<FirewallRule>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatabaseProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub charset: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub collation: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Database {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DatabaseProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatabaseListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Database>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "defaultValue", default, skip_serializing_if = "Option::is_none")]
pub default_value: Option<String>,
#[serde(rename = "dataType", default, skip_serializing_if = "Option::is_none")]
pub data_type: Option<String>,
#[serde(rename = "allowedValues", default, skip_serializing_if = "Option::is_none")]
pub allowed_values: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
#[serde(rename = "isReadOnly", default, skip_serializing_if = "Option::is_none")]
pub is_read_only: Option<configuration_properties::IsReadOnly>,
#[serde(rename = "isConfigPendingRestart", default, skip_serializing_if = "Option::is_none")]
pub is_config_pending_restart: Option<configuration_properties::IsConfigPendingRestart>,
#[serde(rename = "isDynamicConfig", default, skip_serializing_if = "Option::is_none")]
pub is_dynamic_config: Option<configuration_properties::IsDynamicConfig>,
}
pub mod configuration_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum IsReadOnly {
True,
False,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum IsConfigPendingRestart {
True,
False,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum IsDynamicConfig {
True,
False,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Configuration {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ConfigurationProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Configuration>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNetworkSubnetUsageParameter {
#[serde(rename = "virtualNetworkArmResourceId", default, skip_serializing_if = "Option::is_none")]
pub virtual_network_arm_resource_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DelegatedSubnetUsage {
#[serde(rename = "subnetName", default, skip_serializing_if = "Option::is_none")]
pub subnet_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNetworkSubnetUsageResult {
#[serde(rename = "delegatedSubnetsUsage", default, skip_serializing_if = "Vec::is_empty")]
pub delegated_subnets_usage: Vec<DelegatedSubnetUsage>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageMbCapability {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "storageSizeMB", default, skip_serializing_if = "Option::is_none")]
pub storage_size_mb: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VcoreCapability {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "vCores", default, skip_serializing_if = "Option::is_none")]
pub v_cores: Option<i64>,
#[serde(rename = "supportedIops", default, skip_serializing_if = "Option::is_none")]
pub supported_iops: Option<i64>,
#[serde(rename = "supportedMemoryPerVcoreMB", default, skip_serializing_if = "Option::is_none")]
pub supported_memory_per_vcore_mb: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerVersionCapability {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "supportedVcores", default, skip_serializing_if = "Vec::is_empty")]
pub supported_vcores: Vec<VcoreCapability>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageEditionCapability {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "minStorageSize", default, skip_serializing_if = "Option::is_none")]
pub min_storage_size: Option<StorageMbCapability>,
#[serde(rename = "maxStorageSize", default, skip_serializing_if = "Option::is_none")]
pub max_storage_size: Option<StorageMbCapability>,
#[serde(rename = "minBackupRetentionDays", default, skip_serializing_if = "Option::is_none")]
pub min_backup_retention_days: Option<i64>,
#[serde(rename = "maxBackupRetentionDays", default, skip_serializing_if = "Option::is_none")]
pub max_backup_retention_days: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerEditionCapability {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "supportedStorageEditions", default, skip_serializing_if = "Vec::is_empty")]
pub supported_storage_editions: Vec<StorageEditionCapability>,
#[serde(rename = "supportedServerVersions", default, skip_serializing_if = "Vec::is_empty")]
pub supported_server_versions: Vec<ServerVersionCapability>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CapabilityProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub zone: Option<String>,
#[serde(rename = "supportedFlexibleServerEditions", default, skip_serializing_if = "Vec::is_empty")]
pub supported_flexible_server_editions: Vec<ServerEditionCapability>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CapabilitiesListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<CapabilityProperties>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationDisplay {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<OperationDisplay>,
#[serde(rename = "isDataAction", default, skip_serializing_if = "Option::is_none")]
pub is_data_action: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<operation::Origin>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<serde_json::Value>,
}
pub mod operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Origin {
NotSpecified,
#[serde(rename = "user")]
User,
#[serde(rename = "system")]
System,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Operation>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NameAvailabilityRequest {
pub name: String,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NameAvailability {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")]
pub name_available: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudError {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorResponse>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Identity {
#[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")]
pub principal_id: Option<String>,
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<identity::Type>,
}
pub mod identity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
SystemAssigned,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrackedResource {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
pub location: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProxyResource {
#[serde(flatten)]
pub resource: Resource,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<ErrorResponse>,
#[serde(rename = "additionalInfo", default, skip_serializing_if = "Vec::is_empty")]
pub additional_info: Vec<ErrorAdditionalInfo>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorAdditionalInfo {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub info: Option<serde_json::Value>,
}
|
use bincode::{serialize_into, Infinite};
use private;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::fs;
use std::io::{BufWriter, Write};
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
#[inline]
fn u32tou8abe(v: u32) -> [u8; 4] {
[v as u8, (v >> 8) as u8, (v >> 24) as u8, (v >> 16) as u8]
}
#[derive(Debug)]
/// The 'send' side of hopper, similar to
/// [`std::sync::mpsc::Sender`](https://doc.rust-lang.org/std/sync/mpsc/struct.
/// Sender.html).
pub struct Sender<T> {
name: String,
root: PathBuf, // directory we store our queues in
path: PathBuf, // active fp filename
seq_num: usize,
max_bytes: usize,
fs_lock: private::FSLock<T>,
resource_type: PhantomData<T>,
}
impl<'de, T> Clone for Sender<T>
where
T: Serialize + Deserialize<'de>,
{
fn clone(&self) -> Sender<T> {
use std::sync::Arc;
Sender::new(
self.name.clone(),
&self.root,
self.max_bytes,
Arc::clone(&self.fs_lock),
).expect("COULD NOT CLONE")
}
}
impl<T> Sender<T>
where
T: Serialize,
{
#[doc(hidden)]
pub fn new<S>(
name: S,
data_dir: &Path,
max_bytes: usize,
fs_lock: private::FSLock<T>,
) -> Result<Sender<T>, super::Error>
where
S: Into<String> + fmt::Display,
{
use std::sync::Arc;
let init_fs_lock = Arc::clone(&fs_lock);
let mut syn = init_fs_lock.lock().expect("Sender fs_lock poisoned");
if !data_dir.is_dir() {
return Err(super::Error::NoSuchDirectory);
}
let seq_num = match fs::read_dir(data_dir)
.unwrap()
.map(|de| {
de.unwrap()
.path()
.file_name()
.unwrap()
.to_str()
.unwrap()
.parse::<usize>()
.unwrap()
})
.max()
{
Some(sn) => sn,
None => 0,
};
let log = data_dir.join(format!("{}", seq_num));
match fs::OpenOptions::new().append(true).create(true).open(&log) {
Ok(fp) => {
syn.sender_fp = Some(BufWriter::new(fp));
(*syn).sender_seq_num = seq_num;
Ok(Sender {
name: name.into(),
root: data_dir.to_path_buf(),
path: log,
seq_num: seq_num,
max_bytes: max_bytes,
fs_lock: fs_lock,
resource_type: PhantomData,
})
}
Err(e) => panic!("[Sender] failed to start {:?}", e),
}
}
/// send writes data out in chunks, like so:
///
/// u32: payload_size
/// [u8] payload
///
pub fn send(&mut self, event: T) {
let mut syn = self.fs_lock.lock().expect("Sender fs_lock poisoned");
let fslock = &mut (*syn);
if fslock.sender_idx < fslock.in_memory_idx {
fslock.mem_buffer.push_back(event);
} else {
fslock.disk_buffer.push_back(event);
if fslock.disk_buffer.len() >= fslock.in_memory_idx {
while let Some(ev) = fslock.disk_buffer.pop_front() {
let mut pyld = Vec::with_capacity(64);
serialize_into(&mut pyld, &ev, Infinite).expect("could not serialize");
// NOTE The conversion of t.len to u32 and usize is _only_
// safe when u32 <= usize. That's very likely to hold true
// for machines--for now?--that hopper will run on. However!
let pyld_sz_bytes: [u8; 4] = u32tou8abe(pyld.len() as u32);
let mut t = vec![0, 0, 0, 0];
t[0] = pyld_sz_bytes[3];
t[1] = pyld_sz_bytes[2];
t[2] = pyld_sz_bytes[1];
t[3] = pyld_sz_bytes[0];
t.append(&mut pyld);
// If the individual sender writes enough to go over the max
// we mark the file read-only--which will help the receiver
// to decide it has hit the end of its log file--and create
// a new log file.
let bytes_written = fslock.bytes_written + t.len();
if (bytes_written > self.max_bytes) || (self.seq_num != fslock.sender_seq_num)
|| fslock.sender_fp.is_none()
{
// Once we've gone over the write limit for our current
// file or find that we've gotten behind the current
// queue file we need to seek forward to find our place
// in the space of queue files. We mark our current file
// read-only--there's some possibility that this will be
// done redundantly, but that's okay--and then read the
// current sender_seq_num to get up to date.
let _ = fs::metadata(&self.path).map(|p| {
let mut permissions = p.permissions();
permissions.set_readonly(true);
let _ = fs::set_permissions(&self.path, permissions);
});
if fslock.sender_fp.is_some() {
if self.seq_num != fslock.sender_seq_num {
// This thread is behind the leader. We've got to
// set our current notion of seq_num forward and
// then open the corresponding file.
self.seq_num = fslock.sender_seq_num;
} else {
// This thread is the leader. We reset the
// sender_seq_num and bytes written and open the
// next queue file. All follower threads will hit
// the branch above this one.
fslock.sender_seq_num = self.seq_num.wrapping_add(1);
self.seq_num = fslock.sender_seq_num;
fslock.bytes_written = 0;
}
}
self.path = self.root.join(format!("{}", self.seq_num));
match fs::OpenOptions::new()
.append(true)
.create(true)
.open(&self.path)
{
Ok(fp) => fslock.sender_fp = Some(BufWriter::new(fp)),
Err(e) => panic!("FAILED TO OPEN {:?} WITH {:?}", &self.path, e),
}
}
assert!(fslock.sender_fp.is_some());
if let Some(ref mut fp) = fslock.sender_fp {
match fp.write(&t[..]) {
Ok(written) => fslock.bytes_written += written,
Err(e) => panic!("Write error: {}", e),
}
fslock.disk_writes_to_read += 1;
}
}
assert!(fslock.sender_fp.is_some());
if let Some(ref mut fp) = fslock.sender_fp {
fp.flush().expect("unable to flush");
}
}
}
fslock.writes_to_read += 1;
if (fslock.sender_captured_recv_id != fslock.receiver_read_id)
|| fslock.write_bound.is_none()
{
fslock.sender_captured_recv_id = fslock.receiver_read_id;
fslock.write_bound = Some(fslock.sender_idx);
}
fslock.sender_idx += 1;
}
/// Return the sender's name
pub fn name(&self) -> &str {
&self.name
}
}
|
//! ELF Linker/Loader
use error::*;
use goblin;
use goblin::Hint;
use loader::*;
use loader::memory::*;
use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
// http://stackoverflow.com/questions/37678698/function-to-build-a-fixed-sized-array-from-slice/37679019#37679019
use std::convert::AsMut;
fn clone_into_array<A, T>(slice: &[T]) -> A
where A: Sized + Default + AsMut<[T]>,
T: Clone
{
let mut a = Default::default();
<A as AsMut<[T]>>::as_mut(&mut a).clone_from_slice(slice);
a
}
/// The address where the first library will be loaded
const DEFAULT_LIB_BASE: u64 = 0x8000_0000;
/// The step in address between where we will load libraries.
const LIB_BASE_STEP: u64 = 0x0400_0000;
/// Loads and links multiple ELFs together
#[derive(Clone, Debug)]
pub struct ElfLinker {
/// The filename (path included) of the file we're loading.
filename: PathBuf,
/// A mapping from lib name (for example `libc.so.6`) to Elf.
loaded: BTreeMap<String, Elf>,
/// The current memory mapping.
memory: Memory,
/// A mapping of function symbol names to addresses
symbols: BTreeMap<String, u64>,
/// The address we will place the next library at.
next_lib_address: u64,
/// Functions as specified by the user
user_functions: Vec<u64>
}
impl ElfLinker {
/// Takes a path to an Elf and loads the Elf, its dependencies, and links
/// them together.
pub fn new(filename: &Path) -> Result<ElfLinker> {
let mut elf_linker = ElfLinker {
filename: filename.to_owned(),
loaded: BTreeMap::new(),
memory: Memory::new(),
symbols: BTreeMap::new(),
next_lib_address: DEFAULT_LIB_BASE,
user_functions: Vec::new(),
};
elf_linker.load_elf(filename, 0)?;
Ok(elf_linker)
}
/// Takes the path to an Elf, and a base address the Elf should be loaded
/// at. Loads the Elf, all it's dependencies (DT_NEEDED), and then handles
/// the supported relocations.
pub fn load_elf(&mut self, filename: &Path, base_address: u64)
-> Result<()> {
// Does this file exist in the same directory as the original file?
let mut base_path = match self.filename.as_path().parent() {
Some(base_path) => base_path.to_path_buf(),
None => PathBuf::new()
};
base_path.push(filename);
let filename = if base_path.exists() {
&base_path
}
else {
filename
};
info!("Loading {} with base_address 0x{:x}",
filename.to_str().unwrap(),
base_address);
let elf = Elf::from_file_with_base_address(filename, base_address)?;
// Update our memory map based on what's in the Elf
for segment in elf.memory()?.segments() {
self.memory.add_segment(segment.1.clone());
}
// Add this Elf to the loaded Elfs
let filename = filename.file_name()
.unwrap()
.to_str()
.unwrap()
.to_string();
self.loaded.insert(filename.clone(), elf);
{
let ref elf = self.loaded[&filename];
// Add its exported symbols to our symbols
for symbol in elf.exported_symbols() {
if self.symbols.get(symbol.name()).is_some() {
continue;
}
self.symbols.insert(
symbol.name().to_string(),
elf.base_address() + symbol.address()
);
}
}
// Ensure all shared objects we rely on are loaded
for so_name in self.loaded[&filename].dt_needed()?.clone() {
if self.loaded.get(&so_name).is_none() {
self.next_lib_address += LIB_BASE_STEP;
let next_lib_address = self.next_lib_address;
self.load_elf(Path::new(&so_name), next_lib_address)?;
}
}
// Process relocations
let ref elf = self.loaded[&filename];
let dynsyms = elf.elf().dynsyms;
let dynstrtab = elf.elf().dynstrtab;
let header = elf.elf().header;
for reloc in elf.elf()
.dynrelas
.iter()
.chain(elf.elf()
.dynrels
.iter()
.chain(elf.elf()
.pltrelocs
.iter())) {
match header.e_machine {
goblin::elf::header::EM_386 => {
match reloc.r_type {
goblin::elf::reloc::R_386_NONE => {},
goblin::elf::reloc::R_386_32 => {
let value = match self.resolve_reloc_symbol(&filename, &reloc) {
Ok(v) => v.to_owned() as u32,
Err(e) => {
warn!("{}", e);
continue
}
};
self.memory.set_u32_le(
reloc.r_offset as u64 + elf.base_address(),
value
)?;
},
goblin::elf::reloc::R_386_PC32 => {
let value = match self.resolve_reloc_symbol(&filename, &reloc) {
Ok(v) => v.to_owned() as u32,
Err(e) => {
warn!("{}", e);
continue
}
};
self.memory.set_u32_le(
reloc.r_offset as u64 + elf.base_address(),
value - (reloc.r_offset as u32)
)?;
},
goblin::elf::reloc::R_386_GOT32 => {
bail!("R_386_GOT32");
},
goblin::elf::reloc::R_386_PLT32 => {
let ref sym = dynsyms[reloc.r_sym];
let sym_name = dynstrtab.get(sym.st_name);
bail!("R_386_PLT32 {}:0x{:x}:{}", filename, reloc.r_offset, sym_name);
},
goblin::elf::reloc::R_386_COPY => {
let address = match self.resolve_reloc_symbol(&filename, &reloc) {
Ok(v) => v.to_owned() as u64,
Err(e) => {
warn!("{}", e);
continue
}
};
if let Some(value) = self.memory.get_u32_le(address) {
self.memory.set_u32_le(
reloc.r_offset as u64 + elf.base_address(),
value
)?;
} else {
warn!("Could not read address 0x{:x} in R_386_COPY", address);
continue
}
},
goblin::elf::reloc::R_386_GLOB_DAT
| goblin::elf::reloc::R_386_JMP_SLOT => {
let value = match self.resolve_reloc_symbol(&filename, &reloc) {
Ok(v) => v.to_owned() as u32,
Err(e) => {
warn!("{}", e);
continue
}
};
self.memory.set_u32_le(
reloc.r_offset as u64 + elf.base_address(),
value
)?;
},
goblin::elf::reloc::R_386_RELATIVE => {
let value = self.memory.get_u32_le(reloc.r_offset as u64 + elf.base_address());
let value = match value {
Some(value) => elf.base_address() as u32 + value,
None => bail!("Invalid address for R_386_RELATIVE {}:{:x}",
filename,
reloc.r_offset)
};
self.memory.set_u32_le(reloc.r_offset as u64 + elf.base_address(), value)?;
},
goblin::elf::reloc::R_386_GOTPC => {
bail!("R_386_GOT_PC");
},
goblin::elf::reloc::R_386_TLS_TPOFF => {
warn!("Ignoring R_386_TLS_TPOFF Relocation");
},
goblin::elf::reloc::R_386_IRELATIVE => {
warn!("R_386_IRELATIVE {}:0x{:x} going unprocessed", filename, reloc.r_offset);
},
_ => bail!("unhandled relocation type {}", reloc.r_type)
}
},
_ => bail!("unhandled ELF machine {}", header.e_machine)
}
}
Ok(())
}
/// Inform the linker of a function at the given address.
///
/// This function will be added to calls to `function_entries` and will be automatically
/// lifted when calling `to_program`.
pub fn add_user_function(&mut self, address: u64) {
self.user_functions.push(address);
}
fn resolve_reloc_symbol(&self, filename: &str, reloc: &goblin::elf::reloc::Reloc) -> Result<u64> {
let ref elf = self.loaded[filename];
let dynsyms = elf.elf().dynsyms;
let dynstrtab = elf.elf().dynstrtab;
let ref sym = dynsyms[reloc.r_sym];
let sym_name = dynstrtab.get(sym.st_name);
match self.symbols.get(sym_name) {
Some(address) => Ok(*address),
None => Err(format!("Could not resolve symbol {}", sym_name).into())
}
}
}
impl Loader for ElfLinker {
fn memory(&self) -> Result<memory::Memory> {
Ok(self.memory.clone())
}
fn function_entries(&self) -> Result<Vec<FunctionEntry>> {
let mut function_entries = Vec::new();
for loaded in &self.loaded {
// let fe = loaded.1.function_entries()?;
// for e in &fe {
// println!("{} 0x{:x}", loaded.0, e.address());
// }
function_entries.append(&mut loaded.1.function_entries()?);
}
for address in &self.user_functions {
function_entries.push(FunctionEntry::new(*address, None));
}
Ok(function_entries)
}
// TODO Just maybe a bit too much unwrapping here.
fn program_entry(&self) -> u64 {
let filename = self.filename
.as_path()
.file_name()
.unwrap()
.to_str()
.unwrap();
self.loaded[filename].program_entry()
}
fn architecture(&self) -> Result<Architecture> {
let filename = self.filename
.as_path()
.file_name()
.unwrap()
.to_str()
.unwrap();
self.loaded[filename].architecture()
}
}
#[derive(Clone, Debug)]
struct ElfSymbol {
name: String,
address: u64
}
impl ElfSymbol {
fn new<S: Into<String>>(name: S, address: u64) -> ElfSymbol {
ElfSymbol {
name: name.into(),
address: address
}
}
fn name(&self) -> &str {
&self.name
}
fn address(&self) -> u64 {
self.address
}
}
/// Loads a single ELf.
#[derive(Clone, Debug)]
pub struct Elf {
base_address: u64,
bytes: Vec<u8>,
user_function_entries: Vec<u64>
}
impl Elf {
/// Create a new Elf from the given bytes. This Elf will be rebased to the given
/// base address.
pub fn new(bytes: Vec<u8>, base_address: u64) -> Result<Elf> {
let peek_bytes: [u8; 16] = clone_into_array(&bytes[0..16]);
// Load this Elf
let elf = match goblin::peek_bytes(&peek_bytes)? {
Hint::Elf(_) => Elf {
base_address: base_address,
bytes: bytes,
user_function_entries: Vec::new()
},
_ => return Err("Not a valid elf".into())
};
Ok(elf)
}
/// Get the base address of this Elf where it has been loaded into loader
/// memory.
pub fn base_address(&self) -> u64 {
self.base_address
}
/// Load an Elf from a file and use the given base address.
pub fn from_file_with_base_address(filename: &Path, base_address: u64)
-> Result<Elf> {
let mut file = match File::open(filename) {
Ok(file) => file,
Err(e) => return Err(format!(
"Error opening {}: {}",
filename.to_str().unwrap(),
e).into())
};
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
Elf::new(buf, base_address)
}
/// Load an elf from a file and use the base address of 0.
pub fn from_file(filename: &Path) -> Result<Elf> {
Elf::from_file_with_base_address(filename, 0)
}
/// Allow the user to manually specify a function entry
pub fn add_user_function(&mut self, address: u64) {
self.user_function_entries.push(address);
}
/// Return the strings from the DT_NEEDED entries.
pub fn dt_needed(&self) -> Result<Vec<String>> {
let mut v = Vec::new();
let elf = self.elf();
if let Some(dynamic) = elf.dynamic {
// We need that strtab, and we have to do this one manually.
// Get the strtab address
let mut strtab_address = None;
for dyn in &dynamic.dyns {
if dyn.d_tag == goblin::elf::dyn::DT_STRTAB {
strtab_address = Some(dyn.d_val);
break;
}
}
if strtab_address.is_none() {
return Ok(v);
}
let strtab_address = strtab_address.unwrap();
// We're going to make a pretty safe assumption that strtab is all
// in one section
let mut strtab = None;
for section_header in &elf.section_headers {
if section_header.sh_addr > 0
&& section_header.sh_addr <= strtab_address
&& section_header.sh_addr + section_header.sh_size > strtab_address {
let start = section_header.sh_offset + (strtab_address - section_header.sh_addr);
let size = section_header.sh_size - (start - section_header.sh_offset);
let start = start as usize;
let size = size as usize;
let strtab_bytes = self.bytes.get(start..(start + size)).unwrap();
strtab = Some(goblin::strtab::Strtab::new(strtab_bytes.to_vec(), 0));
}
}
if strtab.is_none() {
panic!("Failed to get Dynamic strtab");
}
let strtab = strtab.unwrap();
for dyn in dynamic.dyns {
if dyn.d_tag == goblin::elf::dyn::DT_NEEDED {
let so_name = strtab.get(dyn.d_val as usize);
v.push(so_name.to_string());
}
}
}
Ok(v)
}
/// Return the goblin::elf::Elf for this elf.
fn elf(&self) -> goblin::elf::Elf {
goblin::elf::Elf::parse(&self.bytes).unwrap()
}
/// Return all symbols exported from this Elf
fn exported_symbols(&self) -> Vec<ElfSymbol> {
let mut v = Vec::new();
let elf = self.elf();
for sym in elf.dynsyms {
if sym.st_value == 0 {
continue;
}
if sym.st_bind() == goblin::elf::sym::STB_GLOBAL
|| sym.st_bind() == goblin::elf::sym::STB_WEAK {
v.push(ElfSymbol::new(elf.dynstrtab.get(sym.st_name), sym.st_value));
}
}
v
}
}
impl Loader for Elf {
fn memory(&self) -> Result<Memory> {
let elf = self.elf();
let mut memory = Memory::new();
for ph in elf.program_headers {
if ph.p_type == goblin::elf::program_header::PT_LOAD {
let file_range = (ph.p_offset as usize)..((ph.p_offset + ph.p_filesz) as usize);
let mut bytes = self.bytes
.get(file_range)
.ok_or("Malformed Elf")?
.to_vec();
if bytes.len() != ph.p_memsz as usize {
bytes.append(&mut vec![0; (ph.p_memsz - ph.p_filesz) as usize]);
}
let mut permissions = NONE;
if ph.p_flags & goblin::elf::program_header::PF_R != 0 {
permissions |= READ;
}
if ph.p_flags & goblin::elf::program_header::PF_W != 0 {
permissions |= WRITE;
}
if ph.p_flags & goblin::elf::program_header::PF_X != 0 {
permissions |= EXECUTE;
}
let segment = MemorySegment::new(
ph.p_vaddr + self.base_address,
bytes,
permissions
);
memory.add_segment(segment);
}
}
Ok(memory)
}
fn function_entries(&self) -> Result<Vec<FunctionEntry>> {
let elf = self.elf();
let mut function_entries = Vec::new();
let mut functions_added: BTreeSet<u64> = BTreeSet::new();
// dynamic symbols
for sym in &elf.dynsyms {
if sym.is_function() && sym.st_value != 0 {
let name = elf.dynstrtab.get(sym.st_name).to_string();
function_entries.push(FunctionEntry::new(
sym.st_value + self.base_address,
Some(name)
));
functions_added.insert(sym.st_value);
}
}
// normal symbols
for sym in &elf.syms {
if sym.is_function() && sym.st_value != 0 {
let name = elf.strtab.get(sym.st_name).to_string();
function_entries.push(FunctionEntry::new(
sym.st_value + self.base_address,
Some(name))
);
functions_added.insert(sym.st_value);
}
}
if !functions_added.contains(&elf.header.e_entry) {
function_entries.push(FunctionEntry::new(
elf.header.e_entry + self.base_address,
None
));
}
for user_function_entry in &self.user_function_entries {
if functions_added.get(&(user_function_entry + self.base_address)).is_some() {
continue;
}
function_entries.push(FunctionEntry::new(
user_function_entry + self.base_address,
Some(format!("user_function_{:x}", user_function_entry))
));
}
Ok(function_entries)
}
fn program_entry(&self) -> u64 {
self.elf().header.e_entry
}
fn architecture(&self) -> Result<Architecture> {
let elf = self.elf();
if elf.header.e_machine == goblin::elf::header::EM_386 {
Ok(Architecture::X86)
}
else {
Err("Unsupported Arcthiecture".into())
}
}
}
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CTRL6 {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `CTLINK6`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CTLINK6R {
#[doc = "Use A6/B6 timers as two independent 16-bit timers (default). value."]
TWO_16BIT_TIMERS,
#[doc = "Link A6/B6 timers into a single 32-bit timer. value."]
_32BIT_TIMER,
}
impl CTLINK6R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
CTLINK6R::TWO_16BIT_TIMERS => false,
CTLINK6R::_32BIT_TIMER => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> CTLINK6R {
match value {
false => CTLINK6R::TWO_16BIT_TIMERS,
true => CTLINK6R::_32BIT_TIMER,
}
}
#[doc = "Checks if the value of the field is `TWO_16BIT_TIMERS`"]
#[inline]
pub fn is_two_16bit_timers(&self) -> bool {
*self == CTLINK6R::TWO_16BIT_TIMERS
}
#[doc = "Checks if the value of the field is `_32BIT_TIMER`"]
#[inline]
pub fn is_32bit_timer(&self) -> bool {
*self == CTLINK6R::_32BIT_TIMER
}
}
#[doc = "Possible values of the field `TMRB6POL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB6POLR {
#[doc = "The polarity of the TMRPINB6 pin is the same as the timer output. value."]
NORMAL,
#[doc = "The polarity of the TMRPINB6 pin is the inverse of the timer output. value."]
INVERTED,
}
impl TMRB6POLR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB6POLR::NORMAL => false,
TMRB6POLR::INVERTED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB6POLR {
match value {
false => TMRB6POLR::NORMAL,
true => TMRB6POLR::INVERTED,
}
}
#[doc = "Checks if the value of the field is `NORMAL`"]
#[inline]
pub fn is_normal(&self) -> bool {
*self == TMRB6POLR::NORMAL
}
#[doc = "Checks if the value of the field is `INVERTED`"]
#[inline]
pub fn is_inverted(&self) -> bool {
*self == TMRB6POLR::INVERTED
}
}
#[doc = "Possible values of the field `TMRB6CLR`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB6CLRR {
#[doc = "Allow counter/timer B6 to run value."]
RUN,
#[doc = "Holds counter/timer B6 at 0x0000. value."]
CLEAR,
}
impl TMRB6CLRR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB6CLRR::RUN => false,
TMRB6CLRR::CLEAR => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB6CLRR {
match value {
false => TMRB6CLRR::RUN,
true => TMRB6CLRR::CLEAR,
}
}
#[doc = "Checks if the value of the field is `RUN`"]
#[inline]
pub fn is_run(&self) -> bool {
*self == TMRB6CLRR::RUN
}
#[doc = "Checks if the value of the field is `CLEAR`"]
#[inline]
pub fn is_clear(&self) -> bool {
*self == TMRB6CLRR::CLEAR
}
}
#[doc = "Possible values of the field `TMRB6IE1`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB6IE1R {
#[doc = "Disable counter/timer B6 from generating an interrupt based on COMPR1. value."]
DIS,
#[doc = "Enable counter/timer B6 to generate an interrupt based on COMPR1. value."]
EN,
}
impl TMRB6IE1R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB6IE1R::DIS => false,
TMRB6IE1R::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB6IE1R {
match value {
false => TMRB6IE1R::DIS,
true => TMRB6IE1R::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRB6IE1R::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRB6IE1R::EN
}
}
#[doc = "Possible values of the field `TMRB6IE0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB6IE0R {
#[doc = "Disable counter/timer B6 from generating an interrupt based on COMPR0. value."]
DIS,
#[doc = "Enable counter/timer B6 to generate an interrupt based on COMPR0 value."]
EN,
}
impl TMRB6IE0R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB6IE0R::DIS => false,
TMRB6IE0R::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB6IE0R {
match value {
false => TMRB6IE0R::DIS,
true => TMRB6IE0R::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRB6IE0R::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRB6IE0R::EN
}
}
#[doc = "Possible values of the field `TMRB6FN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB6FNR {
#[doc = "Single count (output toggles and sticks). Count to CMPR0B6, stop. value."]
SINGLECOUNT,
#[doc = "Repeated count (periodic 1-clock-cycle-wide pulses). Count to CMPR0B6, restart. value."]
REPEATEDCOUNT,
#[doc = "Pulse once (aka one-shot). Count to CMPR0B6, assert, count to CMPR1B6, deassert, stop. value."]
PULSE_ONCE,
#[doc = "Pulse continously. Count to CMPR0B6, assert, count to CMPR1B6, deassert, restart. value."]
PULSE_CONT,
#[doc = "Single pattern. value."]
SINGLEPATTERN,
#[doc = "Repeated pattern. value."]
REPEATPATTERN,
#[doc = "Continuous run (aka Free Run). Count continuously. value."]
CONTINUOUS,
#[doc = "Alternate PWM value."]
ALTPWN,
}
impl TMRB6FNR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
TMRB6FNR::SINGLECOUNT => 0,
TMRB6FNR::REPEATEDCOUNT => 1,
TMRB6FNR::PULSE_ONCE => 2,
TMRB6FNR::PULSE_CONT => 3,
TMRB6FNR::SINGLEPATTERN => 4,
TMRB6FNR::REPEATPATTERN => 5,
TMRB6FNR::CONTINUOUS => 6,
TMRB6FNR::ALTPWN => 7,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> TMRB6FNR {
match value {
0 => TMRB6FNR::SINGLECOUNT,
1 => TMRB6FNR::REPEATEDCOUNT,
2 => TMRB6FNR::PULSE_ONCE,
3 => TMRB6FNR::PULSE_CONT,
4 => TMRB6FNR::SINGLEPATTERN,
5 => TMRB6FNR::REPEATPATTERN,
6 => TMRB6FNR::CONTINUOUS,
7 => TMRB6FNR::ALTPWN,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `SINGLECOUNT`"]
#[inline]
pub fn is_singlecount(&self) -> bool {
*self == TMRB6FNR::SINGLECOUNT
}
#[doc = "Checks if the value of the field is `REPEATEDCOUNT`"]
#[inline]
pub fn is_repeatedcount(&self) -> bool {
*self == TMRB6FNR::REPEATEDCOUNT
}
#[doc = "Checks if the value of the field is `PULSE_ONCE`"]
#[inline]
pub fn is_pulse_once(&self) -> bool {
*self == TMRB6FNR::PULSE_ONCE
}
#[doc = "Checks if the value of the field is `PULSE_CONT`"]
#[inline]
pub fn is_pulse_cont(&self) -> bool {
*self == TMRB6FNR::PULSE_CONT
}
#[doc = "Checks if the value of the field is `SINGLEPATTERN`"]
#[inline]
pub fn is_singlepattern(&self) -> bool {
*self == TMRB6FNR::SINGLEPATTERN
}
#[doc = "Checks if the value of the field is `REPEATPATTERN`"]
#[inline]
pub fn is_repeatpattern(&self) -> bool {
*self == TMRB6FNR::REPEATPATTERN
}
#[doc = "Checks if the value of the field is `CONTINUOUS`"]
#[inline]
pub fn is_continuous(&self) -> bool {
*self == TMRB6FNR::CONTINUOUS
}
#[doc = "Checks if the value of the field is `ALTPWN`"]
#[inline]
pub fn is_altpwn(&self) -> bool {
*self == TMRB6FNR::ALTPWN
}
}
#[doc = "Possible values of the field `TMRB6CLK`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB6CLKR {
#[doc = "Clock source is TMRPINB. value."]
TMRPIN,
#[doc = "Clock source is the HFRC / 4 value."]
HFRC_DIV4,
#[doc = "Clock source is HFRC / 16 value."]
HFRC_DIV16,
#[doc = "Clock source is HFRC / 256 value."]
HFRC_DIV256,
#[doc = "Clock source is HFRC / 1024 value."]
HFRC_DIV1024,
#[doc = "Clock source is HFRC / 4096 value."]
HFRC_DIV4K,
#[doc = "Clock source is the XT (uncalibrated). value."]
XT,
#[doc = "Clock source is XT / 2 value."]
XT_DIV2,
#[doc = "Clock source is XT / 16 value."]
XT_DIV16,
#[doc = "Clock source is XT / 128 value."]
XT_DIV128,
#[doc = "Clock source is LFRC / 2 value."]
LFRC_DIV2,
#[doc = "Clock source is LFRC / 32 value."]
LFRC_DIV32,
#[doc = "Clock source is LFRC / 1024 value."]
LFRC_DIV1K,
#[doc = "Clock source is LFRC value."]
LFRC,
#[doc = "Clock source is 100 Hz from the current RTC oscillator. value."]
RTC_100HZ,
#[doc = "Clock source is HCLK / 4 (note: this clock is only available when MCU is in active mode) value."]
HCLK_DIV4,
#[doc = "Clock source is XT / 4 value."]
XT_DIV4,
#[doc = "Clock source is XT / 8 value."]
XT_DIV8,
#[doc = "Clock source is XT / 32 value."]
XT_DIV32,
#[doc = "Clock source is CTIMERA6 OUT. value."]
CTMRA6,
#[doc = "Clock source is CTIMERA3 OUT. value."]
CTMRA3,
#[doc = "Clock source is CTIMERB3 OUT. value."]
CTMRB3,
#[doc = "Clock source is CTIMERA7 OUT. value."]
CTMRA7,
#[doc = "Clock source is CTIMERB7 OUT. value."]
CTMRB7,
#[doc = "Clock source is CTIMERB0 OUT. value."]
CTMRB0,
#[doc = "Clock source is CTIMERB1 OUT. value."]
CTMRB1,
#[doc = "Clock source is CTIMERB2 OUT. value."]
CTMRB2,
#[doc = "Clock source is CTIMERB4 OUT. value."]
CTMRB4,
#[doc = "Clock source is BLE buck converter TON pulses. value."]
BUCKBLE,
#[doc = "Clock source is Memory buck converter TON pulses. value."]
BUCKB,
#[doc = "Clock source is CPU buck converter TON pulses. value."]
BUCKA,
#[doc = r" Reserved"]
_Reserved(u8),
}
impl TMRB6CLKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
TMRB6CLKR::TMRPIN => 0,
TMRB6CLKR::HFRC_DIV4 => 1,
TMRB6CLKR::HFRC_DIV16 => 2,
TMRB6CLKR::HFRC_DIV256 => 3,
TMRB6CLKR::HFRC_DIV1024 => 4,
TMRB6CLKR::HFRC_DIV4K => 5,
TMRB6CLKR::XT => 6,
TMRB6CLKR::XT_DIV2 => 7,
TMRB6CLKR::XT_DIV16 => 8,
TMRB6CLKR::XT_DIV128 => 9,
TMRB6CLKR::LFRC_DIV2 => 10,
TMRB6CLKR::LFRC_DIV32 => 11,
TMRB6CLKR::LFRC_DIV1K => 12,
TMRB6CLKR::LFRC => 13,
TMRB6CLKR::RTC_100HZ => 14,
TMRB6CLKR::HCLK_DIV4 => 15,
TMRB6CLKR::XT_DIV4 => 16,
TMRB6CLKR::XT_DIV8 => 17,
TMRB6CLKR::XT_DIV32 => 18,
TMRB6CLKR::CTMRA6 => 20,
TMRB6CLKR::CTMRA3 => 21,
TMRB6CLKR::CTMRB3 => 22,
TMRB6CLKR::CTMRA7 => 23,
TMRB6CLKR::CTMRB7 => 24,
TMRB6CLKR::CTMRB0 => 25,
TMRB6CLKR::CTMRB1 => 26,
TMRB6CLKR::CTMRB2 => 27,
TMRB6CLKR::CTMRB4 => 28,
TMRB6CLKR::BUCKBLE => 29,
TMRB6CLKR::BUCKB => 30,
TMRB6CLKR::BUCKA => 31,
TMRB6CLKR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> TMRB6CLKR {
match value {
0 => TMRB6CLKR::TMRPIN,
1 => TMRB6CLKR::HFRC_DIV4,
2 => TMRB6CLKR::HFRC_DIV16,
3 => TMRB6CLKR::HFRC_DIV256,
4 => TMRB6CLKR::HFRC_DIV1024,
5 => TMRB6CLKR::HFRC_DIV4K,
6 => TMRB6CLKR::XT,
7 => TMRB6CLKR::XT_DIV2,
8 => TMRB6CLKR::XT_DIV16,
9 => TMRB6CLKR::XT_DIV128,
10 => TMRB6CLKR::LFRC_DIV2,
11 => TMRB6CLKR::LFRC_DIV32,
12 => TMRB6CLKR::LFRC_DIV1K,
13 => TMRB6CLKR::LFRC,
14 => TMRB6CLKR::RTC_100HZ,
15 => TMRB6CLKR::HCLK_DIV4,
16 => TMRB6CLKR::XT_DIV4,
17 => TMRB6CLKR::XT_DIV8,
18 => TMRB6CLKR::XT_DIV32,
20 => TMRB6CLKR::CTMRA6,
21 => TMRB6CLKR::CTMRA3,
22 => TMRB6CLKR::CTMRB3,
23 => TMRB6CLKR::CTMRA7,
24 => TMRB6CLKR::CTMRB7,
25 => TMRB6CLKR::CTMRB0,
26 => TMRB6CLKR::CTMRB1,
27 => TMRB6CLKR::CTMRB2,
28 => TMRB6CLKR::CTMRB4,
29 => TMRB6CLKR::BUCKBLE,
30 => TMRB6CLKR::BUCKB,
31 => TMRB6CLKR::BUCKA,
i => TMRB6CLKR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `TMRPIN`"]
#[inline]
pub fn is_tmrpin(&self) -> bool {
*self == TMRB6CLKR::TMRPIN
}
#[doc = "Checks if the value of the field is `HFRC_DIV4`"]
#[inline]
pub fn is_hfrc_div4(&self) -> bool {
*self == TMRB6CLKR::HFRC_DIV4
}
#[doc = "Checks if the value of the field is `HFRC_DIV16`"]
#[inline]
pub fn is_hfrc_div16(&self) -> bool {
*self == TMRB6CLKR::HFRC_DIV16
}
#[doc = "Checks if the value of the field is `HFRC_DIV256`"]
#[inline]
pub fn is_hfrc_div256(&self) -> bool {
*self == TMRB6CLKR::HFRC_DIV256
}
#[doc = "Checks if the value of the field is `HFRC_DIV1024`"]
#[inline]
pub fn is_hfrc_div1024(&self) -> bool {
*self == TMRB6CLKR::HFRC_DIV1024
}
#[doc = "Checks if the value of the field is `HFRC_DIV4K`"]
#[inline]
pub fn is_hfrc_div4k(&self) -> bool {
*self == TMRB6CLKR::HFRC_DIV4K
}
#[doc = "Checks if the value of the field is `XT`"]
#[inline]
pub fn is_xt(&self) -> bool {
*self == TMRB6CLKR::XT
}
#[doc = "Checks if the value of the field is `XT_DIV2`"]
#[inline]
pub fn is_xt_div2(&self) -> bool {
*self == TMRB6CLKR::XT_DIV2
}
#[doc = "Checks if the value of the field is `XT_DIV16`"]
#[inline]
pub fn is_xt_div16(&self) -> bool {
*self == TMRB6CLKR::XT_DIV16
}
#[doc = "Checks if the value of the field is `XT_DIV128`"]
#[inline]
pub fn is_xt_div128(&self) -> bool {
*self == TMRB6CLKR::XT_DIV128
}
#[doc = "Checks if the value of the field is `LFRC_DIV2`"]
#[inline]
pub fn is_lfrc_div2(&self) -> bool {
*self == TMRB6CLKR::LFRC_DIV2
}
#[doc = "Checks if the value of the field is `LFRC_DIV32`"]
#[inline]
pub fn is_lfrc_div32(&self) -> bool {
*self == TMRB6CLKR::LFRC_DIV32
}
#[doc = "Checks if the value of the field is `LFRC_DIV1K`"]
#[inline]
pub fn is_lfrc_div1k(&self) -> bool {
*self == TMRB6CLKR::LFRC_DIV1K
}
#[doc = "Checks if the value of the field is `LFRC`"]
#[inline]
pub fn is_lfrc(&self) -> bool {
*self == TMRB6CLKR::LFRC
}
#[doc = "Checks if the value of the field is `RTC_100HZ`"]
#[inline]
pub fn is_rtc_100hz(&self) -> bool {
*self == TMRB6CLKR::RTC_100HZ
}
#[doc = "Checks if the value of the field is `HCLK_DIV4`"]
#[inline]
pub fn is_hclk_div4(&self) -> bool {
*self == TMRB6CLKR::HCLK_DIV4
}
#[doc = "Checks if the value of the field is `XT_DIV4`"]
#[inline]
pub fn is_xt_div4(&self) -> bool {
*self == TMRB6CLKR::XT_DIV4
}
#[doc = "Checks if the value of the field is `XT_DIV8`"]
#[inline]
pub fn is_xt_div8(&self) -> bool {
*self == TMRB6CLKR::XT_DIV8
}
#[doc = "Checks if the value of the field is `XT_DIV32`"]
#[inline]
pub fn is_xt_div32(&self) -> bool {
*self == TMRB6CLKR::XT_DIV32
}
#[doc = "Checks if the value of the field is `CTMRA6`"]
#[inline]
pub fn is_ctmra6(&self) -> bool {
*self == TMRB6CLKR::CTMRA6
}
#[doc = "Checks if the value of the field is `CTMRA3`"]
#[inline]
pub fn is_ctmra3(&self) -> bool {
*self == TMRB6CLKR::CTMRA3
}
#[doc = "Checks if the value of the field is `CTMRB3`"]
#[inline]
pub fn is_ctmrb3(&self) -> bool {
*self == TMRB6CLKR::CTMRB3
}
#[doc = "Checks if the value of the field is `CTMRA7`"]
#[inline]
pub fn is_ctmra7(&self) -> bool {
*self == TMRB6CLKR::CTMRA7
}
#[doc = "Checks if the value of the field is `CTMRB7`"]
#[inline]
pub fn is_ctmrb7(&self) -> bool {
*self == TMRB6CLKR::CTMRB7
}
#[doc = "Checks if the value of the field is `CTMRB0`"]
#[inline]
pub fn is_ctmrb0(&self) -> bool {
*self == TMRB6CLKR::CTMRB0
}
#[doc = "Checks if the value of the field is `CTMRB1`"]
#[inline]
pub fn is_ctmrb1(&self) -> bool {
*self == TMRB6CLKR::CTMRB1
}
#[doc = "Checks if the value of the field is `CTMRB2`"]
#[inline]
pub fn is_ctmrb2(&self) -> bool {
*self == TMRB6CLKR::CTMRB2
}
#[doc = "Checks if the value of the field is `CTMRB4`"]
#[inline]
pub fn is_ctmrb4(&self) -> bool {
*self == TMRB6CLKR::CTMRB4
}
#[doc = "Checks if the value of the field is `BUCKBLE`"]
#[inline]
pub fn is_buckble(&self) -> bool {
*self == TMRB6CLKR::BUCKBLE
}
#[doc = "Checks if the value of the field is `BUCKB`"]
#[inline]
pub fn is_buckb(&self) -> bool {
*self == TMRB6CLKR::BUCKB
}
#[doc = "Checks if the value of the field is `BUCKA`"]
#[inline]
pub fn is_bucka(&self) -> bool {
*self == TMRB6CLKR::BUCKA
}
}
#[doc = "Possible values of the field `TMRB6EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB6ENR {
#[doc = "Counter/Timer B6 Disable. value."]
DIS,
#[doc = "Counter/Timer B6 Enable. value."]
EN,
}
impl TMRB6ENR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB6ENR::DIS => false,
TMRB6ENR::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB6ENR {
match value {
false => TMRB6ENR::DIS,
true => TMRB6ENR::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRB6ENR::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRB6ENR::EN
}
}
#[doc = "Possible values of the field `TMRA6POL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA6POLR {
#[doc = "The polarity of the TMRPINA6 pin is the same as the timer output. value."]
NORMAL,
#[doc = "The polarity of the TMRPINA6 pin is the inverse of the timer output. value."]
INVERTED,
}
impl TMRA6POLR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA6POLR::NORMAL => false,
TMRA6POLR::INVERTED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA6POLR {
match value {
false => TMRA6POLR::NORMAL,
true => TMRA6POLR::INVERTED,
}
}
#[doc = "Checks if the value of the field is `NORMAL`"]
#[inline]
pub fn is_normal(&self) -> bool {
*self == TMRA6POLR::NORMAL
}
#[doc = "Checks if the value of the field is `INVERTED`"]
#[inline]
pub fn is_inverted(&self) -> bool {
*self == TMRA6POLR::INVERTED
}
}
#[doc = "Possible values of the field `TMRA6CLR`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA6CLRR {
#[doc = "Allow counter/timer A6 to run value."]
RUN,
#[doc = "Holds counter/timer A6 at 0x0000. value."]
CLEAR,
}
impl TMRA6CLRR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA6CLRR::RUN => false,
TMRA6CLRR::CLEAR => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA6CLRR {
match value {
false => TMRA6CLRR::RUN,
true => TMRA6CLRR::CLEAR,
}
}
#[doc = "Checks if the value of the field is `RUN`"]
#[inline]
pub fn is_run(&self) -> bool {
*self == TMRA6CLRR::RUN
}
#[doc = "Checks if the value of the field is `CLEAR`"]
#[inline]
pub fn is_clear(&self) -> bool {
*self == TMRA6CLRR::CLEAR
}
}
#[doc = "Possible values of the field `TMRA6IE1`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA6IE1R {
#[doc = "Disable counter/timer A6 from generating an interrupt based on COMPR1. value."]
DIS,
#[doc = "Enable counter/timer A6 to generate an interrupt based on COMPR1. value."]
EN,
}
impl TMRA6IE1R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA6IE1R::DIS => false,
TMRA6IE1R::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA6IE1R {
match value {
false => TMRA6IE1R::DIS,
true => TMRA6IE1R::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRA6IE1R::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRA6IE1R::EN
}
}
#[doc = "Possible values of the field `TMRA6IE0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA6IE0R {
#[doc = "Disable counter/timer A6 from generating an interrupt based on COMPR0. value."]
DIS,
#[doc = "Enable counter/timer A6 to generate an interrupt based on COMPR0. value."]
EN,
}
impl TMRA6IE0R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA6IE0R::DIS => false,
TMRA6IE0R::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA6IE0R {
match value {
false => TMRA6IE0R::DIS,
true => TMRA6IE0R::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRA6IE0R::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRA6IE0R::EN
}
}
#[doc = "Possible values of the field `TMRA6FN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA6FNR {
#[doc = "Single count (output toggles and sticks). Count to CMPR0A6, stop. value."]
SINGLECOUNT,
#[doc = "Repeated count (periodic 1-clock-cycle-wide pulses). Count to CMPR0A6, restart. value."]
REPEATEDCOUNT,
#[doc = "Pulse once (aka one-shot). Count to CMPR0A6, assert, count to CMPR1A6, deassert, stop. value."]
PULSE_ONCE,
#[doc = "Pulse continously. Count to CMPR0A6, assert, count to CMPR1A6, deassert, restart. value."]
PULSE_CONT,
#[doc = "Single pattern. value."]
SINGLEPATTERN,
#[doc = "Repeated pattern. value."]
REPEATPATTERN,
#[doc = "Continuous run (aka Free Run). Count continuously. value."]
CONTINUOUS,
#[doc = "Alternate PWM value."]
ALTPWN,
}
impl TMRA6FNR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
TMRA6FNR::SINGLECOUNT => 0,
TMRA6FNR::REPEATEDCOUNT => 1,
TMRA6FNR::PULSE_ONCE => 2,
TMRA6FNR::PULSE_CONT => 3,
TMRA6FNR::SINGLEPATTERN => 4,
TMRA6FNR::REPEATPATTERN => 5,
TMRA6FNR::CONTINUOUS => 6,
TMRA6FNR::ALTPWN => 7,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> TMRA6FNR {
match value {
0 => TMRA6FNR::SINGLECOUNT,
1 => TMRA6FNR::REPEATEDCOUNT,
2 => TMRA6FNR::PULSE_ONCE,
3 => TMRA6FNR::PULSE_CONT,
4 => TMRA6FNR::SINGLEPATTERN,
5 => TMRA6FNR::REPEATPATTERN,
6 => TMRA6FNR::CONTINUOUS,
7 => TMRA6FNR::ALTPWN,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `SINGLECOUNT`"]
#[inline]
pub fn is_singlecount(&self) -> bool {
*self == TMRA6FNR::SINGLECOUNT
}
#[doc = "Checks if the value of the field is `REPEATEDCOUNT`"]
#[inline]
pub fn is_repeatedcount(&self) -> bool {
*self == TMRA6FNR::REPEATEDCOUNT
}
#[doc = "Checks if the value of the field is `PULSE_ONCE`"]
#[inline]
pub fn is_pulse_once(&self) -> bool {
*self == TMRA6FNR::PULSE_ONCE
}
#[doc = "Checks if the value of the field is `PULSE_CONT`"]
#[inline]
pub fn is_pulse_cont(&self) -> bool {
*self == TMRA6FNR::PULSE_CONT
}
#[doc = "Checks if the value of the field is `SINGLEPATTERN`"]
#[inline]
pub fn is_singlepattern(&self) -> bool {
*self == TMRA6FNR::SINGLEPATTERN
}
#[doc = "Checks if the value of the field is `REPEATPATTERN`"]
#[inline]
pub fn is_repeatpattern(&self) -> bool {
*self == TMRA6FNR::REPEATPATTERN
}
#[doc = "Checks if the value of the field is `CONTINUOUS`"]
#[inline]
pub fn is_continuous(&self) -> bool {
*self == TMRA6FNR::CONTINUOUS
}
#[doc = "Checks if the value of the field is `ALTPWN`"]
#[inline]
pub fn is_altpwn(&self) -> bool {
*self == TMRA6FNR::ALTPWN
}
}
#[doc = "Possible values of the field `TMRA6CLK`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA6CLKR {
#[doc = "Clock source is TMRPINA. value."]
TMRPIN,
#[doc = "Clock source is the HFRC / 4 value."]
HFRC_DIV4,
#[doc = "Clock source is HFRC / 16 value."]
HFRC_DIV16,
#[doc = "Clock source is HFRC / 256 value."]
HFRC_DIV256,
#[doc = "Clock source is HFRC / 1024 value."]
HFRC_DIV1024,
#[doc = "Clock source is HFRC / 4096 value."]
HFRC_DIV4K,
#[doc = "Clock source is the XT (uncalibrated). value."]
XT,
#[doc = "Clock source is XT / 2 value."]
XT_DIV2,
#[doc = "Clock source is XT / 16 value."]
XT_DIV16,
#[doc = "Clock source is XT / 128 value."]
XT_DIV128,
#[doc = "Clock source is LFRC / 2 value."]
LFRC_DIV2,
#[doc = "Clock source is LFRC / 32 value."]
LFRC_DIV32,
#[doc = "Clock source is LFRC / 1024 value."]
LFRC_DIV1K,
#[doc = "Clock source is LFRC value."]
LFRC,
#[doc = "Clock source is 100 Hz from the current RTC oscillator. value."]
RTC_100HZ,
#[doc = "Clock source is HCLK / 4 (note: this clock is only available when MCU is in active mode) value."]
HCLK_DIV4,
#[doc = "Clock source is XT / 4 value."]
XT_DIV4,
#[doc = "Clock source is XT / 8 value."]
XT_DIV8,
#[doc = "Clock source is XT / 32 value."]
XT_DIV32,
#[doc = "Clock source is CTIMERB6 OUT. value."]
CTMRB6,
#[doc = "Clock source is CTIMERA3 OUT. value."]
CTMRA3,
#[doc = "Clock source is CTIMERB3 OUT. value."]
CTMRB3,
#[doc = "Clock source is CTIMERA7 OUT. value."]
CTMRA7,
#[doc = "Clock source is CTIMERB7 OUT. value."]
CTMRB7,
#[doc = "Clock source is CTIMERB0 OUT. value."]
CTMRB0,
#[doc = "Clock source is CTIMERB1 OUT. value."]
CTMRB1,
#[doc = "Clock source is CTIMERB2 OUT. value."]
CTMRB2,
#[doc = "Clock source is CTIMERB4 OUT. value."]
CTMRB4,
#[doc = "Clock source is BLE buck converter TON pulses. value."]
BUCKBLE,
#[doc = "Clock source is Memory buck converter TON pulses. value."]
BUCKB,
#[doc = "Clock source is CPU buck converter TON pulses. value."]
BUCKA,
#[doc = r" Reserved"]
_Reserved(u8),
}
impl TMRA6CLKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
TMRA6CLKR::TMRPIN => 0,
TMRA6CLKR::HFRC_DIV4 => 1,
TMRA6CLKR::HFRC_DIV16 => 2,
TMRA6CLKR::HFRC_DIV256 => 3,
TMRA6CLKR::HFRC_DIV1024 => 4,
TMRA6CLKR::HFRC_DIV4K => 5,
TMRA6CLKR::XT => 6,
TMRA6CLKR::XT_DIV2 => 7,
TMRA6CLKR::XT_DIV16 => 8,
TMRA6CLKR::XT_DIV128 => 9,
TMRA6CLKR::LFRC_DIV2 => 10,
TMRA6CLKR::LFRC_DIV32 => 11,
TMRA6CLKR::LFRC_DIV1K => 12,
TMRA6CLKR::LFRC => 13,
TMRA6CLKR::RTC_100HZ => 14,
TMRA6CLKR::HCLK_DIV4 => 15,
TMRA6CLKR::XT_DIV4 => 16,
TMRA6CLKR::XT_DIV8 => 17,
TMRA6CLKR::XT_DIV32 => 18,
TMRA6CLKR::CTMRB6 => 20,
TMRA6CLKR::CTMRA3 => 21,
TMRA6CLKR::CTMRB3 => 22,
TMRA6CLKR::CTMRA7 => 23,
TMRA6CLKR::CTMRB7 => 24,
TMRA6CLKR::CTMRB0 => 25,
TMRA6CLKR::CTMRB1 => 26,
TMRA6CLKR::CTMRB2 => 27,
TMRA6CLKR::CTMRB4 => 28,
TMRA6CLKR::BUCKBLE => 29,
TMRA6CLKR::BUCKB => 30,
TMRA6CLKR::BUCKA => 31,
TMRA6CLKR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> TMRA6CLKR {
match value {
0 => TMRA6CLKR::TMRPIN,
1 => TMRA6CLKR::HFRC_DIV4,
2 => TMRA6CLKR::HFRC_DIV16,
3 => TMRA6CLKR::HFRC_DIV256,
4 => TMRA6CLKR::HFRC_DIV1024,
5 => TMRA6CLKR::HFRC_DIV4K,
6 => TMRA6CLKR::XT,
7 => TMRA6CLKR::XT_DIV2,
8 => TMRA6CLKR::XT_DIV16,
9 => TMRA6CLKR::XT_DIV128,
10 => TMRA6CLKR::LFRC_DIV2,
11 => TMRA6CLKR::LFRC_DIV32,
12 => TMRA6CLKR::LFRC_DIV1K,
13 => TMRA6CLKR::LFRC,
14 => TMRA6CLKR::RTC_100HZ,
15 => TMRA6CLKR::HCLK_DIV4,
16 => TMRA6CLKR::XT_DIV4,
17 => TMRA6CLKR::XT_DIV8,
18 => TMRA6CLKR::XT_DIV32,
20 => TMRA6CLKR::CTMRB6,
21 => TMRA6CLKR::CTMRA3,
22 => TMRA6CLKR::CTMRB3,
23 => TMRA6CLKR::CTMRA7,
24 => TMRA6CLKR::CTMRB7,
25 => TMRA6CLKR::CTMRB0,
26 => TMRA6CLKR::CTMRB1,
27 => TMRA6CLKR::CTMRB2,
28 => TMRA6CLKR::CTMRB4,
29 => TMRA6CLKR::BUCKBLE,
30 => TMRA6CLKR::BUCKB,
31 => TMRA6CLKR::BUCKA,
i => TMRA6CLKR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `TMRPIN`"]
#[inline]
pub fn is_tmrpin(&self) -> bool {
*self == TMRA6CLKR::TMRPIN
}
#[doc = "Checks if the value of the field is `HFRC_DIV4`"]
#[inline]
pub fn is_hfrc_div4(&self) -> bool {
*self == TMRA6CLKR::HFRC_DIV4
}
#[doc = "Checks if the value of the field is `HFRC_DIV16`"]
#[inline]
pub fn is_hfrc_div16(&self) -> bool {
*self == TMRA6CLKR::HFRC_DIV16
}
#[doc = "Checks if the value of the field is `HFRC_DIV256`"]
#[inline]
pub fn is_hfrc_div256(&self) -> bool {
*self == TMRA6CLKR::HFRC_DIV256
}
#[doc = "Checks if the value of the field is `HFRC_DIV1024`"]
#[inline]
pub fn is_hfrc_div1024(&self) -> bool {
*self == TMRA6CLKR::HFRC_DIV1024
}
#[doc = "Checks if the value of the field is `HFRC_DIV4K`"]
#[inline]
pub fn is_hfrc_div4k(&self) -> bool {
*self == TMRA6CLKR::HFRC_DIV4K
}
#[doc = "Checks if the value of the field is `XT`"]
#[inline]
pub fn is_xt(&self) -> bool {
*self == TMRA6CLKR::XT
}
#[doc = "Checks if the value of the field is `XT_DIV2`"]
#[inline]
pub fn is_xt_div2(&self) -> bool {
*self == TMRA6CLKR::XT_DIV2
}
#[doc = "Checks if the value of the field is `XT_DIV16`"]
#[inline]
pub fn is_xt_div16(&self) -> bool {
*self == TMRA6CLKR::XT_DIV16
}
#[doc = "Checks if the value of the field is `XT_DIV128`"]
#[inline]
pub fn is_xt_div128(&self) -> bool {
*self == TMRA6CLKR::XT_DIV128
}
#[doc = "Checks if the value of the field is `LFRC_DIV2`"]
#[inline]
pub fn is_lfrc_div2(&self) -> bool {
*self == TMRA6CLKR::LFRC_DIV2
}
#[doc = "Checks if the value of the field is `LFRC_DIV32`"]
#[inline]
pub fn is_lfrc_div32(&self) -> bool {
*self == TMRA6CLKR::LFRC_DIV32
}
#[doc = "Checks if the value of the field is `LFRC_DIV1K`"]
#[inline]
pub fn is_lfrc_div1k(&self) -> bool {
*self == TMRA6CLKR::LFRC_DIV1K
}
#[doc = "Checks if the value of the field is `LFRC`"]
#[inline]
pub fn is_lfrc(&self) -> bool {
*self == TMRA6CLKR::LFRC
}
#[doc = "Checks if the value of the field is `RTC_100HZ`"]
#[inline]
pub fn is_rtc_100hz(&self) -> bool {
*self == TMRA6CLKR::RTC_100HZ
}
#[doc = "Checks if the value of the field is `HCLK_DIV4`"]
#[inline]
pub fn is_hclk_div4(&self) -> bool {
*self == TMRA6CLKR::HCLK_DIV4
}
#[doc = "Checks if the value of the field is `XT_DIV4`"]
#[inline]
pub fn is_xt_div4(&self) -> bool {
*self == TMRA6CLKR::XT_DIV4
}
#[doc = "Checks if the value of the field is `XT_DIV8`"]
#[inline]
pub fn is_xt_div8(&self) -> bool {
*self == TMRA6CLKR::XT_DIV8
}
#[doc = "Checks if the value of the field is `XT_DIV32`"]
#[inline]
pub fn is_xt_div32(&self) -> bool {
*self == TMRA6CLKR::XT_DIV32
}
#[doc = "Checks if the value of the field is `CTMRB6`"]
#[inline]
pub fn is_ctmrb6(&self) -> bool {
*self == TMRA6CLKR::CTMRB6
}
#[doc = "Checks if the value of the field is `CTMRA3`"]
#[inline]
pub fn is_ctmra3(&self) -> bool {
*self == TMRA6CLKR::CTMRA3
}
#[doc = "Checks if the value of the field is `CTMRB3`"]
#[inline]
pub fn is_ctmrb3(&self) -> bool {
*self == TMRA6CLKR::CTMRB3
}
#[doc = "Checks if the value of the field is `CTMRA7`"]
#[inline]
pub fn is_ctmra7(&self) -> bool {
*self == TMRA6CLKR::CTMRA7
}
#[doc = "Checks if the value of the field is `CTMRB7`"]
#[inline]
pub fn is_ctmrb7(&self) -> bool {
*self == TMRA6CLKR::CTMRB7
}
#[doc = "Checks if the value of the field is `CTMRB0`"]
#[inline]
pub fn is_ctmrb0(&self) -> bool {
*self == TMRA6CLKR::CTMRB0
}
#[doc = "Checks if the value of the field is `CTMRB1`"]
#[inline]
pub fn is_ctmrb1(&self) -> bool {
*self == TMRA6CLKR::CTMRB1
}
#[doc = "Checks if the value of the field is `CTMRB2`"]
#[inline]
pub fn is_ctmrb2(&self) -> bool {
*self == TMRA6CLKR::CTMRB2
}
#[doc = "Checks if the value of the field is `CTMRB4`"]
#[inline]
pub fn is_ctmrb4(&self) -> bool {
*self == TMRA6CLKR::CTMRB4
}
#[doc = "Checks if the value of the field is `BUCKBLE`"]
#[inline]
pub fn is_buckble(&self) -> bool {
*self == TMRA6CLKR::BUCKBLE
}
#[doc = "Checks if the value of the field is `BUCKB`"]
#[inline]
pub fn is_buckb(&self) -> bool {
*self == TMRA6CLKR::BUCKB
}
#[doc = "Checks if the value of the field is `BUCKA`"]
#[inline]
pub fn is_bucka(&self) -> bool {
*self == TMRA6CLKR::BUCKA
}
}
#[doc = "Possible values of the field `TMRA6EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA6ENR {
#[doc = "Counter/Timer A6 Disable. value."]
DIS,
#[doc = "Counter/Timer A6 Enable. value."]
EN,
}
impl TMRA6ENR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA6ENR::DIS => false,
TMRA6ENR::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA6ENR {
match value {
false => TMRA6ENR::DIS,
true => TMRA6ENR::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRA6ENR::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRA6ENR::EN
}
}
#[doc = "Values that can be written to the field `CTLINK6`"]
pub enum CTLINK6W {
#[doc = "Use A6/B6 timers as two independent 16-bit timers (default). value."]
TWO_16BIT_TIMERS,
#[doc = "Link A6/B6 timers into a single 32-bit timer. value."]
_32BIT_TIMER,
}
impl CTLINK6W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
CTLINK6W::TWO_16BIT_TIMERS => false,
CTLINK6W::_32BIT_TIMER => true,
}
}
}
#[doc = r" Proxy"]
pub struct _CTLINK6W<'a> {
w: &'a mut W,
}
impl<'a> _CTLINK6W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: CTLINK6W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Use A6/B6 timers as two independent 16-bit timers (default). value."]
#[inline]
pub fn two_16bit_timers(self) -> &'a mut W {
self.variant(CTLINK6W::TWO_16BIT_TIMERS)
}
#[doc = "Link A6/B6 timers into a single 32-bit timer. value."]
#[inline]
pub fn _32bit_timer(self) -> &'a mut W {
self.variant(CTLINK6W::_32BIT_TIMER)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 31;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB6POL`"]
pub enum TMRB6POLW {
#[doc = "The polarity of the TMRPINB6 pin is the same as the timer output. value."]
NORMAL,
#[doc = "The polarity of the TMRPINB6 pin is the inverse of the timer output. value."]
INVERTED,
}
impl TMRB6POLW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB6POLW::NORMAL => false,
TMRB6POLW::INVERTED => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB6POLW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB6POLW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB6POLW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "The polarity of the TMRPINB6 pin is the same as the timer output. value."]
#[inline]
pub fn normal(self) -> &'a mut W {
self.variant(TMRB6POLW::NORMAL)
}
#[doc = "The polarity of the TMRPINB6 pin is the inverse of the timer output. value."]
#[inline]
pub fn inverted(self) -> &'a mut W {
self.variant(TMRB6POLW::INVERTED)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 28;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB6CLR`"]
pub enum TMRB6CLRW {
#[doc = "Allow counter/timer B6 to run value."]
RUN,
#[doc = "Holds counter/timer B6 at 0x0000. value."]
CLEAR,
}
impl TMRB6CLRW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB6CLRW::RUN => false,
TMRB6CLRW::CLEAR => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB6CLRW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB6CLRW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB6CLRW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Allow counter/timer B6 to run value."]
#[inline]
pub fn run(self) -> &'a mut W {
self.variant(TMRB6CLRW::RUN)
}
#[doc = "Holds counter/timer B6 at 0x0000. value."]
#[inline]
pub fn clear(self) -> &'a mut W {
self.variant(TMRB6CLRW::CLEAR)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 27;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB6IE1`"]
pub enum TMRB6IE1W {
#[doc = "Disable counter/timer B6 from generating an interrupt based on COMPR1. value."]
DIS,
#[doc = "Enable counter/timer B6 to generate an interrupt based on COMPR1. value."]
EN,
}
impl TMRB6IE1W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB6IE1W::DIS => false,
TMRB6IE1W::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB6IE1W<'a> {
w: &'a mut W,
}
impl<'a> _TMRB6IE1W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB6IE1W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable counter/timer B6 from generating an interrupt based on COMPR1. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRB6IE1W::DIS)
}
#[doc = "Enable counter/timer B6 to generate an interrupt based on COMPR1. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRB6IE1W::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 26;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB6IE0`"]
pub enum TMRB6IE0W {
#[doc = "Disable counter/timer B6 from generating an interrupt based on COMPR0. value."]
DIS,
#[doc = "Enable counter/timer B6 to generate an interrupt based on COMPR0 value."]
EN,
}
impl TMRB6IE0W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB6IE0W::DIS => false,
TMRB6IE0W::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB6IE0W<'a> {
w: &'a mut W,
}
impl<'a> _TMRB6IE0W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB6IE0W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable counter/timer B6 from generating an interrupt based on COMPR0. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRB6IE0W::DIS)
}
#[doc = "Enable counter/timer B6 to generate an interrupt based on COMPR0 value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRB6IE0W::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 25;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB6FN`"]
pub enum TMRB6FNW {
#[doc = "Single count (output toggles and sticks). Count to CMPR0B6, stop. value."]
SINGLECOUNT,
#[doc = "Repeated count (periodic 1-clock-cycle-wide pulses). Count to CMPR0B6, restart. value."]
REPEATEDCOUNT,
#[doc = "Pulse once (aka one-shot). Count to CMPR0B6, assert, count to CMPR1B6, deassert, stop. value."]
PULSE_ONCE,
#[doc = "Pulse continously. Count to CMPR0B6, assert, count to CMPR1B6, deassert, restart. value."]
PULSE_CONT,
#[doc = "Single pattern. value."]
SINGLEPATTERN,
#[doc = "Repeated pattern. value."]
REPEATPATTERN,
#[doc = "Continuous run (aka Free Run). Count continuously. value."]
CONTINUOUS,
#[doc = "Alternate PWM value."]
ALTPWN,
}
impl TMRB6FNW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
TMRB6FNW::SINGLECOUNT => 0,
TMRB6FNW::REPEATEDCOUNT => 1,
TMRB6FNW::PULSE_ONCE => 2,
TMRB6FNW::PULSE_CONT => 3,
TMRB6FNW::SINGLEPATTERN => 4,
TMRB6FNW::REPEATPATTERN => 5,
TMRB6FNW::CONTINUOUS => 6,
TMRB6FNW::ALTPWN => 7,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB6FNW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB6FNW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB6FNW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Single count (output toggles and sticks). Count to CMPR0B6, stop. value."]
#[inline]
pub fn singlecount(self) -> &'a mut W {
self.variant(TMRB6FNW::SINGLECOUNT)
}
#[doc = "Repeated count (periodic 1-clock-cycle-wide pulses). Count to CMPR0B6, restart. value."]
#[inline]
pub fn repeatedcount(self) -> &'a mut W {
self.variant(TMRB6FNW::REPEATEDCOUNT)
}
#[doc = "Pulse once (aka one-shot). Count to CMPR0B6, assert, count to CMPR1B6, deassert, stop. value."]
#[inline]
pub fn pulse_once(self) -> &'a mut W {
self.variant(TMRB6FNW::PULSE_ONCE)
}
#[doc = "Pulse continously. Count to CMPR0B6, assert, count to CMPR1B6, deassert, restart. value."]
#[inline]
pub fn pulse_cont(self) -> &'a mut W {
self.variant(TMRB6FNW::PULSE_CONT)
}
#[doc = "Single pattern. value."]
#[inline]
pub fn singlepattern(self) -> &'a mut W {
self.variant(TMRB6FNW::SINGLEPATTERN)
}
#[doc = "Repeated pattern. value."]
#[inline]
pub fn repeatpattern(self) -> &'a mut W {
self.variant(TMRB6FNW::REPEATPATTERN)
}
#[doc = "Continuous run (aka Free Run). Count continuously. value."]
#[inline]
pub fn continuous(self) -> &'a mut W {
self.variant(TMRB6FNW::CONTINUOUS)
}
#[doc = "Alternate PWM value."]
#[inline]
pub fn altpwn(self) -> &'a mut W {
self.variant(TMRB6FNW::ALTPWN)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 7;
const OFFSET: u8 = 22;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB6CLK`"]
pub enum TMRB6CLKW {
#[doc = "Clock source is TMRPINB. value."]
TMRPIN,
#[doc = "Clock source is the HFRC / 4 value."]
HFRC_DIV4,
#[doc = "Clock source is HFRC / 16 value."]
HFRC_DIV16,
#[doc = "Clock source is HFRC / 256 value."]
HFRC_DIV256,
#[doc = "Clock source is HFRC / 1024 value."]
HFRC_DIV1024,
#[doc = "Clock source is HFRC / 4096 value."]
HFRC_DIV4K,
#[doc = "Clock source is the XT (uncalibrated). value."]
XT,
#[doc = "Clock source is XT / 2 value."]
XT_DIV2,
#[doc = "Clock source is XT / 16 value."]
XT_DIV16,
#[doc = "Clock source is XT / 128 value."]
XT_DIV128,
#[doc = "Clock source is LFRC / 2 value."]
LFRC_DIV2,
#[doc = "Clock source is LFRC / 32 value."]
LFRC_DIV32,
#[doc = "Clock source is LFRC / 1024 value."]
LFRC_DIV1K,
#[doc = "Clock source is LFRC value."]
LFRC,
#[doc = "Clock source is 100 Hz from the current RTC oscillator. value."]
RTC_100HZ,
#[doc = "Clock source is HCLK / 4 (note: this clock is only available when MCU is in active mode) value."]
HCLK_DIV4,
#[doc = "Clock source is XT / 4 value."]
XT_DIV4,
#[doc = "Clock source is XT / 8 value."]
XT_DIV8,
#[doc = "Clock source is XT / 32 value."]
XT_DIV32,
#[doc = "Clock source is CTIMERA6 OUT. value."]
CTMRA6,
#[doc = "Clock source is CTIMERA3 OUT. value."]
CTMRA3,
#[doc = "Clock source is CTIMERB3 OUT. value."]
CTMRB3,
#[doc = "Clock source is CTIMERA7 OUT. value."]
CTMRA7,
#[doc = "Clock source is CTIMERB7 OUT. value."]
CTMRB7,
#[doc = "Clock source is CTIMERB0 OUT. value."]
CTMRB0,
#[doc = "Clock source is CTIMERB1 OUT. value."]
CTMRB1,
#[doc = "Clock source is CTIMERB2 OUT. value."]
CTMRB2,
#[doc = "Clock source is CTIMERB4 OUT. value."]
CTMRB4,
#[doc = "Clock source is BLE buck converter TON pulses. value."]
BUCKBLE,
#[doc = "Clock source is Memory buck converter TON pulses. value."]
BUCKB,
#[doc = "Clock source is CPU buck converter TON pulses. value."]
BUCKA,
}
impl TMRB6CLKW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
TMRB6CLKW::TMRPIN => 0,
TMRB6CLKW::HFRC_DIV4 => 1,
TMRB6CLKW::HFRC_DIV16 => 2,
TMRB6CLKW::HFRC_DIV256 => 3,
TMRB6CLKW::HFRC_DIV1024 => 4,
TMRB6CLKW::HFRC_DIV4K => 5,
TMRB6CLKW::XT => 6,
TMRB6CLKW::XT_DIV2 => 7,
TMRB6CLKW::XT_DIV16 => 8,
TMRB6CLKW::XT_DIV128 => 9,
TMRB6CLKW::LFRC_DIV2 => 10,
TMRB6CLKW::LFRC_DIV32 => 11,
TMRB6CLKW::LFRC_DIV1K => 12,
TMRB6CLKW::LFRC => 13,
TMRB6CLKW::RTC_100HZ => 14,
TMRB6CLKW::HCLK_DIV4 => 15,
TMRB6CLKW::XT_DIV4 => 16,
TMRB6CLKW::XT_DIV8 => 17,
TMRB6CLKW::XT_DIV32 => 18,
TMRB6CLKW::CTMRA6 => 20,
TMRB6CLKW::CTMRA3 => 21,
TMRB6CLKW::CTMRB3 => 22,
TMRB6CLKW::CTMRA7 => 23,
TMRB6CLKW::CTMRB7 => 24,
TMRB6CLKW::CTMRB0 => 25,
TMRB6CLKW::CTMRB1 => 26,
TMRB6CLKW::CTMRB2 => 27,
TMRB6CLKW::CTMRB4 => 28,
TMRB6CLKW::BUCKBLE => 29,
TMRB6CLKW::BUCKB => 30,
TMRB6CLKW::BUCKA => 31,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB6CLKW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB6CLKW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB6CLKW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Clock source is TMRPINB. value."]
#[inline]
pub fn tmrpin(self) -> &'a mut W {
self.variant(TMRB6CLKW::TMRPIN)
}
#[doc = "Clock source is the HFRC / 4 value."]
#[inline]
pub fn hfrc_div4(self) -> &'a mut W {
self.variant(TMRB6CLKW::HFRC_DIV4)
}
#[doc = "Clock source is HFRC / 16 value."]
#[inline]
pub fn hfrc_div16(self) -> &'a mut W {
self.variant(TMRB6CLKW::HFRC_DIV16)
}
#[doc = "Clock source is HFRC / 256 value."]
#[inline]
pub fn hfrc_div256(self) -> &'a mut W {
self.variant(TMRB6CLKW::HFRC_DIV256)
}
#[doc = "Clock source is HFRC / 1024 value."]
#[inline]
pub fn hfrc_div1024(self) -> &'a mut W {
self.variant(TMRB6CLKW::HFRC_DIV1024)
}
#[doc = "Clock source is HFRC / 4096 value."]
#[inline]
pub fn hfrc_div4k(self) -> &'a mut W {
self.variant(TMRB6CLKW::HFRC_DIV4K)
}
#[doc = "Clock source is the XT (uncalibrated). value."]
#[inline]
pub fn xt(self) -> &'a mut W {
self.variant(TMRB6CLKW::XT)
}
#[doc = "Clock source is XT / 2 value."]
#[inline]
pub fn xt_div2(self) -> &'a mut W {
self.variant(TMRB6CLKW::XT_DIV2)
}
#[doc = "Clock source is XT / 16 value."]
#[inline]
pub fn xt_div16(self) -> &'a mut W {
self.variant(TMRB6CLKW::XT_DIV16)
}
#[doc = "Clock source is XT / 128 value."]
#[inline]
pub fn xt_div128(self) -> &'a mut W {
self.variant(TMRB6CLKW::XT_DIV128)
}
#[doc = "Clock source is LFRC / 2 value."]
#[inline]
pub fn lfrc_div2(self) -> &'a mut W {
self.variant(TMRB6CLKW::LFRC_DIV2)
}
#[doc = "Clock source is LFRC / 32 value."]
#[inline]
pub fn lfrc_div32(self) -> &'a mut W {
self.variant(TMRB6CLKW::LFRC_DIV32)
}
#[doc = "Clock source is LFRC / 1024 value."]
#[inline]
pub fn lfrc_div1k(self) -> &'a mut W {
self.variant(TMRB6CLKW::LFRC_DIV1K)
}
#[doc = "Clock source is LFRC value."]
#[inline]
pub fn lfrc(self) -> &'a mut W {
self.variant(TMRB6CLKW::LFRC)
}
#[doc = "Clock source is 100 Hz from the current RTC oscillator. value."]
#[inline]
pub fn rtc_100hz(self) -> &'a mut W {
self.variant(TMRB6CLKW::RTC_100HZ)
}
#[doc = "Clock source is HCLK / 4 (note: this clock is only available when MCU is in active mode) value."]
#[inline]
pub fn hclk_div4(self) -> &'a mut W {
self.variant(TMRB6CLKW::HCLK_DIV4)
}
#[doc = "Clock source is XT / 4 value."]
#[inline]
pub fn xt_div4(self) -> &'a mut W {
self.variant(TMRB6CLKW::XT_DIV4)
}
#[doc = "Clock source is XT / 8 value."]
#[inline]
pub fn xt_div8(self) -> &'a mut W {
self.variant(TMRB6CLKW::XT_DIV8)
}
#[doc = "Clock source is XT / 32 value."]
#[inline]
pub fn xt_div32(self) -> &'a mut W {
self.variant(TMRB6CLKW::XT_DIV32)
}
#[doc = "Clock source is CTIMERA6 OUT. value."]
#[inline]
pub fn ctmra6(self) -> &'a mut W {
self.variant(TMRB6CLKW::CTMRA6)
}
#[doc = "Clock source is CTIMERA3 OUT. value."]
#[inline]
pub fn ctmra3(self) -> &'a mut W {
self.variant(TMRB6CLKW::CTMRA3)
}
#[doc = "Clock source is CTIMERB3 OUT. value."]
#[inline]
pub fn ctmrb3(self) -> &'a mut W {
self.variant(TMRB6CLKW::CTMRB3)
}
#[doc = "Clock source is CTIMERA7 OUT. value."]
#[inline]
pub fn ctmra7(self) -> &'a mut W {
self.variant(TMRB6CLKW::CTMRA7)
}
#[doc = "Clock source is CTIMERB7 OUT. value."]
#[inline]
pub fn ctmrb7(self) -> &'a mut W {
self.variant(TMRB6CLKW::CTMRB7)
}
#[doc = "Clock source is CTIMERB0 OUT. value."]
#[inline]
pub fn ctmrb0(self) -> &'a mut W {
self.variant(TMRB6CLKW::CTMRB0)
}
#[doc = "Clock source is CTIMERB1 OUT. value."]
#[inline]
pub fn ctmrb1(self) -> &'a mut W {
self.variant(TMRB6CLKW::CTMRB1)
}
#[doc = "Clock source is CTIMERB2 OUT. value."]
#[inline]
pub fn ctmrb2(self) -> &'a mut W {
self.variant(TMRB6CLKW::CTMRB2)
}
#[doc = "Clock source is CTIMERB4 OUT. value."]
#[inline]
pub fn ctmrb4(self) -> &'a mut W {
self.variant(TMRB6CLKW::CTMRB4)
}
#[doc = "Clock source is BLE buck converter TON pulses. value."]
#[inline]
pub fn buckble(self) -> &'a mut W {
self.variant(TMRB6CLKW::BUCKBLE)
}
#[doc = "Clock source is Memory buck converter TON pulses. value."]
#[inline]
pub fn buckb(self) -> &'a mut W {
self.variant(TMRB6CLKW::BUCKB)
}
#[doc = "Clock source is CPU buck converter TON pulses. value."]
#[inline]
pub fn bucka(self) -> &'a mut W {
self.variant(TMRB6CLKW::BUCKA)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 31;
const OFFSET: u8 = 17;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB6EN`"]
pub enum TMRB6ENW {
#[doc = "Counter/Timer B6 Disable. value."]
DIS,
#[doc = "Counter/Timer B6 Enable. value."]
EN,
}
impl TMRB6ENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB6ENW::DIS => false,
TMRB6ENW::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB6ENW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB6ENW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB6ENW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Counter/Timer B6 Disable. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRB6ENW::DIS)
}
#[doc = "Counter/Timer B6 Enable. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRB6ENW::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 16;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA6POL`"]
pub enum TMRA6POLW {
#[doc = "The polarity of the TMRPINA6 pin is the same as the timer output. value."]
NORMAL,
#[doc = "The polarity of the TMRPINA6 pin is the inverse of the timer output. value."]
INVERTED,
}
impl TMRA6POLW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA6POLW::NORMAL => false,
TMRA6POLW::INVERTED => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA6POLW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA6POLW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA6POLW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "The polarity of the TMRPINA6 pin is the same as the timer output. value."]
#[inline]
pub fn normal(self) -> &'a mut W {
self.variant(TMRA6POLW::NORMAL)
}
#[doc = "The polarity of the TMRPINA6 pin is the inverse of the timer output. value."]
#[inline]
pub fn inverted(self) -> &'a mut W {
self.variant(TMRA6POLW::INVERTED)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA6CLR`"]
pub enum TMRA6CLRW {
#[doc = "Allow counter/timer A6 to run value."]
RUN,
#[doc = "Holds counter/timer A6 at 0x0000. value."]
CLEAR,
}
impl TMRA6CLRW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA6CLRW::RUN => false,
TMRA6CLRW::CLEAR => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA6CLRW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA6CLRW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA6CLRW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Allow counter/timer A6 to run value."]
#[inline]
pub fn run(self) -> &'a mut W {
self.variant(TMRA6CLRW::RUN)
}
#[doc = "Holds counter/timer A6 at 0x0000. value."]
#[inline]
pub fn clear(self) -> &'a mut W {
self.variant(TMRA6CLRW::CLEAR)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 11;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA6IE1`"]
pub enum TMRA6IE1W {
#[doc = "Disable counter/timer A6 from generating an interrupt based on COMPR1. value."]
DIS,
#[doc = "Enable counter/timer A6 to generate an interrupt based on COMPR1. value."]
EN,
}
impl TMRA6IE1W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA6IE1W::DIS => false,
TMRA6IE1W::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA6IE1W<'a> {
w: &'a mut W,
}
impl<'a> _TMRA6IE1W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA6IE1W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable counter/timer A6 from generating an interrupt based on COMPR1. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRA6IE1W::DIS)
}
#[doc = "Enable counter/timer A6 to generate an interrupt based on COMPR1. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRA6IE1W::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 10;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA6IE0`"]
pub enum TMRA6IE0W {
#[doc = "Disable counter/timer A6 from generating an interrupt based on COMPR0. value."]
DIS,
#[doc = "Enable counter/timer A6 to generate an interrupt based on COMPR0. value."]
EN,
}
impl TMRA6IE0W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA6IE0W::DIS => false,
TMRA6IE0W::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA6IE0W<'a> {
w: &'a mut W,
}
impl<'a> _TMRA6IE0W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA6IE0W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable counter/timer A6 from generating an interrupt based on COMPR0. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRA6IE0W::DIS)
}
#[doc = "Enable counter/timer A6 to generate an interrupt based on COMPR0. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRA6IE0W::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 9;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA6FN`"]
pub enum TMRA6FNW {
#[doc = "Single count (output toggles and sticks). Count to CMPR0A6, stop. value."]
SINGLECOUNT,
#[doc = "Repeated count (periodic 1-clock-cycle-wide pulses). Count to CMPR0A6, restart. value."]
REPEATEDCOUNT,
#[doc = "Pulse once (aka one-shot). Count to CMPR0A6, assert, count to CMPR1A6, deassert, stop. value."]
PULSE_ONCE,
#[doc = "Pulse continously. Count to CMPR0A6, assert, count to CMPR1A6, deassert, restart. value."]
PULSE_CONT,
#[doc = "Single pattern. value."]
SINGLEPATTERN,
#[doc = "Repeated pattern. value."]
REPEATPATTERN,
#[doc = "Continuous run (aka Free Run). Count continuously. value."]
CONTINUOUS,
#[doc = "Alternate PWM value."]
ALTPWN,
}
impl TMRA6FNW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
TMRA6FNW::SINGLECOUNT => 0,
TMRA6FNW::REPEATEDCOUNT => 1,
TMRA6FNW::PULSE_ONCE => 2,
TMRA6FNW::PULSE_CONT => 3,
TMRA6FNW::SINGLEPATTERN => 4,
TMRA6FNW::REPEATPATTERN => 5,
TMRA6FNW::CONTINUOUS => 6,
TMRA6FNW::ALTPWN => 7,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA6FNW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA6FNW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA6FNW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Single count (output toggles and sticks). Count to CMPR0A6, stop. value."]
#[inline]
pub fn singlecount(self) -> &'a mut W {
self.variant(TMRA6FNW::SINGLECOUNT)
}
#[doc = "Repeated count (periodic 1-clock-cycle-wide pulses). Count to CMPR0A6, restart. value."]
#[inline]
pub fn repeatedcount(self) -> &'a mut W {
self.variant(TMRA6FNW::REPEATEDCOUNT)
}
#[doc = "Pulse once (aka one-shot). Count to CMPR0A6, assert, count to CMPR1A6, deassert, stop. value."]
#[inline]
pub fn pulse_once(self) -> &'a mut W {
self.variant(TMRA6FNW::PULSE_ONCE)
}
#[doc = "Pulse continously. Count to CMPR0A6, assert, count to CMPR1A6, deassert, restart. value."]
#[inline]
pub fn pulse_cont(self) -> &'a mut W {
self.variant(TMRA6FNW::PULSE_CONT)
}
#[doc = "Single pattern. value."]
#[inline]
pub fn singlepattern(self) -> &'a mut W {
self.variant(TMRA6FNW::SINGLEPATTERN)
}
#[doc = "Repeated pattern. value."]
#[inline]
pub fn repeatpattern(self) -> &'a mut W {
self.variant(TMRA6FNW::REPEATPATTERN)
}
#[doc = "Continuous run (aka Free Run). Count continuously. value."]
#[inline]
pub fn continuous(self) -> &'a mut W {
self.variant(TMRA6FNW::CONTINUOUS)
}
#[doc = "Alternate PWM value."]
#[inline]
pub fn altpwn(self) -> &'a mut W {
self.variant(TMRA6FNW::ALTPWN)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 7;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA6CLK`"]
pub enum TMRA6CLKW {
#[doc = "Clock source is TMRPINA. value."]
TMRPIN,
#[doc = "Clock source is the HFRC / 4 value."]
HFRC_DIV4,
#[doc = "Clock source is HFRC / 16 value."]
HFRC_DIV16,
#[doc = "Clock source is HFRC / 256 value."]
HFRC_DIV256,
#[doc = "Clock source is HFRC / 1024 value."]
HFRC_DIV1024,
#[doc = "Clock source is HFRC / 4096 value."]
HFRC_DIV4K,
#[doc = "Clock source is the XT (uncalibrated). value."]
XT,
#[doc = "Clock source is XT / 2 value."]
XT_DIV2,
#[doc = "Clock source is XT / 16 value."]
XT_DIV16,
#[doc = "Clock source is XT / 128 value."]
XT_DIV128,
#[doc = "Clock source is LFRC / 2 value."]
LFRC_DIV2,
#[doc = "Clock source is LFRC / 32 value."]
LFRC_DIV32,
#[doc = "Clock source is LFRC / 1024 value."]
LFRC_DIV1K,
#[doc = "Clock source is LFRC value."]
LFRC,
#[doc = "Clock source is 100 Hz from the current RTC oscillator. value."]
RTC_100HZ,
#[doc = "Clock source is HCLK / 4 (note: this clock is only available when MCU is in active mode) value."]
HCLK_DIV4,
#[doc = "Clock source is XT / 4 value."]
XT_DIV4,
#[doc = "Clock source is XT / 8 value."]
XT_DIV8,
#[doc = "Clock source is XT / 32 value."]
XT_DIV32,
#[doc = "Clock source is CTIMERB6 OUT. value."]
CTMRB6,
#[doc = "Clock source is CTIMERA3 OUT. value."]
CTMRA3,
#[doc = "Clock source is CTIMERB3 OUT. value."]
CTMRB3,
#[doc = "Clock source is CTIMERA7 OUT. value."]
CTMRA7,
#[doc = "Clock source is CTIMERB7 OUT. value."]
CTMRB7,
#[doc = "Clock source is CTIMERB0 OUT. value."]
CTMRB0,
#[doc = "Clock source is CTIMERB1 OUT. value."]
CTMRB1,
#[doc = "Clock source is CTIMERB2 OUT. value."]
CTMRB2,
#[doc = "Clock source is CTIMERB4 OUT. value."]
CTMRB4,
#[doc = "Clock source is BLE buck converter TON pulses. value."]
BUCKBLE,
#[doc = "Clock source is Memory buck converter TON pulses. value."]
BUCKB,
#[doc = "Clock source is CPU buck converter TON pulses. value."]
BUCKA,
}
impl TMRA6CLKW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
TMRA6CLKW::TMRPIN => 0,
TMRA6CLKW::HFRC_DIV4 => 1,
TMRA6CLKW::HFRC_DIV16 => 2,
TMRA6CLKW::HFRC_DIV256 => 3,
TMRA6CLKW::HFRC_DIV1024 => 4,
TMRA6CLKW::HFRC_DIV4K => 5,
TMRA6CLKW::XT => 6,
TMRA6CLKW::XT_DIV2 => 7,
TMRA6CLKW::XT_DIV16 => 8,
TMRA6CLKW::XT_DIV128 => 9,
TMRA6CLKW::LFRC_DIV2 => 10,
TMRA6CLKW::LFRC_DIV32 => 11,
TMRA6CLKW::LFRC_DIV1K => 12,
TMRA6CLKW::LFRC => 13,
TMRA6CLKW::RTC_100HZ => 14,
TMRA6CLKW::HCLK_DIV4 => 15,
TMRA6CLKW::XT_DIV4 => 16,
TMRA6CLKW::XT_DIV8 => 17,
TMRA6CLKW::XT_DIV32 => 18,
TMRA6CLKW::CTMRB6 => 20,
TMRA6CLKW::CTMRA3 => 21,
TMRA6CLKW::CTMRB3 => 22,
TMRA6CLKW::CTMRA7 => 23,
TMRA6CLKW::CTMRB7 => 24,
TMRA6CLKW::CTMRB0 => 25,
TMRA6CLKW::CTMRB1 => 26,
TMRA6CLKW::CTMRB2 => 27,
TMRA6CLKW::CTMRB4 => 28,
TMRA6CLKW::BUCKBLE => 29,
TMRA6CLKW::BUCKB => 30,
TMRA6CLKW::BUCKA => 31,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA6CLKW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA6CLKW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA6CLKW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Clock source is TMRPINA. value."]
#[inline]
pub fn tmrpin(self) -> &'a mut W {
self.variant(TMRA6CLKW::TMRPIN)
}
#[doc = "Clock source is the HFRC / 4 value."]
#[inline]
pub fn hfrc_div4(self) -> &'a mut W {
self.variant(TMRA6CLKW::HFRC_DIV4)
}
#[doc = "Clock source is HFRC / 16 value."]
#[inline]
pub fn hfrc_div16(self) -> &'a mut W {
self.variant(TMRA6CLKW::HFRC_DIV16)
}
#[doc = "Clock source is HFRC / 256 value."]
#[inline]
pub fn hfrc_div256(self) -> &'a mut W {
self.variant(TMRA6CLKW::HFRC_DIV256)
}
#[doc = "Clock source is HFRC / 1024 value."]
#[inline]
pub fn hfrc_div1024(self) -> &'a mut W {
self.variant(TMRA6CLKW::HFRC_DIV1024)
}
#[doc = "Clock source is HFRC / 4096 value."]
#[inline]
pub fn hfrc_div4k(self) -> &'a mut W {
self.variant(TMRA6CLKW::HFRC_DIV4K)
}
#[doc = "Clock source is the XT (uncalibrated). value."]
#[inline]
pub fn xt(self) -> &'a mut W {
self.variant(TMRA6CLKW::XT)
}
#[doc = "Clock source is XT / 2 value."]
#[inline]
pub fn xt_div2(self) -> &'a mut W {
self.variant(TMRA6CLKW::XT_DIV2)
}
#[doc = "Clock source is XT / 16 value."]
#[inline]
pub fn xt_div16(self) -> &'a mut W {
self.variant(TMRA6CLKW::XT_DIV16)
}
#[doc = "Clock source is XT / 128 value."]
#[inline]
pub fn xt_div128(self) -> &'a mut W {
self.variant(TMRA6CLKW::XT_DIV128)
}
#[doc = "Clock source is LFRC / 2 value."]
#[inline]
pub fn lfrc_div2(self) -> &'a mut W {
self.variant(TMRA6CLKW::LFRC_DIV2)
}
#[doc = "Clock source is LFRC / 32 value."]
#[inline]
pub fn lfrc_div32(self) -> &'a mut W {
self.variant(TMRA6CLKW::LFRC_DIV32)
}
#[doc = "Clock source is LFRC / 1024 value."]
#[inline]
pub fn lfrc_div1k(self) -> &'a mut W {
self.variant(TMRA6CLKW::LFRC_DIV1K)
}
#[doc = "Clock source is LFRC value."]
#[inline]
pub fn lfrc(self) -> &'a mut W {
self.variant(TMRA6CLKW::LFRC)
}
#[doc = "Clock source is 100 Hz from the current RTC oscillator. value."]
#[inline]
pub fn rtc_100hz(self) -> &'a mut W {
self.variant(TMRA6CLKW::RTC_100HZ)
}
#[doc = "Clock source is HCLK / 4 (note: this clock is only available when MCU is in active mode) value."]
#[inline]
pub fn hclk_div4(self) -> &'a mut W {
self.variant(TMRA6CLKW::HCLK_DIV4)
}
#[doc = "Clock source is XT / 4 value."]
#[inline]
pub fn xt_div4(self) -> &'a mut W {
self.variant(TMRA6CLKW::XT_DIV4)
}
#[doc = "Clock source is XT / 8 value."]
#[inline]
pub fn xt_div8(self) -> &'a mut W {
self.variant(TMRA6CLKW::XT_DIV8)
}
#[doc = "Clock source is XT / 32 value."]
#[inline]
pub fn xt_div32(self) -> &'a mut W {
self.variant(TMRA6CLKW::XT_DIV32)
}
#[doc = "Clock source is CTIMERB6 OUT. value."]
#[inline]
pub fn ctmrb6(self) -> &'a mut W {
self.variant(TMRA6CLKW::CTMRB6)
}
#[doc = "Clock source is CTIMERA3 OUT. value."]
#[inline]
pub fn ctmra3(self) -> &'a mut W {
self.variant(TMRA6CLKW::CTMRA3)
}
#[doc = "Clock source is CTIMERB3 OUT. value."]
#[inline]
pub fn ctmrb3(self) -> &'a mut W {
self.variant(TMRA6CLKW::CTMRB3)
}
#[doc = "Clock source is CTIMERA7 OUT. value."]
#[inline]
pub fn ctmra7(self) -> &'a mut W {
self.variant(TMRA6CLKW::CTMRA7)
}
#[doc = "Clock source is CTIMERB7 OUT. value."]
#[inline]
pub fn ctmrb7(self) -> &'a mut W {
self.variant(TMRA6CLKW::CTMRB7)
}
#[doc = "Clock source is CTIMERB0 OUT. value."]
#[inline]
pub fn ctmrb0(self) -> &'a mut W {
self.variant(TMRA6CLKW::CTMRB0)
}
#[doc = "Clock source is CTIMERB1 OUT. value."]
#[inline]
pub fn ctmrb1(self) -> &'a mut W {
self.variant(TMRA6CLKW::CTMRB1)
}
#[doc = "Clock source is CTIMERB2 OUT. value."]
#[inline]
pub fn ctmrb2(self) -> &'a mut W {
self.variant(TMRA6CLKW::CTMRB2)
}
#[doc = "Clock source is CTIMERB4 OUT. value."]
#[inline]
pub fn ctmrb4(self) -> &'a mut W {
self.variant(TMRA6CLKW::CTMRB4)
}
#[doc = "Clock source is BLE buck converter TON pulses. value."]
#[inline]
pub fn buckble(self) -> &'a mut W {
self.variant(TMRA6CLKW::BUCKBLE)
}
#[doc = "Clock source is Memory buck converter TON pulses. value."]
#[inline]
pub fn buckb(self) -> &'a mut W {
self.variant(TMRA6CLKW::BUCKB)
}
#[doc = "Clock source is CPU buck converter TON pulses. value."]
#[inline]
pub fn bucka(self) -> &'a mut W {
self.variant(TMRA6CLKW::BUCKA)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 31;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA6EN`"]
pub enum TMRA6ENW {
#[doc = "Counter/Timer A6 Disable. value."]
DIS,
#[doc = "Counter/Timer A6 Enable. value."]
EN,
}
impl TMRA6ENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA6ENW::DIS => false,
TMRA6ENW::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA6ENW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA6ENW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA6ENW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Counter/Timer A6 Disable. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRA6ENW::DIS)
}
#[doc = "Counter/Timer A6 Enable. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRA6ENW::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 31 - Counter/Timer A6/B6 Link bit."]
#[inline]
pub fn ctlink6(&self) -> CTLINK6R {
CTLINK6R::_from({
const MASK: bool = true;
const OFFSET: u8 = 31;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 28 - Counter/Timer B6 output polarity."]
#[inline]
pub fn tmrb6pol(&self) -> TMRB6POLR {
TMRB6POLR::_from({
const MASK: bool = true;
const OFFSET: u8 = 28;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 27 - Counter/Timer B6 Clear bit."]
#[inline]
pub fn tmrb6clr(&self) -> TMRB6CLRR {
TMRB6CLRR::_from({
const MASK: bool = true;
const OFFSET: u8 = 27;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 26 - Counter/Timer B6 Interrupt Enable bit for COMPR1."]
#[inline]
pub fn tmrb6ie1(&self) -> TMRB6IE1R {
TMRB6IE1R::_from({
const MASK: bool = true;
const OFFSET: u8 = 26;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 25 - Counter/Timer B6 Interrupt Enable bit for COMPR0."]
#[inline]
pub fn tmrb6ie0(&self) -> TMRB6IE0R {
TMRB6IE0R::_from({
const MASK: bool = true;
const OFFSET: u8 = 25;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 22:24 - Counter/Timer B6 Function Select."]
#[inline]
pub fn tmrb6fn(&self) -> TMRB6FNR {
TMRB6FNR::_from({
const MASK: u8 = 7;
const OFFSET: u8 = 22;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 17:21 - Counter/Timer B6 Clock Select."]
#[inline]
pub fn tmrb6clk(&self) -> TMRB6CLKR {
TMRB6CLKR::_from({
const MASK: u8 = 31;
const OFFSET: u8 = 17;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 16 - Counter/Timer B6 Enable bit."]
#[inline]
pub fn tmrb6en(&self) -> TMRB6ENR {
TMRB6ENR::_from({
const MASK: bool = true;
const OFFSET: u8 = 16;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 12 - Counter/Timer A6 output polarity."]
#[inline]
pub fn tmra6pol(&self) -> TMRA6POLR {
TMRA6POLR::_from({
const MASK: bool = true;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 11 - Counter/Timer A6 Clear bit."]
#[inline]
pub fn tmra6clr(&self) -> TMRA6CLRR {
TMRA6CLRR::_from({
const MASK: bool = true;
const OFFSET: u8 = 11;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 10 - Counter/Timer A6 Interrupt Enable bit based on COMPR1."]
#[inline]
pub fn tmra6ie1(&self) -> TMRA6IE1R {
TMRA6IE1R::_from({
const MASK: bool = true;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 9 - Counter/Timer A6 Interrupt Enable bit based on COMPR0."]
#[inline]
pub fn tmra6ie0(&self) -> TMRA6IE0R {
TMRA6IE0R::_from({
const MASK: bool = true;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 6:8 - Counter/Timer A6 Function Select."]
#[inline]
pub fn tmra6fn(&self) -> TMRA6FNR {
TMRA6FNR::_from({
const MASK: u8 = 7;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 1:5 - Counter/Timer A6 Clock Select."]
#[inline]
pub fn tmra6clk(&self) -> TMRA6CLKR {
TMRA6CLKR::_from({
const MASK: u8 = 31;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 0 - Counter/Timer A6 Enable bit."]
#[inline]
pub fn tmra6en(&self) -> TMRA6ENR {
TMRA6ENR::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 31 - Counter/Timer A6/B6 Link bit."]
#[inline]
pub fn ctlink6(&mut self) -> _CTLINK6W {
_CTLINK6W { w: self }
}
#[doc = "Bit 28 - Counter/Timer B6 output polarity."]
#[inline]
pub fn tmrb6pol(&mut self) -> _TMRB6POLW {
_TMRB6POLW { w: self }
}
#[doc = "Bit 27 - Counter/Timer B6 Clear bit."]
#[inline]
pub fn tmrb6clr(&mut self) -> _TMRB6CLRW {
_TMRB6CLRW { w: self }
}
#[doc = "Bit 26 - Counter/Timer B6 Interrupt Enable bit for COMPR1."]
#[inline]
pub fn tmrb6ie1(&mut self) -> _TMRB6IE1W {
_TMRB6IE1W { w: self }
}
#[doc = "Bit 25 - Counter/Timer B6 Interrupt Enable bit for COMPR0."]
#[inline]
pub fn tmrb6ie0(&mut self) -> _TMRB6IE0W {
_TMRB6IE0W { w: self }
}
#[doc = "Bits 22:24 - Counter/Timer B6 Function Select."]
#[inline]
pub fn tmrb6fn(&mut self) -> _TMRB6FNW {
_TMRB6FNW { w: self }
}
#[doc = "Bits 17:21 - Counter/Timer B6 Clock Select."]
#[inline]
pub fn tmrb6clk(&mut self) -> _TMRB6CLKW {
_TMRB6CLKW { w: self }
}
#[doc = "Bit 16 - Counter/Timer B6 Enable bit."]
#[inline]
pub fn tmrb6en(&mut self) -> _TMRB6ENW {
_TMRB6ENW { w: self }
}
#[doc = "Bit 12 - Counter/Timer A6 output polarity."]
#[inline]
pub fn tmra6pol(&mut self) -> _TMRA6POLW {
_TMRA6POLW { w: self }
}
#[doc = "Bit 11 - Counter/Timer A6 Clear bit."]
#[inline]
pub fn tmra6clr(&mut self) -> _TMRA6CLRW {
_TMRA6CLRW { w: self }
}
#[doc = "Bit 10 - Counter/Timer A6 Interrupt Enable bit based on COMPR1."]
#[inline]
pub fn tmra6ie1(&mut self) -> _TMRA6IE1W {
_TMRA6IE1W { w: self }
}
#[doc = "Bit 9 - Counter/Timer A6 Interrupt Enable bit based on COMPR0."]
#[inline]
pub fn tmra6ie0(&mut self) -> _TMRA6IE0W {
_TMRA6IE0W { w: self }
}
#[doc = "Bits 6:8 - Counter/Timer A6 Function Select."]
#[inline]
pub fn tmra6fn(&mut self) -> _TMRA6FNW {
_TMRA6FNW { w: self }
}
#[doc = "Bits 1:5 - Counter/Timer A6 Clock Select."]
#[inline]
pub fn tmra6clk(&mut self) -> _TMRA6CLKW {
_TMRA6CLKW { w: self }
}
#[doc = "Bit 0 - Counter/Timer A6 Enable bit."]
#[inline]
pub fn tmra6en(&mut self) -> _TMRA6ENW {
_TMRA6ENW { w: self }
}
}
|
use crate::format_context::FormatContext;
use crate::stream::Stream;
use crate::tools::rational::Rational;
use ffmpeg_sys_next::*;
use log::LevelFilter;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct Probe {
#[serde(skip_serializing)]
filename: String,
pub format: Option<Format>,
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct Format {
format_name: String,
format_long_name: String,
program_count: u32,
start_time: Option<f32>,
duration: Option<f64>,
bit_rate: Option<i64>,
packet_size: u32,
nb_streams: u32,
metadata: BTreeMap<String, String>,
streams: Vec<StreamDescriptor>,
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct StreamDescriptor {
index: u32,
stream_type: String,
codec_name: Option<String>,
codec_long_name: Option<String>,
codec_tag: Option<String>,
start_time: Option<f32>,
duration: Option<f32>,
bit_rate: Option<i64>,
stream_metadata: HashMap<String, String>,
#[serde(flatten)]
video_properties: Option<VideoProperties>,
#[serde(flatten)]
audio_properties: Option<AudioProperties>,
}
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct VideoProperties {
width: i32,
height: i32,
display_aspect_ratio: Rational,
frame_rate: Rational,
level: Option<i32>,
profile: Option<String>,
scanning_type: Option<String>,
chroma_subsampling: Option<String>,
timecode: Option<String>,
pix_fmt: Option<String>,
nb_frames: Option<i64>,
}
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct AudioProperties {
channels: i32,
sample_rate: i32,
sample_fmt: String,
bits_per_sample: i32,
}
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct SubtitleProperties {}
impl fmt::Display for Format {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "{:30} : {}", "Format name", self.format_name)?;
writeln!(f, "{:30} : {}", "Format long name", self.format_long_name)?;
writeln!(f, "{:30} : {:?}", "Start time", self.start_time)?;
writeln!(f, "{:30} : {:?}", "Duration", self.duration)?;
writeln!(f, "{:30} : {:?}", "Bit rate", self.bit_rate)?;
writeln!(f, "{:30} : {}", "Packet size", self.packet_size)?;
writeln!(f, "{:30} : {}", "Number of streams", self.nb_streams)?;
writeln!(f, "{:30} : {}", "Number of Programs", self.program_count)?;
for (key, value) in &self.metadata {
writeln!(f, "{key:30} : {value}")?;
}
for stream in &self.streams {
writeln!(f, "\n{:30} : {}", "Stream type", stream.stream_type)?;
writeln!(f, "{:30} : {}", "Index", stream.index)?;
writeln!(f, "{:30} : {:?}", "Codec name", stream.codec_name)?;
writeln!(f, "{:30} : {:?}", "Codec long name", stream.codec_long_name)?;
writeln!(f, "{:30} : {:?}", "Codec tag", stream.codec_tag)?;
if let Some(ref vp) = stream.video_properties {
writeln!(f, "{:30} : {}", "Width", vp.width)?;
writeln!(f, "{:30} : {}", "Height", vp.height)?;
writeln!(
f,
"{:30} : {:?}",
"Display aspect ratio", vp.display_aspect_ratio
)?;
writeln!(f, "{:30} : {:?}", "Frame rate", vp.frame_rate)?;
writeln!(f, "{:30} : {:?}", "Level", vp.level)?;
writeln!(f, "{:30} : {:?}", "Profile", vp.profile)?;
writeln!(f, "{:30} : {:?}", "Start time", stream.start_time)?;
writeln!(f, "{:30} : {:?}", "Duration", stream.duration)?;
writeln!(f, "{:30} : {:?}", "Bit rate", stream.bit_rate)?;
writeln!(f, "{:30} : {:?}", "Scanning type", vp.scanning_type)?;
writeln!(
f,
"{:30} : {:?}",
"Chroma subsampling", vp.chroma_subsampling
)?;
writeln!(f, "{:30} : {:?}", "Timecode", vp.timecode)?;
writeln!(f, "{:30} : {:?}", "Pixel format", vp.pix_fmt)?;
writeln!(f, "{:30} : {:?}", "Number of frames", vp.nb_frames)?;
}
if let Some(ref ap) = stream.audio_properties {
writeln!(f, "{:30} : {}", "Channels", ap.channels)?;
writeln!(f, "{:30} : {}", "Sample rate", ap.sample_rate)?;
writeln!(f, "{:30} : {}", "Sample format", ap.sample_fmt)?;
writeln!(f, "{:30} : {}", "Bits per sample", ap.bits_per_sample)?;
writeln!(f, "{:30} : {:?}", "Start time", stream.start_time)?;
writeln!(f, "{:30} : {:?}", "Duration", stream.duration)?;
writeln!(f, "{:30} : {:?}", "Bit rate", stream.bit_rate)?;
}
for (key, value) in &stream.stream_metadata {
writeln!(f, "{key:30} : {value}")?;
}
}
Ok(())
}
}
impl Probe {
pub fn new(filename: &str) -> Self {
Probe {
filename: filename.to_owned(),
format: None,
}
}
pub fn process(&mut self, log_level: LevelFilter) -> Result<(), String> {
let av_log_level = match log_level {
LevelFilter::Error => AV_LOG_ERROR,
LevelFilter::Warn => AV_LOG_WARNING,
LevelFilter::Info => AV_LOG_INFO,
LevelFilter::Debug => AV_LOG_DEBUG,
LevelFilter::Trace => AV_LOG_TRACE,
LevelFilter::Off => AV_LOG_QUIET,
};
unsafe {
av_log_set_level(av_log_level);
}
let mut context = FormatContext::new(&self.filename).unwrap();
if context.open_input().is_err() {
self.format = None;
context.close_input();
return Ok(());
}
let format_name = context.get_format_name();
let format_long_name = context.get_format_long_name();
let program_count = context.get_program_count();
let start_time = context.get_start_time();
let duration = context.get_duration();
let bit_rate = context.get_bit_rate();
let packet_size = context.get_packet_size();
let nb_streams = context.get_nb_streams();
let metadata = context.get_metadata();
let mut streams = vec![];
for index in 0..context.get_nb_streams() {
if let Ok(stream) = Stream::new(context.get_stream(index as isize)) {
let stream_type = context.get_stream_type_name(index as isize);
let codec_name = stream.get_codec_name();
let codec_long_name = stream.get_codec_long_name();
let codec_tag = stream.get_codec_tag();
let duration = stream.get_duration();
let start_time = stream.get_start_time();
let bit_rate = stream.get_bit_rate();
let mut vp = None;
let mut ap = None;
let stream_metadata = stream.get_stream_metadata();
match context.get_stream_type(index as isize) {
AVMediaType::AVMEDIA_TYPE_VIDEO => {
let width = stream.get_width();
let height = stream.get_height();
let display_aspect_ratio = stream.get_display_aspect_ratio();
let frame_rate = stream.get_frame_rate();
let scanning_type = stream.get_scanning_type();
let chroma_subsampling = stream.get_chroma_sub_sample();
let level = stream.get_level();
let profile = stream.get_profile();
let timecode = stream.get_timecode();
let pix_fmt = stream.get_pix_fmt_name();
let nb_frames = stream.get_nb_frames();
vp = Some(VideoProperties {
width,
height,
display_aspect_ratio,
frame_rate,
level,
profile,
scanning_type,
chroma_subsampling,
timecode,
pix_fmt,
nb_frames,
});
}
AVMediaType::AVMEDIA_TYPE_AUDIO => {
let channels = stream.get_channels();
let bits_per_sample = stream.get_bits_per_sample();
let sample_fmt = stream.get_sample_fmt();
let sample_rate = stream.get_sample_rate();
ap = Some(AudioProperties {
channels,
sample_rate,
sample_fmt,
bits_per_sample,
});
}
_ => {}
}
streams.push(StreamDescriptor {
index,
stream_type,
codec_name,
codec_long_name,
codec_tag,
start_time,
duration,
bit_rate,
stream_metadata,
video_properties: vp,
audio_properties: ap,
})
}
}
self.format = Some(Format {
format_name,
format_long_name,
program_count,
start_time,
duration,
bit_rate,
packet_size,
nb_streams,
metadata,
streams,
});
context.close_input();
Ok(())
}
}
#[test]
fn probe_mxf_sample() {
use serde_json;
use std::fs::File;
use std::io::prelude::*;
let mut probe = Probe::new("tests/PAL_1080i_MPEG_XDCAM-HD_colorbar.mxf");
probe.process(LevelFilter::Error).unwrap();
let mut file = File::open("tests/probe.json").unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let reference: Probe = serde_json::from_str(&contents).unwrap();
assert_eq!(probe, reference);
}
|
extern crate num_bigint;
extern crate num_traits;
use num_bigint::BigInt;
use num_bigint::ToBigInt;
use num_traits::{Zero, One};
use num_traits::ToPrimitive;
use std::fs::File;
use std::io::{BufRead, BufReader};
#[derive(Copy, Clone, PartialEq, Debug)]
enum DealType {
NewStack,
WithIncrement(i64),
Cut(i64),
}
fn reorder(input : Vec<DealType>, count : i64) -> Vec<DealType> {
// Compact "deal into stack" shuffles.
//
// Two consecutive "deal into stack" shuffles cancel each other. So we
// iterate over the input list, tracking whether we need to currently need
// reverse the stack, which changes every time we see a "deal into stack"
// shuffle. Then, if we need to reverse at the end, we add a single "deal
// into stack" shuffle to the output.
//
// If we currently need to reverse the stack, we have to modify the other
// shuffles. This boils down to the following two rules, where the list of
// instructions below the line has the same effect as the list of
// instructions above the line:
//
// deal into new stack
// cut x
// -------------------
// cut count-x
// deal into new stack
//
// deal into new stack
// deal with increment x
// ---
// deal with increment x
// cut count+1-x
// deal into new stack
//
let mut compacted = Vec::new();
compacted.reserve(input.len());
let mut reverse = false;
for shuffle in input.iter() {
if *shuffle == DealType::NewStack {
reverse = !reverse;
continue;
}
if !reverse {
compacted.push(*shuffle);
continue;
}
match shuffle {
DealType::WithIncrement(incr) => {
compacted.push(*shuffle);
compacted.push(DealType::Cut(count + 1 - incr));
},
DealType::Cut(n) => {
let mut cut = (n + count) % count; // normalize negative values
cut = count - cut; // reverse cut
compacted.push(DealType::Cut(cut));
},
DealType::NewStack => unreachable!()
};
}
if reverse {
compacted.push(DealType::NewStack);
}
return compacted;
}
fn reorder2(input : Vec<DealType>, count : i64) -> Vec<DealType> {
// Compact "cut" shuffles.
//
// Here we require that the "deal into stack" shuffles have been compacted
// already, so we can insert the "cut" shuffle before the "deal into
// stack" shuffle or at the end. Then, we only have to handle "deal with
// increment" shuffles.
//
// cut x
// cut y
// ---
// cut (x+y) % count
//
// cut x
// deal with increment y
// ---
// deal with increment y
// cut (x*y) % count
//
let mut compacted = Vec::new();
compacted.reserve(input.len());
let mut cut: BigInt = Zero::zero();
for shuffle in input.iter() {
match shuffle {
DealType::NewStack => {
if cut != Zero::zero() {
compacted.push(DealType::Cut(cut.to_i64().unwrap()));
cut = Zero::zero();
}
compacted.push(*shuffle);
},
DealType::WithIncrement(incr) => {
let bi_incr = incr.to_bigint().unwrap();
compacted.push(*shuffle);
cut = (cut * bi_incr) % count;
},
DealType::Cut(n) => {
let bi_n = n.to_bigint().unwrap();
cut = (cut + bi_n) % count;
}
};
}
if cut != Zero::zero() {
compacted.push(DealType::Cut(cut.to_i64().unwrap()));
}
return compacted;
}
fn reduce(input : Vec<DealType>, count : i64) -> Vec<DealType> {
// Compact "deal with increment" shuffles.
//
// Finally, we just have to combine "deal with increment" shuffles.
//
// deal with increment x
// deal with increment y
// ---
// deal with increment (x*y) % count
//
let mut compacted = Vec::new();
compacted.reserve(input.len());
let mut increment : BigInt = One::one();
for shuffle in input.iter() {
match shuffle {
DealType::WithIncrement(incr) => {
let bi_incr = incr.to_bigint().unwrap();
increment = (increment * bi_incr) % count;
},
_ => {
if increment != One::one() {
compacted.push(DealType::WithIncrement(increment.to_i64().unwrap()));
increment = One::one();
}
compacted.push(*shuffle);
}
}
}
if increment != One::one() {
compacted.push(DealType::WithIncrement(increment.to_i64().unwrap()));
}
return compacted;
}
fn compact(input : Vec<DealType>, count : i64) -> Vec<DealType> {
let reorder_input = reorder(input, count);
let reorder2_input = reorder2(reorder_input, count);
return reduce(reorder2_input, count);
}
fn main() {
let filename = "../part1/src/input";
// Open the file in read-only mode (ignoring errors).
let file = File::open(filename).unwrap();
let reader = BufReader::new(file);
let mut shuffle = Vec::new();
// Read the file line by line using the lines() iterator from std::io::BufRead.
for (_, line) in reader.lines().enumerate() {
let line = line.unwrap(); // Ignore errors.
if line.trim().len() == 0 {
break;
}
if line.starts_with("deal w") {
let incr: i64 = line[20..].parse().unwrap();
shuffle.push(DealType::WithIncrement(incr));
} else if line.starts_with("cut") {
let n: i64 = line[4..].parse().unwrap();
shuffle.push(DealType::Cut(n));
} else if line.starts_with("deal i") {
shuffle.push(DealType::NewStack);
} else {
unreachable!();
}
}
const COUNT : i64 = 119315717514047;
const ITERATIONS : i64 = 101741582076661;
let mut shuffles = Vec::new();
// Exponentiation by squaring.
let mut iterations_left = COUNT - ITERATIONS - 1;
while iterations_left != 0 {
if iterations_left % 2 == 1 {
shuffles.append(&mut shuffle.clone());
shuffles = compact(shuffles, COUNT);
}
shuffle.append(&mut shuffle.clone());
shuffle = compact(shuffle, COUNT);
iterations_left /= 2;
}
let mut pos : i64 = 2020;
for shuffle in shuffles.iter() {
match shuffle {
DealType::WithIncrement(incr) => {
let increment = incr;
pos = (pos * increment) % COUNT;
},
DealType::NewStack => {
pos = COUNT - 1 - pos;
},
DealType::Cut(n) => {
if pos < *n {
pos = pos + COUNT - n;
} else {
pos = pos - n;
}
}
};
}
println!("Card in pos: {}", pos);
}
|
#![no_std]
use volatile_cell::VolatileCell;
// Known to apply to (with exceptions noted):
// [RM0360] STM32F030x4/6/8/C and STM32F070x6/B
// [RM0091] STM32F0x1, STM32F0x2, STM32F0x8
// [RM0033] STM32F205xx, STM32F207xx, STM32F215xx and STM32F217xx
// [RM0366] STM32F301x6/8 and STM32F318x8
// [RM0365] STM32F302xB/C/D/E and STM32F302x6/8
// [RM0316] STM32F303xB/C/D/E, STM32F303x6/8, STM32F328x8, STM32F358xC, STM32F398xE
// [RM0364] STM32F334xx
// [RM0313] STM32F37xx
// [RM0090] STM32F4
// [RM0368] STM32F401xB/C and STM32F401xD/E
// [RM0838] STM32F411xC/E
// [RM0390] STM32F446xx
// [RM0385] STM32F75xxx and STM32F74xxx
// [RM0377] STM32L0x1
// [RM0376] STM32L0x2
// [RM0367] STM32L0x3
// [RM0038] STM32L100xx, 151xx, 152xx and 162xx
// [RM0351] STM32L4x6
//
// Known not to apply to:
// [RM0041] STM32F100xx
// [RM0008] STM32F101xx, 2xx, 3xx, 5xx, 7xx
ioregs!(GPIO = {
0x00 => reg32 moder {
0..31 => mode[16] : rw {
0b00 => Input,
0b01 => Output,
0b10 => Alternate,
0b11 => Analog,
},
},
0x04 => reg32 otyper {
0..15 => ot[16] : rw {
0 => PushPull,
1 => OpenDrain,
},
16..31 => reserved : ro,
},
0x08 => reg32 ospeedr {
0..31 => ospeed[16] : rw {
// TODO: names not common to all devices
0b00 => Low,
0b01 => Medium,
0b10 => Fast,
0b11 => High,
}
},
0x0c => reg32 pupdr {
0..31 => pupdr[16] : rw {
0b00 => None,
0b01 => PullUp,
0b10 => PullDown,
0b11 => Reserved,
},
},
0x10 => reg32 idr {
0..15 => idr[16] : ro,
16..31 => reserved : ro,
},
0x14 => reg32 odr {
0..15 => odr[16] : rw,
16..31 => reserved : ro,
},
0x18 => reg32 bsrr {
0..15 => bs[16] : wo,
16..31 => br[16] : wo,
},
0x1c => reg32 lckr {
// TODO: only available on GPIOs A & B for STM32F030x4 et al
// TODO: only available on GPIOs A & B for STM32F0x1 et al.
// TODO: only available on GPIOs A, B & D for STM32F303xB/C and STM32F358xC
// TODO: only available on GPIOs A, B & D for STM32F37xx
// TODO: only available on GPIOs A, B, C, D & F for STM32F303x6/8 and STM32F328x8
// TODO: only available on GPIOs A, B & D for STM32F302xB/C
// TODO: only available on GPIOs A, B, C, D & F for STM32F302x6/8
0..15 => lck[16] : rw,
16 => lckk : rw,
17..31 => reserved : ro,
},
0x20 => reg32 afrl {
// TODO: only available on GPIOs A & B for STM32F030x4 et al. (maybe? manual not self-consistent)
// TODO: values >= 0b1000 only allowed on ports A & B for STM32F334xx
// TODO: values >= 0b1000 only allowed on ports A, B & D for STM32F37xx
// TODO: values >= 0b1000 reserved on STM32F030x4 et al.
// TODO: values >= 0b1000 reserved on STM32F0x1 et al.
// TODO: values >= 0b1000 reserved on STM32L0x3
// TODO: values >= 0b1000 reserved on STM32L0x2
// TODO: values >= 0b1000 reserved on STM32L0x1
0..31 => afr[8] : rw,
},
0x24 => reg32 afrh {
// same caveats as afrl, except:
// STM32F75xxx does not have this register for PORT J
0..31 => afr[8] : rw,
},
0x28 => reg32 brr {
// TODO: not available on STM32F4
// TODO: not available on STM32F411xC/E
// TODO: not available on STM32F205xx et al.
// TODO: not available on STM32F401xB/C et al.
// TODO: not available on STM32F75xxx et al.
// TODO: not available on STM32F446xx
0..15 => br[16] : wo,
16..31 => reserved : ro,
},
0x2c => reg32 ascr {
// TODO: only on STM32L4x6
0..15 => asc[16] : rw,
16..31 => reserved : ro,
}
});
|
#![ feature( optin_builtin_traits ) ]
// Tested:
//
// - ✔ Send message to another thread
// - ✔ Call actor in another thread
// - ✔ Move the future from call to another thread and await it there
mod common;
use
{
futures :: { channel::oneshot } ,
thespis :: { * } ,
log :: { * } ,
thespis_impl :: { * } ,
std :: { thread } ,
common :: { actors::{ Sum, Add, Show } } ,
async_executors :: { AsyncStd } ,
futures :: { executor::block_on } ,
};
async fn sum_send() -> u64
{
let sum = Sum(5);
// Create mailbox
//
let mb : Inbox<Sum> = Inbox::new( Some( "Sum".into() ) );
let mut addr = Addr ::new( mb.sender() );
let mut addr2 = addr.clone();
let mut exec = AsyncStd{};
mb.start( sum, &mut exec ).expect( "Failed to start mailbox" );
thread::spawn( move ||
{
let thread_program = async move
{
addr2.send( Add( 10 ) ).await.expect( "Send failed" );
};
block_on( thread_program );
}).join().expect( "join thread" );
addr.call( Show{} ).await.expect( "Call failed" )
}
async fn sum_call() -> u64
{
let sum = Sum(5);
// Create mailbox
//
let mb : Inbox<Sum> = Inbox::new( Some( "Sum".into() ) );
let mut addr = Addr ::new( mb.sender() );
let mut addr2 = addr.clone();
let mut exec = AsyncStd{};
mb.start( sum, &mut exec ).expect( "Failed to start mailbox" );
let (tx, rx) = oneshot::channel::<()>();
thread::spawn( move ||
{
let thread_program = async move
{
addr2.call( Add( 10 ) ).await.expect( "Call failed" );
};
block_on( thread_program );
tx.send(()).expect( "Signal end of thread" );
});
// TODO: create a way to join threads asynchronously...
//
rx.await.expect( "receive Signal end of thread" );
addr.call( Show{} ).await.expect( "Call failed" )
}
async fn move_call() -> u64
{
let sum = Sum(5);
// Create mailbox
//
let mb : Inbox<Sum> = Inbox::new( Some( "Sum".into() ) );
let mut addr = Addr ::new( mb.sender() );
let mut addr2 = addr.clone();
let mut exec = AsyncStd{};
mb.start( sum, &mut exec ).expect( "Failed to start mailbox" );
let (tx, rx) = oneshot::channel::<()>();
let call_fut = async move { addr2.call( Add( 10 ) ).await.expect( "Call failed" ) };
thread::spawn( move ||
{
let thread_program = async move
{
call_fut.await;
};
block_on( thread_program );
tx.send(()).expect( "Signal end of thread" );
});
// TODO: create a way to join threads asynchronously...
//
rx.await.expect( "receive Signal end of thread" );
addr.call( Show{} ).await.expect( "Call failed" )
}
// Send message to another thread
//
#[test]
//
fn test_basic_send()
{
let program = async move
{
// let _ = simple_logger::init();
trace!( "start program" );
let result = sum_send().await;
trace!( "result is: {}", result );
assert_eq!( 15, result );
};
block_on( program );
}
// Call actor in another thread
//
#[test]
//
fn test_basic_call()
{
let program = async move
{
// let _ = simple_logger::init();
trace!( "start program" );
let result = sum_call().await;
trace!( "result is: {}", result );
assert_eq!( 15, result );
};
block_on( program );
}
// Move the future from call to another thread and await it there
//
#[test]
//
fn test_move_call()
{
let program = async move
{
// let _ = simple_logger::init();
trace!( "start program" );
let result = move_call().await;
trace!( "result is: {}", result );
assert_eq!( 15, result );
};
block_on( program );
}
|
use clap::{Arg, App};
#[derive(Debug, PartialEq)]
pub struct Config {
pub file: String,
}
impl Config {
pub fn new() -> Self {
let matches = App::new("predict")
.version("0.1.0")
.author("Simon Galasso <simon.galasso@hotmail.fr>")
.about("Use save from the learn program to predict the price of a car")
.arg(Arg::with_name("file")
.required(true)
.index(1)
.help("Path to the save file"))
.get_matches();
return Config {
file: matches.value_of("file").unwrap_or("").to_string(),
};
}
} |
use super::{ErrorContext, ErrorKind, MessageType, UnderlyingError};
use std::fmt;
/// An error that occurred in egg-lib
pub struct Error {
kind: ErrorKind,
}
// TODO: A recoverable error - ie a function return that is either a result or a response object, extension to Error trait
impl Error {
// Create a parsing error
pub fn parsing_error(caused_by: Option<UnderlyingError>) -> Error {
Error {
kind: ErrorKind::ParsingError(caused_by, ErrorContext::new()),
}
}
// Create a writing error
pub fn write_error(caused_by: Option<UnderlyingError>) -> Error {
Error {
kind: ErrorKind::WriteFailed(caused_by, ErrorContext::new()),
}
}
// Create a file error
pub fn file_error(caused_by: Option<UnderlyingError>) -> Error {
// TODO: A file error can use the path that caused the problem in a message since it is passed into the error
Error {
kind: ErrorKind::FileOperation(caused_by, ErrorContext::new()),
}
}
// Create a invalid parameter error
pub fn invalid_parameter(caused_by: Option<UnderlyingError>) -> Error {
Error {
kind: ErrorKind::InvalidParameter(caused_by, ErrorContext::new()),
}
}
pub fn repository_not_found() -> Error {
Error {
kind: ErrorKind::RepositoryNotFound(ErrorContext::new()),
}
}
pub fn invalid_repository() -> Error {
Error {
kind: ErrorKind::InvalidRepository(ErrorContext::new()),
}
}
pub fn invalid_state(caused_by: Option<UnderlyingError>) -> Error {
Error {
kind: ErrorKind::InvalidState(caused_by, ErrorContext::new()),
}
}
pub fn invalid_operation(caused_by: Option<UnderlyingError>) -> Error {
Error {
kind: ErrorKind::InvalidOperation(caused_by, ErrorContext::new()),
}
}
}
impl Error {
// TODO: Context should have a state associated with it, if it is for display, debug or both
fn get_context_mut(&mut self) -> &mut ErrorContext {
match self.kind {
ErrorKind::ParsingError(_, ref mut context) => context,
ErrorKind::WriteFailed(_, ref mut context) => context,
ErrorKind::FileOperation(_, ref mut context) => context,
ErrorKind::RepositoryNotFound(ref mut context) => context,
ErrorKind::InvalidRepository(ref mut context) => context,
ErrorKind::InvalidParameter(_, ref mut context) => context,
ErrorKind::InvalidState(_, ref mut context) => context,
ErrorKind::InvalidOperation(_, ref mut context) => context,
}
}
fn get_context(&self) -> &ErrorContext {
match self.kind {
ErrorKind::ParsingError(_, ref context) => context,
ErrorKind::WriteFailed(_, ref context) => context,
ErrorKind::FileOperation(_, ref context) => context,
ErrorKind::RepositoryNotFound(ref context) => context,
ErrorKind::InvalidRepository(ref context) => context,
ErrorKind::InvalidParameter(_, ref context) => context,
ErrorKind::InvalidState(_, ref context) => context,
ErrorKind::InvalidOperation(_, ref context) => context,
}
}
pub fn add_debug_message<S: Into<String>>(mut self, message: S) -> Self {
// TODO: Null Op when debug not set?
let context = self.get_context_mut();
context.add_message(message.into(), MessageType::Debug);
self
}
pub fn add_user_message<S: Into<String>>(mut self, message: S) -> Self {
let context = self.get_context_mut();
context.add_message(message.into(), MessageType::User);
self
}
pub fn add_generic_message<S: Into<String>>(mut self, message: S) -> Self {
let context = self.get_context_mut();
context.add_message(message.into(), MessageType::Both);
self
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.kind).unwrap();
write!(f, "{:?}", self.get_context())
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.kind).unwrap();
write!(f, "{:?}", self.get_context())
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
// Map Option<UnderlyingError> to Option<&(dyn std::error::Error + 'static)>
match self.kind {
ErrorKind::FileOperation(ref error, _) => error.as_ref().map(|e| e.get_error()),
ErrorKind::ParsingError(ref error, _) => error.as_ref().map(|e| e.get_error()),
ErrorKind::WriteFailed(ref error, _) => error.as_ref().map(|e| e.get_error()),
ErrorKind::RepositoryNotFound(_) => None,
ErrorKind::InvalidRepository(_) => None,
ErrorKind::InvalidParameter(ref error, _) => error.as_ref().map(|e| e.get_error()),
ErrorKind::InvalidState(ref error, _) => error.as_ref().map(|e| e.get_error()),
ErrorKind::InvalidOperation(ref error, _) => error.as_ref().map(|e| e.get_error()),
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_basic_error() {
unimplemented!();
}
}
|
use std::convert::TryInto;
use std::ffi::CString;
use std::ptr;
use crate::error::{check_status, Error};
use crate::motherboard_eeprom::MotherboardEeprom;
use crate::range::MetaRange;
use crate::receive_info::ReceiveInfo;
use crate::receive_streamer::ReceiveStreamer;
use crate::stream::{Item, StreamArgs, StreamArgsC};
use crate::string_vector::StringVector;
use crate::utils::copy_string;
use crate::{DaughterBoardEeprom, TimeSpec, TuneRequest, TuneResult};
/// A connection to a USRP device
pub struct Usrp(uhd_sys::uhd_usrp_handle);
impl Usrp {
pub fn find(args: &str) -> Result<Vec<String>, Error> {
let args = CString::new(args)?;
let mut addresses = StringVector::new()?;
check_status(unsafe { uhd_sys::uhd_usrp_find(args.as_ptr(), addresses.handle_mut()) })?;
Ok(addresses.into())
}
/// Opens a connection to a USRP
///
/// args: A string with parameters for the USRP connection. If this is an empty string,
/// one available USRP will be opened with the default settings. Arguments can be specified
/// with the syntax `key=value`, with key-value pairs separated by commas.
///
/// Frequently used arguments:
/// * `addr`: The IP address of the USRP
/// * `type`: The type of the USRP (allowed values include `usrp2` and others)
///
pub fn open(args: &str) -> Result<Self, Error> {
let mut handle: uhd_sys::uhd_usrp_handle = ptr::null_mut();
let args_c = CString::new(args)?;
check_status(unsafe { uhd_sys::uhd_usrp_make(&mut handle, args_c.as_ptr()) })?;
Ok(Usrp(handle))
}
/// Returns a list of registers on this USRP that can be read and written
///
/// mboard: The board number (normally 0 if only one USRP is in use)
pub fn enumerate_registers(&self, mboard: usize) -> Result<Vec<String>, Error> {
let mut vector = StringVector::new()?;
check_status(unsafe {
uhd_sys::uhd_usrp_enumerate_registers(self.0, mboard as _, vector.handle_mut())
})?;
Ok(vector.into())
}
/// Returns the antennas available for transmission
pub fn get_tx_antennas(&self, channel: usize) -> Result<Vec<String>, Error> {
let mut vector = StringVector::new()?;
check_status(unsafe {
uhd_sys::uhd_usrp_get_tx_antennas(self.0, channel as _, vector.handle_mut())
})?;
Ok(vector.into())
}
/// Returns the selected antenna for transmission
pub fn get_tx_antenna(&self, channel: usize) -> Result<String, Error> {
copy_string(|buffer, length| unsafe {
uhd_sys::uhd_usrp_get_tx_antenna(self.0, channel as _, buffer, length as _)
})
}
/// Returns the antennas available for receiving
pub fn get_rx_antennas(&self, channel: usize) -> Result<Vec<String>, Error> {
let mut vector = StringVector::new()?;
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_antennas(self.0, channel as _, vector.handle_mut())
})?;
Ok(vector.into())
}
/// Returns the selected antenna for receiving
pub fn get_rx_antenna(&self, channel: usize) -> Result<String, Error> {
copy_string(|buffer, length| unsafe {
uhd_sys::uhd_usrp_get_rx_antenna(self.0, channel as _, buffer, length as _)
})
}
/// Returns the current receive front-end bandwidth
pub fn get_rx_bandwidth(&self, channel: usize) -> Result<f64, Error> {
let mut value = 0.0;
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_bandwidth(self.0, channel as _, &mut value)
})?;
Ok(value)
}
/// Returns the supported range of receive front-end bandwidth
pub fn get_rx_bandwidth_range(&self, channel: usize) -> Result<MetaRange, Error> {
let mut range = MetaRange::default();
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_bandwidth_range(self.0, channel as _, range.handle())
})?;
Ok(range)
}
/// Returns the current receive frequency
pub fn get_rx_frequency(&self, channel: usize) -> Result<f64, Error> {
let mut value = 0.0;
check_status(unsafe { uhd_sys::uhd_usrp_get_rx_freq(self.0, channel as _, &mut value) })?;
Ok(value)
}
/// Returns the supported range of receive frequencies
pub fn get_rx_frequency_range(&self, channel: usize) -> Result<MetaRange, Error> {
let mut range = MetaRange::default();
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_freq_range(self.0, channel as _, range.handle())
})?;
Ok(range)
}
/// Returns the current gain of the gain element with the specified name
pub fn get_rx_gain(&self, channel: usize, name: &str) -> Result<f64, Error> {
let name = CString::new(name)?;
let mut value = 0.0;
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_gain(self.0, channel as _, name.as_ptr(), &mut value)
})?;
Ok(value)
}
/// Returns the names of controllable gain elements
pub fn get_rx_gain_names(&self, channel: usize) -> Result<Vec<String>, Error> {
let mut names = StringVector::new()?;
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_gain_names(self.0, channel as _, names.handle_mut())
})?;
Ok(names.into())
}
/// Returns the range(s) of gains for a gain element
pub fn get_rx_gain_range(&self, channel: usize, name: &str) -> Result<MetaRange, Error> {
let name = CString::new(name)?;
let mut range = MetaRange::default();
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_gain_range(self.0, name.as_ptr(), channel as _, range.handle())
})?;
Ok(range)
}
/// Clears the command time (?), causing stream commands to be sent immediately
pub fn clear_command_time(&self, mboard: usize) -> Result<(), Error> {
check_status(unsafe { uhd_sys::uhd_usrp_clear_command_time(self.0, mboard as _) })
}
/// Gets the ranges of front-end frequencies for a receive channel
pub fn get_fe_rx_freq_range(&self, channel: usize) -> Result<MetaRange, Error> {
let mut range = MetaRange::default();
check_status(unsafe {
uhd_sys::uhd_usrp_get_fe_rx_freq_range(self.0, channel as _, range.handle())
})?;
Ok(range)
}
/// Gets the ranges of front-end frequencies for a transmit channel
pub fn get_fe_tx_freq_range(&self, channel: usize) -> Result<MetaRange, Error> {
let mut range = MetaRange::default();
check_status(unsafe {
uhd_sys::uhd_usrp_get_fe_tx_freq_range(self.0, channel as _, range.handle())
})?;
Ok(range)
}
/// Returns the frequency of the master clock
pub fn get_master_clock_rate(&self, mboard: usize) -> Result<f64, Error> {
let mut rate = 0.0;
check_status(unsafe {
uhd_sys::uhd_usrp_get_master_clock_rate(self.0, mboard as _, &mut rate)
})?;
Ok(rate)
}
/// Returns the name of the motherboard
pub fn get_motherboard_name(&self, mboard: usize) -> Result<String, Error> {
copy_string(|buffer, length| unsafe {
uhd_sys::uhd_usrp_get_mboard_name(self.0, mboard as _, buffer, length as _)
})
}
/// Returns the transmit gain, normalized to [0, 1]
pub fn get_normalized_tx_gain(&self, channel: usize) -> Result<f64, Error> {
let mut value = 0.0;
check_status(unsafe {
uhd_sys::uhd_usrp_get_normalized_tx_gain(self.0, channel as _, &mut value)
})?;
Ok(value)
}
/// Returns the receive gain, normalized to [0, 1]
pub fn get_normalized_rx_gain(&self, channel: usize) -> Result<f64, Error> {
let mut value = 0.0;
check_status(unsafe {
uhd_sys::uhd_usrp_get_normalized_rx_gain(self.0, channel as _, &mut value)
})?;
Ok(value)
}
/// Returns the number of motherboards that this Usrp object provides access to
pub fn get_num_motherboards(&self) -> Result<usize, Error> {
let mut value = 0usize;
check_status(unsafe {
uhd_sys::uhd_usrp_get_num_mboards(self.0, &mut value as *mut usize as *mut _)
})?;
Ok(value)
}
/// Returns the number of transmit channels
pub fn get_num_tx_channels(&self) -> Result<usize, Error> {
let mut value = 0usize;
check_status(unsafe {
uhd_sys::uhd_usrp_get_tx_num_channels(self.0, &mut value as *mut usize as *mut _)
})?;
Ok(value)
}
/// Returns the number of receive channels
pub fn get_num_rx_channels(&self) -> Result<usize, Error> {
let mut value = 0usize;
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_num_channels(self.0, &mut value as *mut usize as *mut _)
})?;
Ok(value)
}
/// Writes a user register on the USRP
///
/// address: The address of the register
/// value: The value to write
/// mboard: The index of the board to write to (normally 0 when there is only one USRP)
pub fn set_user_register(&self, address: u8, value: u32, mboard: usize) -> Result<(), Error> {
check_status(unsafe {
uhd_sys::uhd_usrp_set_user_register(self.0, address, value, mboard as _)
})
}
/// Returns the current clock source
pub fn get_clock_source(&self, mboard: usize) -> Result<String, Error> {
copy_string(|buffer, length| unsafe {
uhd_sys::uhd_usrp_get_clock_source(self.0, mboard as _, buffer, length as _)
})
}
/// Returns the available clock sources
pub fn get_clock_sources(&self, mboard: usize) -> Result<Vec<String>, Error> {
let mut vector = StringVector::new()?;
check_status(unsafe {
uhd_sys::uhd_usrp_get_clock_sources(self.0, mboard as _, vector.handle_mut())
})?;
Ok(vector.into())
}
/// Returns the available sensors on the motherboard
pub fn get_mboard_sensor_names(&self, mboard: usize) -> Result<Vec<String>, Error> {
let mut vector = StringVector::new()?;
check_status(unsafe {
uhd_sys::uhd_usrp_get_mboard_sensor_names(self.0, mboard as _, vector.handle_mut())
})?;
Ok(vector.into())
}
/// Returns the values stored in the motherboard EEPROM
pub fn get_motherboard_eeprom(&self, mboard: usize) -> Result<MotherboardEeprom, Error> {
let mut eeprom = MotherboardEeprom::default();
check_status(unsafe {
uhd_sys::uhd_usrp_get_mboard_eeprom(self.0, eeprom.handle(), mboard as _)
})?;
Ok(eeprom)
}
/// Returns the values stored in a daughter board EEPROM
///
/// Values for unit and slot can be determined by running uhd_usrp_probe --tree.
/// As an example, the entry `/mboards/0/dboards/A/rx_eeprom` corresponds to unit `rx` and
/// slot `A` of mboard 1.
pub fn get_daughter_board_eeprom(
&self,
unit: &str,
slot: &str,
mboard: usize,
) -> Result<DaughterBoardEeprom, Error> {
let unit = CString::new(unit)?;
let slot = CString::new(slot)?;
let mut eeprom = DaughterBoardEeprom::default();
check_status(unsafe {
uhd_sys::uhd_usrp_get_dboard_eeprom(
self.0,
eeprom.handle(),
unit.as_ptr(),
slot.as_ptr(),
mboard as _,
)
})?;
Ok(eeprom)
}
/// Gets information about the receive configuration of a channel
pub fn get_rx_info(&self, channel: usize) -> Result<ReceiveInfo, Error> {
let mut info_c = uhd_sys::uhd_usrp_rx_info_t {
mboard_id: ptr::null_mut(),
mboard_name: ptr::null_mut(),
mboard_serial: ptr::null_mut(),
rx_id: ptr::null_mut(),
rx_subdev_name: ptr::null_mut(),
rx_subdev_spec: ptr::null_mut(),
rx_serial: ptr::null_mut(),
rx_antenna: ptr::null_mut(),
};
unsafe {
check_status(uhd_sys::uhd_usrp_get_rx_info(
self.0,
channel as _,
&mut info_c,
))?;
let info = ReceiveInfo::from_c(&info_c)?;
uhd_sys::uhd_usrp_rx_info_free(&mut info_c);
Ok(info)
}
}
/// Returns true if the provided local oscillator is exported
pub fn get_rx_lo_export_enabled(&self, channel: usize, name: &str) -> Result<bool, Error> {
let name = CString::new(name)?;
let mut enabled = false;
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_lo_export_enabled(
self.0,
name.as_ptr(),
channel as _,
&mut enabled,
)
})?;
Ok(enabled)
}
/// Returns the frequency of a local oscillator
pub fn get_rx_lo_frequency(&self, channel: usize, name: &str) -> Result<f64, Error> {
let name = CString::new(name)?;
let mut value = 0.0;
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_lo_freq(self.0, name.as_ptr(), channel as _, &mut value)
})?;
Ok(value)
}
/// Returns the names of local oscillators
pub fn get_rx_lo_names(&self, channel: usize) -> Result<Vec<String>, Error> {
let mut vector = StringVector::new()?;
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_lo_names(self.0, channel as _, vector.handle_mut())
})?;
Ok(vector.into())
}
/// Returns the names of sensors that relate to receiving
pub fn get_rx_sensor_names(&self, channel: usize) -> Result<Vec<String>, Error> {
let mut vector = StringVector::new()?;
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_sensor_names(self.0, channel as _, vector.handle_mut())
})?;
Ok(vector.into())
}
/// Opens a stream that can be used to receive samples
pub fn get_rx_stream<I>(&self, args: &StreamArgs<I>) -> Result<ReceiveStreamer<'_, I>, Error>
where
I: Item,
{
// Convert arguments
let args: StreamArgsC = args.try_into()?;
// Convert some *T pointers to *mut T pointers. The C API doesn't mark them const, but
// appears to not write to them.
let mut args_c = uhd_sys::uhd_stream_args_t {
cpu_format: args.host_format.as_ptr() as *mut _,
otw_format: args.wire_format.as_ptr() as *mut _,
args: args.args.as_ptr() as *mut _,
channel_list: args.channels.as_ptr() as *mut _,
n_channels: args
.channels
.len()
.try_into()
.expect("Number of channels too large"),
};
// Create a streamer
let mut streamer = ReceiveStreamer::new();
check_status(unsafe { uhd_sys::uhd_rx_streamer_make(streamer.handle_mut()) })?;
// Associate streamer with USRP
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_stream(self.0, &mut args_c, streamer.handle())
})?;
Ok(streamer)
}
/// Returns the current receive sample rate in samples/second
pub fn get_rx_sample_rate(&self, channel: usize) -> Result<f64, Error> {
let mut value = 0.0;
check_status(unsafe { uhd_sys::uhd_usrp_get_rx_rate(self.0, channel as _, &mut value) })?;
Ok(value)
}
/// Returns the ranges of supported sample rates
pub fn get_rx_sample_rates(&self, channel: usize) -> Result<MetaRange, Error> {
let mut range = MetaRange::new();
check_status(unsafe {
uhd_sys::uhd_usrp_get_rx_rates(self.0, channel as _, range.handle())
})?;
Ok(range)
}
/// Returns the USRP's current time. Commands can be scheduled relative to this time.
pub fn get_current_time(&self, mboard: usize) -> Result<TimeSpec, Error> {
let mut time = TimeSpec::default();
let mut seconds_time_t: libc::time_t = Default::default();
check_status(unsafe {
uhd_sys::uhd_usrp_get_time_now(
self.0,
mboard as _,
&mut seconds_time_t,
&mut time.fraction,
)
})?;
time.seconds = seconds_time_t.into();
Ok(time)
}
/// Enables or disables the receive automatic gain control
pub fn set_rx_agc_enabled(&self, enabled: bool, channel: usize) -> Result<(), Error> {
check_status(unsafe { uhd_sys::uhd_usrp_set_rx_agc(self.0, enabled, channel as _) })
}
/// Sets the antenna used to receive
pub fn set_rx_antenna(&self, antenna: &str, channel: usize) -> Result<(), Error> {
let antenna = CString::new(antenna)?;
check_status(unsafe {
uhd_sys::uhd_usrp_set_rx_antenna(self.0, antenna.as_ptr(), channel as _)
})
}
/// Sets the receive bandwidth
pub fn set_rx_bandwidth(&self, bandwidth: f64, channel: usize) -> Result<(), Error> {
check_status(unsafe { uhd_sys::uhd_usrp_set_rx_bandwidth(self.0, bandwidth, channel as _) })
}
/// Enables or disables DC offset correction
pub fn set_rx_dc_offset_enabled(&self, enabled: bool, channel: usize) -> Result<(), Error> {
check_status(unsafe {
uhd_sys::uhd_usrp_set_rx_dc_offset_enabled(self.0, enabled, channel as _)
})
}
/// Sets the receive center frequency
pub fn set_rx_frequency(
&self,
request: &TuneRequest,
channel: usize,
) -> Result<TuneResult, Error> {
let args = CString::new(&*request.args)?;
let mut request_c = uhd_sys::uhd_tune_request_t {
target_freq: request.target_frequency,
rf_freq_policy: request.rf.c_policy(),
rf_freq: request.rf.frequency(),
dsp_freq_policy: request.dsp.c_policy(),
dsp_freq: request.dsp.frequency(),
// Unsafe cast *const c_char to *mut c_char
// The C++ code probably won't modify this.
args: args.as_ptr() as *mut _,
};
let mut result = TuneResult::default();
check_status(unsafe {
uhd_sys::uhd_usrp_set_rx_freq(self.0, &mut request_c, channel as _, result.inner_mut())
})?;
Ok(result)
}
/// Sets the receive gain
pub fn set_rx_gain(&self, gain: f64, channel: usize, name: &str) -> Result<(), Error> {
let name = CString::new(name)?;
check_status(unsafe {
uhd_sys::uhd_usrp_set_rx_gain(self.0, gain, channel as _, name.as_ptr())
})
}
/// Sets the receive sample rate
pub fn set_rx_sample_rate(&self, rate: f64, channel: usize) -> Result<(), Error> {
check_status(unsafe { uhd_sys::uhd_usrp_set_rx_rate(self.0, rate, channel as _) })
}
/// Sets the antenna used to transmit
pub fn set_tx_antenna(&self, antenna: &str, channel: usize) -> Result<(), Error> {
let antenna = CString::new(antenna)?;
check_status(unsafe {
uhd_sys::uhd_usrp_set_tx_antenna(self.0, antenna.as_ptr(), channel as _)
})
}
/// Returns the available GPIO banks
pub fn get_gpio_banks(&self, mboard: usize) -> Result<Vec<String>, Error> {
let mut banks = StringVector::new()?;
check_status(unsafe {
uhd_sys::uhd_usrp_get_gpio_banks(self.0, mboard as _, banks.handle_mut())
})?;
Ok(banks.into())
}
}
impl Drop for Usrp {
fn drop(&mut self) {
// Ignore error (what errors could really happen that can be handled?)
let _ = unsafe { uhd_sys::uhd_usrp_free(&mut self.0) };
}
}
// Thread safety: see https://files.ettus.com/manual/page_general.html#general_threading
// All functions associated with the Usrp struct are thread-safe
unsafe impl Send for Usrp {}
unsafe impl Sync for Usrp {}
|
use std::cmp::max;
use std;
use num;
use crate::prelude::*;
pub const SHADOW_EPSILON: f32 = 0.0001;
pub const MACHINE_EPSILON: f32 = std::f32::EPSILON * 0.5;
#[inline(always)]
pub const fn gamma(n: i32) -> f32 {
(n as f32 * MACHINE_EPSILON) / (1.0 - n as f32 * MACHINE_EPSILON)
}
#[inline(always)]
pub fn gammaf(n: i32) -> Float {
float(gamma(n))
}
#[inline(always)]
#[cfg_attr(feature = "cargo-clippy", allow(unreadable_literal))]
pub fn gamma_correct(value: Float) -> Float {
if value <= 0.0031308 {
float(2.92) * value
} else {
float(1.055) * value.powf(float(1.0 / 2.4)) - float(0.055)
}
}
#[inline(always)]
pub fn f32_to_bits(f: impl Into<f32>) -> u32 {
let f: f32 = f.into();
f.to_bits()
}
#[inline(always)]
pub fn bits_to_f32(u: u32) -> f32 {
f32::from_bits(u)
}
#[inline(always)]
pub fn next_float_up_f(v: impl Into<f32>) -> Float {
float(next_float_up(v))
}
#[inline(always)]
pub fn next_float_down_f(v: impl Into<f32>) -> Float {
float(next_float_down(v))
}
#[inline(always)]
pub fn next_float_up(v: impl Into<f32>) -> f32 {
let mut v: f32 = v.into();
if v.is_infinite() && v > 0.0 {
return v;
}
if v == -0.0 {
v = 0.0;
}
let mut ui = f32_to_bits(v);
if v >= 0.0 {
ui += 1;
} else {
ui -= 1;
}
bits_to_f32(ui)
}
#[inline(always)]
pub fn next_float_down(v: impl Into<f32>) -> f32 {
let mut v: f32 = v.into();
if v.is_infinite() && v < 0.0 {
return v;
}
if v == 0.0 {
v = -0.0;
}
let mut ui = f32_to_bits(v);
if v > 0.0 {
ui -= 1;
} else {
ui += 1;
}
bits_to_f32(ui)
}
pub fn solve_linear_system_2x2(a: [[Float; 2]; 2], b: [Float; 2]) -> Option<(Float, Float)> {
let det = a[0][0] * a[1][1] - a[0][1] * a[1][0];
if det.abs() < 1e-10 {
return None;
}
let det = det.raw();
let x0 = (a[1][1] * b[0] - a[0][1] * b[1]).raw() / det;
let x1 = (a[0][0] * b[1] - a[1][0] * b[0]).raw() / det;
if x0.is_nan() || x1.is_nan() {
return None;
}
Some((float(x0), float(x1)))
}
pub fn find_interval(size: usize, predicate: impl Fn(usize) -> bool) -> usize {
let mut first = 0;
let mut len = size;
while len > 0 {
let half = len >> 1;
let middle = first + half;
if predicate(middle) {
first = middle + 1;
len -= half + 1;
} else {
len = half;
}
}
num::clamp(first - 1, 0, size - 2)
}
/// this code is originally from (Mokosha's PBRT)[https://github.com/Mokosha/pbrt_rust/blob/75bae9cfbbc32d112d93c0e15841af36e550ec21/src/utils/mod.rs#L122]
pub fn partition_by<T, B: Copy + PartialOrd>(v: &mut [T], f: impl Fn(&T) -> B) {
let nv = v.len();
if nv < 3 {
if nv == 2 && f(&v[1]) < f(&v[0]) {
v.swap(0, 1);
}
return;
}
let pivot = {
// Median of three...
let fst = f(&v[0]);
let mid = f(&v[nv / 2]);
let lst = f(&v[nv - 1]);
if fst < mid && mid < lst {
mid
} else if mid < fst && fst < lst {
fst
} else {
lst
}
};
let mut last_smaller = 0;
let mut num_pivots = 0;
for i in 0..nv {
let bv = f(&v[i]);
if bv < pivot {
v.swap(last_smaller + num_pivots, i);
v.swap(last_smaller + num_pivots, last_smaller);
last_smaller += 1;
} else if bv == pivot {
v.swap(last_smaller + num_pivots, i);
num_pivots += 1;
}
}
let mut pivot_idx = last_smaller;
// We can do this because if pivot_idx == 0, then all
// of the values are larger than the pivot...
pivot_idx = max(pivot_idx, 1);
let (left, right) = v.split_at_mut(pivot_idx);
debug_assert!(!right.is_empty());
debug_assert!(!left.is_empty());
if pivot_idx + num_pivots <= (nv / 2) {
partition_by(right, f);
} else if pivot_idx >= (nv / 2) {
partition_by(left, f);
}
}
|
use tendermint_rpc::Address;
#[cfg(feature = "integration")]
use tendermint_rpc::{endpoints::Status, jsonrpc::Request};
/// Get the address of the local node
pub fn localhost_rpc_addr() -> Address {
"tcp://127.0.0.1:26657".parse().unwrap()
}
// TODO(tarcieri): chunked encoding support
// `/net_info` endpoint integration test
// #[cfg(feature = "integration")]
// #[test]
// fn net_info_integration() {
// let net_info = NetInfo.perform(&localhost_rpc_addr()).unwrap();
// assert!(net_info.listening);
// }
/// `/status` endpoint integration test
#[cfg(feature = "integration")]
#[test]
fn status_integration() {
let status = Status.perform(&localhost_rpc_addr()).unwrap();
// For lack of better things to test
assert_eq!(
status.validator_info.voting_power.value(),
0,
"don't integration test against a validator"
);
}
|
use futures::try_ready;
use log::{debug, error, info};
#[cfg(unix)]
use nix::sys::statvfs::{statvfs, Statvfs};
use std::fs::{self, DirEntry, Metadata};
use std::io;
use std::path::{Path, PathBuf};
#[cfg(windows)]
use std::ptr::null_mut;
use std::time::{Duration, Instant, SystemTime};
use tokio::prelude::*;
use tokio::timer::{Error as TimerError, Interval};
const FREE_SPACE_LOWER_THRESHOLD: f32 = 0.1;
const FREE_SPACE_UPPER_THRESHOLD: f32 = 0.15;
#[derive(Debug)]
struct SpaceData {
available: u64,
total: u64,
}
impl SpaceData {
fn bytes_to_gc(&self) -> Option<u64> {
if self.available as f32 / self.total as f32 > FREE_SPACE_LOWER_THRESHOLD {
return None;
}
let desired = (self.total as f32 * FREE_SPACE_UPPER_THRESHOLD) as u64;
debug_assert!(desired > self.available);
Some(desired - self.available)
}
}
#[cfg(unix)]
impl From<Statvfs> for SpaceData {
#[allow(clippy::identity_conversion)]
fn from(source: Statvfs) -> Self {
Self {
available: u64::from(source.blocks_available()) * source.fragment_size(),
total: u64::from(source.blocks()) * source.fragment_size(),
}
}
}
#[cfg(unix)]
fn get_fs_data(directory: &Path) -> Result<SpaceData, io::Error> {
Ok(statvfs(directory)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?
.into())
}
#[cfg(windows)]
fn get_fs_data(directory: &Path) -> Result<SpaceData, io::Error> {
use widestring::U16CString;
use winapi::shared::minwindef::FALSE;
use winapi::um::{errhandlingapi::GetLastError, fileapi, winnt::ULARGE_INTEGER};
let wstr = U16CString::from_os_str(directory.as_os_str()).unwrap();
let mut avail: ULARGE_INTEGER = Default::default();
let mut total: ULARGE_INTEGER = Default::default();
if unsafe {
fileapi::GetDiskFreeSpaceExW(wstr.as_ptr(), &mut avail as *mut _, &mut total as *mut _, null_mut())
} == FALSE
{
return Err(io::Error::new(
io::ErrorKind::Other,
format!("OS Error: {}", unsafe { GetLastError() }),
));
}
Ok(SpaceData {
available: *unsafe { avail.QuadPart() },
total: *unsafe { total.QuadPart() },
})
}
pub struct UsageMonitor {
interval: Interval,
archive_dir: PathBuf,
}
fn get_entries_with_metadata(directory: &Path) -> Result<Vec<(DirEntry, Option<Metadata>)>, io::Error> {
let readdir = fs::read_dir(directory)?;
let mut result: Vec<(DirEntry, Option<Metadata>)> = Vec::with_capacity(readdir.size_hint().1.unwrap_or(0));
for entry_result in readdir {
match entry_result {
Ok(entry) => {
let metadata = entry
.metadata()
.map_err(|e| error!("Error reading the metadata of {}: {}", entry.path().display(), e))
.ok();
result.push((entry, metadata));
}
Err(e) => error!("Error reading a directory entry: {}", e),
}
}
Ok(result)
}
impl UsageMonitor {
pub fn new(base_dir: &Path) -> Self {
let interval = Interval::new(Instant::now(), Duration::from_secs(60));
UsageMonitor {
interval,
archive_dir: base_dir.join("archived"),
}
}
fn garbage_collect(&self) -> Result<(), io::Error> {
if !self.archive_dir.exists() {
debug!("Archive dir does not exist");
return Ok(());
}
let fs_data = get_fs_data(&self.archive_dir)?;
debug!("Filesytem information: {:?}", fs_data);
if let Some(mut bytes_to_gc) = fs_data.bytes_to_gc() {
debug!("Need to clean {} bytes", bytes_to_gc);
let archived_files = {
let mut l = get_entries_with_metadata(&self.archive_dir)?;
let now = SystemTime::now();
l.sort_by(|a, b| {
let a_mtime = a.1.as_ref().and_then(|m| m.modified().ok()).unwrap_or(now);
let b_mtime = b.1.as_ref().and_then(|m| m.modified().ok()).unwrap_or(now);
a_mtime.cmp(&b_mtime)
});
l
};
for (entry, metadata) in archived_files
.into_iter()
.filter_map(|(entry, metadata)| metadata.map(|m| (entry, m)))
{
info!(
"Deleting {} to free up {} bytes",
entry.path().display(),
metadata.len()
);
match fs::remove_file(entry.path()) {
Ok(()) => {
if let Some(result) = bytes_to_gc.checked_sub(metadata.len()) {
bytes_to_gc = result;
} else {
debug!("Freed enough space");
}
}
Err(e) => {
error!("Cannot remove {}: {}", entry.path().display(), e);
}
}
}
} else {
debug!("No need for GC");
}
Ok(())
}
}
impl Future for UsageMonitor {
type Item = ();
type Error = TimerError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
try_ready!(self.interval.poll()).unwrap();
self.garbage_collect()
.map_err(|e| error!("Disk usage monitor error: {}", e))
.ok();
}
}
}
|
use indexmap::IndexMap;
use std::collections::HashSet;
use syn::{Error, Result, Ident};
use super::component::{Child, Component};
use super::{AllComponents, AllUniques, TypeId};
#[derive(Debug)]
pub struct Unique {
pub id: TypeId,
pub name: String,
pub r#type: Ident,
pub children: Vec<Child>,
}
impl Unique {
pub fn try_into_unique_list(
v: Vec<crate::parsing::unique::Unique>,
all: &AllComponents,
) -> Result<AllUniques> {
let mut list = IndexMap::with_capacity(v.len());
let mut duplicate_check_list = HashSet::with_capacity(v.len());
// Find all the listed components
for c in &v {
let children = Vec::with_capacity(c.children.len());
let id = c.id.unwrap(); //Can this fail? if so, it should be an internal error...
let name = c.r#type.to_string();
if !duplicate_check_list.insert(c.r#type.clone()) {
return Err(Error::new(
c.r#type.span(),
"Duplicate Unique types are not allowed; use the Newtype pattern instead.",
));
}
list.insert(
id,
Self {
id,
r#type: c.r#type.clone(),
children,
name,
},
);
}
// Register all child components and find their component ids
for comp in v {
for child in &comp.children {
let id = match Component::search_component(&child.r#type, all) {
Some(id) => id,
None => {
return Err(Error::new(
child.r#type.span(),
&format!("{} is not registered as a Component.", &child.r#type),
));
}
};
let child_type = child.child_type.into();
list.get_mut(&comp.id.unwrap())
.as_mut()
.unwrap()
.children
.push(Child {
id,
child_type,
span: child.r#type.span(),
});
}
}
Ok(list)
}
pub fn search_component(typ: &Ident, list: &AllComponents) -> Option<TypeId> {
list.iter()
.find_map(|(k, v)| (*typ == v.r#type).then(|| *k))
}
}
|
use axum::{extract, prelude::*, response};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
pub struct BeaconData {
date: String,
os: OSType,
r#type: String,
beacons: Vec<Beacon>,
}
#[derive(Deserialize)]
pub struct Beacon {
uuid: String,
major: i64,
minor: i64,
rssi: f64,
distance: f64,
}
#[derive(Deserialize)]
pub enum OSType {
a,
i,
w,
m,
}
impl OSType {
fn check(&self) -> String {
let result = match self {
OSType::a => "a",
OSType::i => "i",
OSType::w => "w",
OSType::m => "m",
};
result.to_string()
}
}
#[derive(Serialize)]
pub struct BeaconResult {
date: String,
os: String,
r#type: String,
beacons: Vec<String>,
}
pub async fn get_beacon_data(
extract::Json(get_beacon_data): extract::Json<BeaconData>,
) -> response::Json<BeaconResult> {
let beacon_data = get_beacon_data;
if beacon_data.beacons.len() == 0 {
return response::Json(BeaconResult {
date: beacon_data.date,
os: beacon_data.os.check(),
beacons: vec!["".to_string()],
r#type: beacon_data.r#type,
});
}
let beacon_id = beacon_data
.beacons
.iter()
.map(|item| {
(&item.uuid).to_string() + ":" + &item.major.to_string() + ":" + &item.minor.to_string()
})
.collect::<Vec<String>>();
response::Json(BeaconResult {
date: beacon_data.date,
os: beacon_data.os.check(),
beacons: beacon_id,
r#type: beacon_data.r#type,
})
}
|
use async_graphql::{value, EmptyMutation, EmptySubscription, Interface, Object, SimpleObject};
use async_graphql_relay::{RelayContext, RelayGlobalID, RelayNodeEnum};
#[derive(RelayGlobalID)]
pub struct ID(pub String, pub SchemaNodeTypes);
#[derive(Interface, RelayNodeEnum)]
#[graphql(field(name = "id", type = "String"))]
pub enum Node {
User(User),
Tenant(Tenant),
}
#[derive(SimpleObject)]
pub struct User {
pub id: ID,
pub name: String,
}
impl User {
pub async fn get(ctx: RelayContext, id: String) -> Option<Node> {
let ctx_str = ctx.get::<String>().unwrap();
if id != "92ba0c2d-4b4e-4e29-91dd-8f96a078c3ff".to_string()
|| *ctx_str != "ThisIsInTheContext".to_string()
{
None?
}
Some(
User {
id: ID(id, SchemaNodeTypes::User),
name: "Oscar".to_string(),
}
.into(),
)
}
}
#[derive(SimpleObject)]
pub struct Tenant {
pub id: ID,
pub description: String,
}
impl Tenant {
pub async fn get(ctx: RelayContext, id: String) -> Option<Node> {
let ctx_str = ctx.get::<String>().unwrap();
if id != "14b4a5db-b8f0-4bf9-881e-37a9e0d0ae3h".to_string()
|| *ctx_str != "ThisIsInTheContext".to_string()
{
None?
}
Some(
Tenant {
id: ID(id, SchemaNodeTypes::Tenant),
description: "My Company".to_string(),
}
.into(),
)
}
}
pub type Schema = async_graphql::Schema<QueryRoot, EmptyMutation, EmptySubscription>;
pub struct QueryRoot;
#[Object]
impl QueryRoot {
async fn user(&self) -> User {
User {
id: ID(
"92ba0c2d-4b4e-4e29-91dd-8f96a078c3ff".to_string(),
SchemaNodeTypes::User,
),
name: "Oscar".to_string(),
}
}
async fn tenant(&self) -> Tenant {
Tenant {
id: ID(
"14b4a5db-b8f0-4bf9-881e-37a9e0d0ae3h".to_string(),
SchemaNodeTypes::Tenant,
),
description: "My Company".to_string(),
}
}
async fn node(&self, id: String) -> Option<Node> {
let ctx = RelayContext::new::<String>("ThisIsInTheContext".to_string());
Node::get(ctx, id).await
}
}
fn schema() -> Schema {
Schema::new(QueryRoot, EmptyMutation, EmptySubscription)
}
#[tokio::test]
async fn test_user_query() {
let query = "{ user { id, name } }";
assert_eq!(
schema().execute(query).await.data,
value!({
"user": {
"id": "92ba0c2d4b4e4e2991dd8f96a078c3ff1",
"name": "Oscar",
},
})
);
}
#[tokio::test]
async fn test_user_node_query() {
let query = "{ node(id: \"92ba0c2d4b4e4e2991dd8f96a078c3ff1\") { id, ... on User { name } } }";
assert_eq!(
schema().execute(query).await.data,
value!({
"node": {
"id": "92ba0c2d4b4e4e2991dd8f96a078c3ff1",
"name": "Oscar",
},
})
);
}
#[tokio::test]
async fn test_tenant_query() {
let query = "{ tenant { id, description } }";
assert_eq!(
schema().execute(query).await.data,
value!({
"tenant": {
"id": "14b4a5dbb8f04bf9881e37a9e0d0ae3h2",
"description": "My Company",
},
})
);
}
#[tokio::test]
async fn test_tenant_node_query() {
let query =
"{ node(id: \"14b4a5dbb8f04bf9881e37a9e0d0ae3h2\") { id, ... on Tenant { description } } }";
assert_eq!(
schema().execute(query).await.data,
value!({
"node": {
"id": "14b4a5dbb8f04bf9881e37a9e0d0ae3h2",
"description": "My Company",
},
})
);
}
#[tokio::test]
async fn test_tenant_invalid_short_relay_id() {
let query = "{ node(id: \"invalid\") { id } }";
assert_eq!(
schema().execute(query).await.data,
value!({
"node": null,
})
);
}
#[tokio::test]
async fn test_tenant_invalid_long_relay_id() {
let query =
"{ node(id: \"2b0669af44fb4949bed4d7786cc0164b2b0669af44fb4949bed4d7786cc0164b\") { id } }";
assert_eq!(
schema().execute(query).await.data,
value!({
"node": null,
})
);
}
|
use rand::Rng;
pub struct Obstacles {
// tuple vec of objects one for the top and one for the bottom
pub obstacles: Vec<(i32, i32)>,
// how frequently we want each to be created
pub frequency_values: Vec<usize>,
}
// randomly picks a pair of obstacles to generate
impl Obstacles {
pub fn generate_obstacles(&self) -> (i32, i32) {
let freq_total: usize = self.frequency_values.iter().sum();
let mut rng = rand::thread_rng();
let mut x: i32 = rng.gen_range((0 as i32)..(freq_total as i32));
for (f_vals, obs) in self.frequency_values.iter().zip(self.obstacles.iter()) {
x -= *f_vals as i32;
if x < 0 {
return *obs;
}
}
self.obstacles[self.obstacles.len() - 1]
}
}
|
use std::mem;
pub fn run(){
let mut number: Vec<i32> = vec![1, 2, 3, 4, 5];
// Re-assign Value
number[3] = 43;
// Add to vector
number.push(5);
number.push(6);
number.push(7);
// Get the length of a vetor
println!("The length of the vector {}", number.len() );
// Vector are stack allocated
println!("This vector occupied {} bytes", mem::size_of_val(&number) );
// Get slice
let slice: &[i32] = &number[0..2];
println!("{:?}", slice );
for item in number.iter() {
println!("Number {}", item);
}
for item in number.iter_mut() {
*item *= 2;
}
println!("The value {:?}", number);
} |
use diesel::prelude::*;
use crate::storage::db::models;
use crate::storage::db::schema;
pub fn create_user(conn: &SqliteConnection, user: models::NewUser) {
diesel::insert_into(schema::users::table)
.values(&user)
.execute(conn)
.expect("error creating new user");
}
pub fn get_user_from_name(conn: &SqliteConnection, name: &String) -> QueryResult<models::User> {
use schema::users::dsl::*;
users.filter(username.eq(name))
.get_result::<models::User>(conn)
}
pub fn get_user_from_id(conn: &SqliteConnection, uid: i32) -> QueryResult<models::User> {
use schema::users::dsl::*;
users.filter(id.eq(uid))
.get_result::<models::User>(conn)
} |
//! Derive `NumBytes`.
use crate::proc_macro::TokenStream;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use syn::{
parse_macro_input, parse_quote, Data, DeriveInput, Fields, GenericParam,
Index,
};
/// Expand input
pub fn expand(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let root = crate::root_path(&input);
let name = input.ident;
let mut generics = input.generics;
for param in &mut generics.params {
if let GenericParam::Type(ref mut type_param) = *param {
type_param.bounds.push(parse_quote!(NumBytes));
}
}
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let call_site = ::proc_macro2::Span::call_site();
let var = quote!(self);
let add_to_count = match input.data {
Data::Struct(ref data) => match data.fields {
Fields::Named(ref fields) => {
let recurse = fields.named.iter().map(|f| {
let name = &f.ident;
let access = quote_spanned!(call_site => #var.#name);
quote_spanned! { f.span() =>
count += #root::NumBytes::num_bytes(&#access);
}
});
quote! {
#(#recurse)*
}
}
Fields::Unnamed(ref fields) => {
let recurse =
fields.unnamed.iter().enumerate().map(|(i, f)| {
let index = Index {
index: i as u32,
span: call_site,
};
let access = quote_spanned!(call_site => #var.#index);
quote_spanned! { f.span() =>
count += #root::NumBytes::num_bytes(&#access);
}
});
quote! {
#(#recurse)*
}
}
Fields::Unit => {
quote! {}
}
},
Data::Enum(_) | Data::Union(_) => unimplemented!(),
};
let expanded = quote! {
#[automatically_derived]
#[allow(unused_qualifications)]
impl #impl_generics #root::NumBytes for #name #ty_generics #where_clause {
#[inline]
fn num_bytes(&self) -> usize {
let mut count = 0;
#add_to_count
count
}
}
};
TokenStream::from(expanded)
}
|
#[doc = "Register `SPI2S_IFCR` writer"]
pub type W = crate::W<SPI2S_IFCR_SPEC>;
#[doc = "Field `EOTC` writer - EOTC"]
pub type EOTC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TXTFC` writer - TXTFC"]
pub type TXTFC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UDRC` writer - UDRC"]
pub type UDRC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OVRC` writer - OVRC"]
pub type OVRC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CRCEC` writer - CRCEC"]
pub type CRCEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIFREC` writer - TIFREC"]
pub type TIFREC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `MODFC` writer - MODFC"]
pub type MODFC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TSERFC` writer - TSERFC"]
pub type TSERFC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SUSPC` writer - SUSPC"]
pub type SUSPC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl W {
#[doc = "Bit 3 - EOTC"]
#[inline(always)]
#[must_use]
pub fn eotc(&mut self) -> EOTC_W<SPI2S_IFCR_SPEC, 3> {
EOTC_W::new(self)
}
#[doc = "Bit 4 - TXTFC"]
#[inline(always)]
#[must_use]
pub fn txtfc(&mut self) -> TXTFC_W<SPI2S_IFCR_SPEC, 4> {
TXTFC_W::new(self)
}
#[doc = "Bit 5 - UDRC"]
#[inline(always)]
#[must_use]
pub fn udrc(&mut self) -> UDRC_W<SPI2S_IFCR_SPEC, 5> {
UDRC_W::new(self)
}
#[doc = "Bit 6 - OVRC"]
#[inline(always)]
#[must_use]
pub fn ovrc(&mut self) -> OVRC_W<SPI2S_IFCR_SPEC, 6> {
OVRC_W::new(self)
}
#[doc = "Bit 7 - CRCEC"]
#[inline(always)]
#[must_use]
pub fn crcec(&mut self) -> CRCEC_W<SPI2S_IFCR_SPEC, 7> {
CRCEC_W::new(self)
}
#[doc = "Bit 8 - TIFREC"]
#[inline(always)]
#[must_use]
pub fn tifrec(&mut self) -> TIFREC_W<SPI2S_IFCR_SPEC, 8> {
TIFREC_W::new(self)
}
#[doc = "Bit 9 - MODFC"]
#[inline(always)]
#[must_use]
pub fn modfc(&mut self) -> MODFC_W<SPI2S_IFCR_SPEC, 9> {
MODFC_W::new(self)
}
#[doc = "Bit 10 - TSERFC"]
#[inline(always)]
#[must_use]
pub fn tserfc(&mut self) -> TSERFC_W<SPI2S_IFCR_SPEC, 10> {
TSERFC_W::new(self)
}
#[doc = "Bit 11 - SUSPC"]
#[inline(always)]
#[must_use]
pub fn suspc(&mut self) -> SUSPC_W<SPI2S_IFCR_SPEC, 11> {
SUSPC_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "SPI/I2S interrupt/status flags clear register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`spi2s_ifcr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SPI2S_IFCR_SPEC;
impl crate::RegisterSpec for SPI2S_IFCR_SPEC {
type Ux = u32;
}
#[doc = "`write(|w| ..)` method takes [`spi2s_ifcr::W`](W) writer structure"]
impl crate::Writable for SPI2S_IFCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SPI2S_IFCR to value 0"]
impl crate::Resettable for SPI2S_IFCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use iced::advanced::layout::{self, Layout};
use iced::advanced::overlay;
use iced::advanced::renderer;
use iced::advanced::widget::{self, Widget};
use iced::advanced::{self, Clipboard, Shell};
use iced::alignment::{Alignment, Horizontal, Vertical};
use iced::widget::tooltip::Position;
use iced::widget::{
button, horizontal_space, vertical_space, Column, Container, Row, Text, Tooltip,
};
use iced::{
event, mouse, BorderRadius, Color, Element, Event, Font, Length, Point, Rectangle, Renderer,
Size,
};
use crate::gui::styles::button::ButtonType;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::style_constants::FONT_SIZE_TITLE;
use crate::gui::styles::types::gradient_type::GradientType;
use crate::gui::types::message::Message;
use crate::translations::translations::{
ask_clear_all_translation, ask_quit_translation, clear_all_translation, hide_translation,
quit_analysis_translation, yes_translation,
};
use crate::{Language, StyleType};
pub fn get_exit_overlay(
color_gradient: GradientType,
font: Font,
font_headers: Font,
language: Language,
) -> Container<'static, Message, Renderer<StyleType>> {
let row_buttons = confirm_button_row(language, font, Message::Reset);
let content = Column::new()
.align_items(Alignment::Center)
.width(Length::Fill)
.push(get_modal_header(
font,
font_headers,
color_gradient,
language,
quit_analysis_translation(language),
))
.push(vertical_space(Length::Fixed(20.0)))
.push(
ask_quit_translation(language)
.horizontal_alignment(Horizontal::Center)
.font(font),
)
.push(row_buttons);
Container::new(content)
.height(Length::Fixed(160.0))
.width(Length::Fixed(450.0))
.style(ContainerType::Modal)
}
pub fn get_clear_all_overlay(
color_gradient: GradientType,
font: Font,
font_headers: Font,
language: Language,
) -> Container<'static, Message, Renderer<StyleType>> {
let row_buttons = confirm_button_row(language, font, Message::ClearAllNotifications);
let content = Column::new()
.align_items(Alignment::Center)
.width(Length::Fill)
.push(get_modal_header(
font,
font_headers,
color_gradient,
language,
clear_all_translation(language),
))
.push(vertical_space(Length::Fixed(20.0)))
.push(
ask_clear_all_translation(language)
.horizontal_alignment(Horizontal::Center)
.font(font),
)
.push(row_buttons);
Container::new(content)
.height(Length::Fixed(160.0))
.width(Length::Fixed(450.0))
.style(ContainerType::Modal)
}
fn get_modal_header(
font: Font,
font_headers: Font,
color_gradient: GradientType,
language: Language,
title: String,
) -> Container<'static, Message, Renderer<StyleType>> {
let tooltip = hide_translation(language).to_string();
//tooltip.push_str(" [esc]");
Container::new(
Row::new()
.push(horizontal_space(Length::FillPortion(1)))
.push(
Text::new(title)
.font(font_headers)
.size(FONT_SIZE_TITLE)
.width(Length::FillPortion(6))
.horizontal_alignment(Horizontal::Center),
)
.push(
Container::new(
Tooltip::new(
button(
Text::new("×")
.font(font)
.vertical_alignment(Vertical::Center)
.horizontal_alignment(Horizontal::Center)
.size(15),
)
.padding(2)
.height(Length::Fixed(20.0))
.width(Length::Fixed(20.0))
.on_press(Message::HideModal),
tooltip,
Position::Right,
)
.font(font)
.style(ContainerType::Tooltip),
)
.width(Length::FillPortion(1))
.align_x(Horizontal::Center),
),
)
.align_x(Horizontal::Center)
.align_y(Vertical::Center)
.height(Length::Fixed(40.0))
.width(Length::Fill)
.style(ContainerType::Gradient(color_gradient))
}
fn confirm_button_row(
language: Language,
font: Font,
message: Message,
) -> Row<'static, Message, Renderer<StyleType>> {
Row::new()
.height(Length::Fill)
.align_items(Alignment::Center)
.push(
button(
yes_translation(language)
.font(font)
.vertical_alignment(Vertical::Center)
.horizontal_alignment(Horizontal::Center),
)
.padding(5)
.height(Length::Fixed(40.0))
.width(Length::Fixed(80.0))
.style(ButtonType::Alert)
.on_press(message),
)
}
/// A widget that centers a modal element over some base element
pub struct Modal<'a, Message, Renderer> {
base: Element<'a, Message, Renderer>,
modal: Element<'a, Message, Renderer>,
on_blur: Option<Message>,
}
impl<'a, Message, Renderer> Modal<'a, Message, Renderer> {
/// Returns a new [`Modal`]
pub fn new(
base: impl Into<Element<'a, Message, Renderer>>,
modal: impl Into<Element<'a, Message, Renderer>>,
) -> Self {
Self {
base: base.into(),
modal: modal.into(),
on_blur: None,
}
}
/// Sets the message that will be produces when the background
/// of the [`Modal`] is pressed
pub fn on_blur(self, on_blur: Message) -> Self {
Self {
on_blur: Some(on_blur),
..self
}
}
}
impl<'a, Message, Renderer> Widget<Message, Renderer> for Modal<'a, Message, Renderer>
where
Renderer: advanced::Renderer,
Message: Clone,
{
fn children(&self) -> Vec<widget::Tree> {
vec![
widget::Tree::new(&self.base),
widget::Tree::new(&self.modal),
]
}
fn diff(&self, tree: &mut widget::Tree) {
tree.diff_children(&[&self.base, &self.modal]);
}
fn width(&self) -> Length {
self.base.as_widget().width()
}
fn height(&self) -> Length {
self.base.as_widget().height()
}
fn layout(&self, renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
self.base.as_widget().layout(renderer, limits)
}
fn on_event(
&mut self,
state: &mut widget::Tree,
event: Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) -> event::Status {
self.base.as_widget_mut().on_event(
&mut state.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
)
}
fn draw(
&self,
state: &widget::Tree,
renderer: &mut Renderer,
theme: &<Renderer as advanced::Renderer>::Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.base.as_widget().draw(
&state.children[0],
renderer,
theme,
style,
layout,
cursor,
viewport,
);
}
fn overlay<'b>(
&'b mut self,
state: &'b mut widget::Tree,
layout: Layout<'_>,
_renderer: &Renderer,
) -> Option<overlay::Element<'b, Message, Renderer>> {
Some(overlay::Element::new(
layout.position(),
Box::new(Overlay {
content: &mut self.modal,
tree: &mut state.children[1],
size: layout.bounds().size(),
on_blur: self.on_blur.clone(),
}),
))
}
fn mouse_interaction(
&self,
state: &widget::Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &Renderer,
) -> mouse::Interaction {
self.base.as_widget().mouse_interaction(
&state.children[0],
layout,
cursor,
viewport,
renderer,
)
}
fn operate(
&self,
state: &mut widget::Tree,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>,
) {
self.base
.as_widget()
.operate(&mut state.children[0], layout, renderer, operation);
}
}
struct Overlay<'a, 'b, Message, Renderer> {
content: &'b mut Element<'a, Message, Renderer>,
tree: &'b mut widget::Tree,
size: Size,
on_blur: Option<Message>,
}
impl<'a, 'b, Message, Renderer> overlay::Overlay<Message, Renderer>
for Overlay<'a, 'b, Message, Renderer>
where
Renderer: advanced::Renderer,
Message: Clone,
{
fn layout(&self, renderer: &Renderer, _bounds: Size, position: Point) -> layout::Node {
let limits = layout::Limits::new(Size::ZERO, self.size)
.width(Length::Fill)
.height(Length::Fill);
let mut child = self.content.as_widget().layout(renderer, &limits);
child.align(Alignment::Center, Alignment::Center, limits.max());
let mut node = layout::Node::with_children(self.size, vec![child]);
node.move_to(position);
node
}
fn on_event(
&mut self,
event: Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
) -> event::Status {
let content_bounds = layout.children().next().unwrap().bounds();
if let Some(message) = self.on_blur.as_ref() {
if let Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) = &event {
if !cursor.is_over(content_bounds) {
shell.publish(message.clone());
return event::Status::Captured;
}
}
}
self.content.as_widget_mut().on_event(
self.tree,
event,
layout.children().next().unwrap(),
cursor,
renderer,
clipboard,
shell,
&layout.bounds(),
)
}
fn draw(
&self,
renderer: &mut Renderer,
theme: &Renderer::Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
) {
renderer.fill_quad(
renderer::Quad {
bounds: layout.bounds(),
border_radius: BorderRadius::default(),
border_width: 0.0,
border_color: Color::TRANSPARENT,
},
Color {
a: 0.80,
..Color::BLACK
},
);
self.content.as_widget().draw(
self.tree,
renderer,
theme,
style,
layout.children().next().unwrap(),
cursor,
&layout.bounds(),
);
}
fn operate(
&mut self,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>,
) {
self.content.as_widget().operate(
self.tree,
layout.children().next().unwrap(),
renderer,
operation,
);
}
fn mouse_interaction(
&self,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &Renderer,
) -> mouse::Interaction {
self.content.as_widget().mouse_interaction(
self.tree,
layout.children().next().unwrap(),
cursor,
viewport,
renderer,
)
}
fn overlay<'c>(
&'c mut self,
layout: Layout<'_>,
renderer: &Renderer,
) -> Option<overlay::Element<'c, Message, Renderer>> {
self.content
.as_widget_mut()
.overlay(self.tree, layout.children().next().unwrap(), renderer)
}
}
impl<'a, Message, Renderer> From<Modal<'a, Message, Renderer>> for Element<'a, Message, Renderer>
where
Renderer: 'a + advanced::Renderer,
Message: 'a + Clone,
{
fn from(modal: Modal<'a, Message, Renderer>) -> Self {
Element::new(modal)
}
}
|
use regex::Regex;
use std::convert::TryInto;
use std::ops::Add;
// use crate::FromStr;
use crate::cipher::cryptomath::{modulus, find_mod_inverse};
// use std::error::Error;
// use std::fmt;
// use std::fmt::Formatter;
use crate::{ErrorKind, Result, ResultExt};
use std::collections::HashMap;
use std::iter::FromIterator;
use std::hash::Hash;
use std::collections::hash_map::{RandomState, Values, Iter};
/// Common functions to be used across cipher modules.
pub const DEFAULT_CHARSET: &'static str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.";
#[derive(Debug)]
pub enum Ciphers {
CAESAR,
TRANSPOSITION,
AFFINE,
VIGENERE
}
/// Generic function to offset text character frontwards and backwards.
///
/// # Parameters:
/// * text: Text to offset.
/// * key: Number of positions to offset characters.
/// * advance: If True offset characters frontwards.
/// * cipher_used: Kind of cipher we are using for this message.
/// * charset: Charset to use for substitution.
///
/// # Returns:
/// * Offset text.
pub fn offset_text<T, U>(text: T, key: usize, advance: bool, cipher_used: &Ciphers, charset: U) -> Result<String>
where T: AsRef<str>,
U: AsRef<str> {
let mut offset_text = String::new();
for character in text.as_ref().chars() {
let new_character = match get_new_char_position(character.to_string(), key, advance, cipher_used, &charset)? {
Some(new_char_position) => charset.as_ref().chars().nth(new_char_position).unwrap(),
_ => character
};
offset_text = offset_text.add(new_character.to_string().as_str());
}
Ok(offset_text)
}
/// Get position for offset char.
///
/// # Parameters:
/// * char: Actual character with no offset. It should be normalized to be
/// sure it is present at charset.
/// * key: Offset to apply.
/// * advance: If True offset is going to be applied frontwards.
/// * cipher_used: Kind of cipher we are using for this message.
/// * charset: Charset to use for substitution.
///
/// # Returns:
/// * Index in charset for offset char
fn get_new_char_position<T, U>(char: T, key: usize, advance: bool, cipher_used: &Ciphers, charset: U) -> Result<Option<usize>>
where T: AsRef<str>,
U: AsRef<str> {
let charset_length = charset.as_ref().len();
let character_to_find = match char.as_ref().chars().nth(0) {
Some(c)=> c,
None=> bail!(ErrorKind::StringIndexError(char.as_ref().to_string(), "Error at function get_new_char_position()"))
};
let char_position = match charset.as_ref().find(character_to_find) {
Some(index) => index,
_ => return Ok(None)
};
let offset_position = get_offset_position(char_position, key, advance, cipher_used, charset_length)?;
let new_char_position = modulus(offset_position, charset_length as isize);
// Positive operands at modulus give positive modulus result, so it can be casted to usize.
Ok(Some(new_char_position as usize))
}
/// Get new offset depending on ciphering being used.
///
/// # Parameters:
/// * current_position: Charset index of current char we are calculating offset to.
/// * key: Key value used for this message.
/// * advance: If True offset is going to be applied frontwards, that is when you cipher.
/// * cipher_used: Kind of cipher we are using for this message.
/// * charset_length: Length of charset to use for substitution.
///
/// # Returns:
/// * New offset position for this char.
fn get_offset_position(current_position: usize, key: usize, advance: bool, cipher_used: &Ciphers, charset_length: usize)-> Result<isize> {
let i_current_position: isize = current_position.try_into()
.chain_err(|| ErrorKind::ConversionError("current_position", "usize", "isize"))?;
let i_key: isize = key.try_into()
.chain_err(|| ErrorKind::ConversionError("key", "usize", "isize"))?;
match cipher_used {
Ciphers::CAESAR | Ciphers::VIGENERE=> if advance {Ok(i_current_position + i_key)} else {Ok(i_current_position - i_key)},
Ciphers::AFFINE=> {
let (multiplying_key, adding_key) = get_key_parts(key, charset_length);
let i_multiplying_key: isize = multiplying_key.try_into()
.chain_err(|| ErrorKind::ConversionError("multiplying_key", "usize", "isize"))?;
let i_adding_key: isize = adding_key.try_into()
.chain_err(|| ErrorKind::ConversionError("adding_key", "usize", "isize"))?;
if advance {
Ok((i_current_position * i_multiplying_key) + i_adding_key)
} else {
let i_multiplying_key: isize = multiplying_key.try_into()
.chain_err(|| ErrorKind::ConversionError("multiplying_key", "usize", "isize"))?;
let i_charset_length = charset_length.try_into()
.chain_err(|| ErrorKind::ConversionError("charset_length", "usize", "isize"))?;
Ok((i_current_position - i_adding_key) * find_mod_inverse(i_multiplying_key, i_charset_length)
.expect(format!("Modular inverse could not be found for {} and {}", i_multiplying_key, i_charset_length).as_ref()))
}
},
_=> bail!("get_offset_position has been unexpectedly called for {:?} cipher", cipher_used)
}
}
/// Split given key in two parts to be used by Affine cipher.
///
/// # Parameters:
/// * key: Key used for ciphering and deciphering.
/// * charset_length: Length of charset used for Affine method substitutions. Both end should
/// use the same charset or original text won't be properly recovered.
///
/// # Returns:
/// * A tuple whose first component is key used for multiplying while ciphering and second component is used for
/// adding.
pub fn get_key_parts(key: usize, charset_length: usize)-> (usize, usize){
let multiplying_key = key / charset_length;
// Operands for this modulus operation are going to be positive always, so no need
// to use modulus function.
let adding_key = key % charset_length;
(multiplying_key, adding_key)
}
/// Get a list of lowercase words from text without any punctuation marks.
///
/// # Parameters:
/// * text: Text to extract words from.
///
/// # Returns:
/// * A list with all text words in text with lowercased and without any punctuation mark.
pub fn normalize_text<T>(text: T) -> Vec<String>
where T: AsRef<str> {
let mut lowercase_text = text.as_ref().to_lowercase();
// Line breaks are troublesome for further assesment so we remove it.
lowercase_text = lowercase_text.replace("\n", " ");
lowercase_text = lowercase_text.replace("\r", " ");
let re = Regex::new(r"[^\W\d_]+")
.expect("Invalid regex to search for normalized words.");
let mut words_list: Vec<String> = Vec::new();
for _word in re.find_iter(&lowercase_text) {
words_list.push(_word.as_str().to_string());
}
words_list
}
/// Python has a really useful class called Counter whereas Rust has not. This
/// class is a simplified Rust equivalent for that class.
pub struct Counter <T>
where T: Hash + std::cmp::Eq + Clone {
item_dict: HashMap<T, u64>
}
impl<T> Counter<T>
where T: Hash + std::cmp::Eq + Clone {
/// Get amount for every item counted.
pub fn values(&self) -> Values<'_, T, u64>{
self.item_dict.values()
}
/// Get kay-values pairs.
pub fn items(&self) -> Iter<'_, T, u64> {
self.item_dict.iter()
}
/// List the n most common elements and their counts from the most
/// common to the least.
pub fn most_common(&self) -> Vec<(&T, &u64)> {
let mut items: Vec<(&T, &u64)> = self.item_dict.iter().collect();
// Reverse sorting from biggest to smallest.
items.sort_by(|&item_A, &item_B| item_B.1.cmp(item_A.1));
items
}
}
impl<T> From<&HashMap<T, u64>> for Counter<T>
where T: Hash + std::cmp::Eq + Clone{
fn from(dict : &HashMap<T, u64, RandomState>) -> Self {
let mut item_dict: HashMap<T, u64> = HashMap::new();
for key in dict.keys() {
*item_dict.entry(key.clone()).or_insert(0) = dict[key]
}
Counter{
item_dict
}
}
}
impl<T> FromIterator<T> for Counter<T>
where T: Hash + std::cmp::Eq + Clone {
fn from_iter<U: IntoIterator<Item=T>>(iter: U) -> Self {
let mut item_dict: HashMap<T, u64> = HashMap::new();
for key in iter {
*item_dict.entry(key).or_insert(0) += 1;
}
Counter{
item_dict
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::FromStr;
const ENGLISH_TEXT_WITH_PUNCTUATIONS_MARKS: &'static str = "This eBook is for the use of anyone anywhere at no cost and with
almost no restrictions whatsoever.You may copy it, give it away or
re-use it under the terms of the Project Gutenberg License included
with this eBook or online at 2020";
#[test]
fn test_normalize_text() {
let expected_list = vec!["this", "ebook", "is", "for", "the", "use", "of", "anyone",
"anywhere", "at", "no", "cost", "and", "with", "almost", "no",
"restrictions", "whatsoever", "you", "may", "copy", "it",
"give", "it", "away", "or", "re", "use", "it", "under", "the",
"terms", "of", "the", "project", "gutenberg", "license",
"included", "with", "this", "ebook", "or", "online", "at"];
let returned_list = normalize_text(ENGLISH_TEXT_WITH_PUNCTUATIONS_MARKS);
assert_eq!(returned_list, expected_list);
}
#[test]
fn test_counter_char() {
let text = "aaabbccd";
let counter: Counter<char> = Counter::from_iter(text.chars());
assert_eq!(counter.item_dict[&char::fromStr("a")], 3);
assert_eq!(counter.item_dict[&char::fromStr("c")], 2);
assert_eq!(counter.item_dict[&char::fromStr("d")], 1);
}
#[test]
fn test_counter_char_from_hashmap() {
let mut dict: HashMap<char, u64> = HashMap::new();
dict.insert(char::fromStr("a"), 3);
dict.insert(char::fromStr("c"), 2);
dict.insert(char::fromStr("d"), 1);
let counter: Counter<char> = Counter::from(&dict);
assert_eq!(counter.item_dict[&char::fromStr("a")], 3);
assert_eq!(counter.item_dict[&char::fromStr("c")], 2);
assert_eq!(counter.item_dict[&char::fromStr("d")], 1);
}
#[test]
fn test_counter_most_common() {
let text = "aaaabbbccd";
let counter: Counter<char> = Counter::from_iter(text.chars());
let most_common_list = counter.most_common();
assert_eq!(most_common_list[0], (&char::fromStr("a"), &4));
assert_eq!(most_common_list[1], (&char::fromStr("b"), &3));
assert_eq!(most_common_list[2], (&char::fromStr("c"), &2));
assert_eq!(most_common_list[3], (&char::fromStr("d"), &1));
}
}
|
use anyhow::{Result, bail};
use serde_json::{from_str, from_value, Value, json};
use serde::{Serialize, Deserialize};
use std::path::Path;
use std::io::{self, Write};
const PROBLEMS_URL: &str = "https://leetcode.com/api/problems/algorithms";
#[derive(Debug, Serialize, Deserialize)]
pub struct CodeDefinition {
pub value: String,
pub text: String,
#[serde(rename = "defaultCode")]
pub default_code: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct StatWithStatus {
stat: Stat,
difficulty: Difficulty,
paid_only: bool,
is_favor: bool,
frequency: u32,
progress: u32,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Stat {
question_id: u32,
#[serde(rename = "question__article__slug")]
question_article_slug: Option<String>,
#[serde(rename = "question__title")]
question_title: Option<String>,
#[serde(rename = "question__title_slug")]
question_title_slug: Option<String>,
#[serde(rename = "question__hide")]
question_hide: bool,
total_acs: u32,
total_submitted: u32,
frontend_question_id: u32,
is_new_question: bool,
}
#[derive(Debug, Serialize, Deserialize)]
struct Difficulty {
level: u32,
}
#[derive(Debug, Serialize, Deserialize)]
struct Question {
content: String,
stats: String,
#[serde(rename = "codeDefinition")]
code_definition: String,
#[serde(rename = "sampleTestCase")]
sample_test_case: String,
#[serde(rename = "metaData")]
meta_data: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct Query {
#[serde(rename = "operationName")]
operation_name: String,
variables: serde_json::Value,
query: String,
}
const QUESTION_QUERY_STRING: &str = r#"
query questionData($titleSlug: String!) {
question(titleSlug: $titleSlug) {
content
stats
codeDefinition
sampleTestCase
metaData
}
}"#;
impl Query {
fn question_query(title_slug: &str) -> Query {
Query {
operation_name: "questionData".to_string(),
variables: json!({ "titleSlug": title_slug }),
query: QUESTION_QUERY_STRING.to_string(),
}
}
}
#[derive(Debug)]
struct Problem {
id: u32,
title: String,
title_slug: String,
content: String,
code: CodeDefinition,
}
impl Problem {
fn save(&self) -> Result<()> {
let name = format!("{:04}_{}", self.id, self.title_slug.replace("-", "_"));
let prob_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("problems");
let sample_dir = prob_dir.join("sample");
let output_dir = prob_dir.join(&name);
if output_dir.exists() {
bail!("The probelm {} had already been generated.", &name)
} else {
std::fs::create_dir_all(&output_dir)?;
}
// Generate the Cargo.toml
std::fs::write(
&output_dir.join("Cargo.toml"),
std::fs::read_to_string(sample_dir.join("Cargo.toml"))?
.replace("sample", &self.title_slug),
)?;
// Generate the sample source code
std::fs::create_dir_all(&output_dir.join("src"))?;
std::fs::write(
&output_dir.join("src").join("lib.rs"),
std::fs::read_to_string(sample_dir.join("src/lib.rs"))?
.replace("__PROBLEM_ID__", &format!("{}", self.id))
.replace("__PROBLEM_TITLE__", &self.title)
.replace("__PROBLEM_DEFAULT_CODE__", &self.code.default_code)
)?;
// Generate the problem description
std::fs::write(
&output_dir.join("README.md"),
std::fs::read_to_string(sample_dir.join("README.md"))?
.replace("__PROBLEM_ID__", &format!("{}", self.id))
.replace("__PROBLEM_TITLE__", &self.title)
.replace("__PROBLEM_STATEMENT__", &self.content)
.replace(
"__DISCUSS_LINK__",
&format!("https://leetcode.com/problems/{}/discuss", &self.title_slug),
)
.replace(
"__PROBLEM_LINK__",
&format!("https://leetcode.com/problems/{}", &self.title_slug),
)
.replace("__PROBLEM_DEFAULT_CODE__", &self.code.default_code)
)?;
println!("Successfully generate the problem {:?}", &name);
Ok(())
}
}
async fn get_problem_by_id(id: u32) -> Result<Problem> {
let problem_list: Value = from_str(&reqwest::get(PROBLEMS_URL).await?.text().await?)?;
let problem_stats: Vec<StatWithStatus> = from_value(problem_list["stat_status_pairs"].to_owned())?;
let stat = problem_stats
.into_iter()
.find(|x| x.stat.frontend_question_id == id && !x.paid_only)
.expect("Invalid ID or paid only.")
.stat;
let title = stat.question_title.expect("Empty title.");
let title_slug = stat.question_title_slug.expect("Empty title slug.");
let response: Value = from_str(
&reqwest::Client::new()
.post("https://leetcode.com/graphql")
.json(&Query::question_query(&title_slug))
.send()
.await?
.text()
.await?
)?;
let question: Question = from_value(response["data"]["question"].to_owned())?;
let availabe_codes: Vec<CodeDefinition> = from_str(&question.code_definition)?;
let code_definition = availabe_codes
.into_iter()
.find(|x| x.value == "rust")
.expect("Rust version not support.");
Ok(Problem {
id,
title,
title_slug,
code: code_definition,
content: question.content,
})
}
#[tokio::main]
async fn main() -> Result<()> {
let mut id = String::new();
print!("Enter the problem ID to initialize: ");
io::stdout().flush()?;
io::stdin()
.read_line(&mut id)
.expect("Failed to read line");
let problem = get_problem_by_id(id.trim().parse::<u32>()?).await?;
problem.save()?;
Ok(())
}
|
use parameters::params::*;
use find_folder;
use std::path::PathBuf;
use std::collections::HashMap;
use csv::StringRecord;
const FILE_RECORD_LEN: usize = 6;
fn update_parameter(params: &Parameters, record: StringRecord) {
if record.len() != FILE_RECORD_LEN {
println!("Invalid file record len on line {}", record.position().unwrap().line());
} else {
let name = record.get(0).unwrap().to_string();
if let Some(param) = params.get(&name) {
let val_str = record.get(1).unwrap().to_string();
if let Ok(val) = val_str.trim().parse::<f64>() {
param.set(val);
} else {
println!("Could not parse default value {} for {}", val_str, name);
}
let prec_str = record.get(4).unwrap().to_string();
if let Ok(prec) = prec_str.trim().parse::<usize>() {
param.set_precision(prec);
} else {
println!("Could not parse precision {} for {}", val_str, name);
}
} else {
println!("Unknown parameter {}", &name);
}
}
}
pub fn load_file(params: Parameters, path: &PathBuf) -> Parameters {
use csv::{ReaderBuilder, ErrorKind};
if let Ok(mut reader) = ReaderBuilder::new().comment(Some(b'#'))
.from_path(path) {
for result in reader.records() {
match result {
Ok(record) => update_parameter(¶ms, record),
Err(err) => {
match err.kind() {
ErrorKind::UnequalLengths {pos: Some(p), .. } => {
println!("Error! Missing data on line {}", p.line())
},
_ => println!("Unknown error parsing parameter file")
};
}
}
}
}
params
}
pub fn file_defaults() -> Parameters {
let mut P = builtin_defaults();
if let Ok(resources) = find_folder::Search::KidsThenParents(3, 5).for_folder("resources") {
let defaults_path = resources.join("presets/defaults.bass");
P = load_file(P, &defaults_path);
}
P
}
pub fn builtin_defaults() -> Parameters {
// Environmental parameters
let ρ0 = param_simple("ρ0", "kg / m^3", 1.1839, 1.0, 1.4, 4);
let c = param_simple("c", "m/s", 345.0, 340.0, 350.0, 1);
let t = param_simple("t", "s", 1.0, 0.9, 1.1, 1);
// Driver low level parameters
let Xmax = param_simple("Xmax", "mm", 3.0, 0.0, 100.0, 1);
let Vd = param("Vd", "Liter", 0.1, 0.1, 100.0, 1, vd_update);
let Sd = param_simple("Sd", "cm ^ 2", 10.0, 1.0, 1000.0, 1);
let Bl = param_simple("Bl", "tesla m", 1.0, 0.1, 20.0, 1);
let Re = param_simple("Re", "ohm", 4.0, 0.1, 1000.0, 1);
let Mmd = param_simple("Mmd", "g", 10.0, 1.0, 1000.0, 1);
let Mms = param("Mms", "g", 10.0, 1.0, 1000.0, 1, mms_update);
let Mas = param("Mas", "g / cm^4", 10.0, 1.0, 1000.0, 1, mas_update);
let Rms = param_simple("Rms", "N * s / m", 4.0, 0.0, 1000.0, 1);
let Ras = param("Ras", "(Pa * s) / m^3", 1.0, 0.0, 1000.0, 1, ras_update);
let Cms = param_simple("Cms", "m / N", 1.0, 0.1, 1000.0, 1);
let Cas = param("Cas", "m^5 / N", 1.0, 0.0, 100.0, 1, cas_update);
let Vas = param("Vas", "liter", 1.0, 0.0, 100.0, 1, vas_update);
let Rg = param_simple("Rg", "", 0.0, 0.0, 1000.0, 1);
// Driver mid level parameters
let Ts = param("Ts", "s", 0.02, 0.0002, 0.2, 4, ts_update);
let ωs = param("ωs", "Hz", 50.0, 5.0, 5000.0, 1, ωs_update);
let Fs = param("Fs", "Hz", 314.1, 31.4, 31415.9, 1, fs_update);
let Qes = param("Qes", "", 0.5, 0.0, 30.0, 1, qes_update);
let Qms = param("Qms", "", 0.5, 0.0, 30.0, 1, qms_update);
let Qts = param("Qts", "", 0.5, 0.0, 30.0, 1, qts_update);
let Qs = param("Qs", "", 0.5, 0.0, 30.0, 1, qs_update);
let Cab = param_simple("Cab", "m^5 / N", 1.0, 0.0, 100.0, 1);
let Vb = param("Vb", "liter", 0.1, 0.0, 100.0, 1, vb_update);
// Passive radiator low level parameters
let Vap = param("Vap", "liter", 1.0, 0.0, 100.0, 1, vap_update);
let Cmp = param_simple("Cmp", "m / N", 1.0, 0.0, 1000.0, 1);
let Cap = param("Cap", "m^5 / N", 1.0, 0.0, 100.0, 1, cap_update);
let Rmp = param_simple("Rmp", "N * s / m", 4.0, 0.0, 1000.0, 1);
let Rap = param("Rap", "ohm", 1.0, 0.0, 1000.0, 1, rap_update);
let Mmp = param_simple("Mmp", "kg", 1.0, 0.001, 100.0, 3);
let Map = param("Map", "kg / cm^2", 1.0, 0.0, 1000.0, 1, map_update);
let Sp = param_simple("Sp", "cm^2", 10.0, 0.0, 1000.0, 1);
// Passive radiator mid level parameters
let Qmp = param("Qmp", "", 0.5, 0.0, 30.0, 1, qmp_update);
let ωp = param("ωp", "Hz", 20.0, 0.0, 1000.0, 1, ωp_update);
let Fp = param("Fp", "Hz", 120.0, 0.0, 6282.0, 1, fp_update);
let Tp = param("Tp", "s", 0.05, 0.0, 0.1, 1, tp_update);
// Enclosure parameters
let ωb = param("ωb", "Hz", 20.0, 0.0, 1000.0, 1, ωb_update);
let Fb = param("Fb", "Hz", 120.0, 0.0, 6282.0, 1, fb_update);
let Tb = param("Tb", "s", 0.05, 0.0, 0.1, 1, tb_update);
let α = param("α", "", 3.0, 0.0, 100.0, 1, α_update);
let δ = param("δ", "", 7.0, 0.0, 100.0, 1, δ_update);
let y = param("y", "", 0.5, 0.0, 100.0, 1, y_update);
let h = param("h", "", 0.5, 0.0, 100.0, 1, h_update);
let η0 = param("η0", "", 0.4, 0.0, 100.0, 1, η0_update);
let p_arr = vec![Xmax.clone(), Vd.clone(), Sd.clone(), Bl.clone(), Re.clone(), Mmd.clone(), Mms.clone(),
Mas.clone(), Rms.clone(), Ras.clone(), Cms.clone(), Cas.clone(), Vas.clone(), Rg.clone(),
Ts.clone(), ωs.clone(), Fs.clone(), Qes.clone(), Qms.clone(), Qts.clone(), Qs.clone(),
Cab.clone(), Vb.clone(),
Vap.clone(), Cmp.clone(), Cap.clone(), Rmp.clone(), Rap.clone(), Mmp.clone(),
Map.clone(), Sp.clone(), Qmp.clone(), ωp.clone(), Fp.clone(), Tp.clone(),
ωb.clone(), Fb.clone(), Tb.clone(),
α.clone(), δ.clone(), y.clone(), h.clone(), η0.clone(),
ρ0.clone(), c.clone(), t.clone()];
let p_tuples = p_arr.into_iter().map(|p| (p.name.clone(), p)).collect::<Vec<(String, Param)>>();
let p_map: HashMap<String, Param> = p_tuples.iter().cloned().collect();
let mut P = Parameters {
param_map: p_map,
driver: [Xmax.clone(), Vd.clone(), Sd.clone(), Bl.clone(), Re.clone(), Mmd.clone(), Mms.clone(),
Mas.clone(), Rms.clone(), Ras.clone(), Cms.clone(), Cas.clone(), Vas.clone(), Rg.clone(),
Ts.clone(), ωs.clone(), Fs.clone(), Qes.clone(), Qms.clone(), Qts.clone(), Qs.clone(),
Cab.clone(), Vb.clone()],
passive: [Vap.clone(), Cmp.clone(), Cap.clone(), Rmp.clone(), Rap.clone(), Mmp.clone(),
Map.clone(), Sp.clone(), Qmp.clone(), ωp.clone(), Fp.clone(), Tp.clone()],
enclosure: [ωb.clone(), Fb.clone(), Tb.clone(),
α.clone(), δ.clone(), y.clone(), h.clone(), η0.clone()],
constant: [ρ0.clone(), c.clone(), t.clone()],
// Environmental parameters
ρ0, c, t,
// Driver low level parameters
Xmax, Vd, Sd, Bl, Re, Mmd, Mms,
Mas, Rms, Ras, Cms, Cas, Vas, Rg,
// Driver mid level parameters
Ts, ωs, Fs, Qes, Qms, Qts, Qs,
Cab, Vb,
// Passive radiator low level parameters
Vap, Cmp, Cap, Rmp, Rap, Mmp, Map, Sp,
// Passive radiator mid level parameters
Qmp, ωp, Fp, Tp,
// Enclosure parameters
ωb, Fb, Tb, α, δ, y, h, η0,
};
set_children(&mut P.Vd, vec![P.Sd.clone(), P.Xmax.clone()]);
set_children(&mut P.Mms, vec![P.Sd.clone(), P.Mmd.clone(), P.ρ0.clone()]);
set_children(&mut P.Mas, vec![P.Sd.clone(), P.Mms.clone()]);
set_children(&mut P.Ras, vec![P.Sd.clone(), P.Rms.clone()]);
set_children(&mut P.Cas, vec![P.Sd.clone(), P.Cms.clone()]);
set_children(&mut P.Vas, vec![P.Cas.clone(), P.ρ0.clone(), P.c.clone()]);
set_children(&mut P.Ts, vec![P.ωs.clone()]);
set_children(&mut P.ωs, vec![P.Fs.clone()]);
set_children(&mut P.Fs, vec![P.Mas.clone(), P.Cas.clone()]);
set_children(&mut P.Qes, vec![P.ωs.clone(), P.Re.clone(), P.Mas.clone(), P.Sd.clone(), P.Bl.clone()]);
set_children(&mut P.Qms, vec![P.Bl.clone(), P.Cas.clone(), P.Ras.clone()]);
set_children(&mut P.Qts, vec![P.Qes.clone(), P.Qms.clone()]);
set_children(&mut P.Qs, vec![P.Qts.clone()]);
set_children(&mut P.Vb, vec![P.ρ0.clone(), P.c.clone(), P.Cab.clone()]);
set_children(&mut P.Vap, vec![P.ρ0.clone(), P.c.clone(), P.Cap.clone()]);
set_children(&mut P.Cap, vec![P.Cmp.clone(), P.Sp.clone()]);
set_children(&mut P.Rap, vec![P.Rmp.clone(), P.Sp.clone()]);
set_children(&mut P.Map, vec![P.Mmp.clone(), P.Sp.clone()]);
set_children(&mut P.Qmp, vec![P.ωp.clone(), P.Cap.clone(), P.Rap.clone()]);
set_children(&mut P.Fp, vec![P.Map.clone(), P.Cap.clone()]);
set_children(&mut P.Tp, vec![P.ωp.clone()]);
set_children(&mut P.ωp, vec![P.Fp.clone()]);
set_children(&mut P.Fb, vec![P.Cab.clone(), P.Cap.clone(), P.Map.clone()]);
set_children(&mut P.Tb, vec![P.ωp.clone()]);
set_children(&mut P.ωb, vec![P.Fp.clone()]);
set_children(&mut P.α, vec![P.Cas.clone(), P.Cab.clone()]);
set_children(&mut P.δ, vec![P.Cap.clone(), P.Cab.clone()]);
set_children(&mut P.y, vec![P.Fb.clone(), P.Fs.clone()]);
set_children(&mut P.h, vec![P.Fb.clone(), P.Fp.clone()]);
set_children(&mut P.η0, vec![P.c.clone(), P.Fs.clone(), P.Vas.clone(), P.Qes.clone()]);
P
}
|
use itertools::Itertools;
use std::{
collections::{HashMap, HashSet},
fs,
path::Path,
};
//
fn read_input_lines<P, T>(path: P, transformer: fn(&'_ str) -> T) -> std::io::Result<Vec<T>>
where
P: AsRef<Path>,
{
let mut input: Vec<T> = vec![];
let contents = fs::read_to_string(path).unwrap();
for line in contents.lines() {
input.push(transformer(line));
}
Ok(input)
}
//
#[derive(PartialEq, Eq, Debug)]
struct Route {
from: String,
to: String,
distance: i32,
}
impl Route {
fn from_str(s: &str) -> Self {
let components: Vec<&str> = s.split_ascii_whitespace().collect();
Self {
from: components[0].to_string(),
to: components[2].to_string(),
distance: components[4].parse().unwrap(),
}
}
}
fn read_routes() -> Vec<Route> {
let routes: Vec<Route> = read_input_lines("input.txt", Route::from_str).unwrap();
routes
}
fn cities_from_routes(routes: &Vec<Route>) -> HashSet<String> {
let mut cities: HashSet<String> = HashSet::new();
for route in routes {
cities.insert(route.from.clone());
cities.insert(route.to.clone());
}
cities
}
fn distances_from_routes(routes: &Vec<Route>) -> HashMap<Leg, i32> {
let mut distances: HashMap<Leg, i32> = HashMap::new();
for route in routes {
distances.insert(
Leg {
a: route.from.clone(),
b: route.to.clone(),
},
route.distance,
);
distances.insert(
Leg {
a: route.to.clone(),
b: route.from.clone(),
},
route.distance,
);
}
distances
}
//
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
struct Leg {
a: String,
b: String,
}
//
fn trip_distance(trip: Vec<&String>, distances: &HashMap<Leg, i32>) -> i32 {
// let mut distance = 0;
// for (a, b) in trip.iter().tuple_windows() {
// let leg = &Leg {
// a: (**a).clone(),
// b: (**b).clone(),
// };
// distance += distances.get(leg).unwrap();
// }
// distance
trip.iter()
.tuple_windows()
.map(|(a, b)| {
distances
.get(&Leg {
a: (**a).clone(),
b: (**b).clone(),
})
.unwrap()
})
.sum()
}
//
pub fn part1() -> i32 {
let routes = read_routes();
let cities = cities_from_routes(&routes);
let distances = distances_from_routes(&routes);
// let mut min_distance = i32::MAX;
// for trip in cities.iter().permutations(cities.len()).unique() {
// let distance = trip_distance(trip, &distances);
// if distance < min_distance {
// min_distance = distance;
// }
// }
// min_distance
cities
.iter()
.permutations(cities.len())
.unique()
.map(|trip| trip_distance(trip, &distances))
.min()
.unwrap()
}
pub fn part2() -> i32 {
let routes = read_routes();
let cities = cities_from_routes(&routes);
let distances = distances_from_routes(&routes);
// let mut max_distance = i32::MIN;
// for trip in cities.iter().permutations(cities.len()).unique() {
// let distance = trip_distance(trip, &distances);
// if distance > max_distance {
// max_distance = distance;
// }
// }
// max_distance
cities
.iter()
.permutations(cities.len())
.unique()
.map(|trip| trip_distance(trip, &distances))
.max()
.unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_route_from_str() {
assert_eq!(
Route::from_str("Amsterdam to Toronto = 1234"),
Route {
from: "Amsterdam".to_string(),
to: "Toronto".to_string(),
distance: 1234
}
);
}
//
#[test]
fn test_part1() {
assert_eq!(part1(), 141);
}
#[test]
fn test_part2() {
assert_eq!(part2(), 736);
}
}
|
#[doc = "Register `DDRCTRL_INIT3` reader"]
pub type R = crate::R<DDRCTRL_INIT3_SPEC>;
#[doc = "Register `DDRCTRL_INIT3` writer"]
pub type W = crate::W<DDRCTRL_INIT3_SPEC>;
#[doc = "Field `EMR` reader - EMR"]
pub type EMR_R = crate::FieldReader<u16>;
#[doc = "Field `EMR` writer - EMR"]
pub type EMR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>;
#[doc = "Field `MR` reader - MR"]
pub type MR_R = crate::FieldReader<u16>;
#[doc = "Field `MR` writer - MR"]
pub type MR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>;
impl R {
#[doc = "Bits 0:15 - EMR"]
#[inline(always)]
pub fn emr(&self) -> EMR_R {
EMR_R::new((self.bits & 0xffff) as u16)
}
#[doc = "Bits 16:31 - MR"]
#[inline(always)]
pub fn mr(&self) -> MR_R {
MR_R::new(((self.bits >> 16) & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - EMR"]
#[inline(always)]
#[must_use]
pub fn emr(&mut self) -> EMR_W<DDRCTRL_INIT3_SPEC, 0> {
EMR_W::new(self)
}
#[doc = "Bits 16:31 - MR"]
#[inline(always)]
#[must_use]
pub fn mr(&mut self) -> MR_W<DDRCTRL_INIT3_SPEC, 16> {
MR_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "DDRCTRL SDRAM initialization register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ddrctrl_init3::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ddrctrl_init3::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DDRCTRL_INIT3_SPEC;
impl crate::RegisterSpec for DDRCTRL_INIT3_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ddrctrl_init3::R`](R) reader structure"]
impl crate::Readable for DDRCTRL_INIT3_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ddrctrl_init3::W`](W) writer structure"]
impl crate::Writable for DDRCTRL_INIT3_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DDRCTRL_INIT3 to value 0x0510"]
impl crate::Resettable for DDRCTRL_INIT3_SPEC {
const RESET_VALUE: Self::Ux = 0x0510;
}
|
use std::time::Instant;
use std::io::{self, BufRead, Write};
struct Interval {
work: u64,
rest: u64,
}
impl std::default::Default for Interval {
fn default() -> Self {
Interval {
work: 1, // TODO change to minutes after testing
rest: 1, // TODO change to minutes after testing
}
}
}
impl Interval {
fn work_set(&self) {
let now = Instant::now();
let work_sec = self.work * 60;
while now.elapsed().as_secs() <= work_sec {
let sec = work_sec - now.elapsed().as_secs();
let min = sec / 60;
print!("\r{}:{:0>2} min of work remaining", min, (sec % 60));
std::io::stdout().flush().unwrap();
}
println!("\nWork set finished\n");
let mut buffer = String::new();
let stdin = io::stdin();
let mut handle = stdin.lock();
handle.read_line(&mut buffer).unwrap();
println!("stdin: {}", buffer);
}
fn rest_set(&self) {
let now = Instant::now();
let work_sec = self.rest * 60;
while now.elapsed().as_secs() <= work_sec {
let sec = work_sec - now.elapsed().as_secs();
let min = sec / 60;
print!("\r{}:{:0>2} min of rest remaining", min, (sec % 60));
std::io::stdout().flush().unwrap();
}
println!("\nRest set finished\n");
}
}
fn main() {
let interval = Interval::default();
let now = Instant::now();
println!("Starting default of {}min work and {}min rest sets", interval.work, interval.rest);
interval.work_set();
println!("Starting break of 1");
interval.rest_set();
println!("Took {} seconds.", now.elapsed().as_secs());
}
|
use crate::commands::wallet::wallet_update;
use crate::lib::environment::Environment;
use crate::lib::error::DfxResult;
use clap::Clap;
/// Set wallet name.
#[derive(Clap)]
pub struct SetNameOpts {
/// Name of the wallet.
name: String,
}
pub async fn exec(env: &dyn Environment, opts: SetNameOpts) -> DfxResult {
wallet_update(env, "name", opts.name.clone()).await?;
println!("Set name to {}.", opts.name);
Ok(())
}
|
pub mod object_draw;
pub mod system;
pub mod ui_draw;
|
use regex::Regex;
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct Color {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
impl Color {
pub fn new(color_name: &str) -> Option<Self> {
if color_name.chars().next().unwrap() == '#' {
return Color::hex_to_rgba(color_name);
}
Color::default_color_name(color_name)
}
fn hex_to_rgba(mut hex_code: &str) -> Option<Self> {
hex_code = remove_first_char(hex_code);
let re = Regex::new(r"^([A-Fa-f0-9]{3}){1,2}$").unwrap();
let caps = re.captures(hex_code);
let mut hex = match caps {
Some(cap) => cap.get(0).unwrap().as_str().to_string(),
_ => return None,
};
if hex.chars().count() == 3 {
let mut new_hex = String::from("");
for char in hex.chars().into_iter() {
new_hex.push(char);
new_hex.push(char);
}
hex = new_hex;
}
Some(Color {
r: hex_pair(&hex[0..2]),
g: hex_pair(&hex[2..4]),
b: hex_pair(&hex[4..6]),
a: 1,
})
}
pub fn from_rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
Color { r, g, b, a }
}
/// 他のColorを指定することで、その色とのブレンドを行う.
/// alpha: どの程度文字の色と背景色が混ざるかを決定。 0~255の値を指定
pub fn blend(&self, blended_color: Color, alpha: u8) -> Color {
let alpha = alpha as f32 / 255.0;
// 文字のアルファ値の補数を表し、背景色がどの程度透明であるか
let inv_alpha = 1.0 - alpha;
Color {
r: (self.r as f32 * alpha + blended_color.r as f32 * inv_alpha).ceil() as u8,
g: (self.g as f32 * alpha + blended_color.g as f32 * inv_alpha).ceil() as u8,
b: (self.b as f32 * alpha + blended_color.b as f32 * inv_alpha).ceil() as u8,
a: 255,
}
}
fn default_color_name(name: &str) -> Option<Color> {
match name {
"black" => Some(Color {
r: 0,
g: 0,
b: 0,
a: 1,
}),
"gray" => Some(Color {
r: 128,
g: 128,
b: 128,
a: 1,
}),
"white" => Some(Color {
r: 255,
g: 255,
b: 255,
a: 1,
}),
"blue" => Some(Color {
r: 0,
g: 0,
b: 255,
a: 0,
}),
"green" => Some(Color {
r: 0,
g: 128,
b: 0,
a: 1,
}),
"yellow" => Some(Color {
r: 255,
g: 255,
b: 0,
a: 1,
}),
"red" => Some(Color {
r: 255,
g: 0,
b: 0,
a: 1,
}),
_ => None,
}
}
}
fn hex_pair(input: &str) -> u8 {
u8::from_str_radix(input, 16).unwrap()
}
fn remove_first_char(input: &str) -> &str {
let mut chars = input.chars();
chars.next();
chars.as_str()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn color_test() {
let test1 = Color::new("#dedede").unwrap();
assert_eq!(test1.r, 222);
assert_eq!(test1.g, 222);
assert_eq!(test1.b, 222);
assert_eq!(test1.a, 1);
}
#[test]
fn test_blend() {
// 完全に透明な文字の場合、背景色がそのまま返される
let char_color1 = Color::from_rgba(255, 0, 0, 255); // Red
let bg_color1 = Color::from_rgba(0, 255, 0, 255); // Green
let blended_color1 = char_color1.blend(bg_color1, 0);
assert_eq!(bg_color1, blended_color1);
// 完全に不透明な文字の場合、文字色がそのまま返される
let char_color2 = Color::from_rgba(255, 0, 0, 255); // Red
let bg_color2 = Color::from_rgba(0, 255, 0, 255); // Green
let blended_color2 = char_color2.blend(bg_color2, 255);
assert_eq!(char_color2, blended_color2);
// 他の色と透明度の組み合わせでもテスト
let char_color4 = Color::from_rgba(0, 0, 255, 255); // Blue
let bg_color4 = Color::from_rgba(255, 255, 0, 255); // Yellow
let blended_color4 = char_color4.blend(bg_color4, 64);
let expected_color4 = Color::from_rgba(191, 191, 64, 255); // Blended: Light Gray
assert_eq!(expected_color4, blended_color4);
}
}
|
use azure_cosmos::prelude::*;
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
let database = std::env::args()
.nth(1)
.expect("please specify database name as first command line parameter");
let collection = std::env::args()
.nth(2)
.expect("please specify collection name as second command line parameter");
let master_key =
std::env::var("COSMOS_MASTER_KEY").expect("Set env variable COSMOS_MASTER_KEY first!");
let account = std::env::var("COSMOS_ACCOUNT").expect("Set env variable COSMOS_ACCOUNT first!");
let authorization_token = AuthorizationToken::primary_from_base64(&master_key)?;
let client = CosmosClient::new(
account.clone(),
authorization_token,
CosmosOptions::default(),
);
let client = client.into_database_client(database);
let client = client.into_collection_client(collection);
let resp = client.get_partition_key_ranges().execute().await?;
println!("resp == {:#?}", resp);
Ok(())
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// QueryValueWidgetDefinition : Query values display the current value of a given metric, APM, or log query.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct QueryValueWidgetDefinition {
/// Whether to use auto-scaling or not.
#[serde(rename = "autoscale", skip_serializing_if = "Option::is_none")]
pub autoscale: Option<bool>,
/// List of custom links.
#[serde(rename = "custom_links", skip_serializing_if = "Option::is_none")]
pub custom_links: Option<Vec<crate::models::WidgetCustomLink>>,
/// Display a unit of your choice on the widget.
#[serde(rename = "custom_unit", skip_serializing_if = "Option::is_none")]
pub custom_unit: Option<String>,
/// Number of decimals to show. If not defined, the widget uses the raw value.
#[serde(rename = "precision", skip_serializing_if = "Option::is_none")]
pub precision: Option<i64>,
/// Widget definition.
#[serde(rename = "requests")]
pub requests: Vec<crate::models::QueryValueWidgetRequest>,
#[serde(rename = "text_align", skip_serializing_if = "Option::is_none")]
pub text_align: Option<crate::models::WidgetTextAlign>,
#[serde(rename = "time", skip_serializing_if = "Option::is_none")]
pub time: Option<Box<crate::models::WidgetTime>>,
/// Title of your widget.
#[serde(rename = "title", skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(rename = "title_align", skip_serializing_if = "Option::is_none")]
pub title_align: Option<crate::models::WidgetTextAlign>,
/// Size of the title.
#[serde(rename = "title_size", skip_serializing_if = "Option::is_none")]
pub title_size: Option<String>,
#[serde(rename = "type")]
pub _type: crate::models::QueryValueWidgetDefinitionType,
}
impl QueryValueWidgetDefinition {
/// Query values display the current value of a given metric, APM, or log query.
pub fn new(requests: Vec<crate::models::QueryValueWidgetRequest>, _type: crate::models::QueryValueWidgetDefinitionType) -> QueryValueWidgetDefinition {
QueryValueWidgetDefinition {
autoscale: None,
custom_links: None,
custom_unit: None,
precision: None,
requests,
text_align: None,
time: None,
title: None,
title_align: None,
title_size: None,
_type,
}
}
}
|
fn main() {
// let some_u8_value = Some(3u8);
// match some_u8_value{
// Some(3) => println!("three"),
// _ => ()
// }
// if let Some(3) = some_u8_value{
// println!("three")
// };
// let another_u8_value = Some(4u8);
// if some_u8_value == another_u8_value {
// println!("three")
// }
// if let another_u8_value = some_u8_value{
// println!("three")
// }
let coin1 = Coin::Quarter(UsStates::Alabama);
let coin2 = Coin::Penny;
if let Coin::Quarter(state) = &coin1{
println!("quarter {:?}", state);
}else{
println!("other {:?}",&coin1);
}
// println!("{:?}",coin1);
if let Coin::Quarter(state) = coin2{
println!("quarter {:?}", state);
}else{
println!("other {:?}",coin2);
}
// println!("{:?}",coin2);
}
#[derive(Debug)]
enum Coin{
Quarter(UsStates),
Penny,
Dime,
What,
}
#[derive(Debug)]
enum UsStates{
Alabama,
Alaska,
} |
/// haveibeenpwned.com password checking.
///
/// Documented here:
/// https://haveibeenpwned.com/API/v2#SearchingPwnedPasswordsByRange
use sha1::Sha1;
use std::io;
use std::error::Error;
use knock::{HTTP, response::Response};
use secstr::SecStr;
static REQ_BASE: &str = "https://api.pwnedpasswords.com/range/";
static PREFIX_LEN: usize = 5;
fn handle_ok_response(response: &Response, hash_sufx: &str) -> Result<bool, io::Error> {
for line in response.body.lines() {
let check_sufx = match line.split(":").next() {
Some(elem) => elem.to_ascii_lowercase(),
_ => return Err(io::Error::new(
io::ErrorKind::Other, "missing hash suffix in HTTP response")),
};
if check_sufx.len() != hash_sufx.len() {
return Err(io::Error::new(
io::ErrorKind::Other, "hash suffix in HTTP response has wrong length"));
}
if check_sufx == hash_sufx {
// pwned.
return Ok(true);
}
}
Ok(false)
}
/// Returns `Ok(true)` if the has for `pw` is in the pwnedpasswords.com database, or `Ok(false)` if
/// it is not.
pub fn is_pwned(pw: &SecStr) -> Result<bool, Box<Error>> {
let hash = Sha1::from(pw.unsecure()).digest().to_string().to_ascii_lowercase();
let hash_prefix = &hash[..PREFIX_LEN];
let mut req_url = String::from(REQ_BASE);
req_url.push_str(hash_prefix);
let mut http = HTTP::new(&req_url)?;
let response = http.get().send()?;
// According to the docs, only 200 should happen on the range API. It's not even rate limited.
match response.status {
200 => Ok(handle_ok_response(&response, &hash[PREFIX_LEN..])?),
_ => Err(Box::new(io::Error::new(
io::ErrorKind::Other, format!("unhandled HTTP status: {}", response.status)))),
}
}
|
// This file was generated by gir (https://github.com/gtk-rs/gir @ fbb95f4)
// from gir-files (https://github.com/gtk-rs/gir-files @ 77d1f70)
// DO NOT EDIT
use ffi;
use std::ffi::CStr;
lazy_static! {
pub static ref DESKTOP_APP_INFO_LOOKUP_EXTENSION_POINT_NAME: &'static str = unsafe{CStr::from_ptr(ffi::G_DESKTOP_APP_INFO_LOOKUP_EXTENSION_POINT_NAME).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_ACCESS_CAN_DELETE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_ACCESS_CAN_DELETE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_ACCESS_CAN_READ: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_ACCESS_CAN_READ).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_ACCESS_CAN_RENAME: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_ACCESS_CAN_RENAME).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_ACCESS_CAN_TRASH: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_ACCESS_CAN_WRITE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_DOS_IS_ARCHIVE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_DOS_IS_ARCHIVE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_DOS_IS_SYSTEM: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_DOS_IS_SYSTEM).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_ETAG_VALUE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_ETAG_VALUE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_FILESYSTEM_FREE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_FILESYSTEM_FREE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_FILESYSTEM_READONLY: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_FILESYSTEM_READONLY).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_FILESYSTEM_REMOTE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_FILESYSTEM_SIZE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_FILESYSTEM_SIZE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_FILESYSTEM_TYPE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_FILESYSTEM_TYPE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_FILESYSTEM_USED: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_FILESYSTEM_USED).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_FILESYSTEM_USE_PREVIEW: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_FILESYSTEM_USE_PREVIEW).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_GVFS_BACKEND: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_GVFS_BACKEND).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_ID_FILE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_ID_FILE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_ID_FILESYSTEM: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_ID_FILESYSTEM).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_MOUNTABLE_CAN_EJECT: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_MOUNTABLE_CAN_EJECT).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_MOUNTABLE_CAN_MOUNT: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_MOUNTABLE_CAN_MOUNT).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_MOUNTABLE_CAN_POLL: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_MOUNTABLE_CAN_POLL).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_MOUNTABLE_CAN_START: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_MOUNTABLE_CAN_START).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_MOUNTABLE_CAN_START_DEGRADED: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_MOUNTABLE_CAN_START_DEGRADED).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_MOUNTABLE_CAN_STOP: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_MOUNTABLE_CAN_STOP).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_MOUNTABLE_CAN_UNMOUNT: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_MOUNTABLE_CAN_UNMOUNT).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_MOUNTABLE_HAL_UDI: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_MOUNTABLE_HAL_UDI).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_MOUNTABLE_IS_MEDIA_CHECK_AUTOMATIC: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_MOUNTABLE_IS_MEDIA_CHECK_AUTOMATIC).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_MOUNTABLE_START_STOP_TYPE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_MOUNTABLE_START_STOP_TYPE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_MOUNTABLE_UNIX_DEVICE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_MOUNTABLE_UNIX_DEVICE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_MOUNTABLE_UNIX_DEVICE_FILE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_MOUNTABLE_UNIX_DEVICE_FILE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_OWNER_GROUP: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_OWNER_GROUP).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_OWNER_USER: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_OWNER_USER).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_OWNER_USER_REAL: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_OWNER_USER_REAL).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_PREVIEW_ICON: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_PREVIEW_ICON).to_str().unwrap()};
}
#[cfg(any(feature = "v2_52", feature = "dox"))]
lazy_static! {
pub static ref FILE_ATTRIBUTE_RECENT_MODIFIED: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_RECENT_MODIFIED).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_SELINUX_CONTEXT: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_SELINUX_CONTEXT).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_ALLOCATED_SIZE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_ALLOCATED_SIZE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_COPY_NAME: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_COPY_NAME).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_DESCRIPTION: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_DESCRIPTION).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_EDIT_NAME: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_EDIT_NAME).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_ICON: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_ICON).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_IS_BACKUP: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_IS_BACKUP).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_IS_HIDDEN: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_IS_HIDDEN).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_IS_SYMLINK: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_IS_SYMLINK).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_IS_VIRTUAL: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_IS_VIRTUAL).to_str().unwrap()};
}
#[cfg(any(feature = "v2_46", feature = "dox"))]
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_IS_VOLATILE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_IS_VOLATILE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_NAME: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_NAME).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_SIZE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_SIZE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_SORT_ORDER: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_SORT_ORDER).to_str().unwrap()};
}
#[cfg(any(feature = "v2_34", feature = "dox"))]
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_SYMBOLIC_ICON: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_SYMBOLIC_ICON).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_TARGET_URI: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_TARGET_URI).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_STANDARD_TYPE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_STANDARD_TYPE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_THUMBNAILING_FAILED: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_THUMBNAILING_FAILED).to_str().unwrap()};
}
#[cfg(any(feature = "v2_40", feature = "dox"))]
lazy_static! {
pub static ref FILE_ATTRIBUTE_THUMBNAIL_IS_VALID: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_THUMBNAIL_IS_VALID).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_THUMBNAIL_PATH: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_THUMBNAIL_PATH).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_TIME_ACCESS: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_TIME_ACCESS).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_TIME_ACCESS_USEC: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_TIME_ACCESS_USEC).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_TIME_CHANGED: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_TIME_CHANGED).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_TIME_CHANGED_USEC: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_TIME_CHANGED_USEC).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_TIME_CREATED: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_TIME_CREATED).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_TIME_CREATED_USEC: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_TIME_CREATED_USEC).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_TIME_MODIFIED: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_TIME_MODIFIED).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_TIME_MODIFIED_USEC: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_TRASH_DELETION_DATE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_TRASH_DELETION_DATE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_TRASH_ITEM_COUNT: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_TRASH_ITEM_COUNT).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_TRASH_ORIG_PATH: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_TRASH_ORIG_PATH).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_UNIX_BLOCKS: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_UNIX_BLOCKS).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_UNIX_BLOCK_SIZE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_UNIX_BLOCK_SIZE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_UNIX_DEVICE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_UNIX_DEVICE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_UNIX_GID: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_UNIX_GID).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_UNIX_INODE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_UNIX_INODE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_UNIX_IS_MOUNTPOINT: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_UNIX_IS_MOUNTPOINT).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_UNIX_MODE: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_UNIX_MODE).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_UNIX_NLINK: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_UNIX_NLINK).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_UNIX_RDEV: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_UNIX_RDEV).to_str().unwrap()};
}
lazy_static! {
pub static ref FILE_ATTRIBUTE_UNIX_UID: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_UNIX_UID).to_str().unwrap()};
}
lazy_static! {
pub static ref MENU_ATTRIBUTE_ACTION: &'static str = unsafe{CStr::from_ptr(ffi::G_MENU_ATTRIBUTE_ACTION).to_str().unwrap()};
}
#[cfg(any(feature = "v2_36", feature = "dox"))]
lazy_static! {
pub static ref MENU_ATTRIBUTE_ACTION_NAMESPACE: &'static str = unsafe{CStr::from_ptr(ffi::G_MENU_ATTRIBUTE_ACTION_NAMESPACE).to_str().unwrap()};
}
#[cfg(any(feature = "v2_38", feature = "dox"))]
lazy_static! {
pub static ref MENU_ATTRIBUTE_ICON: &'static str = unsafe{CStr::from_ptr(ffi::G_MENU_ATTRIBUTE_ICON).to_str().unwrap()};
}
lazy_static! {
pub static ref MENU_ATTRIBUTE_LABEL: &'static str = unsafe{CStr::from_ptr(ffi::G_MENU_ATTRIBUTE_LABEL).to_str().unwrap()};
}
lazy_static! {
pub static ref MENU_ATTRIBUTE_TARGET: &'static str = unsafe{CStr::from_ptr(ffi::G_MENU_ATTRIBUTE_TARGET).to_str().unwrap()};
}
lazy_static! {
pub static ref MENU_LINK_SECTION: &'static str = unsafe{CStr::from_ptr(ffi::G_MENU_LINK_SECTION).to_str().unwrap()};
}
lazy_static! {
pub static ref MENU_LINK_SUBMENU: &'static str = unsafe{CStr::from_ptr(ffi::G_MENU_LINK_SUBMENU).to_str().unwrap()};
}
lazy_static! {
pub static ref NATIVE_VOLUME_MONITOR_EXTENSION_POINT_NAME: &'static str = unsafe{CStr::from_ptr(ffi::G_NATIVE_VOLUME_MONITOR_EXTENSION_POINT_NAME).to_str().unwrap()};
}
lazy_static! {
pub static ref NETWORK_MONITOR_EXTENSION_POINT_NAME: &'static str = unsafe{CStr::from_ptr(ffi::G_NETWORK_MONITOR_EXTENSION_POINT_NAME).to_str().unwrap()};
}
lazy_static! {
pub static ref PROXY_EXTENSION_POINT_NAME: &'static str = unsafe{CStr::from_ptr(ffi::G_PROXY_EXTENSION_POINT_NAME).to_str().unwrap()};
}
lazy_static! {
pub static ref PROXY_RESOLVER_EXTENSION_POINT_NAME: &'static str = unsafe{CStr::from_ptr(ffi::G_PROXY_RESOLVER_EXTENSION_POINT_NAME).to_str().unwrap()};
}
lazy_static! {
pub static ref SETTINGS_BACKEND_EXTENSION_POINT_NAME: &'static str = unsafe{CStr::from_ptr(ffi::G_SETTINGS_BACKEND_EXTENSION_POINT_NAME).to_str().unwrap()};
}
lazy_static! {
pub static ref TLS_BACKEND_EXTENSION_POINT_NAME: &'static str = unsafe{CStr::from_ptr(ffi::G_TLS_BACKEND_EXTENSION_POINT_NAME).to_str().unwrap()};
}
lazy_static! {
pub static ref TLS_DATABASE_PURPOSE_AUTHENTICATE_CLIENT: &'static str = unsafe{CStr::from_ptr(ffi::G_TLS_DATABASE_PURPOSE_AUTHENTICATE_CLIENT).to_str().unwrap()};
}
lazy_static! {
pub static ref TLS_DATABASE_PURPOSE_AUTHENTICATE_SERVER: &'static str = unsafe{CStr::from_ptr(ffi::G_TLS_DATABASE_PURPOSE_AUTHENTICATE_SERVER).to_str().unwrap()};
}
lazy_static! {
pub static ref VFS_EXTENSION_POINT_NAME: &'static str = unsafe{CStr::from_ptr(ffi::G_VFS_EXTENSION_POINT_NAME).to_str().unwrap()};
}
lazy_static! {
pub static ref VOLUME_IDENTIFIER_KIND_CLASS: &'static str = unsafe{CStr::from_ptr(ffi::G_VOLUME_IDENTIFIER_KIND_CLASS).to_str().unwrap()};
}
lazy_static! {
pub static ref VOLUME_IDENTIFIER_KIND_HAL_UDI: &'static str = unsafe{CStr::from_ptr(ffi::G_VOLUME_IDENTIFIER_KIND_HAL_UDI).to_str().unwrap()};
}
lazy_static! {
pub static ref VOLUME_IDENTIFIER_KIND_LABEL: &'static str = unsafe{CStr::from_ptr(ffi::G_VOLUME_IDENTIFIER_KIND_LABEL).to_str().unwrap()};
}
lazy_static! {
pub static ref VOLUME_IDENTIFIER_KIND_NFS_MOUNT: &'static str = unsafe{CStr::from_ptr(ffi::G_VOLUME_IDENTIFIER_KIND_NFS_MOUNT).to_str().unwrap()};
}
lazy_static! {
pub static ref VOLUME_IDENTIFIER_KIND_UNIX_DEVICE: &'static str = unsafe{CStr::from_ptr(ffi::G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE).to_str().unwrap()};
}
lazy_static! {
pub static ref VOLUME_IDENTIFIER_KIND_UUID: &'static str = unsafe{CStr::from_ptr(ffi::G_VOLUME_IDENTIFIER_KIND_UUID).to_str().unwrap()};
}
lazy_static! {
pub static ref VOLUME_MONITOR_EXTENSION_POINT_NAME: &'static str = unsafe{CStr::from_ptr(ffi::G_VOLUME_MONITOR_EXTENSION_POINT_NAME).to_str().unwrap()};
}
|
#[doc = "Register `SYSCFG_ITLINE25` reader"]
pub type R = crate::R<SYSCFG_ITLINE25_SPEC>;
#[doc = "Field `SPI1` reader - SPI1 interrupt request pending"]
pub type SPI1_R = crate::BitReader;
impl R {
#[doc = "Bit 0 - SPI1 interrupt request pending"]
#[inline(always)]
pub fn spi1(&self) -> SPI1_R {
SPI1_R::new((self.bits & 1) != 0)
}
}
#[doc = "SYSCFG interrupt line 25 status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`syscfg_itline25::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SYSCFG_ITLINE25_SPEC;
impl crate::RegisterSpec for SYSCFG_ITLINE25_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`syscfg_itline25::R`](R) reader structure"]
impl crate::Readable for SYSCFG_ITLINE25_SPEC {}
#[doc = "`reset()` method sets SYSCFG_ITLINE25 to value 0"]
impl crate::Resettable for SYSCFG_ITLINE25_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::libs::idb;
use crate::libs::skyway::MeshRoom;
use crate::model::config::Config;
use futures::join;
use js_sys::Promise;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
pub async fn initialize(
config: Rc<Config>,
common_db: Rc<web_sys::IdbDatabase>,
room_db: Rc<web_sys::IdbDatabase>,
room: MeshRoom,
room_id: Rc<String>,
) -> Option<(Rc<web_sys::IdbDatabase>, web_sys::IdbDatabase, Rc<MeshRoom>)> {
let props = join!(
initialize_room_db(Rc::clone(&room_db), Rc::clone(&room_id)),
initialize_table_db(Rc::clone(&config)),
initialize_room_connection(room)
);
if let Some((room_db, table_db, room)) = join_some!(props.0, props.1, props.2) {
let room_meta_data: js_sys::Object = object! {
"last_access_time": js_sys::Date::now()
}
.into();
idb::assign(
&common_db,
"rooms",
&JsValue::from(room_id.as_str()),
&room_meta_data,
)
.await;
Some((room_db, table_db, room))
} else {
None
}
}
async fn initialize_room_db(
room_db: Rc<web_sys::IdbDatabase>,
room_id: Rc<String>,
) -> Option<Rc<web_sys::IdbDatabase>> {
let room_db = if object_store_names(&room_db)
.into_iter()
.position(|name| name == *room_id.as_ref())
.is_some()
{
room_db
} else {
if let Some(room_db) = idb::create_object_store(&room_db, room_id.as_ref()).await {
Rc::new(room_db)
} else {
return None;
}
};
Some(room_db)
}
async fn initialize_table_db(config: Rc<Config>) -> Option<web_sys::IdbDatabase> {
let table_db_name = format!("{}.table", config.client.db_prefix);
idb::open_db(&table_db_name).await
}
fn object_store_names(db: &web_sys::IdbDatabase) -> Vec<String> {
let mut res = vec![];
let names = db.object_store_names();
for i in 0..names.length() {
if let Some(name) = names.item(i) {
res.push(name);
}
}
res
}
pub async fn initialize_room_connection(room: MeshRoom) -> Option<Rc<MeshRoom>> {
let room = Rc::new(room);
JsFuture::from(Promise::new({
let room = Rc::clone(&room);
&mut move |resolve, _| {
let a = Closure::wrap(Box::new(move || {
let _ = resolve.call1(&js_sys::global(), &JsValue::null());
}) as Box<dyn FnMut()>);
room.on("open", Some(a.as_ref().unchecked_ref()));
a.forget();
}
}))
.await
.ok()
.map(move |_| room)
}
|
// AST node
use super::token::Token;
pub struct AST {
pub children: Vec<AST>,
pub token: Token
}
impl AST {
pub fn new(token: Token, children: Vec<AST>) -> AST {
AST {
token: token,
children: children
}
}
} |
use std::{marker::PhantomData, ops::Deref};
use crate::{ResourceId, World};
/// A trait for accessing read/write multiple resources from a system. This can
/// be used to create dynamic systems that don't specify what they fetch at
/// compile-time.
///
/// For compile-time system data this will all be done for you using
/// `StaticAccessor`.
pub trait Accessor: Sized {
/// Tries to create a new instance of this type. This one returns `Some` in
/// case there is a default, otherwise the system needs to override
/// `System::accessor`.
fn try_new() -> Option<Self>;
/// A list of [`ResourceId`]s the bundle
/// needs read access to in order to
/// build the target resource bundle.
///
/// # Contract
///
/// Exactly return the dependencies you're going to `fetch`! Doing otherwise
/// *will* cause a panic.
///
/// This method is only executed once,
/// thus the returned value may never change
/// (otherwise it has no effect).
///
/// [`ResourceId`]: struct.ResourceId.html
fn reads(&self) -> Vec<ResourceId>;
/// A list of [`ResourceId`]s the bundle
/// needs write access to in order to
/// build the target resource bundle.
///
/// # Contract
///
/// Exactly return the dependencies you're going to `fetch`! Doing otherwise
/// *will* cause a panic.
///
/// This method is only executed once,
/// thus the returned value may never change
/// (otherwise it has no effect).
///
/// [`ResourceId`]: struct.ResourceId.html
fn writes(&self) -> Vec<ResourceId>;
}
impl Accessor for () {
fn try_new() -> Option<Self> {
None
}
fn reads(&self) -> Vec<ResourceId> {
Vec::new()
}
fn writes(&self) -> Vec<ResourceId> {
Vec::new()
}
}
impl<T: ?Sized> Accessor for PhantomData<T> {
fn try_new() -> Option<Self> {
None
}
fn reads(&self) -> Vec<ResourceId> {
Vec::new()
}
fn writes(&self) -> Vec<ResourceId> {
Vec::new()
}
}
/// Either an `Accessor` of the system `T` or a reference to it.
pub enum AccessorCow<'a, 'b, T>
where
AccessorTy<'a, T>: 'b,
T: System<'a> + ?Sized,
'a: 'b,
{
/// A reference to an accessor.
Ref(&'b AccessorTy<'a, T>),
/// An owned accessor.
Owned(AccessorTy<'a, T>),
}
impl<'a, 'b, T> Deref for AccessorCow<'a, 'b, T>
where
AccessorTy<'a, T>: 'b,
T: System<'a> + ?Sized + 'b,
'a: 'b,
{
type Target = AccessorTy<'a, T>;
fn deref(&self) -> &AccessorTy<'a, T> {
match self {
AccessorCow::Ref(r) => r,
AccessorCow::Owned(ref o) => o,
}
}
}
type AccessorTy<'a, T> = <<T as System<'a>>::SystemData as DynamicSystemData<'a>>::Accessor;
/// Trait for fetching data and running systems. Automatically implemented for
/// systems.
pub trait RunNow<'a> {
/// Runs the system now.
///
/// # Panics
///
/// Panics if the system tries to fetch resources
/// which are borrowed in an incompatible way already
/// (tries to read from a resource which is already written to or
/// tries to write to a resource which is read from).
fn run_now(&mut self, world: &'a World);
/// Sets up `World` for a later call to `run_now`.
fn setup(&mut self, world: &mut World);
/// Performs clean up that requires resources from the `World`.
/// This commonly removes components from `world` which depend on external
/// resources.
#[allow(clippy::boxed_local)]
fn dispose(self: Box<Self>, world: &mut World) {
let _ = world;
}
}
impl<'a, T> RunNow<'a> for T
where
T: System<'a>,
{
fn run_now(&mut self, world: &'a World) {
let data = T::SystemData::fetch(&self.accessor(), world);
self.run(data);
}
fn setup(&mut self, world: &mut World) {
T::setup(self, world);
}
fn dispose(self: Box<Self>, world: &mut World) {
T::dispose(*self, world);
}
}
#[repr(u8)]
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug)]
pub enum RunningTime {
VeryShort = 1,
Short = 2,
Average = 3,
Long = 4,
VeryLong = 5,
}
/// A `System`, executed with a set of required [`Resource`]s.
///
/// [`Resource`]: trait.Resource.html
pub trait System<'a> {
/// The resource bundle required to execute this system.
///
/// You will mostly use a tuple of system data (which also implements
/// `SystemData`). You can also create such a resource bundle by simply
/// deriving `SystemData` for a struct.
///
/// Every `SystemData` is also a `DynamicSystemData`.
type SystemData: DynamicSystemData<'a>;
/// Executes the system with the required system
/// data.
fn run(&mut self, data: Self::SystemData);
/// Returns a hint how long the system needs for running.
/// This is used to optimize the way they're executed (might
/// allow more parallelization).
///
/// Defaults to `RunningTime::Average`.
fn running_time(&self) -> RunningTime {
RunningTime::Average
}
/// Return the accessor from the [`SystemData`].
fn accessor<'b>(&'b self) -> AccessorCow<'a, 'b, Self> {
AccessorCow::Owned(
AccessorTy::<'a, Self>::try_new().expect("Missing implementation for `accessor`"),
)
}
/// Sets up the `World` using `Self::SystemData::setup`.
fn setup(&mut self, world: &mut World) {
<Self::SystemData as DynamicSystemData>::setup(&self.accessor(), world)
}
/// Performs clean up that requires resources from the `World`.
/// This commonly removes components from `world` which depend on external
/// resources.
fn dispose(self, world: &mut World)
where
Self: Sized,
{
let _ = world;
}
}
/// A static system data that can specify its dependencies at statically (at
/// compile-time). Most system data is a `SystemData`, the `DynamicSystemData`
/// type is only needed for very special setups.
///
/// You can derive this using the `#[derive(SystemData)]` macro provided by
/// `shred-derive`. That is as simple as enabling the `shred-derive` feature.
///
/// # Examples
///
/// ```rust
/// use shred::{Read, ResourceId, SystemData, World, Write};
///
/// #[derive(Default)]
/// pub struct Clock;
/// #[derive(Default)]
/// pub struct Timer;
///
/// // This will implement `SystemData` for `MySystemData`.
/// // Please note that this will only work if `SystemData`, `World` and `ResourceId` are included.
/// # #[cfg(feature = "shred-derive")]
/// #[derive(SystemData)]
/// pub struct MySystemData<'a> {
/// pub clock: Read<'a, Clock>,
/// pub timer: Write<'a, Timer>,
/// }
/// #
/// # // The following is required for the snippet to compile without the `shred-derive` feature.
/// #
/// # #[cfg(not(feature = "shred-derive"))]
/// # struct MySystemData<'a> {
/// # pub clock: Read<'a, Clock>,
/// # pub timer: Write<'a, Timer>,
/// # }
/// #
/// # #[cfg(not(feature = "shred-derive"))]
/// # impl<'a> SystemData<'a> for MySystemData<'a> {
/// # fn setup(world: &mut World) {
/// # Read::<'_, Clock>::setup(world);
/// # Write::<'_, Timer>::setup(world);
/// # }
/// #
/// # fn fetch(world: &'a World) -> Self {
/// # Self {
/// # clock: Read::<'_, Clock>::fetch(world),
/// # timer: Write::<'_, Timer>::fetch(world),
/// # }
/// # }
/// #
/// # fn reads() -> Vec<ResourceId> {
/// # Read::<'_, Clock>::reads()
/// # }
/// #
/// # fn writes() -> Vec<ResourceId> {
/// # Write::<'_, Timer>::writes()
/// # }
/// # }
/// ```
pub trait SystemData<'a> {
/// Sets up the system data for fetching it from the `World`.
fn setup(world: &mut World);
/// Fetches the system data from `World`. Note that this is only specified
/// for one concrete lifetime `'a`, you need to implement the
/// `SystemData` trait for every possible lifetime.
fn fetch(world: &'a World) -> Self;
/// Returns all read dependencies as fetched from `Self::fetch`.
///
/// Please note that returning wrong dependencies can lead to a panic.
fn reads() -> Vec<ResourceId>;
/// Returns all write dependencies as fetched from `Self::fetch`.
///
/// Please note that returning wrong dependencies can lead to a panic.
fn writes() -> Vec<ResourceId>;
}
impl<'a, T> DynamicSystemData<'a> for T
where
T: SystemData<'a>,
{
type Accessor = StaticAccessor<T>;
fn setup(_: &StaticAccessor<T>, world: &mut World) {
T::setup(world);
}
fn fetch(_: &StaticAccessor<T>, world: &'a World) -> Self {
T::fetch(world)
}
}
impl<'a> SystemData<'a> for () {
fn setup(_: &mut World) {}
fn fetch(_: &'a World) -> Self {}
fn reads() -> Vec<ResourceId> {
Vec::new()
}
fn writes() -> Vec<ResourceId> {
Vec::new()
}
}
/// The static accessor that is used for `SystemData`.
#[derive(Default)]
pub struct StaticAccessor<T> {
marker: PhantomData<fn() -> T>,
}
impl<'a, T> Accessor for StaticAccessor<T>
where
T: SystemData<'a>,
{
fn try_new() -> Option<Self> {
Some(StaticAccessor {
marker: PhantomData,
})
}
fn reads(&self) -> Vec<ResourceId> {
T::reads()
}
fn writes(&self) -> Vec<ResourceId> {
T::writes()
}
}
/// A struct implementing system data indicates that it bundles some resources
/// which are required for the execution.
///
/// This is the more flexible, but complex variant of `SystemData`.
pub trait DynamicSystemData<'a> {
/// The accessor of the `SystemData`, which specifies the read and write
/// dependencies and does the fetching.
type Accessor: Accessor;
/// Sets up `World` for fetching this system data.
fn setup(accessor: &Self::Accessor, world: &mut World);
/// Creates a new resource bundle
/// by fetching the required resources
/// from the [`World`] struct.
///
/// # Contract
///
/// Only fetch the resources you returned from `reads` / `writes`!
///
/// # Panics
///
/// This function may panic if the above contract is violated.
/// This function may panic if the resource doesn't exist. This is only the
/// case if either `setup` was not called or it didn't insert any
/// fallback value.
///
/// [`World`]: trait.World.html
fn fetch(access: &Self::Accessor, world: &'a World) -> Self;
}
impl<'a, T: ?Sized> SystemData<'a> for PhantomData<T> {
fn setup(_: &mut World) {}
fn fetch(_: &World) -> Self {
PhantomData
}
fn reads() -> Vec<ResourceId> {
vec![]
}
fn writes() -> Vec<ResourceId> {
vec![]
}
}
macro_rules! impl_data {
( $($ty:ident),* ) => {
impl<'a, $($ty),*> SystemData<'a> for ( $( $ty , )* )
where $( $ty : SystemData<'a> ),*
{
fn setup(world: &mut World) {
#![allow(unused_variables)]
$(
<$ty as SystemData>::setup(&mut *world);
)*
}
fn fetch(world: &'a World) -> Self {
#![allow(unused_variables)]
( $( <$ty as SystemData<'a>>::fetch(world), )* )
}
fn reads() -> Vec<ResourceId> {
#![allow(unused_mut)]
let mut r = Vec::new();
$( {
let mut reads = <$ty as SystemData>::reads();
r.append(&mut reads);
} )*
r
}
fn writes() -> Vec<ResourceId> {
#![allow(unused_mut)]
let mut r = Vec::new();
$( {
let mut writes = <$ty as SystemData>::writes();
r.append(&mut writes);
} )*
r
}
}
};
}
mod impl_data {
#![cfg_attr(rustfmt, rustfmt_skip)]
use super::*;
impl_data!(A);
impl_data!(A, B);
impl_data!(A, B, C);
impl_data!(A, B, C, D);
impl_data!(A, B, C, D, E);
impl_data!(A, B, C, D, E, F);
impl_data!(A, B, C, D, E, F, G);
impl_data!(A, B, C, D, E, F, G, H);
impl_data!(A, B, C, D, E, F, G, H, I);
impl_data!(A, B, C, D, E, F, G, H, I, J);
impl_data!(A, B, C, D, E, F, G, H, I, J, K);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y);
impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z);
}
|
use std::collections::HashMap;
use std::collections::HashSet;
use std::fs::read_to_string;
fn part1(lines: &Vec<&str>) -> i32 {
let mut num_twos: i32 = 0;
let mut num_threes: i32 = 0;
for line in lines {
let mut char_freqs: HashMap<char, i32> = HashMap::new();
for chr in line.chars() {
let count = char_freqs.entry(chr).or_insert(0);
*count += 1;
}
let values = char_freqs.values();
let values_set: HashSet<&i32> = values.collect();
if values_set.contains(&&2) {
num_twos += 1
}
if values_set.contains(&&3) {
num_threes += 1
}
}
num_twos * num_threes
}
fn part2(lines: &Vec<&str>) -> String {
let mut min_diff: i32 = 1000;
let mut common_letters = String::new();
let mut existing_ids: Vec<&str> = Vec::new();
for line in lines {
for id in &existing_ids {
let mut id_chars = id.chars();
let mut num_diffs = 0;
let mut common_letters_tmp = String::new();
for line_char in line.chars() {
let id_char = id_chars.next();
match id_char {
Some(chr) => {
if line_char != chr {
num_diffs += 1
} else {
common_letters_tmp.push(chr)
}
}
None => num_diffs += 1,
}
if num_diffs > min_diff {
break;
}
}
if num_diffs < min_diff {
min_diff = num_diffs;
common_letters = common_letters_tmp.clone();
}
}
existing_ids.push(line);
}
common_letters
}
pub fn main() {
let filename = "src/day2/input";
let contents = read_to_string(filename).expect("Error reading file");
let lines: Vec<&str> = contents.lines().collect();
print!("part1: {}\n", part1(&lines));
print!("part2: {}", part2(&lines));
}
|
//! Attacks against ciphers which use XOR as the encryption algorithm.
use std::f64;
use utils::data::Data;
use utils::metrics;
use utils::xor::xor;
/// Finds the most likely single-byte key that was used to encrypt the given data.
pub fn best_single_byte_key(data: &Data) -> (Data, f64) {
// Keep track of the best key so far
let (mut best_key, mut best_score) = (Data::new(), 0.0);
// Iterate over every possible byte for the key, and compare its score with the current best
// score.
for key_byte in 0..256 {
let key = Data::from_single_byte(key_byte as u8);
let score = metrics::score_as_english(&xor(data, &key));
if score > best_score {
best_key = key;
best_score = score;
}
}
(best_key, best_score)
}
/// Finds the most likely repeating-XOR key that was used to encrypt the given data.
pub fn best_repeating_key(data: &Data) -> Data {
// First find the most likely key size.
let (mut best_keysize, mut best_score) = (0, f64::INFINITY);
for keysize in 2..40 {
let score = metrics::score_xor_keysize(data, keysize);
if score < best_score {
best_keysize = keysize;
best_score = score;
}
}
// Now split the data into `keysize` streams and solve each one as if it were encrypted using
// single-byte XOR.
let mut key_bytes = Vec::with_capacity(best_keysize);
for ix in 0..best_keysize {
// Fill in the bytes of a particular stream.
let mut stream_bytes = Vec::with_capacity(data.len() / best_keysize + 1);
let mut position = ix;
while position < data.len() {
stream_bytes.push(data.bytes()[position]);
position += best_keysize;
}
// Find the best key for this stream.
let stream_data = Data::from_bytes(stream_bytes);
let (best_key, _) = best_single_byte_key(&stream_data);
key_bytes.push(best_key.bytes()[0]);
}
// Put all the key bytes together to form a single key.
Data::from_bytes(key_bytes)
}
|
#[doc = "Generate markdown from a document tree"];
import std::io;
import std::io::writer_util;
export mk_pass;
fn mk_pass(
writer: fn~() -> io::writer
) -> pass {
ret fn~(
_srv: astsrv::srv,
doc: doc::cratedoc
) -> doc::cratedoc {
write_markdown(doc, writer());
doc
};
}
type ctxt = {
w: io::writer
};
fn write_markdown(
doc: doc::cratedoc,
writer: io::writer
) {
let ctxt = {
w: writer
};
write_crate(ctxt, doc);
}
enum hlvl {
h1 = 1,
h2 = 2,
h3 = 3
}
fn write_header(ctxt: ctxt, lvl: hlvl, title: str) {
let hashes = str::from_chars(vec::init_elt(lvl as uint, '#'));
ctxt.w.write_line(#fmt("%s %s", hashes, title));
ctxt.w.write_line("");
}
fn write_crate(
ctxt: ctxt,
doc: doc::cratedoc
) {
write_header(ctxt, h1, #fmt("Crate %s", doc.topmod.name));
write_top_module(ctxt, doc.topmod);
}
fn write_top_module(
ctxt: ctxt,
moddoc: doc::moddoc
) {
write_mod_contents(ctxt, moddoc);
}
fn write_mod(
ctxt: ctxt,
moddoc: doc::moddoc
) {
let fullpath = str::connect(moddoc.path + [moddoc.name], "::");
write_header(ctxt, h2, #fmt("Module `%s`", fullpath));
write_mod_contents(ctxt, moddoc);
}
#[test]
fn should_write_full_path_to_mod() {
let markdown = test::render("mod a { mod b { mod c { } } }");
assert str::contains(markdown, "## Module `a::b::c`");
}
fn write_mod_contents(
ctxt: ctxt,
doc: doc::moddoc
) {
write_brief(ctxt, doc.brief);
write_desc(ctxt, doc.desc);
for constdoc in *doc.consts {
write_const(ctxt, constdoc);
}
for fndoc in *doc.fns {
write_fn(ctxt, fndoc);
}
for moddoc in *doc.mods {
write_mod(ctxt, moddoc);
}
}
#[test]
fn should_write_crate_brief_description() {
let markdown = test::render("#[doc(brief = \"this is the crate\")];");
assert str::contains(markdown, "this is the crate");
}
#[test]
fn should_write_crate_description() {
let markdown = test::render("#[doc = \"this is the crate\"];");
assert str::contains(markdown, "this is the crate");
}
fn write_fn(
ctxt: ctxt,
doc: doc::fndoc
) {
write_header(ctxt, h3, #fmt("Function `%s`", doc.name));
write_sig(ctxt, doc.sig);
write_brief(ctxt, doc.brief);
write_desc(ctxt, doc.desc);
write_args(ctxt, doc.args);
write_return(ctxt, doc.return);
write_failure(ctxt, doc.failure);
}
fn write_sig(ctxt: ctxt, sig: option<str>) {
alt sig {
some(sig) {
ctxt.w.write_line(code_block_indent(sig));
ctxt.w.write_line("");
}
none { fail "unimplemented" }
}
}
fn code_block_indent(s: str) -> str {
let lines = str::lines_any(s);
let indented = vec::map(lines, { |line| #fmt(" %s", line) });
str::connect(indented, "\n")
}
#[test]
fn should_write_the_function_signature() {
let markdown = test::render("#[doc = \"f\"] fn a() { }");
assert str::contains(markdown, "\n fn a()\n");
}
#[test]
fn should_insert_blank_line_after_fn_signature() {
let markdown = test::render("#[doc = \"f\"] fn a() { }");
assert str::contains(markdown, "fn a()\n\n");
}
#[test]
fn should_correctly_indent_fn_signature() {
let doc = test::create_doc("fn a() { }");
let doc = ~{
topmod: ~{
fns: doc::fnlist([~{
sig: some("line 1\nline 2")
with *doc.topmod.fns[0]
}])
with *doc.topmod
}
with *doc
};
let markdown = test::write_markdown_str(doc);
assert str::contains(markdown, " line 1\n line 2");
}
fn write_brief(
ctxt: ctxt,
brief: option<str>
) {
alt brief {
some(brief) {
ctxt.w.write_line(brief);
ctxt.w.write_line("");
}
none { }
}
}
fn write_desc(
ctxt: ctxt,
desc: option<str>
) {
alt desc {
some(desc) {
ctxt.w.write_line(desc);
ctxt.w.write_line("");
}
none { }
}
}
fn write_args(
ctxt: ctxt,
args: [doc::argdoc]
) {
if vec::is_not_empty(args) {
ctxt.w.write_line("Arguments:");
ctxt.w.write_line("");
vec::iter(args) {|arg| write_arg(ctxt, arg) };
ctxt.w.write_line("");
}
}
fn write_arg(ctxt: ctxt, arg: doc::argdoc) {
assert option::is_some(arg.ty);
ctxt.w.write_str(#fmt(
"* `%s`: `%s`",
arg.name,
option::get(arg.ty)
));
alt arg.desc {
some(desc) {
ctxt.w.write_str(#fmt(" - %s", desc));
}
none { }
}
ctxt.w.write_line("");
}
#[test]
fn should_write_argument_list() {
let source = "fn a(b: int, c: int) { }";
let markdown = test::render(source);
assert str::contains(
markdown,
"Arguments:\n\
\n\
* `b`: `int`\n\
* `c`: `int`\n\
\n"
);
}
#[test]
fn should_not_write_arguments_if_none() {
let source = "fn a() { } fn b() { }";
let markdown = test::render(source);
assert !str::contains(markdown, "Arguments");
}
#[test]
fn should_write_argument_description() {
let source = "#[doc(args(a = \"milk\"))] fn f(a: bool) { }";
let markdown = test::render(source);
assert str::contains(markdown, "`a`: `bool` - milk");
}
fn write_return(
ctxt: ctxt,
doc: doc::retdoc
) {
alt doc.ty {
some(ty) {
ctxt.w.write_str(#fmt("Returns `%s`", ty));
alt doc.desc {
some(d) {
ctxt.w.write_line(#fmt(" - %s", d));
ctxt.w.write_line("");
}
none {
ctxt.w.write_line("");
ctxt.w.write_line("");
}
}
}
none { }
}
}
#[test]
fn should_write_return_type_on_new_line() {
let markdown = test::render("fn a() -> int { }");
assert str::contains(markdown, "\nReturns `int`");
}
#[test]
fn should_write_blank_line_between_return_type_and_next_header() {
let markdown = test::render(
"fn a() -> int { } \
fn b() -> int { }"
);
assert str::contains(markdown, "Returns `int`\n\n##");
}
#[test]
fn should_not_write_return_type_when_there_is_none() {
let markdown = test::render("fn a() { }");
assert !str::contains(markdown, "Returns");
}
#[test]
fn should_write_blank_line_after_return_description() {
let markdown = test::render(
"#[doc(return = \"blorp\")] fn a() -> int { }"
);
assert str::contains(markdown, "blorp\n\n");
}
#[test]
fn should_write_return_description_on_same_line_as_type() {
let markdown = test::render(
"#[doc(return = \"blorp\")] fn a() -> int { }"
);
assert str::contains(markdown, "Returns `int` - blorp");
}
fn write_failure(ctxt: ctxt, str: option<str>) {
alt str {
some(str) {
ctxt.w.write_line(#fmt("Failure conditions: %s", str));
ctxt.w.write_line("");
}
none { }
}
}
#[test]
fn should_write_failure_conditions() {
let markdown = test::render(
"#[doc(failure = \"it's the fail\")] fn a () { }");
assert str::contains(
markdown,
"\n\nFailure conditions: it's the fail\n\n");
}
fn write_const(
ctxt: ctxt,
doc: doc::constdoc
) {
write_header(ctxt, h3, #fmt("Const `%s`", doc.name));
write_sig(ctxt, doc.ty);
write_brief(ctxt, doc.brief);
write_desc(ctxt, doc.desc);
}
#[test]
fn should_write_const_header() {
let markdown = test::render("const a: bool = true;");
assert str::contains(markdown, "### Const `a`\n\n");
}
#[test]
fn should_write_const_description() {
let markdown = test::render(
"#[doc(brief = \"a\", desc = \"b\")]\
const a: bool = true;");
assert str::contains(markdown, "\n\na\n\nb\n\n");
}
#[cfg(test)]
mod test {
fn render(source: str) -> str {
let doc = create_doc(source);
let markdown = write_markdown_str(doc);
#debug("markdown: %s", markdown);
markdown
}
fn create_doc(source: str) -> doc::cratedoc {
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
#debug("doc (extract): %?", doc);
let doc = tystr_pass::mk_pass()(srv, doc);
#debug("doc (tystr): %?", doc);
let doc = path_pass::mk_pass()(srv, doc);
#debug("doc (path): %?", doc);
let doc = attr_pass::mk_pass()(srv, doc);
#debug("doc (attr): %?", doc);
doc
}
fn write_markdown_str(
doc: doc::cratedoc
) -> str {
let buffer = io::mk_mem_buffer();
let writer = io::mem_buffer_writer(buffer);
write_markdown(doc, writer);
ret io::mem_buffer_str(buffer);
}
#[test]
fn write_markdown_should_write_crate_header() {
let srv = astsrv::mk_srv_from_str("");
let doc = extract::from_srv(srv, "belch");
let doc = attr_pass::mk_pass()(srv, doc);
let markdown = write_markdown_str(doc);
assert str::contains(markdown, "# Crate belch");
}
#[test]
fn write_markdown_should_write_function_header() {
let markdown = render("fn func() { }");
assert str::contains(markdown, "### Function `func`");
}
#[test]
fn write_markdown_should_write_mod_headers() {
let markdown = render("mod moo { }");
assert str::contains(markdown, "## Module `moo`");
}
#[test]
fn should_leave_blank_line_after_header() {
let markdown = render("mod morp { }");
assert str::contains(markdown, "Module `morp`\n\n");
}
#[test]
fn should_leave_blank_line_between_fn_header_and_sig() {
let markdown = render("#[doc(brief = \"brief\")] fn a() { }");
assert str::contains(markdown, "Function `a`\n\n fn a()");
}
#[test]
fn should_leave_blank_line_after_brief() {
let markdown = render("#[doc(brief = \"brief\")] fn a() { }");
assert str::contains(markdown, "brief\n\n");
}
#[test]
fn should_leave_blank_line_between_brief_and_desc() {
let markdown = render(
"#[doc(brief = \"brief\", desc = \"desc\")] fn a() { }"
);
assert str::contains(markdown, "brief\n\ndesc");
}
} |
use super::error::{NodError, Result};
use super::fetch;
use super::path::WorkDir;
use super::platform::{Arch, Platform};
use super::teewriter::ProgressWriter;
use super::utils::{getarch, getplatform};
use super::version::Version;
use libarchive::archive::{self, ReadFilter, ReadFormat};
use libarchive::reader::Builder;
use libarchive::writer;
use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use serde_json;
use url::Url;
#[cfg(windows)]
fn symlink<S: AsRef<Path>, D: AsRef<Path>>(source: S, dest: D) -> std::io::Result<()> {
std::os::windows::fs::symlink_dir(source, dest)
}
#[cfg(unix)]
fn symlink<S: AsRef<Path>, D: AsRef<Path>>(source: S, dest: D) -> std::io::Result<()> {
std::os::unix::fs::symlink(source, dest)
}
// use reqwest::header::CONTENT;
const NODE_URL: &'static str = "http://nodejs.org";
pub trait Progress {
fn progress(&mut self, progress: u64, total: u64);
}
pub struct Node {
platform: Platform,
arch: Arch,
path: WorkDir,
url: Url,
}
impl Node {
pub fn new<P: AsRef<Path>>(path: P) -> Result<Node> {
let arch = getarch()?;
let platform = getplatform()?;
let mut root = WorkDir::new(path);
let url = Url::parse(NODE_URL)?;
root.ensure()?;
let n = Node {
arch: arch,
platform: platform,
path: root,
url: url,
};
Ok(n)
}
pub fn get_version<T: Into<String>>(&self, version: T) -> Option<Version> {
let mut v = version.into();
if !v.starts_with("v") {
v = format!("v{}", v);
}
let versions = self.available_versions();
if versions.is_err() {
println!("{}", versions.err().unwrap());
return None;
}
if let Some(v) = versions.unwrap().iter().find(|ver| ver.version == v) {
return Some(v.clone());
}
None
}
pub fn download_size(&self, version: &Version) -> Result<(u64)> {
let mut url = self.url.clone();
let path = version.get_url(&self.platform, &self.arch, false);
url.set_path(&*path);
let headers = fetch::download_header(url)?;
let len = headers
.get("Content-Length")
.map(|ct_len| ct_len.to_str().unwrap().parse::<u64>().unwrap())
.unwrap_or(0);
Ok(len)
}
pub fn download<P: Progress>(&self, version: &Version, write: &mut P) -> Result<()> {
let mut path = self.path.cache();
path.push(version.get_cache_name(&self.platform, &self.arch, false));
if path.exists() {
return Ok(());
}
let size = self.download_size(version)?;
let mut file = File::create(path)?;
{
let writer = ProgressWriter::new(&mut file, write, size as u64);
let mut url = self.url.clone();
url.set_path(&*version.get_url(&self.platform, &self.arch, false));
fetch::download_to(url.as_str(), writer)?;
}
file.flush()?;
Ok(())
}
pub fn unpack(&self, version: &Version) -> Result<()> {
let mut path = self.path.cache();
path.push(version.get_cache_name(&self.platform, &self.arch, false));
if !path.exists() {
return Err(NodError::Other("version not downloaded"));
}
let mut builder = Builder::new();
builder.support_format(ReadFormat::All)?;
builder.support_filter(ReadFilter::All)?;
let mut reader = builder.open_file(path)?;
let mut opts = archive::ExtractOptions::new();
opts.add(archive::ExtractOption::Time);
let writer = writer::Disk::new();
let out_path = self.path.destination();
writer.write(&mut reader, Some(out_path.to_string_lossy().as_ref()))?;
Ok(())
}
pub fn link(&self, version: &Version) -> Result<()> {
let mut path = self.path.destination();
path.push(version.get_dist_name(&self.platform, &self.arch, false));
let current = self.path.current();
if current.exists() {
std::fs::remove_file(¤t)?;
}
symlink(path, current)?;
Ok(())
}
pub fn available_versions(&self) -> Result<Vec<Version>> {
let mut u = self.url.clone();
u.set_path("dist/index.json");
let result = fetch::download(u.as_str())?;
//let as_string = String::from_utf8(result)?;
let decoded: Vec<Version> = serde_json::from_slice(&result)?;
Ok(decoded)
}
pub fn installed_versions(&self) -> Result<Vec<String>> {
let mut dest = self.path.destination();
let mut out = Vec::new();
for entry in dest.read_dir()? {
let entry = entry?;
let path = entry.path();
if !path.is_dir() {
continue;
}
let s = path.file_name().unwrap().to_str().unwrap().to_string();
let k = s
.replace("node", "")
.replace(self.platform.to_string().as_str(), "")
.replace(self.arch.to_string().as_str(), "")
.replace("-", "");
out.push(k);
}
out.sort_by(|a, b| b.cmp(a));
Ok(out)
}
pub fn clean_cache(&self) -> Result<u64> {
let cacheDir = self.path.cache();
let files = cacheDir.read_dir()?;
let mut size: u64 = 0;
for file in files {
let entry = file?;
let path = entry.path();
let meta = entry.metadata()?;
size += meta.len();
if path.is_file() {
fs::remove_file(path);
}
}
Ok(size)
}
} |
// vim:set et sw=4 ts=4 ft=rust:
// Adapted from: https://github.com/steveyen/sqld3/blob/master/sql.pegjs
// And: https://www.sqlite.org/lang.html
use definitions::*;
#[pub]
rusql_stmt -> RusqlStatement
= whitespace s:(alter_table_stmt) whitespace semicolon { s }
/ whitespace s:(create_table_stmt) whitespace semicolon { s }
/ whitespace s:(delete_stmt) whitespace semicolon { s }
/ whitespace s:(drop_table_stmt) whitespace semicolon { s }
/ whitespace s:(insert_stmt) whitespace semicolon { s }
/ whitespace s:(select_stmt) whitespace semicolon { s }
/ whitespace s:(update_stmt) whitespace semicolon { s }
#[pub]
rusql_parse -> Vec<RusqlStatement>
= (r:rusql_stmt whitespace { r })+
//
// Statements
//
// ALTER TABLE
// https://www.sqlite.org/lang_altertable.html
alter_table_stmt -> RusqlStatement
= ALTER TABLE n:table_name a:(rename_to / add_column) {
let def = AlterTableDef {
name: n,
mode: a,
};
RusqlStatement::AlterTable(def)
}
rename_to -> AlterTable
= RENAME TO n:table_name { AlterTable::RenameTo(n) }
add_column -> AlterTable
= ADD COLUMN? c:column_def { AlterTable::AddColumn(c) }
// CREATE TABLE
// https://www.sqlite.org/lang_createtable.html
create_table_stmt -> RusqlStatement
= CREATE TABLE i:(IF NOT EXISTS)?
n:table_name whitespace lparen c:(column_def ++ comma) rparen {
let def = TableDef {
table_name: n,
columns: c,
if_not_exists: i.is_some(),
};
RusqlStatement::CreateTable(def)
}
column_def -> ColumnDef
= n:column_name t:(type_name)? c:(column_constraint)* {
ColumnDef {
name: n,
column_type: t,
column_constraints: c,
}
}
column_constraint -> ColumnConstraint
= (CONSTRAINT name)? (PRIMARY KEY) {
ColumnConstraint::PrimaryKey
}
// DELETE
// https://www.sqlite.org/lang_delete.html
delete_stmt -> RusqlStatement
= DELETE FROM n:qualified_table_name w:where_expr? {
let def = DeleteDef {
name: n,
where_expr: w,
};
RusqlStatement::Delete(def)
}
// DROP TABLE
// https://www.sqlite.org/lang_droptable.html
drop_table_stmt -> RusqlStatement
= DROP TABLE n:table_name {
let def = DropTableDef {
name: n,
};
RusqlStatement::DropTable(def)
}
// INSERT
// https://www.sqlite.org/lang_insert.html
insert_stmt -> RusqlStatement
= INSERT INTO n:table_name cn:insert_column_name? d:insert_data_source {
let def = InsertDef {
table_name: n,
column_names: cn,
data_source: d,
};
RusqlStatement::Insert(def)
}
insert_data_source -> InsertDataSource
= VALUES v:(insert_values ++ comma) { InsertDataSource::Values(v) }
/ s:select_stmt {
match s {
RusqlStatement::Select(stmt) => InsertDataSource::Select(stmt),
_ => InsertDataSource::Error,
}
}
/ DEFAULT VALUES { InsertDataSource::DefaultValues }
insert_column_name -> Vec<String>
= whitespace lparen s:(column_name ++ comma) rparen { s }
insert_values -> Vec<LiteralValue>
= whitespace lparen l:(literal_value ++ comma) rparen { l }
// SELECT
// https://www.sqlite.org/lang_select.html
select_stmt -> RusqlStatement
= SELECT r:result_column
f:from_clause?
w:where_expr?
o:(ORDER BY o:(ordering_term ++ comma) { o })? {
let def = SelectDef {
result_column: r,
from_clause: f,
where_expr: w,
ordering_terms: o,
};
RusqlStatement::Select(def)
}
from_clause -> FromClause
= FROM t:table_or_subquery j:join_clause+ {
FromClause::JoinClause(t, Some(j))
}
/ FROM t:(table_or_subquery ++ comma) { FromClause::TableOrSubquery(t) }
join_operator -> JoinOperator
= JOIN { JoinOperator::Inner }
/ NATURAL JOIN { JoinOperator::Natural }
join_clause -> JoinClause
= j:join_operator t:table_or_subquery c:join_constraint? { (j, t, c) }
join_constraint -> JoinConstraint
= ON e:expr { JoinConstraint::On(e) }
result_column -> ResultColumn
= whitespace1 a:asterisk { ResultColumn::Asterisk }
/ whitespace1 e:(expr ++ comma) { ResultColumn::Expressions(e) }
table_or_subquery -> String
= table_name
ordering_term -> OrderingTerm
= e:expr /*(COLLATE collation_name)?*/ o:asc_or_desc? {
OrderingTerm {
expr: e,
order: if let Some(order) = o { order } else { Order::Ascending }
}
}
asc_or_desc -> Order
= ASC { Order::Ascending }
/ DESC { Order::Descending }
// UPDATE
// https://www.sqlite.org/lang_update.html
update_stmt -> RusqlStatement
= UPDATE n:qualified_table_name SET s:(update_column_equals ++ comma) w:where_expr? {
let def = UpdateDef {
name: n,
set: s,
where_expr: w,
};
RusqlStatement::Update(def)
}
update_column_equals -> (String, Expression)
= n:column_name equals e:expr { (n, e) }
qualified_table_name -> String
= table_name
//
// Expressions
// https://www.sqlite.org/lang_expr.html
//
value -> Expression
= whitespace e:(
l:literal_value { Expression::LiteralValue(l) }
/ lparen e:expr rparen { e }
/ t:table_name dot n:column_name { Expression::TableName((t, box Expression::ColumnName(n))) }
/ !unary_operator n:column_name { Expression::ColumnName(n) }
/ u:unary_operator e:expr { Expression::UnaryOperator((u, box e)) }
) { e }
expr -> Expression
= whitespace (
e1:value b:binary_operator e2:expr { Expression::BinaryOperator((b, box e1, box e2)) }
/ v:value { v }
)
where_expr -> Expression
= WHERE whitespace1 e:expr { e }
binary_operator -> BinaryOperator
= whitespace b:(
asterisk { BinaryOperator::Mult }
/ slash { BinaryOperator::Divide }
/ percent { BinaryOperator::Modulo }
/ plus { BinaryOperator::Plus }
/ minus { BinaryOperator::Minus }
/ not_equals { BinaryOperator::NotEquals }
/ rshift { BinaryOperator::RShift }
/ lshift { BinaryOperator::LShift }
/ le { BinaryOperator::LessEq }
/ lt { BinaryOperator::Less }
/ ge { BinaryOperator::GreaterEq }
/ gt { BinaryOperator::Greater }
/ equals { BinaryOperator::Equals }
/ and { BinaryOperator::And }
/ or { BinaryOperator::Or }
/ band { BinaryOperator::BitAnd }
/ bor { BinaryOperator::BitOr }
) { b }
unary_operator -> UnaryOperator
= plus { UnaryOperator::Plus }
/ minus { UnaryOperator::Minus }
/ not { UnaryOperator::Not }
/ bneg { UnaryOperator::BitNeg }
//////////////////////////////////////////////////////////////////////////////////////////////////
whitespace = [ \t\n\r]*
whitespace1 = [ \t\n\r]+
semicolon = ";"
lparen = "("
rparen = ")"
comma = ","
asterisk = "*"
equals = "==" / "="
not_equals = "!=" / "<>"
plus = "+"
minus = "-"
dot = "."
slash = "/"
percent = "%"
and = whitespace "AND"
not = whitespace "NOT"
or = whitespace "OR"
lt = "<"
gt = ">"
le = "<="
ge = ">="
band = "&"
bor = "|"
bneg = "~"
rshift = ">>"
lshift = "<<"
string_literal -> String
= "\"" s:string "\"" { s }
/ "'" s:string_sq "'" { s }
string -> String
= (escape_char / [^"])* { match_str.to_string() } //"// (syntax highlight fix)
string_sq -> String
= (escape_char / [^'])* { match_str.to_string() }
escape_char = "\\" .
ALTER = whitespace "ALTER"
CREATE = whitespace "CREATE"
DELETE = whitespace "DELETE"
DROP = whitespace "DROP"
INSERT = whitespace "INSERT"
SELECT = whitespace "SELECT"
UPDATE = whitespace "UPDATE"
ADD = whitespace1 "ADD"
ASC = whitespace1 "ASC"
BY = whitespace1 "BY"
COLUMN = whitespace1 "COLUMN"
CONSTRAINT = whitespace1 "CONSTRAINT"
DEFAULT = whitespace1 "DEFAULT"
DESC = whitespace1 "DESC"
EXISTS = whitespace1 "EXISTS"
FROM = whitespace1 "FROM"
JOIN = whitespace1 "JOIN"
INTEGER = whitespace1 "INTEGER"
INTO = whitespace1 "INTO"
IF = whitespace1 "IF"
IS = whitespace1 "IS"
KEY = whitespace1 "KEY"
NATURAL = whitespace1 "NATURAL"
NOT = whitespace1 "NOT"
ON = whitespace1 "ON"
ORDER = whitespace1 "ORDER"
PRIMARY = whitespace1 "PRIMARY"
RENAME = whitespace1 "RENAME"
SET = whitespace1 "SET"
TABLE = whitespace1 "TABLE"
TEXT = whitespace1 "TEXT"
TO = whitespace1 "TO"
VALUES = whitespace1 "VALUES"
WHERE = whitespace1 "WHERE"
// no whitespace name
nws_name -> String
= [A-Za-z0-9_]+ { match_str.to_string() }
name -> String
= whitespace1 n:nws_name { n }
table_name -> String
= whitespace n:nws_name { n }
column_name -> String
= whitespace n:nws_name { n }
type_name -> ColumnType
= INTEGER { ColumnType::Integer }
/ TEXT { ColumnType::Text }
literal_value -> LiteralValue
= whitespace ([0-9]+ { LiteralValue::Integer(match_str.parse::<isize>().unwrap()) })
/ whitespace (s:string_literal { LiteralValue::Text(s) })
|
//! Easy use of LEDs.
use peripheral;
/// All the LEDs.
pub static LEDS: [Led; 4] = [Led { i: 12 },
Led { i: 13 },
Led { i: 14 },
Led { i: 15 }];
/// A single LED.
pub struct Led {
i: u8,
}
impl Led {
/// Turns the LED on.
pub fn on(&self) {
let bsrr = &peripheral::gpiod().bsrr;
match self.i {
12 => bsrr.write(|w| w.bs12(true)),
13 => bsrr.write(|w| w.bs13(true)),
14 => bsrr.write(|w| w.bs14(true)),
15 => bsrr.write(|w| w.bs15(true)),
_ => {}
}
}
/// Turns the LED off.
pub fn off(&self) {
let bsrr = &peripheral::gpiod().bsrr;
match self.i {
12 => bsrr.write(|w| w.br12(true)),
13 => bsrr.write(|w| w.br13(true)),
14 => bsrr.write(|w| w.br14(true)),
15 => bsrr.write(|w| w.br15(true)),
_ => {}
}
}
}
/// Initializes the necessary stuff to drive the LEDs on and off.
///
/// # Safety
///
/// - Must be called once
/// - Must be called in an interrupt-free environment
pub unsafe fn init() {
let gpiod = peripheral::gpiod_mut();
let rcc = peripheral::rcc_mut();
// RCC: Enable GPIOD
rcc.ahb1enr.modify(|_, w| w.gpioden(true));
// GPIOD: Configure pins 12-15 as outputs
gpiod.moder.modify(|_, w| {
w.moder12(0b01)
.moder13(0b01)
.moder14(0b01)
.moder15(0b01)
});
}
/// An enum over the LEDs, each LED has associated to it a colour.
pub enum Colour {
/// Green
Green,
/// Orange
Orange,
/// Red
Red,
/// Blue
Blue,
}
impl Colour {
/// Turns on this LED.
pub fn on(&self) {
match *self {
Colour::Green => LEDS[0].on(),
Colour::Orange => LEDS[1].on(),
Colour::Red => LEDS[2].on(),
Colour::Blue => LEDS[3].on(),
}
}
/// Turns off this LED.
pub fn off(&self) {
match *self {
Colour::Green => LEDS[0].off(),
Colour::Orange => LEDS[1].off(),
Colour::Red => LEDS[2].off(),
Colour::Blue => LEDS[3].off(),
}
}
}
|
/*
chapter 4
syntax and semantics
*/
fn main() {
enum Message {
Quit,
ChangeColor(i32, i32, i32),
Move { x: i32, y: i32 },
Write(&'static str),
}
fn quit() {
println!("quit the program");
}
fn change_color(r: i32, g: i32, b: i32) {
let n = r + g + b;
println!("{}", n);
}
fn move_cursor(x: i32, y: i32) {
let n = x + y;
println!("{}", n);
}
fn process_message(msg: Message) {
match msg {
Message::Quit => quit(),
Message::ChangeColor(r, g, b) => change_color(r, g, b),
Message::Move { x: a, y: b } => move_cursor(a, b),
Message::Write(s) => println!("{}", s),
};
}
process_message(Message::Quit);
process_message(Message::ChangeColor(5, 6, 7));
process_message(Message::Move { x: 8, y: 9 });
process_message(Message::Write("this is a string"));
}
// output should be:
/*
*/
|
use strum_macros::AsRefStr;
#[derive(AsRefStr, Debug)]
#[strum(serialize_all = "lowercase")]
pub(crate) enum RequestType {
Login,
DbStats,
Get,
Set,
}
|
#[macro_use]
extern crate log;
use clap::{App, Arg};
use std::path::PathBuf;
use archiver::cli;
use archiver::config;
use archiver::ctx::Ctx;
use archiver::manual_file::ManualFile;
use archiver::staging;
use archiver::mountable::Mountable;
fn cli_opts<'a, 'b>() -> App<'a, 'b> {
cli::base_opts()
.about("Stages media from the local filesystem for the next upload run")
.arg(Arg::with_name("PATH")
.help("Path to upload from")
.required(true)
.index(1))
}
fn main() {
archiver::cli::run(|| {
let matches = cli_opts().get_matches();
let cfg = config::Config::from_file(matches.value_of("config").unwrap_or("archiver.toml"));
let ctx = Ctx::create(cfg?)?;
let dir = matches.value_of("PATH").expect("Couldn't get path");
let path = PathBuf::from(dir);
let device_name = path.file_name()
.expect("Couldn't get file name")
.to_str()
.expect("Couldn't convert device name to str")
.to_string();
let staging = ctx.staging().mount()?;
info!("Staging to: {:?}", &staging);
for file in ManualFile::iter_from(path) {
staging::stage_file(file, &staging, &device_name)?;
}
Ok(())
})
}
|
//mod historical;
mod simulated;
//pub use historical::Historical;
pub use simulated::Simulated;
use crate::economy::{Market, Monetary, AssetSymbol};
use crate::traders::{Order, Action};
use async_trait::async_trait;
use binance_async::model::{Order as QueryOrder, Symbol};
use std::fmt::Debug;
use std::time::Duration;
#[derive(Debug)]
pub enum Event {
SetMarketValue(String, Monetary),
SetAssetBalance(String, Monetary),
ExecutedOrder(QueryOrder, Monetary),
Evaluate(i64),
}
pub type MarketData = Symbol;
#[async_trait]
pub trait Environment {
async fn initialize(&mut self) -> Result<Vec<MarketData>, ()>;
async fn poll(&mut self) -> Event;
async fn order(&mut self, symbol: &str, order: Order) -> Result<(), ()>;
async fn update_balances(&self, balances: Vec<(&AssetSymbol, Monetary)>);
}
|
///
/// ## slip.rs
///
/// support Serial Line IP protocol
/// ref: IETF RFC1055
///
/// * special characters: END 192, ESC 219.
/// * sending data: host sends data in the packet.
/// * If a byte is the same code as an END character, a two byte sequence of ESC and
/// 220 is sent instead.
/// * If a byte is the same as an ESC char a two byte sequence of ESC and 221 is sent
/// instead.
/// * Begin and end packets with an END char
/// * 1006 bytes recommended maximum datagram size
/// * SLIP does not implicitly provide addressing
/// * |
use crate::algorithms::Bounded;
use euclid::{num::Zero, Length, Point2D, Size2D, Vector2D};
/// An axis-aligned bounding box.
#[derive(Debug, PartialEq)]
pub struct BoundingBox<S> {
bottom_left: Point2D<f64, S>,
top_right: Point2D<f64, S>,
}
impl<S> BoundingBox<S> {
/// Create a new [`BoundingBox`] around two points.
pub fn new(first: Point2D<f64, S>, second: Point2D<f64, S>) -> Self {
let min_x = f64::min(first.x, second.x);
let min_y = f64::min(first.y, second.y);
let max_x = f64::max(first.x, second.x);
let max_y = f64::max(first.y, second.y);
BoundingBox::new_unchecked(
Point2D::new(min_x, min_y),
Point2D::new(max_x, max_y),
)
}
/// Create a new [`BoundingBox`] without ensuring the bottom-left and
/// top-right corners are actually in the bottom-left and top-right.
pub fn new_unchecked(
bottom_left: Point2D<f64, S>,
top_right: Point2D<f64, S>,
) -> Self {
debug_assert!(bottom_left.x <= top_right.x);
debug_assert!(bottom_left.y <= top_right.y);
BoundingBox {
bottom_left,
top_right,
}
}
/// Create a [`BoundingBox`] based on it's centre and dimensions (as an
/// [`euclid::Size2D`]).
pub fn from_centre_and_size(
centre: Point2D<f64, S>,
size: Size2D<f64, S>,
) -> Self {
BoundingBox::from_centre_and_dimensions(
centre,
Length::new(size.width),
Length::new(size.height),
)
}
/// Create a [`BoundingBox`] based on it's centre and dimensions.
pub fn from_centre_and_dimensions(
centre: Point2D<f64, S>,
width: Length<f64, S>,
height: Length<f64, S>,
) -> Self {
debug_assert!(
width >= Length::zero(),
"{} should not be negative",
width
);
debug_assert!(
height >= Length::zero(),
"{} should not be negative",
height
);
let diagonal = Vector2D::from_lengths(width / 2.0, height / 2.0);
let bottom_left = centre - diagonal;
let top_right = centre + diagonal;
BoundingBox::new_unchecked(bottom_left, top_right)
}
/// How wide is the [`BoundingBox`] in the X direction.
pub fn width(self) -> Length<f64, S> { Length::new(self.diagonal().x) }
/// How high is the [`BoundingBox`] in the Y direction.
pub fn height(self) -> Length<f64, S> { Length::new(self.diagonal().y) }
/// Calculate the box's area.
pub fn area(self) -> f64 {
let Vector2D { x, y, .. } = self.diagonal();
x * y
}
/// A vector from the bottom-left corner to the top-right corner.
pub fn diagonal(self) -> Vector2D<f64, S> {
self.top_right - self.bottom_left
}
/// Merge two [`BoundingBox`]es.
pub fn merge(
left: BoundingBox<S>,
right: BoundingBox<S>,
) -> BoundingBox<S> {
BoundingBox::new(left.bottom_left, right.top_right)
}
/// Create a [`BoundingBox`] which fully encompasses a set of [`Bounded`]
/// items.
pub fn around<I, B>(items: I) -> Option<BoundingBox<S>>
where
I: IntoIterator<Item = B>,
B: Bounded<S>,
{
items
.into_iter()
.map(|b| b.bounding_box())
.fold(None, |acc, item| match acc {
Some(acc) => Some(BoundingBox::merge(acc, item)),
None => Some(item),
})
}
/// The bottom-left corner.
pub fn bottom_left(self) -> Point2D<f64, S> { self.bottom_left }
/// The bottom-right corner.
pub fn bottom_right(self) -> Point2D<f64, S> {
self.bottom_left + Vector2D::from_lengths(self.width(), Length::zero())
}
/// The top-right corner.
pub fn top_right(self) -> Point2D<f64, S> { self.top_right }
/// The top-left corner.
pub fn top_left(self) -> Point2D<f64, S> {
self.bottom_left + Vector2D::from_lengths(Length::zero(), self.height())
}
/// The minimum X value.
pub fn min_x(self) -> f64 { self.bottom_left.x }
/// The minimum Y value.
pub fn min_y(self) -> f64 { self.bottom_left.y }
/// The maximum X value.
pub fn max_x(self) -> f64 { self.top_right.x }
/// The maximum Y value.
pub fn max_y(self) -> f64 { self.top_right.y }
/// Does this [`BoundingBox`] fully contain another?
pub fn fully_contains(self, other: BoundingBox<S>) -> bool {
self.min_x() <= other.min_x()
&& other.max_x() <= self.max_x()
&& self.min_y() <= other.min_y()
&& other.max_y() <= self.max_y()
}
/// Do these two [`BoundingBox`]es overlap?
pub fn intersects_with(&self, other: BoundingBox<S>) -> bool {
// FIXME: Actually implement this
self.fully_contains(other)
}
}
impl<Space> Copy for BoundingBox<Space> {}
impl<Space> Clone for BoundingBox<Space> {
fn clone(&self) -> Self { *self }
}
#[cfg(feature = "ecs")]
impl<S: 'static> specs::Component for BoundingBox<S> {
type Storage = specs::FlaggedStorage<Self, specs::DenseVecStorage<Self>>;
}
// The builtin impl for euclid::Point2D saw a type parameter and because it's
// conservative, it only automatically implemented Send + Sync for S: Send +
// Sync.
//
// A bounding box is just a couple numbers, so this is perfectly safe.
unsafe impl<S> Send for BoundingBox<S> {}
unsafe impl<S> Sync for BoundingBox<S> {}
#[cfg(test)]
mod tests {
use super::*;
use euclid::default::Point2D;
#[test]
fn bounding_box_around_corners_gives_same_bounding_box() {
let original =
BoundingBox::new(Point2D::zero(), Point2D::new(10.0, 10.0));
let corners = vec![
original.bottom_left(),
original.bottom_right(),
original.top_left(),
original.top_right(),
];
let got = BoundingBox::around(corners).unwrap();
assert_eq!(got, original);
}
}
|
#[doc = "Register `RCC_OCENCLRR` reader"]
pub type R = crate::R<RCC_OCENCLRR_SPEC>;
#[doc = "Register `RCC_OCENCLRR` writer"]
pub type W = crate::W<RCC_OCENCLRR_SPEC>;
#[doc = "Field `HSION` reader - HSION"]
pub type HSION_R = crate::BitReader;
#[doc = "Field `HSION` writer - HSION"]
pub type HSION_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HSIKERON` reader - HSIKERON"]
pub type HSIKERON_R = crate::BitReader;
#[doc = "Field `HSIKERON` writer - HSIKERON"]
pub type HSIKERON_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSION` reader - CSION"]
pub type CSION_R = crate::BitReader;
#[doc = "Field `CSION` writer - CSION"]
pub type CSION_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSIKERON` reader - CSIKERON"]
pub type CSIKERON_R = crate::BitReader;
#[doc = "Field `CSIKERON` writer - CSIKERON"]
pub type CSIKERON_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DIGBYP` reader - DIGBYP"]
pub type DIGBYP_R = crate::BitReader;
#[doc = "Field `DIGBYP` writer - DIGBYP"]
pub type DIGBYP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HSEON` reader - HSEON"]
pub type HSEON_R = crate::BitReader;
#[doc = "Field `HSEON` writer - HSEON"]
pub type HSEON_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HSEKERON` reader - HSEKERON"]
pub type HSEKERON_R = crate::BitReader;
#[doc = "Field `HSEKERON` writer - HSEKERON"]
pub type HSEKERON_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HSEBYP` reader - HSEBYP"]
pub type HSEBYP_R = crate::BitReader;
#[doc = "Field `HSEBYP` writer - HSEBYP"]
pub type HSEBYP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - HSION"]
#[inline(always)]
pub fn hsion(&self) -> HSION_R {
HSION_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - HSIKERON"]
#[inline(always)]
pub fn hsikeron(&self) -> HSIKERON_R {
HSIKERON_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 4 - CSION"]
#[inline(always)]
pub fn csion(&self) -> CSION_R {
CSION_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - CSIKERON"]
#[inline(always)]
pub fn csikeron(&self) -> CSIKERON_R {
CSIKERON_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 7 - DIGBYP"]
#[inline(always)]
pub fn digbyp(&self) -> DIGBYP_R {
DIGBYP_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - HSEON"]
#[inline(always)]
pub fn hseon(&self) -> HSEON_R {
HSEON_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - HSEKERON"]
#[inline(always)]
pub fn hsekeron(&self) -> HSEKERON_R {
HSEKERON_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - HSEBYP"]
#[inline(always)]
pub fn hsebyp(&self) -> HSEBYP_R {
HSEBYP_R::new(((self.bits >> 10) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - HSION"]
#[inline(always)]
#[must_use]
pub fn hsion(&mut self) -> HSION_W<RCC_OCENCLRR_SPEC, 0> {
HSION_W::new(self)
}
#[doc = "Bit 1 - HSIKERON"]
#[inline(always)]
#[must_use]
pub fn hsikeron(&mut self) -> HSIKERON_W<RCC_OCENCLRR_SPEC, 1> {
HSIKERON_W::new(self)
}
#[doc = "Bit 4 - CSION"]
#[inline(always)]
#[must_use]
pub fn csion(&mut self) -> CSION_W<RCC_OCENCLRR_SPEC, 4> {
CSION_W::new(self)
}
#[doc = "Bit 5 - CSIKERON"]
#[inline(always)]
#[must_use]
pub fn csikeron(&mut self) -> CSIKERON_W<RCC_OCENCLRR_SPEC, 5> {
CSIKERON_W::new(self)
}
#[doc = "Bit 7 - DIGBYP"]
#[inline(always)]
#[must_use]
pub fn digbyp(&mut self) -> DIGBYP_W<RCC_OCENCLRR_SPEC, 7> {
DIGBYP_W::new(self)
}
#[doc = "Bit 8 - HSEON"]
#[inline(always)]
#[must_use]
pub fn hseon(&mut self) -> HSEON_W<RCC_OCENCLRR_SPEC, 8> {
HSEON_W::new(self)
}
#[doc = "Bit 9 - HSEKERON"]
#[inline(always)]
#[must_use]
pub fn hsekeron(&mut self) -> HSEKERON_W<RCC_OCENCLRR_SPEC, 9> {
HSEKERON_W::new(self)
}
#[doc = "Bit 10 - HSEBYP"]
#[inline(always)]
#[must_use]
pub fn hsebyp(&mut self) -> HSEBYP_W<RCC_OCENCLRR_SPEC, 10> {
HSEBYP_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "This register is used to control the oscillators.Writing to this register has no effect, writing will clear the corresponding bits. Reading will give the effective values of the enable bits.If TZEN = , this register can only be modified in secure mode. Write access to this register is not allowed during the clock restore sequence. See Section: The clock restore sequence description for details.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcc_ocenclrr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rcc_ocenclrr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct RCC_OCENCLRR_SPEC;
impl crate::RegisterSpec for RCC_OCENCLRR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`rcc_ocenclrr::R`](R) reader structure"]
impl crate::Readable for RCC_OCENCLRR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`rcc_ocenclrr::W`](W) writer structure"]
impl crate::Writable for RCC_OCENCLRR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets RCC_OCENCLRR to value 0x01"]
impl crate::Resettable for RCC_OCENCLRR_SPEC {
const RESET_VALUE: Self::Ux = 0x01;
}
|
pub mod account;
pub mod loader_instruction;
pub mod pubkey;
extern crate bincode;
extern crate bs58;
extern crate generic_array;
#[macro_use]
extern crate serde_derive;
|
#[doc = "Reader of register FDCAN_TXBCF"]
pub type R = crate::R<u32, super::FDCAN_TXBCF>;
#[doc = "CF\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u32)]
pub enum CF_A {
#[doc = "0: No transmit buffer\r\n cancellation"]
B_0X0 = 0,
#[doc = "1: Transmit buffer cancellation\r\n finished"]
B_0X1 = 1,
}
impl From<CF_A> for u32 {
#[inline(always)]
fn from(variant: CF_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `CF`"]
pub type CF_R = crate::R<u32, CF_A>;
impl CF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u32, CF_A> {
use crate::Variant::*;
match self.bits {
0 => Val(CF_A::B_0X0),
1 => Val(CF_A::B_0X1),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == CF_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == CF_A::B_0X1
}
}
impl R {
#[doc = "Bits 0:31 - CF"]
#[inline(always)]
pub fn cf(&self) -> CF_R {
CF_R::new((self.bits & 0xffff_ffff) as u32)
}
}
|
extern crate bulletrs;
extern crate cgmath;
use cgmath::{Vector3, Vector4};
use bulletrs::*;
#[test()]
fn set_gravity() {
let configuration = CollisionConfiguration::new_default();
let mut dynamics_world = DynamicsWorld::new_discrete_world(
CollisionDispatcher::new(&configuration),
Broadphase::new(BroadphaseInterface::DbvtBroadphase),
ConstraintSolver::new(),
configuration,
);
dynamics_world.set_gravity(Vector3::new(0.0, -10.0, 0.0));
let shape = Shape::new_sphere(2.0);
let mass = 0.1;
let body1 = dynamics_world.add_rigid_body(RigidBody::new(
mass,
shape.calculate_local_inertia(mass),
shape,
Vector3::new(4.0, 2.0, 0.0),
Vector4::new(0.0, 0.0, 0.0, 1.0),
));
let shape2 = Shape::new_sphere(2.0);
let mass = 0.1;
let mut body2 = dynamics_world.add_rigid_body(RigidBody::new(
mass,
shape2.calculate_local_inertia(mass),
shape2,
Vector3::new(0.0, 2.0, 0.0),
Vector4::new(0.0, 0.0, 0.0, 1.0),
));
body2.set_gravity(Vector3::new(0.0, 0.0, 0.0));
for _ in 0 .. 10 {
dynamics_world.step_simulation(0.1, 0, 0.0);
}
let (position, _) = body1.get_world_position_and_orientation();
assert!(position.y != 2.0);
let (position, _) = body2.get_world_position_and_orientation();
assert_eq!(position.y, 2.0);
}
|
extern crate libc;
#[macro_use] extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate termion;
extern crate floating_duration;
pub mod motor_controllers;
pub mod elevator_drivers;
pub mod buildings;
pub mod physics;
pub mod trip_planning;
pub mod data_recorders;
pub mod motion_controllers;
|
use ffi;
lazy_static! {
pub static ref RTE_RING_NAMESIZE: usize = ffi::RTE_MEMZONE_NAMESIZE as usize - ffi::RTE_RING_MZ_PREFIX.len() + 1;
}
|
/*!
Convert values to color simply and securely.
- Convert in hexadecimal, rgb, hsl, cmyk, hsv and hwb formats.
- Case sensitive.
- Always returns the same result for a string (Pure function).
[](https://crates.io/crates/coloring) • [](https://github.com/andrelmlins/coloring/blob/master/LICENSE) • [](https://travis-ci.com/andrelmlins/coloring) • [](https://docs.rs/coloring)
## Installation
Add the dependency in the `Cargo.toml` file:
```toml
[dependencies]
coloring = "0.3"
```
## Basic Use
```rust
extern crate coloring;
pub use coloring::Coloring;
fn main() {
let coloring = Coloring::new("My String");
println!("{}", coloring.to_hexadecimal());
// #259f0c
println!("{:?}", coloring.to_rgb());
// [37, 159, 12]
println!("{:?}", coloring.to_hsl());
// [110.0, 86.0, 34.0]
println!("{:?}", coloring.to_cmyk());
// [77.0, 0.0, 92.0, 38.0]
println!("{:?}", coloring.to_hsv());
// [110.0, 86.0, 34.0]
println!("{:?}", coloring.to_hwb());
// [110.0, 5.0, 38.0]
}
```
*/
mod coloring;
pub use crate::coloring::Coloring;
|
//! The module containing all outgoing packet implementations
/*use super::super::deque_buffer::DequeBuffer;
use super::super::game_connection::GameConnection; //It's super super super effective!
use std::io::Write;
//pub mod handshake; No handshake packets (yet)!
pub mod status;
/// A trait for outgoing packets
pub trait OutgoingPacket {
/// Gets this Packet's ID
///
/// One day, this will be replaced with an associated constant
fn get_id(&self) -> u32;
/// Encodes this Packet's data
fn encode_data(&self, buffer: &mut DequeBuffer);
/// Encodes this OutgoingPacket
fn encode(&self, buffer: &mut DequeBuffer) {
buffer.write_unsigned_varint_32(self.get_id());
self.encode_data(buffer);
}
/// Sends this OutgoingPacket to the client
fn send(&self, connection: &mut GameConnection) {
let mut data_buffer = DequeBuffer::new();
self.encode(&mut data_buffer);
let mut length_buffer = DequeBuffer::new();
length_buffer.write_unsigned_varint_32(data_buffer.remaining() as u32); //TODO: Try to get this as data_buffer.prepend_varint_32 - One day
let buffer: Vec<u8> = length_buffer.data.into_iter().chain(data_buffer.data.into_iter()).collect();
let _buffer: &[u8] = &buffer[..];
if connection.stream.write(_buffer).is_ok() {
let _ = connection.stream.flush();
}
self.post_send(connection);
}
#[allow(unused_variables)]
/// Called after the OutgoingPacket is sent
fn post_send(&self, connection: &mut GameConnection) {
// Do nothing, this may be expanded by default later
}
}*/
/*
use super::super::super::deque_buffer::DequeBuffer;
use super::super::super::game_connection::GameConnection; //It's super super super effective!
use super::super::{ PacketHeader, ID_STC_ };
/// A packet sent from the server to
pub struct Packet {
// Your fields here
}
impl OutgoingPacket for Packet {
/// Gets this Packet's ID
///
/// One day, this will be replaced with an associated constant
fn get_id(&self) -> u32 {
ID_STC_
}
/// Encodes this Packet's data
fn encode_data(&self, buffer: &mut DequeBuffer) {
}
}
impl Packet {
/// Creates a new Packet
pub fn new() -> Packet {
Packet { /*etc*/ }
}
}
*/
|
fn main() {
let x = Some(5);
fn foo(x:i32){println!("{}", x);}
match x{
Some(x) => {foo(x)},
None=>{}
}
if x.is_some() {
let x = x.unwrap();
foo(x);
}
if let Some(x) = x{
foo(x);
}
else
{
println!("don't match");
}
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::hash::LedgerInfoHasher;
use crate::impl_hash;
use libra_crypto::HashValue;
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct LedgerInfo {
version: u64,
/// The root hash of transaction accumulator that includes the latest transaction.
transaction_accumulator_hash: HashValue,
/// Epoch number corresponds to the set of validators that are active for this ledger info.
epoch: u64,
timestamp_usecs: u64,
}
impl Display for LedgerInfo {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
write!(
f,
"LedgerInfo: [version: {}, epoch: {}, timestamp (us): {}, transaction_accumulator_hash: {}]",
self.version(),
self.epoch(),
self.timestamp_usecs(),
self.transaction_accumulator_hash(),
)
}
}
impl LedgerInfo {
/// Constructs a `LedgerInfo` object at a specific version using a given
/// transaction accumulator root and consensus data hash.
pub fn new(
version: u64,
transaction_accumulator_hash: HashValue,
epoch: u64,
timestamp_usecs: u64,
) -> Self {
LedgerInfo {
version,
transaction_accumulator_hash,
epoch,
timestamp_usecs,
}
}
/// Returns the version of this `LedgerInfo`.
pub fn version(&self) -> u64 {
self.version
}
/// Returns the transaction accumulator root of this `LedgerInfo`.
pub fn transaction_accumulator_hash(&self) -> HashValue {
self.transaction_accumulator_hash
}
pub fn epoch(&self) -> u64 {
self.epoch
}
pub fn timestamp_usecs(&self) -> u64 {
self.timestamp_usecs
}
}
impl_hash!(LedgerInfo, LedgerInfoHasher);
|
use std::collections::HashMap;
use thiserror::Error;
#[derive(Debug, Error)]
#[error(r#"there's no "{field}" in `{type_str}`"#)]
pub struct DeserializeMaskError {
pub type_str: &'static str,
pub field: String,
pub depth: u8,
}
pub trait Maskable: Sized {
type Mask;
/// Perform a 'bitor' operation between the `mask` and a fieldmask in string format.
/// When the function returns Ok, `mask` should be modified to include fields in
/// `field_mask_segs`.
fn try_bitor_assign_mask(
// Take a reference here instead of the ownership. Because:
// 1. We may want to try performing other operations on `mask` if the current one doesn't
// work.
// 2. Therefore, if we take the ownership, we will need to return the ownership even when
// the method failed, which is cumbersome.
mask: &mut Self::Mask,
// Take a slice of segments instead of a full fieldmask string. Because:
// 1. It's easier to perform pattern matching on slices.
// 2. It's easier to distinguish empty fieldmask (e.g. "") and empty tail (e.g. "parent.").
field_mask_segs: &[&str],
) -> Result<(), DeserializeMaskError>;
}
pub trait SelfMaskable: Maskable {
/// Implementation of the application process of a mask.
fn apply_mask(&mut self, src: Self, mask: &Self::Mask);
}
pub trait OptionMaskable: Maskable {
/// Implementation of the application process of a mask.
fn apply_mask(&mut self, src: Self, mask: &Self::Mask) -> bool;
}
impl<T: SelfMaskable> OptionMaskable for T
where
T: Default,
T::Mask: PartialEq,
{
fn apply_mask(&mut self, src: Self, mask: &Self::Mask) -> bool {
self.apply_mask(src, mask);
true
}
}
impl<T: Maskable> Maskable for Option<T>
where
T: Default,
T::Mask: PartialEq,
{
type Mask = T::Mask;
fn try_bitor_assign_mask(
mask: &mut Self::Mask,
field_mask_segs: &[&str],
) -> Result<(), DeserializeMaskError> {
T::try_bitor_assign_mask(mask, field_mask_segs)
}
}
impl<T: OptionMaskable> SelfMaskable for Option<T>
where
T: Default,
T::Mask: PartialEq + Default,
{
fn apply_mask(&mut self, src: Self, mask: &Self::Mask) {
if mask == &Self::Mask::default() {
return;
}
match self {
Some(s) => match src {
Some(o) => {
if !s.apply_mask(o, mask) {
*self = None;
}
}
None => *self = None,
},
None => {
if let Some(o) = src {
let mut new = T::default();
if new.apply_mask(o, mask) {
*self = Some(new);
} else {
*self = None;
}
}
}
}
}
}
macro_rules! maskable {
($T:ident) => {
impl Maskable for $T {
type Mask = bool;
fn try_bitor_assign_mask(
mask: &mut Self::Mask,
field_mask_segs: &[&str],
) -> Result<(), DeserializeMaskError> {
if field_mask_segs.len() == 0 {
*mask = true;
Ok(())
} else {
Err(DeserializeMaskError {
type_str: stringify!($T),
field: field_mask_segs[0].into(),
depth: 0,
})
}
}
}
impl SelfMaskable for $T {
fn apply_mask(&mut self, other: Self, mask: &Self::Mask) {
if *mask {
*self = other;
}
}
}
};
}
maskable!(bool);
maskable!(char);
maskable!(f32);
maskable!(f64);
maskable!(i8);
maskable!(u8);
maskable!(i16);
maskable!(u16);
maskable!(i32);
maskable!(u32);
maskable!(i64);
maskable!(u64);
maskable!(i128);
maskable!(u128);
maskable!(isize);
maskable!(usize);
maskable!(String);
#[cfg(feature = "prost")]
maskable!(prost::bytes::Bytes);
impl<T> Maskable for Vec<T> {
type Mask = bool;
fn try_bitor_assign_mask(
mask: &mut Self::Mask,
field_mask_segs: &[&str],
) -> Result<(), DeserializeMaskError> {
if field_mask_segs.is_empty() {
*mask = true;
Ok(())
} else {
Err(DeserializeMaskError {
type_str: "Vec",
field: field_mask_segs[0].into(),
depth: 0,
})
}
}
}
impl<T> SelfMaskable for Vec<T> {
fn apply_mask(&mut self, other: Self, mask: &Self::Mask) {
if *mask {
*self = other;
}
}
}
impl<K, V> Maskable for HashMap<K, V> {
type Mask = bool;
fn try_bitor_assign_mask(
mask: &mut Self::Mask,
field_mask_segs: &[&str],
) -> Result<(), DeserializeMaskError> {
if field_mask_segs.is_empty() {
*mask = true;
Ok(())
} else {
Err(DeserializeMaskError {
type_str: "HashMap",
field: field_mask_segs[0].into(),
depth: 0,
})
}
}
}
impl<K, V> SelfMaskable for HashMap<K, V> {
fn apply_mask(&mut self, other: Self, mask: &Self::Mask) {
if *mask {
*self = other;
}
}
}
|
use std::io::Result;
use super::FileId;
use crate::ArcDataSlice;
/// Abstract interface to a multi-file log stream
pub(super) trait FileStream {
// Constant Maximum File Size
fn const_max_file_size(&self) -> usize;
/// Returns the current file Id, file UUID, Offset
fn status(&self) -> (FileId, uuid::Uuid, usize);
/// Writes the provided data to the file provided by status()
///
/// Returns nothing on success and and error if the write failed
fn write(&mut self, data: Vec<ArcDataSlice>) -> Result<()>;
/// Rotates the underlying files and optionally returns a FileId
/// to prune entries from
fn rotate_files(&mut self) -> Result<Option<FileId>>;
} |
#![allow(unused_parens)]
#![allow(unused_imports)]
use frame_support::{traits::Get, weights::Weight};
use sp_std::marker::PhantomData;
/// Weight functions for pallet_timestamp.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_timestamp::WeightInfo for WeightInfo<T> {
fn set() -> Weight {
(7_543_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn on_finalize() -> Weight {
(4_272_000 as Weight)
}
}
|
fn sum(v: &Vec<i32>) -> i32 {
let mut sum = 0;
// Borrow vector for loop.
for i in v {
sum = sum + i;
}
// Return the value.
sum
// Borrowing of v ends here.
}
fn main() {
let v = vec![2, 3, 4];
// Pass ownership to sum function and rebind
// v and answer from return value.
let answer = sum(&v);
println!("The sum is: {}", answer);
println!("The vector length is: {}", v.len());
}
|
use crate::{util::CountryCode, BotResult, Database};
use dashmap::DashMap;
use futures::stream::StreamExt;
impl Database {
#[cold]
pub async fn get_snipe_countries(&self) -> BotResult<DashMap<CountryCode, String>> {
let mut stream = sqlx::query!("SELECT * FROM snipe_countries").fetch(&self.pool);
let countries = DashMap::with_capacity(128);
while let Some(entry) = stream.next().await.transpose()? {
let country = entry.name;
let code = entry.code;
countries.insert(code.into(), country);
}
Ok(countries)
}
pub async fn insert_snipe_country(&self, country: &str, code: &str) -> BotResult<()> {
sqlx::query!("INSERT INTO snipe_countries VALUES ($1,$2)", country, code)
.execute(&self.pool)
.await?;
Ok(())
}
}
|
use super::*;
pub fn parse_rle_file<S: ToString>(s: &S) -> Result<Pattern, String> {
let s = s.to_string();
let mut pattern = Pattern::default();
// Metadata
let metadata = s.lines().take_while(|x| x.starts_with('#'));
for line in metadata {
let mut linedata = line.chars().skip(1);
match linedata.next() {
Some('N') => {
// Name
let name: String = linedata.collect();
let name = name.trim();
if !name.is_empty() {
pattern.name = Some(String::from(name));
}
}
Some('C') | Some('c') => {
// Comment or description
let description: String = linedata.collect();
let description = description.trim();
if let Some(d) = pattern.description {
pattern.description = Some(format!("{}\n{}", d, description));
} else {
pattern.description = Some(String::from(description));
}
}
Some('O') => {
// Author
let author: String = linedata.collect();
let author = author.trim();
pattern.author = Some(String::from(author));
}
Some(unknown_char) => {
return Err(format!(
"Unknown combination #{} in metadata of .rle file.",
unknown_char
));
}
None => {}
}
}
// Remove all of the lines starting with `#`
let mut lines = s.lines().skip_while(|x| x.starts_with('#'));
// x = m, y = n
let _header = match lines.next() {
Some(v) => v,
None => return Err(String::from("The header for this `.rle` file could not be found because there were no (uncommented) lines.")),
};
// TODO: process header information
let data: String = lines.collect();
let data = data.split('$');
let mut y: isize = 0;
for line in data {
let mut amount: isize = 0;
let mut x = 0;
for c in line.chars() {
match c {
'b' | '.' => {
// Off state
if amount == 0 {
// Not preceded by a number
x += 1;
} else {
x += amount;
amount = 0;
}
}
'o' | 'A' => {
// On state
if amount == 0 {
// Not preceded by a number
pattern.cells.push((x, y));
x += 1;
} else {
for i in 0..amount {
pattern.cells.push((x + i, y));
}
x += amount;
amount = 0;
}
}
'0' => amount *= 10,
'1' => amount = amount * 10 + 1,
'2' => amount = amount * 10 + 2,
'3' => amount = amount * 10 + 3,
'4' => amount = amount * 10 + 4,
'5' => amount = amount * 10 + 5,
'6' => amount = amount * 10 + 6,
'7' => amount = amount * 10 + 7,
'8' => amount = amount * 10 + 8,
'9' => amount = amount * 10 + 9,
'!' => {
// The end of this pattern was reached
return Ok(pattern);
}
unknown => {
return Err(format!(
"Unexpected character `{}` while reading data from a `.rle` file.",
unknown
))
}
}
}
if amount != 0 {
y += amount;
} else {
y += 1;
}
}
Ok(pattern)
}
|
mod core;
mod derive;
mod macros;
mod settings;
#[cfg(feature = "std")]
mod matrix;
|
use std::ops::Add;
pub trait Semigroup {
fn combine(self, other: Self) -> Self;
}
impl<I> Semigroup for I
where
I: Add<I, Output = I>,
{
fn combine(self, other: I) -> I {
self.add(other)
}
}
|
use crate::db::models::*;
use bigdecimal::BigDecimal;
use chrono::offset::Local;
#[derive(Debug, Clone, Default)]
pub struct UserBuilder {
pub email: String,
pub password: String,
pub username: String,
pub tags: Vec<String>,
}
impl UserBuilder {
pub fn username(mut self, username: &str) -> Self {
self.username = username.into();
self
}
pub fn password(mut self, password: &str) -> Self {
self.password = password.into();
self
}
pub fn tags(mut self, tags: Vec<&str>) -> Self {
self.tags = tags.into_iter().map(|t| t.to_string()).collect();
self
}
pub fn finish(self) -> AuthUser {
AuthUser {
id: 1,
username: self.username,
password: self.password,
is_superuser: false,
is_active: true,
is_staff: false,
email: self.email,
first_name: String::new(),
last_name: String::new(),
date_joined: Local::now().naive_local(),
tags: self.tags,
}
}
}
#[derive(Default, Clone)]
pub struct RecordBuilder {
pub amount: BigDecimal,
pub amount_currency: String,
pub id: i32,
pub tags: Vec<String>,
pub transaction_type: String,
pub comment: String,
pub user_id: i32,
}
impl RecordBuilder {
pub fn tags(mut self, tags: Vec<&str>) -> Self {
self.tags = tags.into_iter().map(|s| s.to_string()).collect();
self
}
pub fn transaction_type(mut self, transaction_type: &str) -> Self {
self.transaction_type = transaction_type.to_string();
self
}
pub fn user_id(mut self, user_id: i32) -> Self {
self.user_id = user_id;
self
}
pub fn amount(mut self, amount: f64) -> Self {
self.amount = BigDecimal::from(amount);
self
}
pub fn finish(self) -> Record {
Record {
id: self.id,
amount: self.amount,
amount_currency: self.amount_currency,
created_at: Local::now().naive_local(),
tags: self.tags,
transaction_type: self.transaction_type,
user_id: self.user_id,
comment: Some(self.comment),
}
}
}
#[derive(Default)]
pub struct BudgetBuilder {
pub amount: BigDecimal,
pub amount_currency: String,
pub id: i32,
pub name: String,
pub tags: Vec<String>,
pub tags_type: String,
pub user_id: i32,
}
impl BudgetBuilder {
pub fn tags_type(mut self, tags_type: &str) -> Self {
self.tags_type = tags_type.to_string();
self
}
pub fn tags(mut self, tags: Vec<&str>) -> Self {
self.tags = tags.into_iter().map(|s| s.to_string()).collect();
self
}
pub fn user_id(mut self, user_id: i32) -> Self {
self.user_id = user_id;
self
}
pub fn finish(self) -> Budget {
use chrono::naive::NaiveDate;
Budget {
amount: self.amount,
amount_currency: self.amount_currency,
id: self.id,
name: self.name,
tags: self.tags,
tags_type: self.tags_type,
user_id: self.user_id,
start_date: NaiveDate::from_ymd(2015, 3, 14),
}
}
}
|
//! The main interface for managing a waSCC host
// Copyright 2015-2019 Capital One Services, LLC
//
// 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 super::router::Router;
use super::Result;
use crate::actor::Actor;
use crate::authz;
use crate::capability::{CapabilitySummary, NativeCapability};
use crate::dispatch::WasccNativeDispatcher;
use crate::errors;
use crate::middleware;
use crate::middleware::Middleware;
use crate::plugins::PLUGMAN;
use crate::{manifest::HostManifest, router::InvokerPair};
use crossbeam::{Receiver, Sender};
use crossbeam_channel as channel;
use crossbeam_utils::sync::WaitGroup;
use gantryclient::*;
use std::collections::HashMap;
use std::sync::RwLock;
use std::thread;
use wapc::prelude::*;
use wascap::jwt::Claims;
use wascc_codec::core::{
CapabilityConfiguration, OP_CONFIGURE, OP_PERFORM_LIVE_UPDATE, OP_REMOVE_ACTOR,
};
use wascc_codec::serialize;
pub use authz::set_auth_hook;
lazy_static! {
pub(crate) static ref CAPS: RwLock<Vec<CapabilitySummary>> = { RwLock::new(Vec::new()) };
pub(crate) static ref ROUTER: RwLock<Router> = { RwLock::new(Router::default()) };
pub(crate) static ref TERMINATORS: RwLock<HashMap<String, Sender<bool>>> =
{ RwLock::new(HashMap::new()) };
pub(crate) static ref GANTRYCLIENT: RwLock<gantryclient::Client> =
RwLock::new(Client::default());
}
/// Adds a middleware trait object to the middleware processing pipeline.
pub fn add_middleware(mid: impl Middleware) {
middleware::MIDDLEWARES.write().unwrap().push(Box::new(mid));
}
/// Adds a portable capability provider wasm module to the runtime host. The identity of this provider
/// will be determined by examining the capability attestation in this actor's embedded token.
pub fn add_capability(actor: Actor, wasi: WasiParams) -> Result<()> {
let wg = WaitGroup::new();
spawn_actor_and_listen(
wg.clone(),
actor.token.claims,
actor.bytes.clone(),
Some(wasi),
false,
)?;
wg.wait();
Ok(())
}
/// Manually dispatches an operation and an opaque binary payload to an actor as if it
/// came from a capability. The origin of this message will be `system`. Use this function
/// to perform integration or acceptance tests on actors within a host, or if your host has
/// special invocations that it knows it must call on actors.
pub fn call(actor: &str, op: &str, msg: &[u8]) -> Result<Vec<u8>> {
if actor.contains(':') {
return Err(errors::new(errors::ErrorKind::MiscHost(
"Cannot invoke capability providers through host instead of from an actor".into(),
)));
}
let router = ROUTER.read().unwrap();
let pair = router.get_pair(actor);
match pair {
Some(ref p) => match invoke(p, "system".to_string(), op, msg) {
Ok(resp) => Ok(resp.msg),
Err(e) => Err(e),
},
None => Err(errors::new(errors::ErrorKind::MiscHost(
"No such actor".into(),
))),
}
}
/// Removes a portable capability provider from the host.
pub fn remove_capability(cap_id: &str) -> Result<()> {
if let Some(term_s) = TERMINATORS.read().unwrap().get(cap_id) {
term_s.send(true).unwrap();
Ok(())
} else {
Err(errors::new(errors::ErrorKind::MiscHost(
"No such capability".into(),
)))
}
}
/// Adds an actor module to the runtime host. The identity of this module is determined
/// by inspecting the claims embedded in the module's custom section as a JWT. The identity
/// comes from the `subject` field on the embedded claims and is the primary key of the
/// module identity.
pub fn add_actor(actor: Actor) -> Result<()> {
ensure_extras()?;
let wg = WaitGroup::new();
info!("Adding actor {} to host", actor.public_key());
spawn_actor_and_listen(
wg.clone(),
actor.token.claims,
actor.bytes.clone(),
None,
true,
)?;
wg.wait();
Ok(())
}
/// Applies a manifest containing actors, capabilities, and actor-capability configuration
/// entries. This provides a useful shortcut for provisioning an entire host.
pub fn apply_manifest(manifest: HostManifest) -> Result<()> {
for actor in manifest.actors {
// for now, only support file paths
// TODO: support public keys and fetch from gantry
add_actor(Actor::from_file(actor)?)?;
}
for cap in manifest.capabilities {
// for now, supports only file paths
add_native_capability(NativeCapability::from_file(cap)?)?;
}
for config in manifest.config {
configure(&config.actor, &config.capability, config.values)?;
}
Ok(())
}
fn ensure_extras() -> Result<()> {
if ROUTER.read().unwrap().get_pair("wascc:extras").is_some() {
return Ok(());
}
add_native_capability(NativeCapability::from_instance(
crate::extras::ExtrasCapabilityProvider::default(),
)?)?;
Ok(())
}
/// Replaces one running actor with another live actor with no message loss. Note that
/// the time it takes to perform this replacement can cause pending messages from capability
/// providers (e.g. messages from subscriptions or HTTP requests) to build up in a backlog,
/// so make sure the new actor can handle this stream of these delayed messages
pub fn replace_actor(new_actor: Actor) -> Result<()> {
let public_key = new_actor.token.claims.subject;
match ROUTER.read().unwrap().get_pair(&public_key) {
Some(ref p) => {
match invoke(
p,
"system".into(),
&format!("{}!{}", public_key, OP_PERFORM_LIVE_UPDATE),
&new_actor.bytes,
) {
Ok(_) => {
info!("Actor {} replaced", public_key);
Ok(())
}
Err(e) => Err(e),
}
}
None => Err(errors::new(errors::ErrorKind::MiscHost(
"Cannot replace non-existent actor".into(),
))),
}
}
/// Removes an actor from the host. Stops the thread managing the actor and notifies
/// all capability providers to free up any associated resources being used by the actor. Because
/// this removal is _asynchronous_, the `actors` function might not immediately report
/// the change.
pub fn remove_actor(pk: &str) -> Result<()> {
if let Some(term_s) = TERMINATORS.read().unwrap().get(pk) {
term_s.send(true).unwrap();
Ok(())
} else {
Err(errors::new(errors::ErrorKind::MiscHost(
"No such actor".into(),
)))
}
}
/// Retrieves the list of all actors running in the host, returning a tuple of each
/// actor's primary key and that actor's security claims. The order in which the actors
/// appear in the resulting vector is _not guaranteed_. **NOTE** - Because actors are added and
/// removed asynchronously, this function returns a view of the actors only as seen at
/// the moment the function is invoked.
pub fn actors() -> Vec<(String, Claims<wascap::jwt::Actor>)> {
authz::get_all_claims()
}
/// Retrieves a list of all of the currently registered capability ID
pub fn capabilities() -> Vec<CapabilitySummary> {
let lock = CAPS.read().unwrap();
lock.iter().cloned().collect()
}
/// Retrieves the security claims for a given actor. Returns `None` if that actor is
/// not running in the host. Actors are added and removed asynchronously, and actors are
/// not visible until fully running, so if you attempt to query an actor's claims
/// immediately after calling `add_actor`, this function might (correctly) return `None`
pub fn actor_claims(pk: &str) -> Option<Claims<wascap::jwt::Actor>> {
authz::get_claims(pk)
}
/// Adds a native linux dynamic library (plugin) as a capability provider to the runtime host. The
/// identity and other metadata about this provider is determined by loading the plugin from disk
/// and invoking the appropriate plugin trait methods.
pub fn add_native_capability(capability: NativeCapability) -> Result<()> {
let capid = capability.capid.clone();
if ROUTER.read().unwrap().get_pair(&capid).is_some() {
return Err(errors::new(errors::ErrorKind::CapabilityProvider(format!(
"Attempt to register the same capability provider multiple times: {}",
capid
))));
}
let summary = CapabilitySummary {
id: capid.clone(),
name: capability.name(),
portable: false,
};
CAPS.write().unwrap().push(summary);
crate::plugins::PLUGMAN
.write()
.unwrap()
.add_plugin(capability)?;
let wg = WaitGroup::new();
spawn_capability_provider_and_listen(wg.clone(), &capid)?;
wg.wait();
Ok(())
}
/// Removes a native capability provider from the host.
pub fn remove_native_capability(capid: &str) -> Result<()> {
if let Some(term_s) = TERMINATORS.read().unwrap().get(capid) {
term_s.send(true).unwrap();
Ok(())
} else {
Err(errors::new(errors::ErrorKind::MiscHost(
"No such capability".into(),
)))
}
}
fn remove_cap(capid: &str) -> Result<()> {
CAPS.write().unwrap().retain(|c| c.id != capid);
Ok(())
}
/// Supply a set of key-value pairs for a given actor to a capability provider. This allows
/// the capability provider to set actor-specific data like an HTTP server port or a set of
/// subscriptions, etc.
pub fn configure(module: &str, capid: &str, config: HashMap<String, String>) -> Result<()> {
if !authz::can_invoke(module, capid) {
return Err(errors::new(errors::ErrorKind::Authorization(format!(
"Actor {} is not authorized to use capability {}, configuration rejected",
module, capid
))));
}
info!(
"Attempting to configure actor {} for capability {}",
module, capid
);
let capid = capid.to_string();
let module = module.to_string();
let pair = ROUTER.read().unwrap().get_pair(&capid);
match pair {
Some(pair) => {
trace!("Sending configuration to {}", capid);
let res = invoke(
&pair,
"system".to_string(),
&format!("{}!{}", capid, OP_CONFIGURE),
&gen_config_message(&module, config),
)?;
if let Some(e) = res.error {
Err(errors::new(errors::ErrorKind::CapabilityProvider(format!(
"Failed to configure {} - {}",
capid, e
))))
} else {
Ok(())
}
}
None => Err(errors::new(errors::ErrorKind::CapabilityProvider(format!(
"No such capability provider: {}",
capid
)))),
}
}
/// Connect to a Gantry server
pub fn configure_gantry(nats_urls: Vec<String>, jwt: &str, seed: &str) -> Result<()> {
*GANTRYCLIENT.write().unwrap() = Client::new(nats_urls, jwt, seed);
Ok(())
}
/// Creates a dispatcher and gives it to a native plugin, allowing that plugin to then
/// perform invocations on an actor module via the channels inside the dispatcher. Invocations
/// pulled off the channel are then invoked by looking up the target capability ID on the
/// router and invoking via the channels from the router.
fn spawn_capability_provider_and_listen(wg: WaitGroup, capid: &str) -> Result<()> {
let capid = capid.to_string();
thread::spawn(move || {
let (inv_s, inv_r): (Sender<Invocation>, Receiver<Invocation>) = channel::unbounded();
let (resp_s, resp_r): (Sender<InvocationResponse>, Receiver<InvocationResponse>) =
channel::unbounded();
let (term_s, term_r): (Sender<bool>, Receiver<bool>) = channel::unbounded();
let dispatcher = WasccNativeDispatcher::new(resp_r.clone(), inv_s.clone(), &capid);
crate::plugins::PLUGMAN
.write()
.unwrap()
.register_dispatcher(&capid, dispatcher)
.unwrap();
ROUTER
.write()
.unwrap()
.add_route(capid.to_string(), inv_s, resp_r);
TERMINATORS.write().unwrap().insert(capid.clone(), term_s);
info!("Native capability provider '{}' ready", capid);
drop(wg);
loop {
select! {
recv(inv_r) -> inv => {
if let Ok(inv) = inv {
let v: Vec<_> = inv.operation.split('!').collect();
let target = v[0];
info!(
"Capability {} received invocation for target {}",
capid, target
);
let inv_r = if target == capid {
// if target of invocation is this particular capability,
// then perform the invocation on the plugin
middleware::invoke_capability(inv).unwrap()
} else {
// Capability is handling a dispatch (delivering) to actor module
if !authz::can_invoke(target, &capid) {
InvocationResponse::error(&format!(
"Dispatch between actor and unauthorized capability: {} <-> {}",
target, capid
))
} else {
let pair = ROUTER.read().unwrap().get_pair(target);
match pair {
Some(ref p) => {
invoke(p, capid.clone(), &inv.operation, &inv.msg).unwrap()
}
None => InvocationResponse::error("Dispatch to unknown actor"),
}
}
};
resp_s.send(inv_r).unwrap();
}
},
recv(term_r) -> _term => {
info!("Terminating native capability provider {}", capid);
remove_cap(&capid).unwrap();
PLUGMAN.write().unwrap().remove_plugin(&capid).unwrap();
TERMINATORS.write().unwrap().remove(&capid);
ROUTER.write().unwrap().remove_route(&capid).unwrap();
break;
}
}
}
});
Ok(())
}
/// Spawns a new thread, inside which we create an instance of the wasm module interpreter. This function
/// handles incoming calls _targeted at_ either an actor module or a portable capability provider (both are wasm).
fn spawn_actor_and_listen(
wg: WaitGroup,
claims: Claims<wascap::jwt::Actor>,
buf: Vec<u8>,
wasi: Option<WasiParams>,
actor: bool,
) -> Result<()> {
thread::spawn(move || {
info!(
"Loading {} module...",
if actor { "actor" } else { "capability" }
);
let mut guest = WapcHost::new(host_callback, &buf, wasi).unwrap();
authz::store_claims(claims.clone()).unwrap();
authz::map_claims(guest.id(), &claims.subject);
let (inv_s, inv_r): (Sender<Invocation>, Receiver<Invocation>) = channel::unbounded();
let (resp_s, resp_r): (Sender<InvocationResponse>, Receiver<InvocationResponse>) =
channel::unbounded();
let (term_s, term_r): (Sender<bool>, Receiver<bool>) = channel::unbounded();
let route_key = {
let route_key = if actor {
claims.subject.clone()
} else {
claims.metadata.unwrap().caps.unwrap()[0].to_string() // If we can't unwrap this, the cap is bad, so panic is fine
};
ROUTER
.write()
.unwrap()
.add_route(route_key.clone(), inv_s, resp_r);
TERMINATORS
.write()
.unwrap()
.insert(route_key.clone(), term_s);
if !actor {
CAPS.write().unwrap().push(CapabilitySummary {
id: route_key.clone(),
name: route_key.clone(),
portable: true,
});
}
info!(
"{} {} ready for communications",
if actor {
"Actor"
} else {
"Portable capability"
},
route_key
);
route_key
};
drop(wg); // API call that spawned this thread can now unblock
loop {
select! {
recv(inv_r) -> inv => {
if let Ok(inv) = inv {
let v: Vec<_> = inv.operation.split('!').collect();
let inv = Invocation::new(inv.origin, v[1], inv.msg); // Remove routing prefix from operation
if inv.operation == OP_PERFORM_LIVE_UPDATE {
resp_s.send(live_update(&mut guest, &inv)).unwrap();
continue;
}
let inv_r = middleware::invoke_actor(inv, &mut guest).unwrap();
resp_s.send(inv_r).unwrap();
}
},
recv(term_r) -> _term => {
info!("Terminating {} {}", if actor { "actor" } else { "capability" }, route_key);
if actor {
deconfigure_actor(&route_key);
} else {
remove_cap(&route_key).unwrap();
}
authz::remove_claims(&claims.subject).unwrap();
TERMINATORS.write().unwrap().remove(&route_key);
ROUTER.write().unwrap().remove_route(&route_key).unwrap();
break;
}
}
}
});
Ok(())
}
fn live_update(guest: &mut WapcHost, inv: &Invocation) -> InvocationResponse {
match guest.replace_module(&inv.msg) {
Ok(_) => InvocationResponse::success(vec![]),
Err(e) => {
error!("Failed to perform hot swap, ignoring message: {}", e);
InvocationResponse::error("Failed to perform hot swap")
}
}
}
fn deconfigure_actor(key: &str) {
let cfg = CapabilityConfiguration {
module: key.to_string(),
values: HashMap::new(),
};
let buf = serialize(&cfg).unwrap();
ROUTER
.read()
.unwrap()
.all_capabilities()
.iter()
.for_each(|(capid, (sender, receiver))| {
let inv = Invocation {
origin: "system".to_string(),
msg: buf.clone(),
operation: format!("{}!{}", capid, OP_REMOVE_ACTOR),
};
sender.send(inv).unwrap();
let _res = receiver.recv().unwrap();
});
}
/// This function is called by the underlying waPC host in response to a guest module
/// invoking a host import according to the waPC protobuf-RPC spec. The operation
/// is assumed to be a string in the form [capability_id]![operation] where `capability_id` is a
/// namespace-delimited string like `wapc:messaging` or `wapc:keyvalue`.
fn host_callback(
id: u64,
ns: &str,
op: &str,
payload: &[u8],
) -> std::result::Result<Vec<u8>, Box<dyn std::error::Error>> {
trace!("Guest {} invoking {}:{}", id, ns, op);
let capability_id = ns;
let op = format!("{}!{}", capability_id, op);
if !authz::can_id_invoke(id, capability_id) {
return Err(Box::new(errors::new(errors::ErrorKind::Authorization(
format!(
"Actor {} does not have permission to communicate with {}",
id, capability_id
),
))));
}
if capability_id.len() == 56 && capability_id.starts_with("M") {
// This is an actor-to-actor call
if let Some(pair) = ROUTER.read().unwrap().get_pair(capability_id) {
match invoke(&pair, authz::pk_for_id(id), &op, &payload.to_vec()) {
Ok(ir) => {
if ir.error.is_some() {
Err(ir.error.unwrap().into())
} else {
Ok(ir.msg)
}
}
Err(e) => Err(Box::new(e)),
}
} else {
Err("Attempted actor-to-actor call to non-existent target".into())
}
} else {
let inv = Invocation::new(authz::pk_for_id(id), &op, payload.to_vec());
match middleware::invoke_capability(inv) {
Ok(inv_r) => Ok(inv_r.msg),
Err(e) => Err(Box::new(errors::new(errors::ErrorKind::HostCallFailure(
e.into(),
)))),
}
}
}
/// Send a request on the invoker channel and await a reply on the response channel
pub(crate) fn invoke(
pair: &InvokerPair,
origin: String,
op: &str,
payload: &[u8],
) -> Result<InvocationResponse> {
trace!("invoking: {} from {}", op, origin);
let (inv_s, resp_r) = pair;
inv_s
.send(Invocation::new(origin, op, payload.to_vec()))
.unwrap();
Ok(resp_r.recv().unwrap())
}
/// Converts a hashmap into the CapabilityConfiguration protobuf object to
/// be sent to a capability provider to supply configuration for an actor
fn gen_config_message(module: &str, values: HashMap<String, String>) -> Vec<u8> {
let cfgvals = CapabilityConfiguration {
module: module.to_string(),
values,
};
serialize(&cfgvals).unwrap()
}
/// An immutable representation of an invocation within waSCC
#[derive(Debug, Clone)]
pub struct Invocation {
pub origin: String,
pub operation: String,
pub msg: Vec<u8>,
}
impl Invocation {
pub fn new(origin: String, op: &str, msg: Vec<u8>) -> Invocation {
Invocation {
origin,
operation: op.to_string(),
msg,
}
}
}
/// The response to an invocation
#[derive(Debug, Clone)]
pub struct InvocationResponse {
pub msg: Vec<u8>,
pub error: Option<String>,
}
impl InvocationResponse {
pub fn success(msg: Vec<u8>) -> InvocationResponse {
InvocationResponse { msg, error: None }
}
pub fn error(err: &str) -> InvocationResponse {
InvocationResponse {
msg: Vec::new(),
error: Some(err.to_string()),
}
}
}
|
use std;
use strum_macros::AsRefStr;
/// Wrapped error sources for the geom crate.
#[derive(Debug, AsRefStr)]
pub enum Error {
Sysctl(sysctl::SysctlError),
Decode(quick_xml::DeError),
Parse(strum::ParseError),
Scan(scan_fmt::parse::ScanError),
/// Some internal graph invariant was violated.
GraphError,
}
impl std::convert::From<sysctl::SysctlError> for Error {
fn from(err: sysctl::SysctlError) -> Error {
Self::Sysctl(err)
}
}
impl std::convert::From<quick_xml::DeError> for Error {
fn from(err: quick_xml::DeError) -> Error {
Self::Decode(err)
}
}
impl std::convert::From<strum::ParseError> for Error {
fn from(err: strum::ParseError) -> Error {
Self::Parse(err)
}
}
impl std::convert::From<scan_fmt::parse::ScanError> for Error {
fn from(err: scan_fmt::parse::ScanError) -> Error {
Self::Scan(err)
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_ref())?;
return match self {
Self::Sysctl(e) => write!(f, ": {}", e),
Self::Decode(e) => write!(f, ": {}", e),
Self::Parse(e) => write!(f, ": {}", e),
Self::Scan(e) => write!(f, ": {}", e),
Self::GraphError => Ok(()),
};
}
}
impl std::error::Error for Error {}
#[cfg(test)]
mod test {
use crate::Error;
#[test]
fn display_basic() {
assert_eq!(format!("{}", Error::GraphError), "GraphError");
}
}
|
use crate::{components::Position, traits::*};
#[derive(Default)]
pub struct AiPerson {
texture_index: usize,
position: Position,
hunger: f32,
traveling_to: Option<Position>,
}
impl IsDrawable for AiPerson {
fn render_info(&self) -> (usize, &Position) {
(self.texture_index, &self.position)
}
fn set_texture_index(&mut self, texture_index: usize) {
self.texture_index = texture_index;
}
}
impl NeedsFood for AiPerson {
fn eat(&mut self, food: f32) -> f32 {
if self.hunger <= 0. {
return food;
}
self.hunger -= food;
if self.hunger < 0. {
let leftovers = -self.hunger;
self.hunger = 0.;
return leftovers;
}
0.
}
fn burn_calories(&mut self, burn: f32) {
self.hunger += burn;
}
fn hunger_index(&self) -> f32 {
self.hunger
}
}
impl HasPosition for AiPerson {
fn position(&self) -> &Position {
&self.position
}
fn set_position(&mut self, position: &Position) {
self.position = *position;
}
fn move_delta(&mut self, delta: &Position, seconds: f32) {
if self.hunger_index() < 1. {
self.position.x += delta.x;
self.position.y += delta.y;
self.burn_calories(seconds / 50.)
}
}
}
impl HasTravelingTo for AiPerson {
fn traveling_to(&self) -> Option<&Position> {
(&self.traveling_to).as_ref()
}
fn done_traveling(&mut self) {
self.traveling_to = None;
}
fn set_traveling_to(&mut self, position: &Position) {
self.traveling_to = Some(position.clone());
}
}
|
#![allow(non_snake_case)]
#![allow(unused_assignments)]
use libc::{c_int,c_uint, uint32_t,c_void};
use super::wnd::DWnd;
pub type LPARAM = * const c_void;
pub type WPARAM = * const c_void;
pub static C_NULL:* const c_void = 0 as * const c_void;
pub type WndProc =extern "stdcall" fn (DWnd, u32, WPARAM, LPARAM)->c_int;
pub type WindowHookfn = extern "stdcall" fn(int,* const c_void, * const c_void)->c_int;
#[repr(C)]
pub struct __WIN_HANDLER{
unused:int
}
pub type HMENU = * const __WIN_HANDLER;
pub type HINSTANCE = * const __WIN_HANDLER;
#[repr(C)]
pub struct WNDCLASSEXW{
pub cbSize:uint32_t,
pub style:uint32_t,
pub lpfnWndProc:WndProc,
pub cbClsExtra:c_int,
pub cbWndExtra:c_int,
pub hInstance:HINSTANCE,
pub hIcon:c_int,
pub hCursor:c_int,
pub hbrBackground:c_int,
pub lpszMenuName:* const u16,
pub lpszClassName:* const u16,
pub hIconSm:c_int,
}
#[repr(C)]
pub struct POINT{
pub x:c_int,pub y:c_int
}
#[repr(C)]
pub struct MSG{
pub handle: DWnd,
pub msg: c_uint,
pub wparam:c_int,
pub lparam:c_int,
pub time:uint32_t,
pub pt:POINT
}
extern "stdcall"{
//Messages.
pub fn PostMessageW(hWnd:DWnd, msg:u32, wparam:WPARAM, lparam:LPARAM)->c_int;
pub fn PostQuitMessage(exitCode:c_int)->c_int;
fn GetMessageW(lpMsg:* mut MSG, hWnd:DWnd, wMsgFilterMin:u32, wMsgFilterMax:u32)->bool;
fn TranslateMessage(lpMsg:* const MSG)->c_int;
fn DispatchMessageW(lpMsg:* const MSG)->c_int;
pub fn IsDialogMessage(hWnd:DWnd, lpMsg:* const MSG)->bool;
}
impl MSG{
pub fn GetMessage(&mut self,hWin:DWnd,wMsgFilterMin:u32, wMsgFilterMax:u32)->bool{
unsafe{GetMessageW(self, hWin, wMsgFilterMin, wMsgFilterMax)}
}
pub fn TranslateMessage(&self)->int{
unsafe{
TranslateMessage(self) as int
}
}
pub fn DispatchMessage(&self)->int{
unsafe{
DispatchMessageW(self)as int
}
}
pub fn IsDialogMessage(&self,hWin:DWnd)->bool{
unsafe{
IsDialogMessage(hWin,self)
}
}
}
#[repr(C)]
pub struct INITCOMMONCONTROLSEX{
pub dwSize: u32,
pub dwICC:u32
}
|
use serde::Serialize;
use sqlx::types::ipnetwork::IpNetwork;
use sqlx::types::Uuid;
use crate::common::SideType;
use crate::get5::serializer::{
deserialize_ipnetwork, deserialize_uuid, serialize_ipnetwork, serialize_uuid,
};
pub type CountryCode = String;
#[derive(Deserialize, Serialize, Debug, Clone, sqlx::FromRow)]
pub struct Team {
#[serde(
serialize_with = "serialize_uuid",
deserialize_with = "deserialize_uuid"
)]
pub id: Uuid,
pub name: String,
pub country: Option<CountryCode>,
pub logo: Option<String>,
}
#[derive(Deserialize, Serialize, Debug, Clone, sqlx::FromRow)]
pub struct Player {
#[serde(
serialize_with = "serialize_uuid",
deserialize_with = "deserialize_uuid"
)]
pub id: Uuid,
pub name: Option<String>,
#[serde(
serialize_with = "serialize_uuid",
deserialize_with = "deserialize_uuid"
)]
pub team_id: Uuid,
pub tag: Option<String>,
pub steamid: String,
}
#[derive(Deserialize, Serialize, Debug, Clone, sqlx::FromRow)]
pub struct Server {
#[serde(
serialize_with = "serialize_uuid",
deserialize_with = "deserialize_uuid"
)]
pub id: Uuid,
#[serde(
serialize_with = "serialize_ipnetwork",
deserialize_with = "deserialize_ipnetwork"
)]
pub host: IpNetwork,
pub port: i32,
pub r#type: Option<String>,
pub password: String,
}
#[derive(Deserialize, Serialize, Debug, Clone, sqlx::FromRow)]
pub struct Spectator {
#[serde(
serialize_with = "serialize_uuid",
deserialize_with = "deserialize_uuid"
)]
pub id: Uuid,
// TODO name: should we fetch this from steam?
pub steamid: String,
}
#[derive(Serialize, Debug, Clone, sqlx::FromRow)]
pub struct Match {
#[serde(
serialize_with = "serialize_uuid",
deserialize_with = "deserialize_uuid"
)]
pub id: Uuid,
#[serde(
serialize_with = "serialize_uuid",
deserialize_with = "deserialize_uuid"
)]
pub server_id: Uuid,
#[serde(
serialize_with = "serialize_uuid",
deserialize_with = "deserialize_uuid"
)]
pub team1_id: Uuid,
#[serde(
serialize_with = "serialize_uuid",
deserialize_with = "deserialize_uuid"
)]
pub team2_id: Uuid,
pub team1_score: Option<i32>,
pub team2_score: Option<i32>,
pub num_maps: i32,
pub skip_veto: bool,
pub veto_first: SideType,
pub players_per_team: i32,
pub min_player_to_ready: i32,
}
#[derive(Deserialize, Serialize, Debug, Clone, sqlx::FromRow)]
pub struct MapList {
#[serde(
serialize_with = "serialize_uuid",
deserialize_with = "deserialize_uuid"
)]
pub id: Uuid,
#[serde(
serialize_with = "serialize_uuid",
deserialize_with = "deserialize_uuid"
)]
pub match_id: Uuid,
pub order: i32,
pub map: String,
}
#[derive(Deserialize, Serialize, Debug, Clone, sqlx::FromRow)]
pub struct MatchSpectator {
#[serde(
serialize_with = "serialize_uuid",
deserialize_with = "deserialize_uuid"
)]
pub match_id: Uuid,
#[serde(
serialize_with = "serialize_uuid",
deserialize_with = "deserialize_uuid"
)]
pub spectator_id: Uuid,
}
|
pub mod cli;
mod flags;
mod path_check;
mod size;
pub use flags::Flags;
pub use path_check::Check;
pub use size::{Size, SizeComparison};
|
#![doc = "Peripheral access API for STM32G473XX microcontrollers (generated using svd2rust v0.30.0 (8dd361f 2023-08-19))\n\nYou can find an overview of the generated API [here].\n\nAPI features to be included in the [next]
svd2rust release can be generated by cloning the svd2rust [repository], checking out the above commit, and running `cargo doc --open`.\n\n[here]: https://docs.rs/svd2rust/0.30.0/svd2rust/#peripheral-api\n[next]: https://github.com/rust-embedded/svd2rust/blob/master/CHANGELOG.md#unreleased\n[repository]: https://github.com/rust-embedded/svd2rust"]
use core::marker::PhantomData;
use core::ops::Deref;
#[doc = r"Number available in the NVIC for configuring priority"]
pub const NVIC_PRIO_BITS: u8 = 4;
#[cfg(feature = "rt")]
pub use self::Interrupt as interrupt;
pub use cortex_m::peripheral::Peripherals as CorePeripherals;
pub use cortex_m::peripheral::{CBP, CPUID, DCB, DWT, FPB, FPU, ITM, MPU, NVIC, SCB, SYST, TPIU};
#[cfg(feature = "rt")]
pub use cortex_m_rt::interrupt;
#[cfg(feature = "rt")]
extern "C" {
fn WWDG();
fn PVD_PVM();
fn RTC_TAMP_CSS_LSE();
fn RTC_WKUP();
fn FLASH();
fn RCC();
fn EXTI0();
fn EXTI1();
fn EXTI2();
fn EXTI3();
fn EXTI4();
fn DMA1_CH1();
fn DMA1_CH2();
fn DMA1_CH3();
fn DMA1_CH4();
fn DMA1_CH5();
fn DMA1_CH6();
fn DMA1_CH7();
fn ADC1_2();
fn USB_HP();
fn USB_LP();
fn FDCAN1_INTR1_IT();
fn FDCAN1_INTR0_IT();
fn EXTI9_5();
fn TIM1_BRK_TIM15();
fn TIM1_UP_TIM16();
fn TIM1_TRG_COM();
fn TIM1_CC();
fn TIM2();
fn TIM3();
fn TIM4();
fn I2C1_EV();
fn I2C1_ER();
fn I2C2_EV();
fn I2C2_ER();
fn SPI1();
fn SPI2();
fn USART1();
fn USART2();
fn USART3();
fn EXTI15_10();
fn RTC_ALARM();
fn USBWAKE_UP();
fn TIM8_BRK();
fn TIM8_UP();
fn TIM8_TRG_COM();
fn TIM8_CC();
fn ADC3();
fn FMC();
fn LPTIM1();
fn TIM5();
fn SPI3();
fn UART4();
fn UART5();
fn TIM6_DACUNDER();
fn TIM7();
fn DMA2_CH1();
fn DMA2_CH2();
fn DMA2_CH3();
fn DMA2_CH4();
fn DMA2_CH5();
fn ADC4();
fn ADC5();
fn UCPD1();
fn COMP1_2_3();
fn COMP4_5_6();
fn COMP7();
fn CRS();
fn SAI();
fn TIM20_BRK();
fn TIM20_UP();
fn TIM20_TRG_COM();
fn TIM20_CC();
fn FPU();
fn I2C4_EV();
fn I2C4_ER();
fn SPI4();
fn AES();
fn FDCAN2_INTR0();
fn FDCAN2_INTR1();
fn FDCAN3_INTR0();
fn FDCAN3_INTR1();
fn RNG();
fn LPUART();
fn I2C3_EV();
fn I2C3_ER();
fn DMAMUX_OVR();
fn QUADSPI();
fn DMA1_CH8();
fn DMA2_CH6();
fn DMA2_CH7();
fn DMA2_CH8();
fn CORDIC();
fn FMAC();
}
#[doc(hidden)]
pub union Vector {
_handler: unsafe extern "C" fn(),
_reserved: u32,
}
#[cfg(feature = "rt")]
#[doc(hidden)]
#[link_section = ".vector_table.interrupts"]
#[no_mangle]
pub static __INTERRUPTS: [Vector; 102] = [
Vector { _handler: WWDG },
Vector { _handler: PVD_PVM },
Vector {
_handler: RTC_TAMP_CSS_LSE,
},
Vector { _handler: RTC_WKUP },
Vector { _handler: FLASH },
Vector { _handler: RCC },
Vector { _handler: EXTI0 },
Vector { _handler: EXTI1 },
Vector { _handler: EXTI2 },
Vector { _handler: EXTI3 },
Vector { _handler: EXTI4 },
Vector { _handler: DMA1_CH1 },
Vector { _handler: DMA1_CH2 },
Vector { _handler: DMA1_CH3 },
Vector { _handler: DMA1_CH4 },
Vector { _handler: DMA1_CH5 },
Vector { _handler: DMA1_CH6 },
Vector { _handler: DMA1_CH7 },
Vector { _handler: ADC1_2 },
Vector { _handler: USB_HP },
Vector { _handler: USB_LP },
Vector {
_handler: FDCAN1_INTR1_IT,
},
Vector {
_handler: FDCAN1_INTR0_IT,
},
Vector { _handler: EXTI9_5 },
Vector {
_handler: TIM1_BRK_TIM15,
},
Vector {
_handler: TIM1_UP_TIM16,
},
Vector {
_handler: TIM1_TRG_COM,
},
Vector { _handler: TIM1_CC },
Vector { _handler: TIM2 },
Vector { _handler: TIM3 },
Vector { _handler: TIM4 },
Vector { _handler: I2C1_EV },
Vector { _handler: I2C1_ER },
Vector { _handler: I2C2_EV },
Vector { _handler: I2C2_ER },
Vector { _handler: SPI1 },
Vector { _handler: SPI2 },
Vector { _handler: USART1 },
Vector { _handler: USART2 },
Vector { _handler: USART3 },
Vector {
_handler: EXTI15_10,
},
Vector {
_handler: RTC_ALARM,
},
Vector {
_handler: USBWAKE_UP,
},
Vector { _handler: TIM8_BRK },
Vector { _handler: TIM8_UP },
Vector {
_handler: TIM8_TRG_COM,
},
Vector { _handler: TIM8_CC },
Vector { _handler: ADC3 },
Vector { _handler: FMC },
Vector { _handler: LPTIM1 },
Vector { _handler: TIM5 },
Vector { _handler: SPI3 },
Vector { _handler: UART4 },
Vector { _handler: UART5 },
Vector {
_handler: TIM6_DACUNDER,
},
Vector { _handler: TIM7 },
Vector { _handler: DMA2_CH1 },
Vector { _handler: DMA2_CH2 },
Vector { _handler: DMA2_CH3 },
Vector { _handler: DMA2_CH4 },
Vector { _handler: DMA2_CH5 },
Vector { _handler: ADC4 },
Vector { _handler: ADC5 },
Vector { _handler: UCPD1 },
Vector {
_handler: COMP1_2_3,
},
Vector {
_handler: COMP4_5_6,
},
Vector { _handler: COMP7 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _reserved: 0 },
Vector { _handler: CRS },
Vector { _handler: SAI },
Vector {
_handler: TIM20_BRK,
},
Vector { _handler: TIM20_UP },
Vector {
_handler: TIM20_TRG_COM,
},
Vector { _handler: TIM20_CC },
Vector { _handler: FPU },
Vector { _handler: I2C4_EV },
Vector { _handler: I2C4_ER },
Vector { _handler: SPI4 },
Vector { _handler: AES },
Vector {
_handler: FDCAN2_INTR0,
},
Vector {
_handler: FDCAN2_INTR1,
},
Vector {
_handler: FDCAN3_INTR0,
},
Vector {
_handler: FDCAN3_INTR1,
},
Vector { _handler: RNG },
Vector { _handler: LPUART },
Vector { _handler: I2C3_EV },
Vector { _handler: I2C3_ER },
Vector {
_handler: DMAMUX_OVR,
},
Vector { _handler: QUADSPI },
Vector { _handler: DMA1_CH8 },
Vector { _handler: DMA2_CH6 },
Vector { _handler: DMA2_CH7 },
Vector { _handler: DMA2_CH8 },
Vector { _handler: CORDIC },
Vector { _handler: FMAC },
];
#[doc = r"Enumeration of all the interrupts."]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u16)]
pub enum Interrupt {
#[doc = "0 - Window Watchdog interrupt"]
WWDG = 0,
#[doc = "1 - PVD through EXTI line detection"]
PVD_PVM = 1,
#[doc = "2 - RTC_TAMP_CSS_LSE"]
RTC_TAMP_CSS_LSE = 2,
#[doc = "3 - RTC Wakeup timer"]
RTC_WKUP = 3,
#[doc = "4 - FLASH"]
FLASH = 4,
#[doc = "5 - RCC"]
RCC = 5,
#[doc = "6 - EXTI Line0 interrupt"]
EXTI0 = 6,
#[doc = "7 - EXTI Line1 interrupt"]
EXTI1 = 7,
#[doc = "8 - EXTI Line2 interrupt"]
EXTI2 = 8,
#[doc = "9 - EXTI Line3 interrupt"]
EXTI3 = 9,
#[doc = "10 - EXTI Line4 interrupt"]
EXTI4 = 10,
#[doc = "11 - DMA1 channel 1 interrupt"]
DMA1_CH1 = 11,
#[doc = "12 - DMA1 channel 2 interrupt"]
DMA1_CH2 = 12,
#[doc = "13 - DMA1 channel 3 interrupt"]
DMA1_CH3 = 13,
#[doc = "14 - DMA1 channel 4 interrupt"]
DMA1_CH4 = 14,
#[doc = "15 - DMA1 channel 5 interrupt"]
DMA1_CH5 = 15,
#[doc = "16 - DMA1 channel 6 interrupt"]
DMA1_CH6 = 16,
#[doc = "17 - DMA1 channel 7 interrupt"]
DMA1_CH7 = 17,
#[doc = "18 - ADC1 and ADC2 global interrupt"]
ADC1_2 = 18,
#[doc = "19 - USB_HP"]
USB_HP = 19,
#[doc = "20 - USB_LP"]
USB_LP = 20,
#[doc = "21 - fdcan1_intr1_it"]
FDCAN1_INTR1_IT = 21,
#[doc = "22 - fdcan1_intr0_it"]
FDCAN1_INTR0_IT = 22,
#[doc = "23 - EXTI9_5"]
EXTI9_5 = 23,
#[doc = "24 - TIM1_BRK_TIM15"]
TIM1_BRK_TIM15 = 24,
#[doc = "25 - TIM1_UP_TIM16"]
TIM1_UP_TIM16 = 25,
#[doc = "26 - TIM1_TRG_COM/"]
TIM1_TRG_COM = 26,
#[doc = "27 - TIM1 capture compare interrupt"]
TIM1_CC = 27,
#[doc = "28 - TIM2"]
TIM2 = 28,
#[doc = "29 - TIM3"]
TIM3 = 29,
#[doc = "30 - TIM4"]
TIM4 = 30,
#[doc = "31 - I2C1_EV"]
I2C1_EV = 31,
#[doc = "32 - I2C1_ER"]
I2C1_ER = 32,
#[doc = "33 - I2C2_EV"]
I2C2_EV = 33,
#[doc = "34 - I2C2_ER"]
I2C2_ER = 34,
#[doc = "35 - SPI1"]
SPI1 = 35,
#[doc = "36 - SPI2"]
SPI2 = 36,
#[doc = "37 - USART1"]
USART1 = 37,
#[doc = "38 - USART2"]
USART2 = 38,
#[doc = "39 - USART3"]
USART3 = 39,
#[doc = "40 - EXTI15_10"]
EXTI15_10 = 40,
#[doc = "41 - RTC_ALARM"]
RTC_ALARM = 41,
#[doc = "42 - USBWakeUP"]
USBWAKE_UP = 42,
#[doc = "43 - TIM8_BRK"]
TIM8_BRK = 43,
#[doc = "44 - TIM8_UP"]
TIM8_UP = 44,
#[doc = "45 - TIM8_TRG_COM"]
TIM8_TRG_COM = 45,
#[doc = "46 - TIM8_CC"]
TIM8_CC = 46,
#[doc = "47 - ADC3"]
ADC3 = 47,
#[doc = "48 - FMC"]
FMC = 48,
#[doc = "49 - LPTIM1"]
LPTIM1 = 49,
#[doc = "50 - TIM5"]
TIM5 = 50,
#[doc = "51 - SPI3"]
SPI3 = 51,
#[doc = "52 - UART4"]
UART4 = 52,
#[doc = "53 - UART5"]
UART5 = 53,
#[doc = "54 - TIM6_DACUNDER"]
TIM6_DACUNDER = 54,
#[doc = "55 - TIM7"]
TIM7 = 55,
#[doc = "56 - DMA2_CH1"]
DMA2_CH1 = 56,
#[doc = "57 - DMA2_CH2"]
DMA2_CH2 = 57,
#[doc = "58 - DMA2_CH3"]
DMA2_CH3 = 58,
#[doc = "59 - DMA2_CH4"]
DMA2_CH4 = 59,
#[doc = "60 - DMA2_CH5"]
DMA2_CH5 = 60,
#[doc = "61 - ADC4"]
ADC4 = 61,
#[doc = "62 - ADC5"]
ADC5 = 62,
#[doc = "63 - UCPD1"]
UCPD1 = 63,
#[doc = "64 - COMP1_2_3"]
COMP1_2_3 = 64,
#[doc = "65 - COMP4_5_6"]
COMP4_5_6 = 65,
#[doc = "66 - COMP7"]
COMP7 = 66,
#[doc = "75 - CRS"]
CRS = 75,
#[doc = "76 - SAI"]
SAI = 76,
#[doc = "77 - TIM20_BRK"]
TIM20_BRK = 77,
#[doc = "78 - TIM20_UP"]
TIM20_UP = 78,
#[doc = "79 - TIM20_TRG_COM"]
TIM20_TRG_COM = 79,
#[doc = "80 - TIM20_CC"]
TIM20_CC = 80,
#[doc = "81 - Floating point unit interrupt"]
FPU = 81,
#[doc = "82 - I2C4_EV"]
I2C4_EV = 82,
#[doc = "83 - I2C4_ER"]
I2C4_ER = 83,
#[doc = "84 - SPI4"]
SPI4 = 84,
#[doc = "85 - AES"]
AES = 85,
#[doc = "86 - FDCAN2_intr0"]
FDCAN2_INTR0 = 86,
#[doc = "87 - FDCAN2_intr1"]
FDCAN2_INTR1 = 87,
#[doc = "88 - FDCAN3_intr0"]
FDCAN3_INTR0 = 88,
#[doc = "89 - FDCAN3_intr1"]
FDCAN3_INTR1 = 89,
#[doc = "90 - RNG"]
RNG = 90,
#[doc = "91 - LPUART"]
LPUART = 91,
#[doc = "92 - I2C3_EV"]
I2C3_EV = 92,
#[doc = "93 - I2C3_ER"]
I2C3_ER = 93,
#[doc = "94 - DMAMUX_OVR"]
DMAMUX_OVR = 94,
#[doc = "95 - QUADSPI"]
QUADSPI = 95,
#[doc = "96 - DMA1_CH8"]
DMA1_CH8 = 96,
#[doc = "97 - DMA2_CH6"]
DMA2_CH6 = 97,
#[doc = "98 - DMA2_CH7"]
DMA2_CH7 = 98,
#[doc = "99 - DMA2_CH8"]
DMA2_CH8 = 99,
#[doc = "100 - Cordic"]
CORDIC = 100,
#[doc = "101 - FMAC"]
FMAC = 101,
}
unsafe impl cortex_m::interrupt::InterruptNumber for Interrupt {
#[inline(always)]
fn number(self) -> u16 {
self as u16
}
}
#[doc = "Cyclic redundancy check calculation unit"]
pub struct CRC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for CRC {}
impl CRC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const crc::RegisterBlock = 0x4002_3000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const crc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for CRC {
type Target = crc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for CRC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("CRC").finish()
}
}
#[doc = "Cyclic redundancy check calculation unit"]
pub mod crc;
#[doc = "WinWATCHDOG"]
pub struct IWDG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for IWDG {}
impl IWDG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const iwdg::RegisterBlock = 0x4000_3000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const iwdg::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for IWDG {
type Target = iwdg::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for IWDG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("IWDG").finish()
}
}
#[doc = "WinWATCHDOG"]
pub mod iwdg;
#[doc = "System window watchdog"]
pub struct WWDG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for WWDG {}
impl WWDG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const wwdg::RegisterBlock = 0x4000_2c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const wwdg::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for WWDG {
type Target = wwdg::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for WWDG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("WWDG").finish()
}
}
#[doc = "System window watchdog"]
pub mod wwdg;
#[doc = "Inter-integrated circuit"]
pub struct I2C1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for I2C1 {}
impl I2C1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const i2c1::RegisterBlock = 0x4000_5400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const i2c1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for I2C1 {
type Target = i2c1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for I2C1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("I2C1").finish()
}
}
#[doc = "Inter-integrated circuit"]
pub mod i2c1;
#[doc = "Inter-integrated circuit"]
pub struct I2C2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for I2C2 {}
impl I2C2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const i2c1::RegisterBlock = 0x4000_5800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const i2c1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for I2C2 {
type Target = i2c1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for I2C2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("I2C2").finish()
}
}
#[doc = "Inter-integrated circuit"]
pub use self::i2c1 as i2c2;
#[doc = "Inter-integrated circuit"]
pub struct I2C3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for I2C3 {}
impl I2C3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const i2c1::RegisterBlock = 0x4000_7800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const i2c1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for I2C3 {
type Target = i2c1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for I2C3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("I2C3").finish()
}
}
#[doc = "Inter-integrated circuit"]
pub use self::i2c1 as i2c3;
#[doc = "Inter-integrated circuit"]
pub struct I2C4 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for I2C4 {}
impl I2C4 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const i2c1::RegisterBlock = 0x4000_8400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const i2c1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for I2C4 {
type Target = i2c1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for I2C4 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("I2C4").finish()
}
}
#[doc = "Inter-integrated circuit"]
pub use self::i2c1 as i2c4;
#[doc = "Flash"]
pub struct FLASH {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for FLASH {}
impl FLASH {
#[doc = r"Pointer to the register block"]
pub const PTR: *const flash::RegisterBlock = 0x4002_2000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const flash::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for FLASH {
type Target = flash::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for FLASH {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("FLASH").finish()
}
}
#[doc = "Flash"]
pub mod flash;
#[doc = "Debug support"]
pub struct DBGMCU {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DBGMCU {}
impl DBGMCU {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dbgmcu::RegisterBlock = 0xe004_2000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dbgmcu::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DBGMCU {
type Target = dbgmcu::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DBGMCU {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DBGMCU").finish()
}
}
#[doc = "Debug support"]
pub mod dbgmcu;
#[doc = "Reset and clock control"]
pub struct RCC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for RCC {}
impl RCC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const rcc::RegisterBlock = 0x4002_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const rcc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for RCC {
type Target = rcc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for RCC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("RCC").finish()
}
}
#[doc = "Reset and clock control"]
pub mod rcc;
#[doc = "Power control"]
pub struct PWR {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for PWR {}
impl PWR {
#[doc = r"Pointer to the register block"]
pub const PTR: *const pwr::RegisterBlock = 0x4000_7000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const pwr::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for PWR {
type Target = pwr::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for PWR {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("PWR").finish()
}
}
#[doc = "Power control"]
pub mod pwr;
#[doc = "Random number generator"]
pub struct RNG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for RNG {}
impl RNG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const rng::RegisterBlock = 0x5006_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const rng::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for RNG {
type Target = rng::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for RNG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("RNG").finish()
}
}
#[doc = "Random number generator"]
pub mod rng;
#[doc = "Advanced encryption standard hardware accelerator"]
pub struct AES {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for AES {}
impl AES {
#[doc = r"Pointer to the register block"]
pub const PTR: *const aes::RegisterBlock = 0x5006_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const aes::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for AES {
type Target = aes::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for AES {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("AES").finish()
}
}
#[doc = "Advanced encryption standard hardware accelerator"]
pub mod aes;
#[doc = "General-purpose I/Os"]
pub struct GPIOA {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOA {}
impl GPIOA {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioa::RegisterBlock = 0x4800_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioa::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOA {
type Target = gpioa::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOA {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOA").finish()
}
}
#[doc = "General-purpose I/Os"]
pub mod gpioa;
#[doc = "General-purpose I/Os"]
pub struct GPIOB {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOB {}
impl GPIOB {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpiob::RegisterBlock = 0x4800_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpiob::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOB {
type Target = gpiob::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOB {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOB").finish()
}
}
#[doc = "General-purpose I/Os"]
pub mod gpiob;
#[doc = "General-purpose I/Os"]
pub struct GPIOC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOC {}
impl GPIOC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x4800_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOC {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOC").finish()
}
}
#[doc = "General-purpose I/Os"]
pub mod gpioc;
#[doc = "General-purpose I/Os"]
pub struct GPIOD {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOD {}
impl GPIOD {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x4800_0c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOD {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOD {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOD").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioc as gpiod;
#[doc = "General-purpose I/Os"]
pub struct GPIOE {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOE {}
impl GPIOE {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x4800_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOE {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOE {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOE").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioc as gpioe;
#[doc = "General-purpose I/Os"]
pub struct GPIOF {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOF {}
impl GPIOF {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x4800_1400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOF {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOF {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOF").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioc as gpiof;
#[doc = "General-purpose I/Os"]
pub struct GPIOG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOG {}
impl GPIOG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x4800_1800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOG {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOG").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioc as gpiog;
#[doc = "General purpose timers"]
pub struct TIM15 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM15 {}
impl TIM15 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim15::RegisterBlock = 0x4001_4000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim15::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM15 {
type Target = tim15::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM15 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM15").finish()
}
}
#[doc = "General purpose timers"]
pub mod tim15;
#[doc = "General purpose timers"]
pub struct TIM16 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM16 {}
impl TIM16 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim16::RegisterBlock = 0x4001_4400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim16::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM16 {
type Target = tim16::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM16 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM16").finish()
}
}
#[doc = "General purpose timers"]
pub mod tim16;
#[doc = "General purpose timers"]
pub struct TIM17 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM17 {}
impl TIM17 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim16::RegisterBlock = 0x4001_4800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim16::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM17 {
type Target = tim16::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM17 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM17").finish()
}
}
#[doc = "General purpose timers"]
pub use self::tim16 as tim17;
#[doc = "Advanced-timers"]
pub struct TIM1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM1 {}
impl TIM1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim1::RegisterBlock = 0x4001_2c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM1 {
type Target = tim1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM1").finish()
}
}
#[doc = "Advanced-timers"]
pub mod tim1;
#[doc = "Advanced-timers"]
pub struct TIM20 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM20 {}
impl TIM20 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim1::RegisterBlock = 0x4001_5000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM20 {
type Target = tim1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM20 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM20").finish()
}
}
#[doc = "Advanced-timers"]
pub use self::tim1 as tim20;
#[doc = "Advanced-timers"]
pub struct TIM8 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM8 {}
impl TIM8 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim1::RegisterBlock = 0x4001_3400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM8 {
type Target = tim1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM8 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM8").finish()
}
}
#[doc = "Advanced-timers"]
pub use self::tim1 as tim8;
#[doc = "Advanced-timers"]
pub struct TIM2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM2 {}
impl TIM2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim2::RegisterBlock = 0x4000_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim2::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM2 {
type Target = tim2::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM2").finish()
}
}
#[doc = "Advanced-timers"]
pub mod tim2;
#[doc = "Advanced-timers"]
pub struct TIM3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM3 {}
impl TIM3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim3::RegisterBlock = 0x4000_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim3::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM3 {
type Target = tim3::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM3").finish()
}
}
#[doc = "Advanced-timers"]
pub mod tim3;
#[doc = "Advanced-timers"]
pub struct TIM4 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM4 {}
impl TIM4 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim3::RegisterBlock = 0x4000_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim3::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM4 {
type Target = tim3::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM4 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM4").finish()
}
}
#[doc = "Advanced-timers"]
pub use self::tim3 as tim4;
#[doc = "Advanced-timers"]
pub struct TIM5 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM5 {}
impl TIM5 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim2::RegisterBlock = 0x4000_0c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim2::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM5 {
type Target = tim2::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM5 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM5").finish()
}
}
#[doc = "Advanced-timers"]
pub use self::tim2 as tim5;
#[doc = "Basic-timers"]
pub struct TIM6 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM6 {}
impl TIM6 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim6::RegisterBlock = 0x4000_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim6::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM6 {
type Target = tim6::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM6 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM6").finish()
}
}
#[doc = "Basic-timers"]
pub mod tim6;
#[doc = "Basic-timers"]
pub struct TIM7 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM7 {}
impl TIM7 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim6::RegisterBlock = 0x4000_1400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim6::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM7 {
type Target = tim6::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM7 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM7").finish()
}
}
#[doc = "Basic-timers"]
pub use self::tim6 as tim7;
#[doc = "Low power timer"]
pub struct LPTIMER1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for LPTIMER1 {}
impl LPTIMER1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const lptimer1::RegisterBlock = 0x4000_7c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const lptimer1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for LPTIMER1 {
type Target = lptimer1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for LPTIMER1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("LPTIMER1").finish()
}
}
#[doc = "Low power timer"]
pub mod lptimer1;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct USART1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for USART1 {}
impl USART1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usart1::RegisterBlock = 0x4001_3800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for USART1 {
type Target = usart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for USART1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("USART1").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub mod usart1;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct USART2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for USART2 {}
impl USART2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usart1::RegisterBlock = 0x4000_4400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for USART2 {
type Target = usart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for USART2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("USART2").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub use self::usart1 as usart2;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct USART3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for USART3 {}
impl USART3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usart1::RegisterBlock = 0x4000_4800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for USART3 {
type Target = usart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for USART3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("USART3").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub use self::usart1 as usart3;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct UART4 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for UART4 {}
impl UART4 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const uart4::RegisterBlock = 0x4000_4c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const uart4::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for UART4 {
type Target = uart4::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for UART4 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("UART4").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub mod uart4;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct UART5 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for UART5 {}
impl UART5 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const uart4::RegisterBlock = 0x4000_5000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const uart4::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for UART5 {
type Target = uart4::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for UART5 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("UART5").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub use self::uart4 as uart5;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct LPUART1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for LPUART1 {}
impl LPUART1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const lpuart1::RegisterBlock = 0x4000_8000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const lpuart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for LPUART1 {
type Target = lpuart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for LPUART1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("LPUART1").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub mod lpuart1;
#[doc = "Serial peripheral interface/Inter-IC sound"]
pub struct SPI1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SPI1 {}
impl SPI1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const spi1::RegisterBlock = 0x4001_3000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const spi1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SPI1 {
type Target = spi1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SPI1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SPI1").finish()
}
}
#[doc = "Serial peripheral interface/Inter-IC sound"]
pub mod spi1;
#[doc = "Serial peripheral interface/Inter-IC sound"]
pub struct SPI4 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SPI4 {}
impl SPI4 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const spi4::RegisterBlock = 0x4001_3c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const spi4::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SPI4 {
type Target = spi4::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SPI4 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SPI4").finish()
}
}
#[doc = "Serial peripheral interface/Inter-IC sound"]
pub mod spi4;
#[doc = "Serial peripheral interface/Inter-IC sound"]
pub struct SPI3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SPI3 {}
impl SPI3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const spi4::RegisterBlock = 0x4000_3c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const spi4::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SPI3 {
type Target = spi4::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SPI3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SPI3").finish()
}
}
#[doc = "Serial peripheral interface/Inter-IC sound"]
pub use self::spi4 as spi3;
#[doc = "Serial peripheral interface/Inter-IC sound"]
pub struct SPI2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SPI2 {}
impl SPI2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const spi4::RegisterBlock = 0x4000_3800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const spi4::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SPI2 {
type Target = spi4::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SPI2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SPI2").finish()
}
}
#[doc = "Serial peripheral interface/Inter-IC sound"]
pub use self::spi4 as spi2;
#[doc = "External interrupt/event controller"]
pub struct EXTI {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for EXTI {}
impl EXTI {
#[doc = r"Pointer to the register block"]
pub const PTR: *const exti::RegisterBlock = 0x4001_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const exti::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for EXTI {
type Target = exti::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for EXTI {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("EXTI").finish()
}
}
#[doc = "External interrupt/event controller"]
pub mod exti;
#[doc = "Real-time clock"]
pub struct RTC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for RTC {}
impl RTC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const rtc::RegisterBlock = 0x4000_2800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const rtc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for RTC {
type Target = rtc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for RTC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("RTC").finish()
}
}
#[doc = "Real-time clock"]
pub mod rtc;
#[doc = "Flexible memory controller"]
pub struct FMC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for FMC {}
impl FMC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const fmc::RegisterBlock = 0xa000_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const fmc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for FMC {
type Target = fmc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for FMC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("FMC").finish()
}
}
#[doc = "Flexible memory controller"]
pub mod fmc;
#[doc = "DMA controller"]
pub struct DMA1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DMA1 {}
impl DMA1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dma1::RegisterBlock = 0x4002_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dma1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DMA1 {
type Target = dma1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DMA1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DMA1").finish()
}
}
#[doc = "DMA controller"]
pub mod dma1;
#[doc = "DMA controller"]
pub struct DMA2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DMA2 {}
impl DMA2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dma1::RegisterBlock = 0x4002_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dma1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DMA2 {
type Target = dma1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DMA2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DMA2").finish()
}
}
#[doc = "DMA controller"]
pub use self::dma1 as dma2;
#[doc = "DMAMUX"]
pub struct DMAMUX {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DMAMUX {}
impl DMAMUX {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dmamux::RegisterBlock = 0x4002_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dmamux::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DMAMUX {
type Target = dmamux::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DMAMUX {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DMAMUX").finish()
}
}
#[doc = "DMAMUX"]
pub mod dmamux;
#[doc = "System configuration controller"]
pub struct SYSCFG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SYSCFG {}
impl SYSCFG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const syscfg::RegisterBlock = 0x4001_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const syscfg::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SYSCFG {
type Target = syscfg::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SYSCFG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SYSCFG").finish()
}
}
#[doc = "System configuration controller"]
pub mod syscfg;
#[doc = "Voltage reference buffer"]
pub struct VREFBUF {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for VREFBUF {}
impl VREFBUF {
#[doc = r"Pointer to the register block"]
pub const PTR: *const vrefbuf::RegisterBlock = 0x4001_0030 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const vrefbuf::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for VREFBUF {
type Target = vrefbuf::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for VREFBUF {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("VREFBUF").finish()
}
}
#[doc = "Voltage reference buffer"]
pub mod vrefbuf;
#[doc = "Comparator control and status register"]
pub struct COMP {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for COMP {}
impl COMP {
#[doc = r"Pointer to the register block"]
pub const PTR: *const comp::RegisterBlock = 0x4001_0200 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const comp::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for COMP {
type Target = comp::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for COMP {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("COMP").finish()
}
}
#[doc = "Comparator control and status register"]
pub mod comp;
#[doc = "Operational amplifiers"]
pub struct OPAMP {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for OPAMP {}
impl OPAMP {
#[doc = r"Pointer to the register block"]
pub const PTR: *const opamp::RegisterBlock = 0x4001_0300 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const opamp::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for OPAMP {
type Target = opamp::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for OPAMP {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("OPAMP").finish()
}
}
#[doc = "Operational amplifiers"]
pub mod opamp;
#[doc = "QuadSPI interface"]
pub struct QUADSPI {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for QUADSPI {}
impl QUADSPI {
#[doc = r"Pointer to the register block"]
pub const PTR: *const quadspi::RegisterBlock = 0xa000_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const quadspi::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for QUADSPI {
type Target = quadspi::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for QUADSPI {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("QUADSPI").finish()
}
}
#[doc = "QuadSPI interface"]
pub mod quadspi;
#[doc = "Digital-to-analog converter"]
pub struct DAC1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DAC1 {}
impl DAC1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dac1::RegisterBlock = 0x5000_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dac1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DAC1 {
type Target = dac1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DAC1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DAC1").finish()
}
}
#[doc = "Digital-to-analog converter"]
pub mod dac1;
#[doc = "Digital-to-analog converter"]
pub struct DAC2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DAC2 {}
impl DAC2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dac1::RegisterBlock = 0x5000_0c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dac1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DAC2 {
type Target = dac1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DAC2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DAC2").finish()
}
}
#[doc = "Digital-to-analog converter"]
pub use self::dac1 as dac2;
#[doc = "Digital-to-analog converter"]
pub struct DAC3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DAC3 {}
impl DAC3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dac1::RegisterBlock = 0x5000_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dac1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DAC3 {
type Target = dac1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DAC3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DAC3").finish()
}
}
#[doc = "Digital-to-analog converter"]
pub use self::dac1 as dac3;
#[doc = "Digital-to-analog converter"]
pub struct DAC4 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DAC4 {}
impl DAC4 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dac1::RegisterBlock = 0x5000_1400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dac1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DAC4 {
type Target = dac1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DAC4 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DAC4").finish()
}
}
#[doc = "Digital-to-analog converter"]
pub use self::dac1 as dac4;
#[doc = "Analog-to-Digital Converter"]
pub struct ADC1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ADC1 {}
impl ADC1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc1::RegisterBlock = 0x5000_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for ADC1 {
type Target = adc1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ADC1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ADC1").finish()
}
}
#[doc = "Analog-to-Digital Converter"]
pub mod adc1;
#[doc = "Analog-to-Digital Converter"]
pub struct ADC2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ADC2 {}
impl ADC2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc1::RegisterBlock = 0x5000_0100 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for ADC2 {
type Target = adc1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ADC2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ADC2").finish()
}
}
#[doc = "Analog-to-Digital Converter"]
pub use self::adc1 as adc2;
#[doc = "Analog-to-Digital Converter"]
pub struct ADC3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ADC3 {}
impl ADC3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc3::RegisterBlock = 0x5000_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc3::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for ADC3 {
type Target = adc3::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ADC3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ADC3").finish()
}
}
#[doc = "Analog-to-Digital Converter"]
pub mod adc3;
#[doc = "Analog-to-Digital Converter"]
pub struct ADC4 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ADC4 {}
impl ADC4 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc1::RegisterBlock = 0x5000_0500 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for ADC4 {
type Target = adc1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ADC4 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ADC4").finish()
}
}
#[doc = "Analog-to-Digital Converter"]
pub use self::adc1 as adc4;
#[doc = "Analog-to-Digital Converter"]
pub struct ADC5 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ADC5 {}
impl ADC5 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc3::RegisterBlock = 0x5000_0600 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc3::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for ADC5 {
type Target = adc3::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ADC5 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ADC5").finish()
}
}
#[doc = "Analog-to-Digital Converter"]
pub use self::adc3 as adc5;
#[doc = "Analog-to-Digital Converter"]
pub struct ADC12_COMMON {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ADC12_COMMON {}
impl ADC12_COMMON {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc12_common::RegisterBlock = 0x5000_0300 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc12_common::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for ADC12_COMMON {
type Target = adc12_common::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ADC12_COMMON {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ADC12_COMMON").finish()
}
}
#[doc = "Analog-to-Digital Converter"]
pub mod adc12_common;
#[doc = "Analog-to-Digital Converter"]
pub struct ADC345_COMMON {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ADC345_COMMON {}
impl ADC345_COMMON {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc12_common::RegisterBlock = 0x5000_0700 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc12_common::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for ADC345_COMMON {
type Target = adc12_common::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ADC345_COMMON {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ADC345_COMMON").finish()
}
}
#[doc = "Analog-to-Digital Converter"]
pub use self::adc12_common as adc345_common;
#[doc = "Filter Math Accelerator"]
pub struct FMAC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for FMAC {}
impl FMAC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const fmac::RegisterBlock = 0x4002_1400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const fmac::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for FMAC {
type Target = fmac::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for FMAC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("FMAC").finish()
}
}
#[doc = "Filter Math Accelerator"]
pub mod fmac;
#[doc = "CORDIC Co-processor"]
pub struct CORDIC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for CORDIC {}
impl CORDIC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const cordic::RegisterBlock = 0x4002_0c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const cordic::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for CORDIC {
type Target = cordic::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for CORDIC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("CORDIC").finish()
}
}
#[doc = "CORDIC Co-processor"]
pub mod cordic;
#[doc = "Serial audio interface"]
pub struct SAI {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SAI {}
impl SAI {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sai::RegisterBlock = 0x4001_5400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sai::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SAI {
type Target = sai::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SAI {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SAI").finish()
}
}
#[doc = "Serial audio interface"]
pub mod sai;
#[doc = "Tamper and backup registers"]
pub struct TAMP {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TAMP {}
impl TAMP {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tamp::RegisterBlock = 0x4000_2400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tamp::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TAMP {
type Target = tamp::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TAMP {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TAMP").finish()
}
}
#[doc = "Tamper and backup registers"]
pub mod tamp;
#[doc = "SysTick timer"]
pub struct STK {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for STK {}
impl STK {
#[doc = r"Pointer to the register block"]
pub const PTR: *const stk::RegisterBlock = 0xe000_e010 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const stk::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for STK {
type Target = stk::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for STK {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("STK").finish()
}
}
#[doc = "SysTick timer"]
pub mod stk;
#[doc = "Nested vectored interrupt controller"]
pub struct NVIC_STIR {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for NVIC_STIR {}
impl NVIC_STIR {
#[doc = r"Pointer to the register block"]
pub const PTR: *const nvic_stir::RegisterBlock = 0xe000_ef00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const nvic_stir::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for NVIC_STIR {
type Target = nvic_stir::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for NVIC_STIR {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("NVIC_STIR").finish()
}
}
#[doc = "Nested vectored interrupt controller"]
pub mod nvic_stir;
#[doc = "Floating point unit CPACR"]
pub struct FPU_CPACR {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for FPU_CPACR {}
impl FPU_CPACR {
#[doc = r"Pointer to the register block"]
pub const PTR: *const fpu_cpacr::RegisterBlock = 0xe000_ed88 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const fpu_cpacr::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for FPU_CPACR {
type Target = fpu_cpacr::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for FPU_CPACR {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("FPU_CPACR").finish()
}
}
#[doc = "Floating point unit CPACR"]
pub mod fpu_cpacr;
#[doc = "System control block ACTLR"]
pub struct SCB_ACTLR {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SCB_ACTLR {}
impl SCB_ACTLR {
#[doc = r"Pointer to the register block"]
pub const PTR: *const scb_actlr::RegisterBlock = 0xe000_e008 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const scb_actlr::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SCB_ACTLR {
type Target = scb_actlr::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SCB_ACTLR {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SCB_ACTLR").finish()
}
}
#[doc = "System control block ACTLR"]
pub mod scb_actlr;
#[doc = "FDCAN"]
pub struct FDCAN {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for FDCAN {}
impl FDCAN {
#[doc = r"Pointer to the register block"]
pub const PTR: *const fdcan::RegisterBlock = 0x4000_a400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const fdcan::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for FDCAN {
type Target = fdcan::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for FDCAN {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("FDCAN").finish()
}
}
#[doc = "FDCAN"]
pub mod fdcan;
#[doc = "FDCAN"]
pub struct FDCAN1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for FDCAN1 {}
impl FDCAN1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const fdcan::RegisterBlock = 0x4000_6400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const fdcan::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for FDCAN1 {
type Target = fdcan::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for FDCAN1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("FDCAN1").finish()
}
}
#[doc = "FDCAN"]
pub use self::fdcan as fdcan1;
#[doc = "FDCAN"]
pub struct FDCAN2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for FDCAN2 {}
impl FDCAN2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const fdcan::RegisterBlock = 0x4000_6800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const fdcan::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for FDCAN2 {
type Target = fdcan::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for FDCAN2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("FDCAN2").finish()
}
}
#[doc = "FDCAN"]
pub use self::fdcan as fdcan2;
#[doc = "FDCAN"]
pub struct FDCAN3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for FDCAN3 {}
impl FDCAN3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const fdcan::RegisterBlock = 0x4000_6c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const fdcan::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for FDCAN3 {
type Target = fdcan::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for FDCAN3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("FDCAN3").finish()
}
}
#[doc = "FDCAN"]
pub use self::fdcan as fdcan3;
#[doc = "UCPD1"]
pub struct UCPD1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for UCPD1 {}
impl UCPD1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const ucpd1::RegisterBlock = 0x4000_a000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const ucpd1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for UCPD1 {
type Target = ucpd1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for UCPD1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("UCPD1").finish()
}
}
#[doc = "UCPD1"]
pub mod ucpd1;
#[doc = "USB_FS_device"]
pub struct USB {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for USB {}
impl USB {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usb::RegisterBlock = 0x4000_5c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usb::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for USB {
type Target = usb::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for USB {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("USB").finish()
}
}
#[doc = "USB_FS_device"]
pub mod usb;
#[doc = "CRS"]
pub struct CRS {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for CRS {}
impl CRS {
#[doc = r"Pointer to the register block"]
pub const PTR: *const crs::RegisterBlock = 0x4000_2000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const crs::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for CRS {
type Target = crs::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for CRS {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("CRS").finish()
}
}
#[doc = "CRS"]
pub mod crs;
#[no_mangle]
static mut DEVICE_PERIPHERALS: bool = false;
#[doc = r" All the peripherals."]
#[allow(non_snake_case)]
pub struct Peripherals {
#[doc = "CRC"]
pub CRC: CRC,
#[doc = "IWDG"]
pub IWDG: IWDG,
#[doc = "WWDG"]
pub WWDG: WWDG,
#[doc = "I2C1"]
pub I2C1: I2C1,
#[doc = "I2C2"]
pub I2C2: I2C2,
#[doc = "I2C3"]
pub I2C3: I2C3,
#[doc = "I2C4"]
pub I2C4: I2C4,
#[doc = "FLASH"]
pub FLASH: FLASH,
#[doc = "DBGMCU"]
pub DBGMCU: DBGMCU,
#[doc = "RCC"]
pub RCC: RCC,
#[doc = "PWR"]
pub PWR: PWR,
#[doc = "RNG"]
pub RNG: RNG,
#[doc = "AES"]
pub AES: AES,
#[doc = "GPIOA"]
pub GPIOA: GPIOA,
#[doc = "GPIOB"]
pub GPIOB: GPIOB,
#[doc = "GPIOC"]
pub GPIOC: GPIOC,
#[doc = "GPIOD"]
pub GPIOD: GPIOD,
#[doc = "GPIOE"]
pub GPIOE: GPIOE,
#[doc = "GPIOF"]
pub GPIOF: GPIOF,
#[doc = "GPIOG"]
pub GPIOG: GPIOG,
#[doc = "TIM15"]
pub TIM15: TIM15,
#[doc = "TIM16"]
pub TIM16: TIM16,
#[doc = "TIM17"]
pub TIM17: TIM17,
#[doc = "TIM1"]
pub TIM1: TIM1,
#[doc = "TIM20"]
pub TIM20: TIM20,
#[doc = "TIM8"]
pub TIM8: TIM8,
#[doc = "TIM2"]
pub TIM2: TIM2,
#[doc = "TIM3"]
pub TIM3: TIM3,
#[doc = "TIM4"]
pub TIM4: TIM4,
#[doc = "TIM5"]
pub TIM5: TIM5,
#[doc = "TIM6"]
pub TIM6: TIM6,
#[doc = "TIM7"]
pub TIM7: TIM7,
#[doc = "LPTIMER1"]
pub LPTIMER1: LPTIMER1,
#[doc = "USART1"]
pub USART1: USART1,
#[doc = "USART2"]
pub USART2: USART2,
#[doc = "USART3"]
pub USART3: USART3,
#[doc = "UART4"]
pub UART4: UART4,
#[doc = "UART5"]
pub UART5: UART5,
#[doc = "LPUART1"]
pub LPUART1: LPUART1,
#[doc = "SPI1"]
pub SPI1: SPI1,
#[doc = "SPI4"]
pub SPI4: SPI4,
#[doc = "SPI3"]
pub SPI3: SPI3,
#[doc = "SPI2"]
pub SPI2: SPI2,
#[doc = "EXTI"]
pub EXTI: EXTI,
#[doc = "RTC"]
pub RTC: RTC,
#[doc = "FMC"]
pub FMC: FMC,
#[doc = "DMA1"]
pub DMA1: DMA1,
#[doc = "DMA2"]
pub DMA2: DMA2,
#[doc = "DMAMUX"]
pub DMAMUX: DMAMUX,
#[doc = "SYSCFG"]
pub SYSCFG: SYSCFG,
#[doc = "VREFBUF"]
pub VREFBUF: VREFBUF,
#[doc = "COMP"]
pub COMP: COMP,
#[doc = "OPAMP"]
pub OPAMP: OPAMP,
#[doc = "QUADSPI"]
pub QUADSPI: QUADSPI,
#[doc = "DAC1"]
pub DAC1: DAC1,
#[doc = "DAC2"]
pub DAC2: DAC2,
#[doc = "DAC3"]
pub DAC3: DAC3,
#[doc = "DAC4"]
pub DAC4: DAC4,
#[doc = "ADC1"]
pub ADC1: ADC1,
#[doc = "ADC2"]
pub ADC2: ADC2,
#[doc = "ADC3"]
pub ADC3: ADC3,
#[doc = "ADC4"]
pub ADC4: ADC4,
#[doc = "ADC5"]
pub ADC5: ADC5,
#[doc = "ADC12_COMMON"]
pub ADC12_COMMON: ADC12_COMMON,
#[doc = "ADC345_COMMON"]
pub ADC345_COMMON: ADC345_COMMON,
#[doc = "FMAC"]
pub FMAC: FMAC,
#[doc = "CORDIC"]
pub CORDIC: CORDIC,
#[doc = "SAI"]
pub SAI: SAI,
#[doc = "TAMP"]
pub TAMP: TAMP,
#[doc = "STK"]
pub STK: STK,
#[doc = "NVIC_STIR"]
pub NVIC_STIR: NVIC_STIR,
#[doc = "FPU_CPACR"]
pub FPU_CPACR: FPU_CPACR,
#[doc = "SCB_ACTLR"]
pub SCB_ACTLR: SCB_ACTLR,
#[doc = "FDCAN"]
pub FDCAN: FDCAN,
#[doc = "FDCAN1"]
pub FDCAN1: FDCAN1,
#[doc = "FDCAN2"]
pub FDCAN2: FDCAN2,
#[doc = "FDCAN3"]
pub FDCAN3: FDCAN3,
#[doc = "UCPD1"]
pub UCPD1: UCPD1,
#[doc = "USB"]
pub USB: USB,
#[doc = "CRS"]
pub CRS: CRS,
}
impl Peripherals {
#[doc = r" Returns all the peripherals *once*."]
#[cfg(feature = "critical-section")]
#[inline]
pub fn take() -> Option<Self> {
critical_section::with(|_| {
if unsafe { DEVICE_PERIPHERALS } {
return None;
}
Some(unsafe { Peripherals::steal() })
})
}
#[doc = r" Unchecked version of `Peripherals::take`."]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Each of the returned peripherals must be used at most once."]
#[inline]
pub unsafe fn steal() -> Self {
DEVICE_PERIPHERALS = true;
Peripherals {
CRC: CRC {
_marker: PhantomData,
},
IWDG: IWDG {
_marker: PhantomData,
},
WWDG: WWDG {
_marker: PhantomData,
},
I2C1: I2C1 {
_marker: PhantomData,
},
I2C2: I2C2 {
_marker: PhantomData,
},
I2C3: I2C3 {
_marker: PhantomData,
},
I2C4: I2C4 {
_marker: PhantomData,
},
FLASH: FLASH {
_marker: PhantomData,
},
DBGMCU: DBGMCU {
_marker: PhantomData,
},
RCC: RCC {
_marker: PhantomData,
},
PWR: PWR {
_marker: PhantomData,
},
RNG: RNG {
_marker: PhantomData,
},
AES: AES {
_marker: PhantomData,
},
GPIOA: GPIOA {
_marker: PhantomData,
},
GPIOB: GPIOB {
_marker: PhantomData,
},
GPIOC: GPIOC {
_marker: PhantomData,
},
GPIOD: GPIOD {
_marker: PhantomData,
},
GPIOE: GPIOE {
_marker: PhantomData,
},
GPIOF: GPIOF {
_marker: PhantomData,
},
GPIOG: GPIOG {
_marker: PhantomData,
},
TIM15: TIM15 {
_marker: PhantomData,
},
TIM16: TIM16 {
_marker: PhantomData,
},
TIM17: TIM17 {
_marker: PhantomData,
},
TIM1: TIM1 {
_marker: PhantomData,
},
TIM20: TIM20 {
_marker: PhantomData,
},
TIM8: TIM8 {
_marker: PhantomData,
},
TIM2: TIM2 {
_marker: PhantomData,
},
TIM3: TIM3 {
_marker: PhantomData,
},
TIM4: TIM4 {
_marker: PhantomData,
},
TIM5: TIM5 {
_marker: PhantomData,
},
TIM6: TIM6 {
_marker: PhantomData,
},
TIM7: TIM7 {
_marker: PhantomData,
},
LPTIMER1: LPTIMER1 {
_marker: PhantomData,
},
USART1: USART1 {
_marker: PhantomData,
},
USART2: USART2 {
_marker: PhantomData,
},
USART3: USART3 {
_marker: PhantomData,
},
UART4: UART4 {
_marker: PhantomData,
},
UART5: UART5 {
_marker: PhantomData,
},
LPUART1: LPUART1 {
_marker: PhantomData,
},
SPI1: SPI1 {
_marker: PhantomData,
},
SPI4: SPI4 {
_marker: PhantomData,
},
SPI3: SPI3 {
_marker: PhantomData,
},
SPI2: SPI2 {
_marker: PhantomData,
},
EXTI: EXTI {
_marker: PhantomData,
},
RTC: RTC {
_marker: PhantomData,
},
FMC: FMC {
_marker: PhantomData,
},
DMA1: DMA1 {
_marker: PhantomData,
},
DMA2: DMA2 {
_marker: PhantomData,
},
DMAMUX: DMAMUX {
_marker: PhantomData,
},
SYSCFG: SYSCFG {
_marker: PhantomData,
},
VREFBUF: VREFBUF {
_marker: PhantomData,
},
COMP: COMP {
_marker: PhantomData,
},
OPAMP: OPAMP {
_marker: PhantomData,
},
QUADSPI: QUADSPI {
_marker: PhantomData,
},
DAC1: DAC1 {
_marker: PhantomData,
},
DAC2: DAC2 {
_marker: PhantomData,
},
DAC3: DAC3 {
_marker: PhantomData,
},
DAC4: DAC4 {
_marker: PhantomData,
},
ADC1: ADC1 {
_marker: PhantomData,
},
ADC2: ADC2 {
_marker: PhantomData,
},
ADC3: ADC3 {
_marker: PhantomData,
},
ADC4: ADC4 {
_marker: PhantomData,
},
ADC5: ADC5 {
_marker: PhantomData,
},
ADC12_COMMON: ADC12_COMMON {
_marker: PhantomData,
},
ADC345_COMMON: ADC345_COMMON {
_marker: PhantomData,
},
FMAC: FMAC {
_marker: PhantomData,
},
CORDIC: CORDIC {
_marker: PhantomData,
},
SAI: SAI {
_marker: PhantomData,
},
TAMP: TAMP {
_marker: PhantomData,
},
STK: STK {
_marker: PhantomData,
},
NVIC_STIR: NVIC_STIR {
_marker: PhantomData,
},
FPU_CPACR: FPU_CPACR {
_marker: PhantomData,
},
SCB_ACTLR: SCB_ACTLR {
_marker: PhantomData,
},
FDCAN: FDCAN {
_marker: PhantomData,
},
FDCAN1: FDCAN1 {
_marker: PhantomData,
},
FDCAN2: FDCAN2 {
_marker: PhantomData,
},
FDCAN3: FDCAN3 {
_marker: PhantomData,
},
UCPD1: UCPD1 {
_marker: PhantomData,
},
USB: USB {
_marker: PhantomData,
},
CRS: CRS {
_marker: PhantomData,
},
}
}
}
|
fn main() {
let s = "パトカー".to_string();
let t = "タクシー".to_string();
let mut u = String::new();
for i in 0..s.chars().count() {
u = format!("{}{}{}",
u,
s.chars().nth(i).unwrap(),
t.chars().nth(i).unwrap()
);
}
println!("{}", u);
}
|
extern crate skim;
use skim::prelude::*;
struct MyItem {
inner: String,
}
impl SkimItem for MyItem {
fn text(&self) -> Cow<str> {
Cow::Borrowed(&self.inner)
}
fn preview(&self, _context: PreviewContext) -> ItemPreview {
if self.inner.starts_with("color") {
ItemPreview::AnsiText(format!("\x1b[31mhello:\x1b[m\n{}", self.inner))
} else {
ItemPreview::Text(format!("hello:\n{}", self.inner))
}
}
}
pub fn main() {
let options = SkimOptionsBuilder::default()
.height(Some("50%"))
.multi(true)
.preview(Some("")) // preview should be specified to enable preview window
.build()
.unwrap();
let (tx_item, rx_item): (SkimItemSender, SkimItemReceiver) = unbounded();
let _ = tx_item.send(Arc::new(MyItem {
inner: "color aaaa".to_string(),
}));
let _ = tx_item.send(Arc::new(MyItem {
inner: "bbbb".to_string(),
}));
let _ = tx_item.send(Arc::new(MyItem {
inner: "ccc".to_string(),
}));
drop(tx_item); // so that skim could know when to stop waiting for more items.
let selected_items = Skim::run_with(&options, Some(rx_item))
.map(|out| out.selected_items)
.unwrap_or_else(Vec::new);
for item in selected_items.iter() {
println!("{}", item.output());
}
}
|
use primal::{is_prime, Primes};
use std::time::Instant;
fn main() {
let now = Instant::now();
println!("e35:{:?}, {:?} seconds", e(), now.elapsed());
}
fn e() -> usize {
Primes::all()
.take_while(|&p| p < 1000000)
.filter(|p| is_odd_digits(p))
.filter(|p| is_cycle_prime(p))
.count()
}
fn is_odd_digits(p: &usize) -> bool {
// true if p is composed solely of odd digits.
let s: &str = &format!("{}", p); // 0
// 1
!s.contains("0")
&& !s.contains("2")
&& !s.contains("4")
&& !s.contains("5")
&& !s.contains("6")
&& !s.contains("8")
}
fn is_cycle_prime(p: &usize) -> bool {
// if every cyclic permutation of p is prime, give true.
let s: String = format!("{}", p);
for i in 1..s.len() {
let mut st = String::from(&s[i..]);
st.push_str(&s[..i]);
if !is_prime(st.parse().unwrap()) {
return false;
}
}
true
}
// Results
//e35:53, 82.8052ms seconds
// This would be much faster if I
// rewrote my predicates to use int manipulation, rather
// than strings. But more tedious.
|
use super::DIMENSION;
use tile::Tile;
#[derive(Debug, Serialize, Deserialize)]
pub struct Board {
pub current_id: usize,
pub grid: Vec<Vec<Tile>>
}
impl Board {
pub fn new() -> Board {
let mut id = 0;
Board {
grid: vec![0; DIMENSION]
.iter()
.map(|_| vec![0; DIMENSION]
.iter()
.map(|_| {
id += 1;
Tile::new(id)
}).collect()
).collect(),
current_id: id
}
}
pub fn get_new_id(&mut self) -> usize {
self.current_id += 1;
self.current_id
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let board = Board::new();
// println!("Board {:?}", board);
}
}
|
use rocket::http::Status;
use rocket::request::Request;
use rocket::response::{self, Responder, Response};
use std::{error, fmt, io::Cursor};
#[derive(Debug, Clone)]
pub struct ApiError {
reason: &'static str,
status: u16,
}
impl ApiError {
pub fn new(reason: &'static str, status: u16) -> ApiError {
ApiError { reason, status }
}
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.reason)
}
}
impl error::Error for ApiError {
fn description(&self) -> &str {
self.reason
}
}
impl<'r> Responder<'r> for ApiError {
fn respond_to(self, _: &Request) -> response::Result<'r> {
Response::build()
.status(Status::raw(self.status))
.sized_body(Cursor::new(format!("{}", self)))
.ok()
}
}
|
#[doc = "Register `FDCAN_TTILS` reader"]
pub type R = crate::R<FDCAN_TTILS_SPEC>;
#[doc = "Register `FDCAN_TTILS` writer"]
pub type W = crate::W<FDCAN_TTILS_SPEC>;
#[doc = "Field `SBCL` reader - SBCL"]
pub type SBCL_R = crate::BitReader;
#[doc = "Field `SBCL` writer - SBCL"]
pub type SBCL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SMCL` reader - SMCL"]
pub type SMCL_R = crate::BitReader;
#[doc = "Field `SMCL` writer - SMCL"]
pub type SMCL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSML` reader - CSML"]
pub type CSML_R = crate::BitReader;
#[doc = "Field `CSML` writer - CSML"]
pub type CSML_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SOGL` reader - SOGL"]
pub type SOGL_R = crate::BitReader;
#[doc = "Field `SOGL` writer - SOGL"]
pub type SOGL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RTMIL` reader - RTMIL"]
pub type RTMIL_R = crate::BitReader;
#[doc = "Field `RTMIL` writer - RTMIL"]
pub type RTMIL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TTMIL` reader - TTMIL"]
pub type TTMIL_R = crate::BitReader;
#[doc = "Field `TTMIL` writer - TTMIL"]
pub type TTMIL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SWEL` reader - SWEL"]
pub type SWEL_R = crate::BitReader;
#[doc = "Field `SWEL` writer - SWEL"]
pub type SWEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GTWL` reader - GTWL"]
pub type GTWL_R = crate::BitReader;
#[doc = "Field `GTWL` writer - GTWL"]
pub type GTWL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GTDL` reader - GTDL"]
pub type GTDL_R = crate::BitReader;
#[doc = "Field `GTDL` writer - GTDL"]
pub type GTDL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GTEL` reader - GTEL"]
pub type GTEL_R = crate::BitReader;
#[doc = "Field `GTEL` writer - GTEL"]
pub type GTEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TXUL` reader - TXUL"]
pub type TXUL_R = crate::BitReader;
#[doc = "Field `TXUL` writer - TXUL"]
pub type TXUL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TXOL` reader - TXOL"]
pub type TXOL_R = crate::BitReader;
#[doc = "Field `TXOL` writer - TXOL"]
pub type TXOL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SE1L` reader - SE1L"]
pub type SE1L_R = crate::BitReader;
#[doc = "Field `SE1L` writer - SE1L"]
pub type SE1L_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SE2L` reader - SE2L"]
pub type SE2L_R = crate::BitReader;
#[doc = "Field `SE2L` writer - SE2L"]
pub type SE2L_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ELCL` reader - ELCL"]
pub type ELCL_R = crate::BitReader;
#[doc = "Field `ELCL` writer - ELCL"]
pub type ELCL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IWTL` reader - IWTL"]
pub type IWTL_R = crate::BitReader;
#[doc = "Field `IWTL` writer - IWTL"]
pub type IWTL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `WTL` reader - WTL"]
pub type WTL_R = crate::BitReader;
#[doc = "Field `WTL` writer - WTL"]
pub type WTL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AWL` reader - AWL"]
pub type AWL_R = crate::BitReader;
#[doc = "Field `AWL` writer - AWL"]
pub type AWL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CERL` reader - CERL"]
pub type CERL_R = crate::BitReader;
#[doc = "Field `CERL` writer - CERL"]
pub type CERL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - SBCL"]
#[inline(always)]
pub fn sbcl(&self) -> SBCL_R {
SBCL_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - SMCL"]
#[inline(always)]
pub fn smcl(&self) -> SMCL_R {
SMCL_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - CSML"]
#[inline(always)]
pub fn csml(&self) -> CSML_R {
CSML_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - SOGL"]
#[inline(always)]
pub fn sogl(&self) -> SOGL_R {
SOGL_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - RTMIL"]
#[inline(always)]
pub fn rtmil(&self) -> RTMIL_R {
RTMIL_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - TTMIL"]
#[inline(always)]
pub fn ttmil(&self) -> TTMIL_R {
TTMIL_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - SWEL"]
#[inline(always)]
pub fn swel(&self) -> SWEL_R {
SWEL_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - GTWL"]
#[inline(always)]
pub fn gtwl(&self) -> GTWL_R {
GTWL_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - GTDL"]
#[inline(always)]
pub fn gtdl(&self) -> GTDL_R {
GTDL_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - GTEL"]
#[inline(always)]
pub fn gtel(&self) -> GTEL_R {
GTEL_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - TXUL"]
#[inline(always)]
pub fn txul(&self) -> TXUL_R {
TXUL_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - TXOL"]
#[inline(always)]
pub fn txol(&self) -> TXOL_R {
TXOL_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - SE1L"]
#[inline(always)]
pub fn se1l(&self) -> SE1L_R {
SE1L_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - SE2L"]
#[inline(always)]
pub fn se2l(&self) -> SE2L_R {
SE2L_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - ELCL"]
#[inline(always)]
pub fn elcl(&self) -> ELCL_R {
ELCL_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - IWTL"]
#[inline(always)]
pub fn iwtl(&self) -> IWTL_R {
IWTL_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - WTL"]
#[inline(always)]
pub fn wtl(&self) -> WTL_R {
WTL_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - AWL"]
#[inline(always)]
pub fn awl(&self) -> AWL_R {
AWL_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - CERL"]
#[inline(always)]
pub fn cerl(&self) -> CERL_R {
CERL_R::new(((self.bits >> 18) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - SBCL"]
#[inline(always)]
#[must_use]
pub fn sbcl(&mut self) -> SBCL_W<FDCAN_TTILS_SPEC, 0> {
SBCL_W::new(self)
}
#[doc = "Bit 1 - SMCL"]
#[inline(always)]
#[must_use]
pub fn smcl(&mut self) -> SMCL_W<FDCAN_TTILS_SPEC, 1> {
SMCL_W::new(self)
}
#[doc = "Bit 2 - CSML"]
#[inline(always)]
#[must_use]
pub fn csml(&mut self) -> CSML_W<FDCAN_TTILS_SPEC, 2> {
CSML_W::new(self)
}
#[doc = "Bit 3 - SOGL"]
#[inline(always)]
#[must_use]
pub fn sogl(&mut self) -> SOGL_W<FDCAN_TTILS_SPEC, 3> {
SOGL_W::new(self)
}
#[doc = "Bit 4 - RTMIL"]
#[inline(always)]
#[must_use]
pub fn rtmil(&mut self) -> RTMIL_W<FDCAN_TTILS_SPEC, 4> {
RTMIL_W::new(self)
}
#[doc = "Bit 5 - TTMIL"]
#[inline(always)]
#[must_use]
pub fn ttmil(&mut self) -> TTMIL_W<FDCAN_TTILS_SPEC, 5> {
TTMIL_W::new(self)
}
#[doc = "Bit 6 - SWEL"]
#[inline(always)]
#[must_use]
pub fn swel(&mut self) -> SWEL_W<FDCAN_TTILS_SPEC, 6> {
SWEL_W::new(self)
}
#[doc = "Bit 7 - GTWL"]
#[inline(always)]
#[must_use]
pub fn gtwl(&mut self) -> GTWL_W<FDCAN_TTILS_SPEC, 7> {
GTWL_W::new(self)
}
#[doc = "Bit 8 - GTDL"]
#[inline(always)]
#[must_use]
pub fn gtdl(&mut self) -> GTDL_W<FDCAN_TTILS_SPEC, 8> {
GTDL_W::new(self)
}
#[doc = "Bit 9 - GTEL"]
#[inline(always)]
#[must_use]
pub fn gtel(&mut self) -> GTEL_W<FDCAN_TTILS_SPEC, 9> {
GTEL_W::new(self)
}
#[doc = "Bit 10 - TXUL"]
#[inline(always)]
#[must_use]
pub fn txul(&mut self) -> TXUL_W<FDCAN_TTILS_SPEC, 10> {
TXUL_W::new(self)
}
#[doc = "Bit 11 - TXOL"]
#[inline(always)]
#[must_use]
pub fn txol(&mut self) -> TXOL_W<FDCAN_TTILS_SPEC, 11> {
TXOL_W::new(self)
}
#[doc = "Bit 12 - SE1L"]
#[inline(always)]
#[must_use]
pub fn se1l(&mut self) -> SE1L_W<FDCAN_TTILS_SPEC, 12> {
SE1L_W::new(self)
}
#[doc = "Bit 13 - SE2L"]
#[inline(always)]
#[must_use]
pub fn se2l(&mut self) -> SE2L_W<FDCAN_TTILS_SPEC, 13> {
SE2L_W::new(self)
}
#[doc = "Bit 14 - ELCL"]
#[inline(always)]
#[must_use]
pub fn elcl(&mut self) -> ELCL_W<FDCAN_TTILS_SPEC, 14> {
ELCL_W::new(self)
}
#[doc = "Bit 15 - IWTL"]
#[inline(always)]
#[must_use]
pub fn iwtl(&mut self) -> IWTL_W<FDCAN_TTILS_SPEC, 15> {
IWTL_W::new(self)
}
#[doc = "Bit 16 - WTL"]
#[inline(always)]
#[must_use]
pub fn wtl(&mut self) -> WTL_W<FDCAN_TTILS_SPEC, 16> {
WTL_W::new(self)
}
#[doc = "Bit 17 - AWL"]
#[inline(always)]
#[must_use]
pub fn awl(&mut self) -> AWL_W<FDCAN_TTILS_SPEC, 17> {
AWL_W::new(self)
}
#[doc = "Bit 18 - CERL"]
#[inline(always)]
#[must_use]
pub fn cerl(&mut self) -> CERL_W<FDCAN_TTILS_SPEC, 18> {
CERL_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "The TT interrupt Line select register assigns an interrupt generated by a specific interrupt flag from the TT interrupt register to one of the two module interrupt lines. For interrupt generation the respective interrupt line has to be enabled via FDCAN_ILE.EINT0 and FDCAN_ILE.EINT1.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fdcan_ttils::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`fdcan_ttils::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct FDCAN_TTILS_SPEC;
impl crate::RegisterSpec for FDCAN_TTILS_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`fdcan_ttils::R`](R) reader structure"]
impl crate::Readable for FDCAN_TTILS_SPEC {}
#[doc = "`write(|w| ..)` method takes [`fdcan_ttils::W`](W) writer structure"]
impl crate::Writable for FDCAN_TTILS_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets FDCAN_TTILS to value 0"]
impl crate::Resettable for FDCAN_TTILS_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[cfg(test)]
#[macro_use] extern crate assert_matches;
mod automaton;
mod distinct_map;
mod query_builder;
mod reordered_attrs;
mod store;
pub mod criterion;
use std::fmt;
use std::sync::Arc;
use sdset::SetBuf;
use serde::{Serialize, Deserialize};
use slice_group_by::GroupBy;
use zerocopy::{AsBytes, FromBytes};
pub use self::query_builder::{QueryBuilder, DistinctQueryBuilder, normalize_str};
pub use self::store::Store;
/// Represent an internally generated document unique identifier.
///
/// It is used to inform the database the document you want to deserialize.
/// Helpful for custom ranking.
#[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
#[derive(Serialize, Deserialize)]
#[derive(AsBytes, FromBytes)]
#[repr(C)]
pub struct DocumentId(pub u64);
/// This structure represent the position of a word
/// in a document and its attributes.
///
/// This is stored in the map, generated at index time,
/// extracted and interpreted at search time.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(AsBytes, FromBytes)]
#[repr(C)]
pub struct DocIndex {
/// The document identifier where the word was found.
pub document_id: DocumentId,
/// The attribute in the document where the word was found
/// along with the index in it.
pub attribute: u16,
pub word_index: u16,
/// The position in bytes where the word was found
/// along with the length of it.
///
/// It informs on the original word area in the text indexed
/// without needing to run the tokenizer again.
pub char_index: u16,
pub char_length: u16,
}
/// This structure represent a matching word with informations
/// on the location of the word in the document.
///
/// The order of the field is important because it defines
/// the way these structures are ordered between themselves.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Highlight {
/// The attribute in the document where the word was found
/// along with the index in it.
pub attribute: u16,
/// The position in bytes where the word was found.
///
/// It informs on the original word area in the text indexed
/// without needing to run the tokenizer again.
pub char_index: u16,
/// The length in bytes of the found word.
///
/// It informs on the original word area in the text indexed
/// without needing to run the tokenizer again.
pub char_length: u16,
}
#[doc(hidden)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TmpMatch {
pub query_index: u32,
pub distance: u8,
pub attribute: u16,
pub word_index: u16,
pub is_exact: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Document {
pub id: DocumentId,
pub highlights: Vec<Highlight>,
#[cfg(test)]
pub matches: Vec<TmpMatch>,
}
impl Document {
#[cfg(not(test))]
fn from_raw(raw: RawDocument) -> Document {
Document { id: raw.id, highlights: raw.highlights }
}
#[cfg(test)]
fn from_raw(raw: RawDocument) -> Document {
let len = raw.query_index().len();
let mut matches = Vec::with_capacity(len);
let query_index = raw.query_index();
let distance = raw.distance();
let attribute = raw.attribute();
let word_index = raw.word_index();
let is_exact = raw.is_exact();
for i in 0..len {
let match_ = TmpMatch {
query_index: query_index[i],
distance: distance[i],
attribute: attribute[i],
word_index: word_index[i],
is_exact: is_exact[i],
};
matches.push(match_);
}
Document { id: raw.id, matches, highlights: raw.highlights }
}
}
#[derive(Clone)]
pub struct RawDocument {
pub id: DocumentId,
pub matches: SharedMatches,
pub highlights: Vec<Highlight>,
}
impl RawDocument {
fn new(id: DocumentId, matches: SharedMatches, highlights: Vec<Highlight>) -> RawDocument {
RawDocument { id, matches, highlights }
}
pub fn query_index(&self) -> &[u32] {
let r = self.matches.range;
// it is safe because construction/modifications
// can only be done in this module
unsafe { &self.matches.matches.query_index.get_unchecked(r.start..r.end) }
}
pub fn distance(&self) -> &[u8] {
let r = self.matches.range;
// it is safe because construction/modifications
// can only be done in this module
unsafe { &self.matches.matches.distance.get_unchecked(r.start..r.end) }
}
pub fn attribute(&self) -> &[u16] {
let r = self.matches.range;
// it is safe because construction/modifications
// can only be done in this module
unsafe { &self.matches.matches.attribute.get_unchecked(r.start..r.end) }
}
pub fn word_index(&self) -> &[u16] {
let r = self.matches.range;
// it is safe because construction/modifications
// can only be done in this module
unsafe { &self.matches.matches.word_index.get_unchecked(r.start..r.end) }
}
pub fn is_exact(&self) -> &[bool] {
let r = self.matches.range;
// it is safe because construction/modifications
// can only be done in this module
unsafe { &self.matches.matches.is_exact.get_unchecked(r.start..r.end) }
}
}
impl fmt::Debug for RawDocument {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("RawDocument")
.field("id", &self.id)
.field("query_index", &self.query_index())
.field("distance", &self.distance())
.field("attribute", &self.attribute())
.field("word_index", &self.word_index())
.field("is_exact", &self.is_exact())
.finish()
}
}
fn raw_documents_from_matches(matches: SetBuf<(DocumentId, TmpMatch, Highlight)>) -> Vec<RawDocument> {
let mut docs_ranges: Vec<(_, Range, _)> = Vec::new();
let mut matches2 = Matches::with_capacity(matches.len());
for group in matches.linear_group_by(|(a, _, _), (b, _, _)| a == b) {
let document_id = group[0].0;
let start = docs_ranges.last().map(|(_, r, _)| r.end).unwrap_or(0);
let end = start + group.len();
let highlights = group.iter().map(|(_, _, h)| *h).collect();
docs_ranges.push((document_id, Range { start, end }, highlights));
matches2.extend_from_slice(group);
}
let matches = Arc::new(matches2);
docs_ranges.into_iter().map(|(i, range, highlights)| {
let matches = SharedMatches { range, matches: matches.clone() };
RawDocument::new(i, matches, highlights)
}).collect()
}
#[derive(Debug, Copy, Clone)]
struct Range {
start: usize,
end: usize,
}
#[derive(Clone)]
pub struct SharedMatches {
range: Range,
matches: Arc<Matches>,
}
#[derive(Clone)]
struct Matches {
query_index: Vec<u32>,
distance: Vec<u8>,
attribute: Vec<u16>,
word_index: Vec<u16>,
is_exact: Vec<bool>,
}
impl Matches {
fn with_capacity(cap: usize) -> Matches {
Matches {
query_index: Vec::with_capacity(cap),
distance: Vec::with_capacity(cap),
attribute: Vec::with_capacity(cap),
word_index: Vec::with_capacity(cap),
is_exact: Vec::with_capacity(cap),
}
}
fn extend_from_slice(&mut self, matches: &[(DocumentId, TmpMatch, Highlight)]) {
for (_, match_, _) in matches {
self.query_index.push(match_.query_index);
self.distance.push(match_.distance);
self.attribute.push(match_.attribute);
self.word_index.push(match_.word_index);
self.is_exact.push(match_.is_exact);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem;
#[test]
fn docindex_mem_size() {
assert_eq!(mem::size_of::<DocIndex>(), 16);
}
}
|
use itertools::Itertools;
use std::collections::HashSet;
pub mod part1;
pub mod part2;
pub fn run() {
part1::run();
part2::run();
}
pub fn default_input() -> &'static str {
include_str!("input")
}
pub fn parse_input(input : &str) -> Vec<FoodLine> {
input.lines().map(|l| {
let split = l.split("(contains").collect_vec();
let ingredients = split[0].trim().split(" ").map(|s| s.to_string()).collect();
let allergens = (&(split[1].trim())[..split[1].trim().len() -1]).split(",").map(|s| s.trim().to_string()).collect();
FoodLine {ingredients, allergens}
}).collect_vec()
}
pub struct FoodLine {
pub ingredients: HashSet<String>,
pub allergens: HashSet<String>,
} |
use std::cmp;
use na::{DMatrix, Matrix4};
use nl::Eigen;
use crate::proptest::*;
use proptest::{prop_assert, proptest};
proptest! {
#[test]
fn eigensystem(n in PROPTEST_MATRIX_DIM) {
let n = cmp::min(n, 25);
let m = DMatrix::<f64>::new_random(n, n);
if let Some(eig) = Eigen::new(m.clone(), true, true) {
let eigvals = DMatrix::from_diagonal(&eig.eigenvalues);
let transformed_eigvectors = &m * eig.eigenvectors.as_ref().unwrap();
let scaled_eigvectors = eig.eigenvectors.as_ref().unwrap() * &eigvals;
let transformed_left_eigvectors = m.transpose() * eig.left_eigenvectors.as_ref().unwrap();
let scaled_left_eigvectors = eig.left_eigenvectors.as_ref().unwrap() * &eigvals;
prop_assert!(relative_eq!(transformed_eigvectors, scaled_eigvectors, epsilon = 1.0e-7));
prop_assert!(relative_eq!(transformed_left_eigvectors, scaled_left_eigvectors, epsilon = 1.0e-7));
}
}
#[test]
fn eigensystem_static(m in matrix4()) {
if let Some(eig) = Eigen::new(m, true, true) {
let eigvals = Matrix4::from_diagonal(&eig.eigenvalues);
let transformed_eigvectors = m * eig.eigenvectors.unwrap();
let scaled_eigvectors = eig.eigenvectors.unwrap() * eigvals;
let transformed_left_eigvectors = m.transpose() * eig.left_eigenvectors.unwrap();
let scaled_left_eigvectors = eig.left_eigenvectors.unwrap() * eigvals;
prop_assert!(relative_eq!(transformed_eigvectors, scaled_eigvectors, epsilon = 1.0e-7));
prop_assert!(relative_eq!(transformed_left_eigvectors, scaled_left_eigvectors, epsilon = 1.0e-7));
}
}
}
|
use super::*;
use crate::Name;
impl<'a> Name<'a> for Document<'a> {}
impl<'a> Name<'a> for Definition<'a> {
fn name(&self) -> Option<&'a str> {
match self {
Definition::Schema(_) => None,
Definition::Type(t) => t.name(),
Definition::TypeExtension(te) => te.name(),
Definition::Directive(d) => Some(d.name),
Definition::Operation(o) => o.name,
Definition::Fragment(f) => Some(f.name),
}
}
}
impl<'a> Name<'a> for TypeDefinition<'a> {
fn name(&self) -> Option<&'a str> {
match self {
TypeDefinition::Scalar(s) => Some(s.name),
TypeDefinition::Object(o) => Some(o.name),
TypeDefinition::Interface(i) => Some(i.name),
TypeDefinition::Union(u) => Some(u.name),
TypeDefinition::Enum(e) => Some(e.name),
TypeDefinition::InputObject(io) => Some(io.name),
}
}
}
impl<'a> Name<'a> for TypeExtension<'a> {
fn name(&self) -> Option<&'a str> {
match self {
TypeExtension::Scalar(s) => Some(s.name),
TypeExtension::Object(o) => Some(o.name),
TypeExtension::Interface(i) => Some(i.name),
TypeExtension::Union(u) => Some(u.name),
TypeExtension::Enum(e) => Some(e.name),
TypeExtension::InputObject(io) => Some(io.name),
}
}
}
impl<'a> Name<'a> for Field<'a> {
fn name(&self) -> Option<&'a str> {
Some(self.name)
}
}
impl<'a> Name<'a> for InputValue<'a> {
fn name(&self) -> Option<&'a str> {
Some(self.name)
}
}
impl<'a> Name<'a> for EnumValue<'a> {
fn name(&self) -> Option<&'a str> {
Some(self.name)
}
}
|
#[macro_use]
extern crate log;
extern crate async_std;
extern crate getopts;
extern crate stunnel;
use std::env;
use async_std::net::TcpListener;
use async_std::prelude::*;
use async_std::task;
use stunnel::cryptor::Cryptor;
use stunnel::logger;
use stunnel::server::*;
use stunnel::ucp::UcpListener;
fn main() {
let args: Vec<_> = env::args().collect();
let program = args[0].clone();
let mut opts = getopts::Options::new();
opts.reqopt("l", "listen", "listen address", "listen-address");
opts.reqopt("k", "key", "secret key", "key");
opts.optopt("", "log", "log path", "log-path");
opts.optflag("", "enable-ucp", "enable ucp");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(_) => {
println!("{}", opts.short_usage(&program));
return;
}
};
let listen_addr = matches.opt_str("l").unwrap();
let key = matches.opt_str("k").unwrap().into_bytes();
let log_path = matches.opt_str("log").unwrap_or(String::new());
let enable_ucp = matches.opt_present("enable-ucp");
let (min, max) = Cryptor::key_size_range();
if key.len() < min || key.len() > max {
println!("key length must in range [{}, {}]", min, max);
return;
}
logger::init(log::Level::Info, log_path, 1, 2000000).unwrap();
info!("starting up");
if enable_ucp {
let k = key.clone();
let addr = listen_addr.clone();
task::spawn(async move {
let mut listener = UcpListener::bind(&addr).await;
loop {
let stream = listener.incoming().await;
UcpTunnel::new(k.clone(), stream);
}
});
}
task::block_on(async move {
let listener = TcpListener::bind(&listen_addr).await.unwrap();
let mut incoming = listener.incoming();
while let Some(stream) = incoming.next().await {
match stream {
Ok(stream) => {
TcpTunnel::new(key.clone(), stream);
}
Err(_) => {}
}
}
});
}
|
extern crate capstone;
extern crate jazz_jit;
use capstone::prelude::*;
use jazz_jit::assembler::Assembler;
use jazz_jit::assembler_x64::*;
use jazz_jit::constants_x64::*;
use jazz_jit::{get_executable_memory, Memory};
fn main() {
let mut asm = Assembler::new();
emit_movl_imm_reg(&mut asm, 2, RAX);
emit_retq(&mut asm);
let mem = get_executable_memory(&asm);
let mut asm = Assembler::new();
emit_movq_imm64_reg(&mut asm, mem.ptr() as i64, RAX);
emit_callq_reg(&mut asm, RAX);
emit_retq(&mut asm);
let mem: Memory = get_executable_memory(&asm);
let ptr = mem.ptr();
let mut cs = Capstone::new().x86()
.mode(arch::x86::ArchMode::Mode64)
.syntax(arch::x86::ArchSyntax::Att)
.detail(true)
.build()
.unwrap();
let buf = unsafe { ::std::slice::from_raw_parts(ptr, mem.size()) };
let i = cs.disasm_all(buf, 0x0).unwrap();
for i in i.iter() {
println!("{}", i);
}
let f: fn() -> i32 = unsafe { ::std::mem::transmute(ptr) };
print!("{}\n", f());
}
|
use crate::Idx;
use std::{fmt, marker::PhantomData, ops::Index};
/// A map from arena indexes to some other type.
/// Space requirement is O(highest index).
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ArenaMap<K, V> {
data: Vec<Option<V>>,
_ty: PhantomData<K>,
}
impl<T, V: fmt::Debug> fmt::Debug for ArenaMap<Idx<T>, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
impl<T, V> ArenaMap<Idx<T>, V> {
pub fn new() -> Self { Self::default() }
/// Inserts a value associated with a given arena index into the map.
pub fn insert(&mut self, idx: Idx<T>, t: V) {
let raw = usize::from(idx);
self.data
.resize_with((raw + 1).max(self.data.len()), || None);
self.data[raw] = Some(t);
}
/// Returns a reference to the value associated with the provided index
/// if it is present.
pub fn get(&self, idx: Idx<T>) -> Option<&V> {
self.data.get(usize::from(idx)).and_then(Option::as_ref)
}
/// Returns a mutable reference to the value associated with the provided
/// index if it is present.
pub fn get_mut(&mut self, idx: Idx<T>) -> Option<&mut V> {
self.data.get_mut(usize::from(idx)).and_then(Option::as_mut)
}
/// Returns an iterator over the values in the map.
pub fn values(&self) -> impl Iterator<Item = &V> { self.data.iter().filter_map(Option::as_ref) }
/// Returns an iterator over mutable references to the values in the map.
pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
self.data.iter_mut().filter_map(Option::as_mut)
}
/// Returns an iterator over the arena indexes and values in the map.
pub fn iter(&self) -> impl Iterator<Item = (Idx<T>, &V)> {
self.data
.iter()
.enumerate()
.filter_map(|(idx, o)| Some((idx.into(), o.as_ref()?)))
}
/// Returns an iterator over the arena indexes and values in the map.
pub fn iter_mut(&mut self) -> impl Iterator<Item = (Idx<T>, &mut V)> {
self.data
.iter_mut()
.enumerate()
.filter_map(|(idx, o)| Some((idx.into(), o.as_mut()?)))
}
}
impl<T, V> Default for ArenaMap<Idx<T>, V> {
fn default() -> Self {
Self {
data: Vec::new(),
_ty: PhantomData,
}
}
}
impl<T, V> Index<Idx<V>> for ArenaMap<Idx<V>, T> {
type Output = T;
fn index(&self, idx: Idx<V>) -> &T { self.data[idx.raw as usize].as_ref().unwrap() }
}
|
use {
crate::{data::Value, result::Result},
serde::{Deserialize, Serialize},
serde_json::{Map as JsonMap, Value as JsonValue},
std::{collections::HashMap, fmt::Debug, ops::ControlFlow},
thiserror::Error as ThisError,
};
#[derive(Debug, PartialEq, ThisError, Serialize)]
pub enum MapError {
#[error("parse failed - invalid json")]
InvalidJsonString,
#[error("parse failed - json object type is required")]
ObjectTypeJsonRequired,
#[error("Array type is not yet supported")]
ArrayTypeNotSupported,
#[error("unreachable - failed to parse json number value: {0}")]
UnreachableJsonNumberParseFailure(String),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Map(HashMap<String, Value>);
impl Map {
pub fn parse_json(value: &str) -> Result<Self> {
let value: JsonValue =
serde_json::from_str(value).map_err(|_| MapError::InvalidJsonString)?;
match value {
JsonValue::Object(json_map) => parse_json_map(json_map),
_ => Err(MapError::ObjectTypeJsonRequired.into()),
}
}
pub fn get_value(&self, selector: &str) -> Value {
let splitted = selector.split('.').collect::<Vec<_>>();
let size = splitted.len();
let result = splitted
.into_iter()
.enumerate()
.map(|(i, key)| (i == size - 1, key))
.try_fold(&self.0, |map, (is_last, key)| {
let value = match map.get(key) {
Some(value) => value,
None => {
return ControlFlow::Break(Value::Null);
}
};
match (is_last, value) {
(true, value) => ControlFlow::Break(value.clone()),
(false, Value::Map(map)) => ControlFlow::Continue(&map.0),
(false, _) => ControlFlow::Break(Value::Null),
}
});
match result {
ControlFlow::Continue(map) => Value::Map(Self(map.clone())),
ControlFlow::Break(value) => value,
}
}
}
fn parse_json_map(json_map: JsonMap<String, JsonValue>) -> Result<Map> {
json_map
.into_iter()
.map(|(key, value)| parse_json_value(value).map(|value| (key, value)))
.collect::<Result<HashMap<String, Value>>>()
.map(Map)
}
fn parse_json_value(json_value: JsonValue) -> Result<Value> {
match json_value {
JsonValue::Null => Ok(Value::Null),
JsonValue::Bool(v) => Ok(Value::Bool(v)),
JsonValue::Number(v) => {
if let Some(value) = v.as_i64().map(Value::I64) {
return Ok(value);
}
v.as_f64()
.map(Value::F64)
.ok_or_else(|| MapError::UnreachableJsonNumberParseFailure(v.to_string()).into())
}
JsonValue::String(v) => Ok(Value::Str(v)),
JsonValue::Array(_) => Err(MapError::ArrayTypeNotSupported.into()),
JsonValue::Object(json_map) => parse_json_map(json_map).map(Value::Map),
}
}
|
use crate::analyzer::dex::dex_class_node::DexClassNode;
#[derive(Clone)]
pub struct DexPackageNode {
pub(crate) name: String,
package_name: Option<String>,
pub(crate) class_nodes: Vec<DexClassNode>,
}
impl DexPackageNode {
pub fn new(name: String, package_name: Option<String>) -> DexPackageNode {
DexPackageNode {
name,
package_name,
class_nodes: vec![],
}
}
pub fn combine(parent_package: String, child_name: String) -> String {
if parent_package == "" {
child_name.clone() + "." + &*child_name
} else {
parent_package + "." + &*child_name
}
}
pub fn add_class(&mut self, class_node: DexClassNode) {
self.class_nodes.push((class_node));
}
pub fn get_or_create_class(
&self,
parent_package: String,
class_name: String,
typ: String,
) -> DexClassNode {
let mut dex_class: DexClassNode = DexClassNode::new(String::from(class_name.clone()));
let option = class_name.find(".");
match option {
None => {}
Some(size) => {}
};
dex_class
}
}
#[cfg(test)]
mod tests {
use crate::analyzer::dex::dex_package_node::DexPackageNode;
#[test]
fn should_create_class() {
let node = DexPackageNode::new(String::from("Hello"), Some(String::from("com.phodal")));
node.get_or_create_class(
String::from("com.phodal"),
String::from("Hello"),
String::from("AA"),
);
}
}
|
use std::env;
use std::fs;
use std::path::Path;
use std::collections::HashMap;
const MATRIX_SIZE:usize = 8;
fn read_instructions(filename:&str) ->String{
let fpath = Path::new(filename);
let abspath = env::current_dir()
.unwrap()
.into_boxed_path()
.join(&fpath);
let contents = fs::read_to_string(&abspath)
.expect("Error reading input file!");
return contents
}
fn fill_matrix(contents:&str) -> Vec<Vec<usize>>{
let mut keys:HashMap<&str,usize> =HashMap::new();
let mut matrix = vec![vec![0usize;MATRIX_SIZE];MATRIX_SIZE];
let replaced = contents
.replace("to", " ")
.replace("=", "");
let mut key:usize = 0;
for line in replaced.lines(){
let (l,r);
let fields = line.split_whitespace().collect::<Vec<&str>>();
if keys.contains_key(fields[0]){
l = *keys.get(fields[0]).unwrap();
}else{
l=key;
keys.entry(fields[0]).or_insert(l);
key +=1;
}
if keys.contains_key(fields[1]){
r = *keys.get(fields[1]).unwrap();
}else{
r = key;
keys.entry(fields[1]).or_insert(r);
key +=1;
}
matrix[l][r] = fields[2].parse().unwrap();
matrix[r][l] =fields[2].parse().unwrap();
}
return matrix
}
fn find_min_distance(matrix:Vec<Vec<usize>>) -> usize{
let mut shortest_path = std::usize::MAX;
for i in 0..MATRIX_SIZE{
let mut closed:HashMap<usize,bool> = HashMap::new();
let (mut min_dis, mut min_node, mut current, mut distance) =
(std::usize::MAX, 0usize, 0usize, 0usize);
let mut min_changed = false;
while !closed.contains_key(¤t) {
closed.insert(current, true);
for j in 0..MATRIX_SIZE{
if min_dis > matrix[current][j] && matrix[current][j] != 0 && !closed.contains_key(&j){
min_dis = matrix[current][j];
min_node = j;
min_changed=true;
}
}
if min_changed {
distance+=min_dis;
current = min_node;
min_node= 0;
min_dis =std::usize::MAX;
min_changed=false;
continue;
}
break;
}
if shortest_path > distance{
shortest_path= distance
}
}
return shortest_path;
}
fn find_max_distance(matrix:Vec<Vec<usize>>) -> usize{
let mut longest_path = std::usize::MIN;
for i in 0..MATRIX_SIZE{
let mut closed:HashMap<usize,bool> = HashMap::new();
let (mut max_dis, mut max_node, mut current, mut distance) =
(std::usize::MIN, 0usize, i, 0usize);
let mut max_changed = false;
while !closed.contains_key(¤t) {
closed.insert(current, true);
for j in 0..MATRIX_SIZE{
if max_dis < matrix[current][j] && matrix[current][j] != 0 && !closed.contains_key(&j){
max_dis = matrix[current][j];
max_node = j;
max_changed=true;
}
}
if max_changed {
distance+=max_dis;
current = max_node;
max_node= 0;
max_dis =std::usize::MIN;
max_changed=false;
continue;
}
break;
}
if longest_path < distance{
longest_path= distance
}
}
return longest_path;
}
pub fn run(){
let content = read_instructions("inputs/day-09.txt");
let matrix_min = fill_matrix(&content);
let matrix_max = matrix_min.clone();
let min_distance = find_min_distance(matrix_min);
let max_distance = find_max_distance(matrix_max);
println!("\n-- AoC 2015: -- Day 9: All in a Single Night --");
println!("\n🚀 Shortest Path: {} \n🚂 Longest Path: {}", min_distance, max_distance);
println!("\n-- DONE --\n");
} |
#[doc = "Reader of register MT_DELAY_CFG3"]
pub type R = crate::R<u32, super::MT_DELAY_CFG3>;
#[doc = "Writer for register MT_DELAY_CFG3"]
pub type W = crate::W<u32, super::MT_DELAY_CFG3>;
#[doc = "Register MT_DELAY_CFG3 `reset()`'s with value 0"]
impl crate::ResetValue for super::MT_DELAY_CFG3 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `XTAL_DISABLE_DELAY`"]
pub type XTAL_DISABLE_DELAY_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `XTAL_DISABLE_DELAY`"]
pub struct XTAL_DISABLE_DELAY_W<'a> {
w: &'a mut W,
}
impl<'a> XTAL_DISABLE_DELAY_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0xff) | ((value as u32) & 0xff);
self.w
}
}
#[doc = "Reader of field `DIG_LDO_DISABLE_DELAY`"]
pub type DIG_LDO_DISABLE_DELAY_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DIG_LDO_DISABLE_DELAY`"]
pub struct DIG_LDO_DISABLE_DELAY_W<'a> {
w: &'a mut W,
}
impl<'a> DIG_LDO_DISABLE_DELAY_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 8)) | (((value as u32) & 0xff) << 8);
self.w
}
}
#[doc = "Reader of field `VDDR_STABLE_DELAY`"]
pub type VDDR_STABLE_DELAY_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `VDDR_STABLE_DELAY`"]
pub struct VDDR_STABLE_DELAY_W<'a> {
w: &'a mut W,
}
impl<'a> VDDR_STABLE_DELAY_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16);
self.w
}
}
impl R {
#[doc = "Bits 0:7 - This register specifies the time from switching of logic to Retention LDO in CYBLERD55 to XTAL Disable. This should include the post processing time The delay is in terms of LF Clock cycles. FW has to program this register based on the selected LF clock frequency. At the minimum XTAL_DISABLE_DELAY should be the sum of DIG_LDO_DISABLE_DELAY and the powerdown time of ACTIVE_LDO"]
#[inline(always)]
pub fn xtal_disable_delay(&self) -> XTAL_DISABLE_DELAY_R {
XTAL_DISABLE_DELAY_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:15 - This field holds the delay from the time of diabling Digital LDO to the time at which ACTIVE regulator is disabled"]
#[inline(always)]
pub fn dig_ldo_disable_delay(&self) -> DIG_LDO_DISABLE_DELAY_R {
DIG_LDO_DISABLE_DELAY_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bits 16:23 - This field holds the delay after HVLDO Startup to VDDR Stable. Refer to memo AKK-410"]
#[inline(always)]
pub fn vddr_stable_delay(&self) -> VDDR_STABLE_DELAY_R {
VDDR_STABLE_DELAY_R::new(((self.bits >> 16) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - This register specifies the time from switching of logic to Retention LDO in CYBLERD55 to XTAL Disable. This should include the post processing time The delay is in terms of LF Clock cycles. FW has to program this register based on the selected LF clock frequency. At the minimum XTAL_DISABLE_DELAY should be the sum of DIG_LDO_DISABLE_DELAY and the powerdown time of ACTIVE_LDO"]
#[inline(always)]
pub fn xtal_disable_delay(&mut self) -> XTAL_DISABLE_DELAY_W {
XTAL_DISABLE_DELAY_W { w: self }
}
#[doc = "Bits 8:15 - This field holds the delay from the time of diabling Digital LDO to the time at which ACTIVE regulator is disabled"]
#[inline(always)]
pub fn dig_ldo_disable_delay(&mut self) -> DIG_LDO_DISABLE_DELAY_W {
DIG_LDO_DISABLE_DELAY_W { w: self }
}
#[doc = "Bits 16:23 - This field holds the delay after HVLDO Startup to VDDR Stable. Refer to memo AKK-410"]
#[inline(always)]
pub fn vddr_stable_delay(&mut self) -> VDDR_STABLE_DELAY_W {
VDDR_STABLE_DELAY_W { w: self }
}
}
|
use nom::{
branch::alt,
bytes::complete::{escaped, is_not, tag, take_till, take_till1, take_until},
character::complete::one_of,
IResult,
};
use crate::StraceEvent;
pub fn read_while_args(mut input: &str) -> IResult<&str, Vec<&str>> {
//TODO this sucks
let mut args = vec![];
input = &input[1..];
loop {
let (rest, arg) = take_till(|c| c == ',' || c == '"' || c == ')')(input)?;
input = rest;
match input.chars().next().unwrap() {
',' => {
args.push(arg);
}
'"' => {
input = &input[1..]; // skip quote
if input.chars().next().unwrap() == '"' {
args.push("");
input = &input[1..];
} else {
let (rest, arg) = escaped(is_not("\""), '\\', one_of(r#""'n"#))(input)?;
args.push(arg);
dbg!(arg);
input = &rest[1..];
}
}
')' => {
args.push(arg);
return Ok((&input[1..], args));
}
_ => unreachable!(),
};
input = &input[2..];
}
}
pub fn parse_into_event(input: &str) -> IResult<&str, StraceEvent> {
let (input, syscall) = take_until("(")(input)?;
let (input, args) = read_while_args(input)?;
let result = input;
let input = "";
Ok((
input,
StraceEvent {
syscall,
args,
result,
},
))
}
|
use crate::database::DbConn;
use yew::prelude::*;
pub struct Person {
id: Option<u32>,
can_write: bool,
go_to_persons_list: Option<Callback<()>>,
db_conn: DbConn,
state: State,
link: ComponentLink<Self>,
}
struct State {
is_inserting: bool,
name_value: String,
}
pub enum Msg {
ChangeName(String),
Save,
Cancel,
}
#[derive(Debug, Clone, Properties)]
pub struct PersonProps {
pub id: Option<u32>,
pub name: String,
pub can_write: bool,
pub go_to_persons_list: Option<Callback<()>>,
pub db_conn: Option<DbConn>,
}
impl Default for PersonProps {
fn default() -> Self {
Self {
id: None,
name: String::default(),
can_write: false,
go_to_persons_list: None,
db_conn: None,
}
}
}
impl Component for Person {
type Message = Msg;
type Properties = PersonProps;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
id: props.id,
can_write: props.can_write,
go_to_persons_list: props.go_to_persons_list,
db_conn: props.db_conn.unwrap(),
link,
state: State {
is_inserting: props.id.is_none(),
name_value: props.name,
},
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::ChangeName(value) => self.state.name_value = value,
Msg::Save => {
if self.state.is_inserting {
self.db_conn.borrow_mut().insert(&self.state.name_value);
} else {
self.db_conn
.borrow_mut()
.update(self.id.unwrap(), &self.state.name_value);
}
if let Some(ref go_to_page) = self.go_to_persons_list {
go_to_page.emit(());
}
}
Msg::Cancel => {
if let Some(ref go_to_page) = self.go_to_persons_list {
go_to_page.emit(());
}
}
}
true
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
self.id = props.id;
self.state.name_value = props.name;
self.can_write = props.can_write;
self.state.is_inserting = props.id.is_none();
self.go_to_persons_list = props.go_to_persons_list;
self.db_conn = props.db_conn.unwrap();
true
}
fn view(&self) -> Html {
html! {
<div>
<div>
<label>{"Id: "}</label>
<input
type="number"
value=match self.id { Some(id) => format!("{}", id), _ => String::default() }
disabled=true
/>
</div>
<div>
<label>{"Name: "}</label>
<input
type="text"
value=&self.state.name_value
disabled=!self.can_write
oninput=self.link.callback(|e: InputData| Msg::ChangeName(e.value))
/>
</div>
<div>
<button
onclick=self.link.callback(|_| Msg::Save)
disabled=!self.can_write
>
{
if self.state.is_inserting {
"Insert"
} else {
"Unpdate"
}
}
</button>
<button
onclick=self.link.callback(|_| Msg::Cancel)
disabled=!self.can_write
>
{"Cancel"}
</button>
</div>
</div>
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.