text stringlengths 8 4.13M |
|---|
// 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 std::ops::Deref;
use std::ops::DerefMut;
use common_arrow::arrow::bitmap::Bitmap;
pub struct Wrap<T>(pub T);
impl<T> Deref for Wrap<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
unsafe fn index_of_unchecked<T>(slice: &[T], item: &T) -> usize {
(item as *const _ as usize - slice.as_ptr() as usize) / std::mem::size_of::<T>()
}
fn index_of<T>(slice: &[T], item: &T) -> Option<usize> {
debug_assert!(std::mem::size_of::<T>() > 0);
let ptr = item as *const T;
unsafe {
if slice.as_ptr() < ptr && slice.as_ptr().add(slice.len()) > ptr {
Some(index_of_unchecked(slice, item))
} else {
None
}
}
}
/// Just a wrapper structure. Useful for certain impl specializations
/// This is for instance use to implement
/// `impl<T> FromIterator<T> for NoNull<DFPrimitiveArrary<T>>`
/// as `Option<T>` was already implemented:
/// `impl<T> FromIterator<Option<T>> for DFPrimitiveArrary<T>`
pub struct NoNull<T> {
inner: T,
}
impl<T> NoNull<T> {
pub fn new(inner: T) -> Self {
NoNull { inner }
}
pub fn into_inner(self) -> T {
self.inner
}
}
impl<T> Deref for NoNull<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T> DerefMut for NoNull<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
pub fn get_iter_capacity<T, I: Iterator<Item = T>>(iter: &I) -> usize {
match iter.size_hint() {
(_lower, Some(upper)) => upper,
(0, None) => 1024,
(lower, None) => lower,
}
}
pub fn combine_validities(lhs: Option<&Bitmap>, rhs: Option<&Bitmap>) -> Option<Bitmap> {
match (lhs, rhs) {
(Some(lhs), None) => Some(lhs.clone()),
(None, Some(rhs)) => Some(rhs.clone()),
(None, None) => None,
(Some(lhs), Some(rhs)) => Some(lhs & rhs),
}
}
|
use std::sync::Arc;
use crate::prelude::*;
use crate::light::Light;
use crate::math::*;
use crate::primitive::Primitive;
use crate::interaction::SurfaceInteraction;
pub struct Scene {
pub lights: Vec<Arc<dyn Light + Send + Sync>>,
aggregate: Arc<dyn Primitive + Send + Sync>,
world_bound: Bounds3<Float>,
}
impl Scene {
pub fn new(aggregate: Arc<dyn Primitive + Send + Sync>, mut lights: Vec<Box<dyn Light + Send + Sync>>) -> Self {
let mut scene = Self {
world_bound: aggregate.world_bound(),
lights: vec![],
aggregate,
};
for light in &mut lights {
light.preprocess(&scene);
}
let lights = lights.into_iter()
.map(|l| l.into())
.collect();
scene.lights = lights;
scene
}
pub fn world_bound(&self) -> &Bounds3<Float> {
&self.world_bound
}
pub fn intersect(&self, ray: &mut Ray) -> Option<SurfaceInteraction<'_>> {
assert_ne!(ray.direction, Vector3f::new(float(0), float(0), float(0)));
self.aggregate.intersect(ray)
}
pub fn intersect_p(&self, ray: &Ray) -> bool {
self.aggregate.intersect_p(ray)
}
}
|
use std::sync::{Arc, Mutex};
use std::time::Duration;
use crate::traits::Policy;
use std::ops::DerefMut;
pub struct RetryPolicy<'l, R> {
pub(in crate) matchers: Vec<Arc<dyn Fn(&R) -> bool + 'l>>,
pub(in crate) action: Arc<Mutex<dyn FnMut(R, usize) -> () + 'l>>,
pub(in crate) durations: Vec<Duration>,
}
impl<'l, O, R> Policy<O, R> for RetryPolicy<'l, R>
where
O: FnMut() -> R
{
fn execute(&self, mut operation: O) -> R {
for (retry_count, dur) in self.durations.iter().enumerate() {
let result = operation();
// if all matchers return false -> return result
if !self.matchers.iter().any(|op| op(&result)) {
return result;
} else {
self.action.lock().unwrap().deref_mut()(result, retry_count + 1);
if dur.as_nanos() > 0 {
std::thread::sleep(*dur);
}
}
}
operation()
}
}
pub struct RetryForeverPolicy<'l, R> {
pub(in crate) matchers: Vec<Arc<dyn Fn(&R) -> bool + 'l>>,
pub(in crate) action: Arc<Mutex<dyn FnMut(R) -> () + 'l>>,
pub(in crate) duration: Duration,
}
impl<'l, O, R> Policy<O, R> for RetryForeverPolicy<'l, R>
where
O: FnMut() -> R
{
fn execute(&self, mut operation: O) -> R {
loop {
let result = operation();
if !self.matchers.iter().any(|op| op(&result)) {
return result;
} else {
self.action.lock().unwrap().deref_mut()(result);
if self.duration.as_nanos() > 0 {
std::thread::sleep(self.duration)
}
}
}
}
}
#[cfg(test)]
mod tests {
use crate::retry::RetryPolicy;
use std::sync::{Arc, Mutex};
use crate::traits::Policy;
use std::time::Duration;
#[test]
fn retry_handle() {
let mut counter = 0;
let x = RetryPolicy {
matchers: vec![Arc::new(|_r| true)],
action: Arc::new(Mutex::new(|_, _| {
counter += 1
})),
durations: vec![Duration::from_nanos(0); 5],
};
x.execute(|| ());
drop(x);
assert_eq!(5, counter);
}
#[test]
fn retry_ok() {
let mut counter = 0;
let x = RetryPolicy {
matchers: vec![Arc::new(|_r| false)],
action: Arc::new(Mutex::new(|_, _| {
counter += 1
})),
durations: vec![Duration::from_nanos(0); 5],
};
x.execute(|| ());
drop(x);
assert_eq!(0, counter);
}
} |
use std::process;
use std::sync::{Arc, RwLock};
use gtk::*;
use super::{
Header,
Content,
ConnectedApp,
open::open,
save::save,
equalize_histogram::equalize_histogram
};
use image::Image;
pub struct App {
pub window: Window,
pub header: Header,
pub content: Content
}
impl App {
pub fn new() -> App {
if gtk::init().is_err() {
eprintln!("failed to initialize GTK Application");
process::exit(1);
}
let window = Window::new(WindowType::Toplevel);
window.set_default_size(1280, 680);
let header = Header::new();
window.set_titlebar(&header.container);
let header_title =
match header.container.get_title() {
Some(title) => title,
None => panic!("Failed to optain the header title"), // should never reach this case
};
window.set_wmclass(&header_title, &header_title);
let content = Content::new();
window.add(&content.container);
window.connect_delete_event(move |_, _| {
main_quit();
Inhibit(false)
});
App { window, header, content }
}
pub fn connect_events(self) -> ConnectedApp {
let current_file = Arc::new(RwLock::new(None));
{
let save = &self.header.save;
let save_as = &self.header.save_as;
// Connect all of the events that this UI will act upon.
self.open_file(current_file.clone());
self.save_event(&save, current_file.clone(), false);
self.save_event(&save_as, current_file.clone(), true);
self.equalize_histogram(current_file.clone());
}
ConnectedApp::new(self)
}
fn equalize_histogram(&self, current_file: Arc<RwLock<Option<Image>>>) {
let image_container = self.content.image_container.image_widget.clone();
let equalize_histogram_button = &self.content.side_menu.equalize_histogram;
equalize_histogram_button.connect_clicked(move |ehb| {
ehb.set_sensitive(false);
match equalize_histogram(&image_container, ¤t_file) {
Err(error) => println!("{:?}", error),
Ok(()) => ()
}
ehb.set_sensitive(true);
});
}
fn open_file(&self, current_file: Arc<RwLock<Option<Image>>>) {
let headerbar = self.header.container.clone();
let image_container = self.content.image_container.image_widget.clone();
self.header.open.connect_clicked(move |ob| {
ob.set_sensitive(false);
match open(&headerbar, &image_container, ¤t_file) {
Err(error) => println!("{:?}", error),
Ok(()) => ()
}
ob.set_sensitive(true);
});
}
fn save_event( &self,
button: &Button,
current_file: Arc<RwLock<Option<Image>>>,
save_as: bool,
) {
let headerbar = self.header.container.clone();
button.connect_clicked( move |sb| {
sb.set_sensitive(false);
match save(&headerbar, ¤t_file, save_as) {
Err(error) => println!("{:?}", error),
Ok(()) => ()
}
sb.set_sensitive(true);
});
}
} |
// We comment on Rust like in JavaScript
/*
* This also works, exactly like JavaScript.
*/
/// First Exercise of the Rust by Example Book!
fn main() {
println!("Hello World!");
println!("I'm a Rustacean!");
}
|
// Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::Result;
use datastore::ChangesStore;
use datastore::DeltaStore;
use datastore::ReadonlyStore;
use hh24_types::ToplevelCanonSymbolHash;
use hh24_types::ToplevelSymbolHash;
use naming_provider::NamingProvider;
use ocamlrep::rc::RcOc;
use oxidized::file_info;
use oxidized::file_info::NameType;
use oxidized::naming_types;
use parking_lot::Mutex;
use pos::ConstName;
use pos::FunName;
use pos::ModuleName;
use pos::RelativePath;
use pos::TypeName;
use reverse_naming_table::ReverseNamingTable;
use shm_store::ShmStore;
/// Designed after naming_heap.ml.
pub struct NamingTable {
types: ReverseNamingTable<TypeName, (Pos, naming_types::KindOfType)>,
funs: ReverseNamingTable<FunName, Pos>,
consts: ChangesStore<ToplevelSymbolHash, Pos>,
modules: ChangesStore<ToplevelSymbolHash, Pos>,
db: Arc<MaybeNamingDb>,
}
impl NamingTable {
pub fn new(db_path: Option<PathBuf>) -> Result<Self> {
let db = Arc::new(MaybeNamingDb(Mutex::new(None)));
if let Some(db_path) = db_path {
db.set_db_path(db_path)?;
}
Ok(Self {
types: ReverseNamingTable::new(
Arc::new(TypeDb(Arc::clone(&db))),
"TypePos",
"TypeCanon",
),
funs: ReverseNamingTable::new(Arc::new(FunDb(Arc::clone(&db))), "FunPos", "FunCanon"),
consts: ChangesStore::new(Arc::new(DeltaStore::new(
Arc::new(ShmStore::new(
"ConstPos",
shm_store::Evictability::NonEvictable,
shm_store::Compression::None,
)),
Arc::new(ConstDb(Arc::clone(&db))),
))),
modules: ChangesStore::new(Arc::new(DeltaStore::new(
Arc::new(ShmStore::new(
"ModulePos",
shm_store::Evictability::NonEvictable,
shm_store::Compression::None,
)),
Arc::new(ModuleDb(Arc::clone(&db))),
))),
db,
})
}
pub fn db_path(&self) -> Option<PathBuf> {
self.db.db_path()
}
pub fn set_db_path(&self, db_path: PathBuf) -> Result<()> {
Ok(self.db.set_db_path(db_path)?)
}
pub fn add_type(
&self,
name: TypeName,
pos_and_kind: &(file_info::Pos, naming_types::KindOfType),
) -> Result<()> {
self.types
.insert(name, ((&pos_and_kind.0).into(), pos_and_kind.1))
}
pub fn get_type_pos(
&self,
name: TypeName,
) -> Result<Option<(file_info::Pos, naming_types::KindOfType)>> {
Ok(self
.types
.get_pos(name)?
.map(|(pos, kind)| (pos.into(), kind)))
}
pub fn remove_type_batch(&self, names: &[TypeName]) -> Result<()> {
self.types.remove_batch(names.iter().copied())
}
pub fn get_canon_type_name(&self, name: TypeName) -> Result<Option<TypeName>> {
self.types.get_canon_name(name)
}
pub fn add_fun(&self, name: FunName, pos: &file_info::Pos) -> Result<()> {
self.funs.insert(name, pos.into())
}
pub fn get_fun_pos(&self, name: FunName) -> Result<Option<file_info::Pos>> {
Ok(self.funs.get_pos(name)?.map(Into::into))
}
pub fn remove_fun_batch(&self, names: &[FunName]) -> Result<()> {
self.funs.remove_batch(names.iter().copied())
}
pub fn get_canon_fun_name(&self, name: FunName) -> Result<Option<FunName>> {
self.funs.get_canon_name(name)
}
pub fn add_const(&self, name: ConstName, pos: &file_info::Pos) -> Result<()> {
self.consts.insert(name.into(), pos.into())
}
pub fn get_const_pos(&self, name: ConstName) -> Result<Option<file_info::Pos>> {
Ok(self.consts.get(name.into())?.map(Into::into))
}
pub fn remove_const_batch(&self, names: &[ConstName]) -> Result<()> {
self.consts
.remove_batch(&mut names.iter().copied().map(Into::into))
}
pub fn add_module(&self, name: ModuleName, pos: &file_info::Pos) -> Result<()> {
self.modules.insert(name.into(), pos.into())
}
pub fn get_module_pos(&self, name: ModuleName) -> Result<Option<file_info::Pos>> {
Ok(self.modules.get(name.into())?.map(Into::into))
}
pub fn remove_module_batch(&self, names: &[ModuleName]) -> Result<()> {
self.modules
.remove_batch(&mut names.iter().copied().map(Into::into))
}
pub fn push_local_changes(&self) {
self.types.push_local_changes();
self.funs.push_local_changes();
self.consts.push_local_changes();
self.modules.push_local_changes();
}
pub fn pop_local_changes(&self) {
self.types.pop_local_changes();
self.funs.pop_local_changes();
self.consts.pop_local_changes();
self.modules.pop_local_changes();
}
pub fn get_filenames_by_hash(
&self,
hashes: &deps_rust::DepSet,
) -> Result<std::collections::BTreeSet<RelativePath>> {
hashes
.iter()
.filter_map(|&hash| self.get_filename_by_hash(hash).transpose())
.collect()
}
fn get_filename_by_hash(&self, hash: deps_rust::Dep) -> Result<Option<RelativePath>> {
Ok(self
.db
.with_db(|db| db.get_path_by_symbol_hash(ToplevelSymbolHash::from_u64(hash.into())))?
.as_ref()
.map(Into::into))
}
}
impl NamingProvider for NamingTable {
fn get_type_path_and_kind(
&self,
name: pos::TypeName,
) -> Result<Option<(RelativePath, naming_types::KindOfType)>> {
Ok(self
.get_type_pos(name)?
.map(|(pos, kind)| (pos.path().into(), kind)))
}
fn get_fun_path(&self, name: pos::FunName) -> Result<Option<RelativePath>> {
Ok(self.get_fun_pos(name)?.map(|pos| pos.path().into()))
}
fn get_const_path(&self, name: pos::ConstName) -> Result<Option<RelativePath>> {
Ok(self.get_const_pos(name)?.map(|pos| pos.path().into()))
}
fn get_module_path(&self, name: pos::ModuleName) -> Result<Option<RelativePath>> {
Ok(self.get_module_pos(name)?.map(|pos| pos.path().into()))
}
}
impl std::fmt::Debug for NamingTable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NamingTable").finish()
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
enum Pos {
Full(pos::BPos),
File(NameType, RelativePath),
}
impl From<&file_info::Pos> for Pos {
fn from(pos: &file_info::Pos) -> Self {
match pos {
file_info::Pos::Full(pos) => Self::Full(pos.into()),
file_info::Pos::File(name_type, path) => Self::File(*name_type, (&**path).into()),
}
}
}
impl From<Pos> for file_info::Pos {
fn from(pos: Pos) -> Self {
match pos {
Pos::Full(pos) => Self::Full(pos.into()),
Pos::File(name_type, path) => Self::File(name_type, RcOc::new(path.into())),
}
}
}
struct MaybeNamingDb(Mutex<Option<(names::Names, PathBuf)>>);
impl MaybeNamingDb {
fn db_path(&self) -> Option<PathBuf> {
self.0.lock().as_ref().map(|(_, path)| path.clone())
}
fn set_db_path(&self, db_path: PathBuf) -> Result<()> {
let mut lock = self.0.lock();
*lock = Some((names::Names::from_file_assume_valid_db(&db_path)?, db_path));
Ok(())
}
fn with_db<T, F>(&self, f: F) -> Result<Option<T>>
where
F: FnOnce(&names::Names) -> Result<Option<T>>,
{
match &*self.0.lock() {
Some((db, _)) => Ok(f(db)?),
None => Ok(None),
}
}
}
impl std::fmt::Debug for MaybeNamingDb {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MaybeNamingDb").finish()
}
}
#[derive(Clone, Debug)]
struct TypeDb(Arc<MaybeNamingDb>);
impl ReadonlyStore<ToplevelSymbolHash, (Pos, naming_types::KindOfType)> for TypeDb {
fn get(&self, key: ToplevelSymbolHash) -> Result<Option<(Pos, naming_types::KindOfType)>> {
self.0.with_db(|db| {
Ok(db.get_filename(key)?.and_then(|(path, name_type)| {
let kind = match name_type {
NameType::Class => naming_types::KindOfType::TClass,
NameType::Typedef => naming_types::KindOfType::TTypedef,
_ => return None,
};
Some((Pos::File(kind.into(), (&path).into()), kind))
}))
})
}
}
impl ReadonlyStore<ToplevelCanonSymbolHash, TypeName> for TypeDb {
fn contains_key(&self, key: ToplevelCanonSymbolHash) -> Result<bool> {
Ok(self
.0
.with_db(|db| db.get_type_name_case_insensitive(key))?
.is_some())
}
fn get(&self, key: ToplevelCanonSymbolHash) -> Result<Option<TypeName>> {
self.0
.with_db(|db| Ok(db.get_type_name_case_insensitive(key)?.map(TypeName::new)))
}
}
#[derive(Clone, Debug)]
struct FunDb(Arc<MaybeNamingDb>);
impl ReadonlyStore<ToplevelSymbolHash, Pos> for FunDb {
fn contains_key(&self, key: ToplevelSymbolHash) -> Result<bool> {
Ok(self
.0
.with_db(|db| db.get_path_by_symbol_hash(key))?
.is_some())
}
fn get(&self, key: ToplevelSymbolHash) -> Result<Option<Pos>> {
self.0.with_db(|db| {
Ok(db
.get_path_by_symbol_hash(key)?
.map(|path| Pos::File(NameType::Fun, (&path).into())))
})
}
}
impl ReadonlyStore<ToplevelCanonSymbolHash, FunName> for FunDb {
fn contains_key(&self, key: ToplevelCanonSymbolHash) -> Result<bool> {
Ok(self
.0
.with_db(|db| db.get_fun_name_case_insensitive(key))?
.is_some())
}
fn get(&self, key: ToplevelCanonSymbolHash) -> Result<Option<FunName>> {
self.0
.with_db(|db| Ok(db.get_fun_name_case_insensitive(key)?.map(FunName::new)))
}
}
#[derive(Clone, Debug)]
struct ConstDb(Arc<MaybeNamingDb>);
impl ReadonlyStore<ToplevelSymbolHash, Pos> for ConstDb {
fn contains_key(&self, key: ToplevelSymbolHash) -> Result<bool> {
Ok(self
.0
.with_db(|db| db.get_path_by_symbol_hash(key))?
.is_some())
}
fn get(&self, key: ToplevelSymbolHash) -> Result<Option<Pos>> {
self.0.with_db(|db| {
Ok(db
.get_path_by_symbol_hash(key)?
.map(|path| Pos::File(NameType::Const, (&path).into())))
})
}
}
#[derive(Clone, Debug)]
struct ModuleDb(Arc<MaybeNamingDb>);
impl ReadonlyStore<ToplevelSymbolHash, Pos> for ModuleDb {
fn contains_key(&self, key: ToplevelSymbolHash) -> Result<bool> {
Ok(self
.0
.with_db(|db| db.get_path_by_symbol_hash(key))?
.is_some())
}
fn get(&self, key: ToplevelSymbolHash) -> Result<Option<Pos>> {
self.0.with_db(|db| {
Ok(db
.get_path_by_symbol_hash(key)?
.map(|path| Pos::File(NameType::Module, (&path).into())))
})
}
}
mod reverse_naming_table {
use std::hash::Hash;
use std::sync::Arc;
use anyhow::Result;
use datastore::ChangesStore;
use datastore::DeltaStore;
use datastore::ReadonlyStore;
use hh24_types::ToplevelCanonSymbolHash;
use hh24_types::ToplevelSymbolHash;
use serde::de::DeserializeOwned;
use serde::Serialize;
use shm_store::ShmStore;
/// In-memory delta for symbols which support a canon-name lookup API (types
/// and funs).
pub struct ReverseNamingTable<K, P> {
positions: ChangesStore<ToplevelSymbolHash, P>,
canon_names: ChangesStore<ToplevelCanonSymbolHash, K>,
}
impl<K, P> ReverseNamingTable<K, P>
where
K: Copy + Hash + Eq + Send + Sync + 'static + Serialize + DeserializeOwned,
K: Into<ToplevelSymbolHash> + Into<ToplevelCanonSymbolHash>,
P: Clone + Send + Sync + 'static + Serialize + DeserializeOwned,
{
pub fn new<F>(
fallback: Arc<F>,
pos_prefix: &'static str,
canon_prefix: &'static str,
) -> Self
where
F: ReadonlyStore<ToplevelSymbolHash, P>
+ ReadonlyStore<ToplevelCanonSymbolHash, K>
+ 'static,
{
Self {
positions: ChangesStore::new(Arc::new(DeltaStore::new(
Arc::new(ShmStore::new(
pos_prefix,
shm_store::Evictability::NonEvictable,
shm_store::Compression::None,
)),
Arc::clone(&fallback) as _,
))),
canon_names: ChangesStore::new(Arc::new(DeltaStore::new(
Arc::new(ShmStore::new(
canon_prefix,
shm_store::Evictability::NonEvictable,
shm_store::Compression::None,
)),
fallback,
))),
}
}
pub fn insert(&self, name: K, pos: P) -> Result<()> {
self.positions.insert(name.into(), pos)?;
self.canon_names.insert(name.into(), name)?;
Ok(())
}
pub fn get_pos(&self, name: K) -> Result<Option<P>> {
self.positions.get(name.into())
}
pub fn get_canon_name(&self, name: K) -> Result<Option<K>> {
self.canon_names.get(name.into())
}
pub fn push_local_changes(&self) {
self.canon_names.push_local_changes();
self.positions.push_local_changes();
}
pub fn pop_local_changes(&self) {
self.canon_names.pop_local_changes();
self.positions.pop_local_changes();
}
pub fn remove_batch<I: Iterator<Item = K> + Clone>(&self, keys: I) -> Result<()> {
self.canon_names
.remove_batch(&mut keys.clone().map(Into::into))?;
self.positions.remove_batch(&mut keys.map(Into::into))?;
Ok(())
}
}
}
|
use crate::{routes, Config};
use artell_usecase::system::check_scheduler::system_update_scheduler;
use chrono::{Timelike, Utc};
use futures::{future, StreamExt};
use std::net::SocketAddr;
use tokio::time::{interval_at, Duration, Instant, Interval};
use warp::Filter;
pub async fn bind(config: Config, socket: impl Into<SocketAddr> + 'static) {
let filter = routes::api::route(config.clone()).with(warp::filters::log::log("crop"));
let server = warp::serve(filter);
let server_fut = server.bind(socket);
let cron_fut = start_system_cron(config);
tokio::pin!(cron_fut);
future::select(server_fut, cron_fut).await;
}
async fn start_system_cron(config: Config) {
system_cron_stream()
.for_each(move |_| update_scheduler(config.clone()))
.await
}
fn system_cron_stream() -> Interval {
let interval_dur = Duration::from_secs(60 * 60);
let now = Utc::now();
let mins_to_next_oclock = (60 - now.minute() as u64) % 60;
let dur_to_next_oclock = Duration::from_secs(mins_to_next_oclock * 60);
let next_oclock = Instant::now() + dur_to_next_oclock;
interval_at(next_oclock, interval_dur)
}
async fn update_scheduler(config: Config) {
let scheduler_repo = config.scheduler_repo();
if let Err(e) = system_update_scheduler(scheduler_repo).await {
log::error!("{:?}", e);
}
}
|
extern crate rustc_serialize;
use self::rustc_serialize::hex::FromHex;
use self::rustc_serialize::base64::{ToBase64, STANDARD, Config};
#[allow(dead_code)] // debugging
pub fn pretty_print(string: Vec<u8>) -> String {
match String::from_utf8(string) {
Ok(v) => { v }
Err(_) => { "UNPRINTABLE".to_string() }
}
}
pub fn hex_to_byte_string(hex: &str) -> Vec<u8> {
match hex.from_hex() {
Ok(v) => { v }
Err(e) => { panic!("Can't parse hex: {:?}, error: {:?}", hex, e) }
}
}
#[test]
fn test_hex_to_byte_string() {
assert!(hex_to_byte_string("666f6f20626172") == "foo bar".to_string().into_bytes());
}
pub fn byte_string_to_base64(bytes: Vec<u8>) -> String {
let config = Config {
char_set: STANDARD.char_set,
newline: STANDARD.newline,
pad: false,
line_length: STANDARD.line_length,
};
bytes.to_base64(config)
}
#[test]
fn test_byte_string_to_base64() {
let input = "foo bar".
to_string().into_bytes();
let output = "Zm9vIGJhcg".to_string();
assert!(byte_string_to_base64(input) == output);
}
pub fn xor_byte_strings(string_a: Vec<u8>, string_b: Vec<u8>) -> Vec<u8> {
let mut string_c : Vec<u8> = vec![];
for idx in 0..string_a.len() {
string_c.push(string_a[idx] ^ string_b[idx]);
}
string_c
}
|
use std::fmt::Write;
use crate::{
custom_client::OsekaiUserEntry,
embeds::Footer,
util::{constants::OSU_BASE, numbers::round, CowUtils},
};
pub struct MedalCountEmbed {
description: String,
footer: Footer,
title: &'static str,
url: &'static str,
}
impl MedalCountEmbed {
pub fn new(
ranking: &[OsekaiUserEntry],
index: usize,
author_idx: Option<usize>,
pages: (usize, usize),
) -> Self {
let mut description = String::with_capacity(1024);
for (i, entry) in ranking.iter().enumerate() {
let idx = index + i;
let medal_name = entry.rarest_medal.as_str();
let tmp = medal_name.cow_replace(' ', "+");
let url_name = tmp.cow_replace(',', "%2C");
let _ = writeln!(
description,
"**{idx}.** :flag_{country}: [{author}**{user}**{author}]({base}u/{user_id}): \
`{count}` (`{percent}%`) ▸ [{medal}](https://osekai.net/medals/?medal={url_name})",
idx = idx + 1,
country = entry.country_code.to_ascii_lowercase(),
author = if author_idx == Some(idx) { "__" } else { "" },
user = entry.username,
base = OSU_BASE,
user_id = entry.user_id,
count = entry.medal_count,
percent = round(entry.completion),
medal = entry.rarest_medal,
url_name = url_name,
);
}
let title = "User Ranking based on amount of owned medals";
let url = "https://osekai.net/rankings/?ranking=Medals&type=Users";
let mut footer_text = format!("Page {}/{} • ", pages.0, pages.1);
if let Some(idx) = author_idx {
let _ = write!(footer_text, "Your position: {} • ", idx + 1);
}
footer_text.push_str("Check out osekai.net for more info");
Self {
description,
footer: Footer::new(footer_text),
title,
url,
}
}
}
impl_builder!(MedalCountEmbed {
description,
footer,
title,
url,
});
|
// Any code not in main() is moved here
use std::error::Error;
use std::fs;
/* Using a struct helps to convey meaning that the two values are related
it also makes it easier for others to read the code later
case sensitivity is trigger by T/F - run() will need to check for this */
pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool,
}
impl Config {
// creating a method via impl against Config is more idiomatic as we are returning Config struct
pub fn new(
query: String,
filename: String,
case_sensitive: bool,
) -> Result<Config, &'static str> {
// returns an Ok() variant if not an error
Ok(Config {
query,
filename,
case_sensitive,
})
}
}
// declaring run() to separate logic away from main() - returns a Result with a trait object Box<dyn Error> for error type
// requires std::error::Error be imported - the error here will return a dynamic type that implements Error trait
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
// small change that extracts this code from main()
let mut count = 0;
let contents = fs::read_to_string(config.filename)?;
// check the value of case_sensitive to determine correct search function
let results = if config.case_sensitive {
search(&config.query, &contents)
} else {
search_case_insensitive(&config.query, &contents)
};
for line in results {
// this will print each line returned from the search function - for loop returns each line from search
count += 1;
println!("{}", line)
}
println!(
"\nThere are {} lines containing the word '{}'.",
count, &config.query
);
/*this syntax is the idiomatic way to call run for side effects only
it does not return a value that is needed*/
Ok(())
}
// first iteration of this function will cause the test for 'one_result' to fail
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
// uses the filter adaptor to only keep the lines that match the filter criteria
// the result is then collected into a new vector via collect() and returned
contents
.lines()
.filter(|line| line.contains(query))
.collect()
}
pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
contents
.lines()
.filter(|line| line.to_lowercase().contains(&query.to_lowercase()))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
/* This test searches for the string 'duct'. The test to be searched
contains three lines with one containing the string 'duct'.
Assertion states that the value returned contains only the line we expect.*/
let query = "duct";
let contents = "\
Rust:\n\
safe, fast, productive.\n\
Pick three.\
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
/* This test searches for the string 'duct'. The test to be searched
contains three lines with one containing the string 'duct'.
Assertion states that the value returned contains only the line we expect.*/
let query = "rUst";
let contents = "\
Rust:\n\
safe, fast, productive.\n\
Pick three.\n\
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}
// test 1: cargo run to poem.txt
// test 2: set CASE_SENSITIVE env variable to 1
// $env:CASE_SENSITIVE=1/export CASE_SENSITIVE=1
// cargo run to poem.txt/ CASE_INSENSITIVE=1 cargo run to poem.txt
// EXTRA: allow command line arguments to work as well
|
#![allow(unused_imports)]
pub use flatbuffers;
include!(concat!(env!("OUT_DIR"), "/mod.rs")); |
use std::sync::Arc;
use datafusion::{
arrow::util::pretty::pretty_format_batches,
datasource::TableProvider,
prelude::{ExecutionConfig, ExecutionContext},
};
fn make_ctx() -> ExecutionContext {
// hardcode 1 thread to avoid consuming all CPUs on system which
// both overheats my laptop causing power throttling as well as
// makes the results more subject to other workloads on the
// machine.
let config = ExecutionConfig::new().with_target_partitions(1);
ExecutionContext::with_config(config)
}
pub async fn run_query(csvdata: Arc<dyn TableProvider>, query: &str) {
let mut ctx = make_ctx();
ctx.register_table("t", csvdata).unwrap();
let results = ctx.sql(query).await.unwrap().collect().await.unwrap();
let pretty = pretty_format_batches(&results).unwrap();
println!("{}\n{}", query, pretty);
}
pub async fn run_query_silently(csvdata: Arc<dyn TableProvider>, query: &str) {
let mut ctx = make_ctx();
ctx.register_table("t", csvdata).unwrap();
ctx.sql(query).await.unwrap().collect().await.unwrap();
}
|
extern crate ares;
#[macro_use]
mod util;
#[test]
fn test_and() {
eval_ok!("(and)", true);
eval_ok!("(and true)", true);
eval_ok!("(and false)", false);
eval_ok!("(and true false)", false);
eval_ok!("(and true true)", true);
eval_ok!("(and true true false)", false);
}
#[test]
fn test_or() {
eval_ok!("(or)", false);
eval_ok!("(or true)", true);
eval_ok!("(or false true)", true);
eval_ok!("(or true false)", true);
eval_ok!("(or false false)", false);
eval_ok!("(or false)", false);
}
#[test]
fn test_xor() {
eval_ok!("(xor)", false);
eval_ok!("(xor true)", false);
eval_ok!("(xor false)", false);
eval_ok!("(xor true false)", true);
eval_ok!("(xor true true false)", true);
eval_ok!("(xor true false false)", true);
}
#[test]
fn test_shortcircuit() {
eval_ok!(
"(define x true)
(define setter (lambda () (set! x false)))
(and false (setter))
x", true);
eval_ok!(
"(define x true)
(define setter (lambda () (set! x false)))
(or true (setter))
x", true);
eval_ok!(
"(define x true)
(define setter (lambda () (set! x false)))
(xor true false (setter))
x", true);
}
|
extern crate rsmath as r;
#[cfg(test)]
mod tests {
use r::algebra::matrix::*;
use r::algebra::vector::*;
// --------------- Matrix TEST ----------------------------------------
#[test]
fn matrix_init_test() {
let values: Vec<Vec<i32>> = vec![vec![1, 2], vec![3, 4]];
let m = Matrix::<i32>::init(&values);
assert_eq!(m.get_element(0, 0), values[0][0]);
assert_eq!(m.get_element(1, 0), values[1][0]);
assert_eq!(m.get_element(0, 1), values[0][1]);
assert_eq!(m.get_element(1, 1), values[1][1]);
assert_eq!(m.nrows(), values.len());
assert_eq!(m.ncols(), values[0].len());
}
#[test]
fn matrix_random_test() {
let range: [f64; 2] = [0.0, 10.0];
let m = Matrix::<f64>::random(2, 3, &range);
assert_eq!(m.nrows(), 2);
assert_eq!(m.ncols(), 3);
}
#[test]
fn matrix_create_identity_test() {
let m = Matrix::<f64>::create_identity(3);
assert_eq!(m.get_element(0, 0), 1.0);
assert_eq!(m.get_element(0, 1), 0.0);
assert_eq!(m.get_element(0, 2), 0.0);
assert_eq!(m.get_element(1, 0), 0.0);
assert_eq!(m.get_element(1, 1), 1.0);
assert_eq!(m.get_element(1, 2), 0.0);
assert_eq!(m.get_element(2, 0), 0.0);
assert_eq!(m.get_element(2, 1), 0.0);
assert_eq!(m.get_element(2, 2), 1.0);
}
#[test]
fn matrix_rows_test() {
let m = Matrix::<u32>::init_with_capacity(5, 10);
assert_eq!(m.nrows(), 5);
}
#[test]
fn matrix_cols_test() {
let m = Matrix::<u32>::init_with_capacity(5, 10);
assert_eq!(m.ncols(), 10);
}
#[test]
fn matrix_set_row_test() {
let v: Vec<i32> = vec![-1, 2];
let mut m = Matrix::<i32>::init(&vec![vec![1, 3], vec![2, 5], vec![3, 6]]);
m.set_row(0, &v);
assert_eq!(m.row(0).unwrap().clone(), v);
}
#[test]
fn matrix_get_push_row_test() {
let val: Vec<u32> = vec![1, 2, 3, 4, 5];
let mut m = Matrix::<u32>::init_with_capacity(5, 2);
m.push_row(val.clone());
let result = m.row(0);
let mut get_val: Vec<u32> = Vec::new();
match result {
Some(x) => get_val = x.clone(),
None => assert_eq!(true, false),
}
assert_eq!(get_val.len(), val.len());
}
#[test]
fn matrix_pop_row_test() {
let val: Vec<u32> = vec![1, 2, 3, 4, 5];
let mut m = Matrix::<u32>::new();
for _ in 0..2 {
m.push_row(val.clone());
}
m.pop_row(0);
assert_eq!(1, m.nrows());
}
#[test]
fn matrix_swap_row_test() {
let val: Vec<u32> = vec![1, 2, 3, 4, 5];
let val2: Vec<u32> = vec![6, 7, 8, 9, 10];
let mut m = Matrix::<u32>::new();
m.push_row(val.clone());
m.push_row(val2.clone());
m.swap_row(0, 1);
assert_eq!(val[0], m.get_element(1, 0));
assert_eq!(val2[0], m.get_element(0, 0));
}
#[test]
fn matrix_swap_col_test() {
let val: Vec<u32> = vec![1, 2, 3, 4, 5];
let val2: Vec<u32> = vec![6, 7, 8, 9, 10];
let mut m = Matrix::<u32>::new();
m.push_row(val.clone());
m.push_row(val2.clone());
m.swap_col(0, 1);
assert_eq!(val[1], m.get_element(0, 0));
assert_eq!(val[0], m.get_element(0, 1));
}
#[test]
fn matrix_col_test() {
let resp: Vec<u32> = vec![1];
let row: Vec<u32> = vec![1, 2, 3, 4, 5];
let mut m = Matrix::<u32>::init_with_capacity(1, 5);
m.push_row(row.clone());
let result = m.col(0);
let mut get_val: Vec<u32> = Vec::new();
match result {
Some(x) => get_val = x.clone(),
None => assert_eq!(true, false),
}
assert_eq!(get_val.len(), resp.len());
assert_eq!(get_val[0], resp[0]);
}
#[test]
fn matrix_set_col_test() {
let v: Vec<i32> = vec![-1, 2, 4];
let mut m = Matrix::<i32>::init(&vec![vec![1, 3], vec![2, 5], vec![3, 6]]);
m.set_col(0, &v);
assert_eq!(m.col(0).unwrap().clone(), v);
}
#[test]
fn matrix_push_col_test() {
let mut val: Vec<u32> = vec![1, 2, 3, 4, 5];
let mut m = Matrix::<u32>::new();
for _ in 0..2 {
m.push_row(val.clone());
}
assert_eq!(m.ncols(), val.len());
val = vec![6, 7];
m.push_col(val.clone());
assert_eq!(m.ncols(), 6);
}
#[test]
fn matrix_pop_col_test() {
let val: Vec<u32> = vec![1, 2, 3, 4, 5];
let mut resp: Vec<u32> = val.clone();
resp.remove(0);
let mut m = Matrix::<u32>::new();
m.push_row(val.clone());
m.pop_col(0);
assert_eq!(4, m.ncols());
assert_eq!(resp[0], m.get_element(0, 0));
assert_eq!(resp[1], m.get_element(0, 1));
assert_eq!(resp[2], m.get_element(0, 2));
assert_eq!(resp[3], m.get_element(0, 3));
}
#[test]
fn matrix_get_element_test() {
let row: Vec<u32> = vec![1, 2, 3, 4, 5];
let mut m = Matrix::<u32>::init_with_capacity(1, 5);
m.push_row(row);
assert_eq!(m.get_element(0, 0), 1);
assert_eq!(m.get_element(0, 1), 2);
assert_eq!(m.get_element(0, 2), 3);
assert_eq!(m.get_element(0, 3), 4);
assert_eq!(m.get_element(0, 4), 5);
}
#[test]
fn matrix_contains_test() {
let row: Vec<f32> = vec![0.2, 2.5, 10.2, 8.7, 5.0];
let mut m = Matrix::<f32>::new();
m.push_row(row);
let mut result = m.contains(&0.2);
match result {
Some(x) => assert_eq!(x, 0),
None => assert_eq!(true, false),
}
result = m.contains(&0.7);
match result {
Some(_) => assert_eq!(true, false),
None => assert_eq!(true, true),
}
}
#[test]
fn matrix_contains_row_test() {
let row: Vec<i32> = vec![-1, 0, -2, 2, 3];
let row2: Vec<i32> = vec![0, 0, -2, 2, 2];
let mut m = Matrix::<i32>::new();
m.push_row(row.clone());
let mut result = m.contains_row(&row);
match result {
Some(x) => assert_eq!(x, 0),
None => assert_eq!(true, false),
}
result = m.contains_row(&row2);
match result {
Some(_) => assert_eq!(true, false),
None => assert_eq!(true, true),
}
}
#[test]
fn matrix_contains_col_test() {
let row: Vec<i32> = vec![-1, 0, -2, 2, 3];
let row2: Vec<i32> = vec![0, 0, -2, 2, 2];
let mut m = Matrix::<i32>::new();
m.push_row(row.clone());
m.push_row(row2.clone());
let col: Vec<i32> = vec![row[0], row2[0]];
let col2: Vec<i32> = vec![2, 3];
let mut result = m.contains_col(&col);
match result {
Some(x) => assert_eq!(x, 0),
None => assert_eq!(true, false),
}
result = m.contains_row(&col2);
match result {
Some(_) => assert_eq!(true, false),
None => assert_eq!(true, true),
}
}
#[test]
fn matrix_equal_to_test() {
let row: Vec<i32> = vec![1, 3, 2, 3];
let mut m = Matrix::<i32>::new();
m.push_row(row);
let eq = m.equal_to(&3);
assert_eq!(eq.get_element(0, 0), false);
assert_eq!(eq.get_element(0, 1), true);
assert_eq!(eq.get_element(0, 2), false);
assert_eq!(eq.get_element(0, 3), true);
}
#[test]
fn matrix_equal_to_matrix_test() {
let row: Vec<f32> = vec![1.0, 3.0, 2.0, 3.0];
let mut m = Matrix::<f32>::new();
m.push_row(row);
let row2: Vec<f32> = vec![1.0, 0.5, 0.2, 3.0];
let mut m2 = Matrix::<f32>::new();
m2.push_row(row2);
let eq_matrix = m.equal_to_matrix(&m2);
assert_eq!(eq_matrix.get_element(0, 0), true);
assert_eq!(eq_matrix.get_element(0, 1), false);
assert_eq!(eq_matrix.get_element(0, 2), false);
assert_eq!(eq_matrix.get_element(0, 3), true);
}
#[test]
fn matrix_bigger_than_test() {
let row: Vec<f32> = vec![0.1, 0.5, 0.8, 1.2];
let mut m = Matrix::<f32>::new();
m.push_row(row);
let bigger = m.bigger_than(&0.9);
assert_eq!(bigger.get_element(0, 0), false);
assert_eq!(bigger.get_element(0, 1), false);
assert_eq!(bigger.get_element(0, 2), false);
assert_eq!(bigger.get_element(0, 3), true);
}
#[test]
fn matrix_bigger_than_matrix_test() {
let row: Vec<u32> = vec![1, 3, 2, 3];
let mut m = Matrix::<u32>::new();
m.push_row(row);
let row2: Vec<u32> = vec![2, 0, 6, 3];
let mut m2 = Matrix::<u32>::new();
m2.push_row(row2);
let eq_matrix = m.bigger_than_matrix(&m2);
assert_eq!(eq_matrix.get_element(0, 0), false);
assert_eq!(eq_matrix.get_element(0, 1), true);
assert_eq!(eq_matrix.get_element(0, 2), false);
assert_eq!(eq_matrix.get_element(0, 3), false);
}
#[test]
fn matrix_eq_trait_test() {
let row: Vec<u32> = vec![1, 3, 2, 3];
let mut m = Matrix::<u32>::new();
m.push_row(row);
let m2 = m.clone();
let row3: Vec<u32> = vec![1, 2, 3, 4];
let mut m3 = Matrix::<u32>::new();
m3.push_row(row3);
assert_eq!(m == m2, true);
assert_eq!(m == m3, false);
}
#[test]
fn matrix_add_trait_test(){
let row: Vec<u32> = vec![1, 3, 2, 3];
let mut m = Matrix::<u32>::new();
m.push_row(row);
let m2: Matrix<u32> = m.clone();
let res = &m + &m2;
assert_eq!(res.get_element(0, 0), 2);
assert_eq!(res.get_element(0, 1), 6);
assert_eq!(res.get_element(0, 2), 4);
assert_eq!(res.get_element(0, 3), 6);
assert_eq!(res.ncols(), m.ncols());
assert_eq!(res.nrows(), m2.nrows());
}
#[test]
fn matrix_sub_trait_test(){
let row: Vec<u32> = vec![5, 6, 7, 8];
let mut m = Matrix::<u32>::new();
m.push_row(row);
let row2: Vec<u32> = vec![1, 2, 3, 3];
let mut m2 = Matrix::<u32>::new();
m2.push_row(row2);
let res = &m - &m2;
assert_eq!(res.get_element(0, 0), 4);
assert_eq!(res.get_element(0, 1), 4);
assert_eq!(res.get_element(0, 2), 4);
assert_eq!(res.get_element(0, 3), 5);
assert_eq!(res.ncols(), m.ncols());
assert_eq!(res.nrows(), m.nrows());
}
#[test]
fn matrix_transpose_test(){
let mut row: Vec<i32> = vec![1, 2, 3];
let mut m = Matrix::<i32>::new();
m.push_row(row);
row = vec![5, 7, 8];
m.push_row(row);
let save = m.clone();
m.transpose();
assert_eq!(save.ncols(), m.nrows());
assert_eq!(save.nrows(), m.ncols());
assert_eq!(save.get_element(0, 0), m.get_element(0, 0));
assert_eq!(save.get_element(0, 1), m.get_element(1, 0));
assert_eq!(save.get_element(0, 2), m.get_element(2, 0));
}
#[test]
fn matrix_scalar_mul_test() {
let values: Vec<Vec<i32>> = vec![vec![1, 2, 3], vec![4, 5, 6]];
let m = Matrix::<i32>::init(&values);
let pr = m.scalar_mul(2);
assert_eq!(pr.get_element(0, 0), 2);
assert_eq!(pr.get_element(0, 1), 4);
assert_eq!(pr.get_element(0, 2), 6);
assert_eq!(pr.get_element(1, 0), 8);
assert_eq!(pr.get_element(1, 1), 10);
assert_eq!(pr.get_element(1, 2), 12);
}
#[test]
fn matrix_mul_trait_test(){
let mut values: Vec<Vec<i32>> = vec![vec![1, 4], vec![2, 5], vec![3, 6]];
let m = Matrix::<i32>::init(&values);
values = vec![vec![7, 8, 9], vec![10, 11, 12]];
let m2 = Matrix::<i32>::init(&values);
let prod = &m * &m2;
assert_eq!(prod.ncols(), m.nrows());
assert_eq!(prod.nrows(), m2.ncols());
}
#[test]
fn matrix_get_diagonal_test() {
let values: Vec<Vec<i64>> = vec![vec![1, -2, 2], vec![4, -5, 6], vec![2, 1, -2]];
let m = Matrix::<i64>::init(&values);
let d: Matrix<i64> = m.get_diagonal();
assert_eq!(d.ncols(), m.ncols());
assert_eq!(d.nrows(), m.nrows());
assert_eq!(d.get_element(0, 0), m.get_element(0, 0));
assert_eq!(d.get_element(0, 1), 0);
assert_eq!(d.get_element(0, 2), 0);
assert_eq!(d.get_element(1, 1), m.get_element(1, 1));
assert_eq!(d.get_element(1, 0), 0);
assert_eq!(d.get_element(1, 2), 0);
assert_eq!(d.get_element(2, 2), m.get_element(2, 2));
assert_eq!(d.get_element(2, 0), 0);
assert_eq!(d.get_element(2, 1), 0);
}
#[test]
fn matrix_submatrix_test() {
let values: Vec<Vec<f32>> = vec![vec![1.0, 4.0], vec![2.0, 5.0], vec![3.0, 6.0]];
let m = Matrix::<f32>::init(&values);
let range_row: [usize; 2] = [1, 2];
let range_col: [usize; 2] = [0, 0];
let s = m.submatrix(&range_row, &range_col);
assert_eq!(s.ncols(), (range_col[1] + 1) - range_col[0]);
assert_eq!(s.nrows(), (range_row[1] + 1) - range_row[0]);
}
#[test]
fn matrix_eucl_distance_col_test() {
let m = Matrix::<i32>::init(&vec![vec![1, 3], vec![2, 5], vec![3, 6]]);
let d = m.eucl_distance_row();
assert_eq!(d.ncols(), m.nrows());
assert_eq!(d.nrows(), m.nrows());
}
#[test]
fn matrix_row_iter_at_test() {
let m = Matrix::<i32>::init(&vec![vec![1, 3], vec![2, 5], vec![3, 6]]);
let mut i = m.row_iter_at(1);
assert_eq!(i.next().unwrap(), &vec![2, 5]);
assert_eq!(i.next().unwrap(), &vec![3, 6]);
}
#[test]
fn matrix_row_iter_test() {
let m = Matrix::<i32>::init(&vec![vec![1, 3], vec![2, 5], vec![3, 6]]);
let mut i = m.row_iter();
assert_eq!(i.next().unwrap(), &vec![1, 3]);
assert_eq!(i.next().unwrap(), &vec![2, 5]);
assert_eq!(i.next().unwrap(), &vec![3, 6]);
}
#[test]
fn matrix_col_iter_at_test() {
let m = Matrix::<i32>::init(&vec![vec![1, 3], vec![2, 5], vec![3, 6]]);
let mut i = m.col_iter_at(1);
assert_eq!(i.next().unwrap(), vec![3, 5, 6]);
}
#[test]
fn matrix_col_iter_test() {
let m = Matrix::<i32>::init(&vec![vec![1, 3], vec![2, 5], vec![3, 6]]);
let mut i = m.col_iter();
assert_eq!(i.next().unwrap(), vec![1, 2, 3]);
assert_eq!(i.next().unwrap(), vec![3, 5, 6]);
}
#[test]
fn matrix_el_iter_at_test() {
let m = Matrix::<i32>::init(&vec![vec![1, 3], vec![2, 5], vec![3, 6]]);
let mut i = m.el_iter_at(1);
assert_eq!(i.next().unwrap(), 3);
assert_eq!(i.next().unwrap(), 2);
assert_eq!(i.next().unwrap(), 5);
assert_eq!(i.next().unwrap(), 3);
assert_eq!(i.next().unwrap(), 6);
}
#[test]
fn matrix_el_iter_test() {
let m = Matrix::<i32>::init(&vec![vec![8, 3], vec![5, 10]]);
let mut i = m.el_iter();
assert_eq!(i.next().unwrap(), m.get_element(0, 0));
assert_eq!(i.next().unwrap(), m.get_element(0, 1));
assert_eq!(i.next().unwrap(), m.get_element(1, 0));
assert_eq!(i.next().unwrap(), m.get_element(1, 1));
}
// --------------- Vector TEST ----------------------------------------
#[test]
fn vector_init_test() {
let v = Vector::<f64>::init(&vec![2.5f64, -2.1f64, 5.3f64]);
assert_eq!(v.size(), 3);
assert_eq!(v.el(0), 2.5f64);
assert_eq!(v.el(1), -2.1f64);
assert_eq!(v.el(2), 5.3f64);
}
#[test]
fn vector_zeros_test() {
let v = Vector::<i32>::zeros(2);
assert_eq!(v.size(), 2);
assert_eq!(v.el(0), 0);
assert_eq!(v.el(1), 0);
}
#[test]
fn vector_ones_test() {
let v = Vector::<u32>::ones(2);
assert_eq!(v.size(), 2);
assert_eq!(v.el(0), 1);
assert_eq!(v.el(1), 1);
}
#[test]
fn vector_random_test() {
let v = Vector::<i32>::random(5, &[-1i32, 2i32]);
assert_eq!(v.size(), 5);
assert_eq!(v.el(0) >= -1i32 && v.el(0) <= 2i32, true);
assert_eq!(v.el(1) >= -1i32 && v.el(1) <= 2i32, true);
assert_eq!(v.el(2) >= -1i32 && v.el(2) <= 2i32, true);
assert_eq!(v.el(3) >= -1i32 && v.el(3) <= 2i32, true);
assert_eq!(v.el(4) >= -1i32 && v.el(4) <= 2i32, true);
}
#[test]
fn vector_push_test() {
let mut v = Vector::<f32>::new();
v.push(1f32);
assert_eq!(v.size(), 1);
assert_eq!(v.el(0), 1f32);
}
#[test]
fn vector_remove_test() {
let mut v = Vector::<f32>::init(&vec![2.0, 3.1, 2.1]);
v.remove(1);
assert_eq!(v.size(), 2);
assert_eq!(v.el(0), 2.0);
assert_eq!(v.el(1), 2.1);
}
#[test]
fn vector_pop_test() {
let mut v = Vector::<f64>::init(&vec![2.0, 3.1, 2.1]);
v.pop();
assert_eq!(v.size(), 2);
assert_eq!(v.el(0), 2.0);
assert_eq!(v.el(1), 3.1);
}
#[test]
fn vector_swap_test() {
let mut v = Vector::<i64>::init(&vec![2, -1, 1]);
v.swap(0, 1);
assert_eq!(v.size(), 3);
assert_eq!(v.el(0), -1);
assert_eq!(v.el(1), 2);
assert_eq!(v.el(2), 1);
}
#[test]
fn vector_append_test() {
let mut v1 = Vector::<i64>::init(&vec![2, -1, 1]);
let v2 = Vector::<i64>::init(&vec![5, -7, 10]);
v1.append(&v2);
assert_eq!(v1.size(), 6);
assert_eq!(v2.size(), 3);
}
#[test]
fn vector_clear_test() {
let mut v = Vector::<f32>::init(&vec![2.0, 3.1, 2.1]);
v.clear();
assert_eq!(v.size(), 0);
}
#[test]
fn vector_sort_min_test() {
let mut v = Vector::<i64>::init(&vec![2, -1, 1]);
v.sort_min();
assert_eq!(v.el(0), -1);
assert_eq!(v.el(1), 1);
assert_eq!(v.el(2), 2);
}
#[test]
fn vector_sort_max_test() {
let mut v = Vector::<i64>::init(&vec![2, -1, 1]);
v.sort_max();
assert_eq!(v.el(0), 2);
assert_eq!(v.el(1), 1);
}
#[test]
fn vector_set_el_test() {
let mut v = Vector::<i64>::init(&vec![2, -1, 1]);
v.set_el(2, 5i64);
assert_eq!(v.el(2), 5i64);
}
#[test]
fn vector_max_test() {
let v = Vector::<i64>::init(&vec![2, -1, 1]);
let (max, idx_max) = v.max();
assert_eq!(max, 2i64);
assert_eq!(idx_max, 0usize);
}
#[test]
fn vector_min_test() {
let v = Vector::<i64>::init(&vec![2, -1, 1]);
let (min, idx_min) = v.min();
assert_eq!(min, -1i64);
assert_eq!(idx_min, 1usize);
}
#[test]
fn vector_median_test() {
let v = Vector::<i64>::init(&vec![2, 4, 0, 6]);
let median = v.median();
assert_eq!(median, 3f64);
}
}
|
macro_rules! gost94_impl {
($state:ident, $sbox:expr) => {
use $crate::gost94::{Gost94, SBox, Block};
use generic_array::typenum::U32;
use digest;
use generic_array::GenericArray;
#[derive(Clone, Copy)]
pub struct $state {
sh: Gost94
}
impl $state {
pub fn new() -> Self {
$state{sh: Gost94::new($sbox, Block::default())}
}
}
impl Default for $state {
fn default() -> Self {
Self::new()
}
}
impl digest::Input for $state {
type BlockSize = U32;
fn digest(&mut self, input: &[u8]) {
self.sh.digest(input);
}
}
impl digest::FixedOutput for $state {
type OutputSize = U32;
fn fixed_result(self) -> GenericArray<u8, Self::OutputSize> {
self.sh.fixed_result()
}
}
}}
|
extern crate clap;
extern crate config;
extern crate tinytemplate;
mod cli;
use std::error::Error;
#[tokio::main]
pub async fn main() -> Result<(), Box<dyn Error>> {
cli::execute().await
}
|
/// This enum defines the currently displayed modal.
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum MyModal {
/// Quit modal.
Quit,
/// Clear all modal.
ClearAll,
/// Connection details modal.
ConnectionDetails(usize),
}
|
use hyper::Method;
use lib::models::*;
use stq_static_resources::Currency;
use stq_types::*;
use stq_http::client::{self, ClientHandle as HttpClientHandle};
static MOCK_COMPANIES_PACKAGES_ENDPOINT: &'static str = "companies_packages";
fn create_companies_packages(
company_id: CompanyId,
package_id: PackageId,
shipping_rate_source: ShippingRateSource,
core: &mut tokio_core::reactor::Core,
http_client: &HttpClientHandle,
base_url: String,
user_id: Option<UserId>,
) -> Result<CompanyPackage, client::Error> {
let new_companies_packages = NewCompanyPackage {
company_id,
package_id,
shipping_rate_source: Some(shipping_rate_source),
};
let body: String = serde_json::to_string(&new_companies_packages).unwrap().to_string();
let create_result = core.run(http_client.request_with_auth_header::<CompanyPackage>(
Method::Post,
get_url_request(base_url),
Some(body),
user_id.map(|u| u.to_string()),
));
create_result
}
fn get_url_request_by_id(base_url: String, companies_packages_id: &CompanyPackageId) -> String {
format!("{}/{}/{}", base_url, MOCK_COMPANIES_PACKAGES_ENDPOINT, companies_packages_id)
}
fn get_url_request_by_company_id(base_url: String, company_id: &CompanyId) -> String {
format!("{}/companies/{}/packages", base_url, company_id)
}
fn get_url_request_by_package_id(base_url: String, package_id: &PackageId) -> String {
format!("{}/packages/{}/companies", base_url, package_id)
}
fn get_url_request(base_url: String) -> String {
format!("{}/{}", base_url, MOCK_COMPANIES_PACKAGES_ENDPOINT)
}
fn get_url_request_available_packages(base_url: String, country: Alpha3, size: u32, weight: u32) -> String {
format!(
"{}/available_packages?country={}&size={}&weight={}",
base_url, country.0, size, weight
)
}
fn create_company(name: String) -> NewCompany {
NewCompany {
name,
label: "UPS".to_string(),
description: None,
deliveries_from: vec![Alpha3("RUS".to_string())],
logo: "".to_string(),
currency: Currency::STQ,
}
}
fn create_package(name: String) -> NewPackages {
NewPackages {
name,
max_size: 0,
min_size: 0,
max_weight: 0,
min_weight: 0,
deliveries_to: vec![Alpha3("USA".to_string()), Alpha3("CHN".to_string())],
}
}
#[test]
fn test_companies_packages() {
let (mut core, http_client) = super::common::make_utils();
let base_url = super::common::setup();
test_companies_packages_superuser_crud(&mut core, &http_client, base_url.clone());
test_companies_packages_regular_user_crud(&mut core, &http_client, base_url.clone());
test_companies_packages_unauthorized(&mut core, &http_client, base_url.clone());
}
// test companies_packages by superuser
fn test_companies_packages_superuser_crud(core: &mut tokio_core::reactor::Core, http_client: &HttpClientHandle, base_url: String) {
let user_id = UserId(1);
let package_name = "Avia".to_string();
let company_name = "US UPS".to_string();
let payload = (
create_company(company_name),
create_package(package_name),
ShippingRateSource::NotAvailable,
);
let (package_id, company_id, companies_package_id) =
super::common::create_delivery_objects(payload, core, http_client, base_url.clone(), Some(user_id));
// read search
println!(
"user: {:?} - run search companies_packages by id {:?}",
user_id, companies_package_id
);
let read_result = core.run(http_client.request_with_auth_header::<CompanyPackage>(
Method::Get,
get_url_request_by_id(base_url.clone(), &companies_package_id),
None,
Some(user_id.to_string()),
));
println!(
"user: {:?} - find companies_packages {:?} by id {}",
user_id, read_result, companies_package_id
);
assert!(read_result.is_ok());
// read companies
println!("user: {:?} - run search companies by package id {:?}", user_id, package_id);
let read_result = core.run(http_client.request_with_auth_header::<Vec<Company>>(
Method::Get,
get_url_request_by_package_id(base_url.clone(), &package_id),
None,
Some(user_id.to_string()),
));
println!(
"user: {:?} - find companies by package id {:?} by id {:?}",
user_id, read_result, package_id
);
assert!(read_result.is_ok());
// read packages
println!("user: {:?} - run search packages by company id {:?}", user_id, company_id);
let read_result = core.run(http_client.request_with_auth_header::<Vec<Packages>>(
Method::Get,
get_url_request_by_company_id(base_url.clone(), &company_id),
None,
Some(user_id.to_string()),
));
println!(
"user: {:?} - find packages by company id {:?} by id {:?}",
user_id, read_result, company_id
);
assert!(read_result.is_ok());
// read available packages
let country_search = Alpha3("RUS".to_string());
println!(
"user: {:?} - run search available packages by country {:?}",
user_id, country_search
);
let read_result = core.run(http_client.request_with_auth_header::<Vec<AvailablePackages>>(
Method::Get,
get_url_request_available_packages(base_url.clone(), country_search, 0, 0),
None,
Some(user_id.to_string()),
));
println!("user: {:?} - find available packages {:#?}", user_id, read_result);
assert!(read_result.is_ok());
super::common::delete_deliveries_objects(
(package_id, company_id, companies_package_id),
core,
http_client,
base_url.clone(),
user_id,
);
}
// test companies_packages by regular user
fn test_companies_packages_regular_user_crud(core: &mut tokio_core::reactor::Core, http_client: &HttpClientHandle, base_url: String) {
let package_name = "Avia".to_string();
let company_name = "US UPS".to_string();
let super_user_id = UserId(1);
let payload = (
create_company(company_name),
create_package(package_name),
ShippingRateSource::NotAvailable,
);
let (package_id, company_id, companies_package_id) =
super::common::create_delivery_objects(payload, core, http_client, base_url.clone(), Some(super_user_id.clone()));
// create user for test acl
let user_id = UserId(1123);
let create_role_result = super::common::create_user_role(user_id.clone(), core, &http_client, base_url.clone());
assert!(create_role_result.is_ok());
// create
println!("run create new companies_packages");
let create_result = create_companies_packages(
company_id.clone(),
package_id.clone(),
ShippingRateSource::NotAvailable,
core,
&http_client,
base_url.clone(),
Some(user_id),
);
assert!(create_result.is_err());
// read search
println!("run search companies_packages by id");
let read_result = core.run(http_client.request_with_auth_header::<CompanyPackage>(
Method::Get,
get_url_request_by_id(base_url.clone(), &companies_package_id),
None,
Some(user_id.to_string()),
));
assert!(read_result.is_ok());
// read companies
println!("run search companies by package id");
let read_result = core.run(http_client.request_with_auth_header::<Vec<Company>>(
Method::Get,
get_url_request_by_package_id(base_url.clone(), &package_id),
None,
Some(user_id.to_string()),
));
println!("companies by package id {:?}", read_result);
assert!(read_result.is_ok());
// read packages
println!("run search packages by company id");
let read_result = core.run(http_client.request_with_auth_header::<Vec<Packages>>(
Method::Get,
get_url_request_by_company_id(base_url.clone(), &company_id),
None,
Some(user_id.to_string()),
));
println!("packages by company id {:?}", read_result);
assert!(read_result.is_ok());
// read available packages
let country_search = Alpha3("RUS".to_string());
println!(
"user: {:?} - run search available packages by country {:?}",
user_id, country_search
);
let read_result = core.run(http_client.request_with_auth_header::<Vec<AvailablePackages>>(
Method::Get,
get_url_request_available_packages(base_url.clone(), country_search, 0, 0),
None,
Some(user_id.to_string()),
));
println!("user: {:?} - find available packages {:#?}", user_id, read_result);
assert!(read_result.is_ok());
// delete
println!("run delete companies_packages ");
let delete_result = core.run(http_client.request_with_auth_header::<CompanyPackage>(
Method::Delete,
get_url_request_by_id(base_url.clone(), &companies_package_id),
None,
Some(user_id.to_string()),
));
assert!(delete_result.is_err());
super::common::delete_deliveries_objects(
(package_id, company_id, companies_package_id),
core,
http_client,
base_url.clone(),
super_user_id,
);
}
// test update companies_packages without authorization data
fn test_companies_packages_unauthorized(core: &mut tokio_core::reactor::Core, http_client: &HttpClientHandle, base_url: String) {
let package_name = "Avia".to_string();
let company_name = "US UPS".to_string();
let super_user_id = UserId(1);
let payload = (
create_company(company_name),
create_package(package_name),
ShippingRateSource::NotAvailable,
);
let (package_id, company_id, companies_package_id) =
super::common::create_delivery_objects(payload, core, http_client, base_url.clone(), Some(super_user_id.clone()));
// create
println!("run create new companies_packages ");
let create_result = create_companies_packages(
company_id,
package_id,
ShippingRateSource::NotAvailable,
core,
&http_client,
base_url.clone(),
None,
);
println!("{:?}", create_result);
assert!(create_result.is_err());
// read search
println!("run search companies_packages by id");
let read_result = core.run(http_client.request_with_auth_header::<CompanyPackage>(
Method::Get,
get_url_request_by_id(base_url.clone(), &companies_package_id),
None,
None,
));
assert!(read_result.is_ok());
// read companies
println!("run search companies by package id");
let read_result = core.run(http_client.request_with_auth_header::<Vec<Company>>(
Method::Get,
get_url_request_by_package_id(base_url.clone(), &package_id),
None,
None,
));
println!("companies by package id {:?}", read_result);
assert!(read_result.is_ok());
// read packages
println!("run search packages by company id");
let read_result = core.run(http_client.request_with_auth_header::<Vec<Packages>>(
Method::Get,
get_url_request_by_company_id(base_url.clone(), &company_id),
None,
None,
));
println!("packages by company id {:?}", read_result);
assert!(read_result.is_ok());
// read available packages
let country_search = Alpha3("RUS".to_string());
println!("unauthorized - run search available packages by country {:?}", country_search);
let read_result = core.run(http_client.request_with_auth_header::<Vec<AvailablePackages>>(
Method::Get,
get_url_request_available_packages(base_url.clone(), country_search, 0, 0),
None,
Some(super_user_id.to_string()),
));
println!("unauthorized - find available packages {:#?}", read_result);
assert!(read_result.is_ok());
// delete
println!("run delete companies_packages ");
let delete_result = core.run(http_client.request_with_auth_header::<CompanyPackage>(
Method::Delete,
get_url_request_by_id(base_url.clone(), &companies_package_id),
None,
None,
));
assert!(delete_result.is_err());
super::common::delete_deliveries_objects(
(package_id, company_id, companies_package_id),
core,
http_client,
base_url.clone(),
super_user_id,
);
}
|
use crate::bimap::BiMap;
use crate::conn::{self, ConnEvent, DateTime};
use log::error;
use std::sync::mpsc::SyncSender;
use futures::{Future, Stream};
pub struct DiscordConn {
token: String,
guild_name: String,
guild_id: discord::Snowflake,
channel_ids: BiMap<String, discord::Snowflake>,
last_message_ids: BiMap<String, discord::Snowflake>,
tui_sender: std::sync::mpsc::SyncSender<ConnEvent>,
last_typing_message: chrono::DateTime<chrono::Utc>,
}
fn format_json(text: &[u8]) -> String {
::serde_json::from_slice::<::serde_json::Value>(text)
.and_then(|v| ::serde_json::to_string_pretty(&v))
.unwrap_or_else(|_| String::from_utf8(text.to_vec()).unwrap_or_default())
}
macro_rules! deserialize_or_log {
($response:expr, $type:ty) => {{
::serde_json::from_slice::<$type>(&$response.bytes())
.map_err(|e| error!("{}\n{:#?}", format_json(&$response.bytes()), e))
}};
}
/*
pub fn permissions_in(
chan: &::discord::Channel,
guild: Option<&::discord::Guild>,
roles: &[::discord::Snowflake],
) -> ::discord::Permissions {
let mut perms = match guild {
Some(guild) => {
let perms = guild.permissions;
if (perms.contains(::discord::Permissions::ADMINISTRATOR)) || guild.owner {
::discord::Permissions::all()
} else {
perms
}
}
None => ::discord::Permissions::all(),
};
// Role overrides
for overwrite in chan
.permission_overwrites
.iter()
.filter(|owrite| roles.iter().any(|r| *r == owrite.id))
{
perms.insert(overwrite.allow);
perms.remove(overwrite.deny);
}
perms
}
*/
use weeqwest::Request;
impl DiscordConn {
pub fn create_on(token: &str, sender: SyncSender<ConnEvent>, server: &str) -> Result<(), ()> {
let mut client = weeqwest::Client::new();
let me_resp = client
.send(
Request::get(&format!("{}/users/@me", ::discord::BASE_URL))
.unwrap()
.header("Authorization", token),
)
.wait()
.map_err(|e| error!("{:#?}", e))?;
let me = deserialize_or_log!(me_resp, ::discord::User)?;
let guild_resp = client
.send(
Request::get(&format!("{}{}", ::discord::BASE_URL, "/users/@me/guilds"))
.unwrap()
.header("Authorization", token),
)
.wait()
.map_err(|e| error!("{:#?}", e))?;
let guilds = deserialize_or_log!(guild_resp, Vec<::discord::Guild>)?;
let guild = guilds.into_iter().find(|g| g.name == server).unwrap();
let guild_name = String::from(guild.name.as_str());
let me_resp = client
.send(
Request::get(&format!(
"{}/guilds/{}/members/{}",
::discord::BASE_URL,
guild.id,
me.id
))
.unwrap()
.header("Authorization", token),
)
.wait()
.map_err(|e| error!("{:#?}", e))?;
let me = deserialize_or_log!(me_resp, discord::GuildMember)?;
let mut my_roles = me.roles;
let channels_resp = client
.send(
Request::get(&format!(
"{}/guilds/{}/channels",
::discord::BASE_URL,
guild.id
))
.unwrap()
.header("Authorization", token),
)
.wait()
.map_err(|e| error!("{:#?}", e))?;
let channels = deserialize_or_log!(channels_resp, Vec<::discord::Channel>)?;
let roles_resp = client
.send(
Request::get(&format!(
"{}/guilds/{}/roles",
::discord::BASE_URL,
guild.id
))
.unwrap()
.header("Authorization", token),
)
.wait()
.map_err(|e| error!("{:#?}", e))?;
let roles = deserialize_or_log!(roles_resp, Vec<::discord::Role>)?;
let everyone_role = roles
.into_iter()
.find(|r| r.name == "@everyone")
.unwrap()
.id;
my_roles.push(everyone_role);
let channels: Vec<_> = channels
.into_iter()
.filter(|c| c.ty == 0)
/*
.filter(|c| {
permissions_in(c, Some(&guild), &my_roles)
.contains(::discord::Permissions::READ_MESSAGES)
})
*/
.filter(|c| c.name.is_some())
.collect();
let mut channel_ids: BiMap<String, discord::Snowflake> = BiMap::new();
let mut last_message_ids: BiMap<String, discord::Snowflake> = BiMap::new();
for channel in &channels {
let name = channel.name.clone().unwrap();
channel_ids.insert(name.clone(), channel.id);
last_message_ids.insert(name, channel.last_message_id.unwrap());
}
// This is how the TUI sends me events
let (tx, events_from_tui) = std::sync::mpsc::sync_channel(100);
let now = crate::conn::DateTime::now();
let _ = sender.send(ConnEvent::ServerConnected(crate::tui::Server {
channels: channels
.iter()
.map(|c| crate::tui::Channel {
messages: Vec::new(),
name: c.name.clone().unwrap_or_else(|| String::from("NONAME")),
read_at: now,
latest: now,
has_history: false,
message_scroll_offset: 0,
message_buffer: String::new(),
channel_type: crate::conn::ChannelType::Normal,
})
.collect(),
completer: None,
name: guild_name.clone(),
sender: tx,
channel_scroll_offset: 0,
current_channel: 0,
}));
let mut history_responses = Vec::new();
for channel in channels.into_iter().filter(|c| c.name.is_some()) {
let channel_name = channel.name.unwrap();
let token = token.to_string();
history_responses.push((
channel_name,
client.send(
Request::get(&format!(
"{}/channels/{}/messages?limit=100",
::discord::BASE_URL,
channel.id
))
.unwrap()
.header("Authorization", token.as_str()),
),
));
}
for (channel, history_resp) in history_responses {
let history_resp = history_resp.wait().unwrap();
let _ = deserialize_or_log!(history_resp, Vec<::discord::Message>).map(|history| {
let messages = history
.into_iter()
.map(|message| {
let timestamp = ::chrono::DateTime::parse_from_rfc3339(&message.timestamp)
.map(|d| d.with_timezone(&::chrono::Utc))
.map(|d| d.into())
.unwrap_or_else(|_| DateTime::now());
crate::conn::Message {
sender: message.author.username,
server: guild_name.clone(),
timestamp,
contents: String::from(message.content),
channel: channel.clone(),
reactions: Vec::new(),
}
})
.collect();
let _ = sender.send(ConnEvent::HistoryLoaded {
server: guild_name.clone(),
channel,
messages,
});
});
}
use std::sync::Arc;
use std::sync::RwLock;
let (tx, rx) = futures::sync::mpsc::channel(1);
let connection = Arc::new(RwLock::new(DiscordConn {
token: token.to_string(),
guild_name: guild_name.clone(),
guild_id: guild.id,
channel_ids: channel_ids.clone(),
last_message_ids,
tui_sender: sender.clone(),
last_typing_message: chrono::offset::Utc::now(),
}));
let tconnection = connection.clone();
std::thread::spawn(move || {
for ev in events_from_tui.iter() {
match ev {
conn::TuiEvent::SendMessage {
channel, contents, ..
} => tconnection
.read()
.unwrap()
.send_message(&channel, &contents),
conn::TuiEvent::SendTyping { channel, .. } => {
tconnection.write().unwrap().send_typing(&channel)
}
conn::TuiEvent::MarkRead { channel, .. } => {
tconnection.read().unwrap().mark_read(&channel)
}
_ => error!("unsupported event {:?}", ev),
}
}
});
// Spin off a thread that will feed message events back to the TUI
// websocket does not support the new tokio :(
let i_token = token.to_string();
std::thread::spawn(move || {
use discord::gateway::{Event, GatewayEvent, Hello};
let url_resp = client
.send(
Request::get(&format!("{}{}", ::discord::BASE_URL, "/gateway"))
.unwrap()
.header("Authorization", &i_token),
)
.wait()
.map_err(|e| error!("{:#?}", e))
.unwrap();
let resp = deserialize_or_log!(url_resp, ::discord::GatewayResponse).unwrap();
use futures::sink::Sink;
use websocket::result::WebSocketError;
use websocket::OwnedMessage::{Close, Ping, Pong, Text};
let runner = ::websocket::ClientBuilder::new(&resp.url)
.unwrap()
.async_connect_secure(None)
.and_then(|(duplex, _)| {
let (sink, stream) = duplex.split();
stream
// Maps a message to maybe a response
.filter_map(|message| match message {
Close(_) => {
error!("websocket closed");
None
}
Ping(m) => Some(Pong(m)),
Text(text) => {
let msg = ::serde_json::from_str::<GatewayEvent>(&text);
match msg {
Ok(GatewayEvent {
d:
Some(Event::Hello(Hello {
heartbeat_interval: interval,
..
})),
..
}) => {
let itx = tx.clone();
std::thread::spawn(move || loop {
let itx = itx.clone();
itx.send(Text("{\"op\":1,\"d\":null}".to_string()))
.wait()
.map_err(|e| error!("{:#?}", e))
.unwrap();
std::thread::sleep(std::time::Duration::from_millis(
interval as u64,
));
});
let identify = serde_json::json! {{
"op": 2,
"d": {
"token": i_token,
"properties": {
"$os": "Linux",
"$browser": "Discord Client",
"$device": "Firefox",
"$client_version": "0.0.9",
"$release_channel": "unknown",
},
"large_threshold": 250,
"compress": true,
"v": 6,
}
}}
.to_string();
Some(Text(identify))
}
Ok(gateway_message) => {
connection.read().unwrap().handle_websocket(gateway_message)
}
e => {
error!(
"Unrecognized Discord message: {}\n{:#?}",
format_json(text.as_bytes()),
e
);
None
}
}
}
_ => None,
})
.select(rx.map_err(|_| WebSocketError::NoDataAvailable))
.forward(sink)
});
::tokio::runtime::current_thread::block_on_all(runner).unwrap();
});
Ok(())
}
fn handle_websocket(
&self,
message: discord::gateway::GatewayEvent,
) -> Option<websocket::OwnedMessage> {
use discord::gateway::*;
match message {
GatewayEvent {
d:
Some(Event::MessageCreate(Message {
content: Some(content),
author: Some(discord::User { username, .. }),
channel_id,
guild_id: Some(guild_id),
..
})),
..
} => {
if self.guild_id == guild_id {
self.channel_ids
.get_left(&channel_id)
.map(|channel| {
self.tui_sender
.send(ConnEvent::Message(conn::Message {
server: self.guild_name.clone(),
channel: channel.clone(),
contents: content,
reactions: Vec::new(),
sender: username.clone(),
timestamp: DateTime::now(),
}))
.unwrap();
})
.or_else(|| {
error!(
"Unrecognized channel id in {:?} from {:?}",
channel_id, username
);
None
});
}
}
_ => {}
}
None
}
fn send_message(&self, channel: &str, content: &str) {
let channel = channel.to_string();
let id = *self.channel_ids.get_right(channel.as_str()).unwrap();
let token = self.token.clone();
let body = serde_json::json! {{
"content": content,
"tts": false,
}}
.to_string();
std::thread::spawn(move || {
let request =
weeqwest::Request::post(&format!("{}/channels/{}/messages", discord::BASE_URL, id))
.unwrap()
.header("Authorization", &token)
.json(body);
if let Ok(response) = weeqwest::send(&request) {
if let Err(e) = serde_json::from_slice::<discord::Message>(response.bytes()) {
error!("{:#?}", e);
}
}
});
}
fn send_typing(&mut self, channel: &str) {
let now = chrono::Utc::now();
if (now - self.last_typing_message) < chrono::Duration::seconds(3) {
return;
} else {
self.last_typing_message = now;
}
let id = *self.channel_ids.get_right(channel).unwrap();
let token = self.token.clone();
std::thread::spawn(move || {
let req =
weeqwest::Request::post(&format!("{}/channels/{}/typing", discord::BASE_URL, id))
.unwrap()
.header("Content-Length", "0")
.header("Authorization", &token);
let _ = weeqwest::send(&req).map_err(|e| error!("{:#?}", e));
});
}
fn mark_read(&self, channel: &str) {
let id = *self.channel_ids.get_right(channel).unwrap();
let last_message_id = *self.last_message_ids.get_right(channel).unwrap();
let token = self.token.clone();
let body = serde_json::json! {{"token": token}}.to_string();
std::thread::spawn(move || {
let req = weeqwest::Request::post(&format!(
"{}/channels/{}/messages/{}/ack",
discord::BASE_URL,
id,
last_message_id,
))
.unwrap()
.header("Authorization", &token)
.json(body);
let _ = weeqwest::send(&req).map_err(|e| error!("{:#?}", e));
});
}
}
|
use core::config::Configuration;
use core::net::{self,TcpWriter};
use core::errors::MomoError;
use core::parser::IrcMessage;
use core::threads;
use core::types::NoResult;
// Synchronization primitives
use std::thread;
use chan;
type THandle = thread::JoinHandle<()>;
pub struct Momo {
config: Configuration,
threads: Vec<THandle>,
}
impl Momo {
pub fn new(config: Configuration) -> Momo {
Momo {
config: config,
threads: Vec::new()
}
}
pub fn thread_setup(&mut self, w: &TcpWriter) -> chan::Sender<IrcMessage> {
let (sender, receiver) = chan::async();
let thread_conn = w.clone();
let thread_name = "writer";
self.threads.push(thread::Builder::new()
.name(thread_name.to_string())
.spawn(move || {
threads::new_thread(thread_conn, receiver);
}).ok().expect("Unable to spawn thread!"));
sender
}
pub fn run(&mut self) -> NoResult<MomoError> {
let (mut reader, mut writer) = net::new_connection(&self.config.server,
self.config.port);
let message_sender = self.thread_setup(&writer);
try!(writer.write(&format!("NICK {}", &self.config.nickname)));
try!(writer.write(&format!("USER {} * * :Momo by svkampen",
&self.config.nickname)));
while let Ok(line) = reader.read_line() {
let message = IrcMessage::parse(&line);
if message.method == "PING" {
try!(writer.write(&format!("PONG {}", message.args)));
continue;
}
message_sender.send(message);
};
Ok(())
}
}
|
use opengl_graphics::Texture;
use opengl_graphics::TextureSettings;
use rayon::prelude::*;
lazy_static! {
pub static ref MARS: Texture = Texture::from_path(find_folder::Search::ParentsThenKids(3, 3).for_folder("images").unwrap().join("mars.png"), &TextureSettings::new()).unwrap();
}
|
use crate::schema::refresh_tokens;
use compat_uuid::Uuid;
use diesel::{
self, delete, insert_into, prelude::*, result::Error, update, Associations, FromSqlRow,
Identifiable, Insertable, Queryable,
};
use postgres_resource::*;
#[resource(schema = refresh_tokens, table = "refresh_tokens")]
struct RefreshToken {
uuid: Uuid,
}
|
use validaten::crypto;
fn main() {
println!("1GiWxH6PzSSmbdcK72XfGpqhjSb6nae6h9 => {:?}", crypto::which_cryptocurrency("1GiWxH6PzSSmbdcK72XfGpqhjSb6nae6h9"));
println!("qppjlghjlwg6tgxv7ffhvs43rlul0kpp4c0shk4dr6 => {:?}", crypto::which_cryptocurrency("qppjlghjlwg6tgxv7ffhvs43rlul0kpp4c0shk4dr6"));
println!("0xaae47eae4ddd4877e0ae0bc780cfaee3cc3b52cb => {:?}", crypto::which_cryptocurrency("0xaae47eae4ddd4877e0ae0bc780cfaee3cc3b52cb"));
println!("LQ4i7FLNhfCC9GXw682mS1NzvVKbtJAFZq => {:?}", crypto::which_cryptocurrency("LQ4i7FLNhfCC9GXw682mS1NzvVKbtJAFZq"));
println!("D6K2nqqQKycTucCSFSHhpiig4yQ6NPQRf9 => {:?}", crypto::which_cryptocurrency("D6K2nqqQKycTucCSFSHhpiig4yQ6NPQRf9"));
println!("XqLYPDTADW6EYuQmTcEAx81o8EHTKwqTK8 => {:?}", crypto::which_cryptocurrency("XqLYPDTADW6EYuQmTcEAx81o8EHTKwqTK8"));
println!("41gYNjXMeXaTmZFVv645A1HRVoA637cXFGbDdLV8Gn5hLvfxfRLKigUTvm2HVZhBzDVPeGpDy71qxASTpRFgepDwLexA8Ti => {:?}", crypto::which_cryptocurrency("41gYNjXMeXaTmZFVv645A1HRVoA637cXFGbDdLV8Gn5hLvfxfRLKigUTvm2HVZhBzDVPeGpDy71qxASTpRFgepDwLexA8Ti"));
println!("AeHauBkGkHPTxh4PEUhNr7WRgivmcdCRnR => {:?}", crypto::which_cryptocurrency("AeHauBkGkHPTxh4PEUhNr7WRgivmcdCRnR"));
println!("rUocf1ixKzTuEe34kmVhRvGqNCofY1NJzV => {:?}", crypto::which_cryptocurrency("rUocf1ixKzTuEe34kmVhRvGqNCofY1NJzV"));
} |
use std::collections::{HashMap, HashSet};
use std::fmt;
use crate::object;
use crate::ArcDataSlice;
use crate::hlc;
use crate::network;
use crate::store;
use crate::encoding;
pub mod applyer;
pub mod checker;
pub mod driver;
pub mod locker;
pub mod messages;
pub mod requirements;
pub mod tx;
pub use requirements::{TransactionRequirement, KeyRequirement, TimestampRequirement};
pub use messages::Message;
/// Transaction UUID
///
/// Uniquely identifies a transaction
#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
pub struct Id(pub uuid::Uuid);
impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "TransactionId({})", self.0)
}
}
/// Resolution status of a transaction
#[derive(Debug, Clone, Copy)]
pub enum Status {
Unresolved,
Committed,
Aborted
}
impl fmt::Display for Status {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Status::Unresolved => write!(f, "Unresolved"),
Status::Committed => write!(f, "Committed"),
Status::Aborted => write!(f, "Aborted")
}
}
}
/// Disposition of the store with respect to whether or not the transaction should be committed
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Disposition {
Undetermined,
VoteCommit,
VoteAbort
}
impl Disposition {
pub fn to_u8(&self) -> u8 {
match self {
Disposition::Undetermined => 0u8,
Disposition::VoteCommit => 1u8,
Disposition::VoteAbort => 2u8
}
}
pub fn from_u8(code: u8) -> Result<Disposition, crate::EncodingError> {
match code {
0 => Ok(Disposition::Undetermined),
1 => Ok(Disposition::VoteCommit),
2 => Ok(Disposition::VoteAbort),
_ => Err(crate::EncodingError::ValueOutOfRange)
}
}
}
impl fmt::Display for Disposition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Disposition::Undetermined => write!(f, "Undetermined"),
Disposition::VoteCommit => write!(f, "VoteCommit"),
Disposition::VoteAbort => write!(f, "VoteAbort")
}
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ObjectUpdate {
pub object_id: object::Id,
pub data: ArcDataSlice
}
#[derive(Debug, Clone)]
pub struct SerializedFinalizationAction{
pub type_uuid: uuid::Uuid,
pub data: Vec<u8>
}
#[derive(Clone)]
pub struct TransactionDescription {
pub id: Id,
serialized_transaction_description: Option<ArcDataSlice>,
pub start_timestamp: hlc::Timestamp,
pub primary_object: object::Pointer,
pub designated_leader: u8,
pub requirements: Vec<TransactionRequirement>,
pub finalization_actions: Vec<SerializedFinalizationAction>,
pub originating_client: Option<network::ClientId>,
pub notify_on_resolution: Vec<store::Id>,
pub notes: Vec<String>
}
impl TransactionDescription {
pub fn new(id: Id,
start_timestamp: hlc::Timestamp,
primary_object: object::Pointer,
designated_leader: u8,
requirements: Vec<TransactionRequirement>,
finalization_actions: Vec<SerializedFinalizationAction>,
originating_client: Option<network::ClientId>,
notify_on_resolution: Vec<store::Id>,
notes: Vec<String>) -> TransactionDescription {
TransactionDescription {
id,
serialized_transaction_description: None,
start_timestamp,
primary_object,
designated_leader,
requirements,
finalization_actions,
originating_client,
notify_on_resolution,
notes
}
}
pub fn deserialize(encoded: &ArcDataSlice) -> TransactionDescription {
encoding::deserialize_transaction_description(encoded)
}
pub fn serialized_transaction_description(&mut self) -> ArcDataSlice {
let ads = match &self.serialized_transaction_description {
Some(sd) => sd.clone(),
None => {
let mut builder = flatbuffers::FlatBufferBuilder::new_with_capacity(4096);
let etd = encoding::encode_transaction_description(&mut builder, self);
builder.finish(etd, None);
let buf = builder.finished_data();
ArcDataSlice::from_bytes(buf)
}
};
let r = ads.clone();
self.serialized_transaction_description = Some(ads);
r
}
pub fn designated_leader_store_id(&self) -> store::Id {
store::Id {
pool_uuid: self.primary_object.pool_id.0,
pool_index: self.designated_leader
}
}
pub fn hosted_objects(&self, store_id: store::Id) -> HashMap<object::Id, store::Pointer> {
let mut h: HashMap<object::Id, store::Pointer> = HashMap::new();
let mut f = |ptr: &object::Pointer| {
for sp in &ptr.store_pointers {
if sp.pool_index() == store_id.pool_index {
h.insert(ptr.id, sp.clone());
break;
}
}
};
for r in &self.requirements {
match r {
TransactionRequirement::LocalTime{..} => (),
TransactionRequirement::RevisionLock{pointer, ..} => f(pointer),
TransactionRequirement::VersionBump{pointer, ..} => f(pointer),
TransactionRequirement::RefcountUpdate{pointer, ..} => f(pointer),
TransactionRequirement::DataUpdate{pointer, ..} => f(pointer),
TransactionRequirement::KeyValueUpdate{pointer, ..} => f(pointer),
}
}
h
}
pub fn all_objects(&self) -> HashSet<object::Pointer> {
let mut s: HashSet<object::Pointer> = HashSet::new();
let mut f = |ptr: &object::Pointer| {
s.insert(ptr.clone());
};
for r in &self.requirements {
match r {
TransactionRequirement::LocalTime{..} => (),
TransactionRequirement::RevisionLock{pointer, ..} => f(pointer),
TransactionRequirement::VersionBump{pointer, ..} => f(pointer),
TransactionRequirement::RefcountUpdate{pointer, ..} => f(pointer),
TransactionRequirement::DataUpdate{pointer, ..} => f(pointer),
TransactionRequirement::KeyValueUpdate{pointer, ..} => f(pointer),
}
}
s
}
}
|
use std::sync::MutexGuard;
use nia_interpreter_core::Interpreter;
use nia_interpreter_core::NiaInterpreterCommand;
use nia_interpreter_core::NiaInterpreterCommandResult;
use nia_interpreter_core::{EventLoopHandle, NiaDefineModifierCommandResult};
use crate::error::{NiaServerError, NiaServerResult};
use crate::protocol::{NiaConvertable, NiaDefineModifierRequest, Serializable};
use nia_protocol_rust::DefineModifierResponse;
#[derive(Debug, Clone)]
pub struct NiaDefineModifierResponse {
command_result: NiaDefineModifierCommandResult,
}
impl NiaDefineModifierResponse {
fn try_from(
nia_define_modifier_request: NiaDefineModifierRequest,
event_loop_handle: MutexGuard<EventLoopHandle>,
) -> Result<NiaDefineModifierResponse, NiaServerError> {
let modifier = nia_define_modifier_request.take_modifier();
let interpreter_modifier = modifier.to_interpreter_repr();
let interpreter_command =
NiaInterpreterCommand::make_define_modifier_command(
interpreter_modifier,
);
event_loop_handle
.send_command(interpreter_command)
.map_err(|_| {
NiaServerError::interpreter_error(
"Error sending command to the interpreter.",
)
})?;
let execution_result =
event_loop_handle.receive_result().map_err(|_| {
NiaServerError::interpreter_error(
"Error reading command from the interpreter.",
)
})?;
let response = match execution_result {
NiaInterpreterCommandResult::DefineModifier(command_result) => {
NiaDefineModifierResponse { command_result }
}
_ => {
return NiaServerError::interpreter_error(
"Unexpected command result.",
)
.into()
}
};
Ok(response)
}
pub fn from(
nia_define_modifier_request: NiaDefineModifierRequest,
event_loop_handle: MutexGuard<EventLoopHandle>,
) -> NiaDefineModifierResponse {
println!("{:?}", nia_define_modifier_request);
let try_result = NiaDefineModifierResponse::try_from(
nia_define_modifier_request,
event_loop_handle,
);
match try_result {
Ok(result) => result,
Err(error) => {
let message =
format!("Execution failure: {}", error.get_message());
let command_result =
NiaDefineModifierCommandResult::Failure(message);
NiaDefineModifierResponse { command_result }
}
}
}
}
impl
Serializable<
NiaDefineModifierResponse,
nia_protocol_rust::DefineModifierResponse,
> for NiaDefineModifierResponse
{
fn to_pb(&self) -> DefineModifierResponse {
let result = &self.command_result;
let mut define_modifier_response =
nia_protocol_rust::DefineModifierResponse::new();
match result {
NiaDefineModifierCommandResult::Success() => {
let mut success_result =
nia_protocol_rust::DefineModifierResponse_SuccessResult::new();
success_result.set_message(protobuf::Chars::from(
String::from("Success."),
));
define_modifier_response.set_success_result(success_result);
}
NiaDefineModifierCommandResult::Error(error_message) => {
let mut error_result =
nia_protocol_rust::DefineModifierResponse_ErrorResult::new(
);
error_result
.set_message(protobuf::Chars::from(error_message.clone()));
define_modifier_response.set_error_result(error_result);
}
NiaDefineModifierCommandResult::Failure(failure_message) => {
let mut failure_result =
nia_protocol_rust::DefineModifierResponse_FailureResult::new();
failure_result.set_message(protobuf::Chars::from(
failure_message.clone(),
));
define_modifier_response.set_failure_result(failure_result);
}
}
define_modifier_response
}
fn from_pb(
object_pb: DefineModifierResponse,
) -> NiaServerResult<NiaDefineModifierResponse> {
unreachable!()
}
}
|
use crate::{
db_conn,
schema::{self, dialogs},
DirtyTransaction, Error, Transaction,
};
use common::{
chrono::{DateTime, Utc},
rsip::{self, prelude::*},
uuid::Uuid,
};
use diesel::{
deserialize::FromSql,
pg::Pg,
prelude::*,
serialize::{Output, ToSql},
sql_types::Text,
};
use std::{
convert::{TryFrom, TryInto},
fmt::{self, Debug},
io::Write,
};
#[derive(Queryable, AsChangeset, Insertable, Debug, Clone)]
#[table_name = "dialogs"]
pub struct Dialog {
pub id: i64,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub computed_id: String,
pub call_id: String,
pub from_tag: String,
pub to_tag: String,
pub flow: DialogFlow,
}
#[derive(AsChangeset, Insertable, Debug, Default)]
#[table_name = "dialogs"]
pub struct DirtyDialog {
pub created_at: Option<DateTime<Utc>>,
pub updated_at: Option<DateTime<Utc>>,
pub computed_id: Option<String>,
pub call_id: Option<String>,
pub from_tag: Option<String>,
pub to_tag: Option<String>,
pub flow: Option<DialogFlow>,
}
pub struct DirtyDialogWithTransaction {
pub dialog: DirtyDialog,
pub transaction: DirtyTransaction,
}
pub struct DialogWithTransaction {
pub dialog: Dialog,
pub transaction: Transaction,
}
impl From<(Dialog, Transaction)> for DialogWithTransaction {
fn from(tuple: (Dialog, Transaction)) -> Self {
Self {
dialog: tuple.0,
transaction: tuple.1,
}
}
}
pub struct LazyQuery {
query: dialogs::BoxedQuery<'static, diesel::pg::Pg>,
}
impl LazyQuery {
pub fn new(query: dialogs::BoxedQuery<'static, diesel::pg::Pg>) -> Self {
Self { query }
}
pub fn computed_id(mut self, computed_id: Option<String>) -> Self {
if let Some(computed_id) = computed_id {
self.query = self.query.filter(dialogs::computed_id.eq(computed_id));
}
self
}
pub fn paginate(mut self, page: i64, per_page: i64) -> Self {
let offset = (page - 1) * per_page;
self.query = self.query.offset(offset).limit(per_page);
self
}
pub fn order_by_created_at(mut self) -> Self {
self.query = self.query.order(dialogs::created_at.desc());
self
}
pub async fn load(self) -> Result<Vec<Dialog>, Error> {
Ok(self.query.get_results(&db_conn()?)?)
}
pub async fn first(self) -> Result<Dialog, Error> {
Ok(self.query.first(&db_conn()?)?)
}
}
type DialogsWithTransactions = diesel::query_builder::BoxedSelectStatement<
'static,
(dialogs::SqlType, schema::transactions::SqlType),
diesel::query_source::joins::JoinOn<
diesel::query_source::joins::Join<
schema::dialogs::table,
schema::transactions::table,
diesel::query_source::joins::Inner,
>,
diesel::expression::operators::Eq<
schema::dialogs::columns::id,
schema::transactions::columns::dialog_id,
>,
>,
diesel::pg::Pg,
>;
pub struct LazyQueryWithTransactions {
query: DialogsWithTransactions,
}
impl LazyQueryWithTransactions {
pub fn new(query: DialogsWithTransactions) -> Self {
Self { query }
}
pub fn computed_id(mut self, computed_id: Option<String>) -> Self {
if let Some(computed_id) = computed_id {
self.query = self.query.filter(dialogs::computed_id.eq(computed_id));
}
self
}
pub fn paginate(mut self, page: i64, per_page: i64) -> Self {
let offset = (page - 1) * per_page;
self.query = self.query.offset(offset).limit(per_page);
self
}
pub fn order_by_created_at(mut self) -> Self {
self.query = self.query.order(dialogs::created_at.desc());
self.query = self.query.order(schema::transactions::created_at.desc());
self
}
pub fn load(self) -> Result<Vec<DialogWithTransaction>, Error> {
Ok(self
.query
.get_results(&db_conn()?)?
.into_iter()
.map(|s: (Dialog, Transaction)| s.into())
.collect())
}
pub fn first(self) -> Result<DialogWithTransaction, Error> {
Ok(self
.query
.first::<(Dialog, Transaction)>(&db_conn()?)?
.into())
}
}
impl Dialog {
pub fn query_with_transactions() -> LazyQueryWithTransactions {
LazyQueryWithTransactions::new(
dialogs::table
.inner_join(
schema::transactions::table.on(dialogs::id.eq(schema::transactions::dialog_id)),
)
//.select(charge_locations::table::all_columns())
.distinct()
.into_boxed(),
)
}
pub fn query() -> LazyQuery {
LazyQuery::new(dialogs::table.into_boxed())
}
pub fn find(id: i64) -> Result<Self, Error> {
Ok(dialogs::table.find(id).first::<Self>(&db_conn()?)?)
}
pub fn find_with_transaction(computed_id: String) -> Result<DialogWithTransaction, Error> {
Self::query_with_transactions()
.computed_id(Some(computed_id))
.order_by_created_at()
.first()
}
pub fn find_or_create_dialog(request: rsip::Request) -> Result<DialogWithTransaction, Error> {
//request.debug_with(request.dialog_id().map(|s| s.to_string()));
match request.dialog_id()? {
Some(dialog_id) => Ok(Self::find_with_transaction(dialog_id)?),
None => Ok(Self::create_with_transaction(request)?),
}
}
pub fn create(record: impl Into<DirtyDialog>) -> Result<Self, Error> {
use diesel::insert_into;
Ok(insert_into(dialogs::table)
.values(record.into())
.get_result(&db_conn()?)?)
}
pub fn create_with_transaction(
dirty_struct: impl TryInto<DirtyDialogWithTransaction>,
) -> Result<DialogWithTransaction, Error> {
use diesel::insert_into;
let dirty_struct = dirty_struct.try_into().map_err(|_| {
crate::Error::custom("Failed to convert dialog with transaction".into())
})?;
let connection = db_conn()?;
connection.transaction::<_, Error, _>(|| {
let dialog: Self = insert_into(dialogs::table)
.values(dirty_struct.dialog)
.get_result(&connection)?;
let mut transaction = dirty_struct.transaction;
transaction.dialog_id = Some(dialog.id);
let transaction = insert_into(schema::transactions::table)
.values(transaction)
.get_result(&connection)?;
Ok(DialogWithTransaction::from((dialog, transaction)))
})
}
pub fn update(record: impl Into<DirtyDialog>, id: i64) -> Result<Self, Error> {
Ok(diesel::update(dialogs::table.filter(dialogs::id.eq(id)))
.set(&record.into())
.get_result(&db_conn()?)?)
}
pub fn delete(id: i64) -> Result<Self, Error> {
Ok(diesel::delete(dialogs::table.filter(dialogs::id.eq(id))).get_result(&db_conn()?)?)
}
}
#[derive(FromSqlRow, AsExpression, Copy, Clone, PartialEq, Debug)]
#[sql_type = "Text"]
pub enum DialogFlow {
Registration,
Invite,
Publish,
}
impl fmt::Display for DialogFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(self, f)
}
}
impl ToSql<Text, Pg> for DialogFlow {
fn to_sql<W: Write>(&self, out: &mut Output<W, Pg>) -> diesel::serialize::Result {
<&str as ToSql<Text, Pg>>::to_sql(&self.to_string().to_lowercase().as_str(), out)
}
}
impl FromSql<Text, Pg> for DialogFlow {
fn from_sql(bytes: Option<diesel::pg::PgValue>) -> diesel::deserialize::Result<Self> {
use std::str::FromStr;
Ok(DialogFlow::from_str(
<String as FromSql<Text, Pg>>::from_sql(bytes)?.as_ref(),
)?)
}
}
impl std::str::FromStr for DialogFlow {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
s if s.eq_ignore_ascii_case("registration") => Ok(DialogFlow::Registration),
s if s.eq_ignore_ascii_case("invite") => Ok(DialogFlow::Invite),
s if s.eq_ignore_ascii_case("publish") => Ok(DialogFlow::Publish),
s => Err(format!("invalid DialogFlow `{}`", s)),
}
}
}
impl TryFrom<rsip::Request> for DirtyDialogWithTransaction {
type Error = crate::Error;
fn try_from(model: rsip::Request) -> Result<DirtyDialogWithTransaction, Self::Error> {
//use store::{DialogFlow, RegistrationFlow};
let call_id: String = model.call_id_header()?.clone().into();
let from_tag: String = model
.from_header()?
.typed()?
.tag()
.ok_or("missing call id")?
.clone()
.into();
let branch_id: String = model
.via_header()?
.typed()?
.branch()
.ok_or("missing branch id")?
.clone()
.into();
let to_tag = Uuid::new_v4();
Ok(DirtyDialogWithTransaction {
dialog: DirtyDialog {
computed_id: Some(computed_id_for(&call_id, &from_tag, &to_tag)),
call_id: Some(call_id),
from_tag: Some(from_tag),
to_tag: Some(to_tag.to_string()),
flow: Some(flow_for_method(*model.method())?),
..Default::default()
},
transaction: crate::DirtyTransaction {
branch_id: Some(branch_id),
state: Some(crate::TransactionState::Trying),
..Default::default()
},
})
}
}
#[allow(clippy::from_over_into)]
impl Into<models::Dialog> for DialogWithTransaction {
fn into(self) -> models::Dialog {
models::Dialog {
computed_id: self.dialog.computed_id,
call_id: self.dialog.call_id,
from_tag: self.dialog.from_tag,
to_tag: self.dialog.to_tag,
flow: into_model((self.dialog.flow, self.transaction)),
}
}
}
impl From<models::Dialog> for DirtyDialogWithTransaction {
fn from(model: models::Dialog) -> DirtyDialogWithTransaction {
let (flow, transaction): (DialogFlow, DirtyTransaction) = from_model(model.flow);
DirtyDialogWithTransaction {
dialog: DirtyDialog {
computed_id: Some(model.computed_id),
call_id: Some(model.call_id),
from_tag: Some(model.from_tag),
to_tag: Some(model.to_tag),
flow: Some(flow),
..Default::default()
},
transaction,
}
}
}
fn into_model(tuple: (DialogFlow, Transaction)) -> models::DialogFlow {
match tuple.0 {
DialogFlow::Registration => models::DialogFlow::Registration(tuple.1.into()),
DialogFlow::Invite => models::DialogFlow::Invite(tuple.1.into()),
DialogFlow::Publish => models::DialogFlow::Publish(tuple.1.into()),
}
}
fn from_model(model: models::DialogFlow) -> (DialogFlow, DirtyTransaction) {
match model {
models::DialogFlow::Registration(transaction) => {
(DialogFlow::Registration, transaction.into())
}
models::DialogFlow::Invite(transaction) => (DialogFlow::Invite, transaction.into()),
models::DialogFlow::Publish(transaction) => (DialogFlow::Publish, transaction.into()),
}
}
fn computed_id_for(call_id: &str, from_tag: &str, to_tag: &Uuid) -> String {
format!("{}-{}-{}", call_id, from_tag, to_tag)
}
fn flow_for_method(method: rsip::Method) -> Result<DialogFlow, String> {
use rsip::Method;
match method {
Method::Register => Ok(DialogFlow::Registration),
Method::Invite => Ok(DialogFlow::Invite),
Method::Publish => Ok(DialogFlow::Publish),
Method::Subscribe => Ok(DialogFlow::Publish),
_ => Err("Unsupported method".into()),
}
}
|
#![feature(str_split_once)]
use anyhow::{anyhow, Result};
use reqwest::header::{AUTHORIZATION, USER_AGENT};
use serde::de::{DeserializeOwned, Deserializer};
use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet};
fn main() -> Result<()> {
println!(
"# Libs Meeting {}
###### tags: `Libs Meetings` `Minutes`
## Agenda
- Triage
- Anything else?
## Triage
",
chrono::Utc::now().format("%Y-%m-%d")
);
show_fcps()?;
show_issues()?;
println!(
"## Notes
**Attendees**: ...
...
## Actions
- [ ] Finish action items from the last meeting.
- [ ] Reply to all issues/PRs discussed in this meeting.
"
);
Ok(())
}
fn show_fcps() -> Result<()> {
let p = reqwest::blocking::get("https://rfcbot.rs")?.text()?;
let mut p = p.lines();
p.find(|s| s.trim_end() == "<h4><code>T-libs</code></h4>")
.ok_or_else(|| anyhow!("Missing T-libs section"))?;
let mut fcps = BTreeMap::<&str, Vec<Fcp>>::new();
let mut reviewer_count: BTreeMap<&str, usize> = [
"Amanieu",
"BurntSushi",
"dtolnay",
"KodrAus",
"m-ou-se",
"sfackler",
"withoutboats",
]
.iter()
.map(|&r| (r, 0))
.collect();
loop {
let line = p.next().unwrap();
if line.starts_with("<h4>") {
break;
}
if line.trim() == "<li>" {
let disposition = p.next().unwrap().trim().strip_suffix(":").unwrap();
let url = p
.next()
.unwrap()
.trim()
.strip_prefix("<b><a href=\"")
.unwrap()
.strip_suffix('"')
.unwrap();
assert_eq!(p.next().unwrap().trim(), "target=\"_blank\">");
let title_and_number = p.next().unwrap().trim().strip_suffix(")</a></b>").unwrap();
let (title, number) = title_and_number.rsplit_once(" (").unwrap();
let (repo, number) = number.split_once('#').unwrap();
let mut reviewers = Vec::new();
let mut concerns = false;
loop {
let line = p.next().unwrap().trim();
if line == "</li>" {
break;
}
if line == "pending concerns" {
concerns = true;
} else if let Some(line) = line.strip_prefix("<a href=\"/fcp/") {
let reviewer = line.split_once('"').unwrap().0;
if let Some(n) = reviewer_count.get_mut(reviewer) {
reviewers.push(reviewer);
*n += 1;
}
}
}
fcps.entry(repo).or_default().push(Fcp {
title,
repo,
number,
disposition,
url,
reviewers,
concerns,
});
}
}
println!("### FCPs");
println!();
println!(
"{} open T-libs FCPs:",
fcps.values().map(|v| v.len()).sum::<usize>()
);
for (repo, fcps) in fcps.iter() {
println!("<details><summary><a href=\"https://github.com/{}/issues?q=is%3Aopen+label%3AT-libs+label%3Aproposed-final-comment-period\">{} <code>{}</code> FCPs</a></summary>\n", repo, fcps.len(), repo);
for fcp in fcps {
print!(
" - [[{} {}]({})] *{}*",
fcp.disposition,
fcp.number,
fcp.url,
escape(fcp.title)
);
println!(" - ({} checkboxes left)", fcp.reviewers.len());
if fcp.concerns {
println!(" Blocked on an open concern.");
}
}
println!("</details>");
}
println!("<p></p>\n");
for (i, (&reviewer, &num)) in reviewer_count.iter().enumerate() {
if i != 0 {
print!(", ");
}
print!(
"[{} ({})](https://rfcbot.rs/fcp/{})",
reviewer, num, reviewer
);
}
println!();
println!();
Ok(())
}
fn show_issues() -> Result<()> {
let mut seen = BTreeSet::new();
let mut dedup = |mut issues: Vec<Issue>| -> Vec<Issue> {
issues.retain(|issue| seen.insert(issue.html_url.clone()));
issues
};
let nominated_issues: Vec<Issue> = dedup(github_api(
"repos/rust-lang/rust/issues?labels=T-libs,I-nominated",
)?);
let nominated_rfcs: Vec<Issue> = dedup(github_api(
"repos/rust-lang/rfcs/issues?labels=T-libs,I-nominated",
)?);
let waiting_on_team_issues: Vec<Issue> = dedup(github_api(
"repos/rust-lang/rust/issues?labels=T-libs,S-waiting-on-team",
)?);
let waiting_on_team_rfcs: Vec<Issue> = dedup(github_api(
"repos/rust-lang/rfcs/issues?labels=T-libs,S-waiting-on-team",
)?);
let needs_decision_issues: Vec<Issue> = dedup(github_api(
"repos/rust-lang/rust/issues?labels=T-libs,I-needs-decision",
)?);
let print_issues = |issues: &[Issue]| {
for issue in issues.iter().rev() {
println!(
" - [[{}]({})] *{}*",
issue.number,
issue.html_url,
escape(&issue.title)
);
if issue.labels.iter().any(|l| l == "finished-final-comment-period") {
print!(" FCP finished.");
for label in issue.labels.iter() {
if let Some(disposition) = label.strip_prefix("disposition-") {
print!(" Should be {}d?", disposition);
}
}
println!();
}
}
};
println!("### Nominated");
println!();
println!("- [{} `rust-lang/rfcs` items](https://github.com/rust-lang/rfcs/issues?q=is%3Aopen+label%3AT-libs+label%3AI-nominated)", nominated_rfcs.len());
print_issues(&nominated_rfcs);
println!("- [{} `rust-lang/rust` items](https://github.com/rust-lang/rust/issues?q=is%3Aopen+label%3AT-libs+label%3AI-nominated)", nominated_issues.len());
print_issues(&nominated_issues);
println!();
println!("### Waiting on team");
println!();
println!("- [{} `rust-lang/rfcs` items](https://github.com/rust-lang/rfcs/issues?q=is%3Aopen+label%3AT-libs+label%3AS-waiting-on-team)", waiting_on_team_rfcs.len());
print_issues(&waiting_on_team_rfcs);
println!("- [{} `rust-lang/rust` items](https://github.com/rust-lang/rust/issues?q=is%3Aopen+label%3AT-libs+label%3AS-waiting-on-team)", waiting_on_team_issues.len());
print_issues(&waiting_on_team_issues);
println!();
println!("### Needs decision");
println!();
println!("- [{} `rust-lang/rust` items](https://github.com/rust-lang/rust/issues?q=is%3Aopen+label%3AT-libs+label%3AI-needs-decision)", needs_decision_issues.len());
print_issues(&needs_decision_issues);
println!();
Ok(())
}
#[derive(Debug)]
struct Fcp<'a> {
title: &'a str,
repo: &'a str,
number: &'a str,
disposition: &'a str,
url: &'a str,
reviewers: Vec<&'a str>,
concerns: bool,
}
#[derive(Debug, Deserialize)]
struct Issue {
number: u32,
html_url: String,
title: String,
#[serde(deserialize_with = "deserialize_labels")]
labels: Vec<String>,
}
fn escape(v: &str) -> String {
let mut s = String::with_capacity(v.len() + 10);
v.chars().for_each(|c| {
match c {
'_' | '*' | '\\' | '[' | ']' | '-' | '<' | '>' | '`' => s.push('\\'),
_ => {}
}
s.push(c);
});
s
}
fn github_api<T: DeserializeOwned>(endpoint: &str) -> Result<T> {
let mut client = reqwest::blocking::Client::new()
.get(&format!("https://api.github.com/{}", endpoint))
.header(USER_AGENT, "rust-lang libs agenda maker");
if let Ok(token) = std::env::var("GITHUB_TOKEN") {
client = client.header(AUTHORIZATION, format!("token {}", token));
}
let response = client.send()?;
Ok(response.json()?)
}
fn deserialize_labels<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
#[derive(Debug, Deserialize)]
struct Label {
name: String,
}
let v = Vec::<Label>::deserialize(d)?;
Ok(v.into_iter().map(|l| l.name).collect())
}
|
use std::thread;
fn main() {
let th1 = thread::spawn(move || {
loop {
println!("Hello");
}
});
let th2 = thread::spawn(move || loop {
println!("World");
});
th1.join().expect("The th1 thread has panicked");
th2.join().expect("The th2 thread has panicked");
}
|
use super::super::super::icon;
use super::Msg;
use crate::{block::chat::item::Icon, resource::Data, Resource};
use kagura::prelude::*;
pub fn chat_icon(attrs: Attributes, icon: &Icon, alt: &str, resource: &Resource) -> Html {
match icon {
Icon::None => icon::none(attrs),
Icon::Resource(r_id) => {
if let Some(Data::Image { url: img_url, .. }) = resource.get(&r_id) {
icon::from_img(attrs, img_url.as_str())
} else {
icon::from_str(attrs, alt)
}
}
_ => icon::from_str(attrs, &alt),
}
}
|
#[cfg(test)]
mod tests;
use std::marker::PhantomData;
use serde::{Deserialize, Deserializer};
use serde::de::{DeserializeSeed, MapAccess, SeqAccess, Visitor};
use crate::track::Duration;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
pub struct Entry {
pub id: Box<str>,
pub url: Box<str>, // This is a url fragment, not a complete url.
#[serde(rename(deserialize = "tit_art"))]
pub track_id: Box<str>,
pub duration: Duration,
pub extra: Option<Box<str>>,
}
// Struct to provide flattened deserialization.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Audios(pub Box<[Entry]>);
impl<'de> Deserialize<'de> for Audios {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>
{
Json
::deserialize(deserializer)
.map(
|json| Audios(json.audios.0)
)
}
}
// Struct to provide layered deserialization.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
struct Json {
audios: AudiosObject
}
// Struct to flatten audios values.
#[derive(Debug)]
struct AudiosObjectVisitor;
impl<'de> Visitor<'de> for AudiosObjectVisitor {
type Value = Box<[Entry]>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("audios object")
}
fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Self::Value, M::Error> {
let mut vec: Vec<Entry> = Vec::new();
let mut next = ||
map.next_entry_seed::<PhantomData<&str>, EntriesExtender>(
PhantomData,
EntriesExtender(&mut vec)
);
while let Some(_) = next()? { }
Ok(
vec.into_boxed_slice()
)
}
}
// Struct to collect audios values.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct AudiosObject(Box<[Entry]>);
impl<'de> Deserialize<'de> for AudiosObject {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>
{
deserializer
.deserialize_map(AudiosObjectVisitor)
.map(AudiosObject)
}
}
// Struct to push entries into buffer.
#[derive(Debug)]
struct EntriesVisitor<'a>(&'a mut Vec<Entry>);
impl<'de, 'a> Visitor<'de> for EntriesVisitor<'a> {
type Value = ();
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("audios array")
}
fn visit_seq<S: SeqAccess<'de>>(self, mut seq: S) -> Result<Self::Value, S::Error> {
self.0.reserve(
seq
.size_hint()
.unwrap_or(0)
);
while let Some(entry) = seq.next_element::<Entry>()? {
self.0.push(entry);
}
Ok(())
}
}
// Struct to collect entries.
#[derive(Debug)]
struct EntriesExtender<'a>(&'a mut Vec<Entry>);
impl<'de, 'a> DeserializeSeed<'de> for EntriesExtender<'a> {
// The return type of the `deserialize` method. This implementation
// appends onto an existing vector but does not create any new data
// structure, so the return type is ().
type Value = ();
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_seq(EntriesVisitor(self.0))
}
}
|
mod global;
pub mod metadata;
pub use global::*;
pub(crate) use metadata::is_alloced_by_malloc;
|
use crate::listnode::*;
pub fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut dummy = Box::new(ListNode::new(0));
dummy.next = head;
let mut p = dummy.as_mut();
fn core(p: &mut ListNode) {
match p.next.as_ref() {
None => {},
Some(n1) => {
match n1.next.as_ref() {
None => {},
Some(n2) => {
let mut m2 = ListNode::new(n1.val);
let mut m1 = ListNode::new(n2.val);
m2.next = n2.next.as_ref().cloned();
core(&mut m2);
m1.next = Some(Box::new(m2));
p.next = Some(Box::new(m1));
},
}
}
}
}
core(p);
dummy.next
}
#[test]
fn test_swap_pairs() {
assert_eq!(swap_pairs(arr_to_list(&[2, 1, 4, 3, 6, 5])), arr_to_list(&[1, 2, 3, 4, 5, 6]));
assert_eq!(swap_pairs(arr_to_list(&[2, 1, 4, 3, 5])), arr_to_list(&[1, 2, 3, 4, 5]));
assert_eq!(swap_pairs(arr_to_list(&[2, 1, 4, 3])), arr_to_list(&[1, 2, 3, 4]));
assert_eq!(swap_pairs(arr_to_list(&[2, 1, 4])), arr_to_list(&[1, 2, 4]));
assert_eq!(swap_pairs(arr_to_list(&[2, 1])), arr_to_list(&[1, 2]));
assert_eq!(swap_pairs(arr_to_list(&[1])), arr_to_list(&[1]));
assert_eq!(swap_pairs(arr_to_list(&[])), arr_to_list(&[]));
} |
#[doc = "Register `SUBGHZSPICR` reader"]
pub type R = crate::R<SUBGHZSPICR_SPEC>;
#[doc = "Register `SUBGHZSPICR` writer"]
pub type W = crate::W<SUBGHZSPICR_SPEC>;
#[doc = "Field `NSS` reader - sub-GHz SPI NSS control"]
pub type NSS_R = crate::BitReader<NSS_A>;
#[doc = "sub-GHz SPI NSS control\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NSS_A {
#[doc = "0: Sub-GHz SPI NSS signal at level low"]
Low = 0,
#[doc = "1: Sub-GHz SPI NSS signal is at level high"]
High = 1,
}
impl From<NSS_A> for bool {
#[inline(always)]
fn from(variant: NSS_A) -> Self {
variant as u8 != 0
}
}
impl NSS_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> NSS_A {
match self.bits {
false => NSS_A::Low,
true => NSS_A::High,
}
}
#[doc = "Sub-GHz SPI NSS signal at level low"]
#[inline(always)]
pub fn is_low(&self) -> bool {
*self == NSS_A::Low
}
#[doc = "Sub-GHz SPI NSS signal is at level high"]
#[inline(always)]
pub fn is_high(&self) -> bool {
*self == NSS_A::High
}
}
#[doc = "Field `NSS` writer - sub-GHz SPI NSS control"]
pub type NSS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, NSS_A>;
impl<'a, REG, const O: u8> NSS_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Sub-GHz SPI NSS signal at level low"]
#[inline(always)]
pub fn low(self) -> &'a mut crate::W<REG> {
self.variant(NSS_A::Low)
}
#[doc = "Sub-GHz SPI NSS signal is at level high"]
#[inline(always)]
pub fn high(self) -> &'a mut crate::W<REG> {
self.variant(NSS_A::High)
}
}
impl R {
#[doc = "Bit 15 - sub-GHz SPI NSS control"]
#[inline(always)]
pub fn nss(&self) -> NSS_R {
NSS_R::new(((self.bits >> 15) & 1) != 0)
}
}
impl W {
#[doc = "Bit 15 - sub-GHz SPI NSS control"]
#[inline(always)]
#[must_use]
pub fn nss(&mut self) -> NSS_W<SUBGHZSPICR_SPEC, 15> {
NSS_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "Power SPI3 control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`subghzspicr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`subghzspicr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SUBGHZSPICR_SPEC;
impl crate::RegisterSpec for SUBGHZSPICR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`subghzspicr::R`](R) reader structure"]
impl crate::Readable for SUBGHZSPICR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`subghzspicr::W`](W) writer structure"]
impl crate::Writable for SUBGHZSPICR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SUBGHZSPICR to value 0x8000"]
impl crate::Resettable for SUBGHZSPICR_SPEC {
const RESET_VALUE: Self::Ux = 0x8000;
}
|
//! Deserialization support for the `application/x-www-form-urlencoded` format.
use form_urlencoded::parse;
use form_urlencoded::Parse as UrlEncodedParse;
use serde::de::value::MapDeserializer;
use serde::de::Error as de_Error;
use serde::de::{self, IntoDeserializer};
use serde::forward_to_deserialize_any;
use std::borrow::Cow;
use std::io::Read;
#[doc(inline)]
pub use serde::de::value::Error;
/// Deserializes a `application/x-www-form-urlencoded` value from a `&[u8]`.
///
/// ```
/// let meal = vec![
/// ("bread".to_owned(), "baguette".to_owned()),
/// ("cheese".to_owned(), "comté".to_owned()),
/// ("meat".to_owned(), "ham".to_owned()),
/// ("fat".to_owned(), "butter".to_owned()),
/// ];
///
/// assert_eq!(
/// serde_urlencoded::from_bytes::<Vec<(String, String)>>(
/// b"bread=baguette&cheese=comt%C3%A9&meat=ham&fat=butter"),
/// Ok(meal));
/// ```
pub fn from_bytes<'de, T>(input: &'de [u8]) -> Result<T, Error>
where
T: de::Deserialize<'de>,
{
T::deserialize(Deserializer::new(parse(input)))
}
/// Deserializes a `application/x-www-form-urlencoded` value from a `&str`.
///
/// ```
/// let meal = vec![
/// ("bread".to_owned(), "baguette".to_owned()),
/// ("cheese".to_owned(), "comté".to_owned()),
/// ("meat".to_owned(), "ham".to_owned()),
/// ("fat".to_owned(), "butter".to_owned()),
/// ];
///
/// assert_eq!(
/// serde_urlencoded::from_str::<Vec<(String, String)>>(
/// "bread=baguette&cheese=comt%C3%A9&meat=ham&fat=butter"),
/// Ok(meal));
/// ```
pub fn from_str<'de, T>(input: &'de str) -> Result<T, Error>
where
T: de::Deserialize<'de>,
{
from_bytes(input.as_bytes())
}
/// Convenience function that reads all bytes from `reader` and deserializes
/// them with `from_bytes`.
pub fn from_reader<T, R>(mut reader: R) -> Result<T, Error>
where
T: de::DeserializeOwned,
R: Read,
{
let mut buf = vec![];
reader.read_to_end(&mut buf).map_err(|e| {
de::Error::custom(format_args!("could not read input: {}", e))
})?;
from_bytes(&buf)
}
/// A deserializer for the `application/x-www-form-urlencoded` format.
///
/// * Supported top-level outputs are structs, maps and sequences of pairs,
/// with or without a given length.
///
/// * Main `deserialize` methods defers to `deserialize_map`.
///
/// * Everything else but `deserialize_seq` and `deserialize_seq_fixed_size`
/// defers to `deserialize`.
pub struct Deserializer<'de> {
inner: MapDeserializer<'de, PartIterator<'de>, Error>,
}
impl<'de> Deserializer<'de> {
/// Returns a new `Deserializer`.
pub fn new(parser: UrlEncodedParse<'de>) -> Self {
Deserializer {
inner: MapDeserializer::new(PartIterator(parser)),
}
}
}
impl<'de> de::Deserializer<'de> for Deserializer<'de> {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
self.deserialize_map(visitor)
}
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_map(self.inner)
}
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_seq(self.inner)
}
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
self.inner.end()?;
visitor.visit_unit()
}
forward_to_deserialize_any! {
bool
u8
u16
u32
u64
i8
i16
i32
i64
f32
f64
char
str
string
option
bytes
byte_buf
unit_struct
newtype_struct
tuple_struct
struct
identifier
tuple
enum
ignored_any
}
}
struct PartIterator<'de>(UrlEncodedParse<'de>);
impl<'de> Iterator for PartIterator<'de> {
type Item = (Part<'de>, Part<'de>);
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|(k, v)| (Part(k), Part(v)))
}
}
struct Part<'de>(Cow<'de, str>);
impl<'de> IntoDeserializer<'de> for Part<'de> {
type Deserializer = Self;
fn into_deserializer(self) -> Self::Deserializer {
self
}
}
macro_rules! forward_parsed_value {
($($ty:ident => $method:ident,)*) => {
$(
fn $method<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor<'de>
{
match self.0.parse::<$ty>() {
Ok(val) => val.into_deserializer().$method(visitor),
Err(e) => Err(de::Error::custom(e))
}
}
)*
}
}
impl<'de> de::Deserializer<'de> for Part<'de> {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
match self.0 {
Cow::Borrowed(value) => visitor.visit_borrowed_str(value),
Cow::Owned(value) => visitor.visit_string(value),
}
}
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_some(self)
}
fn deserialize_enum<V>(
self,
_name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_enum(ValueEnumAccess(self.0))
}
fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
forward_to_deserialize_any! {
char
str
string
unit
bytes
byte_buf
unit_struct
tuple_struct
struct
identifier
tuple
ignored_any
seq
map
}
forward_parsed_value! {
bool => deserialize_bool,
u8 => deserialize_u8,
u16 => deserialize_u16,
u32 => deserialize_u32,
u64 => deserialize_u64,
i8 => deserialize_i8,
i16 => deserialize_i16,
i32 => deserialize_i32,
i64 => deserialize_i64,
f32 => deserialize_f32,
f64 => deserialize_f64,
}
}
struct ValueEnumAccess<'de>(Cow<'de, str>);
impl<'de> de::EnumAccess<'de> for ValueEnumAccess<'de> {
type Error = Error;
type Variant = UnitOnlyVariantAccess;
fn variant_seed<V>(
self,
seed: V,
) -> Result<(V::Value, Self::Variant), Self::Error>
where
V: de::DeserializeSeed<'de>,
{
let variant = seed.deserialize(self.0.into_deserializer())?;
Ok((variant, UnitOnlyVariantAccess))
}
}
struct UnitOnlyVariantAccess;
impl<'de> de::VariantAccess<'de> for UnitOnlyVariantAccess {
type Error = Error;
fn unit_variant(self) -> Result<(), Self::Error> {
Ok(())
}
fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
Err(Error::custom("expected unit variant"))
}
fn tuple_variant<V>(
self,
_len: usize,
_visitor: V,
) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
Err(Error::custom("expected unit variant"))
}
fn struct_variant<V>(
self,
_fields: &'static [&'static str],
_visitor: V,
) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
Err(Error::custom("expected unit variant"))
}
}
|
pub mod regions {
pub fn process_command() {
loop {
println!("Please input an army command or help to see available commands or back to go back!");
let mut input = String::new();
std::io::stdin()
.read_line(&mut input)
.expect("Error parsing input!");
let input: &str = input.trim();
if input == "help" {
println!("Available commands: 'print', 'move_army', 'print_beseiged', 'change_owner', 'add_building',
'remove_building'");
} else if input == "back" {
break;
} else if input == "print" {
execute::print();
} else if input == "move_army" {
execute::move_army();
} else if input == "print_beseiged" {
execute::print_beseiged();
} else if input == "change_owner" {
execute::change_owner();
} else if input == "add_building" {
execute::add_building();
} else if input == "remove_building" {
execute::remove_building();
} else {
println!("Invalid command. Use 'help' to see available.");
}
}
return;
}
pub mod execute {
pub fn print() {}
pub fn move_army() {}
pub fn print_beseiged() {}
pub fn change_owner() {}
pub fn add_building() {}
pub fn remove_building() {}
}
}
|
use ndarray::prelude::*;
use ndarray_stats::QuantileExt;
use crate::neuron::{losses::Loss, networks::Network};
pub trait Optimizer {
/// Get optimizer Loss
fn get_loss(&self) -> &Loss;
/// Optimize the network on batch
fn optimize_batch(
&self,
network: &mut Network,
batch_inputs: &[Array1<f32>],
batch_expected: &[Array1<f32>],
learning_rate: f32,
);
/// Optimize the network once
fn optimize_once(
&self,
network: &mut Network,
input: Array1<f32>,
expected: Array1<f32>,
learning_rate: f32,
) {
let batch_inputs = vec![input];
let batch_expected = vec![expected];
self.optimize_batch(network, &batch_inputs, &batch_expected, learning_rate);
}
/// Train the network
fn train(
&self,
network: &mut Network,
train: &(Vec<Array1<f32>>, Vec<Array1<f32>>),
test: &(Vec<Array1<f32>>, Vec<Array1<f32>>),
learning_rate: f32,
batch_size: usize,
epochs: usize,
) {
let (train_x, train_y) = train;
assert_eq!(train_x.len(), train_y.len(), "X and Y lengths must be equal");
let batches = train_x.len() / batch_size;
for e in 0..epochs {
// split data into batches
for b in 0..batches {
print!(
"batch {}/{} ({:.2}%) \r",
b,
batches,
(b as f32 / batches as f32) * 100.
);
let batch_inputs = &train_x[b..(b + batch_size)];
let batch_expected = &train_y[b..(b + batch_size)];
self.optimize_batch(network, batch_inputs, batch_expected, learning_rate);
}
print_network_score(&network, e, train, test, self.get_loss());
}
}
}
fn print_network_score(
network: &Network,
epoch: usize,
train: &(Vec<Array1<f32>>, Vec<Array1<f32>>),
test: &(Vec<Array1<f32>>, Vec<Array1<f32>>),
loss: &Loss,
) {
let (train_x, train_y) = train;
let (test_x, test_y) = test;
let train_samples = train_x.len();
let test_samples = test_x.len();
let mut train_loss = 0.;
let mut train_mistakes = 0.;
for (input, expected) in train_x.iter().zip(train_y.iter()) {
let prediction = network.predict(input);
if prediction.argmax().unwrap() != expected.argmax().unwrap() {
train_mistakes += 1.;
}
train_loss += loss.loss(&prediction, expected).sum();
}
let mut test_loss = 0.;
let mut test_mistakes = 0.;
for (input, expected) in test_x.iter().zip(test_y.iter()) {
let prediction = network.predict(input);
if prediction.argmax().unwrap() != expected.argmax().unwrap() {
test_mistakes += 1.;
}
test_loss += loss.loss(&prediction, expected).sum();
}
println!(
"epoch {} | train loss: {:.4} accuracy: {:.2}% | test loss: {:.4} accuracy: {:.2}%",
epoch,
train_loss / (train_samples as f32),
(1. - (train_mistakes / (train_samples as f32))) * 100.,
test_loss / (test_samples as f32),
(1. - (test_mistakes / (test_samples as f32))) * 100.,
);
}
|
pub mod ping_result_processor;
mod ping_result_processor_console_logger;
mod ping_result_processor_csv_logger;
pub mod ping_result_processor_factory;
mod ping_result_processor_json_logger;
mod ping_result_processor_latency_bucket_logger;
mod ping_result_processor_latency_scatter_logger;
mod ping_result_processor_result_scatter_logger;
mod ping_result_processor_text_logger;
#[cfg(test)]
mod ping_result_processor_test_common;
|
use vcf::population::Population;
use vcf::predictor::{Predictor, PredictorFactory, PredictorJoaoFactory};
use vcf::stream::MetadataReader;
use utils::{process_variant, split};
use itertools::Itertools;
use std::collections::HashMap;
fn predict<S, PF>(mut stream: S, population: &Population, ratio: f32, factory: PF, min_dist: f32)
where
S: MetadataReader,
PF: PredictorFactory,
<PF as PredictorFactory>::Predictor: Predictor<Prediction = f32>,
{
let unfolded = stream.unfold().unwrap();
let individuals = unfolded.individuals;
let labels = population
.labels(individuals.iter())
.map(|s| s.to_string())
.collect::<Vec<_>>();
let to_split = 0..individuals.len();
let split_index = (to_split.len() as f32 * ratio) as usize;
let (train_idxs, target_idxs) = split(to_split, split_index);
let mut cumulative_labels: Vec<HashMap<String, f32>> = vec![HashMap::new(); individuals.len()];
for polymorphism in unfolded.stream {
let genotypes = polymorphism
.genotypes()
.map(|s| process_variant(s).unwrap_or(0.0))
.collect::<Vec<_>>();
let genotypes_and_labels = genotypes.iter().cloned().zip(labels.iter().cloned());
let predictor = factory.build(genotypes_and_labels);
for &target_idx in target_idxs.iter() {
let genotype = genotypes[target_idx];
let predictions = predictor.predict(genotype);
for (prediction, confidence) in predictions {
*cumulative_labels[target_idx]
.entry(prediction.to_string())
.or_default() += confidence;
}
}
}
let relative = 0.0 < min_dist && min_dist < 1.0;
for target_idx in target_idxs {
let predictions = cumulative_labels[target_idx]
.iter()
.sorted_by(|(_, f1), (_, f2)| f2.partial_cmp(f1).unwrap());
let mut diff = (predictions[0].1 - predictions[1].1) as f32;
if relative {
diff /= predictions[0].1;
}
let final_prediction = if diff >= min_dist {
predictions[0].0
} else {
"---"
};
println!(
"{}\t{}\t{}",
individuals[target_idx], labels[target_idx], final_prediction
)
}
}
pub fn main() -> ::std::io::Result<()> {
use std::fs::File;
use std::io::{stdin, BufReader};
use vcf::stream::from_text_stream;
let predictor_factory = PredictorJoaoFactory { threshold: 0.0 };
let file = File::open("../populations/superpopulations.txt")?;
let reader = BufReader::new(file);
let population = Population::parse(reader)?;
let stdin = stdin();
let handle = stdin.lock();
let stream = from_text_stream(handle);
predict(stream, &population, 0.1, predictor_factory, 0.0);
Ok(())
}
|
use std::{
collections::HashMap,
future::Future,
io,
pin::Pin,
process::exit,
sync::{Arc, Weak},
task::{Context, Poll},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use byteorder::{BigEndian, ByteOrder};
use bytes::Bytes;
use futures_core::TryStream;
use futures_util::{future, ready, StreamExt, TryStreamExt};
use num_traits::FromPrimitive;
use once_cell::sync::OnceCell;
use parking_lot::RwLock;
use quick_xml::events::Event;
use thiserror::Error;
use tokio::{sync::mpsc, time::Instant};
use tokio_stream::wrappers::UnboundedReceiverStream;
use crate::{
apresolve::ApResolver,
audio_key::AudioKeyManager,
authentication::Credentials,
cache::Cache,
channel::ChannelManager,
config::SessionConfig,
connection::{self, AuthenticationError},
http_client::HttpClient,
mercury::MercuryManager,
packet::PacketType,
protocol::keyexchange::ErrorCode,
spclient::SpClient,
token::TokenProvider,
Error,
};
#[derive(Debug, Error)]
pub enum SessionError {
#[error(transparent)]
AuthenticationError(#[from] AuthenticationError),
#[error("Cannot create session: {0}")]
IoError(#[from] io::Error),
#[error("Session is not connected")]
NotConnected,
#[error("packet {0} unknown")]
Packet(u8),
}
impl From<SessionError> for Error {
fn from(err: SessionError) -> Self {
match err {
SessionError::AuthenticationError(_) => Error::unauthenticated(err),
SessionError::IoError(_) => Error::unavailable(err),
SessionError::NotConnected => Error::unavailable(err),
SessionError::Packet(_) => Error::unimplemented(err),
}
}
}
pub type UserAttributes = HashMap<String, String>;
#[derive(Debug, Clone, Default)]
pub struct UserData {
pub country: String,
pub canonical_username: String,
pub attributes: UserAttributes,
}
#[derive(Debug, Clone, Default)]
struct SessionData {
client_id: String,
client_name: String,
client_brand_name: String,
client_model_name: String,
connection_id: String,
time_delta: i64,
invalid: bool,
user_data: UserData,
last_ping: Option<Instant>,
}
struct SessionInternal {
config: SessionConfig,
data: RwLock<SessionData>,
http_client: HttpClient,
tx_connection: OnceCell<mpsc::UnboundedSender<(u8, Vec<u8>)>>,
apresolver: OnceCell<ApResolver>,
audio_key: OnceCell<AudioKeyManager>,
channel: OnceCell<ChannelManager>,
mercury: OnceCell<MercuryManager>,
spclient: OnceCell<SpClient>,
token_provider: OnceCell<TokenProvider>,
cache: Option<Arc<Cache>>,
handle: tokio::runtime::Handle,
}
/// A shared reference to a Spotify session.
///
/// After instantiating, you need to login via [Session::connect].
/// You can either implement the whole playback logic yourself by using
/// this structs interface directly or hand it to a
/// `Player`.
///
/// *Note*: [Session] instances cannot yet be reused once invalidated. After
/// an unexpectedly closed connection, you'll need to create a new [Session].
#[derive(Clone)]
pub struct Session(Arc<SessionInternal>);
impl Session {
pub fn new(config: SessionConfig, cache: Option<Cache>) -> Self {
let http_client = HttpClient::new(config.proxy.as_ref());
debug!("new Session");
let session_data = SessionData {
client_id: config.client_id.clone(),
..SessionData::default()
};
Self(Arc::new(SessionInternal {
config,
data: RwLock::new(session_data),
http_client,
tx_connection: OnceCell::new(),
cache: cache.map(Arc::new),
apresolver: OnceCell::new(),
audio_key: OnceCell::new(),
channel: OnceCell::new(),
mercury: OnceCell::new(),
spclient: OnceCell::new(),
token_provider: OnceCell::new(),
handle: tokio::runtime::Handle::current(),
}))
}
pub async fn connect(
&self,
credentials: Credentials,
store_credentials: bool,
) -> Result<(), Error> {
let (reusable_credentials, transport) = loop {
let ap = self.apresolver().resolve("accesspoint").await?;
info!("Connecting to AP \"{}:{}\"", ap.0, ap.1);
let mut transport =
connection::connect(&ap.0, ap.1, self.config().proxy.as_ref()).await?;
match connection::authenticate(
&mut transport,
credentials.clone(),
&self.config().device_id,
)
.await
{
Ok(creds) => break (creds, transport),
Err(e) => {
if let Some(AuthenticationError::LoginFailed(ErrorCode::TryAnotherAP)) =
e.error.downcast_ref::<AuthenticationError>()
{
warn!("Instructed to try another access point...");
continue;
} else {
return Err(e);
}
}
}
};
info!("Authenticated as \"{}\" !", reusable_credentials.username);
self.set_username(&reusable_credentials.username);
if let Some(cache) = self.cache() {
if store_credentials {
let cred_changed = cache
.credentials()
.map(|c| c != reusable_credentials)
.unwrap_or(true);
if cred_changed {
cache.save_credentials(&reusable_credentials);
}
}
}
let (tx_connection, rx_connection) = mpsc::unbounded_channel();
self.0
.tx_connection
.set(tx_connection)
.map_err(|_| SessionError::NotConnected)?;
let (sink, stream) = transport.split();
let sender_task = UnboundedReceiverStream::new(rx_connection)
.map(Ok)
.forward(sink);
let receiver_task = DispatchTask(stream, self.weak());
let timeout_task = Session::session_timeout(self.weak());
tokio::spawn(async move {
let result = future::try_join3(sender_task, receiver_task, timeout_task).await;
if let Err(e) = result {
error!("{}", e);
}
});
Ok(())
}
pub fn apresolver(&self) -> &ApResolver {
self.0
.apresolver
.get_or_init(|| ApResolver::new(self.weak()))
}
pub fn audio_key(&self) -> &AudioKeyManager {
self.0
.audio_key
.get_or_init(|| AudioKeyManager::new(self.weak()))
}
pub fn channel(&self) -> &ChannelManager {
self.0
.channel
.get_or_init(|| ChannelManager::new(self.weak()))
}
pub fn http_client(&self) -> &HttpClient {
&self.0.http_client
}
pub fn mercury(&self) -> &MercuryManager {
self.0
.mercury
.get_or_init(|| MercuryManager::new(self.weak()))
}
pub fn spclient(&self) -> &SpClient {
self.0.spclient.get_or_init(|| SpClient::new(self.weak()))
}
pub fn token_provider(&self) -> &TokenProvider {
self.0
.token_provider
.get_or_init(|| TokenProvider::new(self.weak()))
}
/// Returns an error, when we haven't received a ping for too long (2 minutes),
/// which means that we silently lost connection to Spotify servers.
async fn session_timeout(session: SessionWeak) -> io::Result<()> {
// pings are sent every 2 minutes and a 5 second margin should be fine
const SESSION_TIMEOUT: Duration = Duration::from_secs(125);
while let Some(session) = session.try_upgrade() {
if session.is_invalid() {
break;
}
let last_ping = session.0.data.read().last_ping.unwrap_or_else(Instant::now);
if last_ping.elapsed() >= SESSION_TIMEOUT {
session.shutdown();
// TODO: Optionally reconnect (with cached/last credentials?)
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"session lost connection to server",
));
}
// drop the strong reference before sleeping
drop(session);
// a potential timeout cannot occur at least until SESSION_TIMEOUT after the last_ping
tokio::time::sleep_until(last_ping + SESSION_TIMEOUT).await;
}
Ok(())
}
pub fn time_delta(&self) -> i64 {
self.0.data.read().time_delta
}
pub fn spawn<T>(&self, task: T)
where
T: Future + Send + 'static,
T::Output: Send + 'static,
{
self.0.handle.spawn(task);
}
fn debug_info(&self) {
debug!(
"Session strong={} weak={}",
Arc::strong_count(&self.0),
Arc::weak_count(&self.0)
);
}
fn check_catalogue(attributes: &UserAttributes) {
if let Some(account_type) = attributes.get("type") {
if account_type != "premium" {
error!("librespot does not support {:?} accounts.", account_type);
info!("Please support Spotify and your artists and sign up for a premium account.");
// TODO: logout instead of exiting
exit(1);
}
}
}
fn dispatch(&self, cmd: u8, data: Bytes) -> Result<(), Error> {
use PacketType::*;
let packet_type = FromPrimitive::from_u8(cmd);
let cmd = match packet_type {
Some(cmd) => cmd,
None => {
trace!("Ignoring unknown packet {:x}", cmd);
return Err(SessionError::Packet(cmd).into());
}
};
match packet_type {
Some(Ping) => {
let server_timestamp = BigEndian::read_u32(data.as_ref()) as i64;
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or(Duration::ZERO)
.as_secs() as i64;
{
let mut data = self.0.data.write();
data.time_delta = server_timestamp.saturating_sub(timestamp);
data.last_ping = Some(Instant::now());
}
self.debug_info();
self.send_packet(Pong, vec![0, 0, 0, 0])
}
Some(CountryCode) => {
let country = String::from_utf8(data.as_ref().to_owned())?;
info!("Country: {:?}", country);
self.0.data.write().user_data.country = country;
Ok(())
}
Some(StreamChunkRes) | Some(ChannelError) => self.channel().dispatch(cmd, data),
Some(AesKey) | Some(AesKeyError) => self.audio_key().dispatch(cmd, data),
Some(MercuryReq) | Some(MercurySub) | Some(MercuryUnsub) | Some(MercuryEvent) => {
self.mercury().dispatch(cmd, data)
}
Some(ProductInfo) => {
let data = std::str::from_utf8(&data)?;
let mut reader = quick_xml::Reader::from_str(data);
let mut buf = Vec::new();
let mut current_element = String::new();
let mut user_attributes: UserAttributes = HashMap::new();
loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref element)) => {
current_element = std::str::from_utf8(element)?.to_owned()
}
Ok(Event::End(_)) => {
current_element = String::new();
}
Ok(Event::Text(ref value)) => {
if !current_element.is_empty() {
let _ = user_attributes
.insert(current_element.clone(), value.unescape()?.to_string());
}
}
Ok(Event::Eof) => break,
Ok(_) => (),
Err(e) => warn!(
"Error parsing XML at position {}: {:?}",
reader.buffer_position(),
e
),
}
}
trace!("Received product info: {:#?}", user_attributes);
Self::check_catalogue(&user_attributes);
self.0.data.write().user_data.attributes = user_attributes;
Ok(())
}
Some(PongAck)
| Some(SecretBlock)
| Some(LegacyWelcome)
| Some(UnknownDataAllZeros)
| Some(LicenseVersion) => Ok(()),
_ => {
trace!("Ignoring {:?} packet with data {:#?}", cmd, data);
Err(SessionError::Packet(cmd as u8).into())
}
}
}
pub fn send_packet(&self, cmd: PacketType, data: Vec<u8>) -> Result<(), Error> {
match self.0.tx_connection.get() {
Some(tx) => Ok(tx.send((cmd as u8, data))?),
None => Err(SessionError::NotConnected.into()),
}
}
pub fn cache(&self) -> Option<&Arc<Cache>> {
self.0.cache.as_ref()
}
pub fn config(&self) -> &SessionConfig {
&self.0.config
}
// This clones a fairly large struct, so use a specific getter or setter unless
// you need more fields at once, in which case this can spare multiple `read`
// locks.
pub fn user_data(&self) -> UserData {
self.0.data.read().user_data.clone()
}
pub fn device_id(&self) -> &str {
&self.config().device_id
}
pub fn client_id(&self) -> String {
self.0.data.read().client_id.clone()
}
pub fn set_client_id(&self, client_id: &str) {
self.0.data.write().client_id = client_id.to_owned();
}
pub fn client_name(&self) -> String {
self.0.data.read().client_name.clone()
}
pub fn set_client_name(&self, client_name: &str) {
self.0.data.write().client_name = client_name.to_owned();
}
pub fn client_brand_name(&self) -> String {
self.0.data.read().client_brand_name.clone()
}
pub fn set_client_brand_name(&self, client_brand_name: &str) {
self.0.data.write().client_brand_name = client_brand_name.to_owned();
}
pub fn client_model_name(&self) -> String {
self.0.data.read().client_model_name.clone()
}
pub fn set_client_model_name(&self, client_model_name: &str) {
self.0.data.write().client_model_name = client_model_name.to_owned();
}
pub fn connection_id(&self) -> String {
self.0.data.read().connection_id.clone()
}
pub fn set_connection_id(&self, connection_id: &str) {
self.0.data.write().connection_id = connection_id.to_owned();
}
pub fn username(&self) -> String {
self.0.data.read().user_data.canonical_username.clone()
}
pub fn set_username(&self, username: &str) {
self.0.data.write().user_data.canonical_username = username.to_owned();
}
pub fn country(&self) -> String {
self.0.data.read().user_data.country.clone()
}
pub fn filter_explicit_content(&self) -> bool {
match self.get_user_attribute("filter-explicit-content") {
Some(value) => matches!(&*value, "1"),
None => false,
}
}
pub fn autoplay(&self) -> bool {
if let Some(overide) = self.config().autoplay {
return overide;
}
match self.get_user_attribute("autoplay") {
Some(value) => matches!(&*value, "1"),
None => false,
}
}
pub fn set_user_attribute(&self, key: &str, value: &str) -> Option<String> {
let mut dummy_attributes = UserAttributes::new();
dummy_attributes.insert(key.to_owned(), value.to_owned());
Self::check_catalogue(&dummy_attributes);
self.0
.data
.write()
.user_data
.attributes
.insert(key.to_owned(), value.to_owned())
}
pub fn set_user_attributes(&self, attributes: UserAttributes) {
Self::check_catalogue(&attributes);
self.0.data.write().user_data.attributes.extend(attributes)
}
pub fn get_user_attribute(&self, key: &str) -> Option<String> {
self.0
.data
.read()
.user_data
.attributes
.get(key)
.map(Clone::clone)
}
fn weak(&self) -> SessionWeak {
SessionWeak(Arc::downgrade(&self.0))
}
pub fn shutdown(&self) {
debug!("Invalidating session");
self.0.data.write().invalid = true;
self.mercury().shutdown();
self.channel().shutdown();
}
pub fn is_invalid(&self) -> bool {
self.0.data.read().invalid
}
}
#[derive(Clone)]
pub struct SessionWeak(Weak<SessionInternal>);
impl SessionWeak {
fn try_upgrade(&self) -> Option<Session> {
self.0.upgrade().map(Session)
}
pub(crate) fn upgrade(&self) -> Session {
self.try_upgrade()
.expect("session was dropped and so should have this component")
}
}
impl Drop for SessionInternal {
fn drop(&mut self) {
debug!("drop Session");
}
}
struct DispatchTask<S>(S, SessionWeak)
where
S: TryStream<Ok = (u8, Bytes)> + Unpin;
impl<S> Future for DispatchTask<S>
where
S: TryStream<Ok = (u8, Bytes)> + Unpin,
<S as TryStream>::Ok: std::fmt::Debug,
{
type Output = Result<(), S::Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let session = match self.1.try_upgrade() {
Some(session) => session,
None => return Poll::Ready(Ok(())),
};
loop {
let (cmd, data) = match ready!(self.0.try_poll_next_unpin(cx)) {
Some(Ok(t)) => t,
None => {
warn!("Connection to server closed.");
session.shutdown();
return Poll::Ready(Ok(()));
}
Some(Err(e)) => {
session.shutdown();
return Poll::Ready(Err(e));
}
};
if let Err(e) = session.dispatch(cmd, data) {
debug!("could not dispatch command: {}", e);
}
}
}
}
impl<S> Drop for DispatchTask<S>
where
S: TryStream<Ok = (u8, Bytes)> + Unpin,
{
fn drop(&mut self) {
debug!("drop Dispatch");
}
}
|
pub mod iterm;
|
use std::cell::RefCell;
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::rc::Rc;
mod environment;
mod execute;
mod object;
mod parser;
mod scanner;
#[cfg(test)]
mod test;
mod value;
use crate::environment::Environment;
use crate::execute::execute_node;
use crate::parser::Parser;
use crate::scanner::scan;
use crate::value::Value;
fn println(_base: Option<Value>, args: Vec<Value>) -> Value {
println!("println: {:?}", args);
Value::Nothing
}
fn main() -> Result<(), Box<dyn Error>> {
let name = env::args().nth(1).ok_or("missing file argument")?;
let mut f = File::open(name)?;
let mut buffer = String::new();
f.read_to_string(&mut buffer)?;
let tokens = scan(&buffer)?;
println!("{:?}", tokens);
let mut parser = Parser::new(tokens);
let node = parser.parse()?;
println!("{:?}", node);
let env = Rc::new(RefCell::new(Environment::new()));
env.borrow_mut()
.define("println".to_string(), Value::NativeFunction(println));
match execute_node(&Box::new(node), &env) {
Ok(v) => println!("ok: {}", v),
Err(e) => println!("error: {:?}", e),
}
// and more! See the other methods for more details.
Ok(())
}
|
// Javascript object style
struct Point {
x: f64,
y: f64
}
struct Line {
start: Point,
end: Point
}
fn structures() {
let p = Point {x: 3.2, y:4.3};
println!("point at ({}, {})", p.x, p.y);
}
enum Color
{
Red, Green, Blue,
RGBColor(u8, u8, u8), // tuple
Cmyk{cyan:u8, magenta:u8, yellow:u8, black:u8}, // struct
}
fn enums(c:Color) {
println!("enums test --------------------------");
match c {
Color::Red => println!("color is red"),
Color::Green => println!("color is green"),
Color::RGBColor(0,0,0) => println!("black"),
Color::RGBColor(r,g,b) => println!("r,g,b({}, {}, {})", r, g, b),
Color::Cmyk{cyan:_, magenta:_, yellow:_, black:255} => println!("color is black"),
Color::Cmyk{black:255, ..} => println!("color is black"), // means the same as the line above, cause unreachable pattern warning
_ => println!("unkown color"),
}
}
union IntOrFloat
{
i: i32,
f: f32
}
fn union_test(iof:IntOrFloat){
println!("union_test ---------------------");
let value = unsafe {iof.i};
// let value = iof.i;
println!("iof.i = {}", value);
unsafe {
match iof {
IntOrFloat {i:42} => println!("value is 42"),
IntOrFloat {ref f} => println!("float is {}", f) // "ref" means pass by reference instead of by value
}
}
}
fn option_test(x:f32, y:f32) {
println!("option_test -----------------");
let result =
if y != 0.0 {Some(x/y)} else {None};
match result {
Some(z) => println!("{} / {} = {}", x, y, z),
None => println!("Cannot devide by 0.0")
}
if let Some(z) = result { // compare option
println!("result = {}", z)
}
}
fn array_test() { // fixed size
println!("array test ----------------------");
let mut a:[i32;5] = [1,2,3,4,5];
let b = [1,2,3,4,5];
a[0] = 322;
println!("{:?}", a); // rust style loop, not seen in other languages!
if a != [1,2,3,4,5] {
println!("not equal [1,2,3,4,5]") // not seen in other languages!
}
let b = [1u16; 10]; // "1" is initial value, "u16" is type casting
println!("{:?}", b); //[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
let c:[[u16; 3]; 2] = [
[1,2,3],
[4,5,6]
];
println!("{:?}", c);
for i in 0..c.len() {
for j in 0..c[i].len() {
print!("c[{}, {}] = {}; ", i, j, c[i][j]);
}
}
}
fn slice_test(slice: &mut[i16]) {
println!("first element = {}, len = {}", slice[0], slice.len());
slice[0] = 198;
}
fn sum_product(x:u16, y:u16) -> (u16, f32) {
(x + y, 1.0 * 3.2)
}
// struct tuple
struct Colour(u8, u8, u8);
fn tuple_test() {
println!("tuple test ---------------------------");
let x = 3;
let y = 4;
let sp = {(x + y, x as f32 * y as f32 )};
println!("{:?}", sp);
println!("{0} + {1} = {2}, {0} * {1} = {3}", x, y, sp.0, sp.1);
// destructure
let (a, b) = sp;
let sp2 = sum_product(2, 7);
let combined = (sp, sp2);
println!("last element is {}", (combined.1).1); //nested tuple
let single_ele_tpl = (32, ); //single element tuple, python similarity
let red = Colour(255, 0, 0);
println!("red is {}, {}, {}", red.0, red.1, red.2);
}
struct PointG<T, V> {
x: T,
y: V
}
struct LineG<T,V> {
start: PointG<T,V>,
end: PointG<T,V>
}
fn generic_test() {
let a: PointG<i32, i16> = PointG {x:2, y:4};
let b = PointG {x:2, y:4};
let line_c = LineG {start: a, end: b};
}
pub fn data_structure() {
generic_test();
tuple_test();
let mut data = [1,2,3,4,5];
slice_test(&mut data[1..4]);
println!("{:?}", data); // [1, 198, 3, 4, 5]
slice_test(&mut data);
println!("{:?}", data); // [198, 198, 3, 4, 5]
array_test();
let x = 3.0;
let mut y = 0.0;
option_test(x, y);
y = 2.0;
option_test(x, y);
let mut iof = IntOrFloat{i:42};
union_test(iof);
iof.i = 22;
union_test(iof); //float is 0.000000000000000000000000000000000000000000031
let c:Color = Color::Red;
enums(c);
let c1:Color = Color::RGBColor(1,2,3);
enums(c1);
let c2:Color = Color::Cmyk{cyan:0, magenta:123, yellow:2, black:0};
enums(c2);
structures();
} |
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CQPAUSE {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `CQMASK`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CQMASKR {
#[doc = "CQ Stop Flag. When set, CQ processing will complete. value."]
STOP,
#[doc = "CQ Index Pointers (CURIDX/ENDIDX) match. value."]
CQIDX,
#[doc = "DMA Complete Status (hardwired DMACPL bit in DMASTAT) value."]
DMACPL,
#[doc = "PIO Operation completed (STATUS bit in CTRL register) value."]
CMDCPL,
#[doc = "IOM Buffer 1 Ready Status (from selected IOM). This status is the result of XOR'ing the IOM0START with the incoming status from the IOM. When high, MSPI can send to the buffer. value."]
IOM1READY,
#[doc = "IOM Buffer 0 Ready Status (from selected IOM). This status is the result of XOR'ing the IOM0START with the incoming status from the IOM. When high, MSPI can send to the buffer. value."]
IOM0READY,
#[doc = "Software flag 7. Can be used by software to start/pause operations value."]
SWFLAG7,
#[doc = "Software flag 6. Can be used by software to start/pause operatoins value."]
SWFLAG6,
#[doc = "Software flag 5. Can be used by software to start/pause operations value."]
SWFLAG5,
#[doc = "Software flag 4. Can be used by software to start/pause operatoins value."]
SWFLAG4,
#[doc = "Software flag 3. Can be used by software to start/pause operations value."]
SWFLAG3,
#[doc = "Software flag 2. Can be used by software to start/pause operatoins value."]
SWFLAG2,
#[doc = "Software flag 1. Can be used by software to start/pause operations value."]
SWFLAG1,
#[doc = "Software flag 0. Can be used by software to start/pause operatoins value."]
SWFLAG0,
#[doc = r" Reserved"]
_Reserved(u16),
}
impl CQMASKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u16 {
match *self {
CQMASKR::STOP => 32768,
CQMASKR::CQIDX => 16384,
CQMASKR::DMACPL => 2048,
CQMASKR::CMDCPL => 1024,
CQMASKR::IOM1READY => 512,
CQMASKR::IOM0READY => 256,
CQMASKR::SWFLAG7 => 128,
CQMASKR::SWFLAG6 => 64,
CQMASKR::SWFLAG5 => 32,
CQMASKR::SWFLAG4 => 16,
CQMASKR::SWFLAG3 => 8,
CQMASKR::SWFLAG2 => 4,
CQMASKR::SWFLAG1 => 2,
CQMASKR::SWFLAG0 => 1,
CQMASKR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u16) -> CQMASKR {
match value {
32768 => CQMASKR::STOP,
16384 => CQMASKR::CQIDX,
2048 => CQMASKR::DMACPL,
1024 => CQMASKR::CMDCPL,
512 => CQMASKR::IOM1READY,
256 => CQMASKR::IOM0READY,
128 => CQMASKR::SWFLAG7,
64 => CQMASKR::SWFLAG6,
32 => CQMASKR::SWFLAG5,
16 => CQMASKR::SWFLAG4,
8 => CQMASKR::SWFLAG3,
4 => CQMASKR::SWFLAG2,
2 => CQMASKR::SWFLAG1,
1 => CQMASKR::SWFLAG0,
i => CQMASKR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `STOP`"]
#[inline]
pub fn is_stop(&self) -> bool {
*self == CQMASKR::STOP
}
#[doc = "Checks if the value of the field is `CQIDX`"]
#[inline]
pub fn is_cqidx(&self) -> bool {
*self == CQMASKR::CQIDX
}
#[doc = "Checks if the value of the field is `DMACPL`"]
#[inline]
pub fn is_dmacpl(&self) -> bool {
*self == CQMASKR::DMACPL
}
#[doc = "Checks if the value of the field is `CMDCPL`"]
#[inline]
pub fn is_cmdcpl(&self) -> bool {
*self == CQMASKR::CMDCPL
}
#[doc = "Checks if the value of the field is `IOM1READY`"]
#[inline]
pub fn is_iom1ready(&self) -> bool {
*self == CQMASKR::IOM1READY
}
#[doc = "Checks if the value of the field is `IOM0READY`"]
#[inline]
pub fn is_iom0ready(&self) -> bool {
*self == CQMASKR::IOM0READY
}
#[doc = "Checks if the value of the field is `SWFLAG7`"]
#[inline]
pub fn is_swflag7(&self) -> bool {
*self == CQMASKR::SWFLAG7
}
#[doc = "Checks if the value of the field is `SWFLAG6`"]
#[inline]
pub fn is_swflag6(&self) -> bool {
*self == CQMASKR::SWFLAG6
}
#[doc = "Checks if the value of the field is `SWFLAG5`"]
#[inline]
pub fn is_swflag5(&self) -> bool {
*self == CQMASKR::SWFLAG5
}
#[doc = "Checks if the value of the field is `SWFLAG4`"]
#[inline]
pub fn is_swflag4(&self) -> bool {
*self == CQMASKR::SWFLAG4
}
#[doc = "Checks if the value of the field is `SWFLAG3`"]
#[inline]
pub fn is_swflag3(&self) -> bool {
*self == CQMASKR::SWFLAG3
}
#[doc = "Checks if the value of the field is `SWFLAG2`"]
#[inline]
pub fn is_swflag2(&self) -> bool {
*self == CQMASKR::SWFLAG2
}
#[doc = "Checks if the value of the field is `SWFLAG1`"]
#[inline]
pub fn is_swflag1(&self) -> bool {
*self == CQMASKR::SWFLAG1
}
#[doc = "Checks if the value of the field is `SWFLAG0`"]
#[inline]
pub fn is_swflag0(&self) -> bool {
*self == CQMASKR::SWFLAG0
}
}
#[doc = "Values that can be written to the field `CQMASK`"]
pub enum CQMASKW {
#[doc = "CQ Stop Flag. When set, CQ processing will complete. value."]
STOP,
#[doc = "CQ Index Pointers (CURIDX/ENDIDX) match. value."]
CQIDX,
#[doc = "DMA Complete Status (hardwired DMACPL bit in DMASTAT) value."]
DMACPL,
#[doc = "PIO Operation completed (STATUS bit in CTRL register) value."]
CMDCPL,
#[doc = "IOM Buffer 1 Ready Status (from selected IOM). This status is the result of XOR'ing the IOM0START with the incoming status from the IOM. When high, MSPI can send to the buffer. value."]
IOM1READY,
#[doc = "IOM Buffer 0 Ready Status (from selected IOM). This status is the result of XOR'ing the IOM0START with the incoming status from the IOM. When high, MSPI can send to the buffer. value."]
IOM0READY,
#[doc = "Software flag 7. Can be used by software to start/pause operations value."]
SWFLAG7,
#[doc = "Software flag 6. Can be used by software to start/pause operatoins value."]
SWFLAG6,
#[doc = "Software flag 5. Can be used by software to start/pause operations value."]
SWFLAG5,
#[doc = "Software flag 4. Can be used by software to start/pause operatoins value."]
SWFLAG4,
#[doc = "Software flag 3. Can be used by software to start/pause operations value."]
SWFLAG3,
#[doc = "Software flag 2. Can be used by software to start/pause operatoins value."]
SWFLAG2,
#[doc = "Software flag 1. Can be used by software to start/pause operations value."]
SWFLAG1,
#[doc = "Software flag 0. Can be used by software to start/pause operatoins value."]
SWFLAG0,
}
impl CQMASKW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u16 {
match *self {
CQMASKW::STOP => 32768,
CQMASKW::CQIDX => 16384,
CQMASKW::DMACPL => 2048,
CQMASKW::CMDCPL => 1024,
CQMASKW::IOM1READY => 512,
CQMASKW::IOM0READY => 256,
CQMASKW::SWFLAG7 => 128,
CQMASKW::SWFLAG6 => 64,
CQMASKW::SWFLAG5 => 32,
CQMASKW::SWFLAG4 => 16,
CQMASKW::SWFLAG3 => 8,
CQMASKW::SWFLAG2 => 4,
CQMASKW::SWFLAG1 => 2,
CQMASKW::SWFLAG0 => 1,
}
}
}
#[doc = r" Proxy"]
pub struct _CQMASKW<'a> {
w: &'a mut W,
}
impl<'a> _CQMASKW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: CQMASKW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "CQ Stop Flag. When set, CQ processing will complete. value."]
#[inline]
pub fn stop(self) -> &'a mut W {
self.variant(CQMASKW::STOP)
}
#[doc = "CQ Index Pointers (CURIDX/ENDIDX) match. value."]
#[inline]
pub fn cqidx(self) -> &'a mut W {
self.variant(CQMASKW::CQIDX)
}
#[doc = "DMA Complete Status (hardwired DMACPL bit in DMASTAT) value."]
#[inline]
pub fn dmacpl(self) -> &'a mut W {
self.variant(CQMASKW::DMACPL)
}
#[doc = "PIO Operation completed (STATUS bit in CTRL register) value."]
#[inline]
pub fn cmdcpl(self) -> &'a mut W {
self.variant(CQMASKW::CMDCPL)
}
#[doc = "IOM Buffer 1 Ready Status (from selected IOM). This status is the result of XOR'ing the IOM0START with the incoming status from the IOM. When high, MSPI can send to the buffer. value."]
#[inline]
pub fn iom1ready(self) -> &'a mut W {
self.variant(CQMASKW::IOM1READY)
}
#[doc = "IOM Buffer 0 Ready Status (from selected IOM). This status is the result of XOR'ing the IOM0START with the incoming status from the IOM. When high, MSPI can send to the buffer. value."]
#[inline]
pub fn iom0ready(self) -> &'a mut W {
self.variant(CQMASKW::IOM0READY)
}
#[doc = "Software flag 7. Can be used by software to start/pause operations value."]
#[inline]
pub fn swflag7(self) -> &'a mut W {
self.variant(CQMASKW::SWFLAG7)
}
#[doc = "Software flag 6. Can be used by software to start/pause operatoins value."]
#[inline]
pub fn swflag6(self) -> &'a mut W {
self.variant(CQMASKW::SWFLAG6)
}
#[doc = "Software flag 5. Can be used by software to start/pause operations value."]
#[inline]
pub fn swflag5(self) -> &'a mut W {
self.variant(CQMASKW::SWFLAG5)
}
#[doc = "Software flag 4. Can be used by software to start/pause operatoins value."]
#[inline]
pub fn swflag4(self) -> &'a mut W {
self.variant(CQMASKW::SWFLAG4)
}
#[doc = "Software flag 3. Can be used by software to start/pause operations value."]
#[inline]
pub fn swflag3(self) -> &'a mut W {
self.variant(CQMASKW::SWFLAG3)
}
#[doc = "Software flag 2. Can be used by software to start/pause operatoins value."]
#[inline]
pub fn swflag2(self) -> &'a mut W {
self.variant(CQMASKW::SWFLAG2)
}
#[doc = "Software flag 1. Can be used by software to start/pause operations value."]
#[inline]
pub fn swflag1(self) -> &'a mut W {
self.variant(CQMASKW::SWFLAG1)
}
#[doc = "Software flag 0. Can be used by software to start/pause operatoins value."]
#[inline]
pub fn swflag0(self) -> &'a mut W {
self.variant(CQMASKW::SWFLAG0)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
const MASK: u16 = 65535;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:15 - CQ will pause processing until all specified events are satisfied."]
#[inline]
pub fn cqmask(&self) -> CQMASKR {
CQMASKR::_from({
const MASK: u16 = 65535;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u16
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:15 - CQ will pause processing until all specified events are satisfied."]
#[inline]
pub fn cqmask(&mut self) -> _CQMASKW {
_CQMASKW { w: self }
}
}
|
use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, TokenData, Validation};
use serde::{Deserialize, Serialize};
use crate::config::CONFIG;
use crate::jwks::FIREBASE_JWKS;
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub aud: String,
pub exp: usize,
pub iat: usize,
pub iss: String,
pub sub: String,
}
pub fn verify_id_token(id_token: String) -> Result<TokenData<Claims>, String> {
let header = match decode_header(&id_token) {
Ok(header) => header,
Err(_) => return Err(String::from("couldn't decode header")),
};
let kid = match header.kid {
Some(kid) => kid,
None => return Err(String::from("kid is not found")),
};
let jwks = FIREBASE_JWKS.get().unwrap();
let jwk = match jwks.get_key(kid) {
Some(jwk) => jwk,
None => return Err(String::from("JWK is not found")),
};
let project_id = &CONFIG.firebase_project_id;
let mut validation = Validation {
validate_exp: true,
iss: Some("https://securetoken.google.com/".to_string() + project_id),
..Validation::new(Algorithm::RS256)
};
validation.set_audience(&[project_id]);
let decoding_key = DecodingKey::from_rsa_components(&jwk.n, &jwk.e);
let decoded_token = decode::<Claims>(&id_token, &decoding_key, &validation);
let token_data = match decoded_token {
Ok(token) => token,
Err(e) => return Err(format!("{}", e)),
};
Ok(token_data)
}
|
#[cfg(test)]
mod tests {
use lib::get_sum_numbers_combinations_for_amount;
#[test]
fn tests_get_sum_numbers_combinations_for_amount() {
let allowed_numbers: [u8; 4] = [1, 2, 4, 5];
let amount: u32 = 5;
assert_eq!(
get_sum_numbers_combinations_for_amount(
&allowed_numbers,
amount,
),
vec![
vec![1, 1, 1, 1, 1],
vec![1, 1, 1, 2],
vec![1, 2, 2],
vec![1, 4],
vec![5],
]
);
}
#[test]
fn tests_get_sum_numbers_combinations_for_amount_higher_amount() {
let allowed_numbers: [u8; 3] = [2, 4, 5];
let amount: u32 = 15;
assert_eq!(
get_sum_numbers_combinations_for_amount(
&allowed_numbers,
amount,
),
vec![
vec![2, 2, 2, 2, 2, 5],
vec![2, 2, 2, 4, 5],
vec![2, 4, 4, 5],
vec![5, 5, 5],
]
);
}
}
|
#[doc = "Register `AHB2SMENR` reader"]
pub type R = crate::R<AHB2SMENR_SPEC>;
#[doc = "Register `AHB2SMENR` writer"]
pub type W = crate::W<AHB2SMENR_SPEC>;
#[doc = "Field `GPIOASMEN` reader - IO port A clocks enable during Sleep and Stop modes"]
pub type GPIOASMEN_R = crate::BitReader<GPIOASMEN_A>;
#[doc = "IO port A clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GPIOASMEN_A {
#[doc = "0: IO port x clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: IO port x clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<GPIOASMEN_A> for bool {
#[inline(always)]
fn from(variant: GPIOASMEN_A) -> Self {
variant as u8 != 0
}
}
impl GPIOASMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> GPIOASMEN_A {
match self.bits {
false => GPIOASMEN_A::Disabled,
true => GPIOASMEN_A::Enabled,
}
}
#[doc = "IO port x clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == GPIOASMEN_A::Disabled
}
#[doc = "IO port x clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == GPIOASMEN_A::Enabled
}
}
#[doc = "Field `GPIOASMEN` writer - IO port A clocks enable during Sleep and Stop modes"]
pub type GPIOASMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, GPIOASMEN_A>;
impl<'a, REG, const O: u8> GPIOASMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "IO port x clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(GPIOASMEN_A::Disabled)
}
#[doc = "IO port x clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(GPIOASMEN_A::Enabled)
}
}
#[doc = "Field `GPIOBSMEN` reader - IO port B clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_R as GPIOBSMEN_R;
#[doc = "Field `GPIOCSMEN` reader - IO port C clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_R as GPIOCSMEN_R;
#[doc = "Field `GPIODSMEN` reader - IO port D clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_R as GPIODSMEN_R;
#[doc = "Field `GPIOESMEN` reader - IO port E clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_R as GPIOESMEN_R;
#[doc = "Field `GPIOFSMEN` reader - IO port F clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_R as GPIOFSMEN_R;
#[doc = "Field `GPIOGSMEN` reader - IO port G clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_R as GPIOGSMEN_R;
#[doc = "Field `GPIOHSMEN` reader - IO port H clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_R as GPIOHSMEN_R;
#[doc = "Field `GPIOISMEN` reader - IO port I clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_R as GPIOISMEN_R;
#[doc = "Field `GPIOBSMEN` writer - IO port B clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_W as GPIOBSMEN_W;
#[doc = "Field `GPIOCSMEN` writer - IO port C clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_W as GPIOCSMEN_W;
#[doc = "Field `GPIODSMEN` writer - IO port D clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_W as GPIODSMEN_W;
#[doc = "Field `GPIOESMEN` writer - IO port E clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_W as GPIOESMEN_W;
#[doc = "Field `GPIOFSMEN` writer - IO port F clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_W as GPIOFSMEN_W;
#[doc = "Field `GPIOGSMEN` writer - IO port G clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_W as GPIOGSMEN_W;
#[doc = "Field `GPIOHSMEN` writer - IO port H clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_W as GPIOHSMEN_W;
#[doc = "Field `GPIOISMEN` writer - IO port I clocks enable during Sleep and Stop modes"]
pub use GPIOASMEN_W as GPIOISMEN_W;
#[doc = "Field `SRAM2SMEN` reader - SRAM2 interface clocks enable during Sleep and Stop modes"]
pub type SRAM2SMEN_R = crate::BitReader<SRAM2SMEN_A>;
#[doc = "SRAM2 interface clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SRAM2SMEN_A {
#[doc = "0: SRAMx clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: SRAMx clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<SRAM2SMEN_A> for bool {
#[inline(always)]
fn from(variant: SRAM2SMEN_A) -> Self {
variant as u8 != 0
}
}
impl SRAM2SMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SRAM2SMEN_A {
match self.bits {
false => SRAM2SMEN_A::Disabled,
true => SRAM2SMEN_A::Enabled,
}
}
#[doc = "SRAMx clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == SRAM2SMEN_A::Disabled
}
#[doc = "SRAMx clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == SRAM2SMEN_A::Enabled
}
}
#[doc = "Field `SRAM2SMEN` writer - SRAM2 interface clocks enable during Sleep and Stop modes"]
pub type SRAM2SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SRAM2SMEN_A>;
impl<'a, REG, const O: u8> SRAM2SMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "SRAMx clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(SRAM2SMEN_A::Disabled)
}
#[doc = "SRAMx clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(SRAM2SMEN_A::Enabled)
}
}
#[doc = "Field `SRAM3SMEN` reader - SRAM2 interface clocks enable during Sleep and Stop modes"]
pub use SRAM2SMEN_R as SRAM3SMEN_R;
#[doc = "Field `SRAM3SMEN` writer - SRAM2 interface clocks enable during Sleep and Stop modes"]
pub use SRAM2SMEN_W as SRAM3SMEN_W;
#[doc = "Field `OTGFSSMEN` reader - OTG full speed clocks enable during Sleep and Stop modes"]
pub type OTGFSSMEN_R = crate::BitReader<OTGFSSMEN_A>;
#[doc = "OTG full speed clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OTGFSSMEN_A {
#[doc = "0: USB OTG full speed clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: USB OTG full speed clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<OTGFSSMEN_A> for bool {
#[inline(always)]
fn from(variant: OTGFSSMEN_A) -> Self {
variant as u8 != 0
}
}
impl OTGFSSMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> OTGFSSMEN_A {
match self.bits {
false => OTGFSSMEN_A::Disabled,
true => OTGFSSMEN_A::Enabled,
}
}
#[doc = "USB OTG full speed clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == OTGFSSMEN_A::Disabled
}
#[doc = "USB OTG full speed clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == OTGFSSMEN_A::Enabled
}
}
#[doc = "Field `OTGFSSMEN` writer - OTG full speed clocks enable during Sleep and Stop modes"]
pub type OTGFSSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, OTGFSSMEN_A>;
impl<'a, REG, const O: u8> OTGFSSMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "USB OTG full speed clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(OTGFSSMEN_A::Disabled)
}
#[doc = "USB OTG full speed clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(OTGFSSMEN_A::Enabled)
}
}
#[doc = "Field `ADCSMEN` reader - ADC clocks enable during Sleep and Stop modes"]
pub type ADCSMEN_R = crate::BitReader<ADCSMEN_A>;
#[doc = "ADC clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ADCSMEN_A {
#[doc = "0: ADC clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: ADC clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<ADCSMEN_A> for bool {
#[inline(always)]
fn from(variant: ADCSMEN_A) -> Self {
variant as u8 != 0
}
}
impl ADCSMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ADCSMEN_A {
match self.bits {
false => ADCSMEN_A::Disabled,
true => ADCSMEN_A::Enabled,
}
}
#[doc = "ADC clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == ADCSMEN_A::Disabled
}
#[doc = "ADC clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == ADCSMEN_A::Enabled
}
}
#[doc = "Field `ADCSMEN` writer - ADC clocks enable during Sleep and Stop modes"]
pub type ADCSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, ADCSMEN_A>;
impl<'a, REG, const O: u8> ADCSMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "ADC clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(ADCSMEN_A::Disabled)
}
#[doc = "ADC clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(ADCSMEN_A::Enabled)
}
}
#[doc = "Field `DCMISMEN` reader - DCMI clock enable during Sleep and Stop modes"]
pub type DCMISMEN_R = crate::BitReader<DCMISMEN_A>;
#[doc = "DCMI clock enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DCMISMEN_A {
#[doc = "0: DCMI/PSSI clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: DCMI/PSSI clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<DCMISMEN_A> for bool {
#[inline(always)]
fn from(variant: DCMISMEN_A) -> Self {
variant as u8 != 0
}
}
impl DCMISMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DCMISMEN_A {
match self.bits {
false => DCMISMEN_A::Disabled,
true => DCMISMEN_A::Enabled,
}
}
#[doc = "DCMI/PSSI clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == DCMISMEN_A::Disabled
}
#[doc = "DCMI/PSSI clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == DCMISMEN_A::Enabled
}
}
#[doc = "Field `DCMISMEN` writer - DCMI clock enable during Sleep and Stop modes"]
pub type DCMISMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DCMISMEN_A>;
impl<'a, REG, const O: u8> DCMISMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "DCMI/PSSI clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(DCMISMEN_A::Disabled)
}
#[doc = "DCMI/PSSI clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(DCMISMEN_A::Enabled)
}
}
#[doc = "Field `PKASMEN` reader - PKA clocks enable during Sleep and Stop modes"]
pub type PKASMEN_R = crate::BitReader<PKASMEN_A>;
#[doc = "PKA clocks enable during Sleep and Stop modes\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PKASMEN_A {
#[doc = "0: PKA clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: PKA clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<PKASMEN_A> for bool {
#[inline(always)]
fn from(variant: PKASMEN_A) -> Self {
variant as u8 != 0
}
}
impl PKASMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PKASMEN_A {
match self.bits {
false => PKASMEN_A::Disabled,
true => PKASMEN_A::Enabled,
}
}
#[doc = "PKA clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == PKASMEN_A::Disabled
}
#[doc = "PKA clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == PKASMEN_A::Enabled
}
}
#[doc = "Field `PKASMEN` writer - PKA clocks enable during Sleep and Stop modes"]
pub type PKASMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PKASMEN_A>;
impl<'a, REG, const O: u8> PKASMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "PKA clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(PKASMEN_A::Disabled)
}
#[doc = "PKA clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(PKASMEN_A::Enabled)
}
}
#[doc = "Field `AESSMEN` reader - AES accelerator clocks enable during Sleep and Stop modes"]
pub type AESSMEN_R = crate::BitReader<AESSMEN_A>;
#[doc = "AES accelerator clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AESSMEN_A {
#[doc = "0: AES clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: AES clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<AESSMEN_A> for bool {
#[inline(always)]
fn from(variant: AESSMEN_A) -> Self {
variant as u8 != 0
}
}
impl AESSMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> AESSMEN_A {
match self.bits {
false => AESSMEN_A::Disabled,
true => AESSMEN_A::Enabled,
}
}
#[doc = "AES clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == AESSMEN_A::Disabled
}
#[doc = "AES clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == AESSMEN_A::Enabled
}
}
#[doc = "Field `AESSMEN` writer - AES accelerator clocks enable during Sleep and Stop modes"]
pub type AESSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, AESSMEN_A>;
impl<'a, REG, const O: u8> AESSMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "AES clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(AESSMEN_A::Disabled)
}
#[doc = "AES clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(AESSMEN_A::Enabled)
}
}
#[doc = "Field `HASHSMEN` reader - HASH clock enable during Sleep and Stop modes"]
pub type HASHSMEN_R = crate::BitReader<HASHSMEN_A>;
#[doc = "HASH clock enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HASHSMEN_A {
#[doc = "0: HASH clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: HASH clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<HASHSMEN_A> for bool {
#[inline(always)]
fn from(variant: HASHSMEN_A) -> Self {
variant as u8 != 0
}
}
impl HASHSMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> HASHSMEN_A {
match self.bits {
false => HASHSMEN_A::Disabled,
true => HASHSMEN_A::Enabled,
}
}
#[doc = "HASH clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == HASHSMEN_A::Disabled
}
#[doc = "HASH clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == HASHSMEN_A::Enabled
}
}
#[doc = "Field `HASHSMEN` writer - HASH clock enable during Sleep and Stop modes"]
pub type HASHSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, HASHSMEN_A>;
impl<'a, REG, const O: u8> HASHSMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "HASH clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(HASHSMEN_A::Disabled)
}
#[doc = "HASH clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(HASHSMEN_A::Enabled)
}
}
#[doc = "Field `RNGSMEN` reader - Random Number Generator clocks enable during Sleep and Stop modes"]
pub type RNGSMEN_R = crate::BitReader<RNGSMEN_A>;
#[doc = "Random Number Generator clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RNGSMEN_A {
#[doc = "0: Random Number Generator clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: Random Number Generator clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<RNGSMEN_A> for bool {
#[inline(always)]
fn from(variant: RNGSMEN_A) -> Self {
variant as u8 != 0
}
}
impl RNGSMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RNGSMEN_A {
match self.bits {
false => RNGSMEN_A::Disabled,
true => RNGSMEN_A::Enabled,
}
}
#[doc = "Random Number Generator clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == RNGSMEN_A::Disabled
}
#[doc = "Random Number Generator clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == RNGSMEN_A::Enabled
}
}
#[doc = "Field `RNGSMEN` writer - Random Number Generator clocks enable during Sleep and Stop modes"]
pub type RNGSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, RNGSMEN_A>;
impl<'a, REG, const O: u8> RNGSMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Random Number Generator clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(RNGSMEN_A::Disabled)
}
#[doc = "Random Number Generator clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(RNGSMEN_A::Enabled)
}
}
#[doc = "Field `OSPIMSMEN` reader - OctoSPI IO manager clocks enable during Sleep and Stop modes"]
pub type OSPIMSMEN_R = crate::BitReader<OSPIMSMEN_A>;
#[doc = "OctoSPI IO manager clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OSPIMSMEN_A {
#[doc = "0: OCTOSPIM clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: OCTOSPIM clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<OSPIMSMEN_A> for bool {
#[inline(always)]
fn from(variant: OSPIMSMEN_A) -> Self {
variant as u8 != 0
}
}
impl OSPIMSMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> OSPIMSMEN_A {
match self.bits {
false => OSPIMSMEN_A::Disabled,
true => OSPIMSMEN_A::Enabled,
}
}
#[doc = "OCTOSPIM clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == OSPIMSMEN_A::Disabled
}
#[doc = "OCTOSPIM clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == OSPIMSMEN_A::Enabled
}
}
#[doc = "Field `OSPIMSMEN` writer - OctoSPI IO manager clocks enable during Sleep and Stop modes"]
pub type OSPIMSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, OSPIMSMEN_A>;
impl<'a, REG, const O: u8> OSPIMSMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "OCTOSPIM clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(OSPIMSMEN_A::Disabled)
}
#[doc = "OCTOSPIM clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(OSPIMSMEN_A::Enabled)
}
}
#[doc = "Field `SDMMC1SMEN` reader - SDMMC1 clocks enable during Sleep and Stop modes"]
pub type SDMMC1SMEN_R = crate::BitReader<SDMMC1SMEN_A>;
#[doc = "SDMMC1 clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SDMMC1SMEN_A {
#[doc = "0: SDMMCx clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: SDMMCx clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<SDMMC1SMEN_A> for bool {
#[inline(always)]
fn from(variant: SDMMC1SMEN_A) -> Self {
variant as u8 != 0
}
}
impl SDMMC1SMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SDMMC1SMEN_A {
match self.bits {
false => SDMMC1SMEN_A::Disabled,
true => SDMMC1SMEN_A::Enabled,
}
}
#[doc = "SDMMCx clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == SDMMC1SMEN_A::Disabled
}
#[doc = "SDMMCx clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == SDMMC1SMEN_A::Enabled
}
}
#[doc = "Field `SDMMC1SMEN` writer - SDMMC1 clocks enable during Sleep and Stop modes"]
pub type SDMMC1SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SDMMC1SMEN_A>;
impl<'a, REG, const O: u8> SDMMC1SMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "SDMMCx clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(SDMMC1SMEN_A::Disabled)
}
#[doc = "SDMMCx clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(SDMMC1SMEN_A::Enabled)
}
}
#[doc = "Field `SDMMC2SMEN` reader - SDMMC2 clocks enable during Sleep and Stop modes"]
pub use SDMMC1SMEN_R as SDMMC2SMEN_R;
#[doc = "Field `SDMMC2SMEN` writer - SDMMC2 clocks enable during Sleep and Stop modes"]
pub use SDMMC1SMEN_W as SDMMC2SMEN_W;
impl R {
#[doc = "Bit 0 - IO port A clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpioasmen(&self) -> GPIOASMEN_R {
GPIOASMEN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - IO port B clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpiobsmen(&self) -> GPIOBSMEN_R {
GPIOBSMEN_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - IO port C clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpiocsmen(&self) -> GPIOCSMEN_R {
GPIOCSMEN_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - IO port D clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpiodsmen(&self) -> GPIODSMEN_R {
GPIODSMEN_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - IO port E clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpioesmen(&self) -> GPIOESMEN_R {
GPIOESMEN_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - IO port F clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpiofsmen(&self) -> GPIOFSMEN_R {
GPIOFSMEN_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - IO port G clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpiogsmen(&self) -> GPIOGSMEN_R {
GPIOGSMEN_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - IO port H clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpiohsmen(&self) -> GPIOHSMEN_R {
GPIOHSMEN_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - IO port I clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn gpioismen(&self) -> GPIOISMEN_R {
GPIOISMEN_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - SRAM2 interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn sram2smen(&self) -> SRAM2SMEN_R {
SRAM2SMEN_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - SRAM2 interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn sram3smen(&self) -> SRAM3SMEN_R {
SRAM3SMEN_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 12 - OTG full speed clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn otgfssmen(&self) -> OTGFSSMEN_R {
OTGFSSMEN_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - ADC clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn adcsmen(&self) -> ADCSMEN_R {
ADCSMEN_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - DCMI clock enable during Sleep and Stop modes"]
#[inline(always)]
pub fn dcmismen(&self) -> DCMISMEN_R {
DCMISMEN_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - PKA clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn pkasmen(&self) -> PKASMEN_R {
PKASMEN_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - AES accelerator clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn aessmen(&self) -> AESSMEN_R {
AESSMEN_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - HASH clock enable during Sleep and Stop modes"]
#[inline(always)]
pub fn hashsmen(&self) -> HASHSMEN_R {
HASHSMEN_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - Random Number Generator clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn rngsmen(&self) -> RNGSMEN_R {
RNGSMEN_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 20 - OctoSPI IO manager clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn ospimsmen(&self) -> OSPIMSMEN_R {
OSPIMSMEN_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 22 - SDMMC1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn sdmmc1smen(&self) -> SDMMC1SMEN_R {
SDMMC1SMEN_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - SDMMC2 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn sdmmc2smen(&self) -> SDMMC2SMEN_R {
SDMMC2SMEN_R::new(((self.bits >> 23) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - IO port A clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpioasmen(&mut self) -> GPIOASMEN_W<AHB2SMENR_SPEC, 0> {
GPIOASMEN_W::new(self)
}
#[doc = "Bit 1 - IO port B clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpiobsmen(&mut self) -> GPIOBSMEN_W<AHB2SMENR_SPEC, 1> {
GPIOBSMEN_W::new(self)
}
#[doc = "Bit 2 - IO port C clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpiocsmen(&mut self) -> GPIOCSMEN_W<AHB2SMENR_SPEC, 2> {
GPIOCSMEN_W::new(self)
}
#[doc = "Bit 3 - IO port D clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpiodsmen(&mut self) -> GPIODSMEN_W<AHB2SMENR_SPEC, 3> {
GPIODSMEN_W::new(self)
}
#[doc = "Bit 4 - IO port E clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpioesmen(&mut self) -> GPIOESMEN_W<AHB2SMENR_SPEC, 4> {
GPIOESMEN_W::new(self)
}
#[doc = "Bit 5 - IO port F clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpiofsmen(&mut self) -> GPIOFSMEN_W<AHB2SMENR_SPEC, 5> {
GPIOFSMEN_W::new(self)
}
#[doc = "Bit 6 - IO port G clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpiogsmen(&mut self) -> GPIOGSMEN_W<AHB2SMENR_SPEC, 6> {
GPIOGSMEN_W::new(self)
}
#[doc = "Bit 7 - IO port H clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpiohsmen(&mut self) -> GPIOHSMEN_W<AHB2SMENR_SPEC, 7> {
GPIOHSMEN_W::new(self)
}
#[doc = "Bit 8 - IO port I clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn gpioismen(&mut self) -> GPIOISMEN_W<AHB2SMENR_SPEC, 8> {
GPIOISMEN_W::new(self)
}
#[doc = "Bit 9 - SRAM2 interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn sram2smen(&mut self) -> SRAM2SMEN_W<AHB2SMENR_SPEC, 9> {
SRAM2SMEN_W::new(self)
}
#[doc = "Bit 10 - SRAM2 interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn sram3smen(&mut self) -> SRAM3SMEN_W<AHB2SMENR_SPEC, 10> {
SRAM3SMEN_W::new(self)
}
#[doc = "Bit 12 - OTG full speed clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn otgfssmen(&mut self) -> OTGFSSMEN_W<AHB2SMENR_SPEC, 12> {
OTGFSSMEN_W::new(self)
}
#[doc = "Bit 13 - ADC clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn adcsmen(&mut self) -> ADCSMEN_W<AHB2SMENR_SPEC, 13> {
ADCSMEN_W::new(self)
}
#[doc = "Bit 14 - DCMI clock enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn dcmismen(&mut self) -> DCMISMEN_W<AHB2SMENR_SPEC, 14> {
DCMISMEN_W::new(self)
}
#[doc = "Bit 15 - PKA clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn pkasmen(&mut self) -> PKASMEN_W<AHB2SMENR_SPEC, 15> {
PKASMEN_W::new(self)
}
#[doc = "Bit 16 - AES accelerator clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn aessmen(&mut self) -> AESSMEN_W<AHB2SMENR_SPEC, 16> {
AESSMEN_W::new(self)
}
#[doc = "Bit 17 - HASH clock enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn hashsmen(&mut self) -> HASHSMEN_W<AHB2SMENR_SPEC, 17> {
HASHSMEN_W::new(self)
}
#[doc = "Bit 18 - Random Number Generator clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn rngsmen(&mut self) -> RNGSMEN_W<AHB2SMENR_SPEC, 18> {
RNGSMEN_W::new(self)
}
#[doc = "Bit 20 - OctoSPI IO manager clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn ospimsmen(&mut self) -> OSPIMSMEN_W<AHB2SMENR_SPEC, 20> {
OSPIMSMEN_W::new(self)
}
#[doc = "Bit 22 - SDMMC1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn sdmmc1smen(&mut self) -> SDMMC1SMEN_W<AHB2SMENR_SPEC, 22> {
SDMMC1SMEN_W::new(self)
}
#[doc = "Bit 23 - SDMMC2 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn sdmmc2smen(&mut self) -> SDMMC2SMEN_W<AHB2SMENR_SPEC, 23> {
SDMMC2SMEN_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "AHB2 peripheral clocks enable in Sleep and Stop modes register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb2smenr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ahb2smenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct AHB2SMENR_SPEC;
impl crate::RegisterSpec for AHB2SMENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ahb2smenr::R`](R) reader structure"]
impl crate::Readable for AHB2SMENR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ahb2smenr::W`](W) writer structure"]
impl crate::Writable for AHB2SMENR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets AHB2SMENR to value 0x0057_77ff"]
impl crate::Resettable for AHB2SMENR_SPEC {
const RESET_VALUE: Self::Ux = 0x0057_77ff;
}
|
#[doc = "Register `SRCR` reader"]
pub type R = crate::R<SRCR_SPEC>;
#[doc = "Register `SRCR` writer"]
pub type W = crate::W<SRCR_SPEC>;
#[doc = "Field `IMR` reader - Immediate Reload"]
pub type IMR_R = crate::BitReader<IMR_A>;
#[doc = "Immediate Reload\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IMR_A {
#[doc = "0: This bit is set by software and cleared only by hardware after reload (it cannot be cleared through register write once it is set)"]
NoEffect = 0,
#[doc = "1: The shadow registers are reloaded immediately. This bit is set by software and cleared only by hardware after reload"]
Reload = 1,
}
impl From<IMR_A> for bool {
#[inline(always)]
fn from(variant: IMR_A) -> Self {
variant as u8 != 0
}
}
impl IMR_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> IMR_A {
match self.bits {
false => IMR_A::NoEffect,
true => IMR_A::Reload,
}
}
#[doc = "This bit is set by software and cleared only by hardware after reload (it cannot be cleared through register write once it is set)"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == IMR_A::NoEffect
}
#[doc = "The shadow registers are reloaded immediately. This bit is set by software and cleared only by hardware after reload"]
#[inline(always)]
pub fn is_reload(&self) -> bool {
*self == IMR_A::Reload
}
}
#[doc = "Field `IMR` writer - Immediate Reload"]
pub type IMR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, IMR_A>;
impl<'a, REG, const O: u8> IMR_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "This bit is set by software and cleared only by hardware after reload (it cannot be cleared through register write once it is set)"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(IMR_A::NoEffect)
}
#[doc = "The shadow registers are reloaded immediately. This bit is set by software and cleared only by hardware after reload"]
#[inline(always)]
pub fn reload(self) -> &'a mut crate::W<REG> {
self.variant(IMR_A::Reload)
}
}
#[doc = "Field `VBR` reader - Vertical Blanking Reload"]
pub type VBR_R = crate::BitReader<VBR_A>;
#[doc = "Vertical Blanking Reload\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VBR_A {
#[doc = "0: This bit is set by software and cleared only by hardware after reload (it cannot be cleared through register write once it is set)"]
NoEffect = 0,
#[doc = "1: The shadow registers are reloaded during the vertical blanking period (at the beginning of the first line after the active display area)."]
Reload = 1,
}
impl From<VBR_A> for bool {
#[inline(always)]
fn from(variant: VBR_A) -> Self {
variant as u8 != 0
}
}
impl VBR_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> VBR_A {
match self.bits {
false => VBR_A::NoEffect,
true => VBR_A::Reload,
}
}
#[doc = "This bit is set by software and cleared only by hardware after reload (it cannot be cleared through register write once it is set)"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == VBR_A::NoEffect
}
#[doc = "The shadow registers are reloaded during the vertical blanking period (at the beginning of the first line after the active display area)."]
#[inline(always)]
pub fn is_reload(&self) -> bool {
*self == VBR_A::Reload
}
}
#[doc = "Field `VBR` writer - Vertical Blanking Reload"]
pub type VBR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, VBR_A>;
impl<'a, REG, const O: u8> VBR_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "This bit is set by software and cleared only by hardware after reload (it cannot be cleared through register write once it is set)"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut crate::W<REG> {
self.variant(VBR_A::NoEffect)
}
#[doc = "The shadow registers are reloaded during the vertical blanking period (at the beginning of the first line after the active display area)."]
#[inline(always)]
pub fn reload(self) -> &'a mut crate::W<REG> {
self.variant(VBR_A::Reload)
}
}
impl R {
#[doc = "Bit 0 - Immediate Reload"]
#[inline(always)]
pub fn imr(&self) -> IMR_R {
IMR_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Vertical Blanking Reload"]
#[inline(always)]
pub fn vbr(&self) -> VBR_R {
VBR_R::new(((self.bits >> 1) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Immediate Reload"]
#[inline(always)]
#[must_use]
pub fn imr(&mut self) -> IMR_W<SRCR_SPEC, 0> {
IMR_W::new(self)
}
#[doc = "Bit 1 - Vertical Blanking Reload"]
#[inline(always)]
#[must_use]
pub fn vbr(&mut self) -> VBR_W<SRCR_SPEC, 1> {
VBR_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "Shadow Reload Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`srcr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`srcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SRCR_SPEC;
impl crate::RegisterSpec for SRCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`srcr::R`](R) reader structure"]
impl crate::Readable for SRCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`srcr::W`](W) writer structure"]
impl crate::Writable for SRCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SRCR to value 0"]
impl crate::Resettable for SRCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
table! {
datasets (id) {
id -> Int4,
seed -> Int8,
gmm -> Array<Jsonb>,
}
}
|
extern crate rusty_flow;
extern crate image;
use std::path::Path;
use std::fs::File;
const DETAIL: u32 = 10;
fn main() {
let buffer = rusty_flow::diamond_square::construct(DETAIL);
let buffer = rusty_flow::diamond_square::normalize_pixel_map(buffer);
let image_size: u32 = buffer.size();
let mut img_buf = image::ImageBuffer::new(image_size as u32, image_size as u32);
for (x, y, pixel) in img_buf.enumerate_pixels_mut() {
let value: u8 = buffer.get_pixel(x, y);
*pixel = image::Luma([value]);
}
// Save the image as “fractal.png”
let ref mut fout = File::create(&Path::new("fractal.png")).unwrap();
// We must indicate the image’s color type and what format to save as
let _ = image::ImageLuma8(img_buf).save(fout, image::PNG);
}
|
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
extern crate tle;
#[test]
fn norad100() {
let f = File::open("tests/visual-100-brightest-2018-01-13.txt").unwrap();
let mut reader = BufReader::new(f);
let mut contents = String::new();
reader.read_to_string(&mut contents).unwrap();
let lines :Vec<&str> = contents.split("\r\n").collect();
let num_tles = lines.len() / 3;
let mut tle;
for i in 0..num_tles {
tle = tle::parse_tle(&format!("{}\n{}\n{}", lines[3*i], lines[3*i + 1], lines[3*i + 2]));
}
// just making sure it doesn't panic.
assert_eq!(2, 2);
}
|
use abin::{AnyBin, BinFactory, NewBin, NewStr, Str, StrFactory};
#[test]
fn slice() {
let str1 = NewStr::from_static("Some text.");
assert_eq!(
"Some text.".get(5..9).unwrap(),
str1.slice(5..9).unwrap().as_str()
);
let str2 = NewStr::from_static("Warning: Don't open the door!");
assert_eq!("Don't open the door!", str2.slice(9..).unwrap().as_str());
// out of bounds returns `None`
let str3 = NewStr::from_static("HELLO");
assert!(str3.slice(0..6).is_none());
// invalid range returns none.
let str4 = NewStr::from_static("HELLO");
assert!(str4.slice(2..1).is_none())
}
/// A binary can always be converted to a string (as long as it's valid UTF-8).
#[test]
fn convert_from_utf8() {
// valid utf-8
let valid_utf8 = NewBin::from_static("Hello, world!".as_bytes());
let bin_ptr = valid_utf8.as_slice().as_ptr();
let string = Str::from_utf8(valid_utf8).unwrap();
assert_eq!("Hello, world!", string.as_str());
// no memory-copy / zero-allocation (still the same pointer).
assert_eq!(bin_ptr, string.as_ptr());
// invalid UTF-8
let invalid_utf8 = NewBin::from_static(&[0xa0, 0xa1]);
match Str::from_utf8(invalid_utf8) {
Ok(_) => {
panic!("Expected an error");
}
Err(err) => {
// we get the original binary back.
let (_, bin) = err.deconstruct();
assert_eq!(&[0xa0, 0xa1], bin.as_slice());
}
}
}
/// A binary/string can always be converted back to a Vec/String.
///
/// The implementation guarantees zero-allocation / zero-copy.
#[test]
fn convert_to_vec_string() {
let input_data = "This is some input data. It has some length to make sure it's \
not stored on the stack (if stored on the stack, the test would fail - in that case a new vec \
has to be allocated and the pointers would differ)";
// with string:
let str = NewStr::copy_from_str(input_data);
// save the pointer to the data.
let pointer = str.as_str().as_ptr();
// now convert to String
let string = str.into_string();
assert_eq!(input_data, string.as_str());
// still the same pointer.
assert_eq!(pointer, string.as_ptr());
// with binary:
let bin = NewBin::copy_from_slice(input_data.as_bytes());
// save the pointer to the data.
let pointer = bin.as_slice().as_ptr();
// now convert to Vec<u8>
let vec = bin.into_vec();
assert_eq!(input_data.as_bytes(), vec.as_slice());
// still the same pointer.
assert_eq!(pointer, vec.as_ptr());
}
#[test]
fn ord() {
assert!(NewStr::from_static("aaa") < NewStr::from_static("az"));
assert!(NewBin::from_static(&[15u8, 77u8, 20u8]) < NewBin::from_static(&[15u8, 78u8]));
}
|
fn main() {
c1_visibility();
println!();
c2_struct_visibility();
println!();
c3_use();
println!();
c4_super_self();
}
mod c1_my {
// Items in modules default to private visibility
fn private_function() {
println!("called c1_my::private_function()");
}
// Use the `pub` modifier to override default visibility
pub fn function() {
println!("called c1_my::function()");
}
// Items can access other items in the same module, even when private.
pub fn indirect_access() {
print!("called c1_my::indirect_access(), then\n> ");
private_function();
}
// Modules can also be nested
pub mod nested {
pub fn function() {
println!("c1_my::nested::function()");
}
#[allow(dead_code)]
fn private_function() {
println!("called c1_my::nested::private_function()");
}
}
// Nested modules follow the same rules for visibility
mod private_nested {
#[allow(dead_code)]
pub fn function() {
println!("called c1_my::private_nested::function()");
}
}
}
fn function() {
println!("called function()");
}
fn c1_visibility() {
// Modules allow disambiguation between items that have the same name.
function();
c1_my::function();
// Public items, including those inside nested modules, can be
// accessed from outside the parent module.
c1_my::indirect_access();
c1_my::nested::function();
}
mod c2_my {
// A public struct with a public field of generic type T
pub struct WhiteBox<T> {
pub contents: T,
}
// A public struct with a private field of generic type `T`
#[allow(dead_code)]
pub struct BlackBox<T> {
contents: T,
}
impl<T> BlackBox<T> {
// A public constructor method
pub fn new(contents: T) -> BlackBox<T> {
BlackBox { contents }
}
}
}
fn c2_struct_visibility() {
// Public structs with public fields can be constructed as usual
let white_box = c2_my::WhiteBox {
contents: "public information",
};
// and their fields can be normally accessed.
println!("The white box contains: {}", white_box.contents);
// Public structs with private fields cannot be constructed using field names.
// Error! `BlackBox` has private fields
//let black_box = c2_my::BlackBox { contents: "classified information" };
// However, structs with private fields can be created using
// public constructors
let _black_box = c2_my::BlackBox::new("classified information");
// and the private fields of a public struct cannot be accessed.
// Error! The `contents` field is private
//println!("The black box contains: {}", _black_box.contents);
}
mod deeply {
pub mod nested {
pub fn function() {
println!("called deeply::nested::function()");
}
}
}
use crate::deeply::nested::function as other_function;
fn c3_use() {
// easier access to deeply::nested::function
other_function();
println!("Entering block");
{
// This is equivalent to `use deeply::nested::function as function`.
// This `function()` will shadow the outer one.
use crate::deeply::nested::function;
function();
// `use` bindings have a local scope. In this case, the
// shadowing of `function()` is only in this block.
println!("Leaving block");
}
function();
}
mod cool {
pub fn function() {
println!("called cool::function()");
}
}
mod c4_my {
fn function() {
println!("called c4_my::function()");
}
mod cool {
pub fn function() {
println!("called c4_my::cool::function()");
}
}
pub fn indirect_call() {
// Let's access all the functions named `function` from this scope!
println!("called c4_my::indirect_call()");
// The `self` keyword refers to the current module scope -
// in this case `c4_my`.
// Calling `self::function()` and calling `function()` directly both
// give the same result, because they refer to the same function.
self::function();
function();
// We can also use `self` to access another module inside `my`:
self::cool::function();
// The `super` keyword refers to the parent scope
// (outside the `my` module).
super::function();
// This will bind to the `cool::function` in the *crate* scope.
// In this case the crate scope is the outermost scope.
{
use crate::cool::function as root_function;
root_function();
}
}
}
fn c4_super_self() {
c4_my::indirect_call();
}
|
#[doc = "Reader of register CLK_ADC_SELECTED"]
pub type R = crate::R<u32, super::CLK_ADC_SELECTED>;
impl R {}
|
use crate::color::{color, Color};
use crate::texture::{perlin::Perlin, Texture, TextureColor};
use crate::vec::Vec3;
// MarbleTexture
#[derive(Debug, Clone)]
pub struct MarbleTexture {
pub noise: Perlin,
pub scale: f64,
}
impl MarbleTexture {
pub fn new(seed: u64, scale: f64) -> Texture {
Texture::from(MarbleTexture {
noise: Perlin::new(seed),
scale: scale,
})
}
}
impl TextureColor for MarbleTexture {
fn value(&self, _u: f64, _v: f64, p: Vec3) -> Color {
color(1.0, 1.0, 1.0)
* 0.5
* (1.0 + f64::sin(self.scale * p.z + 10. * self.noise.turb(p * self.scale, 7)))
}
}
|
use std::collections::HashMap;
fn main() {
/////////////////////////
// CHAPTER 8 EXERCISES //
/////////////////////////
///////////////////
// integer stats //
///////////////////
// tests
assert_eq!(mean(&vec![1, 2, 3]), 2.0);
assert_eq!(median(&mut vec![1, 2, 3]), 2);
assert_eq!(mode(&vec![1, 2, 2, 3]), Some(2));
// code
fn mean(nums: &Vec<u32>) -> f32 {
(nums.iter().fold(0, |acc, n| acc + n) as f32) / (nums.len() as f32)
}
fn median(nums: &mut Vec<u32>) -> u32 {
nums.sort();
nums[nums.len() / 2]
}
fn mode(nums: &Vec<u32>) -> Option<u32> {
let counts = count_occurences(nums);
counts.values().cloned().max()
}
fn count_occurences(nums: &Vec<u32>) -> HashMap<&u32, u32> {
// hmmm... i wonder if there's a more functional way to do this?
let mut counts = HashMap::new();
for n in nums {
let count = counts.entry(n).or_insert(0);
*count += 1;
}
counts
}
///////////////
// pig-latin //
///////////////
// tests
assert_eq!(
pig_latinize(String::from("first")),
String::from("irst-fay")
);
assert_eq!(
pig_latinize(String::from("apple")),
String::from("apple-hay")
);
// code
fn pig_latinize(word: String) -> String {
let (hd, tl) = get_head_and_tail(&word[..]);
if is_consonant(hd) {
format!("{}-{}ay", tl, hd)
} else {
format!("{}-hay", word)
}
}
fn get_head_and_tail(word: &str) -> (&str, &str) {
(&word[..1], &word[1..])
}
const CONSONANTS: [char; 21] = [
'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w',
'x', 'y', 'z',
];
fn is_consonant(str: &str) -> bool {
let first_char = str.chars().next().unwrap();
CONSONANTS.contains(&first_char)
}
///////////////
// directory //
///////////////
// tests
let directory = build_directory(vec![
"Add Connor to Joy",
"Add Austin to Planmaking",
"Add Ziggy to Gadgets",
"Add Jenny to Planmaking",
"Add Emma to Planmaking",
"Add Monica to Joy",
"Add Kelley to Gadgets",
]);
assert_eq!(
directory,
[
(
String::from("Joy"),
vec![String::from("Connor"), String::from("Monica")]
),
(
String::from("Planmaking"),
vec![
String::from("Austin"),
String::from("Emma"),
String::from("Jenny"),
],
),
(
String::from("Gadgets"),
vec![String::from("Kelley"), String::from("Ziggy")],
)
].iter()
.cloned()
.collect()
);
assert_eq!(
people_in_department(&directory, String::from("Joy")),
String::from("Connor, Monica")
);
assert_eq!(
people_in_department(&directory, String::from("Non-existent")),
String::from("Nobody")
);
assert_eq!(
people_by_department(&directory),
String::from(
"Gadgets: Kelley, Ziggy\n\
Joy: Connor, Monica\n\
Planmaking: Austin, Emma, Jenny"
)
);
//code
type Directory = HashMap<String, Vec<String>>; // would prefer &str but don't understand lifetimes yet!
fn build_directory(cmds: Vec<&str>) -> Directory {
let mut dir = Directory::new();
for cmd in cmds {
process_cmd(&mut dir, cmd);
}
for (_, v) in &mut dir {
v.sort()
}
dir
}
fn process_cmd(dir: &mut Directory, cmd: &str) {
let pair = cmd[4..].split(" to ").collect::<Vec<&str>>();
let (name, dept) = (String::from(pair[0]), String::from(pair[1]));
let names = dir.entry(dept).or_insert(Vec::new());
names.push(name);
}
fn people_in_department(dir: &Directory, dpt: String) -> String {
dir.get(&dpt)
.get_or_insert(&vec![String::from("Nobody")])
.join(", ")
}
fn people_by_department(dir: &Directory) -> String {
let mut dept_listings: Vec<String> = dir
.iter()
.map(|(k, v)| format!("{}: {}", k, v.join(", ")))
.collect();
dept_listings.sort();
dept_listings.join("\n")
}
}
|
/*!
[](https://github.com/LPGhatguy/nonmax/actions)
[](https://crates.io/crates/nonmax)
[](https://docs.rs/nonmax)
nonmax provides types similar to the std `NonZero*` types, but instead requires
that their values are not the maximum for their type. This ensures that
`Option<NonMax*>` is no larger than `NonMax*`.
nonmax supports every type that has a corresponding non-zero variant in the
standard library:
* `NonMaxI8`
* `NonMaxI16`
* `NonMaxI32`
* `NonMaxI64`
* `NonMaxIsize`
* `NonMaxU8`
* `NonMaxU16`
* `NonMaxU32`
* `NonMaxU64`
* `NonMaxUsize`
## Example
```
use nonmax::{NonMaxI16, NonMaxU8};
let value = NonMaxU8::new(16).expect("16 should definitely fit in a u8");
assert_eq!(value.get(), 16);
assert_eq!(std::mem::size_of_val(&value), 1);
let signed = NonMaxI16::new(i16::min_value()).expect("minimum values are fine");
assert_eq!(signed.get(), i16::min_value());
assert_eq!(std::mem::size_of_val(&signed), 2);
let oops = NonMaxU8::new(255);
assert_eq!(oops, None);
```
## Minimum Supported Rust Version (MSRV)
nonmax supports Rust 1.46.0 and newer. Until this library reaches 1.0,
changes to the MSRV will require major version bumps. After 1.0, MSRV changes
will only require minor version bumps, but will need significant justification.
*/
#![forbid(missing_docs)]
macro_rules! nonmax {
( $nonmax: ident, $non_zero: ident, $primitive: ident ) => {
/// An integer that is known not to equal its maximum value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct $nonmax(std::num::$non_zero);
impl $nonmax {
/// Creates a new non-max if the given value is not the maximum
/// value.
#[inline]
pub const fn new(value: $primitive) -> Option<Self> {
if value == $primitive::max_value() {
None
} else {
let inner = unsafe {
std::num::$non_zero::new_unchecked(value ^ $primitive::max_value())
};
Some(Self(inner))
}
}
/// Creates a new non-max without checking the value.
///
/// # Safety
///
/// The value must not equal the maximum representable value for the
/// primitive type.
#[inline]
pub const unsafe fn new_unchecked(value: $primitive) -> Self {
let inner = std::num::$non_zero::new_unchecked(value ^ $primitive::max_value());
Self(inner)
}
/// Returns the value as a primitive type.
#[inline]
pub const fn get(&self) -> $primitive {
self.0.get() ^ $primitive::max_value()
}
}
#[cfg(test)]
mod $primitive {
use super::*;
use std::mem::size_of;
#[test]
fn construct() {
let zero = $nonmax::new(0).unwrap();
assert_eq!(zero.get(), 0);
let some = $nonmax::new(19).unwrap();
assert_eq!(some.get(), 19);
let max = $nonmax::new($primitive::max_value());
assert_eq!(max, None);
}
#[test]
fn sizes_correct() {
assert_eq!(size_of::<$primitive>(), size_of::<$nonmax>());
assert_eq!(size_of::<$nonmax>(), size_of::<Option<$nonmax>>());
}
}
};
}
nonmax!(NonMaxI8, NonZeroI8, i8);
nonmax!(NonMaxI16, NonZeroI16, i16);
nonmax!(NonMaxI32, NonZeroI32, i32);
nonmax!(NonMaxI64, NonZeroI64, i64);
nonmax!(NonMaxIsize, NonZeroIsize, isize);
nonmax!(NonMaxU8, NonZeroU8, u8);
nonmax!(NonMaxU16, NonZeroU16, u16);
nonmax!(NonMaxU32, NonZeroU32, u32);
nonmax!(NonMaxU64, NonZeroU64, u64);
nonmax!(NonMaxUsize, NonZeroUsize, usize);
|
#[doc = "Register `SYSCFG_CFGR1` reader"]
pub type R = crate::R<SYSCFG_CFGR1_SPEC>;
#[doc = "Register `SYSCFG_CFGR1` writer"]
pub type W = crate::W<SYSCFG_CFGR1_SPEC>;
#[doc = "Field `MEM_MODE` reader - Memory mapping selection bits This bitfield controlled by software selects the memory internally mapped at the address 0x0000 0000. Its reset value is determined by the boot mode configuration. Refer to for more details. x0: Main Flash memory"]
pub type MEM_MODE_R = crate::FieldReader;
#[doc = "Field `MEM_MODE` writer - Memory mapping selection bits This bitfield controlled by software selects the memory internally mapped at the address 0x0000 0000. Its reset value is determined by the boot mode configuration. Refer to for more details. x0: Main Flash memory"]
pub type MEM_MODE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `PA11_RMP` reader - PA11 pin remapping This bit is set and cleared by software. When set, it remaps the PA11 pin to operate as PA9 GPIO port, instead as PA11 GPIO port."]
pub type PA11_RMP_R = crate::BitReader;
#[doc = "Field `PA11_RMP` writer - PA11 pin remapping This bit is set and cleared by software. When set, it remaps the PA11 pin to operate as PA9 GPIO port, instead as PA11 GPIO port."]
pub type PA11_RMP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PA12_RMP` reader - PA12 pin remapping This bit is set and cleared by software. When set, it remaps the PA12 pin to operate as PA10 GPIO port, instead as PA12 GPIO port."]
pub type PA12_RMP_R = crate::BitReader;
#[doc = "Field `PA12_RMP` writer - PA12 pin remapping This bit is set and cleared by software. When set, it remaps the PA12 pin to operate as PA10 GPIO port, instead as PA12 GPIO port."]
pub type PA12_RMP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IR_POL` reader - IR output polarity selection"]
pub type IR_POL_R = crate::BitReader;
#[doc = "Field `IR_POL` writer - IR output polarity selection"]
pub type IR_POL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IR_MOD` reader - IR Modulation Envelope signal selection This bitfield selects the signal for IR modulation envelope:"]
pub type IR_MOD_R = crate::FieldReader;
#[doc = "Field `IR_MOD` writer - IR Modulation Envelope signal selection This bitfield selects the signal for IR modulation envelope:"]
pub type IR_MOD_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `I2C_PB6_FMP` reader - Fast Mode Plus (FM+) enable for PB6 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB6 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PB6_FMP_R = crate::BitReader;
#[doc = "Field `I2C_PB6_FMP` writer - Fast Mode Plus (FM+) enable for PB6 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB6 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PB6_FMP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C_PB7_FMP` reader - Fast Mode Plus (FM+) enable for PB7 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB7 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PB7_FMP_R = crate::BitReader;
#[doc = "Field `I2C_PB7_FMP` writer - Fast Mode Plus (FM+) enable for PB7 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB7 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PB7_FMP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C_PB8_FMP` reader - Fast Mode Plus (FM+) enable for PB8 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB8 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PB8_FMP_R = crate::BitReader;
#[doc = "Field `I2C_PB8_FMP` writer - Fast Mode Plus (FM+) enable for PB8 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB8 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PB8_FMP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C_PB9_FMP` reader - Fast Mode Plus (FM+) enable for PB9 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB9 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PB9_FMP_R = crate::BitReader;
#[doc = "Field `I2C_PB9_FMP` writer - Fast Mode Plus (FM+) enable for PB9 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB9 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PB9_FMP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C1_FMP` reader - Fast Mode Plus (FM+) enable for I2C1 This bit is set and cleared by software. It enables I2C FM+ driving capability on I/O ports configured as I2C1 through GPIOx_AFR registers. With this bit in disable state, the I2C FM+ driving capability on I/O ports configured as I2C1 can be enabled through their corresponding I2Cx_FMP bit. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C1_FMP_R = crate::BitReader;
#[doc = "Field `I2C1_FMP` writer - Fast Mode Plus (FM+) enable for I2C1 This bit is set and cleared by software. It enables I2C FM+ driving capability on I/O ports configured as I2C1 through GPIOx_AFR registers. With this bit in disable state, the I2C FM+ driving capability on I/O ports configured as I2C1 can be enabled through their corresponding I2Cx_FMP bit. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C1_FMP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C_PA9_FMP` reader - Fast Mode Plus (FM+) enable for PA9 This bit is set and cleared by software. It enables I2C FM+ driving capability on PA9 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PA9_FMP_R = crate::BitReader;
#[doc = "Field `I2C_PA9_FMP` writer - Fast Mode Plus (FM+) enable for PA9 This bit is set and cleared by software. It enables I2C FM+ driving capability on PA9 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PA9_FMP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C_PA10_FMP` reader - Fast Mode Plus (FM+) enable for PA10 This bit is set and cleared by software. It enables I2C FM+ driving capability on PA10 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PA10_FMP_R = crate::BitReader;
#[doc = "Field `I2C_PA10_FMP` writer - Fast Mode Plus (FM+) enable for PA10 This bit is set and cleared by software. It enables I2C FM+ driving capability on PA10 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PA10_FMP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C_PC14_FMP` reader - Fast Mode Plus (FM+) enable for PC14 This bit is set and cleared by software. It enables I2C FM+ driving capability on PC14 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PC14_FMP_R = crate::BitReader;
#[doc = "Field `I2C_PC14_FMP` writer - Fast Mode Plus (FM+) enable for PC14 This bit is set and cleared by software. It enables I2C FM+ driving capability on PC14 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
pub type I2C_PC14_FMP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bits 0:1 - Memory mapping selection bits This bitfield controlled by software selects the memory internally mapped at the address 0x0000 0000. Its reset value is determined by the boot mode configuration. Refer to for more details. x0: Main Flash memory"]
#[inline(always)]
pub fn mem_mode(&self) -> MEM_MODE_R {
MEM_MODE_R::new((self.bits & 3) as u8)
}
#[doc = "Bit 3 - PA11 pin remapping This bit is set and cleared by software. When set, it remaps the PA11 pin to operate as PA9 GPIO port, instead as PA11 GPIO port."]
#[inline(always)]
pub fn pa11_rmp(&self) -> PA11_RMP_R {
PA11_RMP_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - PA12 pin remapping This bit is set and cleared by software. When set, it remaps the PA12 pin to operate as PA10 GPIO port, instead as PA12 GPIO port."]
#[inline(always)]
pub fn pa12_rmp(&self) -> PA12_RMP_R {
PA12_RMP_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - IR output polarity selection"]
#[inline(always)]
pub fn ir_pol(&self) -> IR_POL_R {
IR_POL_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bits 6:7 - IR Modulation Envelope signal selection This bitfield selects the signal for IR modulation envelope:"]
#[inline(always)]
pub fn ir_mod(&self) -> IR_MOD_R {
IR_MOD_R::new(((self.bits >> 6) & 3) as u8)
}
#[doc = "Bit 16 - Fast Mode Plus (FM+) enable for PB6 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB6 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
pub fn i2c_pb6_fmp(&self) -> I2C_PB6_FMP_R {
I2C_PB6_FMP_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - Fast Mode Plus (FM+) enable for PB7 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB7 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
pub fn i2c_pb7_fmp(&self) -> I2C_PB7_FMP_R {
I2C_PB7_FMP_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - Fast Mode Plus (FM+) enable for PB8 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB8 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
pub fn i2c_pb8_fmp(&self) -> I2C_PB8_FMP_R {
I2C_PB8_FMP_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - Fast Mode Plus (FM+) enable for PB9 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB9 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
pub fn i2c_pb9_fmp(&self) -> I2C_PB9_FMP_R {
I2C_PB9_FMP_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - Fast Mode Plus (FM+) enable for I2C1 This bit is set and cleared by software. It enables I2C FM+ driving capability on I/O ports configured as I2C1 through GPIOx_AFR registers. With this bit in disable state, the I2C FM+ driving capability on I/O ports configured as I2C1 can be enabled through their corresponding I2Cx_FMP bit. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
pub fn i2c1_fmp(&self) -> I2C1_FMP_R {
I2C1_FMP_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 22 - Fast Mode Plus (FM+) enable for PA9 This bit is set and cleared by software. It enables I2C FM+ driving capability on PA9 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
pub fn i2c_pa9_fmp(&self) -> I2C_PA9_FMP_R {
I2C_PA9_FMP_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - Fast Mode Plus (FM+) enable for PA10 This bit is set and cleared by software. It enables I2C FM+ driving capability on PA10 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
pub fn i2c_pa10_fmp(&self) -> I2C_PA10_FMP_R {
I2C_PA10_FMP_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - Fast Mode Plus (FM+) enable for PC14 This bit is set and cleared by software. It enables I2C FM+ driving capability on PC14 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
pub fn i2c_pc14_fmp(&self) -> I2C_PC14_FMP_R {
I2C_PC14_FMP_R::new(((self.bits >> 24) & 1) != 0)
}
}
impl W {
#[doc = "Bits 0:1 - Memory mapping selection bits This bitfield controlled by software selects the memory internally mapped at the address 0x0000 0000. Its reset value is determined by the boot mode configuration. Refer to for more details. x0: Main Flash memory"]
#[inline(always)]
#[must_use]
pub fn mem_mode(&mut self) -> MEM_MODE_W<SYSCFG_CFGR1_SPEC, 0> {
MEM_MODE_W::new(self)
}
#[doc = "Bit 3 - PA11 pin remapping This bit is set and cleared by software. When set, it remaps the PA11 pin to operate as PA9 GPIO port, instead as PA11 GPIO port."]
#[inline(always)]
#[must_use]
pub fn pa11_rmp(&mut self) -> PA11_RMP_W<SYSCFG_CFGR1_SPEC, 3> {
PA11_RMP_W::new(self)
}
#[doc = "Bit 4 - PA12 pin remapping This bit is set and cleared by software. When set, it remaps the PA12 pin to operate as PA10 GPIO port, instead as PA12 GPIO port."]
#[inline(always)]
#[must_use]
pub fn pa12_rmp(&mut self) -> PA12_RMP_W<SYSCFG_CFGR1_SPEC, 4> {
PA12_RMP_W::new(self)
}
#[doc = "Bit 5 - IR output polarity selection"]
#[inline(always)]
#[must_use]
pub fn ir_pol(&mut self) -> IR_POL_W<SYSCFG_CFGR1_SPEC, 5> {
IR_POL_W::new(self)
}
#[doc = "Bits 6:7 - IR Modulation Envelope signal selection This bitfield selects the signal for IR modulation envelope:"]
#[inline(always)]
#[must_use]
pub fn ir_mod(&mut self) -> IR_MOD_W<SYSCFG_CFGR1_SPEC, 6> {
IR_MOD_W::new(self)
}
#[doc = "Bit 16 - Fast Mode Plus (FM+) enable for PB6 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB6 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
#[must_use]
pub fn i2c_pb6_fmp(&mut self) -> I2C_PB6_FMP_W<SYSCFG_CFGR1_SPEC, 16> {
I2C_PB6_FMP_W::new(self)
}
#[doc = "Bit 17 - Fast Mode Plus (FM+) enable for PB7 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB7 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
#[must_use]
pub fn i2c_pb7_fmp(&mut self) -> I2C_PB7_FMP_W<SYSCFG_CFGR1_SPEC, 17> {
I2C_PB7_FMP_W::new(self)
}
#[doc = "Bit 18 - Fast Mode Plus (FM+) enable for PB8 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB8 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
#[must_use]
pub fn i2c_pb8_fmp(&mut self) -> I2C_PB8_FMP_W<SYSCFG_CFGR1_SPEC, 18> {
I2C_PB8_FMP_W::new(self)
}
#[doc = "Bit 19 - Fast Mode Plus (FM+) enable for PB9 This bit is set and cleared by software. It enables I2C FM+ driving capability on PB9 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
#[must_use]
pub fn i2c_pb9_fmp(&mut self) -> I2C_PB9_FMP_W<SYSCFG_CFGR1_SPEC, 19> {
I2C_PB9_FMP_W::new(self)
}
#[doc = "Bit 20 - Fast Mode Plus (FM+) enable for I2C1 This bit is set and cleared by software. It enables I2C FM+ driving capability on I/O ports configured as I2C1 through GPIOx_AFR registers. With this bit in disable state, the I2C FM+ driving capability on I/O ports configured as I2C1 can be enabled through their corresponding I2Cx_FMP bit. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
#[must_use]
pub fn i2c1_fmp(&mut self) -> I2C1_FMP_W<SYSCFG_CFGR1_SPEC, 20> {
I2C1_FMP_W::new(self)
}
#[doc = "Bit 22 - Fast Mode Plus (FM+) enable for PA9 This bit is set and cleared by software. It enables I2C FM+ driving capability on PA9 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
#[must_use]
pub fn i2c_pa9_fmp(&mut self) -> I2C_PA9_FMP_W<SYSCFG_CFGR1_SPEC, 22> {
I2C_PA9_FMP_W::new(self)
}
#[doc = "Bit 23 - Fast Mode Plus (FM+) enable for PA10 This bit is set and cleared by software. It enables I2C FM+ driving capability on PA10 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
#[must_use]
pub fn i2c_pa10_fmp(&mut self) -> I2C_PA10_FMP_W<SYSCFG_CFGR1_SPEC, 23> {
I2C_PA10_FMP_W::new(self)
}
#[doc = "Bit 24 - Fast Mode Plus (FM+) enable for PC14 This bit is set and cleared by software. It enables I2C FM+ driving capability on PC14 I/O port. With this bit in disable state, the I2C FM+ driving capability on this I/O port can be enabled through one of I2Cx_FMP bits. When I2C FM+ is enabled, the speed control is ignored."]
#[inline(always)]
#[must_use]
pub fn i2c_pc14_fmp(&mut self) -> I2C_PC14_FMP_W<SYSCFG_CFGR1_SPEC, 24> {
I2C_PC14_FMP_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "SYSCFG configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`syscfg_cfgr1::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`syscfg_cfgr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SYSCFG_CFGR1_SPEC;
impl crate::RegisterSpec for SYSCFG_CFGR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`syscfg_cfgr1::R`](R) reader structure"]
impl crate::Readable for SYSCFG_CFGR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`syscfg_cfgr1::W`](W) writer structure"]
impl crate::Writable for SYSCFG_CFGR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SYSCFG_CFGR1 to value 0"]
impl crate::Resettable for SYSCFG_CFGR1_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use macroquad::prelude::*;
use na::{Vector2};
use std::process::exit;
use crate::fiz::Fiz;
// use crate::thing::lines;
use crate::thing::make_cube;
use crate::thing::make_cuboid;
// use crate::thing::transform;
use crate::thing::make_grid_xy;
pub struct Game {
pub fiz: Fiz,
}
impl Game {
pub fn new() -> Game {
return Game {
fiz: Fiz::new(),
};
}
pub async fn main(&mut self) {
let mut fiz_things = Vec::new();
let grid = make_grid_xy(5);
let cube = make_cube();
// let axisangle = Vector3::y() * std::f32::consts::FRAC_PI_4;
// let tr = Isometry3::new(Vector3::new(0., 0., 3.), axisangle);
// let cube2 = transform(cube, tr);
#[allow(unused_variables)] // TODO remove
// let rot = 0.9*3.14159265*0.25:
let rot = 0.0;
for i in 0..=2 {
println!("UUU {}", i);
let f = (i-1) as f32;
let cube_ft = self.fiz.add_thing(&cube, Vector2::new(0.0, f), rot, Vector2::new(15.0, 0.0), false);
fiz_things.push(cube_ft);
}
// wall
// let ground_size = r!(5.0);
let wall_cuboid = make_cuboid(1.0, 10.0, 1.0);
fiz_things.push(
self.fiz.add_thing(&wall_cuboid, Vector2::new(10.0, 0.), 0.0, Vector2::new(0.0, 0.0), true));
fiz_things.push(
self.fiz.add_thing(&wall_cuboid, Vector2::new(-10.0, 0.), 0.0, Vector2::new(0.0, 0.0), true));
fiz_things.push(
self.fiz.add_thing(&wall_cuboid, Vector2::new(0.0, 10.), std::f32::consts::FRAC_PI_2, Vector2::new(0.0, 0.0), true));
fiz_things.push(
self.fiz.add_thing(&wall_cuboid, Vector2::new(0.0, -10.), std::f32::consts::FRAC_PI_2, Vector2::new(0.0, 0.0), true));
loop {
clear_background(LIGHTGRAY);
// Going 3d!
let _x = 10.;
let _y = 7.;
// let ang = get_time() * 1.;
let ang = core::f32::consts::PI/1.0;
// let ang: f32 = 0.0;
// let ang: f32 = 0.0; // 1.8;
let _c = ang.cos();
let _s = ang.sin();
// let rx = x * c + y * s;
// let ry = y * c - x * s;
set_camera(&Camera3D {
// position: vec3(-20., 15., 0.),
// position: vec3(rx as f32, 36., ry as f32),
// position: vec3(0., 0., 10.0),
position: vec3(1., -8., 20.0),
// position: vec3(0.8, 6., 8.),
up: vec3(0., 1., 0.),
target: vec3(0., 0., 0.),
..Default::default()
});
// draw_grid(20, 1., BLACK, GRAY);
self.fiz.step();
for ft in &fiz_things {
let current = self.fiz.current(&ft);
crate::thing::lines::draw_thing(¤t);
}
crate::thing::lines::draw_thing(&grid);
// Back to screen space, render some text
set_default_camera();
draw_text(&format!("WELCOME TO 3D WORLD (fps {})", get_fps()), 10.0, 20.0, 30.0, BLACK);
if is_key_down(KeyCode::LeftSuper) && is_key_down(KeyCode::Q) {
exit(0);
}
next_frame().await
}
}
}
|
// actual size of the window
const SCREEN_WIDTH: i32 = 80;
const SCREEN_HEIGHT: i32 = 50;
// size of the map
//thore: map_start für die statusanzeige hinzugefügt
const MAP_WIDTH: i32 = 80;
const MAP_HEIGHT: i32 = 50;
const MAP_START_HEIGHT: i32 = 0;
const ROOM_MAX_SIZE: i32 = 10;
const ROOM_MIN_SIZE: i32 = 6;
const MAX_ROOM: i32 = 30;
//jonny: Konstanten für field of view
const FOV_ALGO: FovAlgorithm = FovAlgorithm::Basic; // standard FOV Algorithmus
const FOV_LIGHT_WALLS: bool = true; // Soll die Wand gesehen werden?
//David
const MAX_ROOM_MONSTERS: i32 = 8;
const MIN_ROOM_MONSTERS: i32 = 8;
//chance for monsters to appear, together all should be 100%
const RANDOM_ORC: f32 = 0.5;
const RANDOM_MAGE: f32 = 0.25+RANDOM_ORC;
const RANDOM_BRICK: f32 = 0.25+RANDOM_MAGE;
// frame limit
const LIMIT_FPS: i32 = 60;
//jonny
use tcod::map::{FovAlgorithm, Map as FovMap};
use std::cmp;
use rand::Rng;
use tcod::colors::*;
use tcod::console::*;
//Jonny save game
use std::error::Error;
use std::fs::File;
use std::io::{Read, Write};
use serde::{Deserialize, Serialize};
//jonny: Farben für das "Licht"
const COLOR_LIGHT_WALL: Color = Color {
r: 130,
g: 110,
b: 50,
};
const COLOR_LIGHT_GROUND: Color = Color {
r: 200,
g: 180,
b: 50,
};
const COLOR_DARK_WALL: Color = Color { r: 0, g: 0, b: 100 };
const COLOR_DARK_GROUND: Color = Color { r: 50,g: 50,b: 150 };
//thore: constanten für übersichtlichere listen durchgänge hinzugefügt
const PLAYER: usize = 0;
const SWORD: usize = 1;
const SHOWEL: usize = 2;
const BUCKET: usize = 3;
const ARROW: usize = 5;
const BOW: usize = 4;
struct Tcod {
root: Root,
con : Offscreen,
fov: FovMap,
}
//Generic object for player, enemys, items etc..
//thore: visable, direction health, images attributes added
#[derive(Debug, Serialize, Deserialize)]
struct Object {
name: String, //thore
state: i32,
x: i32,
y: i32,
char: char,
color: Color,
visable: bool,
direction: (i32,i32),
health: i32,
images: [char;4],
}
//thore: visable, direction health, images attributes added
impl Object {
pub fn new(name: String, state:i32, x: i32, y: i32, char: char, color: Color, visable: bool, direction: (i32,i32), health: i32, images: [char;4]) -> Self {
Object {name, state, x, y, char, color, visable, direction, health, images }
}
/// move by the given amount, if the destination is not blocked
pub fn move_by(&mut self, dx: i32, dy: i32, game: &Game) {
if !game.map[(self.x + dx) as usize][(self.y + dy) as usize].blocked && self.direction == (dx,dy) {
self.x += dx;
self.y += dy;
}
self.direction = (dx,dy);
}
/// set the color and then draw the character that represents this object at its position
pub fn draw(&self, con: &mut dyn Console) {
con.set_default_foreground(self.color);
con.put_char(self.x, self.y, self.char, BackgroundFlag::None);
}
pub fn pos(&self) -> (i32, i32) { //jonny
(self.x, self.y)
}
//thore: funktion erstellt für weapons, damit sie an der richtigen stelle erscheinen (vor den gegnern)
pub fn update(&mut self, x:i32, y:i32, direction:(i32,i32)){
self.x = x + direction.0;
self.y = y + direction.1;
self.direction = direction;
}
//thore: collsions function, do two objects hit?
//david added x and y work arrow fight system
pub fn collision(&self, object: &Object, x1:i32, y1:i32, x2:i32, y2:i32) -> bool{
self.x+x1 == object.x+x2 && self.y+y1 == object.y+y2
}
//david: monster takes dmg
pub fn takedmg(&mut self, dmg:i32){
self.health -=dmg;
if self.health <= 0{
self.visable = false;
}
}
fn fight(&mut self, monsters: &mut [Object]){
for monster in monsters{
//test if self hits an enemy
if self.collision(monster,0,0,0,0) && self.visable{
monster.takedmg(100);
}
}
}
}
/// A tile of the map and its properties
#[derive(Clone, Debug, Serialize, Deserialize)]
struct Tile {
blocked: bool,
explored: bool, //jonny
block_sight: bool,
name: String, //thore
}
impl Tile {
pub fn empty() -> Self {
Tile {
blocked: false,
explored: false, //jonny
block_sight: false,
name: "tile".to_string(), //thore
}
}
pub fn wall() -> Self {
Tile {
blocked: true,
explored: false, //jonny
block_sight: true,
name: "wall".to_string(), //thore
}
}
}
type Map = Vec<Vec<Tile>>;
#[derive(Serialize, Deserialize)] //Jonny
struct Game {
map: Map,
}
fn render_all(tcod: &mut Tcod, game: &mut Game, objects: &[Object], fov_recompute: bool,torch_radius: i32, monsters: &[Object], projectiles: &[Object] ) {
if fov_recompute { //jonny
// recompute FOV if needed (the player moved or something)
let player = &objects[PLAYER];
tcod.fov
.compute_fov(player.x, player.y, torch_radius, FOV_LIGHT_WALLS, FOV_ALGO);
}
// draw all objects in the list
// thore: visable abfrage hinzugefügt, es muss sichtbar sein um gemalt zu werden
// for object in objects{
//if object.visable && object.health > 0{
// object.draw(&mut tcod.con);
// }
// }
// draw all objects in the list
//jonny:
for object in objects {
if tcod.fov.is_in_fov(object.x, object.y) && object.visable && object.health > 0 {
object.draw(&mut tcod.con);
}
}
for object in projectiles {
if tcod.fov.is_in_fov(object.x, object.y) && object.visable && object.health > 0 {
object.draw(&mut tcod.con);
}
}
//david render monsters
for object in monsters {
if tcod.fov.is_in_fov(object.x, object.y) && object.visable && object.health > 0 {
object.draw(&mut tcod.con);
}
}
// go through all tiles, and set their background color
//thore: die map wird erst ab map_start angefangen zu zeichnen, damit platz für das hud ist
for y in MAP_START_HEIGHT..MAP_HEIGHT {
for x in 0..MAP_WIDTH {
let visible = tcod.fov.is_in_fov(x, y);
let wall = game.map[x as usize][y as usize].block_sight;
let color = match (visible, wall) {
// outside of field of view: jonny
(false, true) => COLOR_DARK_WALL,
(false, false) => COLOR_DARK_GROUND,
// inside fov:
(true, true) => COLOR_LIGHT_WALL,
(true, false) => COLOR_LIGHT_GROUND,
};
let explored = &mut game.map[x as usize][y as usize].explored;
if visible {
// since it's visible, explore it
*explored = true;
}
if *explored {
// show explored tiles only (any visible tile is explored already)
tcod.con
.set_char_background(x, y, color, BackgroundFlag::Set);
}
}
}
//thore: draw the hud
tcod.con.set_default_foreground(WHITE);
let health = objects[PLAYER].health;
let dirt = objects[BUCKET].health - 1;
let bow = objects[BOW].health - 1;
let enemys = monsters.len();
tcod.con.print_ex(0, 0, BackgroundFlag::None, TextAlignment::Left, &format!("V: {} M: {} S: {} W: {}", health,dirt,bow,enemys));
//draw con on window
blit(
&tcod.con,
(0, 0),
(MAP_WIDTH, MAP_HEIGHT),
&mut tcod.root,
(0, 0),
1.0,
1.0,
);
}
fn handle_keys(tcod: &mut Tcod, game: &mut Game, objects: &mut Vec<Object>, monsters: &mut Vec<Object>, projectiles: &mut Vec<Object>) -> bool {
//thore: hide weapons after each new frame
weapon_query(0, objects, game, monsters, projectiles);
use tcod::input::Key;
use tcod::input::KeyCode::*;
let key = tcod.root.wait_for_keypress(true);
match key {
// player movement keys
Key { code: Up, .. } => objects[PLAYER].move_by(0, -1, game),
Key { code: Down, .. } => objects[PLAYER].move_by(0, 1, game),
Key { code: Left, .. } => objects[PLAYER].move_by(-1, 0, game),
Key { code: Right, .. } => objects[PLAYER].move_by(1, 0, game),
Key { code: Enter, alt:true, .. } => {
let fullscreen = tcod.root.is_fullscreen();
tcod.root.set_fullscreen(!fullscreen);
}
Key { code:Escape,.. } => return true,
//thore: key querys for weapons
Key { code: Spacebar,.. } => weapon_query(SWORD,objects, game, monsters, projectiles),
Key { code: Number1,.. } => weapon_query(SHOWEL,objects, game, monsters, projectiles),
Key { code: Number2,.. } => weapon_query(BUCKET,objects, game, monsters, projectiles),
Key { code: Number3,.. } => weapon_query(BOW,objects, game, monsters, projectiles),
_ => {}
}
//thore: test for Arrow
weapon_query(ARROW, objects, game, monsters, projectiles);
return false;
}
//thore: funktion die auf die direction eines objektes guckt und dann das richtige sprite auswählt
fn animation(objects: &mut [Object]){
for object in objects{
let image = object.direction;
match image {
(0,-1) => object.char = object.images[0],
(0,1) => object.char = object.images[1],
(-1,0) => object.char = object.images[2],
(1,0) => object.char = object.images[3],
_ => {}
}
}
}
//thore: weapon verhaltens und eigenschaften funktion
fn weapon_query(weapon: usize,objects: &mut Vec<Object>, game: &mut Game, monsters: &mut Vec<Object>, projectiles: &mut Vec<Object>){
//thore: zeige schwert und lass es vor dem player erscheinen
if weapon == SWORD{
let x:i32 = objects[PLAYER].x;
let y:i32 = objects[PLAYER].y;
let xy:(i32,i32) = objects[PLAYER].direction;
objects[SWORD].visable = true;
objects[SWORD].update(x, y, xy);
//david test if sword hits enemies
objects[SWORD].fight(monsters);
}
//thore: showel
if weapon == SHOWEL{
let x:i32 = objects[PLAYER].x;
let y:i32 = objects[PLAYER].y;
let xy:(i32,i32) = objects[PLAYER].direction;
objects[SHOWEL].visable = true;
objects[SHOWEL].update(x, y, xy);
if game.map[(objects[SHOWEL].x) as usize][(objects[SHOWEL].y) as usize].blocked {
objects[BUCKET].health += 1;
game.map[(objects[SHOWEL].x) as usize][(objects[SHOWEL].y) as usize] = Tile::empty();
};
}
//thore: bucket
if weapon == BUCKET{
let x:i32 = objects[PLAYER].x;
let y:i32 = objects[PLAYER].y;
let xy:(i32,i32) = objects[PLAYER].direction;
objects[BUCKET].visable = true;
objects[BUCKET].update(x, y, xy);
if objects[BUCKET].health > 1 {
objects[BUCKET].health -= 1;
game.map[(objects[BUCKET].x) as usize][(objects[BUCKET].y) as usize] = Tile::wall();
}
}
//thore: bow
if weapon == BOW{
let x:i32 = objects[PLAYER].x;
let y:i32 = objects[PLAYER].y;
let xy:(i32,i32) = objects[PLAYER].direction;
objects[BOW].visable = true;
objects[BOW].update(x, y, xy);
if objects[BOW].health > 1 {
objects[BOW].health -= 1 ;
//push new arrow to object list
projectiles.push(Object::new("arrow".to_string(), 0, x+xy.0, y+xy.1, 'S', WHITE, true, xy, 100, ['R','S','T','U']));
}
}
//thore: hide all weapons after each farme
if weapon == 0{
objects[SWORD].visable = false;
objects[SHOWEL].visable = false;
objects[BUCKET].visable = false;
objects[BOW].visable = false;
}
//david fightsystem (monsters) will always go in here
if weapon == ARROW && projectiles.len()>0{
//go through all projectiles
for prjctl in projectiles{
//thore: move projectiles aslong its not a wall HIER IST EIN FEHLER ----------------------------------------------------------------------
let new_x = prjctl.x + prjctl.direction.0;
let new_y = prjctl.y + prjctl.direction.1;
if new_x>=0 && new_y>=0 {
if game.map[new_x as usize][new_y as usize].name != "wall" && (prjctl.name =="arrow" || prjctl.name=="stein") {
prjctl.x = new_x;
prjctl.y = new_y;
}
}
if prjctl.name == "arrow"{
//thore: test if player stands on arrow, if so pick it up
if objects[PLAYER].collision(prjctl,0,0,0,0){
objects[BOW].health += 1;
prjctl.health=0;
}
//else test if arrow hits an enemy
else{
//for testing if arrow flew over (passed) an enemy
let dx = prjctl.direction.0;
let dy = prjctl.direction.1;
for i in 0..monsters.len()-1{
//tests if arrow hits an enemy or passed it, if so, delete arrow
if prjctl.collision(&monsters[i],0,0,0,0) || prjctl.collision(&monsters[i], 0,0,dx,dy){
monsters[i].takedmg(100);
prjctl.takedmg(100);
}
}
}
}
else if prjctl.name == "stein"{
//for testing if stein flew over (passed) an player
let dx = prjctl.direction.0;
let dy = prjctl.direction.1;
//test if stein will hit wall, if so delete stein
if game.map[new_x as usize][new_y as usize].name == "wall"{
prjctl.takedmg(100);
}
//tests if stein hit player, if so, delete stein and damage player
else if prjctl.collision(&objects[PLAYER],0,0,0,0) || prjctl.collision(&objects[PLAYER],0,0,dx,dy){
objects[PLAYER].takedmg(1);
prjctl.takedmg(100);
}
}
else if prjctl.name == "spike"{
//test if spike will hit wall, if so delete spike
if game.map[prjctl.x as usize][prjctl.y as usize].name == "wall"{
prjctl.takedmg(100);
}
//tests if spike hit player, if so, delete spike and damage player
else if prjctl.collision(&objects[PLAYER],0,0,0,0){
objects[PLAYER].takedmg(1);
prjctl.takedmg(100);
}
}
//thore: destroy projectiles if hit with sword
if objects[SWORD].visable && objects[SWORD].collision(prjctl,0,0,0,0) {
prjctl.health=0;
}
}
}
}
// Qianli: A rectangle on the map, used to characterise a room.
#[derive(Clone, Copy, Debug)]
struct Rect {
x1: i32,
y1: i32,
x2: i32,
y2: i32,
}
impl Rect {
pub fn new(x: i32, y: i32, w: i32, h: i32) -> Self {
Rect {
x1: x,
y1: y,
x2: x + w,
y2: y + h,
}
}
pub fn center(&self) -> (i32, i32){
let center_x = (self.x1 + self.x2) / 2;
let center_y = (self.y1 + self.y2) / 2;
(center_x, center_y)
}
pub fn intersects_with(&self, other: &Rect) -> bool{
(self.x1 <= other.x2)
&& (self.x2 >= other.x1)
&& (self.y1 <= other.y2)
&& (self.y2 >= other.y1)
}
}
// Qianli: go through the tiles in the rectangle and make them passable
fn create_room(room: Rect, map: &mut Map) {
for x in (room.x1 + 1)..room.x2 {
for y in (room.y1 + 1)..room.y2 {
map[x as usize][y as usize] = Tile::empty();
}
}
}
// Qianli: horizontal tunnel.
fn create_h_tunnel(x1: i32, x2: i32, y: i32, map: &mut Map) {
for x in cmp::min(x1, x2)..(cmp::max(x1, x2) + 1) {
map[x as usize][y as usize] = Tile::empty();
}
}
// Qianli: vertical tunnel
fn create_v_tunnel(y1: i32, y2: i32, x: i32, map: &mut Map) {
for y in cmp::min(y1, y2)..(cmp::max(y1, y2) + 1) {
map[x as usize][y as usize] = Tile::empty();
}
}
// Qianli: create rooms and tunnels randomly.
fn make_map(objects: &mut Vec<Object>) -> (Map, Vec<Rect>) {
// fill map with "blocked" tiles
let mut map = vec![vec![Tile::wall(); MAP_HEIGHT as usize]; MAP_WIDTH as usize];
let mut rooms = vec![];
for _ in 0..MAX_ROOM{
let w = rand::thread_rng().gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1);
let h = rand::thread_rng().gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1);
let x = rand::thread_rng().gen_range(0, MAP_WIDTH - w);
let y = rand::thread_rng().gen_range(0, MAP_HEIGHT - h);
let new_room = Rect::new(x, y, w, h);
// run through the other rooms and see if they intersect with this one
let failed = rooms
.iter()
.any(|other_room| new_room.intersects_with(other_room));
if !failed {
// this means there are no intersections, so this room is valid
// "paint" it to the map's tiles
create_room(new_room, &mut map);
// center coordinates of the new room, will be useful later
let (new_x, new_y) = new_room.center();
if rooms.is_empty() {
// this is the first room, where the player starts at
objects[0].x = new_x;
objects[0].y = new_y;
// Qianli: put the player and npc in the same room while initializing the game(Location randomly)
objects[1].x = rand::thread_rng().gen_range(new_room.x1 + 1, new_room.x2);
objects[1].y = rand::thread_rng().gen_range(new_room.y1 + 1, new_room.y2);
} else {
// all rooms after the first:
// connect it to the previous room with a tunnel
// center coordinates of the previous room
let (prev_x, prev_y) = rooms[rooms.len() - 1].center();
// toss a coin (random bool value -- either true or false)
if rand::random() {
// first move horizontally, then vertically
create_h_tunnel(prev_x, new_x, prev_y, &mut map);
create_v_tunnel(prev_y, new_y, new_x, &mut map);
} else {
// first move vertically, then horizontally
create_v_tunnel(prev_y, new_y, prev_x, &mut map);
create_h_tunnel(prev_x, new_x, new_y, &mut map);
}
}
// finally, append the new room to the list
rooms.push(new_room);
}
}
return (map,rooms);
}
// Qianli: test, whether play has touched the npc
//David: changed the function, tests for health
fn can_survive(objects: &mut Vec<Object>) -> bool{
let player = &objects[0];
return player.health<=0;
}
// Qianli: let npc follow player and sleep for a while
// David: added monster functionality --------------------------------------------------------------------------------------------
#[allow(dead_code)]
fn ai_follow_player(objects: &mut [Object], game: &mut Game, monsters: &mut Vec<Object>){
for monster in monsters{
//test for green monster
if monster.name=="orc"{
//david unblock position on which the monster stands
game.map[monster.x as usize][monster.y as usize].blocked = false;
//distance to player
let dis_x = &objects[PLAYER].x - &monster.x;
let dis_y = &objects[PLAYER].y - &monster.y;
let random = rand::thread_rng().gen_range(0, 2);
if random == 1 && dis_y != 0
{
//david test for collision with player, (do not move into player!)
if objects[PLAYER].collision(monster, 0,0,0, &dis_y / &dis_y.abs()){
//if monster is prepared for attack attack!
if monster.state == 1{
objects[PLAYER].health-=1;
monster.color = GREEN;
monster.state = 0;
}
//prepare for attack
else{
monster.color = RED;
monster.state = 1;
}
}
//else move
else{
monster.move_by(0, &dis_y / &dis_y.abs(), game);
monster.color = GREEN;
}
}
else if dis_x != 0
{
//david test for collision with player, (do not move into player!)
if objects[PLAYER].collision(monster, 0, 0, &dis_x / &dis_x.abs(), 0){
//if monster is prepared for attack attack!
if monster.state == 1{
objects[PLAYER].health-=1;
monster.color = GREEN;
monster.state = 0;
}
//prepare for attack
else{
monster.color = RED;
monster.state = 1;
}
}
//else move
else{
monster.move_by(&dis_x / &dis_x.abs(), 0, game);
monster.color = GREEN;
}
}
//david block the new position on which the monster stands
game.map[monster.x as usize][monster.y as usize].blocked = true;
}
//if not green monster, ignore this ai
else{
}
}
}
//thore, mage does not move but shoot rocks
#[allow(dead_code)]
fn ai_shoot(game: &mut Game, monsters: &mut Vec<Object>, projectiles: &mut Vec<Object>){
for monster in monsters{
//test for mage monster
if monster.name=="shoot"{
// block the position on which the monster stands
game.map[monster.x as usize][monster.y as usize].blocked = true;
//fire attack!
if monster.state == 5{
monster.state = 0;
monster.char='W';
//projectile cords
let x:i32 = monster.x;
let y:i32 = monster.y;
//attacking diraction
let choose = vec![(0,1),(1,0),(-1,0),(0,-1)];
let direction = choose[rand::thread_rng().gen_range(0, 4)];
//push projectile
projectiles.push(Object::new("stein".to_string(), 0, x, y, 'R', RED, true, direction, 100, ['R','S','T','U']));
}
//load more attack
else if monster.state == 4 {
monster.char='Y';
monster.state +=1;
}
//load attack
else if monster.state == 3 || monster.state == 2 || monster.state == 1{
monster.char='X';
monster.state +=1;
}
//prepare for attack
else if monster.state == 0 {
monster.char='W';
monster.state +=1;
}
}
//if not mage monster, ignore this ai
else {
}
}
}
//thore, mage does not move but shoot rocks
#[allow(dead_code)]
fn ai_spikes(game: &mut Game, monsters: &mut Vec<Object>, projectiles: &mut Vec<Object>){
for monster in monsters{
//test for mage monster
if monster.name=="spike"{
// block the position on which the monster stands
game.map[monster.x as usize][monster.y as usize].blocked = true;
//fire attack!
if monster.state == 5{
monster.state = 0;
monster.char='W';
//projectile cords
let x:i32 = monster.x;
let y:i32 = monster.y;
//attacking diraction
let choose = vec![(0,1),(1,0),(-1,0),(0,-1)];
let direction = choose[rand::thread_rng().gen_range(0, 4)];
//push projectile
projectiles.push(Object::new("spike".to_string(), 0, x+direction.0, y+direction.1, 'S', WHITE, true, direction, 100, ['@','[','\\',']']));
}
//load more attack
else if monster.state == 4 {
monster.char='Y';
monster.state +=1;
}
//load attack
else if monster.state == 3 || monster.state == 2 || monster.state == 1{
monster.char='X';
monster.state +=1;
}
//prepare for attack
else if monster.state == 0 {
monster.char='W';
monster.state +=1;
}
}
//if not mage monster, ignore this ai
else {
}
}
}
fn remove_objects_with_zero_health(game: &mut Game, object: &mut Vec<Object>){
//david objects if health 0
let mut i = 0;
while i<object.len(){
if object[i].health<=0{
//david unblock objects position (usefull for monsters)
game.map[object[i].x as usize][object[i].y as usize].blocked = false;
object.remove(i);
}
i+=1;
}
}
//David
fn placing_monster(game: &mut Game, rooms: Vec<Rect>, monsters: &mut Vec<Object>) {
let num_monsters = rand::thread_rng().gen_range(MIN_ROOM_MONSTERS, MAX_ROOM_MONSTERS + 1);
//place monsters in every room but the first (player room)
for i in 0..rooms.len(){
if i == 0 {}
else{
let room = rooms[i];
for _i in 0..num_monsters {
//chose random spot for this monster
let mut x = rand::thread_rng().gen_range(room.x1 + 1, room.x2);
let mut y = rand::thread_rng().gen_range(room.y1 + 1, room.y2);
//try as long as possible to find a free spot for monster
while game.map[x as usize][y as usize].blocked == true{
x = rand::thread_rng().gen_range(room.x1 + 1, room.x2);
y = rand::thread_rng().gen_range(room.y1 + 1, room.y2);
}
//block spot for monster
game.map[x as usize][y as usize].blocked = true;
// rand::random::<f32> will create a random number between 0.0 and 1.0 which is 100%
let rand = rand::random::<f32>();
if rand < RANDOM_ORC {
let orc = Object::new("orc".to_string(), 0, x, y, 'W', GREEN, true, (0,1), 100,['W','w','W','W']);
monsters.append(&mut vec![orc]);
}
else if rand < RANDOM_MAGE {
//append new shoot monster with random state
let shoot = Object::new("shoot".to_string(), rand::thread_rng().gen_range(0,6) , x, y, 'W', PURPLE, true, (0,1), 50, ['W', 'W', 'W', 'W']);
monsters.append(&mut vec![shoot]);
}
else if rand < RANDOM_BRICK {
//append new spike monster with random state
let spike = Object::new("spike".to_string(), rand::thread_rng().gen_range(0,6) , x, y, 'W', LIGHT_FLAME, true, (0,1), 50, ['W', 'W', 'W', 'W']);
monsters.append(&mut vec![spike]);
}
}
}
}
}
fn new_game(tcod: &mut Tcod) -> (Game, Vec<Object>,Vec<Object>, Vec<Object>) {
//thore: added atributes visable, direction health, images to all objects
// create object representing the player
let player = Object::new("player".to_string(), 0, 0, 0, '@', WHITE, true, (0,1), 10, ['A','B','C','D']);
//thore: create all Weapons
let sword = Object::new("sword".to_string(), 0, 0, 0, 'S', WHITE, false, (0,0), 1, ['E','F','G','H']);
let shovel = Object::new("shovel".to_string(), 0, 0, 0, 'S', WHITE, false, (0,0), 1, ['I','J','K','L']);
let bucket = Object::new("bucket".to_string(), 0, 0, 0, 'S', WHITE, false, (0,0), 1, ['M','M','M','M']);
let bow = Object::new("bow".to_string(), 0, 0, 0, 'S', WHITE, false, (0,0), 4, ['N','O','P','Q']);
let arrow = Object::new("arrow".to_string(), 0, 0, 0, 'S', WHITE, false, (0,0), 1, ['R','S','T','U']);
// the list of objects with those two
//thore: added weapon objects to list
let mut objects: Vec<Object> = vec![player, sword, shovel, bucket, bow, arrow];
//thore: added list for projectiles
let projectiles: Vec<Object> = vec![];
//david declare vec list in which monsters will be stored
let mut monsters: Vec<Object> = vec![];
// generate map (at this point it's not drawn to the screen)
let map_and_rooms = make_map(&mut objects);
let rooms = map_and_rooms.1;
let mut game = Game {
map: map_and_rooms.0,
};
//add a number of monsters to each room
placing_monster(&mut game, rooms, &mut monsters);
initialise_fov(tcod, &game.map);
(game, objects,monsters,projectiles)
}
fn initialise_fov(tcod: &mut Tcod, map: &Map) {
//jonny: fov
for y in MAP_START_HEIGHT..MAP_HEIGHT {
for x in 0..MAP_WIDTH {
tcod.fov.set(
x,
y,
!map[x as usize][y as usize].block_sight, ///////////////////////////////////////////////////////////////////////
!map[x as usize][y as usize].blocked,
);
}
}
// unexplored areas start black (which is the default background color)
tcod.con.clear();
}
fn play_game(tcod: &mut Tcod, game: &mut Game, objects: &mut Vec<Object>, torch_radius: i32, monsters: &mut Vec<Object>, projectiles: &mut Vec<Object>) {
let mut previous_player_position = (-1, -1); //jonny: FOV neu berechnen
//game loop
while !tcod.root.window_closed() {
tcod.con.clear();
//thore: check for animation
animation(objects);
animation(projectiles);
let fov_recompute = previous_player_position != (objects[PLAYER].pos());//jonny
render_all( tcod, game, objects, fov_recompute,torch_radius, monsters, projectiles );
tcod.root.flush();
previous_player_position = objects[PLAYER].pos(); //jonny
//monster actions
ai_follow_player( objects, game, monsters);
ai_shoot(game, monsters, projectiles);
ai_spikes(game, monsters, projectiles);
// handle keys and exit game if needed
let exit = handle_keys(tcod, game, objects, monsters, projectiles);
//remove monsters (after handle keys_ so that player can attack fist)
remove_objects_with_zero_health(game, monsters);
//remove projectiles
remove_objects_with_zero_health(game, projectiles);
if exit {
save_game(game, objects,torch_radius, monsters, projectiles).unwrap();
break;
}
if monsters.len()<= 0 {
msgbox("\nherzlichen glueckwunsch du lappen, du hast gewonnen\n", 24, &mut tcod.root);
break;
}
// Qianli: check for the break condition
if can_survive( objects) {
msgbox("\ndu bist gestorben.\n\ndruecke eine beliebige taste um ins hauptmenue zu gelangen.\n", 24, &mut tcod.root);
break}
}
}
fn menu<T: AsRef<str>>(header: &str, options: &[T], width: i32, root: &mut Root) -> Option<usize> {
assert!(
options.len() <= 26, //Buchstaben von A-Z
"cannot have a menu with more than 26 options."
);
// calculate total height for the header (after auto-wrap) and one line per option
let header_height = if header.is_empty() {
0
} else {
root.get_height_rect(0, 0, width, SCREEN_HEIGHT, header)
};
let height = options.len() as i32 + header_height;
// create an off-screen console that represents the menu's window
let mut window = Offscreen::new(width, height);
// print the header, with auto-wrap
window.set_default_foreground(WHITE);
window.print_rect_ex(
0,
0,
width,
height,
BackgroundFlag::None,
TextAlignment::Left,
header,
);
// print all the options
for (index, option_text) in options.iter().enumerate() {
let menu_letter = (b'a' + index as u8) as char;
let text = format!("({}) {}", menu_letter, option_text.as_ref());
window.print_ex(
0,
header_height + index as i32,
BackgroundFlag::None,
TextAlignment::Left,
text,
);
}
// blit the contents of "window" to the root console
let x = SCREEN_WIDTH / 2 - width / 2;
let y = SCREEN_HEIGHT / 2 - height / 2;
blit(&window, (0, 0), (width, height), root, (x, y), 1.0, 0.7);
// present the root console to the player and wait for a key-press
root.flush();
let key = root.wait_for_keypress(true);
// convert the ASCII code to an index; if it corresponds to an option, return it
if key.printable.is_alphabetic() {
let index = key.printable.to_ascii_lowercase() as usize - 'a' as usize;
if index < options.len() {
Some(index)
} else {
None
}
} else {
None
}
}
fn main_menu(tcod: &mut Tcod) {
let img = tcod::image::Image::from_file("bg.png")
.ok()
.expect("Hintergrund nicht gefunden");
tcod.root.set_default_foreground(LIGHT_YELLOW);
tcod.root.print_ex(
SCREEN_WIDTH / 2,
SCREEN_HEIGHT / 2 - 4,
BackgroundFlag::None,
TextAlignment::Center,
"Test2",
);
tcod.root.print_ex(
SCREEN_WIDTH / 2,
SCREEN_HEIGHT - 2,
BackgroundFlag::None,
TextAlignment::Center,
"Test1",
);
while !tcod.root.window_closed() {
// show the background image, at twice the regular console resolution
tcod::image::blit_2x(&img, (0, 0), (-1, -1), &mut tcod.root, (0, 0));
// show options and wait for the player's choice
let choices = &["neues Spiel", "spiel fortsetzen", "hardcore mode","verlassen"];
let choice = menu("", choices, 24, &mut tcod.root);
let torch_radius: i32 = 10; //FOV Radius
match choice {
Some(0) => {
// new game
let (mut game, mut objects, mut monsters, mut projectiles) = new_game(tcod);
play_game(tcod, &mut game, &mut objects, torch_radius, &mut monsters, &mut projectiles);
}
Some(1) => {
// load game
match load_game() {
Ok((mut game, mut objects, torch_radius, mut monsters, mut projectiles)) => {
initialise_fov(tcod, &game.map);
play_game(tcod, &mut game, &mut objects, torch_radius, &mut monsters, &mut projectiles);
}
Err(_e) => {
msgbox("\nNo saved game to load.\n", 24, &mut tcod.root);
continue;
}
}
}
Some(2) => {
// new game
let torch_radius: i32 = 2;
let (mut game, mut objects, mut monsters, mut projectiles) = new_game(tcod);
play_game(tcod, &mut game, &mut objects,torch_radius, &mut monsters, &mut projectiles);
}
Some(3) => {
// quit
break;
}
_ => {}
}
}
}
fn msgbox(text: &str, width: i32, root: &mut Root) {
let options: &[&str] = &[];
menu(text, options, width, root);
}
fn save_game(game: &Game, objects: &[Object], torch_radius: i32, monsters: &mut [Object], projectiles: &mut [Object]) -> Result<(), Box<dyn Error>> {
let save_data = serde_json::to_string(&(game, objects, torch_radius, monsters, projectiles))?;
let mut file = File::create("savegame")?;
file.write_all(save_data.as_bytes())?;
Ok(())
}
fn load_game() -> Result<(Game, Vec<Object>, i32, Vec<Object>, Vec<Object>), Box<dyn Error>> {
let mut json_save_state = String::new();
let mut file = File::open("savegame")?;
file.read_to_string(&mut json_save_state)?;
let result = serde_json::from_str::<(Game, Vec<Object>, i32, Vec<Object>, Vec<Object>)>(&json_save_state)?;
Ok(result)
}
fn main() {
//Window
let root = Root::initializer()
.font("sprites.png" , FontLayout::Tcod)
.font_type(FontType::Greyscale)
.size(SCREEN_WIDTH, SCREEN_HEIGHT)
.title("WindowName")
.init();
//Screen Console
let mut tcod = Tcod {
root,
con: Offscreen::new(MAP_WIDTH, MAP_HEIGHT),
fov: FovMap::new(MAP_WIDTH, MAP_HEIGHT), //Jonny FOV
};
tcod::system::set_fps(LIMIT_FPS);
main_menu(&mut tcod);
}
|
#[doc = "Register `MMCTIMR` reader"]
pub type R = crate::R<MMCTIMR_SPEC>;
#[doc = "Register `MMCTIMR` writer"]
pub type W = crate::W<MMCTIMR_SPEC>;
#[doc = "Field `TGFSCM` reader - Transmitted good frames single collision mask"]
pub type TGFSCM_R = crate::BitReader<TGFSCM_A>;
#[doc = "Transmitted good frames single collision mask\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TGFSCM_A {
#[doc = "0: Transmitted-good-single-collision half-full interrupt enabled"]
Unmasked = 0,
#[doc = "1: Transmitted-good-single-collision half-full interrupt disabled"]
Masked = 1,
}
impl From<TGFSCM_A> for bool {
#[inline(always)]
fn from(variant: TGFSCM_A) -> Self {
variant as u8 != 0
}
}
impl TGFSCM_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TGFSCM_A {
match self.bits {
false => TGFSCM_A::Unmasked,
true => TGFSCM_A::Masked,
}
}
#[doc = "Transmitted-good-single-collision half-full interrupt enabled"]
#[inline(always)]
pub fn is_unmasked(&self) -> bool {
*self == TGFSCM_A::Unmasked
}
#[doc = "Transmitted-good-single-collision half-full interrupt disabled"]
#[inline(always)]
pub fn is_masked(&self) -> bool {
*self == TGFSCM_A::Masked
}
}
#[doc = "Field `TGFSCM` writer - Transmitted good frames single collision mask"]
pub type TGFSCM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TGFSCM_A>;
impl<'a, REG, const O: u8> TGFSCM_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Transmitted-good-single-collision half-full interrupt enabled"]
#[inline(always)]
pub fn unmasked(self) -> &'a mut crate::W<REG> {
self.variant(TGFSCM_A::Unmasked)
}
#[doc = "Transmitted-good-single-collision half-full interrupt disabled"]
#[inline(always)]
pub fn masked(self) -> &'a mut crate::W<REG> {
self.variant(TGFSCM_A::Masked)
}
}
#[doc = "Field `TGFMSCM` reader - Transmitted good frames more than single collision mask"]
pub type TGFMSCM_R = crate::BitReader<TGFMSCM_A>;
#[doc = "Transmitted good frames more than single collision mask\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TGFMSCM_A {
#[doc = "0: Transmitted-good-multiple-collision half-full interrupt enabled"]
Unmasked = 0,
#[doc = "1: Transmitted-good-multiple-collision half-full interrupt disabled"]
Masked = 1,
}
impl From<TGFMSCM_A> for bool {
#[inline(always)]
fn from(variant: TGFMSCM_A) -> Self {
variant as u8 != 0
}
}
impl TGFMSCM_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TGFMSCM_A {
match self.bits {
false => TGFMSCM_A::Unmasked,
true => TGFMSCM_A::Masked,
}
}
#[doc = "Transmitted-good-multiple-collision half-full interrupt enabled"]
#[inline(always)]
pub fn is_unmasked(&self) -> bool {
*self == TGFMSCM_A::Unmasked
}
#[doc = "Transmitted-good-multiple-collision half-full interrupt disabled"]
#[inline(always)]
pub fn is_masked(&self) -> bool {
*self == TGFMSCM_A::Masked
}
}
#[doc = "Field `TGFMSCM` writer - Transmitted good frames more than single collision mask"]
pub type TGFMSCM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TGFMSCM_A>;
impl<'a, REG, const O: u8> TGFMSCM_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Transmitted-good-multiple-collision half-full interrupt enabled"]
#[inline(always)]
pub fn unmasked(self) -> &'a mut crate::W<REG> {
self.variant(TGFMSCM_A::Unmasked)
}
#[doc = "Transmitted-good-multiple-collision half-full interrupt disabled"]
#[inline(always)]
pub fn masked(self) -> &'a mut crate::W<REG> {
self.variant(TGFMSCM_A::Masked)
}
}
#[doc = "Field `TGFM` reader - Transmitted good frames mask"]
pub type TGFM_R = crate::BitReader<TGFM_A>;
#[doc = "Transmitted good frames mask\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TGFM_A {
#[doc = "0: Transmitted-good counter half-full interrupt enabled"]
Unmasked = 0,
#[doc = "1: Transmitted-good counter half-full interrupt disabled"]
Masked = 1,
}
impl From<TGFM_A> for bool {
#[inline(always)]
fn from(variant: TGFM_A) -> Self {
variant as u8 != 0
}
}
impl TGFM_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TGFM_A {
match self.bits {
false => TGFM_A::Unmasked,
true => TGFM_A::Masked,
}
}
#[doc = "Transmitted-good counter half-full interrupt enabled"]
#[inline(always)]
pub fn is_unmasked(&self) -> bool {
*self == TGFM_A::Unmasked
}
#[doc = "Transmitted-good counter half-full interrupt disabled"]
#[inline(always)]
pub fn is_masked(&self) -> bool {
*self == TGFM_A::Masked
}
}
#[doc = "Field `TGFM` writer - Transmitted good frames mask"]
pub type TGFM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TGFM_A>;
impl<'a, REG, const O: u8> TGFM_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Transmitted-good counter half-full interrupt enabled"]
#[inline(always)]
pub fn unmasked(self) -> &'a mut crate::W<REG> {
self.variant(TGFM_A::Unmasked)
}
#[doc = "Transmitted-good counter half-full interrupt disabled"]
#[inline(always)]
pub fn masked(self) -> &'a mut crate::W<REG> {
self.variant(TGFM_A::Masked)
}
}
impl R {
#[doc = "Bit 14 - Transmitted good frames single collision mask"]
#[inline(always)]
pub fn tgfscm(&self) -> TGFSCM_R {
TGFSCM_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - Transmitted good frames more than single collision mask"]
#[inline(always)]
pub fn tgfmscm(&self) -> TGFMSCM_R {
TGFMSCM_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 21 - Transmitted good frames mask"]
#[inline(always)]
pub fn tgfm(&self) -> TGFM_R {
TGFM_R::new(((self.bits >> 21) & 1) != 0)
}
}
impl W {
#[doc = "Bit 14 - Transmitted good frames single collision mask"]
#[inline(always)]
#[must_use]
pub fn tgfscm(&mut self) -> TGFSCM_W<MMCTIMR_SPEC, 14> {
TGFSCM_W::new(self)
}
#[doc = "Bit 15 - Transmitted good frames more than single collision mask"]
#[inline(always)]
#[must_use]
pub fn tgfmscm(&mut self) -> TGFMSCM_W<MMCTIMR_SPEC, 15> {
TGFMSCM_W::new(self)
}
#[doc = "Bit 21 - Transmitted good frames mask"]
#[inline(always)]
#[must_use]
pub fn tgfm(&mut self) -> TGFM_W<MMCTIMR_SPEC, 21> {
TGFM_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "Ethernet MMC transmit interrupt mask register (ETH_MMCTIMR)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmctimr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`mmctimr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct MMCTIMR_SPEC;
impl crate::RegisterSpec for MMCTIMR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`mmctimr::R`](R) reader structure"]
impl crate::Readable for MMCTIMR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`mmctimr::W`](W) writer structure"]
impl crate::Writable for MMCTIMR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets MMCTIMR to value 0"]
impl crate::Resettable for MMCTIMR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::collections::HashMap;
fn orbit_count(orbits: &HashMap<String, Vec<String>>, object: &str, current: u32) -> u32 {
current + match orbits.get(object) {
Some(orbiting_objects) => orbiting_objects.iter().map(|x| orbit_count(orbits, x, current + 1)).sum(),
None => 0
}
}
fn main() {
let reader = BufReader::new(File::open("input.txt").unwrap());
let mut orbits = HashMap::new();
for line in reader.lines() {
let line = line.unwrap();
let objects: Vec<_> = line.split(')').collect();
let a = objects[0].to_string();
let b = objects[1].to_string();
orbits.entry(a).or_insert(vec!()).push(b);
}
println!("{}", orbit_count(&orbits, "COM", 0));
} |
//! A helper module which contains functionality to run feasibility checks on solution.
use vrp_pragmatic::checker::CheckerContext;
use vrp_pragmatic::format::problem::{deserialize_matrix, deserialize_problem, PragmaticProblem};
use vrp_pragmatic::format::solution::deserialize_solution;
use std::io::{BufReader, Read};
use std::process;
use std::sync::Arc;
use vrp_pragmatic::format::FormatError;
/// Checks pragmatic solution feasibility.
pub fn check_pragmatic_solution<F: Read>(
problem_reader: BufReader<F>,
solution_reader: BufReader<F>,
matrices_readers: Option<Vec<BufReader<F>>>,
) -> Result<(), Vec<String>> {
let problem = deserialize_problem(problem_reader).unwrap_or_else(|errs| {
eprintln!("cannot read problem: '{}'", FormatError::format_many(&errs, ","));
process::exit(1);
});
let solution = deserialize_solution(solution_reader).unwrap_or_else(|err| {
eprintln!("cannot read solution: '{}'", err);
process::exit(1);
});
let matrices = matrices_readers.map(|matrices| {
matrices
.into_iter()
.map(|file| {
deserialize_matrix(BufReader::new(file)).unwrap_or_else(|errs| {
eprintln!("cannot read matrix: '{}'", FormatError::format_many(&errs, ","));
process::exit(1);
})
})
.collect::<Vec<_>>()
});
let core_problem = Arc::new((problem.clone(), matrices.clone()).read_pragmatic().unwrap_or_else(|err| {
eprintln!("cannot read pragmatic problem: {}", FormatError::format_many(&err, ","));
process::exit(1);
}));
CheckerContext::new(core_problem, problem, matrices, solution).check()
}
|
use crate::{alphabet::Alphabet, nfa::NFA, range_set::Range, state::State};
use core::cmp::Ordering;
use hashbrown::HashSet;
use valis_ds::set::{Set, VectorSet};
// this variant of an NFA does not have any epsilon transitions
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct StandardNFA<A: Alphabet, I: State> {
// set of states that indicate that the input is accepted
accept_states: HashSet<I>,
// transitions each state has a VectorSet and the ordering in each vector set is by the present
// symbols of the alphabet
transitions: Vec<VectorSet<Transition<A, I>>>,
// The states that nfa simulations start from
start_states: HashSet<I>,
// Acceptable state values
states: Range<I>,
}
impl<A, I> StandardNFA<A, I>
where
A: Alphabet,
I: State,
{
pub fn new(
states: Range<I>,
transitions: Vec<VectorSet<Transition<A, I>>>,
accept_states: HashSet<I>,
start_states: HashSet<I>,
) -> Self {
assert_eq!(transitions.len(), states.size());
debug_assert!(transitions.iter().all(|transitions| transitions
.into_iter()
.all(|trans| states.contains(trans.1))));
debug_assert!(Set::is_subset(&start_states, &states));
debug_assert!(Set::is_subset(&accept_states, &states));
StandardNFA {
states,
transitions,
accept_states,
start_states,
}
}
#[inline]
pub fn states(&self) -> &Range<I> {
&self.states
}
#[inline]
pub fn transitions(&self) -> &[VectorSet<Transition<A, I>>] {
&self.transitions
}
#[inline]
pub fn start_states(&self) -> &HashSet<I> {
&self.start_states
}
#[inline]
pub fn accept_states(&self) -> &HashSet<I> {
&self.accept_states
}
pub(crate) fn lookup(&self, state: I, sym: A) -> impl Iterator<Item = I> + '_ {
self.transitions[state.to_usize()]
.as_slice()
.iter()
.filter_map(move |trans| if trans.0 == sym { Some(trans.1) } else { None })
}
}
impl<A: Alphabet, I: State> NFA<A> for StandardNFA<A, I> {
type ID = I;
#[inline]
fn start_states(&self) -> HashSet<Self::ID> {
self.start_states.clone()
}
#[inline]
fn all_states(&self) -> &Range<Self::ID> {
self.states()
}
fn next_states(&self, current: &HashSet<Self::ID>, sym: A) -> Vec<Self::ID> {
current
.iter()
.flat_map(|state| self.lookup(*state, sym))
.collect()
}
fn is_accept(&self, states: &HashSet<Self::ID>) -> bool {
states
.iter()
.any(|state| self.accept_states.contains(state))
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Transition<A: Alphabet, I: State>(pub A, pub I);
impl<A: Alphabet, I: State> From<(A, I)> for Transition<A, I> {
fn from((sym, state): (A, I)) -> Self {
Transition(sym, state)
}
}
impl<A: Alphabet, I: State> PartialOrd for Transition<A, I> {
fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
Some(self.cmp(rhs))
}
}
impl<A: Alphabet, I: State> Ord for Transition<A, I> {
fn cmp(&self, rhs: &Self) -> Ordering {
let (Transition(sym_l, state_l), Transition(sym_r, state_r)) = (self, rhs);
sym_l
.to_usize()
.cmp(&sym_r.to_usize())
.then(state_l.cmp(&state_r))
}
}
|
use std::collections::{VecDeque, HashSet};
use crate::days::day22::{parse_input, default_input};
pub fn run() {
println!("{}", combat_str(default_input()).unwrap())
}
pub fn combat_str(input : &str) -> Result<i64, ()> {
let (p1, p2) = parse_input(input);
combat(p1, p2)
}
pub fn combat(mut p1: VecDeque<i64>, mut p2 : VecDeque<i64>) -> Result<i64, ()> {
simulate_game(&mut p1, &mut p2);
let final_stack;
if p1.is_empty() {
final_stack = p2;
} else {
final_stack = p1;
}
Ok(calculate_score(&final_stack))
}
fn calculate_score(stack : &VecDeque<i64>) -> i64 {
stack.iter().rev().enumerate().map(|(i, v)| v * (i as i64 +1)).sum()
}
fn combat_winner(mut p1: VecDeque<i64>, mut p2 : VecDeque<i64>) -> bool {
if p1.iter().max() > p2.iter().max() {
return true
}
simulate_game(&mut p1, &mut p2);
if p1.is_empty() {
false
} else {
true
}
}
fn simulate_game(p1 : &mut VecDeque<i64>, p2 : &mut VecDeque<i64>) {
let mut happened: HashSet<(i64, i64)> = HashSet::new();
while !(p1.is_empty() | p2.is_empty()) {
if !happened.insert((calculate_score(&p1), calculate_score(&p2))) {
p2.clear();
break;
}
let card1 = p1.pop_front().unwrap();
let card2 = p2.pop_front().unwrap();
if (p1.len() as i64 >= card1) & (p2.len() as i64 >= card2) {
if combat_winner(p1.iter().take(card1 as usize).map(|n| *n).collect(), p2.iter().take(card2 as usize).map(|n| *n).collect()) {
p1.push_back(card1);
p1.push_back(card2);
} else {
p2.push_back(card2);
p2.push_back(card1);
}
} else {
if card1 > card2 {
p1.push_back(card1);
p1.push_back(card2);
} else {
p2.push_back(card2);
p2.push_back(card1);
}
}
}
}
#[cfg(test)]
pub mod tests {
use super::*;
#[test]
pub fn example() {
assert_eq!(combat_str("Player 1:
9
2
6
3
1
Player 2:
5
8
4
7
10").unwrap(), 291)
}
#[test]
pub fn part2_answer() {
assert_eq!(combat_str(default_input()).unwrap(), 32317)
}
} |
#![allow(dead_code)]
use library::doc::DocType::*;
use library::lexeme::definition::TokenType::*;
use library::lexeme::definition::{TokenKind, TokenType};
use library::lexeme::token::Token;
use library::parser::helper::*;
use library::parser::rust_type::*;
#[derive(Debug)]
struct SymbolTable {
symbol_type: TokenType,
symbol_modifier: Modifier,
id_name: String,
is_assigned: bool,
is_ptr: bool,
assigned_val: String,
}
#[derive(Debug)]
struct CStructMem {
name: String,
member_type: TokenType,
identifier: String,
}
impl Clone for SymbolTable {
fn clone(&self) -> SymbolTable {
let id = self.id_name.clone();
let val = self.assigned_val.clone();
SymbolTable {
assigned_val: val,
id_name: id,
symbol_modifier: self.symbol_modifier,
symbol_type: self.symbol_type,
is_ptr: self.is_ptr,
is_assigned: self.is_assigned,
}
}
}
impl Clone for CStructMem {
fn clone(&self) -> CStructMem {
CStructMem {
name: self.name.clone(),
member_type: self.member_type,
identifier: self.identifier.clone(),
}
}
}
struct Parser {
from: usize,
//for symbol table
once_warned: bool,
//default false
in_block_stmnt: bool,
//default false
in_expr: bool,
//default false
in_switch: bool,
//defalt false
strict: bool,
//default true
in_main: bool,
sym_tab: Vec<SymbolTable>,
// structure book keeping
struct_mem: Vec<CStructMem>,
typde_def_table: Vec<String>,
struct_in_body_declaration: bool,
}
pub fn init_parser(lexeme: &Vec<Token>, strict_parser: bool) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
stream.push(CRUST.get_doc().to_string());
let mut parser = Parser {
from: 0,
once_warned: false,
in_block_stmnt: false,
in_expr: false,
in_switch: false,
strict: strict_parser,
in_main: false,
sym_tab: Vec::new(),
struct_mem: Vec::new(),
typde_def_table: Vec::new(),
struct_in_body_declaration: false,
};
stream.append(&mut parser.parse_program(&lexeme));
stream
}
impl Parser {
fn parse_program(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut head: usize = 0;
let mut lookahead: usize;
let mut temp_lexeme: Vec<Token> = Vec::new();
while head < lexeme.len() {
lookahead = head;
//match over token kind and token type
match lexeme[head].get_type() {
(TokenKind::Typedef, Typedef) => {
//typedef STRUCT struct_t or
//typedef struct typename {struct_def} new_type_name;
if lexeme[head + 1].get_token_type() == KeywordStruct {
//read in struct definition
while lexeme[head].get_token_type() != RightCurlyBrace {
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
}
while lexeme[head].get_token_type() != Semicolon {
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
temp_lexeme.push(lexeme[head].clone());
stream.append(&mut self.parse_typdef(&temp_lexeme));
head += 1;
temp_lexeme.clear();
}
// matches any datatype
(TokenKind::DataTypes, _) => {
//if token is modifiers , move lookahead pointer to next lexeme
if lexeme[head].get_token_type() == Signed
|| lexeme[head].get_token_type() == Unsigned
{
lookahead += 1;
}
//To see whats after the given identifier
//ex : int a = 0; int a;
// int foo(){}
lookahead += 2;
match lexeme[lookahead].get_token_type() {
// function declaration
LeftBracket => {
//inside the function
self.in_block_stmnt = true;
//move till end of function argument declaration
while lexeme[lookahead].get_token_type() != RightBracket {
lookahead += 1;
}
//move ahead of )
lookahead += 1;
// skip function body declaration
if lexeme[lookahead].get_token_type() != LeftCurlyBrace {
lookahead += 1;
head = lookahead;
//FIXME : Why is continue here ?
//continue; ??
}
// advance lookahead to end of block
lookahead = skip_block(&lexeme, lookahead + 1);
// collect entire function block
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
//parse function block
stream.append(&mut self.parse_function(&temp_lexeme));
temp_lexeme.clear();
self.in_block_stmnt = false;
}
//array declaration found
LeftSquareBracket => {
lookahead = skip_stmt(&lexeme, lookahead);
// collect variable declaration
while head != lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse declaration
stream.append(&mut self.parse_array_declaration(&temp_lexeme));
temp_lexeme.clear();
}
// variable declaration or declaration + assignment
Semicolon | Comma | Assignment => {
lookahead = skip_stmt(&lexeme, lookahead);
// collect variable declaration
while head != lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse declaration
stream.append(&mut self.parse_declaration(&temp_lexeme, false));
temp_lexeme.clear();
}
Identifier => {
//in case of pointer declaration : int *a;
while lexeme[head].get_token_type() != Semicolon {
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
temp_lexeme.push(lexeme[head].clone());
stream.append(&mut self.parse_declaration(&temp_lexeme, false));
head += 1;
temp_lexeme.clear();
}
_ => {}
};
}
// matches if statement
(TokenKind::Keyword, KeywordIf) => {
// let mut temp_lexeme: Vec<Token> = Vec::new();
// move lookahead past conditon
while lexeme[lookahead].get_token_type() != RightBracket {
lookahead += 1;
}
lookahead += 1;
// move lookahead past block
if lexeme[lookahead].get_token_type() == LeftCurlyBrace {
lookahead = skip_block(&lexeme, lookahead + 1);
}
// move lookahead past block for 'if' without braces
else {
lookahead = skip_stmt(&lexeme, lookahead);
}
// collect if block
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse if
stream.append(&mut self.parse_if(&temp_lexeme));
temp_lexeme.clear();
}
(TokenKind::Keyword, KeywordElse) => {
stream.push("else".to_string());
head += 1;
lookahead = head;
if lexeme[head].get_token_type() == KeywordIf {
continue;
} else {
if lexeme[lookahead].get_token_type() == LeftCurlyBrace {
head += 1;
lookahead = skip_block(&lexeme, head) - 1;
} else {
lookahead = skip_stmt(&lexeme, lookahead);
}
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
//** parse else body
stream.push("{".to_string());
stream.append(&mut self.parse_program(&temp_lexeme));
temp_lexeme.clear();
stream.push("}".to_string());
}
}
(TokenKind::Keyword, KeywordSwitch) => {
while lexeme[lookahead].get_token_type() != LeftCurlyBrace {
lookahead += 1;
}
lookahead += 1;
lookahead = skip_block(&lexeme, lookahead);
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
self.in_switch = true;
stream.append(&mut self.parse_switch(&temp_lexeme));
temp_lexeme.clear();
self.in_switch = false;
}
(TokenKind::Keyword, KeywordWhile) => {
// let mut temp_lexeme: Vec<Token> = Vec::new();
// move lookahead past conditon
while lexeme[lookahead].get_token_type() != RightBracket {
lookahead += 1;
}
lookahead += 1;
// move lookahead past block
if lexeme[lookahead].get_token_type() == LeftCurlyBrace {
lookahead = skip_block(&lexeme, lookahead + 1);
}
// move lookahead past block for 'if' without braces
else {
lookahead = skip_stmt(&lexeme, lookahead);
}
// collect if block
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
let was_in_switch: bool;
was_in_switch = self.in_switch;
self.in_switch = false;
// parse if
stream.append(&mut self.parse_while(&temp_lexeme));
self.in_switch = was_in_switch;
temp_lexeme.clear();
}
// matches do while statement
(TokenKind::Keyword, KeywordDo) => {
// move lookahead past block
lookahead = skip_block(&lexeme, lookahead + 2);
lookahead = skip_stmt(&lexeme, lookahead);
// collect while block
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse while
let was_in_switch: bool;
was_in_switch = self.in_switch;
self.in_switch = false;
stream.append(&mut self.parse_dowhile(&temp_lexeme));
temp_lexeme.clear();
self.in_switch = was_in_switch;
}
// matches for statement
(_, KeywordFor) => {
//read till end of for()
while lexeme[lookahead].get_token_type() != RightBracket {
lookahead += 1;
}
//forward the look ahead buffer if block statements found
lookahead += 1;
if lexeme[lookahead].get_token_type() == LeftCurlyBrace {
/*
for(x;y;z){
c=a+b;
}*/
lookahead = skip_block(&lexeme, lookahead);
} else {
/*
for(x;y;z)
c=a+b;
*/
//read till end of following expression/statement. i.e semicolon
lookahead = skip_stmt(&lexeme, lookahead);
}
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
let was_in_switch = self.in_switch;
self.in_switch = false;
stream.append(&mut self.parse_for(&temp_lexeme));
temp_lexeme.clear();
self.in_switch = was_in_switch;
}
// matches single and multi-line comment
(TokenKind::Comments, _) => {
stream.push(lexeme[head].get_token_value() + "\n");
head += 1;
}
// assignment statements
(_, Identifier) => {
// let mut temp_lexeme: Vec<Token> = Vec::new();
//identifier = expr
//identifier()
//identifier+expr
//identifier OP_INC|OP_DEC; =>postfix
match lexeme[head + 1].get_type() {
(TokenKind::Identifiers, Identifier) => {
if self
.typde_def_table
.contains(&lexeme[head].get_token_value())
{
lookahead = skip_stmt(&lexeme, lookahead);
// collect variable declaration
while head != lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse declaration
stream.append(&mut self.parse_declaration(&temp_lexeme, false));
} else {
while lexeme[head].get_token_type() != Semicolon {
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
temp_lexeme.push(lexeme[head].clone());
head += 1;
stream.append(&mut self.parse_class_decl(&temp_lexeme));
}
temp_lexeme.clear();
}
(TokenKind::AssignmentOperators, Assignment) => {
// move lookahead past statement
if lexeme[head + 3].get_token_type() == Comma {
lookahead = head + 3;
while head < lookahead + 1 {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
stream.append(&mut self.parse_assignment(&temp_lexeme));
temp_lexeme.clear();
} else {
lookahead = skip_stmt(&lexeme, lookahead);
// collect statement
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse assignment
stream.append(&mut self.parse_assignment(&temp_lexeme));
temp_lexeme.clear();
}
}
(TokenKind::UnaryOperators, _) => {
if self.in_expr != true {
stream.push(lexeme[head].get_token_value());
stream.push(match lexeme[head + 1].get_token_type() {
Increment => "+=1".to_string(),
Decrement => "-=1".to_string(),
_ => " ;".to_string(),
});
head += 2;
} else {
head += 2;
}
}
(TokenKind::BinaryOperators, _) => {
lookahead = skip_stmt(&lexeme, lookahead);
//check if overloaded operators is in effect like << >>
if lexeme[head + 2].get_token_type() == StringValue
|| lexeme[head + 2].get_token_type() == CharValue
{
stream.push(
"\n//This statement need to be handled manually \n".to_string(),
);
while head < lookahead {
stream.push(lexeme[head].get_token_value());
head += 1;
}
} else {
// move lookahead past statement
// collect statement
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse assignment
stream.append(&mut self.parse_expr(&temp_lexeme));
temp_lexeme.clear();
}
}
(TokenKind::SpecialChars, LeftBracket) => {
//function call?
let mut temp_lexeme: Vec<Token> = Vec::new();
stream.push(lexeme[head].get_token_value());
stream.push(lexeme[head + 1].get_token_value());
head += 2;
let lookahead = skip_paranthised_block(&lexeme, head);
while head < lookahead - 1 {
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
let mut parsed_expr = self.parse_params(&temp_lexeme);
stream.append(&mut parsed_expr);
stream.push(lexeme[head].get_token_value());
head += 1;
}
// (_, LEFT_SBRACKET) => {
// while lexeme[head].get_token_type() != RIGHT_SBRACKET {
// stream.push(lexeme[head].get_token_value());
// head += 1;
// }
// stream.push(lexeme[head].get)
// }
(_, _) => {
if lexeme[head].get_token_type() != RightCurlyBrace {
stream.push(lexeme[head].get_token_value());
}
head += 1;
}
};
}
(TokenKind::UnaryOperators, _) => {
stream.push(lexeme[head + 1].get_token_value());
stream.push(match lexeme[head].get_token_type() {
Increment => "+=1".to_string(),
Decrement => "-=1".to_string(),
_ => " ;".to_string(),
});
head += 2;
}
(_, KeywordStruct) => {
if lexeme[head + 2].get_token_type() == LeftCurlyBrace {
//struct A{};
while lexeme[head].get_token_type() != RightCurlyBrace {
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
//push the right curly brace
temp_lexeme.push(lexeme[head].clone());
stream.append(&mut self.parse_struct(&temp_lexeme));
temp_lexeme.clear();
head += 2; //skip semicolon
} else {
//struct variable declaration
while lexeme[head].get_token_type() != Semicolon {
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
temp_lexeme.push(lexeme[head].clone());
head += 1;
stream.append(&mut self.parse_struct_decl(&temp_lexeme));
temp_lexeme.clear();
}
}
(_, KeywordUnion) => {
if lexeme[head + 2].get_token_type() == LeftCurlyBrace {
stream.push(UNION.get_doc().to_string());
//struct A{};
while lexeme[head].get_token_type() != RightCurlyBrace {
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
//push the right curly brace
temp_lexeme.push(lexeme[head].clone());
stream.append(&mut self.parse_union(&temp_lexeme));
temp_lexeme.clear();
head += 2; //skip semicolon
} else {
//struct variable declaration
while lexeme[head].get_token_type() != Semicolon {
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
temp_lexeme.push(lexeme[head].clone());
head += 1;
stream.append(&mut self.parse_union_decl(&temp_lexeme));
temp_lexeme.clear();
}
}
(_, KeywordClass) => {
if lexeme[head + 2].get_token_type() == LeftCurlyBrace {
//struct A{};
while lexeme[head].get_token_type() != RightCurlyBrace
|| lexeme[head + 1].get_token_type() != Semicolon
{
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
//push the right curly brace
temp_lexeme.push(lexeme[head].clone());
stream.append(&mut self.parse_class(&temp_lexeme));
temp_lexeme.clear();
head += 2; //skip semicolon
}
}
(_, KeywordEnum) => {
while lexeme[head].get_token_type() != Semicolon {
stream.push(lexeme[head].get_token_value());
head += 1;
}
head += 1;
}
(_, KeywordReturn) => {
let mut t = head;
stream.push(NO_RETURN.get_doc().to_string());
while lexeme[t].get_token_type() != Semicolon {
t += 1;
}
if t != lexeme.len() - 1 {
while lexeme[head].get_token_type() != Semicolon {
stream.push(lexeme[head].get_token_value());
head += 1;
}
stream.push(lexeme[head].get_token_value());
head += 1;
} else {
//convert to shorthand notation
head += 1;
if self.in_main {
stream.push("std::process::exit(".to_string());
while lexeme[head].get_token_type() != Semicolon {
stream.push(lexeme[head].get_token_value());
head += 1;
}
stream.push(");".to_string());
} else {
while lexeme[head].get_token_type() != Semicolon {
stream.push(lexeme[head].get_token_value());
head += 1;
}
}
head += 1;
}
}
(TokenKind::Preprocessors, _) => {
let line_num = lexeme[head].get_token_line_num();
if self.once_warned == false {
stream.push(INCLUDE_STMT.get_doc().to_string());
} else {
//if warned once is set, we have already started the preprocessor block and commented out using multi line comment.
//which is ended at line L369 below. Need to pop that out before writing next pre-processor statement.
stream.pop();
}
//read in the current line as is.
while lexeme[head].get_token_line_num() != line_num {
stream.push(lexeme[head].get_token_value());
head += 1;
}
stream.push(lexeme[head].get_token_value() + "\n");
stream.push("**/\n".to_string());
head += 1;
self.once_warned = true;
}
(TokenKind::SpecialChars, LeftBracket) => {
let mut temp_lexeme: Vec<Token> = Vec::new();
while lexeme[head].get_token_type() != RightBracket {
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
temp_lexeme.push(lexeme[head].clone());
stream.append(&mut self.parse_typecast(&temp_lexeme));
head += 1;
}
// if all fails
(_, _) => {
if lexeme[head].get_token_type() != RightCurlyBrace {
if lexeme[head].get_token_type() == Comma {
stream.push(";".to_string());
} else if lexeme[head].get_token_type() == KeywordBreak {
if !self.in_switch {
stream.push(lexeme[head].get_token_value());
}
} else {
stream.push(lexeme[head].get_token_value());
}
}
head += 1;
}
};
}
//return the rust lexeme to main
stream
}
/**
* print_lexemes: DEBUG_ONLY
* prints the lexemes in the lexeme vector
* from index start to end
*/
fn print_lexemes(lexeme: &Vec<Token>, start: usize, end: usize) {
println!("----------lexeme-start------------");
for i in start..end {
println!(
"Line Num {} , {}> {:?}",
lexeme[i].get_token_line_num(),
i,
lexeme[i],
);
}
println!("----------lexeme-end------------");
}
/**
* parse_function:
* parse c/c++ function into rust equivalent function
*/
fn parse_function(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut temp_lexeme: Vec<Token> = Vec::new();
let mut head: usize = 3;
let mut lookahead: usize = head;
let mut stream: Vec<String> = Vec::new();
stream.push("fn".to_string());
stream.push(lexeme[1].get_token_value());
stream.push("(".to_string());
// parse arguments differently for functions that are not main
// since rust does not have arguments or return type for main
if lexeme[1].get_token_type() != Main {
// collect arguments
while lexeme[lookahead].get_token_type() != RightBracket {
lookahead += 1;
}
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse arguments
stream.append(&mut self.parse_arguments(&temp_lexeme));
temp_lexeme.clear();
stream.push(")".to_string());
// parse return type
if let Some(rust_type) = parse_type(lexeme[0].get_token_type(), Modifier::Default) {
if rust_type != "void".to_string() {
stream.push("->".to_string());
stream.push(rust_type);
}
}
stream.push("{".to_string());
}
// declare argc and argv inside main, if required
else {
//parsing main function
self.in_main = true;
stream.push(")".to_string());
stream.push("{".to_string());
if lexeme[head].get_token_type() != RightBracket {
if self.strict == false {
stream.push(NO_STRICT.get_doc().to_string());
stream.push("let mut argv: Vec<_> = std::env::args().collect();".to_string());
stream.push("let mut argc = argv.len();".to_string());
} else {
stream.push(STRICT.get_doc().to_string());
stream.push("let argv: Vec<_> = std::env::args().collect();".to_string());
stream.push("let argc = argv.len();".to_string());
}
}
}
while lexeme[head].get_token_type() != LeftCurlyBrace {
head += 1
}
head += 1;
// collect function body
// len - 1 so that '}' is excluded
while head < lexeme.len() - 1 {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse function body
stream.append(&mut self.parse_program(&temp_lexeme));
stream.push("}".to_string());
self.in_main = false;
stream
}
/**
* parse-arguments:
* parse c/c++ formal arguments in the function signature
* into rust equivalent arguments
*/
fn parse_arguments(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut head: usize = 0;
while head < lexeme.len() {
let mut declaration_lexeme: Vec<Token> = Vec::new();
while head < lexeme.len() && lexeme[head].get_token_type() != Comma {
//create a subset of argument declaration
declaration_lexeme.push(lexeme[head].clone());
head += 1;
}
head += 1;
let mut parsed_argument = self.parse_declaration(&declaration_lexeme, true);
stream.append(&mut parsed_argument);
stream.push(",".to_string());
}
stream
}
fn parse_params(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
//create expression termination token ';'
let terminal_token = Token::new(";".to_string(), TokenKind::SpecialChars, Semicolon, 0, 0);
let mut head: usize = 0;
let mut temp_lexeme: Vec<Token> = Vec::new();
while head < lexeme.len() {
if lexeme[head].get_token_type() == Comma {
temp_lexeme.push(terminal_token.clone());
let mut parsed_expr = self.parse_expr(&temp_lexeme);
//pop the tailing semicolon
parsed_expr.pop();
stream.append(&mut parsed_expr);
stream.push(",".to_string());
temp_lexeme.clear();
} else {
temp_lexeme.push(lexeme[head].clone());
}
head += 1;
}
temp_lexeme.push(terminal_token.clone());
let mut parsed_expr = self.parse_expr(&temp_lexeme);
//pop the tailing semicolon
parsed_expr.pop();
stream.append(&mut parsed_expr);
return stream;
}
/**
* parse_declaration:
* parse c/c++ declaration into rust
* equivalent statements */
fn parse_declaration(
&mut self,
lexeme: &Vec<Token>,
argument_declaration: bool,
) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
// let mut sym_tab: Vec<SymbolTable> = Vec::new();
//self.sym_tab.clear();
let mut sym: SymbolTable = SymbolTable {
symbol_type: Others,
symbol_modifier: Modifier::Default,
id_name: "undefined_var".to_string(),
is_assigned: false,
is_ptr: false,
assigned_val: "NONE".to_string(),
};
//check if there is any modifier present
let (token_kind, token_type) = lexeme[0].get_type();
let mut type_index = 0;
if token_kind == TokenKind::Modifiers {
//type name can be found in next lexeme
type_index = 1;
match token_type {
Signed => {
sym.symbol_modifier = Modifier::Signed;
}
Unsigned => {
sym.symbol_modifier = Modifier::Unsigned;
}
KeywordStatic => {
sym.symbol_modifier = Modifier::Static;
}
KeywordConst => {
sym.symbol_modifier = Modifier::Const;
}
_ => {}
}
}
let type_token = &lexeme[type_index];
let typdef_type = type_token.get_token_value(); //get the type name
let mut head: usize = type_index + 1;
//let sym_idx:usize=0;
while head < lexeme.len() {
match lexeme[head].get_token_type() {
Identifier => sym.id_name = lexeme[head].get_token_value(),
Assignment => {
sym.is_assigned = true;
sym.assigned_val = "".to_string();
head += 1;
let mut br = 0;
let mut lhead = head;
if sym.is_ptr == true {
if lexeme[head].get_token_type() == Null {
while lexeme[lhead].get_token_type() != Semicolon
&& lexeme[lhead].get_token_type() != Comma
{
lhead += 1;
}
sym.is_assigned = false;
}
}
let mut temp_lex: Vec<Token> = Vec::new();
while lexeme[head].get_token_type() != Semicolon
&& !(br == 0 && lexeme[head].get_token_type() == Comma)
{
if lexeme[head].get_token_type() == LeftBracket {
br += 1;
}
if lexeme[head].get_token_type() == RightBracket {
br -= 1;
}
temp_lex.push(lexeme[head].clone());
//parse assigned value for expression
head += 1;
}
temp_lex.push(lexeme[head].clone());
let a_val = self.parse_expr(&temp_lex);
let mut a_value = String::new();
for val in a_val {
a_value = a_value + &val;
}
sym.assigned_val.push_str(a_value.as_str());
continue;
}
Semicolon | Comma => {
// used enum value in the symbol table
sym.symbol_type = type_token.get_token_type();
self.sym_tab.push(sym.clone());
}
//int * a ;
Multiplication => {
sym.is_ptr = true;
}
_ => {
sym.assigned_val.push_str(&lexeme[head].get_token_value());
}
};
head += 1;
}
if !self.struct_in_body_declaration {
if self.strict == false {
stream.push(NO_STRICT.get_doc().to_string());
} else {
stream.push(STRICT.get_doc().to_string());
}
}
//from `from` start declaration statement generation
let (_, sym_table_right) = self.sym_tab.split_at(self.from);
for i in sym_table_right {
// get identifier
//for declaration out of any blocks(global)
self.from += 1;
match i.symbol_modifier {
Modifier::Const => {
stream.push("const".to_string());
}
_ => {
if !self.struct_in_body_declaration {
if self.strict == false {
if self.in_block_stmnt == true {
stream.push("let mut".to_string());
} else {
stream.push("static mut".to_string());
}
} else {
if self.in_block_stmnt == true {
stream.push("let".to_string());
} else {
stream.push("static".to_string());
}
}
}
}
}
stream.push(i.id_name.clone());
stream.push(":".to_string());
if i.is_ptr == true {
stream.push("&".to_string());
if self.strict == false {
stream.push("mut".to_string());
}
}
// get the rust type
if let Some(rust_type) = parse_type(i.symbol_type, i.symbol_modifier) {
if rust_type == "_".to_string() {
//not able to find the type, let the rust compiler do the type inference.
stream.pop();
} else {
stream.push(rust_type);
}
} else {
// if type parser dint return Some type, then it must be user defined type.
//TODO : should check the typedef table
stream.push(typdef_type.clone());
}
// take care of assignment
if i.is_assigned {
stream.push("=".to_string());
if i.is_ptr == true {
stream.push("&".to_string());
}
if self.strict == false && i.is_ptr == true {
stream.push("mut".to_string());
}
stream.push((&i.assigned_val).to_string());
}
if !argument_declaration {
stream.push(";".to_string());
}
}
stream
}
/* parse simple typedef definition of form
* typedef typename newtype;
*/
fn parse_typdef(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut struct_token_index = 1;
let mut alias_type_index = 2;
//extract struct definition if present
//typdef struct strcutname{} alias_type;
let mut struct_lexeme: Vec<Token> = Vec::new();
if lexeme.get(1).unwrap().get_token_type() == TokenType::KeywordStruct {
let mut head: usize = 1;
while lexeme.get(head).unwrap().get_token_type() != TokenType::RightCurlyBrace {
struct_lexeme.push(lexeme.get(head).unwrap().clone());
head += 1;
}
struct_lexeme.push(lexeme.get(head).unwrap().clone());
//3 token will be struct name
struct_token_index = 2;
//move head to point to alias type token
head += 1;
alias_type_index = head;
}
let alias_type = lexeme[alias_type_index].get_token_value();
let mut struct_token = lexeme[struct_token_index].clone();
if alias_type == struct_token.get_token_value() {
//rust doesnt allow to have struct with same name as type alias, so we need to scramble the name here
let new_name = struct_token.get_token_value() + "_alas_t";
struct_lexeme[1].set_token_value(&new_name);
struct_token = struct_lexeme[1].clone();
}
stream.push("\n".to_string());
let mut parsed_struct = self.parse_struct(&struct_lexeme);
stream.append(&mut parsed_struct);
stream.push("type".to_string());
stream.push(alias_type.clone() + "=");
self.typde_def_table.push(alias_type.clone());
if let Some(typ) = parse_type(struct_token.get_token_type(), Modifier::Default) {
stream.push(typ);
} else {
stream.push(struct_token.get_token_value());
}
stream.push(";".to_string());
return stream;
}
/**
* parse_if:
* parse c/c++ if statements into rust
* equivalent statements
*/
fn parse_if(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut head: usize = 0;
stream.push("if".to_string());
stream.push("(".to_string());
head += 1;
//skip '('
head += 1;
// condition
while lexeme[head].get_token_type() != RightBracket {
stream.push(lexeme[head].get_token_value());
head += 1;
}
head += 1;
stream.push(")".to_string());
stream.push("== true".to_string());
stream.push("{".to_string());
if lexeme[head].get_token_type() == LeftCurlyBrace {
head += 1;
}
// collect if body
let mut temp_lexeme: Vec<Token> = Vec::new();
while head < lexeme.len() {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse if body
stream.append(&mut self.parse_program(&temp_lexeme));
stream.push("}".to_string());
stream
}
/**
* parse_while:
* parse c/c++ while statements into rust
* equivalent statements
*/
fn parse_while(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut head: usize = 0;
let mut no_cond = false;
head += 1;
//skip '('
head += 1;
// condition
let mut cond_stream: Vec<String> = Vec::new();
while lexeme[head].get_token_type() != RightBracket {
cond_stream.push(lexeme[head].get_token_value());
head += 1;
}
if cond_stream.len() == 1
&& (cond_stream[0] == "1".to_string() || cond_stream[0] == "true".to_string())
{
no_cond = true;
}
head += 1;
if lexeme[head].get_token_type() == LeftCurlyBrace {
head += 1;
}
// collect while body
let mut temp_lexeme: Vec<Token> = Vec::new();
while head < lexeme.len() {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse while body
let mut body_stream = &mut self.parse_program(&temp_lexeme);
if no_cond == true {
stream.push("loop".to_string());
} else {
stream.push("while".to_string());
stream.push("(".to_string());
stream.append(&mut cond_stream);
stream.push(")".to_string());
stream.push("== true".to_string());
}
stream.push("{".to_string());
stream.append(&mut body_stream);
stream.push("}".to_string());
stream
}
/**
* parse_dowhile:
* parse c/c++ do while statements into rust
* equivalent statements
*/
fn parse_dowhile(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut temp_stream: Vec<String> = Vec::new();
let mut head: usize = 0;
let mut lookahead: usize;
head += 2;
lookahead = head;
lookahead = skip_block(&lexeme, lookahead) - 1;
// collect while body
let mut temp_lexeme: Vec<Token> = Vec::new();
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse while body
temp_stream.append(&mut self.parse_program(&temp_lexeme));
temp_lexeme.clear();
head += 3;
if (lexeme[head].get_token_value() == String::from("1")
|| lexeme[head].get_token_value() == String::from("true"))
&& lexeme[head + 1].get_token_type() == RightBracket
{
stream.push("loop".to_string());
stream.push("{".to_string());
stream.append(&mut temp_stream);
stream.push("}".to_string());
} else {
stream.push("while".to_string());
stream.push("{".to_string());
stream.append(&mut temp_stream);
stream.push("(".to_string());
while lexeme[head].get_token_type() != RightBracket {
stream.push(lexeme[head].get_token_value());
head += 1;
}
stream.push(")".to_string());
stream.push("== true".to_string());
stream.push("}".to_string());
stream.push("{".to_string());
stream.push("}".to_string());
}
stream.push(";".to_string());
stream
}
fn parse_switch(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut head: usize = 2;
let mut lookahead: usize = 2;
let mut stream: Vec<String> = Vec::new();
let mut temp_lexeme: Vec<Token> = Vec::new();
stream.push("match".to_string());
// find starting of switch block
while lexeme[lookahead].get_token_type() != LeftCurlyBrace {
lookahead += 1;
}
// {
// move back to find the variable/result to be matched
lookahead -= 1;
// single variable
if lookahead - head == 1 {
stream.push(lexeme[lookahead - 1].get_token_value());
}
// expression
else {
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
head -= 1;
stream.append(&mut self.parse_program(&temp_lexeme));
temp_lexeme.clear();
}
// move forward to the starting of the block
head += 3;
stream.push("{".to_string());
//head is at case
lookahead = skip_block(&lexeme, head) - 1;
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
stream.append(&mut self.parse_case(&temp_lexeme));
stream.push("}".to_string());
stream
}
fn parse_case(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
//head is at case
let mut head: usize = 0;
let mut lookahead: usize;
let mut temp_lexeme: Vec<Token> = Vec::new();
let mut def: bool = false;
//look whether default case is handled for exaustive search
while head < lexeme.len() {
if lexeme[head].get_token_type() == KeywordDefault {
stream.push("_".to_string());
def = true;
} else {
head += 1; //head is at matching value
stream.push(lexeme[head].get_token_value());
}
head += 1; // head is at :
stream.push("=>".to_string());
// either brace or no brace
head += 1;
if lexeme[head].get_token_type() == LeftCurlyBrace {
head += 1;
lookahead = skip_block(&lexeme, head) - 1;
} else {
lookahead = head;
while lookahead < lexeme.len()
&& lexeme[lookahead].get_token_type() != KeywordCase
&& lexeme[lookahead].get_token_type() != KeywordDefault
{
lookahead += 1;
}
}
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
stream.push("{".to_string());
stream.append(&mut self.parse_program(&temp_lexeme));
stream.push("}".to_string());
if head < lexeme.len() && lexeme[head].get_token_type() == RightCurlyBrace {
head += 1;
}
temp_lexeme.clear();
}
if def == false {
stream.push("_".to_string());
stream.push("=>".to_string());
stream.push("{".to_string());
stream.push("}".to_string());
}
stream
}
/**
* parse_for:
* parse c/c++ do while statements into rust
* equivalent statements
*
* Identify infinite loops and replace for with loop{}
*/
fn parse_for(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut head: usize = 0;
let mut lookahead: usize;
let mut temp_lexeme: Vec<Token> = Vec::new();
while lexeme[head].get_token_type() != LeftBracket {
head += 1;
}
head += 1;
lookahead = head;
//for (int i =0; )
let decl: bool = if lexeme[head].get_token_kind() == TokenKind::DataTypes {
true
} else {
false
};
// let mut no_init:bool; //no initialization
let mut no_cond: bool = false; //if no condition to terminate
let mut no_updation: bool = false; //no inc/dec of loop counter
let mut body: Vec<String> = Vec::new();
let mut updation: Vec<String> = Vec::new();
let mut term_cond: Vec<String> = Vec::new();
// initial assignment
lookahead = skip_stmt(&lexeme, lookahead);
//incase of initialization expression for (;i<10;i++) ; common case
if head + 1 < lookahead {
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
if decl == true {
stream.append(&mut self.parse_declaration(&temp_lexeme, false));
} else {
stream.append(&mut self.parse_assignment(&temp_lexeme));
}
} else {
head += 1;
// no_init = true;
}
temp_lexeme.clear();
// terminating condition
lookahead = skip_stmt(&lexeme, lookahead);
if head + 1 < lookahead {
while head < lookahead - 1 {
term_cond.push(lexeme[head].get_token_value());
head += 1;
}
} else {
no_cond = true;
}
head += 1;
temp_lexeme.clear();
lookahead = head;
// update expression
while lexeme[lookahead].get_token_type() != RightBracket {
let l: Token = lexeme[lookahead].clone();
temp_lexeme.push(l);
lookahead += 1;
}
//no_updation
if head == lookahead {
no_updation = true;
} else {
temp_lexeme.push(Token::new(
String::from(";"),
TokenKind::SpecialChars,
Semicolon,
0,
0,
));
updation.append(&mut self.parse_program(&temp_lexeme));
temp_lexeme.clear();
}
head = lookahead;
head += 1;
if lexeme[head].get_token_type() == LeftCurlyBrace {
head += 1;
lookahead = skip_block(&lexeme, head);
} else {
lookahead = skip_stmt(&lexeme, head);
}
// lookahead = skip_block(&lexeme, lookahead);
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
body.append(&mut self.parse_program(&temp_lexeme));
if no_cond == true {
stream.push("loop".to_string());
} else {
stream.push("while".to_string());
stream.append(&mut term_cond); //append termianating condition
}
stream.push("{".to_string());
stream.append(&mut body);
if no_updation != true {
stream.append(&mut updation);
}
stream.push("}".to_string());
stream
}
/* parse_assignment:
* parse c/c++ assignment statements into rust equivalent code
* compound assignments must be converted to declarations
* as rust doesnt support compound assignment
*/
fn parse_assignment(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
// let mut lookahead = lexeme.len();
let mut thead: usize = 2;
let mut lexeme1: Vec<Token> = Vec::new();
let mut n = 2;
let m = 3;
let mut tstream: Vec<String> = Vec::new();
if lexeme[n].get_token_kind() == TokenKind::UnaryOperators {
while lexeme[thead].get_token_type() != Semicolon {
lexeme1.push(lexeme[thead].clone());
thead += 1;
}
lexeme1.push(lexeme[thead].clone());
stream.push(lexeme[0].get_token_value());
stream.push(lexeme[1].get_token_value());
stream.append(&mut self.parse_expr(&lexeme1));
} else if lexeme[m].get_token_kind() == TokenKind::UnaryOperators {
while lexeme[thead].get_token_type() != Semicolon {
lexeme1.push(lexeme[thead].clone());
thead += 1;
}
lexeme1.push(lexeme[thead].clone());
stream.push(lexeme[0].get_token_value());
stream.push(lexeme[1].get_token_value());
stream.append(&mut self.parse_expr(&lexeme1));
} else if lexeme[m].get_token_kind() == TokenKind::BinaryOperators {
while lexeme[thead].get_token_type() != Semicolon {
lexeme1.push(lexeme[thead].clone());
thead += 1;
}
lexeme1.push(lexeme[thead].clone());
stream.push(lexeme[0].get_token_value());
stream.push(lexeme[1].get_token_value());
stream.append(&mut self.parse_expr(&lexeme1));
} else if lexeme[n].get_token_type() == BitwiseAnd {
stream.push(lexeme[0].get_token_value());
stream.push(lexeme[1].get_token_value());
while lexeme[thead].get_token_type() != Semicolon {
stream.push(lexeme[thead].get_token_value());
thead += 1;
}
} else {
if lexeme[m].get_token_type() == Assignment {
while lexeme[thead].get_token_type() != Semicolon
&& lexeme[thead].get_token_type() != Comma
{
lexeme1.push(lexeme[thead].clone());
thead += 1;
}
lexeme1.push(lexeme[thead].clone());
stream.append(&mut self.parse_program(&lexeme1));
}
stream.push(lexeme[0].get_token_value());
stream.push(lexeme[1].get_token_value());
if lexeme[n].get_token_kind() == TokenKind::UnaryOperators {
stream.push(lexeme[m].get_token_value());
} else {
stream.push(lexeme[n].get_token_value());
n += 1;
if lexeme[n].get_token_type() == LeftBracket
|| lexeme[n].get_token_type() == LeftSquareBracket
{
while lexeme[n].get_token_type() != Semicolon {
stream.push(lexeme[n].get_token_value());
n += 1;
}
}
stream.push(";".to_string());
}
}
if tstream.len() > 0 {
stream.append(&mut tstream);
}
stream
}
/* parse_expr:
* parse c/c++ expression statements into rust equivalent code
*/
fn parse_expr(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
// let mut lookahead = lexeme.len();
let mut tstream: Vec<String> = Vec::new();
let mut thead: usize = 0;
let mut prev_id = " ".to_string();
let mut typ = Others;
//a=b+c++;
while thead < lexeme.len() && lexeme[thead].get_token_type() != Semicolon {
if lexeme[thead].get_token_kind() == TokenKind::UnaryOperators {
if lexeme[thead].get_token_type() == SizeOf {
stream.push("std::mem::size_of(".to_string());
thead += 2;
if lexeme[thead].get_token_kind() == TokenKind::DataTypes {
if let Some(t) =
parse_type(lexeme[thead].get_token_type(), Modifier::Default)
{
stream.push(t)
}
} else {
stream.push(lexeme[thead].get_token_value());
}
stream.push(")".to_string());
thead += 1;
} else {
//incase of post
if typ == Identifier {
tstream.push(prev_id.clone());
tstream.push(match lexeme[thead].get_token_type() {
Increment => "+=1".to_string(),
Decrement => "-=1".to_string(),
_ => " ;".to_string(),
});
tstream.push(";".to_string());
thead += 1;
//continue;
}
// incase of pre
else {
stream.push("(".to_string());
stream.push(lexeme[thead + 1].get_token_value());
stream.push(match lexeme[thead].get_token_type() {
Increment => "+=1".to_string(),
Decrement => "-=1".to_string(),
_ => " ;".to_string(),
});
stream.push(")".to_string());
thead += 1;
}
}
} else if lexeme[thead].get_token_kind() == TokenKind::SpecialChars {
if lexeme[thead].get_token_type() == LeftBracket
&& lexeme[thead + 1].get_token_kind() == TokenKind::DataTypes
{
//type cast expression.
let mut temp_lexeme: Vec<Token> = Vec::new();
while thead < lexeme.len()
&& lexeme[thead].get_token_type() != Semicolon
&& lexeme[thead].get_token_type() != Comma
{
temp_lexeme.push(lexeme[thead].clone());
thead += 1;
}
let mut parsed_stmnt = self.parse_typecast(&temp_lexeme);
stream.append(&mut parsed_stmnt);
//move back from end of statement, so next move thead inc will not panic
thead -= 1;
}
} else {
stream.push(lexeme[thead].get_token_value());
}
typ = lexeme[thead].get_token_type();
prev_id = lexeme[thead].get_token_value();
thead += 1;
}
stream.push(";".to_string());
if tstream.len() > 0 {
stream.append(&mut tstream);
}
stream
}
/**
* Parse simple type case statement of form (int)a or (int *)a
* */
fn parse_typecast(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
//get the type
let mut lookahead: usize = 0;
while lexeme[lookahead].get_token_type() != RightBracket {
lookahead += 1;
}
//lookahead - 1 is *, then its a pointer
let is_ptr = if lexeme[lookahead - 1].get_token_type() == Multiplication {
true
} else {
false
};
let type_index = lookahead - 2;
//move lookahead to poit to expression
lookahead += 1;
while lookahead < lexeme.len() {
//TODO: skip address of op operator ?
stream.push(lexeme[lookahead].get_token_value());
if lexeme[lookahead].get_token_type() == BitwiseAnd && !self.strict {
stream.push(" mut ".to_string());
}
lookahead += 1;
}
//get the rust equivalent type
let mut typ: String = "".to_string();
if let Some(t) = parse_type(lexeme[type_index].get_token_type(), Modifier::Default) {
typ = t;
}
if is_ptr {
//TODO : Equivalent of this??
if self.strict {
stream.push(" as & ".to_string());
} else {
stream.push(" as &mut ".to_string());
}
stream.push(typ);
} else {
stream.push(" as ".to_string());
stream.push(typ);
}
//check if its a pointer
return stream;
}
fn parse_array_declaration(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut typ: String = " ".to_string();
//int a[10];
if let Some(t) = parse_type(lexeme[0].get_token_type(), Modifier::Default) {
typ = t;
}
if !self.struct_in_body_declaration {
if self.strict == true {
stream.push(STRICT.get_doc().to_string());
stream.push("let".to_string());
} else {
stream.push(NO_STRICT.get_doc().to_string());
stream.push("let mut".to_string());
}
}
let mut head = 0;
stream.push(lexeme[head + 1].get_token_value());
stream.push(":".to_string());
stream
.push("[".to_string() + &typ[..] + ";" + &lexeme[head + 3].get_token_value()[..] + "]");
head = 5;
let mut lookahead = head;
while lexeme[lookahead].get_token_type() != Semicolon {
lookahead += 1;
}
let mut temp_lexeme: Vec<Token> = Vec::new();
if lexeme[head].get_token_type() == Comma {
temp_lexeme.push(lexeme[0].clone());
//move to next
head += 1;
while lexeme[head].get_token_type() != Semicolon {
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
stream.push(";".to_string());
temp_lexeme.push(lexeme[head].clone());
stream.append(&mut self.parse_program(&temp_lexeme));
} else if lexeme[head].get_token_type() == Assignment {
while lexeme[head].get_token_type() != Semicolon
&& lexeme[head].get_token_type() != RightCurlyBrace
{
stream.push(match lexeme[head].get_token_type() {
LeftCurlyBrace => "[".to_string(),
_ => lexeme[head].get_token_value(),
});
head += 1;
}
stream.push("]".to_string());
stream.push(";".to_string());
} else {
stream.push(";".to_string());
}
stream
}
// not tested
fn parse_struct(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut head: usize = 0;
stream.push(lexeme[head].get_token_value()); //push the keyword struct
head += 1;
//push the struct id_name
stream.push(lexeme[head].get_token_value()); //push the struct name
let name = lexeme[head].get_token_value();
stream.push("{".to_string());
head += 2;
let mut temp_lexeme: Vec<Token> = Vec::new();
while lexeme[head].get_token_type() != RightCurlyBrace {
while lexeme[head].get_token_type() != Semicolon {
temp_lexeme.push(lexeme[head].clone());
head += 1
}
temp_lexeme.push(lexeme[head].clone());
head += 1;
//check if line comment is present
if lexeme[head].get_token_type() == SingleLineComment {
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
stream.append(&mut self.parse_struct_inbody_decl(&temp_lexeme, &name));
temp_lexeme.clear();
}
stream.push(lexeme[head].get_token_value() + "\n");
stream
}
// not tested
fn parse_struct_inbody_decl(&mut self, lexeme: &Vec<Token>, _name: &String) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
//push the identifier
self.struct_in_body_declaration = true;
let mut head: usize = 0;
let mut array_decl = false;
while head + 2 < lexeme.len() {
if lexeme[head].get_token_type() == LeftSquareBracket
&& lexeme[head + 2].get_token_type() == RightSquareBracket
&& lexeme[head + 1].get_token_type() == NumberInteger
//this pretty much defines the array decl, i guess
{
array_decl = true;
};
head += 1;
}
let mut parsed_decl: Vec<String>;
if array_decl {
parsed_decl = self.parse_array_declaration(&lexeme);
} else {
parsed_decl = self.parse_declaration(&lexeme, true);
}
//remove tailing semicolon added by parser
if parsed_decl.last().unwrap() == ";" {
parsed_decl.pop();
}
self.struct_in_body_declaration = false;
stream.append(&mut parsed_decl);
stream.push(",".to_string());
stream
}
// not tested
fn parse_struct_decl(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
stream.push(STRUCT_INIT.get_doc().to_string());
stream.push("let".to_string());
let mut head = 1;
//struct FilePointer fp;
let struct_name = lexeme[head].get_token_value();
head += 1;
stream.push(lexeme[head].get_token_value()); //push the identifer => let a
stream.push("=".to_string());
stream.push(struct_name.clone());
stream.push("{".to_string());
for row in &self.struct_mem {
if row.name == struct_name {
stream.push(row.identifier.clone());
stream.push(":".to_string());
stream.push(get_default_value_for(row.member_type));
stream.push(",".to_string());
}
}
stream.push("};".to_string());
stream
}
//parse tagged union
fn parse_union(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut head: usize = 0;
stream.push("enum".to_string()); //push the keyword union
head += 1;
//push the struct id_name
stream.push(lexeme[head].get_token_value()); //push the struct name
let name = lexeme[head].get_token_value();
stream.push("{".to_string());
head += 2;
let mut temp_lexeme: Vec<Token> = Vec::new();
while lexeme[head].get_token_type() != RightCurlyBrace {
while lexeme[head].get_token_type() != Semicolon {
temp_lexeme.push(lexeme[head].clone());
head += 1
}
temp_lexeme.push(lexeme[head].clone());
head += 1;
stream.append(&mut self.parse_union_inbody_decl(&temp_lexeme, &name));
temp_lexeme.clear();
}
stream.push(lexeme[head].get_token_value() + "\n");
stream
}
/* parse union type declarations
* input : union tag_name var [;= ...]
* output : let [mut] variant_name = Sometype_variant
*/
fn parse_union_decl(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut head: usize = 0;
stream.push(UNION_DECL.get_doc().to_string());
//push the keyword let
stream.push("let".to_string());
if !self.strict {
stream.push("mut".to_string());
}
stream.push(lexeme[head + 2].get_token_value());
head += 3;
while lexeme[head].get_token_type() != Semicolon {
stream.push(lexeme[head].get_token_value());
head += 1;
}
stream.push(";".to_string());
stream
}
/* parse union body into Some type body
* return rust stream
*/
fn parse_union_inbody_decl(&mut self, lexeme: &Vec<Token>, name: &String) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut head = 0;
//push the identifier
stream.push(lexeme[head + 1].get_token_value());
stream.push("(".to_string());
let mut struct_memt = CStructMem {
identifier: "NONE".to_string(),
name: name.clone(),
member_type: TokenType::Others,
};
let mut rust_type = "RUST_TYPE".to_string();
//push the type
if let Some(rust_typ) = parse_type(lexeme[head].get_token_type(), Modifier::Default) {
rust_type = rust_typ.clone();
stream.push(rust_typ);
struct_memt.member_type = lexeme[head].get_token_type();
struct_memt.identifier = lexeme[head + 1].get_token_value();
}
head += 2;
stream.push("),".to_string());
//update struct member table (may require for analysis
self.struct_mem.push(struct_memt.clone());
while lexeme[head].get_token_type() != Semicolon {
if lexeme[head].get_token_type() == Comma {
head += 1;
}
struct_memt.identifier = lexeme[head].get_token_value();
stream.push(lexeme[head].get_token_value());
stream.push("(".to_string());
stream.push(rust_type.clone());
head += 1;
stream.push("),".to_string());
self.struct_mem.push(struct_memt.clone());
}
stream
}
// not tested
fn parse_class(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut head: usize = 0;
let mut method_stream: Vec<String> = Vec::new();
stream.push("struct".to_string()); //push the keyword struct
head += 1;
//push the struct id_name
let class_name = lexeme[head].get_token_value();
stream.push(class_name.clone()); //push the class name
let name = lexeme[head].get_token_value();
stream.push("{".to_string());
head += 2;
let mut modifier: String = " ".to_string();
let mut temp_lexeme: Vec<Token> = Vec::new();
let mut tstream: Vec<String> = Vec::new();
while lexeme[head].get_token_type() != RightCurlyBrace
&& lexeme[head + 1].get_token_type() != Semicolon
{
match lexeme[head].get_type() {
(TokenKind::Modifiers, _) => {
match lexeme[head].get_token_type() {
KeywordPublic => {
head += 2;
modifier = "pub".to_string();
}
KeywordProtected | keywordPrivate => {
head += 2;
modifier = "".to_string();
}
_ => {}
};
}
(_, Identifier) => {
if lexeme[head].get_token_value() == class_name {
tstream.push(CONSTRUCTOR.get_doc().to_string());
let mut lookahead = head;
while lexeme[lookahead].get_token_type() != LeftCurlyBrace {
lookahead += 1;
}
lookahead += 1;
lookahead = skip_block(lexeme, lookahead);
while head < lookahead {
tstream.push(lexeme[head].get_token_value());
head += 1;
}
tstream.push("\n **/\n".to_string());
continue;
}
}
_ => {}
}
if lexeme[head + 2].get_token_type() == LeftBracket {
while lexeme[head].get_token_type() != RightCurlyBrace {
temp_lexeme.push(lexeme[head].clone());
head += 1;
}
temp_lexeme.push(lexeme[head].clone());
head += 1;
method_stream.append(&mut self.parse_method_decl(&temp_lexeme, &modifier));
temp_lexeme.clear();
} else {
while lexeme[head].get_token_type() != RightCurlyBrace
&& lexeme[head].get_token_kind() != TokenKind::Modifiers
{
while lexeme[head].get_token_type() != Semicolon {
temp_lexeme.push(lexeme[head].clone());
head += 1
}
temp_lexeme.push(lexeme[head].clone());
head += 1;
stream.append(&mut self.parse_class_inbody_decl(
&temp_lexeme,
&name,
&modifier,
));
temp_lexeme.clear();
}
}
}
stream.push(lexeme[head].get_token_value());
stream.push(
"\n\n/**Method declarations are wrapped inside the impl block \
\n * Which implements the corresponding structure\
\n **/\n"
.to_string(),
);
stream.push("impl".to_string());
stream.push(name.clone());
stream.push("{\n".to_string());
if tstream.len() > 0 {
stream.append(&mut tstream);
}
stream.append(&mut method_stream);
stream.push("}\n".to_string());
stream
}
// not tested
fn parse_method_decl(&mut self, lexeme: &Vec<Token>, modifier: &String) -> Vec<String> {
let mut temp_lexeme: Vec<Token> = Vec::new();
let mut head: usize = 3;
let mut lookahead: usize = head;
let mut stream: Vec<String> = Vec::new();
if modifier.len() > 1 {
stream.push(modifier.clone());
}
stream.push("fn".to_string());
stream.push(lexeme[1].get_token_value());
stream.push("(".to_string());
stream.push("&self".to_string()); //first argument of method must be self, for sefety we consider reference/borrow
// parse arguments differenly for functions that are not main
// collect arguments
while lexeme[lookahead].get_token_type() != RightBracket {
lookahead += 1;
}
if head < lookahead {
stream.push(",".to_string());
}
while head < lookahead {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse arguments
stream.append(&mut self.parse_arguments(&temp_lexeme));
temp_lexeme.clear();
stream.push(")".to_string());
// parse return type
if let Some(rust_type) = parse_type(lexeme[0].get_token_type(), Modifier::Default) {
if rust_type != "void".to_string() {
stream.push("->".to_string());
stream.push(rust_type);
}
}
stream.push("{".to_string());
while lexeme[head].get_token_type() != LeftCurlyBrace {
head += 1
}
head += 1;
// collect function body
// len - 1 so that '}' is excluded
while head < lexeme.len() - 1 {
let l: Token = lexeme[head].clone();
temp_lexeme.push(l);
head += 1;
}
// parse function body
stream.append(&mut self.parse_program(&temp_lexeme));
stream.push("}".to_string());
stream
}
// not tested
fn parse_class_inbody_decl(
&mut self,
lexeme: &Vec<Token>,
name: &String,
modifier: &String,
) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
let mut head = 0;
//push the identifier
if modifier.len() > 1 {
stream.push(modifier.clone());
}
stream.push(lexeme[head + 1].get_token_value());
stream.push(":".to_string());
let mut struct_memt = CStructMem {
identifier: "NONE".to_string(),
name: name.clone(),
member_type: TokenType::Others,
};
let mut rust_type: String = " ".to_string();
if let Some(rust_typ) = parse_type(lexeme[0].get_token_type(), Modifier::Default) {
rust_type = rust_typ.clone();
stream.push(rust_typ);
struct_memt.member_type = lexeme[0].get_token_type();
struct_memt.identifier = lexeme[1].get_token_value();
}
stream.push(",".to_string());
self.struct_mem.push(struct_memt.clone());
head += 2;
while lexeme[head].get_token_type() != Semicolon {
if lexeme[head].get_token_type() == Comma {
head += 1;
}
stream.push(lexeme[head].get_token_value());
stream.push(":".to_string());
stream.push(rust_type.clone());
struct_memt.identifier = lexeme[head].get_token_value();
self.struct_mem.push(struct_memt.clone());
head += 1;
}
stream
}
// not tested
fn parse_class_decl(&mut self, lexeme: &Vec<Token>) -> Vec<String> {
let mut stream: Vec<String> = Vec::new();
stream.push(STRUCT_INIT.get_doc().to_string());
stream.push("let".to_string());
let mut head = 0;
//struct FilePointer fp;
let struct_name = lexeme[head].get_token_value();
head += 1;
stream.push(lexeme[head].get_token_value()); //push the identifer => let a
stream.push("=".to_string());
stream.push(struct_name.clone());
stream.push("{".to_string());
for row in &self.struct_mem {
if row.name == struct_name {
stream.push(row.identifier.clone());
stream.push(":".to_string());
stream.push(get_default_value_for(row.member_type));
stream.push(",".to_string());
}
}
stream.push("};".to_string());
stream
}
}
|
// The noise channels produced white noise and was generally used for the
// percussions of the songs
use serde::{Deserialize, Serialize};
use super::LENGTH_TABLE;
/// Table of the different timer periods
const TIMER_TABLE: [u16; 16] = [
4, 8, 16, 32, 64, 96, 128, 160, 202, 254, 380, 508, 762, 1016, 2034, 4068,
];
/// Audio noise channel
#[derive(Serialize, Deserialize)]
pub struct Noise {
enabled: bool,
mode: bool,
timer_period: u16,
timer: u16,
length_halt: bool,
length_counter: u8,
constant_volume: bool,
volume: u8,
envelope_timer: u8,
envelope_volume: u8,
shift: u16,
}
impl Noise {
pub fn new() -> Self {
Self {
enabled: false,
mode: false,
timer_period: 0,
timer: 0,
length_halt: false,
length_counter: 0,
constant_volume: false,
volume: 0,
envelope_timer: 0,
envelope_volume: 0,
shift: 1,
}
}
/// Resets the channel state
pub fn reset(&mut self) {
self.enabled = false;
self.mode = false;
self.timer_period = 0;
self.timer = 0;
self.length_halt = false;
self.length_counter = 0;
self.constant_volume = false;
self.volume = 0;
self.envelope_volume = 0;
self.shift = 1;
}
/// Enables or disables the channel
pub fn set_enabled(&mut self, v: bool) {
self.enabled = v;
// If disabled, set the length counter to zero
if !v {
self.length_counter = 0;
}
}
/// Sets register 0x400C
pub fn write_vol(&mut self, data: u8) {
// --LC VVVV
// L: Envelope loop / length counter halt
// C: Output constant volume
// V: Volume value / envelope period
self.length_halt = data & 0x20 != 0;
self.constant_volume = data & 0x10 != 0;
self.volume = data & 0xF;
}
/// Sets register 0x400E
pub fn write_lo(&mut self, data: u8) {
// M--- PPPP
// M: Mode flag
// P: Timer period table index
self.mode = data & 0x80 != 0;
self.timer_period = TIMER_TABLE[(data & 0xF) as usize];
}
/// Sets register 0x400F
pub fn write_hi(&mut self, data: u8) {
// LLLL L---
// L: Length counter table index
self.length_counter = LENGTH_TABLE[(data >> 3) as usize];
// Also restarts the envelope generator
self.envelope_volume = 15;
self.envelope_timer = self.volume + 1;
}
pub fn tick_timer(&mut self) {
match self.timer == 0 {
true => {
self.timer = self.timer_period;
let bit = match self.mode {
true => 6,
false => 1,
};
let feedback = (self.shift ^ (self.shift >> bit)) & 0x1;
self.shift = (self.shift >> 1) | (feedback << 14);
}
false => self.timer -= 1,
}
}
/// Clocks the length counter
pub fn tick_length(&mut self) {
// The length counter is a simple gate which lets the channel output
// a signal when it is not 0. It can only be reloaded by writing to
// register 0x400F.
// It is like "for how many clocks the channel can output a signal"
// If the length halt flag is not set and the counter is greater than
// 0, decrement.
if !self.length_halt && self.length_counter > 0 {
self.length_counter -= 1;
}
}
/// Clocks the envelope
pub fn tick_envelope(&mut self) {
match self.envelope_timer > 0 {
// If the timer is not 0, decrement it.
true => self.envelope_timer -= 1,
// If it is 0...
false => {
// If the volume is not 0, decrement it
if self.envelope_volume > 0 {
self.envelope_volume -= 1;
// Otherwise if it is 0 and the loop flag is set,
// reset it to 15
} else if self.length_halt {
self.envelope_volume = 15;
}
// Reset the timer to its period value + 1
self.envelope_timer = self.volume + 1;
}
}
}
/// Returns the output volume of the channel
pub fn output(&mut self) -> u8 {
// All the conditions below silence the channel.
if !self.enabled || self.length_counter == 0 || self.shift & 0x1 != 0 {
return 0;
}
// Check if we should output constant volume or the envelope volume
match self.constant_volume {
true => self.volume,
false => self.envelope_volume,
}
}
/// Returns the length counter value
pub fn length_counter(&self) -> u8 {
self.length_counter
}
}
|
use ai::constants::AI_DTOR;
use ai::vector::AtVector;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct AtMatrix {
pub data: [[f32; 4]; 4],
}
pub const AI_M4_IDENTITY: AtMatrix = AtMatrix {
data: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]],
};
pub const AI_M4_ZERO: AtMatrix = AtMatrix {
data: [[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.0]],
};
impl AtMatrix {
pub fn translation(t: &AtVector) -> AtMatrix {
AtMatrix {
data: [[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[t.x, t.y, t.z, 1.0]],
}
}
pub fn rotation_x(x: f32) -> AtMatrix {
let c = (x * AI_DTOR).cos();
let s = (x * AI_DTOR).sin();
AtMatrix {
data: [[1.0, 0.0, 0.0, 0.0], [0.0, c, s, 0.0], [0.0, -s, c, 0.0], [0.0, 0.0, 0.0, 1.0]],
}
}
pub fn rotation_y(y: f32) -> AtMatrix {
let c = (y * AI_DTOR).cos();
let s = (y * AI_DTOR).sin();
AtMatrix {
data: [[c, 0.0, s, 0.0], [0.0, 1.0, 0.0, 0.0], [-s, 0.0, c, 0.0], [0.0, 0.0, 0.0, 1.0]],
}
}
pub fn rotation_z(z: f32) -> AtMatrix {
let c = (z * AI_DTOR).cos();
let s = (z * AI_DTOR).sin();
AtMatrix {
data: [[c, s, 0.0, 0.0], [-s, c, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]],
}
}
pub fn scaling(s: &AtVector) -> AtMatrix {
AtMatrix {
data: [[s.x, 0.0, 0.0, 0.0],
[0.0, s.y, 0.0, 0.0],
[0.0, 0.0, s.z, 0.0],
[0.0, 0.0, 0.0, 1.0]],
}
}
pub fn frame(o: &AtVector, u: &AtVector, v: &AtVector, w: &AtVector) -> AtMatrix {
AtMatrix {
data: [[u.x, v.x, w.x, 0.0],
[u.y, v.y, w.y, 0.0],
[u.z, v.z, w.z, 0.0],
[o.x, o.y, o.z, 1.0]],
}
}
}
|
#[doc = "Reader of register RCC_MCO2CFGR"]
pub type R = crate::R<u32, super::RCC_MCO2CFGR>;
#[doc = "Writer for register RCC_MCO2CFGR"]
pub type W = crate::W<u32, super::RCC_MCO2CFGR>;
#[doc = "Register RCC_MCO2CFGR `reset()`'s with value 0"]
impl crate::ResetValue for super::RCC_MCO2CFGR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "MCO2SEL\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum MCO2SEL_A {
#[doc = "0: MPU clock selected (mpuss_ck)\r\n (default after reset)"]
B_0X0 = 0,
#[doc = "1: AXI clock selected\r\n (axiss_ck)"]
B_0X1 = 1,
#[doc = "2: MCU clock selected\r\n (mcuss_ck)"]
B_0X2 = 2,
#[doc = "3: PLL4 clock selected\r\n (pll4_p_ck)"]
B_0X3 = 3,
#[doc = "4: HSE clock selected\r\n (hse_ck)"]
B_0X4 = 4,
#[doc = "5: HSI clock selected\r\n (hsi_ck)"]
B_0X5 = 5,
}
impl From<MCO2SEL_A> for u8 {
#[inline(always)]
fn from(variant: MCO2SEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `MCO2SEL`"]
pub type MCO2SEL_R = crate::R<u8, MCO2SEL_A>;
impl MCO2SEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, MCO2SEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(MCO2SEL_A::B_0X0),
1 => Val(MCO2SEL_A::B_0X1),
2 => Val(MCO2SEL_A::B_0X2),
3 => Val(MCO2SEL_A::B_0X3),
4 => Val(MCO2SEL_A::B_0X4),
5 => Val(MCO2SEL_A::B_0X5),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == MCO2SEL_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == MCO2SEL_A::B_0X1
}
#[doc = "Checks if the value of the field is `B_0X2`"]
#[inline(always)]
pub fn is_b_0x2(&self) -> bool {
*self == MCO2SEL_A::B_0X2
}
#[doc = "Checks if the value of the field is `B_0X3`"]
#[inline(always)]
pub fn is_b_0x3(&self) -> bool {
*self == MCO2SEL_A::B_0X3
}
#[doc = "Checks if the value of the field is `B_0X4`"]
#[inline(always)]
pub fn is_b_0x4(&self) -> bool {
*self == MCO2SEL_A::B_0X4
}
#[doc = "Checks if the value of the field is `B_0X5`"]
#[inline(always)]
pub fn is_b_0x5(&self) -> bool {
*self == MCO2SEL_A::B_0X5
}
}
#[doc = "Write proxy for field `MCO2SEL`"]
pub struct MCO2SEL_W<'a> {
w: &'a mut W,
}
impl<'a> MCO2SEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MCO2SEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "MPU clock selected (mpuss_ck) (default after reset)"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(MCO2SEL_A::B_0X0)
}
#[doc = "AXI clock selected (axiss_ck)"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(MCO2SEL_A::B_0X1)
}
#[doc = "MCU clock selected (mcuss_ck)"]
#[inline(always)]
pub fn b_0x2(self) -> &'a mut W {
self.variant(MCO2SEL_A::B_0X2)
}
#[doc = "PLL4 clock selected (pll4_p_ck)"]
#[inline(always)]
pub fn b_0x3(self) -> &'a mut W {
self.variant(MCO2SEL_A::B_0X3)
}
#[doc = "HSE clock selected (hse_ck)"]
#[inline(always)]
pub fn b_0x4(self) -> &'a mut W {
self.variant(MCO2SEL_A::B_0X4)
}
#[doc = "HSI clock selected (hsi_ck)"]
#[inline(always)]
pub fn b_0x5(self) -> &'a mut W {
self.variant(MCO2SEL_A::B_0X5)
}
#[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) | ((value as u32) & 0x07);
self.w
}
}
#[doc = "MCO2DIV\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum MCO2DIV_A {
#[doc = "0: bypass (default after\r\n reset)"]
B_0X0 = 0,
#[doc = "1: division by 2"]
B_0X1 = 1,
#[doc = "2: division by 3"]
B_0X2 = 2,
#[doc = "15: division by 16"]
B_0XF = 15,
}
impl From<MCO2DIV_A> for u8 {
#[inline(always)]
fn from(variant: MCO2DIV_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `MCO2DIV`"]
pub type MCO2DIV_R = crate::R<u8, MCO2DIV_A>;
impl MCO2DIV_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, MCO2DIV_A> {
use crate::Variant::*;
match self.bits {
0 => Val(MCO2DIV_A::B_0X0),
1 => Val(MCO2DIV_A::B_0X1),
2 => Val(MCO2DIV_A::B_0X2),
15 => Val(MCO2DIV_A::B_0XF),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == MCO2DIV_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == MCO2DIV_A::B_0X1
}
#[doc = "Checks if the value of the field is `B_0X2`"]
#[inline(always)]
pub fn is_b_0x2(&self) -> bool {
*self == MCO2DIV_A::B_0X2
}
#[doc = "Checks if the value of the field is `B_0XF`"]
#[inline(always)]
pub fn is_b_0x_f(&self) -> bool {
*self == MCO2DIV_A::B_0XF
}
}
#[doc = "Write proxy for field `MCO2DIV`"]
pub struct MCO2DIV_W<'a> {
w: &'a mut W,
}
impl<'a> MCO2DIV_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MCO2DIV_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "bypass (default after reset)"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(MCO2DIV_A::B_0X0)
}
#[doc = "division by 2"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(MCO2DIV_A::B_0X1)
}
#[doc = "division by 3"]
#[inline(always)]
pub fn b_0x2(self) -> &'a mut W {
self.variant(MCO2DIV_A::B_0X2)
}
#[doc = "division by 16"]
#[inline(always)]
pub fn b_0x_f(self) -> &'a mut W {
self.variant(MCO2DIV_A::B_0XF)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4);
self.w
}
}
#[doc = "MCO2ON\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MCO2ON_A {
#[doc = "0: The MCO2 output is\r\n disabled"]
B_0X0 = 0,
#[doc = "1: The MCO2 output is\r\n enabled"]
B_0X1 = 1,
}
impl From<MCO2ON_A> for bool {
#[inline(always)]
fn from(variant: MCO2ON_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `MCO2ON`"]
pub type MCO2ON_R = crate::R<bool, MCO2ON_A>;
impl MCO2ON_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MCO2ON_A {
match self.bits {
false => MCO2ON_A::B_0X0,
true => MCO2ON_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == MCO2ON_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == MCO2ON_A::B_0X1
}
}
#[doc = "Write proxy for field `MCO2ON`"]
pub struct MCO2ON_W<'a> {
w: &'a mut W,
}
impl<'a> MCO2ON_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MCO2ON_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The MCO2 output is disabled"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(MCO2ON_A::B_0X0)
}
#[doc = "The MCO2 output is enabled"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(MCO2ON_A::B_0X1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
impl R {
#[doc = "Bits 0:2 - MCO2SEL"]
#[inline(always)]
pub fn mco2sel(&self) -> MCO2SEL_R {
MCO2SEL_R::new((self.bits & 0x07) as u8)
}
#[doc = "Bits 4:7 - MCO2DIV"]
#[inline(always)]
pub fn mco2div(&self) -> MCO2DIV_R {
MCO2DIV_R::new(((self.bits >> 4) & 0x0f) as u8)
}
#[doc = "Bit 12 - MCO2ON"]
#[inline(always)]
pub fn mco2on(&self) -> MCO2ON_R {
MCO2ON_R::new(((self.bits >> 12) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:2 - MCO2SEL"]
#[inline(always)]
pub fn mco2sel(&mut self) -> MCO2SEL_W {
MCO2SEL_W { w: self }
}
#[doc = "Bits 4:7 - MCO2DIV"]
#[inline(always)]
pub fn mco2div(&mut self) -> MCO2DIV_W {
MCO2DIV_W { w: self }
}
#[doc = "Bit 12 - MCO2ON"]
#[inline(always)]
pub fn mco2on(&mut self) -> MCO2ON_W {
MCO2ON_W { w: self }
}
}
|
#![deny(unsafe_code)]
#![no_std]
#![no_main]
extern crate cortex_m;
extern crate cortex_m_rt;
extern crate cortex_m_semihosting;
extern crate panic_halt;
extern crate stm32l4xx_hal;
use crate::cortex_m_rt::entry;
use crate::stm32l4xx_hal::delay::Delay;
use crate::stm32l4xx_hal::prelude::*;
use crate::cortex_m_semihosting::hio;
use core::fmt::Write;
#[entry]
fn main() -> ! {
const BLINK_MS: u32 = 500;
let mut hstdout = hio::hstdout().unwrap();
writeln!(hstdout, "Hello, world!").unwrap();
let cp = cortex_m::Peripherals::take().unwrap();
let dp = stm32l4xx_hal::stm32::Peripherals::take().unwrap();
let mut flash = dp.FLASH.constrain();
let mut rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.hclk(8.mhz()).freeze(&mut flash.acr);
let mut timer = Delay::new(cp.SYST, clocks);
let mut gpiob = dp.GPIOB.split(&mut rcc.ahb2);
let mut led = gpiob
.pb3
.into_push_pull_output(&mut gpiob.moder, &mut gpiob.otyper);
let mut i: usize = 0;
loop {
timer.delay_ms(BLINK_MS);
writeln!(hstdout, "{} Blink on!", i).unwrap();
led.set_high().unwrap();
timer.delay_ms(BLINK_MS);
writeln!(hstdout, "{} Blink off!", i).unwrap();
led.set_low().unwrap();
i += 1;
}
}
|
error_chain! {
foreign_links {
Bson(::bson::ValueAccessError);
Bcrypt(::bcrypt::BcryptError);
Jwt(::jwt::Error);
}
errors {
NoCredentialsMatch
}
}
|
use serde::de;
use crate::de::{Deserializer, Error, Result};
pub(crate) struct SeqAccess<'a, 'b>
{
first: bool,
de: &'a mut Deserializer<'b>,
}
impl<'a, 'b> SeqAccess<'a, 'b> {
pub fn new(de: &'a mut Deserializer<'b>) -> Self {
SeqAccess { de, first: true }
}
}
impl<'a, 'de> de::SeqAccess<'de> for SeqAccess<'a, 'de> {
type Error = Error;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
where
T: de::DeserializeSeed<'de>,
{
let peek = match self
.de
.parse_whitespace()
.ok_or(Error::EofWhileParsingList)?
{
b']' => return Ok(None),
b',' => {
self.de.eat_char();
self.de
.parse_whitespace()
.ok_or(Error::EofWhileParsingValue)?
}
c => {
if self.first {
self.first = false;
c
} else {
return Err(Error::ExpectedListCommaOrEnd);
}
}
};
if peek == b']' {
Err(Error::TrailingComma)
} else {
Ok(Some(seed.deserialize(&mut *self.de)?))
}
}
}
|
use serde::Deserialize;
use crate::models::media::{MediaBase, MediaConnection, MediaEdge};
use crate::models::{AniListID, MediaType};
use crate::utils::{media_base_to_legend, na_long_str, synopsis};
const MAX_RELATED_MEDIA_ENTRIES: usize = 10;
#[derive(Clone, Debug, Deserialize)]
pub struct CharacterConnection {
edges: Vec<CharacterEdge>,
// nodes: Vec<CharacterBase>,
// page_info: PageInfo,
}
#[derive(Clone, Debug, Deserialize)]
pub struct CharacterEdge {
node: CharacterBase,
role: CharacterRole,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum CharacterRole {
Main,
Supporting,
Background,
}
impl std::fmt::Display for CharacterRole {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let string = match self {
CharacterRole::Main => "Main",
CharacterRole::Supporting => "Supporting",
CharacterRole::Background => "Background",
};
write!(f, "{}", string)
}
}
#[derive(Clone, Debug, Deserialize)]
pub struct CharacterName {
first: Option<String>,
last: Option<String>,
full: String,
native: Option<String>,
alternative: Vec<String>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct CharacterImage {
large: Option<String>,
medium: Option<String>,
}
type CharacterBase = Character;
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Character {
pub id: AniListID,
name: CharacterName,
image: CharacterImage,
description: Option<String>,
pub site_url: String,
pub media: Option<MediaConnection>,
favourites: u32,
}
impl Character {
pub fn name(&self) -> String {
self.name.full.clone()
}
pub fn synopsis(&self) -> String {
if let Some(description) = &self.description {
return synopsis(description, 300);
}
na_long_str()
}
pub fn avatar(&self) -> String {
if let Some(image) = &self.image.large {
return image.clone();
}
if let Some(image) = &self.image.medium {
return image.clone();
}
"https://s4.anilist.co/file/anilistcdn/character/large/default.jpg".to_string()
}
fn _related_media_url(&self, media: &MediaBase, role: Option<CharacterRole>) -> String {
let mut url = media.markdown_link_with_status();
if let Some(role) = role {
url.push_str(&format!(" ({} role)", role.to_string()));
}
url
}
fn _take_related_media(
&self,
media_type: MediaType,
n: usize,
) -> Option<(Vec<MediaEdge>, usize)> {
let edges = self.media.as_ref()?.edges.as_ref()?;
let filtered_media = edges
.iter()
.filter(|edge| edge.node.r#type == media_type)
.collect::<Vec<_>>();
let total = filtered_media.len();
let media = filtered_media
.into_iter()
.take(n)
.cloned()
.collect::<Vec<_>>();
if !media.is_empty() {
return Some((media, total.saturating_sub(n)));
}
None
}
fn _related_media(&self, media_type: MediaType) -> Option<String> {
let (related_media, remaining) =
self._take_related_media(media_type, MAX_RELATED_MEDIA_ENTRIES)?;
let mut related_media: Vec<String> = related_media
.iter()
.map(|edge| self._related_media_url(&edge.node, edge.character_role.clone()))
.collect();
if remaining > 0 {
related_media.push(format!("**+ {} more...**", remaining));
}
if !related_media.is_empty() {
return Some(related_media.join("\n"));
}
None
}
pub fn related_anime(&self) -> String {
self._related_media(MediaType::Anime)
.unwrap_or_else(na_long_str)
}
pub fn related_manga(&self) -> String {
self._related_media(MediaType::Manga)
.unwrap_or_else(na_long_str)
}
fn _media_legend(&self, media_type: MediaType) -> Option<String> {
let (media, _) = self._take_related_media(media_type, MAX_RELATED_MEDIA_ENTRIES)?;
let media = media
.iter()
.map(|edge| edge.node.clone())
.collect::<Vec<_>>();
media_base_to_legend(&media)
}
pub fn anime_legend(&self) -> Option<String> {
self._media_legend(MediaType::Anime)
}
pub fn manga_legend(&self) -> Option<String> {
self._media_legend(MediaType::Manga)
}
}
|
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
// !! Entry represents an entry in database.
#[derive(Clone)]
pub struct Entry {
pub link: String,
pub author: Option<u64>,
}
impl Hash for Entry {
fn hash<H: Hasher>(&self, state: &mut H) {
self.link.hash(state);
}
}
pub fn calculate_hash<T: Hash>(t: &T) -> u64 {
let mut s = DefaultHasher::new();
t.hash(&mut s);
s.finish()
}
|
use tests_build::tokio;
#[tokio::main]
async fn missing_semicolon_or_return_type() {
Ok(())
}
#[tokio::main]
async fn missing_return_type() {
/* TODO(taiki-e): one of help messages still wrong
help: consider using a semicolon here
|
16 | return Ok(());;
|
*/
return Ok(());
}
#[tokio::main]
async fn extra_semicolon() -> Result<(), ()> {
/* TODO(taiki-e): help message still wrong
help: try using a variant of the expected enum
|
29 | Ok(Ok(());)
|
29 | Err(Ok(());)
|
*/
Ok(());
}
fn main() {}
|
// ===============================================================================
// Authors: AFRL/RQQA
// Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
//
// Copyright (c) 2017 Government of the United State of America, as represented by
// the Secretary of the Air Force. No copyright is claimed in the United States under
// Title 17, U.S. Code. All Other Rights Reserved.
// ===============================================================================
// This file was auto-created by LmcpGen. Modifications will be overwritten.
use avtas::lmcp::{Error, ErrorType, Lmcp, LmcpSubscription, SrcLoc, Struct, StructInfo};
use std::fmt::Debug;
#[derive(Clone, Debug, Default)]
#[repr(C)]
pub struct AbstractZone {
pub zone_id: i64,
pub min_altitude: f32,
pub min_altitude_type: ::afrl::cmasi::altitude_type::AltitudeType,
pub max_altitude: f32,
pub max_altitude_type: ::afrl::cmasi::altitude_type::AltitudeType,
pub affected_aircraft: Vec<i64>,
pub start_time: i64,
pub end_time: i64,
pub padding: f32,
pub label: Vec<u8>,
pub boundary: Box<::afrl::cmasi::abstract_geometry::AbstractGeometryT>,
}
impl PartialEq for AbstractZone {
fn eq(&self, _other: &AbstractZone) -> bool {
true
&& &self.zone_id == &_other.zone_id
&& &self.min_altitude == &_other.min_altitude
&& &self.min_altitude_type == &_other.min_altitude_type
&& &self.max_altitude == &_other.max_altitude
&& &self.max_altitude_type == &_other.max_altitude_type
&& &self.affected_aircraft == &_other.affected_aircraft
&& &self.start_time == &_other.start_time
&& &self.end_time == &_other.end_time
&& &self.padding == &_other.padding
&& &self.label == &_other.label
&& &self.boundary == &_other.boundary
}
}
impl LmcpSubscription for AbstractZone {
fn subscription() -> &'static str { "afrl.cmasi.AbstractZone" }
}
impl Struct for AbstractZone {
fn struct_info() -> StructInfo {
StructInfo {
exist: 1,
series: 4849604199710720000u64,
version: 3,
struct_ty: 10,
}
}
}
impl Lmcp for AbstractZone {
fn ser(&self, buf: &mut[u8]) -> Result<usize, Error> {
let mut pos = 0;
{
let x = Self::struct_info().ser(buf)?;
pos += x;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.zone_id.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.min_altitude.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.min_altitude_type.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.max_altitude.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.max_altitude_type.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.affected_aircraft.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.start_time.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.end_time.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.padding.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.label.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.boundary.ser(r)?;
pos += writeb;
}
Ok(pos)
}
fn deser(buf: &[u8]) -> Result<(AbstractZone, usize), Error> {
let mut pos = 0;
let (si, u) = StructInfo::deser(buf)?;
pos += u;
if si == AbstractZone::struct_info() {
let mut out: AbstractZone = Default::default();
{
let r = get!(buf.get(pos ..));
let (x, readb): (i64, usize) = Lmcp::deser(r)?;
out.zone_id = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.min_altitude = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (::afrl::cmasi::altitude_type::AltitudeType, usize) = Lmcp::deser(r)?;
out.min_altitude_type = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.max_altitude = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (::afrl::cmasi::altitude_type::AltitudeType, usize) = Lmcp::deser(r)?;
out.max_altitude_type = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (Vec<i64>, usize) = Lmcp::deser(r)?;
out.affected_aircraft = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (i64, usize) = Lmcp::deser(r)?;
out.start_time = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (i64, usize) = Lmcp::deser(r)?;
out.end_time = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.padding = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (Vec<u8>, usize) = Lmcp::deser(r)?;
out.label = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (Box<::afrl::cmasi::abstract_geometry::AbstractGeometryT>, usize) = Lmcp::deser(r)?;
out.boundary = x;
pos += readb;
}
Ok((out, pos))
} else {
Err(error!(ErrorType::InvalidStructInfo))
}
}
fn size(&self) -> usize {
let mut size = 15;
size += self.zone_id.size();
size += self.min_altitude.size();
size += self.min_altitude_type.size();
size += self.max_altitude.size();
size += self.max_altitude_type.size();
size += self.affected_aircraft.size();
size += self.start_time.size();
size += self.end_time.size();
size += self.padding.size();
size += self.label.size();
size += self.boundary.size();
size
}
}
pub trait AbstractZoneT: Debug + Send {
fn as_afrl_cmasi_abstract_zone(&self) -> Option<&AbstractZone> { None }
fn as_mut_afrl_cmasi_abstract_zone(&mut self) -> Option<&mut AbstractZone> { None }
fn as_afrl_cmasi_keep_out_zone(&self) -> Option<&::afrl::cmasi::keep_out_zone::KeepOutZone> { None }
fn as_mut_afrl_cmasi_keep_out_zone(&mut self) -> Option<&mut ::afrl::cmasi::keep_out_zone::KeepOutZone> { None }
fn as_afrl_impact_water_zone(&self) -> Option<&::afrl::impact::water_zone::WaterZone> { None }
fn as_mut_afrl_impact_water_zone(&mut self) -> Option<&mut ::afrl::impact::water_zone::WaterZone> { None }
fn as_afrl_cmasi_keep_in_zone(&self) -> Option<&::afrl::cmasi::keep_in_zone::KeepInZone> { None }
fn as_mut_afrl_cmasi_keep_in_zone(&mut self) -> Option<&mut ::afrl::cmasi::keep_in_zone::KeepInZone> { None }
fn zone_id(&self) -> i64;
fn zone_id_mut(&mut self) -> &mut i64;
fn min_altitude(&self) -> f32;
fn min_altitude_mut(&mut self) -> &mut f32;
fn min_altitude_type(&self) -> ::afrl::cmasi::altitude_type::AltitudeType;
fn min_altitude_type_mut(&mut self) -> &mut ::afrl::cmasi::altitude_type::AltitudeType;
fn max_altitude(&self) -> f32;
fn max_altitude_mut(&mut self) -> &mut f32;
fn max_altitude_type(&self) -> ::afrl::cmasi::altitude_type::AltitudeType;
fn max_altitude_type_mut(&mut self) -> &mut ::afrl::cmasi::altitude_type::AltitudeType;
fn affected_aircraft(&self) -> &Vec<i64>;
fn affected_aircraft_mut(&mut self) -> &mut Vec<i64>;
fn start_time(&self) -> i64;
fn start_time_mut(&mut self) -> &mut i64;
fn end_time(&self) -> i64;
fn end_time_mut(&mut self) -> &mut i64;
fn padding(&self) -> f32;
fn padding_mut(&mut self) -> &mut f32;
fn label(&self) -> &Vec<u8>;
fn label_mut(&mut self) -> &mut Vec<u8>;
fn boundary(&self) -> &Box<::afrl::cmasi::abstract_geometry::AbstractGeometryT>;
fn boundary_mut(&mut self) -> &mut Box<::afrl::cmasi::abstract_geometry::AbstractGeometryT>;
}
impl Clone for Box<AbstractZoneT> {
fn clone(&self) -> Box<AbstractZoneT> {
if let Some(x) = AbstractZoneT::as_afrl_cmasi_abstract_zone(self.as_ref()) {
Box::new(x.clone())
} else if let Some(x) = AbstractZoneT::as_afrl_cmasi_keep_out_zone(self.as_ref()) {
Box::new(x.clone())
} else if let Some(x) = AbstractZoneT::as_afrl_impact_water_zone(self.as_ref()) {
Box::new(x.clone())
} else if let Some(x) = AbstractZoneT::as_afrl_cmasi_keep_in_zone(self.as_ref()) {
Box::new(x.clone())
} else {
unreachable!()
}
}
}
impl Default for Box<AbstractZoneT> {
fn default() -> Box<AbstractZoneT> { Box::new(AbstractZone::default()) }
}
impl PartialEq for Box<AbstractZoneT> {
fn eq(&self, other: &Box<AbstractZoneT>) -> bool {
if let (Some(x), Some(y)) =
(AbstractZoneT::as_afrl_cmasi_abstract_zone(self.as_ref()),
AbstractZoneT::as_afrl_cmasi_abstract_zone(other.as_ref())) {
x == y
} else if let (Some(x), Some(y)) =
(AbstractZoneT::as_afrl_cmasi_keep_out_zone(self.as_ref()),
AbstractZoneT::as_afrl_cmasi_keep_out_zone(other.as_ref())) {
x == y
} else if let (Some(x), Some(y)) =
(AbstractZoneT::as_afrl_impact_water_zone(self.as_ref()),
AbstractZoneT::as_afrl_impact_water_zone(other.as_ref())) {
x == y
} else if let (Some(x), Some(y)) =
(AbstractZoneT::as_afrl_cmasi_keep_in_zone(self.as_ref()),
AbstractZoneT::as_afrl_cmasi_keep_in_zone(other.as_ref())) {
x == y
} else {
false
}
}
}
impl Lmcp for Box<AbstractZoneT> {
fn ser(&self, buf: &mut[u8]) -> Result<usize, Error> {
if let Some(x) = AbstractZoneT::as_afrl_cmasi_abstract_zone(self.as_ref()) {
x.ser(buf)
} else if let Some(x) = AbstractZoneT::as_afrl_cmasi_keep_out_zone(self.as_ref()) {
x.ser(buf)
} else if let Some(x) = AbstractZoneT::as_afrl_impact_water_zone(self.as_ref()) {
x.ser(buf)
} else if let Some(x) = AbstractZoneT::as_afrl_cmasi_keep_in_zone(self.as_ref()) {
x.ser(buf)
} else {
unreachable!()
}
}
fn deser(buf: &[u8]) -> Result<(Box<AbstractZoneT>, usize), Error> {
let (si, _) = StructInfo::deser(buf)?;
if si == AbstractZone::struct_info() {
let (x, readb) = AbstractZone::deser(buf)?;
Ok((Box::new(x), readb))
} else if si == ::afrl::cmasi::keep_out_zone::KeepOutZone::struct_info() {
let (x, readb) = ::afrl::cmasi::keep_out_zone::KeepOutZone::deser(buf)?;
Ok((Box::new(x), readb))
} else if si == ::afrl::impact::water_zone::WaterZone::struct_info() {
let (x, readb) = ::afrl::impact::water_zone::WaterZone::deser(buf)?;
Ok((Box::new(x), readb))
} else if si == ::afrl::cmasi::keep_in_zone::KeepInZone::struct_info() {
let (x, readb) = ::afrl::cmasi::keep_in_zone::KeepInZone::deser(buf)?;
Ok((Box::new(x), readb))
} else {
Err(error!(ErrorType::InvalidStructInfo))
}
}
fn size(&self) -> usize {
if let Some(x) = AbstractZoneT::as_afrl_cmasi_abstract_zone(self.as_ref()) {
x.size()
} else if let Some(x) = AbstractZoneT::as_afrl_cmasi_keep_out_zone(self.as_ref()) {
x.size()
} else if let Some(x) = AbstractZoneT::as_afrl_impact_water_zone(self.as_ref()) {
x.size()
} else if let Some(x) = AbstractZoneT::as_afrl_cmasi_keep_in_zone(self.as_ref()) {
x.size()
} else {
unreachable!()
}
}
}
impl AbstractZoneT for AbstractZone {
fn as_afrl_cmasi_abstract_zone(&self) -> Option<&AbstractZone> { Some(self) }
fn as_mut_afrl_cmasi_abstract_zone(&mut self) -> Option<&mut AbstractZone> { Some(self) }
fn zone_id(&self) -> i64 { self.zone_id }
fn zone_id_mut(&mut self) -> &mut i64 { &mut self.zone_id }
fn min_altitude(&self) -> f32 { self.min_altitude }
fn min_altitude_mut(&mut self) -> &mut f32 { &mut self.min_altitude }
fn min_altitude_type(&self) -> ::afrl::cmasi::altitude_type::AltitudeType { self.min_altitude_type }
fn min_altitude_type_mut(&mut self) -> &mut ::afrl::cmasi::altitude_type::AltitudeType { &mut self.min_altitude_type }
fn max_altitude(&self) -> f32 { self.max_altitude }
fn max_altitude_mut(&mut self) -> &mut f32 { &mut self.max_altitude }
fn max_altitude_type(&self) -> ::afrl::cmasi::altitude_type::AltitudeType { self.max_altitude_type }
fn max_altitude_type_mut(&mut self) -> &mut ::afrl::cmasi::altitude_type::AltitudeType { &mut self.max_altitude_type }
fn affected_aircraft(&self) -> &Vec<i64> { &self.affected_aircraft }
fn affected_aircraft_mut(&mut self) -> &mut Vec<i64> { &mut self.affected_aircraft }
fn start_time(&self) -> i64 { self.start_time }
fn start_time_mut(&mut self) -> &mut i64 { &mut self.start_time }
fn end_time(&self) -> i64 { self.end_time }
fn end_time_mut(&mut self) -> &mut i64 { &mut self.end_time }
fn padding(&self) -> f32 { self.padding }
fn padding_mut(&mut self) -> &mut f32 { &mut self.padding }
fn label(&self) -> &Vec<u8> { &self.label }
fn label_mut(&mut self) -> &mut Vec<u8> { &mut self.label }
fn boundary(&self) -> &Box<::afrl::cmasi::abstract_geometry::AbstractGeometryT> { &self.boundary }
fn boundary_mut(&mut self) -> &mut Box<::afrl::cmasi::abstract_geometry::AbstractGeometryT> { &mut self.boundary }
}
#[cfg(test)]
pub mod tests {
use super::*;
use quickcheck::*;
impl Arbitrary for AbstractZone {
fn arbitrary<G: Gen>(_g: &mut G) -> AbstractZone {
AbstractZone {
zone_id: Arbitrary::arbitrary(_g),
min_altitude: Arbitrary::arbitrary(_g),
min_altitude_type: Arbitrary::arbitrary(_g),
max_altitude: Arbitrary::arbitrary(_g),
max_altitude_type: Arbitrary::arbitrary(_g),
affected_aircraft: Arbitrary::arbitrary(_g),
start_time: Arbitrary::arbitrary(_g),
end_time: Arbitrary::arbitrary(_g),
padding: Arbitrary::arbitrary(_g),
label: Arbitrary::arbitrary(_g),
boundary: Box::new(::afrl::cmasi::abstract_geometry::AbstractGeometry::arbitrary(_g)),
}
}
}
quickcheck! {
fn serializes(x: AbstractZone) -> Result<TestResult, Error> {
use std::u16;
if x.affected_aircraft.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
let mut buf: Vec<u8> = vec![0; x.size()];
let sx = x.ser(&mut buf)?;
Ok(TestResult::from_bool(sx == x.size()))
}
fn roundtrips(x: AbstractZone) -> Result<TestResult, Error> {
use std::u16;
if x.affected_aircraft.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
let mut buf: Vec<u8> = vec![0; x.size()];
let sx = x.ser(&mut buf)?;
let (y, sy) = AbstractZone::deser(&buf)?;
Ok(TestResult::from_bool(sx == sy && x == y))
}
}
}
|
use js_sys::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// Tracks mutable access to a value using a dirty flag.
///
/// The dirty flag is asserted whenever this type's `DerefMut` impl is
/// invoked and can be reset to `false` via the `Dirty::clean` method.
///
/// Values are initially dirty when created, cloned or deserialized.
#[derive(Copy, Debug, Default)]
pub struct Dirty<T> {
is_clean: bool,
inner: T,
}
impl<T> Dirty<T> {
/// Creates a new dirty value.
pub fn new(inner: T) -> Self {
Self {
is_clean: false,
inner,
}
}
/// Forcibly dirties the value.
pub fn dirty(this: &mut Self) {
this.is_clean = false;
}
/// Returns the value only if it is dirty.
pub fn as_dirty(this: &Self) -> Option<&T> {
if this.is_clean {
return None;
}
Some(&this.inner)
}
/// Returns whether the value is dirty.
pub fn is_dirty(this: &Self) -> bool {
!this.is_clean
}
/// Marks the value as clean and returns whether it was dirty.
///
/// The `update` callback is invoked if the value is dirty. If the callback
/// fails by returning an error, the value will remain dirty and unchanged.
pub fn clean(
this: &mut Self,
update: impl FnOnce(&T) -> Result<(), Error>,
) -> Result<bool, Error> {
if this.is_clean {
return Ok(false);
}
update(&this.inner)?;
this.is_clean = true;
Ok(true)
}
}
impl<T: Clone + PartialEq> Dirty<T> {
/// Allows mutating the value and dirties it if it was changed.
pub fn modify(this: &mut Self, callback: impl FnOnce(&mut T)) {
let mut modified = this.inner.clone();
callback(&mut modified);
if this.inner != modified {
this.inner = modified;
this.is_clean = false;
}
}
}
impl<T: Clone> Clone for Dirty<T> {
fn clone(&self) -> Self {
Self::new(self.inner.clone())
}
}
impl<T> std::ops::Deref for Dirty<T> {
type Target = T;
fn deref(&self) -> &T {
&self.inner
}
}
impl<T> std::ops::DerefMut for Dirty<T> {
fn deref_mut(&mut self) -> &mut T {
self.is_clean = false;
&mut self.inner
}
}
impl<'de, T: Deserialize<'de>> Deserialize<'de> for Dirty<T> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self::new(T::deserialize(deserializer)?))
}
}
impl<T: PartialEq> PartialEq for Dirty<T> {
fn eq(&self, other: &Self) -> bool {
self.inner.eq(&other.inner)
}
}
impl<T: Serialize> Serialize for Dirty<T> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.inner.serialize(serializer)
}
}
|
use std::ops;
#[derive(Debug, PartialEq, Copy)]
pub struct Vec3(pub f64, pub f64, pub f64);
impl Vec3 {
pub fn x(&self) -> f64 {
self.0
}
pub fn y(&self) -> f64 {
self.1
}
pub fn z(&self) -> f64 {
self.2
}
pub fn r(&self) -> f64 {
self.0
}
pub fn g(&self) -> f64 {
self.1
}
pub fn b(&self) -> f64 {
self.2
}
pub fn length(&self) -> f64 {
(self.0 * self.0 + self.1 * self.1 + self.2 * self.2).sqrt()
}
pub fn squared_length(&self) -> f64 {
self.0 * self.0 + self.1 * self.1 + self.2 * self.2
}
pub fn normalized(&self) -> (Vec3) {
*self / self.length()
}
pub fn dot(&self, rhs: Vec3) -> f64 {
self.0 * rhs.0 + self.1 * rhs.1 + self.2 * rhs.2
}
pub fn cross(&self, rhs: Vec3) -> Vec3 {
Vec3(
self.1 * rhs.2 - self.2 * rhs.1,
-(self.0 * rhs.2 - self.2 * rhs.0),
self.0 * rhs.1 - self.1 * rhs.0,
)
}
}
impl Clone for Vec3 {
fn clone(&self) -> Self {
*self
}
}
impl ops::Add<Vec3> for Vec3 {
type Output = Vec3;
fn add(self, rhs: Vec3) -> Vec3 {
Vec3(self.0 + rhs.0, self.1 + rhs.1, self.2 + rhs.2)
}
}
impl ops::Neg for Vec3 {
type Output = Vec3;
fn neg(self) -> Vec3 {
Vec3(-self.0, -self.1, -self.2)
}
}
impl ops::Sub<Vec3> for Vec3 {
type Output = Vec3;
fn sub(self, rhs: Vec3) -> Vec3 {
Vec3(self.0 - rhs.0, self.1 - rhs.1, self.2 - rhs.2)
}
}
impl ops::AddAssign<Vec3> for Vec3 {
fn add_assign(&mut self, rhs: Vec3) -> () {
self.0 += rhs.0;
self.1 += rhs.1;
self.2 += rhs.2;
}
}
impl ops::SubAssign<Vec3> for Vec3 {
fn sub_assign(&mut self, rhs: Vec3) -> () {
self.0 -= rhs.0;
self.1 -= rhs.1;
self.2 -= rhs.2;
}
}
impl ops::Mul<Vec3> for Vec3 {
type Output = Vec3;
fn mul(self, rhs: Vec3) -> Vec3 {
Vec3(self.0 * rhs.0, self.1 * rhs.1, self.2 * rhs.2)
}
}
impl ops::Mul<f64> for Vec3 {
type Output = Vec3;
fn mul(self, rhs: f64) -> Vec3 {
Vec3(self.0 * rhs, self.1 * rhs, self.2 * rhs)
}
}
impl ops::Mul<Vec3> for f64 {
type Output = Vec3;
fn mul(self, rhs: Vec3) -> Vec3 {
Vec3(self * rhs.0, self * rhs.1, self * rhs.2)
}
}
impl ops::Div<Vec3> for Vec3 {
type Output = Vec3;
fn div(self, rhs: Vec3) -> Vec3 {
Vec3(self.0 / rhs.0, self.1 / rhs.1, self.2 / rhs.2)
}
}
impl ops::Div<f64> for Vec3 {
type Output = Vec3;
fn div(self, rhs: f64) -> Vec3 {
Vec3(self.0 / rhs, self.1 / rhs, self.2 / rhs)
}
}
impl ops::MulAssign<Vec3> for Vec3 {
fn mul_assign(&mut self, rhs: Vec3) -> () {
self.0 *= rhs.0;
self.1 *= rhs.1;
self.2 *= rhs.2;
}
}
impl ops::MulAssign<f64> for Vec3 {
fn mul_assign(&mut self, rhs: f64) -> () {
self.0 *= rhs;
self.1 *= rhs;
self.2 *= rhs;
}
}
impl ops::DivAssign<Vec3> for Vec3 {
fn div_assign(&mut self, rhs: Vec3) -> () {
self.0 /= rhs.0;
self.1 /= rhs.1;
self.2 /= rhs.2;
}
}
impl ops::DivAssign<f64> for Vec3 {
fn div_assign(&mut self, rhs: f64) -> () {
self.0 /= rhs;
self.1 /= rhs;
self.2 /= rhs;
}
}
#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;
#[test]
fn accessors_work() {
let v = Vec3(1.0, 2.0, 3.0);
assert_eq!(v.x(), v.0);
assert_eq!(v.y(), v.1);
assert_eq!(v.z(), v.2);
assert_eq!(v.r(), v.0);
assert_eq!(v.g(), v.1);
assert_eq!(v.b(), v.2);
}
#[test]
fn adds_two_vectors() {
let v = Vec3(1.0, 2.0, 3.0);
let v2 = Vec3(5.0, 1.0, 0.0);
assert_eq!(v + v2, Vec3(1.0 + 5.0, 2.0 + 1.0, 3.0 + 0.0));
}
#[test]
fn negative_operator() {
let v = Vec3(1.0, 2.0, 3.0);
assert_eq!(-v, Vec3(-1.0, -2.0, -3.0));
}
#[test]
fn subtracts_two_vectors() {
let v = Vec3(1.0, 2.0, 3.0);
let v2 = Vec3(5.0, 1.0, 0.0);
assert_eq!(v - v2, Vec3(1.0 - 5.0, 2.0 - 1.0, 3.0 - 0.0));
}
#[test]
fn add_assign() {
let mut v = Vec3(1.0, 2.0, 3.0);
let v2 = Vec3(5.0, 1.0, 0.0);
v += v2;
assert_eq!(v, Vec3(1.0 + 5.0, 2.0 + 1.0, 3.0 + 0.0));
}
#[test]
fn sub_assign() {
let mut v = Vec3(1.0, 2.0, 3.0);
let v2 = Vec3(5.0, 1.0, 0.0);
v -= v2;
assert_eq!(v, Vec3(1.0 - 5.0, 2.0 - 1.0, 3.0 - 0.0));
}
#[test]
fn mul_two_vectors() {
let v = Vec3(1.0, 2.0, 3.0);
let v2 = Vec3(5.0, 1.0, 0.0);
assert_eq!(v * v2, Vec3(1.0 * 5.0, 2.0 * 1.0, 3.0 * 0.0));
}
#[test]
fn mul_scalar_and_vector() {
let v = Vec3(1.0, 2.0, 3.0);
let s = 5.0;
assert_eq!(s * v, Vec3(s * 1.0, s * 2.0, s * 3.0));
assert_eq!(v * s, Vec3(s * 1.0, s * 2.0, s * 3.0));
}
#[test]
fn mul_assign_with_scalar() {
let mut v = Vec3(1.0, 2.0, 3.0);
let s = 5.0;
v *= s;
assert_eq!(v, Vec3(s * 1.0, s * 2.0, s * 3.0));
}
#[test]
fn mul_assign_with_vector() {
let mut v = Vec3(1.0, 2.0, 3.0);
let v2 = Vec3(2.0, 3.0, 4.0);
v *= v2;
assert_eq!(v, Vec3(2.0 * 1.0, 3.0 * 2.0, 4.0 * 3.0));
}
#[test]
fn div_assign_with_scalar() {
let mut v = Vec3(1.0, 2.0, 3.0);
let s = 5.0;
v /= s;
assert_eq!(v, Vec3(1.0 / s, 2.0 / s, 3.0 / s));
}
#[test]
fn div_assign_with_vector() {
let mut v = Vec3(2.0, 3.0, 4.0);
let v2 = Vec3(1.0, 2.0, 3.0);
v /= v2;
assert_eq!(v, Vec3(2.0 / 1.0, 3.0 / 2.0, 4.0 / 3.0));
}
#[test]
fn assign_by_copying() {
let mut v = Vec3(1.0, 2.0, 3.0);
let v2 = v;
v.0 = 7.0;
assert_eq!(v.0, 7.0);
assert_eq!(v2.0, 1.0);
}
#[test]
fn assign_by_copying_mut() {
let mut v = Vec3(1.0, 2.0, 3.0);
let v2 = v;
v.0 = 7.0;
assert_eq!(v.0, 7.0);
assert_eq!(v2.0, 1.0);
}
#[test]
fn copy_ref() {
let mut v = Vec3(1.0, 2.0, 3.0);
assert_eq!(v.0, 1.0);
let ref mut v2 = v;
v2.0 = 7.0;
assert_eq!(v2.0, 7.0);
assert_eq!(v.0, 7.0);
v.0 = 5.0;
assert_eq!(v.0, 5.0);
}
#[test]
fn div_two_vectors() {
let v = Vec3(1.0, 2.0, 3.0);
let v2 = Vec3(5.0, 1.0, 0.0);
assert_eq!(v / v2, Vec3(1.0 / 5.0, 2.0 / 1.0, 3.0 / 0.0));
}
#[test]
fn div_scalar_and_vector() {
let v = Vec3(1.0, 2.0, 3.0);
let s = 5.0;
assert_eq!(v / s, Vec3(1.0 / s, 2.0 / s, 3.0 / s));
}
#[test]
fn length() {
let v = Vec3(3.0, 4.0, 0.0);
assert_eq!(v.length(), 5.0);
}
#[test]
fn squared_length() {
let v = Vec3(3.0, 2.0, 1.0);
assert_eq!(v.squared_length(), 14.0);
}
#[test]
fn normalized() {
let v = Vec3(3.0, 2.0, 1.0);
assert_eq!(
v.normalized(),
Vec3(3.0, 2.0, 1.0) / Vec3(3.0, 2.0, 1.0).length()
);
assert_eq!(Vec3(6.0, 0.0, 0.0).normalized(), Vec3(1.0, 0.0, 0.0));
}
#[test]
fn dot() {
let v = Vec3(3.0, 2.0, 1.0);
let v2 = Vec3(1.0, 2.0, 1.0);
assert_eq!(v.dot(v2), 3.0 + 4.0 + 1.0);
let v = Vec3(3.0, -5.0, 4.0);
let v2 = Vec3(2.0, 6.0, 5.0);
assert_eq!(v.dot(v2), -4.0);
}
#[test]
fn cross() {
let v = Vec3(3.0, -5.0, 4.0);
let v2 = Vec3(2.0, 6.0, 5.0);
assert_eq!(v.cross(v2), Vec3(-49.0, -7.0, 28.0));
}
#[test]
fn cross_is_right_handed() {
let x = Vec3(1.0, 0.0, 0.0);
let y = Vec3(0.0, 1.0, 0.0);
let z = Vec3(0.0, 0.0, 1.0);
assert_eq!(x.cross(y), z);
assert_eq!(y.cross(z), x);
assert_eq!(z.cross(x), y);
assert_eq!(x.cross(z), -y);
}
}
|
use super::super::{
program::TableGridProgram,
webgl::{WebGlF32Vbo, WebGlI16Ibo},
ModelMatrix,
};
use super::WebGlRenderingContext;
use crate::block;
use ndarray::Array2;
pub struct MeasureRenderer {
vertexis_buffer: WebGlF32Vbo,
index_buffer: WebGlI16Ibo,
table_grid_program: TableGridProgram,
}
impl MeasureRenderer {
pub fn new(gl: &WebGlRenderingContext) -> Self {
let vertexis_buffer =
gl.create_vbo_with_f32array(&[[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]].concat());
let index_buffer = gl.create_ibo_with_i16array(&[0, 1, 2, 3, 2, 1]);
let table_grid_program = TableGridProgram::new(gl);
Self {
vertexis_buffer,
index_buffer,
table_grid_program,
}
}
pub fn render<'a>(
&mut self,
gl: &WebGlRenderingContext,
vp_matrix: &Array2<f32>,
data_field: &block::Field,
) {
self.table_grid_program.use_program(gl);
gl.set_attribute(
&self.vertexis_buffer,
&self.table_grid_program.a_vertex_location,
3,
0,
);
gl.bind_buffer(
web_sys::WebGlRenderingContext::ELEMENT_ARRAY_BUFFER,
Some(&self.index_buffer),
);
gl.uniform1f(Some(&self.table_grid_program.u_point_size_location), 8.0);
for (_, measure) in data_field.all::<block::table_object::Measure>() {
let s = measure.vec();
let p = measure.org();
let model_matrix: Array2<f32> = ModelMatrix::new()
.with_scale(&[s[0], s[1], s[2]])
.with_movement(&p)
.into();
let mvp_matrix = vp_matrix.dot(&model_matrix);
let mvp_matrix = mvp_matrix.t();
gl.uniform_matrix4fv_with_f32_array(
Some(&self.table_grid_program.u_translate_location),
false,
&[
mvp_matrix.row(0).to_vec(),
mvp_matrix.row(1).to_vec(),
mvp_matrix.row(2).to_vec(),
mvp_matrix.row(3).to_vec(),
]
.concat()
.into_iter()
.map(|a| a as f32)
.collect::<Vec<f32>>(),
);
gl.uniform4fv_with_f32_array(
Some(&self.table_grid_program.u_mask_color_location),
&measure.color().to_f32array(),
);
gl.draw_elements_with_i32(
web_sys::WebGlRenderingContext::LINES,
2,
web_sys::WebGlRenderingContext::UNSIGNED_SHORT,
0,
);
gl.draw_elements_with_i32(
web_sys::WebGlRenderingContext::POINTS,
2,
web_sys::WebGlRenderingContext::UNSIGNED_SHORT,
0,
);
}
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - interrupt status register"]
pub isr: ISR,
#[doc = "0x04 - interrupt flag clear register"]
pub ifcr: IFCR,
#[doc = "0x08 - channel x configuration register"]
pub ccr1: CCR1,
#[doc = "0x0c - channel x number of data register"]
pub cndtr1: CNDTR1,
#[doc = "0x10 - channel x peripheral address register"]
pub cpar1: CPAR1,
#[doc = "0x14 - channel x memory address register"]
pub cm0ar1: CM0AR1,
#[doc = "0x18 - channel x memory address register"]
pub cm1ar1: CM1AR1,
#[doc = "0x1c - channel x configuration register"]
pub ccr2: CCR2,
#[doc = "0x20 - channel x number of data register"]
pub cndtr2: CNDTR2,
#[doc = "0x24 - channel x peripheral address register"]
pub cpar2: CPAR2,
#[doc = "0x28 - channel x memory address register"]
pub cm0ar2: CM0AR2,
#[doc = "0x2c - channel x memory address register"]
pub cm1ar2: CM1AR2,
#[doc = "0x30 - channel x configuration register"]
pub ccr3: CCR3,
#[doc = "0x34 - channel x number of data register"]
pub cndtr3: CNDTR3,
#[doc = "0x38 - channel x peripheral address register"]
pub cpar3: CPAR3,
#[doc = "0x3c - channel x memory address register"]
pub cm0ar3: CM0AR3,
#[doc = "0x40 - channel x memory address register"]
pub cm1ar3: CM1AR3,
#[doc = "0x44 - channel x configuration register"]
pub ccr4: CCR4,
#[doc = "0x48 - channel x number of data register"]
pub cndtr4: CNDTR4,
#[doc = "0x4c - channel x peripheral address register"]
pub cpar4: CPAR4,
#[doc = "0x50 - channel x memory address register"]
pub cm0ar4: CM0AR4,
#[doc = "0x54 - channel x memory address register"]
pub cm1ar4: CM1AR4,
#[doc = "0x58 - channel x configuration register"]
pub ccr5: CCR5,
#[doc = "0x5c - channel x number of data register"]
pub cndtr5: CNDTR5,
#[doc = "0x60 - channel x peripheral address register"]
pub cpar5: CPAR5,
#[doc = "0x64 - channel x memory address register"]
pub cm0ar5: CM0AR5,
#[doc = "0x68 - channel x memory address register"]
pub cm1ar5: CM1AR5,
#[doc = "0x6c - channel x configuration register"]
pub ccr6: CCR6,
#[doc = "0x70 - channel x number of data register"]
pub cndtr6: CNDTR6,
#[doc = "0x74 - channel x peripheral address register"]
pub cpar6: CPAR6,
#[doc = "0x78 - channel x memory address register"]
pub cm0ar6: CM0AR6,
#[doc = "0x7c - channel x memory address register"]
pub cm1ar6: CM1AR6,
#[doc = "0x80 - channel x configuration register"]
pub ccr7: CCR7,
#[doc = "0x84 - channel x number of data register"]
pub cndtr7: CNDTR7,
#[doc = "0x88 - channel x peripheral address register"]
pub cpar7: CPAR7,
#[doc = "0x8c - channel x memory address register"]
pub cm0ar7: CM0AR7,
#[doc = "0x90 - channel x memory address register"]
pub cm1ar7: CM1AR7,
#[doc = "0x94 - channel x configuration register"]
pub ccr8: CCR8,
#[doc = "0x98 - channel x number of data register"]
pub cndtr8: CNDTR8,
#[doc = "0x9c - channel x peripheral address register"]
pub cpar8: CPAR8,
#[doc = "0xa0 - channel x peripheral address register"]
pub cm0ar8: CM0AR8,
#[doc = "0xa4 - channel x peripheral address register"]
pub cm1ar8: CM1AR8,
#[doc = "0xa8 - channel selection register"]
pub cselr: CSELR,
}
#[doc = "ISR (r) register accessor: interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`isr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`isr`]
module"]
pub type ISR = crate::Reg<isr::ISR_SPEC>;
#[doc = "interrupt status register"]
pub mod isr;
#[doc = "IFCR (w) register accessor: interrupt flag clear register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ifcr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ifcr`]
module"]
pub type IFCR = crate::Reg<ifcr::IFCR_SPEC>;
#[doc = "interrupt flag clear register"]
pub mod ifcr;
#[doc = "CCR1 (rw) register accessor: channel x configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccr1`]
module"]
pub type CCR1 = crate::Reg<ccr1::CCR1_SPEC>;
#[doc = "channel x configuration register"]
pub mod ccr1;
#[doc = "CNDTR1 (rw) register accessor: channel x number of data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cndtr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cndtr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cndtr1`]
module"]
pub type CNDTR1 = crate::Reg<cndtr1::CNDTR1_SPEC>;
#[doc = "channel x number of data register"]
pub mod cndtr1;
#[doc = "CPAR1 (rw) register accessor: channel x peripheral address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpar1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpar1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpar1`]
module"]
pub type CPAR1 = crate::Reg<cpar1::CPAR1_SPEC>;
#[doc = "channel x peripheral address register"]
pub mod cpar1;
#[doc = "CM0AR1 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm0ar1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm0ar1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm0ar1`]
module"]
pub type CM0AR1 = crate::Reg<cm0ar1::CM0AR1_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm0ar1;
#[doc = "CM1AR1 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm1ar1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm1ar1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm1ar1`]
module"]
pub type CM1AR1 = crate::Reg<cm1ar1::CM1AR1_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm1ar1;
#[doc = "CCR2 (rw) register accessor: channel x configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccr2`]
module"]
pub type CCR2 = crate::Reg<ccr2::CCR2_SPEC>;
#[doc = "channel x configuration register"]
pub mod ccr2;
#[doc = "CNDTR2 (rw) register accessor: channel x number of data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cndtr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cndtr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cndtr2`]
module"]
pub type CNDTR2 = crate::Reg<cndtr2::CNDTR2_SPEC>;
#[doc = "channel x number of data register"]
pub mod cndtr2;
#[doc = "CPAR2 (rw) register accessor: channel x peripheral address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpar2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpar2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpar2`]
module"]
pub type CPAR2 = crate::Reg<cpar2::CPAR2_SPEC>;
#[doc = "channel x peripheral address register"]
pub mod cpar2;
#[doc = "CM0AR2 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm0ar2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm0ar2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm0ar2`]
module"]
pub type CM0AR2 = crate::Reg<cm0ar2::CM0AR2_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm0ar2;
#[doc = "CM1AR2 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm1ar2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm1ar2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm1ar2`]
module"]
pub type CM1AR2 = crate::Reg<cm1ar2::CM1AR2_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm1ar2;
#[doc = "CCR3 (rw) register accessor: channel x configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccr3`]
module"]
pub type CCR3 = crate::Reg<ccr3::CCR3_SPEC>;
#[doc = "channel x configuration register"]
pub mod ccr3;
#[doc = "CNDTR3 (rw) register accessor: channel x number of data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cndtr3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cndtr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cndtr3`]
module"]
pub type CNDTR3 = crate::Reg<cndtr3::CNDTR3_SPEC>;
#[doc = "channel x number of data register"]
pub mod cndtr3;
#[doc = "CPAR3 (rw) register accessor: channel x peripheral address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpar3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpar3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpar3`]
module"]
pub type CPAR3 = crate::Reg<cpar3::CPAR3_SPEC>;
#[doc = "channel x peripheral address register"]
pub mod cpar3;
#[doc = "CM0AR3 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm0ar3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm0ar3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm0ar3`]
module"]
pub type CM0AR3 = crate::Reg<cm0ar3::CM0AR3_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm0ar3;
#[doc = "CM1AR3 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm1ar3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm1ar3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm1ar3`]
module"]
pub type CM1AR3 = crate::Reg<cm1ar3::CM1AR3_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm1ar3;
#[doc = "CCR4 (rw) register accessor: channel x configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr4::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccr4::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccr4`]
module"]
pub type CCR4 = crate::Reg<ccr4::CCR4_SPEC>;
#[doc = "channel x configuration register"]
pub mod ccr4;
#[doc = "CNDTR4 (rw) register accessor: channel x number of data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cndtr4::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cndtr4::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cndtr4`]
module"]
pub type CNDTR4 = crate::Reg<cndtr4::CNDTR4_SPEC>;
#[doc = "channel x number of data register"]
pub mod cndtr4;
#[doc = "CPAR4 (rw) register accessor: channel x peripheral address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpar4::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpar4::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpar4`]
module"]
pub type CPAR4 = crate::Reg<cpar4::CPAR4_SPEC>;
#[doc = "channel x peripheral address register"]
pub mod cpar4;
#[doc = "CM0AR4 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm0ar4::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm0ar4::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm0ar4`]
module"]
pub type CM0AR4 = crate::Reg<cm0ar4::CM0AR4_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm0ar4;
#[doc = "CM1AR4 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm1ar4::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm1ar4::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm1ar4`]
module"]
pub type CM1AR4 = crate::Reg<cm1ar4::CM1AR4_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm1ar4;
#[doc = "CCR5 (rw) register accessor: channel x configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr5::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccr5::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccr5`]
module"]
pub type CCR5 = crate::Reg<ccr5::CCR5_SPEC>;
#[doc = "channel x configuration register"]
pub mod ccr5;
#[doc = "CNDTR5 (rw) register accessor: channel x number of data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cndtr5::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cndtr5::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cndtr5`]
module"]
pub type CNDTR5 = crate::Reg<cndtr5::CNDTR5_SPEC>;
#[doc = "channel x number of data register"]
pub mod cndtr5;
#[doc = "CPAR5 (rw) register accessor: channel x peripheral address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpar5::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpar5::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpar5`]
module"]
pub type CPAR5 = crate::Reg<cpar5::CPAR5_SPEC>;
#[doc = "channel x peripheral address register"]
pub mod cpar5;
#[doc = "CM0AR5 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm0ar5::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm0ar5::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm0ar5`]
module"]
pub type CM0AR5 = crate::Reg<cm0ar5::CM0AR5_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm0ar5;
#[doc = "CM1AR5 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm1ar5::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm1ar5::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm1ar5`]
module"]
pub type CM1AR5 = crate::Reg<cm1ar5::CM1AR5_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm1ar5;
#[doc = "CCR6 (rw) register accessor: channel x configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr6::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccr6::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccr6`]
module"]
pub type CCR6 = crate::Reg<ccr6::CCR6_SPEC>;
#[doc = "channel x configuration register"]
pub mod ccr6;
#[doc = "CNDTR6 (rw) register accessor: channel x number of data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cndtr6::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cndtr6::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cndtr6`]
module"]
pub type CNDTR6 = crate::Reg<cndtr6::CNDTR6_SPEC>;
#[doc = "channel x number of data register"]
pub mod cndtr6;
#[doc = "CPAR6 (rw) register accessor: channel x peripheral address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpar6::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpar6::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpar6`]
module"]
pub type CPAR6 = crate::Reg<cpar6::CPAR6_SPEC>;
#[doc = "channel x peripheral address register"]
pub mod cpar6;
#[doc = "CM0AR6 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm0ar6::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm0ar6::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm0ar6`]
module"]
pub type CM0AR6 = crate::Reg<cm0ar6::CM0AR6_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm0ar6;
#[doc = "CM1AR6 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm1ar6::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm1ar6::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm1ar6`]
module"]
pub type CM1AR6 = crate::Reg<cm1ar6::CM1AR6_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm1ar6;
#[doc = "CCR7 (rw) register accessor: channel x configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr7::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccr7::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccr7`]
module"]
pub type CCR7 = crate::Reg<ccr7::CCR7_SPEC>;
#[doc = "channel x configuration register"]
pub mod ccr7;
#[doc = "CNDTR7 (rw) register accessor: channel x number of data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cndtr7::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cndtr7::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cndtr7`]
module"]
pub type CNDTR7 = crate::Reg<cndtr7::CNDTR7_SPEC>;
#[doc = "channel x number of data register"]
pub mod cndtr7;
#[doc = "CPAR7 (rw) register accessor: channel x peripheral address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpar7::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpar7::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpar7`]
module"]
pub type CPAR7 = crate::Reg<cpar7::CPAR7_SPEC>;
#[doc = "channel x peripheral address register"]
pub mod cpar7;
#[doc = "CM0AR7 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm0ar7::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm0ar7::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm0ar7`]
module"]
pub type CM0AR7 = crate::Reg<cm0ar7::CM0AR7_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm0ar7;
#[doc = "CM1AR7 (rw) register accessor: channel x memory address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm1ar7::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm1ar7::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm1ar7`]
module"]
pub type CM1AR7 = crate::Reg<cm1ar7::CM1AR7_SPEC>;
#[doc = "channel x memory address register"]
pub mod cm1ar7;
#[doc = "CCR8 (rw) register accessor: channel x configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr8::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccr8::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccr8`]
module"]
pub type CCR8 = crate::Reg<ccr8::CCR8_SPEC>;
#[doc = "channel x configuration register"]
pub mod ccr8;
#[doc = "CNDTR8 (rw) register accessor: channel x number of data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cndtr8::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cndtr8::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cndtr8`]
module"]
pub type CNDTR8 = crate::Reg<cndtr8::CNDTR8_SPEC>;
#[doc = "channel x number of data register"]
pub mod cndtr8;
#[doc = "CPAR8 (rw) register accessor: channel x peripheral address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpar8::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpar8::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpar8`]
module"]
pub type CPAR8 = crate::Reg<cpar8::CPAR8_SPEC>;
#[doc = "channel x peripheral address register"]
pub mod cpar8;
#[doc = "CM0AR8 (rw) register accessor: channel x peripheral address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm0ar8::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm0ar8::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm0ar8`]
module"]
pub type CM0AR8 = crate::Reg<cm0ar8::CM0AR8_SPEC>;
#[doc = "channel x peripheral address register"]
pub mod cm0ar8;
#[doc = "CM1AR8 (rw) register accessor: channel x peripheral address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cm1ar8::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cm1ar8::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cm1ar8`]
module"]
pub type CM1AR8 = crate::Reg<cm1ar8::CM1AR8_SPEC>;
#[doc = "channel x peripheral address register"]
pub mod cm1ar8;
#[doc = "CSELR (rw) register accessor: channel selection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cselr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cselr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cselr`]
module"]
pub type CSELR = crate::Reg<cselr::CSELR_SPEC>;
#[doc = "channel selection register"]
pub mod cselr;
|
use futures::{Async, Future, Poll};
use super::{FilterBase, Filter};
#[derive(Clone, Copy, Debug)]
pub struct Unit<T> {
pub(super) filter: T,
}
impl<T> FilterBase for Unit<T>
where
T: Filter<Extract=((),)>,
{
type Extract = ();
type Error = T::Error;
type Future = UnitFuture<T>;
#[inline]
fn filter(&self) -> Self::Future {
UnitFuture {
extract: self.filter.filter(),
}
}
}
#[allow(missing_debug_implementations)]
pub struct UnitFuture<T: Filter> {
extract: T::Future,
}
impl<T> Future for UnitFuture<T>
where
T: Filter<Extract=((),)>,
{
type Item = ();
type Error = T::Error;
#[inline]
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let ((),) = try_ready!(self.extract.poll());
Ok(Async::Ready(()))
}
}
|
use super::{callbacks, controls, ids};
use std::collections::HashMap;
use std::fmt;
use std::marker::PhantomData;
use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor};
use typemap::{Key, TypeMap};
pub type MemberType = String;
pub type MemberSpawner = fn() -> Box<dyn controls::Control>;
struct CallbackKeyWrapper<T>(PhantomData<T>);
struct CallbackWrapper<T: callbacks::Callback>(T);
impl<T: 'static> Key for CallbackKeyWrapper<T>
where
T: callbacks::Callback,
{
type Value = CallbackWrapper<T>;
}
pub const ID: &str = "id";
pub const TYPE: &str = "type";
pub const CHILD: &str = "child";
pub const CHILDREN: &str = "children";
const FIELDS: &[&str] = &[ID, TYPE];
pub const MEMBER_TYPE_SPLITTED: &str = "Splitted";
pub const MEMBER_TYPE_FRAME: &str = "Frame";
pub const MEMBER_TYPE_LINEAR_LAYOUT: &str = "LinearLayout";
pub const MEMBER_TYPE_BUTTON: &str = "Button";
pub const MEMBER_TYPE_TEXT: &str = "Text";
pub const MEMBER_TYPE_IMAGE: &str = "Image";
pub const MEMBER_TYPE_PROGRESS_BAR: &str = "ProgressBar";
pub const MEMBER_TYPE_LIST: &str = "List";
pub struct MarkupRegistry {
spawners: HashMap<MemberType, MemberSpawner>,
ids: HashMap<String, ids::Id>,
bindings: HashMap<String, TypeMap>,
}
impl MarkupRegistry {
pub fn new() -> MarkupRegistry {
MarkupRegistry {
spawners: HashMap::new(),
ids: HashMap::new(),
bindings: HashMap::new(),
}
}
pub fn register_member(&mut self, member_type: MemberType, member_spawner: MemberSpawner) -> Result<(), MarkupError> {
if self.spawners.get(&member_type).is_none() {
self.spawners.insert(member_type, member_spawner);
Ok(())
} else {
Err(MarkupError::MemberAlreadyRegistered)
}
}
pub fn unregister_member(&mut self, member_type: &MemberType) -> Result<(), MarkupError> {
if self.spawners.remove(member_type).is_none() {
Err(MarkupError::MemberNotFound)
} else {
Ok(())
}
}
pub fn member(&self, member_type: &MemberType) -> Result<&MemberSpawner, MarkupError> {
self.spawners.get(member_type).ok_or(MarkupError::MemberNotFound)
}
pub fn push_callback<CallbackFn>(&mut self, name: &str, callback: CallbackFn) -> Result<(), MarkupError>
where
CallbackFn: callbacks::Callback + 'static,
{
if self.bindings.get(name).is_none() {
let mut tm = TypeMap::new();
tm.insert::<CallbackKeyWrapper<CallbackFn>>(CallbackWrapper(callback));
self.bindings.insert(name.into(), tm);
Ok(())
} else {
Err(MarkupError::CallbackAlreadyBinded)
}
}
pub fn peek_callback<CallbackFn>(&self, name: &str) -> Result<&CallbackFn, MarkupError>
where
CallbackFn: callbacks::Callback + 'static,
{
let tm = self.bindings.get(name).ok_or(MarkupError::CallbackNotFound)?;
tm.get::<CallbackKeyWrapper<CallbackFn>>().ok_or(MarkupError::CallbackNotFound).map(|wrapper| &wrapper.0)
}
pub fn pop_callback<CallbackFn>(&mut self, name: &str) -> Result<CallbackFn, MarkupError>
where
CallbackFn: callbacks::Callback + 'static,
{
let tm = self.bindings.get_mut(name).ok_or(MarkupError::CallbackNotFound)?;
tm.remove::<CallbackKeyWrapper<CallbackFn>>().ok_or(MarkupError::CallbackNotFound).map(|wrapper| wrapper.0)
}
pub fn store_id(&mut self, control_id: &str, generated_id: super::ids::Id) -> Result<(), MarkupError> {
if self.ids.get(control_id).is_none() {
self.ids.insert(control_id.into(), generated_id);
Ok(())
} else {
Err(MarkupError::IdAlreadyExists)
}
}
pub fn remove_id(&mut self, control_id: &str) -> Result<(), MarkupError> {
if self.ids.remove(control_id).is_none() {
Err(MarkupError::IdNotFound)
} else {
Ok(())
}
}
pub fn id(&self, control_id: &str) -> Result<&super::ids::Id, MarkupError> {
self.ids.get(control_id).ok_or(MarkupError::IdNotFound)
}
}
#[derive(Debug, Clone)]
pub enum MarkupError {
MemberNotFound,
MemberAlreadyRegistered,
CallbackNotFound,
CallbackAlreadyBinded,
IdNotFound,
IdAlreadyExists,
}
#[derive(Debug, Clone)]
pub struct Markup {
pub id: Option<String>,
pub member_type: MemberType,
pub attributes: HashMap<String, MarkupNode>,
}
#[derive(Debug, Clone)]
pub enum MarkupNode {
Attribute(String),
Child(Markup),
Children(Vec<Markup>),
}
impl MarkupNode {
pub fn as_attribute(&self) -> &str {
match *self {
MarkupNode::Attribute(ref attr) => attr.as_str(),
_ => panic!("MarkupNode is not an Attribute: {:?}", self),
}
}
pub fn as_child(&self) -> &Markup {
match *self {
MarkupNode::Child(ref markup) => markup,
_ => panic!("MarkupNode is not a Child Markup: {:?}", self),
}
}
pub fn as_children(&self) -> &[Markup] {
match *self {
MarkupNode::Children(ref children) => children.as_slice(),
_ => panic!("MarkupNode is not the Children Markups: {:?}", self),
}
}
}
impl<'de> Deserialize<'de> for Markup {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_struct("Markup", FIELDS, MarkupVisitor)
}
}
struct MarkupVisitor;
impl<'de> Visitor<'de> for MarkupVisitor {
type Value = Markup;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("struct Markup")
}
fn visit_map<V>(self, mut map: V) -> Result<Markup, V::Error>
where
V: MapAccess<'de>,
{
let mut id = None;
let mut member_type = None;
let mut child_found = false;
let mut attributes = HashMap::new();
while let Some(key) = map.next_key()? {
println!("{} found", key);
match key {
TYPE => {
if member_type.is_some() {
return Err(de::Error::duplicate_field(TYPE));
}
member_type = Some(map.next_value()?);
}
ID => {
if id.is_some() {
return Err(de::Error::duplicate_field(ID));
}
id = Some(map.next_value()?);
}
CHILD => {
if child_found {
return Err(de::Error::duplicate_field("child / children"));
} else {
attributes.insert(key.into(), MarkupNode::Child(map.next_value::<Markup>()?));
child_found = true;
}
}
CHILDREN => {
if child_found {
return Err(de::Error::duplicate_field("child / children"));
} else {
attributes.insert(key.into(), MarkupNode::Children(map.next_value::<Vec<Markup>>()?));
child_found = true;
}
}
_ => {
attributes.insert(key.into(), MarkupNode::Attribute(map.next_value::<String>()?));
}
}
}
Ok(Markup {
id: id,
member_type: member_type.ok_or_else(|| de::Error::missing_field(TYPE))?,
attributes: attributes,
})
}
}
pub fn parse_markup(json: &str, registry: &mut MarkupRegistry) -> Box<dyn crate::controls::Control> {
let markup: Markup = serde_json::from_str(json).unwrap();
let mut control = registry.member(&markup.member_type).unwrap()();
control.fill_from_markup(&markup, registry);
control
}
#[macro_export]
macro_rules! bind_markup_callback {
($reg: ident, $cb: ident) => {
registry.bind_callback(stringify!($cb), $cb as CallbackPtr).unwrap();
};
}
#[macro_export]
macro_rules! fill_from_markup_base {
($this: expr, $mem: expr, $mrk: ident, $reg: ident, $typ:ty, [$($arg:ident),+]) => {
if !&[$($arg),+].contains(&$mrk.member_type.as_str()) {
match $mrk.id {
Some(ref id) => panic!("Markup does not belong to {}: {} ({})", stringify!($typ), $mrk.member_type, id),
None => panic!("Markup does not belong to {}: {}", stringify!($typ), $mrk.member_type),
}
}
if let Some(ref id) = $mrk.id {
$reg.store_id(&id, $mem.id()).unwrap();
}
}
}
#[macro_export]
macro_rules! fill_from_markup_label {
($this: expr, $mem: expr, $mrk: ident) => {
use plygui_api::development::HasLabelInner;
$this.set_label($mem, $mrk.attributes.get("label").unwrap().as_attribute().into());
};
}
#[macro_export]
macro_rules! fill_from_markup_callbacks {
($this: expr, $mrk: ident, $reg: ident, [$($cbname:ident => $cbtyp:ty),+]) => {
$(if let Some(callback) = $mrk.attributes.get(stringify!($cbname)) {
let callback: $cbtyp = $reg.pop_callback(callback.as_attribute()).unwrap();
$this.$cbname(Some(callback));
})+
}
}
#[macro_export]
macro_rules! fill_from_markup_children {
($this: expr, $mem: expr, $mrk: ident, $reg: ident) => {
for child_markup in $mrk.attributes.get(::plygui_api::markup::CHILDREN).unwrap_or(&::plygui_api::markup::MarkupNode::Children(vec![])).as_children() {
use plygui_api::development::MultiContainerInner;
let mut child = $reg.member(&child_markup.member_type).unwrap()();
child.fill_from_markup(child_markup, $reg);
$this.push_child($mem, child);
}
};
}
#[macro_export]
macro_rules! fill_from_markup_child {
($this: expr, $mem: expr, $mrk: ident, $reg: ident) => {
if let Some(child_markup) = $mrk.attributes.get(::plygui_api::markup::CHILD).map(|m| m.as_child()) {
use plygui_api::development::SingleContainerInner;
let mut child = $reg.member(&child_markup.member_type).unwrap()();
child.fill_from_markup(child_markup, $reg);
$this.set_child($mem, Some(child));
}
};
}
|
mod common;
use cached::cached;
use proptest::prelude::*;
use valis_automata::nfa::{
standard_eps::{NFABuilder, StandardEpsilonNFA},
NFA,
};
cached! {
ALTERNATING;
fn alternating_language() -> StandardEpsilonNFA<bool, u8> = {
let mut builder = NFABuilder::new((0..=4).into());
builder
.add_accepts([0, 1, 2, 3, 4].iter().cloned())
.set_start(0)
.add_eps_transitions(0, [1, 3].iter().cloned())
.add_transition(1, true, 2)
.add_transition(2, false, 1)
.add_transition(3, false, 4)
.add_transition(4, true, 3);
let nfa = builder.finish().expect("Built NFA incorrectly");
common::render_nfa_to_file("alternating.dot", &nfa);
nfa
}
}
#[test]
fn accept_alternating_non_random() {
let nfa_1 = alternating_language();
assert!(nfa_1.accept(vec![false, true]));
assert!(nfa_1.accept(vec![true, false, true, false, true, false, true, false]));
assert!(!nfa_1.accept(vec![true, false, true, false, false, true, false, true]));
}
proptest! {
#[test]
fn accept_alternating_random(s in "1|0|(01)*|(10)*") {
let nfa_1 = alternating_language();
let string = common::convert_string(s, common::binary_converter());
prop_assert!(nfa_1.accept(string));
}
#[test]
fn reject_non_alternating_random(s in "(([01]*00[01]*)|([01]*11[01]*))") {
let nfa_1 = alternating_language();
let string = common::convert_string(s, common::binary_converter());
prop_assert!(!nfa_1.accept(string));
}
}
|
extern crate statrs;
use statrs::function::erf::erf;
use std::f64::consts::PI;
#[derive(Copy, Clone)]
pub enum OptionType {
Call,
Put,
}
pub struct NormalDistribution {
mean: f64,
std_dev: f64,
}
impl NormalDistribution {
fn pdf(&self, value: f64) -> f64 {
(-(value - self.mean).powi(2) / (2.0 * self.std_dev.powi(2))).exp()
/ (self.std_dev * (2.0 * PI).sqrt())
}
fn cdf(&self, value: f64) -> f64 {
0.5 * (1.0 + erf((value - self.mean) / (self.std_dev * 2.0f64.sqrt())))
}
}
pub fn make_std_norm_dist() -> NormalDistribution {
NormalDistribution {
mean: 0.0,
std_dev: 1.0,
}
}
pub struct BlackSholeModelParams {
pub k: f64, // Exercie price
pub s: f64, // Underlying price
pub t: f64, // Years until expiration
pub r: f64, // Applicable interest rate
pub v: f64, // Future realized volatilty of the underlying
}
impl BlackSholeModelParams {
fn d1(&self) -> f64 {
((self.s / self.k).ln() + (self.r + 0.5 * self.v.powi(2)) * self.t)
/ (self.v * self.t.sqrt())
}
fn d2(&self) -> f64 {
((self.s / self.k).ln() + (self.r - 0.5 * self.v.powi(2)) * self.t)
/ (self.v * self.t.sqrt())
}
}
#[derive(Debug)]
#[derive(PartialEq)]
pub struct BlackSholeModelResults {
pub price: f64,
pub delta: f64,
pub gamma: f64,
pub theta: f64,
pub vega: f64,
pub rho: f64,
}
pub struct BlackSholeModel {
dist: NormalDistribution,
}
pub fn make_black_shole_model(dist: NormalDistribution) -> BlackSholeModel {
BlackSholeModel { dist }
}
impl BlackSholeModel {
pub fn calc(
&self,
params: &BlackSholeModelParams,
option_type: OptionType,
) -> BlackSholeModelResults {
BlackSholeModelResults {
price: self.price(params, option_type),
delta: self.delta(params, option_type),
gamma: self.gamma(params, option_type),
theta: self.theta(params, option_type),
vega: self.vega(params, option_type),
rho: self.rho(params, option_type),
}
}
pub fn price(&self, params: &BlackSholeModelParams, option_type: OptionType) -> f64 {
params.s * self.delta(params, option_type) - self.rho(params, option_type) / params.t
}
pub fn delta(&self, params: &BlackSholeModelParams, option_type: OptionType) -> f64 {
if let OptionType::Call = option_type {
self.dist.cdf(params.d1())
} else {
-self.dist.cdf(-params.d1())
}
}
pub fn gamma(&self, params: &BlackSholeModelParams, _option_type: OptionType) -> f64 {
self.dist.pdf(params.d1()) / (params.s * params.v * params.t.sqrt())
}
pub fn theta(&self, params: &BlackSholeModelParams, option_type: OptionType) -> f64 {
-params.v * 0.5 * self.vega(params, option_type) / params.t
- params.r * self.rho(params, option_type) / params.t
}
pub fn vega(&self, params: &BlackSholeModelParams, _option_type: OptionType) -> f64 {
params.s * self.dist.pdf(params.d1()) * params.t.sqrt()
}
pub fn rho(&self, params: &BlackSholeModelParams, option_type: OptionType) -> f64 {
if let OptionType::Call = option_type {
params.k * params.t * (-params.r * params.t).exp() * self.dist.cdf(params.d2())
} else {
-params.k * params.t * (-params.r * params.t).exp() * self.dist.cdf(-params.d2())
}
}
}
#[cfg(test)]
mod norm_dist_test {
use super::*;
#[test]
fn test_pdf() {
let dist = make_std_norm_dist();
assert_eq!(dist.pdf(0.0), 0.3989422804014327);
assert_eq!(dist.pdf(0.1), 0.3969525474770118);
assert_eq!(dist.pdf(0.5), 0.3520653267642995);
assert_eq!(dist.pdf(1.0), 0.24197072451914337);
assert_eq!(dist.pdf(-1.0), 0.24197072451914337);
assert_eq!(dist.pdf(3.0), 0.0044318484119380075);
assert_eq!(dist.pdf(-5.0), 1.4867195147342979e-06);
}
#[test]
fn test_cdf() {
let dist = make_std_norm_dist();
assert_eq!(dist.cdf(0.0), 0.5);
assert_eq!(dist.cdf(0.1), 0.539827837277029);
assert_eq!(dist.cdf(0.5), 0.6914624612740131);
assert_eq!(dist.cdf(1.0), 0.8413447460549428);
assert_eq!(dist.cdf(-1.0), 0.15865525394505725);
assert_eq!(dist.cdf(3.0), 0.9986501019684255);
assert_eq!(dist.cdf(-5.0), 2.8665157186802404e-07);
}
}
#[cfg(test)]
mod black_sholes_test {
use super::*;
fn get_params() -> BlackSholeModelParams{
BlackSholeModelParams {
k: 100.0,
t: 1.0,
r: 0.05,
s: 100.0,
v: 0.2,
}
}
#[test]
fn test_call_option() {
let model = make_black_shole_model(make_std_norm_dist());
assert_eq!(model.calc(&get_params(), OptionType::Call), BlackSholeModelResults{
price: 10.450583572185565,
delta: 0.6368306511756191,
gamma: 0.018762017345846895,
theta: -6.414027546438197,
vega: 37.52403469169379,
rho: 53.232481545376345,
});
}
#[test]
fn test_put_option() {
let model = make_black_shole_model(make_std_norm_dist());
assert_eq!(model.calc(&get_params(), OptionType::Put), BlackSholeModelResults{
price: 5.573526022256971,
delta: -0.3631693488243809,
gamma: 0.018762017345846895,
theta: -1.6578804239346265,
vega: 37.52403469169379,
rho: -41.89046090469506,
});
}
}
|
use std::io;
use std::io::prelude::*;
fn find_primes(primes: &mut Vec<i32>) {
primes.retain(|&x| x > 1);
let mut i = 2;
while i < *primes.last().unwrap() {
primes.retain(|&x| x == i || x % i != 0);
i = *primes.iter().find(|&x| *x > i).unwrap();
}
}
fn main() {
let mut input = String::new();
print!("Find primes upto: ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut input).ok().expect("failed to read line");
let n: i32 = input.trim().parse().expect("Please type a number!");
let mut primes: Vec<i32> = (1..=n).collect();
find_primes(&mut primes);
println!("The primes upto {} are {:?}, count: {}", n, primes, primes.len());
}
|
use std::{io, net::ToSocketAddrs};
use tokio::net::TcpStream;
use url::Url;
use crate::proxytunnel;
pub async fn connect(host: &str, port: u16, proxy: Option<&Url>) -> io::Result<TcpStream> {
let socket = if let Some(proxy_url) = proxy {
info!("Using proxy \"{}\"", proxy_url);
let socket_addr = proxy_url.socket_addrs(|| None).and_then(|addrs| {
addrs.into_iter().next().ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"Can't resolve proxy server address",
)
})
})?;
let socket = TcpStream::connect(&socket_addr).await?;
proxytunnel::proxy_connect(socket, host, &port.to_string()).await?
} else {
let socket_addr = (host, port).to_socket_addrs()?.next().ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"Can't resolve access point address",
)
})?;
TcpStream::connect(&socket_addr).await?
};
Ok(socket)
}
|
mod values;
mod scalar;
mod index;
pub use self::values::{Array, Object, Value};
pub use self::index::Index;
pub use self::scalar::{Date, Scalar};
|
// error-pattern:put in non-iterator
fn f() -> int { put 10; }
fn main() { }
|
use clap::ArgMatches;
use config::Config;
use std::error::Error;
pub fn setup(app_m: &ArgMatches) -> Result<config::Config, Box<dyn Error>> {
let mut config = Config::default();
config
.set_default("debug", false)?
.set_default("log_level", "info")?
.set_default("database_url", "feedspool.sqlite")?
// TODO: split this up so subcommands can contribute defaults?
.set_default("http_server_address", "0.0.0.0:3010")?
.set_default("http_server_static_path", "./www/")?
.set_default("fetch_feeds_filename", "feed-urls.txt")?
.set_default("fetch_retain_src", false)?
.set_default("fetch_skip_entry_update", true)?
.set_default("fetch_min_fetch_period", 60 * 30)?
.set_default("fetch_request_timeout", 5)?
.set_default("fetch_concurrency_limit", 16)?
.merge(config::File::with_name("config").required(false))?
.merge(config::Environment::with_prefix("APP"))?;
if app_m.is_present("debug") {
config.set_default("debug", true)?;
config.set("log_level", "debug")?;
}
Ok(config)
}
|
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() <= 1 {
eprintln!("Error: No brainfuck file specified.");
std::process::exit(1);
}
match brainfuck_interpreter::run(&args[1][..]) {
Ok(()) => (),
Err(e) => eprintln!("Error: {}", e),
}
}
|
//! This crate allows you to display progress bar in a terminal.
//!
//! # Example
//!
//! ```
//! use progress_bar::progress_bar::ProgressBar;
//! use progress_bar::color::{Color, Style};
//! use std::{thread, time};
//!
//! // if you have 81 pages to load
//! let mut progress_bar = ProgressBar::new(81);
//! progress_bar.set_action("Loading", Color::Blue, Style::Bold);
//!
//! for i in 0..81 {
//! // load page
//! thread::sleep(time::Duration::from_millis(500));
//!
//! // log the result
//! if i == 14 {
//! progress_bar.print_info("Failed", "https://zefzef.zef", Color::Red, Style::Normal);
//! } else if i == 41 {
//! rogress_bar.print_info("Success", "https://example.com", Color::Green, Style::Bold);
//! }
//!
//! // update the progression by 1
//! progress_bar.inc();
//! }
//! ```
//!
//! 
pub mod progress_bar;
pub mod color;
|
pub mod buffer;
pub mod camera;
pub mod camera_controller;
pub mod instance;
pub mod state;
pub mod texture;
pub mod tracing;
pub mod uniforms;
|
use crate::ast::*;
use proc_macro2::TokenStream;
use quote::quote;
pub fn gen(input: Input<'_>) -> TokenStream {
match input {
Input::Struct(input) => gen_input(input),
}
}
fn gen_input(input: Struct<'_>) -> TokenStream {
let struct_name = &input.ident;
let status = input.status();
let intercom = input.intercom();
let stop = input.stop();
let start = input.start();
let new = input.new();
quote! {
#[async_trait::async_trait]
#[allow(clippy::unit_arg)]
impl ::organix::Organix for #struct_name {
#new
#start
#status
#intercom
#stop
}
}
}
impl<'a> Struct<'a> {
fn fields(&self) -> impl Iterator<Item = &Field<'a>> {
self.fields.iter().filter(|field| !field.skip())
}
fn possible_values(&self) -> Vec<TokenStream> {
self.fields()
.map(|field| {
let field_name = field.original.ident.as_ref().unwrap();
let entry = field_name.to_string();
quote! {
#entry
}
})
.collect()
}
#[allow(clippy::new_ret_no_self)]
fn new(&self) -> TokenStream {
let default_is_shared = self.default_is_shared();
let cases = self.fields().map(|field| {
let field_name = field.original.ident.as_ref().unwrap();
let thread_name = field_name.to_string();
if field.shared(default_is_shared) {
quote! {
#field_name: {
let rt = runtimes.shared_mut();
::organix::service::ServiceManager::with_runtime(rt)
}
}
} else {
let io_driver = field.io_driver();
let time_driver = field.time_driver();
quote! {
#field_name: {
let mut cfg = ::organix::runtime::RuntimeConfig::new(#thread_name);
cfg.io_driver = #io_driver;
cfg.time_driver = #time_driver;
let mut rt = ::organix::runtime::Runtime::build(cfg).unwrap();
let sm = ::organix::service::ServiceManager::with_runtime(&mut rt);
runtimes.add(rt);
sm
}
}
}
});
quote! {
fn new(runtimes: &mut ::organix::runtime::Runtimes) -> Self {
Self {
#( #cases ),*
}
}
}
}
fn start(&self) -> TokenStream {
let possible_values = self.possible_values();
let cases = self.fields().map(|field| {
let field_name = field.original.ident.as_ref().unwrap();
let entry = field_name.to_string();
quote! {
#entry => {
match self.#field_name.runtime(watchdog_query) {
Ok(rt) => Ok(rt.start()),
Err(source) => Err(::organix::WatchdogError::CannotStartService {
service_identifier,
source,
})
}
}
}
});
quote! {
fn start(
&mut self,
service_identifier: ::organix::ServiceIdentifier,
watchdog_query: ::organix::WatchdogQuery,
) -> Result<(), ::organix::WatchdogError> {
match service_identifier {
#( #cases ),*
_ => Err(::organix::WatchdogError::UnknownService {
service_identifier,
possible_values: &[#( #possible_values ),*],
})
}
}
}
}
fn stop(&self) -> TokenStream {
let possible_values = self.possible_values();
let cases = self.fields().map(|field| {
let field_name = field.original.ident.as_ref().unwrap();
let entry = field_name.to_string();
quote! {
#entry => { Ok(self.#field_name.shutdown()) }
}
});
quote! {
fn stop(
&mut self,
service_identifier: ::organix::ServiceIdentifier,
) -> Result<(), ::organix::WatchdogError> {
match service_identifier {
#( #cases ),*
_ => Err(::organix::WatchdogError::UnknownService {
service_identifier,
possible_values: &[#( #possible_values ),*],
})
}
}
}
}
fn intercom(&self) -> TokenStream {
let possible_values = self.possible_values();
let cases = self.fields().map(|field| {
let field_name = field.original.ident.as_ref().unwrap();
let entry = field_name.to_string();
quote! {
#entry => { Ok(Box::new(self.#field_name.intercom())) }
}
});
quote! {
fn intercoms(
&mut self,
service_identifier: ::organix::ServiceIdentifier,
) -> Result<Box<dyn ::std::any::Any + Send>, ::organix::WatchdogError> {
match service_identifier {
#( #cases ),*
_ => Err(::organix::WatchdogError::UnknownService {
service_identifier,
possible_values: &[#( #possible_values ),*],
})
}
}
}
}
fn status(&self) -> TokenStream {
let possible_values = self.possible_values();
let cases = self.fields().map(|field| {
let field_name = field.original.ident.as_ref().unwrap();
let entry = field_name.to_string();
quote! {
#entry => { Ok(self.#field_name.status().await) }
}
});
quote! {
async fn status(
&mut self,
service_identifier: ::organix::ServiceIdentifier,
) -> Result<::organix::service::StatusReport, ::organix::WatchdogError> {
match service_identifier {
#( #cases ),*
_ => Err(::organix::WatchdogError::UnknownService {
service_identifier,
possible_values: &[#( #possible_values ),*],
})
}
}
}
}
}
|
use crate::peer_info::{protocol, PeerInfo};
use futures::future::BoxFuture;
use futures::prelude::*;
use libp2p::core::upgrade::ReadyUpgrade;
use libp2p::swarm::handler::{
ConnectionEvent, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound,
ListenUpgradeError, StreamUpgradeError as ConnectionHandlerUpgrErr,
};
use libp2p::swarm::{
ConnectionHandler, ConnectionHandlerEvent, KeepAlive, Stream as NegotiatedSubstream,
SubstreamProtocol,
};
use libp2p::StreamProtocol;
use std::error::Error;
use std::io;
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
use std::time::Duration;
use tracing::debug;
/// The configuration for peer-info protocol.
#[derive(Debug, Clone)]
pub struct Config {
/// Protocol timeout.
timeout: Duration,
/// Protocol name.
protocol_name: &'static str,
}
impl Config {
/// Creates a new [`Config`] with the following default settings:
///
/// * [`Config::with_timeout`] 20s
pub fn new(protocol_name: &'static str) -> Self {
Self {
timeout: Duration::from_secs(20),
protocol_name,
}
}
/// Sets the protocol timeout.
pub fn with_timeout(mut self, d: Duration) -> Self {
self.timeout = d;
self
}
}
/// The successful result of processing an inbound or outbound peer info requests.
#[derive(Debug)]
pub enum PeerInfoSuccess {
/// Local peer received peer info from a remote peer.
Received(PeerInfo),
/// Local peer sent its peer info to a remote peer.
Sent,
}
/// A peer info protocol failure.
#[derive(Debug, thiserror::Error)]
pub enum PeerInfoError {
/// The peer does not support the peer info protocol.
#[error("Peer info protocol is not supported.")]
#[allow(dead_code)] // We preserve errors on dial upgrades for future use.
Unsupported,
/// The peer info request failed.
#[error("Peer info error: {error}")]
Other {
#[source]
error: Box<dyn Error + Send + 'static>,
},
}
/// Struct for outbound peer-info requests.
#[derive(Debug, Clone)]
pub struct HandlerInEvent {
pub peer_info: Arc<PeerInfo>,
}
/// Protocol handler that handles peer-info requests.
///
/// Any protocol failure produces an error that closes the connection.
pub struct Handler {
/// Configuration options.
config: Config,
/// The outbound request state.
outbound: Option<OutboundState>,
/// The inbound request future.
inbound: Option<InPeerInfoFuture>,
/// Last peer-info error.
error: Option<PeerInfoError>,
/// Future waker.
waker: Option<Waker>,
}
impl Handler {
/// Builds a new [`Handler`] with the given configuration.
pub fn new(config: Config) -> Self {
Handler {
config,
outbound: None,
inbound: None,
error: None,
waker: None,
}
}
fn wake(&self) {
if let Some(waker) = &self.waker {
waker.wake_by_ref()
}
}
}
impl ConnectionHandler for Handler {
type FromBehaviour = HandlerInEvent;
type ToBehaviour = Result<PeerInfoSuccess, PeerInfoError>;
type Error = PeerInfoError;
type InboundProtocol = ReadyUpgrade<StreamProtocol>;
type OutboundProtocol = ReadyUpgrade<StreamProtocol>;
type OutboundOpenInfo = Arc<PeerInfo>;
type InboundOpenInfo = ();
fn listen_protocol(&self) -> SubstreamProtocol<ReadyUpgrade<StreamProtocol>, ()> {
SubstreamProtocol::new(
ReadyUpgrade::new(StreamProtocol::new(self.config.protocol_name)),
(),
)
}
fn on_behaviour_event(&mut self, event: Self::FromBehaviour) {
if let Some(OutboundState::Idle(stream)) = self.outbound.take() {
self.outbound = Some(OutboundState::SendingData(
protocol::send(stream, event.peer_info).boxed(),
));
} else {
self.outbound = Some(OutboundState::RequestNewStream(event.peer_info));
}
self.wake();
}
fn connection_keep_alive(&self) -> KeepAlive {
KeepAlive::No
}
fn poll(
&mut self,
cx: &mut Context<'_>,
) -> Poll<
ConnectionHandlerEvent<
ReadyUpgrade<StreamProtocol>,
Self::OutboundOpenInfo,
Result<PeerInfoSuccess, PeerInfoError>,
Self::Error,
>,
> {
if let Some(error) = self.error.take() {
return Poll::Ready(ConnectionHandlerEvent::Close(error));
}
// Respond to inbound requests.
if let Some(fut) = self.inbound.as_mut() {
match fut.poll_unpin(cx) {
Poll::Pending => {}
Poll::Ready(Err(err)) => {
debug!(?err, "Peer info handler: inbound peer info error.");
return Poll::Ready(ConnectionHandlerEvent::Close(PeerInfoError::Other {
error: Box::new(err),
}));
}
Poll::Ready(Ok((stream, peer_info))) => {
debug!(?peer_info, "Inbound peer info");
self.inbound = Some(protocol::recv(stream).boxed());
return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(Ok(
PeerInfoSuccess::Received(peer_info),
)));
}
}
}
// Outbound requests.
match self.outbound.take() {
Some(OutboundState::SendingData(mut peer_info_fut)) => {
match peer_info_fut.poll_unpin(cx) {
Poll::Pending => {
self.outbound = Some(OutboundState::SendingData(peer_info_fut));
}
Poll::Ready(Ok(stream)) => {
self.outbound = Some(OutboundState::Idle(stream));
return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(Ok(
PeerInfoSuccess::Sent,
)));
}
Poll::Ready(Err(error)) => {
debug!(?error, "Outbound peer info error.",);
self.error = Some(PeerInfoError::Other {
error: Box::new(error),
});
}
}
}
Some(OutboundState::Idle(stream)) => {
// Nothing to do but we have a negotiated stream.
self.outbound = Some(OutboundState::Idle(stream));
}
Some(OutboundState::NegotiatingStream) => {
self.outbound = Some(OutboundState::NegotiatingStream);
}
Some(OutboundState::RequestNewStream(peer_info)) => {
self.outbound = Some(OutboundState::NegotiatingStream);
let protocol = SubstreamProtocol::new(
ReadyUpgrade::new(StreamProtocol::new(self.config.protocol_name)),
peer_info,
)
.with_timeout(self.config.timeout);
return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol });
}
None => {
// Not initialized yet.
}
}
self.waker = Some(cx.waker().clone());
Poll::Pending
}
fn on_connection_event(
&mut self,
event: ConnectionEvent<
Self::InboundProtocol,
Self::OutboundProtocol,
Self::InboundOpenInfo,
Self::OutboundOpenInfo,
>,
) {
match event {
ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound {
protocol: stream,
..
}) => {
self.inbound = Some(protocol::recv(stream).boxed());
}
ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound {
protocol: stream,
info,
}) => {
self.outbound = Some(OutboundState::SendingData(
protocol::send(stream, info).boxed(),
));
}
ConnectionEvent::DialUpgradeError(DialUpgradeError { error, .. }) => {
match error {
ConnectionHandlerUpgrErr::NegotiationFailed
| ConnectionHandlerUpgrErr::Apply(..) => {
debug!("Peer-info protocol dial upgrade failed.");
}
e => {
self.error = Some(PeerInfoError::Other { error: Box::new(e) });
}
};
}
ConnectionEvent::ListenUpgradeError(ListenUpgradeError { error, .. }) => {
self.error = Some(PeerInfoError::Other {
error: Box::new(error),
});
}
ConnectionEvent::AddressChange(_) => {}
ConnectionEvent::LocalProtocolsChange(_) => {}
ConnectionEvent::RemoteProtocolsChange(_) => {}
}
self.wake();
}
}
type InPeerInfoFuture = BoxFuture<'static, Result<(NegotiatedSubstream, PeerInfo), io::Error>>;
type OutPeerInfoFuture = BoxFuture<'static, Result<NegotiatedSubstream, io::Error>>;
/// The current state w.r.t. outbound peer info requests.
enum OutboundState {
RequestNewStream(Arc<PeerInfo>),
/// A new substream is being negotiated for the protocol.
NegotiatingStream,
/// A peer info request is being sent and the response awaited.
SendingData(OutPeerInfoFuture),
/// The substream is idle, waiting to send the next peer info request.
Idle(NegotiatedSubstream),
}
|
use materials::Material;
use patterns::pattern_at_shape;
use shapes::Shape;
use tuples::Tuple;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct PointLight {
pub position: Tuple,
pub intensity: Tuple,
}
impl PointLight {
pub fn new(position: Tuple, intensity: Tuple) -> Self {
PointLight {
position,
intensity,
}
}
}
#[test]
fn test_a_point_light_has_a_position_and_intensity() {
let intensity = Tuple::color(1.0, 1.0, 1.0);
let position = Tuple::point(0.0, 0.0, 0.0);
let light = PointLight::new(position, intensity);
assert_eq!(light.intensity, intensity);
assert_eq!(light.position, position);
}
pub fn lighting(
material: Material,
object: Shape,
light: PointLight,
point: Tuple,
eyev: Tuple,
normalv: Tuple,
in_shadow: bool,
) -> Tuple {
let black = Tuple::color(0.0, 0.0, 0.0);
let diffuse;
let specular;
let color = material
.pattern
.map(|pattern| pattern_at_shape(pattern, object, point))
.unwrap_or(material.color);
let effective_color = color * light.intensity;
let lightv = (light.position - point).normalize();
let ambient = effective_color * material.ambient;
let light_dot_normal = lightv.dot(normalv);
if light_dot_normal < 0.0 {
diffuse = black;
specular = black;
} else {
diffuse = effective_color * material.diffuse * light_dot_normal;
let reflectv = -lightv.reflect(normalv);
let reflect_dot_eye = reflectv.dot(eyev).powf(material.shininess);
specular = if reflect_dot_eye <= 0.0 {
black
} else {
light.intensity * material.specular * reflect_dot_eye
};
}
if in_shadow {
ambient
} else {
ambient + diffuse + specular
}
}
#[test]
fn test_lighting_with_the_eye_between_the_light_and_the_surface() {
let object = Shape::default();
let m = Material::default();
let position = Tuple::point(0.0, 0.0, 0.0);
let eyev = Tuple::vector(0.0, 0.0, -1.0);
let normalv = Tuple::vector(0.0, 0.0, -1.0);
let light = PointLight::new(
Tuple::point(0.0, 0.0, -10.0),
Tuple::color(1.0, 1.0, 1.0),
);
let in_shadow = false;
let result = lighting(m, object, light, position, eyev, normalv, in_shadow);
assert_eq!(result, Tuple::color(1.9, 1.9, 1.9));
}
#[test]
fn test_lighting_with_the_eye_between_light_and_surface_eye_offset_45_degrees()
{
let object = Shape::default();
let m = Material::default();
let position = Tuple::point(0.0, 0.0, 0.0);
let eyev = Tuple::vector(0.0, 2f32.sqrt() / 2.0, -2f32.sqrt() / 2.0);
let normalv = Tuple::vector(0.0, 0.0, -1.0);
let light = PointLight::new(
Tuple::point(0.0, 0.0, -10.0),
Tuple::color(1.0, 1.0, 1.0),
);
let in_shadow = false;
let result = lighting(m, object, light, position, eyev, normalv, in_shadow);
assert_eq!(result, Tuple::color(1.0, 1.0, 1.0));
}
#[test]
fn test_lighting_with_eye_opposite_surface_light_offset_45_degrees() {
let object = Shape::default();
let m = Material::default();
let position = Tuple::point(0.0, 0.0, 0.0);
let eyev = Tuple::vector(0.0, 0.0, -1.0);
let normalv = Tuple::vector(0.0, 0.0, -1.0);
let light = PointLight::new(
Tuple::point(0.0, 10.0, -10.0),
Tuple::color(1.0, 1.0, 1.0),
);
let in_shadow = false;
let result = lighting(m, object, light, position, eyev, normalv, in_shadow);
assert_eq!(result, Tuple::color(0.7364, 0.7364, 0.7364));
}
#[test]
fn test_lighting_with_eye_in_the_path_of_the_reflection_vector() {
let object = Shape::default();
let m = Material::default();
let position = Tuple::point(0.0, 0.0, 0.0);
let eyev = Tuple::vector(0.0, -2f32.sqrt() / 2.0, -2f32.sqrt() / 2.0);
let normalv = Tuple::vector(0.0, 0.0, -1.0);
let light = PointLight::new(
Tuple::point(0.0, 10.0, -10.0),
Tuple::color(1.0, 1.0, 1.0),
);
let in_shadow = false;
let result = lighting(m, object, light, position, eyev, normalv, in_shadow);
assert_eq!(result, Tuple::color(1.63638, 1.63638, 1.63638));
}
#[test]
fn test_lighting_with_the_light_behind_the_surface() {
let object = Shape::default();
let m = Material::default();
let position = Tuple::point(0.0, 0.0, 0.0);
let eyev = Tuple::vector(0.0, 0.0, -1.0);
let normalv = Tuple::vector(0.0, 0.0, -1.0);
let light = PointLight::new(
Tuple::point(0.0, 0.0, 10.0),
Tuple::color(1.0, 1.0, 1.0),
);
let in_shadow = false;
let result = lighting(m, object, light, position, eyev, normalv, in_shadow);
assert_eq!(result, Tuple::color(0.1, 0.1, 0.1));
}
#[test]
fn test_lighting_with_the_surface_in_shadow() {
let object = Shape::default();
let m = Material::default();
let position = Tuple::point(0.0, 0.0, 0.0);
let eyev = Tuple::vector(0.0, 0.0, -1.0);
let normalv = Tuple::vector(0.0, 0.0, -1.0);
let light = PointLight::new(
Tuple::point(0.0, 0.0, -10.0),
Tuple::color(1.0, 1.0, 1.0),
);
let in_shadow = true;
let result = lighting(m, object, light, position, eyev, normalv, in_shadow);
assert_eq!(result, Tuple::color(0.1, 0.1, 0.1));
}
#[test]
fn test_lighting_with_a_pattern_applied() {
// FIXME: we can remove this when parent module imports this...
use patterns::Pattern;
let object = Shape::default();
let mut m = Material::default();
m.pattern = Some(Pattern::stripe(
Tuple::color(1.0, 1.0, 1.0),
Tuple::color(0.0, 0.0, 0.0),
));
m.ambient = 1.0;
m.diffuse = 0.0;
m.specular = 0.0;
let eyev = Tuple::vector(0.0, 0.0, -1.0);
let normalv = Tuple::vector(0.0, 0.0, -1.0);
let light = PointLight::new(
Tuple::point(0.0, 0.0, -10.0),
Tuple::color(1.0, 1.0, 1.0),
);
let c1 = lighting(
m,
object,
light,
Tuple::point(0.9, 0.0, 0.0),
eyev,
normalv,
false,
);
let c2 = lighting(
m,
object,
light,
Tuple::point(1.0, 0.0, 0.0),
eyev,
normalv,
false,
);
assert_eq!(c1, Tuple::color(1.0, 1.0, 1.0));
assert_eq!(c2, Tuple::color(0.0, 0.0, 0.0));
}
|
use paris::{info, success, warn};
use std::io;
use rand::prelude::*;
fn main() {
let mut correct_number = reset();
loop {
let mut number = String::new();
info!("Guess a number:");
io::stdin().read_line(&mut number).unwrap();
println!("{}", number);
let parsed_number = number.trim().parse::<i32>().unwrap_or(0);
if let Some(response) = number_in_range(parsed_number, correct_number) {
warn!("{}", response);
continue;
}
if parsed_number == correct_number {
success!("You guessed right! Would you like to try again? [Y/n]");
let mut answer = String::new();
io::stdin().read_line(&mut answer).unwrap();
match answer.to_lowercase().as_str().trim() {
"y" => correct_number = reset(),
_ => break
}
}
}
info!("The game is now over. Congratz, hope you had fun.");
}
fn reset() -> i32 {
let mut max_number = String::new();
info!("Select a max value");
io::stdin().read_line(&mut max_number).unwrap();
get_random_num(max_number.trim().parse::<i32>().unwrap_or(1000))
}
fn number_in_range(number: i32, correct_number: i32) -> Option<String> {
if number > correct_number {
return Some(format!("Number <blue>{}</> is too high", number));
}
if number < correct_number {
return Some(format!("Number <blue>{}</> is too low", number));
}
None
}
fn get_random_num(max_value: i32) -> i32 {
let mut rng = rand::thread_rng();
rng.gen_range(0, max_value)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_random_num() {
assert!(get_random_num(2) < 3);
}
}
|
#[doc = "Register `GICH_VTR` reader"]
pub type R = crate::R<GICH_VTR_SPEC>;
#[doc = "Field `LISTREGS` reader - LISTREGS"]
pub type LISTREGS_R = crate::FieldReader;
#[doc = "Field `PREBITS` reader - PREBITS"]
pub type PREBITS_R = crate::FieldReader;
#[doc = "Field `PRIBITS` reader - PRIBITS"]
pub type PRIBITS_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:4 - LISTREGS"]
#[inline(always)]
pub fn listregs(&self) -> LISTREGS_R {
LISTREGS_R::new((self.bits & 0x1f) as u8)
}
#[doc = "Bits 26:28 - PREBITS"]
#[inline(always)]
pub fn prebits(&self) -> PREBITS_R {
PREBITS_R::new(((self.bits >> 26) & 7) as u8)
}
#[doc = "Bits 29:31 - PRIBITS"]
#[inline(always)]
pub fn pribits(&self) -> PRIBITS_R {
PRIBITS_R::new(((self.bits >> 29) & 7) as u8)
}
}
#[doc = "GICH VGIC type register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gich_vtr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct GICH_VTR_SPEC;
impl crate::RegisterSpec for GICH_VTR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`gich_vtr::R`](R) reader structure"]
impl crate::Readable for GICH_VTR_SPEC {}
#[doc = "`reset()` method sets GICH_VTR to value 0x9000_0003"]
impl crate::Resettable for GICH_VTR_SPEC {
const RESET_VALUE: Self::Ux = 0x9000_0003;
}
|
use std::io;
use structopt::StructOpt;
extern crate guitar_pedal;
#[derive(Debug, StructOpt)]
struct Opt {
#[structopt(short, long, default_value = "80")]
bpm: usize,
}
fn main() {
let opt = Opt::from_args();
let (playback_manager, loop_manager, interface) = guitar_pedal::init(opt.bpm);
loop_manager.run();
interface.run();
guitar_pedal::activate_client(playback_manager);
println!("Press enter/return to quit...");
let mut user_input = String::new();
io::stdin().read_line(&mut user_input).ok();
}
|
pub mod actrl {
pub mod disfold {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0xE000E008u32 as *const u32) >> 2) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0xE000E008u32 as *const u32);
reg &= 0xFFFFFFFBu32;
reg |= (val & 0x1) << 2;
core::ptr::write_volatile(0xE000E008u32 as *mut u32, reg);
}
}
}
pub mod fpexcodis {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0xE000E008u32 as *const u32) >> 10) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0xE000E008u32 as *const u32);
reg &= 0xFFFFFBFFu32;
reg |= (val & 0x1) << 10;
core::ptr::write_volatile(0xE000E008u32 as *mut u32, reg);
}
}
}
pub mod disramode {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0xE000E008u32 as *const u32) >> 11) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0xE000E008u32 as *const u32);
reg &= 0xFFFFF7FFu32;
reg |= (val & 0x1) << 11;
core::ptr::write_volatile(0xE000E008u32 as *mut u32, reg);
}
}
}
pub mod disitmatbflush {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0xE000E008u32 as *const u32) >> 12) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0xE000E008u32 as *const u32);
reg &= 0xFFFFEFFFu32;
reg |= (val & 0x1) << 12;
core::ptr::write_volatile(0xE000E008u32 as *mut u32, reg);
}
}
}
}
|
//! Handles edge cases that have caused trouble at times.
use anyhow::Result;
use ndarray::{array, Array2};
use ndarray_glm::{Logistic, ModelBuilder};
use num_traits::float::FloatCore;
/// Ensure that a valid likelihood is returned when the initial guess is the
/// best one.
#[test]
fn start_zero() -> Result<()> {
// Exactly half of the data are true, meaning the initial guess of beta = 0 will be the best.
let data_y = array![true, false, false, true];
let data_x: Array2<f64> = array![[], [], [], []];
let model = ModelBuilder::<Logistic>::data(data_y.view(), data_x.view()).build()?;
let fit = model.fit()?;
assert_eq!(fit.model_like > -f64::infinity(), true);
Ok(())
}
|
// This file is part of dpdk. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT. No part of dpdk, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2017 The developers of dpdk. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT.
pub trait EventData
{
#[doc(hidden)]
#[inline(always)]
fn pointer(&self) -> *mut rdma_cm_event;
/// .len() may be greater than the amount of data sent by the remote side, but all excess bytes are g'teed to be zero
/// .len() will be between 1 and 255 inclusive, but "The length of the private data provided by the user is limited to 196 bytes for RDMA_PS_TCP, or 136 bytes for RDMA_PS_UDP." (rdma_accept man page)
/// Note that private data of length zero is not transmitted on rejection; it is impossible to distinguish no private data from null
#[inline(always)]
fn privateData<'a>(&'a self) -> Option<&'a [u8]>;
#[inline(always)]
fn remoteQueuePairNumber(&self) -> QueuePairNumber;
}
#[inline(always)]
fn privateDataConn<'a>(data: rdma_conn_param) -> Option<&'a [u8]>
{
let pointer = data.private_data;
if unlikely(pointer.is_null())
{
None
}
else
{
Some(unsafe { from_raw_parts(pointer as *const u8, data.private_data_len as usize) })
}
}
#[inline(always)]
fn remoteQueuePairNumberConn(data: rdma_conn_param) -> QueuePairNumber
{
data.qp_num
}
#[inline(always)]
fn privateDataUd<'a>(data: rdma_ud_param) -> Option<&'a [u8]>
{
let pointer = data.private_data;
if unlikely(pointer.is_null())
{
None
}
else
{
Some(unsafe { from_raw_parts(pointer as *const u8, data.private_data_len as usize) })
}
}
#[inline(always)]
fn remoteQueuePairNumberUd(data: rdma_ud_param) -> QueuePairNumber
{
data.qp_num
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.