text stringlengths 8 4.13M |
|---|
//! This module is used to find three way merges
use crate::git_utils;
use std::collections::HashSet;
/// Walks through commits, looking for those with (exactly) two parents. Collects parents and
/// the common base.
pub fn find_merges(
repo: &git2::Repository,
revwalk: git2::Revwalk,
before: Option<i64>,
) -> Vec<ThreeWayMerge> {
revwalk
.map(|oid| {
repo.find_commit(oid.expect("Failed to get Oid"))
.expect("Failed to turn oid into a commit")
})
.filter(|commit| commit.parent_count() == 2)
.filter(|commit| {
if let Some(before) = before {
commit.time().seconds() < before
} else {
true
}
})
// filter_map is map + flatten. Filters out None and unwraps Some
.filter_map(|commit| {
match ThreeWayMerge::new(repo, &commit) {
Ok(twm) => Some(twm),
Err(e) => {
eprintln!(
"Failed to find either parent commits or their common base for {}. Full error: {}",
commit.id(),
e
);
None
}
}
})
.collect()
}
/// Represents the four parts of a merge by storing the Oid of the merge commit, its parent
/// commits, and the original base commit.
pub struct ThreeWayMerge {
/// The original base commit
pub o: git2::Oid,
/// One parent
pub a: git2::Oid,
/// Another parent
pub b: git2::Oid,
/// The merge commit
pub m: git2::Oid,
}
impl ThreeWayMerge {
// Create new ThreeWayMerge based on a valid merge commit.
fn new(repo: &git2::Repository, commit: &git2::Commit) -> Result<ThreeWayMerge, git2::Error> {
// Parent order is deterministic and saved as part of the merge commit. Subsequent runs
// will thus give the same parents for each position.
let parent1 = commit.parent_id(0)?;
let parent2 = commit.parent_id(1)?;
let base = repo.merge_base(parent1, parent2)?;
Ok(ThreeWayMerge {
o: base,
a: parent1,
b: parent2,
m: commit.id(),
})
}
/// Return a comma separated line of the four commits that form a three way merge. Order:
/// O,A,B,M.
pub fn to_csv_line(&self) -> String {
format!(
"{o},{a},{b},{m}",
o = self.o,
a = self.a,
b = self.b,
m = self.m
)
}
pub fn from_oid_str(
o_str: &str,
a_str: &str,
b_str: &str,
m_str: &str,
) -> Result<Self, git2::Error> {
let o = git2::Oid::from_str(o_str)?;
let a = git2::Oid::from_str(a_str)?;
let b = git2::Oid::from_str(b_str)?;
let m = git2::Oid::from_str(m_str)?;
Ok(Self { o, a, b, m })
}
/// Analyse the merge diffs to decide which files have been modified and are thus
/// interesting.
///
/// Currently this only considers O to M, which may miss some changed behaviour
/// disappearing again. TODO
pub fn files_to_consider(&self, repo: &git2::Repository) -> std::collections::HashSet<String> {
let mut diffoptions = git2::DiffOptions::new();
diffoptions.minimal(true).ignore_whitespace(true);
let o = repo.find_commit(self.o).expect("Failed to find O commit");
let otree = o.tree().expect("Failed to find tree for commit O");
let m = repo.find_commit(self.m).expect("Failed to find M commit");
let mtree = m.tree().expect("Failed to find tree for commit M");
let diff = repo
.diff_tree_to_tree(Some(&otree), Some(&mtree), Some(&mut diffoptions))
.expect("Should be able to diff O to M");
let mut paths = std::collections::HashSet::new();
for delta in diff.deltas() {
paths.insert(
delta
.old_file()
.path()
.unwrap()
.to_str()
.unwrap()
.to_owned(),
);
paths.insert(
delta
.new_file()
.path()
.unwrap()
.to_str()
.unwrap()
.to_owned(),
);
}
paths
}
/// For a given list of files, locates them in each part of the ThreeWayMerge. Places them
/// in o, a, b, or m folders which are created as subfolders of the provided folder.
pub fn write_files_to_disk<P: AsRef<std::path::Path>>(
&self,
folder: P,
files: std::collections::HashSet<String>,
repo: &git2::Repository,
) {
let folder = folder.as_ref();
let paths = [
folder.join("o"),
folder.join("a"),
folder.join("b"),
folder.join("m"),
];
for path in &paths {
std::fs::create_dir_all(path).expect("Could not create folder");
}
git_utils::write_files_from_commit_to_disk(folder.join("o"), self.o, repo, &files, "O");
git_utils::write_files_from_commit_to_disk(folder.join("a"), self.a, repo, &files, "A");
git_utils::write_files_from_commit_to_disk(folder.join("b"), self.b, repo, &files, "B");
git_utils::write_files_from_commit_to_disk(folder.join("m"), self.m, repo, &files, "M");
}
/// For O, A, B, and M, writes all the files in each version to disk. In other words, a file
/// does not need to be present in all four parts, let alone needing to have a change.
pub fn write_all_files_to_disk<P: AsRef<std::path::Path>>(
&self,
folder: P,
repo: &git2::Repository,
) {
let folder = folder.as_ref();
let paths = [
folder.join("o"),
folder.join("a"),
folder.join("b"),
folder.join("m"),
];
for path in &paths {
std::fs::create_dir_all(path).expect("Could not create folder");
}
// Create a list of all files for each version
let commit = repo.find_commit(self.o).unwrap();
let o_paths = git_utils::get_all_paths(&commit.tree().unwrap(), "", repo);
let commit = repo.find_commit(self.a).unwrap();
let a_paths = git_utils::get_all_paths(&commit.tree().unwrap(), "", repo);
let commit = repo.find_commit(self.b).unwrap();
let b_paths = git_utils::get_all_paths(&commit.tree().unwrap(), "", repo);
let commit = repo.find_commit(self.m).unwrap();
let m_paths = git_utils::get_all_paths(&commit.tree().unwrap(), "", repo);
git_utils::write_files_from_commit_to_disk(folder.join("o"), self.o, repo, &o_paths, "O");
git_utils::write_files_from_commit_to_disk(folder.join("a"), self.a, repo, &a_paths, "A");
git_utils::write_files_from_commit_to_disk(folder.join("b"), self.b, repo, &b_paths, "B");
git_utils::write_files_from_commit_to_disk(folder.join("m"), self.m, repo, &m_paths, "M");
}
/// Returns epoch seconds for the merge commit of the ThreeWayMerge. Timezone information is
/// discarded.
pub fn time(&self, repo: &git2::Repository) -> i64 {
repo.find_commit(self.m)
.expect("Failed to find merge commit")
.time()
.seconds()
}
/// Check whether O is a different commit than A or B. If it is the same as either, then we're
/// not *really* working with a twm, but more the joining of a PR to an unchanged master
/// branch. In other words, no changes on the other side.
pub fn has_distinct_o(&self) -> bool {
self.o != self.a && self.o != self.b
}
pub fn a_b_change_same_file(&self, repo: &git2::Repository, only_extensions: &[&str]) -> bool {
crate::git_utils::changed_same_file(
repo,
&self.o,
&self.a,
&self.o,
&self.b,
only_extensions,
)
}
/// Returns a list of files that were changed in O→A AND in O→B
pub fn files_changed_in_both_branches(&self, repo: &git2::Repository) -> HashSet<String> {
let o_to_a = git_utils::changed_filenames(repo, &self.o, &self.a);
let o_to_b = git_utils::changed_filenames(repo, &self.o, &self.b);
o_to_a
.intersection(&o_to_b)
.map(|filename| filename.to_owned())
.collect()
}
}
|
mod crypto;
mod event;
mod message;
mod session;
mod stream;
pub use self::crypto::{read_rmux_event, write_encrypt_event, CryptoContext};
pub use self::event::{new_auth_event, Event, FLAG_AUTH};
pub use self::message::{AuthRequest, AuthResponse};
pub use self::session::{
create_stream, dump_session_state, get_channel_session_size, handle_rmux_session,
process_rmux_session, routine_all_sessions, MuxContext,
};
pub const DEFAULT_RECV_BUF_SIZE: usize = 64 * 1024;
|
use super::{
builders::{DeleteBuilder, ParamsBuilder},
TypeAttrs,
};
use darling::util::SpannedValue;
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens, TokenStreamExt as _};
use std::marker::PhantomData;
use syn::LitInt;
pub(super) struct Delete<'a, S> {
attrs: &'a TypeAttrs,
_s: PhantomData<S>,
}
impl<'a, S> Delete<'a, S> {
pub fn new(attrs: &'a TypeAttrs) -> Self {
Self {
attrs,
_s: PhantomData,
}
}
}
impl<'a, S> ToTokens for Delete<'a, S>
where
S: AttrsSelector,
{
fn to_tokens(&self, tokens: &mut TokenStream) {
let table = S::table(self.attrs);
if table.is_empty() {
return;
}
let mut errors = Vec::new();
let mut params = ParamsBuilder::default();
let mut delete = DeleteBuilder::default();
let keys = S::keys(self.attrs, &mut errors);
add_keys(&keys, &mut params, &mut delete);
let sql = delete.to_sql_lit(table);
tokens.append_all(quote! {
storm::tri!(storm_mssql::Execute::execute(provider, #sql, #params).await);
#(#errors)*
});
}
}
#[cold]
fn add_key_many(keys: &[&str], params: &mut ParamsBuilder, builder: &mut DeleteBuilder) {
for (index, column) in keys.iter().enumerate() {
let i = LitInt::new(&index.to_string(), Span::call_site());
add_key_single(column, quote!(&k.#i as _), params, builder);
}
}
fn add_key_single(
column: &str,
ts: TokenStream,
params: &mut ParamsBuilder,
builder: &mut DeleteBuilder,
) {
let i = params.add_ts(ts);
builder.add_key(column, &i.to_string());
}
fn add_keys(keys: &[&str], params: &mut ParamsBuilder, builder: &mut DeleteBuilder) {
match keys {
[k] => add_key_single(k, quote!(k as _), params, builder),
_ => add_key_many(keys, params, builder),
}
}
pub(super) trait AttrsSelector {
fn keys<'a>(attrs: &'a TypeAttrs, errors: &mut Vec<TokenStream>) -> Vec<&'a str>;
fn table(attrs: &TypeAttrs) -> &SpannedValue<String>;
}
macro_rules! selector {
($t:ty, $keys:ident, $table:ident) => {
impl AttrsSelector for $t {
fn keys<'a>(attrs: &'a TypeAttrs, errors: &mut Vec<TokenStream>) -> Vec<&'a str> {
attrs.$keys(errors)
}
fn table(attrs: &TypeAttrs) -> &SpannedValue<String> {
&attrs.$table
}
}
};
}
pub(super) mod selectors {
use super::*;
pub struct Normal;
pub struct Translate;
selector!(Normal, keys, table);
selector!(Translate, translate_keys, translate_table);
}
|
#[doc = "Reader of register DDRPHYC_DTPR0"]
pub type R = crate::R<u32, super::DDRPHYC_DTPR0>;
#[doc = "Writer for register DDRPHYC_DTPR0"]
pub type W = crate::W<u32, super::DDRPHYC_DTPR0>;
#[doc = "Register DDRPHYC_DTPR0 `reset()`'s with value 0x3012_666e"]
impl crate::ResetValue for super::DDRPHYC_DTPR0 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x3012_666e
}
}
#[doc = "Reader of field `TMRD`"]
pub type TMRD_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TMRD`"]
pub struct TMRD_W<'a> {
w: &'a mut W,
}
impl<'a> TMRD_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 & !0x03) | ((value as u32) & 0x03);
self.w
}
}
#[doc = "Reader of field `TRTP`"]
pub type TRTP_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TRTP`"]
pub struct TRTP_W<'a> {
w: &'a mut W,
}
impl<'a> TRTP_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 & !(0x07 << 2)) | (((value as u32) & 0x07) << 2);
self.w
}
}
#[doc = "Reader of field `TWTR`"]
pub type TWTR_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TWTR`"]
pub struct TWTR_W<'a> {
w: &'a mut W,
}
impl<'a> TWTR_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 & !(0x07 << 5)) | (((value as u32) & 0x07) << 5);
self.w
}
}
#[doc = "Reader of field `TRP`"]
pub type TRP_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TRP`"]
pub struct TRP_W<'a> {
w: &'a mut W,
}
impl<'a> TRP_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8);
self.w
}
}
#[doc = "Reader of field `TRCD`"]
pub type TRCD_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TRCD`"]
pub struct TRCD_W<'a> {
w: &'a mut W,
}
impl<'a> TRCD_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 12)) | (((value as u32) & 0x0f) << 12);
self.w
}
}
#[doc = "Reader of field `TRAS`"]
pub type TRAS_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TRAS`"]
pub struct TRAS_W<'a> {
w: &'a mut W,
}
impl<'a> TRAS_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 & !(0x1f << 16)) | (((value as u32) & 0x1f) << 16);
self.w
}
}
#[doc = "Reader of field `TRRD`"]
pub type TRRD_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TRRD`"]
pub struct TRRD_W<'a> {
w: &'a mut W,
}
impl<'a> TRRD_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 21)) | (((value as u32) & 0x0f) << 21);
self.w
}
}
#[doc = "Reader of field `TRC`"]
pub type TRC_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TRC`"]
pub struct TRC_W<'a> {
w: &'a mut W,
}
impl<'a> TRC_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 & !(0x3f << 25)) | (((value as u32) & 0x3f) << 25);
self.w
}
}
#[doc = "Reader of field `TCCD`"]
pub type TCCD_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TCCD`"]
pub struct TCCD_W<'a> {
w: &'a mut W,
}
impl<'a> TCCD_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bits 0:1 - TMRD"]
#[inline(always)]
pub fn tmrd(&self) -> TMRD_R {
TMRD_R::new((self.bits & 0x03) as u8)
}
#[doc = "Bits 2:4 - TRTP"]
#[inline(always)]
pub fn trtp(&self) -> TRTP_R {
TRTP_R::new(((self.bits >> 2) & 0x07) as u8)
}
#[doc = "Bits 5:7 - TWTR"]
#[inline(always)]
pub fn twtr(&self) -> TWTR_R {
TWTR_R::new(((self.bits >> 5) & 0x07) as u8)
}
#[doc = "Bits 8:11 - TRP"]
#[inline(always)]
pub fn trp(&self) -> TRP_R {
TRP_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 12:15 - TRCD"]
#[inline(always)]
pub fn trcd(&self) -> TRCD_R {
TRCD_R::new(((self.bits >> 12) & 0x0f) as u8)
}
#[doc = "Bits 16:20 - TRAS"]
#[inline(always)]
pub fn tras(&self) -> TRAS_R {
TRAS_R::new(((self.bits >> 16) & 0x1f) as u8)
}
#[doc = "Bits 21:24 - TRRD"]
#[inline(always)]
pub fn trrd(&self) -> TRRD_R {
TRRD_R::new(((self.bits >> 21) & 0x0f) as u8)
}
#[doc = "Bits 25:30 - TRC"]
#[inline(always)]
pub fn trc(&self) -> TRC_R {
TRC_R::new(((self.bits >> 25) & 0x3f) as u8)
}
#[doc = "Bit 31 - TCCD"]
#[inline(always)]
pub fn tccd(&self) -> TCCD_R {
TCCD_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:1 - TMRD"]
#[inline(always)]
pub fn tmrd(&mut self) -> TMRD_W {
TMRD_W { w: self }
}
#[doc = "Bits 2:4 - TRTP"]
#[inline(always)]
pub fn trtp(&mut self) -> TRTP_W {
TRTP_W { w: self }
}
#[doc = "Bits 5:7 - TWTR"]
#[inline(always)]
pub fn twtr(&mut self) -> TWTR_W {
TWTR_W { w: self }
}
#[doc = "Bits 8:11 - TRP"]
#[inline(always)]
pub fn trp(&mut self) -> TRP_W {
TRP_W { w: self }
}
#[doc = "Bits 12:15 - TRCD"]
#[inline(always)]
pub fn trcd(&mut self) -> TRCD_W {
TRCD_W { w: self }
}
#[doc = "Bits 16:20 - TRAS"]
#[inline(always)]
pub fn tras(&mut self) -> TRAS_W {
TRAS_W { w: self }
}
#[doc = "Bits 21:24 - TRRD"]
#[inline(always)]
pub fn trrd(&mut self) -> TRRD_W {
TRRD_W { w: self }
}
#[doc = "Bits 25:30 - TRC"]
#[inline(always)]
pub fn trc(&mut self) -> TRC_W {
TRC_W { w: self }
}
#[doc = "Bit 31 - TCCD"]
#[inline(always)]
pub fn tccd(&mut self) -> TCCD_W {
TCCD_W { w: self }
}
}
|
fn main() {
let x = { // 最终 x 是 (), 空的 tup
3;
2; // 分号则不是 表达式, 错误
};
println!("{:?}", x);
}
|
#[cfg(test)]
mod cli {
use assert_cmd::prelude::*;
use predicates::prelude::*;
use std::io::Write;
use std::process::Command;
#[test]
fn should_read_input_file_when_provided() {
let mut cmd = Command::main_binary().unwrap();
let mut tmp_file = tempfile::NamedTempFile::new().unwrap();
tmp_file
.write_all(include_str!("./input/events.json").as_bytes())
.unwrap();
cmd.arg(".").arg("-f").arg(&tmp_file.path());
cmd.assert()
.success()
.stdout(include_str!("./input/events.output.json"));
}
#[test]
fn should_reject_invalid_json_when_reading_a_file() {
let mut cmd = Command::main_binary().unwrap();
let mut tmp_file = tempfile::NamedTempFile::new().unwrap();
tmp_file
.write_all(include_str!("./input/invalid_events.json").as_bytes())
.unwrap();
cmd.arg(".").arg("-f").arg(&tmp_file.path());
cmd.assert()
.success()
.stdout(include_str!("./input/invalid_events.output.json"));
}
#[test]
fn should_panic_when_the_specified_file_is_missing() {
let mut cmd = Command::main_binary().unwrap();
cmd.arg(".").arg("-f").arg("./missing_file.json");
cmd.assert().failure().stderr(
predicate::str::is_match(
r#"The specified input file could not be found: "./missing_file.json""#,
)
.unwrap(),
);
}
}
|
use basespace_dl::util;
use basespace_dl::workspace::Workspace;
use clap::{App, Arg, ArgMatches};
use console::style;
use failure::bail;
use failure::ResultExt;
use futures::future;
use log::{info, warn};
use regex::Regex;
use std::collections::HashSet;
use std::fs::File;
use std::io::{Read, Write};
use std::path::PathBuf;
use tabwriter::TabWriter;
fn build_app() -> App<'static, 'static> {
App::new("basespace-dl")
.version(env!("CARGO_PKG_VERSION"))
.author("dweb0")
.about("Multi-account basespace file downloader")
.args(&[
Arg::with_name("project")
.index(1)
.required(true)
.takes_value(true)
.help("Project name (e.g. project17890). Use ALL to print all projects"),
Arg::with_name("list-files")
.long("list-files")
.short("F")
.takes_value(false)
.help("List all files for a given project. Use -l to also print file metadata."),
Arg::with_name("pattern")
.long("pattern")
.short("p")
.takes_value(true)
.help("Only select files according to this regex pattern"),
Arg::with_name("select-files")
.long("select-files")
.short("f")
.takes_value(true)
.help("Only select files from this list. Accepts a file or - for STDIN."),
Arg::with_name("directory")
.long("directory")
.short("d")
.takes_value(true)
.help("Download files to this directory."),
Arg::with_name("undetermined")
.long("undetermined")
.short("U")
.required(false)
.takes_value(false)
.help("Fetch undetermined files as well. These are stored in the \"Unindexed Reads\" project."),
Arg::with_name("config")
.long("config")
.short("C")
.takes_value(true)
.help("Alternate config. Stored in $HOME/.config/basespace-dl/{name}.toml"),
Arg::with_name("skip-completion-check")
.long("skip-completion-check")
.required(false)
.takes_value(false)
.help("Skip the requirement that all samples in a project be finished processing"),
Arg::with_name("long-format")
.long("long-format")
.short("l")
.takes_value(false)
.help("Long format. Prints file size if listing files or more project info if listing projects"),
Arg::with_name("verbose")
.long("verbose")
.short("v")
.required(false)
.help("Print status messages"),
])
}
#[tokio::main]
async fn main() {
let app = build_app();
let matches = app.get_matches();
if matches.is_present("verbose") {
std::env::set_var("RUST_LOG", "info");
} else {
std::env::set_var("RUST_LOG", "warn");
}
env_logger::init();
if let Err(e) = real_main(matches).await {
eprintln!("{} {}", style("error:").bold().red(), e);
std::process::exit(1);
}
}
async fn real_main(matches: ArgMatches<'static>) -> Result<(), failure::Error> {
let ws = match matches.value_of("config") {
Some(config) => Workspace::with_config(config),
None => Workspace::new(),
}
.with_context(|e| format!("Could not generate workspace. {}", e))?;
let directory = match matches.value_of("directory") {
Some(dir) => {
let path_dir = PathBuf::from(dir);
if !path_dir.is_dir() {
bail!("{} is not a valid directory", dir);
}
path_dir
}
None => PathBuf::from("."),
};
let multi = ws
.to_multiapi()
.with_context(|e| format!("Could not generate multi-api from workspace. {}", e))?;
let query = matches.value_of("project").unwrap();
let projects = multi.get_projects().await?;
if query == "ALL" {
if matches.is_present("long-format") {
// Only print YYYY-MM-DD and not timestamp
// Timestamp should ALWAYS include this
let date_re = Regex::new(r"^\d{4,4}-\d{2,2}-\d{2,2}").unwrap();
for project in projects {
let date = match date_re.find(&project.date_created) {
Some(mat) => mat.as_str(),
None => ""
};
println!(
"{},{},{},{}",
project.name,
project.user_owned_by.id,
project.user_owned_by.name,
date,
);
}
} else {
for project in projects {
println!("{}", project.name);
}
}
std::process::exit(0);
}
let mut matching_projects: Vec<_> = projects.iter().filter(|p| p.name == query).collect();
let project = if matching_projects.is_empty() {
let candidates = util::did_you_mean(query, projects);
if candidates.is_empty() {
bail!("no such project {}.", query);
}
bail!(
"no such project {}. Did you mean one of these?\n\n{}",
query,
candidates.join("\n")
);
} else if matching_projects.len() > 1 {
util::resolve_duplicate_projects(matching_projects)
} else {
matching_projects.remove(0)
};
let samples = if matches.is_present("undetermined") {
if project.user_fetched_by_id != project.user_owned_by.id {
bail!("Must be the owner of a project to access its \"Unindexed Reads\".");
}
let unindexed_reads = projects.iter().find(|x| {
x.name == "Unindexed Reads" && x.user_fetched_by_id == project.user_fetched_by_id
});
let unindexed_reads = match unindexed_reads {
Some(unindexed_reads) => unindexed_reads,
None => bail!("Could not find Unindexed Reads in basespace account."),
};
let undetermined_sample = multi.get_undetermined_sample(project, unindexed_reads);
let samples = multi.get_samples(project);
// Fetch main samples + the undetermined sample concurrently
let (samples, undetermined_sample) = future::join(samples, undetermined_sample).await;
let mut samples = samples?;
let undetermined_sample = undetermined_sample?;
samples.push(undetermined_sample);
samples
} else {
multi.get_samples(project).await?
};
let (samples, unfinished_samples): (Vec<_>, Vec<_>) =
samples.into_iter().partition(|s| s.status == "Complete");
if !unfinished_samples.is_empty() {
if matches.is_present("skip-completion-check") {
warn!(
"Warning: {} samples still processing. Downloading anyway.",
unfinished_samples.len()
);
} else {
bail!(
"Project not finished yet. {} samples still processing.",
unfinished_samples.len()
);
}
}
info!("Found {} completed samples", samples.len());
info!("Fetching files...");
let mut files = multi.get_files(project, &samples).await?;
if let Some(pattern) = matches.value_of("pattern") {
let re = Regex::new(pattern).with_context(|e| format!("Invalid regex pattern. {}", e))?;
files = files
.into_iter()
.filter(|file| re.find(&file.name).is_some())
.collect();
}
if let Some(filelist) = matches.value_of("select-files") {
let mut rdr: Box<dyn Read> = match filelist {
"-" => Box::new(std::io::stdin()),
_ => Box::new(File::open(filelist)?),
};
let mut buffer = String::new();
rdr.read_to_string(&mut buffer)?;
let filter_list: HashSet<String> = buffer.lines().map(|line| line.to_owned()).collect();
files = files
.into_iter()
.filter(|file| filter_list.contains(&file.name))
.collect();
}
if matches.is_present("list-files") {
let stdout = std::io::stdout();
let mut stdout = stdout.lock();
if matches.occurrences_of("list-files") > 1 || matches.is_present("long-format") {
let mut writer = TabWriter::new(&mut stdout);
for file in files {
writeln!(
&mut writer,
"{:>4}\t{}",
util::convert_bytes(file.size as f64),
file.name
)
.unwrap_or_else(|_| {
std::process::exit(0);
});
}
writer.flush()?;
} else {
for file in files {
writeln!(&mut stdout, "{}", file.name).unwrap_or_else(|_| {
std::process::exit(0);
});
}
}
std::process::exit(0);
}
info!("Downloading {} files...", files.len());
multi
.download_files(&files, project, directory)
.with_context(|e| format!("Could not download files. {}", e))?;
Ok(())
}
|
use anyhow::{format_err, Error};
use std::path::Path;
use url::Url;
use crate::{
file_info::{FileInfo, FileInfoTrait, FileStat, Md5Sum, ServiceId, ServiceSession, Sha1Sum},
file_service::FileService,
};
#[derive(Debug, Clone)]
pub struct FileInfoSSH(pub FileInfo);
impl FileInfoSSH {
/// # Errors
/// Return error if init fails
pub fn from_url(url: &Url) -> Result<Self, Error> {
if url.scheme() == "ssh" {
let path = url.path();
let filepath = Path::new(&path);
let filename = filepath
.file_name()
.ok_or_else(|| format_err!("Parse failure"))?
.to_os_string()
.to_string_lossy()
.into_owned()
.into();
let finfo = FileInfo::new(
filename,
filepath.to_path_buf().into(),
url.clone().into(),
None,
None,
FileStat::default(),
ServiceId::default(),
FileService::SSH,
ServiceSession::default(),
);
Ok(Self(finfo))
} else {
Err(format_err!("Wrong scheme"))
}
}
}
impl FileInfoTrait for FileInfoSSH {
fn get_finfo(&self) -> &FileInfo {
&self.0
}
fn into_finfo(self) -> FileInfo {
self.0
}
fn get_md5(&self) -> Option<Md5Sum> {
self.0.md5sum.clone()
}
fn get_sha1(&self) -> Option<Sha1Sum> {
self.0.sha1sum.clone()
}
fn get_stat(&self) -> FileStat {
self.0.filestat
}
}
#[cfg(test)]
mod tests {
use crate::{file_info::FileInfoTrait, file_info_ssh::FileInfoSSH};
use url::Url;
#[test]
fn test_file_info_ssh() {
let url: Url = "ssh://ubuntu@cloud.ddboline.net/home/ubuntu/movie_queue.sql"
.parse()
.unwrap();
let finfo = FileInfoSSH::from_url(&url).unwrap();
assert_eq!(
finfo.get_finfo().urlname.as_str(),
"ssh://ubuntu@cloud.ddboline.net/home/ubuntu/movie_queue.sql"
);
assert_eq!(&finfo.get_finfo().filename, "movie_queue.sql");
}
}
|
use std::io::{Error, ErrorKind, Result, Write};
#[macro_export]
macro_rules! row {
($( $x:expr ),*) => {
{
let mut row = Row::new();
$(row.add_cell($x);)*
row
}
};
}
#[macro_export]
macro_rules! blank {
($x:expr) => {{
CellValue::Blank($x)
}};
() => {{
CellValue::Blank(1)
}};
}
pub struct AutoFilter {
pub start_col: String,
pub end_col: String,
pub start_row: usize,
pub end_row: usize
}
impl ToString for AutoFilter {
fn to_string(&self) -> String {
format!("{}{}:{}{}", self.start_col, self.start_row, self.end_col, self.end_row)
}
}
#[derive(Default)]
pub struct Sheet {
pub id: usize,
pub name: String,
pub columns: Vec<Column>,
max_row_index: usize,
pub calc_chain: Vec<String>,
pub merged_cells: Vec<MergedCell>,
pub auto_filter: Option<AutoFilter>
}
#[derive(Default)]
pub struct Row {
pub cells: Vec<Cell>,
row_index: usize,
max_col_index: usize,
calc_chain: Vec<String>,
}
pub struct Cell {
pub column_index: usize,
pub value: CellValue,
}
pub struct MergedCell {
pub start_ref: String,
pub end_ref: String,
}
pub struct Column {
pub width: f32,
}
#[derive(Clone)]
pub enum CellValue {
Bool(bool),
Number(f64),
NumberFormatted((f64, u16)),
#[cfg(feature = "chrono")]
Date(f64),
#[cfg(feature = "chrono")]
Datetime(f64),
String(String),
Formula(String),
Blank(usize),
SharedString(String),
}
pub struct SheetWriter<'a, 'b>
where
'b: 'a,
{
sheet: &'a mut Sheet,
writer: &'b mut Vec<u8>,
shared_strings: &'b mut crate::SharedStrings,
}
pub trait ToCellValue {
fn to_cell_value(&self) -> CellValue;
}
impl ToCellValue for bool {
fn to_cell_value(&self) -> CellValue {
CellValue::Bool(self.to_owned())
}
}
impl ToCellValue for (f64, u16) {
fn to_cell_value(&self) -> CellValue {
CellValue::NumberFormatted(self.to_owned())
}
}
impl ToCellValue for f64 {
fn to_cell_value(&self) -> CellValue {
CellValue::Number(self.to_owned())
}
}
impl ToCellValue for String {
fn to_cell_value(&self) -> CellValue {
if self.starts_with('=') {
return CellValue::Formula(self.to_owned());
}
CellValue::String(self.to_owned())
}
}
impl<'a> ToCellValue for &'a str {
fn to_cell_value(&self) -> CellValue {
if self.starts_with('=') {
return CellValue::Formula(self.to_string());
}
CellValue::String(self.to_string())
}
}
impl ToCellValue for () {
fn to_cell_value(&self) -> CellValue {
CellValue::Blank(1)
}
}
#[cfg(feature = "chrono")]
impl ToCellValue for chrono::NaiveDateTime {
fn to_cell_value(&self) -> CellValue {
let seconds = self.timestamp();
let nanos = f64::from(self.timestamp_subsec_nanos()) * 1e-9;
let unix_seconds = seconds as f64 + nanos;
let unix_days = unix_seconds / 86400.;
CellValue::Datetime(unix_days + 25569.)
}
}
#[cfg(feature = "chrono")]
impl ToCellValue for chrono::NaiveDate {
fn to_cell_value(&self) -> CellValue {
use chrono::Datelike;
const UNIX_EPOCH_DAY: i32 = 719_163;
let unix_days: f64 = (self.num_days_from_ce() - UNIX_EPOCH_DAY).into();
CellValue::Date(unix_days + 25569.)
}
}
impl Row {
pub fn new() -> Row {
Row {
..Default::default()
}
}
pub fn from_iter<T>(iter: impl Iterator<Item = T>) -> Row
where
T: ToCellValue + Sized,
{
let mut row = Row::new();
for val in iter {
row.add_cell(val)
}
row
}
pub fn add_cell<T>(&mut self, value: T)
where
T: ToCellValue + Sized,
{
let value = value.to_cell_value();
match &value {
CellValue::Formula(f) => {
self.calc_chain.push(f.to_owned());
self.max_col_index += 1;
self.cells.push(Cell {
column_index: self.max_col_index,
value,
})
}
CellValue::Blank(cols) => self.max_col_index += cols,
_ => {
self.max_col_index += 1;
self.cells.push(Cell {
column_index: self.max_col_index,
value,
})
}
}
}
pub fn add_empty_cells(&mut self, cols: usize) {
self.max_col_index += cols
}
pub fn join(&mut self, row: Row) {
for cell in row.cells.into_iter() {
self.inner_add_cell(cell)
}
}
fn inner_add_cell(&mut self, cell: Cell) {
self.max_col_index += 1;
self.cells.push(Cell {
column_index: self.max_col_index,
value: cell.value,
})
}
pub fn write(&mut self, writer: &mut dyn Write) -> Result<()> {
let head = format!("<row r=\"{}\">\n", self.row_index);
writer.write_all(head.as_bytes())?;
for c in self.cells.iter() {
c.write(self.row_index, writer)?;
}
writer.write_all(b"\n</row>\n")
}
pub fn replace_strings(mut self, shared: &mut crate::SharedStrings) -> Self {
if !shared.used() {
return self;
}
for cell in self.cells.iter_mut() {
cell.value = match &cell.value {
CellValue::String(val) => shared.register(&escape_xml(val)),
x => x.to_owned(),
};
}
self
}
}
impl ToCellValue for CellValue {
fn to_cell_value(&self) -> CellValue {
self.clone()
}
}
fn write_value(cv: &CellValue, ref_id: String, writer: &mut dyn Write) -> Result<()> {
match cv {
CellValue::Bool(b) => {
let v = if *b { 1 } else { 0 };
let s = format!("<c r=\"{}\" t=\"b\"><v>{}</v></c>", ref_id, v);
writer.write_all(s.as_bytes())?;
}
&CellValue::Number(num) => write_number(&ref_id, num, None, writer)?,
&CellValue::NumberFormatted(num) => write_number(&ref_id, num.0, Some(num.1), writer)?,
#[cfg(feature = "chrono")]
&CellValue::Date(num) => write_number(&ref_id, num, Some(1), writer)?,
#[cfg(feature = "chrono")]
&CellValue::Datetime(num) => write_number(&ref_id, num, Some(2), writer)?,
CellValue::String(ref s) => {
let s = format!(
"<c r=\"{}\" t=\"str\"><v>{}</v></c>",
ref_id,
escape_xml(&s)
);
writer.write_all(s.as_bytes())?;
}
CellValue::Formula(ref s) => {
let s = format!(
"<c r=\"{}\" t=\"str\"><f>{}</f></c>",
ref_id,
escape_xml(&s)
);
writer.write_all(s.as_bytes())?;
}
CellValue::SharedString(ref s) => {
let s = format!("<c r=\"{}\" t=\"s\"><v>{}</v></c>", ref_id, s);
writer.write_all(s.as_bytes())?;
}
CellValue::Blank(_) => {}
}
Ok(())
}
fn write_number(
ref_id: &str,
value: f64,
style: Option<u16>,
writer: &mut dyn Write,
) -> Result<()> {
match style {
Some(style) => write!(
writer,
r#"<c r="{}" s="{}"><v>{}</v></c>"#,
ref_id, style, value
),
None => write!(writer, r#"<c r="{}"><v>{}</v></c>"#, ref_id, value),
}
}
pub fn escape_xml(str: &str) -> String {
let str = str.replace("&", "&");
let str = str.replace("<", "<");
let str = str.replace(">", ">");
let str = str.replace("'", "'");
str.replace("\"", """)
}
impl Cell {
fn write(&self, row_index: usize, writer: &mut dyn Write) -> Result<()> {
write_value(&self.value, ref_id(self.column_index, row_index), writer)
}
}
impl MergedCell {
fn write(&self, writer: &mut dyn Write) -> Result<()> {
write!(
writer,
"<mergeCell ref=\"{}:{}\" />",
self.start_ref, self.end_ref
)?;
Ok(())
}
}
pub fn ref_id(column_index: usize, row_index: usize) -> String {
format!("{}{}", column_letter(column_index), row_index)
}
/**
* column_index : 1-based
*/
pub fn column_letter(column_index: usize) -> String {
let mut column_index = (column_index - 1) as isize; // turn to 0-based;
let single = |n: u8| {
// n : 0-based
(b'A' + n) as char
};
let mut result = vec![];
while column_index >= 0 {
result.push(single((column_index % 26) as u8));
column_index = column_index / 26 - 1;
}
let result = result.into_iter().rev();
use std::iter::FromIterator;
String::from_iter(result)
}
pub fn validate_name(name: &str) -> String {
escape_xml(name).replace("/", "-")
}
impl Sheet {
pub fn new(id: usize, sheet_name: &str) -> Sheet {
Sheet {
id,
name: validate_name(sheet_name), //sheet_name.to_owned(),//escape_xml(sheet_name),
..Default::default()
}
}
/// Adds the "AutoFilter" feature to the specified range of columns and rows (1-indexed).
/// The arguments are used to construct the range of columns and rows used by the "AutoFilter"
/// feature. For example: Column 1, Row 1 to Column 2, Row 2 will create the range "A1:B2".
/// If invalid parameters are provided, the "AutoFilter" is not created.
pub fn add_auto_filter(&mut self, start_col: usize, end_col: usize, start_row: usize, end_row: usize) {
if start_col > 0 && start_row > 0 && start_col <= end_col && start_row <= end_row {
self.auto_filter = Some(AutoFilter{ start_col: column_letter(start_col),
end_col: column_letter(end_col),
start_row, end_row });
}
}
pub fn add_column(&mut self, column: Column) {
self.columns.push(column)
}
fn write_row<W>(&mut self, writer: &mut W, mut row: Row) -> Result<()>
where
W: Write + Sized,
{
self.max_row_index += 1;
row.row_index = self.max_row_index;
self.calc_chain.append(&mut row.calc_chain);
row.write(writer)
}
fn write_blank_rows(&mut self, rows: usize) {
self.max_row_index += rows;
}
fn write_head(&self, writer: &mut dyn Write) -> Result<()> {
let header = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
"#;
writer.write_all(header.as_bytes())?;
/*
let dimension = format!("<dimension ref=\"A1:{}{}\"/>", column_letter(self.dimension.columns), self.dimension.rows);
writer.write_all(dimension.as_bytes())?;
*/
if self.columns.is_empty() {
return Ok(());
}
writer.write_all(b"\n<cols>\n")?;
let mut i = 1;
for col in self.columns.iter() {
writer.write_all(
format!(
"<col min=\"{}\" max=\"{}\" width=\"{}\" customWidth=\"1\"/>\n",
&i, &i, col.width
)
.as_bytes(),
)?;
i += 1;
}
writer.write_all(b"</cols>\n")
}
fn write_merged_cells(&self, writer: &mut dyn Write) -> Result<()> {
if !self.merged_cells.is_empty() {
write!(writer, "<mergeCells count=\"{}\">", self.merged_cells.len())?;
for merged_cell in self.merged_cells.iter() {
merged_cell.write(writer)?;
}
write!(writer, "</mergeCells>")?;
}
writer.flush()?;
Ok(())
}
fn write_data_begin(&self, writer: &mut dyn Write) -> Result<()> {
writer.write_all(b"\n<sheetData>\n")
}
fn write_data_end(&self, writer: &mut dyn Write) -> Result<()> {
if let Some(auto_filter) = &self.auto_filter {
writer.write_all(format!("\n</sheetData>\n<autoFilter ref=\"{}\"/>\n", auto_filter.to_string()).as_bytes())
} else {
writer.write_all(b"\n</sheetData>\n")
}
}
fn close(&self, writer: &mut dyn Write) -> Result<()> {
writer.write_all(b"</worksheet>\n")
}
}
impl<'a, 'b> SheetWriter<'a, 'b> {
pub fn new(
sheet: &'a mut Sheet,
writer: &'b mut Vec<u8>,
shared_strings: &'b mut crate::SharedStrings,
) -> SheetWriter<'a, 'b> {
SheetWriter {
sheet,
writer,
shared_strings,
}
}
pub fn append_row(&mut self, row: Row) -> Result<()> {
self.sheet
.write_row(self.writer, row.replace_strings(&mut self.shared_strings))
}
pub fn append_blank_rows(&mut self, rows: usize) {
self.sheet.write_blank_rows(rows)
}
/// Merges the range between `start` and `end` cells, specified as 1-based `(column, row)` pairs.
/// For example, `(1, 2)` is equivalent to cell `A2`.
pub fn merge_cells(&mut self, start: (usize, usize), end: (usize, usize)) -> Result<()> {
if end.0 >= start.0 && end.1 >= start.1 {
self.sheet.merged_cells.push(MergedCell {
start_ref: ref_id(start.0, start.1),
end_ref: ref_id(end.0, end.1),
});
Ok(())
} else {
Err(Error::new(ErrorKind::Other, "invalid range"))
}
}
/// Merges the range between `start_ref` and `end_ref` cells, specified as cell ref IDs (e.g.
/// `B3`).
pub fn merge_range(&mut self, start_ref: String, end_ref: String) -> Result<()> {
self.sheet
.merged_cells
.push(MergedCell { start_ref, end_ref });
Ok(())
}
/// Merges cells in a `width` by `height` range beginning at `start`.
/// Arguments `width` and `height` specify the final size of the merged range, so specifying
/// `1` for each would result in a single cell with no change, and specifying `0` for either is
/// invalid.
pub fn merge_area(&mut self, start: (usize, usize), width: usize, height: usize) -> Result<()> {
self.merge_cells(start, (start.0 + width - 1, start.1 + height - 1))
}
pub fn write<F>(&mut self, write_data: F) -> Result<()>
where
F: FnOnce(&mut SheetWriter) -> Result<()> + Sized,
{
self.sheet.write_head(self.writer)?;
self.sheet.write_data_begin(self.writer)?;
write_data(self)?;
self.sheet.write_data_end(self.writer)?;
self.sheet.write_merged_cells(self.writer)?;
self.sheet.close(self.writer)
}
}
#[cfg(test)]
#[cfg(feature = "chrono")]
mod chrono_tests {
use chrono::NaiveDate;
use super::*;
#[test]
fn chrono_datetime() {
const EXPECTED: f64 = 41223.63725694444;
let cell = NaiveDate::from_ymd(2012, 11, 10)
.and_hms(15, 17, 39)
.to_cell_value();
match cell {
CellValue::Datetime(n) if n == EXPECTED => {}
CellValue::Datetime(n) => panic!(
"invalid chrono::NaiveDateTime conversion to CellValue. {} is expected, found {}",
EXPECTED, n
),
_ => panic!("invalid chrono::NaiveDateTime conversion to CellValue"),
}
}
#[test]
fn chrono_date() {
const EXPECTED: f64 = 41223.;
let cell = NaiveDate::from_ymd(2012, 11, 10).to_cell_value();
match cell {
CellValue::Date(n) if n == EXPECTED => {}
CellValue::Date(n) => panic!(
"invalid chrono::NaiveDate conversion to CellValue. {} is expected, found {}",
EXPECTED, n
),
_ => panic!("invalid chrono::NaiveDate conversion to CellValue"),
}
}
}
|
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
mod actor_code;
pub use self::actor_code::*;
use address::Address;
use cid::Cid;
use clock::ChainEpoch;
use commcid::{cid_to_data_commitment_v1, cid_to_replica_commitment_v1, data_commitment_v1_to_cid};
use crypto::{DomainSeparationTag, Signature};
use filecoin_proofs_api::seal::{compute_comm_d, verify_seal as proofs_verify_seal};
use filecoin_proofs_api::{ProverId, SectorId};
use forest_encoding::{blake2b_256, Cbor};
use ipld_blockstore::BlockStore;
use message::UnsignedMessage;
use std::convert::TryFrom;
use std::error::Error as StdError;
use vm::{
zero_piece_commitment, ActorError, ExitCode, MethodNum, PaddedPieceSize, PieceInfo, Randomness,
RegisteredProof, SealVerifyInfo, Serialized, TokenAmount, WindowPoStVerifyInfo,
};
/// Runtime is the VM's internal runtime object.
/// this is everything that is accessible to actors, beyond parameters.
pub trait Runtime<BS: BlockStore> {
/// Information related to the current message being executed.
fn message(&self) -> &UnsignedMessage;
/// The current chain epoch number. The genesis block has epoch zero.
fn curr_epoch(&self) -> ChainEpoch;
/// Validates the caller against some predicate.
/// Exported actor methods must invoke at least one caller validation before returning.
fn validate_immediate_caller_accept_any(&self);
fn validate_immediate_caller_is<'a, I>(&self, addresses: I) -> Result<(), ActorError>
where
I: IntoIterator<Item = &'a Address>;
fn validate_immediate_caller_type<'a, I>(&self, types: I) -> Result<(), ActorError>
where
I: IntoIterator<Item = &'a Cid>;
/// The balance of the receiver.
fn current_balance(&self) -> Result<TokenAmount, ActorError>;
/// Resolves an address of any protocol to an ID address (via the Init actor's table).
/// This allows resolution of externally-provided SECP, BLS, or actor addresses to the canonical form.
/// If the argument is an ID address it is returned directly.
fn resolve_address(&self, address: &Address) -> Result<Address, ActorError>;
/// Look up the code ID at an actor address.
fn get_actor_code_cid(&self, addr: &Address) -> Result<Cid, ActorError>;
/// Randomness returns a (pseudo)random byte array drawing from a
/// random beacon at a given epoch and incorporating reequisite entropy
fn get_randomness(
personalization: DomainSeparationTag,
rand_epoch: ChainEpoch,
entropy: &[u8],
) -> Randomness;
/// Initializes the state object.
/// This is only valid in a constructor function and when the state has not yet been initialized.
fn create<C: Cbor>(&mut self, obj: &C) -> Result<(), ActorError>;
/// Loads a readonly copy of the state of the receiver into the argument.
///
/// Any modification to the state is illegal and will result in an abort.
fn state<C: Cbor>(&self) -> Result<C, ActorError>;
/// Loads a mutable version of the state into the `obj` argument and protects
/// the execution from side effects (including message send).
///
/// The second argument is a function which allows the caller to mutate the state.
/// The return value from that function will be returned from the call to Transaction().
///
/// If the state is modified after this function returns, execution will abort.
///
/// The gas cost of this method is that of a Store.Put of the mutated state object.
fn transaction<C: Cbor, R, F>(&mut self, f: F) -> Result<R, ActorError>
where
F: FnOnce(&mut C, &Self) -> R;
/// Returns reference to blockstore
fn store(&self) -> &BS;
/// Sends a message to another actor, returning the exit code and return value envelope.
/// If the invoked method does not return successfully, its state changes (and that of any messages it sent in turn)
/// will be rolled back.
fn send(
&mut self,
to: &Address,
method: MethodNum,
params: &Serialized,
value: &TokenAmount,
) -> Result<Serialized, ActorError>;
/// Halts execution upon an error from which the receiver cannot recover. The caller will receive the exitcode and
/// an empty return value. State changes made within this call will be rolled back.
/// This method does not return.
/// The message and args are for diagnostic purposes and do not persist on chain.
fn abort<S: AsRef<str>>(&self, exit_code: ExitCode, msg: S) -> ActorError;
/// Computes an address for a new actor. The returned address is intended to uniquely refer to
/// the actor even in the event of a chain re-org (whereas an ID-address might refer to a
/// different actor after messages are re-ordered).
/// Always an ActorExec address.
fn new_actor_address(&mut self) -> Result<Address, ActorError>;
/// Creates an actor with code `codeID` and address `address`, with empty state. May only be called by Init actor.
fn create_actor(&mut self, code_id: &Cid, address: &Address) -> Result<(), ActorError>;
/// Deletes the executing actor from the state tree. May only be called by the actor itself.
fn delete_actor(&mut self) -> Result<(), ActorError>;
/// Provides the system call interface.
fn syscalls(&self) -> &dyn Syscalls;
}
/// Message information available to the actor about executing message.
pub trait MessageInfo {
// The address of the immediate calling actor. Always an ID-address.
fn caller(&self) -> Address;
// The address of the actor receiving the message. Always an ID-address.
fn receiver(&self) -> Address;
// The value attached to the message being processed, implicitly added to current_balance() before method invocation.
fn value_received(&self) -> TokenAmount;
}
/// Pure functions implemented as primitives by the runtime.
pub trait Syscalls {
/// Verifies that a signature is valid for an address and plaintext.
fn verify_signature(
&self,
signature: &Signature,
signer: &Address,
plaintext: &[u8],
) -> Result<(), Box<dyn StdError>> {
Ok(signature.verify(plaintext, signer)?)
}
/// Hashes input data using blake2b with 256 bit output.
fn hash_blake2b(&self, data: &[u8]) -> Result<[u8; 32], Box<dyn StdError>> {
Ok(blake2b_256(data))
}
/// Computes an unsealed sector CID (CommD) from its constituent piece CIDs (CommPs) and sizes.
fn compute_unsealed_sector_cid(
&self,
proof_type: RegisteredProof,
pieces: &[PieceInfo],
) -> Result<Cid, Box<dyn StdError>> {
let sum: u64 = pieces.iter().map(|p| p.size.0).sum();
let ssize = proof_type.sector_size() as u64;
let mut fcp_pieces: Vec<filecoin_proofs_api::PieceInfo> = pieces
.iter()
.map(filecoin_proofs_api::PieceInfo::try_from)
.collect::<Result<_, &'static str>>()
.map_err(|e| ActorError::new(ExitCode::ErrPlaceholder, e.to_string()))?;
// pad remaining space with 0 piece commitments
{
let mut to_fill = ssize - sum;
let n = to_fill.count_ones();
for _ in 0..n {
let next = to_fill.trailing_zeros();
let p_size = 1 << next;
to_fill ^= p_size;
let padded = PaddedPieceSize(p_size);
fcp_pieces.push(filecoin_proofs_api::PieceInfo {
commitment: zero_piece_commitment(padded),
size: padded.unpadded().into(),
});
}
}
let comm_d = compute_comm_d(proof_type.into(), &fcp_pieces)
.map_err(|e| ActorError::new(ExitCode::ErrPlaceholder, e.to_string()))?;
Ok(data_commitment_v1_to_cid(&comm_d))
}
/// Verifies a sector seal proof.
fn verify_seal(&self, vi: &SealVerifyInfo) -> Result<(), Box<dyn StdError>> {
let commd = cid_to_data_commitment_v1(&vi.unsealed_cid)?;
let commr = cid_to_replica_commitment_v1(&vi.on_chain.sealed_cid)?;
let miner_addr = Address::new_id(vi.sector_id.miner);
let miner_payload = miner_addr.payload_bytes();
let mut prover_id = ProverId::default();
prover_id[..miner_payload.len()].copy_from_slice(&miner_payload);
if !proofs_verify_seal(
vi.on_chain.registered_proof.into(),
commr,
commd,
prover_id,
SectorId::from(vi.sector_id.number),
vi.randomness,
vi.interactive_randomness,
&vi.on_chain.proof,
)? {
return Err(format!(
"Invalid proof detected: {:?}",
base64::encode(&vi.on_chain.proof)
)
.into());
}
Ok(())
}
/// Verifies a proof of spacetime.
fn verify_post(&self, _vi: &WindowPoStVerifyInfo) -> Result<(), Box<dyn StdError>> {
// TODO
todo!()
}
/// Verifies that two block headers provide proof of a consensus fault:
/// - both headers mined by the same actor
/// - headers are different
/// - first header is of the same or lower epoch as the second
/// - at least one of the headers appears in the current chain at or after epoch `earliest`
/// - the headers provide evidence of a fault (see the spec for the different fault types).
/// The parameters are all serialized block headers. The third "extra" parameter is consulted only for
/// the "parent grinding fault", in which case it must be the sibling of h1 (same parent tipset) and one of the
/// blocks in the parent of h2 (i.e. h2's grandparent).
/// Returns nil and an error if the headers don't prove a fault.
fn verify_consensus_fault(
&self,
h1: &[u8],
h2: &[u8],
extra: &[u8],
_earliest: ChainEpoch,
) -> Result<Option<ConsensusFault>, Box<dyn StdError>>;
}
/// Result of checking two headers for a consensus fault.
pub struct ConsensusFault {
/// Address of the miner at fault (always an ID address).
pub target: Address,
/// Epoch of the fault, which is the higher epoch of the two blocks causing it.
pub epoch: ChainEpoch,
/// Type of fault.
pub fault_type: ConsensusFaultType,
}
/// Consensus fault types in VM.
#[derive(Clone, Copy)]
pub enum ConsensusFaultType {
DoubleForkMining = 1,
ParentGrinding = 2,
TimeOffsetMining = 3,
}
|
pub use mutable::FnStackMut;
pub use once::FnStackOnce;
pub use raw::FnBox;
pub use reference::FnStackRef;
use std::mem::{align_of, size_of, uninitialized};
mod mutable;
mod once;
mod raw;
mod reference;
mod private {
pub struct Private;
}
pub trait Array: Sized {
fn align() -> usize {
align_of::<Self>()
}
fn size() -> usize {
size_of::<Self>()
}
unsafe fn uninitialized() -> Self {
uninitialized()
}
fn as_ptr(&self) -> *const u8;
fn as_mut_ptr(&mut self) -> *mut u8;
/// Only `fnstack` may implement this trait.
fn _private() -> private::Private;
}
macro_rules! impl_array {
($($n:expr)*) => {
$(
impl Array for [u8; $n] {
fn as_ptr(&self) -> *const u8 {
<[u8]>::as_ptr(self)
}
fn as_mut_ptr(&mut self) -> *mut u8 {
<[u8]>::as_mut_ptr(self)
}
fn _private() -> private::Private {
private::Private
}
}
)*
};
}
impl_array!(
64 32 24 16 12 8 4 0
);
pub trait StaticFn<A, O> {
fn call(args: A) -> O;
}
|
// MIT License
//
// Copyright (c) 2021 Miguel Peláez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use wasmi::{
Error, FuncRef, GlobalDescriptor, GlobalRef, MemoryDescriptor, MemoryRef, ModuleImportResolver,
Signature, TableDescriptor, TableRef,
};
use crate::prelude::*;
pub struct WasiImportResolver;
impl WasiImportResolver {
pub fn new() -> Self {
Self {}
}
}
impl ModuleImportResolver for WasiImportResolver {
/// Resolve a function.
fn resolve_func(&self, field_name: &str, _signature: &Signature) -> Result<FuncRef, Error> {
Err(Error::Instantiation(format!("Export {} not found", field_name)))
}
/// Resolve a global variable.
fn resolve_global(&self, field_name: &str, _global_type: &GlobalDescriptor) -> Result<GlobalRef, Error> {
Err(Error::Instantiation(format!("Export {} not found", field_name)))
}
/// Resolve a memory.
fn resolve_memory(&self, field_name: &str, _memory_type: &MemoryDescriptor) -> Result<MemoryRef, Error> {
Err(Error::Instantiation(format!("Export {} not found", field_name)))
}
/// Resolve a table.
fn resolve_table(&self, field_name: &str, _table_type: &TableDescriptor) -> Result<TableRef, Error> {
Err(Error::Instantiation(format!("Export {} not found", field_name)))
}
}
|
use crate::common::*;
pub(crate) trait Error: Display {
fn code(&self) -> i32 {
EXIT_FAILURE
}
}
|
mod counter;
use counter::*;
use ini::Ini;
use std::process::abort;
fn main() {
let mut key = String::new();
let file = Ini::load_from_file("input.ini").unwrap();
let mut input_name = String::new();
let mut mode = String::new();
for (sec, prop) in file.iter() {
for (k, v) in prop.iter() {
match (sec, k) {
(Some("Cypher"), "Key") => key = String::from(v),
(Some("Cypher"), "KeyLength") => {
if v != "128" {
println!("Key length must be 128!");
abort();
}
}
(Some("Stream"), "File") => input_name = String::from(v),
(Some("Stream"), "Mode") => {
mode = String::from(v);
if mode.as_str() != "crypt" && mode.as_str() != "decrypt" {
println!("Mode must be \"crypt\" or \"decrypt\"!");
abort();
}
}
_ => {}
};
}
}
let key = u128::from_str_radix(&key, 16).unwrap();
match mode.as_str() {
"crypt" => {
println!("Crypting of {}", input_name);
crypt(&input_name, key);
println!("Done!");
},
"decrypt" => {
println!("Decrypting of {}", input_name);
decrypt(&input_name, key);
println!("Done!");
},
_ => {}
}
}
|
#[macro_use]
extern crate cycle_match;
#[test]
fn loop_match() {
let data = b"123456789";
let mut num = 0usize;
let mut iter = data.iter();
loop_match!((iter.next()) -> || {
Some(b'0') => {},
Some(a @ b'1' ..= b'9') => {
num *= 10;
num += (a - b'0') as usize;
},
Some(a) => panic!("Unk byte: {:?}", a),
_ => break
});
assert_eq!(num, 123456789);
}
#[test]
fn loop_match_2() {
let data = "1234567890";
let mut iter = data.as_bytes().into_iter();
let data_n_index = loop_match!((iter.next(), 0usize) -> |data_n_index| {
Some(a) => data_n_index += *a as usize,
_ => break data_n_index,
});
assert_eq!(data_n_index, 525);
} |
use std::fs;
use day_10::process_part1;
fn main() {
let input = fs::read_to_string("input.txt").unwrap();
println!("{}", process_part1(&input));
} |
pub mod datasource;
pub mod stream;
pub mod types;
|
use std::{fs, collections::BTreeSet};
fn main() {
let input = fs::read_to_string("./input.txt").unwrap_or_default();
let mut unique_houses: BTreeSet<(i32, i32)> = BTreeSet::new();
let mut x = 0;
let mut y = 0;
for direction in input.chars() {
match direction {
'^' => y -= 1,
'v' => y += 1,
'<' => x -= 1,
'>' => x += 1,
_ => (),
}
unique_houses.insert((x, y));
}
dbg!(unique_houses.len() + 1);
}
|
fn hofq(q: &mut Vec<u32>, x : u32) -> u32 {
let cur_len=q.len()-1;
let i=x as usize;
if i>cur_len {
// extend storage
q.reserve(i+1);
for j in (cur_len+1)..(i+1) {
let qj=(q[j-q[j-1] as usize]+q[j-q[j-2] as usize]) as u32;
q.push(qj);
}
}
q[i]
}
fn main() {
let mut q_memo: Vec<u32>=vec![0,1,1];
let mut q=|i| {hofq(&mut q_memo, i)};
for i in 1..11 {
println!("Q({})={}", i, q(i));
}
println!("Q(1000)={}", q(1000));
let q100001=q(100_000); // precompute all
println!("Q(100000)={}", q100001);
let nless=(1..100_000).fold(0,|s,i|{if q(i+1)<q(i) {s+1} else {s}});
println!("Term is less than preceding term {} times", nless);
}
|
#[macro_use]
extern crate simple_error;
pub mod expr;
pub mod lexer;
pub mod parser;
pub mod truth_table;
pub fn eval_str(input: String) -> String {
let parsed = match parser::parse_str(&input) {
Ok(parsed) => parsed,
Err(err) => {
return format!("invalid: {}\n", err);
}
};
let evaluated = parsed.eval();
format!("{}", evaluated)
}
|
use std::fs::File;
use std::io::Read;
#[derive(Debug)]
pub struct Parser {
lines: Vec<String>,
idx: usize,
}
#[derive(Debug, Eq, PartialEq)]
pub enum CommandType {
CArithmetic(String),
CPush(String, usize),
CPop(String, usize),
CLabel,
CGoto,
CIf,
CFunction(String, usize),
CReturn,
CCall(String, usize),
NotCommand,
}
impl CommandType {
fn new(words: Vec<&str>) -> Self {
if let Some(&word) = words.get(0) {
match word {
"push" => {
CommandType::CPush(words[1].to_string(), words[2].parse::<usize>().unwrap())
},
"pop" => {
CommandType::CPop(words[1].to_string(), words[2].parse::<usize>().unwrap())
}
"add" => CommandType::CArithmetic(words[0].to_string()),
"eq" => CommandType::CArithmetic(words[0].to_string()),
"lt" => CommandType::CArithmetic(words[0].to_string()),
"gt" => CommandType::CArithmetic(words[0].to_string()),
"sub" => CommandType::CArithmetic(words[0].to_string()),
"neg" => CommandType::CArithmetic(words[0].to_string()),
"and" => CommandType::CArithmetic(words[0].to_string()),
"or" => CommandType::CArithmetic(words[0].to_string()),
"not" => CommandType::CArithmetic(words[0].to_string()),
_ => CommandType::NotCommand,
}
} else {
CommandType::NotCommand
}
}
}
impl Parser {
pub fn new(path: &str) -> Self {
let mut file = File::open(path).expect("File not found!");
let mut strings = String::new();
file.read_to_string(&mut strings)
.expect("Something went wrong reading the file!");
let test = strings
.split('\n')
.map(|str| str.to_string())
.collect::<Vec<String>>();
Parser {
lines: test,
idx: 0,
}
}
pub fn has_more_commands(&self) -> bool {
self.lines.get(self.idx).is_some()
}
pub fn advance(&mut self) {
self.idx += 1;
}
pub fn command_type(&self) -> CommandType {
let line = self.lines.get(self.idx).unwrap();
let line = line.split("//").collect::<Vec<&str>>();
let words = line[0].split_whitespace().collect::<Vec<&str>>();
CommandType::new(words)
}
}
|
#[doc = "Register `ATOR` reader"]
pub type R = crate::R<ATOR_SPEC>;
#[doc = "Field `PRNG` reader - Pseudo-random generator value This field provides the values of the PRNG output. Because of potential inconsistencies due to synchronization delays, PRNG must be read at least twice. The read value is correct if it is equal to previous read value. This field can only be read when the APB is in secure mode."]
pub type PRNG_R = crate::FieldReader;
#[doc = "Field `SEEDF` reader - Seed running flag This flag is set by hardware when a new seed is written in the TAMP_ATSEEDR. It is cleared by hardware when the PRNG has absorbed this new seed, and by system reset. The TAMP APB cock must not be switched off as long as SEEDF is set."]
pub type SEEDF_R = crate::BitReader;
#[doc = "Field `INITS` reader - Active tamper initialization status This flag is set by hardware when the PRNG has absorbed the first 128-bit seed, meaning that the enabled active tampers are functional. This flag is cleared when the active tampers are disabled."]
pub type INITS_R = crate::BitReader;
impl R {
#[doc = "Bits 0:7 - Pseudo-random generator value This field provides the values of the PRNG output. Because of potential inconsistencies due to synchronization delays, PRNG must be read at least twice. The read value is correct if it is equal to previous read value. This field can only be read when the APB is in secure mode."]
#[inline(always)]
pub fn prng(&self) -> PRNG_R {
PRNG_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bit 14 - Seed running flag This flag is set by hardware when a new seed is written in the TAMP_ATSEEDR. It is cleared by hardware when the PRNG has absorbed this new seed, and by system reset. The TAMP APB cock must not be switched off as long as SEEDF is set."]
#[inline(always)]
pub fn seedf(&self) -> SEEDF_R {
SEEDF_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - Active tamper initialization status This flag is set by hardware when the PRNG has absorbed the first 128-bit seed, meaning that the enabled active tampers are functional. This flag is cleared when the active tampers are disabled."]
#[inline(always)]
pub fn inits(&self) -> INITS_R {
INITS_R::new(((self.bits >> 15) & 1) != 0)
}
}
#[doc = "TAMP active tamper output register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ator::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ATOR_SPEC;
impl crate::RegisterSpec for ATOR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ator::R`](R) reader structure"]
impl crate::Readable for ATOR_SPEC {}
#[doc = "`reset()` method sets ATOR to value 0"]
impl crate::Resettable for ATOR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[macro_use]
extern crate glium;
extern crate clock_ticks;
use glium::Surface;
use glium::glutin;
fn main() {
use glium::DisplayBuild;
let display = glutin::WindowBuilder::new()
.build_glium()
.unwrap();
let frames = 60 * 5;
let trials = 3;
for _ in 0.. trials {
let start_ns = clock_ticks::precise_time_ns();
let mut last = start_ns;
for f in 0..frames {
let before = last;
display.draw().finish().unwrap();
let after = clock_ticks::precise_time_ns();
println!("Frame #{:3}: {:8} {:10}", f, after - before, (after % 16_666_667));
last = after;
}
let duration_ns = clock_ticks::precise_time_ns() - start_ns;
let duration_s = (duration_ns as f64) / 1_000_000_000f64;
let fps = (frames as f64) / duration_s;
let dropped = (duration_s - (frames as f64 * (1f64/60f64))) / (1f64/60f64);
println!("{} frames in {:.6} seconds = {:.3} fps (estimated {:.1} frames dropped)", frames, duration_s, fps, dropped);
}
}
|
use super::error::*;
use ffi::cudart::*;
use std::mem::size_of;
use std::ops::{Deref, DerefMut, Index, IndexMut};
use std::os::raw::*;
use std::ptr::null_mut;
use std::slice::{from_raw_parts, from_raw_parts_mut};
#[derive(Debug)]
pub struct DVec<T> {
ptr: *mut T,
n: usize,
}
impl<T> DVec<T> {
pub unsafe fn uninitialized(n: usize) -> Result<Self> {
let mut ptr: *mut c_void = null_mut();
cudaMalloc(&mut ptr as *mut *mut c_void, n * size_of::<T>()).check()?;
Ok(DVec { ptr: ptr as *mut T, n })
}
pub fn fill_zero(&mut self) -> Result<()> {
unsafe { cudaMemset(self.ptr as *mut c_void, 0, self.n * size_of::<T>()).check() }
}
pub fn new(n: usize) -> Result<Self> {
let mut v = unsafe { Self::uninitialized(n) }?;
v.fill_zero()?;
Ok(v)
}
pub fn memcpy(&mut self, src: &[T]) {
assert!(src.len() <= self.n);
unsafe {
cudaMemcpy(self.ptr as *mut c_void, src as *const _ as *const c_void, src.len(),
cudaMemcpyKind_cudaMemcpyHostToDevice);
}
}
}
impl<T> Drop for DVec<T> {
fn drop(&mut self) {
unsafe { cudaFree(self.ptr as *mut c_void) }
.check()
.expect("Free failed");
}
}
#[cfg(test)]
mod tests {
// TODO
}
|
use std::sync::Arc;
use crate::{
util::{constants::GENERAL_ISSUE, MessageExt},
BotResult, CommandData, Context, MessageBuilder,
};
use super::BgGameState;
#[command]
#[short_desc("Increase the size of the image")]
#[aliases("b", "enhance")]
#[bucket("bg_bigger")]
pub(super) async fn bigger(ctx: Arc<Context>, data: CommandData) -> BotResult<()> {
match ctx.bg_games().get(&data.channel_id()) {
Some(state) => match state.value() {
BgGameState::Running { game } => match game.sub_image().await {
Ok(bytes) => {
let builder = MessageBuilder::new().file("bg_img.png", bytes);
data.create_message(&ctx, builder).await?;
Ok(())
}
Err(err) => {
let _ = data.error(&ctx, GENERAL_ISSUE).await;
Err(err.into())
}
},
BgGameState::Setup { author, .. } => {
let content = format!(
"The game is currently being setup.\n\
<@{author}> must click on the \"Start\" button to begin."
);
data.error(&ctx, content).await
}
},
None => {
let content = "No running game in this channel. Start one with `/bg`.";
data.error(&ctx, content).await
}
}
}
|
use crate::parser_module::*;
/**
* Translates VM commands into Hack assembly code.
*/
pub struct CodeWriter {
index: usize,
commands: Vec<String>,
}
impl CodeWriter {
pub fn new() -> CodeWriter {
CodeWriter {
index: 0,
commands: Vec::new(),
}
}
pub fn commands(&self) -> &Vec<String> {
&self.commands
}
pub fn commands_mut(&mut self) -> &mut Vec<String> {
&mut self.commands
}
// Informs the code writer that the translation
// of a new VM file is started
pub fn set_file_name(&self, file_name: String) {
// Does a thing
}
// Writes the assembly code that is the translation
// of the given arithmetic command.
pub fn write_arithmetic(&mut self, command: &str, label_id: &str) {
// Responsible for setting comp and jump bits for C_Instruction
// -1 = True
// 0 = False
match command {
"sub" => {
self.pop_val_sp();
self.dec_sp();
self.commands.push("D=M-D".to_string());
}
"add" => {
self.pop_val_sp();
self.dec_sp();
self.commands.push("D=D+M".to_string());
}
"eq" | "lt" | "gt" => {
let mut branch1 = label_id.to_string();
branch1.push_str(".1");
let mut branch2 = label_id.to_string();
branch2.push_str(".2");
let (eq_ptr, eq_label) = CodeWriter::get_label_ptr_pair(&branch1);
let (d_eq_ptr, d_eq_label) = CodeWriter::get_label_ptr_pair(&branch2);
self.pop_val_sp();
self.dec_sp();
self.commands.push("D=M-D".to_string());
self.commands.push(eq_ptr.to_string());
match command {
"eq" => self.commands.push("D;JEQ".to_string()),
"lt" => self.commands.push("D;JLT".to_string()),
// "gt" case
_ => self.commands.push("D;JGT".to_string()),
}
self.commands.push("D=0".to_string()); // Set to false
self.commands.push(d_eq_ptr.to_string());
self.commands.push("0;JMP".to_string());
self.commands.push(eq_label.to_string());
self.commands.push("D=-1".to_string()); // Set to true
self.commands.push(d_eq_label.to_string());
}
"neg" => {
self.pop_val_sp();
self.commands.push("D=-D".to_string());
}
"not" => {
self.pop_val_sp();
self.commands.push("D=!D".to_string())
}
"and" => {
self.pop_val_sp();
self.dec_sp();
self.commands.push("D=D&M".to_string());
}
"or" => {
self.pop_val_sp();
self.dec_sp();
self.commands.push("D=D|M".to_string());
}
_ => panic!("Unknown command: {}", command),
}
self.set_m_to_sp();
self.store_d();
}
fn get_label_ptr_pair(label_id: &str) -> (String, String) {
let mut name = "LABEL_".to_string();
name.push_str(label_id);
let mut ptr = "@".to_string();
ptr.push_str(&name);
let mut label = "()".to_string();
label.insert_str(1, &name);
(ptr, label)
}
fn pop_val(&mut self, segment: &str, val: &str) {
match segment {
"constant" => {
self.pop_val_sp();
}
//"argument" => {}
//"local" => {}
//"pointer" => {}
//"static" => {}
//"this" => {}
//"that" => {}
//"temp" => {}
_ => panic!("Unknown segment: {}", segment),
}
}
fn push_val(&mut self, segment: &str, val: &str) {
let mut addr = "@".to_string();
match segment {
"constant" => {
addr.push_str(val);
self.commands.push(addr.to_string());
self.commands.push("D=A".to_string());
self.set_m_to_sp();
self.store_d();
}
_ => panic!("Unknown segment: {}", segment),
}
}
// Decrements SP
// Sets D to SP
fn pop_val_sp(&mut self) {
self.dec_sp();
self.commands.push("D=M".to_string());
}
// Convenience function to store the current value to SP
fn set_m_to_sp(&mut self) {
self.commands.push("@SP".to_string());
self.commands.push("A=M".to_string());
}
// Stores a value to A address
// Increments SP
fn store_d(&mut self) {
self.commands.push("M=D".to_string());
self.inc_sp();
}
fn inc_sp(&mut self) {
self.commands.push("@SP".to_string());
self.commands.push("AM=M+1".to_string());
}
fn dec_sp(&mut self) {
self.commands.push("@SP".to_string());
self.commands.push("AM=M-1".to_string());
}
// Writes the assembly code that is the translation
// of the given command, where command is either C_Push or C_Pop
pub fn write_push_pop(&mut self, command: CommandType, segment: &str, val: &str) {
match command {
CommandType::C_Push => self.push_val(segment, val),
CommandType::C_Pop => self.pop_val(segment, val),
_ => panic!("Unknown command type: {:?}", command),
}
}
// Closes the output file
pub fn close(&self, command: String) {
// Does a thing
}
}
|
use crate::{
composite_renderer::{Command, Image},
sprite_sheet_asset_protocol::SpriteSheetAsset,
};
use core::{
assets::{
asset::{Asset, AssetId},
database::AssetsDatabase,
protocol::{AssetLoadResult, AssetProtocol, AssetVariant, Meta},
},
Ignite, Scalar,
};
use serde::{Deserialize, Serialize};
use std::{any::Any, collections::HashMap};
#[derive(Ignite, Debug, Clone, Serialize, Deserialize)]
pub struct LayerObject {
pub name: String,
pub object_type: String,
pub visible: bool,
pub x: isize,
pub y: isize,
pub width: usize,
pub height: usize,
}
#[derive(Ignite, Debug, Clone, Serialize, Deserialize)]
pub enum LayerData {
Tiles(Vec<usize>),
Objects(Vec<LayerObject>),
}
impl LayerData {
pub fn tiles(&self) -> Option<&[usize]> {
if let LayerData::Tiles(data) = self {
Some(data)
} else {
None
}
}
pub fn objects(&self) -> Option<&[LayerObject]> {
if let LayerData::Objects(data) = self {
Some(data)
} else {
None
}
}
}
#[derive(Ignite, Debug, Clone, Serialize, Deserialize)]
pub struct Layer {
pub name: String,
pub data: LayerData,
}
#[derive(Ignite, Debug, Clone, Serialize, Deserialize)]
pub struct Map {
pub cols: usize,
pub rows: usize,
pub tile_width: usize,
pub tile_height: usize,
pub sprite_sheets: Vec<String>,
pub tiles_mapping: HashMap<usize, (String, String)>,
pub layers: Vec<Layer>,
}
impl Map {
pub fn size(&self) -> (usize, usize) {
(self.cols * self.tile_width, self.rows * self.tile_height)
}
pub fn layer_by_name(&self, name: &str) -> Option<&Layer> {
self.layers.iter().find(|layer| layer.name == name)
}
pub fn build_render_commands_from_layer_by_name<'a>(
&self,
name: &str,
chunk_offset: (usize, usize),
chunk_size: Option<(usize, usize)>,
assets: &AssetsDatabase,
) -> Option<Vec<Command<'a>>> {
let index = self.layers.iter().position(|layer| layer.name == name)?;
self.build_render_commands_from_layer(index, chunk_offset, chunk_size, assets)
}
pub fn build_render_commands_from_layer<'a>(
&self,
index: usize,
chunk_offset: (usize, usize),
chunk_size: Option<(usize, usize)>,
assets: &AssetsDatabase,
) -> Option<Vec<Command<'a>>> {
if self.tiles_mapping.is_empty() {
return None;
}
let layer = self.layers.get(index)?;
if let LayerData::Tiles(data) = &layer.data {
let atlases = self
.sprite_sheets
.iter()
.map(|s| {
let info = assets
.asset_by_path(&format!("atlas://{}", s))?
.get::<SpriteSheetAsset>()?
.info();
Some((s.clone(), info))
})
.collect::<Option<HashMap<_, _>>>()?;
let mut commands = Vec::with_capacity(2 + self.cols * self.rows);
commands.push(Command::Store);
let width = self.tile_width as Scalar;
let height = self.tile_height as Scalar;
let chunk_size = chunk_size.unwrap_or((self.cols, self.rows));
let cols_start = chunk_offset.0.min(self.cols);
let cols_end = (chunk_offset.0 + chunk_size.0).min(self.cols);
let rows_start = chunk_offset.1.min(self.rows);
let rows_end = (chunk_offset.1 + chunk_size.1).min(self.rows);
for col in cols_start..cols_end {
for row in rows_start..rows_end {
let i = self.cols * row + col;
let id = data.get(i).unwrap_or(&0);
if let Some((sprite_sheet, name)) = &self.tiles_mapping.get(id) {
let info = atlases.get(sprite_sheet)?;
let x = width * col as Scalar;
let y = height * row as Scalar;
let frame = info.frames.get(name)?.frame;
commands.push(Command::Draw(
Image::new_owned(info.meta.image_name())
.source(Some(frame))
.destination(Some([x, y, width, height].into()))
.into(),
));
}
}
}
commands.push(Command::Restore);
Some(commands)
} else {
None
}
}
}
pub struct MapAsset {
map: Map,
sprite_sheet_assets: Vec<AssetId>,
}
impl MapAsset {
pub fn map(&self) -> &Map {
&self.map
}
pub fn sprite_sheet_assets(&self) -> &[AssetId] {
&self.sprite_sheet_assets
}
}
pub struct MapAssetProtocol;
impl AssetProtocol for MapAssetProtocol {
fn name(&self) -> &str {
"map"
}
fn on_load(&mut self, data: Vec<u8>) -> AssetLoadResult {
let map: Map = bincode::deserialize(&data).unwrap();
let list = map
.sprite_sheets
.iter()
.map(|s| (s.clone(), format!("atlas://{}", s)))
.collect::<Vec<_>>();
AssetLoadResult::Yield(Some(Box::new(map)), list)
}
fn on_resume(&mut self, payload: Meta, list: &[(&str, &Asset)]) -> AssetLoadResult {
let map = *(payload.unwrap() as Box<dyn Any + Send>)
.downcast::<Map>()
.unwrap();
let sprite_sheet_assets = list.iter().map(|(_, asset)| asset.id()).collect::<Vec<_>>();
AssetLoadResult::Data(Box::new(MapAsset {
map,
sprite_sheet_assets,
}))
}
fn on_unload(&mut self, asset: &Asset) -> Option<Vec<AssetVariant>> {
asset.get::<MapAsset>().map(|asset| {
asset
.sprite_sheet_assets
.iter()
.map(|a| AssetVariant::Id(*a))
.collect::<Vec<_>>()
})
}
}
|
use super::field_table::{FieldTableEntry, FieldTableType};
pub struct DeviceInfoTable {
table: FieldTableType
}
impl FieldTableEntry for DeviceInfoTable {
fn get(&self, key: i32) -> String {
let result = self.table.get(&key);
match result {
Some(r) => r.clone(),
// None => panic!("Unrecognized Devce Info Key: {}", key)
None => {
// let s = format!("{}", key);
// s.as_str().clone()
key.to_string()
}
}
}
}
impl DeviceInfoTable {
pub fn new() -> DeviceInfoTable {
DeviceInfoTable {
table: DeviceInfoTable::make_table()
}
}
fn make_table() -> FieldTableType {
let mut table = FieldTableType::new();
table.insert(253, String::from("timestamp"));
table.insert(0, String::from("device_index"));
table.insert(1, String::from("device_type"));
table.insert(2, String::from("manufacturer"));
table.insert(3, String::from("serial_number"));
table.insert(4, String::from("product"));
table.insert(5, String::from("software_version"));
table.insert(6, String::from("hardware_version"));
table.insert(7, String::from("cum_operating_time"));
table.insert(10, String::from("battery_voltage"));
table.insert(11, String::from("battery_status"));
table.insert(18, String::from("sensor_position"));
table.insert(19, String::from("descriptor"));
table.insert(20, String::from("ant_transmission_type"));
table.insert(21, String::from("ant_device_number"));
table.insert(22, String::from("ant_network"));
table.insert(25, String::from("source_type"));
table.insert(27, String::from("product_name"));
table
}
}
|
fn main() {
// To create a new, empty vector, we can call the `Vec::new()` function.
// let v: Vec<i32> = Vec::new();
// It’s more common to create a `Vec<T>` that has initial values, and Rust provides the `vec!` macro for convenience.
{
let _v = vec![1, 2, 3, 4];
} // <- v goes out of scope and is freed here
let mut v = Vec::new();
v.push(5);
v.push(6);
v.push(7);
v.push(8);
let v = vec![1, 2, 3, 4, 5];
let second: &i32 = &v[1];
let third: Option<&i32> = v.get(2);
println!("{:?}", second);
println!("{:?}", third);
}
|
#[doc = "Reader of register FMC_BCHISR"]
pub type R = crate::R<u32, super::FMC_BCHISR>;
#[doc = "Reader of field `DUEF`"]
pub type DUEF_R = crate::R<bool, bool>;
#[doc = "Reader of field `DERF`"]
pub type DERF_R = crate::R<bool, bool>;
#[doc = "Reader of field `DEFF`"]
pub type DEFF_R = crate::R<bool, bool>;
#[doc = "Reader of field `DSRF`"]
pub type DSRF_R = crate::R<bool, bool>;
#[doc = "Reader of field `EPBRF`"]
pub type EPBRF_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - DUEF"]
#[inline(always)]
pub fn duef(&self) -> DUEF_R {
DUEF_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - DERF"]
#[inline(always)]
pub fn derf(&self) -> DERF_R {
DERF_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - DEFF"]
#[inline(always)]
pub fn deff(&self) -> DEFF_R {
DEFF_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - DSRF"]
#[inline(always)]
pub fn dsrf(&self) -> DSRF_R {
DSRF_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - EPBRF"]
#[inline(always)]
pub fn epbrf(&self) -> EPBRF_R {
EPBRF_R::new(((self.bits >> 4) & 0x01) != 0)
}
}
|
//個人的に行列はglmのオーダーがいい。glamはglmと違うっぽい?
// |
use std::io;
pub fn question4() {
println!("Hello, world!");
println!("Enter Radius Of Circle?");
let mut number1 = String::new();
io::stdin().read_line(&mut number1)
.expect("Failed to read line");
let number1: f64 = number1.trim().parse()
.expect("Please type a number!");
let pi =3.141592654;
println!("The Are Of Circle is {}",(number1 * number1) * pi);
} |
use average::*;
use average::{Max, Min, Variance};
use serde;
use serde::ser::{SerializeStruct};
pub struct Stats {
min: Min,
max: Max,
var: Variance,
}
impl Stats {
fn new() -> Stats {
Stats {
min: Min::default(),
max: Max::default(),
var: Variance::default(),
}
}
fn add(&mut self, x: f64) {
self.min.add(x);
self.max.add(x);
self.var.add(x);
}
fn min(&self) -> f64 {
self.min.min()
}
fn max(&self) -> f64 {
self.max.max()
}
fn mean(&self) -> f64 {
self.var.mean()
}
fn var(&self) -> f64 {
self.var.population_variance()
}
}
impl Default for Stats {
fn default() -> Stats {
Stats::new()
}
}
impl_from_iterator!(Stats);
impl serde::Serialize for Stats {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut state = serializer.serialize_struct("Stats", 4)?;
state.serialize_field("min", &self.min())?;
state.serialize_field("max", &self.max())?;
state.serialize_field("mean", &self.mean())?;
state.serialize_field("var", &self.var())?;
state.end()
}
}
|
use std::collections::HashMap;
use std::i32;
use std::sync::{Arc, RwLock};
use lazy_static::lazy_static;
use rusttype::{point, Error, Font, Scale, SharedBytes};
use font_loader::system_fonts;
use font_loader::system_fonts::FontPropertyBuilder;
use super::{FontData, FontFamily, FontTransform, LayoutBox};
type FontResult<T> = Result<T, FontError>;
#[derive(Debug, Clone)]
pub enum FontError {
LockError,
NoSuchFont,
FontLoadError(Arc<Error>),
}
impl std::fmt::Display for FontError {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
FontError::LockError => write!(fmt, "Could not lock mutex"),
FontError::NoSuchFont => write!(fmt, "No such font"),
FontError::FontLoadError(e) => write!(fmt, "Font loading error: {}", e),
}
}
}
impl std::error::Error for FontError {}
lazy_static! {
static ref CACHE: RwLock<HashMap<String, FontResult<Font<'static>>>> =
RwLock::new(HashMap::new());
}
#[allow(dead_code)]
/// Lazily load font data. Font type doesn't own actual data, which
/// lives in the cache.
fn load_font_data(face: &str) -> FontResult<Font<'static>> {
let cache = CACHE.read().unwrap();
if let Some(cached) = cache.get(face) {
return cached.clone();
}
drop(cache);
let mut cache = CACHE.write().unwrap();
let query = FontPropertyBuilder::new().family(face).build();
let result = system_fonts::get(&query)
.map(|(data, _)| data.into())
.ok_or(FontError::NoSuchFont)
.and_then(|bytes: SharedBytes| {
Font::from_bytes(bytes).map_err(|err| FontError::FontLoadError(Arc::new(err)))
});
cache.insert(face.into(), result.clone());
result
}
/// Remove all cached fonts data.
#[allow(dead_code)]
pub fn clear_font_cache() -> FontResult<()> {
let mut cache = CACHE.write().map_err(|_| FontError::LockError)?;
cache.clear();
Ok(())
}
#[derive(Clone)]
pub struct FontDataInternal(Font<'static>);
impl FontData for FontDataInternal {
type ErrorType = FontError;
fn new(family: FontFamily) -> Result<Self, FontError> {
Ok(FontDataInternal(load_font_data(family.as_str())?))
}
fn estimate_layout(&self, size: f64, text: &str) -> Result<LayoutBox, Self::ErrorType> {
let scale = Scale::uniform(size as f32);
let (mut min_x, mut min_y) = (i32::MAX, i32::MAX);
let (mut max_x, mut max_y) = (0, 0);
let font = &self.0;
font.layout(text, scale, point(0.0, 0.0)).for_each(|g| {
if let Some(rect) = g.pixel_bounding_box() {
min_x = min_x.min(rect.min.x);
min_y = min_y.min(rect.min.y);
max_x = max_x.max(rect.max.x);
max_y = max_y.max(rect.max.y);
}
});
if min_x == i32::MAX || min_y == i32::MAX {
return Ok(((0, 0), (0, 0)));
}
Ok(((min_x, min_y), (max_x, max_y)))
}
fn draw<E, DrawFunc: FnMut(i32, i32, f32) -> Result<(), E>>(
&self,
(x, y): (i32, i32),
size: f64,
text: &str,
trans: FontTransform,
mut draw: DrawFunc,
) -> Result<Result<(), E>, Self::ErrorType> {
let layout = self.estimate_layout(size, text)?;
let scale = Scale::uniform(size as f32);
let mut result = Ok(());
let font = &self.0;
let base_x = x + trans.offset(layout).0;
let base_y = y + trans.offset(layout).1;
for g in font.layout(text, scale, point(0.0, 0.0)) {
if let Some(rect) = g.pixel_bounding_box() {
let x0 = rect.min.x;
let y0 = rect.min.y - (layout.0).1;
g.draw(|x, y, v| {
let (x, y) = trans.transform(x as i32 + x0, y as i32 + y0);
if x + base_x >= 0 && y + base_y >= 0 && result.is_ok() {
result = draw(x + base_x, y + base_y, v);
}
});
}
}
Ok(result)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_font_cache() -> FontResult<()> {
clear_font_cache()?;
assert_eq!(CACHE.read().unwrap().len(), 0);
load_font_data("serif")?;
assert_eq!(CACHE.read().unwrap().len(), 1);
load_font_data("serif")?;
assert_eq!(CACHE.read().unwrap().len(), 1);
return Ok(());
}
}
|
#[doc = "Reader of register CTL"]
pub type R = crate::R<u32, super::CTL>;
#[doc = "Writer for register CTL"]
pub type W = crate::W<u32, super::CTL>;
#[doc = "Register CTL `reset()`'s with value 0x0002_0808"]
impl crate::ResetValue for super::CTL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x0002_0808
}
}
#[doc = "Reader of field `PGA_R`"]
pub type PGA_R_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `PGA_R`"]
pub struct PGA_R_W<'a> {
w: &'a mut W,
}
impl<'a> PGA_R_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f);
self.w
}
}
#[doc = "Reader of field `PGA_L`"]
pub type PGA_L_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `PGA_L`"]
pub struct PGA_L_W<'a> {
w: &'a mut W,
}
impl<'a> PGA_L_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8);
self.w
}
}
#[doc = "Reader of field `SOFT_MUTE`"]
pub type SOFT_MUTE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SOFT_MUTE`"]
pub struct SOFT_MUTE_W<'a> {
w: &'a mut W,
}
impl<'a> SOFT_MUTE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `STEP_SEL`"]
pub type STEP_SEL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `STEP_SEL`"]
pub struct STEP_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> STEP_SEL_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `ENABLED`"]
pub type ENABLED_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ENABLED`"]
pub struct ENABLED_W<'a> {
w: &'a mut W,
}
impl<'a> ENABLED_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bits 0:3 - Right channel PGA gain: +1.5dB/step, -12dB ~ +10.5dB '0': -12 dB '1': -10.5 dB ... '15' +10.5 dB (Note: These bits are connected to AR36U12.PDM_CORE_CFG.PGA_R)"]
#[inline(always)]
pub fn pga_r(&self) -> PGA_R_R {
PGA_R_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 8:11 - Left channel PGA gain: +1.5dB/step, -12dB ~ +10.5dB '0': -12 dB '1': -10.5 dB ... '15': +10.5 dB (Note: These bits are connected to AR36U12.PDM_CORE_CFG.PGA_L)"]
#[inline(always)]
pub fn pga_l(&self) -> PGA_L_R {
PGA_L_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bit 16 - Soft mute function to mute the volume smoothly '0': Disabled. '1': Enabled. (Note: This bit is connected to AR36U12.PDM_CORE_CFG.SOFT_MUTE)"]
#[inline(always)]
pub fn soft_mute(&self) -> SOFT_MUTE_R {
SOFT_MUTE_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - Set fine gain step for smooth PGA or Soft-Mute attenuation transition. '0': 0.13dB '1': 0.26dB (Note: This bit is connected to AR36U12.PDM_CORE2_CFG.SEL_STEP)"]
#[inline(always)]
pub fn step_sel(&self) -> STEP_SEL_R {
STEP_SEL_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 31 - Enables the PDM component: '0': Disabled. '1': Enabled."]
#[inline(always)]
pub fn enabled(&self) -> ENABLED_R {
ENABLED_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:3 - Right channel PGA gain: +1.5dB/step, -12dB ~ +10.5dB '0': -12 dB '1': -10.5 dB ... '15' +10.5 dB (Note: These bits are connected to AR36U12.PDM_CORE_CFG.PGA_R)"]
#[inline(always)]
pub fn pga_r(&mut self) -> PGA_R_W {
PGA_R_W { w: self }
}
#[doc = "Bits 8:11 - Left channel PGA gain: +1.5dB/step, -12dB ~ +10.5dB '0': -12 dB '1': -10.5 dB ... '15': +10.5 dB (Note: These bits are connected to AR36U12.PDM_CORE_CFG.PGA_L)"]
#[inline(always)]
pub fn pga_l(&mut self) -> PGA_L_W {
PGA_L_W { w: self }
}
#[doc = "Bit 16 - Soft mute function to mute the volume smoothly '0': Disabled. '1': Enabled. (Note: This bit is connected to AR36U12.PDM_CORE_CFG.SOFT_MUTE)"]
#[inline(always)]
pub fn soft_mute(&mut self) -> SOFT_MUTE_W {
SOFT_MUTE_W { w: self }
}
#[doc = "Bit 17 - Set fine gain step for smooth PGA or Soft-Mute attenuation transition. '0': 0.13dB '1': 0.26dB (Note: This bit is connected to AR36U12.PDM_CORE2_CFG.SEL_STEP)"]
#[inline(always)]
pub fn step_sel(&mut self) -> STEP_SEL_W {
STEP_SEL_W { w: self }
}
#[doc = "Bit 31 - Enables the PDM component: '0': Disabled. '1': Enabled."]
#[inline(always)]
pub fn enabled(&mut self) -> ENABLED_W {
ENABLED_W { w: self }
}
}
|
use std::{marker::PhantomData, ops::Index};
use crate::{Dim, Matrix};
/// A view into (slice of) a matrix. Or, a reference to a matrix.
///
/// Any view should consist of a refernce to a matrix, and little more.
/// It must be cheap to copy.
/// # Examples
pub trait View<'a>: Sized + Copy
where
Self: Index<usize, Output = Self::Entry> + Index<[usize; 2], Output = Self::Entry>,
{
type M: Dim;
type N: Dim;
type Entry: 'a;
fn m(&self) -> Self::M;
fn n(&self) -> Self::N;
/// Gets the entry at specified indices,
/// or returns nothing if the index is invalid.
fn get(&self, i: usize, j: usize) -> Option<&'a Self::Entry>;
type Iter: Iterator<Item = &'a Self::Entry>;
fn iter(&self) -> Self::Iter;
/// Checks if the two views are equal to one another.
/// # Examples
/// ```
/// # use safemat::prelude::*;
/// let m = Matrix::from_array([
/// [1, 2, 3],
/// [2, 3, 4],
/// [3, 4, 5]
/// ]);
/// let a = m.row_at(1);
/// let b = m.col_at(1);
/// assert!(a.equal(b.transpose_ref()));
/// ```
fn equal<'b, V>(&self, rhs: V) -> bool
where
V: View<'b>,
Self::Entry: PartialEq<V::Entry>,
Self::M: PartialEq<V::M>,
Self::N: PartialEq<V::N>,
{
if self.m() != rhs.m() || self.n() != rhs.n() {
return false;
}
self.iter().zip(rhs.iter()).all(|(a, b)| a == b)
}
/// Clones each entry in this view into a new owned [`Matrix`].
/// # Examples
/// Row/column slices.
/// ```
/// # use safemat::{*, view::View};
/// let a = Matrix::from_array([
/// [1, 2, 3, 4 ],
/// [5, 6, 7, 8 ],
/// [9, 10, 11, 12]
/// ]);
///
/// let b = a.row_at(1).to_matrix();
/// assert_eq!(b, mat![5, 6, 7, 8]);
///
/// let c = a.col_at(2).to_matrix();
/// assert_eq!(c, mat![3; 7; 11]);
/// ```
fn to_matrix(self) -> Matrix<Self::Entry, Self::M, Self::N>
where
Self::Entry: Clone,
{
Matrix::try_from_iter_with_dim(self.m(), self.n(), self.iter().cloned()).unwrap()
}
/// Gets an interface for accessing a transposed form of this matrix;
/// does not actually rearrange any data.
/// # Examples
/// ```
/// # use safemat::prelude::*;
/// let a = mat![1, 2, 3 ; 4, 5, 6];
/// let b = a.as_view().transpose_ref().to_matrix();
/// assert_eq!(b, mat![1, 4 ; 2, 5 ; 3, 6]);
/// ```
/// It also supports iteration that yields indices.
/// ```
/// # use safemat::prelude::*;
/// let a = Matrix::from_array([
/// [1, 2, 3],
/// [4, 5, 6],
/// ]);
/// let b = a.as_view().transpose_ref();
/// let mut i = b.iter().indices();
/// assert_eq!(i.next(), Some((0, 0, &1)));
/// assert_eq!(i.next(), Some((0, 1, &4)));
/// assert_eq!(i.next(), Some((1, 0, &2)));
/// // etc...
/// # assert_eq!(i.next(), Some((1, 1, &5)));
/// # assert_eq!(i.next(), Some((2, 0, &3)));
/// # assert_eq!(i.next(), Some((2, 1, &6)));
/// ```
#[inline]
fn transpose_ref(self) -> Transpose<'a, Self> {
Transpose {
view: self,
_p: PhantomData,
}
}
}
pub mod row;
pub mod col;
impl<T, M: Dim, N: Dim> Matrix<T, M, N> {
#[inline]
pub fn as_view(&self) -> &Self {
self
}
pub fn row_at(&self, i: usize) -> row::RowSlice<'_, T, M, N> {
row::RowSlice::new(self, i)
}
#[inline]
pub fn col_at(&self, j: usize) -> col::ColumnSlice<'_, T, M, N> {
col::ColumnSlice::new(self, j)
}
}
/// Interchanges the indices when accessing a matrix view.
/// ```
/// # use safemat::prelude::*;
/// let a = Matrix::from_array([
/// [1, 2, 3, 4],
/// [5, 6, 7, 8],
/// ]);
/// let t = a.as_view().transpose_ref();
/// // linear indexing:
/// assert_eq!(t[0], 1);
/// assert_eq!(t[1], 5);
/// assert_eq!(t[2], 2);
/// // etc...
/// # assert_eq!(t[3], 6);
/// # assert_eq!(t[4], 3);
/// # assert_eq!(t[5], 7);
/// # assert_eq!(t[6], 4);
/// # assert_eq!(t[7], 8);
///
/// // square indexing:
/// assert_eq!(t[[0,0]], 1);
/// assert_eq!(t[[1,0]], 2);
/// assert_eq!(t[[2,0]], 3);
/// // etc...
/// # assert_eq!(t[[3,0]], 4);
/// # assert_eq!(t[[0,1]], 5);
/// # assert_eq!(t[[1,1]], 6);
/// # assert_eq!(t[[2,1]], 7);
/// # assert_eq!(t[[3,1]], 8);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Transpose<'a, V: 'a> {
view: V,
_p: PhantomData<&'a V>,
}
impl<'a, V> View<'a> for Transpose<'a, V>
where
V: View<'a>,
{
type M = V::N;
type N = V::M;
type Entry = V::Entry;
#[inline]
fn m(&self) -> V::N {
self.view.n()
}
#[inline]
fn n(&self) -> V::M {
self.view.m()
}
#[inline]
fn get(&self, i: usize, j: usize) -> Option<&'a Self::Entry> {
self.view.get(j, i)
}
type Iter = TransposeIter<'a, V>;
#[inline]
fn iter(&self) -> Self::Iter {
TransposeIter {
view: self.view,
i: 0,
j: 0,
_p: PhantomData,
}
}
}
impl<'a, V> Index<usize> for Transpose<'a, V>
where
V: View<'a>,
{
type Output = V::Entry;
#[inline]
fn index(&self, idx: usize) -> &Self::Output {
let i = idx / self.view.m().dim();
let j = idx % self.view.m().dim();
&self.view[[j, i]]
}
}
impl<'a, V> Index<[usize; 2]> for Transpose<'a, V>
where
V: View<'a>,
{
type Output = V::Entry;
#[inline]
fn index(&self, [i, j]: [usize; 2]) -> &Self::Output {
&self.view[[j, i]]
}
}
/// An iterator over the transpose of a [`View`].
pub struct TransposeIter<'a, V> {
view: V,
_p: PhantomData<&'a V>,
i: usize,
j: usize,
}
impl<'a, V: View<'a>> TransposeIter<'a, V> {
#[inline]
pub fn indices(self) -> crate::iter::Indices<Self> {
crate::iter::Indices(self)
}
}
impl<'a, V> Iterator for TransposeIter<'a, V>
where
V: View<'a>,
{
type Item = &'a V::Entry;
fn next(&mut self) -> Option<Self::Item> {
let j = self.j;
if j < self.view.n().dim() {
let i = self.i;
self.i += 1;
if self.i == self.view.m().dim() {
self.i = 0;
self.j += 1;
}
self.view.get(i, j) // Due to this line, this is NOT a fused iterator.
} else {
None
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}
impl<'a, V: View<'a>> crate::iter::IndexIterator for TransposeIter<'a, V> {
fn get_indices(&self) -> (usize, usize) {
(self.j, self.i)
}
fn get_indices_back(&self) -> (usize, usize)
where
Self: DoubleEndedIterator,
{
unimplemented!() // we don't support this 'round these parts
}
}
impl<'a, V> ExactSizeIterator for TransposeIter<'a, V>
where
V: View<'a>,
{
#[inline]
fn len(&self) -> usize {
let idx = self.i * self.view.n().dim() + self.j;
self.view.m().dim() * self.view.n().dim() - idx
}
}
impl<'a, T, M: Dim, N: Dim> View<'a> for &'a Matrix<T, M, N> {
type M = M;
type N = N;
type Entry = T;
#[inline]
fn m(&self) -> M {
self.m
}
#[inline]
fn n(&self) -> N {
self.n
}
#[inline]
fn get(&self, i: usize, j: usize) -> Option<&'a T> {
(*self).get(i, j)
}
type Iter = crate::iter::Iter<'a, T, M, N>;
#[inline]
fn iter(&self) -> Self::Iter {
Matrix::iter(self)
}
}
pub mod entry {
use std::ops::Index;
use super::View;
use crate::{dim, dim::Dim, Matrix};
/// A [`View`] referring to a single entry in a matrix.
/// # Examples
/// ```
/// # use safemat::{prelude::*, view::entry::Entry};
/// let m = mat![1, 2; 3, 4];
/// assert_eq!(Entry::new(&m, 0, 1), &mat![2]);
/// assert_eq!(Entry::new(&m, 1, 0), &mat![3]);
#[derive(Debug)]
pub struct Entry<'a, T, M, N> {
mat: &'a Matrix<T, M, N>,
i: usize,
j: usize,
}
impl<'a, T, M: Dim, N: Dim> Entry<'a, T, M, N> {
#[inline]
pub fn new(mat: &'a Matrix<T, M, N>, i: usize, j: usize) -> Self {
assert!(i < mat.m.dim());
assert!(j < mat.n.dim());
Self { mat, i, j }
}
}
impl<T, M, N> Copy for Entry<'_, T, M, N> {}
impl<T, M, N> Clone for Entry<'_, T, M, N> {
fn clone(&self) -> Self {
Self {
mat: self.mat,
i: self.i,
j: self.j,
}
}
}
impl<'a, T, M: Dim, N: Dim> View<'a> for Entry<'a, T, M, N> {
type Entry = T;
type M = dim!(1);
type N = dim!(1);
fn m(&self) -> dim!(1) {
dim!(1)
}
fn n(&self) -> dim!(1) {
dim!(1)
}
fn get(&self, i: usize, j: usize) -> Option<&'a T> {
if i == 0 && j == 0 {
Some(&self.mat.items[self.i * self.mat.n.dim() + self.j])
} else {
None
}
}
type Iter = std::iter::Once<&'a T>;
fn iter(&self) -> Self::Iter {
std::iter::once(self.get(0, 0).unwrap())
}
}
impl<T, M: Dim, N: Dim> Index<usize> for Entry<'_, T, M, N> {
type Output = T;
fn index(&self, i: usize) -> &T {
assert_eq!(i, 0);
&self.mat[[self.i, self.j]]
}
}
impl<T, M: Dim, N: Dim> Index<[usize; 2]> for Entry<'_, T, M, N> {
type Output = T;
fn index(&self, [i, j]: [usize; 2]) -> &T {
assert_eq!(i, 0);
assert_eq!(j, 0);
&self.mat[[self.i, self.j]]
}
}
impl<'a, T, M: Dim, N: Dim, V> PartialEq<V> for Entry<'a, T, M, N>
where
V: View<'a>,
T: PartialEq<V::Entry>,
dim!(1): PartialEq<V::M> + PartialEq<V::N>,
{
#[inline]
fn eq(&self, rhs: &V) -> bool {
self.equal(*rhs)
}
}
}
|
extern crate crypto;
extern crate time;
#[macro_use]
extern crate serde_derive;
extern crate serde;
pub mod blockchain {
use std::sync::RwLock;
use std::fmt;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use time;
#[derive(Debug)]
pub enum BlockchainError {
InvalidBlockchain,
InvalidBlock
}
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Block {
pub index: u64,
pub previous_hash: String,
pub timestamp: u64,
pub data: String,
pub hash: String,
}
impl Block {
pub fn new<S>(index: u64, previous_hash: S, timestamp: u64, data: S, hash: S) -> Block where S: Into<String> {
Block { index: index, previous_hash: previous_hash.into(), timestamp: timestamp, data: data.into(), hash: hash.into() }
}
}
impl fmt::Display for Block {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<Block: {}>", self.index)
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Blockchain {
blocks: RwLock<Vec<Block>>,
}
impl Blockchain {
pub fn new() -> Blockchain {
Blockchain { blocks: RwLock::new(vec![Blockchain::generate_genesis_block()]) }
}
pub fn len(&self) -> usize {
let blocks = self.blocks.read().unwrap();
blocks.len()
}
fn calculate_hash(index: u64, previous_hash: &String, timestamp: u64, data: &String) -> String {
let init_str = format!("{}{}{}{}", index, previous_hash, timestamp, data);
let mut sha256 = Sha256::new();
sha256.input_str(&init_str);
sha256.result_str()
}
pub fn calculate_hash_for_block(block: &Block) -> String {
Blockchain::calculate_hash(block.index, &block.previous_hash, block.timestamp, &block.data)
}
pub fn generate_genesis_block() -> Block {
Block::new(0, "0".to_string(), 1465154705, "my genesis block!!".to_string(),
"816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7".to_string())
}
pub fn generate_new_block<S>(&self, data: S) -> Block where S: Into<String> {
let new_index = self.latest_block().index + 1;
let new_timestamp = time::now_utc().to_timespec().sec as u64;
let data = data.into();
let new_hash = Blockchain::calculate_hash(new_index, &self.latest_block().hash, new_timestamp, &data);
Block::new(new_index, self.latest_block().hash.clone(), new_timestamp, data, new_hash)
}
pub fn is_valid_new_block(&self, block: &Block) -> bool {
let latest_block = &self.latest_block();
self.is_valid_block(&block, latest_block)
}
fn is_valid_block(&self, block: &Block, prev_block: &Block) -> bool {
if prev_block.index + 1 != block.index {
false
} else if prev_block.hash != block.previous_hash {
false
} else if Blockchain::calculate_hash_for_block(&block) != block.hash {
false
} else {
true
}
}
pub fn add_block(&self, block: &Block) -> Result<Block, BlockchainError> {
match self.is_valid_new_block(block) {
true => {
let mut blocks = self.blocks.write().unwrap();
blocks.push(block.clone());
Ok(block.clone())
}
false => Err(BlockchainError::InvalidBlock),
}
}
pub fn genesis_block(&self) -> Block {
let blocks = self.blocks.read().unwrap();
blocks[0].clone()
}
pub fn latest_block(&self) -> Block {
let chain = self.blocks.read().unwrap();
chain[chain.len() - 1].clone()
}
pub fn is_valid_chain(&self, other_chain: &Blockchain) -> bool {
if self.genesis_block() != other_chain.genesis_block() {
return false
}
let chain = other_chain.blocks.read().unwrap();
(1..chain.len()).all(|i| { self.is_valid_block(&chain[i], &chain[i - 1]) })
}
pub fn replace_chain(&self, other_chain: &Blockchain) -> Result<&Blockchain, BlockchainError> {
if other_chain.len() > self.len() && self.is_valid_chain(other_chain) {
let new_blockchain = other_chain.blocks.read().unwrap();
let (_, new_blocks_slice) = new_blockchain.as_slice().split_at(self.len());
let mut blocks = self.blocks.write().unwrap();
blocks.extend(new_blocks_slice.to_vec().into_iter());
Ok(&self)
} else {
Err(BlockchainError::InvalidBlockchain)
}
}
}
} |
use crate::{bson::Document, event, test::Matchable};
use bson::Bson;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CommandStartedEvent {
command_name: Option<String>,
database_name: Option<String>,
command: Document,
}
impl CommandStartedEvent {
pub fn matches_expected(
&self,
expected: &CommandStartedEvent,
session0_lsid: &Document,
session1_lsid: &Document,
) -> Result<(), String> {
if expected.command_name.is_some() && self.command_name != expected.command_name {
return Err(format!(
"command name mismatch, expected {:?} got {:?}",
expected.command_name, self.command
));
}
if expected.database_name.is_some() && self.database_name != expected.database_name {
return Err(format!(
"database name mismatch, expected {:?} got {:?}",
expected.database_name, self.database_name
));
}
let mut expected = expected.command.clone();
if let Some(Bson::String(session)) = expected.remove("lsid") {
match session.as_str() {
"session0" => {
expected.insert("lsid", session0_lsid.clone());
}
"session1" => {
expected.insert("lsid", session1_lsid.clone());
}
other => panic!("unknown session name: {}", other),
}
}
self.command.content_matches(&expected)
}
}
impl From<event::command::CommandStartedEvent> for CommandStartedEvent {
fn from(event: event::command::CommandStartedEvent) -> Self {
CommandStartedEvent {
command_name: Some(event.command_name),
database_name: Some(event.db),
command: event.command,
}
}
}
|
use crate::prelude::*;
/// Utility struct to allow storing child expressions of binary expressions
/// continuously in memory while having a name `lhs` and `rhs` to refer to them
/// for improved usability.
///
/// All binary expressions should strive to use this utility to store their
/// child expressions.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BinExprChildren {
pub lhs: AnyExpr,
pub rhs: AnyExpr
}
impl BinExprChildren {
/// Creates a new `BinExprChildren` for the given child expressions.
#[inline]
pub fn new(lhs: AnyExpr, rhs: AnyExpr) -> BinExprChildren {
BinExprChildren{lhs, rhs}
}
/// Creates a new boxed (on heap) `BinExprChildren` for the given child expressions.
#[inline]
pub fn new_boxed(lhs: AnyExpr, rhs: AnyExpr) -> P<BinExprChildren> {
P::new(BinExprChildren::new(lhs, rhs))
}
/// Swaps its left-hand side child with the right-hand side child.
pub fn swap_children(&mut self) {
use std::mem;
mem::swap(&mut self.lhs, &mut self.rhs)
}
/// Returns a pair of both child expressions.
///
/// Note: Consumes `self`.
pub fn into_children_pair(self) -> (AnyExpr, AnyExpr) {
(self.lhs, self.rhs)
}
}
impl Children for BinExprChildren {
/// Returns an immutable iterator over the two child expressions.
#[inline]
fn children(&self) -> ChildrenIter {
ChildrenIter::binary(&self.lhs, &self.rhs)
}
}
impl ChildrenMut for BinExprChildren {
/// Returns an mutable iterator over the two child expressions.
#[inline]
fn children_mut(&mut self) -> ChildrenIterMut {
ChildrenIterMut::binary(&mut self.lhs, &mut self.rhs)
}
}
impl IntoChildren for BinExprChildren {
/// Consumes this `BinExprChildren` and returns an iterator over its two child expressions.
///
/// This may be used to transfer ownership of its child expressions.
#[inline]
fn into_children(self) -> IntoChildrenIter {
IntoChildrenIter::binary(self.lhs, self.rhs)
}
}
impl HasArity for BinExprChildren {
#[inline]
fn arity(&self) -> usize {
2
}
}
impl BinaryExpr for BinExprChildren {
fn lhs_child(&self) -> &AnyExpr {
&self.lhs
}
fn rhs_child(&self) -> &AnyExpr {
&self.rhs
}
}
|
// Copyright 2020 Xavier Gillard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
use graph_gen::{ErModel, Graph, Max2SatGraph, Generatable, WeightedMaxCliqueGraph};
use structopt::StructOpt;
use crate::Output::Dimacs;
use std::str::FromStr;
/// Convenience tool to generate pseudo random graphs.
#[derive(StructOpt)]
struct Args {
/// The number of vertices in the generated graph
#[structopt(name="nb_vertices", short, long)]
n: usize,
/// The likelihood of any edge to be picked
#[structopt(name="probability", short, long)]
p: f64,
/// If set, self loops are allowed in the generated graph
#[structopt(name="loops", short, long)]
loops: bool,
/// If set, the generated graph will be a digraph
#[structopt(name="digraph", short, long)]
digraph: bool,
/// If set, the generated graph will be a max2sat instance
#[structopt(name="max2sat", short, long)]
max2sat: bool,
/// If set, the generated graph will be a misp/maxclique instance
#[structopt(name="misp", short, long)]
misp: bool,
/// The output language (defaults to dimacs)
#[structopt(name="output", short, long)]
output : Option<Output>,
/// Optional weight candidates
#[structopt(name="weights", short, long)]
weights: Option<Vec<isize>>
}
enum Output {
Dimacs, GraphViz
}
impl Default for Output {
fn default() -> Self {
Dimacs
}
}
impl FromStr for Output {
type Err = String;
fn from_str(txt: &str) -> Result<Output, String> {
if &txt.to_lowercase() == "dimacs" {
return Ok(Output::Dimacs);
}
if &txt.to_lowercase() == "graphviz" {
return Ok(Output::GraphViz);
}
if &txt.to_lowercase() == "dot" {
return Ok(Output::GraphViz);
}
Err(txt.to_owned())
}
}
impl Args {
fn graph(&self) -> Graph {
let n = if self.max2sat { 2 * self.n } else { self.n };
let mut model = ErModel::new(n, self.p);
if self.digraph {
model = model.digraph();
}
if self.loops {
model = model.with_self_loops();
}
model.generator().gen()
}
fn wcnf(&self, g: Graph) -> Max2SatGraph {
Max2SatGraph::new(g)
}
fn generatable(&self) -> Generatable {
let mut graph = self.graph();
if self.max2sat {
if let Some(weights) = self.weights.as_ref() {
graph.pluck_random_weights(weights);
}
Generatable::GenSat {s : self.wcnf(graph)}
} else if self.misp {
let mut g = WeightedMaxCliqueGraph::new(graph);
if let Some(weights) = self.weights.as_ref() {
g.pluck_random_weights(weights);
}
Generatable::ClqGraph {g}
} else {
if let Some(weights) = self.weights.as_ref() {
graph.pluck_random_weights(weights);
}
Generatable::GenGraph {g : graph}
}
}
fn output(&self, g: &Generatable) -> String {
match &self.output {
None => g.to_dimacs(),
Some(o) => match o {
Output::Dimacs => g.to_dimacs(),
Output::GraphViz => g.to_dot()
}
}
}
}
fn main() {
let args = Args::from_args();
let graph= args.generatable();
let out = args.output(&graph);
println!("{}", out);
}
|
#[macro_export]
macro_rules! add_css_provider {
($provider:expr, $($widget:expr),*) => (
{
$(
$widget
.get_style_context()
.add_provider($provider,
gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
)*
}
);
}
// Make moving clones into closures more convenient.
// Sourced from https://github.com/gtk-rs/examples/blob/e17372b1c65788b022ff152fff37d392d0f31e87/src/bin/treeview.rs#L20-L36
#[macro_export]
macro_rules! clone {
(@param _) => ( _ );
(@param $x:ident) => ( $x );
($($n:ident),+ => move || $body:expr) => (
{
$( let $n = $n.clone(); )+
move || $body
}
);
($($n:ident),+ => move |$($p:tt),+| $body:expr) => (
{
$( let $n = $n.clone(); )+
move |$(clone!(@param $p),)+| $body
}
);
}
// Upgrade weak reference or return.
// Sourced from https://github.com/gtk-rs/examples/blob/e17372b1c65788b022ff152fff37d392d0f31e87/src/bin/gtktest.rs#L36-L48
#[macro_export]
macro_rules! upgrade_weak {
($x:ident, $r:expr) => {{
match $x.upgrade() {
Some(o) => o,
None => return $r,
}
}};
($x:ident) => {
upgrade_weak!($x, ())
};
}
mod cmdline;
pub mod color;
mod common;
#[cfg(feature = "libwebkit2gtk")]
mod cursor_tooltip;
mod font;
mod grid;
mod popupmenu;
mod state;
mod tabline;
#[allow(clippy::module_inception)]
mod ui;
mod wildmenu;
mod window;
pub use self::ui::UI;
|
use serde::{Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
pub struct HeaderDoc{
#[serde(rename = "_id")]
pub id: String,
#[serde(rename = "delete_key")]
pub delete_key: String,
#[serde(rename = "content_type")]
pub content_type: String,
#[serde(rename = "file_extension")]
pub file_extension: String,
#[serde(rename = "content_length")]
pub content_length: u32,
#[serde(rename = "uploaded_at")]
pub uploaded_at: u64,
#[serde(rename = "total_chunks")]
pub total_chunks: u32,
}
impl HeaderDoc {
pub fn new(id: String, delete_key: String, content_type: String, file_extension: String, content_length: u32, uploaded_at: u64, total_chunks: u32) -> Self {
HeaderDoc { id, delete_key, content_type, file_extension, content_length, uploaded_at, total_chunks }
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChunkDoc{
#[serde(rename = "parent_id")]
pub parent_id: String,
pub index: i32,
#[serde(with = "serde_bytes")]
pub data: Vec<u8>
}
impl ChunkDoc {
pub fn new(parent_id: String, index: i32, data: Vec<u8>) -> Self {
ChunkDoc { parent_id, index, data }
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Error {
error: String
}
impl Error {
pub fn new(error: String) -> Self {
Error { error }
}
} |
// Std
use std::env;
// Crates
use anyhow::{Context, Result};
use dotenv::dotenv;
use sqlx::sqlite::{SqlitePool, SqliteQueryAs};
use crate::{Entry, Project};
pub async fn setup_db(pool: &SqlitePool) -> Result<()> {
sqlx::query!(
"CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY,
start TEXT NOT NULL,
stop TEXT NOT NULL,
week_day TEXT NOT NULL,
code TEXT NOT NULL,
memo TEXT NOT NULL)"
)
.execute(pool)
.await?;
sqlx::query!(
"CREATE TABLE IF NOT EXISTS projects (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
code TEXT NOT NULL)"
)
.execute(pool)
.await?;
Ok(())
}
pub async fn setup_pool() -> Result<SqlitePool> {
dotenv().ok();
let db_url = env::var("TIMECARD_DB").context("TIMECARD_DB env var must be set!")?;
Ok(SqlitePool::new(&db_url).await?)
}
pub async fn read_entry(pool: &SqlitePool, id: i32) -> Result<Entry> {
Ok(
sqlx::query_as!(Entry, "select * from entries where id = ?", id)
.fetch_one(pool)
.await?,
)
}
pub async fn read_last_entry(pool: &SqlitePool) -> Result<Entry> {
Ok(
sqlx::query_as!(Entry, "select * from entries order by id desc limit 1")
.fetch_one(pool)
.await?,
)
}
pub async fn read_all_entries(pool: &SqlitePool) -> Result<Vec<Entry>> {
Ok(sqlx::query_as!(Entry, "select * from entries")
.fetch_all(pool)
.await?)
}
pub async fn read_entries_between(
pool: &SqlitePool,
start_date: String,
end_date: String,
) -> Result<Vec<Entry>> {
Ok(sqlx::query_as!(
Entry,
"SELECT * FROM entries WHERE start >= ? AND start <= ?",
start_date,
end_date
)
.fetch_all(pool)
.await?)
}
pub async fn write_entry(pool: &SqlitePool, entry: &Entry) -> Result<i32> {
sqlx::query!(
"INSERT INTO entries(start, stop, week_day, code, memo) VALUES(?, ?, ?, ?, ?)",
entry.start,
entry.stop,
entry.week_day,
entry.code,
entry.memo
)
.execute(pool)
.await?;
let rec: (i32,) = sqlx::query_as("SELECT last_insert_rowid()")
.fetch_one(pool)
.await?;
Ok(rec.0)
}
pub async fn update_entry(pool: &SqlitePool, entry: &Entry) -> Result<()> {
sqlx::query!(
"UPDATE entries SET start=?, stop=?, week_day=?, code=?, memo=?
WHERE id=?",
entry.start,
entry.stop,
entry.week_day,
entry.code,
entry.memo,
entry.id
)
.execute(pool)
.await?;
Ok(())
}
pub async fn delete_entry(pool: &SqlitePool, id: i32) -> Result<()> {
sqlx::query!("DELETE FROM entries WHERe id=?", id)
.execute(pool)
.await?;
Ok(())
}
pub async fn delete_last_entry(pool: &SqlitePool) -> Result<()> {
sqlx::query!("DELETE FROM entries WHERE id = (SELECT MAX(id) FROM entries LIMIT 1);")
.execute(pool)
.await?;
Ok(())
}
pub async fn read_project(pool: &SqlitePool, id: i32) -> Result<Project> {
Ok(
sqlx::query_as!(Project, "select * from projects where id = ?", id)
.fetch_one(pool)
.await?,
)
}
pub async fn read_all_projects(pool: &SqlitePool) -> Result<Vec<Project>> {
Ok(sqlx::query_as!(Project, "select * from projects")
.fetch_all(pool)
.await?)
}
pub async fn write_project(pool: &SqlitePool, project: &Project) -> Result<i32> {
sqlx::query!(
"INSERT INTO projects(name, code) VALUES(?, ?)",
project.name,
project.code,
)
.execute(pool)
.await?;
let rec: (i32,) = sqlx::query_as("SELECT last_insert_rowid()")
.fetch_one(pool)
.await?;
Ok(rec.0)
}
pub async fn update_project(pool: &SqlitePool, project: &Project) -> Result<()> {
sqlx::query!(
"UPDATE projects SET name=?, code=?
WHERE id=?",
project.name,
project.code,
project.id,
)
.execute(pool)
.await?;
Ok(())
}
pub async fn delete_project(pool: &SqlitePool, code: String) -> Result<()> {
sqlx::query!("DELETE FROM projects WHERe code=?", code)
.execute(pool)
.await?;
Ok(())
}
#[cfg(test)]
pub mod tests {
use super::*;
use chrono::{Datelike, Duration, Local, Timelike};
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
pub async fn setup_test_db() -> Result<SqlitePool> {
let db_name: String = random_name();
let pool = SqlitePool::new(&format!("sqlite:///tmp/{}_test.db", db_name)).await?;
Ok(pool)
}
pub async fn setup_entries_table(pool: &SqlitePool) -> Result<()> {
sqlx::query!(
"CREATE TABLE IF NOT EXISTS entries(
id INTEGER PRIMARY KEY,
start TEXT,
stop TEXT,
week_day TEXT,
code TEXT,
memo TEXT)",
)
.execute(pool)
.await?;
Ok(())
}
pub async fn setup_projects_table(pool: &SqlitePool) -> Result<()> {
sqlx::query!(
"CREATE TABLE IF NOT EXISTS projects(
id INTEGER PRIMARY KEY,
name TEXT,
code TEXT)",
)
.execute(pool)
.await?;
Ok(())
}
fn random_name() -> String {
thread_rng().sample_iter(&Alphanumeric).take(16).collect()
}
fn iso8601_to_db_format<T: Timelike + Datelike>(date: T) -> String {
format!(
"{}-{:02}-{:02} {:02}:{:02}:{:02}",
date.year(),
date.month(),
date.day(),
date.hour(),
date.minute(),
0
)
}
#[tokio::test]
async fn test_write_and_read_entry() -> Result<()> {
let pool = setup_test_db().await?;
setup_entries_table(&pool).await?;
let mut exp_entry = Entry {
id: None,
start: "0900".to_string(),
stop: "1000".to_string(),
week_day: "WED".to_string(),
code: "20-008".to_string(),
memo: "work, work, work".to_string(),
};
let id = write_entry(&pool, &exp_entry).await?;
exp_entry.id = Some(id);
let entry = read_entry(&pool, id).await?;
assert_eq!(entry, exp_entry);
Ok(())
}
#[tokio::test]
async fn test_read_last_entry() -> Result<()> {
let pool = setup_test_db().await?;
setup_entries_table(&pool).await?;
let entry = Entry {
id: None,
start: "0900".to_string(),
stop: "1000".to_string(),
week_day: "WED".to_string(),
code: "20-008".to_string(),
memo: "work, work, work".to_string(),
};
let mut last_entry = Entry {
id: None,
start: "1300".to_string(),
stop: "1530".to_string(),
week_day: "FRI".to_string(),
code: "20-000-00".to_string(),
memo: "work, work, work".to_string(),
};
write_entry(&pool, &entry).await?;
let id = write_entry(&pool, &last_entry).await?;
last_entry.id = Some(id);
let entry = read_last_entry(&pool).await?;
assert_eq!(entry, last_entry);
Ok(())
}
#[tokio::test]
async fn test_read_all_entries() -> Result<()> {
let pool = setup_test_db().await?;
setup_entries_table(&pool).await?;
let mut exp_entry1 = Entry {
id: None,
start: "0900".to_string(),
stop: "1000".to_string(),
week_day: "WED".to_string(),
code: "20-008".to_string(),
memo: "work, work, work".to_string(),
};
let mut exp_entry2 = Entry {
id: None,
start: "1200".to_string(),
stop: "1430".to_string(),
week_day: "FRI".to_string(),
code: "20-000".to_string(),
memo: "work, work, work".to_string(),
};
let id1 = write_entry(&pool, &exp_entry1).await?;
let id2 = write_entry(&pool, &exp_entry2).await?;
exp_entry1.id = Some(id1);
exp_entry2.id = Some(id2);
let entries = read_all_entries(&pool).await?;
assert_eq!(entries[0], exp_entry1);
assert_eq!(entries[1], exp_entry2);
Ok(())
}
#[tokio::test]
async fn test_read_entries_between() -> Result<()> {
let pool = setup_test_db().await?;
setup_entries_table(&pool).await?;
let code = "20-008".to_string();
let start_date = Local::now() - Duration::days(7);
let end_date = Local::now();
let invalid_date1 = Local::now() - Duration::days(8);
let invalid_weekday1 = invalid_date1.weekday().to_string();
let invalid_start1 = iso8601_to_db_format(invalid_date1);
let invalid_stop1 = iso8601_to_db_format(invalid_date1 + Duration::hours(2));
let invalid_date2 = Local::now() - Duration::days(11);
let invalid_weekday2 = invalid_date2.weekday().to_string();
let invalid_start2 = iso8601_to_db_format(invalid_date2);
let invalid_stop2 = iso8601_to_db_format(invalid_date2 + Duration::hours(2));
let valid_date1 = start_date + Duration::days(2);
let valid_weekday1 = valid_date1.weekday().to_string();
let valid_start1 = iso8601_to_db_format(valid_date1);
let valid_stop1 = iso8601_to_db_format(valid_date1 + Duration::hours(2));
let valid_date2 = start_date + Duration::days(5);
let valid_weekday2 = valid_date2.weekday().to_string();
let valid_start2 = iso8601_to_db_format(valid_date2);
let valid_stop2 = iso8601_to_db_format(valid_date2 + Duration::hours(2));
let mut invalid_entry1 = Entry {
id: None,
start: invalid_start1,
stop: invalid_stop1,
week_day: invalid_weekday1,
code: code.clone(),
memo: "work, work, work".to_string(),
};
let mut invalid_entry2 = Entry {
id: None,
start: invalid_start2,
stop: invalid_stop2,
week_day: invalid_weekday2,
code: code.clone(),
memo: "work, work, work".to_string(),
};
let mut valid_entry1 = Entry {
id: None,
start: valid_start1,
stop: valid_stop1,
week_day: valid_weekday1,
code: code.clone(),
memo: "work, work, work".to_string(),
};
let mut valid_entry2 = Entry {
id: None,
start: valid_start2,
stop: valid_stop2,
week_day: valid_weekday2,
code: code.clone(),
memo: "work, work, work".to_string(),
};
invalid_entry1.id = Some(write_entry(&pool, &invalid_entry1).await?);
invalid_entry2.id = Some(write_entry(&pool, &invalid_entry2).await?);
valid_entry1.id = Some(write_entry(&pool, &valid_entry1).await?);
valid_entry2.id = Some(write_entry(&pool, &valid_entry2).await?);
let entries =
read_entries_between(&pool, start_date.to_string(), end_date.to_string()).await?;
assert!(entries.len() == 2);
assert_eq!(entries[0], valid_entry1);
assert_eq!(entries[1], valid_entry2);
Ok(())
}
#[tokio::test]
async fn test_update_entry() -> Result<()> {
let pool = setup_test_db().await?;
setup_entries_table(&pool).await?;
let mut exp_entry = Entry {
id: None,
start: "0900".to_string(),
stop: "1000".to_string(),
week_day: "WED".to_string(),
code: "20-008".to_string(),
memo: "work, work, work".to_string(),
};
let id = write_entry(&pool, &exp_entry).await?;
exp_entry.id = Some(id);
let entry = read_entry(&pool, id).await?;
assert_eq!(entry.week_day, exp_entry.week_day);
exp_entry.week_day = "THU".to_string();
update_entry(&pool, &exp_entry).await?;
let entry = read_entry(&pool, id).await?;
assert_eq!(entry.week_day, exp_entry.week_day);
Ok(())
}
#[tokio::test]
async fn test_delete_entry() -> Result<()> {
let pool = setup_test_db().await?;
setup_entries_table(&pool).await?;
let mut exp_entry = Entry {
id: None,
start: "0900".to_string(),
stop: "1000".to_string(),
week_day: "WED".to_string(),
code: "20-008".to_string(),
memo: "work, work, work".to_string(),
};
let id = write_entry(&pool, &exp_entry).await?;
exp_entry.id = Some(id);
delete_entry(&pool, id).await?;
assert!(read_entry(&pool, id).await.is_err());
Ok(())
}
#[tokio::test]
async fn test_delete_last_entry() -> Result<()> {
let pool = setup_test_db().await?;
setup_entries_table(&pool).await?;
let entry = Entry {
id: None,
start: "0900".to_string(),
stop: "1000".to_string(),
week_day: "WED".to_string(),
code: "20-008".to_string(),
memo: "work, work, work".to_string(),
};
let last_entry = Entry {
id: None,
start: "1300".to_string(),
stop: "1530".to_string(),
week_day: "FRI".to_string(),
code: "20-000-00".to_string(),
memo: "work, work, work".to_string(),
};
let id1 = write_entry(&pool, &entry).await?;
let id2 = write_entry(&pool, &last_entry).await?;
delete_last_entry(&pool).await?;
assert!(read_entry(&pool, id1).await.is_ok());
assert!(read_entry(&pool, id2).await.is_err());
Ok(())
}
#[tokio::test]
async fn test_write_and_read_project() -> Result<()> {
let pool = setup_test_db().await?;
setup_projects_table(&pool).await?;
let mut exp_project = Project {
id: None,
name: "PPP".to_string(),
code: "20-008".to_string(),
};
let id = write_project(&pool, &exp_project).await?;
exp_project.id = Some(id);
let project = read_project(&pool, id).await?;
assert_eq!(project, exp_project);
Ok(())
}
#[tokio::test]
async fn test_read_all_projects() -> Result<()> {
let pool = setup_test_db().await?;
setup_projects_table(&pool).await?;
let mut exp_project1 = Project {
id: None,
name: "PPP".to_string(),
code: "20-008".to_string(),
};
let mut exp_project2 = Project {
id: None,
name: "General".to_string(),
code: "20-000-00".to_string(),
};
let id1 = write_project(&pool, &exp_project1).await?;
let id2 = write_project(&pool, &exp_project2).await?;
exp_project1.id = Some(id1);
exp_project2.id = Some(id2);
let projects = read_all_projects(&pool).await?;
assert_eq!(projects[0], exp_project1);
assert_eq!(projects[1], exp_project2);
Ok(())
}
#[tokio::test]
async fn test_update_project() -> Result<()> {
let pool = setup_test_db().await?;
setup_projects_table(&pool).await?;
let mut exp_project = Project {
id: None,
name: "PPP".to_string(),
code: "20-008".to_string(),
};
let id = write_project(&pool, &exp_project).await?;
exp_project.id = Some(id);
let project = read_project(&pool, id).await?;
assert_eq!(project.name, project.name);
exp_project.name = "New name".to_string();
update_project(&pool, &exp_project).await?;
let project = read_project(&pool, id).await?;
assert_eq!(project.name, exp_project.name);
Ok(())
}
#[tokio::test]
async fn test_delete_project() -> Result<()> {
let pool = setup_test_db().await?;
setup_projects_table(&pool).await?;
let name = String::from("PPP");
let code = String::from("20-008");
let mut exp_project = Project {
id: None,
name,
code: code.clone(),
};
let id = write_project(&pool, &exp_project).await?;
exp_project.id = Some(id);
delete_project(&pool, code).await?;
assert!(read_project(&pool, id).await.is_err());
Ok(())
}
}
|
extern crate exact_cover;
use exact_cover::{Problem};
use exact_cover::{Solver};
#[test]
fn solve_problem() {
let mut p = Problem::new();
p.add_action(0, &[0, 1, 2]);
p.add_action(1, &[3, 4]);
p.add_action(2, &[2, 4]);
let solver = Solver::new(p);
assert!(solver.first_solution().is_some());
}
|
pub fn server_ui(){
}
pub fn server_logic(){
}
|
use skiplist::skiplist::SkipList;
use crate::change::Change;
pub type Range = std::ops::Range<usize>;
/// Bitfield instance.
#[derive(Debug)]
pub struct Bitfield {
/// A [skiplist] instance.
///
/// [skiplist]: https://docs.rs/skiplist/
skiplist: SkipList<Range>,
}
impl Bitfield {
/// Create a new instance.
///
/// ## Panics
/// The page size must be a multiple of 2, and bigger than 0.
#[inline]
pub fn new() -> Self {
Bitfield {
skiplist: SkipList::new(),
}
}
/// Set or reset a bit.
/// Returns a `Change` indicating if the value was changed.
#[inline]
pub fn set_or_reset(&mut self, index: usize, value: bool) -> Change {
if value {
self.set(index)
}
else {
self.reset(index)
}
}
/// Set a bit.
/// Returns a `Change` indicating if the value was changed.
#[inline]
pub fn set(&mut self, index: usize) -> Change {
let mut iter = self.skiplist
.iter_mut()
// advance iterator to the relevant part
.skip_while(|range| range.start < index);
match iter.next() {
// inserting at end
None => match self.skiplist.back_mut() {
// skiplist is empty
None => {
self.skiplist
.push_back(Range { start: index, end: index + 1 });
Change::Changed
},
// skiplist is not empty
Some(range) =>
// inside the range
if range.contains(&index) {
Change::Unchanged
}
// at the end of the range
else if range.end == index {
range.end = range.end + 1;
Change::Changed
}
// after the range
else {
self.skiplist
.push_back(Range { start: index, end: index + 1});
Change::Changed
},
},
// inserting in middle or beginning (not at end)
Some(range) => {
// inside the range
if range.contains(&index) {
Change::Unchanged
}
// at the end of the range
else if range.end == index {
range.end = range.end + 1;
// check if we can merge with next range
if let Some(next) = iter.next() {
if range.end == next.start {
range.end = next.end;
if let Some(next_index) = iter.position(|_| true) {
self.skiplist
.remove(next_index - 1);
}
}
}
Change::Changed
}
// after the range
else {
match iter.next() {
// insert at end
None => {
self.skiplist
.push_back(Range { start: index, end: index + 1 });
Change::Changed
},
// inserting before a next range
Some(next) => {
if index + 1 == next.start {
next.start = index
}
else {
let new_range = Range { start: index, end: index + 1 };
match iter.position(|_| true) {
Some(next_index) => {
if next_index > 0 {
self.skiplist.insert(new_range, next_index - 1);
}
else {
self.skiplist.push_front(new_range);
}
},
None => {
self.skiplist.push_back(new_range);
},
}
}
Change::Changed
},
}
}
},
}
}
/// Reset a bit.
/// Returns a `Change` indicating if the value was changed.
#[inline]
pub fn reset(&mut self, _index: usize) -> Change {
unimplemented!()
}
/// Get the value of a bit.
#[inline]
pub fn get(&self, index: usize) -> bool {
let mut iter = self.skiplist
.iter()
.skip_while(|range| {
index < range.start
});
match iter.next() {
None => false,
Some(range) => range.contains(&index),
}
}
/// Get the amount of bits in the bitfield.
///
/// ## Examples
/// ```rust
/// # extern crate sparser_bitfield;
/// # use sparser_bitfield::Bitfield;
/// let mut bits = Bitfield::new();
/// assert_eq!(bits.len(), 0);
/// bits.set(0);
/// assert_eq!(bits.len(), 1);
/// bits.set(1);
/// assert_eq!(bits.len(), 2);
/// bits.reset(9);
/// assert_eq!(bits.len(), 2);
/// ```
#[inline]
pub fn len(&self) -> usize {
self.skiplist
.back()
.map_or(
0,
|last| last.end)
}
/// Returns `true` if no bits are stored.
///
/// ## Examples
/// ```rust
/// # extern crate sparser_bitfield;
/// # use sparser_bitfield::Bitfield;
/// let mut bits = Bitfield::new();
/// assert!(bits.is_empty());
/// bits.set(0);
/// assert!(!bits.is_empty());
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
self.skiplist
.is_empty()
}
}
|
use crate::vec3::{Vec3, Point3};
use crate::ray::{Ray};
pub struct Camera {
pub origin: Point3,
pub lower_left_corner: Point3,
pub horizontal: Vec3,
pub vertical: Vec3,
}
impl Camera {
pub fn new() -> Camera {
const ASPECT_RATIO: f64 = 16.0 / 9.0;
let viewport_height: f64 = 2.0;
let viewport_width: f64 = ASPECT_RATIO * viewport_height;
let focal_length: f64 = 1.0;
let origin: Point3 = Point3::new(0.0, 0.0, 0.0);
let horizontal: Vec3 = Vec3::new(viewport_width, 0.0, 0.0);
let vertical: Vec3 = Vec3::new(0.0, viewport_height, 0.0);
let lower_left_corner: Vec3 = &(&origin - &(&horizontal/2.0)) - &(&vertical/2.0) - Vec3::new(0.0, 0.0, focal_length);
Camera {
origin, horizontal, vertical, lower_left_corner
}
}
pub fn get_ray(&self, u: f64, v: f64) -> Ray {
let origin = &self.origin;
let lower_left_corner = &self.lower_left_corner;
let horizontal = &self.horizontal;
let vertical = &self.vertical;
// I know this sucks and could be avoided by defining &u + v and u + &v, but I want to practice understanding ownership
Ray::new(origin, &(lower_left_corner + &(&(horizontal * u) + &(&(vertical * v) - origin))))
}
} |
use metro::Event;
fn main() {
let events = [
Event::station(0, "Station 1"),
Event::station(0, "Station 2"),
Event::station(0, "Station 3"),
Event::SplitTrack(0, 1),
Event::station(1, "Station 4"),
Event::SplitTrack(1, 2),
Event::station(1, "Station 5"),
Event::station(2, "Station 6"),
Event::station(0, "Station 7"),
Event::station(1, "Station 8"),
Event::station(2, "Station 9"),
Event::SplitTrack(2, 3),
Event::SplitTrack(3, 4),
Event::station(5, "Station 10 (Detached)"),
Event::JoinTrack(4, 0),
Event::station(3, "Station 11"),
Event::StopTrack(1),
Event::station(0, "Station 12"),
Event::station(2, "Station 13"),
Event::station(3, "Station 14"),
Event::JoinTrack(3, 0),
Event::station(2, "Station 15"),
Event::StopTrack(2),
Event::station(0, "Station 16"),
];
let string = metro::to_string(&events).unwrap();
println!("{}", string);
}
|
use ComponentBitField;
use chunk::Chunk;
use component_group::ComponentGroup;
use component_group::UnsafeSendablePointer;
use entity::Entity;
use rayon::prelude::*;
use std::collections::HashMap;
use worker::Connection;
use worker::schema::GeneratedSchema;
use world::PartialEntity;
use world::WorldTime;
/// A view into the `World`'s entities, at a particular point in time.
///
/// This struct can be used to iterate over entities that match a particular
/// `ComponentGroup`.
///
/// This iteration can be done sequentially or in parallel.
pub struct Entities<'a, S: 'a + GeneratedSchema> {
entities: &'a mut EntityCollection<S>,
from_time: WorldTime,
}
impl<'a, S: 'static + GeneratedSchema> Entities<'a, S> {
#[doc(hidden)]
pub fn entities_from_time(
entities: &'a mut EntityCollection<S>,
from_time: &'a WorldTime,
) -> Entities<'a, S> {
Entities {
entities,
from_time: from_time.clone(),
}
}
/// Gets an iterator over all entities in the worker's local view which
/// match the `ComponentGroup` `G`.
///
/// ## Example
///
/// ```
/// for mut entity in entities.get::<MovementData>() {
/// entity.position.coords.x = rand::thread_rng().gen::<f64>();
///
/// println!("Entity of type {} has an x value of {}",
/// *entity.metadata.entity_type,
/// entity.position.coords.x);
/// }
/// ```
pub fn get<'b, G: 'b + ComponentGroup<'b, S>>(&'b mut self) -> Box<Iterator<Item = G> + 'b> {
let mut group_bit_field = S::ComponentBitField::new();
G::add_to_bit_field(&mut group_bit_field);
let from_time = &self.from_time;
Box::new(
self.entities
.get_chunks_with_components(group_bit_field)
.flat_map(move |chunk| G::get_iterator(chunk, from_time)),
)
}
/// Executes the given closure for each entity in the worker's local view
/// that matches the `ComponentGroup` `G`.
///
/// The closure will likely be run in parallel, however if it is more effective
/// to execute them in series, that will be done. Please see the [rayon](https://docs.rs/rayon/1.0.2/rayon)
/// documentation for more details.
///
/// ## Example
///
/// ```
/// entities.par_for_each::<MovementData, _>(|entity| {
/// entity.position.coords.x = rand::thread_rng().gen::<f64>();
/// });
/// ```
pub fn par_for_each<'b, G: 'b + ComponentGroup<'b, S>, F: Send + Sync>(&'b mut self, cb: F)
where
F: Fn(&mut G),
{
let mut group_bit_field = S::ComponentBitField::new();
G::add_to_bit_field(&mut group_bit_field);
let from_time = &self.from_time;
self.entities
.par_for_each_chunks_with_components(group_bit_field, |chunk| {
G::par_for_each(chunk, from_time, &cb);
})
}
}
pub struct EntityCollection<S: GeneratedSchema> {
chunks: Vec<Chunk<S>>,
map: HashMap<S::ComponentBitField, Vec<usize>>,
}
impl<S: 'static + GeneratedSchema> EntityCollection<S> {
pub fn new() -> EntityCollection<S> {
EntityCollection {
chunks: Vec::new(),
map: HashMap::new(),
}
}
pub fn replicate(&mut self, connection: &mut Connection) {
for chunk in self.chunks.iter_mut() {
chunk.replicate(connection);
}
}
pub fn cleanup_after_frame(&mut self) {
for chunk in self.chunks.iter_mut() {
chunk.cleanup_after_frame();
}
}
pub fn get_chunk_for_entity(&mut self, entity: &Entity<S>) -> &mut Chunk<S> {
&mut self.chunks[entity.chunk_index]
}
pub fn get_free_chunk(
&mut self,
bit_field: &S::ComponentBitField,
world_time: &mut WorldTime,
template_entity: &PartialEntity<S>,
) -> &mut Chunk<S> {
if let Some(indices) = self.map.get_mut(bit_field) {
for index in indices {
if (&self.chunks[*index]).has_space() {
return &mut self.chunks[*index];
}
}
}
// No space
self.add_chunk(bit_field, world_time, template_entity)
}
pub fn get_chunks_with_components<'a>(
&'a mut self,
component_bit_field: S::ComponentBitField,
) -> Box<Iterator<Item = &mut Chunk<S>> + 'a> {
let chunks: *mut Vec<Chunk<S>> = &mut self.chunks;
Box::new(
self.map
.iter_mut()
.filter(move |(bit_field, _)| bit_field.is_subset(&component_bit_field))
.flat_map(move |(_, chunk_indices)| {
chunk_indices
.iter()
.map(move |index| unsafe { &mut (*chunks)[*index] })
}),
)
}
pub fn par_for_each_chunks_with_components<'b, F: Send + Sync>(
&'b mut self,
component_bit_field: S::ComponentBitField,
cb: F,
) where
F: Fn(&'b mut Chunk<S>),
{
let chunks =
UnsafeSendablePointer::<Vec<Chunk<S>>>((&mut self.chunks) as *mut Vec<Chunk<S>>);
self.map
.par_iter_mut()
.filter(|(bit_field, _)| bit_field.is_subset(&component_bit_field))
.flat_map(|(_, chunk_indices)| {
chunk_indices.par_iter().map(|index| unsafe {
let chunks_ref = &mut *(chunks.0);
let chunk = &mut chunks_ref[*index];
UnsafeSendablePointer::<Chunk<S>>(chunk)
})
})
.for_each(|chunk_ptr| unsafe {
let chunk = &mut (*chunk_ptr.0);
cb(chunk);
});
}
fn add_chunk(
&mut self,
bit_field: &S::ComponentBitField,
world_time: &mut WorldTime,
template_entity: &PartialEntity<S>,
) -> &mut Chunk<S> {
let index = self.chunks.len();
let chunk = Chunk::new(index, world_time, template_entity);
self.chunks.push(chunk);
self.map.entry(*bit_field).or_insert(Vec::new()).push(index);
&mut self.chunks[index]
}
}
|
// Copyright 2020 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use common_meta_api::MetaApi;
use common_meta_api_vo::*;
use common_metatypes::MetaId;
use common_metatypes::MetaVersion;
use common_planners::CreateDatabasePlan;
use common_planners::CreateTablePlan;
use common_planners::DropDatabasePlan;
use common_planners::DropTablePlan;
use crate::action_declare;
use crate::store_do_action::StoreDoAction;
use crate::RequestFor;
use crate::StoreClient;
#[async_trait::async_trait]
impl MetaApi for StoreClient {
/// Create database call.
async fn create_database(
&self,
plan: CreateDatabasePlan,
) -> common_exception::Result<CreateDatabaseReply> {
self.do_action(CreateDatabaseAction { plan }).await
}
async fn get_database(&self, db: &str) -> common_exception::Result<DatabaseInfo> {
self.do_action(GetDatabaseAction { db: db.to_string() })
.await
}
/// Drop database call.
async fn drop_database(&self, plan: DropDatabasePlan) -> common_exception::Result<()> {
self.do_action(DropDatabaseAction { plan }).await
}
/// Create table call.
async fn create_table(
&self,
plan: CreateTablePlan,
) -> common_exception::Result<CreateTableReply> {
self.do_action(CreateTableAction { plan }).await
}
/// Drop table call.
async fn drop_table(&self, plan: DropTablePlan) -> common_exception::Result<()> {
self.do_action(DropTableAction { plan }).await
}
/// Get table.
async fn get_table(&self, db: &str, table: &str) -> common_exception::Result<TableInfo> {
self.do_action(GetTableAction {
db: db.to_string(),
table: table.to_string(),
})
.await
}
async fn get_table_by_id(
&self,
tbl_id: MetaId,
tbl_ver: Option<MetaVersion>,
) -> common_exception::Result<TableInfo> {
self.do_action(GetTableExtReq { tbl_id, tbl_ver }).await
}
async fn get_databases(&self) -> common_exception::Result<GetDatabasesReply> {
self.do_action(GetDatabasesAction {}).await
}
/// Get tables.
async fn get_tables(&self, db: &str) -> common_exception::Result<GetTablesReply> {
self.do_action(GetTablesAction { db: db.to_string() }).await
}
}
// == database actions ==
// - create database
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct CreateDatabaseAction {
pub plan: CreateDatabasePlan,
}
action_declare!(
CreateDatabaseAction,
CreateDatabaseReply,
StoreDoAction::CreateDatabase
);
// - get database
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct GetDatabaseAction {
pub db: String,
}
action_declare!(GetDatabaseAction, DatabaseInfo, StoreDoAction::GetDatabase);
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct DropDatabaseAction {
pub plan: DropDatabasePlan,
}
action_declare!(DropDatabaseAction, (), StoreDoAction::DropDatabase);
// == table actions ==
// - create table
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct CreateTableAction {
pub plan: CreateTablePlan,
}
action_declare!(
CreateTableAction,
CreateTableReply,
StoreDoAction::CreateTable
);
// - drop table
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct DropTableAction {
pub plan: DropTablePlan,
}
action_declare!(DropTableAction, (), StoreDoAction::DropTable);
// - get table
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct GetTableAction {
pub db: String,
pub table: String,
}
action_declare!(GetTableAction, TableInfo, StoreDoAction::GetTable);
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct GetTableExtReq {
pub tbl_id: MetaId,
pub tbl_ver: Option<MetaVersion>,
}
action_declare!(GetTableExtReq, TableInfo, StoreDoAction::GetTableExt);
// - get tables
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct GetTablesAction {
pub db: String,
}
action_declare!(GetTablesAction, GetTablesReply, StoreDoAction::GetTables);
// -get databases
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
pub struct GetDatabasesAction;
action_declare!(
GetDatabasesAction,
GetDatabasesReply,
StoreDoAction::GetDatabases
);
|
use super::VhdError;
use crate::prelude::*;
use rdisk_shared::AsByteSlice;
pub struct Bat {
entries: Vec<u32>,
}
pub const UNUSED_BLOCK_ID: u32 = 0xFFFF_FFFF;
impl Bat {
pub fn new(entries_count: u32) -> Self {
Self {
entries: vec![0xFF_FF_FF_FF; entries_count as usize],
}
}
pub fn read(stream: &impl ReadAt, offset: u64, entries_count: u32) -> Result<Self> {
let entries_count = entries_count as usize;
let mut table = Bat {
entries: Vec::with_capacity(entries_count),
};
let buffer = unsafe {
table.entries.set_len(entries_count);
core::slice::from_raw_parts_mut(table.entries.as_mut_ptr() as *mut u8, entries_count * 4)
};
stream.read_exact_at(offset, buffer)?;
for entry in &mut table.entries {
*entry = entry.swap_bytes();
}
Ok(table)
}
pub fn write(&self, stream: &impl WriteAt, offset: u64) -> Result<usize> {
let mut temp = self.entries.clone();
for entry in &mut temp {
*entry = entry.swap_bytes();
}
// The BAT is always extended to a sector boundary.
let size = math::round_up(self.entries.len() * 4, crate::sizes::SECTOR as usize);
let mut buffer = vec![0xFF_u8; size];
let data = unsafe { temp.as_byte_slice() };
buffer[..data.len()].copy_from_slice(data);
stream.write_all_at(offset, &buffer)?;
Ok(buffer.len())
}
pub fn block_id(&self, index: usize) -> Result<u32> {
match self.entries.get(index) {
Some(id) => Ok(*id),
None => Err(Error::from(VhdError::InvalidBlockIndex(index))),
}
}
/// The `index` MUST always be valid!
pub fn set_block_id(&mut self, index: usize, id: u32) {
self.entries[index] = id;
}
}
|
use bevy::input::mouse::MouseMotion;
use bevy::prelude::*;
use bevy::utils::HashSet;
use bevy::{input::{Axis, Input}};
#[derive(Default)]
pub struct GamepadLobby {
gamepads: HashSet<Gamepad>,
}
pub fn gamepad_connection_system(
mut lobby: ResMut<GamepadLobby>,
mut gamepad_event: EventReader<GamepadEvent>,
) {
for event in gamepad_event.iter() {
match &event {
GamepadEvent(gamepad, GamepadEventType::Connected) => {
lobby.gamepads.insert(*gamepad);
info!("{:?} Connected", gamepad);
}
GamepadEvent(gamepad, GamepadEventType::Disconnected) => {
lobby.gamepads.remove(gamepad);
info!("{:?} Disconnected", gamepad);
}
_ => (),
}
}
}
pub fn gamepad_system(
lobby: Res<GamepadLobby>,
_button_inputs: Res<Input<GamepadButton>>,
button_axes: Res<Axis<GamepadButton>>,
axes: Res<Axis<GamepadAxis>>,
mut camera_query: Query<&mut crate::camera::PlayerCamera, With<crate::camera::PlayerCamera>>
) {
for gamepad in lobby.gamepads.iter().cloned() {
match camera_query.single_mut() {
Ok(mut pc) => {
let pos_speed = pc.position_speed;
let rot_speed = pc.rotation_speed;
let mut xr = Quat::IDENTITY;
let mut yr = Quat::IDENTITY;
if let Some(right_stick_x) = axes.get(GamepadAxis(gamepad, GamepadAxisType::RightStickX)) {
if right_stick_x.abs() > 0.1 {
xr = Quat::from_rotation_y( - right_stick_x * rot_speed);
}
}
if let Some(right_stick_y) = axes.get(GamepadAxis(gamepad, GamepadAxisType::RightStickY)) {
if right_stick_y.abs() > 0.1 {
yr = Quat::from_rotation_x(right_stick_y * rot_speed);
}
}
let mut xp = 0f32;
if let Some(left_stick_x) = axes.get(GamepadAxis(gamepad, GamepadAxisType::LeftStickX)) {
if left_stick_x.abs() > 0.1 {
xp = left_stick_x * pos_speed;
}
}
let mut yp = 0f32;
if let Some(left_stick_y) = axes.get(GamepadAxis(gamepad, GamepadAxisType::LeftStickY)) {
if left_stick_y.abs() > 0.1 {
yp = left_stick_y * pos_speed;
}
}
let mut zp = 0.0f32;
if let Some(mut right_trigger) = button_axes.get(GamepadButton(gamepad, GamepadButtonType::RightTrigger2)) {
if right_trigger.abs() < 0.1 {
right_trigger = 0.0f32;
}
if let Some(mut left_trigger) = button_axes.get(GamepadButton(gamepad, GamepadButtonType::LeftTrigger2)) {
if left_trigger.abs() < 0.1 {
left_trigger = 0.0f32;
}
zp = (right_trigger - left_trigger) * pos_speed;
}
}
pc.rotation *= xr * yr;
let rotation = pc.rotation;
pc.position += rotation * Vec3::new(xp, zp, -yp);
}
Err(e) => {
println!("{:?}", e);
}
}
}
}
pub fn mouse_keyboard_system(
mut windows: ResMut<Windows>,
btn: Res<Input<MouseButton>>,
keyboard_input: Res<Input<KeyCode>>,
mut mouse_motion_events: EventReader<MouseMotion>,
mut camera_query: Query<&mut crate::camera::PlayerCamera, With<crate::camera::PlayerCamera>>
) {
let window = windows.get_primary_mut().unwrap();
if btn.just_pressed(MouseButton::Left) {
window.set_cursor_lock_mode(true);
window.set_cursor_visibility(false);
}
if window.cursor_locked() {
if keyboard_input.just_pressed(KeyCode::Escape) {
window.set_cursor_lock_mode(false);
window.set_cursor_visibility(true);
}
// match camera_query.single_mut() {
// Ok(mut pc) => {
// let pos_speed = pc.position_speed;
// let rot_speed = pc.rotation_speed;
// let mut xr = Quat::IDENTITY;
// let mut yr = Quat::IDENTITY;
// for event in mouse_motion_events.iter() {
// xr = Quat::from_rotation_x( -event.delta.y * 0.2 * rot_speed);
// yr = Quat::from_rotation_y( -event.delta.x * 0.2 * rot_speed);
// }
// let mut xp = 0f32;
// let mut yp = 0f32;
// let mut zp = 0.0f32;
// if keyboard_input.pressed(KeyCode::W) {
// yp = 0.50 * pos_speed;
// } else if keyboard_input.pressed(KeyCode::S) {
// yp = -0.50 * pos_speed;
// }
// if keyboard_input.pressed(KeyCode::D) {
// xp = 0.50 * pos_speed;
// } else if keyboard_input.pressed(KeyCode::A) {
// xp = -0.50 * pos_speed;
// }
// if keyboard_input.pressed(KeyCode::Space) {
// zp = 0.50 * pos_speed;
// } else if keyboard_input.pressed(KeyCode::LControl) {
// zp = -0.50 * pos_speed;
// }
// pc.rotation *= xr * yr;
// let rotation = pc.rotation;
// pc.position += rotation * Vec3::new(xp, zp, -yp);
// }
// Err(e) => {
// println!("{:?}", e);
// }
// }
}
} |
extern crate sdl2;
use sdl2::image::LoadTexture;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
mod vector;
mod display;
mod sprite;
pub fn main() -> Result<(), String> {
let mut display = display::Display::new("Salut", 800, 800);
let texture = display.load_texture("robot.jpg");
let mut sprite = sprite::Sprite::new(texture);
// let texture_creator = display.canvas.texture_creator();
// let texture = texture_creator.load_texture("robot.jpg")?;
while !display.should_close {
display.update();
// display.canvas.clear();
// display.canvas.copy(&texture, None, Rect::new(0,0, 128, 128))?;
display.present();
}
println!("Closing, bye");
Ok(())
}
|
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate rulinalg;
mod gaussian;
use rulinalg::matrix::{Matrix, BaseMatrix};
use rulinalg::utils;
use std::io;
fn main() {
env_logger::init().unwrap();
// Read count of train elements and count of features.
println!("Input count of train elements and count of features (e.g. 20 2):");
let mut properties = String::new();
io::stdin().read_line(&mut properties).expect("Error of reading properties of train data.");
let mut properties = properties.split_whitespace();
let count_elements: usize = properties.next()
.and_then(|x| x.trim().parse().ok())
.expect("Error of read count of elements of train data.");
let count_features: usize = properties.next()
.and_then(|x| x.trim().parse().ok())
.expect("Error of read count of features of train data.");
println!("Count of elements: {}; count of features: {}.",
count_elements,
count_features);
// Read train data.
println!("Input train data (e.g.\n1.332 234.2\n2.34 3\n4 5):");
let mut train_data: Vec<f64> = Vec::new();
for _ in 0..count_elements {
let mut buf = String::new();
io::stdin().read_line(&mut buf).expect("Error of reading train data.");
let mut buf = buf.split_whitespace();
while let Some(buf) = buf.next() {
train_data.push(buf.trim().parse().expect("Error of parsing train data."));
}
}
let train = Matrix::new(count_elements, count_features, train_data);
println!("Train data:\n{}", train);
// Read count of classes.
println!("Input count of classes:");
let mut count_classes = String::new();
io::stdin().read_line(&mut count_classes).expect("Error of reading count of classes.");
let count_classes: usize = count_classes.trim()
.parse()
.expect("Error of parsing count of classes.");
// Read data of class.
let mut class_data: Vec<f64> = Vec::new();
println!("Input classes data (e.g.\n1 0 0\n0 0 1\n0 1 0):");
for _ in 0..count_elements {
let mut buf = String::new();
io::stdin().read_line(&mut buf).expect("Error of reading class data.");
let mut buf = buf.split_whitespace();
while let Some(buf) = buf.next() {
class_data.push(buf.trim().parse().expect("Error of parsing class data."));
}
}
let class = Matrix::new(count_elements, count_classes, class_data);
println!("Class data:\n{}", class);
// Read count of targets.
println!("Input count of targets for predict:");
let mut count_targets = String::new();
io::stdin().read_line(&mut count_targets).expect("Error of reading count of target data.");
let count_elements_target: usize = count_targets.trim()
.parse()
.expect("Error of parsing count of elements of target data.");
// Read data of targets.
println!("Count of elements: {}; count of features: {}",
count_elements_target,
count_features);
println!("Input target data (e.g.\n1.332 234.2 3.4\n2.34 3 5.6\n4 5 0.0):");
let mut target_data: Vec<f64> = Vec::new();
for _ in 0..count_elements_target {
let mut buf = String::new();
io::stdin().read_line(&mut buf).expect("Error of reading target data.");
let mut buf = buf.split_whitespace();
while let Some(buf) = buf.next() {
target_data.push(buf.trim().parse().expect("Error of parsing target data."));
}
}
let targets = Matrix::new(count_elements_target, count_features, target_data);
println!("Targets data:\n{}", targets);
let class_count = class.cols();
let feature_count = train.cols();
let data_counts = train.rows() as f64;
let mut class_counts = vec![0; class_count];
let mut class_data: Vec<Vec<usize>> = vec![Vec::new(); class_count];
let mut g = gaussian::Gaussian::from_model(class_count, feature_count);
// Detect rows of the train data, that match specific class.
for (num_row, row) in class.iter_rows().enumerate() {
let mut class: i32 = -1;
for (num_col, c) in row.into_iter().enumerate() {
if *c == 1f64 {
class = num_col as i32;
}
}
// If class not detect then will be panic because index is -1.
class_data[class as usize].push(num_row);
class_counts[class as usize] += 1;
}
debug!("class_data: {:?}", class_data);
debug!("class_counts: {:?}", class_counts);
// Compute Gaussian function for every class and feature.
for (num_class, rows_of_inputs) in class_data.into_iter().enumerate() {
g.compute_gaussian(&train.select_rows(&rows_of_inputs), num_class);
}
debug!("Computed Gaussian: {:?}", g);
// Compute Class Prior Probability (P(c)) for classes.
let class_prior: Vec<f64> = class_counts.iter().map(|c| *c as f64 / data_counts).collect();
debug!("Class Prior Probability: {:?}", class_prior);
let result = g.compute_likehood_and_predict(&targets, &class_prior);
debug!("Result:\n{}", result);
for (target_num, row) in result.iter_rows().enumerate() {
println!("Class of target #{} is {}",
target_num,
utils::argmax(row).0 + 1);
}
}
#[cfg(test)]
mod tests {
use gaussian;
use rulinalg::matrix::{Matrix, BaseMatrix};
use rulinalg::utils;
#[test]
fn test_gaussian() {
let train = Matrix::new(6,
2,
vec![1.0, 1.1, 1.1, 0.9, 2.2, 2.3, 2.5, 2.7, 5.2, 4.3, 6.2, 7.3]);
let class = Matrix::new(6,
3,
vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 1.0, 0.0, 0.0, 1.0]);
let targets = Matrix::new(6,
2,
vec![1.0, 1.1, 1.1, 0.9, 2.2, 2.3, 2.5, 2.7, 5.2, 4.3, 6.2, 7.3]);
let class_count = class.cols();
let feature_count = train.cols();
let data_counts = train.rows() as f64;
let mut class_counts = vec![0; class_count];
let mut class_data: Vec<Vec<usize>> = vec![Vec::new(); class_count];
let mut g = gaussian::Gaussian::from_model(class_count, feature_count);
// Detect rows of the train data, that match specific class.
for (num_row, row) in class.iter_rows().enumerate() {
let mut class: i32 = -1;
for (num_col, c) in row.into_iter().enumerate() {
if *c == 1f64 {
class = num_col as i32;
}
}
// If class not detect then will be panic because index is -1.
class_data[class as usize].push(num_row);
class_counts[class as usize] += 1;
}
debug!("class_data: {:?}", class_data);
debug!("class_counts: {:?}", class_counts);
// Compute Gaussian function for every class and feature.
for (num_class, rows_of_inputs) in class_data.into_iter().enumerate() {
g.compute_gaussian(&train.select_rows(&rows_of_inputs), num_class);
}
debug!("Computed Gaussian: {:?}", g);
// Compute Class Prior Probability (P(c)) for classes.
let class_prior: Vec<f64> = class_counts.iter().map(|c| *c as f64 / data_counts).collect();
debug!("Class Prior Probability: {:?}", class_prior);
let result = g.compute_likehood_and_predict(&targets, &class_prior);
debug!("Result:\n{}", result);
let outputs: Vec<usize> = result.iter_rows().map(|x| utils::argmax(x).0).collect();
assert_eq!(outputs, [0, 0, 1, 1, 2, 2]);
}
}
|
mod flow_description;
mod utils;
mod work_description;
mod work_target;
pub use self::flow_description::*;
pub use self::utils::*;
pub use self::work_description::*;
pub use self::work_target::*;
|
// structs1.rs
// Address all the TODOs to make the tests pass!
// I AM DONE
struct ColorClassicStruct {
color_name: String,
color_type: String,
// TODO: Something goes here
}
struct ColorTupleStruct(/* TODO: Something goes here */ String, String);
#[derive(Debug)]
struct UnitStruct;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classic_c_structs() {
// TODO: Instantiate a classic c struct!
let c_name = String::from("green");
let c_type = String::from("#00FF00");
let green = ColorClassicStruct{
color_name: c_name,
color_type: c_type,
};
assert_eq!(green.color_name, "green");
assert_eq!(green.color_type, "#00FF00");
}
#[test]
fn tuple_structs() {
// TODO: Instantiate a tuple struct!
let color_name = String::from("green");
let color_type = String::from("#00FF00");
let green = ColorTupleStruct(color_name,color_type);
assert_eq!(green.0, "green");
assert_eq!(green.1, "#00FF00");
}
#[test]
fn unit_structs() {
// TODO: Instantiate a unit struct!
let unit_struct = UnitStruct;
let message = format!("{:?}s are fun!", unit_struct);
assert_eq!(message, "UnitStructs are fun!");
}
}
|
use crate::crypto::hash::H256;
use bigint::uint::U256;
const AVG_TX_SIZE: u32 = 168; // average size of a transaction (in Bytes)
const PROPOSER_TX_REF_HEADROOM: f32 = 10.0;
const SORTITION_PRECISION: u64 = std::u64::MAX;
const DECONFIRM_HEADROOM: f32 = 1.05;
// Chain IDs
pub const PROPOSER_INDEX: u16 = 0;
pub const TRANSACTION_INDEX: u16 = 1;
pub const FIRST_VOTER_INDEX: u16 = 2;
#[derive(Clone)]
pub struct BlockchainConfig {
/// Number of voter chains.
pub voter_chains: u16,
/// Maximum size of a transaction block in terms of transactions.
pub tx_txs: u32,
/// Maximum number of transaction block references in a proposer block.
pub proposer_tx_refs: u32,
/// Proposer block minng rate in blocks/sec.
pub proposer_mining_rate: f32,
/// Voter block minng rate for one voter chain, in blocks/sec.
pub voter_mining_rate: f32,
/// Transaction block minng rate in blocks/sec.
pub tx_mining_rate: f32,
/// Hash of proposer genesis block.
pub proposer_genesis: H256,
/// Hashes of voter genesis blocks.
pub voter_genesis: Vec<H256>,
total_mining_rate: f32,
total_sortition_width: U256,
proposer_sortition_width: U256,
voter_sortition_width: U256,
tx_sortition_width: U256,
pub adversary_ratio: f32,
log_epsilon: f32,
pub quantile_epsilon_confirm: f32,
pub quantile_epsilon_deconfirm: f32,
}
impl BlockchainConfig {
pub fn new(
voter_chains: u16,
tx_size: u32,
tx_throughput: u32,
proposer_rate: f32,
voter_rate: f32,
adv_ratio: f32,
log_epsilon: f32,
) -> Self {
let tx_txs = tx_size / AVG_TX_SIZE;
let proposer_genesis: H256 = {
let mut raw_hash: [u8; 32] = [0; 32];
let bytes = PROPOSER_INDEX.to_be_bytes();
raw_hash[30] = bytes[0];
raw_hash[31] = bytes[1];
raw_hash.into()
};
let voter_genesis_hashes: Vec<H256> = {
let mut v: Vec<H256> = vec![];
for chain_num in 0..voter_chains {
let mut raw_hash: [u8; 32] = [0; 32];
let bytes = (chain_num + FIRST_VOTER_INDEX).to_be_bytes();
raw_hash[30] = bytes[0];
raw_hash[31] = bytes[1];
v.push(raw_hash.into());
}
v
};
let tx_mining_rate: f32 = {
let tx_thruput: f32 = tx_throughput as f32;
let tx_txs: f32 = tx_txs as f32;
tx_thruput / tx_txs
};
let total_mining_rate: f32 =
proposer_rate + voter_rate * f32::from(voter_chains) + tx_mining_rate;
let proposer_width: u64 = {
let precise: f32 = (proposer_rate / total_mining_rate) * SORTITION_PRECISION as f32;
precise.ceil() as u64
};
let voter_width: u64 = {
let precise: f32 = (voter_rate / total_mining_rate) * SORTITION_PRECISION as f32;
precise.ceil() as u64
};
let tx_width: u64 =
SORTITION_PRECISION - proposer_width - voter_width * u64::from(voter_chains);
let log_epsilon_confirm = log_epsilon * DECONFIRM_HEADROOM;
let quantile_confirm: f32 = (2.0 * log_epsilon_confirm
- (2.0 * log_epsilon_confirm).ln()
- (2.0 * 3.141_692_6 as f32).ln())
.sqrt();
let quantile_deconfirm: f32 =
(2.0 * log_epsilon - (2.0 * log_epsilon).ln() - (2.0 * 3.141_692_6 as f32).ln()).sqrt();
Self {
voter_chains,
tx_txs,
proposer_tx_refs: (tx_mining_rate / proposer_rate * PROPOSER_TX_REF_HEADROOM).ceil()
as u32,
proposer_mining_rate: proposer_rate,
voter_mining_rate: voter_rate,
tx_mining_rate,
proposer_genesis,
voter_genesis: voter_genesis_hashes,
total_mining_rate,
total_sortition_width: SORTITION_PRECISION.into(),
proposer_sortition_width: proposer_width.into(),
voter_sortition_width: voter_width.into(),
tx_sortition_width: tx_width.into(),
adversary_ratio: adv_ratio,
log_epsilon,
quantile_epsilon_confirm: quantile_confirm,
quantile_epsilon_deconfirm: quantile_deconfirm,
}
}
pub fn sortition_hash(&self, hash: &H256, difficulty: &H256) -> Option<u16> {
let hash = U256::from_big_endian(hash.as_ref());
let difficulty = U256::from_big_endian(difficulty.as_ref());
let multiplier = difficulty / self.total_sortition_width;
let proposer_width = multiplier * self.proposer_sortition_width;
let transaction_width =
multiplier * (self.proposer_sortition_width + self.tx_sortition_width);
if hash < proposer_width {
Some(PROPOSER_INDEX)
} else if hash < (transaction_width + proposer_width) {
Some(TRANSACTION_INDEX)
} else if hash < difficulty {
let voter_idx = (hash - proposer_width - transaction_width) % self.voter_chains.into();
Some(voter_idx.as_u32() as u16 + FIRST_VOTER_INDEX)
} else {
None
}
}
}
lazy_static! {
pub static ref DEFAULT_DIFFICULTY: H256 = {
let raw: [u8; 32] = [255; 32];
raw.into()
};
}
|
// An attribute to hide warnings for unused code.
#![allow(dead_code)]
// enum with implicit discriminator (starts at 0)
enum Number {
Zero,
One,
Two,
Eleven = 'a',
}
fn main() {
// `enums` can be cast as integers.
println!("zero is {}", Number::Zero as i32);
println!("one is {}", Number::One as i32);
println!("Eleven is {}", Number::Eleven as i32);
}
|
use specs::prelude::*;
pub mod baseline_benches;
pub mod legion_benches;
pub mod legion_parallel;
pub mod specs_benches;
pub mod specs_parallel;
#[derive(Component, Copy, Clone, Debug, Default)]
#[storage(VecStorage)]
pub struct A(u32);
#[derive(Component, Copy, Clone, Debug, Default)]
#[storage(VecStorage)]
pub struct B(u32);
#[derive(Component, Copy, Clone, Debug, Default)]
#[storage(VecStorage)]
pub struct C(u32);
#[derive(Component, Copy, Clone, Debug, Default)]
#[storage(VecStorage)]
pub struct D(u32);
#[derive(Component, Copy, Clone, Debug, Default)]
#[storage(VecStorage)]
pub struct E(u32);
#[derive(Component, Copy, Clone, Debug, Default)]
#[storage(VecStorage)]
pub struct F(u32);
#[derive(Component, Copy, Clone, Debug, Default)]
#[storage(VecStorage)]
pub struct G(u32);
#[derive(Component, Copy, Clone, Debug, Default)]
#[storage(VecStorage)]
pub struct H(u32);
#[derive(Component, Copy, Clone, Debug, Default)]
#[storage(VecStorage)]
pub struct I(u32);
#[derive(Component, Copy, Clone, Debug, Default)]
#[storage(VecStorage)]
pub struct J(u32);
#[derive(Component, Copy, Clone, Debug, Default)]
#[storage(VecStorage)]
pub struct K(u32);
|
use std::collections::HashMap;
pub fn nucleotide_counts(s: &str) -> HashMap<char, usize> {
s.to_string().chars()
.fold("ATCG".chars().map(|c| (c, 0)).collect::<HashMap<_,_>>(),
|mut m, c| {
*m.entry(c).or_insert(0) += 1;
m
})
}
pub fn count(c: char, s: &str) -> usize {
*nucleotide_counts(s).get(&c).unwrap()
}
|
use azure_core::Context;
use azure_cosmos::prelude::*;
use futures::stream::StreamExt;
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
// First we retrieve the account name and master key from environment variables.
// We expect master keys (ie, not resource constrained)
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 database_name = std::env::args()
.nth(1)
.expect("please specify the database name as first command line parameter");
let user_name = std::env::args()
.nth(2)
.expect("please specify the user name as first command line parameter");
let authorization_token = AuthorizationToken::primary_from_base64(&master_key)?;
let client = CosmosClient::new(
account.clone(),
authorization_token,
CosmosOptions::default(),
);
let database_client = client.into_database_client(database_name);
let user_client = database_client.clone().into_user_client(user_name.clone());
let create_user_response = user_client
.create_user(Context::new(), CreateUserOptions::new())
.await?;
println!("create_user_response == {:#?}", create_user_response);
let users = Box::pin(database_client.list_users(Context::new(), ListUsersOptions::new()))
.next()
.await
.unwrap()?;
println!("list_users_response == {:#?}", users);
let get_user_response = user_client
.get_user(Context::new(), GetUserOptions::new())
.await?;
println!("get_user_response == {:#?}", get_user_response);
let new_user = format!("{}replaced", user_name);
let replace_user_response = user_client
.replace_user(Context::new(), &new_user, ReplaceUserOptions::new())
.await?;
println!("replace_user_response == {:#?}", replace_user_response);
let user_client = database_client.into_user_client(new_user);
let delete_user_response = user_client
.delete_user(Context::new(), DeleteUserOptions::new())
.await?;
println!("delete_user_response == {:#?}", delete_user_response);
Ok(())
}
|
use crate::{ArgMatchesExt, Result};
use clap::{App, Arg, ArgMatches};
use ronor::Sonos;
pub const NAME: &str = "get-playlist";
pub fn build() -> App<'static, 'static> {
App::new(NAME)
.about("Get list of tracks contained in a playlist")
.arg(crate::household_arg())
.arg(Arg::with_name("PLAYLIST").required(true))
}
pub fn run(sonos: &mut Sonos, matches: &ArgMatches) -> Result<()> {
let household = matches.household(sonos)?;
let playlist = matches.playlist(sonos, &household)?;
for track in sonos.get_playlist(&household, &playlist)?.tracks.iter() {
match &track.album {
Some(album) => println!("{} - {} - {}", &track.name, &track.artist, album),
None => println!("{} - {}", &track.name, &track.artist)
}
}
Ok(())
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - LPCOMP Configuration Register"]
pub config: CONFIG,
#[doc = "0x04 - LPCOMP Status Register"]
pub status: STATUS,
_reserved2: [u8; 8usize],
#[doc = "0x10 - LPCOMP Interrupt request register"]
pub intr: INTR,
#[doc = "0x14 - LPCOMP Interrupt set register"]
pub intr_set: INTR_SET,
#[doc = "0x18 - LPCOMP Interrupt request mask"]
pub intr_mask: INTR_MASK,
#[doc = "0x1c - LPCOMP Interrupt request masked"]
pub intr_masked: INTR_MASKED,
_reserved6: [u8; 32usize],
#[doc = "0x40 - Comparator 0 control Register"]
pub cmp0_ctrl: CMP0_CTRL,
_reserved7: [u8; 12usize],
#[doc = "0x50 - Comparator 0 switch control"]
pub cmp0_sw: CMP0_SW,
#[doc = "0x54 - Comparator 0 switch control clear"]
pub cmp0_sw_clear: CMP0_SW_CLEAR,
_reserved9: [u8; 40usize],
#[doc = "0x80 - Comparator 1 control Register"]
pub cmp1_ctrl: CMP1_CTRL,
_reserved10: [u8; 12usize],
#[doc = "0x90 - Comparator 1 switch control"]
pub cmp1_sw: CMP1_SW,
#[doc = "0x94 - Comparator 1 switch control clear"]
pub cmp1_sw_clear: CMP1_SW_CLEAR,
}
#[doc = "LPCOMP Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [config](config) module"]
pub type CONFIG = crate::Reg<u32, _CONFIG>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CONFIG;
#[doc = "`read()` method returns [config::R](config::R) reader structure"]
impl crate::Readable for CONFIG {}
#[doc = "`write(|w| ..)` method takes [config::W](config::W) writer structure"]
impl crate::Writable for CONFIG {}
#[doc = "LPCOMP Configuration Register"]
pub mod config;
#[doc = "LPCOMP Status Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [status](status) module"]
pub type STATUS = crate::Reg<u32, _STATUS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _STATUS;
#[doc = "`read()` method returns [status::R](status::R) reader structure"]
impl crate::Readable for STATUS {}
#[doc = "LPCOMP Status Register"]
pub mod status;
#[doc = "LPCOMP Interrupt request register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr](intr) module"]
pub type INTR = crate::Reg<u32, _INTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR;
#[doc = "`read()` method returns [intr::R](intr::R) reader structure"]
impl crate::Readable for INTR {}
#[doc = "`write(|w| ..)` method takes [intr::W](intr::W) writer structure"]
impl crate::Writable for INTR {}
#[doc = "LPCOMP Interrupt request register"]
pub mod intr;
#[doc = "LPCOMP Interrupt set register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_set](intr_set) module"]
pub type INTR_SET = crate::Reg<u32, _INTR_SET>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_SET;
#[doc = "`read()` method returns [intr_set::R](intr_set::R) reader structure"]
impl crate::Readable for INTR_SET {}
#[doc = "`write(|w| ..)` method takes [intr_set::W](intr_set::W) writer structure"]
impl crate::Writable for INTR_SET {}
#[doc = "LPCOMP Interrupt set register"]
pub mod intr_set;
#[doc = "LPCOMP Interrupt request mask\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_mask](intr_mask) module"]
pub type INTR_MASK = crate::Reg<u32, _INTR_MASK>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_MASK;
#[doc = "`read()` method returns [intr_mask::R](intr_mask::R) reader structure"]
impl crate::Readable for INTR_MASK {}
#[doc = "`write(|w| ..)` method takes [intr_mask::W](intr_mask::W) writer structure"]
impl crate::Writable for INTR_MASK {}
#[doc = "LPCOMP Interrupt request mask"]
pub mod intr_mask;
#[doc = "LPCOMP Interrupt request masked\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_masked](intr_masked) module"]
pub type INTR_MASKED = crate::Reg<u32, _INTR_MASKED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_MASKED;
#[doc = "`read()` method returns [intr_masked::R](intr_masked::R) reader structure"]
impl crate::Readable for INTR_MASKED {}
#[doc = "LPCOMP Interrupt request masked"]
pub mod intr_masked;
#[doc = "Comparator 0 control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cmp0_ctrl](cmp0_ctrl) module"]
pub type CMP0_CTRL = crate::Reg<u32, _CMP0_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CMP0_CTRL;
#[doc = "`read()` method returns [cmp0_ctrl::R](cmp0_ctrl::R) reader structure"]
impl crate::Readable for CMP0_CTRL {}
#[doc = "`write(|w| ..)` method takes [cmp0_ctrl::W](cmp0_ctrl::W) writer structure"]
impl crate::Writable for CMP0_CTRL {}
#[doc = "Comparator 0 control Register"]
pub mod cmp0_ctrl;
#[doc = "Comparator 0 switch control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cmp0_sw](cmp0_sw) module"]
pub type CMP0_SW = crate::Reg<u32, _CMP0_SW>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CMP0_SW;
#[doc = "`read()` method returns [cmp0_sw::R](cmp0_sw::R) reader structure"]
impl crate::Readable for CMP0_SW {}
#[doc = "`write(|w| ..)` method takes [cmp0_sw::W](cmp0_sw::W) writer structure"]
impl crate::Writable for CMP0_SW {}
#[doc = "Comparator 0 switch control"]
pub mod cmp0_sw;
#[doc = "Comparator 0 switch control clear\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cmp0_sw_clear](cmp0_sw_clear) module"]
pub type CMP0_SW_CLEAR = crate::Reg<u32, _CMP0_SW_CLEAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CMP0_SW_CLEAR;
#[doc = "`read()` method returns [cmp0_sw_clear::R](cmp0_sw_clear::R) reader structure"]
impl crate::Readable for CMP0_SW_CLEAR {}
#[doc = "`write(|w| ..)` method takes [cmp0_sw_clear::W](cmp0_sw_clear::W) writer structure"]
impl crate::Writable for CMP0_SW_CLEAR {}
#[doc = "Comparator 0 switch control clear"]
pub mod cmp0_sw_clear;
#[doc = "Comparator 1 control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cmp1_ctrl](cmp1_ctrl) module"]
pub type CMP1_CTRL = crate::Reg<u32, _CMP1_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CMP1_CTRL;
#[doc = "`read()` method returns [cmp1_ctrl::R](cmp1_ctrl::R) reader structure"]
impl crate::Readable for CMP1_CTRL {}
#[doc = "`write(|w| ..)` method takes [cmp1_ctrl::W](cmp1_ctrl::W) writer structure"]
impl crate::Writable for CMP1_CTRL {}
#[doc = "Comparator 1 control Register"]
pub mod cmp1_ctrl;
#[doc = "Comparator 1 switch control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cmp1_sw](cmp1_sw) module"]
pub type CMP1_SW = crate::Reg<u32, _CMP1_SW>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CMP1_SW;
#[doc = "`read()` method returns [cmp1_sw::R](cmp1_sw::R) reader structure"]
impl crate::Readable for CMP1_SW {}
#[doc = "`write(|w| ..)` method takes [cmp1_sw::W](cmp1_sw::W) writer structure"]
impl crate::Writable for CMP1_SW {}
#[doc = "Comparator 1 switch control"]
pub mod cmp1_sw;
#[doc = "Comparator 1 switch control clear\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cmp1_sw_clear](cmp1_sw_clear) module"]
pub type CMP1_SW_CLEAR = crate::Reg<u32, _CMP1_SW_CLEAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CMP1_SW_CLEAR;
#[doc = "`read()` method returns [cmp1_sw_clear::R](cmp1_sw_clear::R) reader structure"]
impl crate::Readable for CMP1_SW_CLEAR {}
#[doc = "`write(|w| ..)` method takes [cmp1_sw_clear::W](cmp1_sw_clear::W) writer structure"]
impl crate::Writable for CMP1_SW_CLEAR {}
#[doc = "Comparator 1 switch control clear"]
pub mod cmp1_sw_clear;
|
use piston_window::{rectangle, Context, G2d};
use piston_window::types::Color;
const BLOCK_SIZE: f64 = 25.0;
pub fn to_coord(game_coord: i32) -> f64 {
game_coord as f64 * BLOCK_SIZE
}
pub fn draw_block(c: Color, game_x: i32, game_y: i32, con: &Context, g: &mut G2d) {
let gui_x = to_coord(game_x);
let gui_y = to_coord(game_y);
rectangle(c, [gui_x, gui_y, BLOCK_SIZE, BLOCK_SIZE], con.transform, g);
}
pub fn draw_rectangle(c: Color, game_x: i32, game_y: i32, game_w: i32, game_h: i32, con: &Context, g: &mut G2d) {
let gui_x = to_coord(game_x);
let gui_y = to_coord(game_y);
rectangle(c,
[gui_x, gui_y, BLOCK_SIZE * game_w as f64, BLOCK_SIZE * game_h as f64],
con.transform,
g);
}
|
//! Cargo registry macos keychain credential process.
use cargo_credential::{Credential, Error};
use security_framework::os::macos::keychain::SecKeychain;
struct MacKeychain;
/// The account name is not used.
const ACCOUNT: &'static str = "";
fn registry(registry_name: &str) -> String {
format!("cargo-registry:{}", registry_name)
}
impl Credential for MacKeychain {
fn name(&self) -> &'static str {
env!("CARGO_PKG_NAME")
}
fn get(&self, registry_name: &str, _api_url: &str) -> Result<String, Error> {
let keychain = SecKeychain::default().unwrap();
let service_name = registry(registry_name);
let (pass, _item) = keychain.find_generic_password(&service_name, ACCOUNT)?;
String::from_utf8(pass.as_ref().to_vec())
.map_err(|_| "failed to convert token to UTF8".into())
}
fn store(&self, registry_name: &str, _api_url: &str, token: &str) -> Result<(), Error> {
let keychain = SecKeychain::default().unwrap();
let service_name = registry(registry_name);
if let Ok((_pass, mut item)) = keychain.find_generic_password(&service_name, ACCOUNT) {
item.set_password(token.as_bytes())?;
} else {
keychain.add_generic_password(&service_name, ACCOUNT, token.as_bytes())?;
}
Ok(())
}
fn erase(&self, registry_name: &str, _api_url: &str) -> Result<(), Error> {
let keychain = SecKeychain::default().unwrap();
let service_name = registry(registry_name);
let (_pass, item) = keychain.find_generic_password(&service_name, ACCOUNT)?;
item.delete();
Ok(())
}
}
fn main() {
cargo_credential::main(MacKeychain);
}
|
#![recursion_limit = "256"]
#[macro_use]
extern crate quote;
extern crate crc16;
extern crate xml;
mod binder;
mod parser;
mod util;
use crate::util::to_module_name;
use std::env;
use std::fs::{read_dir, File};
use std::path::{Path, PathBuf};
use std::process::Command;
pub fn main() {
let src_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
// Update and init submodule
match Command::new("git")
.arg("submodule")
.arg("update")
.arg("--init")
.current_dir(&src_dir)
.status()
{
Ok(_) => {}
Err(error) => eprintln!("{}", error),
}
// find & apply patches to XML definitions to avoid crashes
let mut patch_dir = src_dir.to_path_buf();
patch_dir.push("build/patches");
let mut mavlink_dir = src_dir.to_path_buf();
mavlink_dir.push("mavlink");
if let Ok(dir) = read_dir(patch_dir) {
for entry in dir {
if let Ok(entry) = entry {
match Command::new("git")
.arg("apply")
.arg(entry.path().as_os_str())
.current_dir(&mavlink_dir)
.status()
{
Ok(_) => (),
Err(error) => eprintln!("{}", error),
}
}
}
}
let mut definitions_dir = src_dir.to_path_buf();
definitions_dir.push("mavlink/message_definitions/v1.0");
let out_dir = env::var("OUT_DIR").unwrap();
let mut modules = vec![];
for entry in read_dir(&definitions_dir).expect("could not read definitions directory") {
let entry = entry.expect("could not read directory entry");
let definition_file = entry.file_name();
let module_name = to_module_name(&definition_file);
let mut definition_rs = PathBuf::from(&module_name);
definition_rs.set_extension("rs");
modules.push(module_name);
let in_path = Path::new(&definitions_dir).join(&definition_file);
let mut inf = File::open(&in_path).unwrap();
let dest_path = Path::new(&out_dir).join(definition_rs);
let mut outf = File::create(&dest_path).unwrap();
// generate code
parser::generate(&mut inf, &mut outf);
// format code
match Command::new("rustfmt")
.arg(dest_path.as_os_str())
.current_dir(&out_dir)
.status()
{
Ok(_) => (),
Err(error) => eprintln!("{}", error),
}
// Re-run build if common.xml changes
println!("cargo:rerun-if-changed={}", entry.path().to_string_lossy());
}
// output mod.rs
{
let dest_path = Path::new(&out_dir).join("mod.rs");
let mut outf = File::create(&dest_path).unwrap();
// generate code
binder::generate(modules, &mut outf);
// format code
match Command::new("rustfmt")
.arg(dest_path.as_os_str())
.current_dir(&out_dir)
.status()
{
Ok(_) => (),
Err(error) => eprintln!("{}", error),
}
}
}
|
use actix_files::NamedFile;
use actix_web::{error, web, App, HttpRequest, HttpServer, Result};
use std::path::PathBuf;
async fn index() -> Result<NamedFile> {
find_file("index.html").await
}
async fn static_file(name: HttpRequest) -> Result<NamedFile> {
find_file(&name.path()[1..]).await
}
async fn find_file(path: &str) -> Result<NamedFile> {
let mut final_path = "frontend".parse::<PathBuf>().unwrap();
final_path.push(path.parse::<PathBuf>().unwrap());
match NamedFile::open(&final_path) {
Ok(x) => Ok(x),
Err(x) => {
println!("Error finding file: {}", final_path.display());
println!("{}", x);
Err(error::ErrorNotFound("File Not Found"))
}
}
}
async fn serve(address: &str) {
HttpServer::new(|| {
App::new()
.route("/", web::get().to(index))
.route("/scripts/.*", web::get().to(static_file))
.route("/styles/.*", web::get().to(static_file))
.route("/dist/.*", web::get().to(static_file))
})
.bind(address)
.unwrap()
.run()
.await
.unwrap();
}
#[actix_rt::main]
async fn main() {
let address = "127.0.0.1:8808";
let server = serve(address);
println!("Listening on {a}", a = address);
server.await
}
|
#![allow(non_camel_case_types)]
use libc::{c_char, c_int, c_void};
use std::ffi::{CStr, CString};
pub const FLB_ERROR: u32 = 0;
pub const FLB_OK: u32 = 1;
pub const FLB_RETRY: u32 = 2;
pub const FLB_PROXY_OUTPUT_PLUGIN: u32 = 2;
pub const FLB_PROXY_GOLANG: u32 = 11;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct flb_plugin_proxy_def {
pub type_: c_int,
pub proxy: c_int,
pub flags: c_int,
pub name: *mut c_char,
pub description: *mut c_char,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
struct flb_plugin_proxy_context {
remote_context: *mut c_void,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct flb_output_instance {
_address: u8,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct flb_api {
pub output_get_property: ::std::option::Option<
unsafe extern "C" fn(arg1: *mut c_char, arg2: *mut c_void) -> *mut c_char,
>,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct flbgo_output_plugin {
__: *mut c_void,
pub api: *mut flb_api,
pub o_ins: *mut flb_output_instance,
context: *mut flb_plugin_proxy_context,
}
pub type FLBPluginProxyDef = flb_plugin_proxy_def;
pub type FLBOutPlugin = flbgo_output_plugin;
/// Basic plugin information
#[derive(Default)]
pub struct PluginInfo {
/// Plugin's name
pub name: String,
/// Plugin's description
pub description: String,
}
/// Fluent-bit error definitions
pub enum FLBError {
/// The data have been processed normally.
FLB_ERROR,
/// A recoverable error have ocurred, the engine can try to flush the records/data later.
FLB_RETRY,
}
/// Custom result for any plugin's operation
pub type FLBResult = Result<(), FLBError>;
impl From<FLBError> for i32 {
fn from(error: FLBError) -> Self {
match error {
FLBError::FLB_ERROR => 0,
FLBError::FLB_RETRY => 2,
}
}
}
/// Trait which defines the functions that should be implemented by any rust plugin
pub trait FLBPluginMethods {
/// A plugin register method
///
/// When the FLBPluginInit is triggered by Fluent Bit, a plugin context
/// is passed and the next step is to invoke this FLBPluginRegister() function
/// to fill the required information: name and
/// description.
/// # Arguments
/// * `info` A mutable reference to a PluginInfo struct where the plugin's name and description will be filled
/// # Returns
/// If the operation was successful an Ok(()) is returned otherwise FLBError
fn plugin_register(&mut self, info: &mut PluginInfo) -> FLBResult;
/// Before the engine starts, it initialize all plugins that were requested to start
/// Useful for initializing any data structure that would be used for this plugin during the processing
/// # Arguments
/// * `plugin` A reference to the inner plugin representation which could be used for getting
/// any parameter passed in to the plugin
/// # Returns
/// If the operation was successful an Ok(()) is returned otherwise FLBError
fn plugin_init(&mut self, plugin: &FLBPlugin) -> FLBResult;
/// Upon flush time, when Fluent Bit want's to flush it buffers, the runtime flush callback will be triggered.
/// The callback will receive a raw buffer of msgpack data.
/// The passed data is a bytes buffer which could be processed in anyway. A there are differents crates that would be helpful
/// in the ecosystem, such as
/// [`rmp`](https://crates.io/crates/rmp), [`msgpack`](https://crates.io/crates/msgpack)
/// or you can implement a custom parser by using one of most parser libraries in the rust ecosystem.
/// # Arguments
/// * `data` A byte buffer with the message in a MsgPack format
/// * `tag` A str containing the tag from fluent-bit
/// # Returns
/// If the operation was successful an Ok(()) is returned otherwise FLBError
fn plugin_flush(&mut self, data: &[u8], tag: &str) -> FLBResult;
/// When Fluent Bit will stop using the instance of the plugin, it will trigger the exit callback.
/// # Returns
/// If the operation was successful an Ok(()) is returned otherwise FLBError
fn plugin_exit(&mut self) -> FLBResult;
}
/// Internal plugin pointer
///
/// This is passed in during the init function to
/// get any parameter that is required during the plugin's
/// initialization
pub struct FLBPlugin {
pub(crate) plugin_ptr: *mut libc::c_void,
}
impl FLBPlugin {
// Creates a new plugin ptr instance
//
// This method should not be called
// by the user.
pub fn new(ptr: *mut c_void) -> Self {
Self { plugin_ptr: ptr }
}
/// Request the value of a param named *key*
/// # Returns
/// Returns and option if succeeded
/// or and error if the key is not valid.
pub fn config_param<K: AsRef<str>>(&self, key: K) -> Result<Option<String>, ()> {
unsafe {
let p = self.plugin_ptr as *mut flbgo_output_plugin;
let key = CString::new(key.as_ref()).map_err(|_| ())?;
let param = if let Some(f) = (*(*p).api).output_get_property {
f(key.as_ptr() as _, (*p).o_ins as _)
} else {
return Ok(None);
};
if !param.is_null() {
let result = CStr::from_ptr(param).to_str().map_err(|_| ())?;
return Ok(Some(result.to_owned()));
}
Ok(None)
}
}
}
/// This macro will generate the needed boilerplate for output plugins
///
/// Only one plugin instance is supported, later multi-instance plugins support would be added
#[macro_export]
macro_rules! create_boilerplate{
($e:expr) => {
use std::panic::{self, AssertUnwindSafe};
use libc::{c_char, c_int, c_void};
use std::ffi::{CStr, CString, NulError};
use std::slice;
use std::sync::{Mutex};
use std::cell::RefCell;
#[macro_use]
extern crate lazy_static;
lazy_static! {
static ref handler: Mutex<Box<dyn FLBPluginMethods + Send>> = Mutex::new(Box::new($e));
}
// Catch panics
fn catch<F: FnOnce() -> c_int>(f: F) -> Option<c_int> {
match panic::catch_unwind(AssertUnwindSafe(f)) {
Ok(ret) => Some(ret),
Err(_) => {
exit(std::line!(), std::file!());
None
}
}
}
fn exit(line: u32, file: &str) {
eprintln!("catching panic generated at: {} in file: {}", line, file);
eprintln!("exiting process!");
std::process::exit(-1);
}
#[no_mangle]
pub extern fn FLBPluginRegister( ptr: *mut c_void) -> c_int {
catch(|| unsafe {
let p = &mut *(ptr as *mut FLBPluginProxyDef);
p.type_ = FLB_PROXY_OUTPUT_PLUGIN as c_int;
p.proxy = FLB_PROXY_GOLANG as c_int;
p.flags = 0;
let mut plugin_info = PluginInfo::default();
match handler.lock().unwrap().plugin_register(&mut plugin_info){
Ok(()) => {
if let Ok(cname) = CString::new(plugin_info.name.as_bytes()) {
p.name = cname.into_raw() as *mut _;
} else {
return FLB_ERROR as c_int;
}
if let Ok(d) = CString::new(plugin_info.description.as_bytes()) {
p.description = d.into_raw() as *mut _;
} else {
return FLB_ERROR as c_int;
}
},
Err(e) => return i32::from(e) as c_int,
}
FLB_OK as c_int
}).unwrap()
}
#[no_mangle]
pub extern fn FLBPluginInit(ptr: *mut c_void) -> c_int {
let plugin = FLBPlugin::new(ptr);
catch(|| {
if let Err(e) = handler.lock().unwrap().plugin_init(&plugin){
return i32::from(e) as c_int;
}
FLB_OK as c_int
}).unwrap()
}
#[no_mangle]
pub extern fn FLBPluginFlush(data: *mut c_void, length: c_int, tag: *const c_char) -> c_int {
catch( || unsafe {
let bytes = slice::from_raw_parts(data as *const _, length as usize);
let tag = match CStr::from_ptr(tag).to_str() {
Ok(str) => str,
_ => return FLB_ERROR as c_int,
};
if let Err(e) = handler.lock().unwrap().plugin_flush(bytes, tag){
return i32::from(e) as c_int;
}
FLB_OK as c_int
}).unwrap()
}
#[no_mangle]
pub extern fn FLBPluginExit() -> c_int {
catch( || {
if let Err(e) = handler.lock().unwrap().plugin_exit(){
return i32::from(e) as c_int;
}
FLB_OK as c_int
}).unwrap()
}
#[no_mangle]
pub extern fn FLBPluginUnregister( ptr: *mut c_void) -> c_int {
catch(|| unsafe {
let p = &mut *(ptr as *mut FLBPluginProxyDef);
p.type_ = FLB_PROXY_OUTPUT_PLUGIN as c_int;
p.proxy = FLB_PROXY_GOLANG as c_int;
p.flags = 0;
let _ = CString::from_raw(p.name);
let _ = CString::from_raw(p.description);
FLB_OK as c_int
}).unwrap()
}
}
}
|
// Copyright 2013-2017, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use Cancellable;
use Error;
use ffi;
use glib::object::IsA;
use glib::translate::*;
use glib::Priority;
use glib_ffi;
use gobject_ffi;
use std::mem;
use std::ptr;
use InputStream;
pub trait InputStreamExtManual {
fn read<'a, B: AsMut<[u8]>, P: Into<Option<&'a Cancellable>>>(&self, buffer: B, cancellable: P) -> Result<usize, Error>;
fn read_all<'a, B: AsMut<[u8]>, P: Into<Option<&'a Cancellable>>>(&self, buffer: B, cancellable: P) -> Result<(usize, Option<Error>), Error>;
#[cfg(any(feature = "v2_44", feature = "dox"))]
fn read_all_async<'a, B: AsMut<[u8]> + Send + 'static, P: Into<Option<&'a Cancellable>>, Q: FnOnce(Result<(B, usize, Option<Error>), (B, Error)>) + Send + 'static>(&self, buffer: B, io_priority: Priority, cancellable: P, callback: Q);
fn read_async<'a, B: AsMut<[u8]> + Send + 'static, P: Into<Option<&'a Cancellable>>, Q: FnOnce(Result<(B, usize), (B, Error)>) + Send + 'static>(&self, buffer: B, io_priority: Priority, cancellable: P, callback: Q);
}
impl<O: IsA<InputStream>> InputStreamExtManual for O {
fn read<'a, B: AsMut<[u8]>, P: Into<Option<&'a Cancellable>>>(&self, mut buffer: B, cancellable: P) -> Result<usize, Error> {
let cancellable = cancellable.into();
let cancellable = cancellable.to_glib_none();
let buffer = buffer.as_mut();
let buffer_ptr = buffer.as_mut_ptr();
let count = buffer.len();
unsafe {
let mut error = ptr::null_mut();
let ret = ffi::g_input_stream_read(self.to_glib_none().0, buffer_ptr, count, cancellable.0, &mut error);
if error.is_null() {
Ok(ret as usize)
} else {
Err(from_glib_full(error))
}
}
}
fn read_all<'a, B: AsMut<[u8]>, P: Into<Option<&'a Cancellable>>>(&self, mut buffer: B, cancellable: P) -> Result<(usize, Option<Error>), Error> {
let cancellable = cancellable.into();
let cancellable = cancellable.to_glib_none();
let buffer = buffer.as_mut();
let buffer_ptr = buffer.as_mut_ptr();
let count = buffer.len();
unsafe {
let mut bytes_read = mem::uninitialized();
let mut error = ptr::null_mut();
let _ = ffi::g_input_stream_read_all(self.to_glib_none().0, buffer_ptr, count, &mut bytes_read, cancellable.0, &mut error);
if error.is_null() {
Ok((bytes_read, None))
} else if bytes_read != 0 {
Ok((bytes_read, Some(from_glib_full(error))))
} else {
Err( from_glib_full(error))
}
}
}
#[cfg(any(feature = "v2_44", feature = "dox"))]
fn read_all_async<'a, B: AsMut<[u8]> + Send + 'static, P: Into<Option<&'a Cancellable>>, Q: FnOnce(Result<(B, usize, Option<Error>), (B, Error)>) + Send + 'static>(&self, buffer: B, io_priority: Priority, cancellable: P, callback: Q) {
let cancellable = cancellable.into();
let cancellable = cancellable.to_glib_none();
let mut buffer: Box<B> = Box::new(buffer);
let (count, buffer_ptr) = {
let slice = (*buffer).as_mut();
(slice.len(), slice.as_mut_ptr())
};
let user_data: Box<Option<(Box<Q>, Box<B>)>> = Box::new(Some((Box::new(callback), buffer)));
unsafe extern "C" fn read_all_async_trampoline<B: AsMut<[u8]> + Send + 'static, Q: FnOnce(Result<(B, usize, Option<Error>), (B, Error)>) + Send + 'static>(_source_object: *mut gobject_ffi::GObject, res: *mut ffi::GAsyncResult, user_data: glib_ffi::gpointer)
{
callback_guard!();
let mut user_data: Box<Option<(Box<Q>, Box<B>)>> = Box::from_raw(user_data as *mut _);
let (callback, buffer) = user_data.take().unwrap();
let buffer = *buffer;
let mut error = ptr::null_mut();
let mut bytes_read = mem::uninitialized();
let _ = ffi::g_input_stream_read_all_finish(_source_object as *mut _, res, &mut bytes_read, &mut error);
let result = if error.is_null() {
Ok((buffer, bytes_read, None))
} else if bytes_read != 0 {
Ok((buffer, bytes_read, Some(from_glib_full(error))))
} else {
Err((buffer, from_glib_full(error)))
};
callback(result);
}
let callback = read_all_async_trampoline::<B, Q>;
unsafe {
ffi::g_input_stream_read_all_async(self.to_glib_none().0, buffer_ptr, count, io_priority.to_glib(), cancellable.0, Some(callback), Box::into_raw(user_data) as *mut _);
}
}
fn read_async<'a, B: AsMut<[u8]> + Send + 'static, P: Into<Option<&'a Cancellable>>, Q: FnOnce(Result<(B, usize), (B, Error)>) + Send + 'static>(&self, buffer: B, io_priority: Priority, cancellable: P, callback: Q) {
let cancellable = cancellable.into();
let cancellable = cancellable.to_glib_none();
let mut buffer: Box<B> = Box::new(buffer);
let (count, buffer_ptr) = {
let slice = (*buffer).as_mut();
(slice.len(), slice.as_mut_ptr())
};
let user_data: Box<Option<(Box<Q>, Box<B>)>> = Box::new(Some((Box::new(callback), buffer)));
unsafe extern "C" fn read_async_trampoline<B: AsMut<[u8]> + Send + 'static, Q: FnOnce(Result<(B, usize), (B, Error)>) + Send + 'static>(_source_object: *mut gobject_ffi::GObject, res: *mut ffi::GAsyncResult, user_data: glib_ffi::gpointer)
{
callback_guard!();
let mut user_data: Box<Option<(Box<Q>, Box<B>)>> = Box::from_raw(user_data as *mut _);
let (callback, buffer) = user_data.take().unwrap();
let buffer = *buffer;
let mut error = ptr::null_mut();
let ret = ffi::g_input_stream_read_finish(_source_object as *mut _, res, &mut error);
let result = if error.is_null() {
Ok((buffer, ret as usize))
} else {
Err((buffer, from_glib_full(error)))
};
callback(result);
}
let callback = read_async_trampoline::<B, Q>;
unsafe {
ffi::g_input_stream_read_async(self.to_glib_none().0, buffer_ptr, count, io_priority.to_glib(), cancellable.0, Some(callback), Box::into_raw(user_data) as *mut _);
}
}
}
#[cfg(all(test,any(feature = "v2_34", feature = "dox")))]
mod tests {
use glib::*;
use test_util::run_async;
use *;
#[test]
#[cfg(all(test,any(feature = "v2_44", feature = "dox")))]
fn read_all_async() {
let ret = run_async(|tx, l| {
let b = Bytes::from_owned(vec![1, 2, 3]);
let strm = MemoryInputStream::new_from_bytes(&b);
let buf = vec![0;10];
strm.read_all_async(buf, PRIORITY_DEFAULT_IDLE, None, move |ret| {
tx.send(ret).unwrap();
l.quit();
});
});
let (buf, count, err) = ret.unwrap();
assert_eq!(count, 3);
assert!(err.is_none());
assert_eq!(buf[0], 1);
assert_eq!(buf[1], 2);
assert_eq!(buf[2], 3);
}
#[test]
fn read_all() {
let b = Bytes::from_owned(vec![1, 2, 3]);
let strm = MemoryInputStream::new_from_bytes(&b);
let mut buf = vec![0;10];
let ret = strm.read_all(&mut buf, None).unwrap();
assert_eq!(ret.0, 3);
assert!(ret.1.is_none());
assert_eq!(buf[0], 1);
assert_eq!(buf[1], 2);
assert_eq!(buf[2], 3);
}
#[test]
fn read() {
let b = Bytes::from_owned(vec![1, 2, 3]);
let strm = MemoryInputStream::new_from_bytes(&b);
let mut buf = vec![0;10];
let ret = strm.read(&mut buf, None);
assert_eq!(ret.unwrap(), 3);
assert_eq!(buf[0], 1);
assert_eq!(buf[1], 2);
assert_eq!(buf[2], 3);
}
#[test]
fn read_async() {
let ret = run_async(|tx, l| {
let b = Bytes::from_owned(vec![1, 2, 3]);
let strm = MemoryInputStream::new_from_bytes(&b);
let buf = vec![0;10];
strm.read_async(buf, PRIORITY_DEFAULT_IDLE, None, move |ret| {
tx.send(ret).unwrap();
l.quit();
});
});
let (buf, count) = ret.unwrap();
assert_eq!(count, 3);
assert_eq!(buf[0], 1);
assert_eq!(buf[1], 2);
assert_eq!(buf[2], 3);
}
#[test]
#[cfg(any(feature = "v2_34", feature = "dox"))]
fn read_bytes_async() {
let ret = run_async(|tx, l| {
let b = Bytes::from_owned(vec![1, 2, 3]);
let strm = MemoryInputStream::new_from_bytes(&b);
strm.read_bytes_async(10, PRIORITY_DEFAULT_IDLE, None, move |ret| {
tx.send(ret).unwrap();
l.quit();
});
});
let bytes = ret.unwrap();
assert_eq!(bytes, vec![1, 2, 3]);
}
#[test]
fn skip_async() {
let ret = run_async(|tx, l| {
let b = Bytes::from_owned(vec![1, 2, 3]);
let strm = MemoryInputStream::new_from_bytes(&b);
strm.skip_async(10, PRIORITY_DEFAULT_IDLE, None, move |ret| {
tx.send(ret).unwrap();
l.quit();
});
});
let skipped = ret.unwrap();
assert_eq!(skipped, 3);
}
}
|
pub fn get<UD>(in_: &crate::base::In<UD>) -> Result<crate::Response, crate::Error>
where
UD: crate::UserData,
{
if !crate::base::is_test() {
return Err(crate::Error::PageNotFound {
message: "server not running in test mode".to_string(),
});
}
Ok(crate::Response::Http(
in_.ctx.response(
r#"<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Realm iFrame Controller</title>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<script src='/static/iframe.js'></script>
</body>
</html>"#
.into(),
)?,
))
}
|
use std::fmt;
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq)]
/// A simple UUID (v4) implementation.
///
/// Rather than using the `uuid` crate, tycho has it's own implementation of uuids
/// for better handling between serde and elements.
///
///
pub struct Uuid(u128);
impl Uuid {
/// Create a new uuid (any version) using a random number
pub fn new() -> Self {
Self(rand::random())
}
/// Create a new v4 (typed) uuid with a random number.
pub fn v4() -> Self {
Self((
rand::random::<u128>()
& 0xffffffff_ffff_0fff_ffff_ffffffffffffu128)
| 0x00000000_0000_4000_0000_000000000000u128)
}
/// Get the hex representation of the uuid (no hyphens)
///
/// ```
/// use tycho::Uuid;
/// let uuid = Uuid::from_numeric(62911151285467627956781226334379231326);
///
/// assert_eq!(uuid.hex(), "2f543f3c06594e9233b0c8a85c2ac85e");
/// ```
pub fn hex(&self) -> String {
format!("{:032x?}", self.0)
}
/// Get the formated hex representation of the uuid (with hyphens)
///
/// ```
/// use tycho::Uuid;
/// let uuid = Uuid::from_numeric(62911151285467627956781226334379231326);
///
/// assert_eq!(uuid.string(), "2f543f3c-0659-4e92-33b0-c8a85c2ac85e");
/// ```
pub fn string(&self) -> String {
let mut hex = self.hex();
hex.insert(8, '-');
hex.insert(13, '-');
hex.insert(18, '-');
hex.insert(23, '-');
hex
}
/// Get the numerical representation of the uuid as a unsigned 128-bit number.
///
/// ```
/// use tycho::Uuid;
/// let uuid = Uuid::from_string("2f543f3c-0659-4e92-33b0-c8a85c2ac85e").unwrap();
///
/// assert_eq!(uuid.numeric(), 62911151285467627956781226334379231326);
/// ```
pub fn numeric(&self) -> u128 {
self.0
}
/// Get the bytes representation of a uuid.
/// ```
/// use tycho::Uuid;
/// let uuid = Uuid::from_string("2f543f3c-0659-4e92-33b0-c8a85c2ac85e").unwrap();
/// assert_eq!(uuid.bytes(), vec![47, 84, 63, 60, 6, 89, 78, 146, 51, 176, 200, 168, 92, 42, 200, 94]);
/// ```
pub fn bytes(&self) -> Vec<u8> { self.0.to_be_bytes().to_vec() }
/// Get the slice of the bytes representation of a uuid.
/// ```
/// use tycho::Uuid;
/// let uuid = Uuid::from_string("2f543f3c-0659-4e92-33b0-c8a85c2ac85e").unwrap();
/// assert_eq!(uuid.slice(), [47, 84, 63, 60, 6, 89, 78, 146, 51, 176, 200, 168, 92, 42, 200, 94]);
/// ```
pub fn slice(&self) -> [u8; 16] { self.0.to_be_bytes() }
/// Get a null (0 value) uuid.
///
/// `00000000-0000-0000-0000-000000000000`
pub fn nil() -> Self {
Self(0)
}
/// Check if the uuid is nil, a value of 0.
/// ```
/// use tycho::Uuid;
///
/// let uuid = Uuid::nil();
/// assert_eq!(uuid.is_nil(), true);
/// ```
pub fn is_nil(&self) -> bool {
self.0 == 0
}
/// Get the version number of a uuid as an u8.
///
/// ```
/// use tycho::Uuid;
/// let uuid = Uuid::from_numeric(62911151285467627956781226334379231326);
///
/// assert_eq!(uuid.version(), 4);
/// ```
pub fn version(&self) -> u8 {
((self.0 & 0x00000000_0000_f000_0000_000000000000u128) >> 76) as u8
}
/// Create an uuid from a numerical value.
/// ```
/// use tycho::Uuid;
/// let uuid = Uuid::from_numeric(62911151285467627956781226334379231326);
///
/// assert_eq!(uuid.hex(), "2f543f3c06594e9233b0c8a85c2ac85e");
/// ```
pub fn from_numeric(x: u128) -> Self {
Self(x)
}
/// Create a uuid from an unformatted 32 length hex string.
///
/// Returns none on failure.
/// ```
/// use tycho::Uuid;
/// let uuid = Uuid::from_hex("2f543f3c06594e9233b0c8a85c2ac85e").unwrap();
///
/// assert_eq!(uuid.hex(), "2f543f3c06594e9233b0c8a85c2ac85e");
/// ```
pub fn from_hex(x: &str) -> Option<Self> {
Some(Self(u128::from_str_radix(x, 16).ok()?))
}
/// Create a uuid from an formatted 32 length hex string.
///
/// Returns none on failure.
/// ```
/// use tycho::Uuid;
/// let uuid = Uuid::from_string("2f543f3c-0659-4e92-33b0-c8a85c2ac85e").unwrap();
/// assert_eq!(uuid.hex(), "2f543f3c06594e9233b0c8a85c2ac85e");
/// ```
pub fn from_string(x: &str) -> Option<Self> {
Self::from_hex(&x.replace("-", ""))
}
/// Try to create a uuid from any string.
///
/// This function strips all non-hex characters and trims length of string.
///
/// If it fails, it returns a nil uuid.
/// ```
/// use tycho::Uuid;
/// let uuid = Uuid::from_string_lossy("2<f54>??z3f3c-0659-[4]e92_33b0-c8a85opolc2ac85e@bbc.co.uk");
///
/// assert_eq!(uuid.hex(), "2f543f3c06594e9233b0c8a85c2ac85e");
/// ```
pub fn from_string_lossy(x: &str) -> Self {
let mut y = x.chars().filter(|x|
x == &'0' || x == &'1' || x == &'2' || x == &'3'
|| x == &'4' || x == &'5' || x == &'6' || x == &'7'
|| x == &'8' || x == &'9' || x == &'a' || x == &'b'
|| x == &'c' || x == &'d' || x == &'e' || x == &'f' )
.collect::<String>();
y.truncate(32);
Self::from_hex(&y).unwrap_or(Uuid::nil())
}
/// Create a uuid from a slice of length 16.
///
/// ```
/// use tycho::Uuid;
/// let uuid = Uuid::from_slice([47, 84, 63, 60, 6, 89, 78, 146, 51, 176, 200, 168, 92, 42, 200, 94]);
///
/// assert_eq!(uuid.string(), "2f543f3c-0659-4e92-33b0-c8a85c2ac85e");
/// ```
pub fn from_slice(x: [u8; 16]) -> Self {
Self(u128::from_be_bytes(x))
}
/// Create a uuid from any size vec of u8.
///
/// ```
/// use tycho::Uuid;
/// let uuid = Uuid::from_bytes(&vec![47, 84, 63, 60, 6, 89, 78, 146, 51, 176, 200, 168, 92, 42, 200, 94]);
///
/// assert_eq!(uuid.string(), "2f543f3c-0659-4e92-33b0-c8a85c2ac85e");
/// ```
pub fn from_bytes(x: &[u8]) -> Self {
let mut bytes = [0u8; 16];
bytes.copy_from_slice(&x);
Self(u128::from_be_bytes(bytes))
}
}
impl Default for Uuid {
fn default() -> Self {
Self::nil()
}
}
impl fmt::Debug for Uuid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("UUID(")?;
f.write_str(&self.string())?;
f.write_str(")")
}
}
impl fmt::Display for Uuid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.string())
}
}
#[cfg(feature="serde")]
use serde::{Serialize, Serializer, Deserialize, Deserializer, de::Visitor, de::Error as DeError, ser::SerializeStruct};
#[cfg(feature="serde")]
impl Serialize for Uuid {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where
S: Serializer {
#[cfg(feature="serde_types")]
return if serializer.is_human_readable() {
serializer.serialize_str(&self.string())
} else {
let mut stu = serializer.serialize_struct("___tycho___/uuid", 1)?;
stu.serialize_field("inner", &UuidBytes(self.slice()))?;
stu.end()
};
#[cfg(not(feature="serde_types"))]
return serializer.serialize_str(&self.string())
}
}
#[cfg(feature="serde")]
pub struct UuidBytes([u8; 16]);
#[cfg(feature="serde")]
impl Serialize for UuidBytes {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where
S: Serializer {
serializer.serialize_bytes(&self.0)
}
}
#[cfg(feature="serde")]
impl<'de> Deserialize<'de> for Uuid {
fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> where
D: Deserializer<'de> {
deserializer.deserialize_any(UuidVisitor)
}
}
#[cfg(feature="serde")]
pub struct UuidVisitor;
#[cfg(feature="serde")]
impl<'de> Visitor<'de> for UuidVisitor {
type Value = Uuid;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("valid UUID.")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where
E: DeError, {
if let Some(value) = Uuid::from_string(&v) {
Ok(value)
} else {
Err(E::custom("Invalid UUID"))
}
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> where
E: DeError, {
Ok(Uuid::from_bytes(&v))
}
}
impl From<uuid::Uuid> for Uuid {
fn from(x: uuid::Uuid) -> Self {
Self(x.as_u128())
}
}
impl Into<uuid::Uuid> for Uuid {
fn into(self) -> uuid::Uuid {
uuid::Uuid::from_u128(self.0)
}
}
use std::hash::{Hash, Hasher};
impl Hash for Uuid {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.hash(state)
}
} |
fn comp(a: Vec<i64>, b: Vec<i64>) -> bool {
let mut tab_a = a;
let mut tab_b = b;
//if tab_b.len() != tab_a.len() { return false }
for i in 0..tab_a.len() {
tab_a[i] = tab_a[i]*tab_a[i];
}
tab_a.sort(); tab_b.sort();
tab_a == tab_b
}
#[test]
fn test0() { assert_eq!(comp(vec![], vec![]), true);
}
#[test]
fn test1() { assert_eq!(comp(vec![1], vec![1]), true);
}
#[test]
fn test2() { assert_eq!(comp(vec![1,1], vec![1,1]), true);
}
#[test]
fn test3() { assert_eq!(comp(vec![1,1,1], vec![1,1,1]), true);
}
#[test]
fn test4() { assert_eq!(comp(vec![2], vec![4]), true);
}
#[test]
fn test5() { assert_eq!(comp(vec![2,2,2], vec![4,4,4]), true);
}
#[test]
fn test6() { assert_eq!(comp(vec![1,2,3], vec![1,4,9]), true);
}
#[test]
fn test7() { assert_eq!(comp(vec![1,2,3], vec![9,4,1]), true);
}
#[test]
fn test8() { assert_eq!(comp(vec![3,2,1], vec![4,1,9]), true);
}
#[test]
fn test9() { assert_eq!(comp(vec![0], vec![0]), true);
}
fn main() {
println!("Hello, world!");
}
|
use std::time::Duration;
use Sample;
pub use self::amplify::Amplify;
pub use self::buffered::Buffered;
pub use self::delay::Delay;
pub use self::fadein::FadeIn;
pub use self::mix::Mix;
pub use self::repeat::Repeat;
pub use self::sine::SineWave;
pub use self::speed::Speed;
pub use self::take::TakeDuration;
pub use self::uniform::UniformSourceIterator;
mod amplify;
mod buffered;
mod delay;
mod fadein;
mod mix;
mod repeat;
mod sine;
mod speed;
mod take;
mod uniform;
/// A source of samples.
pub trait Source: Iterator where Self::Item: Sample {
/// Returns the number of samples before the current channel ends. `None` means "infinite".
/// Should never return 0 unless there's no more data.
///
/// After the engine has finished reading the specified number of samples, it will assume that
/// the value of `get_channels()` and/or `get_samples_rate()` have changed.
fn get_current_frame_len(&self) -> Option<usize>;
/// Returns the number of channels. Channels are always interleaved.
fn get_channels(&self) -> u16;
/// Returns the rate at which the source should be played.
fn get_samples_rate(&self) -> u32;
/// Returns the total duration of this source, if known.
///
/// `None` indicates at the same time "infinite" or "unknown".
fn get_total_duration(&self) -> Option<Duration>;
/// Stores the source in a buffer in addition to returning it. This iterator can be cloned.
#[inline]
fn buffered(self) -> Buffered<Self> where Self: Sized {
buffered::buffered(self)
}
/// Mixes this source with another one.
#[inline]
fn mix<S>(self, other: S) -> Mix<Self, S> where Self: Sized, S: Source, S::Item: Sample {
mix::mix(self, other)
}
/// Repeats this source forever.
///
/// Note that this works by storing the data in a buffer, so the amount of memory used is
/// proportional to the size of the sound.
#[inline]
fn repeat_infinite(self) -> Repeat<Self> where Self: Sized {
repeat::repeat(self)
}
/// Takes a certain duration of this source and then stops.
#[inline]
fn take_duration(self, duration: Duration) -> TakeDuration<Self> where Self: Sized {
take::take_duration(self, duration)
}
/// Delays the sound by a certain duration.
///
/// The rate and channels of the silence will use the same format as the first frame of the
/// source.
#[inline]
fn delay(self, duration: Duration) -> Delay<Self> where Self: Sized {
delay::delay(self, duration)
}
/// Amplifies the sound by the given value.
#[inline]
fn amplify(self, value: f32) -> Amplify<Self> where Self: Sized {
amplify::amplify(self, value)
}
/// Fades in the sound.
#[inline]
fn fade_in(self, duration: Duration) -> FadeIn<Self> where Self: Sized {
fadein::fadein(self, duration)
}
/// Changes the play speed of the sound. Does not adjust the samples, only the play speed.
#[inline]
fn speed(self, ratio: f32) -> Speed<Self> where Self: Sized {
speed::speed(self, ratio)
}
/// Adds a basic reverb effect.
///
/// This function requires the source to implement `Clone`. This can be done by using
/// `buffered()`.
///
/// # Example
///
/// ```ignore
/// use std::time::Duration;
///
/// let source = source.buffered().reverb(Duration::from_millis(100), 0.7);
/// ```
#[inline]
fn reverb(self, duration: Duration, amplitude: f32) -> Mix<Self, Delay<Amplify<Self>>>
where Self: Sized + Clone
{
let echo = self.clone().amplify(amplitude).delay(duration);
self.mix(echo)
}
}
|
use crate::utils::{
build_block, build_block_transactions, build_compact_block, build_compact_block_with_prefilled,
build_header, build_headers, clear_messages, wait_until,
};
use crate::{Net, Spec, TestProtocol, DEFAULT_TX_PROPOSAL_WINDOW};
use ckb_dao::DaoCalculator;
use ckb_sync::NetworkProtocol;
use ckb_test_chain_utils::MockStore;
use ckb_types::{
bytes::Bytes,
core::{
cell::{resolve_transaction, ResolvedTransaction},
BlockBuilder, HeaderBuilder, HeaderView, TransactionBuilder,
},
h256,
packed::{self, CellInput, GetHeaders, RelayMessage, SyncMessage},
prelude::*,
H256,
};
use std::collections::HashSet;
use std::time::Duration;
pub struct CompactBlockEmptyParentUnknown;
impl Spec for CompactBlockEmptyParentUnknown {
crate::name!("compact_block_empty_parent_unknown");
crate::setup!(protocols: vec![TestProtocol::sync(), TestProtocol::relay()]);
// Case: Sent to node0 a parent-unknown empty block, node0 should be unable to reconstruct
// it and send us back a `GetHeaders` message
fn run(&self, net: &mut Net) {
net.exit_ibd_mode();
let node = &net.nodes[0];
net.connect(node);
let (peer_id, _, _) = net.receive();
node.generate_block();
let _ = net.receive();
let parent_unknown_block = node
.new_block_builder(None, None, None)
.header(
HeaderBuilder::default()
.parent_hash(h256!("0x123456").pack())
.build(),
)
.build();
let tip_block = node.get_tip_block();
net.send(
NetworkProtocol::RELAY.into(),
peer_id,
build_compact_block(&parent_unknown_block),
);
let ret = wait_until(10, move || node.get_tip_block() != tip_block);
assert!(!ret, "Node0 should reconstruct empty block failed");
net.should_receive(
|data: &Bytes| {
SyncMessage::from_slice(&data)
.map(|message| message.to_enum().item_name() == GetHeaders::NAME)
.unwrap_or(false)
},
"Node0 should send back GetHeaders message for unknown parent header",
);
}
}
pub struct CompactBlockEmpty;
impl Spec for CompactBlockEmpty {
crate::name!("compact_block_empty");
crate::setup!(protocols: vec![TestProtocol::sync(), TestProtocol::relay()]);
// Case: Send to node0 a parent-known empty block, node0 should be able to reconstruct it
fn run(&self, net: &mut Net) {
let node = &net.nodes[0];
net.exit_ibd_mode();
net.connect(node);
let (peer_id, _, _) = net.receive();
let new_empty_block = node.new_block(None, None, None);
net.send(
NetworkProtocol::RELAY.into(),
peer_id,
build_compact_block(&new_empty_block),
);
let ret = wait_until(10, move || node.get_tip_block() == new_empty_block);
assert!(ret, "Node0 should reconstruct empty block successfully");
}
}
pub struct CompactBlockPrefilled;
impl Spec for CompactBlockPrefilled {
crate::name!("compact_block_prefilled");
crate::setup!(protocols: vec![TestProtocol::sync(), TestProtocol::relay()]);
// Case: Send to node0 a block with all transactions prefilled, node0 should be able to reconstruct it
fn run(&self, net: &mut Net) {
let node = &net.nodes[0];
net.exit_ibd_mode();
net.connect(node);
let (peer_id, _, _) = net.receive();
node.generate_blocks((DEFAULT_TX_PROPOSAL_WINDOW.1 + 2) as usize);
// Proposal a tx, and grow up into proposal window
let new_tx = node.new_transaction(node.get_tip_block().transactions()[0].hash());
node.submit_block(
&node
.new_block_builder(None, None, None)
.proposal(new_tx.proposal_short_id())
.build(),
);
node.generate_blocks(3);
// Relay a block contains `new_tx` as committed
let new_block = node
.new_block_builder(None, None, None)
.transaction(new_tx)
.build();
net.send(
NetworkProtocol::RELAY.into(),
peer_id,
build_compact_block_with_prefilled(&new_block, vec![1]),
);
let ret = wait_until(10, move || node.get_tip_block() == new_block);
assert!(
ret,
"Node0 should reconstruct all-prefilled block successfully"
);
}
}
pub struct CompactBlockMissingFreshTxs;
impl Spec for CompactBlockMissingFreshTxs {
crate::name!("compact_block_missing_fresh_txs");
crate::setup!(protocols: vec![TestProtocol::sync(), TestProtocol::relay()]);
// Case: Send to node0 a block which missing a tx, which is a fresh tx for
// tx_pool, node0 should send `GetBlockTransactions` back for requesting
// these missing txs
fn run(&self, net: &mut Net) {
let node = &net.nodes[0];
net.exit_ibd_mode();
net.connect(node);
let (peer_id, _, _) = net.receive();
node.generate_blocks((DEFAULT_TX_PROPOSAL_WINDOW.1 + 2) as usize);
let new_tx = node.new_transaction(node.get_tip_block().transactions()[0].hash());
node.submit_block(
&node
.new_block_builder(None, None, None)
.proposal(new_tx.proposal_short_id())
.build(),
);
node.generate_blocks(3);
// Net consume and ignore the recent blocks
(0..(DEFAULT_TX_PROPOSAL_WINDOW.1 + 6)).for_each(|_| {
net.receive();
});
// Relay a block contains `new_tx` as committed, but not include in prefilled
let new_block = node
.new_block_builder(None, None, None)
.transaction(new_tx)
.build();
net.send(
NetworkProtocol::RELAY.into(),
peer_id,
build_compact_block(&new_block),
);
let ret = wait_until(10, move || node.get_tip_block() == new_block);
assert!(!ret, "Node0 should be unable to reconstruct the block");
net.should_receive(
|data: &Bytes| {
let get_block_txns = RelayMessage::from_slice(&data)
.map(|message| {
message.to_enum().item_name() == packed::GetBlockTransactions::NAME
})
.unwrap_or(false);
let get_block = SyncMessage::from_slice(&data)
.map(|message| message.to_enum().item_name() == packed::GetBlocks::NAME)
.unwrap_or(false);
get_block_txns || get_block
},
"Node0 should send GetBlockTransactions message for missing transactions",
);
}
}
pub struct CompactBlockMissingNotFreshTxs;
impl Spec for CompactBlockMissingNotFreshTxs {
crate::name!("compact_block_missing_not_fresh_txs");
crate::setup!(protocols: vec![TestProtocol::sync(), TestProtocol::relay()]);
// Case: As for the missing transactions of a compact block, we should try to find it from
// tx_pool. If we find out, we can reconstruct the target block without any requests
// to the peer.
// 1. Put the target tx into tx_pool, and proposal it. Then move it into proposal window
// 2. Relay target block which contains the target transaction as committed transaction. Expect
// successful to reconstruct the target block and grow up.
fn run(&self, net: &mut Net) {
let node = &net.nodes[0];
net.exit_ibd_mode();
net.connect(node);
let (peer_id, _, _) = net.receive();
node.generate_blocks((DEFAULT_TX_PROPOSAL_WINDOW.1 + 2) as usize);
// Build the target transaction
let new_tx = node.new_transaction(node.get_tip_block().transactions()[0].hash());
node.submit_block(
&node
.new_block_builder(None, None, None)
.proposal(new_tx.proposal_short_id())
.build(),
);
node.generate_blocks(3);
// Generate the target block which contains the target transaction as a committed transaction
let new_block = node
.new_block_builder(None, None, None)
.transaction(new_tx.clone())
.build();
// Put `new_tx` as an not fresh tx into tx_pool
node.rpc_client().send_transaction(new_tx.data().into());
// Relay the target block
clear_messages(&net);
net.send(
NetworkProtocol::RELAY.into(),
peer_id,
build_compact_block(&new_block),
);
let ret = wait_until(10, move || node.get_tip_block() == new_block);
assert!(ret, "Node0 should be able to reconstruct the block");
}
}
pub struct CompactBlockLoseGetBlockTransactions;
impl Spec for CompactBlockLoseGetBlockTransactions {
crate::name!("compact_block_lose_get_block_transactions");
crate::setup!(
num_nodes: 2,
connect_all: false,
protocols: vec![TestProtocol::sync(), TestProtocol::relay()],
);
fn run(&self, net: &mut Net) {
net.exit_ibd_mode();
let node0 = &net.nodes[0];
net.connect(node0);
let (peer_id0, _, _) = net.receive();
let node1 = &net.nodes[1];
net.connect(node1);
let _ = net.receive();
node0.generate_blocks((DEFAULT_TX_PROPOSAL_WINDOW.1 + 2) as usize);
let new_tx = node0.new_transaction(node0.get_tip_block().transactions()[0].hash());
node0.submit_block(
&node0
.new_block_builder(None, None, None)
.proposal(new_tx.proposal_short_id())
.build(),
);
// Proposal a tx, and grow up into proposal window
node0.generate_blocks(6);
// Make node0 and node1 reach the same height
node1.generate_block();
node0.connect(node1);
node0.waiting_for_sync(node1, node0.get_tip_block().header().number());
// Net consume and ignore the recent blocks
clear_messages(&net);
// Construct a new block contains one transaction
let block = node0
.new_block_builder(None, None, None)
.transaction(new_tx)
.build();
// Net send the compact block to node0, but dose not send the corresponding missing
// block transactions. It will make node0 unable to reconstruct the complete block
net.send(
NetworkProtocol::RELAY.into(),
peer_id0,
build_compact_block(&block),
);
net.should_receive(
|data: &Bytes| {
let get_block_txns = RelayMessage::from_slice(&data)
.map(|message| {
message.to_enum().item_name() == packed::GetBlockTransactions::NAME
})
.unwrap_or(false);
let get_block = SyncMessage::from_slice(&data)
.map(|message| message.to_enum().item_name() == packed::GetBlocks::NAME)
.unwrap_or(false);
get_block_txns || get_block
},
"Node0 should send GetBlockTransactions message for missing transactions",
);
// Submit the new block to node1. We expect node1 will relay the new block to node0.
node1.submit_block(&block);
node1.waiting_for_sync(node0, node1.get_tip_block().header().number());
}
}
pub struct CompactBlockRelayParentOfOrphanBlock;
impl Spec for CompactBlockRelayParentOfOrphanBlock {
crate::name!("compact_block_relay_parent_of_orphan_block");
crate::setup!(protocols: vec![TestProtocol::sync(), TestProtocol::relay()]);
// Case: A <- B, A == B.parent
// 1. Sync B to node0. Node0 will put B into orphan_block_pool since B's parent unknown
// 2. Relay A to node0. Node0 will handle A, and by the way process B, which is in
// orphan_block_pool now
fn run(&self, net: &mut Net) {
let node = &net.nodes[0];
net.exit_ibd_mode();
net.connect(node);
let (peer_id, _, _) = net.receive();
node.generate_blocks((DEFAULT_TX_PROPOSAL_WINDOW.1 + 2) as usize);
// Proposal a tx, and grow up into proposal window
let new_tx = node.new_transaction_spend_tip_cellbase();
node.submit_block(
&node
.new_block_builder(None, None, None)
.proposal(new_tx.proposal_short_id())
.build(),
);
node.generate_blocks(6);
let consensus = node.consensus();
let mock_store = MockStore::default();
for i in 0..=node.get_tip_block_number() {
let block = node.get_block_by_number(i);
mock_store.insert_block(&block, consensus.genesis_epoch_ext());
}
let parent = node
.new_block_builder(None, None, None)
.transaction(new_tx)
.build();
let mut seen_inputs = HashSet::new();
let transactions = parent.transactions();
let rtxs: Vec<ResolvedTransaction> = transactions
.into_iter()
.map(|tx| resolve_transaction(tx, &mut seen_inputs, &mock_store, &mock_store).unwrap())
.collect();
let calculator = DaoCalculator::new(&consensus, mock_store.store());
let dao = calculator
.dao_field(&rtxs, &node.get_tip_block().header())
.unwrap();
let header = parent.header().as_advanced_builder().dao(dao).build();
let parent = parent.as_advanced_builder().header(header).build();
mock_store.insert_block(&parent, consensus.genesis_epoch_ext());
let fakebase = node.new_block(None, None, None).transactions()[0].clone();
let output = fakebase
.outputs()
.as_reader()
.get(0)
.unwrap()
.to_entity()
.as_builder()
.capacity(
calculator
.base_block_reward(&parent.header())
.unwrap()
.pack(),
)
.build();
let output_data = fakebase
.outputs_data()
.as_reader()
.get(0)
.unwrap()
.to_entity();
let cellbase = TransactionBuilder::default()
.output(output)
.output_data(output_data)
.witness(fakebase.witnesses().as_reader().get(0).unwrap().to_entity())
.input(CellInput::new_cellbase_input(parent.header().number() + 1))
.build();
let rtxs = vec![resolve_transaction(
cellbase.clone(),
&mut HashSet::new(),
&mock_store,
&mock_store,
)
.unwrap()];
let dao = DaoCalculator::new(&consensus, mock_store.store())
.dao_field(&rtxs, &parent.header())
.unwrap();
let block = BlockBuilder::default()
.transaction(cellbase)
.header(
parent
.header()
.as_advanced_builder()
.number((parent.header().number() + 1).pack())
.timestamp((parent.header().timestamp() + 1).pack())
.parent_hash(parent.hash())
.dao(dao)
.epoch(
consensus
.genesis_epoch_ext()
.number_with_fraction(parent.header().number() + 1)
.pack(),
)
.build(),
)
.build();
let old_tip = node.get_tip_block().header().number();
net.send(
NetworkProtocol::RELAY.into(),
peer_id,
build_compact_block(&parent),
);
// pending for GetBlockTransactions
clear_messages(&net);
net.send(
NetworkProtocol::SYNC.into(),
peer_id,
build_header(&parent.header()),
);
net.send(
NetworkProtocol::SYNC.into(),
peer_id,
build_header(&block.header()),
);
clear_messages(&net);
net.send(NetworkProtocol::SYNC.into(), peer_id, build_block(&block));
net.send(
NetworkProtocol::RELAY.into(),
peer_id,
build_block_transactions(&parent),
);
let ret = wait_until(20, move || {
node.get_tip_block().header().number() == old_tip + 2
});
assert!(
ret,
"relayer should process the two blocks, including the orphan block"
);
}
}
pub struct CompactBlockRelayLessThenSharedBestKnown;
impl Spec for CompactBlockRelayLessThenSharedBestKnown {
crate::name!("compact_block_relay_less_then_shared_best_known");
crate::setup!(
num_nodes: 2,
connect_all: false,
protocols: vec![TestProtocol::sync(), TestProtocol::relay()],
);
// Case: Relay a compact block which has lower total difficulty than shared_best_known
// 1. Synchronize Headers[Tip+1, Tip+10]
// 2. Relay CompactBlock[Tip+1]
fn run(&self, net: &mut Net) {
let node0 = &net.nodes[0];
let node1 = &net.nodes[1];
net.exit_ibd_mode();
net.connect(node0);
let (peer_id, _, _) = net.receive();
assert_eq!(node0.get_tip_block(), node1.get_tip_block());
let old_tip = node1.get_tip_block_number();
node1.generate_blocks(10);
let headers: Vec<HeaderView> = (old_tip + 1..node1.get_tip_block_number())
.map(|i| node1.rpc_client().get_header_by_number(i).unwrap().into())
.collect();
net.send(
NetworkProtocol::SYNC.into(),
peer_id,
build_headers(&headers),
);
{
let (_, _, data) = net.receive_timeout(Duration::from_secs(5)).expect("");
assert_eq!(
SyncMessage::from_slice(&data)
.unwrap()
.to_enum()
.item_name(),
packed::GetBlocks::NAME,
"Node0 should send GetBlocks message",
);
}
let new_block = node0.new_block(None, None, None);
net.send(
NetworkProtocol::RELAY.into(),
peer_id,
build_compact_block(&new_block),
);
assert!(
wait_until(20, move || node0.get_tip_block().header().number() == old_tip + 1),
"node0 should process the new block, even its difficulty is less than best_shared_known",
);
}
}
|
pub fn exp(x: f64) -> f64 {
const MAX_ITER: i32 = 200;
let mut sum = 1.0;
let mut term = 1.0;
for n in 1..MAX_ITER {
term *= x / n as f64;
sum += term;
};
return sum
}
fn probe_func_sec(x: f64, y: f64) -> f64 {
return 2.0 * x.cos() /
(1.0 - (x.sin().powi(2)) * (y.cos().powi(2)));
}
pub fn probe_func_main(x: f64, y: f64, p: f64) -> f64 {
return (4.0 / std::f64::consts::PI) *
(1.0 - exp(-p * probe_func_sec(x, y))) *
x.cos() * x.sin();
}
pub fn simpson(func: Box<dyn Fn(f64) -> f64>, a: f64, b: f64, num: usize) -> f64 {
if num < 3 || num & 1 == 0 {
panic!("Wrong num value!");
}
let h: f64 = (b - a) / (num - 1) as f64;
let mut x: f64 = a;
let mut res: f64 = 0.0;
for n in 0..((num - 1) / 2) {
res += func(x) + 4.0 * func(x + (h as f64)) + func(x + 2.0 * (h as f64));
x += 2.0 * (h as f64);
}
return res * (h as f64 / 3.0);
}
|
use serde::{Serialize, Deserialize};
use warp::{reject, Reply, Rejection};
use super::errors::ErrorVariant;
#[derive(Deserialize)]
pub struct UserParams {
pub email: String,
pub password: String
}
#[derive(Serialize)]
pub struct AuthInfo {
pub token: String
}
#[derive(Serialize)]
pub struct ErrorResponse {
pub message: String
}
// TODO: There is probably a way to refactor this to fully use warp rejections.
pub async fn auth_handler(
db: crate::DbConnectionPool,
data: UserParams
) -> std::result::Result<impl Reply, Rejection> {
let client = super::database::get_db_conn(&db)
.await
.map_err(|e| reject::custom(e))?;
super::auth::find_user(
&client,
&data.email
)
.await
.map_err(|e| reject::custom(e))
.map(|user|
match super::auth::valid_password(
&data.password,
&user.encrypted_password
) {
false => {
Ok(
warp::reply::with_status(
warp::reply::json(&"{}"),
warp::http::StatusCode::from_u16(403).unwrap()
)
)
},
true => {
Ok(
warp::reply::with_status(
warp::reply::json(& AuthInfo { token: user.token }),
warp::http::StatusCode::from_u16(200).unwrap()
)
)
}
}
)
}
pub async fn rejection_handler(
err: Rejection
) -> std::result::Result<impl Reply, std::convert::Infallible> {
let code ;
let message;
if err.is_not_found() {
code = warp::http::StatusCode::NOT_FOUND;
message = "Not found";
} else if let Some(_) = err.find::<warp::filters::body::BodyDeserializeError>() {
code = warp::http::StatusCode::BAD_REQUEST;
message = "Invalid Body";
} else if let Some(e) = err.find::<ErrorVariant>() {
match e {
ErrorVariant::DbPoolError(_) => {
code = warp::http::StatusCode::SERVICE_UNAVAILABLE;
message = "Database connection lost";
}
ErrorVariant::DbQueryError(_) => {
code = warp::http::StatusCode::BAD_REQUEST;
message = "Query error";
}
}
} else {
warn!("unhandled error: {:?}", err);
code = warp::http::StatusCode::INTERNAL_SERVER_ERROR;
message = "Internal Server Error";
}
let body = warp::reply::json(& ErrorResponse {
message: message.into()
});
Ok(warp::reply::with_status(body, code))
}
|
use chip8::Address;
use std::fmt;
const FRAME_COUNT: usize = 16;
pub struct Stack {
frames: [u16; FRAME_COUNT],
sp: u8,
}
impl fmt::Debug for Stack {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[sp] {}", self.sp)?;
write!(
f,
" [top] {:04x}",
self.frames[(self.sp.saturating_sub(1)) as usize]
)
}
}
impl Stack {
pub fn new() -> Stack {
Stack {
frames: [0; FRAME_COUNT],
sp: 0,
}
}
pub fn push(&mut self, addr: Address) {
self.frames[self.sp as usize] = addr;
self.sp += 1;
}
pub fn pop(&mut self) -> Address {
self.sp -= 1;
self.frames[self.sp as usize]
}
}
|
use chrono::Duration;
use drogue_cloud_database_common::{
models::outbox::{OutboxAccessor, OutboxEntry, PostgresOutboxAccessor},
utils::millis_since_epoch,
Client,
};
use drogue_cloud_test_common::{client, db};
use futures::TryStreamExt;
use log::LevelFilter;
use serial_test::serial;
use tokio_postgres::NoTls;
pub fn init() {
let _ = env_logger::builder()
.is_test(true)
.filter_level(LevelFilter::Debug)
.try_init();
}
#[tokio::test]
#[serial]
async fn test_outbox() -> anyhow::Result<()> {
init();
let cli = client();
let db = db(&cli, |pg| pg)?;
let pool = db.config.create_pool(NoTls)?;
let c = pool.get().await?;
let outbox = PostgresOutboxAccessor::new(&c);
// create a first entry
let ms1 = millis_since_epoch();
outbox
.create(OutboxEntry {
instance: "instance1".to_string(),
app: "app1".to_string(),
device: None,
uid: "a".to_string(),
path: ".path".to_string(),
generation: ms1,
})
.await?;
// fetch
let entries: Vec<_> = outbox
.fetch_unread(Duration::zero())
.await?
.try_collect()
.await?;
// there should be one entry now
assert_eq!(
entries,
vec![OutboxEntry {
instance: "instance1".to_string(),
app: "app1".to_string(),
device: None,
uid: "a".to_string(),
path: ".path".to_string(),
generation: ms1,
}]
);
// update the same entry
let ms2 = millis_since_epoch();
outbox
.create(OutboxEntry {
instance: "instance1".to_string(),
app: "app1".to_string(),
device: None,
uid: "a".to_string(),
path: ".path".to_string(),
generation: ms2,
})
.await?;
// fetch
let entries: Vec<_> = outbox
.fetch_unread(Duration::zero())
.await?
.try_collect()
.await?;
// there still should be only one entry
assert_eq!(
entries,
vec![OutboxEntry {
instance: "instance1".to_string(),
app: "app1".to_string(),
device: None,
uid: "a".to_string(),
path: ".path".to_string(),
generation: ms2,
}]
);
// mark seen - ms1
outbox
.mark_seen(OutboxEntry {
instance: "instance1".to_string(),
app: "app1".to_string(),
device: None,
uid: "a".to_string(),
path: ".path".to_string(),
generation: ms1,
})
.await?;
// fetch
let entries: Vec<_> = outbox
.fetch_unread(Duration::zero())
.await?
.try_collect()
.await?;
// there still should be one entry, as the timestamp was older
assert_eq!(
entries,
vec![OutboxEntry {
instance: "instance1".to_string(),
app: "app1".to_string(),
device: None,
uid: "a".to_string(),
path: ".path".to_string(),
generation: ms2,
}]
);
// mark seen - ms2
outbox
.mark_seen(OutboxEntry {
instance: "instance1".to_string(),
app: "app1".to_string(),
device: None,
uid: "a".to_string(),
path: ".path".to_string(),
generation: ms2,
})
.await?;
// fetch
let entries: Vec<_> = outbox
.fetch_unread(Duration::zero())
.await?
.try_collect()
.await?;
// now there should be no entry
assert_eq!(entries, vec![]);
Ok(())
}
struct CreateApp {
app: String,
uid: String,
path: String,
generation: u64,
}
impl CreateApp {
fn new(app: &str, uid: &str, path: &str, generation: u64) -> Self {
Self {
app: app.to_string(),
uid: uid.to_string(),
path: path.to_string(),
generation,
}
}
async fn run<C: Client>(self, outbox: &PostgresOutboxAccessor<'_, C>) -> anyhow::Result<()> {
outbox
.create(OutboxEntry {
instance: "instance1".to_string(),
app: self.app,
device: None,
uid: self.uid,
path: self.path,
generation: self.generation,
})
.await?;
Ok(())
}
}
#[tokio::test]
#[serial]
async fn test_recreate_resource() -> anyhow::Result<()> {
init();
let cli = client();
let db = db(&cli, |pg| pg)?;
let pool = db.config.create_pool(NoTls)?;
let c = pool.get().await?;
let outbox = PostgresOutboxAccessor::new(&c);
// create a flow of events
for i in vec![
CreateApp::new("app1", "a", ".path", 1),
CreateApp::new("app1", "a", ".path", 2),
CreateApp::new("app1", "a", ".path", 3),
CreateApp::new("app1", "b", ".path", 1),
CreateApp::new("app1", "b", ".path", 2),
] {
i.run(&outbox).await?;
}
// now check
// fetch
let entries: Vec<_> = outbox
.fetch_unread(Duration::zero())
.await?
.try_collect()
.await?;
// there still should be one entry, as the timestamp was older
assert_eq!(
entries,
vec![OutboxEntry {
instance: "instance1".to_string(),
app: "app1".to_string(),
device: None,
uid: "b".to_string(),
path: ".path".to_string(),
generation: 2,
}]
);
Ok(())
}
|
struct JSJIT(u64);
enum JSJITorExpr {
Jit { label: JSJIT },
Expr { expr: Box<JSExpr> }
}
enum JSExpr {
Integer { value: u64 },
String { value: String },
OperatorAdd { lexpr: Box<JSJITorExpr>, rexpr: Box<JSJITorExpr> },
OperatorMul { lexpr: Box<JSJITorExpr>, rexpr: Box<JSJITorExpr> }
}
fn jump(l: JSJIT) -> JSJITorExpr
{
//jump to compiled code
//this depends on implementation
//so we will just leave this as a stub
JSJITorExpr::Jit { label: JSJIT(0) }
}
fn eval(e: JSJITorExpr) -> JSJITorExpr
{
match e
{
JSJITorExpr::Jit { label: label } => jump(label),
JSJITorExpr::Expr { expr: expr } => {
let rawexpr = *expr;
match rawexpr
{
JSExpr::Integer {..} => JSJITorExpr::Expr { expr: Box::new(rawexpr) },
JSExpr::String {..} => JSJITorExpr::Expr { expr: Box::new(rawexpr) },
JSExpr::OperatorAdd { lexpr: l, rexpr: r } => {
let l = eval(*l);
let r = eval(*r);
//call add op codes for possible l,r representations
//should return wrapped value from above
JSJITorExpr::Jit { label: JSJIT(0) }
}
JSExpr::OperatorMul { lexpr: l, rexpr: r } => {
let l = eval(*l);
let r = eval(*r);
//call mul op codes for possible l,r representations
//should return wrapped value from above
JSJITorExpr::Jit { label: JSJIT(0) }
}
}
}
}
}
pub trait HList: Sized {}
pub struct HNil;
impl HList for HNil {}
pub struct HCons<H, T> {
pub head: H,
pub tail: T,
}
impl<H, T: HList> HList for HCons<H, T> {}
impl<H, T> HCons<H, T> {
pub fn pop(self) -> (H, T) {
(self.head, self.tail)
}
}
fn main()
{
let hl = HCons {
head: 2,
tail: HCons {
head: "abcd".to_string(),
tail: HNil
}
};
let (h1,t1) = hl.pop();
let (h2,t2) = t1.pop();
//this would fail
//HNil has no .pop method
//t2.pop();
}
|
use crate::zx::constants::{ATTR_BASE_REL, ATTR_COLS, ATTR_MAX_REL, CANVAS_HEIGHT};
/// Encode line number to read memory address
pub fn bitmap_line_addr(line: usize) -> u16 {
assert!(line < CANVAS_HEIGHT);
// 0 1 0 Y7 Y6 Y2 Y1 Y0 | Y5 Y4 Y3 X4 X3 X2 X1 X0
(0x4000 | (line << 5) & 0x1800 | (line << 8) & 0x0700 | (line << 2) & 0x00E0) as u16
}
/// Get pixel id from address
pub fn bitmap_line_rel(addr: u16) -> usize {
assert!(addr < ATTR_BASE_REL);
let [l, h] = addr.to_le_bytes();
// 0 0 0 Y7 Y6 Y2 Y1 Y0 | Y5 Y4 Y3 X4 X3 X2 X1 X0
// extract lowest 5 bits as x coordinate base
let y = (h & 0x07) | ((l >> 2) & 0x38) | ((h << 3) & 0xC0);
y as usize
}
/// get bitmap column from address
pub fn bitmap_col_rel(addr: u16) -> usize {
assert!(addr < ATTR_BASE_REL);
let [l, _] = addr.to_le_bytes();
// extract lowest 5 bits as x coordinate base
(l & 0x1F) as usize
}
/// get attribute row from address
pub fn attr_row_rel(addr: u16) -> usize {
assert!((ATTR_BASE_REL..=ATTR_MAX_REL).contains(&addr));
((addr - ATTR_BASE_REL) / ATTR_COLS as u16) as usize
}
/// get attribute column from address
pub fn attr_col_rel(addr: u16) -> usize {
assert!((ATTR_BASE_REL..=ATTR_MAX_REL).contains(&addr));
((addr - ATTR_BASE_REL) % ATTR_COLS as u16) as usize
}
|
use eyre::Error;
use std::fmt::Display;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use serde_json;
const DARKSKY_FORECAST_URL: &str = "https://api.darksky.net/forecast/";
type UnixTime = u64;
type Temperature = f32;
type Bearing = u16;
type Speed = f32;
type UvIndex = u8;
type CloudCover = f32;
type Humidity = f32;
type Probability = f32;
type Intensity = f32;
type MoonPhase = f32;
type Pressure = f32;
type Distance = f32;
type Ozone = f32;
#[derive(Debug, Serialize, Deserialize)]
pub struct DarkskyResult {
latitude: Decimal,
longitude: Decimal,
timezone: String,
currently: Weather,
minutely: Option<MinutelySeries>,
hourly: HourlySeries,
daily: DailySeries,
alerts: Option<Vec<Alerts>>,
flags: Flags,
offset: i8,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Weather {
time: UnixTime,
summary: String,
icon: String,
nearest_storm_distance: Option<Distance>,
nearest_storm_bearing: Option<Bearing>,
precip_intensity: Intensity,
precip_probability: Probability,
precip_type: Option<String>,
temperature: Temperature,
apparent_temperature: Temperature,
dew_point: Temperature,
humidity: Humidity,
pressure: Pressure,
wind_speed: Speed,
wind_gust: Speed,
wind_bearing: Bearing,
cloud_cover: CloudCover,
uv_index: UvIndex,
visibility: Distance,
ozone: Ozone,
}
#[derive(Debug, Serialize, Deserialize)]
struct MinutelySeries {
summary: String,
icon: String,
data: Vec<Precipation>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Precipation {
time: UnixTime,
precip_intensity: Intensity,
precip_probability: Probability,
}
#[derive(Debug, Serialize, Deserialize)]
struct HourlySeries {
summary: String,
icon: String,
data: Vec<Weather>,
}
#[derive(Debug, Serialize, Deserialize)]
struct DailySeries {
summary: String,
icon: String,
data: Vec<DailyWeather>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct DailyWeather {
time: UnixTime,
summary: String,
icon: String,
sunrise_time: UnixTime,
sunset_time: UnixTime,
moon_phase: MoonPhase,
precip_intensity: Intensity,
precip_intensity_max: Intensity,
precip_intensity_max_time: Option<UnixTime>,
precip_probability: Probability,
precip_type: Option<String>,
temperature_high: Temperature,
temperature_high_time: UnixTime,
temperature_low: Temperature,
temperature_low_time: UnixTime,
apparent_temperature_high: Temperature,
apparent_temperature_high_time: UnixTime,
apparent_temperature_low: Temperature,
apparent_temperature_low_time: UnixTime,
dew_point: Temperature,
humidity: Humidity,
pressure: Pressure,
wind_speed: Speed,
wind_gust: Speed,
wind_gust_time: UnixTime,
wind_bearing: Bearing,
cloud_cover: CloudCover,
uv_index: UvIndex,
uv_index_time: UnixTime,
visibility: Distance,
ozone: Ozone,
}
#[derive(Debug, Serialize, Deserialize)]
struct Alerts {
title: String,
time: UnixTime,
expires: UnixTime,
description: String,
uri: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct Flags {
sources: Vec<String>,
nearest_station: Distance,
units: String,
}
fn get_weather_icon(iconstr: &str) -> &str {
match iconstr {
"clear-day" => "☀️",
"clear-night" => "🌙",
"rain" => "🌧",
"snow" => "🌨",
"sleet" => "🌨",
"wind" => "💨",
"fog" => "🌫",
"cloudy" => "☁️",
"partly-cloudy-day" => "⛅️",
"partly-cloudy-night" => "🌙",
"hail" => "🌧",
"thunderstorm" => "⛈",
"tornado" => "🌪",
_ => "",
}
}
impl DarkskyResult {
pub async fn new(api_key: &str, lat: Decimal, lng: Decimal) -> Result<DarkskyResult, Error> {
let request_url = format!(
"{}{}/{},{}",
DARKSKY_FORECAST_URL,
urlencoding::encode(api_key),
lat,
lng,
);
let response = reqwest::get(request_url).await?;
let response_body = response.text().await?;
Ok(serde_json::from_str::<DarkskyResult>(&response_body)?)
}
fn get_unit(&self) -> &str {
match self.flags.units.as_str() {
"us" => "F",
_ => "C",
}
}
fn get_current_weather_str(&self) -> String {
format!(
"{:.1}°{} {} {}",
self.currently.temperature,
self.get_unit(),
get_weather_icon(self.currently.icon.as_str()),
self.currently.summary
)
}
}
impl Display for DarkskyResult {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.get_current_weather_str())
}
}
|
use crate::libs::skyway::{MeshRoom, Peer};
use js_sys::Promise;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
pub async fn close_room_connection(room: Rc<MeshRoom>) {
let _ = 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;
}
pub async fn try_to_open_room_connection(
peer: Rc<Peer>,
room_id: Rc<String>,
) -> Option<Rc<MeshRoom>> {
let room = Rc::new(peer.join_room(&room_id));
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)
}
|
use std::collections::HashMap;
use std::f64;
/* Symbol frequency. */
pub static mut SYMBOL : Vec<char> = Vec::new();
pub fn seq_weight( seq_list : &Vec<String>, site_list : &Vec<String>, arg_w : &String ) -> Vec<f64>
{
/* Amino acid list for Position-Based mothod. */
unsafe { SYMBOL = "ARNDCQEGHILKMFPSTWYV-".chars().collect(); }
if *arg_w == "va" { weight_va( seq_list ) }
else { weight_henikoff( site_list ) }
}
///////////////////////////////////////////////////////////////////////////
// POSITION-BASED METHOD
///////////////////////////////////////////////////////////////////////////
fn weight_henikoff( site_list : &Vec<String> /*, arg_t : &String */ ) -> Vec<f64>
{
/* Number of the sequences and sites. */
let num_seq : usize = ( *site_list )[ 0 ].len();
let num_site : usize = ( *site_list ).len();
let mut weight_list : Vec<f64> = vec![ 0.0; num_seq ];
/*
* Calculate weighting factor using position based method (Henikoff-Henikoff, 1994).
* r = Number of AA types in a site.
* s = Frequency of the AA in a site.
* weight_factor = 1 / (r * s).
*/
for site in site_list.iter() {
//println!( "{}", *site );
let r : usize = count_types( site );
for i in 0 .. ( *site ).len() {
let aa_vec : Vec<char> = ( *site ).chars().collect();
let aa : char = aa_vec[ i ];
//println!( "{}", aa );
let s : usize = count_freq( aa, site );
let weight_factor : f64 = 1.0 / ( ( r as f64 ) * ( s as f64 ) );
//println!( "weight_factor : {}", weight_factor );
weight_list[ i ] += weight_factor;
}
}
let mut sum_weight : f64 = 0.0;
/*
* Get sequence weight by calculating mean of weighting factors in each sites.
* num_site = Denominator of mean.
*/
for i in 0 .. weight_list.len() {
weight_list[ i ] = weight_list[ i ] / ( num_site as f64 );
//println!( "Weight of Sequence {} : {:.3}", i + 1, weight_list[ i ] );
sum_weight += weight_list[ i ];
}
println!( "\nSum of sequence weighting : {:.3}", sum_weight );
weight_list.shrink_to_fit();
weight_list
}
fn count_types( arg_site : &String ) -> usize
{
let mut count : HashMap<char, usize> = HashMap::new();
unsafe {
for aa in SYMBOL.iter() { count.insert( *aa, 0 ); }
}
for aa in ( *arg_site ).chars() {
let inc : usize = count[ &aa ] + 1;
count.insert( aa, inc );
}
let mut num_type : usize = 0;
unsafe {
for aa in SYMBOL.iter() {
if count[ aa ] != 0 {
num_type += 1;
}
}
}
//println!( "Number of AA types in {} : {}", *arg_site, num_types);
num_type
}
fn count_freq( arg_aa : char, arg_site : &String ) -> usize
{
let aa_list : Vec<char> = ( *arg_site ).chars().collect();
let mut freq : usize = 0;
for i in 0 .. aa_list.len() {
if arg_aa == aa_list[ i ] {
freq += 1;
}
}
//println!( "Frequency of {} in {} : {}", arg_aa, *arg_site, freq );
freq
}
///////////////////////////////////////////////////////////////////////////
// DISTANCE-BASED METHOD
///////////////////////////////////////////////////////////////////////////
fn weight_va( seq_list : &Vec<String> ) -> Vec<f64>
{
/* Number of the sequences and sites. */
let num_seq : usize = ( *seq_list ).len();
let mut weight_list : Vec<f64> = vec![ 0.0; num_seq ];
/*
* Calculate pairwise distance by counting differd symbols (Vingron-Argos, 1989).
* seq_pair_1 = One pairwised sequence.
* seq_pair_2 = The other pairwised one.
* num_diff = Number of the differences in pairwised sequences.
*/
for i in 0 .. num_seq {
let seq_pair_1 : &String = &( seq_list[ i ] );
//println!( "seq_pair_1 : {}", seq_pair_1 );
for j in 0 .. num_seq {
if i != j {
let seq_pair_2 : &String = &( seq_list[ j ] );
//println!( "seq_pair_2 : {}", seq_pair_2 );
let num_diff : usize = count_diff( seq_pair_1, seq_pair_2 );
weight_list[ i ] += num_diff as f64;
}
}
//println!( "" );
}
//println!( "Weights : {:?}", weight_list );
/* Normalize the weighting factors so that sum is 1. */
weight_list = normalize( &weight_list );
//println!( "Normalized weights : {:?}", weight_list );
let sum_norm_weight : f64 = ( weight_list ).iter().sum();
println!( "\nSum of sequence weighting : {:.3}", sum_norm_weight );
weight_list.shrink_to_fit();
weight_list
}
fn count_diff( seq_1 : &String, seq_2 : &String ) -> usize
{
let num_seq : usize = ( *seq_1 ).len();
let seq_1_vec : Vec<char> = ( *seq_1 ).chars().collect();
let seq_2_vec : Vec<char> = ( *seq_2 ).chars().collect();
/*
* Count the number of different symbols.
* seq_1_vec = One pairwised sequence.
* seq_2_vec = The other pairwised one.
* counter = Counter.
*/
let mut counter : usize = 0;
for i in 0 .. num_seq {
if seq_1_vec[ i ] != seq_2_vec[ i ] {
counter += 1;
}
}
counter
}
fn normalize( diff_list : &Vec<f64> ) -> Vec<f64>
{
let len_list : usize = ( *diff_list ).len();
let mut weight_norm : Vec<f64> = Vec::new();
let sum : f64 = ( *diff_list ).iter().sum();
/*
* Normalize the weight factors so that sum is 1.
* val_norm = Normalized values.
* diff_list = Numerator (weights).
* sum = Denominator (Sum of weights).
*/
for i in 0 .. len_list {
let val_norm : f64 = ( *diff_list )[ i ] / sum;
weight_norm.push( val_norm );
}
weight_norm
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Processor core identifier\\n Value is 0 when read from processor core 0, and 1 when read from processor core 1."]
pub cpuid: CPUID,
#[doc = "0x04 - Input value for GPIO pins"]
pub gpio_in: GPIO_IN,
#[doc = "0x08 - Input value for QSPI pins"]
pub gpio_hi_in: GPIO_HI_IN,
_reserved3: [u8; 4usize],
#[doc = "0x10 - GPIO output value"]
pub gpio_out: GPIO_OUT,
#[doc = "0x14 - GPIO output value set"]
pub gpio_out_set: GPIO_OUT_SET,
#[doc = "0x18 - GPIO output value clear"]
pub gpio_out_clr: GPIO_OUT_CLR,
#[doc = "0x1c - GPIO output value XOR"]
pub gpio_out_xor: GPIO_OUT_XOR,
#[doc = "0x20 - GPIO output enable"]
pub gpio_oe: GPIO_OE,
#[doc = "0x24 - GPIO output enable set"]
pub gpio_oe_set: GPIO_OE_SET,
#[doc = "0x28 - GPIO output enable clear"]
pub gpio_oe_clr: GPIO_OE_CLR,
#[doc = "0x2c - GPIO output enable XOR"]
pub gpio_oe_xor: GPIO_OE_XOR,
#[doc = "0x30 - QSPI output value"]
pub gpio_hi_out: GPIO_HI_OUT,
#[doc = "0x34 - QSPI output value set"]
pub gpio_hi_out_set: GPIO_HI_OUT_SET,
#[doc = "0x38 - QSPI output value clear"]
pub gpio_hi_out_clr: GPIO_HI_OUT_CLR,
#[doc = "0x3c - QSPI output value XOR"]
pub gpio_hi_out_xor: GPIO_HI_OUT_XOR,
#[doc = "0x40 - QSPI output enable"]
pub gpio_hi_oe: GPIO_HI_OE,
#[doc = "0x44 - QSPI output enable set"]
pub gpio_hi_oe_set: GPIO_HI_OE_SET,
#[doc = "0x48 - QSPI output enable clear"]
pub gpio_hi_oe_clr: GPIO_HI_OE_CLR,
#[doc = "0x4c - QSPI output enable XOR"]
pub gpio_hi_oe_xor: GPIO_HI_OE_XOR,
#[doc = "0x50 - Status register for inter-core FIFOs (mailboxes).\\n There is one FIFO in the core 0 -> core 1 direction, and one core 1 -> core 0. Both are 32 bits wide and 8 words deep.\\n Core 0 can see the read side of the 1->0 FIFO (RX), and the write side of 0->1 FIFO (TX).\\n Core 1 can see the read side of the 0->1 FIFO (RX), and the write side of 1->0 FIFO (TX).\\n The SIO IRQ for each core is the logical OR of the VLD, WOF and ROE fields of its FIFO_ST register."]
pub fifo_st: FIFO_ST,
#[doc = "0x54 - Write access to this core's TX FIFO"]
pub fifo_wr: FIFO_WR,
#[doc = "0x58 - Read access to this core's RX FIFO"]
pub fifo_rd: FIFO_RD,
#[doc = "0x5c - Spinlock state\\n A bitmap containing the state of all 32 spinlocks (1=locked).\\n Mainly intended for debugging."]
pub spinlock_st: SPINLOCK_ST,
#[doc = "0x60 - Divider unsigned dividend\\n Write to the DIVIDEND operand of the divider, i.e. the p in `p / q`.\\n Any operand write starts a new calculation. The results appear in QUOTIENT, REMAINDER.\\n UDIVIDEND/SDIVIDEND are aliases of the same internal register. The U alias starts an\\n unsigned calculation, and the S alias starts a signed calculation."]
pub div_udividend: DIV_UDIVIDEND,
#[doc = "0x64 - Divider unsigned divisor\\n Write to the DIVISOR operand of the divider, i.e. the q in `p / q`.\\n Any operand write starts a new calculation. The results appear in QUOTIENT, REMAINDER.\\n UDIVIDEND/SDIVIDEND are aliases of the same internal register. The U alias starts an\\n unsigned calculation, and the S alias starts a signed calculation."]
pub div_udivisor: DIV_UDIVISOR,
#[doc = "0x68 - Divider signed dividend\\n The same as UDIVIDEND, but starts a signed calculation, rather than unsigned."]
pub div_sdividend: DIV_SDIVIDEND,
#[doc = "0x6c - Divider signed divisor\\n The same as UDIVISOR, but starts a signed calculation, rather than unsigned."]
pub div_sdivisor: DIV_SDIVISOR,
#[doc = "0x70 - Divider result quotient\\n The result of `DIVIDEND / DIVISOR` (division). Contents undefined while CSR_READY is low.\\n For signed calculations, QUOTIENT is negative when the signs of DIVIDEND and DIVISOR differ.\\n This register can be written to directly, for context save/restore purposes. This halts any\\n in-progress calculation and sets the CSR_READY and CSR_DIRTY flags.\\n Reading from QUOTIENT clears the CSR_DIRTY flag, so should read results in the order\\n REMAINDER, QUOTIENT if CSR_DIRTY is used."]
pub div_quotient: DIV_QUOTIENT,
#[doc = "0x74 - Divider result remainder\\n The result of `DIVIDEND % DIVISOR` (modulo). Contents undefined while CSR_READY is low.\\n For signed calculations, REMAINDER is negative only when DIVIDEND is negative.\\n This register can be written to directly, for context save/restore purposes. This halts any\\n in-progress calculation and sets the CSR_READY and CSR_DIRTY flags."]
pub div_remainder: DIV_REMAINDER,
#[doc = "0x78 - Control and status register for divider."]
pub div_csr: DIV_CSR,
_reserved30: [u8; 4usize],
#[doc = "0x80 - Read/write access to accumulator 0"]
pub interp0_accum0: INTERP0_ACCUM0,
#[doc = "0x84 - Read/write access to accumulator 1"]
pub interp0_accum1: INTERP0_ACCUM1,
#[doc = "0x88 - Read/write access to BASE0 register."]
pub interp0_base0: INTERP0_BASE0,
#[doc = "0x8c - Read/write access to BASE1 register."]
pub interp0_base1: INTERP0_BASE1,
#[doc = "0x90 - Read/write access to BASE2 register."]
pub interp0_base2: INTERP0_BASE2,
#[doc = "0x94 - Read LANE0 result, and simultaneously write lane results to both accumulators (POP)."]
pub interp0_pop_lane0: INTERP0_POP_LANE0,
#[doc = "0x98 - Read LANE1 result, and simultaneously write lane results to both accumulators (POP)."]
pub interp0_pop_lane1: INTERP0_POP_LANE1,
#[doc = "0x9c - Read FULL result, and simultaneously write lane results to both accumulators (POP)."]
pub interp0_pop_full: INTERP0_POP_FULL,
#[doc = "0xa0 - Read LANE0 result, without altering any internal state (PEEK)."]
pub interp0_peek_lane0: INTERP0_PEEK_LANE0,
#[doc = "0xa4 - Read LANE1 result, without altering any internal state (PEEK)."]
pub interp0_peek_lane1: INTERP0_PEEK_LANE1,
#[doc = "0xa8 - Read FULL result, without altering any internal state (PEEK)."]
pub interp0_peek_full: INTERP0_PEEK_FULL,
#[doc = "0xac - Control register for lane 0"]
pub interp0_ctrl_lane0: INTERP0_CTRL_LANE0,
#[doc = "0xb0 - Control register for lane 1"]
pub interp0_ctrl_lane1: INTERP0_CTRL_LANE1,
#[doc = "0xb4 - Values written here are atomically added to ACCUM0\\n Reading yields lane 0's raw shift and mask value (BASE0 not added)."]
pub interp0_accum0_add: INTERP0_ACCUM0_ADD,
#[doc = "0xb8 - Values written here are atomically added to ACCUM1\\n Reading yields lane 1's raw shift and mask value (BASE1 not added)."]
pub interp0_accum1_add: INTERP0_ACCUM1_ADD,
#[doc = "0xbc - On write, the lower 16 bits go to BASE0, upper bits to BASE1 simultaneously.\\n Each half is sign-extended to 32 bits if that lane's SIGNED flag is set."]
pub interp0_base_1and0: INTERP0_BASE_1AND0,
#[doc = "0xc0 - Read/write access to accumulator 0"]
pub interp1_accum0: INTERP1_ACCUM0,
#[doc = "0xc4 - Read/write access to accumulator 1"]
pub interp1_accum1: INTERP1_ACCUM1,
#[doc = "0xc8 - Read/write access to BASE0 register."]
pub interp1_base0: INTERP1_BASE0,
#[doc = "0xcc - Read/write access to BASE1 register."]
pub interp1_base1: INTERP1_BASE1,
#[doc = "0xd0 - Read/write access to BASE2 register."]
pub interp1_base2: INTERP1_BASE2,
#[doc = "0xd4 - Read LANE0 result, and simultaneously write lane results to both accumulators (POP)."]
pub interp1_pop_lane0: INTERP1_POP_LANE0,
#[doc = "0xd8 - Read LANE1 result, and simultaneously write lane results to both accumulators (POP)."]
pub interp1_pop_lane1: INTERP1_POP_LANE1,
#[doc = "0xdc - Read FULL result, and simultaneously write lane results to both accumulators (POP)."]
pub interp1_pop_full: INTERP1_POP_FULL,
#[doc = "0xe0 - Read LANE0 result, without altering any internal state (PEEK)."]
pub interp1_peek_lane0: INTERP1_PEEK_LANE0,
#[doc = "0xe4 - Read LANE1 result, without altering any internal state (PEEK)."]
pub interp1_peek_lane1: INTERP1_PEEK_LANE1,
#[doc = "0xe8 - Read FULL result, without altering any internal state (PEEK)."]
pub interp1_peek_full: INTERP1_PEEK_FULL,
#[doc = "0xec - Control register for lane 0"]
pub interp1_ctrl_lane0: INTERP1_CTRL_LANE0,
#[doc = "0xf0 - Control register for lane 1"]
pub interp1_ctrl_lane1: INTERP1_CTRL_LANE1,
#[doc = "0xf4 - Values written here are atomically added to ACCUM0\\n Reading yields lane 0's raw shift and mask value (BASE0 not added)."]
pub interp1_accum0_add: INTERP1_ACCUM0_ADD,
#[doc = "0xf8 - Values written here are atomically added to ACCUM1\\n Reading yields lane 1's raw shift and mask value (BASE1 not added)."]
pub interp1_accum1_add: INTERP1_ACCUM1_ADD,
#[doc = "0xfc - On write, the lower 16 bits go to BASE0, upper bits to BASE1 simultaneously.\\n Each half is sign-extended to 32 bits if that lane's SIGNED flag is set."]
pub interp1_base_1and0: INTERP1_BASE_1AND0,
#[doc = "0x100 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock0: SPINLOCK0,
#[doc = "0x104 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock1: SPINLOCK1,
#[doc = "0x108 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock2: SPINLOCK2,
#[doc = "0x10c - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock3: SPINLOCK3,
#[doc = "0x110 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock4: SPINLOCK4,
#[doc = "0x114 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock5: SPINLOCK5,
#[doc = "0x118 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock6: SPINLOCK6,
#[doc = "0x11c - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock7: SPINLOCK7,
#[doc = "0x120 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock8: SPINLOCK8,
#[doc = "0x124 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock9: SPINLOCK9,
#[doc = "0x128 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock10: SPINLOCK10,
#[doc = "0x12c - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock11: SPINLOCK11,
#[doc = "0x130 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock12: SPINLOCK12,
#[doc = "0x134 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock13: SPINLOCK13,
#[doc = "0x138 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock14: SPINLOCK14,
#[doc = "0x13c - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock15: SPINLOCK15,
#[doc = "0x140 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock16: SPINLOCK16,
#[doc = "0x144 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock17: SPINLOCK17,
#[doc = "0x148 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock18: SPINLOCK18,
#[doc = "0x14c - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock19: SPINLOCK19,
#[doc = "0x150 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock20: SPINLOCK20,
#[doc = "0x154 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock21: SPINLOCK21,
#[doc = "0x158 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock22: SPINLOCK22,
#[doc = "0x15c - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock23: SPINLOCK23,
#[doc = "0x160 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock24: SPINLOCK24,
#[doc = "0x164 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock25: SPINLOCK25,
#[doc = "0x168 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock26: SPINLOCK26,
#[doc = "0x16c - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock27: SPINLOCK27,
#[doc = "0x170 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock28: SPINLOCK28,
#[doc = "0x174 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock29: SPINLOCK29,
#[doc = "0x178 - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock30: SPINLOCK30,
#[doc = "0x17c - Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub spinlock31: SPINLOCK31,
}
#[doc = "Processor core identifier\\n Value is 0 when read from processor core 0, and 1 when read from processor core 1.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cpuid](cpuid) module"]
pub type CPUID = crate::Reg<u32, _CPUID>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CPUID;
#[doc = "`read()` method returns [cpuid::R](cpuid::R) reader structure"]
impl crate::Readable for CPUID {}
#[doc = "Processor core identifier\\n Value is 0 when read from processor core 0, and 1 when read from processor core 1."]
pub mod cpuid;
#[doc = "Input value for GPIO pins\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_in](gpio_in) module"]
pub type GPIO_IN = crate::Reg<u32, _GPIO_IN>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_IN;
#[doc = "`read()` method returns [gpio_in::R](gpio_in::R) reader structure"]
impl crate::Readable for GPIO_IN {}
#[doc = "Input value for GPIO pins"]
pub mod gpio_in;
#[doc = "Input value for QSPI pins\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_hi_in](gpio_hi_in) module"]
pub type GPIO_HI_IN = crate::Reg<u32, _GPIO_HI_IN>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_HI_IN;
#[doc = "`read()` method returns [gpio_hi_in::R](gpio_hi_in::R) reader structure"]
impl crate::Readable for GPIO_HI_IN {}
#[doc = "Input value for QSPI pins"]
pub mod gpio_hi_in;
#[doc = "GPIO output value\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_out](gpio_out) module"]
pub type GPIO_OUT = crate::Reg<u32, _GPIO_OUT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_OUT;
#[doc = "`read()` method returns [gpio_out::R](gpio_out::R) reader structure"]
impl crate::Readable for GPIO_OUT {}
#[doc = "`write(|w| ..)` method takes [gpio_out::W](gpio_out::W) writer structure"]
impl crate::Writable for GPIO_OUT {}
#[doc = "GPIO output value"]
pub mod gpio_out;
#[doc = "GPIO output value set\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_out_set](gpio_out_set) module"]
pub type GPIO_OUT_SET = crate::Reg<u32, _GPIO_OUT_SET>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_OUT_SET;
#[doc = "`read()` method returns [gpio_out_set::R](gpio_out_set::R) reader structure"]
impl crate::Readable for GPIO_OUT_SET {}
#[doc = "`write(|w| ..)` method takes [gpio_out_set::W](gpio_out_set::W) writer structure"]
impl crate::Writable for GPIO_OUT_SET {}
#[doc = "GPIO output value set"]
pub mod gpio_out_set;
#[doc = "GPIO output value clear\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_out_clr](gpio_out_clr) module"]
pub type GPIO_OUT_CLR = crate::Reg<u32, _GPIO_OUT_CLR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_OUT_CLR;
#[doc = "`read()` method returns [gpio_out_clr::R](gpio_out_clr::R) reader structure"]
impl crate::Readable for GPIO_OUT_CLR {}
#[doc = "`write(|w| ..)` method takes [gpio_out_clr::W](gpio_out_clr::W) writer structure"]
impl crate::Writable for GPIO_OUT_CLR {}
#[doc = "GPIO output value clear"]
pub mod gpio_out_clr;
#[doc = "GPIO output value XOR\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_out_xor](gpio_out_xor) module"]
pub type GPIO_OUT_XOR = crate::Reg<u32, _GPIO_OUT_XOR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_OUT_XOR;
#[doc = "`read()` method returns [gpio_out_xor::R](gpio_out_xor::R) reader structure"]
impl crate::Readable for GPIO_OUT_XOR {}
#[doc = "`write(|w| ..)` method takes [gpio_out_xor::W](gpio_out_xor::W) writer structure"]
impl crate::Writable for GPIO_OUT_XOR {}
#[doc = "GPIO output value XOR"]
pub mod gpio_out_xor;
#[doc = "GPIO output enable\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_oe](gpio_oe) module"]
pub type GPIO_OE = crate::Reg<u32, _GPIO_OE>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_OE;
#[doc = "`read()` method returns [gpio_oe::R](gpio_oe::R) reader structure"]
impl crate::Readable for GPIO_OE {}
#[doc = "`write(|w| ..)` method takes [gpio_oe::W](gpio_oe::W) writer structure"]
impl crate::Writable for GPIO_OE {}
#[doc = "GPIO output enable"]
pub mod gpio_oe;
#[doc = "GPIO output enable set\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_oe_set](gpio_oe_set) module"]
pub type GPIO_OE_SET = crate::Reg<u32, _GPIO_OE_SET>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_OE_SET;
#[doc = "`read()` method returns [gpio_oe_set::R](gpio_oe_set::R) reader structure"]
impl crate::Readable for GPIO_OE_SET {}
#[doc = "`write(|w| ..)` method takes [gpio_oe_set::W](gpio_oe_set::W) writer structure"]
impl crate::Writable for GPIO_OE_SET {}
#[doc = "GPIO output enable set"]
pub mod gpio_oe_set;
#[doc = "GPIO output enable clear\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_oe_clr](gpio_oe_clr) module"]
pub type GPIO_OE_CLR = crate::Reg<u32, _GPIO_OE_CLR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_OE_CLR;
#[doc = "`read()` method returns [gpio_oe_clr::R](gpio_oe_clr::R) reader structure"]
impl crate::Readable for GPIO_OE_CLR {}
#[doc = "`write(|w| ..)` method takes [gpio_oe_clr::W](gpio_oe_clr::W) writer structure"]
impl crate::Writable for GPIO_OE_CLR {}
#[doc = "GPIO output enable clear"]
pub mod gpio_oe_clr;
#[doc = "GPIO output enable XOR\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_oe_xor](gpio_oe_xor) module"]
pub type GPIO_OE_XOR = crate::Reg<u32, _GPIO_OE_XOR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_OE_XOR;
#[doc = "`read()` method returns [gpio_oe_xor::R](gpio_oe_xor::R) reader structure"]
impl crate::Readable for GPIO_OE_XOR {}
#[doc = "`write(|w| ..)` method takes [gpio_oe_xor::W](gpio_oe_xor::W) writer structure"]
impl crate::Writable for GPIO_OE_XOR {}
#[doc = "GPIO output enable XOR"]
pub mod gpio_oe_xor;
#[doc = "QSPI output value\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_hi_out](gpio_hi_out) module"]
pub type GPIO_HI_OUT = crate::Reg<u32, _GPIO_HI_OUT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_HI_OUT;
#[doc = "`read()` method returns [gpio_hi_out::R](gpio_hi_out::R) reader structure"]
impl crate::Readable for GPIO_HI_OUT {}
#[doc = "`write(|w| ..)` method takes [gpio_hi_out::W](gpio_hi_out::W) writer structure"]
impl crate::Writable for GPIO_HI_OUT {}
#[doc = "QSPI output value"]
pub mod gpio_hi_out;
#[doc = "QSPI output value set\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_hi_out_set](gpio_hi_out_set) module"]
pub type GPIO_HI_OUT_SET = crate::Reg<u32, _GPIO_HI_OUT_SET>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_HI_OUT_SET;
#[doc = "`read()` method returns [gpio_hi_out_set::R](gpio_hi_out_set::R) reader structure"]
impl crate::Readable for GPIO_HI_OUT_SET {}
#[doc = "`write(|w| ..)` method takes [gpio_hi_out_set::W](gpio_hi_out_set::W) writer structure"]
impl crate::Writable for GPIO_HI_OUT_SET {}
#[doc = "QSPI output value set"]
pub mod gpio_hi_out_set;
#[doc = "QSPI output value clear\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_hi_out_clr](gpio_hi_out_clr) module"]
pub type GPIO_HI_OUT_CLR = crate::Reg<u32, _GPIO_HI_OUT_CLR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_HI_OUT_CLR;
#[doc = "`read()` method returns [gpio_hi_out_clr::R](gpio_hi_out_clr::R) reader structure"]
impl crate::Readable for GPIO_HI_OUT_CLR {}
#[doc = "`write(|w| ..)` method takes [gpio_hi_out_clr::W](gpio_hi_out_clr::W) writer structure"]
impl crate::Writable for GPIO_HI_OUT_CLR {}
#[doc = "QSPI output value clear"]
pub mod gpio_hi_out_clr;
#[doc = "QSPI output value XOR\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_hi_out_xor](gpio_hi_out_xor) module"]
pub type GPIO_HI_OUT_XOR = crate::Reg<u32, _GPIO_HI_OUT_XOR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_HI_OUT_XOR;
#[doc = "`read()` method returns [gpio_hi_out_xor::R](gpio_hi_out_xor::R) reader structure"]
impl crate::Readable for GPIO_HI_OUT_XOR {}
#[doc = "`write(|w| ..)` method takes [gpio_hi_out_xor::W](gpio_hi_out_xor::W) writer structure"]
impl crate::Writable for GPIO_HI_OUT_XOR {}
#[doc = "QSPI output value XOR"]
pub mod gpio_hi_out_xor;
#[doc = "QSPI output enable\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_hi_oe](gpio_hi_oe) module"]
pub type GPIO_HI_OE = crate::Reg<u32, _GPIO_HI_OE>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_HI_OE;
#[doc = "`read()` method returns [gpio_hi_oe::R](gpio_hi_oe::R) reader structure"]
impl crate::Readable for GPIO_HI_OE {}
#[doc = "`write(|w| ..)` method takes [gpio_hi_oe::W](gpio_hi_oe::W) writer structure"]
impl crate::Writable for GPIO_HI_OE {}
#[doc = "QSPI output enable"]
pub mod gpio_hi_oe;
#[doc = "QSPI output enable set\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_hi_oe_set](gpio_hi_oe_set) module"]
pub type GPIO_HI_OE_SET = crate::Reg<u32, _GPIO_HI_OE_SET>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_HI_OE_SET;
#[doc = "`read()` method returns [gpio_hi_oe_set::R](gpio_hi_oe_set::R) reader structure"]
impl crate::Readable for GPIO_HI_OE_SET {}
#[doc = "`write(|w| ..)` method takes [gpio_hi_oe_set::W](gpio_hi_oe_set::W) writer structure"]
impl crate::Writable for GPIO_HI_OE_SET {}
#[doc = "QSPI output enable set"]
pub mod gpio_hi_oe_set;
#[doc = "QSPI output enable clear\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_hi_oe_clr](gpio_hi_oe_clr) module"]
pub type GPIO_HI_OE_CLR = crate::Reg<u32, _GPIO_HI_OE_CLR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_HI_OE_CLR;
#[doc = "`read()` method returns [gpio_hi_oe_clr::R](gpio_hi_oe_clr::R) reader structure"]
impl crate::Readable for GPIO_HI_OE_CLR {}
#[doc = "`write(|w| ..)` method takes [gpio_hi_oe_clr::W](gpio_hi_oe_clr::W) writer structure"]
impl crate::Writable for GPIO_HI_OE_CLR {}
#[doc = "QSPI output enable clear"]
pub mod gpio_hi_oe_clr;
#[doc = "QSPI output enable XOR\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_hi_oe_xor](gpio_hi_oe_xor) module"]
pub type GPIO_HI_OE_XOR = crate::Reg<u32, _GPIO_HI_OE_XOR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_HI_OE_XOR;
#[doc = "`read()` method returns [gpio_hi_oe_xor::R](gpio_hi_oe_xor::R) reader structure"]
impl crate::Readable for GPIO_HI_OE_XOR {}
#[doc = "`write(|w| ..)` method takes [gpio_hi_oe_xor::W](gpio_hi_oe_xor::W) writer structure"]
impl crate::Writable for GPIO_HI_OE_XOR {}
#[doc = "QSPI output enable XOR"]
pub mod gpio_hi_oe_xor;
#[doc = "Status register for inter-core FIFOs (mailboxes).\\n There is one FIFO in the core 0 -> core 1 direction, and one core 1 -> core 0. Both are 32 bits wide and 8 words deep.\\n Core 0 can see the read side of the 1->0 FIFO (RX), and the write side of 0->1 FIFO (TX).\\n Core 1 can see the read side of the 0->1 FIFO (RX), and the write side of 1->0 FIFO (TX).\\n The SIO IRQ for each core is the logical OR of the VLD, WOF and ROE fields of its FIFO_ST register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fifo_st](fifo_st) module"]
pub type FIFO_ST = crate::Reg<u32, _FIFO_ST>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FIFO_ST;
#[doc = "`read()` method returns [fifo_st::R](fifo_st::R) reader structure"]
impl crate::Readable for FIFO_ST {}
#[doc = "`write(|w| ..)` method takes [fifo_st::W](fifo_st::W) writer structure"]
impl crate::Writable for FIFO_ST {}
#[doc = "Status register for inter-core FIFOs (mailboxes).\\n There is one FIFO in the core 0 -> core 1 direction, and one core 1 -> core 0. Both are 32 bits wide and 8 words deep.\\n Core 0 can see the read side of the 1->0 FIFO (RX), and the write side of 0->1 FIFO (TX).\\n Core 1 can see the read side of the 0->1 FIFO (RX), and the write side of 1->0 FIFO (TX).\\n The SIO IRQ for each core is the logical OR of the VLD, WOF and ROE fields of its FIFO_ST register."]
pub mod fifo_st;
#[doc = "Write access to this core's TX FIFO\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fifo_wr](fifo_wr) module"]
pub type FIFO_WR = crate::Reg<u32, _FIFO_WR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FIFO_WR;
#[doc = "`write(|w| ..)` method takes [fifo_wr::W](fifo_wr::W) writer structure"]
impl crate::Writable for FIFO_WR {}
#[doc = "Write access to this core's TX FIFO"]
pub mod fifo_wr;
#[doc = "Read access to this core's RX FIFO\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fifo_rd](fifo_rd) module"]
pub type FIFO_RD = crate::Reg<u32, _FIFO_RD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FIFO_RD;
#[doc = "`read()` method returns [fifo_rd::R](fifo_rd::R) reader structure"]
impl crate::Readable for FIFO_RD {}
#[doc = "Read access to this core's RX FIFO"]
pub mod fifo_rd;
#[doc = "Spinlock state\\n A bitmap containing the state of all 32 spinlocks (1=locked).\\n Mainly intended for debugging.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock_st](spinlock_st) module"]
pub type SPINLOCK_ST = crate::Reg<u32, _SPINLOCK_ST>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK_ST;
#[doc = "`read()` method returns [spinlock_st::R](spinlock_st::R) reader structure"]
impl crate::Readable for SPINLOCK_ST {}
#[doc = "Spinlock state\\n A bitmap containing the state of all 32 spinlocks (1=locked).\\n Mainly intended for debugging."]
pub mod spinlock_st;
#[doc = "Divider unsigned dividend\\n Write to the DIVIDEND operand of the divider, i.e. the p in `p / q`.\\n Any operand write starts a new calculation. The results appear in QUOTIENT, REMAINDER.\\n UDIVIDEND/SDIVIDEND are aliases of the same internal register. The U alias starts an\\n unsigned calculation, and the S alias starts a signed calculation.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [div_udividend](div_udividend) module"]
pub type DIV_UDIVIDEND = crate::Reg<u32, _DIV_UDIVIDEND>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DIV_UDIVIDEND;
#[doc = "`read()` method returns [div_udividend::R](div_udividend::R) reader structure"]
impl crate::Readable for DIV_UDIVIDEND {}
#[doc = "`write(|w| ..)` method takes [div_udividend::W](div_udividend::W) writer structure"]
impl crate::Writable for DIV_UDIVIDEND {}
#[doc = "Divider unsigned dividend\\n Write to the DIVIDEND operand of the divider, i.e. the p in `p / q`.\\n Any operand write starts a new calculation. The results appear in QUOTIENT, REMAINDER.\\n UDIVIDEND/SDIVIDEND are aliases of the same internal register. The U alias starts an\\n unsigned calculation, and the S alias starts a signed calculation."]
pub mod div_udividend;
#[doc = "Divider unsigned divisor\\n Write to the DIVISOR operand of the divider, i.e. the q in `p / q`.\\n Any operand write starts a new calculation. The results appear in QUOTIENT, REMAINDER.\\n UDIVIDEND/SDIVIDEND are aliases of the same internal register. The U alias starts an\\n unsigned calculation, and the S alias starts a signed calculation.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [div_udivisor](div_udivisor) module"]
pub type DIV_UDIVISOR = crate::Reg<u32, _DIV_UDIVISOR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DIV_UDIVISOR;
#[doc = "`read()` method returns [div_udivisor::R](div_udivisor::R) reader structure"]
impl crate::Readable for DIV_UDIVISOR {}
#[doc = "`write(|w| ..)` method takes [div_udivisor::W](div_udivisor::W) writer structure"]
impl crate::Writable for DIV_UDIVISOR {}
#[doc = "Divider unsigned divisor\\n Write to the DIVISOR operand of the divider, i.e. the q in `p / q`.\\n Any operand write starts a new calculation. The results appear in QUOTIENT, REMAINDER.\\n UDIVIDEND/SDIVIDEND are aliases of the same internal register. The U alias starts an\\n unsigned calculation, and the S alias starts a signed calculation."]
pub mod div_udivisor;
#[doc = "Divider signed dividend\\n The same as UDIVIDEND, but starts a signed calculation, rather than unsigned.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [div_sdividend](div_sdividend) module"]
pub type DIV_SDIVIDEND = crate::Reg<u32, _DIV_SDIVIDEND>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DIV_SDIVIDEND;
#[doc = "`read()` method returns [div_sdividend::R](div_sdividend::R) reader structure"]
impl crate::Readable for DIV_SDIVIDEND {}
#[doc = "`write(|w| ..)` method takes [div_sdividend::W](div_sdividend::W) writer structure"]
impl crate::Writable for DIV_SDIVIDEND {}
#[doc = "Divider signed dividend\\n The same as UDIVIDEND, but starts a signed calculation, rather than unsigned."]
pub mod div_sdividend;
#[doc = "Divider signed divisor\\n The same as UDIVISOR, but starts a signed calculation, rather than unsigned.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [div_sdivisor](div_sdivisor) module"]
pub type DIV_SDIVISOR = crate::Reg<u32, _DIV_SDIVISOR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DIV_SDIVISOR;
#[doc = "`read()` method returns [div_sdivisor::R](div_sdivisor::R) reader structure"]
impl crate::Readable for DIV_SDIVISOR {}
#[doc = "`write(|w| ..)` method takes [div_sdivisor::W](div_sdivisor::W) writer structure"]
impl crate::Writable for DIV_SDIVISOR {}
#[doc = "Divider signed divisor\\n The same as UDIVISOR, but starts a signed calculation, rather than unsigned."]
pub mod div_sdivisor;
#[doc = "Divider result quotient\\n The result of `DIVIDEND / DIVISOR` (division). Contents undefined while CSR_READY is low.\\n For signed calculations, QUOTIENT is negative when the signs of DIVIDEND and DIVISOR differ.\\n This register can be written to directly, for context save/restore purposes. This halts any\\n in-progress calculation and sets the CSR_READY and CSR_DIRTY flags.\\n Reading from QUOTIENT clears the CSR_DIRTY flag, so should read results in the order\\n REMAINDER, QUOTIENT if CSR_DIRTY is used.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [div_quotient](div_quotient) module"]
pub type DIV_QUOTIENT = crate::Reg<u32, _DIV_QUOTIENT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DIV_QUOTIENT;
#[doc = "`read()` method returns [div_quotient::R](div_quotient::R) reader structure"]
impl crate::Readable for DIV_QUOTIENT {}
#[doc = "`write(|w| ..)` method takes [div_quotient::W](div_quotient::W) writer structure"]
impl crate::Writable for DIV_QUOTIENT {}
#[doc = "Divider result quotient\\n The result of `DIVIDEND / DIVISOR` (division). Contents undefined while CSR_READY is low.\\n For signed calculations, QUOTIENT is negative when the signs of DIVIDEND and DIVISOR differ.\\n This register can be written to directly, for context save/restore purposes. This halts any\\n in-progress calculation and sets the CSR_READY and CSR_DIRTY flags.\\n Reading from QUOTIENT clears the CSR_DIRTY flag, so should read results in the order\\n REMAINDER, QUOTIENT if CSR_DIRTY is used."]
pub mod div_quotient;
#[doc = "Divider result remainder\\n The result of `DIVIDEND % DIVISOR` (modulo). Contents undefined while CSR_READY is low.\\n For signed calculations, REMAINDER is negative only when DIVIDEND is negative.\\n This register can be written to directly, for context save/restore purposes. This halts any\\n in-progress calculation and sets the CSR_READY and CSR_DIRTY flags.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [div_remainder](div_remainder) module"]
pub type DIV_REMAINDER = crate::Reg<u32, _DIV_REMAINDER>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DIV_REMAINDER;
#[doc = "`read()` method returns [div_remainder::R](div_remainder::R) reader structure"]
impl crate::Readable for DIV_REMAINDER {}
#[doc = "`write(|w| ..)` method takes [div_remainder::W](div_remainder::W) writer structure"]
impl crate::Writable for DIV_REMAINDER {}
#[doc = "Divider result remainder\\n The result of `DIVIDEND % DIVISOR` (modulo). Contents undefined while CSR_READY is low.\\n For signed calculations, REMAINDER is negative only when DIVIDEND is negative.\\n This register can be written to directly, for context save/restore purposes. This halts any\\n in-progress calculation and sets the CSR_READY and CSR_DIRTY flags."]
pub mod div_remainder;
#[doc = "Control and status register for divider.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [div_csr](div_csr) module"]
pub type DIV_CSR = crate::Reg<u32, _DIV_CSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DIV_CSR;
#[doc = "`read()` method returns [div_csr::R](div_csr::R) reader structure"]
impl crate::Readable for DIV_CSR {}
#[doc = "Control and status register for divider."]
pub mod div_csr;
#[doc = "Read/write access to accumulator 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_accum0](interp0_accum0) module"]
pub type INTERP0_ACCUM0 = crate::Reg<u32, _INTERP0_ACCUM0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_ACCUM0;
#[doc = "`read()` method returns [interp0_accum0::R](interp0_accum0::R) reader structure"]
impl crate::Readable for INTERP0_ACCUM0 {}
#[doc = "`write(|w| ..)` method takes [interp0_accum0::W](interp0_accum0::W) writer structure"]
impl crate::Writable for INTERP0_ACCUM0 {}
#[doc = "Read/write access to accumulator 0"]
pub mod interp0_accum0;
#[doc = "Read/write access to accumulator 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_accum1](interp0_accum1) module"]
pub type INTERP0_ACCUM1 = crate::Reg<u32, _INTERP0_ACCUM1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_ACCUM1;
#[doc = "`read()` method returns [interp0_accum1::R](interp0_accum1::R) reader structure"]
impl crate::Readable for INTERP0_ACCUM1 {}
#[doc = "`write(|w| ..)` method takes [interp0_accum1::W](interp0_accum1::W) writer structure"]
impl crate::Writable for INTERP0_ACCUM1 {}
#[doc = "Read/write access to accumulator 1"]
pub mod interp0_accum1;
#[doc = "Read/write access to BASE0 register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_base0](interp0_base0) module"]
pub type INTERP0_BASE0 = crate::Reg<u32, _INTERP0_BASE0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_BASE0;
#[doc = "`read()` method returns [interp0_base0::R](interp0_base0::R) reader structure"]
impl crate::Readable for INTERP0_BASE0 {}
#[doc = "`write(|w| ..)` method takes [interp0_base0::W](interp0_base0::W) writer structure"]
impl crate::Writable for INTERP0_BASE0 {}
#[doc = "Read/write access to BASE0 register."]
pub mod interp0_base0;
#[doc = "Read/write access to BASE1 register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_base1](interp0_base1) module"]
pub type INTERP0_BASE1 = crate::Reg<u32, _INTERP0_BASE1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_BASE1;
#[doc = "`read()` method returns [interp0_base1::R](interp0_base1::R) reader structure"]
impl crate::Readable for INTERP0_BASE1 {}
#[doc = "`write(|w| ..)` method takes [interp0_base1::W](interp0_base1::W) writer structure"]
impl crate::Writable for INTERP0_BASE1 {}
#[doc = "Read/write access to BASE1 register."]
pub mod interp0_base1;
#[doc = "Read/write access to BASE2 register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_base2](interp0_base2) module"]
pub type INTERP0_BASE2 = crate::Reg<u32, _INTERP0_BASE2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_BASE2;
#[doc = "`read()` method returns [interp0_base2::R](interp0_base2::R) reader structure"]
impl crate::Readable for INTERP0_BASE2 {}
#[doc = "`write(|w| ..)` method takes [interp0_base2::W](interp0_base2::W) writer structure"]
impl crate::Writable for INTERP0_BASE2 {}
#[doc = "Read/write access to BASE2 register."]
pub mod interp0_base2;
#[doc = "Read LANE0 result, and simultaneously write lane results to both accumulators (POP).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_pop_lane0](interp0_pop_lane0) module"]
pub type INTERP0_POP_LANE0 = crate::Reg<u32, _INTERP0_POP_LANE0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_POP_LANE0;
#[doc = "`read()` method returns [interp0_pop_lane0::R](interp0_pop_lane0::R) reader structure"]
impl crate::Readable for INTERP0_POP_LANE0 {}
#[doc = "Read LANE0 result, and simultaneously write lane results to both accumulators (POP)."]
pub mod interp0_pop_lane0;
#[doc = "Read LANE1 result, and simultaneously write lane results to both accumulators (POP).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_pop_lane1](interp0_pop_lane1) module"]
pub type INTERP0_POP_LANE1 = crate::Reg<u32, _INTERP0_POP_LANE1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_POP_LANE1;
#[doc = "`read()` method returns [interp0_pop_lane1::R](interp0_pop_lane1::R) reader structure"]
impl crate::Readable for INTERP0_POP_LANE1 {}
#[doc = "Read LANE1 result, and simultaneously write lane results to both accumulators (POP)."]
pub mod interp0_pop_lane1;
#[doc = "Read FULL result, and simultaneously write lane results to both accumulators (POP).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_pop_full](interp0_pop_full) module"]
pub type INTERP0_POP_FULL = crate::Reg<u32, _INTERP0_POP_FULL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_POP_FULL;
#[doc = "`read()` method returns [interp0_pop_full::R](interp0_pop_full::R) reader structure"]
impl crate::Readable for INTERP0_POP_FULL {}
#[doc = "Read FULL result, and simultaneously write lane results to both accumulators (POP)."]
pub mod interp0_pop_full;
#[doc = "Read LANE0 result, without altering any internal state (PEEK).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_peek_lane0](interp0_peek_lane0) module"]
pub type INTERP0_PEEK_LANE0 = crate::Reg<u32, _INTERP0_PEEK_LANE0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_PEEK_LANE0;
#[doc = "`read()` method returns [interp0_peek_lane0::R](interp0_peek_lane0::R) reader structure"]
impl crate::Readable for INTERP0_PEEK_LANE0 {}
#[doc = "Read LANE0 result, without altering any internal state (PEEK)."]
pub mod interp0_peek_lane0;
#[doc = "Read LANE1 result, without altering any internal state (PEEK).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_peek_lane1](interp0_peek_lane1) module"]
pub type INTERP0_PEEK_LANE1 = crate::Reg<u32, _INTERP0_PEEK_LANE1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_PEEK_LANE1;
#[doc = "`read()` method returns [interp0_peek_lane1::R](interp0_peek_lane1::R) reader structure"]
impl crate::Readable for INTERP0_PEEK_LANE1 {}
#[doc = "Read LANE1 result, without altering any internal state (PEEK)."]
pub mod interp0_peek_lane1;
#[doc = "Read FULL result, without altering any internal state (PEEK).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_peek_full](interp0_peek_full) module"]
pub type INTERP0_PEEK_FULL = crate::Reg<u32, _INTERP0_PEEK_FULL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_PEEK_FULL;
#[doc = "`read()` method returns [interp0_peek_full::R](interp0_peek_full::R) reader structure"]
impl crate::Readable for INTERP0_PEEK_FULL {}
#[doc = "Read FULL result, without altering any internal state (PEEK)."]
pub mod interp0_peek_full;
#[doc = "Control register for lane 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_ctrl_lane0](interp0_ctrl_lane0) module"]
pub type INTERP0_CTRL_LANE0 = crate::Reg<u32, _INTERP0_CTRL_LANE0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_CTRL_LANE0;
#[doc = "`read()` method returns [interp0_ctrl_lane0::R](interp0_ctrl_lane0::R) reader structure"]
impl crate::Readable for INTERP0_CTRL_LANE0 {}
#[doc = "`write(|w| ..)` method takes [interp0_ctrl_lane0::W](interp0_ctrl_lane0::W) writer structure"]
impl crate::Writable for INTERP0_CTRL_LANE0 {}
#[doc = "Control register for lane 0"]
pub mod interp0_ctrl_lane0;
#[doc = "Control register for lane 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_ctrl_lane1](interp0_ctrl_lane1) module"]
pub type INTERP0_CTRL_LANE1 = crate::Reg<u32, _INTERP0_CTRL_LANE1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_CTRL_LANE1;
#[doc = "`read()` method returns [interp0_ctrl_lane1::R](interp0_ctrl_lane1::R) reader structure"]
impl crate::Readable for INTERP0_CTRL_LANE1 {}
#[doc = "`write(|w| ..)` method takes [interp0_ctrl_lane1::W](interp0_ctrl_lane1::W) writer structure"]
impl crate::Writable for INTERP0_CTRL_LANE1 {}
#[doc = "Control register for lane 1"]
pub mod interp0_ctrl_lane1;
#[doc = "Values written here are atomically added to ACCUM0\\n Reading yields lane 0's raw shift and mask value (BASE0 not added).\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_accum0_add](interp0_accum0_add) module"]
pub type INTERP0_ACCUM0_ADD = crate::Reg<u32, _INTERP0_ACCUM0_ADD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_ACCUM0_ADD;
#[doc = "`read()` method returns [interp0_accum0_add::R](interp0_accum0_add::R) reader structure"]
impl crate::Readable for INTERP0_ACCUM0_ADD {}
#[doc = "`write(|w| ..)` method takes [interp0_accum0_add::W](interp0_accum0_add::W) writer structure"]
impl crate::Writable for INTERP0_ACCUM0_ADD {}
#[doc = "Values written here are atomically added to ACCUM0\\n Reading yields lane 0's raw shift and mask value (BASE0 not added)."]
pub mod interp0_accum0_add;
#[doc = "Values written here are atomically added to ACCUM1\\n Reading yields lane 1's raw shift and mask value (BASE1 not added).\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_accum1_add](interp0_accum1_add) module"]
pub type INTERP0_ACCUM1_ADD = crate::Reg<u32, _INTERP0_ACCUM1_ADD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_ACCUM1_ADD;
#[doc = "`read()` method returns [interp0_accum1_add::R](interp0_accum1_add::R) reader structure"]
impl crate::Readable for INTERP0_ACCUM1_ADD {}
#[doc = "`write(|w| ..)` method takes [interp0_accum1_add::W](interp0_accum1_add::W) writer structure"]
impl crate::Writable for INTERP0_ACCUM1_ADD {}
#[doc = "Values written here are atomically added to ACCUM1\\n Reading yields lane 1's raw shift and mask value (BASE1 not added)."]
pub mod interp0_accum1_add;
#[doc = "On write, the lower 16 bits go to BASE0, upper bits to BASE1 simultaneously.\\n Each half is sign-extended to 32 bits if that lane's SIGNED flag is set.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp0_base_1and0](interp0_base_1and0) module"]
pub type INTERP0_BASE_1AND0 = crate::Reg<u32, _INTERP0_BASE_1AND0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP0_BASE_1AND0;
#[doc = "`read()` method returns [interp0_base_1and0::R](interp0_base_1and0::R) reader structure"]
impl crate::Readable for INTERP0_BASE_1AND0 {}
#[doc = "`write(|w| ..)` method takes [interp0_base_1and0::W](interp0_base_1and0::W) writer structure"]
impl crate::Writable for INTERP0_BASE_1AND0 {}
#[doc = "On write, the lower 16 bits go to BASE0, upper bits to BASE1 simultaneously.\\n Each half is sign-extended to 32 bits if that lane's SIGNED flag is set."]
pub mod interp0_base_1and0;
#[doc = "Read/write access to accumulator 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_accum0](interp1_accum0) module"]
pub type INTERP1_ACCUM0 = crate::Reg<u32, _INTERP1_ACCUM0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_ACCUM0;
#[doc = "`read()` method returns [interp1_accum0::R](interp1_accum0::R) reader structure"]
impl crate::Readable for INTERP1_ACCUM0 {}
#[doc = "`write(|w| ..)` method takes [interp1_accum0::W](interp1_accum0::W) writer structure"]
impl crate::Writable for INTERP1_ACCUM0 {}
#[doc = "Read/write access to accumulator 0"]
pub mod interp1_accum0;
#[doc = "Read/write access to accumulator 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_accum1](interp1_accum1) module"]
pub type INTERP1_ACCUM1 = crate::Reg<u32, _INTERP1_ACCUM1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_ACCUM1;
#[doc = "`read()` method returns [interp1_accum1::R](interp1_accum1::R) reader structure"]
impl crate::Readable for INTERP1_ACCUM1 {}
#[doc = "`write(|w| ..)` method takes [interp1_accum1::W](interp1_accum1::W) writer structure"]
impl crate::Writable for INTERP1_ACCUM1 {}
#[doc = "Read/write access to accumulator 1"]
pub mod interp1_accum1;
#[doc = "Read/write access to BASE0 register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_base0](interp1_base0) module"]
pub type INTERP1_BASE0 = crate::Reg<u32, _INTERP1_BASE0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_BASE0;
#[doc = "`read()` method returns [interp1_base0::R](interp1_base0::R) reader structure"]
impl crate::Readable for INTERP1_BASE0 {}
#[doc = "`write(|w| ..)` method takes [interp1_base0::W](interp1_base0::W) writer structure"]
impl crate::Writable for INTERP1_BASE0 {}
#[doc = "Read/write access to BASE0 register."]
pub mod interp1_base0;
#[doc = "Read/write access to BASE1 register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_base1](interp1_base1) module"]
pub type INTERP1_BASE1 = crate::Reg<u32, _INTERP1_BASE1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_BASE1;
#[doc = "`read()` method returns [interp1_base1::R](interp1_base1::R) reader structure"]
impl crate::Readable for INTERP1_BASE1 {}
#[doc = "`write(|w| ..)` method takes [interp1_base1::W](interp1_base1::W) writer structure"]
impl crate::Writable for INTERP1_BASE1 {}
#[doc = "Read/write access to BASE1 register."]
pub mod interp1_base1;
#[doc = "Read/write access to BASE2 register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_base2](interp1_base2) module"]
pub type INTERP1_BASE2 = crate::Reg<u32, _INTERP1_BASE2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_BASE2;
#[doc = "`read()` method returns [interp1_base2::R](interp1_base2::R) reader structure"]
impl crate::Readable for INTERP1_BASE2 {}
#[doc = "`write(|w| ..)` method takes [interp1_base2::W](interp1_base2::W) writer structure"]
impl crate::Writable for INTERP1_BASE2 {}
#[doc = "Read/write access to BASE2 register."]
pub mod interp1_base2;
#[doc = "Read LANE0 result, and simultaneously write lane results to both accumulators (POP).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_pop_lane0](interp1_pop_lane0) module"]
pub type INTERP1_POP_LANE0 = crate::Reg<u32, _INTERP1_POP_LANE0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_POP_LANE0;
#[doc = "`read()` method returns [interp1_pop_lane0::R](interp1_pop_lane0::R) reader structure"]
impl crate::Readable for INTERP1_POP_LANE0 {}
#[doc = "Read LANE0 result, and simultaneously write lane results to both accumulators (POP)."]
pub mod interp1_pop_lane0;
#[doc = "Read LANE1 result, and simultaneously write lane results to both accumulators (POP).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_pop_lane1](interp1_pop_lane1) module"]
pub type INTERP1_POP_LANE1 = crate::Reg<u32, _INTERP1_POP_LANE1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_POP_LANE1;
#[doc = "`read()` method returns [interp1_pop_lane1::R](interp1_pop_lane1::R) reader structure"]
impl crate::Readable for INTERP1_POP_LANE1 {}
#[doc = "Read LANE1 result, and simultaneously write lane results to both accumulators (POP)."]
pub mod interp1_pop_lane1;
#[doc = "Read FULL result, and simultaneously write lane results to both accumulators (POP).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_pop_full](interp1_pop_full) module"]
pub type INTERP1_POP_FULL = crate::Reg<u32, _INTERP1_POP_FULL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_POP_FULL;
#[doc = "`read()` method returns [interp1_pop_full::R](interp1_pop_full::R) reader structure"]
impl crate::Readable for INTERP1_POP_FULL {}
#[doc = "Read FULL result, and simultaneously write lane results to both accumulators (POP)."]
pub mod interp1_pop_full;
#[doc = "Read LANE0 result, without altering any internal state (PEEK).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_peek_lane0](interp1_peek_lane0) module"]
pub type INTERP1_PEEK_LANE0 = crate::Reg<u32, _INTERP1_PEEK_LANE0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_PEEK_LANE0;
#[doc = "`read()` method returns [interp1_peek_lane0::R](interp1_peek_lane0::R) reader structure"]
impl crate::Readable for INTERP1_PEEK_LANE0 {}
#[doc = "Read LANE0 result, without altering any internal state (PEEK)."]
pub mod interp1_peek_lane0;
#[doc = "Read LANE1 result, without altering any internal state (PEEK).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_peek_lane1](interp1_peek_lane1) module"]
pub type INTERP1_PEEK_LANE1 = crate::Reg<u32, _INTERP1_PEEK_LANE1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_PEEK_LANE1;
#[doc = "`read()` method returns [interp1_peek_lane1::R](interp1_peek_lane1::R) reader structure"]
impl crate::Readable for INTERP1_PEEK_LANE1 {}
#[doc = "Read LANE1 result, without altering any internal state (PEEK)."]
pub mod interp1_peek_lane1;
#[doc = "Read FULL result, without altering any internal state (PEEK).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_peek_full](interp1_peek_full) module"]
pub type INTERP1_PEEK_FULL = crate::Reg<u32, _INTERP1_PEEK_FULL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_PEEK_FULL;
#[doc = "`read()` method returns [interp1_peek_full::R](interp1_peek_full::R) reader structure"]
impl crate::Readable for INTERP1_PEEK_FULL {}
#[doc = "Read FULL result, without altering any internal state (PEEK)."]
pub mod interp1_peek_full;
#[doc = "Control register for lane 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_ctrl_lane0](interp1_ctrl_lane0) module"]
pub type INTERP1_CTRL_LANE0 = crate::Reg<u32, _INTERP1_CTRL_LANE0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_CTRL_LANE0;
#[doc = "`read()` method returns [interp1_ctrl_lane0::R](interp1_ctrl_lane0::R) reader structure"]
impl crate::Readable for INTERP1_CTRL_LANE0 {}
#[doc = "`write(|w| ..)` method takes [interp1_ctrl_lane0::W](interp1_ctrl_lane0::W) writer structure"]
impl crate::Writable for INTERP1_CTRL_LANE0 {}
#[doc = "Control register for lane 0"]
pub mod interp1_ctrl_lane0;
#[doc = "Control register for lane 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_ctrl_lane1](interp1_ctrl_lane1) module"]
pub type INTERP1_CTRL_LANE1 = crate::Reg<u32, _INTERP1_CTRL_LANE1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_CTRL_LANE1;
#[doc = "`read()` method returns [interp1_ctrl_lane1::R](interp1_ctrl_lane1::R) reader structure"]
impl crate::Readable for INTERP1_CTRL_LANE1 {}
#[doc = "`write(|w| ..)` method takes [interp1_ctrl_lane1::W](interp1_ctrl_lane1::W) writer structure"]
impl crate::Writable for INTERP1_CTRL_LANE1 {}
#[doc = "Control register for lane 1"]
pub mod interp1_ctrl_lane1;
#[doc = "Values written here are atomically added to ACCUM0\\n Reading yields lane 0's raw shift and mask value (BASE0 not added).\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_accum0_add](interp1_accum0_add) module"]
pub type INTERP1_ACCUM0_ADD = crate::Reg<u32, _INTERP1_ACCUM0_ADD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_ACCUM0_ADD;
#[doc = "`read()` method returns [interp1_accum0_add::R](interp1_accum0_add::R) reader structure"]
impl crate::Readable for INTERP1_ACCUM0_ADD {}
#[doc = "`write(|w| ..)` method takes [interp1_accum0_add::W](interp1_accum0_add::W) writer structure"]
impl crate::Writable for INTERP1_ACCUM0_ADD {}
#[doc = "Values written here are atomically added to ACCUM0\\n Reading yields lane 0's raw shift and mask value (BASE0 not added)."]
pub mod interp1_accum0_add;
#[doc = "Values written here are atomically added to ACCUM1\\n Reading yields lane 1's raw shift and mask value (BASE1 not added).\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_accum1_add](interp1_accum1_add) module"]
pub type INTERP1_ACCUM1_ADD = crate::Reg<u32, _INTERP1_ACCUM1_ADD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_ACCUM1_ADD;
#[doc = "`read()` method returns [interp1_accum1_add::R](interp1_accum1_add::R) reader structure"]
impl crate::Readable for INTERP1_ACCUM1_ADD {}
#[doc = "`write(|w| ..)` method takes [interp1_accum1_add::W](interp1_accum1_add::W) writer structure"]
impl crate::Writable for INTERP1_ACCUM1_ADD {}
#[doc = "Values written here are atomically added to ACCUM1\\n Reading yields lane 1's raw shift and mask value (BASE1 not added)."]
pub mod interp1_accum1_add;
#[doc = "On write, the lower 16 bits go to BASE0, upper bits to BASE1 simultaneously.\\n Each half is sign-extended to 32 bits if that lane's SIGNED flag is set.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interp1_base_1and0](interp1_base_1and0) module"]
pub type INTERP1_BASE_1AND0 = crate::Reg<u32, _INTERP1_BASE_1AND0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTERP1_BASE_1AND0;
#[doc = "`read()` method returns [interp1_base_1and0::R](interp1_base_1and0::R) reader structure"]
impl crate::Readable for INTERP1_BASE_1AND0 {}
#[doc = "`write(|w| ..)` method takes [interp1_base_1and0::W](interp1_base_1and0::W) writer structure"]
impl crate::Writable for INTERP1_BASE_1AND0 {}
#[doc = "On write, the lower 16 bits go to BASE0, upper bits to BASE1 simultaneously.\\n Each half is sign-extended to 32 bits if that lane's SIGNED flag is set."]
pub mod interp1_base_1and0;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock0](spinlock0) module"]
pub type SPINLOCK0 = crate::Reg<u32, _SPINLOCK0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK0;
#[doc = "`read()` method returns [spinlock0::R](spinlock0::R) reader structure"]
impl crate::Readable for SPINLOCK0 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock0;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock1](spinlock1) module"]
pub type SPINLOCK1 = crate::Reg<u32, _SPINLOCK1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK1;
#[doc = "`read()` method returns [spinlock1::R](spinlock1::R) reader structure"]
impl crate::Readable for SPINLOCK1 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock1;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock2](spinlock2) module"]
pub type SPINLOCK2 = crate::Reg<u32, _SPINLOCK2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK2;
#[doc = "`read()` method returns [spinlock2::R](spinlock2::R) reader structure"]
impl crate::Readable for SPINLOCK2 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock2;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock3](spinlock3) module"]
pub type SPINLOCK3 = crate::Reg<u32, _SPINLOCK3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK3;
#[doc = "`read()` method returns [spinlock3::R](spinlock3::R) reader structure"]
impl crate::Readable for SPINLOCK3 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock3;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock4](spinlock4) module"]
pub type SPINLOCK4 = crate::Reg<u32, _SPINLOCK4>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK4;
#[doc = "`read()` method returns [spinlock4::R](spinlock4::R) reader structure"]
impl crate::Readable for SPINLOCK4 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock4;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock5](spinlock5) module"]
pub type SPINLOCK5 = crate::Reg<u32, _SPINLOCK5>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK5;
#[doc = "`read()` method returns [spinlock5::R](spinlock5::R) reader structure"]
impl crate::Readable for SPINLOCK5 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock5;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock6](spinlock6) module"]
pub type SPINLOCK6 = crate::Reg<u32, _SPINLOCK6>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK6;
#[doc = "`read()` method returns [spinlock6::R](spinlock6::R) reader structure"]
impl crate::Readable for SPINLOCK6 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock6;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock7](spinlock7) module"]
pub type SPINLOCK7 = crate::Reg<u32, _SPINLOCK7>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK7;
#[doc = "`read()` method returns [spinlock7::R](spinlock7::R) reader structure"]
impl crate::Readable for SPINLOCK7 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock7;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock8](spinlock8) module"]
pub type SPINLOCK8 = crate::Reg<u32, _SPINLOCK8>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK8;
#[doc = "`read()` method returns [spinlock8::R](spinlock8::R) reader structure"]
impl crate::Readable for SPINLOCK8 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock8;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock9](spinlock9) module"]
pub type SPINLOCK9 = crate::Reg<u32, _SPINLOCK9>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK9;
#[doc = "`read()` method returns [spinlock9::R](spinlock9::R) reader structure"]
impl crate::Readable for SPINLOCK9 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock9;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock10](spinlock10) module"]
pub type SPINLOCK10 = crate::Reg<u32, _SPINLOCK10>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK10;
#[doc = "`read()` method returns [spinlock10::R](spinlock10::R) reader structure"]
impl crate::Readable for SPINLOCK10 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock10;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock11](spinlock11) module"]
pub type SPINLOCK11 = crate::Reg<u32, _SPINLOCK11>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK11;
#[doc = "`read()` method returns [spinlock11::R](spinlock11::R) reader structure"]
impl crate::Readable for SPINLOCK11 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock11;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock12](spinlock12) module"]
pub type SPINLOCK12 = crate::Reg<u32, _SPINLOCK12>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK12;
#[doc = "`read()` method returns [spinlock12::R](spinlock12::R) reader structure"]
impl crate::Readable for SPINLOCK12 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock12;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock13](spinlock13) module"]
pub type SPINLOCK13 = crate::Reg<u32, _SPINLOCK13>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK13;
#[doc = "`read()` method returns [spinlock13::R](spinlock13::R) reader structure"]
impl crate::Readable for SPINLOCK13 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock13;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock14](spinlock14) module"]
pub type SPINLOCK14 = crate::Reg<u32, _SPINLOCK14>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK14;
#[doc = "`read()` method returns [spinlock14::R](spinlock14::R) reader structure"]
impl crate::Readable for SPINLOCK14 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock14;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock15](spinlock15) module"]
pub type SPINLOCK15 = crate::Reg<u32, _SPINLOCK15>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK15;
#[doc = "`read()` method returns [spinlock15::R](spinlock15::R) reader structure"]
impl crate::Readable for SPINLOCK15 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock15;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock16](spinlock16) module"]
pub type SPINLOCK16 = crate::Reg<u32, _SPINLOCK16>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK16;
#[doc = "`read()` method returns [spinlock16::R](spinlock16::R) reader structure"]
impl crate::Readable for SPINLOCK16 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock16;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock17](spinlock17) module"]
pub type SPINLOCK17 = crate::Reg<u32, _SPINLOCK17>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK17;
#[doc = "`read()` method returns [spinlock17::R](spinlock17::R) reader structure"]
impl crate::Readable for SPINLOCK17 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock17;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock18](spinlock18) module"]
pub type SPINLOCK18 = crate::Reg<u32, _SPINLOCK18>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK18;
#[doc = "`read()` method returns [spinlock18::R](spinlock18::R) reader structure"]
impl crate::Readable for SPINLOCK18 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock18;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock19](spinlock19) module"]
pub type SPINLOCK19 = crate::Reg<u32, _SPINLOCK19>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK19;
#[doc = "`read()` method returns [spinlock19::R](spinlock19::R) reader structure"]
impl crate::Readable for SPINLOCK19 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock19;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock20](spinlock20) module"]
pub type SPINLOCK20 = crate::Reg<u32, _SPINLOCK20>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK20;
#[doc = "`read()` method returns [spinlock20::R](spinlock20::R) reader structure"]
impl crate::Readable for SPINLOCK20 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock20;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock21](spinlock21) module"]
pub type SPINLOCK21 = crate::Reg<u32, _SPINLOCK21>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK21;
#[doc = "`read()` method returns [spinlock21::R](spinlock21::R) reader structure"]
impl crate::Readable for SPINLOCK21 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock21;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock22](spinlock22) module"]
pub type SPINLOCK22 = crate::Reg<u32, _SPINLOCK22>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK22;
#[doc = "`read()` method returns [spinlock22::R](spinlock22::R) reader structure"]
impl crate::Readable for SPINLOCK22 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock22;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock23](spinlock23) module"]
pub type SPINLOCK23 = crate::Reg<u32, _SPINLOCK23>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK23;
#[doc = "`read()` method returns [spinlock23::R](spinlock23::R) reader structure"]
impl crate::Readable for SPINLOCK23 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock23;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock24](spinlock24) module"]
pub type SPINLOCK24 = crate::Reg<u32, _SPINLOCK24>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK24;
#[doc = "`read()` method returns [spinlock24::R](spinlock24::R) reader structure"]
impl crate::Readable for SPINLOCK24 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock24;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock25](spinlock25) module"]
pub type SPINLOCK25 = crate::Reg<u32, _SPINLOCK25>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK25;
#[doc = "`read()` method returns [spinlock25::R](spinlock25::R) reader structure"]
impl crate::Readable for SPINLOCK25 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock25;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock26](spinlock26) module"]
pub type SPINLOCK26 = crate::Reg<u32, _SPINLOCK26>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK26;
#[doc = "`read()` method returns [spinlock26::R](spinlock26::R) reader structure"]
impl crate::Readable for SPINLOCK26 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock26;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock27](spinlock27) module"]
pub type SPINLOCK27 = crate::Reg<u32, _SPINLOCK27>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK27;
#[doc = "`read()` method returns [spinlock27::R](spinlock27::R) reader structure"]
impl crate::Readable for SPINLOCK27 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock27;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock28](spinlock28) module"]
pub type SPINLOCK28 = crate::Reg<u32, _SPINLOCK28>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK28;
#[doc = "`read()` method returns [spinlock28::R](spinlock28::R) reader structure"]
impl crate::Readable for SPINLOCK28 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock28;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock29](spinlock29) module"]
pub type SPINLOCK29 = crate::Reg<u32, _SPINLOCK29>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK29;
#[doc = "`read()` method returns [spinlock29::R](spinlock29::R) reader structure"]
impl crate::Readable for SPINLOCK29 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock29;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock30](spinlock30) module"]
pub type SPINLOCK30 = crate::Reg<u32, _SPINLOCK30>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK30;
#[doc = "`read()` method returns [spinlock30::R](spinlock30::R) reader structure"]
impl crate::Readable for SPINLOCK30 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock30;
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [spinlock31](spinlock31) module"]
pub type SPINLOCK31 = crate::Reg<u32, _SPINLOCK31>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SPINLOCK31;
#[doc = "`read()` method returns [spinlock31::R](spinlock31::R) reader structure"]
impl crate::Readable for SPINLOCK31 {}
#[doc = "Reading from a spinlock address will:\\n - Return 0 if lock is already locked\\n - Otherwise return nonzero, and simultaneously claim the lock\\n\\n Writing (any value) releases the lock.\\n If core 0 and core 1 attempt to claim the same lock simultaneously, core 0 wins.\\n The value returned on success is 0x1 << lock number."]
pub mod spinlock31;
|
use rdkafka::ClientConfig;
use serde::Deserialize;
use std::collections::HashMap;
use std::ops::Deref;
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
pub struct KafkaClientConfig {
#[serde(default = "kafka_bootstrap_servers")]
pub bootstrap_servers: String,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub properties: HashMap<String, String>,
}
impl Default for KafkaClientConfig {
fn default() -> Self {
Self {
bootstrap_servers: kafka_bootstrap_servers(),
properties: Default::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
pub struct KafkaConfig {
#[serde(flatten)]
pub client: KafkaClientConfig,
pub topic: String,
}
impl From<KafkaClientConfig> for ClientConfig {
fn from(cfg: KafkaClientConfig) -> Self {
let mut result = ClientConfig::new();
result.set("bootstrap.servers", &cfg.bootstrap_servers);
for (k, v) in cfg.properties {
result.set(k.replace('_', "."), v);
}
result
}
}
impl Deref for KafkaConfig {
type Target = KafkaClientConfig;
fn deref(&self) -> &Self::Target {
&self.client
}
}
#[inline]
pub fn kafka_bootstrap_servers() -> String {
"drogue-iot-kafka-bootstrap:9092".into()
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_custom() {
std::env::set_var("KAFKA__PROPERTIES__A_B_C", "d.e.f");
let env = config::Environment::with_prefix(&format!("{}_", "KAFKA"));
let mut cfg = config::Config::new();
cfg.merge(env.separator("__")).unwrap();
let kafka: KafkaClientConfig = cfg.try_into().unwrap();
assert_eq!(kafka.properties.get("a_b_c").cloned(), Some("d.e.f".into()));
std::env::remove_var("KAFKA__PROPERTIES__A_B_C");
}
}
|
mod construction;
pub mod display;
mod encode_into;
mod parameter_type;
mod utils;
pub use encode_into::encode_into;
pub use parameter_type::ParameterType;
use utils::*;
use ethane_types::{Address, H256};
/// An ABI function parameter type enclosing the underlying
/// numeric data bytes.
#[derive(Clone)]
pub enum Parameter {
Address(H256),
Bool(H256),
Int(H256, usize),
Uint(H256, usize),
String(Vec<u8>),
Bytes(Vec<u8>),
FixedBytes(Vec<u8>),
Array(Vec<Parameter>),
FixedArray(Vec<Parameter>),
Tuple(Vec<Parameter>),
}
impl Parameter {
/// Encodes strictly the data part of the underlying type.
///
/// It will not check whether the parameter is dynamic or not, it simply
/// encodes the enclosed data in place. For some types, it first writes the
/// number of elements of the data in bytes. For further info, check the
/// Solidity [contract ABI
/// specification](https://docs.soliditylang.org/en/v0.5.3/abi-spec.html#function-selector).
pub fn static_encode(&self) -> Vec<u8> {
match self {
Self::Address(data) | Self::Bool(data) | Self::Int(data, _) | Self::Uint(data, _) => {
data.as_bytes().to_vec()
}
Self::FixedBytes(data) => right_pad_to_32_multiples(data).to_vec(),
Self::Bytes(data) | Self::String(data) => {
let mut encoded = left_pad_to_32_bytes(&data.len().to_be_bytes()).to_vec();
encoded.extend_from_slice(&right_pad_to_32_multiples(data));
encoded
}
Self::FixedArray(params) | Self::Tuple(params) => {
let mut encoded = Vec::<u8>::new();
for p in params {
encoded.extend_from_slice(&p.static_encode());
}
encoded
}
Self::Array(_) => panic!("Array type cannot be statically encoded!"),
}
}
/// Recursively checks wether a given parameter is dynamic.
///
/// For example, a [`Tuple`](Parameter::Tuple) can be dynamic if any of its
/// contained types are dynamic. Additionally, a
/// [`FixedArray`](Parameter::FixedArray) is static if it contains values
/// with static type and dynamic otherwise.
pub fn is_dynamic(&self) -> bool {
match self {
Self::Array(_) | Self::Bytes(_) | Self::String(_) => true,
Self::FixedArray(parameters) | Self::Tuple(parameters) => {
parameters.iter().any(|x| x.is_dynamic())
}
_ => false,
}
}
pub fn decode(parameter_type: &ParameterType, raw_bytes: &[u8]) -> (Self, usize) {
match parameter_type {
ParameterType::Address => {
let mut bytes = [0u8; 20];
bytes.copy_from_slice(&raw_bytes[12..32]);
(Self::from(Address::from(bytes)), 32)
}
ParameterType::Bool => {
let mut bytes = [0u8; 32];
bytes.copy_from_slice(&raw_bytes[..32]);
(Self::Bool(H256::from(bytes)), 32)
}
ParameterType::Int(_) => {
let mut bytes = [0u8; 32];
bytes.copy_from_slice(&raw_bytes[..32]);
(Self::new_int(bytes, true), 32)
}
ParameterType::Uint(_) => {
let mut bytes = [0u8; 32];
bytes.copy_from_slice(&raw_bytes[..32]);
(Self::new_int(bytes, false), 32)
}
//ParameterType::String => {
// (Self::String(raw_bytes.to_vec()), )
//},
//ParameterType::Bytes => {
// Ok(Self::Bytes(raw_bytes.to_vec()))
//},
//ParameterType::FixedBytes(len) => {
// Ok(Self::FixedBytes(raw_bytes.to_vec())
//},
//// TODO do we need more complicated types?
_ => unimplemented!(),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
#[rustfmt::skip]
fn parameter_encode() {
assert_eq!(Parameter::Address(H256::zero()).static_encode(), vec![0u8; 32]);
assert_eq!(Parameter::from("Hello, World!").static_encode(), vec![
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0x0d,
0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57,
0x6f, 0x72, 0x6c, 0x64, 0x21, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
]);
assert_eq!(Parameter::FixedArray(vec![
Parameter::Uint(H256::from_int_unchecked(0x4a_u8), 8),
Parameter::Uint(H256::from_int_unchecked(0xff_u8), 8),
Parameter::Uint(H256::from_int_unchecked(0xde_u8), 8),
]).static_encode(),
vec![
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0x4a, // first
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0xff, // second
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0xde, // third
]);
}
#[test]
fn parameter_is_dynamic() {
assert!(!Parameter::Address(H256::zero()).is_dynamic());
assert!(!Parameter::Bool(H256::zero()).is_dynamic());
assert!(Parameter::Bytes(Vec::new()).is_dynamic());
assert!(!Parameter::FixedBytes(Vec::new()).is_dynamic());
assert!(!Parameter::Uint(H256::zero(), 16).is_dynamic());
assert!(!Parameter::Int(H256::zero(), 32).is_dynamic());
assert!(Parameter::String(Vec::new()).is_dynamic());
assert!(Parameter::Array(vec![Parameter::Address(H256::zero()); 5]).is_dynamic());
assert!(Parameter::Array(vec![Parameter::Bytes(Vec::new())]).is_dynamic());
assert!(!Parameter::FixedArray(vec![Parameter::Uint(H256::zero(), 64); 3]).is_dynamic());
assert!(Parameter::FixedArray(vec![Parameter::String(Vec::new()); 2]).is_dynamic());
assert!(!Parameter::Tuple(vec![
Parameter::Address(H256::zero()),
Parameter::Uint(H256::zero(), 32),
Parameter::FixedBytes(Vec::new())
])
.is_dynamic());
assert!(Parameter::Tuple(vec![
Parameter::FixedBytes(Vec::new()),
Parameter::Uint(H256::zero(), 32),
Parameter::String(Vec::new())
])
.is_dynamic());
assert!(!Parameter::FixedArray(vec![
Parameter::FixedArray(vec![
Parameter::Int(
H256::zero(),
8
);
5
]);
2
])
.is_dynamic());
assert!(Parameter::Tuple(vec![
Parameter::FixedBytes(Vec::new()),
Parameter::Uint(H256::zero(), 32),
Parameter::FixedArray(vec![Parameter::String(Vec::new()); 3])
])
.is_dynamic());
}
#[test]
#[rustfmt::skip]
fn decode_parameter() {
let result = vec![
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x0a, 0xff,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x0b, 0xff,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x0c, 0xff,
];
let mut index = 0;
let (addr, bytes_read) = Parameter::decode(&ParameterType::Address, &result);
index += bytes_read;
let (a, bytes_read) = Parameter::decode(&ParameterType::Uint(16), &result[index..]);
index += bytes_read;
let (b, bytes_read) = Parameter::decode(&ParameterType::Uint(16), &result[index..]);
index += bytes_read;
let (c, bytes_read) = Parameter::decode(&ParameterType::Uint(16), &result[index..]);
index += bytes_read;
assert_eq!(index, 128);
assert_eq!(addr.to_string(), String::from("0xffffffffffffffffffffffffffffffffffffffff"));
assert_eq!(a.to_string(), String::from("2815"));
assert_eq!(b.to_string(), String::from("3071"));
assert_eq!(c.to_string(), String::from("3327"));
}
}
|
use std::fmt;
use std::rc::{Rc, Weak};
use std::cell::RefCell;
use std::hash::{Hash, Hasher};
use std::collections::HashMap;
use sha3::{Sha3_256, Digest};
use faster_hex::{hex_string};
#[derive(Debug, Clone)]
enum NodeType<'a> {
Branch{
left: Rc<Node<'a>>, // shared ownership
right: Rc<Node<'a>>, // shared ownership
},
Leaf{
data: &'a [u8]
},
}
#[derive(Debug)]
struct Node<'a> {
r#type: NodeType<'a>,
label: String,
parent: RefCell<Weak<Node<'a>>>, // interior mutability
}
impl<'a> Hash for Node<'a> {
fn hash<H: Hasher>(&self, state: &mut H) {
for b in self.label.as_bytes() {
state.write_u8(*b);
}
}
}
/**
* Balanced binary Merkle tree.
* Balanced: left and right subtrees of every node differ in height by no more than 1.
*/
pub struct MerkleTree<'a> {
root: Rc<Node<'a>>,
nodes: HashMap<String, Rc<Node<'a>>>, // indexed by label
// data_map: HashMap<String, Rc<Node<'a>>>,
}
impl<'a> fmt::Debug for MerkleTree<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:#?}", self.root)
}
}
impl<'a> MerkleTree<'a> {
/**
* Time complexity wrt data items: n + log2(n)
*
* NEW ALGO TODO for proper+complete binary tree
* - let complete_tree = make_tree(leaves.rev()[0..floor(log2(leaves.length))])
* ^--> create a proper and complete tree starting from the _last_ "smallest power of 2" leaves
* - add new level s.t.
*
*/
pub fn from_data(data: &[&'a[u8]]) -> MerkleTree<'a> {
// Stores branches for the 'current' tree level to be processed
let mut nodes_stack: Vec<Rc<Node<'a>>> = vec![];
let mut nodes_map: HashMap<String, Rc<Node<'a>>> = HashMap::new();
// let mut leaves_map = HashMap::new();
// The balanced binary Merkle tree is built starting from the leaves.
for d/*: &[u8] */ in data.into_iter().rev() {
let _z: &'a[u8] = d;
let leaf = MerkleTree::make_leaf(d);
nodes_map.insert(leaf.label.clone(), leaf.clone());
nodes_stack.push(leaf);
}
// process current level nodes to build nodes for the upper level.
while nodes_stack.len() > 1 {
let mut parents: Vec<Rc<Node<'a>>> = Vec::new(); // New nodes for the upper level
// Builds parent nodes
while nodes_stack.len() > 1 {
let child_left = nodes_stack.pop().unwrap();
let child_right = nodes_stack.pop().unwrap(); // nodes.len() > 1
let b = MerkleTree::make_branch(child_left, child_right); // moves ownership of children
nodes_map.insert(b.label.clone(), b.clone());
parents.insert(0, b);
}
if let Some(n) = nodes_stack.pop() {
parents.insert(0, n); // odd number of nodes, moves the remaining node to the right of the tree
}
nodes_stack = parents;
}
assert_eq!(nodes_stack.len(), 1);
let tree = MerkleTree{
root: nodes_stack.pop().unwrap_or_else(|| panic!("Empty merkle tree!?")).clone(),
nodes: nodes_map
};
tree
}
// #[allow(dead_code)]
// pub fn complete_from_data(data: &[&'a[u8]]) -> MerkleTree<'a> {
// }
/**
* [Auth0, Auth1, .., Auth(i)] where 0 <= i < Height
* i.e. from the leaf's sibling to the root's children
*/
pub fn make_proof(&self, data: &'a [u8]) -> Result<Vec<String>, &'static str> {
let hash = MerkleTree::sha3_hex(data);
// let node = *self..
let leaf: &Rc<Node> = self.nodes.get(hash.as_str()).ok_or_else(|| "Provided data not included in the tree")?;
let mut node = leaf.clone();
let mut proof = Vec::new();
while let Some(parent) = node.clone().parent.borrow().upgrade() {
match &parent.r#type { // parent: Rc<Node>
NodeType::Branch{left: l, right: r} => {
if Rc::ptr_eq(l, &node) {
proof.push(r.label.clone());
} else if Rc::ptr_eq(r, &node) {
proof.push(l.label.clone());
} else {
panic!("Wrong parent<->children references");
}
}
_ => ()
}
node = parent;
}
// assert proof length = height - 1
return Ok(proof);
}
/**
* Problem:
* the current method requires knowledge of the tree structure
* in order to properly concatenate hashes (left||right !== right||left)s
*/
pub fn authenticate(&self, data: &'a [u8], proof: &[String]) -> bool {
let mut node = match self.nodes.get(&MerkleTree::make_label(data)) {
Some(n) => n.clone(),
None => return false
};
for auth in proof {
let parent = match node.parent.borrow().upgrade() {
Some(n) => n,
None => return false // every proof's hash must have a parent. Root is not included in proofs.
};
let sibling: &Rc<Node<'a>> = match &parent.r#type {
NodeType::Branch{left: l, right: r} => {
match &l.label == auth {
true => l,
false => r,
}
}
_ => panic!("Parent must have children!")
};
if sibling.label != *auth {
return false;
}
node = parent;
}
true
}
fn make_leaf(data: &'a [u8]) -> Rc<Node<'a>> { // 1st + 2nd lifetime elision rule???
Rc::new(Node{
r#type: NodeType::Leaf{ data: data },
label: MerkleTree::make_label(data),
parent: RefCell::new(Weak::new()),
})
}
fn make_branch(child_left: Rc<Node<'a>>, child_right: Rc<Node<'a>>) -> Rc<Node<'a>> {
let label: String = MerkleTree::make_label([
child_left.label.as_str(), child_right.label.as_str()
].concat().as_bytes());
// Rc needed to be able to create a weak reference for its children
let branch = Rc::new(Node{
r#type: NodeType::Branch {
left: child_left,
right: child_right,
},
label: label,
parent: RefCell::new(Weak::new()),
});
if let NodeType::Branch{left: l, right: r, ..} = &branch.r#type {
*l.parent.borrow_mut() = Rc::downgrade(&branch);
*r.parent.borrow_mut() = Rc::downgrade(&branch);
}
branch
}
#[allow(dead_code)]
fn node_depth(&self, node: &Rc<Node>) -> usize {
let mut depth = 0;
let mut node: Rc<Node> = node.clone();
while let Some(parent) = node.clone().parent.borrow().upgrade() {
node = parent;
depth = depth + 1;
}
depth
}
#[allow(dead_code)]
fn count_nodes(&self) -> usize {
MerkleTree::count_descendants(&self.root)
}
#[allow(dead_code)]
fn count_leaves(&self) -> usize {
MerkleTree::count_descendant_leaves(&self.root)
}
fn count_descendants(node: &Rc<Node>) -> usize {
1 + match &node.r#type {
NodeType::Branch{left: l, right: r, ..} => MerkleTree::count_descendants(l) + MerkleTree::count_descendants(r),
NodeType::Leaf{..} => 0
}
}
fn count_descendant_leaves(node: &Rc<Node>) -> usize {
match &node.r#type {
NodeType::Branch{left: l, right: r, ..} => MerkleTree::count_descendant_leaves(l) + MerkleTree::count_descendant_leaves(r),
NodeType::Leaf{..} => 1,
}
}
fn make_label(data: &[u8]) -> String {
MerkleTree::sha3_hex(data)
}
fn sha3_hex(data: &[u8]) -> String {
hex_string(Sha3_256::digest(data).as_slice()).unwrap()
}
}
// Merkle Root represent a version of the state
// get(root, addr) should return data stored at address, given a specific version of the state
// Sawtooth uses the Radix Merkle Trie to make fast queries to the state and to guarantee its integrity
// and transaction order
// Sawtooth uses the Radix Merkle tree to retrieve the location of data???
// .. but if LMDB is already a key/value store, why cant we just get(address) ?
// .. because for whatever reason an address
#[cfg(test)]
mod tests {
use super::*; // includes private functions
use rand::{thread_rng, Rng};
fn make_data(amount: usize) -> Vec<Vec<u8>> {
let mut data: Vec<Vec<u8>> = Vec::new();
for d in 1..=amount {
// data.push(format!("Id = {}", d).into_bytes());
data.push(vec![d as u8]);
}
data
}
fn make_data_refs<'a>(data: &'a Vec<Vec<u8>>) -> Vec<&'a [u8]> {
let refs: Vec<&[u8]> = data.iter().map(|d| d.as_slice()).collect();
refs
}
#[test]
fn sha3_hash() {
let data = "Some random data".as_bytes();
assert_eq!(hex_string(Sha3_256::digest(data).as_slice()).unwrap(), "5b054cb1c47ebc3e0bd156e474a36ab2068807eb14bbe609639fc1f9bf53261a");
}
#[test]
#[ignore]
fn tree_nodes_count() {
for leaves_count in 2..=97 {
let data: Vec<Vec<u8>> = make_data(leaves_count);
let data_refs: Vec<&[u8]> = make_data_refs(&data);
let tree = MerkleTree::from_data(&data_refs);
let leaves = tree.count_leaves();
let branches = tree.count_nodes() - leaves;
println!("Merkle tree leaves={} branches={} leaves-branches={}", leaves, branches, leaves-branches);
assert_eq!(branches, leaves - 1);
}
}
#[test]
fn tree_leaf_depth() {
let data: Vec<Vec<u8>> = make_data(11);
let data_refs: Vec<&[u8]> = make_data_refs(&data);
let tree = MerkleTree::from_data(&data_refs);
let rightmost = dbg!(tree.nodes.get("8bf02b8b238233453488311be9b316e58ab7e1356ce948cb90dfef1af56992eb").unwrap()); //9
let leftmost = dbg!(tree.nodes.get("2767f15c8af2f2c7225d5273fdd683edc714110a987d1054697c348aed4e6cc7").unwrap()); //1
let center = dbg!(tree.nodes.get("989216075a288af2c12f115557518d248f93c434965513f5f739df8c9d6e1932").unwrap()); // 4
dbg!(tree.node_depth(rightmost));
dbg!(tree.node_depth(leftmost));
dbg!(tree.node_depth(center));
assert_eq!(tree.node_depth(&tree.root), 0);
match &tree.root.r#type {
// root
NodeType::Branch{left: l, right: r} => {
assert_eq!(tree.node_depth(r), 1);
assert_eq!(tree.node_depth(l), 1);
match &l.r#type {
// root -> left
NodeType::Branch{left: l_l, right: l_r, ..} => {
assert_eq!(tree.node_depth(l_l), 2);
assert_eq!(tree.node_depth(l_r), 2);
match &l_l.r#type {
// root -> left -> left
NodeType::Branch{left: l_l_l, right: l_l_r, .. } => {
assert_eq!(tree.node_depth(l_l_l), 3);
assert_eq!(tree.node_depth(l_l_r), 3);
},
_ => panic!("Unexpected node type"),
}
}
_ => panic!("Unexpected node type"),
}
match &r.r#type {
// root -> right
NodeType::Branch{left: r_l, right: r_r} => {
assert_eq!(tree.node_depth(r_l), 2);
assert_eq!(tree.node_depth(r_r), 2);
match &r_r.r#type {
// root -> right -> right
NodeType::Leaf{..} => assert_eq!(tree.node_depth(&r_r), 2),
_ => panic!("Unexpected root type NodeType::Leaf"),
}
},
_ => panic!("Unexpected node type"),
}
},
_ => panic!("Unexpected root type NodeType::Leaf"),
};
}
#[test]
fn data_proofs() {
let data: Vec<Vec<u8>> = make_data(5);
let data_refs: Vec<&[u8]> = make_data_refs(&data);
let tree = MerkleTree::from_data(&data_refs);
let datum: &[u8] = data_refs[4];
let proof = tree.make_proof(datum).unwrap();
assert_eq!(proof, [
"5ea0ffd548dacbbfc23452a271a0fab46f39114bda991ce85bf0386ca2294d3f"
]);
assert!(tree.authenticate(datum, &proof));
let datum: &[u8] = data_refs[3];
let proof = tree.make_proof(datum).unwrap();
assert_eq!(proof, [
"e3ed56bd086d8958483a12734fa0ae7f5c8bb160ef9092c67e82ed9b19e4c7b2",
"bfec02f100e0803e2124e5c28a567ccc5547640e96aa1ca3ed8798ba21d2e1ab",
"3b0c4d506212cd7e7b88bc93b5b1811ab5de6796d2780e9de7378c87fe9a80a6"
]);
assert!(tree.authenticate(datum, &proof));
let datum: &[u8] = data_refs[thread_rng().gen_range(0u8, 5u8) as usize];
let proof = tree.make_proof(datum).unwrap();
assert!(tree.authenticate(datum, &proof), format!("Invalid proof for {:?}", datum));
assert!(tree.make_proof(&[6u8]).is_err());
}
#[test]
fn single_node_tree() {
let data = make_data(1);
let refs = make_data_refs(&data);
let tree = MerkleTree::from_data(&refs);
assert_eq!(tree.count_leaves(), 1);
assert_eq!(tree.count_nodes(), 1);
assert_eq!(tree.node_depth(&tree.root), 0);
assert!(tree.make_proof(refs[0]).unwrap().is_empty());
assert!(tree.authenticate(refs[0], &tree.make_proof(refs[0]).unwrap()));
}
#[test]
fn complete_tree() {
// Complete (=> balanced, but not perfect) proper binary tree
for ln in 1..1000 {
// Levels start from 0 i.e. = depth
let last_filled_level = (ln as f64).log2().floor() as u32;
let leaves_on_last_level = (ln - 2usize.pow(last_filled_level)) * 2; // multiple of 2
println!("Leaves={}, last_filled_level={}, leaves_last_level={}", ln, last_filled_level, leaves_on_last_level);
assert!(leaves_on_last_level < 2usize.pow(last_filled_level+1));
assert_eq!(leaves_on_last_level % 2, 0);
// put first <leaves_on_last_level> leaves on the stack in rev order | O(L-1)
// while (take 2 nodes from the stack):
// make parent branch; | O(k)
// push branch on TOP of the stack; | O(2)
}
}
} |
use std::fs::{read_dir, write};
fn main() -> std::io::Result<()> {
// see https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed
// XXX: Removing this causes `cargo watch` to loop infinitely because we keep changing the
// filesystem contents.
for ent in read_dir("tests")? {
let path = ent?.path();
if let Some(ext) = path.extension() {
if ext == "graphql" {
println!("cargo:rerun-if-changed={}", path.display());
}
}
}
let mut output = String::from(
"// Autogenerated by graphql-parser/build.rs
//
// This file is autogenerated by scanning the tests for *.graphql files.
// To add a sample to the test corpus, don't edit this file. Instead, just
// add a new .graphql file to the tests/ directory.
// The tests are added sorted by name so that different machines building will not yield a git diff.
// Sample names are easier to read with two underscores in them
#![allow(non_snake_case)]
mod helpers;
use graphql_parser::parse_query;
use graphql_parser::parse_schema;
use helpers::*;
use insta::assert_snapshot;
use pretty_assertions::assert_eq;
",
);
let mut tests: Vec<String> = Vec::new();
for ent in read_dir("tests")? {
let entry = ent?;
let mut path = entry.path();
if let (Some(osname), Some(ext)) = (path.file_stem(), path.extension()) {
let name = osname.to_str().unwrap().to_owned();
if name.contains('.') || ext != "graphql" {
continue;
}
let src = entry.file_name().to_str().unwrap().to_owned();
let canonical_src = format!("{}.canonical.graphql", name);
path.pop();
path.push(canonical_src.clone());
tests.push(format!(
"test!(\n {},\n include_str!(\"{}\"),\n include_str!(\"{}\")\n);\n",
&name,
&src,
if path.is_file() { &canonical_src } else { &src }
));
}
}
tests.sort();
for line in tests.iter() {
output.push_str(line.as_str());
}
write("tests/tests.rs", output)?;
Ok(())
}
|
use azure_core::Context;
use azure_cosmos::prelude::*;
use futures::stream::StreamExt;
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
// First we retrieve the account name and master key from environment variables.
// We expect master keys (ie, not resource constrained)
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, authorization_token, CosmosOptions::default());
let database_client = client.into_database_client("pollo");
println!("database_name == {}", database_client.database_name());
let collections =
Box::pin(database_client.list_collections(Context::new(), ListCollectionsOptions::new()))
.next()
.await
.unwrap()?;
println!("collections == {:#?}", collections);
let collection_client = database_client.into_collection_client("cnt");
let collection = collection_client
.get_collection(Context::new(), GetCollectionOptions::new())
.await?;
println!("collection == {:#?}", collection);
Ok(())
}
|
#[doc = "Reader of register ITARGETSR2"]
pub type R = crate::R<u32, super::ITARGETSR2>;
#[doc = "Reader of field `CPU_TARGETS0`"]
pub type CPU_TARGETS0_R = crate::R<u8, u8>;
#[doc = "Reader of field `CPU_TARGETS1`"]
pub type CPU_TARGETS1_R = crate::R<u8, u8>;
#[doc = "Reader of field `CPU_TARGETS2`"]
pub type CPU_TARGETS2_R = crate::R<u8, u8>;
#[doc = "Reader of field `CPU_TARGETS3`"]
pub type CPU_TARGETS3_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:1 - CPU(s) target for interrupt"]
#[inline(always)]
pub fn cpu_targets0(&self) -> CPU_TARGETS0_R {
CPU_TARGETS0_R::new((self.bits & 0x03) as u8)
}
#[doc = "Bits 8:9 - CPU(s) target for interrupt"]
#[inline(always)]
pub fn cpu_targets1(&self) -> CPU_TARGETS1_R {
CPU_TARGETS1_R::new(((self.bits >> 8) & 0x03) as u8)
}
#[doc = "Bits 16:17 - CPU(s) target for interrupt"]
#[inline(always)]
pub fn cpu_targets2(&self) -> CPU_TARGETS2_R {
CPU_TARGETS2_R::new(((self.bits >> 16) & 0x03) as u8)
}
#[doc = "Bits 24:25 - CPU(s) target for interrupt"]
#[inline(always)]
pub fn cpu_targets3(&self) -> CPU_TARGETS3_R {
CPU_TARGETS3_R::new(((self.bits >> 24) & 0x03) as u8)
}
}
|
struct Generator {
current: usize,
factor: usize,
}
impl Generator {
pub fn new(current: usize, factor: usize) -> Generator {
Generator {
current,
factor,
}
}
}
impl Iterator for Generator {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
self.current = (self.current * self.factor) % 2147483647;
Some(self.current)
}
}
pub fn parse(input: &str) -> usize {
let start: Vec<_> = input.lines().map(|line | line.parse::<usize>().unwrap()).collect();
let a = Generator::new(start[0], 16807);
let b = Generator::new(start[1], 48271);
a.zip(b)
.take(40_000_000)
.filter(|&(v1, v2)| {
v1 & 0xffff == v2 & 0xffff
})
.count()
}
#[cfg(test)]
mod tests {
use super::{Generator, parse};
#[test]
fn day15_part1_test1() {
let mut generator = Generator::new(65, 16807);
assert_eq!(1092455, generator.next().unwrap());
assert_eq!(1181022009, generator.next().unwrap());
assert_eq!(245556042, generator.next().unwrap());
assert_eq!(1744312007, generator.next().unwrap());
assert_eq!(1352636452, generator.next().unwrap());
}
#[test]
fn day15_part1_test2() {
let mut generator = Generator::new(8921, 48271);
assert_eq!(430625591, generator.next().unwrap());
assert_eq!(1233683848, generator.next().unwrap());
assert_eq!(1431495498, generator.next().unwrap());
assert_eq!(137874439, generator.next().unwrap());
assert_eq!(285222916, generator.next().unwrap());
}
#[test]
fn day15_part1_test3() {
assert_eq!(588, parse("65\n8921\n"));
}
}
|
pub mod song;
pub mod sound {
use std::sync::mpsc;
use px8::packet;
use chiptune;
use std::collections::HashMap;
use sdl2;
use sdl2::mixer;
use std::sync::{Arc, Mutex};
pub struct SoundInternal {
player: chiptune::Chiptune,
chiptune_music_tracks: HashMap<String, chiptune::ChiptuneSong>,
chiptune_sound_tracks: HashMap<String, chiptune::ChiptuneSound>,
music_tracks: HashMap<String, mixer::Music>,
sound_tracks: HashMap<String, mixer::Chunk>,
pub csend: mpsc::Sender<Vec<u8>>,
crecv: mpsc::Receiver<Vec<u8>>,
}
impl SoundInternal {
pub fn new() -> SoundInternal {
let (csend, crecv) = mpsc::channel();
SoundInternal {
player: chiptune::Chiptune::new(),
chiptune_music_tracks: HashMap::new(),
chiptune_sound_tracks: HashMap::new(),
music_tracks: HashMap::new(),
sound_tracks: HashMap::new(),
csend: csend,
crecv: crecv,
}
}
pub fn init(&mut self) {
info!("query spec => {:?}", sdl2::mixer::query_spec());
}
pub fn pause(&mut self) {
info!("[SOUND] Pause");
sdl2::mixer::Music::pause();
sdl2::mixer::channel(-1).pause();
self.player.pause(1);
}
pub fn resume(&mut self) {
info!("[SOUND] Resume");
sdl2::mixer::Music::resume();
sdl2::mixer::channel(-1).resume();
self.player.pause(0);
}
pub fn stop(&mut self) {
info!("[SOUND] Stop");
sdl2::mixer::Music::halt();
sdl2::mixer::channel(-1).halt();
self.player.stop();
}
pub fn update(&mut self, sound: Arc<Mutex<Sound>>) {
for sound_packet in self.crecv.try_iter() {
debug!("[SOUND] PACKET {:?}", sound_packet);
match packet::read_packet(sound_packet).unwrap() {
// Chiptune
packet::Packet::ChiptunePlay(res) => {
let filename = res.filename.clone();
// New song -> Load it before
if res.filetype == 0 {
if !self.chiptune_music_tracks.contains_key(&filename) {
let song = self.player.load_music(filename.clone());
match song {
Ok(chip_song) => {
self.chiptune_music_tracks.insert(filename.clone(), chip_song);
}
Err(e) => error!("ERROR to load the song {:?}", e),
}
}
match self.chiptune_music_tracks.get_mut(&filename) {
Some(mut song) => {
self.player.play_music(&mut song, res.start_position);
self.player.set_looping(res.loops);
}
None => {},
}
}
// New sound effect
if res.filetype == 1 {
if !self.chiptune_sound_tracks.contains_key(&filename) {
let sound = self.player.load_sound(filename.clone());
match sound {
Ok(chip_sound) => {
self.chiptune_sound_tracks.insert(filename.clone(), chip_sound);
}
Err(e) => error!("ERROR to load the song {:?}", e),
}
}
match self.chiptune_sound_tracks.get_mut(&filename) {
Some(mut sound) => {
self.player.play_sound(&mut sound, -1, 0, chiptune::CYD_PAN_CENTER);
}
None => {},
}
}
}
packet::Packet::ChiptuneStop(res) => {
if res.music == 1 && res.sound == 1 {
self.player.stop();
}
if res.music == 1 && res.sound == 0 {
self.player.stop_music();
}
if res.music == 0 && res.sound == 1 {
self.player.stop_sound();
}
}
packet::Packet::ChiptunePause(res) => {
if res.music == 1 && res.sound == 1 {
self.player.pause(1);
}
if res.music == 1 && res.sound == 0 {
self.player.pause_music(1);
}
if res.music == 0 && res.sound == 1 {
self.player.pause_sound(1);
}
}
packet::Packet::ChiptuneResume(res) => {
if res.music == 1 && res.sound == 1 {
self.player.pause(0);
}
if res.music == 1 && res.sound == 0 {
self.player.pause_music(0);
}
if res.music == 0 && res.sound == 1 {
self.player.pause_sound(0);
}
}
packet::Packet::ChiptuneVolume(res) => {
self.player.set_volume(res.volume);
}
// Music
packet::Packet::LoadMusic(res) => {
let filename = res.filename.clone();
let track = mixer::Music::from_file(filename.as_ref()).unwrap();
debug!("[SOUND][SoundInternal] MUSIC Track {:?}", filename);
debug!("music type => {:?}", track.get_type());
self.music_tracks.insert(filename, track);
}
packet::Packet::PlayMusic(res) => {
let filename = res.filename.clone();
self.music_tracks
.get(&filename)
.expect("music: Attempted to play value that is not bound to asset")
.play(res.loops)
.unwrap();
}
packet::Packet::StopMusic(_res) => {
sdl2::mixer::Music::halt();
}
packet::Packet::PauseMusic(_res) => {
sdl2::mixer::Music::pause();
}
packet::Packet::RewindMusic(_res) => {
sdl2::mixer::Music::rewind();
}
packet::Packet::ResumeMusic(_res) => {
sdl2::mixer::Music::resume();
}
packet::Packet::VolumeMusic(res) => {
sdl2::mixer::Music::set_volume(res.volume);
}
// Sound
packet::Packet::LoadSound(res) => {
let filename = res.filename.clone();
let track = mixer::Chunk::from_file(filename.as_ref()).unwrap();
debug!("[SOUND][SoundInternal] SOUND Track {:?}", filename);
self.sound_tracks.insert(filename, track);
}
packet::Packet::PlaySound(res) => {
let filename = res.filename.clone();
sdl2::mixer::channel(res.channel)
.play(&self.sound_tracks.get(&filename).unwrap(), res.loops);
}
packet::Packet::PauseSound(res) => {
sdl2::mixer::channel(res.channel).pause();
}
packet::Packet::ResumeSound(res) => {
sdl2::mixer::channel(res.channel).resume();
}
packet::Packet::StopSound(res) => {
sdl2::mixer::channel(res.channel).halt();
}
packet::Packet::VolumeSound(res) => {
sdl2::mixer::channel(res.channel).set_volume(res.volume);
}
}
}
for i in 0..16 {
sound.lock().unwrap().channels[i] = sdl2::mixer::channel(i as i32).is_playing();
}
sound.lock().unwrap().chiptune_position = self.player.get_position();
}
}
pub struct Sound {
csend: mpsc::Sender<Vec<u8>>,
channels: [bool; 16],
chiptune_position: i32,
}
impl Sound {
pub fn new(csend: mpsc::Sender<Vec<u8>>) -> Sound {
Sound {
csend: csend,
channels: [false; 16],
chiptune_position: 0,
}
}
// Chiptune
pub fn chiptune_play(&mut self, filetype: i32, filename: String, loops: i32, start_position: i32) {
debug!("[SOUND] Chiptune PLAY {:?}", filename);
let p = packet::ChiptunePlay { filetype: filetype, filename: filename, loops: loops, start_position: start_position };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn chiptune_stop(&mut self, music: i32, sound: i32) {
debug!("[SOUND] Chiptune STOP");
let p = packet::ChiptuneStop { music: music, sound: sound };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn chiptune_pause(&mut self, music: i32, sound: i32) {
debug!("[SOUND] Chiptune Pause");
let p = packet::ChiptunePause { music: music, sound: sound };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn chiptune_resume(&mut self, music: i32, sound: i32) {
debug!("[SOUND] Chiptune Resume");
let p = packet::ChiptuneResume { music: music, sound: sound };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn chiptune_volume(&mut self, volume: i32) {
debug!("[SOUND] Chiptune volume");
let p = packet::ChiptuneVolume { volume: volume };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn chiptune_get_position(&mut self) -> i32 {
self.chiptune_position
}
// Music
pub fn load(&mut self, filename: String) -> i32 {
debug!("[SOUND] Load music {:?}", filename);
let p = packet::LoadMusic { filename: filename };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
0
}
pub fn play(&mut self, filename: String, loops: i32) {
debug!("[SOUND] Play music {:?} {:?}", filename, loops);
let p = packet::PlayMusic {
filename: filename,
loops: loops,
};
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn stop(&mut self) {
debug!("[SOUND] Stop music");
let p = packet::StopMusic { filename: "".to_string() };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn pause(&mut self) {
debug!("[SOUND] Pause music");
let p = packet::PauseMusic { filename: "".to_string() };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn resume(&mut self) {
debug!("[SOUND] Resume music");
let p = packet::ResumeMusic { filename: "".to_string() };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn rewind(&mut self) {
debug!("[SOUND] Rewind music");
let p = packet::RewindMusic { filename: "".to_string() };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn volume(&mut self, volume: i32) {
debug!("[SOUND] Volume music");
let p = packet::VolumeMusic { volume: volume };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
// Sound
pub fn sound_load(&mut self, filename: String) -> i32 {
debug!("[SOUND] Load sound {:?}", filename);
let p = packet::LoadSound { filename: filename };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
0
}
pub fn sound_play(&mut self, filename: String, loops: i32, channel: i32) {
debug!("[SOUND] Play sound {:?} {:?} {:?}",
filename,
loops,
channel);
let p = packet::PlaySound {
filename: filename,
loops: loops,
channel: channel,
};
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn sound_pause(&mut self, channel: i32) {
debug!("[SOUND] Pause sound {:?}", channel);
let p = packet::PauseSound { channel: channel };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn sound_resume(&mut self, channel: i32) {
debug!("[SOUND] Resume sound {:?}", channel);
let p = packet::ResumeSound { channel: channel };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn sound_stop(&mut self, channel: i32) {
debug!("[SOUND] Stop sound {:?}", channel);
let p = packet::StopSound { channel: channel };
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn sound_volume(&mut self, volume: i32, channel: i32) {
debug!("[SOUND] Volume sound {:?} {:?}", volume, channel);
let p = packet::VolumeSound {
volume: volume,
channel: channel,
};
self.csend.send(packet::write_packet(p).unwrap()).unwrap();
}
pub fn sound_isplaying(&mut self, channel: i32) -> bool {
self.channels[channel as usize]
}
}
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
//! Protects a set of file descriptors from getting closed.
use std::os::unix::io::AsRawFd;
use std::os::unix::io::RawFd;
use parking_lot::Mutex;
use syscalls::Sysno;
use syscalls::SysnoSet;
// TODO: Remove this lazy_static after upgrading to parking_lot >= 0.12.1.
// Mutex::new is a const fn in newer versions.
lazy_static::lazy_static! {
/// A set of file descriptors that should not get closed.
static ref PROTECTED_FILES: Mutex<ProtectedFiles> = Mutex::new(ProtectedFiles::new());
}
struct ProtectedFiles {
// We have to use Vec here to ensure `new` can be a const fn, which is
// required for global static variables. This should be fine, since we don't
// expect to be protecting more than a handful of file descriptors.
files: Vec<RawFd>,
}
impl ProtectedFiles {
pub const fn new() -> Self {
Self { files: Vec::new() }
}
pub fn contains<Fd: AsRawFd>(&self, fd: &Fd) -> bool {
self.files.contains(&fd.as_raw_fd())
}
pub fn insert<Fd: AsRawFd>(&mut self, fd: &Fd) -> bool {
if self.contains(fd) {
true
} else {
self.files.push(fd.as_raw_fd());
false
}
}
pub fn remove<Fd: AsRawFd>(&mut self, fd: &Fd) -> bool {
let fd = fd.as_raw_fd();
if let Some(index) = self.files.iter().position(|item| item == &fd) {
self.files.swap_remove(index);
true
} else {
false
}
}
}
/// A file descriptor that is internal to the plugin and not visible to the
/// client. These file descriptors cannot be closed by the client.
pub struct ProtectedFd<T: AsRawFd>(T);
impl<T: AsRawFd> Drop for ProtectedFd<T> {
fn drop(&mut self) {
PROTECTED_FILES.lock().remove(&self.0);
}
}
impl<T: AsRawFd> AsRef<T> for ProtectedFd<T> {
fn as_ref(&self) -> &T {
&self.0
}
}
impl<T: AsRawFd> AsMut<T> for ProtectedFd<T> {
fn as_mut(&mut self) -> &mut T {
&mut self.0
}
}
/// Takes a closure `f` that creates and returns a file descriptor. The file
/// descriptor that is returned is protected from getting closed. This is safe
/// even if another thread is trying to close this same file descriptor.
pub fn protect_with<F, T, E>(f: F) -> Result<ProtectedFd<T>, E>
where
F: FnOnce() -> Result<T, E>,
T: AsRawFd,
{
let mut protected_files = PROTECTED_FILES.lock();
f().map(|fd| {
protected_files.insert(&fd);
ProtectedFd(fd)
})
}
/// Returns true if a file descriptor is protected and shouldn't be closed.
pub fn is_protected<Fd: AsRawFd>(fd: &Fd) -> bool {
PROTECTED_FILES.lock().contains(fd)
}
/// All of these syscalls take the input file descriptor as the first argument.
/// Some syscalls, like mmap, don't conform to this pattern and need to be
/// handled in a special way.
static FD_ARG0_SYSCALLS: SysnoSet = SysnoSet::new(&[
Sysno::close,
Sysno::dup,
Sysno::dup2,
Sysno::openat,
Sysno::fstat,
Sysno::read,
Sysno::write,
Sysno::lseek,
Sysno::ioctl,
Sysno::pread64,
Sysno::pwrite64,
Sysno::readv,
Sysno::writev,
Sysno::connect,
Sysno::accept,
Sysno::sendto,
Sysno::recvfrom,
Sysno::sendmsg,
Sysno::recvmsg,
Sysno::shutdown,
Sysno::bind,
Sysno::listen,
Sysno::getsockname,
Sysno::getpeername,
Sysno::getsockopt,
Sysno::fcntl,
Sysno::flock,
Sysno::fsync,
Sysno::fdatasync,
Sysno::ftruncate,
Sysno::getdents,
Sysno::getdents64,
Sysno::fchdir,
Sysno::fchmod,
Sysno::fchown,
Sysno::fstatfs,
Sysno::readahead,
Sysno::fsetxattr,
Sysno::fgetxattr,
Sysno::flistxattr,
Sysno::fremovexattr,
Sysno::fadvise64,
Sysno::epoll_wait,
Sysno::epoll_ctl,
Sysno::inotify_add_watch,
Sysno::inotify_rm_watch,
Sysno::mkdirat,
Sysno::mknodat,
Sysno::fchownat,
Sysno::futimesat,
Sysno::newfstatat,
Sysno::unlinkat,
Sysno::renameat,
Sysno::linkat,
Sysno::readlinkat,
Sysno::fchmodat,
Sysno::faccessat,
Sysno::sync_file_range,
Sysno::vmsplice,
Sysno::utimensat,
Sysno::epoll_pwait,
Sysno::signalfd,
Sysno::fallocate,
Sysno::timerfd_settime,
Sysno::timerfd_gettime,
Sysno::accept4,
Sysno::signalfd4,
Sysno::dup3,
Sysno::preadv,
Sysno::pwritev,
Sysno::recvmmsg,
Sysno::fanotify_mark,
Sysno::name_to_handle_at,
Sysno::open_by_handle_at,
Sysno::syncfs,
Sysno::sendmmsg,
Sysno::setns,
Sysno::finit_module,
Sysno::renameat2,
Sysno::kexec_file_load,
Sysno::execveat,
Sysno::preadv2,
Sysno::pwritev2,
Sysno::statx,
Sysno::pidfd_send_signal,
Sysno::io_uring_enter,
Sysno::io_uring_register,
Sysno::open_tree,
Sysno::move_mount,
Sysno::fsconfig,
Sysno::fsmount,
Sysno::fspick,
Sysno::openat2,
Sysno::pidfd_getfd,
]);
static FD_ARG1_SYSCALLS: SysnoSet = SysnoSet::new(&[Sysno::dup2, Sysno::dup3]);
/// Returns true if the given syscall operates on a protected file descriptor.
pub fn uses_protected_fd(sysno: Sysno, arg0: usize, arg1: usize) -> bool {
(FD_ARG0_SYSCALLS.contains(sysno) && is_protected(&(arg0 as i32)))
|| (FD_ARG1_SYSCALLS.contains(sysno) && is_protected(&(arg1 as i32)))
}
|
use im::Vector;
use ndarray::prelude::*;
use std::convert::{TryFrom, TryInto};
use std::iter::FromIterator;
use common::*;
use common::primitives::*;
macro_rules! assert_num_args {
($name:expr, $args:expr, $len:expr) => {
if $args.len() != $len {
return Err(format!("{} requires {} arguments but got {}", $name, $len, $args.len()));
}
};
}
macro_rules! _n {
($newn:ident, $n:expr, $l:expr, $v:expr) => {
let mut $newn = $n;
if $n < 0 {
$newn = $l as isize - $n - 2;
}
if $n >= $l as isize {
panic!(
"Out of bounds access in vector (at {} in vector with length {}: {:?})",
$n, $l, $v
);
}
};
}
fn _get_nth(builtin: Builtin, args: &[Primitive], n: isize) -> Result<Primitive, String> {
match &args[0] {
Primitive::Vector(v) => {
let l = v.len();
_n!(n_, n, l, v);
Ok(v[n_ as usize].clone())
}
Primitive::EvaluatedVector(v) => {
_n!(n_, n, v.len(), v);
Ok(Primitive::from(v[n_ as usize] as f64))
}
_ => Err(format!(
"{:?} requries a `vector` argument, but got {:?}.",
builtin, args[0]
)),
}
}
pub fn eval_builtin(builtin: Builtin, args: &[Primitive]) -> Result<Primitive, String> {
match builtin {
Builtin::First => {
assert_num_args!("(first v)", &args, 1);
_get_nth(builtin, args, 0)
}
Builtin::Second => {
assert_num_args!("(second v)", &args, 1);
_get_nth(builtin, args, 1)
}
Builtin::Last => {
assert_num_args!("(last v)", &args, 1);
_get_nth(builtin, args, -1)
}
Builtin::Rest => {
assert_num_args!("(rest v)", &args, 1);
match &args[0] {
Primitive::Vector(v) => {
let mut v = v.clone();
v.pop_front();
Ok(Primitive::from(v))
}
Primitive::EvaluatedVector(v) => {
let mut new = Array1::zeros(v.len() - 1);
for i in 1..(v.len()) {
new[i - 1] = v[i];
}
Ok(Primitive::EvaluatedVector(new))
}
_ => Err(String::from("(rest xs) requires vector argument")),
}
}
Builtin::Get => {
assert_num_args!("(get collection key)", args, 2);
if args[0].is_vector() {
let n = usize::try_from(&args[1]).expect("(get (vector …) n) requires `n` numeric.");
_get_nth(builtin, args, n as isize)
} else if let Ok(h) = PHashMap::try_from(args[0].clone()) {
Ok(h.get(&args[1]).expect(&format!("Key {:?} not found for {:?}", &args[1], &h)).clone())
} else {
Err(format!("(get collection key) requires collection to be either vector or hash map, but was {:?}", args[0]))
}
}
Builtin::Put => {
assert_num_args!("(put collection key value)", args, 3);
match &args[0] {
Primitive::Vector(v) => {
let n = usize::try_from(&args[1]).expect("(get vector n) requires n integral.");
Ok(Primitive::from(v.update(n, args[2].clone())))
},
Primitive::EvaluatedVector(v) => {
let n = usize::try_from(&args[1]).expect("(get vector n) requires n integral.");
if let Ok(f) = f64::try_from(&args[2]) {
let mut v = v.clone();
v[n] = f;
Ok(Primitive::EvaluatedVector(v))
} else {
let mut new = Vector::from_iter(v.into_iter().map(|x| Primitive::from(*x)));
new[n] = args[2].clone();
Ok(Primitive::Vector(new))
}
}
Primitive::HashMap(h) => Ok(Primitive::from(h.update(args[1].clone(), args[2].clone()))),
_ => Err(format!("(put) requres vector or hash-map, but got {:?}", &args[1]))
}
}
Builtin::Append => {
assert_num_args!("(append v x)", args, 2);
match &args[0] {
Primitive::Vector(v) => {
let mut v = v.clone();
v.push_back(args[1].clone());
Ok(Primitive::Vector(v))
}
Primitive::EvaluatedVector(v) => {
if let Ok(f) = f64::try_from(&args[1]) {
let mut nv = Array1::zeros(v.len() + 1);
for i in 0..v.len() {
nv[i] = v[i];
}
nv[v.len()] = f;
Ok(Primitive::from(nv))
} else {
let mut new = Vector::from_iter(v.into_iter().map(|x| Primitive::from(*x)));
new.push_back(args[2].clone());
Ok(Primitive::Vector(new))
}
},
_ => Err(format!("(append) requires vector, but got {:?}", args[0]))
}
}
Builtin::Conj => match &args[0] {
Primitive::Vector(v) => {
let mut v = v.clone();
// v.reserve(v.len() + args.len());
for a in &args[1..] {
v.push_front(a.clone())
}
Ok(Primitive::from(v))
}
Primitive::EvaluatedVector(v) => {
if args.len() == 1 {
return Ok(Primitive::EvaluatedVector(v.clone()))
}
let all_num = (&args[1..]).iter().all(|x| x.is_number());
if all_num {
let mut new = Array1::zeros(v.len() + args.len() - 1);
let args = &args[1..];
for i in 0..args.len() {
new[i] = (&args[i]).try_into().expect(&format!("Converting {:?} to f64 failed.", &args[i]));
}
for i in 0..v.len() {
new[args.len() + i] = v[i];
}
Ok(Primitive::from(new))
} else {
let mut new = Vec::with_capacity(v.len() + args.len() - 1);
let args = &args[1..];
for i in 0..args.len() {
new.push(args[i].clone());
}
for i in 0..v.len() {
new.push(Primitive::from(v[i] as f64));
}
Ok(Primitive::from(new))
}
}
_ => Err(format!("(conj) requires vector, but got {:?}", args[0]))
},
Builtin::Cons => {
assert_num_args!("(cons x v)", args, 2);
match &args[1] {
Primitive::Vector(v) => {
let mut v = v.clone();
v.push_front(args[1].clone());
Ok(Primitive::Vector(v))
}
Primitive::EvaluatedVector(v) => {
if let Ok(f) = f64::try_from(&args[0]) {
let mut new = Array1::zeros(v.len() + 1);
for i in 0..v.len() {
new[i + 1] = v[i];
}
new[0] = f;
Ok(Primitive::from(new))
} else {
let mut new = Vec::with_capacity(v.len() + 1);
new.push(args[0].clone());
for i in 0..v.len() {
new.push(Primitive::from(v[i]));
}
Ok(Primitive::from(new))
}
},
_ => panic!("(append) requires vector, but got {:?}", args[0]),
}
}
Builtin::IsEmpty => {
assert_num_args!("(empty? v)", args, 1);
Ok(Primitive::from(match &args[0] {
Primitive::Vector(v) => v.len() == 0,
Primitive::EvaluatedVector(v) => v.len() == 0,
Primitive::HashMap(h) => h.len() == 0,
_ => {return Err(format!("(empty?) not defined for {:?}", &args[0]));}
}))
}
Builtin::Vector => {
let all_num = args.iter().all(|x| x.is_number());
if all_num {
Ok(Primitive::from(Array1::from_iter(args.iter().map(|x| x.try_into().unwrap()))))
} else {
Ok(Primitive::from(Vec::from_iter(args.iter().cloned())))
}
}
Builtin::HashMap => {
if args.len() % 2 != 0 {
return Err(String::from("(hash-map ...) requires an even number of arguments."));
}
let iter = args.iter()
.step_by(2)
.cloned()
.zip(args.iter()
.skip(1)
.step_by(2)
.cloned());
Ok(Primitive::from(PHashMap::from_iter(iter)))
}
Builtin::Add | Builtin::Sub | Builtin::Mul | Builtin::Pow => {
assert_num_args!("(binary-op x y)", args, 2);
if let Some((l, r)) = integral_pair(&args[0], &args[1]) {
Ok(Primitive::from(match builtin {
Builtin::Add => l + r,
Builtin::Sub => l - r,
Builtin::Mul => l * r,
Builtin::Pow => l.pow(r as u32),
_ => unreachable!(),
}))
} else if let Some((l, r)) = try_pair::<f64>(&args[0], &args[1]) {
Ok(Primitive::from(match builtin {
Builtin::Add => l + r,
Builtin::Sub => l - r,
Builtin::Mul => l * r,
Builtin::Pow => l.powf(r),
_ => unreachable!(),
}))
} else {
Err(format!("(binary-op x y) requires x, y numeric, but they are {:?}, {:?}", &args[0], &args[1]))
}
}
Builtin::Div => {
assert_num_args!("(/ x y)", args, 2);
if let Some((l, r)) = try_pair::<f64>(&args[0], &args[1]) {
Ok(Primitive::from(l / r))
} else {
Err(format!("(/ x y) requires x, y numeric, but they are {:?}, {:?}", args[0], args[1]))
}
}
Builtin::IsLess | Builtin::IsEqual | Builtin::IsGreater => {
assert_num_args!("(cmp x y)", args, 2);
if let Some((l, r)) = try_pair::<f64>(&args[0], &args[1]) {
Ok(Primitive::from(match builtin {
Builtin::IsLess => l < r,
Builtin::IsEqual => l == r,
Builtin::IsGreater => l > r,
_ => unreachable!()
}))
} else {
Err(format!("(cmp x y) requires x, y numeric, but they are {:?}, {:?}", args[0], args[1]))
}
}
Builtin::And | Builtin::Or => {
assert_num_args!("(logical x y)", args, 2);
if let Some((l, r)) = try_pair(&args[0], &args[1]) {
Ok(Primitive::from(match builtin {
Builtin::And => l && r,
Builtin::Or => l || r,
_ => unreachable!()
}))
} else {
Err(format!("(logical-cmp x y) requires x, y logical, but they are {:?}, {:?}", args[0], args[1]))
}
}
Builtin::Sqrt => {
assert_num_args!("(sqrt x)", args, 1);
if let Ok(f) = f64::try_from(&args[0]) {
if f < 0.0 {
Err(format!("(sqrt x) requires x > 0, but it is {:?}", args[0]))
} else {
Ok(Primitive::from(f.sqrt()))
}
} else {
Err(format!("(sqrt x) requires x numeric, but it is {:?}", args[0]))
}
}
Builtin::Abs => {
assert_num_args!("(abs x)", args, 1);
if let Ok(i) = i128::try_from(&args[0]) {
Ok(Primitive::from(i.abs()))
} else if let Ok(f) = f64::try_from(&args[0]) {
Ok(Primitive::from(f.abs()))
} else {
Err(format!("(abs x) requires x numeric, but it is {:?}", args[0]))
}
}
Builtin::Ln => {
assert_num_args!("(ln x)", args, 1);
if let Ok(f) = f64::try_from(&args[0]) {
if f < 0.0 {
Err(format!("(ln x) requires x > 0, but it is {:?}", args[0]))
} else {
Ok(Primitive::from(f.ln()))
}
} else {
Err(format!("(ln x) requires x numeric, but it is {:?}", args[0]))
}
}
Builtin::IntRange => {
assert_num_args!("(int-range a b)", args, 2);
if let Some(pair) = integral_pair(&args[0], &args[1]) {
Ok(Primitive::from(Domain::IntRange(pair.0, pair.1)))
} else {
Err(format!("(int-range a b) requires a, b integral"))
}
}
Builtin::OneOf => {
if args.len() == 0 {
Err(String::from("(one-of x...) requires at least one argument."))
} else {
Ok(Primitive::from(Domain::OneOf(args.iter().cloned().collect())))
}
}
_ => panic!("{:?} not implemented", builtin)
}
} |
use std::io::{stdout, Write};
use termion::raw::IntoRawMode;
fn main() {
let mut stdout = stdout().into_raw_mode().unwrap();
write!(stdout, "Hey there.").unwrap();
}
|
pub mod transport_parameters;
pub use transport_parameters::TransportParameters;
|
use std::ops::Deref;
use std::str::FromStr;
use std::io::Read;
use rustc_serialize::base64::{ToBase64, MIME};
use hyper;
use hyper::Client;
use hyper::header::{Accept, UserAgent, qitem};
use hyper::mime::Mime;
use rustc_serialize::json;
use rustc_serialize::{Decoder, Decodable, DecoderHelpers, Encoder, Encodable, EncoderHelpers};
use oauth::Authorization;
header! { (XRateLimit, "X-RateLimit-Limit") => [String] }
header! { (XRateLimitRemaining, "X-RateLimit-Remaining") => [String] }
header! { (XPollInterval, "X-Poll-Interval") => [String] }
#[derive(Clone, Debug)]
pub struct NotificationResponse {
pub poll_interval: usize,
pub rate_limit: usize,
pub rate_limit_remaining: usize,
pub notifications: Notifications
}
#[derive(Clone, Debug)]
pub struct Notifications {
pub list: Vec<Notification>
}
#[derive(Clone, Debug)]
pub struct Notification {
pub id: String,
pub repository: Repository,
pub subject: Subject,
pub reason: String,
pub unread: bool,
pub updated_at: String,
pub last_read_at: Option<String>,
pub url: String,
pub subscription_url: String
}
#[derive(Clone, Debug)]
pub struct Repository {
pub id: usize,
pub name: String,
pub full_name: String,
pub owner: Owner,
pub private: bool,
pub html_url: String,
pub description: String,
pub fork: bool,
pub url: String,
pub forks_url: String,
pub keys_url: String,
pub collaborators_url: String,
pub teams_url: String,
pub hooks_url: String,
pub issue_events_url: String,
pub events_url: String,
pub assignees_url: String,
pub branches_url: String,
pub tags_url: String,
pub blobs_url: String,
pub git_tags_url: String,
pub git_refs_url: String,
pub trees_url: String,
pub statuses_url: String,
pub languages_url: String,
pub stargazers_url: String,
pub contributors_url: String,
pub subscribers_url: String,
pub subscription_url: String,
pub commits_url: String,
pub git_commits_url: String,
pub comments_url: String,
pub issue_comment_url: String,
pub contents_url: String,
pub compare_url: String,
pub merges_url: String,
pub archive_url: String,
pub downloads_url: String,
pub issues_url: String,
pub pulls_url: String,
pub milestones_url: String,
pub notifications_url: String,
pub labels_url: String,
pub releases_url: String,
pub deployments_url: String
}
#[derive(Clone, Debug)]
pub struct Owner {
pub login: String,
pub id: usize,
pub avatar_url: String,
pub gravatar_id: String,
pub url: String,
pub html_url: String,
pub followers_url: String,
pub following_url: String,
pub gists_url: String,
pub starred_url: String,
pub subscriptions_url: String,
pub organizations_url: String,
pub repos_url: String,
pub events_url: String,
pub received_events_url: String,
pub owner_type: String,
pub site_admin: bool
}
#[derive(Clone, Debug)]
pub struct Subject {
pub title: String,
pub url: String,
pub latest_comment_url: Option<String>,
pub subject_type: String
}
/// Sends a request to get unread notifications for the supplied user
/// Returns a result where Ok == valid response, and Err == Error description
pub fn get_notifications_basic(username: &str, password: &str) -> Result<NotificationResponse, String> {
let auth_str = "Basic ".to_string() + &format!("Basic {}:{}", username, password).as_bytes().to_base64(MIME);
get_notifications(&auth_str)
}
/// Sends a request to get unread notifications for the user assigned to the supplied oauth token
/// Returns a result where Ok == valid response, and Err == Error description
pub fn get_notifications_oauth(oauth_token: &str) -> Result<NotificationResponse, String> {
let auth_str = format!("token {}", oauth_token);
get_notifications(&auth_str)
}
fn get_notifications(auth_str: &str) -> Result<NotificationResponse, String> {
let content_type: Mime = try!(Mime::from_str("Application/Json").map_err(|_| "Mime type not found"));
let client = Client::new();
let request = client.get("https://api.github.com/notifications")
.header(Authorization(auth_str.to_string()))
.header(Accept(vec![qitem(content_type)]))
.header(UserAgent("rusthub".to_string()));
let mut response = try!(request.send().map_err(|err| err.to_string()));
let mut json_str = String::new();
let notifications: Notifications = match response.read_to_string(&mut json_str) {
Ok(_) => {
let result = json::decode(&json_str);
match result {
Ok(notification_response) => notification_response,
Err(err) => return Err(err.to_string())
}
},
Err(err) => return Err(err.to_string())
};
if response.status != hyper::Ok {
return Err(json_str)
}
let pi_header: String = match response.headers.get::<XPollInterval>() {
Some(val) => val.deref().clone(),
None => return Err("XPollInterval header expected but not received".to_string())
};
let rl_header: String = match response.headers.get::<XRateLimit>() {
Some(val) => val.deref().clone(),
None => return Err("XRateLimit header expected but not received".to_string())
};
let rlr_header: String = match response.headers.get::<XRateLimitRemaining>() {
Some(val) => val.deref().clone(),
None => return Err("XRateLimitRemaining header expected but not received".to_string())
};
let poll_interval: usize = try!(usize::from_str_radix(&pi_header, 10_u32).map_err(|err| err.to_string()));
let rate_limit: usize = try!(usize::from_str_radix(&rl_header, 10_u32).map_err(|err| err.to_string()));
let rate_limit_remaining: usize = try!(usize::from_str_radix(&rlr_header, 10_u32).map_err(|err| err.to_string()));
Ok(NotificationResponse {
poll_interval: poll_interval,
rate_limit: rate_limit,
rate_limit_remaining: rate_limit_remaining,
notifications: notifications
})
}
impl Decodable for Notifications {
fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
Ok(Notifications {
list: try!(d.read_to_vec(|d| { Decodable::decode(d) }))
})
}
}
impl Decodable for Notification {
fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
d.read_struct("root", 0, |d| {
Ok(Notification {
id: try!(d.read_struct_field("id", 0, |d| Decodable::decode(d))),
unread: try!(d.read_struct_field("unread", 1, |d| Decodable::decode(d))),
reason: try!(d.read_struct_field("reason", 2, |d| Decodable::decode(d))),
updated_at: try!(d.read_struct_field("updated_at", 3, |d| Decodable::decode(d))),
last_read_at: try!(d.read_struct_field("last_read_at", 4, |d| Decodable::decode(d))),
subject: try!(d.read_struct_field("subject", 5, |d| Decodable::decode(d))),
repository: try!(d.read_struct_field("repository", 6, |d| Decodable::decode(d))),
url: try!(d.read_struct_field("url", 7, |d| Decodable::decode(d))),
subscription_url: try!(d.read_struct_field("subscription_url", 8, |d| Decodable::decode(d)))
})
})
}
}
impl Decodable for Repository {
fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
d.read_struct("root", 0, |d| {
Ok(Repository {
id: try!(d.read_struct_field("id", 0, |d| Decodable::decode(d))),
name: try!(d.read_struct_field("name", 1, |d| Decodable::decode(d))),
full_name: try!(d.read_struct_field("full_name", 2, |d| Decodable::decode(d))),
owner: try!(d.read_struct_field("owner", 3, |d| Decodable::decode(d))),
private: try!(d.read_struct_field("private", 4, |d| Decodable::decode(d))),
html_url: try!(d.read_struct_field("html_url", 5, |d| Decodable::decode(d))),
description: try!(d.read_struct_field("description", 6, |d| Decodable::decode(d))),
fork: try!(d.read_struct_field("fork", 7, |d| Decodable::decode(d))),
url: try!(d.read_struct_field("url", 8, |d| Decodable::decode(d))),
forks_url: try!(d.read_struct_field("forks_url", 9, |d| Decodable::decode(d))),
keys_url: try!(d.read_struct_field("keys_url", 10, |d| Decodable::decode(d))),
collaborators_url: try!(d.read_struct_field("collaborators_url", 11, |d| Decodable::decode(d))),
teams_url: try!(d.read_struct_field("teams_url", 12, |d| Decodable::decode(d))),
hooks_url: try!(d.read_struct_field("hooks_url", 13, |d| Decodable::decode(d))),
issue_events_url: try!(d.read_struct_field("issue_events_url", 14, |d| Decodable::decode(d))),
events_url: try!(d.read_struct_field("events_url", 15, |d| Decodable::decode(d))),
assignees_url: try!(d.read_struct_field("assignees_url", 16, |d| Decodable::decode(d))),
branches_url: try!(d.read_struct_field("branches_url", 17, |d| Decodable::decode(d))),
tags_url: try!(d.read_struct_field("tags_url", 18, |d| Decodable::decode(d))),
blobs_url: try!(d.read_struct_field("blobs_url", 19, |d| Decodable::decode(d))),
git_tags_url: try!(d.read_struct_field("git_tags_url", 20, |d| Decodable::decode(d))),
git_refs_url: try!(d.read_struct_field("git_refs_url", 21, |d| Decodable::decode(d))),
trees_url: try!(d.read_struct_field("trees_url", 22, |d| Decodable::decode(d))),
statuses_url: try!(d.read_struct_field("statuses_url", 23, |d| Decodable::decode(d))),
languages_url: try!(d.read_struct_field("languages_url", 24, |d| Decodable::decode(d))),
stargazers_url: try!(d.read_struct_field("stargazers_url", 25, |d| Decodable::decode(d))),
contributors_url: try!(d.read_struct_field("contributors_url", 26, |d| Decodable::decode(d))),
subscribers_url: try!(d.read_struct_field("subscribers_url", 27, |d| Decodable::decode(d))),
subscription_url: try!(d.read_struct_field("subscription_url", 28, |d| Decodable::decode(d))),
commits_url: try!(d.read_struct_field("commits_url", 29, |d| Decodable::decode(d))),
git_commits_url: try!(d.read_struct_field("git_commits_url", 30, |d| Decodable::decode(d))),
comments_url: try!(d.read_struct_field("comments_url", 31, |d| Decodable::decode(d))),
issue_comment_url: try!(d.read_struct_field("issue_comment_url", 32, |d| Decodable::decode(d))),
contents_url: try!(d.read_struct_field("contents_url", 33, |d| Decodable::decode(d))),
compare_url: try!(d.read_struct_field("compare_url", 34, |d| Decodable::decode(d))),
merges_url: try!(d.read_struct_field("merges_url", 35, |d| Decodable::decode(d))),
archive_url: try!(d.read_struct_field("archive_url", 36, |d| Decodable::decode(d))),
downloads_url: try!(d.read_struct_field("downloads_url", 37, |d| Decodable::decode(d))),
issues_url: try!(d.read_struct_field("issues_url", 38, |d| Decodable::decode(d))),
pulls_url: try!(d.read_struct_field("pulls_url", 39, |d| Decodable::decode(d))),
milestones_url: try!(d.read_struct_field("milestones_url", 40, |d| Decodable::decode(d))),
notifications_url: try!(d.read_struct_field("notifications_url", 41, |d| Decodable::decode(d))),
labels_url: try!(d.read_struct_field("labels_url", 42, |d| Decodable::decode(d))),
releases_url: try!(d.read_struct_field("releases_url", 43, |d| Decodable::decode(d))),
deployments_url: try!(d.read_struct_field("deployments_url", 44, |d| Decodable::decode(d)))
})
})
}
}
impl Decodable for Owner {
fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
d.read_struct("root", 0, |d| {
Ok(Owner {
login: try!(d.read_struct_field("login", 0, |d| Decodable::decode(d))),
id: try!(d.read_struct_field("id", 1, |d| Decodable::decode(d))),
avatar_url: try!(d.read_struct_field("avatar_url", 2, |d| Decodable::decode(d))),
gravatar_id: try!(d.read_struct_field("gravatar_id", 3, |d| Decodable::decode(d))),
url: try!(d.read_struct_field("url", 4, |d| Decodable::decode(d))),
html_url: try!(d.read_struct_field("html_url", 5, |d| Decodable::decode(d))),
followers_url: try!(d.read_struct_field("followers_url", 6, |d| Decodable::decode(d))),
following_url: try!(d.read_struct_field("following_url", 7, |d| Decodable::decode(d))),
gists_url: try!(d.read_struct_field("gists_url", 8, |d| Decodable::decode(d))),
starred_url: try!(d.read_struct_field("starred_url", 9, |d| Decodable::decode(d))),
subscriptions_url: try!(d.read_struct_field("subscriptions_url", 10, |d| Decodable::decode(d))),
organizations_url: try!(d.read_struct_field("organizations_url", 11, |d| Decodable::decode(d))),
repos_url: try!(d.read_struct_field("repos_url", 12, |d| Decodable::decode(d))),
events_url: try!(d.read_struct_field("events_url", 13, |d| Decodable::decode(d))),
received_events_url: try!(d.read_struct_field("received_events_url", 14, |d| Decodable::decode(d))),
owner_type: try!(d.read_struct_field("type", 15, |d| Decodable::decode(d))),
site_admin: try!(d.read_struct_field("site_admin", 16, |d| Decodable::decode(d)))
})
})
}
}
impl Decodable for Subject {
fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
d.read_struct("root", 0, |d| {
Ok(Subject {
title: try!(d.read_struct_field("title", 0, |d| Decodable::decode(d))),
url: try!(d.read_struct_field("url", 1, |d| Decodable::decode(d))),
latest_comment_url: try!(d.read_struct_field("latest_comment_url", 2, |d| Decodable::decode(d))),
subject_type: try!(d.read_struct_field("type", 3, |d| Decodable::decode(d)))
})
})
}
}
impl Encodable for Notifications {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_from_vec(&self.list, |s,e| {
e.encode(s)
})
}
}
impl Encodable for Notification {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_struct("Notification", 9, |s| {
try!(s.emit_struct_field("id", 0, |s| {
s.emit_str(&self.id)
}));
try!(s.emit_struct_field("unread", 1, |s| {
s.emit_bool(self.unread)
}));
try!(s.emit_struct_field("reason", 2, |s| {
s.emit_str(&self.reason)
}));
try!(s.emit_struct_field("updated_at", 3, |s| {
s.emit_str(&self.updated_at)
}));
try!(s.emit_struct_field("last_read_at", 4, |s| {
s.emit_option(|s| {
match &self.last_read_at {
&Some(ref lra) => s.emit_option_some(|s| s.emit_str(&lra)),
&None => s.emit_option_none()
}
})
}));
try!(s.emit_struct_field("subject", 5, |s| {
self.subject.encode(s)
}));
try!(s.emit_struct_field("repository", 6, |s| {
self.repository.encode(s)
}));
try!(s.emit_struct_field("url", 7, |s| {
s.emit_str(&self.url)
}));
try!(s.emit_struct_field("subscription_url", 8, |s| {
s.emit_str(&self.subscription_url)
}));
Ok(())
})
}
}
impl Encodable for Repository {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_struct("Repository", 45, |s| {
try!(s.emit_struct_field("id", 0, |s| {
s.emit_usize(self.id)
}));
try!(s.emit_struct_field("name", 1, |s| {
s.emit_str(&self.name)
}));
try!(s.emit_struct_field("full_name", 2, |s| {
s.emit_str(&self.full_name)
}));
try!(s.emit_struct_field("owner", 3, |s| {
self.owner.encode(s)
}));
try!(s.emit_struct_field("private", 4, |s| {
s.emit_bool(self.private)
}));
try!(s.emit_struct_field("html_url", 5, |s| {
s.emit_str(&self.html_url)
}));
try!(s.emit_struct_field("description", 6, |s| {
s.emit_str(&self.description)
}));
try!(s.emit_struct_field("fork", 7, |s| {
s.emit_bool(self.fork)
}));
try!(s.emit_struct_field("url", 8, |s| {
s.emit_str(&self.url)
}));
try!(s.emit_struct_field("forks_url", 9, |s| {
s.emit_str(&self.forks_url)
}));
try!(s.emit_struct_field("keys_url", 10, |s| {
s.emit_str(&self.keys_url)
}));
try!(s.emit_struct_field("collaborators_url", 11, |s| {
s.emit_str(&self.collaborators_url)
}));
try!(s.emit_struct_field("teams_url", 12, |s| {
s.emit_str(&self.teams_url)
}));
try!(s.emit_struct_field("hooks_url", 13, |s| {
s.emit_str(&self.hooks_url)
}));
try!(s.emit_struct_field("issue_events_url", 14, |s| {
s.emit_str(&self.issue_events_url)
}));
try!(s.emit_struct_field("events_url", 15, |s| {
s.emit_str(&self.events_url)
}));
try!(s.emit_struct_field("assignees_url", 16, |s| {
s.emit_str(&self.assignees_url)
}));
try!(s.emit_struct_field("branches_url", 17, |s| {
s.emit_str(&self.branches_url)
}));
try!(s.emit_struct_field("tags_url", 18, |s| {
s.emit_str(&self.tags_url)
}));
try!(s.emit_struct_field("blobs_url", 19, |s| {
s.emit_str(&self.blobs_url)
}));
try!(s.emit_struct_field("git_tags_url", 20, |s| {
s.emit_str(&self.git_tags_url)
}));
try!(s.emit_struct_field("git_refs_url", 21, |s| {
s.emit_str(&self.git_refs_url)
}));
try!(s.emit_struct_field("trees_url", 22, |s| {
s.emit_str(&self.trees_url)
}));
try!(s.emit_struct_field("statuses_url", 23, |s| {
s.emit_str(&self.statuses_url)
}));
try!(s.emit_struct_field("languages_url", 24, |s| {
s.emit_str(&self.languages_url)
}));
try!(s.emit_struct_field("stargazers_url", 25, |s| {
s.emit_str(&self.stargazers_url)
}));
try!(s.emit_struct_field("contributors_url", 26, |s| {
s.emit_str(&self.contributors_url)
}));
try!(s.emit_struct_field("subscribers_url", 27, |s| {
s.emit_str(&self.subscribers_url)
}));
try!(s.emit_struct_field("subscription_url", 28, |s| {
s.emit_str(&self.subscription_url)
}));
try!(s.emit_struct_field("commits_url", 29, |s| {
s.emit_str(&self.commits_url)
}));
try!(s.emit_struct_field("git_commits_url", 30, |s| {
s.emit_str(&self.git_commits_url)
}));
try!(s.emit_struct_field("comments_url", 31, |s| {
s.emit_str(&self.comments_url)
}));
try!(s.emit_struct_field("issue_comment_url", 32, |s| {
s.emit_str(&self.issue_comment_url)
}));
try!(s.emit_struct_field("contents_url", 33, |s| {
s.emit_str(&self.contents_url)
}));
try!(s.emit_struct_field("compare_url", 34, |s| {
s.emit_str(&self.compare_url)
}));
try!(s.emit_struct_field("merges_url", 35, |s| {
s.emit_str(&self.merges_url)
}));
try!(s.emit_struct_field("archive_url", 36, |s| {
s.emit_str(&self.archive_url)
}));
try!(s.emit_struct_field("downloads_url", 37, |s| {
s.emit_str(&self.downloads_url)
}));
try!(s.emit_struct_field("issues_url", 38, |s| {
s.emit_str(&self.issues_url)
}));
try!(s.emit_struct_field("pulls_url", 39, |s| {
s.emit_str(&self.pulls_url)
}));
try!(s.emit_struct_field("milestones_url", 40, |s| {
s.emit_str(&self.milestones_url)
}));
try!(s.emit_struct_field("notifications_url", 41, |s| {
s.emit_str(&self.notifications_url)
}));
try!(s.emit_struct_field("labels_url", 42, |s| {
s.emit_str(&self.labels_url)
}));
try!(s.emit_struct_field("releases_url", 43, |s| {
s.emit_str(&self.releases_url)
}));
try!(s.emit_struct_field("deployments_url", 44, |s| {
s.emit_str(&self.deployments_url)
}));
Ok(())
})
}
}
impl Encodable for Owner {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_struct("Owner", 17, |s| {
try!(s.emit_struct_field("login", 0, |s| {
s.emit_str(&self.login)
}));
try!(s.emit_struct_field("id", 1, |s| {
s.emit_usize(self.id)
}));
try!(s.emit_struct_field("avatar_url", 2, |s| {
s.emit_str(&self.avatar_url)
}));
try!(s.emit_struct_field("gravatar_id", 3, |s| {
s.emit_str(&self.gravatar_id)
}));
try!(s.emit_struct_field("url", 4, |s| {
s.emit_str(&self.url)
}));
try!(s.emit_struct_field("html_url", 5, |s| {
s.emit_str(&self.html_url)
}));
try!(s.emit_struct_field("followers_url", 6, |s| {
s.emit_str(&self.followers_url)
}));
try!(s.emit_struct_field("following_url", 7, |s| {
s.emit_str(&self.following_url)
}));
try!(s.emit_struct_field("gists_url", 8, |s| {
s.emit_str(&self.gists_url)
}));
try!(s.emit_struct_field("starred_url", 9, |s| {
s.emit_str(&self.starred_url)
}));
try!(s.emit_struct_field("subscriptions_url", 10, |s| {
s.emit_str(&self.subscriptions_url)
}));
try!(s.emit_struct_field("organizations_url", 11, |s| {
s.emit_str(&self.organizations_url)
}));
try!(s.emit_struct_field("repos_url", 12, |s| {
s.emit_str(&self.repos_url)
}));
try!(s.emit_struct_field("events_url", 13, |s| {
s.emit_str(&self.events_url)
}));
try!(s.emit_struct_field("received_events_url", 14, |s| {
s.emit_str(&self.received_events_url)
}));
try!(s.emit_struct_field("type", 15, |s| {
s.emit_str(&self.owner_type)
}));
try!(s.emit_struct_field("site_admin", 16, |s| {
s.emit_bool(self.site_admin)
}));
Ok(())
})
}
}
impl Encodable for Subject {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_struct("Subject", 4, |s| {
try!(s.emit_struct_field("title", 0, |s| {
s.emit_str(&self.title)
}));
try!(s.emit_struct_field("url", 1, |s| {
s.emit_str(&self.url)
}));
try!(s.emit_struct_field("latest_comment_url", 2, |s| {
s.emit_option(|s| {
match &self.latest_comment_url {
&Some(ref lcu) => s.emit_option_some(|s| s.emit_str(&lcu)),
&None => s.emit_option_none()
}
})
}));
try!(s.emit_struct_field("type", 3, |s| {
s.emit_str(&self.subject_type)
}));
Ok(())
})
}
} |
// Check if two device_id's have a relationship
// true: They do
// false: They don't
use crate::DATABASE;
use rusqlite::{Connection, Result};
#[derive(Debug)]
pub struct Pairing {
pub id: i32,
pub device_one: String,
pub device_two: String,
pub pairing: i32,
}
// checks if pairing exists
// true: if one does
// false: if one does not
pub fn is_paired(from: &String, to: &String) -> Result<bool> {
let mut count = 0;
let conn = Connection::open(DATABASE.to_owned())?;
let mut stmt = conn.prepare("SELECT COUNT(*) FROM pairing WHERE pairing != 0 AND ((device_one = ?1 AND device_two = ?2) OR (device_one = ?2 AND device_two = ?1))")?;
stmt.query_row(&[from, to], |row| Ok(count = row.get(0)?))?;
if count > 0 {
return Ok(true);
}
return Ok(false);
}
// gets the realtionship from the db
pub fn get(device_one: &String, device_two: &String) -> Result<Pairing> {
let conn = Connection::open(DATABASE.to_owned())?;
let mut stmt = conn.prepare("SELECT id, device_one, device_two, pairing FROM pairing WHERE (device_one = ?1 AND device_two = ?2)")?;
let rel = stmt.query_row(&[device_one, device_two], |row| {
Ok(Pairing {
id: row.get(0)?,
device_one: row.get(1)?,
device_two: row.get(2)?,
pairing: row.get(3)?,
})
})?;
return Ok(rel);
}
// creates a relationship between two devices
pub fn create(device_one: &String, device_two: &String) -> Result<bool> {
// if a relationship exists, then return with an ok
let exists = is_paired(device_one, device_two)?;
if exists == true {
println!(
"Pairing {:?} with {:?} already exists with status 1",
device_one, device_two
);
return Ok(true);
}
let conn = Connection::open(DATABASE.to_owned())?;
let dev_one = get(device_one, device_two);
let dev_two = get(device_two, device_one);
// If no pairing has occured
if dev_one.is_err() == true && dev_two.is_err() == true {
// Insert a new record into the database
let mut stmt = conn
.prepare("INSERT INTO pairing (device_one, device_two, pairing) VALUES (?1, ?2, 0)")?;
stmt.execute(&[device_one, device_two])?;
return Ok(true);
}
// if dev_one exists, use it's ID to increment the pairing to 1
if dev_one.is_err() == true && dev_two.is_err() == false {
let mut stmt = conn.prepare("UPDATE pairing SET pairing = 1 WHERE id = ?1")?;
stmt.execute(&[&dev_two?.id])?;
} else {
println!(
"Pairing {:?} with {:?} already exists with status {:?}",
device_one, device_two, dev_one?.pairing
);
return Ok(true);
}
Ok(true)
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Control"]
pub ctl: CTL,
#[doc = "0x04 - Status"]
pub status: STATUS,
_reserved2: [u8; 60usize],
#[doc = "0x44 - Transmitter command FIFO status"]
pub tx_cmd_fifo_status: TX_CMD_FIFO_STATUS,
_reserved3: [u8; 8usize],
#[doc = "0x50 - Transmitter command FIFO write"]
pub tx_cmd_fifo_wr: TX_CMD_FIFO_WR,
_reserved4: [u8; 44usize],
#[doc = "0x80 - Transmitter data FIFO control"]
pub tx_data_fifo_ctl: TX_DATA_FIFO_CTL,
#[doc = "0x84 - Transmitter data FIFO status"]
pub tx_data_fifo_status: TX_DATA_FIFO_STATUS,
_reserved6: [u8; 8usize],
#[doc = "0x90 - Transmitter data FIFO write"]
pub tx_data_fifo_wr1: TX_DATA_FIFO_WR1,
#[doc = "0x94 - Transmitter data FIFO write"]
pub tx_data_fifo_wr2: TX_DATA_FIFO_WR2,
#[doc = "0x98 - Transmitter data FIFO write"]
pub tx_data_fifo_wr4: TX_DATA_FIFO_WR4,
_reserved9: [u8; 36usize],
#[doc = "0xc0 - Receiver data FIFO control"]
pub rx_data_fifo_ctl: RX_DATA_FIFO_CTL,
#[doc = "0xc4 - Receiver data FIFO status"]
pub rx_data_fifo_status: RX_DATA_FIFO_STATUS,
_reserved11: [u8; 8usize],
#[doc = "0xd0 - Receiver data FIFO read"]
pub rx_data_fifo_rd1: RX_DATA_FIFO_RD1,
#[doc = "0xd4 - Receiver data FIFO read"]
pub rx_data_fifo_rd2: RX_DATA_FIFO_RD2,
#[doc = "0xd8 - Receiver data FIFO read"]
pub rx_data_fifo_rd4: RX_DATA_FIFO_RD4,
_reserved14: [u8; 4usize],
#[doc = "0xe0 - Receiver data FIFO silent read"]
pub rx_data_fifo_rd1_silent: RX_DATA_FIFO_RD1_SILENT,
_reserved15: [u8; 28usize],
#[doc = "0x100 - Slow cache control"]
pub slow_ca_ctl: SLOW_CA_CTL,
_reserved16: [u8; 4usize],
#[doc = "0x108 - Slow cache command"]
pub slow_ca_cmd: SLOW_CA_CMD,
_reserved17: [u8; 116usize],
#[doc = "0x180 - Fast cache control"]
pub fast_ca_ctl: FAST_CA_CTL,
_reserved18: [u8; 4usize],
#[doc = "0x188 - Fast cache command"]
pub fast_ca_cmd: FAST_CA_CMD,
_reserved19: [u8; 116usize],
#[doc = "0x200 - Cryptography Command"]
pub crypto_cmd: CRYPTO_CMD,
_reserved20: [u8; 28usize],
#[doc = "0x220 - Cryptography input 0"]
pub crypto_input0: CRYPTO_INPUT0,
#[doc = "0x224 - Cryptography input 1"]
pub crypto_input1: CRYPTO_INPUT1,
#[doc = "0x228 - Cryptography input 2"]
pub crypto_input2: CRYPTO_INPUT2,
#[doc = "0x22c - Cryptography input 3"]
pub crypto_input3: CRYPTO_INPUT3,
_reserved24: [u8; 16usize],
#[doc = "0x240 - Cryptography key 0"]
pub crypto_key0: CRYPTO_KEY0,
#[doc = "0x244 - Cryptography key 1"]
pub crypto_key1: CRYPTO_KEY1,
#[doc = "0x248 - Cryptography key 2"]
pub crypto_key2: CRYPTO_KEY2,
#[doc = "0x24c - Cryptography key 3"]
pub crypto_key3: CRYPTO_KEY3,
_reserved28: [u8; 16usize],
#[doc = "0x260 - Cryptography output 0"]
pub crypto_output0: CRYPTO_OUTPUT0,
#[doc = "0x264 - Cryptography output 1"]
pub crypto_output1: CRYPTO_OUTPUT1,
#[doc = "0x268 - Cryptography output 2"]
pub crypto_output2: CRYPTO_OUTPUT2,
#[doc = "0x26c - Cryptography output 3"]
pub crypto_output3: CRYPTO_OUTPUT3,
_reserved32: [u8; 1360usize],
#[doc = "0x7c0 - Interrupt register"]
pub intr: INTR,
#[doc = "0x7c4 - Interrupt set register"]
pub intr_set: INTR_SET,
#[doc = "0x7c8 - Interrupt mask register"]
pub intr_mask: INTR_MASK,
#[doc = "0x7cc - Interrupt masked register"]
pub intr_masked: INTR_MASKED,
_reserved36: [u8; 48usize],
#[doc = "0x800 - Device (only used in XIP mode)"]
pub device0: DEVICE,
_reserved37: [u8; 12usize],
#[doc = "0x880 - Device (only used in XIP mode)"]
pub device1: DEVICE,
_reserved38: [u8; 12usize],
#[doc = "0x900 - Device (only used in XIP mode)"]
pub device2: DEVICE,
_reserved39: [u8; 12usize],
#[doc = "0x980 - Device (only used in XIP mode)"]
pub device3: DEVICE,
}
#[doc = r"Register block"]
#[repr(C)]
pub struct DEVICE {
#[doc = "0x00 - Control"]
pub ctl: self::device::CTL,
_reserved1: [u8; 4usize],
#[doc = "0x08 - Device region base address"]
pub addr: self::device::ADDR,
#[doc = "0x0c - Device region mask"]
pub mask: self::device::MASK,
_reserved3: [u8; 16usize],
#[doc = "0x20 - Address control"]
pub addr_ctl: self::device::ADDR_CTL,
_reserved4: [u8; 28usize],
#[doc = "0x40 - Read command control"]
pub rd_cmd_ctl: self::device::RD_CMD_CTL,
#[doc = "0x44 - Read address control"]
pub rd_addr_ctl: self::device::RD_ADDR_CTL,
#[doc = "0x48 - Read mode control"]
pub rd_mode_ctl: self::device::RD_MODE_CTL,
#[doc = "0x4c - Read dummy control"]
pub rd_dummy_ctl: self::device::RD_DUMMY_CTL,
#[doc = "0x50 - Read data control"]
pub rd_data_ctl: self::device::RD_DATA_CTL,
_reserved9: [u8; 12usize],
#[doc = "0x60 - Write command control"]
pub wr_cmd_ctl: self::device::WR_CMD_CTL,
#[doc = "0x64 - Write address control"]
pub wr_addr_ctl: self::device::WR_ADDR_CTL,
#[doc = "0x68 - Write mode control"]
pub wr_mode_ctl: self::device::WR_MODE_CTL,
#[doc = "0x6c - Write dummy control"]
pub wr_dummy_ctl: self::device::WR_DUMMY_CTL,
#[doc = "0x70 - Write data control"]
pub wr_data_ctl: self::device::WR_DATA_CTL,
}
#[doc = r"Register block"]
#[doc = "Device (only used in XIP mode)"]
pub mod device;
#[doc = "Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ctl](ctl) module"]
pub type CTL = crate::Reg<u32, _CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CTL;
#[doc = "`read()` method returns [ctl::R](ctl::R) reader structure"]
impl crate::Readable for CTL {}
#[doc = "`write(|w| ..)` method takes [ctl::W](ctl::W) writer structure"]
impl crate::Writable for CTL {}
#[doc = "Control"]
pub mod ctl;
#[doc = "Status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [status](status) module"]
pub type STATUS = crate::Reg<u32, _STATUS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _STATUS;
#[doc = "`read()` method returns [status::R](status::R) reader structure"]
impl crate::Readable for STATUS {}
#[doc = "Status"]
pub mod status;
#[doc = "Transmitter command FIFO status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tx_cmd_fifo_status](tx_cmd_fifo_status) module"]
pub type TX_CMD_FIFO_STATUS = crate::Reg<u32, _TX_CMD_FIFO_STATUS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TX_CMD_FIFO_STATUS;
#[doc = "`read()` method returns [tx_cmd_fifo_status::R](tx_cmd_fifo_status::R) reader structure"]
impl crate::Readable for TX_CMD_FIFO_STATUS {}
#[doc = "Transmitter command FIFO status"]
pub mod tx_cmd_fifo_status;
#[doc = "Transmitter command FIFO write\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tx_cmd_fifo_wr](tx_cmd_fifo_wr) module"]
pub type TX_CMD_FIFO_WR = crate::Reg<u32, _TX_CMD_FIFO_WR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TX_CMD_FIFO_WR;
#[doc = "`write(|w| ..)` method takes [tx_cmd_fifo_wr::W](tx_cmd_fifo_wr::W) writer structure"]
impl crate::Writable for TX_CMD_FIFO_WR {}
#[doc = "Transmitter command FIFO write"]
pub mod tx_cmd_fifo_wr;
#[doc = "Transmitter data FIFO control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tx_data_fifo_ctl](tx_data_fifo_ctl) module"]
pub type TX_DATA_FIFO_CTL = crate::Reg<u32, _TX_DATA_FIFO_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TX_DATA_FIFO_CTL;
#[doc = "`read()` method returns [tx_data_fifo_ctl::R](tx_data_fifo_ctl::R) reader structure"]
impl crate::Readable for TX_DATA_FIFO_CTL {}
#[doc = "`write(|w| ..)` method takes [tx_data_fifo_ctl::W](tx_data_fifo_ctl::W) writer structure"]
impl crate::Writable for TX_DATA_FIFO_CTL {}
#[doc = "Transmitter data FIFO control"]
pub mod tx_data_fifo_ctl;
#[doc = "Transmitter data FIFO status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tx_data_fifo_status](tx_data_fifo_status) module"]
pub type TX_DATA_FIFO_STATUS = crate::Reg<u32, _TX_DATA_FIFO_STATUS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TX_DATA_FIFO_STATUS;
#[doc = "`read()` method returns [tx_data_fifo_status::R](tx_data_fifo_status::R) reader structure"]
impl crate::Readable for TX_DATA_FIFO_STATUS {}
#[doc = "Transmitter data FIFO status"]
pub mod tx_data_fifo_status;
#[doc = "Transmitter data FIFO write\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tx_data_fifo_wr1](tx_data_fifo_wr1) module"]
pub type TX_DATA_FIFO_WR1 = crate::Reg<u32, _TX_DATA_FIFO_WR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TX_DATA_FIFO_WR1;
#[doc = "`write(|w| ..)` method takes [tx_data_fifo_wr1::W](tx_data_fifo_wr1::W) writer structure"]
impl crate::Writable for TX_DATA_FIFO_WR1 {}
#[doc = "Transmitter data FIFO write"]
pub mod tx_data_fifo_wr1;
#[doc = "Transmitter data FIFO write\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tx_data_fifo_wr2](tx_data_fifo_wr2) module"]
pub type TX_DATA_FIFO_WR2 = crate::Reg<u32, _TX_DATA_FIFO_WR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TX_DATA_FIFO_WR2;
#[doc = "`write(|w| ..)` method takes [tx_data_fifo_wr2::W](tx_data_fifo_wr2::W) writer structure"]
impl crate::Writable for TX_DATA_FIFO_WR2 {}
#[doc = "Transmitter data FIFO write"]
pub mod tx_data_fifo_wr2;
#[doc = "Transmitter data FIFO write\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tx_data_fifo_wr4](tx_data_fifo_wr4) module"]
pub type TX_DATA_FIFO_WR4 = crate::Reg<u32, _TX_DATA_FIFO_WR4>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TX_DATA_FIFO_WR4;
#[doc = "`write(|w| ..)` method takes [tx_data_fifo_wr4::W](tx_data_fifo_wr4::W) writer structure"]
impl crate::Writable for TX_DATA_FIFO_WR4 {}
#[doc = "Transmitter data FIFO write"]
pub mod tx_data_fifo_wr4;
#[doc = "Receiver data FIFO control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_data_fifo_ctl](rx_data_fifo_ctl) module"]
pub type RX_DATA_FIFO_CTL = crate::Reg<u32, _RX_DATA_FIFO_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RX_DATA_FIFO_CTL;
#[doc = "`read()` method returns [rx_data_fifo_ctl::R](rx_data_fifo_ctl::R) reader structure"]
impl crate::Readable for RX_DATA_FIFO_CTL {}
#[doc = "`write(|w| ..)` method takes [rx_data_fifo_ctl::W](rx_data_fifo_ctl::W) writer structure"]
impl crate::Writable for RX_DATA_FIFO_CTL {}
#[doc = "Receiver data FIFO control"]
pub mod rx_data_fifo_ctl;
#[doc = "Receiver data FIFO status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_data_fifo_status](rx_data_fifo_status) module"]
pub type RX_DATA_FIFO_STATUS = crate::Reg<u32, _RX_DATA_FIFO_STATUS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RX_DATA_FIFO_STATUS;
#[doc = "`read()` method returns [rx_data_fifo_status::R](rx_data_fifo_status::R) reader structure"]
impl crate::Readable for RX_DATA_FIFO_STATUS {}
#[doc = "Receiver data FIFO status"]
pub mod rx_data_fifo_status;
#[doc = "Receiver data FIFO read\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_data_fifo_rd1](rx_data_fifo_rd1) module"]
pub type RX_DATA_FIFO_RD1 = crate::Reg<u32, _RX_DATA_FIFO_RD1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RX_DATA_FIFO_RD1;
#[doc = "`read()` method returns [rx_data_fifo_rd1::R](rx_data_fifo_rd1::R) reader structure"]
impl crate::Readable for RX_DATA_FIFO_RD1 {}
#[doc = "Receiver data FIFO read"]
pub mod rx_data_fifo_rd1;
#[doc = "Receiver data FIFO read\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_data_fifo_rd2](rx_data_fifo_rd2) module"]
pub type RX_DATA_FIFO_RD2 = crate::Reg<u32, _RX_DATA_FIFO_RD2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RX_DATA_FIFO_RD2;
#[doc = "`read()` method returns [rx_data_fifo_rd2::R](rx_data_fifo_rd2::R) reader structure"]
impl crate::Readable for RX_DATA_FIFO_RD2 {}
#[doc = "Receiver data FIFO read"]
pub mod rx_data_fifo_rd2;
#[doc = "Receiver data FIFO read\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_data_fifo_rd4](rx_data_fifo_rd4) module"]
pub type RX_DATA_FIFO_RD4 = crate::Reg<u32, _RX_DATA_FIFO_RD4>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RX_DATA_FIFO_RD4;
#[doc = "`read()` method returns [rx_data_fifo_rd4::R](rx_data_fifo_rd4::R) reader structure"]
impl crate::Readable for RX_DATA_FIFO_RD4 {}
#[doc = "Receiver data FIFO read"]
pub mod rx_data_fifo_rd4;
#[doc = "Receiver data FIFO silent read\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rx_data_fifo_rd1_silent](rx_data_fifo_rd1_silent) module"]
pub type RX_DATA_FIFO_RD1_SILENT = crate::Reg<u32, _RX_DATA_FIFO_RD1_SILENT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RX_DATA_FIFO_RD1_SILENT;
#[doc = "`read()` method returns [rx_data_fifo_rd1_silent::R](rx_data_fifo_rd1_silent::R) reader structure"]
impl crate::Readable for RX_DATA_FIFO_RD1_SILENT {}
#[doc = "Receiver data FIFO silent read"]
pub mod rx_data_fifo_rd1_silent;
#[doc = "Slow cache control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [slow_ca_ctl](slow_ca_ctl) module"]
pub type SLOW_CA_CTL = crate::Reg<u32, _SLOW_CA_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SLOW_CA_CTL;
#[doc = "`read()` method returns [slow_ca_ctl::R](slow_ca_ctl::R) reader structure"]
impl crate::Readable for SLOW_CA_CTL {}
#[doc = "`write(|w| ..)` method takes [slow_ca_ctl::W](slow_ca_ctl::W) writer structure"]
impl crate::Writable for SLOW_CA_CTL {}
#[doc = "Slow cache control"]
pub mod slow_ca_ctl;
#[doc = "Slow cache command\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [slow_ca_cmd](slow_ca_cmd) module"]
pub type SLOW_CA_CMD = crate::Reg<u32, _SLOW_CA_CMD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SLOW_CA_CMD;
#[doc = "`read()` method returns [slow_ca_cmd::R](slow_ca_cmd::R) reader structure"]
impl crate::Readable for SLOW_CA_CMD {}
#[doc = "`write(|w| ..)` method takes [slow_ca_cmd::W](slow_ca_cmd::W) writer structure"]
impl crate::Writable for SLOW_CA_CMD {}
#[doc = "Slow cache command"]
pub mod slow_ca_cmd;
#[doc = "Fast cache control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [fast_ca_ctl](fast_ca_ctl) module"]
pub type FAST_CA_CTL = crate::Reg<u32, _FAST_CA_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FAST_CA_CTL;
#[doc = "`read()` method returns [fast_ca_ctl::R](fast_ca_ctl::R) reader structure"]
impl crate::Readable for FAST_CA_CTL {}
#[doc = "`write(|w| ..)` method takes [fast_ca_ctl::W](fast_ca_ctl::W) writer structure"]
impl crate::Writable for FAST_CA_CTL {}
#[doc = "Fast cache control"]
pub mod fast_ca_ctl;
#[doc = "Fast cache command\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [fast_ca_cmd](fast_ca_cmd) module"]
pub type FAST_CA_CMD = crate::Reg<u32, _FAST_CA_CMD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FAST_CA_CMD;
#[doc = "`read()` method returns [fast_ca_cmd::R](fast_ca_cmd::R) reader structure"]
impl crate::Readable for FAST_CA_CMD {}
#[doc = "`write(|w| ..)` method takes [fast_ca_cmd::W](fast_ca_cmd::W) writer structure"]
impl crate::Writable for FAST_CA_CMD {}
#[doc = "Fast cache command"]
pub mod fast_ca_cmd;
#[doc = "Cryptography Command\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [crypto_cmd](crypto_cmd) module"]
pub type CRYPTO_CMD = crate::Reg<u32, _CRYPTO_CMD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRYPTO_CMD;
#[doc = "`read()` method returns [crypto_cmd::R](crypto_cmd::R) reader structure"]
impl crate::Readable for CRYPTO_CMD {}
#[doc = "`write(|w| ..)` method takes [crypto_cmd::W](crypto_cmd::W) writer structure"]
impl crate::Writable for CRYPTO_CMD {}
#[doc = "Cryptography Command"]
pub mod crypto_cmd;
#[doc = "Cryptography input 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [crypto_input0](crypto_input0) module"]
pub type CRYPTO_INPUT0 = crate::Reg<u32, _CRYPTO_INPUT0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRYPTO_INPUT0;
#[doc = "`read()` method returns [crypto_input0::R](crypto_input0::R) reader structure"]
impl crate::Readable for CRYPTO_INPUT0 {}
#[doc = "`write(|w| ..)` method takes [crypto_input0::W](crypto_input0::W) writer structure"]
impl crate::Writable for CRYPTO_INPUT0 {}
#[doc = "Cryptography input 0"]
pub mod crypto_input0;
#[doc = "Cryptography input 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [crypto_input1](crypto_input1) module"]
pub type CRYPTO_INPUT1 = crate::Reg<u32, _CRYPTO_INPUT1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRYPTO_INPUT1;
#[doc = "`read()` method returns [crypto_input1::R](crypto_input1::R) reader structure"]
impl crate::Readable for CRYPTO_INPUT1 {}
#[doc = "`write(|w| ..)` method takes [crypto_input1::W](crypto_input1::W) writer structure"]
impl crate::Writable for CRYPTO_INPUT1 {}
#[doc = "Cryptography input 1"]
pub mod crypto_input1;
#[doc = "Cryptography input 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [crypto_input2](crypto_input2) module"]
pub type CRYPTO_INPUT2 = crate::Reg<u32, _CRYPTO_INPUT2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRYPTO_INPUT2;
#[doc = "`read()` method returns [crypto_input2::R](crypto_input2::R) reader structure"]
impl crate::Readable for CRYPTO_INPUT2 {}
#[doc = "`write(|w| ..)` method takes [crypto_input2::W](crypto_input2::W) writer structure"]
impl crate::Writable for CRYPTO_INPUT2 {}
#[doc = "Cryptography input 2"]
pub mod crypto_input2;
#[doc = "Cryptography input 3\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [crypto_input3](crypto_input3) module"]
pub type CRYPTO_INPUT3 = crate::Reg<u32, _CRYPTO_INPUT3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRYPTO_INPUT3;
#[doc = "`read()` method returns [crypto_input3::R](crypto_input3::R) reader structure"]
impl crate::Readable for CRYPTO_INPUT3 {}
#[doc = "`write(|w| ..)` method takes [crypto_input3::W](crypto_input3::W) writer structure"]
impl crate::Writable for CRYPTO_INPUT3 {}
#[doc = "Cryptography input 3"]
pub mod crypto_input3;
#[doc = "Cryptography key 0\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [crypto_key0](crypto_key0) module"]
pub type CRYPTO_KEY0 = crate::Reg<u32, _CRYPTO_KEY0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRYPTO_KEY0;
#[doc = "`write(|w| ..)` method takes [crypto_key0::W](crypto_key0::W) writer structure"]
impl crate::Writable for CRYPTO_KEY0 {}
#[doc = "Cryptography key 0"]
pub mod crypto_key0;
#[doc = "Cryptography key 1\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [crypto_key1](crypto_key1) module"]
pub type CRYPTO_KEY1 = crate::Reg<u32, _CRYPTO_KEY1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRYPTO_KEY1;
#[doc = "`write(|w| ..)` method takes [crypto_key1::W](crypto_key1::W) writer structure"]
impl crate::Writable for CRYPTO_KEY1 {}
#[doc = "Cryptography key 1"]
pub mod crypto_key1;
#[doc = "Cryptography key 2\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [crypto_key2](crypto_key2) module"]
pub type CRYPTO_KEY2 = crate::Reg<u32, _CRYPTO_KEY2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRYPTO_KEY2;
#[doc = "`write(|w| ..)` method takes [crypto_key2::W](crypto_key2::W) writer structure"]
impl crate::Writable for CRYPTO_KEY2 {}
#[doc = "Cryptography key 2"]
pub mod crypto_key2;
#[doc = "Cryptography key 3\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [crypto_key3](crypto_key3) module"]
pub type CRYPTO_KEY3 = crate::Reg<u32, _CRYPTO_KEY3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRYPTO_KEY3;
#[doc = "`write(|w| ..)` method takes [crypto_key3::W](crypto_key3::W) writer structure"]
impl crate::Writable for CRYPTO_KEY3 {}
#[doc = "Cryptography key 3"]
pub mod crypto_key3;
#[doc = "Cryptography output 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [crypto_output0](crypto_output0) module"]
pub type CRYPTO_OUTPUT0 = crate::Reg<u32, _CRYPTO_OUTPUT0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRYPTO_OUTPUT0;
#[doc = "`read()` method returns [crypto_output0::R](crypto_output0::R) reader structure"]
impl crate::Readable for CRYPTO_OUTPUT0 {}
#[doc = "`write(|w| ..)` method takes [crypto_output0::W](crypto_output0::W) writer structure"]
impl crate::Writable for CRYPTO_OUTPUT0 {}
#[doc = "Cryptography output 0"]
pub mod crypto_output0;
#[doc = "Cryptography output 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [crypto_output1](crypto_output1) module"]
pub type CRYPTO_OUTPUT1 = crate::Reg<u32, _CRYPTO_OUTPUT1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRYPTO_OUTPUT1;
#[doc = "`read()` method returns [crypto_output1::R](crypto_output1::R) reader structure"]
impl crate::Readable for CRYPTO_OUTPUT1 {}
#[doc = "`write(|w| ..)` method takes [crypto_output1::W](crypto_output1::W) writer structure"]
impl crate::Writable for CRYPTO_OUTPUT1 {}
#[doc = "Cryptography output 1"]
pub mod crypto_output1;
#[doc = "Cryptography output 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [crypto_output2](crypto_output2) module"]
pub type CRYPTO_OUTPUT2 = crate::Reg<u32, _CRYPTO_OUTPUT2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRYPTO_OUTPUT2;
#[doc = "`read()` method returns [crypto_output2::R](crypto_output2::R) reader structure"]
impl crate::Readable for CRYPTO_OUTPUT2 {}
#[doc = "`write(|w| ..)` method takes [crypto_output2::W](crypto_output2::W) writer structure"]
impl crate::Writable for CRYPTO_OUTPUT2 {}
#[doc = "Cryptography output 2"]
pub mod crypto_output2;
#[doc = "Cryptography output 3\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [crypto_output3](crypto_output3) module"]
pub type CRYPTO_OUTPUT3 = crate::Reg<u32, _CRYPTO_OUTPUT3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRYPTO_OUTPUT3;
#[doc = "`read()` method returns [crypto_output3::R](crypto_output3::R) reader structure"]
impl crate::Readable for CRYPTO_OUTPUT3 {}
#[doc = "`write(|w| ..)` method takes [crypto_output3::W](crypto_output3::W) writer structure"]
impl crate::Writable for CRYPTO_OUTPUT3 {}
#[doc = "Cryptography output 3"]
pub mod crypto_output3;
#[doc = "Interrupt register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr](intr) module"]
pub type INTR = crate::Reg<u32, _INTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR;
#[doc = "`read()` method returns [intr::R](intr::R) reader structure"]
impl crate::Readable for INTR {}
#[doc = "`write(|w| ..)` method takes [intr::W](intr::W) writer structure"]
impl crate::Writable for INTR {}
#[doc = "Interrupt register"]
pub mod intr;
#[doc = "Interrupt set register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_set](intr_set) module"]
pub type INTR_SET = crate::Reg<u32, _INTR_SET>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_SET;
#[doc = "`read()` method returns [intr_set::R](intr_set::R) reader structure"]
impl crate::Readable for INTR_SET {}
#[doc = "`write(|w| ..)` method takes [intr_set::W](intr_set::W) writer structure"]
impl crate::Writable for INTR_SET {}
#[doc = "Interrupt set register"]
pub mod intr_set;
#[doc = "Interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_mask](intr_mask) module"]
pub type INTR_MASK = crate::Reg<u32, _INTR_MASK>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_MASK;
#[doc = "`read()` method returns [intr_mask::R](intr_mask::R) reader structure"]
impl crate::Readable for INTR_MASK {}
#[doc = "`write(|w| ..)` method takes [intr_mask::W](intr_mask::W) writer structure"]
impl crate::Writable for INTR_MASK {}
#[doc = "Interrupt mask register"]
pub mod intr_mask;
#[doc = "Interrupt masked register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_masked](intr_masked) module"]
pub type INTR_MASKED = crate::Reg<u32, _INTR_MASKED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_MASKED;
#[doc = "`read()` method returns [intr_masked::R](intr_masked::R) reader structure"]
impl crate::Readable for INTR_MASKED {}
#[doc = "Interrupt masked register"]
pub mod intr_masked;
|
use amethyst::shred::{System,Dispatcher,DispatcherBuilder};
use amethyst::prelude::{DataInit,World};
use amethyst::core::{SystemBundle, ArcThreadPool};
use amethyst::Error;
pub struct CustomGameData<'a, 'b> {
core_dispatcher: Dispatcher<'a, 'b>,
running_dispatcher: Dispatcher<'a, 'b>,
}
impl<'a, 'b> CustomGameData<'a, 'b> {
pub fn update(&mut self, world: &World, running: bool) {
if running {
self.running_dispatcher.dispatch(&world.res);
}
self.core_dispatcher.dispatch(&world.res);
}
}
pub struct CustomGameDataBuilder<'a, 'b> {
pub core: DispatcherBuilder<'a, 'b>,
pub running: DispatcherBuilder<'a, 'b>,
}
impl<'a, 'b> Default for CustomGameDataBuilder<'a, 'b> {
fn default() -> Self {
CustomGameDataBuilder::new()
}
}
impl<'a, 'b> CustomGameDataBuilder<'a, 'b> {
pub fn new() -> Self {
CustomGameDataBuilder {
core: DispatcherBuilder::new(),
running: DispatcherBuilder::new(),
}
}
pub fn with_base_bundle<B>(mut self, bundle: B) -> Result<Self, Error>
where
B: SystemBundle<'a, 'b>,
{
bundle
.build(&mut self.core)
.map_err(|err| Error::Core(err))?;
Ok(self)
}
pub fn with_running_bundle<B>(mut self, bundle: B) -> Result<Self, Error>
where
B: SystemBundle<'a, 'b>,
{
bundle
.build(&mut self.running)
.map_err(|err| Error::Core(err))?;
Ok(self)
}
}
impl<'a, 'b> DataInit<CustomGameData<'a, 'b>> for CustomGameDataBuilder<'a, 'b> {
fn build(self, world: &mut World) -> CustomGameData<'a, 'b> {
// Get a handle to the `ThreadPool`.
let pool = world.read_resource::<ArcThreadPool>().clone();
let mut core_dispatcher = self.core.with_pool(pool.clone()).build();
let mut running_dispatcher = self.running.with_pool(pool.clone()).build();
core_dispatcher.setup(&mut world.res);
running_dispatcher.setup(&mut world.res);
CustomGameData { core_dispatcher, running_dispatcher }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.