text stringlengths 8 4.13M |
|---|
pub mod hex;
mod input_buffer;
mod output_buffer;
mod string_buffer;
pub use self::input_buffer::InputBuffer;
pub use self::output_buffer::OutputBuffer;
pub use self::string_buffer::StringBuffer;
|
pub mod tracker;
pub use tracker::ui as tracker;
//mod insights;
//pub use insights::ui as insights;
|
use std::cmp::{max, min};
use tuikit::prelude::*;
use std::time::Duration;
use std::env;
use tuikit::attr::{Attr, Color};
//use rand::Rng;
fn main() {
//let term: Term<()> = Term::with_height(TermHeight::Percent(30)).unwrap();
let args: Vec<String> = env::args().collect();
let count: i32 = args[1].parse().unwrap();
let term = Term::<()>::new().unwrap();
let mut row = 1;
let mut col = 0;
let _ = term.print(0, 0, "press arrow key to move the text, (q) to quit");
let _ = term.present();
let mut jug: u8 = 0;
jug = 0;
//while let Ok(ev) = term.poll_event() {
let _ = term.clear();
//let _ = term.print(0, 0, "press arrow key to move the text, (q) to quit");
let (width, height) = term.term_size().unwrap();
for n in 0..count {
let attr = Attr { bg: Color::AnsiValue(jug), effect: Effect::BOLD, ..Attr::default() };
for xx in 0..height {
for yy in 0..width {
let attr = Attr { bg: Color::AnsiValue(jug), effect: Effect::BOLD, ..Attr::default() };
let _ = term.print_with_attr(xx,yy," ", attr);
jug +=1;
if jug >= 255{
jug = 0;
}
}
}
//let _ = term.print_with_attr(row, col, &format!("col: {} row:{}",col, row), Color::RED);
//let _ = term.print_with_attr(row+1, col+1, &format!("{:?}",ev), attr );
//let _ = term.set_cursor(row, col);
let _ = term.present();
jug +=1;
if jug >= 255{
jug = 0;
}
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 alloc::string::String;
use alloc::vec::Vec;
//use alloc::string::ToString;
use alloc::sync::Arc;
use super::super::super::super::qlib::common::*;
use super::super::super::super::kernel::time::*;
use super::super::super::super::qlib::linux_def::*;
use super::super::super::super::qlib::auth::*;
use super::super::super::super::task::*;
use super::super::super::inode::*;
use super::super::super::dirent::*;
use super::super::super::file::*;
use super::super::super::attr::*;
use super::super::super::flags::*;
use super::super::super::mount::*;
use super::super::super::host::hostinodeop::*;
use super::super::file::fileopsutil::*;
pub enum InodeOpsData {
None,
}
pub type GetFileOp = fn(_data: &InodeOpsData, task: &Task) -> Result<Arc<FileOperations>>;
pub type InodeTypeFn = fn(_data: &InodeOpsData) -> InodeType;
pub type WouldBlock = fn(_data: &InodeOpsData) -> bool;
pub type Lookup = fn(_data: &InodeOpsData, task: &Task, dir: &Inode, name: &str) -> Result<Dirent>;
pub type Create = fn(_data: &InodeOpsData, task: &Task, dir: &mut Inode, name: &str, flags: &FileFlags, perm: &FilePermissions) -> Result<File>;
pub type CreateDirectory = fn(_data: &InodeOpsData, task: &Task, dir: &mut Inode, name: &str, perm: &FilePermissions) -> Result<()>;
pub type CreateLink = fn(_data: &InodeOpsData, task: &Task, dir: &mut Inode, oldname: &str, newname: &str) -> Result<()>;
pub type CreateHardLink = fn(_data: &InodeOpsData, task: &Task, dir: &mut Inode, target: &Inode, name: &str) -> Result<()>;
pub type CreateFifo = fn(_data: &InodeOpsData, task: &Task, dir: &mut Inode, name: &str, perm: &FilePermissions) -> Result<()>;
//pub type RemoveDirent(&mut self, dir: &mut InodeStruStru, remove: &Arc<Mutex<Dirent>>) -> Result<()> ;
pub type Remove = fn(_data: &InodeOpsData, task: &Task, dir: &mut Inode, name: &str) -> Result<()>;
pub type RemoveDirectory = fn(_data: &InodeOpsData, task: &Task, dir: &mut Inode, name: &str) -> Result<()>;
pub type Rename = fn(_data: &InodeOpsData, task: &Task, dir: &mut Inode, oldParent: &Inode, oldname: &str, newParent: &Inode, newname: &str, replacement: bool) -> Result<()>;
pub type GetFile = fn(_data: &InodeOpsData, task: &Task, dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File>;
pub type UnstableAttrFn= fn(_data: &InodeOpsData, task: &Task, dir: &Inode) -> Result<UnstableAttr>;
pub type Getxattr = fn(_data: &InodeOpsData, dir: &Inode, name: &str) -> Result<String>;
pub type Setxattr = fn(_data: &InodeOpsData, dir: &mut Inode, name: &str, value: &str) -> Result<()>;
pub type Listxattr = fn(_data: &InodeOpsData, dir: &Inode) -> Result<Vec<String>>;
pub type Check = fn(_data: &InodeOpsData, task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool>;
pub type SetPermissions = fn(_data: &InodeOpsData, task: &Task, dir: &mut Inode, f: FilePermissions) -> bool;
pub type SetOwner = fn(_data: &InodeOpsData, task: &Task, dir: &mut Inode, owner: &FileOwner) -> Result<()>;
pub type SetTimestamps = fn(_data: &InodeOpsData, task: &Task, dir: &mut Inode, ts: &InterTimeSpec) -> Result<()>;
pub type Truncate = fn(_data: &InodeOpsData, task: &Task, dir: &mut Inode, size: i64) -> Result<()>;
pub type Allocate = fn(_data: &InodeOpsData, task: &Task, dir: &mut Inode, offset: i64, length: i64) -> Result<()>;
pub type ReadLink = fn(_data: &InodeOpsData, _task: &Task,dir: &Inode) -> Result<String>;
pub type GetLink = fn(_data: &InodeOpsData, _task: &Task, dir: &Inode) -> Result<Dirent>;
pub type AddLink = fn(_data: &InodeOpsData, _task: &Task);
pub type DropLink = fn(_data: &InodeOpsData, _task: &Task);
pub type IsVirtual = fn(_data: &InodeOpsData) -> bool;
pub type Sync = fn(_data: &InodeOpsData) -> Result<()>;
pub type StatFS = fn(_data: &InodeOpsData, task: &Task) -> Result<FsInfo>;
pub type Mmap = fn(_data: &InodeOpsData, task: &Task, len: u64, hugePage: bool, offset: u64, share: bool, prot: u64) -> Result<u64>;
pub type Mappable = fn(_data: &InodeOpsData) -> Option<HostInodeOp>;
fn InodeNotDirectory_Lookup(_data: &InodeOpsData, _task: &Task, _dir: &Inode, _name: &str) -> Result<Dirent> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn InodeNotDirectory_Create(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _name: &str, _flags: &FileFlags, _perm: &FilePermissions) -> Result<File> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn InodeNotDirectory_CreateDirectory(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn InodeNotDirectory_CreateLink(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _oldname: &str, _newname: &str) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn InodeNotDirectory_CreateHardLink(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _target: &Inode, _name: &str) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn InodeNotDirectory_CreateFifo(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _name: &str, _perm: &FilePermissions) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn InodeNotDirectory_Remove(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn InodeNotDirectory_RemoveDirectory(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _name: &str) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTDIR))
}
fn InodeNotDirectory_Rename(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _oldParent: &Inode, _oldname: &str, _newParent: &Inode, _newname: &str, _replacement: bool) -> Result<()> {
return Err(Error::SysError(SysErr::EINVAL))
}
fn InodeNotTruncatable_Truncate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _size: i64) -> Result<()> {
return Err(Error::SysError(SysErr::EINVAL))
}
fn InodeIsDirTruncate_Truncate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _size: i64) -> Result<()> {
return Err(Error::SysError(SysErr::EISDIR))
}
fn InodeNoopTruncate_Truncate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _size: i64) -> Result<()> {
return Ok(())
}
fn InodeNotRenameable_Rename(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _oldParent: &Inode, _oldname: &str, _newParent: &Inode, _newname: &str, _replacement: bool) -> Result<()> {
return Err(Error::SysError(SysErr::EINVAL))
}
fn InodeNotOpenable_GetFile(_data: &InodeOpsData, _task: &Task, _dir: &Inode, _dirent: &Dirent, _flags: FileFlags) -> Result<File> {
return Err(Error::SysError(SysErr::EIO))
}
fn InodeNotVirtual_IsVirtual(_data: &InodeOpsData) -> bool {
return false
}
fn InodeVirtual_IsVirtual(_data: &InodeOpsData) -> bool {
return true
}
fn InodeNotSymlink_ReadLink(_data: &InodeOpsData, _task: &Task,_dir: &Inode) -> Result<String> {
return Err(Error::SysError(SysErr::ENOLINK))
}
fn InodeNotSymlink_GetLink(_data: &InodeOpsData, _task: &Task, _dir: &Inode) -> Result<Dirent> {
return Err(Error::SysError(SysErr::ENOLINK))
}
fn InodeNotSymlink_AddLink(_data: &InodeOpsData, _task: &Task) {
}
fn InodeNotSymlink_DropLink(_data: &InodeOpsData, _task: &Task) {
}
fn InodeNoExtendedAttributes_Getxattr(_data: &InodeOpsData, _dir: &Inode, _name: &str) -> Result<String> {
return Err(Error::SysError(SysErr::EOPNOTSUPP))
}
fn InodeNoExtendedAttributes_Setxattr(_data: &InodeOpsData, _dir: &mut Inode, _name: &str, _value: &str) -> Result<()> {
return Err(Error::SysError(SysErr::EOPNOTSUPP))
}
fn InodeNoExtendedAttributes_Listxattr(_data: &InodeOpsData, _dir: &Inode) -> Result<Vec<String>> {
return Err(Error::SysError(SysErr::EOPNOTSUPP))
}
fn InodeGenericChecker_Check(_data: &InodeOpsData, task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool> {
return ContextCanAccessFile(task, inode, reqPerms)
}
fn InodeDenyWriteChecker_Check(_data: &InodeOpsData, task: &Task, inode: &Inode, reqPerms: &PermMask) -> Result<bool> {
if reqPerms.write {
return Ok(false)
}
return ContextCanAccessFile(task, inode, reqPerms)
}
fn InodeNotAllocatable_Allocate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _offset: i64, _length: i64) -> Result<()> {
return Err(Error::SysError(SysErr::EOPNOTSUPP))
}
fn InodeNoopAllocate_Allocate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _offset: i64, _length: i64) -> Result<()> {
return Ok(())
}
fn InodeIsDirAllocate_Allocate(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _offset: i64, _length: i64) -> Result<()> {
return Err(Error::SysError(SysErr::EISDIR))
}
fn InodeNotMappable_Mmap(_data: &InodeOpsData, _task: &Task, _len: u64, _hugePage: bool, _offset: u64, _share: bool, _prot: u64) -> Result<u64> {
return Err(Error::SysError(SysErr::EACCES))
}
fn InodeNotMappable_Mappable(_data: &InodeOpsData) -> Option<HostInodeOp> {
return None;
}
fn InodeNotInodeType_InodeType(_data: &InodeOpsData) -> InodeType {
return InodeType::None
}
fn InodeWouldBlock_WouldBlock(_data: &InodeOpsData) -> bool {
return false
}
fn InodeDefault_UnstableAttr(_data: &InodeOpsData, _task: &Task, _dir: &Inode) -> Result<UnstableAttr> {
return Err(Error::SysError(SysErr::ENOSYS))
}
fn InodeNoop_SetPermissions(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _f: FilePermissions) -> bool {
return true
}
fn InodeDefault_SetOwner(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _owner: &FileOwner) -> Result<()> {
return Err(Error::SysError(SysErr::ENOSYS))
}
fn InodeDefault_SetTimestamps(_data: &InodeOpsData, _task: &Task, _dir: &mut Inode, _ts: &InterTimeSpec) -> Result<()> {
return Err(Error::SysError(SysErr::ENOSYS))
}
fn InodeDefault_StatFS(_data: &InodeOpsData, _task: &Task) -> Result<FsInfo> {
return Err(Error::SysError(SysErr::ENOSYS))
}
fn InodeDefault_Sync(_data: &InodeOpsData) -> Result<()> {
return Err(Error::SysError(SysErr::ENOSYS))
}
fn InodeDefault_GetFileOp(_data: &InodeOpsData, _task: &Task) -> Result<Arc<FileOperations>> {
return Ok(Arc::new(FileOptionsUtil::default()))
}
pub struct InodeOpsUtil {
pub data: InodeOpsData,
pub getFileOp: GetFileOp,
pub inodeType: InodeTypeFn,
pub wouldBlock: WouldBlock,
pub lookup: Lookup,
pub create: Create,
pub createDirectory: CreateDirectory,
pub createLink: CreateLink,
pub createHardLink: CreateHardLink,
pub createFifo: CreateFifo,
pub remove: Remove,
pub removeDirectory: RemoveDirectory,
pub rename: Rename,
pub getFile: GetFile,
pub unstableAttr: UnstableAttrFn,
pub getxattr: Getxattr,
pub setxattr: Setxattr,
pub listxattr: Listxattr,
pub check: Check,
pub setPermissions: SetPermissions,
pub setOwner: SetOwner,
pub setTimestamps: SetTimestamps,
pub truncate: Truncate,
pub allocate: Allocate,
pub readLink: ReadLink,
pub getLink: GetLink,
pub addLink: AddLink,
pub dropLink: DropLink,
pub isVirtual: IsVirtual,
pub sync: Sync,
pub statFS: StatFS,
pub mmap: Mmap,
pub mappable: Mappable,
}
impl Default for InodeOpsUtil {
fn default() -> Self {
return Self {
data: InodeOpsData::None,
getFileOp: InodeDefault_GetFileOp,
inodeType: InodeNotInodeType_InodeType,
wouldBlock: InodeWouldBlock_WouldBlock,
lookup: InodeNotDirectory_Lookup,
create: InodeNotDirectory_Create,
createDirectory: InodeNotDirectory_CreateDirectory,
createLink: InodeNotDirectory_CreateLink,
createHardLink: InodeNotDirectory_CreateHardLink,
createFifo: InodeNotDirectory_CreateFifo,
remove: InodeNotDirectory_Remove,
removeDirectory: InodeNotDirectory_RemoveDirectory,
rename: InodeNotDirectory_Rename,
getFile: InodeNotOpenable_GetFile,
unstableAttr: InodeDefault_UnstableAttr,
getxattr: InodeNoExtendedAttributes_Getxattr,
setxattr: InodeNoExtendedAttributes_Setxattr,
listxattr: InodeNoExtendedAttributes_Listxattr,
check: InodeGenericChecker_Check,
setPermissions: InodeNoop_SetPermissions,
setOwner: InodeDefault_SetOwner,
setTimestamps: InodeDefault_SetTimestamps,
truncate: InodeNotTruncatable_Truncate,
allocate: InodeNotAllocatable_Allocate,
readLink: InodeNotSymlink_ReadLink,
getLink: InodeNotSymlink_GetLink,
addLink: InodeNotSymlink_AddLink,
dropLink: InodeNotSymlink_DropLink,
isVirtual: InodeVirtual_IsVirtual,
sync: InodeDefault_Sync,
statFS: InodeDefault_StatFS,
mmap: InodeNotMappable_Mmap,
mappable: InodeNotMappable_Mappable,
}
}
}
impl InodeOpsUtil {
pub fn SetInodeNotDirectory(&mut self) {
self.lookup = InodeNotDirectory_Lookup;
self.create = InodeNotDirectory_Create;
self.createDirectory = InodeNotDirectory_CreateDirectory;
self.createLink = InodeNotDirectory_CreateLink;
self.createHardLink = InodeNotDirectory_CreateHardLink;
self.createFifo = InodeNotDirectory_CreateFifo;
self.remove = InodeNotDirectory_Remove;
self.removeDirectory = InodeNotDirectory_RemoveDirectory;
self.rename = InodeNotDirectory_Rename;
}
pub fn SetInodeNotTruncatable(&mut self) {
self.truncate = InodeNotTruncatable_Truncate;
}
pub fn SetInodeNoopTruncate(&mut self) {
self.truncate = InodeNoopTruncate_Truncate;
}
pub fn SetInodeNotRenameable(&mut self) {
self.rename = InodeNotRenameable_Rename;
}
pub fn SetInodeNotOpenable(&mut self) {
self.getFile = InodeNotOpenable_GetFile;
}
pub fn SetInodeNotVirtual(&mut self) {
self.isVirtual = InodeNotVirtual_IsVirtual;
}
pub fn SetInodeVirtual(&mut self) {
self.isVirtual = InodeVirtual_IsVirtual;
}
pub fn SetInodeNotSymlink(&mut self) {
self.readLink = InodeNotSymlink_ReadLink;
self.getLink = InodeNotSymlink_GetLink;
}
pub fn SetInodeNoExtendedAttributes(&mut self) {
self.getxattr = InodeNoExtendedAttributes_Getxattr;
self.setxattr = InodeNoExtendedAttributes_Setxattr;
self.listxattr = InodeNoExtendedAttributes_Listxattr;
}
pub fn SetInodeGenericChecker(&mut self) {
self.check = InodeGenericChecker_Check;
}
pub fn SetInodeDenyWriteChecker(&mut self) {
self.check = InodeDenyWriteChecker_Check;
}
pub fn SetInodeNotAllocatable(&mut self) {
self.allocate = InodeNotAllocatable_Allocate;
}
pub fn SetInodeNoopAllocate(&mut self) {
self.allocate = InodeNoopAllocate_Allocate;
}
pub fn SetInodeNotMappable(&mut self) {
self.mmap = InodeNotMappable_Mmap;
self.mappable = InodeNotMappable_Mappable;
}
pub fn SetInodeIsDir(&mut self) {
self.allocate = InodeIsDirAllocate_Allocate;
self.truncate = InodeIsDirTruncate_Truncate;
}
} |
use crate::{ast, match_ast, AstNode, SyntaxError, SyntaxNode, T};
pub(crate) fn validate(root: &SyntaxNode) -> Vec<SyntaxError> {
// FIXME:
// * Add unescape validation of raw string literals and raw byte string literals
// * Add validation of doc comments are being attached to nodes
let mut errors = Vec::new();
for node in root.descendants() {
match_ast! {
match node {
ast::Literal(it) => validate_literal(it, &mut errors),
_ => (),
}
}
}
errors
}
fn validate_literal(literal: ast::Literal, acc: &mut Vec<SyntaxError>) {}
pub(crate) fn validate_block_structure(root: &SyntaxNode) {
let mut stack = Vec::new();
for node in root.descendants() {
match node.kind() {
T!['{'] => stack.push(node),
T!['}'] => {
if let Some(pair) = stack.pop() {
assert_eq!(
node.parent(),
pair.parent(),
"\nunpaired curleys:\n{}\n{:#?}\n",
root.text(),
root,
);
assert!(
node.next_sibling().is_none() && pair.prev_sibling().is_none(),
"\nfloating curlys at {:?}\nfile:\n{}\nerror:\n{}\n",
node,
root.text(),
node.text(),
);
}
}
_ => (),
}
}
}
|
use anyhow::*;
use liblumen_alloc::erts::exception::{self, error};
use liblumen_alloc::erts::process::trace::Trace;
use liblumen_alloc::erts::term::prelude::Term;
#[native_implemented::function(erlang:error/1)]
pub fn result(reason: Term) -> exception::Result<Term> {
Err(error(
reason,
None,
Trace::capture(),
Some(anyhow!("explicit error from Erlang").into()),
)
.into())
}
|
use std::fmt;
use titlecase::titlecase;
use chrono::NaiveDate;
use super::{db, Command, CommandArgs, Error, Result};
use super::formatter::format_currency;
pub(super) struct Stats;
struct _Stats {
pub name: String,
pub ticker: String,
pub date: NaiveDate,
pub min: f32,
pub average: f32,
pub median: f32,
pub std_dev: f32,
pub max: f32,
}
impl Stats {
fn query(&self, db: &db::DB, coin: String, date: NaiveDate) -> Option<_Stats> {
let query =
"select name, ticker, date, cast(min_euro as real), cast(average_euro as real), cast(median_euro as real),
cast(std_dev as real), cast(max_euro as real)
from daily_stats
join coins using(coin_id)
where name = $1
and date = $2";
let rows = db.connection.query(&query, &[&coin, &date]).unwrap();
if rows.is_empty() {
return None;
}
let row = rows.get(0);
Some(_Stats{
name: row.get(0),
ticker: row.get(1),
date: row.get(2),
min: row.get(3),
average: row.get(4),
median: row.get(5),
std_dev: row.get(6),
max: row.get(7),
})
}
}
impl Command for Stats {
fn name(&self) -> &'static str {
"!stats"
}
fn run(&self, db: &db::DB, msg: &Option<&str>) -> Result<String> {
let commands: Vec<&str> = msg.unwrap().split_whitespace().collect();
let coin = self.get_coin(&db, self.parse_coin_arg(&commands));
let date = self.parse_date(&commands);
let stats = self.query(&db, coin, date);
match stats {
Some(s) => Ok(s.to_string()),
None => Err(Error::Contact)
}
}
fn help(&self) -> &'static str {
"!stats [coin|ticker] [date]: Get the statistics for a coin's price over the course of a day. \
Defaults to btc and yesterday's date."
}
}
impl CommandArgs for Stats {}
impl fmt::Display for _Stats {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Stats for {} ({}) on {}: Min €{} Mean €{} Std Dev €{} Median €{} Max €{}",
titlecase(&self.name), self.ticker.to_uppercase(), self.date, format_currency(self.min),
format_currency(self.average), format_currency(self.std_dev),
format_currency(self.median), format_currency(self.max))
}
} |
use std::fmt::Display;
use data_types::{CompactionLevel, ParquetFile};
use observability_deps::tracing::info;
use crate::{file_classification::FilesToSplitOrCompact, partition_info::PartitionInfo};
use super::SplitOrCompact;
#[derive(Debug)]
pub struct LoggingSplitOrCompactWrapper<T>
where
T: SplitOrCompact,
{
inner: T,
}
impl<T> LoggingSplitOrCompactWrapper<T>
where
T: SplitOrCompact,
{
pub fn new(inner: T) -> Self {
Self { inner }
}
}
impl<T> Display for LoggingSplitOrCompactWrapper<T>
where
T: SplitOrCompact,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "display({})", self.inner)
}
}
impl<T> SplitOrCompact for LoggingSplitOrCompactWrapper<T>
where
T: SplitOrCompact,
{
fn apply(
&self,
partition_info: &PartitionInfo,
files: Vec<ParquetFile>,
target_level: CompactionLevel,
) -> (FilesToSplitOrCompact, Vec<ParquetFile>) {
let (files_to_split_or_compact, files_to_keep) =
self.inner.apply(partition_info, files, target_level);
info!(
partition_id = partition_info.partition_id.get(),
target_level = %target_level,
files_to_compact = files_to_split_or_compact.num_files_to_compact(),
files_to_split = files_to_split_or_compact.num_files_to_split(),
files_to_keep = files_to_keep.len(),
"split or compact"
);
(files_to_split_or_compact, files_to_keep)
}
}
|
use crate::io::BufMut;
use crate::mysql::protocol::{Capabilities, Encode};
// https://dev.mysql.com/doc/dev/mysql-server/8.0.12/page_protocol_com_stmt_prepare.html
#[derive(Debug)]
pub struct ComStmtPrepare<'a> {
pub query: &'a str,
}
impl Encode for ComStmtPrepare<'_> {
fn encode(&self, buf: &mut Vec<u8>, _: Capabilities) {
// COM_STMT_PREPARE : int<1>
buf.put_u8(0x16);
// query : string<EOF>
buf.put_str(self.query);
}
}
|
use crate::ui;
use crate::window::LllPanel;
#[derive(Debug)]
pub struct LllView {
pub top_win: LllPanel,
pub tab_win: LllPanel,
pub left_win: LllPanel,
pub mid_win: LllPanel,
pub right_win: LllPanel,
pub bot_win: LllPanel,
pub win_ratio: (usize, usize, usize),
}
impl LllView {
pub fn new(win_ratio: (usize, usize, usize)) -> Self {
let sum_ratio: usize = win_ratio.0 + win_ratio.1 + win_ratio.2;
let (term_rows, term_cols) = ui::getmaxyx();
let term_divide: i32 = term_cols / sum_ratio as i32;
// window for tabs
let win_xy: (i32, i32) = (1, 10);
let win_coord: (usize, usize) = (0, term_cols as usize - win_xy.1 as usize);
let tab_win = LllPanel::new(win_xy.0, win_xy.1, win_coord);
let win_xy: (i32, i32) = (1, term_cols - tab_win.cols);
let win_coord: (usize, usize) = (0, 0);
let top_win = LllPanel::new(win_xy.0, win_xy.1, win_coord);
let offset = 0;
let win_xy: (i32, i32) = (term_rows - 2, (term_divide * win_ratio.0 as i32) - 1);
let win_coord: (usize, usize) = (1, offset);
let left_win = LllPanel::new(win_xy.0, win_xy.1, win_coord);
let offset = offset + win_ratio.0;
let win_xy: (i32, i32) = (term_rows - 2, (term_divide * win_ratio.1 as i32) - 1);
let win_coord: (usize, usize) = (1, term_divide as usize * offset);
let mid_win = LllPanel::new(win_xy.0, win_xy.1, win_coord);
let offset = offset + win_ratio.1;
let win_xy: (i32, i32) = (term_rows - 2, term_cols - (term_divide * offset as i32) - 1);
let win_coord: (usize, usize) = (1, term_divide as usize * offset);
let right_win = LllPanel::new(win_xy.0, win_xy.1, win_coord);
let win_xy: (i32, i32) = (1, term_cols);
let win_coord: (usize, usize) = (term_rows as usize - 1, 0);
let bot_win = LllPanel::new(win_xy.0, win_xy.1, win_coord);
LllView {
top_win,
tab_win,
left_win,
mid_win,
right_win,
bot_win,
win_ratio,
}
}
pub fn resize_views(&mut self) {
let new_view = Self::new(self.win_ratio);
self.top_win = new_view.top_win;
self.bot_win = new_view.bot_win;
self.tab_win = new_view.tab_win;
self.left_win = new_view.left_win;
self.mid_win = new_view.mid_win;
self.right_win = new_view.right_win;
}
}
|
use crate::controls::ControlHandle;
use crate::win32::window::bind_raw_event_handler_inner;
use crate::win32::window_helper as wh;
use crate::NwgError;
use winapi::shared::windef::{HWND};
use std::rc::Rc;
use std::cell::RefCell;
use std::ptr;
/// A control item in a GridLayout
#[derive(Debug)]
pub struct GridLayoutItem {
/// The handle to the control in the item
control: HWND,
/// The column position of the control in the layout
pub col: u32,
/// The row position of the control in the layout
pub row: u32,
/// The number column this item should span. Should be 1 for single column item.
pub col_span: u32,
/// The number row this item should span. Should be 1 for single row item.
pub row_span: u32
}
impl GridLayoutItem {
/// Initialize a new grid layout item
pub fn new<W: Into<ControlHandle>>(c: W, col: u32, row: u32, col_span: u32, row_span: u32) -> GridLayoutItem {
let control = c.into().hwnd().expect("Child must be a window-like control (HWND handle)");
GridLayoutItem {
control,
col,
row,
col_span,
row_span
}
}
}
/// A layout that lays out widgets in a grid
/// This is the inner data shared between the callback and the application
pub struct GridLayoutInner {
/// The control that holds the layout
base: HWND,
/// The children of the control that fit in the layout
children: Vec<GridLayoutItem>,
/// The top, right, bottom, left space around the layout
margins: [u32; 4],
/// The minimum size of the layout. Used if `base` is smaller than `min_size`.
min_size: [u32; 2],
/// The maximum size of the layout. Used if `base` is bigger than `min_size`.
max_size: [u32; 2],
/// The number of column. If None, compute the value from children.
column_count: Option<u32>,
/// The number of row. If None, compute the value from children.
row_count: Option<u32>,
/// The spacing between controls
spacing: u32
}
/**
A layout that lays out widgets in a grid
NWG layouts use interior mutability to manage their controls.
A GridLayouts has the following properties:
* margin - The top, right, bottom, left margins of the layout - (default: [5, 5, 5, 5])
* spacing - The spacing between children controls - (default: 5)
* min_size - The minimum size of the layout - (default: [0, 0])
* max_size - The maximum size of the layout - (default: [u32::max_value(), u32::max_value()])
* max_column - Number of columns - (default: None),
* max_row - Number of rows - (default: None),
```rust
use native_windows_gui as nwg;
fn layout(layout: &nwg::GridLayout, window: &nwg::Window, item1: &nwg::Button, item2: &nwg::Button) {
nwg::GridLayout::builder()
.parent(window)
.max_row(Some(6))
.spacing(5)
.margin([0,0,0,0])
.child(0, 0, item1)
.child_item(nwg::GridLayoutItem::new(item2, 1, 0, 2, 1))
.build(&layout);
}
```
*/
#[derive(Clone)]
pub struct GridLayout {
inner: Rc<RefCell<GridLayoutInner>>
}
impl GridLayout {
pub fn builder() -> GridLayoutBuilder {
let layout = GridLayoutInner {
base: ptr::null_mut(),
children: Vec::new(),
margins: [5, 5, 5, 5],
spacing: 5,
min_size: [0, 0],
max_size: [u32::max_value(), u32::max_value()],
column_count: None,
row_count: None
};
GridLayoutBuilder { layout }
}
/**
Add a children control to the grid layout.
This is a simplified interface over `add_child_item`
Panic:
- If the layout is not initialized
- If the control is not window-like (HWND handle)
*/
pub fn add_child<W: Into<ControlHandle>>(&self, col: u32, row: u32, c: W) {
let h = c.into().hwnd().expect("Child must be a window-like control (HWND handle)");
let item = GridLayoutItem {
control: h,
col,
row,
col_span: 1,
row_span: 1,
};
self.add_child_item(item);
}
/**
Add a children control to the grid layout.
Panic:
- If the layout is not initialized
- If the control is not window-like (HWND handle)
*/
pub fn add_child_item(&self, i: GridLayoutItem) {
let base = {
let mut inner = self.inner.borrow_mut();
if inner.base.is_null() {
panic!("GridLayout is not initialized");
}
// No need to check the layout item control because it's checked in `GridLayoutItem::new`
inner.children.push(i);
inner.base
};
let (w, h) = unsafe { wh::get_window_size(base) };
self.update_layout(w as u32, h as u32);
}
/**
Remove the children control in the layout. See also `remove_child_by_pos`.
Note that the child control won't be hidden after being removed from the control.
This method won't do anything if there is no control at the specified position.
Panic:
- If the layout is not initialized
*/
pub fn remove_child<W: Into<ControlHandle>>(&self, c: W) {
let base = {
let mut inner = self.inner.borrow_mut();
if inner.base.is_null() {
panic!("GridLayout is not initialized");
}
let handle = c.into().hwnd().expect("Control must be window-like (HWND handle)");
let index = inner.children.iter().position(|item| item.control == handle);
match index {
Some(i) => { inner.children.remove(i); },
None => { return; }
}
inner.base
};
let (w, h) = unsafe { wh::get_window_size(base) };
self.update_layout(w as u32, h as u32);
}
/**
Remove the children control in the layout. See also `remove_child_by_pos`.
Note that the child control won't be hidden after being removed from the control.
This method won't do anything if there is no control at the specified position.
Panic:
- If the layout is not initialized
*/
pub fn remove_child_by_pos(&self, col: u32, row: u32) {
let base = {
let mut inner = self.inner.borrow_mut();
if inner.base.is_null() {
panic!("GridLayout is not initialized");
}
let index = inner.children.iter().position(|item| item.col == col && item.row == row);
match index {
Some(i) => { inner.children.remove(i); },
None => {}
}
inner.base
};
let (w, h) = unsafe { wh::get_window_size(base) };
self.update_layout(w as u32, h as u32);
}
/**
Move the selected control to a new position in the grid layout. The old position
becomes empty (as if `remove_child` was called). However it won't remove the control
at the new position if there is one.
This method won't do anything if there is no control at the specified position.
Panic:
- If the layout is not initialized
*/
pub fn move_child<W: Into<ControlHandle>>(&self, c: W, col: u32, row: u32) {
let base = {
let mut inner = self.inner.borrow_mut();
if inner.base.is_null() {
panic!("GridLayout is not initialized");
}
let handle = c.into().hwnd().expect("Control must be window-like (HWND handle)");
let index = inner.children.iter().position(|item| item.control == handle);
match index {
Some(i) => {
let mut child = inner.children.remove(i);
child.col = col;
child.row = row;
inner.children.push(child);
}
None => { return; }
}
inner.base
};
let (w, h) = unsafe { wh::get_window_size(base) };
self.update_layout(w as u32, h as u32);
}
/**
Move the selected control to a new position in the grid layout. The old position
becomes empty (as if `remove_child` was called). However it won't remove the control
at the new position if there is one.
This method won't do anything if there is no control at the specified position.
Panic:
- If the layout is not initialized
*/
pub fn move_child_by_pos<W: Into<ControlHandle>>(&self, col: u32, row: u32, new_col: u32, new_row: u32) {
let base = {
let mut inner = self.inner.borrow_mut();
if inner.base.is_null() {
panic!("GridLayout is not initialized");
}
let index = inner.children.iter().position(|item| item.col == col && item.row == row);
match index {
Some(i) => {
let mut child = inner.children.remove(i);
child.col = new_col;
child.row = new_row;
inner.children.push(child);
},
None => {}
}
inner.base
};
let (w, h) = unsafe { wh::get_window_size(base) };
self.update_layout(w as u32, h as u32);
}
/**
Check if a window control is a children of the layout
Panic:
- If the layout is not initialized
- If the child is not a window-like control
*/
pub fn has_child<W: Into<ControlHandle>>(&self, c: W) -> bool {
let inner = self.inner.borrow();
if inner.base.is_null() {
panic!("GridLayout is not initialized");
}
let handle = c.into().hwnd().expect("Children is not a window-like control (HWND handle)");
inner.children.iter().any(|c| c.control == handle )
}
/// Resize the layout as if the parent window had the specified size.
///
/// Arguments:
/// w: New width of the layout
/// h: New height of the layout
///
/// Panic:
/// - The layout must have been successfully built otherwise this function will panic.
pub fn resize(&self, w: u32, h: u32) {
let inner = self.inner.borrow();
if inner.base.is_null() {
panic!("Grid layout is not bound to a parent control.")
}
self.update_layout(w, h);
}
/// Resize the layout to fit the parent window size
///
/// Panic:
/// - The layout must have been successfully built otherwise this function will panic.
pub fn fit(&self) {
let inner = self.inner.borrow();
if inner.base.is_null() {
panic!("Grid layout is not bound to a parent control.")
}
let (w, h) = unsafe { wh::get_window_size(inner.base) };
self.update_layout(w, h);
}
/// Set the margins of the layout. The four values are in this order: top, right, bottom, left.
pub fn margin(&self, m: [u32; 4]) {
let mut inner = self.inner.borrow_mut();
inner.margins = m;
}
/// Set the size of the space between the children in the layout. Default value is 5.
pub fn spacing(&self, sp: u32) {
let mut inner = self.inner.borrow_mut();
inner.spacing = sp;
}
/// Sets the minimum size of the layout
pub fn min_size(&self, sz: [u32; 2]) {
let mut inner = self.inner.borrow_mut();
inner.min_size = sz;
}
/// Sets the maximum size of the layout
pub fn max_size(&self, sz: [u32; 2]) {
let mut inner = self.inner.borrow_mut();
inner.max_size = sz;
}
/// Set the number of column in the layout
pub fn max_column(&self, count: Option<u32>) {
let mut inner = self.inner.borrow_mut();
inner.column_count = count;
}
/// Set the number of row in the layout
pub fn max_row(&self, count: Option<u32>) {
let mut inner = self.inner.borrow_mut();
inner.row_count = count;
}
fn update_layout(&self, mut width: u32, mut height: u32) -> () {
let inner = self.inner.borrow();
if inner.base.is_null() || inner.children.len() == 0 {
return;
}
let [m_top, m_right, m_bottom, m_left] = inner.margins;
let sp = inner.spacing;
let children = &inner.children;
let [min_w, min_h] = inner.min_size;
if width < min_w { width = min_w; }
if height < min_h { height = min_h; }
let [max_w, max_h] = inner.max_size;
if width > max_w { width = max_w; }
if height > max_h { height = max_h; }
let column_count = match inner.column_count {
Some(c) => c,
None => children.iter().map(|item| item.col + item.col_span).max().unwrap_or(1)
};
let row_count = match inner.row_count {
Some(c) => c,
None => children.iter().map(|item| item.row + item.row_span).max().unwrap_or(1)
};
if width < (m_right + m_left) + ((sp * 2) * column_count) {
return;
}
if height < (m_top + m_bottom) + ((sp * 2) * row_count) {
return;
}
// Apply margins
width = width - m_right - m_left;
height = height - m_top - m_bottom;
// Apply spacing
width = width - ((sp * 2) * column_count);
height = height - ((sp * 2) * row_count);
let item_width = width / column_count;
let item_height = height / row_count;
let sp2 = sp * 2;
let mut columns = vec![item_width; column_count as usize];
let mut rows = vec![item_height; row_count as usize];
let extra_width = width - item_width * column_count;
if extra_width > 0 {
for x in &mut columns[0..(extra_width as usize)] {
*x += 1;
}
}
let extra_height = height - item_height * row_count;
if extra_height > 0 {
for x in &mut rows[0..(extra_height as usize)] {
*x += 1;
}
}
let mut last_handle = None;
for item in inner.children.iter() {
let x: u32 = m_left + (sp + (sp2 * item.col)) + columns[0..(item.col as usize)].iter().sum::<u32>();
let y: u32 = m_top + (sp + (sp2 * item.row)) + rows[0..(item.row as usize)].iter().sum::<u32>();
let local_width: u32 = &columns[(item.col as usize)..((item.col + item.col_span) as usize)].iter().sum::<u32>() + (sp2 * (item.col_span - 1));
let local_height: u32 = &rows[(item.row as usize)..((item.row + item.row_span) as usize)].iter().sum::<u32>() + (sp2 * (item.row_span - 1));
unsafe {
wh::set_window_position(item.control, x as i32, y as i32);
wh::set_window_size(item.control, local_width, local_height, false);
wh::set_window_after(item.control, last_handle)
}
last_handle = Some(item.control);
}
}
}
impl Default for GridLayout {
fn default() -> GridLayout {
let inner = GridLayoutInner {
base: ptr::null_mut(),
children: Vec::new(),
margins: [5, 5, 5, 5],
min_size: [0, 0],
max_size: [u32::max_value(), u32::max_value()],
column_count: None,
row_count: None,
spacing: 5,
};
GridLayout {
inner: Rc::new(RefCell::new(inner))
}
}
}
/// Builder for a `GridLayout` struct
pub struct GridLayoutBuilder {
layout: GridLayoutInner
}
impl GridLayoutBuilder {
/// Set the layout parent. The handle must be a window object otherwise the function will panic
pub fn parent<W: Into<ControlHandle>>(mut self, p: W) -> GridLayoutBuilder {
self.layout.base = p.into().hwnd().expect("Parent must be HWND");
self
}
/// Add a children to the layout at the position `col` and `row`.
/// This is a shortcut over `child_item` for item with default span.
/// The handle must be a window object otherwise the function will panic
pub fn child<W: Into<ControlHandle>>(mut self, col: u32, row: u32, c: W) -> GridLayoutBuilder {
let h = c.into().hwnd().expect("Child must be HWND");
self.layout.children.push(GridLayoutItem {
control: h,
col,
row,
col_span: 1,
row_span: 1,
});
self
}
/// Add a children to the layout
/// The handle must be a window object otherwise the function will panic
pub fn child_item(mut self, item: GridLayoutItem) -> GridLayoutBuilder {
self.layout.children.push(item);
self
}
/// Set the margins of the layout. The four values are in this order: top, right, bottom, left.
pub fn margin(mut self, m: [u32; 4]) -> GridLayoutBuilder {
self.layout.margins = m;
self
}
/// Set the size of the space between the children in the layout. Default value is 5.
pub fn spacing(mut self, sp: u32) -> GridLayoutBuilder {
self.layout.spacing = sp;
self
}
/// Sets the minimum size of the layout
pub fn min_size(mut self, sz: [u32; 2]) -> GridLayoutBuilder {
self.layout.min_size = sz;
self
}
/// Sets the maximum size of the layout
pub fn max_size(mut self, sz: [u32; 2]) -> GridLayoutBuilder {
self.layout.max_size = sz;
self
}
/// Set the number of column in the layout
pub fn max_column(mut self, count: Option<u32>) -> GridLayoutBuilder {
self.layout.column_count = count;
self
}
/// Set the number of row in the layout
pub fn max_row(mut self, count: Option<u32>) -> GridLayoutBuilder {
self.layout.row_count = count;
self
}
/// Build the layout object and bind the callback.
/// Children must only contains window object otherwise this method will panic.
pub fn build(self, layout: &GridLayout) -> Result<(), NwgError> {
use winapi::um::winuser::WM_SIZE;
use winapi::shared::minwindef::{HIWORD, LOWORD};
if self.layout.base.is_null() {
return Err(NwgError::layout_create("Gridlayout does not have a parent."));
}
// Checks if the layouts cell or row are outside max_column or max_row
if let Some(max_row) = self.layout.row_count {
if let Some(item) = self.layout.children.iter().find(|c| c.row >= max_row) {
return Err(NwgError::layout_create(format!("A layout item row is bigger or equal than the max number of row. {} >= {}", item.row, max_row)));
}
}
if let Some(max_column) = self.layout.column_count {
if let Some(item) = self.layout.children.iter().find(|c| c.col >= max_column) {
return Err(NwgError::layout_create(format!("A layout item column is bigger or equal than the max number of column. {} >= {}", item.col, max_column)));
}
}
let (w, h) = unsafe { wh::get_window_size(self.layout.base) };
let base_handle = ControlHandle::Hwnd(self.layout.base);
// Saves the new layout. TODO: should free the old one too (if any)
{
let mut layout_inner = layout.inner.borrow_mut();
*layout_inner = self.layout;
}
// Initial layout update
layout.update_layout(w, h);
// Bind the event handler
let event_layout = layout.clone();
let cb = move |_h, msg, _w, l| {
if msg == WM_SIZE {
let size = l as u32;
let width = LOWORD(size) as i32;
let height = HIWORD(size) as i32;
let (w, h) = unsafe { crate::win32::high_dpi::physical_to_logical(width, height) };
GridLayout::update_layout(&event_layout, w as u32, h as u32);
}
None
};
/// Keep generating ids so that multiple layouts can be applied to the same parent
use std::sync::atomic::{AtomicUsize, Ordering};
static BOX_LAYOUT_ID: AtomicUsize = AtomicUsize::new(0x8FFF);
bind_raw_event_handler_inner(&base_handle, BOX_LAYOUT_ID.fetch_add(1, Ordering::SeqCst), cb).unwrap();
Ok(())
}
}
|
// Copyright 2021 Chiral Ltd.
// Licensed under the Apache-2.0 license (https://opensource.org/licenses/Apache-2.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
use crate::core;
use super::mapping_ops;
use super::case_breakable;
use super::case_cyclic;
const MAX_REDUCIBLE_CYCLE_SIZE: usize = 8;
/// for (k, v) in returned HashMap, vertex k is removed and reduced into a custom vertex with index v
fn get_reduced_groups(
mapping: &mapping_ops::VertexMapping,
boundary_edges: &Vec<Vec<mapping_ops::SimpleEdge>>
) -> std::collections::HashMap<usize, usize> {
let keys: Vec<usize> = boundary_edges.iter().map(|bes| bes[0].0).collect();
let mut reduced_groups: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
for idx in 0..keys.len() {
for jdx in 0..mapping[idx].len() {
reduced_groups.insert(mapping[idx][jdx], keys[idx]);
}
}
reduced_groups
}
fn new_vertex_index(
vertex_index: usize,
reduced_groups: &std::collections::HashMap<usize, usize>
) -> usize {
match reduced_groups.get(&vertex_index) {
Some(&target_index) => target_index,
None => vertex_index
}
}
fn new_boundary_edge(
edge: &mapping_ops::SimpleEdge,
reduced_groups: &std::collections::HashMap<usize, usize>
) -> mapping_ops::SimpleEdge {
(new_vertex_index(edge.0, reduced_groups), new_vertex_index(edge.1, reduced_groups))
}
fn get_new_boundary_edges(
edges: &Vec<mapping_ops::SimpleEdge>,
reduced_groups: &std::collections::HashMap<usize, usize>
) -> Vec<mapping_ops::SimpleEdge> {
edges.iter()
.map(|edge| new_boundary_edge(edge, reduced_groups))
.collect()
}
fn get_symmetric_index(
vertex_index: usize,
orbits_symmetry: &Vec<core::orbit_ops::Orbit>,
reduced_groups: &std::collections::HashMap<usize, usize>,
) -> usize {
let vertex_new = match reduced_groups.get(&vertex_index) {
Some(&reduced_vertex) => reduced_vertex,
None => vertex_index
};
for orbit in orbits_symmetry.iter() {
if orbit.contains(&vertex_new) {
return orbit[0];
}
}
vertex_new
}
/// ReducibleGraph: struct & implementation
#[derive(Debug, Clone)]
pub struct ReducibleGraph<T: core::graph::Vertex> {
pub vv: core::graph::VertexVec<T>,
pub mapping: mapping_ops::VertexMapping,
pub boundary_edges: mapping_ops::BoundaryEdges,
pub orbits_after_partition: Vec<core::orbit_ops::Orbit>,
pub numbering: Vec<usize>,
}
impl<T: core::graph::Vertex> ReducibleGraph<T> {
pub fn init(
vv: core::graph::VertexVec<T>,
mapping: mapping_ops::VertexMapping,
boundary_edges: Vec<Vec<(usize, usize)>>,
orbits_after_partition: Vec<core::orbit_ops::Orbit>,
numbering: Vec<usize>,
) -> Self {
Self { vv, mapping, boundary_edges, orbits_after_partition, numbering }
}
pub fn create_mapping(&mut self) -> Result<(), String> {
if cfg!(debug_assertions) {
println!("\nOrbits after partition: {:?}, total: {}", self.orbits_after_partition, self.orbits_after_partition.iter().map(|orbit| orbit.len()).collect::<Vec<usize>>().iter().sum::<usize>());
println!("All {} vertices: {:?}", self.vv.len(), self.vv.valid_indexes());
}
match case_breakable::create_mapping(&self.orbits_after_partition, &self.numbering, &self.vv) {
Ok((mapping, boundary_edges)) => {
self.mapping = mapping;
self.boundary_edges = boundary_edges;
return Ok(());
},
Err(_) => ()
}
match case_cyclic::create_mapping(&self.orbits_after_partition, &self.numbering, &self.vv, MAX_REDUCIBLE_CYCLE_SIZE) {
Ok((mapping, boundary_edges)) => {
self.mapping = mapping;
self.boundary_edges = boundary_edges;
return Ok(())
},
Err(_) => ()
}
Err("Reduce Mapping Error".to_string())
}
pub fn get_simplified_graph(&self, custom_marker: &mut usize) -> Self {
if self.mapping.len() == 0 {
panic!("Reduce mapping not done")
}
if self.mapping.len() == 1 {
panic!("Cannot reduce only 1 vertex")
}
let removed_indexes: Vec<usize> = self.mapping.to_vec().into_iter().flatten().collect();
let mut indexes_new: Vec<usize> = self.vv.valid_indexes().to_vec().into_iter()
.filter(|idx| !removed_indexes.contains(idx))
.collect();
let mut vertices_new = self.vv.all_vertices().to_vec();
let reduced_groups: std::collections::HashMap<usize, usize> = get_reduced_groups(&self.mapping, &self.boundary_edges);
for &vi in indexes_new.iter() {
vertices_new[vi].update_edges_in_reduced_graph(vi, &reduced_groups, &self.numbering);
}
*custom_marker += 1;
for idx in 0..self.boundary_edges.len() {
let vertex_index: usize = self.boundary_edges[idx][0].0;
let custom_vertice = T::custom_new_in_reduced_graph(
vertex_index, *custom_marker, &self.boundary_edges[idx], &get_new_boundary_edges(&self.boundary_edges[idx], &reduced_groups), self.vv.all_vertices(), &self.numbering
);
indexes_new.push(vertex_index);
vertices_new[vertex_index] = custom_vertice;
}
let new_vv = core::graph::VertexVec::init(indexes_new, vertices_new);
ReducibleGraph {
vv: new_vv,
mapping: vec![],
boundary_edges: vec![],
orbits_after_partition: vec![],
numbering: vec![]
}
}
pub fn get_folded_subgraph(&self,
custom_marker: &mut usize,
orbits_symmetry: &Vec<core::orbit_ops::Orbit>
) -> Self {
let mut indexes_new: Vec<usize> = self.mapping[0].clone();
let mut vertices_new = self.vv.all_vertices().to_vec();
let mut mapping_sliced = self.mapping.clone(); mapping_sliced.remove(0);
let mut boundary_edges_sliced = self.boundary_edges.clone(); boundary_edges_sliced.remove(0);
let reduced_groups: std::collections::HashMap<usize, usize> = get_reduced_groups(&mapping_sliced, &boundary_edges_sliced);
let mut edges_with_value: Vec<(usize, usize, usize)> = self.boundary_edges[0].iter()
.map(|edge| (edge.0, edge.1, get_symmetric_index(edge.1, orbits_symmetry, &reduced_groups)))
.collect();
edges_with_value.sort_by_key(|edge| edge.2);
*custom_marker += 1;
let mut current_symmetric_index = edges_with_value[0].2;
for edge in edges_with_value.iter() {
if edge.2 > current_symmetric_index {
current_symmetric_index = edge.2;
*custom_marker += 1;
}
indexes_new.push(edge.1);
let custom_vertex = T::custom_new_in_folded_graph(*custom_marker, &(edge.0, edge.1), self.vv.all_vertices());
vertices_new[edge.1] = custom_vertex;
}
let new_vv = core::graph::VertexVec::init(indexes_new, vertices_new);
ReducibleGraph {
vv: new_vv,
mapping: vec![],
boundary_edges: vec![],
orbits_after_partition: vec![],
numbering: vec![]
}
}
pub fn reduced_subgraph_indexes(&self) -> Vec<usize> {
self.boundary_edges.iter()
.map(|bes| bes[0].0)
.collect()
}
pub fn symmetric_orbits_from_folded_graph(&self) -> Vec<core::orbit_ops::Orbit> {
(0..self.mapping[0].len())
.map(|idx| self.mapping.iter().map(|m| m[idx]).collect())
.collect()
}
pub fn is_reducible(&self) -> bool {
self.mapping[0].len() > 1
}
}
impl<T: core::graph::Vertex> std::fmt::Display for ReducibleGraph<T> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut output_content: String = "".to_string();
output_content += &self.vv.valid_indexes().iter().map(|vi| vi.to_string()).collect::<Vec<String>>().join("\t");
output_content += "\n";
output_content += &self.vv.valid_indexes().iter().map(|&vi| self.numbering[vi].to_string()).collect::<Vec<String>>().join("\t");
output_content += "\n";
write!(f, "{}", format!("{}", output_content))
}
}
#[cfg(test)]
mod test_reduce_graph {
use crate::ext::molecule;
use super::*;
#[test]
fn test_reducible_graph() {
let smiles_vec: Vec<String> = vecNCCCCCCCCCCCCNC(=O)[C@@H](CCCCNC(=O)CCCC(=O)O)N(Cc1ccc(OCc2ccccc2)cc1)Cc1ccc(OCc2ccccc2)cc1)N(Cc1ccc(OCc2ccccc2)cc1)Cc1ccc(OCc2ccccc2)cc1",
"CCOP(=O)(OCC)OCc1ccc(S(=O)(=O)CC(C[C@H]2O[C@@H]3C[C@]4(C)CC[C@H]5[C@H](C)CC[C@@H]([C@H]2C)[C@]53OO4)C[C@H]2O[C@@H]3C[C@]4(C)CC[C@H]5[C@H](C)CC[C@@H]([C@H]2C)[C@]53OO4)cc1",
"CC(C)(C)c1cc2c(OCCCCNC(=N)N)c(c1)Cc1cc(C(C)(C)C)cc(c1OCCCCNC(=N)N)Cc1cc(C(C)(C)C)cc(c1OCCCCNC(=N)N)Cc1cc(C(C)(C)C)cc(c1OCCCCNC(=N)N)C2",
"O=c1cc(-c2ccc(OCCOCCOCCOCCOCCOCCOCCOCCOCCOCCOCCOCCOCCOc3ccc(-c4cc(=O)c5ccccc5o4)cc3)cc2)oc2ccccc12",
// "c1cc2cc3ccc(cc4ccc(cc5ccc(cc1n2)n5)n4)n3",
].iter().map(|s| s.to_string()).collect();
let results = vec![
(vec![22, 23], vec![22, 21, 20, 19, 18, 17, 16, 14, 15, 13, 12, 77, 11, 78, 93, 10, 79, 94, 9, 92, 80, 107, 95, 8, 91, 81, 106, 96, 6, 82, 97, 7, 5, 83, 98, 4, 84, 99, 3, 85, 100, 1, 90, 86, 105, 101, 2, 0, 89, 87, 104, 102, 88, 103, 23], 202),
(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 59, 60, 19, 39], vec![19, 20, 21, 34, 22, 35, 33, 23, 36, 32, 24, 37, 28, 31, 25, 26, 38, 27, 29, 30, 18], 202),
(vec![0, 1, 2, 3, 4, 5, 6, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 79, 7, 29, 49, 69], vec![7, 8, 9, 10, 11, 12, 13, 14, 16, 15, 6, 17], 202),
(vec![27, 28], vec![27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 65, 5, 66, 4, 3, 2, 67, 1, 68, 0, 73, 69, 72, 70, 71, 28], 202),
// (vec![3, 8, 13, 18, 19, 14, 12, 4], vec![10, 11, 9, 12, 22, 8, 13], 202),
];
for (idx, smiles) in smiles_vec.iter().enumerate() {
let mol = molecule::Molecule::from_smiles(smiles);
if cfg!(debug_assertions) {
println!("{}", mol.smiles_with_index(smiles, &vec![]));
}
let vv = core::graph::VertexVec::init((0..mol.atoms.len()).collect(), mol.atoms.clone());
let mut rg = ReducibleGraph {
vv: vv,
mapping: vec![],
boundary_edges: vec![],
orbits_after_partition: vec![],
numbering: vec![]
};
let mut numbering_rg: Vec<usize> = vec![];
let mut orbits_after_partition_rg: Vec<core::orbit_ops::Orbit> = vec![];
core::givp::run::<molecule::AtomExtendable>(&rg.vv, &mut numbering_rg, &mut orbits_after_partition_rg);
rg.numbering = numbering_rg;
rg.orbits_after_partition = orbits_after_partition_rg;
match rg.create_mapping() {
Ok(_) => {
let mut custom_marker: usize = 200;
let sg = rg.get_simplified_graph(&mut custom_marker);
let fg = rg.get_folded_subgraph(&mut custom_marker, &rg.orbits_after_partition);
assert_eq!(
(sg.vv.valid_indexes().to_vec(), fg.vv.valid_indexes().to_vec(), custom_marker),
results[idx]
);
},
Err(_) => ()
}
}
}
} |
#[doc = "Reader of register EXTILEVEL"]
pub type R = crate::R<u32, super::EXTILEVEL>;
#[doc = "Writer for register EXTILEVEL"]
pub type W = crate::W<u32, super::EXTILEVEL>;
#[doc = "Register EXTILEVEL `reset()`'s with value 0"]
impl crate::ResetValue for super::EXTILEVEL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `EM4WU0`"]
pub type EM4WU0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EM4WU0`"]
pub struct EM4WU0_W<'a> {
w: &'a mut W,
}
impl<'a> EM4WU0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `EM4WU1`"]
pub type EM4WU1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EM4WU1`"]
pub struct EM4WU1_W<'a> {
w: &'a mut W,
}
impl<'a> EM4WU1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `EM4WU4`"]
pub type EM4WU4_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EM4WU4`"]
pub struct EM4WU4_W<'a> {
w: &'a mut W,
}
impl<'a> EM4WU4_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Reader of field `EM4WU8`"]
pub type EM4WU8_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EM4WU8`"]
pub struct EM4WU8_W<'a> {
w: &'a mut W,
}
impl<'a> EM4WU8_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `EM4WU9`"]
pub type EM4WU9_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EM4WU9`"]
pub struct EM4WU9_W<'a> {
w: &'a mut W,
}
impl<'a> EM4WU9_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Reader of field `EM4WU12`"]
pub type EM4WU12_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EM4WU12`"]
pub struct EM4WU12_W<'a> {
w: &'a mut W,
}
impl<'a> EM4WU12_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
impl R {
#[doc = "Bit 16 - EM4 Wake Up Level for EM4WU0 Pin"]
#[inline(always)]
pub fn em4wu0(&self) -> EM4WU0_R {
EM4WU0_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - EM4 Wake Up Level for EM4WU1 Pin"]
#[inline(always)]
pub fn em4wu1(&self) -> EM4WU1_R {
EM4WU1_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 20 - EM4 Wake Up Level for EM4WU4 Pin"]
#[inline(always)]
pub fn em4wu4(&self) -> EM4WU4_R {
EM4WU4_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 24 - EM4 Wake Up Level for EM4WU8 Pin"]
#[inline(always)]
pub fn em4wu8(&self) -> EM4WU8_R {
EM4WU8_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 25 - EM4 Wake Up Level for EM4WU9 Pin"]
#[inline(always)]
pub fn em4wu9(&self) -> EM4WU9_R {
EM4WU9_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 28 - EM4 Wake Up Level for EM4WU12 Pin"]
#[inline(always)]
pub fn em4wu12(&self) -> EM4WU12_R {
EM4WU12_R::new(((self.bits >> 28) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 16 - EM4 Wake Up Level for EM4WU0 Pin"]
#[inline(always)]
pub fn em4wu0(&mut self) -> EM4WU0_W {
EM4WU0_W { w: self }
}
#[doc = "Bit 17 - EM4 Wake Up Level for EM4WU1 Pin"]
#[inline(always)]
pub fn em4wu1(&mut self) -> EM4WU1_W {
EM4WU1_W { w: self }
}
#[doc = "Bit 20 - EM4 Wake Up Level for EM4WU4 Pin"]
#[inline(always)]
pub fn em4wu4(&mut self) -> EM4WU4_W {
EM4WU4_W { w: self }
}
#[doc = "Bit 24 - EM4 Wake Up Level for EM4WU8 Pin"]
#[inline(always)]
pub fn em4wu8(&mut self) -> EM4WU8_W {
EM4WU8_W { w: self }
}
#[doc = "Bit 25 - EM4 Wake Up Level for EM4WU9 Pin"]
#[inline(always)]
pub fn em4wu9(&mut self) -> EM4WU9_W {
EM4WU9_W { w: self }
}
#[doc = "Bit 28 - EM4 Wake Up Level for EM4WU12 Pin"]
#[inline(always)]
pub fn em4wu12(&mut self) -> EM4WU12_W {
EM4WU12_W { w: self }
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type CONDITION_OPERATION = i32;
pub const COP_IMPLICIT: CONDITION_OPERATION = 0i32;
pub const COP_EQUAL: CONDITION_OPERATION = 1i32;
pub const COP_NOTEQUAL: CONDITION_OPERATION = 2i32;
pub const COP_LESSTHAN: CONDITION_OPERATION = 3i32;
pub const COP_GREATERTHAN: CONDITION_OPERATION = 4i32;
pub const COP_LESSTHANOREQUAL: CONDITION_OPERATION = 5i32;
pub const COP_GREATERTHANOREQUAL: CONDITION_OPERATION = 6i32;
pub const COP_VALUE_STARTSWITH: CONDITION_OPERATION = 7i32;
pub const COP_VALUE_ENDSWITH: CONDITION_OPERATION = 8i32;
pub const COP_VALUE_CONTAINS: CONDITION_OPERATION = 9i32;
pub const COP_VALUE_NOTCONTAINS: CONDITION_OPERATION = 10i32;
pub const COP_DOSWILDCARDS: CONDITION_OPERATION = 11i32;
pub const COP_WORD_EQUAL: CONDITION_OPERATION = 12i32;
pub const COP_WORD_STARTSWITH: CONDITION_OPERATION = 13i32;
pub const COP_APPLICATION_SPECIFIC: CONDITION_OPERATION = 14i32;
pub type CONDITION_TYPE = i32;
pub const CT_AND_CONDITION: CONDITION_TYPE = 0i32;
pub const CT_OR_CONDITION: CONDITION_TYPE = 1i32;
pub const CT_NOT_CONDITION: CONDITION_TYPE = 2i32;
pub const CT_LEAF_CONDITION: CONDITION_TYPE = 3i32;
|
pub mod bytecode;
pub mod classpath;
pub mod cmd;
mod classfile; |
use std::collections::HashMap;
use crate::{
utils::log::Log,
scene::{
node::Node,
base::AsBase,
},
core::{
pool::{
Handle,
Pool,
PoolIterator,
PoolIteratorMut,
PoolPairIterator,
PoolPairIteratorMut,
},
math::{
mat4::Mat4,
vec3::Vec3,
vec2::Vec2
},
visitor::{
Visit,
Visitor,
VisitResult
},
}
};
pub struct Graph {
root: Handle<Node>,
pool: Pool<Node>,
stack: Vec<Handle<Node>>,
}
impl Default for Graph {
fn default() -> Self {
Self {
root: Handle::NONE,
pool: Pool::new(),
stack: Vec::new(),
}
}
}
impl Graph {
/// Creates new graph instance with single root node.
pub fn new() -> Self {
let mut pool: Pool<Node> = Pool::new();
let mut root = Node::Base(Default::default());
root.base_mut().set_name("__ROOT__");
let root = pool.spawn(root);
Self {
stack: Vec::new(),
root,
pool,
}
}
/// Adds new node to the graph. Node will be transferred into implementation-defined
/// storage and you'll get a handle to the node. Node will be automatically attached
/// to root node of graph, it is required because graph can contain only one root.
#[inline]
pub fn add_node(&mut self, node: Node) -> Handle<Node> {
let handle = self.pool.spawn(node);
self.link_nodes(handle, self.root);
handle
}
/// Tries to borrow shared reference to a node by specified handle. Will panic if handle
/// is invalid. Handle can be invalid for either because its index out-of-bounds or generation
/// of handle does not match generation of node.
pub fn get(&self, node: Handle<Node>) -> &Node {
self.pool.borrow(node)
}
/// Tries to borrow mutable reference to a node by specified handle. Will panic if handle
/// is invalid. Handle can be invalid for either because its index out-of-bounds or generation
/// of handle does not match generation of node.
pub fn get_mut(&mut self, node: Handle<Node>) -> &mut Node {
self.pool.borrow_mut(node)
}
/// Tries to borrow mutable references to two nodes at the same time by given handles. Will
/// return Err of handles overlaps (points to same node).
pub fn get_two_mut(&mut self, nodes: (Handle<Node>, Handle<Node>))
-> (&mut Node, &mut Node) {
self.pool.borrow_two_mut(nodes)
}
/// Tries to borrow mutable references to three nodes at the same time by given handles. Will
/// return Err of handles overlaps (points to same node).
pub fn get_three_mut(&mut self, nodes: (Handle<Node>, Handle<Node>, Handle<Node>))
-> (&mut Node, &mut Node, &mut Node) {
self.pool.borrow_three_mut(nodes)
}
/// Tries to borrow mutable references to four nodes at the same time by given handles. Will
/// return Err of handles overlaps (points to same node).
pub fn get_four_mut(&mut self, nodes: (Handle<Node>, Handle<Node>, Handle<Node>, Handle<Node>))
-> (&mut Node, &mut Node, &mut Node, &mut Node) {
self.pool.borrow_four_mut(nodes)
}
/// Returns root node of current graph.
pub fn get_root(&self) -> Handle<Node> {
self.root
}
/// Destroys node and its children recursively.
#[inline]
pub fn remove_node(&mut self, node_handle: Handle<Node>) {
self.unlink_internal(node_handle);
self.stack.clear();
self.stack.push(node_handle);
while let Some(handle) = self.stack.pop() {
let base = self.pool.borrow(handle).base();
for child in base.children().iter() {
self.stack.push(*child);
}
self.pool.free(handle);
}
}
fn unlink_internal(&mut self, node_handle: Handle<Node>) {
// Replace parent handle of child
let node = self.pool.borrow_mut(node_handle);
let parent_handle = node.base().parent;
node.base_mut().parent = Handle::NONE;
// Remove child from parent's children list
if parent_handle.is_some() {
let parent = self.pool.borrow_mut(parent_handle);
if let Some(i) = parent.base().children().iter().position(|h| *h == node_handle) {
parent.base_mut().children.remove(i);
}
}
}
/// Links specified child with specified parent.
#[inline]
pub fn link_nodes(&mut self, child_handle: Handle<Node>, parent_handle: Handle<Node>) {
self.unlink_internal(child_handle);
let child = self.pool.borrow_mut(child_handle);
child.base_mut().parent = parent_handle;
let parent = self.pool.borrow_mut(parent_handle);
parent.base_mut().children.push(child_handle);
}
/// Unlinks specified node from its parent and attaches it to root graph node.
#[inline]
pub fn unlink_node(&mut self, node_handle: Handle<Node>) {
self.unlink_internal(node_handle);
self.link_nodes(node_handle, self.root);
self.get_mut(node_handle)
.base_mut()
.local_transform_mut()
.set_position(Vec3::ZERO);
}
/// Tries to find a copy of `node_handle` in hierarchy tree starting from `root_handle`.
pub fn find_copy_of(&self, root_handle: Handle<Node>, node_handle: Handle<Node>) -> Handle<Node> {
let root = self.pool.borrow(root_handle);
if root.base().original_handle() == node_handle {
return root_handle;
}
for child_handle in root.base().children() {
let out = self.find_copy_of(*child_handle, node_handle);
if out.is_some() {
return out;
}
}
Handle::NONE
}
/// Searches node with specified name starting from specified node. If nothing was found,
/// [`Handle::NONE`] is returned.
pub fn find_by_name(&self, root_node: Handle<Node>, name: &str) -> Handle<Node> {
let base = self.pool.borrow(root_node).base();
if base.name() == name {
root_node
} else {
let mut result: Handle<Node> = Handle::NONE;
for child in base.children() {
let child_handle = self.find_by_name(*child, name);
if !child_handle.is_none() {
result = child_handle;
break;
}
}
result
}
}
/// Searches node with specified name starting from root. If nothing was found, `Handle::NONE`
/// is returned.
pub fn find_by_name_from_root(&self, name: &str) -> Handle<Node> {
self.find_by_name(self.root, name)
}
/// Creates deep copy of node with all children. This is relatively heavy operation!
/// In case if any error happened it returns `Handle::NONE`. This method can be used
/// to create exact copy of given node hierarchy. For example you can prepare rocket
/// model: case of rocket will be mesh, and fire from nozzle will be particle system,
/// and when you fire from rocket launcher you just need to create a copy of such
/// "prefab".
///
/// # Notes
///
/// This method does *not* copy any animations! You have to copy them manually. In most
/// cases it is fine to retarget animation from a resource you want, it will create
/// animation copy from resource that will work with your nodes hierarchy.
///
/// # Implementation notes
///
/// This method automatically remaps bones for copied surfaces.
pub fn copy_node(&self, node_handle: Handle<Node>, dest_graph: &mut Graph) -> Handle<Node> {
let mut old_new_mapping: HashMap<Handle<Node>, Handle<Node>> = HashMap::new();
let root_handle = self.copy_node_raw(node_handle, dest_graph, &mut old_new_mapping);
// Iterate over instantiated nodes and remap bones handles.
for (_, new_node_handle) in old_new_mapping.iter() {
if let Node::Mesh(mesh) = dest_graph.pool.borrow_mut(*new_node_handle) {
for surface in mesh.surfaces_mut() {
for bone_handle in surface.bones.iter_mut() {
if let Some(entry) = old_new_mapping.get(bone_handle) {
*bone_handle = *entry;
}
}
}
}
}
root_handle
}
fn copy_node_raw(&self, root_handle: Handle<Node>, dest_graph: &mut Graph, old_new_mapping: &mut HashMap<Handle<Node>, Handle<Node>>) -> Handle<Node> {
let src_node = self.pool.borrow(root_handle);
let mut dest_node = src_node.clone();
dest_node.base_mut().original = root_handle;
let dest_copy_handle = dest_graph.add_node(dest_node);
old_new_mapping.insert(root_handle, dest_copy_handle);
for src_child_handle in src_node.base().children() {
let dest_child_handle = self.copy_node_raw(*src_child_handle, dest_graph, old_new_mapping);
if !dest_child_handle.is_none() {
dest_graph.link_nodes(dest_child_handle, dest_copy_handle);
}
}
dest_copy_handle
}
/// Searches root node in given hierarchy starting from given node. This method is used
/// when you need to find a root node of a model in complex graph.
fn find_model_root(&self, from: Handle<Node>) -> Handle<Node> {
let mut model_root_handle = from;
while model_root_handle.is_some() {
let model_node = self.pool.borrow(model_root_handle).base();
if model_node.parent().is_none() {
// We have no parent on node, then it must be root.
return model_root_handle;
}
if model_node.is_resource_instance() {
return model_root_handle;
}
// Continue searching up on hierarchy.
model_root_handle = model_node.parent();
}
model_root_handle
}
pub(in crate) fn resolve(&mut self) {
Log::writeln("Resolving graph...".to_owned());
self.update_transforms();
// Resolve original handles. Original handle is a handle to a node in resource from which
// a node was instantiated from. We can resolve it only by names of nodes, but this is not
// reliable way of doing this, because some editors allow nodes to have same names for
// objects, but here we'll assume that modellers will not create models with duplicated
// names.
for node in self.pool.iter_mut() {
let base = node.base_mut();
if let Some(model) = base.resource() {
let model = model.lock().unwrap();
for (handle, resource_node) in model.get_scene().graph.pair_iter() {
if resource_node.base().name() == base.name() {
base.original = handle;
base.inv_bind_pose_transform = resource_node.base().inv_bind_pose_transform();
break;
}
}
}
}
Log::writeln("Original handles resolved!".to_owned());
// Taking second reference to self is safe here because we need it only
// to iterate over graph and find copy of bone node. We won't modify pool
// while iterating over it, so it is double safe.
let graph = unsafe { &*(self as *const Graph) };
// Then iterate over all scenes and resolve changes in surface data, remap bones, etc.
// This step is needed to take correct graphical data from resource, we do not store
// meshes in save files, just references to resource this data was taken from. So on
// resolve stage we just copying surface from resource, do bones remapping. Bones remapping
// is required stage because we copied surface from resource and bones are mapped to nodes
// in resource, but we must have them mapped to instantiated nodes on scene. To do that
// we'll try to find a root for each node, and starting from it we'll find corresponding
// bone nodes. I know that this sounds too confusing but try to understand it.
for (node_handle, node) in self.pool.pair_iter_mut() {
if let Node::Mesh(mesh) = node {
let root_handle = graph.find_model_root(node_handle);
let node_name = String::from(mesh.base().name());
if let Some(model) = mesh.base().resource() {
let model = model.lock().unwrap();
let resource_node_handle = model.find_node_by_name(node_name.as_str());
if let Node::Mesh(resource_mesh) = model.get_scene().graph.get(resource_node_handle) {
// Copy surfaces from resource and assign to meshes.
mesh.clear_surfaces();
for resource_surface in resource_mesh.surfaces() {
mesh.add_surface(resource_surface.clone());
}
// Remap bones
for surface in mesh.surfaces_mut() {
for bone_handle in surface.bones.iter_mut() {
*bone_handle = graph.find_copy_of(root_handle, *bone_handle);
}
}
}
}
}
}
Log::writeln("Graph resolved successfully!".to_owned());
}
pub fn update_transforms(&mut self) {
// Calculate transforms on nodes
self.stack.clear();
self.stack.push(self.root);
while let Some(handle) = self.stack.pop() {
// Calculate local transform and get parent handle
let parent_handle = self.pool.borrow_mut(handle).base().parent();
let (parent_global_transform, parent_visibility) =
if parent_handle.is_some() {
let parent = self.pool.borrow(parent_handle).base();
(parent.global_transform(), parent.global_visibility())
} else {
(Mat4::IDENTITY, true)
};
let base = self.pool.borrow_mut(handle).base_mut();
base.global_transform = parent_global_transform * base.local_transform().matrix();
base.global_visibility = parent_visibility && base.visibility();
// Queue children and continue traversal on them
for child_handle in base.children() {
self.stack.push(child_handle.clone());
}
}
}
pub fn is_valid_handle(&self, node_handle: Handle<Node>) -> bool {
self.pool.is_valid_handle(node_handle)
}
pub fn update_nodes(&mut self, frame_size: Vec2, dt: f32) {
self.update_transforms();
for node in self.pool.iter_mut() {
if let Some(lifetime) = node.base().lifetime() {
node.base_mut().set_lifetime(lifetime - dt);
}
match node {
Node::Camera(camera) => camera.calculate_matrices(frame_size),
Node::ParticleSystem(particle_system) => particle_system.update(dt),
_ => ()
}
}
for i in 0..self.pool.get_capacity() {
let remove = if let Some(node) = self.pool.at(i) {
if let Some(lifetime) = node.base().lifetime() {
lifetime <= 0.0
} else {
false
}
} else {
continue;
};
if remove {
self.remove_node(self.pool.handle_from_index(i));
}
}
}
/// Creates an iterator that has linear iteration order over internal collection
/// of nodes. It does *not* perform any tree traversal!
pub fn linear_iter(&self) -> PoolIterator<Node> {
self.pool.iter()
}
/// Creates an iterator that has linear iteration order over internal collection
/// of nodes. It does *not* perform any tree traversal!
pub fn linear_iter_mut(&mut self) -> PoolIteratorMut<Node> {
self.pool.iter_mut()
}
/// Creates new iterator that iterates over internal collection giving (handle; node) pairs.
pub fn pair_iter(&self) -> PoolPairIterator<Node> {
self.pool.pair_iter()
}
/// Creates new iterator that iterates over internal collection giving (handle; node) pairs.
pub fn pair_iter_mut(&mut self) -> PoolPairIteratorMut<Node> {
self.pool.pair_iter_mut()
}
/// Create graph depth traversal iterator.
///
/// # Notes
///
/// This method allocates temporal array so it is not cheap! Should not be
/// used on each frame.
pub fn traverse_iter(&self, from: Handle<Node>) -> GraphTraverseIterator {
GraphTraverseIterator {
graph: self,
stack: vec![from],
}
}
/// Create graph depth traversal iterator which will emit *handles* to nodes.
///
/// # Notes
///
/// This method allocates temporal array so it is not cheap! Should not be
/// used on each frame.
pub fn traverse_handle_iter(&self, from: Handle<Node>) -> GraphHandleTraverseIterator {
GraphHandleTraverseIterator {
graph: self,
stack: vec![from],
}
}
}
pub struct GraphTraverseIterator<'a> {
graph: &'a Graph,
stack: Vec<Handle<Node>>,
}
impl<'a> Iterator for GraphTraverseIterator<'a> {
type Item = &'a Node;
fn next(&mut self) -> Option<Self::Item> {
if let Some(handle) = self.stack.pop() {
let node = self.graph.get(handle);
for child_handle in node.base().children() {
self.stack.push(*child_handle);
}
return Some(node);
}
None
}
}
pub struct GraphHandleTraverseIterator<'a> {
graph: &'a Graph,
stack: Vec<Handle<Node>>,
}
impl<'a> Iterator for GraphHandleTraverseIterator<'a> {
type Item = Handle<Node>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(handle) = self.stack.pop() {
for child_handle in self.graph.get(handle).base().children() {
self.stack.push(*child_handle);
}
return Some(handle);
}
None
}
}
impl Visit for Graph {
fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
visitor.enter_region(name)?;
// Pool must be empty, otherwise handles will be invalid and everything will blow up.
if visitor.is_reading() && self.pool.get_capacity() != 0 {
panic!("Graph pool must be empty on load!")
}
self.root.visit("Root", visitor)?;
self.pool.visit("Pool", visitor)?;
visitor.leave_region()
}
}
#[cfg(test)]
mod test {
use crate::{
scene::{
graph::Graph,
node::Node,
base::Base,
},
core::pool::Handle
};
#[test]
fn graph_init_test() {
let graph = Graph::new();
assert_ne!(graph.root, Handle::NONE);
assert_eq!(graph.pool.alive_count(), 1);
}
#[test]
fn graph_node_test() {
let mut graph = Graph::new();
let a = graph.add_node(Node::Base(Base::default()));
let b = graph.add_node(Node::Base(Base::default()));
let c = graph.add_node(Node::Base(Base::default()));
assert_eq!(graph.pool.alive_count(), 4);
}
} |
fn main() {
let some_u8_value: Option<u32> = Some(3);
// Using match
match some_u8_value {
Some(3) => println!("Oh, this is three."),
_ => println!("Can't read this value.")
}
// Using if let syntax
if let Some(3) = some_u8_value {
println!("Oh, this is three.");
} else {
println!("Can't read this value.");
}
}
|
use std::iter::IntoIterator;
use std::iter::Iterator;
#[derive(Copy,Clone)]
pub struct NewStruct {
field1: i32,
field2: i32,
field3: i32,
field4: i32,
field5: i32,
}
pub struct NewStructIntoIter {
count: usize,
new_struct: NewStruct,
}
impl IntoIterator for NewStruct {
type Item = i32;
type IntoIter = NewStructIntoIter;
fn into_iter( self: NewStruct ) -> NewStructIntoIter {
NewStructIntoIter {
count: 0 as usize,
new_struct: self,
}
}
}
// The above was from the previous src1.rs file excluding comments
// Here is the Iterator trait definition for reference
/* pub trait Iterator {
*
* type Item;
*
* fn next<'a>( self: &'a mut Self ) -> Option<Self::Item>;
*
* ... (loads of other functions, the other functions are called iterator adapters)
* }
*/
// The next method takes a mutable reference -- so it can update our `tracking` variable such as a counter
// or length which we use to track the progress of the iteration and returns an Optional value, either an
// item from our object or None. Once `next` returns None the iteration is done. Please read the explanation.txt
// doc in the foler to see the expansion of the for loop syntax to see why.
impl Iterator for NewStructIntoIter {
type Item = i32;
fn next<'a>( self: &'a mut Self ) -> Option<i32> { // removed syntatic sugar of &'a mut self and added the lifetime param
// first we are going to bump the count by 1 since IntoIterator initially set it to zero
// also, note this is why next takes a mutable reference, so we can do these types of update operations
self.count += 1;
// now match on the count to see where we are in the iteration process. You can either do cascading if/else or match
match self.count {
1 => { Some(self.new_struct.field1) }, // if the count is one return the first field of the base structure
2 => { Some(self.new_struct.field2) }, // there is nothing dictating how this should be done, it is user defined
3 => { Some(self.new_struct.field3) },
4 => { Some(self.new_struct.field4) },
5 => { Some(self.new_struct.field5) },
_ => { None },
}
// once our count exceeds 5 the for loop will halt operations
}
}
// With IntoIterator defined for NewStruct and Iterator defined for NewStructIntoIterator we can now use the for loop syntax
fn main() -> () {
let n: NewStruct = NewStruct {
field1: 1,
field2: 2,
field3: 3,
field4: 4,
field5: 5,
};
for x in n {
println!( "{}", x );
}
// NOTE: you can also write the first line of the for loop as "for x in n.into_iter()" as well
}
// This code prints the field values of the NewStruct object n
// 1
// 2
// 3
// 4
// 5
|
// Definition for a binary tree node.
use std::mem;
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::VecDeque;
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None
}
}
}
pub fn vector2tree(v: &Vec<i32>, tree: &mut Vec<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
//println!("tree[0] is {:?}\n", tree[0]);
if v.len() < 1 { return None; }
let mut idx : usize = 0;
let mut node : Rc<RefCell<TreeNode>> = Rc::clone(&tree[idx]);
node.borrow_mut().val = v[idx];
idx += 1;
let mut vnodes : VecDeque<Rc<RefCell<TreeNode>>> = VecDeque::new();
vnodes.push_back(node);
while idx < v.len() {
node = vnodes.pop_front().unwrap();
if v[idx] != -1 {
tree[idx].borrow_mut().val = v[idx];
node.borrow_mut().left = Some(Rc::clone(&tree[idx]));
vnodes.push_back(Rc::clone(&tree[idx]));
//println!("node.val({}) has a left child with value {}", node.borrow().val, tree[idx].borrow().val);
} //else { println!("node.val({}) has no left child", node.borrow().val); }
idx += 1;
if idx < v.len() && v[idx] != -1 {
tree[idx].borrow_mut().val = v[idx];
node.borrow_mut().right = Some(Rc::clone(&tree[idx]));
vnodes.push_back(Rc::clone(&tree[idx]));
//println!("node.val({}) has a right child with value {}", node.borrow().val, tree[idx].borrow().val);
} //else { println!("node.val({}) has no right child", node.borrow().val); }
idx += 1;
}
Some(tree[0].clone())
}
pub fn tree2vector(root : Rc<RefCell<TreeNode>>, v: &mut Vec<i32>) {
let mut layer : Vec<Option<Rc<RefCell<TreeNode>>>> = Vec::new();
let mut nextlayer : Vec<Option<Rc<RefCell<TreeNode>>>> = Vec::new();
layer.push(Some(root));
let (mut nodecount, mut next_nodecount) = (0, 0);
while ! layer.is_empty() {
let node = layer.pop().unwrap();
if node.is_none() {
if nodecount > 0 || next_nodecount != 0 {
v.push(-1);
}
}
else {
let n = node.unwrap();
v.push(n.borrow().val);
if !n.borrow_mut().left.is_none() { next_nodecount += 1; }
if !n.borrow_mut().right.is_none() { next_nodecount += 1; }
nextlayer.push(n.borrow().left.clone());
nextlayer.push(n.borrow().right.clone());
nodecount -= 1;
}
if layer.is_empty() {
/* swap the queues */
mem::swap(&mut layer, &mut nextlayer);
if next_nodecount > 0 {
nodecount = next_nodecount;
}
next_nodecount = 0;
}
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::sync::Arc;
use common_exception::Result;
use crate::interpreters::access::PrivilegeAccess;
use crate::interpreters::ManagementModeAccess;
use crate::sessions::QueryContext;
use crate::sql::plans::Plan;
#[async_trait::async_trait]
pub trait AccessChecker: Sync + Send {
// Check the access permission for the plan.
async fn check(&self, _plan: &Plan) -> Result<()>;
}
pub struct Accessor {
accessors: HashMap<String, Box<dyn AccessChecker>>,
}
impl Accessor {
pub fn create(ctx: Arc<QueryContext>) -> Self {
let mut accessors: HashMap<String, Box<dyn AccessChecker>> = Default::default();
accessors.insert("management".to_string(), ManagementModeAccess::create());
accessors.insert("privilege".to_string(), PrivilegeAccess::create(ctx));
Accessor { accessors }
}
pub async fn check(&self, plan: &Plan) -> Result<()> {
for accessor in self.accessors.values() {
accessor.check(plan).await?;
}
Ok(())
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
super::typeface::{Collection as TypefaceCollection, TypefaceInfoAndCharSet},
fidl_fuchsia_fonts::GenericFontFamily,
unicase::UniCase,
};
#[derive(Debug)]
pub enum FamilyOrAlias {
Family(FontFamily),
/// Represents an alias to a `Family` whose name is the associated [`UniCase`]`<`[`String`]`>`.
Alias(UniCase<String>),
}
#[derive(Debug)]
pub struct FontFamily {
pub name: String,
pub faces: TypefaceCollection,
pub generic_family: Option<GenericFontFamily>,
}
impl FontFamily {
pub fn new(name: String, generic_family: Option<GenericFontFamily>) -> FontFamily {
FontFamily { name, faces: TypefaceCollection::new(), generic_family }
}
/// Get owned copies of the family's typefaces as `TypefaceInfo`
pub fn extract_faces<'a>(&'a self) -> impl Iterator<Item = TypefaceInfoAndCharSet> + 'a {
// Convert Vec<Arc<Typeface>> to Vec<TypefaceInfo>
self.faces
.faces
.iter()
// Copy most fields from `Typeface` and use the canonical family name
.map(move |face| TypefaceInfoAndCharSet::from_typeface(face, self.name.clone()))
}
}
|
use std::env;
use regex::{Regex,Captures};
use std::iter::Iterator;
use std::fs;
use std::io::{self,Read};
use std::process::exit;
fn envsubst(s: &String) -> String {
let re = Regex::new("\\$(\\w+)").unwrap();
re.replace_all(s, |caps: &Captures| {
let var = &caps[1];
env::var(var)
.expect(format!("Invalid variable ${}", var).as_str())
.to_string()
}).to_string()
}
fn main() {
let args: Vec<String> = env::args().collect();
let mut content: String;
if args.len() > 1{
let input_file_path = &args[1];
content = match fs::read_to_string(input_file_path){
Ok(c) => c,
Err(_err) => {
println!("File not found: {}", input_file_path);
exit(1);
}
}
} else {
content = String::new();
match io::stdin().read_to_string(&mut content) {
Ok(_) => {},
Err(_err) => {
println!("Expecting stdin content or filepath argument");
exit(1);
}
}
}
println!("{}", envsubst(&content));
}
|
use minifb::{Key, Window, WindowOptions, MouseMode, MouseButton};
use image::RgbaImage;
pub trait ViewerStrategy {
fn mouse_move(&self, x: f32, y: f32);
fn mouse_pressed(&mut self, x: f32, y: f32, button: MouseButton);
fn mouse_wheel(dx: u32, dy: u32, is_direction_normal: bool);
fn key_pressed(&self, key: minifb::Key);
fn redraw(&mut self, img: &mut RgbaImage);
fn new() -> Self;
}
pub struct Viewer<S: ViewerStrategy> {
pub redraw_next: bool,
window: Window,
buffer: RgbaImage,
pub s: S,
}
impl<S: ViewerStrategy> Viewer<S> {
pub fn new(window_name: &str, w: usize, h: usize) -> Self {
let window = Window::new(window_name, w, h, WindowOptions::default())
.unwrap_or_else(|e| panic!("{}", e));
let buffer = RgbaImage::new(w as u32, h as u32);
Self {
redraw_next: true,
window,
buffer,
s: S::new(),
}
}
pub fn resize(w: u32, h: u32) {}
pub fn update(&mut self) {
if !self.redraw_next {
return;
}
self.redraw_next = false;
self.s.redraw(&mut self.buffer);
}
pub fn launch(&mut self, redraw_interval: std::time::Duration) {
self.window.limit_update_rate(Some(redraw_interval));
while self.window.is_open() && !self.window.is_key_down(Key::Escape) {
self.window.get_mouse_pos(MouseMode::Discard).map(|(x, y)| {
self.s.mouse_move(x, y);
if self.window.get_mouse_down(MouseButton::Left) {
self.s.mouse_pressed(x, y, MouseButton::Left);
self.redraw_next = true;
} else if self.window.get_mouse_down(MouseButton::Right) {
self.s.mouse_pressed(x, y, MouseButton::Right);
self.redraw_next = true;
}
});
self.window.get_keys_pressed(minifb::KeyRepeat::No).map(|keys| {
for key in keys {
self.s.key_pressed(key)
}
});
let linear_buffer = &self.buffer.pixels().into_iter().map(| pixel| {
let color: u32 = (pixel[3] as u32) << 24
| (pixel[0] as u32) << 16
| (pixel[1] as u32) << 8
| pixel[2] as u32;
color
}).collect::<Vec<u32>>();
self.update();
let w = self.buffer.width() as usize;
let h = self.buffer.height() as usize;
self.window.update_with_buffer(&linear_buffer, w, h).unwrap();
}
}
}
|
#[doc = "Reader of register CSR"]
pub type R = crate::R<u32, super::CSR>;
#[doc = "Reader of field `AWD1`"]
pub type AWD1_R = crate::R<bool, bool>;
#[doc = "Reader of field `EOC1`"]
pub type EOC1_R = crate::R<bool, bool>;
#[doc = "Reader of field `JEOC1`"]
pub type JEOC1_R = crate::R<bool, bool>;
#[doc = "Reader of field `JSTRT1`"]
pub type JSTRT1_R = crate::R<bool, bool>;
#[doc = "Reader of field `STRT1`"]
pub type STRT1_R = crate::R<bool, bool>;
#[doc = "Reader of field `OVR1`"]
pub type OVR1_R = crate::R<bool, bool>;
#[doc = "Reader of field `ADONS1`"]
pub type ADONS1_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Analog watchdog flag of the ADC"]
#[inline(always)]
pub fn awd1(&self) -> AWD1_R {
AWD1_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - End of conversion of the ADC"]
#[inline(always)]
pub fn eoc1(&self) -> EOC1_R {
EOC1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Injected channel end of conversion of the ADC"]
#[inline(always)]
pub fn jeoc1(&self) -> JEOC1_R {
JEOC1_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Injected channel Start flag of the ADC"]
#[inline(always)]
pub fn jstrt1(&self) -> JSTRT1_R {
JSTRT1_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Regular channel Start flag of the ADC"]
#[inline(always)]
pub fn strt1(&self) -> STRT1_R {
STRT1_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Overrun flag of the ADC"]
#[inline(always)]
pub fn ovr1(&self) -> OVR1_R {
OVR1_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - ADON Status of ADC1"]
#[inline(always)]
pub fn adons1(&self) -> ADONS1_R {
ADONS1_R::new(((self.bits >> 6) & 0x01) != 0)
}
}
|
/// HTTP request message
pub mod request;
/// HTTP response message
pub mod response;
/// HTTP header fields
pub mod headers;
/// HTTP server
pub mod server;
/// HTTP server handlers
pub mod handlers;
pub use http::server::Server;
pub use http::request::Request;
pub use http::response::Response;
|
use proc_macro::TokenStream;
use quote::quote;
use syn::{
parse::{Parse, ParseStream},
parse_macro_input,
spanned::Spanned,
FnArg, Ident, ImplItemMethod, Pat, Type,
};
type Res<T> = syn::parse::Result<T>;
pub fn wrapped_tramp(attr: TokenStream, item: TokenStream) -> TokenStream {
let TrampArgs { wrapper } = parse_macro_input!(attr as TrampArgs);
let meth: ImplItemMethod = parse_macro_input!(item as ImplItemMethod);
crate::error::wrap(wrapped_tramp_with_type(wrapper, meth))
}
pub fn defer_tramp(attr: TokenStream, item: TokenStream) -> TokenStream {
let TrampArgs { wrapper } = parse_macro_input!(attr as TrampArgs);
let meth: ImplItemMethod = parse_macro_input!(item as ImplItemMethod);
crate::error::wrap(wrapped_defer_tramp_with_type(wrapper, meth))
}
pub fn wrapped_sel_list_tramp(attr: TokenStream, item: TokenStream) -> TokenStream {
let TrampArgs { wrapper } = parse_macro_input!(attr as TrampArgs);
let meth: ImplItemMethod = parse_macro_input!(item as ImplItemMethod);
crate::error::wrap(wrapped_sel_list_tramp_with_type(wrapper, meth))
}
// tramp still has selector, but it isn't passed on to wrapped method
pub fn wrapped_list_tramp(attr: TokenStream, item: TokenStream) -> TokenStream {
let TrampArgs { wrapper } = parse_macro_input!(attr as TrampArgs);
let meth: ImplItemMethod = parse_macro_input!(item as ImplItemMethod);
crate::error::wrap(wrapped_list_tramp_with_type(wrapper, meth))
}
pub fn wrapped_attr_get_tramp(attr: TokenStream, item: TokenStream) -> TokenStream {
let TrampArgs { wrapper } = parse_macro_input!(attr as TrampArgs);
let meth: ImplItemMethod = parse_macro_input!(item as ImplItemMethod);
crate::error::wrap(wrapped_attr_get_tramp_with_type(wrapper, meth))
}
pub fn wrapped_attr_set_tramp(attr: TokenStream, item: TokenStream) -> TokenStream {
let TrampArgs { wrapper } = parse_macro_input!(attr as TrampArgs);
let meth: ImplItemMethod = parse_macro_input!(item as ImplItemMethod);
crate::error::wrap(wrapped_attr_set_tramp_with_type(wrapper, meth))
}
struct Names {
meth_name: Ident,
tramp_name: Ident,
}
fn get_names(meth: &ImplItemMethod) -> Names {
let meth_name = meth.sig.ident.clone();
let tramp_name = Ident::new(
&format!("{}_tramp", meth_name.to_string()),
meth_name.span(),
);
Names {
meth_name,
tramp_name,
}
}
pub fn wrapped_tramp_with_type(t: Type, meth: ImplItemMethod) -> Res<TokenStream> {
let Names {
meth_name,
tramp_name,
} = get_names(&meth);
//get args, skip self
let args: Vec<&FnArg> = meth.sig.inputs.iter().skip(1).collect();
let vars = args
.iter()
.map(|a| match a {
FnArg::Receiver(r) => Err(syn::Error::new(
r.span(),
format!("unexpected type in signature"),
)),
FnArg::Typed(t) => Ok(t.clone().pat),
})
.collect::<Result<Vec<Box<Pat>>, _>>()?;
let expanded = quote! {
pub extern "C" fn #tramp_name(wrapper: &#t, #(#args)*) {
::median::wrapper::WrapperWrapped::wrapped(wrapper).#meth_name(#(#vars)*)
}
#meth
};
Ok(expanded.into())
}
pub fn wrapped_defer_tramp_with_type(t: Type, meth: ImplItemMethod) -> Res<TokenStream> {
let Names {
meth_name,
tramp_name,
} = get_names(&meth);
//TODO check signature
//TODO allow for no sym and or no atoms
let expanded = quote! {
pub extern "C" fn #tramp_name(
wrapper: &#t,
sel: *mut ::median::max_sys::t_symbol,
ac: ::std::os::raw::c_long,
av: *const ::median::max_sys::t_atom,
) {
median::method::sel_list(sel, ac, av, |sym, atoms| {
::median::wrapper::WrapperWrapped::wrapped(wrapper).#meth_name(&sym, atoms);
});
}
#meth
};
Ok(expanded.into())
}
pub fn wrapped_sel_list_tramp_with_type(t: Type, meth: ImplItemMethod) -> Res<TokenStream> {
let Names {
meth_name,
tramp_name,
} = get_names(&meth);
//TODO check signature
let expanded = quote! {
pub extern "C" fn #tramp_name(
wrapper: &#t,
sel: *mut ::median::max_sys::t_symbol,
ac: ::std::os::raw::c_long,
av: *const ::median::max_sys::t_atom,
) {
median::method::sel_list(sel, ac, av, |sym, atoms| {
::median::wrapper::WrapperWrapped::wrapped(wrapper).#meth_name(&sym, atoms);
});
}
#meth
};
Ok(expanded.into())
}
pub fn wrapped_list_tramp_with_type(t: Type, meth: ImplItemMethod) -> Res<TokenStream> {
let Names {
meth_name,
tramp_name,
} = get_names(&meth);
//TODO check signature
let expanded = quote! {
pub extern "C" fn #tramp_name(
wrapper: &#t,
sel: *mut ::median::max_sys::t_symbol,
ac: ::std::os::raw::c_long,
av: *const ::median::max_sys::t_atom,
) {
median::method::sel_list(sel, ac, av, |_sym, atoms| {
::median::wrapper::WrapperWrapped::wrapped(wrapper).#meth_name(atoms);
});
}
#meth
};
Ok(expanded.into())
}
pub fn wrapped_attr_get_tramp_with_type(t: Type, meth: ImplItemMethod) -> Res<TokenStream> {
let Names {
meth_name,
tramp_name,
} = get_names(&meth);
//TODO check signature to make sure it has no inputs and returns a type we support
let expanded = quote! {
pub extern "C" fn #tramp_name(
wrapper: &#t,
_attr: ::std::ffi::c_void,
ac: *mut ::std::os::raw::c_long,
av: *mut *mut ::median::max_sys::t_atom,
) {
::median::attr::get(ac, av, || ::median::wrapper::WrapperWrapped::wrapped(wrapper).#meth_name());
}
#meth
};
Ok(expanded.into())
}
pub fn wrapped_attr_set_tramp_with_type(t: Type, meth: ImplItemMethod) -> Res<TokenStream> {
let Names {
meth_name,
tramp_name,
} = get_names(&meth);
//get args, skip self
let args: Vec<&FnArg> = meth.sig.inputs.iter().skip(1).collect();
let vars = args
.iter()
.map(|a| match a {
FnArg::Receiver(r) => Err(syn::Error::new(
r.span(),
format!("unexpected type in signature"),
)),
FnArg::Typed(t) => Ok(t.clone().pat),
})
.collect::<Result<Vec<Box<Pat>>, _>>()?;
//TODO check signature to make sure it has 1 input and no returns with the type we support
let expanded = quote! {
pub extern "C" fn #tramp_name(
wrapper: &#t,
_attr: ::std::ffi::c_void,
ac: ::std::os::raw::c_long,
av: *mut ::median::max_sys::t_atom,
) {
::median::attr::set(ac, av, |#(#args)*| ::median::wrapper::WrapperWrapped::wrapped(wrapper).#meth_name(#(#vars)*));
}
#meth
};
Ok(expanded.into())
}
struct TrampArgs {
pub wrapper: syn::Type,
}
impl Parse for TrampArgs {
fn parse(input: ParseStream) -> Res<Self> {
let wrapper: syn::Type = input.parse()?;
Ok(Self { wrapper })
}
}
|
//! Styling legacy Windows terminals
//!
//! See [`Console`]
//!
//! This fills a similar role as [`winapi-util`](https://crates.io/crates/winapi-util) does for
//! [`termcolor`](https://crates.io/crates/termcolor) with the differences
//! - Uses `windows-sys` rather than `winapi`
//! - Uses [`anstyle`](https://crates.io/crates/termcolor) rather than defining its own types
//! - More focused, smaller
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
mod console;
mod lockable;
mod stream;
#[cfg(windows)]
mod windows;
pub use console::Console;
pub use lockable::Lockable;
pub use stream::WinconStream;
|
// This file is part of linux-epoll. 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/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
use super::*;
include!("DataType.rs");
include!("Message.rs");
include!("MessageBitField1.rs");
include!("MessageBitField2.rs");
include!("MessageHeader.rs");
include!("MessageOpcode.rs");
include!("MessageResponseCode.rs");
include!("MessageType.rs");
include!("MetaType.rs");
include!("QueryClass.rs");
include!("QuerySectionEntry.rs");
include!("QuerySectionEntryFooter.rs");
include!("QueryType.rs");
include!("QueryTypeOrDataType.rs");
include!("ResourceData.rs");
include!("ResourceRecord.rs");
include!("ResourceRecordClass.rs");
include!("ResourceRecordFooter.rs");
include!("TcpMessage.rs");
|
/// The Olin ABI implemented for pa'i. This mostly contains rigging and other
/// internal implementation details.
/// Environment variables
pub mod env;
/// Input/Output
pub mod io;
/// Logging support
pub mod log;
/// Simple entropy
pub mod random;
/// Resources
pub mod resource;
/// Runtime interop
pub mod runtime;
/// Startup/cli args
pub mod startup;
/// Time
pub mod time;
|
//! An arbitrary precision unsigned integer.
use core::cmp::Ordering::{Equal, Greater, Less};
use std::{
fmt,
ops::{Add, AddAssign, Sub},
};
use num_bigint::BigUint;
use num_traits::{Num, Zero};
use serde;
/// An arbitrary precision unsigned integer.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Quantity(BigUint);
impl Quantity {
/// Subtracts two numbers, checking for underflow. If underflow happens, `None` is returned.
#[inline]
pub fn checked_sub(&self, other: &Quantity) -> Option<Quantity> {
// NOTE: This does not implemented the num_traits::CheckedSub trait because this forces
// one to also implement Sub which we explicitly don't want to do.
match self.0.cmp(&other.0) {
Less => None,
Equal => Some(Zero::zero()),
Greater => Some(Quantity(self.0.clone().sub(&other.0))),
}
}
}
impl Zero for Quantity {
fn zero() -> Self {
Quantity(BigUint::zero())
}
fn is_zero(&self) -> bool {
self.0.is_zero()
}
}
impl From<u64> for Quantity {
fn from(v: u64) -> Quantity {
Quantity(BigUint::from(v))
}
}
impl Add for Quantity {
type Output = Quantity;
fn add(mut self, other: Quantity) -> Quantity {
self += &other;
self
}
}
impl<'a> Add<&'a Quantity> for Quantity {
type Output = Quantity;
fn add(mut self, other: &Quantity) -> Quantity {
self += other;
self
}
}
impl<'a> AddAssign<&'a Quantity> for Quantity {
fn add_assign(&mut self, other: &Quantity) {
self.0 += &other.0;
}
}
impl fmt::Display for Quantity {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl serde::Serialize for Quantity {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let is_human_readable = serializer.is_human_readable();
if is_human_readable {
serializer.serialize_str(&self.0.to_str_radix(10))
} else {
if self.0.is_zero() {
serializer.serialize_bytes(&[])
} else {
let data = self.0.to_bytes_be();
serializer.serialize_bytes(&data)
}
}
}
}
impl<'de> serde::Deserialize<'de> for Quantity {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct BytesVisitor;
impl<'de> serde::de::Visitor<'de> for BytesVisitor {
type Value = Quantity;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("bytes or string expected")
}
fn visit_str<E>(self, data: &str) -> Result<Quantity, E>
where
E: serde::de::Error,
{
Ok(Quantity(
BigUint::from_str_radix(data, 10)
.map_err(|e| serde::de::Error::custom(format!("{}", e)))?,
))
}
fn visit_bytes<E>(self, data: &[u8]) -> Result<Quantity, E>
where
E: serde::de::Error,
{
Ok(Quantity(BigUint::from_bytes_be(data)))
}
}
if deserializer.is_human_readable() {
Ok(deserializer.deserialize_string(BytesVisitor)?)
} else {
Ok(deserializer.deserialize_bytes(BytesVisitor)?)
}
}
}
#[cfg(test)]
mod test {
use rustc_hex::ToHex;
use crate::common::{cbor, quantity::Quantity};
#[test]
fn test_serialization() {
// NOTE: These should be synced with go/common/quantity/quantity_test.go.
let cases = vec![
(0, "40"),
(1, "4101"),
(10, "410a"),
(100, "4164"),
(1000, "4203e8"),
(1000000, "430f4240"),
(18446744073709551615, "48ffffffffffffffff"),
];
for tc in cases {
let q = Quantity::from(tc.0);
let enc = cbor::to_vec(&q);
assert_eq!(enc.to_hex::<String>(), tc.1, "serialization should match");
let dec: Quantity = cbor::from_slice(&enc).expect("deserialization should succeed");
assert_eq!(dec, q, "serialization should round-trip");
}
}
}
|
use std::{env, fs, io::{stdin, Read}};
mod lexer;
mod parser;
mod runtime;
mod types;
fn lexemes(text: String) {
match lexer::lex(&mut text.chars()) {
Ok(lx) => lx
.iter()
.enumerate()
.for_each(|(i, l)| println!("{}:\n{:#?}", i, l)),
Err(err) => eprintln!("{}", err),
}
}
fn tree(text: String) {
match lexer::lex(&mut text.chars()) {
Ok(lexemes) => match parser::parse(&mut lexemes.into_iter()) {
Ok(values) => values
.iter()
.enumerate()
.for_each(|(i, v)| println!("{}:\n{:#?}", i, v)),
Err(err) => eprintln!("{}", err),
},
Err(err) => eprintln!("{}", err),
}
}
fn exec(text: String) {
match lexer::lex(&mut text.chars()) {
Ok(lexemes) => match parser::parse(&mut lexemes.into_iter()) {
Ok(values) => match runtime::execute(&mut values.into_iter()) {
Ok(_) => {}
Err(err) => {
let lines: Vec<_> = text.lines().collect();
eprintln!("Traceback:");
for position in err.traceback.iter() {
if let Some(pos) = position {
eprintln!("{}-{}", pos.0, pos.1);
eprintln!("{}", lines[pos.0 as usize - 1]);
let mut arrow = std::iter::repeat("-")
.take(pos.1 as usize - 1)
.collect::<String>();
arrow.push('^');
eprintln!("{}", arrow);
}
}
eprintln!("Exception: {:#?}", &err.thrown_object.content);
}
},
Err(err) => eprintln!("{}", err),
},
Err(err) => eprintln!("{}", err),
}
}
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() != 2 {
eprintln!("There most be 1 argument, given {}", args.len() - 1);
return;
}
let mode = &args[1];
match mode.as_str() {
"--lexemes" => {
let mut buffer = String::new();
stdin().read_to_string(&mut buffer).unwrap();
println!("Ctrl^D");
lexemes(buffer)
}
"--tree" => {
let mut buffer = String::new();
stdin().read_to_string(&mut buffer).unwrap();
println!("Ctrl^D");
tree(buffer)
}
"--exec" => {
let mut buffer = String::new();
stdin().read_to_string(&mut buffer).unwrap();
println!("Ctrl^D");
exec(buffer)
}
filename => {
let contents = fs::read_to_string(filename)
.expect("Something went wrong reading the file");
exec(contents)
},
}
}
|
//! Generating identicons.
extern crate rand;
mod data;
mod shields;
mod shapes;
pub use self::shields::{ShieldIconData, ShieldIconTreatment};
pub use self::shapes::{ShapeIconData, ShapeType};
trait RngExt {
/// Choose a random item from a collection by weight.
fn weighted_choice<T>(&mut self, choices: Vec<(T, usize)>) -> T;
}
impl<R: rand::Rng> RngExt for R {
fn weighted_choice<T>(&mut self, choices: Vec<(T, usize)>) -> T {
let sum_weights = choices.iter().map(|c| c.1).sum();
let mut choice = self.gen_range(0, sum_weights);
for (item, weight) in choices.into_iter() {
if choice < weight {
return item;
}
choice -= weight;
}
unreachable!("No items chosen");
}
}
/// An RGB color.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Color {
/// Red component
pub r: u8,
/// Blue component
pub g: u8,
/// Green component
pub b: u8,
}
impl Color {
/// Create the black color.
pub fn black() -> Self {
Self { r: 0, g: 0, b: 0 }
}
/// Create the white color.
pub fn white() -> Self {
Self { r: 255, g: 255, b: 255 }
}
/// Format this color as a CSS color.
///
/// # use identicons::icons::Color;
/// let c = Color { r: 12, g: 34, b: 56 };
/// assert_eq!(c.css_color(), "rgb(12,34,56)".to_string());
///
pub fn css_color(&self) -> String {
format!("rgb({},{},{})", self.r, self.g, self.b)
}
/// Get this color's luminance.
pub fn luminance(&self) -> f32 {
0.2126 * self.r as f32 + 0.7152 * self.g as f32 + 0.0722 * self.b as f32
}
/// Does this color contrast well with that other color?
pub fn contrasts_well(&self, other: &Self) -> bool {
(self.luminance() - other.luminance()).abs() > 75.0
}
}
|
use super::super::grouped::{GroupedOperation, GroupedOperator};
use nom_sql::SqlType;
use serde::Deserialize;
use std::collections::HashMap;
use std::convert::{TryFrom, TryInto};
use prelude::*;
use super::att3::TestCount;
#[derive(Serialize, Deserialize, Clone)]
pub enum GroupingFuncType {
TestCount(TestCount),
}
impl From<TestCount> for GroupingFuncType {
fn from(i: TestCount) -> Self {
GroupingFuncType::TestCount(i)
}
}
macro_rules! impl_grouping_udf_type {
($self:ident, $func:ident, $( $arg:ident ),* ) => {
match *$self {
GroupingFuncType::TestCount(ref mut c) => c.$func($($arg),*),
}
}
}
trait GroupingUDF {
fn visit(&mut self, item: &DataType) -> DataType;
fn unvisit(&mut self, item: &DataType) -> DataType;
}
impl GroupingUDF for TestCount {
fn visit(&mut self, _item: &DataType) -> DataType {
self.0 += 1;
self.0.into()
}
fn unvisit(&mut self, _item: &DataType) -> DataType {
self.0 -= 1;
self.0.into()
}
}
impl GroupingUDF for GroupingFuncType {
fn visit(&mut self, item: &DataType) -> DataType {
impl_grouping_udf_type!(self, visit, item)
}
fn unvisit(&mut self, item: &DataType) -> DataType {
impl_grouping_udf_type!(self, unvisit, item)
}
}
fn grouped_function_type_from_string(name: &String) -> GroupingFuncType {
match name.as_str() {
"test_count" => TestCount(0).into(),
_ => unimplemented!(),
}
}
pub fn grouped_function_from_string(parent: IndexPair, name: String) -> GroupingUDFOp {
GroupingUDFOp {
function: grouped_function_type_from_string(&name),
parent: parent,
function_name: name,
}
}
#[derive(Clone, Serialize, Deserialize)]
pub struct GroupingUDFOp {
function: GroupingFuncType,
parent: IndexPair,
function_name: String,
}
impl Ingredient for GroupingUDFOp {
fn take(&mut self) -> NodeOperator {
Clone::clone(self).into()
}
fn ancestors(&self) -> Vec<NodeIndex> {
vec![self.parent.as_global()]
}
fn on_connected(&mut self, _graph: &Graph) {
// No I need to do something here?
}
fn on_commit(&mut self, _you: NodeIndex, remap: &HashMap<NodeIndex, IndexPair>) {
self.parent.remap(remap)
}
fn on_input(
&mut self,
_executor: &mut Executor,
_from: LocalNodeIndex,
data: Records,
_tracer: &mut Tracer,
_replay_key_cols: Option<&[usize]>,
_domain: &DomainNodes,
_states: &StateMap,
) -> ProcessingResult {
let res = data
.iter()
.map(|d| {
let spin = d.is_positive();
let vals = d.rec();
assert!(vals.len() == 1);
let ref i = vals[0];
let res = if spin {
self.function.visit(i)
} else {
self.function.unvisit(i)
};
Record::from((vec![res], spin))
})
.collect();
ProcessingResult {
results: res,
..Default::default()
}
}
fn description(&self, _detailed: bool) -> String {
format!("grouping-udf:{}", self.function_name)
}
fn suggest_indexes(&self, _you: NodeIndex) -> HashMap<NodeIndex, Vec<usize>> {
HashMap::new()
}
fn resolve(&self, i: usize) -> Option<Vec<(NodeIndex, usize)>> {
Some(vec![(self.parent.as_global(), i)])
}
fn parent_columns(&self, column: usize) -> Vec<(NodeIndex, Option<usize>)> {
vec![(self.parent.as_global(), Some(column))]
}
}
|
use super::*;
impl Image {
pub(crate) fn build_parts(&self) -> Vec<String> {
let mut out = self.prefixes.clone();
let mut info = vec![
self.identifier.clone(),
self.region.to_string(),
self.size.to_string(),
self.rotation.to_string(),
format!("{}.{}", self.quality.to_string(), self.format.to_string()),
];
out.append(&mut info);
out
}
pub(crate) fn build_info_parts(&self) -> Vec<String> {
let mut out = self.prefixes.clone();
let mut info = vec![self.identifier.to_string(), "info.json".to_string()];
out.append(&mut info);
out.to_vec()
}
pub(crate) fn build_uri(self, parts: Vec<String>) -> Url {
let mut url = Url::parse(&self.host).expect("Parsing URL Host");
for part in parts {
url.path_segments_mut()
.expect("Constructing URL Parts")
.pop_if_empty()
.push(&part);
}
url
}
} |
use af;
use af::{Array, MatProp};
use std::sync::{Arc, Mutex};
use activations;
use params::Params;
use layer::Layer;
pub struct Dense {
pub input_size: usize,
pub output_size: usize,
}
impl Layer for Dense
{
fn forward(&self, params: Arc<Mutex<Params>>, inputs: &Array)-> Array
{
// get a handle to the underlying params
let mut ltex = params.lock().unwrap();
// z_t = xW + b [the bias is added in parallel for batch]
let wx = af::matmul(&inputs // activated_input
, <ex.weights[0] // layer weights
, MatProp::NONE
, MatProp::NONE);
let z_t = af::transpose(&af::add(&af::transpose(&wx, false)
, <ex.biases[0], true), false);
// a_t = sigma(z_t)
let a_t = activations::get_activation(<ex.activations[0], &z_t).unwrap();
// parameter manager keeps the output & inputs
let current_unroll = ltex.current_unroll;
if ltex.inputs.len() > current_unroll { // store in existing
ltex.inputs[current_unroll] = inputs.clone();
ltex.outputs[current_unroll] = a_t.clone();
}else{ // add new
ltex.inputs.push(inputs.clone());
ltex.outputs.push(a_t.clone());
}
// update location in vector
ltex.current_unroll += 1;
a_t.clone() // clone just increases the ref count
}
fn backward(&self, params: Arc<Mutex<Params>>, delta: &Array) -> Array {
// get a handle to the underlying params
let mut ltex = params.lock().unwrap();
let current_unroll = ltex.current_unroll;
assert!(current_unroll > 0
, "Cannot call backward pass without at least 1 forward pass");
// delta_t = (transpose(W_{t+1}) * d_{l+1}) .* dActivation(z)
// delta_{t-1} = (transpose(W_{t}) * d_{l})
let dz = activations::get_derivative(<ex.activations[0]
, <ex.outputs[current_unroll - 1]).unwrap();
let delta_t = af::mul(delta, &dz, false);
let dw = af::matmul(<ex.inputs[current_unroll - 1]
, &delta_t // delta_w = delta_t * a_{t}
, af::MatProp::TRANS
, af::MatProp::NONE);
let db = af::transpose(&af::sum(&delta_t, 0), false); // delta_b = sum_{batch}delta
ltex.deltas[0] = af::add(<ex.deltas[0], &dw, false);
ltex.deltas[1] = af::add(<ex.deltas[1], &db, false);
ltex.current_unroll -= 1;
af::matmul(&delta_t, <ex.weights[0], af::MatProp::NONE, af::MatProp::TRANS)
}
}
|
fn main() {
let tweet = Tweet {
username: String::from("ebooks"),
content: String::from("you don't know everything - read them"),
reply: false,
retweet: false,
};
println!("1 new tweet: {}", tweet.summarize());
let news = NewsArticle {
headline: String::from("Markets soar"),
location: String::from("Mumbai"),
author: String::from("Tejas"),
content: String::from("Markets on monday soared to a 52 week record high"),
};
println!("Breaking news: {}", news.summarize());
notify(tweet);
}
trait Summary {
fn summarize(&self) -> String;
}
struct Tweet {
username: String,
content: String,
reply: bool,
retweet: bool,
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
trait SummaryWithDefault {
fn summarize(&self) -> String {
String::from("(Read more...)")
}
}
struct NewsArticle {
headline: String,
location: String,
author: String,
content: String,
}
// use default implementation
impl SummaryWithDefault for NewsArticle {}
fn notify(item: impl Summary) {
println!("Breaking news! {}", item.summarize());
}
|
#[doc = "Reader of register TSCC"]
pub type R = crate::R<u32, super::TSCC>;
#[doc = "Writer for register TSCC"]
pub type W = crate::W<u32, super::TSCC>;
#[doc = "Register TSCC `reset()`'s with value 0"]
impl crate::ResetValue for super::TSCC {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `TSS`"]
pub type TSS_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TSS`"]
pub struct TSS_W<'a> {
w: &'a mut W,
}
impl<'a> TSS_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03);
self.w
}
}
#[doc = "Reader of field `TCP`"]
pub type TCP_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TCP`"]
pub struct TCP_W<'a> {
w: &'a mut W,
}
impl<'a> TCP_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16);
self.w
}
}
impl R {
#[doc = "Bits 0:1 - TSS"]
#[inline(always)]
pub fn tss(&self) -> TSS_R {
TSS_R::new((self.bits & 0x03) as u8)
}
#[doc = "Bits 16:19 - TCP"]
#[inline(always)]
pub fn tcp(&self) -> TCP_R {
TCP_R::new(((self.bits >> 16) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:1 - TSS"]
#[inline(always)]
pub fn tss(&mut self) -> TSS_W {
TSS_W { w: self }
}
#[doc = "Bits 16:19 - TCP"]
#[inline(always)]
pub fn tcp(&mut self) -> TCP_W {
TCP_W { w: self }
}
}
|
use std::cell::RefCell;
use wayland_client::protocol::wl_display::WlDisplay;
use wayland_client::protocol::{wl_compositor, wl_surface};
use wayland_client::Main;
use wayland_client::{Attached, Display, EventQueue, GlobalManager};
use wayland_protocols::wlr::unstable::layer_shell::v1::client::zwlr_layer_shell_v1::{
Layer, ZwlrLayerShellV1,
};
use wayland_protocols::wlr::unstable::layer_shell::v1::client::zwlr_layer_surface_v1::{
Anchor, Event, ZwlrLayerSurfaceV1,
};
pub struct Window {
pub display: Display,
pub events: RefCell<EventQueue>,
pub attached_display: Attached<WlDisplay>,
pub globals: GlobalManager,
pub surface: Main<wl_surface::WlSurface>,
pub layer: Main<ZwlrLayerShellV1>,
pub layer_surface: Main<ZwlrLayerSurfaceV1>,
}
unsafe impl Send for Window {}
unsafe impl Sync for Window {}
#[derive(Debug)]
pub enum WindowError {
Todo(Box<dyn std::error::Error>),
}
impl From<wayland_client::ConnectError> for WindowError {
fn from(e: wayland_client::ConnectError) -> Self {
Self::Todo(Box::new(e))
}
}
impl Window {
pub fn spawn(
width: u32,
height: u32,
offset_top: i32,
offset_left: i32,
) -> Result<Window, WindowError> {
let display = Display::connect_to_env()?;
let mut event_queue = display.create_event_queue();
let attached_display = (*display).clone().attach(event_queue.get_token());
let globals = GlobalManager::new(&attached_display);
event_queue.sync_roundtrip(|_, _| unreachable!()).unwrap();
let compositor = globals
.instantiate_exact::<wl_compositor::WlCompositor>(1)
.unwrap();
let surface = compositor.create_surface();
let layer = globals.instantiate_exact::<ZwlrLayerShellV1>(1).unwrap();
let layer_surface =
layer.get_layer_surface(&surface, None, Layer::Top, String::from("infolauncher"));
layer_surface.set_size(width, height);
layer_surface.set_anchor(Anchor::Top);
layer_surface.set_margin(offset_top, 0, 0, offset_left);
layer_surface.set_keyboard_interactivity(1);
layer_surface.assign_mono(move |layer_surface, event| match event {
Event::Configure {
width: given_width, height: given_height, serial
} => {
println!("Configuring layer surface with {}:{} -> {}", width, height, serial);
if (given_width, given_height) != (width, height) {
panic!("I was prevented by the compositor from using the appropriate window width and height");
}
layer_surface.ack_configure(serial);
}
Event::Closed => {eprintln!("Got close event!"); *super::STATUS.lock().unwrap() = super::Status::Closing},
_ => println!("Unhandled event"),
});
let _eventsn = event_queue.sync_roundtrip(|_, _| {}).unwrap();
eprintln!("Syncing after Configure event");
surface.commit();
let _eventsn = event_queue.sync_roundtrip(|_, _| {}).unwrap();
Ok(Self {
display,
events: RefCell::new(event_queue),
attached_display,
globals,
surface,
layer,
layer_surface,
})
}
}
|
//! This module contains the main source code for the circuit simulation.
//! The code for the menu, circuit solver, side panel parser are here.
//! The following is a breif overview of code flow.
//!
//! `circuit_sim` is the most important function in this module.
//! Everything happens here. `circuit_sim` requires keyboard, text and mouse information
//! structs as input. These structs contain all interactive data the application needs to run.
//! You may find the definitions of these structs in the `inputhandler` module, though it
//! should be noted that these structs are filled out on an operating system by operating
//! system bases. You may need to look into the `macos`, `windows` or `unix` modules for
//! interface details.
//!
//! The struct `app_storage` and `os_package` are also required by `circuit_sim`.
//! `app_storage` contains information specific to the simulation program that is required
//! to persist between frames. This includes circuit specifics, among other things.
//! `os_package` contains information regarding the drawing window, most importantly the window
//! backbuffer. The window backbuffer, window canvas, is an array of pixels shared
//! between this program and the operating system. Draw calls are done on the window canvas.
//! The `rendertools` contains these functions.
//!
//! ## Program structure
//!
//! `circuit_sim` begins with an initialization block, `app_storage.init`.
//! In this block application properties, and assets are initialized and configured.
//! Configuration files are also loaded in this block.
//! If you wish to incorporate more assets they should be initialized here.
//!
//! TA mode is handled shortly after.
//! TA mode give the user the ability to author content. The retractable size panel
//! and the Custom Element panel can be edited using TA mode.
//! TA mode is activated when a file with the name
//! given by `TA_FILE_NAME` is in the program's directory and the tab button is pressed.
//!
//! User created circuits, and associated circuit elements, are render next.
//! Logic relating to circuit element property panels are handled in this block as well.
//! The block has three distinct parts.
//! - Circuit element rendering, movement logic,
//! - property panel z-coordinate organization,
//! - property panel rendering and logic.
//! Z-coordinate organization refers to the order property panels are rendered and
//! which panels has inputs recognized if multiple panels overlap.
//!
//!
//! The final block handles circuit simulation. `compute_circuit` is these most
//! important function in this section. The circuit simulation is done using the
//! sparse tableau network analysis approach, using Gaussian elimination to solve the
//! resulting matrix. You can find the text [here](http://web.engr.oregonstate.edu/~karti/ece521/sta.pdf).
//!
//!
//!
#![allow(unused_must_use)]
use crate::rendertools::*;
use crate::inputhandler::*;
use crate::{WindowCanvas, OsPackage, set_icon};
use crate::stb_image_sys::{stbi_load_from_memory_32bit};
use crate::miniz;
use crate::{FONT_NOTOSANS, FONT_NOTOSANS_BOLD};
use crate::misc::*;
use crate::ui_tools;
use matrixmath::*;
#[allow(unused_attributes)]
#[macro_use]
use crate::{timeit, DEBUG_timeit};
use crate::debug_tools::*;
use std::io::prelude::*;
use std::f32::consts::PI;
use std::f32::consts::FRAC_PI_2;
use std::time::{Instant, Duration};
use rand::thread_rng;
use rand_distr::{Normal, Distribution};
use parser::*;
const WINDOW_WIDTH : i32 = 1250;
const WINDOW_HEIGHT : i32 = 750;
const IMG_RESISTOR : &[u8] = std::include_bytes!("../assets/resistor.bmp");
const IMG_BATTERY : &[u8] = std::include_bytes!("../assets/battery.bmp");
const IMG_VOLTMETER : &[u8] = std::include_bytes!("../assets/voltmeter.bmp");
const IMG_AMMETER : &[u8] = std::include_bytes!("../assets/ammeter.bmp");
const IMG_CAPACITOR : &[u8] = std::include_bytes!("../assets/capacitor.bmp");
const IMG_INDUCTOR : &[u8] = std::include_bytes!("../assets/inductor.bmp");
const IMG_SWITCH_OPEN : &[u8] = std::include_bytes!("../assets/switch_open.bmp");
const IMG_SWITCH_CLOSED : &[u8] = std::include_bytes!("../assets/switch_closed.bmp");
const IMG_AC : &[u8] = std::include_bytes!("../assets/ac.bmp");
const IMG_WIRE : &[u8] = std::include_bytes!("../assets/wire.bmp");
const IMG_CUSTOM : &[u8] = std::include_bytes!("../assets/custom_circuit_element.bmp");
const IMG_ICON : &[u8] = std::include_bytes!("../assets/sdfviewer.bmp"); //TODO this is temp
const IMG_ARROW : &[u8] = std::include_bytes!("../assets/arrow.bmp");
const IMG_SCREENSHOT : &[u8] = std::include_bytes!("../assets/screenshot_icon.bmp");
const IMG_SAVE : &[u8] = std::include_bytes!("../assets/save.bmp");
const IMG_SAVE_ALT : &[u8] = std::include_bytes!("../assets/save_alt.bmp");
const TA_FILE_NAME : &str = "TA.txt";
const CUSTOM_FILE_NAME : &str = "custom.cce";
const CUSTOM_FILE_EXT : &str = ".cce";
const CIRCUIT_PANEL_FILE_NAME : &str = "circuit_worksheet.exp";
const PANEL_FILE_EXT : &str = ".exp";
const CIRCUIT_FILE_EXT : &str = ".cd";
const TIME_STEP: f32 = 0.006;//TODO this should be frame rate independent
const MAX_SAVED_MEASURMENTS : usize = 4000;
const FONT_MERRIWEATHER_LIGHT : &[u8] = std::include_bytes!("../assets/Merriweather-Light.ttf");
const PROPERTIES_W : i32 = 280;
const PROPERTIES_H : i32 = 260;
static mut GLOBAL_PROPERTIES_Z: usize = 0;
const DEFAULT_MESSAGE_ONSCREEN_DURATION : Duration = Duration::from_millis(5100);
const ERROR_MESSAGE_ONSCREEN_DURATION : Duration = Duration::from_millis(7500);
const DELTA_MAX_TIME_PANEL_MOVE : f32 = 0.2E6;
const RUN_PAUSE_RECT : [i32; 4] = [40, 115, 150, 40];
const CLEAR_RECT : [i32; 4] = [40, 50, 150, 40];
const SELECTED_OFFSET : i32 = 50/3;
static mut CAMERA : [i32; 2] = [0, 0];
#[allow(unused)]
fn get_camera()->[i32; 2]{unsafe{
return CAMERA;
}}
#[allow(unused)]
fn get_camera_x()->i32{unsafe{
return CAMERA[0];
}}
#[allow(unused)]
fn get_camera_y()->i32{unsafe{
return CAMERA[1];
}}
#[allow(unused)]
fn set_camera(c: [i32; 2]){unsafe{
CAMERA = c;
}}
#[allow(unused)]
fn set_camera_x(x: i32){unsafe{
CAMERA[0] = x;
}}
#[allow(unused)]
fn set_camera_y(y: i32){unsafe{
CAMERA[1] = y;
}}
/// This funciton sets the static variable `GLOBAL_PROPERTIES_Z`.
/// This is not thread safe.
#[allow(unused)]
fn set_global_properties_z(x: usize){unsafe{
GLOBAL_PROPERTIES_Z = x;
}}
/// This function returns the last `GLOBAL_PROPERTIES_Z` and increments the varable.
/// This is not thread safe.
fn get_and_update_global_properties_z()->usize{unsafe{
let rt = GLOBAL_PROPERTIES_Z;
GLOBAL_PROPERTIES_Z += 1;
return rt;
}}
/// This function returns the value of `GLOBAL_PROPERTIES_Z`.
/// This is not thread safe.
fn get_global_properties_z()->usize{unsafe{
let rt = GLOBAL_PROPERTIES_Z;
return rt;
}}
const DEFAULT_CUSTOM_ELEMENTS : [CircuitElement ; 4] = {
let mut resistor_1 = CircuitElement::empty();
{
resistor_1.circuit_element_type = SelectedCircuitElement::Custom;
resistor_1.resistance = 5f32;
resistor_1.label = TinyString::new();
resistor_1.label.buffer[0] = 'R' as u8;
resistor_1.label.buffer[1] = 'e' as u8;
resistor_1.label.buffer[2] = 's' as u8;
resistor_1.label.buffer[3] = 'i' as u8;
resistor_1.label.buffer[4] = 's' as u8;
resistor_1.label.buffer[5] = 't' as u8;
resistor_1.label.buffer[6] = 'o' as u8;
resistor_1.label.buffer[7] = 'r' as u8;
resistor_1.label.buffer[8] = '_' as u8;
resistor_1.label.buffer[9] = '1' as u8;
resistor_1.label.cursor = 10;
}
let mut resistor_2 = CircuitElement::empty();
{
resistor_2.circuit_element_type = SelectedCircuitElement::Custom;
resistor_2.resistance = 2.0f32;
resistor_2.unc_resistance = 0.5f32;
resistor_2.label = TinyString::new();
resistor_2.label.buffer[0] = 'R' as u8;
resistor_2.label.buffer[1] = '2' as u8;
resistor_2.label.buffer[2] = 'v' as u8;
resistor_2.label.buffer[3] = '1' as u8;
resistor_2.label.cursor = 4;
}
let mut resistor_3 = CircuitElement::empty();
{
resistor_3.circuit_element_type = SelectedCircuitElement::Custom;
resistor_3.resistance = 2.1f32;
resistor_3.unc_resistance = 0.01f32;
resistor_3.label = TinyString::new();
resistor_3.label.buffer[0] = 'R' as u8;
resistor_3.label.buffer[1] = '2' as u8;
resistor_3.label.buffer[2] = 'v' as u8;
resistor_3.label.buffer[3] = '2' as u8;
resistor_3.label.cursor = 4;
}
let mut resistor_4 = CircuitElement::empty();
{
resistor_4.circuit_element_type = SelectedCircuitElement::Custom;
resistor_4.resistance = 5.3f32;
resistor_4.unc_resistance = 0.25f32;
resistor_4.label = TinyString::new();
resistor_4.label.buffer[0] = 'R' as u8;
resistor_4.label.buffer[1] = '_' as u8;
resistor_4.label.buffer[2] = '5' as u8;
resistor_4.label.buffer[3] = 'o' as u8;
resistor_4.label.buffer[4] = 'h' as u8;
resistor_4.label.buffer[5] = 'm' as u8;
resistor_4.label.buffer[6] = '?' as u8;
resistor_4.label.cursor = 7;
}
[resistor_4, resistor_1, resistor_2, resistor_3, ]
};
//TODO Color should be capped
pub const COLOR_BKG : [f32; 4] = [81.0/255.0, 33.0/255.0, 1.0, 1.0];
pub const COLOR_MENU_BKG : [f32; 4] = [97.0/255.0, 163.0/255.0, 1.0, 1.0];
pub const COLOR_GRID : [f32; 4] = [101.0/255.0, 53.0/255.0, 1.0, 1.0];
pub const COLOR_TEXT : [f32; 4] = C4_WHITE;
pub const COLOR_TEXT_SOLV : [f32; 4] = C4_YELLOW;
pub const COLOR_PROPERTY_BKG1 : [f32; 4] = C4_BLACK;
pub const COLOR_PROPERTY_BKG2 : [f32; 4] = [0.12, 0.12, 0.12, 1.0f32];
pub const COLOR_PROPERTY_MOVE1 : [f32; 4] = [0.23, 0.05, 0.23, 1.0f32];
pub const COLOR_PROPERTY_MOVE2 : [f32; 4] = [0.3, 0.12, 0.3, 1.0f32];
//
//pub const COLOR_BUTTON : [f32; 4] = C4_WHITE;
//pub const COLOR_BUTTON_TEXT : [f32; 4] = C4_WHITE;
const GRID_SIZE: i32 = 20;
const DEFAULT_RESISTANCE : f32 = 2.0;
const DEFAULT_VOLTAGE : f32 = 2.0;
const DEFAULT_CAPACITANCE : f32 = 2.0;
const DEFAULT_INDUCTANCE : f32 = 2.0;
const DEFAULT_FREQUENCY : f32 = 0.5;
const VOLTMETER_RESISTANCE : f32 = 99999.0;
const WIRE_RESISTANCE : f32 = 0.000001;
const CURRENT_INF_CUT : f32 = 1E4;
const PANEL_FONT : f32 = 23.0;
#[derive(PartialEq, Copy, Clone, Debug)]
enum SelectedCircuitElement{
Resistor,
Wire,
Battery,
Capacitor,
Inductor,
Voltmeter,
Ammeter,
Switch,
AC,
Custom,
None,
CustomVoltmeter,
CustomAmmeter,
}
#[derive(PartialEq, Copy, Clone, Debug)]
enum ACSourceType{
Sin,
Step,
}
static mut UNIQUE_NODE_INT: usize = 0;
/// This function returned a unique integer to be used to uniquely identify circuit elements.
/// This function is not thread safe.
fn get_unique_id()->usize{unsafe{
let id = UNIQUE_NODE_INT;
UNIQUE_NODE_INT += 1;
return id;
}}
/// This function sets `UNIQUE_NODE_INT`.
/// This function is not thread safe.
fn set_unique_id(n: usize){unsafe{
UNIQUE_NODE_INT = n;
}}
#[derive(PartialEq, Copy, Clone, Debug)]
enum CircuitElementDirection{
AtoB,
BtoA,
}
struct CircuitElementTextBox{
resistance_textbox : TextBox,
voltage_textbox : TextBox,
//current_textbox : TextBox,
capacitance_textbox : TextBox,
inductance_textbox : TextBox,
charge_textbox : TextBox,
magflux_textbox : TextBox,
max_voltage_textbox : TextBox,
frequency_textbox : TextBox,
label_textbox : TextBox,
unc_resistance_textbox : TextBox,
unc_voltage_textbox : TextBox,
//unc_current_textbox : TextBox,
unc_capacitance_textbox : TextBox,
unc_inductance_textbox : TextBox,
unc_charge_textbox : TextBox,
unc_magflux_textbox : TextBox,
bias_textbox : TextBox,
noise_textbox : TextBox,
drift_textbox : TextBox,
}
impl CircuitElementTextBox{
fn new()->CircuitElementTextBox{
fn fn_textbox()->TextBox{
let mut tb = TextBox::new();
tb.max_char = 6;
tb.text_size = PANEL_FONT;
tb.max_render_length = get_advance_string(&"X".repeat(tb.max_char as _), PANEL_FONT);
tb
}
let mut label = TextBox::new();
label.text_size = PANEL_FONT;
label.max_char = _FIXED_CHAR_BUFFER_SIZE as i32;
label.max_render_length = get_advance_string(&"X".repeat(label.max_char as _), PANEL_FONT);
CircuitElementTextBox{
resistance_textbox : fn_textbox(),
voltage_textbox : fn_textbox(),
//current_textbox : fn_textbox(),
capacitance_textbox : fn_textbox(),
inductance_textbox : fn_textbox(),
charge_textbox : fn_textbox(),
magflux_textbox : fn_textbox(),
max_voltage_textbox : fn_textbox(),
frequency_textbox : fn_textbox(),
label_textbox : label,
unc_resistance_textbox : fn_textbox(),
unc_voltage_textbox : fn_textbox(),
//unc_current_textbox : fn_textbox(),
unc_capacitance_textbox : fn_textbox(),
unc_inductance_textbox : fn_textbox(),
unc_charge_textbox : fn_textbox(),
unc_magflux_textbox : fn_textbox(),
bias_textbox : fn_textbox(),
noise_textbox : fn_textbox(),
drift_textbox : fn_textbox(),
}
}
fn new_guess_length()->CircuitElementTextBox{
fn fn_textbox()->TextBox{
let mut tb = TextBox::new();
tb.max_char = 6;
tb.text_size = PANEL_FONT;
tb.max_render_length = (tb.max_char as f32 * PANEL_FONT/2f32) as i32;
tb
}
let mut label = TextBox::new();
label.text_size = PANEL_FONT;
label.max_char = _FIXED_CHAR_BUFFER_SIZE as i32;
label.max_render_length = (label.max_char as f32 * PANEL_FONT/2f32) as i32;
CircuitElementTextBox{
resistance_textbox : fn_textbox(),
voltage_textbox : fn_textbox(),
//current_textbox : fn_textbox(),
capacitance_textbox : fn_textbox(),
inductance_textbox : fn_textbox(),
charge_textbox : fn_textbox(),
magflux_textbox : fn_textbox(),
max_voltage_textbox : fn_textbox(),
frequency_textbox : fn_textbox(),
label_textbox : label,
unc_resistance_textbox : fn_textbox(),
unc_voltage_textbox : fn_textbox(),
//unc_current_textbox : fn_textbox(),
unc_capacitance_textbox : fn_textbox(),
unc_inductance_textbox : fn_textbox(),
unc_charge_textbox : fn_textbox(),
unc_magflux_textbox : fn_textbox(),
bias_textbox : fn_textbox(),
noise_textbox : fn_textbox(),
drift_textbox : fn_textbox(),
}
}
}
/// CircuitElement is the primary structure of this module.
/// The struct is used to store the element properties ie. voltage, resistance, capacitance etc.
/// Position and orientation are also stored here.
///
/// Each circuit element placed in the user area are given a set of unique identifiers.
/// The unique identifier is determined by `get_unique_id`. This function is not thread safe.
/// Do not use CircuitElement::new() in a multi threaded capacity.
#[repr(C)]
#[derive(Copy, Clone, Debug)]
struct CircuitElement{
circuit_element_type: SelectedCircuitElement,
orientation: f32,
x: i32,
y: i32,
length: i32,
selected: bool,
selected_rotation: bool,
properties_selected: bool,
properties_move_selected: bool,
properties_offset_x: Option<i32>,
properties_offset_y: Option<i32>,
unique_a_node: usize,
a_node: usize,
unique_b_node: usize,
b_node: usize,
resistance: f32,
voltage: f32,
current: f32,
unc_resistance: f32,
unc_voltage: f32,
unc_current: f32,
capacitance: f32,
inductance: f32,
charge: f32,
magnetic_flux: f32,
unc_capacitance: f32,
unc_inductance: f32,
unc_charge: f32,
unc_magnetic_flux: f32,
max_voltage: f32,
d_voltage_over_dt: f32,
frequency: f32,
solved_voltage: Option<f32>,
solved_current: Option<f32>,
print_voltage: Option<f32>,
print_current: Option<f32>,
discovered: bool,
direction : Option<CircuitElementDirection>,
is_circuit_element: bool, //TODO we will test without using this
a_index: [Option<usize>; 3],//TODO do we use this?
b_index: [Option<usize>; 3],//TODO do we use this?
ac_source_type: ACSourceType,
temp_step_voltage : f32,
alt_sim_time: f32,
properties_z: usize,
label: TinyString,
bias: f32,
noise: f32,
drift: f32,
initial_altered_rotation: f32,
time: f32,
}
impl CircuitElement{
pub const fn empty()->CircuitElement{
CircuitElement{
circuit_element_type: SelectedCircuitElement::None,
orientation: 0.0,
x: 0,
y: 0,
length: 0,
selected: false,
selected_rotation: false,
properties_selected: false,
properties_move_selected: false,
properties_offset_x: None,
properties_offset_y: None,
resistance: 0.0f32,
voltage: 0.0f32,
current: 0.0f32,
unc_resistance: 0.0f32,
unc_voltage: 0.0f32,
unc_current: 0.0f32,
capacitance: 0f32,
inductance : 0f32,
charge : 0f32,
magnetic_flux: 0f32,
unc_capacitance: 0f32,
unc_inductance : 0f32,
unc_charge : 0f32,
unc_magnetic_flux: 0f32,
max_voltage : 0f32,
d_voltage_over_dt: 0f32,
frequency : 0f32,
solved_voltage: None,
solved_current: None,
print_voltage: None,
print_current: None,
unique_a_node: 0,
a_node: 0,
unique_b_node: 0,
b_node: 0,
discovered: false,
direction : None,
is_circuit_element: false,
a_index: [None; 3],
b_index: [None; 3],
ac_source_type: ACSourceType::Sin,
temp_step_voltage : 0f32,
alt_sim_time: 0f32,
properties_z: 0,
label: TinyString::new(),
bias: 0f32,
noise: 0f32,
drift: 0f32,
initial_altered_rotation: 0f32,
time: 0f32,
}
}
pub fn new()->CircuitElement{
let a_id = get_unique_id();
let b_id = get_unique_id();
let mut ce = CircuitElement::empty();
ce.unique_a_node = a_id;
ce.a_node = a_id;
ce.unique_b_node = b_id;
ce.b_node = b_id;
return ce;
}
}
#[derive(PartialEq)]
enum SaveLoadEnum{
Save,
Load,
}
#[derive(PartialEq)]
enum ProgramElementsEnum{
CustomElement,
SidePanel,
Circuit,
}
#[derive(PartialEq)]
enum CircuitMenuType{
Custom,
Default,
}
#[derive(PartialEq)]
pub enum MessageType{
Error,
Default
}
/// LsAppStorage contains data that must be stored across the frame boundary.
///
/// LsAppStorage contians a vast amount of information including circuit elements placed by the user.
/// If any informationg needs to be stored beyond the frame boundary it should be stored here.
///
pub struct LsAppStorage{
pub init: bool,
pub menu_canvas: SubCanvas,
pub menu_move_activated_time: u128,
pub menu_move_activated: bool,
pub menu_offscreen: bool,
pub timer: Instant,
stop_watch: f32,
timer_init: bool,
circuit_element_canvas: SubCanvas,
selected_circuit_element: SelectedCircuitElement,
selected_circuit_element_orientation: f32,
selected_circuit_properties : Option<CircuitElement>,
resistor_bmp : TGBitmap,
battery_bmp : TGBitmap,
capacitor_bmp : TGBitmap,
inductor_bmp : TGBitmap,
voltmeter_bmp : TGBitmap,
ammeter_bmp : TGBitmap,
switch_open_bmp : TGBitmap,
switch_closed_bmp: TGBitmap,
ac_bmp : TGBitmap,
wire_bmp : TGBitmap,
custom_bmp : TGBitmap,
arrow_bmp : TGBitmap,
pub screenshot_icon_bmp: TGBitmap,
save_icon_bmp : TGBitmap,
save_icon_bmp_alt: TGBitmap,
save_toggle: bool,
save_toggle_saveload: SaveLoadEnum,
save_toggle_programelements: ProgramElementsEnum,
save_textbox : TextBox,
ce_save_textbox : TextBox,
panel_save_textbox : TextBox,
arr_circuit_elements: Vec<CircuitElement>,
arr_panels: Vec<Panel>,
panel_index: usize,
saved_circuit_currents: std::collections::HashMap<(usize, usize), [Vec<f32>; 2]>,
saved_circuit_volts : std::collections::HashMap<(usize, usize), [Vec<f32>; 2]>,
teacher_mode: bool,
lab_text: String,
panel_previously_modified : std::time::SystemTime,
run_circuit: bool,
sim_time: f32,
circuit_textbox_hash: std::collections::HashMap<(usize, usize), CircuitElementTextBox>,
messages: Vec<(MessageType, String)>,
message_index: Option<usize>,
message_timer: StopWatch,
custom_circuit_elements: Vec<CircuitElement>,
circuit_menu_type: CircuitMenuType,
create_custom_circuit: bool,
panel_custom_circuit: bool,
custom_circuit_cursor: usize,
custom_circuit_textbox: CircuitElementTextBox,
global_time : StopWatch,
arrow_toggled : bool,
}
impl LsAppStorage{
pub fn new()->LsAppStorage{
LsAppStorage{
init: false,
menu_canvas: SubCanvas::new(0,0),
menu_move_activated_time: 0,
menu_move_activated: false,
menu_offscreen: false,
timer: Instant::now(),
stop_watch: 0f32,//StopWatch::new(),
timer_init: false,
circuit_element_canvas: SubCanvas::new(0,0),
selected_circuit_element: SelectedCircuitElement::None,
selected_circuit_element_orientation: 0f32,
selected_circuit_properties : None,
resistor_bmp: TGBitmap::new(0,0),
battery_bmp: TGBitmap::new(0,0),
capacitor_bmp: TGBitmap::new(0,0),
inductor_bmp : TGBitmap::new(0,0),
voltmeter_bmp: TGBitmap::new(0,0),
ammeter_bmp: TGBitmap::new(0,0),
switch_open_bmp: TGBitmap::new(0,0),
switch_closed_bmp: TGBitmap::new(0,0),
ac_bmp: TGBitmap::new(0,0),
wire_bmp: TGBitmap::new(0,0),
custom_bmp: TGBitmap::new(0,0),
arrow_bmp: TGBitmap::new(0,0),
screenshot_icon_bmp: TGBitmap::new(0,0),
save_icon_bmp: TGBitmap::new(0,0),
save_icon_bmp_alt: TGBitmap::new(0,0),
save_toggle: false,
save_toggle_saveload: SaveLoadEnum::Load,
save_toggle_programelements: ProgramElementsEnum::Circuit,
save_textbox : TextBox::new(),
ce_save_textbox : TextBox::new(),
panel_save_textbox : TextBox::new(),
arr_circuit_elements: Vec::new(),
arr_panels: Vec::new(),
panel_index: 0,
saved_circuit_currents: std::collections::HashMap::new(),
saved_circuit_volts : std::collections::HashMap::new(),
teacher_mode: false,
lab_text: String::new(),
panel_previously_modified : std::time::SystemTime::now(),
run_circuit: false,
sim_time: 0f32,
circuit_textbox_hash : std::collections::HashMap::new(),
messages: Vec::new(),
message_index: None,
message_timer: StopWatch::new(),
custom_circuit_elements: Vec::new(),
circuit_menu_type: CircuitMenuType::Default,
create_custom_circuit: false,
panel_custom_circuit: false,
custom_circuit_cursor: 0,
custom_circuit_textbox: CircuitElementTextBox::new_guess_length(),
global_time : StopWatch::new(),
arrow_toggled : false,
}
}
}
const EXAMPLE_LAB : &str =
"//
//
#Section
#Text
Hello,
welcome to the circuit simulation software lab. This software is designed for easy and intuitive construction of circuits, as well as their computation. It is an environment where lab TAs and professors can craft lessons for their students. The following panels are an example lab designed to help users acclimate to the software.
#Header Quick Tips:
#Text
- To create a new element left click circuit element you desire using in the panel on the left.
- Place a new element using a left click.
- Release the creation tool by right clicking or left clicking on a previously placed element.
- To move an element click and drag a previously placed element.
- To rotate use the mouse wheel or equilvalent with trackpad
- Or left click and hold the edge of an element then drag your cursor to the desired orientation.
#Section
#Header Additional Tips:
#Text
+ Left click, 2 finger click or double click to access circuit element properties.
+ Circuit elements can be rotated using property's panel or on grid.
Hover mouse over far edge of element until you see a rectangle. Click and hold to rotate.
+ Circuit element properties can be changed by typing.
+ Click the download button on the upper right hand of the screen, or top of this panel to save and load circuits.
When saving circuits be sure to press 'Enter' to complete the save.
+ Current arrows can be toggled using the icon on the top right, behind this panel.
+ A screen shot can be taken using the camera icon on the top right, behind this panel.
#Section
#Header Introduction:
#Text
Circuits are the way with which we make electricity do useful things. And it is through the study of circuits, that we are able to produce many of the tools we use today. In 1827 Ohm published \"The Galvanic Circuit Studied Mathematically\", which experimentally established the relationship between current, I, and potential difference, V. You will verify these relationships.
Voltage, Current and Resistance:
The most simple of circuits contain a battery, the source of the electromotive force, and a resistor, a component through which electricity does work.
The circuit below is one such circuit. Recreate this circuit. Using the panel to the left and place the components on the graph board.
#image circuit.png
#Section
#Text
By pressing \"Run\" the simulation will begin. Double or right click the battery element to access its property. Increase and decrease the voltage, note the circuit's behavior.
NOTE: Each circuit element can be adjusted using their property panel.
#Question
What occurred when you increased the voltage?
#answerwrong The speed of the red strips was the same.
#answercorrect The red strips began to move faster.
#answerwrong The speed slowed down.
#Section
#Text
The red strips symbolize electrons as they move through the circuit. While noticing visual differences is useful, measurements should be obtained using an ammeter. The ammeter measures current, while the voltmeter measures voltage. Take measurements of the current to determine how voltage and resistance impact the current of a circuit. Given a data set one can ascertain the relationship between current, voltage and resistance.
#image circuit_ammeter.png
#Question
Construct a simple circuit measure the current for a set of voltages between -2V and 3V. Using this data set what is the relationship between current and voltage?
#answercorrect linear
#answerwrong quadratic
#answerwrong power
#Section
#Text
Scientist often notice patterns in the data they collect then try to construct a mathematical representation of the phenomena encountered. Repeat the measurement from the last slide changing the resistance instead of the voltage. Using the data collected attempt to construct a formula that uses the voltage and resistance to determine the current. Use this to answer the question below. Feel free to check your answers using the simulator.
#Question Assuming a simple resistor, battery circuit what combination of voltage and resistance gives a current of 2.75A?
#answerwrong Voltage: 7V, Resistance: 8Ω
#answerwrong Voltage: 5V, Resistance: 2Ω
#answercorrect Voltage: 8.25V, Resistance: 3Ω
#Section
#Text
So far you've set the values of circuit components by hand. In the real world the properties of components may not be known, or are known to some finite precision. The 'Custom' tab contains circuit elements with hidden properties. In this menu you'll find an element labelled 'Resistor_1'. Use what you learned from previous exercises to determine the resistance of this element.
#Question
What is the resistance of 'Resistor_1'?
#answerwrong 4Ω
#answercorrect 5Ω
#answerwrong 2.5Ω
#Section
#Text
During your studies you may recall your professors and TAs highlighting the impact of uncertainties. When a resistor, for example, is made the manufacturer will guarantee its value to a certain level of precision. In the 'Custom' tab you will find a circuit element labelled 'R2v1'. Imagine you are constructing an apparatus using this resistor. According to the manufacturer this resistor has 2Ω of resistance. They guarantee the difference in resistance for each resistor to be less than mΩ. Your advisor is skeptical and asks you to measure multiple 'R2v1' resistors to verify their claims.
#Question
Are the 'R2v1' resistors precise to a mΩ?
#answerwrong Yes
#answercorrect No
#Section
#Text
Your advisor contacts the manufacturer and informs them of the issue with 'R2v1'. The manufacturer delivers a new version of the resistor, 'R2v2'.
Measure this new resistors, and take note of their variance and mean.
#Question
Are 'R2v2' resistors perfect 2Ω resistors?
#answerwrong Yes
#answercorrect No
#section
#Header
END
#text
Thanks for using the lab circuit software.
";
struct PanelFile{
original_length: u64,
buffer: Vec<u8>,
}
impl PanelFile{
fn save(&self, name: &str){
use std::io::prelude::*;
let mut f = std::fs::File::create(name).expect("File could not be created.");
f.write_all( b"PF" ).expect("write all has been interrupted.");
unsafe{
f.write_all( &std::mem::transmute::<u64, [u8; 8]>(self.original_length) ).expect("write all has been interrupted.");
}
f.write( &self.buffer );
}
fn load(name: &str)->PanelFile{
use std::io::prelude::*;
let mut panelfile = PanelFile{ original_length: 0, buffer: vec![]};
let mut f = std::fs::File::open(name).expect("File could not be created.");
let mut file_header_buffer = [0u8;2];
f.read( &mut file_header_buffer).expect("Could not read from file.");
if file_header_buffer[0] as char == 'P'
&& file_header_buffer[1] as char == 'F'{
} else {
panic!("File type is wrong.");
}
let mut org_size_buffer = [0u8;8];
f.read(&mut org_size_buffer).expect("Could not read from file.");
unsafe{
panelfile.original_length = std::mem::transmute(org_size_buffer);
}
f.read_to_end( &mut panelfile.buffer);
return panelfile;
}
}
fn compress_panelfile( text: &str )->Vec<u8>{
let compressed = miniz::compress(text.as_bytes());
return compressed.expect("compress panelfile");
}
#[allow(unused)]
fn uncompress_panelfile( panelfile: &PanelFile )->String{
let len = panelfile.original_length;
let uncompressed = miniz::uncompress(&panelfile.buffer, len as usize);
return String::from_utf8_lossy(&uncompressed.expect("uncompressed")).into_owned();
}
/// This function is the most important to the application. User interaction, rendering and so one
/// is done here.
///
/// `circuit_sim` is the most important function in this module.
/// Everything happens here. `circuit_sim` requires keyboard, text and mouse information
/// structs as input. These structs contain all interactive data the application needs to run.
/// You may find the definitions of these structs in the `inputhandler` module, though it
/// should be noted that these structs are filled out on an operating system by operating
/// system bases. You may need to look into the `macos`, `windows` or `unix` modules for
/// interface details.
///
/// `circuit_sim` begins with an initialization block, `app_storage.init`.
/// In this block window size is set, assets are initialized and configuration files are
/// loaded. If you wish to incorporate more assets they should be initialized here.
///
/// TA mode is handled shortly after.
/// TA mode give the user the ability to author content. The retractable size panel
/// and the Custom Element panel can be edited using TA mode.
/// TA mode is activated when a file with the name
/// given by `TA_FILE_NAME` is in the program's directory and the tab button is pressed.
///
/// User created circuits, and associated circuit elements, are render next.
/// Logic relating to circuit element property panels are handled in this block as well.
/// The block has three distinct parts.
/// - Circuit element rendering, movement logic,
/// - property panel z-coordinate organization,
/// - property panel rendering and logic.
/// Z-coordinate organization refers to the order property panels are rendered and
/// which panels has inputs recognized if multiple panels overlap.
///
///
/// The final block handles circuit simulation. `compute_circuit` is these most
/// important function in this section. The circuit simulation is done using the
/// sparse tableau network analysis approach, using Gaussian elimination to solve the
/// resulting matrix. You can find the text [here](http://web.engr.oregonstate.edu/~karti/ece521/sta.pdf).
pub fn circuit_sim(os_package: &mut OsPackage, app_storage: &mut LsAppStorage, keyboardinfo: &KeyboardInfo, textinfo: &TextInfo, mouseinfo: &MouseInfo)->i32{
let window_w = os_package.window_canvas.w;
let window_h = os_package.window_canvas.h;
let panel_font = PANEL_FONT;
if !app_storage.init {
app_storage.init = true;
//NOTE we are setting the window size for next frame
if os_package.window_canvas.display_width != 0
&& os_package.window_canvas.display_height != 0 {
if WINDOW_WIDTH >= os_package.window_canvas.display_width {
os_package.window_info.w = os_package.window_canvas.display_width - 10;
} else {
os_package.window_info.w = WINDOW_WIDTH;
}
if WINDOW_HEIGHT >= os_package.window_canvas.display_height {
os_package.window_info.h = os_package.window_canvas.display_height - 10;
} else {
os_package.window_info.h = WINDOW_HEIGHT;
}
} else {
os_package.window_info.w = WINDOW_WIDTH;
os_package.window_info.h = WINDOW_HEIGHT;
}
app_storage.menu_canvas = SubCanvas::new( 492, window_h);
app_storage.circuit_element_canvas = SubCanvas::new(180,350);
app_storage.save_textbox.text_buffer += "MyCircuit.cd";
app_storage.ce_save_textbox.text_buffer += CUSTOM_FILE_NAME;
app_storage.panel_save_textbox.text_buffer += CIRCUIT_PANEL_FILE_NAME;
if std::path::Path::new(CIRCUIT_PANEL_FILE_NAME).is_file(){
let pf = PanelFile::load(CIRCUIT_PANEL_FILE_NAME);
let buffer = miniz::uncompress(&pf.buffer, pf.original_length as usize);
app_storage.lab_text = String::from_utf8_lossy(&buffer.expect("something went wrong with decompression")).to_string();
} else {
app_storage.lab_text = EXAMPLE_LAB.to_string();
}
let (panels, errors) = parse_and_panel_filebuffer(&app_storage.lab_text);
app_storage.messages = errors;
app_storage.arr_panels = panels;
if std::path::Path::new(CUSTOM_FILE_NAME).is_file(){
let custom_elements = load_circuit_diagram(CUSTOM_FILE_NAME);
app_storage.custom_circuit_elements = custom_elements;
} else {
app_storage.custom_circuit_elements.clear();
app_storage.custom_circuit_elements.extend_from_slice(&DEFAULT_CUSTOM_ELEMENTS);
}
app_storage.resistor_bmp = TGBitmap::from_buffer(IMG_RESISTOR);
app_storage.battery_bmp = TGBitmap::from_buffer(IMG_BATTERY);
app_storage.capacitor_bmp = TGBitmap::from_buffer(IMG_CAPACITOR);
app_storage.inductor_bmp = TGBitmap::from_buffer(IMG_INDUCTOR);
app_storage.voltmeter_bmp = TGBitmap::from_buffer(IMG_VOLTMETER);
app_storage.ammeter_bmp = TGBitmap::from_buffer(IMG_AMMETER);
app_storage.switch_open_bmp = TGBitmap::from_buffer(IMG_SWITCH_OPEN);
app_storage.switch_closed_bmp = TGBitmap::from_buffer(IMG_SWITCH_CLOSED);
app_storage.ac_bmp = TGBitmap::from_buffer(IMG_AC);
app_storage.wire_bmp = TGBitmap::from_buffer(IMG_WIRE);
app_storage.custom_bmp = TGBitmap::from_buffer(IMG_CUSTOM);
app_storage.arrow_bmp = TGBitmap::from_buffer(IMG_ARROW);
app_storage.screenshot_icon_bmp = TGBitmap::from_buffer(IMG_SCREENSHOT);
app_storage.save_icon_bmp = TGBitmap::from_buffer(IMG_SAVE);
app_storage.save_icon_bmp_alt = TGBitmap::from_buffer(IMG_SAVE_ALT);
//TODO
let icon = TGBitmap::from_buffer(IMG_ICON);
set_icon(&icon);
change_font(FONT_NOTOSANS);
}
//NOTE Frame rate cap of 60 frames per sec.
{
match Duration::from_millis(16).checked_sub(app_storage.global_time.get_time()){
Some(d)=>{
std::thread::sleep(d);
},
_=>{}
}
app_storage.global_time.reset()
}
let circuit_element_canvas_x_offset = 25;
let circuit_element_canvas_y_offset = (window_h/2 - app_storage.circuit_element_canvas.canvas.h/2).max(window_h-4*window_h/5);
//if os_package.window_info.h != app_storage.menu_canvas.canvas.h {
if window_h != app_storage.menu_canvas.canvas.h {
app_storage.menu_canvas = SubCanvas::new( 492, window_h);
}
//TODO teacher mode turn on
let mut just_switched_modes = false;
if keyboardinfo.is_key_released(KeyboardEnum::Tab)
&& std::path::Path::new(TA_FILE_NAME).is_file()
&& app_storage.teacher_mode == false {
app_storage.teacher_mode = true;
just_switched_modes = true;
}
if app_storage.teacher_mode {
if keyboardinfo.is_key_released(KeyboardEnum::Tab)
&& !just_switched_modes {
app_storage.teacher_mode = false;
app_storage.selected_circuit_element = SelectedCircuitElement::None;
app_storage.create_custom_circuit = false;
app_storage.panel_custom_circuit = false;
}
let circuit_panel_path = std::path::Path::new("circuit_panels.txt");
if !circuit_panel_path.exists(){
let mut f = std::fs::File::create(circuit_panel_path).expect("Could not create file.");
f.write_all(app_storage.lab_text.as_bytes()).expect("write all has been interrupted.");
let date_modified = circuit_panel_path.metadata().expect("Could not retrieve panel file meta data!").modified().unwrap();
app_storage.panel_previously_modified = date_modified;
} else {
let date_modified = circuit_panel_path.metadata().expect("Could not retrieve panel file meta data!").modified().unwrap();
if date_modified > app_storage.panel_previously_modified {
let mut f = std::fs::File::open(circuit_panel_path).expect("Could not open file.");
app_storage.lab_text.clear();
f.read_to_string(&mut app_storage.lab_text);
let (mut panels, mut errors) = parse_and_panel_filebuffer(&app_storage.lab_text);
app_storage.arr_panels.clear();
app_storage.arr_panels.append( &mut panels );
app_storage.messages.clear();
app_storage.messages.append(&mut errors);
app_storage.message_index = None;
app_storage.panel_previously_modified = date_modified;
}
}
if keyboardinfo.is_key_pressed(KeyboardEnum::Tab){
let mut panel = PanelFile{ original_length: app_storage.lab_text.as_bytes().len() as u64,
buffer: Vec::new()
};
panel.buffer = compress_panelfile(&app_storage.lab_text);
panel.save(CIRCUIT_PANEL_FILE_NAME);//TODO
}
}
//Draw bkg color
draw_rect(&mut os_package.window_canvas, [0, 0, window_w, window_h], COLOR_BKG, true);
draw_grid(os_package.window_canvas, GRID_SIZE, get_camera());
change_font(FONT_MERRIWEATHER_LIGHT);
let title_length = get_advance_string("Circuit Simulation", 46.0);
draw_string(&mut os_package.window_canvas, "Circuit Simulation", window_w/2-title_length/2, window_h-60, COLOR_TEXT, 46.0);
change_font(FONT_NOTOSANS);
let mut copy_circuit_buffer= vec![];
for it in app_storage.arr_circuit_elements.iter(){
copy_circuit_buffer.push(*it);
}
//Change mouse
match app_storage.selected_circuit_element{
SelectedCircuitElement::Resistor | SelectedCircuitElement::Battery | SelectedCircuitElement::Capacitor | SelectedCircuitElement::Inductor |
SelectedCircuitElement::Voltmeter| SelectedCircuitElement::Ammeter | SelectedCircuitElement::Switch | SelectedCircuitElement::AC |
SelectedCircuitElement::Wire | SelectedCircuitElement::Custom | SelectedCircuitElement::CustomVoltmeter | SelectedCircuitElement::CustomAmmeter=> {
let x = mouseinfo.x - SELECTED_OFFSET;
let y = mouseinfo.y - SELECTED_OFFSET;
let mut resize_bmp = TGBitmap::new(0,0);
if app_storage.selected_circuit_element == SelectedCircuitElement::Resistor{
resize_bmp = sampling_reduction_bmp(&app_storage.resistor_bmp, 80, 80);
} else if app_storage.selected_circuit_element == SelectedCircuitElement::Battery{
resize_bmp = sampling_reduction_bmp(&app_storage.battery_bmp, 80, 80);
} else if app_storage.selected_circuit_element == SelectedCircuitElement::Capacitor{
resize_bmp = sampling_reduction_bmp(&app_storage.capacitor_bmp, 80, 80);
} else if app_storage.selected_circuit_element == SelectedCircuitElement::Inductor{
resize_bmp = sampling_reduction_bmp(&app_storage.inductor_bmp, 80, 80);
} else if app_storage.selected_circuit_element == SelectedCircuitElement::Voltmeter{
resize_bmp = sampling_reduction_bmp(&app_storage.voltmeter_bmp, 80, 80);
} else if app_storage.selected_circuit_element == SelectedCircuitElement::Ammeter{
resize_bmp = sampling_reduction_bmp(&app_storage.ammeter_bmp, 80, 80);
} else if app_storage.selected_circuit_element == SelectedCircuitElement::Switch{
resize_bmp = sampling_reduction_bmp(&app_storage.switch_open_bmp, 80, 80);
} else if app_storage.selected_circuit_element == SelectedCircuitElement::AC{
resize_bmp = sampling_reduction_bmp(&app_storage.ac_bmp, 80, 80);
} else if app_storage.selected_circuit_element == SelectedCircuitElement::Wire{
resize_bmp = sampling_reduction_bmp(&app_storage.wire_bmp, 80, 80);
} else if app_storage.selected_circuit_element == SelectedCircuitElement::Custom
|| app_storage.selected_circuit_element == SelectedCircuitElement::CustomVoltmeter
|| app_storage.selected_circuit_element == SelectedCircuitElement::CustomAmmeter
{
resize_bmp = sampling_reduction_bmp(&app_storage.custom_bmp, 80, 80);
}
let rotated_bmp = rotate_bmp(&mut resize_bmp, app_storage.selected_circuit_element_orientation).unwrap();
draw_bmp(&mut os_package.window_canvas, &rotated_bmp, x, y, 0.98, None, None);
if app_storage.selected_circuit_element == SelectedCircuitElement::Custom
|| app_storage.selected_circuit_element == SelectedCircuitElement::CustomVoltmeter
|| app_storage.selected_circuit_element == SelectedCircuitElement::CustomAmmeter{
let orientation = app_storage.selected_circuit_element_orientation.sin().abs().round();
if orientation == 0.0 {
let c_it = &app_storage.custom_circuit_elements[app_storage.custom_circuit_cursor];
change_font(FONT_NOTOSANS_BOLD);
let _adv = get_advance_string(c_it.label.as_ref(), 20f32);
draw_string(&mut os_package.window_canvas, c_it.label.as_ref(), x+rotated_bmp.width/2-_adv/2-6, y + 3, C4_WHITE, 20f32);
change_font(FONT_NOTOSANS);
}
}
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down
&& in_rect(mouseinfo.x, mouseinfo.y, [circuit_element_canvas_x_offset, circuit_element_canvas_y_offset,
app_storage.circuit_element_canvas.canvas.w, app_storage.circuit_element_canvas.canvas.h]){
app_storage.selected_circuit_element = SelectedCircuitElement::None;
app_storage.selected_circuit_element_orientation = 0f32;
app_storage.selected_circuit_properties = None;
}
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down
&& !in_rect(mouseinfo.x, mouseinfo.y, [circuit_element_canvas_x_offset, circuit_element_canvas_y_offset,
app_storage.circuit_element_canvas.canvas.w, app_storage.circuit_element_canvas.canvas.h]){
let mut element = CircuitElement::new();
element.circuit_element_type = app_storage.selected_circuit_element;
match app_storage.selected_circuit_element{
SelectedCircuitElement::Resistor=>{
match app_storage.selected_circuit_properties{
Some(copy_ele) => {
element.resistance = copy_ele.resistance;
},
None=>{
element.resistance = DEFAULT_RESISTANCE;
}
}
},
SelectedCircuitElement::Battery=>{
match app_storage.selected_circuit_properties{
Some(copy_ele)=>{
element.voltage = copy_ele.voltage;
},
None=>{
element.voltage = DEFAULT_VOLTAGE;
},
}
},
SelectedCircuitElement::Capacitor=>{
match app_storage.selected_circuit_properties{
Some(copy_ele)=>{
element.capacitance = copy_ele.capacitance;
element.resistance = WIRE_RESISTANCE;
},
None=>{
element.capacitance = DEFAULT_CAPACITANCE;
element.resistance = WIRE_RESISTANCE;
},
}
},
SelectedCircuitElement::Inductor=>{
match app_storage.selected_circuit_properties{
Some(copy_ele)=>{
element.inductance = copy_ele.inductance;
},
None=>{
element.inductance = DEFAULT_INDUCTANCE;
},
}
},
SelectedCircuitElement::Voltmeter=>{
element.resistance = VOLTMETER_RESISTANCE;
app_storage.saved_circuit_volts.insert((element.unique_a_node, element.unique_b_node), [Vec::new(), Vec::new()]);
},
SelectedCircuitElement::Ammeter=>{
element.resistance = WIRE_RESISTANCE;
app_storage.saved_circuit_currents.insert((element.unique_a_node, element.unique_b_node), [Vec::new(), Vec::new()]);
},
SelectedCircuitElement::Switch=>{
match app_storage.selected_circuit_properties{
Some(copy_ele)=>{
element.resistance = copy_ele.resistance;
},
None=>{
element.resistance = VOLTMETER_RESISTANCE;
},
}
},
SelectedCircuitElement::AC=>{
element.voltage = 0.0;
element.max_voltage = DEFAULT_VOLTAGE;
element.d_voltage_over_dt = DEFAULT_FREQUENCY * 2f32 * PI;
element.frequency = DEFAULT_FREQUENCY;
element.ac_source_type = ACSourceType::Sin;
//TODO maybe
},
SelectedCircuitElement::Custom |
SelectedCircuitElement::CustomVoltmeter |
SelectedCircuitElement::CustomAmmeter=>{
let c_it = &app_storage.custom_circuit_elements[app_storage.custom_circuit_cursor];
if c_it.circuit_element_type == SelectedCircuitElement::CustomVoltmeter {
app_storage.saved_circuit_volts.insert((element.unique_a_node, element.unique_b_node), [Vec::new(), Vec::new()]);
}
if c_it.circuit_element_type == SelectedCircuitElement::CustomAmmeter {
app_storage.saved_circuit_currents.insert((element.unique_a_node, element.unique_b_node), [Vec::new(), Vec::new()]);
}
element.circuit_element_type = c_it.circuit_element_type;
element.label = c_it.label;
element.voltage = c_it.voltage;
element.current = c_it.current;
element.resistance = c_it.resistance;
element.unc_voltage = sample_normal(c_it.unc_voltage);
element.unc_current = sample_normal(c_it.unc_current);
element.unc_resistance = sample_normal(c_it.unc_resistance);
element.capacitance = c_it.capacitance;
element.inductance = c_it.inductance;
element.unc_capacitance = sample_normal(c_it.unc_capacitance);
element.unc_inductance = sample_normal(c_it.unc_inductance);
element.charge = c_it.charge;
element.magnetic_flux = c_it.magnetic_flux;
element.unc_charge = sample_normal(c_it.unc_charge);
element.unc_magnetic_flux = sample_normal(c_it.unc_magnetic_flux);
element.bias = c_it.bias;
element.noise = c_it.noise;
element.drift = c_it.drift;
},
SelectedCircuitElement::Wire=>{
element.resistance = WIRE_RESISTANCE;
},
SelectedCircuitElement::None=>{panic!("Selected circuit should not be a None. Something very wrong occurred.");},
_=>{panic!("Selected circuit should not be a WTF it is. Something very wrong occurred.");},
}
let camera = get_camera();
element.x = (x as f32 / GRID_SIZE as f32).round() as i32 * GRID_SIZE - camera[0];
element.y = (y as f32 / GRID_SIZE as f32).round() as i32 * GRID_SIZE - camera[1];
//element.x = (x as f32 / GRID_SIZE as f32).round() as i32 * GRID_SIZE;
//element.y = (y as f32 / GRID_SIZE as f32).round() as i32 * GRID_SIZE;
element.orientation = app_storage.selected_circuit_element_orientation;
app_storage.arr_circuit_elements.push(element);
app_storage.circuit_textbox_hash.insert((element.unique_a_node, element.unique_b_node), CircuitElementTextBox::new());
}
},
_=>{}
}
if mouseinfo.rclicked(){
app_storage.selected_circuit_element_orientation = 0f32;
app_storage.selected_circuit_element = SelectedCircuitElement::None;
app_storage.selected_circuit_properties = None;
}
if mouseinfo.lbutton == ButtonStatus::Down
&& (in_rect(mouseinfo.x, mouseinfo.y, RUN_PAUSE_RECT) || in_rect(mouseinfo.x, mouseinfo.y, CLEAR_RECT)){
app_storage.selected_circuit_element_orientation = 0f32;
app_storage.selected_circuit_element = SelectedCircuitElement::None;
app_storage.selected_circuit_properties = None;
}
if mouseinfo.lbutton == ButtonStatus::Down
&& in_rect(mouseinfo.x, mouseinfo.y, [0, window_h - 2*GRID_SIZE, window_w, 2*GRID_SIZE]){
app_storage.selected_circuit_element_orientation = 0f32;
app_storage.selected_circuit_element = SelectedCircuitElement::None;
app_storage.selected_circuit_properties = None;
}
if mouseinfo.wheel_delta != 0
&& app_storage.selected_circuit_element != SelectedCircuitElement::None{
app_storage.selected_circuit_element_orientation += mouseinfo.wheel_delta.signum() as f32 * PI/2f32;
}
let mut is_element_rotate_selected = false;
let mut is_element_selected = false;
let mut in_properties = false;
let mut is_properties_move = false;
if app_storage.selected_circuit_element != SelectedCircuitElement::None {
is_element_selected = true;
}
{//z circuit
//select circuit element
fn mouse_in_properties_rect(mouseinfo: &MouseInfo, z_arr: &[(i32, i32, i32, i32)])->bool{
for it in z_arr.iter(){
if in_rect(mouseinfo.x, mouseinfo.y, [it.0, it.1, it.2, it.3]){
return true;
}
}
return false;
}
let mut z_vec = Vec::with_capacity(app_storage.arr_circuit_elements.len());
for (_, it) in app_storage.arr_circuit_elements.iter().enumerate(){
let camera = get_camera();
let it_x = it.x + camera[0];
let it_y = it.y + camera[1];
if it.properties_selected
&& it.properties_offset_x.is_some(){
let px = it.properties_offset_x.unwrap();
let py = it.properties_offset_y.unwrap();
let pw = PROPERTIES_W;
let ph = PROPERTIES_H;
z_vec.push(( px, py, pw, ph ));
}
let it_rect = [it_x, it_y, GRID_SIZE*4, GRID_SIZE*4];
let _rect = [mouseinfo.x-SELECTED_OFFSET, mouseinfo.y-SELECTED_OFFSET, GRID_SIZE*4, GRID_SIZE*4];
if overlap_rect_area(it_rect, _rect) > (2.5*GRID_SIZE as f32).powi(2) as i32
&& mouseinfo.lbutton == ButtonStatus::Down{
app_storage.selected_circuit_element_orientation = 0f32;
app_storage.selected_circuit_element = SelectedCircuitElement::None;
app_storage.selected_circuit_properties = None;
}
}
//NOTE
//Cicuit Selection loop
let mut elements_for_removal = vec![];
for (_i_index, it) in app_storage.arr_circuit_elements.iter_mut().enumerate(){
if mouseinfo.old_lbutton == ButtonStatus::Up
&& mouseinfo.lbutton == ButtonStatus::Up{
it.selected = false;
it.selected_rotation = false;
let camera = get_camera();
let rect1 = [it.x+camera[0], it.y+camera[1], 80, 80];
let rect2 = [circuit_element_canvas_x_offset,
circuit_element_canvas_y_offset,
app_storage.circuit_element_canvas.canvas.w,
app_storage.circuit_element_canvas.canvas.h,
];
if overlap_rect_area( rect1, rect2) > 0 {
elements_for_removal.push(_i_index);
}
}
if mouseinfo.old_lbutton == ButtonStatus::Up{
match &it.circuit_element_type{
SelectedCircuitElement::Resistor | SelectedCircuitElement::Battery | SelectedCircuitElement::Capacitor | SelectedCircuitElement::Inductor |
SelectedCircuitElement::Voltmeter| SelectedCircuitElement::Ammeter | SelectedCircuitElement::Switch | SelectedCircuitElement::AC |
SelectedCircuitElement::Wire | SelectedCircuitElement::Custom | SelectedCircuitElement::CustomVoltmeter | SelectedCircuitElement::CustomAmmeter => {
it.x = (it.x as f32 / GRID_SIZE as f32 ).round() as i32 * GRID_SIZE;
it.y = (it.y as f32 / GRID_SIZE as f32 ).round() as i32 * GRID_SIZE;
let camera = get_camera();
let it_x = it.x + camera[0];
let it_y = it.y + camera[1];
let mut _mouse_in_rect = [it_x+2, it_y-4+25, 76+it.length, 40];
let mut c1_x = it_x + 2 - it.length;
let mut c1_y = it_y + 41;
let mut c2_x = it_x + it.length + 82;
let mut c2_y = it_y + 41;
if it.orientation.sin().abs() == 1.0 {
_mouse_in_rect = [it_x + 12, it_y+4, 40, 73 + it.length];
c1_x = it_x + 4 + 38;
c1_y = it_y ;
c2_x = it_x + 4 + 38;
c2_y = it_y + it.length + 3 + 80;
}
if app_storage.selected_circuit_element == SelectedCircuitElement::None
&& in_rect( mouseinfo.x, mouseinfo.y, _mouse_in_rect )
&& !mouse_in_properties_rect(mouseinfo, &z_vec){
draw_circle(&mut os_package.window_canvas, c1_x, c1_y, 4.0, C4_WHITE);
draw_circle(&mut os_package.window_canvas, c2_x, c2_y, 4.0, C4_WHITE);
//TODO moves should be handled using selected boolean not whether for not mouse is in bounding box of properties if properties are open
//or any porperties that have been open
if mouseinfo.lbutton == ButtonStatus::Down{
it.selected = true;
}
//TODO should be handled using selected boolean not whether for not mouse is in bounding box of properties if properties are open
//or any porperties that have been open
if mouseinfo.rclicked()
|| mouseinfo.double_lbutton{
it.properties_selected = true;
it.properties_z = get_and_update_global_properties_z();
if it.properties_offset_x.is_some() {
let properties_x = it_x+it.length+95;
let properties_y = it_y-PROPERTIES_H/2;
it.properties_offset_x = Some(properties_x);
it.properties_offset_y = Some(properties_y);
}
}
}
if it.orientation.sin().abs() < 0.001f32{//Horizontal orientation
let right_rect = [c2_x-5, c2_y-5, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, right_rect)
&& !mouse_in_properties_rect(mouseinfo, &z_vec){
//Right side
draw_circle(&mut os_package.window_canvas, c2_x, c2_y, 4.0, C4_WHITE);
draw_rect(&mut os_package.window_canvas, right_rect, C4_WHITE, false);
if mouseinfo.lbutton == ButtonStatus::Down{
it.selected_rotation = true;
app_storage.selected_circuit_element_orientation = 0f32;
app_storage.selected_circuit_element = SelectedCircuitElement::None;
app_storage.selected_circuit_properties = None;
}
}
let left_rect = [c1_x-9, c1_y-5, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, left_rect)
&& !mouse_in_properties_rect(mouseinfo, &z_vec){
//Left side
draw_circle(&mut os_package.window_canvas, c1_x, c1_y, 4.0, C4_WHITE);
draw_rect(&mut os_package.window_canvas, left_rect, C4_WHITE, false);
if mouseinfo.lbutton == ButtonStatus::Down{
it.selected_rotation = true;
app_storage.selected_circuit_element_orientation = 0f32;
app_storage.selected_circuit_element = SelectedCircuitElement::None;
app_storage.selected_circuit_properties = None;
}
}
} else if it.orientation.sin().abs() == 1f32{//Vertical
let right_rect = [c2_x-6, c2_y-5, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, right_rect)
&& !mouse_in_properties_rect(mouseinfo, &z_vec){
//Top side
draw_circle(&mut os_package.window_canvas, c2_x, c2_y, 4.0, C4_WHITE);
draw_rect(&mut os_package.window_canvas, right_rect, C4_WHITE, false);
if mouseinfo.lbutton == ButtonStatus::Down{
it.selected_rotation = true;
app_storage.selected_circuit_element_orientation = 0f32;
app_storage.selected_circuit_element = SelectedCircuitElement::None;
app_storage.selected_circuit_properties = None;
}
}
let left_rect = [c1_x-6, c1_y-7, 10, 10];//TODO these should be 11x11 to have the result render symmetrically
if in_rect(mouseinfo.x, mouseinfo.y, left_rect)
&& !mouse_in_properties_rect(mouseinfo, &z_vec){
//Bottom side
draw_circle(&mut os_package.window_canvas, c1_x, c1_y, 4.0, C4_WHITE);
draw_rect(&mut os_package.window_canvas, left_rect, C4_WHITE, false);
if mouseinfo.lbutton == ButtonStatus::Down{
it.selected_rotation = true;
app_storage.selected_circuit_element_orientation = 0f32;
app_storage.selected_circuit_element = SelectedCircuitElement::None;
app_storage.selected_circuit_properties = None;
}
}
}
if it.selected_rotation {
it.initial_altered_rotation = {
let d_x = (mouseinfo.x - (it_x + 40)) as f32;//NOTE 40 is half of the bitmap width
let d_y = (mouseinfo.y - (it_y + 40)) as f32;//NOTE 40 is half the bitmap height
let mut theta = (d_x/(d_y.powi(2) + d_x.powi(2)).sqrt()).acos();
if d_y < 0f32 {
theta *= -1f32;
}
if theta.abs() < 0.1 {
theta += it.orientation;
} else {
theta -= it.orientation;
}
theta
};
}
},
_=>{}
}
} else { //if Button status is Down
match &it.circuit_element_type{
SelectedCircuitElement::Resistor | SelectedCircuitElement::Battery | SelectedCircuitElement::Capacitor | SelectedCircuitElement::Inductor |
SelectedCircuitElement::Voltmeter| SelectedCircuitElement::Ammeter | SelectedCircuitElement::Switch | SelectedCircuitElement::AC |
SelectedCircuitElement::Wire | SelectedCircuitElement::Custom | SelectedCircuitElement::CustomVoltmeter | SelectedCircuitElement::CustomAmmeter=>{
if it.selected {
is_element_selected = true;
it.x += mouseinfo.delta_x;
it.y += mouseinfo.delta_y;
if mouseinfo.wheel_delta != 0 {
it.orientation += mouseinfo.wheel_delta.signum() as f32 * PI/2f32;
}
}
if it.selected_rotation {
is_element_rotate_selected = true;
}
if it.properties_selected {
let x = *it.properties_offset_x.as_ref().unwrap();
let y = *it.properties_offset_y.as_ref().unwrap();
if in_rect(mouseinfo.x, mouseinfo.y, [x, y, PROPERTIES_W, PROPERTIES_H]){
in_properties = true;
}
}
if it.properties_move_selected {
is_properties_move = true;
}
},
_=>{}
}
}
}
{//remove circuit elements that are in the circuit elements
for it in elements_for_removal.iter().rev(){
app_storage.arr_circuit_elements.remove(*it);
}
}
}
if !is_element_selected
&& !is_element_rotate_selected
&& !in_rect(mouseinfo.x, mouseinfo.y, CLEAR_RECT)
&& !in_rect(mouseinfo.x, mouseinfo.y, RUN_PAUSE_RECT)
&& !in_rect(mouseinfo.x, mouseinfo.y, [circuit_element_canvas_x_offset, circuit_element_canvas_y_offset,
app_storage.circuit_element_canvas.canvas.w, app_storage.circuit_element_canvas.canvas.h])
&& !(in_rect(mouseinfo.x, mouseinfo.y, [window_w - app_storage.menu_canvas.canvas.w, 0,
app_storage.menu_canvas.canvas.w, app_storage.menu_canvas.canvas.h])
&& !app_storage.menu_offscreen)
&& !in_rect(mouseinfo.x, mouseinfo.y, [0, window_h - GRID_SIZE, window_w, 5*GRID_SIZE])
&& !in_properties
&& !is_properties_move
&& mouseinfo.lbutton == ButtonStatus::Down{
set_camera_x(get_camera_x() + mouseinfo.delta_x);
set_camera_y(get_camera_y() + mouseinfo.delta_y);
}
{
//NOTE
//Render loop
let mut arrow_resize_bmp = sampling_reduction_bmp(&app_storage.arrow_bmp, 20, 20);
let mut delete_list = vec![];
for (_, it) in app_storage.arr_circuit_elements.iter_mut().enumerate(){
match &it.circuit_element_type{
SelectedCircuitElement::Resistor | SelectedCircuitElement::Battery | SelectedCircuitElement::Capacitor | SelectedCircuitElement::Inductor |
SelectedCircuitElement::Voltmeter| SelectedCircuitElement::Ammeter | SelectedCircuitElement::Switch | SelectedCircuitElement::AC |
SelectedCircuitElement::Wire | SelectedCircuitElement::Custom | SelectedCircuitElement::CustomVoltmeter | SelectedCircuitElement::CustomAmmeter=>{
let camera = get_camera();
let it_x = it.x + camera[0];
let it_y = it.y + camera[1];
//TODO this is an example draw_bmp(&mut os_package.window_canvas, &_bmp, it.x+camera[0], it.y+camera[1], 0.98, None, None); //TODO
if is_element_selected {
let mut c1_x = it_x + 2 - it.length;
let mut c1_y = it_y + 41;
let mut c2_x = it_x + it.length + 82;
let mut c2_y = it_y + 41;
if it.orientation.sin().abs() == 1.0 {
c1_x = it_x + 4 + 38;
c1_y = it_y ;
c2_x = it_x + 4 + 38;
c2_y = it_y + it.length + 3 + 80;
}
draw_circle(&mut os_package.window_canvas, c1_x, c1_y, 4.0, C4_WHITE);
draw_circle(&mut os_package.window_canvas, c2_x, c2_y, 4.0, C4_WHITE);
}
if it.properties_z == get_global_properties_z()-1
&& it.properties_selected {
let font_size = 15f32;
let offset_x = if it.orientation.sin().abs() < 0.001 { -5 } else { 1 };
let offset_y = if it.orientation.sin().abs() < 0.001 { 0 } else { -10 };
//NOTE
//unique_a
let pos_x = if it.orientation.sin().abs() < 0.001 {
let _oset = if it.orientation.sin().signum() == -1f32 { -4 } else { 0 };
it_x + ((it.orientation / 2f32).sin().abs() * (GRID_SIZE * 4) as f32) as i32 + 6 * it.orientation.sin().signum() as i32 + _oset
} else {
it_x + (it.orientation.sin().abs() * (GRID_SIZE * 2) as f32) as i32
};
let pos_y = if it.orientation.sin().abs() < 0.001 {
it_y + (it.orientation.cos().abs() * (GRID_SIZE * 2) as f32) as i32
} else {
it_y + (( (it.orientation - PI/ 2f32) / 2f32 ).sin().abs() * (GRID_SIZE * 4) as f32) as i32 + 7 * it.orientation.sin().signum() as i32
};
draw_string(&mut os_package.window_canvas, &format!("{}", it.unique_a_node), pos_x + offset_x, pos_y + offset_y, C4_WHITE, font_size);
//NOTE
//unique_b
let pos_x = if it.orientation.sin().abs() < 0.001 {
let _oset = if it.orientation.sin().signum() == 1f32 { -4 } else { 0 };
it_x + ((it.orientation / 2f32).cos().abs() * (GRID_SIZE * 4) as f32) as i32 - 6 * it.orientation.sin().signum() as i32 + _oset
} else {
it_x + (it.orientation.sin().abs() * (GRID_SIZE * 2) as f32) as i32
};
let pos_y = if it.orientation.sin().abs() < 0.001 {
it_y + (it.orientation.cos().abs() * (GRID_SIZE * 2) as f32) as i32
} else {
it_y + (( (it.orientation - PI/ 2f32) / 2f32 ).cos().abs() * (GRID_SIZE * 4) as f32) as i32 - 7 * it.orientation.sin().signum() as i32
};
draw_string(&mut os_package.window_canvas, &format!("{}", it.unique_b_node), pos_x + offset_x, pos_y + offset_y, C4_WHITE, font_size);
}
let temp_bmp;
let mut bmp = &app_storage.resistor_bmp;
if it.circuit_element_type == SelectedCircuitElement::Battery{
bmp = &app_storage.battery_bmp;
if it.voltage < 0.0 {
temp_bmp = rotate_bmp(&mut app_storage.battery_bmp, PI).unwrap();
bmp = &temp_bmp;
}
} else if it.circuit_element_type == SelectedCircuitElement::Capacitor {
bmp = &app_storage.capacitor_bmp;
} else if it.circuit_element_type == SelectedCircuitElement::Inductor {
bmp = &app_storage.inductor_bmp;
} else if it.circuit_element_type == SelectedCircuitElement::Voltmeter {
bmp = &app_storage.voltmeter_bmp;
} else if it.circuit_element_type == SelectedCircuitElement::Ammeter {
bmp = &app_storage.ammeter_bmp;
} else if it.circuit_element_type == SelectedCircuitElement::Switch {
if it.resistance > 0.0 {
bmp = &app_storage.switch_open_bmp;
} else {
bmp = &app_storage.switch_closed_bmp;
}
} else if it.circuit_element_type == SelectedCircuitElement::AC {
bmp = &app_storage.ac_bmp;
} else if it.circuit_element_type == SelectedCircuitElement::Wire{
bmp = &app_storage.wire_bmp;
} else if it.circuit_element_type == SelectedCircuitElement::Custom
|| it.circuit_element_type == SelectedCircuitElement::CustomVoltmeter
|| it.circuit_element_type == SelectedCircuitElement::CustomAmmeter
{
bmp = &app_storage.custom_bmp;
}
let current_good = { if it.solved_current.is_some() {
true
}
else { false }
};
let orientation = it.orientation.sin().abs().round();
let mut direction = 0f32;
match it.direction{
Some(CircuitElementDirection::AtoB)=>{
direction = 1.0;
},
Some(CircuitElementDirection::BtoA)=>{
direction = -1.0;
},
None=>{},
}
if it.solved_current.is_none(){
it.alt_sim_time = 0f32;
}
let mut _bmp = sampling_reduction_bmp(bmp, 82, 80);
if it.selected_rotation{
let d_x = (mouseinfo.x - (it_x + 40)) as f32;//NOTE 40 is half of the bitmap width
let d_y = (mouseinfo.y - (it_y + 40)) as f32;//NOTE 40 is half the bitmap height
let mut theta = (d_x/(d_y.powi(2) + d_x.powi(2)).sqrt()).acos() - it.initial_altered_rotation;
{
if d_y < 0f32 {
theta *= -1f32;
}
}
let _rbmp = rotate_bmp(&mut _bmp, theta).unwrap();
draw_bmp(&mut os_package.window_canvas, &_rbmp, it_x, it_y, 0.7, None, None);
if mouseinfo.lclicked(){
//TODO !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
let _sin = theta.sin().round();
let _cos = theta.cos().round();
if _sin.abs() <= 0.5 {
if _cos >= 0f32 {
theta = 0f32;
}
else {
theta = PI;
}
} else {
if _sin >= 0f32 {
theta = FRAC_PI_2;
}
else {
theta = 3f32*FRAC_PI_2;
}
}
it.orientation = theta;
}
}
if it.print_current.is_some()
&& current_good{
let current = *it.print_current.as_ref().unwrap();
if app_storage.run_circuit {
it.alt_sim_time += TIME_STEP * current.abs() * direction;
}
render_current_wire(&mut _bmp, it.alt_sim_time);
if it.circuit_element_type == SelectedCircuitElement::Capacitor{//TODO this should be some where else
render_charge_capacitor(&mut _bmp, it.charge, it.capacitance);
}
}
if orientation == 0.0 {
let mut _bmp = rotate_bmp(&mut _bmp, it.orientation).unwrap();
draw_bmp(&mut os_package.window_canvas, &_bmp, it_x, it_y, 0.98, None, None); //TODO
if it.circuit_element_type == SelectedCircuitElement::Custom
|| it.circuit_element_type == SelectedCircuitElement::CustomVoltmeter
|| it.circuit_element_type == SelectedCircuitElement::CustomAmmeter{
change_font(FONT_NOTOSANS_BOLD);
let _adv = get_advance_string(it.label.as_ref(), 20f32);
draw_string(&mut os_package.window_canvas, it.label.as_ref(), it_x+_bmp.width/2-_adv/2-6, it_y + 3, C4_WHITE, 20f32);
change_font(FONT_NOTOSANS);
}
}
else if orientation == 1.0 {
let mut _bmp = rotate_bmp(&mut _bmp, it.orientation).unwrap();
draw_bmp(&mut os_package.window_canvas, &_bmp, it_x, it_y, 0.98, None, None);
if it.circuit_element_type == SelectedCircuitElement::Custom
|| it.circuit_element_type == SelectedCircuitElement::CustomVoltmeter
|| it.circuit_element_type == SelectedCircuitElement::CustomAmmeter{
change_font(FONT_NOTOSANS_BOLD);
let _adv = get_advance_string(it.label.as_ref(), 20f32);
draw_string(&mut os_package.window_canvas, it.label.as_ref(), it_x+_bmp.width/2, it_y+it.length/2-5, C4_WHITE, 20f32);
change_font(FONT_NOTOSANS);
}
}
let current_good = { if it.solved_current.is_some() {
if it.solved_current.as_mut().unwrap().abs() > 0.001 {true }
else { false }
}
else { false }
};
if current_good
&& app_storage.arrow_toggled {
//&& app_storage.teacher_mode {
match it.direction{
Some(CircuitElementDirection::AtoB)=>{
if orientation == 0.0 {
let rotated_bmp = rotate_bmp( &mut arrow_resize_bmp, PI).unwrap(); //TODO do this some where else further up stream maybe
draw_bmp( &mut os_package.window_canvas, &rotated_bmp, it_x + 30, it_y, 0.98, None, None);
} else if orientation == 1.0 {
let rotated_bmp = rotate_bmp(&mut arrow_resize_bmp, PI*3.0/2.0).unwrap();
draw_bmp( &mut os_package.window_canvas, &rotated_bmp, it_x+60, it_y +30, 0.98, None, None);
}
},
Some(CircuitElementDirection::BtoA)=>{
if orientation == 0.0 {
draw_bmp( &mut os_package.window_canvas, &arrow_resize_bmp, it_x+30, it_y, 0.98, None, None);
} else if orientation == 1.0 {
let rotated_bmp = rotate_bmp(&mut arrow_resize_bmp, FRAC_PI_2).unwrap();
draw_bmp( &mut os_package.window_canvas, &rotated_bmp, it_x+60, it_y+30, 0.98, None, None);
}
},
None=>{},
}
}
},
_=>{}
}
}
let properties_w = PROPERTIES_W;
let properties_h = PROPERTIES_H;
/////////////
let mut z_vec = Vec::with_capacity(app_storage.arr_circuit_elements.len());
for (i_it, it) in app_storage.arr_circuit_elements.iter().enumerate(){
if it.properties_selected{
z_vec.push(( i_it, it.properties_z ));
}
}
z_vec.sort_by( |a, b| b.1.cmp(&a.1) );
for zt in z_vec.iter().rev(){
let it = &mut app_storage.arr_circuit_elements[zt.0];
let px = match it.properties_offset_x{
Some(px) => {px},
None => { 0 },
};
let py = match it.properties_offset_y{
Some(py) => {py},
None => { 0 },
};
if px != py {
if in_rect(mouseinfo.x, mouseinfo.y, [px, py, properties_w, properties_h])
&& mouseinfo.old_lbutton == ButtonStatus::Up
&& mouseinfo.lbutton == ButtonStatus::Down
{
if it.properties_z < get_global_properties_z() - 1{
it.properties_z = get_and_update_global_properties_z();
}
}
}
}
z_vec.sort_by( |a, b| b.1.cmp(&a.1) );
for zt in z_vec.iter().rev(){
let it = &mut app_storage.arr_circuit_elements[zt.0];
let i_it = zt.0;
if it.properties_selected {//TODO should this be removed we already know that these elements have properties selected.
let node_a = it.unique_a_node;
let node_b = it.unique_b_node;
let mut label = String::new();
if it.circuit_element_type != SelectedCircuitElement::Custom
&& it.circuit_element_type != SelectedCircuitElement::CustomVoltmeter
&& it.circuit_element_type != SelectedCircuitElement::CustomAmmeter{
label += &format!("{:?}", it.circuit_element_type);
} else {
label += &format!("{}", it.label.as_ref());
}
let label = format!("{}: ({} {})", label, node_a, node_b);
let camera = get_camera();
let it_x = it.x + camera[0];
let it_y = it.y + camera[1];
let mut properties_x = it_x+it.length+95;
let mut properties_y = it_y-properties_h/2;
match it.properties_offset_x {
None => {
it.properties_offset_x = Some(properties_x);
it.properties_offset_y = Some(properties_y);
},
_=>{
properties_x = it.properties_offset_x.unwrap();
properties_y = it.properties_offset_y.unwrap();
}
}
if it.properties_z == get_global_properties_z() - 1{
draw_rect(&mut os_package.window_canvas, [properties_x, properties_y, properties_w, properties_h], COLOR_PROPERTY_BKG1, true);
//NOTE indication that panel can be moved.
if in_rect(mouseinfo.x, mouseinfo.y, [properties_x, properties_y+properties_h-30, properties_w, 30]){
draw_rect(&mut os_package.window_canvas, [properties_x, properties_y+properties_h-30, properties_w, 30], COLOR_PROPERTY_MOVE2, true);
} else {
draw_rect(&mut os_package.window_canvas, [properties_x, properties_y+properties_h-30, properties_w, 30], COLOR_PROPERTY_MOVE1, true);
}
} else {
draw_rect(&mut os_package.window_canvas, [properties_x, properties_y, properties_w, properties_h], COLOR_PROPERTY_BKG2, true);
}
draw_string(&mut os_package.window_canvas, &label, properties_x+2, properties_y+properties_h-30, COLOR_TEXT, 26.0);
{//Exit properties
let char_x_len = get_advance('x', 26.0);
let button_x = properties_x + properties_w - get_advance('x', 26.0) - 8;
let button_y = properties_y + properties_h - 26;
let mut color = C4_WHITE;
if in_rect(mouseinfo.x, mouseinfo.y, [button_x, button_y, char_x_len+5, 26]){
color = C4_RED;
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.properties_selected = false;
}
}
draw_string(&mut os_package.window_canvas, "x", button_x, button_y, color, 26.0);
}
//Delineation bar between header and info
draw_rect(&mut os_package.window_canvas, [properties_x+1, properties_y+properties_h-30, properties_w-2, 1], [0.3, 0.3, 0.3, 1.0], true);
{//move parameter panels
if in_rect(mouseinfo.x, mouseinfo.y, [properties_x, properties_y+properties_h-30, properties_w, 30]){
if mouseinfo.lbutton == ButtonStatus::Down
&& it.properties_z == get_global_properties_z() - 1{
it.properties_move_selected = true;
}
}
if mouseinfo.lbutton == ButtonStatus::Up{
it.properties_move_selected = false;
}
if it.properties_move_selected {
*it.properties_offset_x.as_mut().unwrap() += mouseinfo.delta_x;
*it.properties_offset_y.as_mut().unwrap() += mouseinfo.delta_y;
}
}
{
let mut offset_x = 0;
let mut offset_y = 57;
let textbox = app_storage.circuit_textbox_hash.get_mut(&(it.unique_a_node, it.unique_b_node)).expect("could not find textbox");
fn do_text_box_things( tb: &mut TextBox, properties_x: i32, properties_y: i32, _properties_w: i32, properties_h: i32, properties_z: usize,
textinfo: &TextInfo, mouseinfo: &MouseInfo, keyboardinfo: &KeyboardInfo,
it_property: &mut f32, window_canvas: &mut WindowCanvas, time: f32,
offset_x : &mut i32, offset_y: i32){
tb.x = properties_x+*offset_x;
tb.y = properties_y+properties_h-offset_y;
let tb_previously_active = tb.active;
if properties_z == get_global_properties_z()-1{
tb.update(keyboardinfo, textinfo, mouseinfo);
}
if keyboardinfo.key.contains(&KeyboardEnum::Enter) {
match tb.text_buffer.parse::<f32>(){
Ok(parsed_f32)=>{ *it_property = parsed_f32; },
Err(_)=>{},
}
}
if tb.active{
} else {
if tb_previously_active {
match tb.text_buffer.parse::<f32>(){
Ok(parsed_f32)=>{ *it_property = parsed_f32; },
Err(_)=>{},
}
}
tb.text_buffer.clear();
tb.text_cursor = 0;
tb.text_buffer += &format!("{:.2}", it_property);
}
tb.draw(window_canvas, time);
*offset_x += tb.max_render_length;
}
fn do_clear_button(canvas: &mut WindowCanvas, mouseinfo: &MouseInfo, properties_x: i32, properties_y: i32, properties_h: i32, properties_z: usize,
offset_x: i32, offset_y: i32, property: &mut f32, panel_font: f32){
let clear_rect = [properties_x+offset_x+14, properties_y+properties_h-offset_y+3, get_advance_string("clear", panel_font)+5, panel_font as _];
if in_rect(mouseinfo.x, mouseinfo.y, clear_rect){
draw_rect(canvas, clear_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& properties_z == get_global_properties_z() - 1{
*property = 0.0;
}
}
draw_string(canvas, "clear", properties_x+12+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
}
match it.circuit_element_type{
SelectedCircuitElement::Wire |
SelectedCircuitElement::Custom=>{
draw_string(&mut os_package.window_canvas, "No changeable properties.", properties_x, properties_y+properties_h-offset_y, C4_GREY, 20.0);
offset_y += 20;
if it.circuit_element_type == SelectedCircuitElement::Custom
&& app_storage.teacher_mode {
draw_string(&mut os_package.window_canvas, &format!("Resistance(Ω): {} {}", it.resistance, it.unc_resistance),
properties_x, properties_y+properties_h-offset_y, C4_LGREY, 20.0);
offset_y += 20;
draw_string(&mut os_package.window_canvas, &format!("Voltage(V): {} {}", it.voltage, it.unc_voltage),
properties_x, properties_y+properties_h-offset_y, C4_LGREY, 20.0);
offset_y += 20;
//draw_string(&mut os_package.window_canvas, &format!("Current(A): {} {}", it.current, it.unc_current),
// properties_x, properties_y+properties_h-offset_y, C4_LGREY, 20.0);
//offset_y += 20;
draw_string(&mut os_package.window_canvas, &format!("Capacitance(F): {} {}", it.capacitance, it.unc_capacitance),
properties_x, properties_y+properties_h-offset_y, C4_LGREY, 20.0);
offset_y += 20;
draw_string(&mut os_package.window_canvas, &format!("Inductance(H): {} {}", it.inductance, it.unc_inductance),
properties_x, properties_y+properties_h-offset_y, C4_LGREY, 20.0);
offset_y += 20;
draw_string(&mut os_package.window_canvas, &format!("Charge(C): {} {}", it.charge, it.unc_charge),
properties_x, properties_y+properties_h-offset_y, C4_LGREY, 20.0);
offset_y += 20;
draw_string(&mut os_package.window_canvas, &format!("Flux(Wb): {} {}", it.magnetic_flux, it.unc_magnetic_flux),
properties_x, properties_y+properties_h-offset_y, C4_LGREY, 20.0);
offset_y += 20;
}
},
SelectedCircuitElement::Battery=>{
offset_x += draw_string(&mut os_package.window_canvas, "Voltage(V): ", properties_x+2, properties_y+properties_h-offset_y, C4_GREY, panel_font);
do_text_box_things(&mut textbox.voltage_textbox, properties_x, properties_y, properties_w, properties_h, it.properties_z,
textinfo, mouseinfo, keyboardinfo, &mut it.voltage, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
&mut offset_x, offset_y);
offset_x += 5;
let plus_rect = [properties_x+offset_x+6, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, plus_rect){
draw_rect(&mut os_package.window_canvas, plus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.voltage += 1.0;
//TODO we need to reset solved values it there are solved values
}
}
offset_x += draw_char(&mut os_package.window_canvas, '+', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
offset_x += 10;
let minus_rect = [properties_x+offset_x+4, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, minus_rect){
draw_rect(&mut os_package.window_canvas, minus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.voltage -= 1.0;
}
}
offset_x += draw_char(&mut os_package.window_canvas, '-', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
do_clear_button(&mut os_package.window_canvas, mouseinfo, properties_x, properties_y, properties_h, it.properties_z,
offset_x, offset_y, &mut it.voltage, panel_font);
},
SelectedCircuitElement::Capacitor=>{
//TODO need ability to change values
offset_x += draw_string(&mut os_package.window_canvas, "Capacitance(F): ", properties_x+2, properties_y+properties_h-offset_y, C4_GREY, panel_font);
do_text_box_things(&mut textbox.capacitance_textbox, properties_x, properties_y, properties_w, properties_h, it.properties_z,
textinfo, mouseinfo, keyboardinfo, &mut it.capacitance, &mut os_package.window_canvas,
app_storage.timer.elapsed().as_secs_f32(),
&mut offset_x, offset_y);
offset_x += 5;
let plus_rect = [properties_x+offset_x+6, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, plus_rect){
draw_rect(&mut os_package.window_canvas, plus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.capacitance += 0.25;
}
}
offset_x += draw_char(&mut os_package.window_canvas, '+', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
offset_x += 10;
let minus_rect = [properties_x+offset_x+4, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, minus_rect){
draw_rect(&mut os_package.window_canvas, minus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.capacitance -= 0.25;
if it.capacitance < 0f32 { it.capacitance = 0.0; }
}
}
offset_x += draw_char(&mut os_package.window_canvas, '-', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
do_clear_button(&mut os_package.window_canvas, mouseinfo, properties_x, properties_y, properties_h, it.properties_z,
offset_x, offset_y, &mut it.capacitance, panel_font);
offset_y += 23;
offset_x = 0;
offset_x += draw_string(&mut os_package.window_canvas, "Charge(C): ", properties_x+2, properties_y+properties_h-offset_y, C4_GREY, panel_font);
do_text_box_things(&mut textbox.charge_textbox, properties_x, properties_y, properties_w, properties_h, it.properties_z,
textinfo, mouseinfo, keyboardinfo, &mut it.charge, &mut os_package.window_canvas,
app_storage.timer.elapsed().as_secs_f32(),
&mut offset_x, offset_y);
offset_x += 5;
let plus_rect = [properties_x+offset_x+6, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, plus_rect){
draw_rect(&mut os_package.window_canvas, plus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.charge += 0.25;
if it.charge.is_nan() || it.charge.is_infinite(){
it.charge = 0.0;
}
//TODO we need to reset solved values it there are solved values
}
}
offset_x += draw_char(&mut os_package.window_canvas, '+', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
offset_x += 10;
let minus_rect = [properties_x+offset_x+4, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, minus_rect){
draw_rect(&mut os_package.window_canvas, minus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.charge -= 0.25;
if it.charge.is_nan() || it.charge.is_infinite(){
it.charge = 0.0;
}
}
}
offset_x += draw_char(&mut os_package.window_canvas, '-', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
do_clear_button(&mut os_package.window_canvas, mouseinfo, properties_x, properties_y, properties_h, it.properties_z,
offset_x, offset_y, &mut it.charge, panel_font);
},
SelectedCircuitElement::Inductor=>{
offset_x += draw_string(&mut os_package.window_canvas, "Inductance(H): ", properties_x+2, properties_y+properties_h-offset_y, C4_GREY, panel_font);
do_text_box_things(&mut textbox.inductance_textbox, properties_x, properties_y, properties_w, properties_h, it.properties_z,
textinfo, mouseinfo, keyboardinfo, &mut it.inductance, &mut os_package.window_canvas,
app_storage.timer.elapsed().as_secs_f32(),
&mut offset_x, offset_y);
offset_x += 5;
let plus_rect = [properties_x+offset_x+6, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, plus_rect){
draw_rect(&mut os_package.window_canvas, plus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.inductance += 0.25;
//TODO we need to reset solved values it there are solved values
}
}
offset_x += draw_char(&mut os_package.window_canvas, '+', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
offset_x += 10;
let minus_rect = [properties_x+offset_x+4, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, minus_rect){
draw_rect(&mut os_package.window_canvas, minus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.inductance -= 0.25;
if it.inductance < 0f32 { it.capacitance = 0.0; }
}
}
offset_x += draw_char(&mut os_package.window_canvas, '-', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
do_clear_button(&mut os_package.window_canvas, mouseinfo, properties_x, properties_y, properties_h, it.properties_z,
offset_x, offset_y, &mut it.inductance, panel_font);
offset_y += 23;
offset_x = 0;
offset_x += draw_string(&mut os_package.window_canvas, "Flux(Wb): ", properties_x+2, properties_y+properties_h-offset_y, C4_GREY, panel_font);
do_text_box_things(&mut textbox.magflux_textbox, properties_x, properties_y, properties_w, properties_h, it.properties_z,
textinfo, mouseinfo, keyboardinfo, &mut it.magnetic_flux, &mut os_package.window_canvas,
app_storage.timer.elapsed().as_secs_f32(),
&mut offset_x, offset_y);
offset_x += 5;
let plus_rect = [properties_x+offset_x+6, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, plus_rect){
draw_rect(&mut os_package.window_canvas, plus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.magnetic_flux += 1.0;
if it.magnetic_flux.is_nan() || it.magnetic_flux.is_infinite(){
it.magnetic_flux = 0.0;
}
}
}
offset_x += draw_char(&mut os_package.window_canvas, '+', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
offset_x += 10;
let minus_rect = [properties_x+offset_x+4, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, minus_rect){
draw_rect(&mut os_package.window_canvas, minus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.magnetic_flux -= 1.0;
if it.magnetic_flux.is_nan() || it.magnetic_flux.is_infinite(){
it.magnetic_flux = 0.0;
}
}
}
offset_x += draw_char(&mut os_package.window_canvas, '-', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
do_clear_button(&mut os_package.window_canvas, mouseinfo, properties_x, properties_y, properties_h, it.properties_z,
offset_x, offset_y, &mut it.magnetic_flux, panel_font);
},
SelectedCircuitElement::Resistor=>{
offset_x += draw_string(&mut os_package.window_canvas, "Resistance(Ω): ", properties_x+2, properties_y+properties_h-offset_y, C4_GREY, panel_font);
do_text_box_things(&mut textbox.resistance_textbox, properties_x, properties_y, properties_w, properties_h, it.properties_z,
textinfo, mouseinfo, keyboardinfo, &mut it.resistance, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
&mut offset_x, offset_y);
offset_x += 5;
let plus_rect = [properties_x+offset_x+6, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, plus_rect){
draw_rect(&mut os_package.window_canvas, plus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.resistance += 1.0;
}
}
offset_x += draw_char(&mut os_package.window_canvas, '+', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
offset_x += 10;
let minus_rect = [properties_x+offset_x+4, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, minus_rect){
draw_rect(&mut os_package.window_canvas, minus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.resistance -= 1.0;
}
}
offset_x += draw_char(&mut os_package.window_canvas, '-', properties_x+2+offset_x, properties_y+properties_h-offset_y+1, C4_WHITE, panel_font);
do_clear_button(&mut os_package.window_canvas, mouseinfo, properties_x, properties_y, properties_h, it.properties_z,
offset_x, offset_y, &mut it.resistance, panel_font);
},
SelectedCircuitElement::Voltmeter | SelectedCircuitElement::CustomVoltmeter=>{
draw_string(&mut os_package.window_canvas, "No changeable properties.", properties_x, properties_y+properties_h-offset_y, C4_GREY, 20.0);
if it.circuit_element_type == SelectedCircuitElement::CustomVoltmeter
&& app_storage.teacher_mode {
offset_y += 20;
draw_string(&mut os_package.window_canvas, &format!("Bias: {:.3} Noise: {:.3} Drift: {:.3}", it.bias, it.noise, it.drift),
properties_x, properties_y+properties_h-offset_y, C4_LGREY, 20.0);
offset_y += 20;
}
},
SelectedCircuitElement::Ammeter | SelectedCircuitElement::CustomAmmeter=>{
draw_string(&mut os_package.window_canvas, "No changeable properties.", properties_x, properties_y+properties_h-offset_y, C4_GREY, 20.0);
if it.circuit_element_type == SelectedCircuitElement::CustomAmmeter
&& app_storage.teacher_mode {
offset_y += 20;
draw_string(&mut os_package.window_canvas, &format!("Bias: : {} Noise: {} Drift: {}", it.bias, it.noise, it.drift),
properties_x, properties_y+properties_h-offset_y, C4_LGREY, 20.0);
offset_y += 20;
}
},
SelectedCircuitElement::Switch=>{
let mut open_color = C4_WHITE;
let mut closed_color = C4_GREY;
if it.resistance == 0.0{
open_color = C4_GREY;
closed_color = C4_WHITE;
}
let mut _offset = get_advance_string( "Open", 24f32 );
let open_rect = [properties_x+5, properties_y+properties_h-offset_y, _offset, 24];
if in_rect(mouseinfo.x, mouseinfo.y, open_rect){
draw_rect(&mut os_package.window_canvas, open_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.resistance = VOLTMETER_RESISTANCE;
}
}
draw_string(&mut os_package.window_canvas, "Open", properties_x, properties_y+properties_h-offset_y, open_color, 24.0);
_offset += get_advance_string("/", 24.0);
let __offset = get_advance_string( "Closed", 24.0);
let closed_rect = [properties_x+__offset+10, properties_y+properties_h-offset_y, __offset, 24];
if in_rect(mouseinfo.x, mouseinfo.y, closed_rect){//CLOSED
draw_rect(&mut os_package.window_canvas, closed_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.resistance = 0.0;
}
}
_offset += draw_string(&mut os_package.window_canvas, "/ ", properties_x+_offset, properties_y+properties_h-offset_y, C4_LGREY, 24.0);
draw_string(&mut os_package.window_canvas, "Closed", properties_x+_offset, properties_y+properties_h-offset_y, closed_color, 24.0);
},
SelectedCircuitElement::AC =>{
offset_x += draw_string(&mut os_package.window_canvas, "Max Voltage(V): ", properties_x+2, properties_y+properties_h-offset_y, C4_GREY, panel_font);
do_text_box_things(&mut textbox.max_voltage_textbox, properties_x, properties_y, properties_w, properties_h, it.properties_z,
textinfo, mouseinfo, keyboardinfo, &mut it.max_voltage, &mut os_package.window_canvas,
app_storage.timer.elapsed().as_secs_f32(),
&mut offset_x, offset_y);
offset_x += 5;
let plus_rect = [properties_x+offset_x+6, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, plus_rect){
draw_rect(&mut os_package.window_canvas, plus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.voltage = it.voltage/it.max_voltage;
it.max_voltage += 1.0;
it.voltage *= it.max_voltage;
//TODO we need to reset solved values it there are solved values
}
}
offset_x += draw_char(&mut os_package.window_canvas, '+', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
offset_x += 10;
let minus_rect = [properties_x+offset_x+4, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, minus_rect){
draw_rect(&mut os_package.window_canvas, minus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.voltage = it.voltage/it.max_voltage;
it.max_voltage -= 1.0;
if it.max_voltage < 0f32 { it.max_voltage = 0.0; }
it.voltage *= it.max_voltage;
}
}
offset_x += draw_char(&mut os_package.window_canvas, '-', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
do_clear_button(&mut os_package.window_canvas, mouseinfo, properties_x, properties_y, properties_h, it.properties_z,
offset_x, offset_y, &mut it.max_voltage, panel_font);
offset_y += 23;
offset_x = 0;
offset_x += draw_string(&mut os_package.window_canvas, "Frequency(Hz): ", properties_x+2, properties_y+properties_h-offset_y, C4_GREY, panel_font);
do_text_box_things(&mut textbox.frequency_textbox, properties_x, properties_y, properties_w, properties_h, it.properties_z,
textinfo, mouseinfo, keyboardinfo, &mut it.frequency, &mut os_package.window_canvas,
app_storage.timer.elapsed().as_secs_f32(),
&mut offset_x, offset_y);
offset_x += 5;
let plus_rect = [properties_x+offset_x+6, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, plus_rect){
draw_rect(&mut os_package.window_canvas, plus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.d_voltage_over_dt = it.d_voltage_over_dt / ( 2f32 * PI * it.frequency );
it.frequency += 0.25;
it.d_voltage_over_dt = it.d_voltage_over_dt * it.frequency * 2f32 * PI;
}
}
offset_x += draw_char(&mut os_package.window_canvas, '+', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
offset_x += 10;
let minus_rect = [properties_x+offset_x+4, properties_y+properties_h-offset_y+9, 10, 10];
if in_rect(mouseinfo.x, mouseinfo.y, minus_rect){
draw_rect(&mut os_package.window_canvas, minus_rect, C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.d_voltage_over_dt = it.d_voltage_over_dt / ( 2f32 * PI * it.frequency );
it.frequency -= 0.25;
if it.frequency < 0f32 {
it.frequency = 0.00001;
}
it.d_voltage_over_dt = it.d_voltage_over_dt * it.frequency * 2f32 * PI;
}
}
offset_x += draw_char(&mut os_package.window_canvas, '-', properties_x+2+offset_x, properties_y+properties_h-offset_y, C4_WHITE, panel_font);
do_clear_button(&mut os_package.window_canvas, mouseinfo, properties_x, properties_y, properties_h, it.properties_z,
offset_x, offset_y, &mut it.frequency, panel_font);
offset_y += 23;
offset_x = 0;
offset_x += draw_string(&mut os_package.window_canvas, "Source Type: ", properties_x+2, properties_y+properties_h-offset_y, C4_GREY, panel_font);
let mut step_color = C4_GREY;
let mut sin_color = C4_LGREY;
if it.ac_source_type == ACSourceType::Step{
step_color = C4_WHITE;
sin_color = C4_GREY;
}
let sin_offset_x = get_advance_string("Sin ", panel_font);
if in_rect(mouseinfo.x, mouseinfo.y, [properties_x+offset_x+4, properties_y+properties_h-offset_y, sin_offset_x, panel_font as i32]){
draw_rect(&mut os_package.window_canvas, [properties_x+offset_x+4, properties_y+properties_h-offset_y, sin_offset_x, panel_font as i32], C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.ac_source_type = ACSourceType::Sin;
}
}
draw_string(&mut os_package.window_canvas, "Sin ", properties_x+offset_x+2, properties_y+properties_h-offset_y, sin_color, panel_font);
offset_x += sin_offset_x;
offset_x += draw_string(&mut os_package.window_canvas, "/ ", properties_x+offset_x+2, properties_y+properties_h-offset_y, C4_GREY, panel_font);
let step_offset_x = get_advance_string( "Step ", panel_font);
if in_rect(mouseinfo.x, mouseinfo.y, [properties_x+offset_x+4, properties_y+properties_h-offset_y, step_offset_x, panel_font as i32]){
draw_rect(&mut os_package.window_canvas, [properties_x+offset_x+4, properties_y+properties_h-offset_y, step_offset_x, panel_font as i32], C4_DGREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.ac_source_type = ACSourceType::Step;
}
}
draw_string(&mut os_package.window_canvas, "Step ", properties_x+offset_x+2, properties_y+properties_h-offset_y, step_color, panel_font);
offset_x += step_offset_x;
},
_=>{panic!("TODO");}
}
offset_y += 23;
if app_storage.teacher_mode {
match it.print_current{
Some(c)=>{
draw_string(&mut os_package.window_canvas, &format!("Solv. Current(A): {:.2}", c), properties_x+2, properties_y+properties_h-offset_y, COLOR_TEXT_SOLV, panel_font);
},
None=>{},
}
offset_y += 20;
match it.print_voltage{
Some(v)=>{
draw_string(&mut os_package.window_canvas, &format!("Voltage Diff(V): {:.2}", v), properties_x+2, properties_y+properties_h-offset_y, COLOR_TEXT_SOLV, panel_font);
},
None=>{},
}
} else {
if it.circuit_element_type == SelectedCircuitElement::Voltmeter || it.circuit_element_type == SelectedCircuitElement::CustomVoltmeter{
match it.print_voltage{
Some(v)=>{
let voltage = v;
draw_string(&mut os_package.window_canvas, &format!("Voltage (V): {:.2}", voltage), properties_x+2, properties_y+properties_h-offset_y, COLOR_TEXT_SOLV, panel_font);
offset_y += (properties_h/2 - 5).max(45);
let y_x = app_storage.saved_circuit_volts.get_mut(&(it.unique_a_node, it.unique_b_node)).expect("Could not find node");
draw_graph(&mut os_package.window_canvas, &y_x[1], &y_x[0],
[properties_x+2, properties_y+properties_h-offset_y, properties_w-4, (properties_h/2).max(50)],
5.0, 18.0, mouseinfo);
offset_y += 23;
let save_rect = [properties_x+properties_w-62, properties_y+properties_h-offset_y, 60, 20];
let mut save_rect_color = C4_DGREY;
if in_rect(mouseinfo.x, mouseinfo.y, save_rect){
save_rect_color = C4_GREY;
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
let filename = generate_csv_name(&format!("voltmeter_{}_{}.csv", node_a, node_b));
save_csv(&filename, &[&y_x[1], &y_x[0]], &["time(s)", "voltage(V)"]);
app_storage.messages.push( (MessageType::Default, format!("Message: {} saved.", filename)) );
}
}
draw_rect(&mut os_package.window_canvas, save_rect, save_rect_color, true);
draw_string(&mut os_package.window_canvas, "Save", save_rect[0]+8, save_rect[1]-4, C4_WHITE, 22.0);
let clear_rect = [properties_x+properties_w-124, properties_y+properties_h-offset_y, 60, 20];
let mut clear_rect_color = C4_DGREY;
if in_rect(mouseinfo.x, mouseinfo.y, clear_rect){
clear_rect_color = C4_GREY;
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
y_x[0].clear();
y_x[1].clear();
it.time = 0f32;
}
}
draw_rect(&mut os_package.window_canvas, clear_rect, clear_rect_color, true);
draw_string(&mut os_package.window_canvas, "Clear", clear_rect[0]+8, clear_rect[1]-4, C4_WHITE, 22.0);
},
None=>{
offset_y += (properties_h/2 - 5).max(45);
draw_graph(&mut os_package.window_canvas, &[], &[],
[properties_x+2, properties_y+properties_h-offset_y, properties_w-4, (properties_h/2).max(50)],
5.0, 18.0, mouseinfo);
change_font(FONT_NOTOSANS_BOLD);
draw_string(&mut os_package.window_canvas, "No Data", properties_x+properties_w/2-50, properties_y+properties_h-offset_y+45, C4_BLACK, 30.0);
change_font(FONT_NOTOSANS);
},
}
}
if it.circuit_element_type == SelectedCircuitElement::Ammeter || it.circuit_element_type == SelectedCircuitElement::CustomAmmeter{
match it.print_current{
Some(c)=>{
let current = c;
draw_string(&mut os_package.window_canvas, &format!("Current(A): {:.2}", current), properties_x+2, properties_y+properties_h-offset_y, COLOR_TEXT_SOLV, panel_font);
offset_y += (properties_h/2 - 5).max(45);
let y_x = app_storage.saved_circuit_currents.get_mut(&(it.unique_a_node, it.unique_b_node)).expect("Could not find node");
draw_graph(&mut os_package.window_canvas, &y_x[1], &y_x[0],
[properties_x+2, properties_y+properties_h-offset_y, properties_w-4, (properties_h/2).max(50)],
5.0, 18.0, mouseinfo);
offset_y += 22;
let save_rect = [properties_x+properties_w-62, properties_y+properties_h-offset_y, 60, 20];
let mut save_rect_color = C4_DGREY;
if in_rect(mouseinfo.x, mouseinfo.y, save_rect){
save_rect_color = C4_GREY;
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
let filename = generate_csv_name(&format!("ammeter_{}_{}.csv", node_a, node_b));
save_csv(&filename, &[&y_x[1], &y_x[0]], &["time(s)", "current(A)"]);
app_storage.messages.push( (MessageType::Default, format!("Message: {} saved.", filename, )) );
}
}
draw_rect(&mut os_package.window_canvas, save_rect, save_rect_color, true);
draw_string(&mut os_package.window_canvas, "Save", save_rect[0]+8, save_rect[1]-4, C4_WHITE, 22.0);
let clear_rect = [properties_x+properties_w-124, properties_y+properties_h-offset_y, 60, 20];
let mut clear_rect_color = C4_DGREY;
if in_rect(mouseinfo.x, mouseinfo.y, clear_rect){
clear_rect_color = C4_GREY;
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
y_x[0].clear();
y_x[1].clear();
it.time = 0f32;
}
}
draw_rect(&mut os_package.window_canvas, clear_rect, clear_rect_color, true);
draw_string(&mut os_package.window_canvas, "Clear", clear_rect[0]+8, clear_rect[1]-4, C4_WHITE, 22.0);
},
None=>{
offset_y += (properties_h/2 - 5).max(45);
draw_graph(&mut os_package.window_canvas, &[], &[],
[properties_x+2, properties_y+properties_h-offset_y, properties_w-4, (properties_h/2).max(50)],
5.0, 18.0, mouseinfo);
change_font(FONT_NOTOSANS_BOLD);
draw_string(&mut os_package.window_canvas, "No Data", properties_x+properties_w/2-50, properties_y+properties_h-offset_y+45, C4_DGREY, 30.0);
change_font(FONT_NOTOSANS);
},
}
}
}
}
//Delineation bar between info and image manipulation
draw_rect(&mut os_package.window_canvas, [properties_x+1, properties_y+35, properties_w-2, 1], C4_DGREY, true);
////Rotate Button
let rotation_button_width = {
let button_x = properties_x+5;
let button_w = get_advance_string("Rotate", 22.0) + 10; //TODO something weird is going on with get_advanced. something I don't understand. the width is not correct
let button_h = 25;
let button_y = properties_y + 5;
draw_rect(&mut os_package.window_canvas, [button_x, button_y, button_w, button_h], C4_DGREY, true);
if in_rect(mouseinfo.x, mouseinfo.y,[button_x, button_y, button_w, button_h]){
draw_rect(&mut os_package.window_canvas, [button_x, button_y, button_w, button_h], C4_GREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
it.orientation += FRAC_PI_2;
//if (it.orientation/PI).abs().fract() < 0.001 { it.orientation = 0.0; }
//else if (it.orientation/(PI/2.0)).abs().fract() < 0.001 { it.orientation = PI/2.0; }
}
}
draw_string(&mut os_package.window_canvas, "Rotate", button_x, button_y-3, C4_LGREY, 22.0);
button_w
};
////Delete Button
let delete_button_width = {
let button_x = properties_x+rotation_button_width+10;
let button_w = get_advance_string("Delete", 22.0) + 10; //TODO something weird is going on with get_advanced. something I don't understand. the width is not correct
let button_h = 25;
let button_y = properties_y + 5;
draw_rect(&mut os_package.window_canvas, [button_x, button_y, button_w, button_h], C4_DGREY, true);
if in_rect(mouseinfo.x, mouseinfo.y,[button_x, button_y, button_w, button_h]){
draw_rect(&mut os_package.window_canvas, [button_x, button_y, button_w, button_h], C4_GREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
delete_list.push(i_it);
}
}
draw_string(&mut os_package.window_canvas, "Delete", button_x, button_y-3, C4_LGREY, 22.0);
button_w
};
////Duplicate Button
{
let button_x = properties_x+rotation_button_width+delete_button_width+15;
let button_w = get_advance_string("Delete", 22.0) + 10; //TODO something weird is going on with get_advanced. something I don't understand. the width is not correct
let copy_w = get_advance_string("Copy", 22.0) + 10; //TODO something weird is going on with get_advanced. something I don't understand. the width is not correct
let button_h = 25;
let button_y = properties_y + 5;
draw_rect(&mut os_package.window_canvas, [button_x, button_y, button_w, button_h], C4_DGREY, true);
if in_rect(mouseinfo.x, mouseinfo.y,[button_x, button_y, button_w, button_h]){
draw_rect(&mut os_package.window_canvas, [button_x, button_y, button_w, button_h], C4_GREY, true);
if mouseinfo.lclicked()
&& it.properties_z == get_global_properties_z() - 1{
app_storage.selected_circuit_element = it.circuit_element_type;
app_storage.selected_circuit_element_orientation = it.orientation;
it.properties_selected = false;
let mut copied_circuit = CircuitElement::new();
copied_circuit.resistance = it.resistance;
copied_circuit.voltage = it.voltage;
copied_circuit.current = it.current;
copied_circuit.capacitance = it.capacitance;
copied_circuit.inductance = it.inductance;
copied_circuit.charge = it.charge;
copied_circuit.magnetic_flux = it.magnetic_flux;
copied_circuit.max_voltage = it.max_voltage;
copied_circuit.d_voltage_over_dt = it.d_voltage_over_dt;
copied_circuit.frequency = it.frequency;
copied_circuit.ac_source_type = it.ac_source_type;
copied_circuit.bias = it.bias;
copied_circuit.noise = it.noise;
copied_circuit.drift = it.drift;
app_storage.selected_circuit_properties = Some(copied_circuit);
}
}
draw_string(&mut os_package.window_canvas, "Copy", button_x + (button_w - copy_w)/2, button_y-3, C4_LGREY, 22.0);
}
}
}
////////////////////////////
loop{
let it = delete_list.pop();
match it {
Some(n)=>{
let a_b = (app_storage.arr_circuit_elements[n].unique_a_node, app_storage.arr_circuit_elements[n].unique_b_node);
app_storage.saved_circuit_volts.remove(&a_b);
app_storage.saved_circuit_currents.remove(&a_b);
app_storage.arr_circuit_elements.remove(n);
},
None=>{break;},
}
}
}
//////////////////////////////////////////////////////////////////////
let temp_w = app_storage.menu_canvas.canvas.w;
let temp_h = app_storage.menu_canvas.canvas.h;
//Draw Background Color
draw_rect(&mut app_storage.menu_canvas.canvas, [0, 0, temp_w, temp_h], COLOR_MENU_BKG, true);
if app_storage.menu_move_activated == true
|| app_storage.menu_offscreen == false {//Render panels
let i = app_storage.panel_index;
let panel = &mut app_storage.arr_panels[i];
let mut current_cursor_position = temp_h - 35;
for p in panel.contents.iter_mut(){
match p {
PanelContent::Image(im) => {
let ratio_w = im.width as f32 / temp_w as f32 ;
let mut w = None;
let mut h = None;
if ratio_w > 0.6{
w = Some( (0.6 * temp_w as f32) as i32 );
h = Some(((0.6 * temp_w as f32 / im.width as f32) * im.height as f32) as i32 );
current_cursor_position -= ((0.6 * temp_w as f32 / im.width as f32) * im.height as f32) as i32;
} else {
current_cursor_position -= im.height;
}
let x = match w { Some(_w)=>{ temp_w/2 - _w/2 }, None=>{ temp_w/2 - im.width/2} } ;
draw_bmp(&mut app_storage.menu_canvas.canvas, im, x, current_cursor_position, 0.999, w, h);
},
PanelContent::Text(text) => {
let strings = generate_wrapped_strings(&text, 26.0, temp_w);
//TODO
//cap length.
for i in 0..strings.len(){
current_cursor_position -= 24;
draw_string(&mut app_storage.menu_canvas.canvas, &strings[i], 10, current_cursor_position, COLOR_TEXT, 26.0);
}
},
PanelContent::Header(text) => {
change_font(FONT_NOTOSANS_BOLD);
let strings = generate_wrapped_strings(&text, 32.0, temp_w);
for i in 0..strings.len(){
current_cursor_position -= 30;
draw_string(&mut app_storage.menu_canvas.canvas, &strings[i], 10, current_cursor_position, COLOR_TEXT, 32.0);
}
change_font(FONT_NOTOSANS);
},
PanelContent::Question(mq) => {
if mq.answer_index.is_none() {
//TODO we have a problem
panic!();
}
change_font(FONT_MERRIWEATHER_LIGHT);
let strings = generate_wrapped_strings(&mq.question, 26.0, temp_w);
change_font(FONT_NOTOSANS);
current_cursor_position -= 26;
change_font(FONT_NOTOSANS_BOLD);
draw_string(&mut app_storage.menu_canvas.canvas, "Question:", 10, current_cursor_position, COLOR_TEXT, 30.0);
change_font(FONT_NOTOSANS);
current_cursor_position -= 30;
for i in 0..strings.len(){
change_font(FONT_MERRIWEATHER_LIGHT);
draw_string(&mut app_storage.menu_canvas.canvas, &strings[i], 10, current_cursor_position, COLOR_TEXT, 24.0);
change_font(FONT_NOTOSANS);
current_cursor_position -= 24;
}
current_cursor_position += 20;
let choice_arr = vec!["A)", "B)","C)","D)","E)", "F)", "H)"];
let mut rects_arr = vec![];
for i in 0..mq.choices.len() {
let strings = generate_wrapped_strings(&mq.choices[i], 24.0, temp_w);
let string_width = draw_string(&mut app_storage.menu_canvas.canvas, &choice_arr[i], 3, current_cursor_position, COLOR_TEXT, 24.0);
rects_arr.push([3, current_cursor_position+2, string_width + 3, 24]);
for j in 0..strings.len(){
rects_arr[i][2] += draw_string(&mut app_storage.menu_canvas.canvas, &strings[j], 20, current_cursor_position, COLOR_TEXT, 24.0);
current_cursor_position -= 13;
}
}
if mq.answers.len() < mq.number_chances{ //TODO how should this work... I don't know
for i in 0..rects_arr.len(){
//TODO make this general
if in_rect(mouseinfo.x - window_w + temp_w, mouseinfo.y, rects_arr[i]){
draw_rect(&mut app_storage.menu_canvas.canvas, rects_arr[i], C4_YELLOW, false);
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down{
mq.answers.push(i);
if i == mq.answer_index.unwrap() { mq.number_chances = 0; } //NOTE: we may not want to use number of chances in this way. It changes the meaning of the phrase.
}
}
}
if mq.answers.len() > 0 {
let index = mq.answers.len()-1;
if mq.answers[index] != mq.answer_index.unwrap() {
change_font(FONT_NOTOSANS_BOLD);
draw_string(&mut app_storage.menu_canvas.canvas, &format!("Incorrect: {}/{}", mq.answers.len(), mq.number_chances), 2, current_cursor_position+15, C4_DGREY, 22.0);
change_font(FONT_NOTOSANS);
}
}
} else {
if mq.answers.len() > 0 {
let index = mq.answers.len()-1;
if mq.answers[index] == mq.answer_index.unwrap() {
change_font(FONT_NOTOSANS_BOLD);
draw_string(&mut app_storage.menu_canvas.canvas, "Correct", 2, current_cursor_position+15, C4_DGREY, 22.0);
change_font(FONT_NOTOSANS);
} else {
change_font(FONT_NOTOSANS_BOLD);
draw_string(&mut app_storage.menu_canvas.canvas, &format!("Incorrect: The answer is ({}", choice_arr[mq.answer_index.unwrap()]), 2, current_cursor_position+15, C4_DGREY, 22.0);
change_font(FONT_NOTOSANS);
}
}
}
},
_=>{},
}
}
if i < app_storage.arr_panels.len()-1
&& !app_storage.menu_offscreen{
let x = os_package.window_canvas.w - app_storage.menu_canvas.canvas.w;
if in_rect(mouseinfo.x - x, mouseinfo.y, [temp_w-102, 10, 102, 30]){
draw_rect(&mut app_storage.menu_canvas.canvas, [temp_w-102, 10, 102, 30], C4_GREY, true);
if mouseinfo.lclicked() {
app_storage.panel_index += 1;
}
} else {
draw_rect(&mut app_storage.menu_canvas.canvas, [temp_w-102, 10, 102, 30], C4_DGREY, true);
}
draw_string(&mut app_storage.menu_canvas.canvas, "Continue", temp_w - 100, 10, C4_WHITE, 26.0);
}
if i > 0
&& !app_storage.menu_offscreen{
let x = os_package.window_canvas.w - app_storage.menu_canvas.canvas.w;
if in_rect(mouseinfo.x - x, mouseinfo.y, [0, 10, 102, 30]){
draw_rect(&mut app_storage.menu_canvas.canvas, [0, 10, 102, 30], C4_GREY, true);
if mouseinfo.lclicked() {
app_storage.panel_index -= 1;
}
} else {
draw_rect(&mut app_storage.menu_canvas.canvas, [0, 10, 102, 30], C4_DGREY, true);
}
draw_string(&mut app_storage.menu_canvas.canvas, "Previous", 2, 10, C4_WHITE, 26.0);
}
}
{//NOTE toggle arrows
let arrow_rect = [ window_w - 125, window_h - 25, 20, 20];
let mut arrow_bmp = sampling_reduction_bmp(&app_storage.arrow_bmp, 22,22);
if in_rect(mouseinfo.x, mouseinfo.y, arrow_rect) {
if app_storage.arrow_toggled { render_red(&mut arrow_bmp)}
else {render_grey(&mut arrow_bmp);}
if mouseinfo.lclicked()
&& app_storage.menu_offscreen {
app_storage.arrow_toggled = !app_storage.arrow_toggled;
}
} else {
if app_storage.arrow_toggled { render_pink(&mut arrow_bmp) }
}
draw_bmp(&mut os_package.window_canvas, &arrow_bmp, arrow_rect[0], arrow_rect[1], 0.98, None, None);
}
{//NOTE screen shot
let screenshot_rect = [ window_w - 95, window_h - 25, 20, 20];
let mut icon_bmp = app_storage.screenshot_icon_bmp.clone();
if in_rect(mouseinfo.x, mouseinfo.y, screenshot_rect) {
render_grey(&mut icon_bmp);
if mouseinfo.lclicked()
&& app_storage.menu_offscreen {
let mut bmp = TGBitmap::new(os_package.window_canvas.w, os_package.window_canvas.h);
bmp.file_header.off_bits = 54; //TODO
bmp.file_header.size_ = (4*bmp.width * bmp.height) as u32 + bmp.file_header.off_bits;
bmp.info_header.header_size = 40;
bmp.info_header.compression = 0;
bmp.info_header.image_size = (4*bmp.width * bmp.height) as u32;
bmp.info_header.x_px_per_meter = 1;
bmp.info_header.y_px_per_meter = 1;
unsafe{
let buffer = os_package.window_canvas.buffer as *const u8;
for i in 0..(bmp.width*bmp.height) as usize{
bmp.rgba[4*i + 0] = *buffer.offset(4*i as isize + 0);
bmp.rgba[4*i + 1] = *buffer.offset(4*i as isize + 1);
bmp.rgba[4*i + 2] = *buffer.offset(4*i as isize + 2);
bmp.rgba[4*i + 3] = *buffer.offset(4*i as isize + 3);
}
}
bmp.save_bmp("screenshot.bmp");//TODO search for conflicts
app_storage.messages.push((MessageType::Default, "Message: screenshot saved to screenshot.bmp".to_string()));
}
}
draw_bmp(&mut os_package.window_canvas, &icon_bmp, screenshot_rect[0], screenshot_rect[1], 0.98, Some(20), Some(20));
}
//////////////////////////////////////////////////////////////////////
//NOTE draw circuit ingredient panel
{
let subcanvas_w = app_storage.circuit_element_canvas.canvas.w;
let subcanvas_h = app_storage.circuit_element_canvas.canvas.h;
let x_offset = circuit_element_canvas_x_offset;
let y_offset = circuit_element_canvas_y_offset;
let mut standard_color = C4_WHITE;
let mut unique_color = C4_DGREY;
if app_storage.circuit_menu_type != CircuitMenuType::Default{
standard_color = C4_DGREY;
unique_color = C4_WHITE;
}
{//Standard button
let std_rect = [25, y_offset+subcanvas_h-1, subcanvas_w/2, 25];
draw_rect(&mut os_package.window_canvas, std_rect, standard_color, true);
if in_rect(mouseinfo.x, mouseinfo.y, std_rect)
&& mouseinfo.lclicked(){
app_storage.circuit_menu_type = CircuitMenuType::Default;
}
change_font(FONT_NOTOSANS_BOLD);
let adv = get_advance_string("Standard", 24.0) + 4;
draw_string(&mut os_package.window_canvas, "Standard", std_rect[0]+subcanvas_w/4-adv/2, std_rect[1]-4, C4_GREY, 24.0);
change_font(FONT_NOTOSANS);
}
{//Custom button
let unq_rect = [25 + subcanvas_w/2, y_offset+subcanvas_h-1, subcanvas_w/2-1, 25];
draw_rect(&mut os_package.window_canvas, unq_rect, unique_color, true);
if in_rect(mouseinfo.x, mouseinfo.y, unq_rect)
&& mouseinfo.lclicked(){
app_storage.circuit_menu_type = CircuitMenuType::Custom;
}
change_font(FONT_NOTOSANS_BOLD);
let adv = get_advance_string("Custom", 24.0) + 4;
draw_string(&mut os_package.window_canvas, "Custom", 25+(3*subcanvas_w)/4-adv/2, unq_rect[1]-4, C4_GREY, 24.0);
change_font(FONT_NOTOSANS);
}
if app_storage.teacher_mode
&& app_storage.circuit_menu_type == CircuitMenuType::Custom{//Save button
let save_rect = [25 + subcanvas_w/2, y_offset-25, subcanvas_w/2-1, 25];
draw_rect(&mut os_package.window_canvas, save_rect, C4_RED, true);
if in_rect(mouseinfo.x, mouseinfo.y, save_rect)
&& mouseinfo.lclicked(){
save_circuit_diagram(CUSTOM_FILE_NAME, &app_storage.custom_circuit_elements);
app_storage.messages.push((MessageType::Default, "Message: A custom circuit set has been saved.".to_string()));
}
change_font(FONT_NOTOSANS_BOLD);
let adv = get_advance_string("Save", 24.0) + 4;
draw_string(&mut os_package.window_canvas, "Save", save_rect[0] + save_rect[2]/2 - adv/2, save_rect[1]-4, C4_WHITE, 24.0);
change_font(FONT_NOTOSANS);
}
if app_storage.circuit_menu_type == CircuitMenuType::Custom{
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [0, 0, subcanvas_w, subcanvas_h], C4_WHITE, true);
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [3, 3, subcanvas_w-6, subcanvas_h-6], COLOR_MENU_BKG, true);
let mut index : i32 = 0;
for it in app_storage.custom_circuit_elements.iter(){
let rect = [80*(index%2)+5+4, subcanvas_h - 70*((index+2)/2) - 5, 80, 70];
let _rect = [rect[0]-15+x_offset, rect[1]-15 + y_offset, 80, 70];
draw_bmp(&mut app_storage.circuit_element_canvas.canvas, &app_storage.custom_bmp, rect[0] + 15, rect[1] + 15, 0.98, Some(50), Some(50));
let mut temp_str = it.label.as_ref().to_string();
temp_str.truncate(8);
let string_length = get_advance_string(&temp_str, 23.0);
draw_string(&mut app_storage.circuit_element_canvas.canvas, &temp_str, rect[0]-8 + rect[2]/2 - string_length/2, rect[1]-5, C4_WHITE, 23.0);
if in_rect(mouseinfo.x, mouseinfo.y, _rect){
draw_rect(&mut app_storage.circuit_element_canvas.canvas, rect, C4_YELLOW, false);
if mouseinfo.lclicked(){
app_storage.create_custom_circuit = true;
app_storage.custom_circuit_cursor = index as usize;
}
if mouseinfo.rclicked()
&& app_storage.teacher_mode {
app_storage.panel_custom_circuit = true;
app_storage.custom_circuit_cursor = index as usize;
}
}
index += 1;
}
if app_storage.custom_circuit_cursor < app_storage.custom_circuit_elements.len()
&& app_storage.create_custom_circuit {
app_storage.selected_circuit_element = SelectedCircuitElement::Custom;
app_storage.create_custom_circuit = false;
}
if app_storage.teacher_mode {
//TODO check if there are less that 10 elements
let rect = [80*(index%2)+5, subcanvas_h - 70*((index+2)/2) - 5, 80, 70];
let add_x_offset = 25;
let add_y_offset = 5;
let _rect = [rect[0]-15+x_offset, rect[1]-15 + y_offset, 80, 70];
draw_char(&mut app_storage.circuit_element_canvas.canvas, '+', rect[0] + add_x_offset, rect[1]+add_y_offset, C4_WHITE, 50.0);
if in_rect(mouseinfo.x, mouseinfo.y, _rect){
draw_rect(&mut app_storage.circuit_element_canvas.canvas, rect, C4_YELLOW, false);
if mouseinfo.lclicked(){
let mut circuit_element = CircuitElement::empty();
circuit_element.label.copystr(&format!("Custom {}", index));
circuit_element.circuit_element_type = SelectedCircuitElement::Custom;
app_storage.custom_circuit_elements.push(circuit_element);
app_storage.panel_custom_circuit = true;
app_storage.custom_circuit_cursor = index as usize;
}
}
let mut remove_element = false;
if app_storage.panel_custom_circuit
&& app_storage.custom_circuit_cursor < app_storage.custom_circuit_elements.len(){
let properties_rect = [subcanvas_w+20+x_offset, y_offset, PROPERTIES_W, subcanvas_h];
let mut prop_y_offset = subcanvas_h + y_offset - 30;
draw_rect(&mut os_package.window_canvas, properties_rect, C4_BLACK, true);
draw_string(&mut os_package.window_canvas, "Custom Element Builder", properties_rect[0]+2, prop_y_offset, C4_WHITE, 28.0);
prop_y_offset -= 30;
{//Exit properties
let char_x_len = get_advance('x', 26.0);
let button_x = properties_rect[0] + properties_rect[2] - get_advance('x', 26.0) - 8;
let button_y = properties_rect[1] + properties_rect[3] - 26;
let mut color = C4_WHITE;
if in_rect(mouseinfo.x, mouseinfo.y, [button_x, button_y, char_x_len+5, 26]){
color = C4_RED;
if mouseinfo.lclicked(){
app_storage.panel_custom_circuit = false;
}
}
draw_char(&mut os_package.window_canvas, 'x', button_x, button_y, color, 26.0);
}
let it = &mut app_storage.custom_circuit_elements[app_storage.custom_circuit_cursor];
let c_textbox = &mut app_storage.custom_circuit_textbox;
let lstr_len = draw_string(&mut os_package.window_canvas, "Label: ", properties_rect[0], prop_y_offset, C4_WHITE, PANEL_FONT);
draw_string(&mut os_package.window_canvas, it.label.as_ref(), properties_rect[0] + lstr_len, prop_y_offset, C4_WHITE, PANEL_FONT);
{//
c_textbox.label_textbox.x = properties_rect[0] + lstr_len;
c_textbox.label_textbox.y = prop_y_offset;
c_textbox.label_textbox.text_buffer.clear();
c_textbox.label_textbox.text_buffer.push_str(it.label.as_ref());
c_textbox.label_textbox.update(keyboardinfo, textinfo, mouseinfo);
c_textbox.label_textbox.draw(&mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32());
//Sync
//TODO we will run into problems if custom names overlap
for jt in app_storage.arr_circuit_elements.iter_mut(){
if it.label == jt.label
&& (jt.circuit_element_type == SelectedCircuitElement::Custom
|| jt.circuit_element_type == SelectedCircuitElement::CustomVoltmeter
|| jt.circuit_element_type == SelectedCircuitElement::CustomAmmeter){
jt.label.copystr(&c_textbox.label_textbox.text_buffer);
}
}
it.label.copystr(&c_textbox.label_textbox.text_buffer);
}
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
{//Select type of custom element
use ui_tools::*;
let mut cl_x_offset = properties_rect[0];
let mut custom_bg = C4_DGREY;
let mut voltme_bg = C4_DGREY;
let mut ammete_bg = C4_DGREY;
let font_size = 18f32;
if it.circuit_element_type == SelectedCircuitElement::Custom{
custom_bg = C4_GREY;
} else if it.circuit_element_type == SelectedCircuitElement::CustomVoltmeter {
voltme_bg = C4_GREY;
} else if it.circuit_element_type == SelectedCircuitElement::CustomAmmeter {
ammete_bg = C4_GREY;
}
{
set_button_bg_color1(custom_bg);
let brt = basic_button( &mut os_package.window_canvas, "Custom", cl_x_offset, prop_y_offset, font_size, mouseinfo );
cl_x_offset += brt.rect[2];
if brt.lclicked {
it.circuit_element_type = SelectedCircuitElement::Custom;
}
}
{
set_button_bg_color1(voltme_bg);
let brt = basic_button( &mut os_package.window_canvas, "Custom Voltmeter", cl_x_offset, prop_y_offset, font_size, mouseinfo );
cl_x_offset += brt.rect[2];
if brt.lclicked {
it.circuit_element_type = SelectedCircuitElement::CustomVoltmeter;
}
}
{
set_button_bg_color1(ammete_bg);
let brt = basic_button( &mut os_package.window_canvas, "Custom Ammeter", cl_x_offset, prop_y_offset, font_size, mouseinfo );
cl_x_offset += brt.rect[2];
if brt.lclicked {
it.circuit_element_type = SelectedCircuitElement::CustomAmmeter;
}
}
reset_button_bg_color1();
}
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
fn do_text_box_things( tb: &mut TextBox, properties_x: i32, properties_y: i32,
textinfo: &TextInfo, mouseinfo: &MouseInfo, keyboardinfo: &KeyboardInfo,
it_property: &mut f32, window_canvas: &mut WindowCanvas, time: f32,
){
tb.x = properties_x;
tb.y = properties_y;
let tb_previously_active = tb.active;
tb.update(keyboardinfo, textinfo, mouseinfo);
if keyboardinfo.key.contains(&KeyboardEnum::Enter) {
match tb.text_buffer.parse::<f32>(){
Ok(parsed_f32)=>{ *it_property = parsed_f32; },
Err(_)=>{},
}
}
if tb.active{
} else {
if tb_previously_active {
match tb.text_buffer.parse::<f32>(){
Ok(parsed_f32)=>{ *it_property = parsed_f32; },
Err(_)=>{},
}
}
tb.text_buffer.clear();
tb.text_cursor = 0;
tb.text_buffer += &format!("{:.2}", it_property);
}
tb.draw(window_canvas, time);
}
if it.circuit_element_type == SelectedCircuitElement::CustomVoltmeter
|| it.circuit_element_type == SelectedCircuitElement::CustomAmmeter{
{
let rstr_len = draw_string(&mut os_package.window_canvas, "Bias: ", properties_rect[0], prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.bias_textbox, properties_rect[0] + rstr_len, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.bias, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
if it.circuit_element_type == SelectedCircuitElement::CustomVoltmeter{
it.resistance = VOLTMETER_RESISTANCE;
}
}
{
let rstr_len = draw_string(&mut os_package.window_canvas, "Noise: ", properties_rect[0], prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.noise_textbox, properties_rect[0] + rstr_len, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.noise, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
}
{
let rstr_len = draw_string(&mut os_package.window_canvas, "Drift: ", properties_rect[0], prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.drift_textbox, properties_rect[0] + rstr_len, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.drift, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
if it.drift > 1f32 {
it.drift = 1f32;
} else if it.drift < 0f32 {
it.drift = 0f32;
}
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
draw_string(&mut os_package.window_canvas, "d := drift, p_m := previous_measurement", properties_rect[0], prop_y_offset, C4_WHITE, 18f32);
prop_y_offset -= (18f32 + 2f32) as i32;
draw_string(&mut os_package.window_canvas, "m := current nominal measurement", properties_rect[0], prop_y_offset, C4_WHITE, 18f32);
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
draw_string(&mut os_package.window_canvas, "measurement :=", properties_rect[0], prop_y_offset, C4_WHITE, 18f32);
prop_y_offset -= (18f32 + 2f32) as i32;
draw_string(&mut os_package.window_canvas, "d * p_m + (1-d) * (m +bias) + sample_N(noise)", properties_rect[0], prop_y_offset, C4_WHITE, 18f32);
prop_y_offset -= (18f32 + 2f32) as i32;
draw_string(&mut os_package.window_canvas, "A good drift is 0.8.", properties_rect[0], prop_y_offset, C4_WHITE, 18f32);
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
}
} else if it.circuit_element_type == SelectedCircuitElement::Custom{
let pm_len = get_advance_string( "+ ", PANEL_FONT);
let textbox_width = c_textbox.resistance_textbox.max_render_length + 5 + pm_len + c_textbox.unc_resistance_textbox.max_render_length;
let textbox_x = properties_rect[0] + properties_rect[2] - textbox_width;
{
draw_string(&mut os_package.window_canvas, "Resistance(Ω): ", properties_rect[0], prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.resistance_textbox, textbox_x, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.resistance, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
let _len = textbox_x+c_textbox.resistance_textbox.max_render_length;
let pm_len = draw_string(&mut os_package.window_canvas, "+ ", _len,
prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.unc_resistance_textbox, _len + pm_len, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.unc_resistance, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
}
{
draw_string(&mut os_package.window_canvas, "Voltage(V): ", properties_rect[0], prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.voltage_textbox, textbox_x, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.voltage, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
let _len = textbox_x+c_textbox.voltage_textbox.max_render_length;
let pm_len = draw_string(&mut os_package.window_canvas, "+ ", _len,
prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.unc_voltage_textbox, _len + pm_len, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.unc_voltage, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
}
//{
// let cstr_len = draw_string(&mut os_package.window_canvas, "Current(A): ", properties_rect[0], prop_y_offset, C4_WHITE, PANEL_FONT);
// do_text_box_things( &mut c_textbox.current_textbox, properties_rect[0] + cstr_len, prop_y_offset,
// textinfo, mouseinfo, keyboardinfo,
// &mut it.current, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
// );
// let _len = properties_rect[0]+cstr_len+c_textbox.current_textbox.max_render_length;
// let pm_len = draw_string(&mut os_package.window_canvas, "±: ", _len,
// prop_y_offset, C4_WHITE, PANEL_FONT);
// do_text_box_things( &mut c_textbox.unc_current_textbox, _len + pm_len, prop_y_offset,
// textinfo, mouseinfo, keyboardinfo,
// &mut it.unc_current, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
// );
// prop_y_offset -= (PANEL_FONT + 2f32) as i32;
//}
{
draw_string(&mut os_package.window_canvas, "Capacitance(F): ", properties_rect[0], prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.capacitance_textbox, textbox_x, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.capacitance, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
let _len = textbox_x + c_textbox.capacitance_textbox.max_render_length;
let pm_len = draw_string(&mut os_package.window_canvas, "+ ", _len,
prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.unc_capacitance_textbox, _len + pm_len, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.unc_capacitance, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
}
{
draw_string(&mut os_package.window_canvas, "Inductance(H): ", properties_rect[0], prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.inductance_textbox, textbox_x, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.inductance, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
let _len = textbox_x+c_textbox.inductance_textbox.max_render_length;
let pm_len = draw_string(&mut os_package.window_canvas, "+ ", _len,
prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.unc_inductance_textbox, _len + pm_len, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.unc_inductance, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
}
{
draw_string(&mut os_package.window_canvas, "Charge(C): ", properties_rect[0], prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.charge_textbox, textbox_x, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.charge, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
let _len = textbox_x+c_textbox.charge_textbox.max_render_length;
let pm_len = draw_string(&mut os_package.window_canvas, "+ ", _len,
prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.unc_charge_textbox, _len + pm_len, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.unc_charge, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
}
{
draw_string(&mut os_package.window_canvas, "Flux(Wb): ", properties_rect[0], prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.magflux_textbox, textbox_x, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.magnetic_flux, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
let _len = textbox_x+c_textbox.magflux_textbox.max_render_length;
let pm_len = draw_string(&mut os_package.window_canvas, "+ ", _len,
prop_y_offset, C4_WHITE, PANEL_FONT);
do_text_box_things( &mut c_textbox.unc_magflux_textbox, _len + pm_len, prop_y_offset,
textinfo, mouseinfo, keyboardinfo,
&mut it.unc_magnetic_flux, &mut os_package.window_canvas, app_storage.timer.elapsed().as_secs_f32(),
);
prop_y_offset -= (PANEL_FONT + 2f32) as i32;
}
}
//////////
//Syncing
for jt in app_storage.arr_circuit_elements.iter_mut(){
if it.label == jt.label
&& jt.circuit_element_type == SelectedCircuitElement::Custom{
jt.resistance = it.resistance;
jt.voltage = it.voltage;
jt.current = it.current;
jt.capacitance= it.capacitance;
jt.inductance = it.inductance;
jt.charge = it.charge;
jt.magnetic_flux = it.magnetic_flux;
jt.unc_resistance = sample_normal(it.unc_resistance);
jt.unc_voltage = sample_normal(it.unc_voltage);
jt.unc_current = sample_normal(it.unc_current);
jt.unc_capacitance = sample_normal(it.unc_capacitance);
jt.unc_inductance = sample_normal(it.unc_inductance);
jt.unc_charge = sample_normal(it.unc_charge);
jt.unc_magnetic_flux = sample_normal(it.unc_magnetic_flux);
jt.bias = 0f32;
jt.noise = 0f32;
jt.drift = 0f32;
}
if it.label == jt.label
&& jt.circuit_element_type == SelectedCircuitElement::CustomVoltmeter{
jt.resistance = VOLTMETER_RESISTANCE;
jt.voltage = 0f32;
jt.current = 0f32;
jt.capacitance= 0f32;
jt.inductance = 0f32;
jt.charge = 0f32;
jt.magnetic_flux = 0f32;
jt.unc_resistance = 0f32;
jt.unc_voltage = 0f32;
jt.unc_current = 0f32;
jt.unc_capacitance = 0f32;
jt.unc_inductance = 0f32;
jt.unc_charge = 0f32;
jt.unc_magnetic_flux = 0f32;
jt.bias = it.bias;
jt.noise = it.noise;
jt.drift = it.drift;
}
if it.label == jt.label
&& jt.circuit_element_type == SelectedCircuitElement::CustomAmmeter{
jt.resistance = WIRE_RESISTANCE;
jt.voltage = 0f32;
jt.current = 0f32;
jt.capacitance= 0f32;
jt.inductance = 0f32;
jt.charge = 0f32;
jt.magnetic_flux = 0f32;
jt.unc_resistance = 0f32;
jt.unc_voltage = 0f32;
jt.unc_current = 0f32;
jt.unc_capacitance = 0f32;
jt.unc_inductance = 0f32;
jt.unc_charge = 0f32;
jt.unc_magnetic_flux = 0f32;
jt.bias = it.bias;
jt.noise = it.noise;
jt.drift = it.drift;
}
}
////////
{//Delete element
let _w = get_advance_string("Delete", PANEL_FONT);
let d_w = _w + 16;
let d_x = properties_rect[0] + properties_rect[2] - d_w - 5;
let d_h = PANEL_FONT as i32 + 2;
let d_y = properties_rect[1] + 2;
let rect = [d_x, d_y, d_w, d_h];
draw_rect(&mut os_package.window_canvas, rect, C4_DGREY, true);
if in_rect(mouseinfo.x, mouseinfo.y, rect) {
draw_rect(&mut os_package.window_canvas, rect, C4_LGREY, true);
if mouseinfo.lclicked() {
remove_element = true;
}
}
draw_string(&mut os_package.window_canvas, "Delete", d_x + d_w / 2 - _w / 2 - 5, d_y, C4_LGREY, PANEL_FONT);
}
}
if remove_element {
app_storage.custom_circuit_elements.remove(app_storage.custom_circuit_cursor);
app_storage.create_custom_circuit = false;
}
}
}
else if app_storage.circuit_menu_type == CircuitMenuType::Default{
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [0, 0, subcanvas_w, subcanvas_h], C4_WHITE, true);
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [3, 3, subcanvas_w-6, subcanvas_h-6], COLOR_MENU_BKG, true);
//TODO remake assets
let alter_offset_y = 10;//TODO BAD
///////////////////////
{ // Resistor
let resistor_xy = [20, 280+alter_offset_y];
draw_bmp(&mut app_storage.circuit_element_canvas.canvas, &app_storage.resistor_bmp, resistor_xy[0], resistor_xy[1], 0.98, Some(50), Some(50));
draw_string(&mut app_storage.circuit_element_canvas.canvas, "Resistor", resistor_xy[0] - 10, resistor_xy[1] - 15, COLOR_TEXT, 23.0);
let _rect = [resistor_xy[0]-15+x_offset, resistor_xy[1]-15 + y_offset, 80, 70];
if in_rect(mouseinfo.x, mouseinfo.y, _rect){
//NOTE Resistor
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [resistor_xy[0]-15, resistor_xy[1]-15, 80, 70], C4_YELLOW, false);
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down {
app_storage.selected_circuit_element = SelectedCircuitElement::Resistor;
}
}
}
{ // Voltmeter
let voltm_xy = [110, 280+alter_offset_y];
draw_bmp(&mut app_storage.circuit_element_canvas.canvas, &app_storage.voltmeter_bmp, voltm_xy[0], voltm_xy[1], 0.98, Some(50), Some(50));
draw_string(&mut app_storage.circuit_element_canvas.canvas, "Voltmeter", voltm_xy[0]-15, voltm_xy[1]-15, COLOR_TEXT, 23.0);
let _rect = [voltm_xy[0]-15+x_offset, voltm_xy[1]-15+y_offset, 80, 70];
if in_rect(mouseinfo.x, mouseinfo.y, _rect ){
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [voltm_xy[0]-15, voltm_xy[1]-15, 80, 70], C4_YELLOW, false);
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down {
app_storage.selected_circuit_element = SelectedCircuitElement::Voltmeter;
}
}
}
{ //Wire
let wire_xy = [20, 237+alter_offset_y];
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [wire_xy[0], wire_xy[1], 50, 2], C4_WHITE, true);
draw_string(&mut app_storage.circuit_element_canvas.canvas, "Wire", wire_xy[0]+5, wire_xy[1]-45+6, COLOR_TEXT, 23.0);
let _rect = [wire_xy[0]-15+x_offset, wire_xy[1]-35+y_offset, 80, 65];
if in_rect(mouseinfo.x, mouseinfo.y, _rect ){
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [wire_xy[0]-15, wire_xy[1]-35, 80, 65], C4_YELLOW, false);
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down {
app_storage.selected_circuit_element = SelectedCircuitElement::Wire;
}
}
}
{//Ammeter
let ammeter_xy = [110, 212+alter_offset_y];
draw_bmp(&mut app_storage.circuit_element_canvas.canvas, &app_storage.ammeter_bmp, ammeter_xy[0], ammeter_xy[1], 0.98, Some(50), Some(50));
draw_string(&mut app_storage.circuit_element_canvas.canvas, "Ammeter", ammeter_xy[0]-15, ammeter_xy[1]-20+5, COLOR_TEXT, 23.0);
let _rect = [ammeter_xy[0]-15+x_offset, ammeter_xy[1]-10+y_offset, 80, 65];
if in_rect(mouseinfo.x, mouseinfo.y, _rect ){
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [ammeter_xy[0]-15, ammeter_xy[1]-10, 80, 65], C4_YELLOW, false);
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down {
app_storage.selected_circuit_element = SelectedCircuitElement::Ammeter;
}
}
}
{//Battery
let battery_xy = [20, 145+alter_offset_y];
draw_bmp(&mut app_storage.circuit_element_canvas.canvas, &app_storage.battery_bmp, battery_xy[0], battery_xy[1], 0.98, Some(50), Some(50));
draw_string(&mut app_storage.circuit_element_canvas.canvas, "Battery", battery_xy[0]-5, battery_xy[1]-15, COLOR_TEXT, 23.0);
let _rect = [battery_xy[0]-15+x_offset, battery_xy[1]-15+y_offset, 80, 65];
if in_rect(mouseinfo.x, mouseinfo.y, _rect ){
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [battery_xy[0]-15, battery_xy[1]-15, 80, 65], C4_YELLOW, false);
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down {
app_storage.selected_circuit_element = SelectedCircuitElement::Battery;
}
}
}
{//Inductor
let inductor_xy = [110, 145+alter_offset_y];
draw_bmp(&mut app_storage.circuit_element_canvas.canvas, &app_storage.inductor_bmp, inductor_xy[0], inductor_xy[1], 0.98, Some(50), Some(50));
draw_string(&mut app_storage.circuit_element_canvas.canvas, "Inductor", inductor_xy[0]-12, inductor_xy[1]-15, COLOR_TEXT, 23.0);
let _rect = [inductor_xy[0]-15+x_offset, inductor_xy[1]-15+y_offset, 80, 65];
if in_rect(mouseinfo.x, mouseinfo.y, _rect ){
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [inductor_xy[0]-15, inductor_xy[1]-15, 80, 65], C4_YELLOW, false);
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down {
app_storage.selected_circuit_element = SelectedCircuitElement::Inductor;
}
}
}
{//Capacitor
let capacitor_xy = [20, 75+alter_offset_y];
draw_bmp(&mut app_storage.circuit_element_canvas.canvas, &app_storage.capacitor_bmp, capacitor_xy[0], capacitor_xy[1], 0.98, Some(50), Some(50));
draw_string(&mut app_storage.circuit_element_canvas.canvas, "Capacitor", capacitor_xy[0]-15, capacitor_xy[1]-15, COLOR_TEXT, 23.0);
let _rect = [capacitor_xy[0]-15+x_offset, capacitor_xy[1]-15+y_offset, 80, 65];
if in_rect(mouseinfo.x, mouseinfo.y, _rect ){
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [capacitor_xy[0]-15, capacitor_xy[1]-15, 80, 65], C4_YELLOW, false);
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down {
app_storage.selected_circuit_element = SelectedCircuitElement::Capacitor;
}
}
}
{//Switch
let switch_xy = [110, 75+alter_offset_y];
draw_bmp(&mut app_storage.circuit_element_canvas.canvas, &app_storage.switch_open_bmp, switch_xy[0], switch_xy[1], 0.98, Some(50), Some(50));
draw_string(&mut app_storage.circuit_element_canvas.canvas, "Switch", switch_xy[0]-5, switch_xy[1]-15, COLOR_TEXT, 23.0);
let _rect = [switch_xy[0]-15+x_offset, switch_xy[1]-15+y_offset, 80, 65];
if in_rect(mouseinfo.x, mouseinfo.y, _rect ){
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [switch_xy[0]-15, switch_xy[1]-15, 80, 65], C4_YELLOW, false);
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down {
app_storage.selected_circuit_element = SelectedCircuitElement::Switch;
}
}
}
{//AC
let ac_xy = [20, 5+alter_offset_y];
draw_bmp(&mut app_storage.circuit_element_canvas.canvas, &app_storage.ac_bmp, ac_xy[0], ac_xy[1]+5, 0.98, Some(50), Some(50));
draw_string(&mut app_storage.circuit_element_canvas.canvas, "AC", ac_xy[0]+10, ac_xy[1]-13, COLOR_TEXT, 23.0);
let _rect = [ac_xy[0]-15+x_offset, ac_xy[1]-15+y_offset, 80, 65];
if in_rect(mouseinfo.x, mouseinfo.y, _rect ){
draw_rect(&mut app_storage.circuit_element_canvas.canvas, [ac_xy[0]-15, ac_xy[1]-10, 80, 65], C4_YELLOW, false);
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down {
app_storage.selected_circuit_element = SelectedCircuitElement::AC;
}
}
}
}
draw_subcanvas(&mut os_package.window_canvas, &app_storage.circuit_element_canvas, x_offset, y_offset, 1.0);
}
//////////////////////////////////////////////////////////////////////
let mut subcanvas_x = 0;
{//Moving subcanvas
let mut x = os_package.window_canvas.w - app_storage.menu_canvas.canvas.w;
let mut short_cut_pressed = 0;
for it in keyboardinfo.key.iter(){
if *it == KeyboardEnum::A
|| *it == KeyboardEnum::Ctrl{ //TODO we need to change how keyboard info works
short_cut_pressed += 1;
}
}
if short_cut_pressed == 2
&& app_storage.menu_move_activated_time == 0{
app_storage.menu_move_activated = true;
app_storage.menu_move_activated_time = app_storage.timer.elapsed().as_micros();
}
let rect_main_canvas = [window_w-25, window_h-26, 20, 20];
let rect_sub_ = [x+5, temp_h-25, 20, 20];
let rect_sub = [ 5, temp_h-25, 20, 20];
let mut color = C4_WHITE;
if app_storage.menu_offscreen {
if in_rect(mouseinfo.x, mouseinfo.y, rect_main_canvas) {
color = C4_LGREY;
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down{
app_storage.menu_move_activated = true;
app_storage.menu_move_activated_time = app_storage.timer.elapsed().as_micros();
}
}
} else {
if in_rect(mouseinfo.x, mouseinfo.y, rect_sub_) { //NOTE if subcanvas is on screen
color = C4_LGREY;
if mouseinfo.lbutton == ButtonStatus::Up && mouseinfo.old_lbutton == ButtonStatus::Down{
app_storage.menu_move_activated = true;
app_storage.menu_move_activated_time = app_storage.timer.elapsed().as_micros();
}
}
}
for i in 1..4{
let y = (5.0 * i as f32) as i32 + rect_main_canvas[1];
let _rect = [rect_main_canvas[0], y, rect_main_canvas[2], 2];
draw_rect(&mut os_package.window_canvas, _rect, color, true);
}
for i in 1..4{
let y = (5.0 * i as f32) as i32 + rect_sub[1];
let _rect = [rect_sub[0], y, rect_sub[2], 2];
draw_rect(&mut app_storage.menu_canvas.canvas, _rect, color, true);
}
let delta_max_time = DELTA_MAX_TIME_PANEL_MOVE;
if app_storage.menu_move_activated {
let delta = (app_storage.timer.elapsed().as_micros() - app_storage.menu_move_activated_time) as f32;
x = ((os_package.window_canvas.w - app_storage.menu_canvas.canvas.w) as f32 * ((delta_max_time + delta) / delta_max_time)) as i32; //TODO
if app_storage.menu_offscreen {
x = ((window_w as f32 - (delta/delta_max_time) * (window_w as f32 / 2.0)) as i32).max(os_package.window_canvas.w - app_storage.menu_canvas.canvas.w); //TODO
}
if delta.abs() > delta_max_time{
app_storage.menu_move_activated = false;
app_storage.menu_move_activated_time = 0;
app_storage.menu_offscreen = !app_storage.menu_offscreen; //TODO this is kinda trash will need to rewrite
}
}
if app_storage.menu_offscreen && app_storage.menu_move_activated == false {
x = window_w;
}
subcanvas_x = x;
}
//NOTE save and load circuit
{
let mut icon = &app_storage.save_icon_bmp;
let mut icon_rect = [window_w-65, window_h-28, 26, 26];
let mut _icon_rect = [window_w-65, window_h-28, 26, 26];
let mut rect = [window_w-icon_rect[2]-300, icon_rect[1]-35, 110, 31];
let canvas;
draw_bmp(&mut os_package.window_canvas, icon, icon_rect[0], icon_rect[1], 0.98, Some(icon_rect[2]), Some(icon_rect[3]));
draw_bmp(&mut app_storage.menu_canvas.canvas, icon, 30, icon_rect[1], 0.98, Some(icon_rect[2]), Some(icon_rect[3]));
if !app_storage.menu_offscreen{
icon_rect = [subcanvas_x+30, window_h-28, 26, 26];
_icon_rect = [30, window_h-28, 26, 26];
rect = [0, icon_rect[1]-35, 110, 31];
canvas = &mut app_storage.menu_canvas.canvas;
} else {
canvas = &mut os_package.window_canvas;
}
{
if app_storage.save_toggle == true{
icon = &app_storage.save_icon_bmp_alt;
draw_bmp(canvas, icon, _icon_rect[0], _icon_rect[1], 0.98, Some(icon_rect[2]), Some(icon_rect[3]));
}
if in_rect(mouseinfo.x, mouseinfo.y, icon_rect){
icon = &app_storage.save_icon_bmp_alt;
if mouseinfo.lclicked() {
app_storage.save_toggle = !app_storage.save_toggle;
}
draw_bmp(canvas, icon, _icon_rect[0], _icon_rect[1], 0.98, Some(icon_rect[2]), Some(icon_rect[3]));
}
if app_storage.save_toggle {
let mut previously_saved_circuits = vec![];
let mut previously_saved_custom = vec![];
let mut previously_saved_panels = vec![];
for it in std::fs::read_dir("./").unwrap(){//TODO why so many layers deep this is stupid
if it.is_ok(){
let ref_it = it.as_ref().unwrap().path();
if ref_it.is_file(){
match ref_it.extension(){
Some(temp_str)=>{
if temp_str == "cd"{
previously_saved_circuits.push(ref_it.to_str().unwrap().to_string());
}
if temp_str == "cce"{
previously_saved_custom.push(ref_it.to_str().unwrap().to_string());
}
if temp_str == "exp"{
previously_saved_panels.push(ref_it.to_str().unwrap().to_string());
}
},
_=>{}
}
}
}
}
//TODO set background color
fn _button_fn(canvas: &mut WindowCanvas, text_input: &str,
menu_rect: &[i32; 4], subcanvas_x: i32, menu_x: i32,
menu_font: f32, mouseinfo: &MouseInfo, menu_offscreen: bool, mut bg_color: [f32;4])->(i32, bool){
let length = get_advance_string(text_input, menu_font)+8;
let mut _rect = [menu_rect[0]+menu_x-3, menu_rect[1], length, menu_rect[3]];//TODO Handle when in menu canvas
let _rect_in = if !menu_offscreen { [_rect[0]+subcanvas_x, _rect[1], _rect[2], _rect[3]] }
else { _rect };
let mut clicked = false;
if in_rect(mouseinfo.x, mouseinfo.y, _rect_in) {
bg_color = C4_LGREY;
if mouseinfo.lclicked(){
clicked = true;
}
}
_rect[0] += 4;
_rect[1] += 2;
_rect[2] -= 4;
_rect[3] -= 4;
draw_rect(canvas, _rect, bg_color, true);
let x = draw_string(canvas, text_input, menu_rect[0]+menu_x, menu_rect[1]-3, C4_WHITE, menu_font);
return (x+8, clicked);
}
let rect_background_width = 330;
{
let _rect = if !app_storage.menu_offscreen{
[rect[0], rect[1]-100, rect_background_width, 130]
} else {
[rect[0], rect[1]-100, rect_background_width, 130]
};
draw_rect(canvas, _rect, C4_BLACK, true);
}
let mut offset_y = 0;
{
let menu_font = 26.0;
let mut menu_rect = [rect[0]+2, rect[1], 325, menu_font as i32 ];
let mut menu_x = 0;
if !app_storage.menu_offscreen {
menu_rect[0] = 2;
}
draw_rect(canvas, menu_rect, C4_BLACK, true);
change_font(FONT_NOTOSANS_BOLD);
let base_bg_color = [0.3, 0.3, 0.3, 1.0];
let l_bg_color = [0.7, 0.7, 0.7, 1.0];
let c_bg_color = if app_storage.save_toggle_programelements == ProgramElementsEnum::Circuit { l_bg_color }
else { base_bg_color };
let c_button_result = _button_fn(canvas, "Circuit", &menu_rect, subcanvas_x, menu_x, menu_font, mouseinfo, app_storage.menu_offscreen, c_bg_color);
menu_x += c_button_result.0;
if c_button_result.1 {
app_storage.save_toggle_programelements = ProgramElementsEnum::Circuit;
}
let sp_bg_color = if app_storage.save_toggle_programelements == ProgramElementsEnum::SidePanel { l_bg_color }
else { base_bg_color };
let sp_button_result = _button_fn(canvas, "SidePanel", &menu_rect, subcanvas_x, menu_x, menu_font, mouseinfo, app_storage.menu_offscreen, sp_bg_color);
menu_x += sp_button_result.0;
if sp_button_result.1 {
app_storage.save_toggle_programelements = ProgramElementsEnum::SidePanel;
}
let ce_bg_color = if app_storage.save_toggle_programelements == ProgramElementsEnum::CustomElement { l_bg_color }
else { base_bg_color };
let ce_button_result = _button_fn(canvas, "CustomElements", &menu_rect, subcanvas_x, menu_x, menu_font, mouseinfo, app_storage.menu_offscreen, ce_bg_color);
menu_x += ce_button_result.0;
if ce_button_result.1 {
app_storage.save_toggle_programelements = ProgramElementsEnum::CustomElement;
}
change_font(FONT_NOTOSANS);
offset_y += rect[3];
}
{
let menu_font = 24.0;
{
let mut _rect = rect;
_rect[1] -= offset_y;
draw_rect(canvas, _rect, C4_BLACK, true);
}
let mut save_color = C4_GREY;
let save_rect = [rect[0]+57, rect[1]+4-offset_y, 50, menu_font as i32];
let mut _save_rect = [rect[0]+57, rect[1]+4-offset_y, 50, menu_font as i32];
if !app_storage.menu_offscreen {
_save_rect[0] = rect[0]+57 + subcanvas_x;
}
if in_rect(mouseinfo.x, mouseinfo.y, _save_rect){
save_color = C4_LGREY;
if mouseinfo.lclicked(){
app_storage.save_toggle_saveload = SaveLoadEnum::Save;
}
}
if app_storage.save_toggle_saveload == SaveLoadEnum::Save{
save_color = C4_LGREY;
}
draw_rect(canvas, save_rect, save_color, true);
draw_string(canvas, "Save", save_rect[0], save_rect[1]-2, C4_WHITE, menu_font);
let mut load_color = C4_GREY;
let load_rect = [rect[0]+4, rect[1]+4-offset_y, 50, menu_font as i32];
let mut _load_rect = [rect[0]+4, rect[1]+4-offset_y, 50, menu_font as i32];
if !app_storage.menu_offscreen {
_load_rect[0] = rect[0]+ 4 + subcanvas_x;
}
if in_rect(mouseinfo.x, mouseinfo.y, _load_rect){
load_color = C4_LGREY;
if mouseinfo.lclicked(){
app_storage.save_toggle_saveload = SaveLoadEnum::Load;
}
}
if app_storage.save_toggle_saveload == SaveLoadEnum::Load{
load_color = C4_LGREY;
}
draw_rect(canvas, load_rect, load_color, true);
draw_string(canvas, "Load", load_rect[0], load_rect[1]-2, C4_WHITE, menu_font);
offset_y += rect[3];
}
match app_storage.save_toggle_programelements{
ProgramElementsEnum::Circuit=>{
match app_storage.save_toggle_saveload{
SaveLoadEnum::Save=>{
let save_menu_font = 26.0;
let mut save_menu_rect = [rect[0], rect[1]-save_menu_font as i32 * previously_saved_circuits.len() as i32 - offset_y,
rect_background_width, save_menu_font as i32 * ( 1 + previously_saved_circuits.len() as i32 )];
if !app_storage.menu_offscreen {
save_menu_rect[0] = 0;
}
draw_rect(canvas, save_menu_rect, C4_BLACK, true);
draw_string(canvas, "Save:", save_menu_rect[0]+4, save_menu_rect[1] + save_menu_rect[3] - save_menu_font as i32, C4_WHITE, save_menu_font);
for (i, it) in previously_saved_circuits.iter().enumerate(){
let y = save_menu_rect[1] + save_menu_rect[3] - (i + 2) as i32 * save_menu_font as i32 - 2;
let sub_rect = [save_menu_rect[0], y, save_menu_rect[2], save_menu_font as i32];
let _sub_rect = if app_storage.menu_offscreen{ [save_menu_rect[0], y, save_menu_rect[2], save_menu_font as i32]}
else { [subcanvas_x+save_menu_rect[0], y, save_menu_rect[2], save_menu_font as i32] };
if in_rect(mouseinfo.x, mouseinfo.y, _sub_rect){
draw_rect(canvas, sub_rect, C4_GREY, true);
if mouseinfo.lclicked(){
app_storage.save_textbox.text_buffer = it.to_string();
}
}
draw_string(canvas, it, save_menu_rect[0]+4, y, C4_WHITE, save_menu_font);
}
if !app_storage.menu_offscreen { app_storage.save_textbox.offset_x = subcanvas_x;}
app_storage.save_textbox.x = save_menu_rect[0]+50;
app_storage.save_textbox.y = save_menu_rect[1] + save_menu_rect[3] - save_menu_font as i32;
app_storage.save_textbox.omega = 4.0;
app_storage.save_textbox.update(keyboardinfo, textinfo, mouseinfo);
app_storage.save_textbox.draw(canvas, app_storage.timer.elapsed().as_secs_f32());
if keyboardinfo.key.contains(&KeyboardEnum::Enter) {
if app_storage.arr_circuit_elements.len() != 0 {
let mut filename = app_storage.save_textbox.text_buffer.to_string();
if !filename.contains(CIRCUIT_FILE_EXT) {
filename += CIRCUIT_FILE_EXT;
}
save_circuit_diagram(&filename, &app_storage.arr_circuit_elements);
app_storage.messages.push( (MessageType::Default, format!("Message: {} saved.", filename)) );
app_storage.save_toggle = false;
} else {
app_storage.messages.push( (MessageType::Error, "Error: no circuit elements to save.".to_string()) );
app_storage.save_toggle = false;
}
}
},
SaveLoadEnum::Load=>{
let load_menu_font = 26.0;
let mut load_menu_rect = [rect[0],
rect[1] - load_menu_font as i32 * previously_saved_circuits.len() as i32 - offset_y,
rect_background_width,
load_menu_font as i32 * ( 1 + previously_saved_circuits.len() as i32 )];
if !app_storage.menu_offscreen {
load_menu_rect[0] = 0;
}
draw_rect(canvas, load_menu_rect, C4_BLACK, true);
let load_offset = draw_string(canvas, "Load:", load_menu_rect[0]+4, load_menu_rect[1] + load_menu_rect[3] - load_menu_font as i32, C4_WHITE, load_menu_font);
if previously_saved_circuits.len() == 0 {
draw_string(canvas, " No files could be found.", load_menu_rect[0]+4+load_offset, load_menu_rect[1] + load_menu_rect[3] - load_menu_font as i32,
C4_WHITE, load_menu_font);
}
let mut temp_string = String::new();
for (i, it) in previously_saved_circuits.iter().enumerate(){
let y = load_menu_rect[1] + load_menu_rect[3] - (i + 2) as i32 * load_menu_font as i32 - 2;
let sub_rect = [load_menu_rect[0], y, load_menu_rect[2], load_menu_font as i32];
let _sub_rect = if app_storage.menu_offscreen{ [load_menu_rect[0], y, load_menu_rect[2], load_menu_font as i32]}
else { [subcanvas_x+load_menu_rect[0], y, load_menu_rect[2], load_menu_font as i32] };
if in_rect(mouseinfo.x, mouseinfo.y, _sub_rect){
draw_rect(canvas, sub_rect, C4_GREY, true);
if mouseinfo.lclicked(){
temp_string = it.to_string();
}
}
draw_string(canvas, it, load_menu_rect[0]+4, y, C4_WHITE, load_menu_font);
}
if previously_saved_circuits.contains(&temp_string) {
let v = load_circuit_diagram(&temp_string);
app_storage.arr_circuit_elements = v;
app_storage.saved_circuit_volts.clear();
app_storage.saved_circuit_currents.clear();
app_storage.circuit_textbox_hash.clear();
for it in app_storage.arr_circuit_elements.iter(){
app_storage.circuit_textbox_hash.insert((it.unique_a_node, it.unique_b_node), CircuitElementTextBox::new());
if it.circuit_element_type == SelectedCircuitElement::Voltmeter
|| it.circuit_element_type == SelectedCircuitElement::CustomVoltmeter{
app_storage.saved_circuit_volts.insert((it.unique_a_node, it.unique_b_node), [Vec::new(), Vec::new()]);
}
if it.circuit_element_type == SelectedCircuitElement::Ammeter
|| it.circuit_element_type == SelectedCircuitElement::CustomAmmeter{
app_storage.saved_circuit_currents.insert((it.unique_a_node, it.unique_b_node), [Vec::new(), Vec::new()]);
}
}
app_storage.save_toggle = false;
}
},
}
},
ProgramElementsEnum::SidePanel=>{
match app_storage.save_toggle_saveload{
SaveLoadEnum::Save=>{
let save_menu_font = 26.0;
let mut save_menu_rect = [rect[0],
rect[1]-save_menu_font as i32 * previously_saved_panels.len() as i32 - offset_y,
rect_background_width,
save_menu_font as i32 * ( 1 + previously_saved_panels.len() as i32 )];
if !app_storage.menu_offscreen {
save_menu_rect[0] = 0;
}
draw_rect(canvas, save_menu_rect, C4_BLACK, true);
draw_string(canvas, "Save:", save_menu_rect[0]+4, save_menu_rect[1] + save_menu_rect[3] - save_menu_font as i32, C4_WHITE, save_menu_font);
for (i, it) in previously_saved_panels.iter().enumerate(){
let y = save_menu_rect[1] + save_menu_rect[3] - (i + 2) as i32 * save_menu_font as i32 - 2;
let sub_rect = [save_menu_rect[0], y, save_menu_rect[2], save_menu_font as i32];
let _sub_rect = if app_storage.menu_offscreen{ [save_menu_rect[0], y, save_menu_rect[2], save_menu_font as i32]}
else { [subcanvas_x+save_menu_rect[0], y, save_menu_rect[2], save_menu_font as i32] };
if in_rect(mouseinfo.x, mouseinfo.y, _sub_rect){
draw_rect(canvas, sub_rect, C4_GREY, true);
if mouseinfo.lclicked(){
app_storage.panel_save_textbox.text_buffer = it.to_string();
}
}
draw_string(canvas, it, save_menu_rect[0]+4, y, C4_WHITE, save_menu_font);
}
if !app_storage.menu_offscreen { app_storage.panel_save_textbox.offset_x = subcanvas_x;}
app_storage.panel_save_textbox.x = save_menu_rect[0]+50;
app_storage.panel_save_textbox.y = save_menu_rect[1] + save_menu_rect[3] - save_menu_font as i32;
app_storage.panel_save_textbox.omega = 4.0;
app_storage.panel_save_textbox.update(keyboardinfo, textinfo, mouseinfo);
app_storage.panel_save_textbox.draw(canvas, app_storage.timer.elapsed().as_secs_f32());
if keyboardinfo.key.contains(&KeyboardEnum::Enter) {
let mut panel = PanelFile{ original_length: app_storage.lab_text.as_bytes().len() as u64,
buffer: Vec::new()
};
panel.buffer = compress_panelfile(&app_storage.lab_text);
let mut filename = app_storage.panel_save_textbox.text_buffer.to_string();
if !filename.contains(PANEL_FILE_EXT) {
filename += PANEL_FILE_EXT;
}
panel.save(&filename);
app_storage.messages.push( (MessageType::Default, format!("Message: {} saved.", filename)) );
app_storage.save_toggle = false;
}
},
SaveLoadEnum::Load=>{
let load_menu_font = 26.0;
let mut load_menu_rect = [rect[0],
rect[1] - load_menu_font as i32 * previously_saved_panels.len() as i32 - offset_y,
rect_background_width,
load_menu_font as i32 * ( 1 + previously_saved_panels.len() as i32 )];
if !app_storage.menu_offscreen {
load_menu_rect[0] = 0;
}
draw_rect(canvas, load_menu_rect, C4_BLACK, true);
let load_offset = draw_string(canvas, "Load:", load_menu_rect[0]+4, load_menu_rect[1] + load_menu_rect[3] - load_menu_font as i32, C4_WHITE, load_menu_font);
if previously_saved_panels.len() == 0 {
draw_string(canvas, " No files could be found.", load_menu_rect[0]+4+load_offset, load_menu_rect[1] + load_menu_rect[3] - load_menu_font as i32,
C4_WHITE, load_menu_font);
}
let mut temp_string = String::new();
for (i, it) in previously_saved_panels.iter().enumerate(){
let y = load_menu_rect[1] + load_menu_rect[3] - (i + 2) as i32 * load_menu_font as i32 - 2;
let sub_rect = [load_menu_rect[0], y, load_menu_rect[2], load_menu_font as i32];
let _sub_rect = if app_storage.menu_offscreen{ [load_menu_rect[0], y, load_menu_rect[2], load_menu_font as i32]}
else { [subcanvas_x+load_menu_rect[0], y, load_menu_rect[2], load_menu_font as i32] };
if in_rect(mouseinfo.x, mouseinfo.y, _sub_rect){
draw_rect(canvas, sub_rect, C4_GREY, true);
if mouseinfo.lclicked(){
temp_string = it.to_string();
}
}
draw_string(canvas, it, load_menu_rect[0]+4, y, C4_WHITE, load_menu_font);
}
if previously_saved_panels.contains(&temp_string) {
//TODO
let pf = PanelFile::load(&temp_string);
let buffer = miniz::uncompress(&pf.buffer, pf.original_length as usize);
app_storage.lab_text.clear();
app_storage.lab_text.insert_str( 0, &String::from_utf8_lossy(&buffer.expect("something went wrong with decompression")) );
let (mut panels, errors) = parse_and_panel_filebuffer(&app_storage.lab_text);
app_storage.arr_panels.clear();
app_storage.arr_panels.append( &mut panels );
app_storage.messages = errors;
app_storage.save_toggle = false;
}
},
}
},
ProgramElementsEnum::CustomElement=>{
match app_storage.save_toggle_saveload{
SaveLoadEnum::Save=>{
let save_menu_font = 26.0;
let mut save_menu_rect = [rect[0],
rect[1]-save_menu_font as i32 * previously_saved_custom.len() as i32 - offset_y,
rect_background_width,
save_menu_font as i32 * ( 1 + previously_saved_custom.len() as i32 )];
if !app_storage.menu_offscreen {
save_menu_rect[0] = 0;
}
draw_rect(canvas, save_menu_rect, C4_BLACK, true);
draw_string(canvas, "Save:", save_menu_rect[0]+4, save_menu_rect[1] + save_menu_rect[3] - save_menu_font as i32, C4_WHITE, save_menu_font);
for (i, it) in previously_saved_custom.iter().enumerate(){
let y = save_menu_rect[1] + save_menu_rect[3] - (i + 2) as i32 * save_menu_font as i32 - 2;
let sub_rect = [save_menu_rect[0], y, save_menu_rect[2], save_menu_font as i32];
let _sub_rect = if app_storage.menu_offscreen{ [save_menu_rect[0], y, save_menu_rect[2], save_menu_font as i32]}
else { [subcanvas_x+save_menu_rect[0], y, save_menu_rect[2], save_menu_font as i32] };
if in_rect(mouseinfo.x, mouseinfo.y, _sub_rect){
draw_rect(canvas, sub_rect, C4_GREY, true);
if mouseinfo.lclicked(){
app_storage.ce_save_textbox.text_buffer = it.to_string();
}
}
draw_string(canvas, it, save_menu_rect[0]+4, y, C4_WHITE, save_menu_font);
}
if !app_storage.menu_offscreen { app_storage.ce_save_textbox.offset_x = subcanvas_x;}
app_storage.ce_save_textbox.x = save_menu_rect[0]+50;
app_storage.ce_save_textbox.y = save_menu_rect[1] + save_menu_rect[3] - save_menu_font as i32;
app_storage.ce_save_textbox.omega = 4.0;
app_storage.ce_save_textbox.update(keyboardinfo, textinfo, mouseinfo);
app_storage.ce_save_textbox.draw(canvas, app_storage.timer.elapsed().as_secs_f32());
if keyboardinfo.key.contains(&KeyboardEnum::Enter) {
let mut filename = app_storage.ce_save_textbox.text_buffer.to_string();
if !filename.contains(CUSTOM_FILE_EXT) {//TODO this should not be a contains but an ext check
filename += CUSTOM_FILE_EXT;
}
save_circuit_diagram(&filename, &app_storage.custom_circuit_elements);
app_storage.messages.push( (MessageType::Default, format!("Message: {} saved.", filename)) );
app_storage.save_toggle = false;
}
},
SaveLoadEnum::Load=>{
let load_menu_font = 26.0;
let mut load_menu_rect = [rect[0],
rect[1] - load_menu_font as i32 * previously_saved_custom.len() as i32 - offset_y,
rect_background_width,
load_menu_font as i32 * ( 1 + previously_saved_custom.len() as i32 )];
if !app_storage.menu_offscreen {
load_menu_rect[0] = 0;
}
draw_rect(canvas, load_menu_rect, C4_BLACK, true);
let load_offset = draw_string(canvas, "Load:", load_menu_rect[0]+4, load_menu_rect[1] + load_menu_rect[3] - load_menu_font as i32, C4_WHITE, load_menu_font);
if previously_saved_custom.len() == 0 {
draw_string(canvas, " No files could be found.", load_menu_rect[0]+4+load_offset, load_menu_rect[1] + load_menu_rect[3] - load_menu_font as i32,
C4_WHITE, load_menu_font);
}
let mut temp_string = String::new();
for (i, it) in previously_saved_custom.iter().enumerate(){
let y = load_menu_rect[1] + load_menu_rect[3] - (i + 2) as i32 * load_menu_font as i32 - 2;
let sub_rect = [load_menu_rect[0], y, load_menu_rect[2], load_menu_font as i32];
let _sub_rect = if app_storage.menu_offscreen{ [load_menu_rect[0], y, load_menu_rect[2], load_menu_font as i32]}
else { [subcanvas_x+load_menu_rect[0], y, load_menu_rect[2], load_menu_font as i32] };
if in_rect(mouseinfo.x, mouseinfo.y, _sub_rect){
draw_rect(canvas, sub_rect, C4_GREY, true);
if mouseinfo.lclicked(){
temp_string = it.to_string();
}
}
draw_string(canvas, it, load_menu_rect[0]+4, y, C4_WHITE, load_menu_font);
}
if previously_saved_custom.contains(&temp_string) {
let mut custom_elements = load_circuit_diagram(&temp_string);
app_storage.custom_circuit_elements.clear();
app_storage.custom_circuit_elements.append(&mut custom_elements);
app_storage.save_toggle = false;
}
},
}
},
}
}
}
}
{//error report
let messages = &mut app_storage.messages;
let message_index = &mut app_storage.message_index;
let message_stopwatch = &mut app_storage.message_timer;
if messages.len() > 5 {//NOTE caps the number of messages. This should really be done by taking times.
for _ in 0..5-messages.len() {
messages.remove(0);
}
}
if messages.len() > 0 {
let index = match message_index {
Some(_index)=>{
let id = *_index;
if id < messages.len() {
let mut message_onscreen_duration = DEFAULT_MESSAGE_ONSCREEN_DURATION;
if messages[id].0 == MessageType::Error{
message_onscreen_duration = ERROR_MESSAGE_ONSCREEN_DURATION;
}
if message_stopwatch.get_time() >= message_onscreen_duration {
*message_index = Some(id + 1);
message_stopwatch.reset();
}
}
id
},
None=>{
*message_index = Some(0);
message_stopwatch.reset();
0
}
};
if index >= messages.len() {
messages.clear();
*message_index = None;
} else{
let rect = [0, 0, window_w, PANEL_FONT as i32 + 8];
let alpha =
{
let x = message_stopwatch.get_time().as_millis() as f32 * 0.001;
let max_duration = if messages[index].0 == MessageType::Default {
DEFAULT_MESSAGE_ONSCREEN_DURATION.as_millis() as f32 * 0.001
} else {
ERROR_MESSAGE_ONSCREEN_DURATION.as_millis() as f32 * 0.001
};
let mut rt = x;
if x > max_duration - 1f32{
rt = max_duration - x ;
}
if rt > 1.0{
rt = 1.0;
} else if rt < 0f32 {
rt = 0.0;
}
rt
};
let mut color_rect = c3_to_c4(C3_MGREEN, alpha);
if messages[index].0 == MessageType::Error{
color_rect = c3_to_c4(C3_RED, alpha);
}
draw_rect(&mut os_package.window_canvas, rect, color_rect, true);
let mut text_pos = get_advance_string(&messages[index].1, panel_font);
text_pos = window_w/2 - text_pos/2;
change_font(FONT_NOTOSANS_BOLD);
draw_string(&mut os_package.window_canvas, &messages[index].1, text_pos, 2, c3_to_c4(C3_WHITE, alpha.powi(2)), panel_font);
change_font(FONT_NOTOSANS);
}
}
}
draw_subcanvas(&mut os_package.window_canvas, &app_storage.menu_canvas, subcanvas_x, 0, 1.0);
{
//app_storage.run_circuit = false;
let mut circuit_has_been_altered = false;
if copy_circuit_buffer.len() == app_storage.arr_circuit_elements.len(){
for (i, it) in copy_circuit_buffer.iter().enumerate(){
if it.x != app_storage.arr_circuit_elements[i].x
|| it.y != app_storage.arr_circuit_elements[i].y
|| it.orientation != app_storage.arr_circuit_elements[i].orientation{
circuit_has_been_altered = true;
}
}
} else {
circuit_has_been_altered = true;
}
//copy circuit buffer before buffer is updated then check if the positions and rotations are the same if not the circuit has been_altered.
if circuit_has_been_altered
|| app_storage.arr_circuit_elements.len() < 4{
app_storage.run_circuit = false;
for it in app_storage.arr_circuit_elements.iter_mut(){
it.solved_current = None;
it.solved_voltage = None;
it.direction = None;
}
}
{//TODO Draw simulate button
let mut color = C4_DGREY;
let rect = RUN_PAUSE_RECT;
if in_rect(mouseinfo.x, mouseinfo.y, rect){
color = C4_GREY;
if mouseinfo.lclicked() {
if app_storage.arr_circuit_elements.len() >= 4 {//TODO this is not a good solution to the problem.
//Breifly rending the wrong thing if there is no good circuit present
//should not be addressed here
//but after we determine the
//status of the circuit.
app_storage.run_circuit = !app_storage.run_circuit;
}
app_storage.selected_circuit_element = SelectedCircuitElement::None;
app_storage.selected_circuit_element_orientation = 0f32;
app_storage.selected_circuit_properties = None;
if app_storage.run_circuit
&& app_storage.timer_init == false{
app_storage.timer_init = true;
app_storage.stop_watch = 0f32;
} else if app_storage.run_circuit == false
&& app_storage.timer_init == true {
app_storage.stop_watch += TIME_STEP;
app_storage.stop_watch = 0f32;
} else if app_storage.run_circuit
&& app_storage.timer_init == true{
app_storage.stop_watch = 0f32;
}
}
}
if mouseinfo.lbutton == ButtonStatus::Down{
color = C4_DGREY;
}
draw_rect(&mut os_package.window_canvas, rect, color, true);
if app_storage.run_circuit {//TODO StopWatch
app_storage.stop_watch += TIME_STEP;
}
if app_storage.run_circuit{//TODO timer
let string_w = get_advance_string("Pause", 30.0);
draw_string(&mut os_package.window_canvas, "Pause", rect[0]+rect[2]/2-string_w/2-4, rect[1]+4, C4_LGREY, 30.0);
} else{
let string_w = get_advance_string("Run", 30.0);
draw_string(&mut os_package.window_canvas, "Run", rect[0]+rect[2]/2-string_w/2-4, rect[1]+4, C4_LGREY, 30.0);
}
}
{//Clear screen button
let rect = CLEAR_RECT;
let mut bg_color = C4_DGREY;
let txt_color = C4_LGREY;
if in_rect(mouseinfo.x, mouseinfo.y, rect){
bg_color = C4_GREY;
if mouseinfo.lclicked(){
app_storage.selected_circuit_element = SelectedCircuitElement::None;
app_storage.selected_circuit_element_orientation = 0f32;
app_storage.selected_circuit_properties = None;
app_storage.arr_circuit_elements.clear();
}
}
draw_rect(&mut os_package.window_canvas, rect, bg_color, true);
draw_string(&mut os_package.window_canvas, "Clear Board", rect[0]+10, rect[1]+4, txt_color, 30f32);
}
if app_storage.run_circuit
&& app_storage.arr_circuit_elements.len() >= 4 //NOTE you can't have a circuit with less than 4 edges
{
//NOTE Updating the charge of capacitors and inductors
app_storage.sim_time += TIME_STEP;
for it in app_storage.arr_circuit_elements.iter_mut(){
it.time += TIME_STEP;
if it.circuit_element_type == SelectedCircuitElement::Custom{
//TODO this is redundant with the standard case. We should only be doing this thing once.
if it.capacitance.abs() > 0.00001f32
&& it.solved_current.is_some(){
let current = if *it.direction.as_ref().unwrap() == CircuitElementDirection::AtoB{
it.solved_current.as_ref().unwrap().abs()
} else {
it.solved_current.as_ref().unwrap().abs() * -1f32
};
it.charge += current * TIME_STEP;
}
if it.inductance.abs() > 0.00001f32
&& it.solved_voltage.is_some(){
it.magnetic_flux += *it.solved_voltage.as_ref().unwrap() * TIME_STEP; //TODO i think this is wrong
}
}
if it.circuit_element_type == SelectedCircuitElement::Capacitor
&& it.solved_current.is_some(){
//TODO this is redundant with the custom case. We should only be doing this thing once.
let current = if *it.direction.as_ref().unwrap() == CircuitElementDirection::AtoB{
it.solved_current.as_ref().unwrap().abs()
} else {
it.solved_current.as_ref().unwrap().abs() * -1f32
};
it.charge += current * TIME_STEP;
}
if it.circuit_element_type == SelectedCircuitElement::Inductor
&& it.solved_voltage.is_some(){
it.magnetic_flux += *it.solved_voltage.as_ref().unwrap() * TIME_STEP; //TODO i think this is wrong
}
if it.circuit_element_type == SelectedCircuitElement::AC
&& it.solved_current.is_some(){//TODO does not work when you change max voltage or frequency
if it.ac_source_type == ACSourceType::Sin{
//let max_voltage = it.max_voltage * PI;
//let d_voltage2_over_dt2 = -1.0* ( 2f32*PI*it.frequency ).powi(2)*it.temp_step_voltage;
//it.d_voltage_over_dt += d_voltage2_over_dt2 * TIME_STEP;
//it.d_voltage_over_dt = it.d_voltage_over_dt.max(-1.0).min(1.0);
//it.temp_step_voltage += it.d_voltage_over_dt * TIME_STEP;
//it.temp_step_voltage = it.temp_step_voltage.max(-1.0/PI).min(1.0/PI);
//it.voltage = it.temp_step_voltage * max_voltage;
it.voltage = it.max_voltage * (2f32 * PI * it.frequency * it.time).sin();
} else if it.ac_source_type == ACSourceType::Step{
//let d_voltage2_over_dt2 = -1.0*( 2f32*PI*it.frequency ).powi(2)*it.temp_step_voltage/it.max_voltage;
//it.d_voltage_over_dt += d_voltage2_over_dt2 * TIME_STEP;
//it.d_voltage_over_dt = it.d_voltage_over_dt.max(-1.0).min(1.0);
//let d_voltage_over_dt = it.d_voltage_over_dt;
//it.temp_step_voltage += it.d_voltage_over_dt * TIME_STEP * it.max_voltage;
it.temp_step_voltage = (2f32 * PI * it.frequency * it.time).sin();
it.voltage = if it.temp_step_voltage > 0f32 { it.max_voltage } else { -1.0*it.max_voltage};
}
}
}
for it in app_storage.arr_circuit_elements.iter_mut(){
it.solved_current = None;
it.solved_voltage = None;
it.direction = None;
//it.print_current = None;
//it.print_voltage = None;
if it.charge.is_nan() {
it.charge = 0f32;
}
if it.magnetic_flux.is_nan() {
it.magnetic_flux = 0f32;
}
}
//TODO determine which elements are apart of a circuit
for i in 0..app_storage.arr_circuit_elements.len(){
let it = app_storage.arr_circuit_elements[i].clone();
for j in i+1..app_storage.arr_circuit_elements.len(){
let jt = app_storage.arr_circuit_elements[j].clone();
let (it_x1, it_y1) = match it.circuit_element_type {
SelectedCircuitElement::Resistor |
SelectedCircuitElement::Battery |
SelectedCircuitElement::Inductor |
SelectedCircuitElement::Voltmeter |
SelectedCircuitElement::Ammeter |
SelectedCircuitElement::Switch |
SelectedCircuitElement::Wire |
SelectedCircuitElement::AC |
SelectedCircuitElement::Custom |
SelectedCircuitElement::CustomVoltmeter |
SelectedCircuitElement::CustomAmmeter |
SelectedCircuitElement::Capacitor => {
let _x = if it.orientation.sin().abs() < 0.001 {
it.x + ((it.orientation / 2f32).sin().abs() * (GRID_SIZE * 4) as f32) as i32
} else {
it.x + (it.orientation.sin().abs() * (GRID_SIZE * 2) as f32) as i32
};
let _y = if it.orientation.sin().abs() < 0.001 {
it.y + (it.orientation.cos().abs() * (GRID_SIZE * 2) as f32) as i32
} else {
it.y + (( (it.orientation - PI/ 2f32) / 2f32 ).sin().abs() * (GRID_SIZE * 4) as f32) as i32
};
(_x, _y)
},
_=>{ panic!("ASDF {:?}", it.circuit_element_type); }
};
let (jt_x1, jt_y1) = match jt.circuit_element_type {
SelectedCircuitElement::Resistor |
SelectedCircuitElement::Battery |
SelectedCircuitElement::Inductor |
SelectedCircuitElement::Voltmeter |
SelectedCircuitElement::Ammeter |
SelectedCircuitElement::Switch |
SelectedCircuitElement::Wire |
SelectedCircuitElement::AC |
SelectedCircuitElement::Custom |
SelectedCircuitElement::CustomVoltmeter |
SelectedCircuitElement::CustomAmmeter |
SelectedCircuitElement::Capacitor => {
let _x = if jt.orientation.sin().abs() < 0.001 {
jt.x + ((jt.orientation / 2f32).sin().abs() * (GRID_SIZE * 4) as f32) as i32
} else {
jt.x + (jt.orientation.sin().abs() * (GRID_SIZE * 2) as f32) as i32
};
let _y = if jt.orientation.sin().abs() < 0.001 {
jt.y + (jt.orientation.cos().abs() * (GRID_SIZE * 2) as f32) as i32
} else {
jt.y + (( (jt.orientation - PI/ 2f32) / 2f32 ).sin().abs() * (GRID_SIZE * 4) as f32) as i32
};
(_x, _y)
},
_=>{ panic!("ASDF {:?}", jt.circuit_element_type); }
};
let it_x2 = if it.orientation.sin().abs() < 0.001 {
it.x + ((it.orientation / 2f32).cos().abs() * (GRID_SIZE * 4) as f32) as i32
} else {
it.x + (it.orientation.sin().abs() * (GRID_SIZE * 2) as f32) as i32
};
let it_y2 = if it.orientation.sin().abs() < 0.001 {
it.y + (it.orientation.cos().abs() * (GRID_SIZE * 2) as f32) as i32
} else {
it.y + (( (it.orientation - PI/ 2f32) / 2f32 ).cos().abs() * (GRID_SIZE * 4) as f32) as i32
};
//Depricated 02/08/2021
//let it_x2 = (it.orientation.cos().abs()*(GRID_SIZE * 4) as f32 ) as i32 + it_x1;
//let it_y2 = (it.orientation.sin().abs()*(GRID_SIZE * 4) as f32 ) as i32 + it_y1;
let jt_x2 = if jt.orientation.sin().abs() < 0.001 {
jt.x + ((jt.orientation / 2f32).cos().abs() * (GRID_SIZE * 4) as f32) as i32
} else {
jt.x + (jt.orientation.sin().abs() * (GRID_SIZE * 2) as f32) as i32
};
let jt_y2 = if jt.orientation.sin().abs() < 0.001 {
jt.y + (jt.orientation.cos().abs() * (GRID_SIZE * 2) as f32) as i32
} else {
jt.y + (( (jt.orientation - PI/ 2f32) / 2f32 ).cos().abs() * (GRID_SIZE * 4) as f32) as i32
};
if (it_x1 == jt_x1 && it_y1 == jt_y1)
|| (it_x2 == jt_x2 && it_y2 == jt_y2)
|| (it_x2 == jt_x1 && it_y2 == jt_y1)
|| (it_x1 == jt_x2 && it_y1 == jt_y2)
{
//TODO reset the current nodes it the nodes are not touched during this process
if it_x1 == jt_x1 && it_y1 == jt_y1 {
app_storage.arr_circuit_elements[i].a_node = it.a_node.min(jt.a_node);
app_storage.arr_circuit_elements[j].a_node = it.a_node.min(jt.a_node);
for index in 0..it.a_index.len(){
match it.a_index[index] {
None=>{ app_storage.arr_circuit_elements[i].a_index[index] = Some(j); break; }, //TODO some is incorrect
Some(n)=>{ if j == n { break; } },
}
}
for index in 0..jt.a_index.len(){
match jt.a_index[index] {
None=>{ app_storage.arr_circuit_elements[j].a_index[index] = Some(i); break; }, //TODO some is incorrect
Some(n)=>{ if i == n { break; } },
}
}
}
if it_x2 == jt_x2 && it_y2 == jt_y2 {
app_storage.arr_circuit_elements[i].b_node = it.b_node.min(jt.b_node);
app_storage.arr_circuit_elements[j].b_node = it.b_node.min(jt.b_node);
//println!("1 {} {}", i, j);
for index in 0..it.b_index.len(){
match it.b_index[index] {
None=>{ app_storage.arr_circuit_elements[i].b_index[index] = Some(j); break; }, //TODO some is incorrect
Some(n)=>{ if j == n { break; } },
}
}
for index in 0..jt.b_index.len(){
match jt.b_index[index] {
None=>{ app_storage.arr_circuit_elements[j].b_index[index] = Some(i); break; }, //TODO some is incorrect
Some(n)=>{ if i == n { break; } },
}
}
}
if it_x2 == jt_x1 && it_y2 == jt_y1 {
app_storage.arr_circuit_elements[i].b_node = it.b_node.min(jt.a_node);
app_storage.arr_circuit_elements[j].a_node = it.b_node.min(jt.a_node);
for index in 0..it.b_index.len(){
match it.b_index[index] {
None=>{ app_storage.arr_circuit_elements[i].b_index[index] = Some(j); break; }, //TODO some is incorrect
Some(n)=>{ if j == n { break; } },
}
}
for index in 0..jt.a_index.len(){
match jt.a_index[index] {
None=>{ app_storage.arr_circuit_elements[j].a_index[index] = Some(i); break; }, //TODO some is incorrect
Some(n)=>{ if i == n { break; } },
}
}
}
if it_x1 == jt_x2 && it_y1 == jt_y2 {
app_storage.arr_circuit_elements[i].a_node = it.a_node.min(jt.b_node);
app_storage.arr_circuit_elements[j].b_node = it.a_node.min(jt.b_node);
for index in 0..it.a_index.len(){
match it.a_index[index] {
None=>{ app_storage.arr_circuit_elements[i].a_index[index] = Some(j); break; }, //TODO some is incorrect
Some(n)=>{ if j == n { break; } },
}
}
for index in 0..jt.b_index.len(){
match jt.b_index[index] {
None=>{ app_storage.arr_circuit_elements[j].b_index[index] = Some(i); break; }, //TODO some is incorrect
Some(n)=>{ if i == n { break; } },
}
}
}
} else {
//line seg 1: it_x1 it_y1, it_x2 it_y2
//line seg 2: jt_x1 jt_y1, jt_x2 jt_y2
let e1 = edgefunction_i32(&[it_x1, it_y1], &[jt_x1, jt_y1], &[jt_x2, jt_y2]);
let e2 = edgefunction_i32(&[jt_x1, jt_y1], &[it_x2, it_y2], &[it_x1, it_y1]);
let e3 = edgefunction_i32(&[jt_x2, jt_y2], &[jt_x1, jt_y1], &[it_x2, it_y2]);
let e4 = edgefunction_i32(&[it_x1, it_y1], &[it_x2, it_y2], &[jt_x2, jt_y2]);
let error_message = "Error: Please connect elements at their edges.".to_string();
if e1 == 0f32
&& e2 == 0f32
&& e3 == 0f32
&& e4 == 0f32{
//
} else
if e1 == e3
&& e2 == e4{
if !app_storage.messages.contains(&(MessageType::Error, error_message.clone())){
app_storage.messages.push((MessageType::Error, error_message));
println!("A");
}
} else {
let mut a = false;
if e1 == 0f32
&& e2*e3*e4 != 0f32
&& (e2*e3*e4).signum() == e2.signum()
&& (e2*e3*e4).signum() == e3.signum(){
a = true;
}
if e2 == 0f32
&& e1*e3*e4 != 0f32
&& (e1*e3*e4).signum() == e1.signum()
&& (e1*e3*e4).signum() == e3.signum(){
a = true;
}
if e3 == 0f32
&& e1*e2*e4 != 0f32
&& (e1*e2*e4).signum() == e1.signum()
&& (e1*e2*e4).signum() == e2.signum(){
a = true;
}
if e1*e2*e3 != 0f32
&& e4 == 0f32
&& (e1*e2*e3).signum() == e1.signum()
&& (e1*e2*e3).signum() == e2.signum() {
a = true;
}
if a
&& !(it_x1 == jt_x1 && it_y1 == jt_y1)
&& !(it_x2 == jt_x2 && it_y2 == jt_y2)
&& !(it_x2 == jt_x1 && it_y2 == jt_y1)
&& !(it_x1 == jt_x2 && it_y1 == jt_y2)
{
if !app_storage.messages.contains(&(MessageType::Error, error_message.clone())){
app_storage.messages.push((MessageType::Error, error_message));
}
}
}
}
}
}
let (mut c_matrix, pairs, _) = compute_circuit(&mut app_storage.arr_circuit_elements);
if pairs.len() == 0 {
app_storage.run_circuit = false;
}
let mut bad_solved_value = false;
for (i, it) in pairs.iter().enumerate(){
let minus_one = c_matrix.columns - 1;
let solved_current = *c_matrix.get_element(i, minus_one);
let solved_voltage = *c_matrix.get_element(i+pairs.len(), minus_one);
if bad_solved_value == false{
if !solved_current.is_finite()
|| !solved_voltage.is_finite(){
let text = format!("Error: Current({}) and or voltage({}), is not finite. Impacted nodes {} {}. Tip: Does the circuit include a resistor?",
solved_current, solved_voltage,
app_storage.arr_circuit_elements[it.orig_element_index].unique_a_node,
app_storage.arr_circuit_elements[it.orig_element_index].unique_b_node);
if !app_storage.messages.contains(&(MessageType::Error, text.clone())){
app_storage.messages.push((MessageType::Error, text));
}
bad_solved_value = true;
app_storage.run_circuit = false;
}
if solved_current.abs() >= CURRENT_INF_CUT{
let text = format!("Error: Current({}) is very large. A (larger)resistor maybe required. Impacted nodes {} {}.",
solved_current,
app_storage.arr_circuit_elements[it.orig_element_index].unique_a_node,
app_storage.arr_circuit_elements[it.orig_element_index].unique_b_node,
);
if !app_storage.messages.contains(&(MessageType::Error, text.clone())){
app_storage.messages.push((MessageType::Error, text));
}
bad_solved_value = true;
//app_storage.run_circuit = false;
}
}
app_storage.arr_circuit_elements[it.orig_element_index].solved_current = Some(solved_current);
app_storage.arr_circuit_elements[it.orig_element_index].solved_voltage = Some(solved_voltage);
let mut print_current = solved_current;
let mut print_voltage = solved_voltage;
let mut _direction;
if it.in_node == app_storage.arr_circuit_elements[it.orig_element_index].a_node{
_direction = CircuitElementDirection::AtoB;
if solved_current < 0.0 {
app_storage.arr_circuit_elements[it.orig_element_index].direction = Some( CircuitElementDirection::BtoA );
} else{
app_storage.arr_circuit_elements[it.orig_element_index].direction = Some( CircuitElementDirection::AtoB );
}
} else {
_direction = CircuitElementDirection::BtoA;
if solved_current < 0.0 {
app_storage.arr_circuit_elements[it.orig_element_index].direction = Some( CircuitElementDirection::AtoB );
} else{
app_storage.arr_circuit_elements[it.orig_element_index].direction = Some( CircuitElementDirection::BtoA );
}
}
//We correct current and voltage to match what we assume a convention. Where current is assumed to enter node A and exit node B.
match app_storage.arr_circuit_elements[it.orig_element_index].direction{
Some(CircuitElementDirection::AtoB)=>{
print_current = print_current.abs();
},
Some(CircuitElementDirection::BtoA)=>{
print_current = -1f32 * print_current.abs();
},
_=>{}
}
print_voltage = if print_current.signum() == -1f32 { -1f32 * print_voltage.abs() } else { print_voltage.abs() };
let element = app_storage.arr_circuit_elements[it.orig_element_index];
if element.circuit_element_type == SelectedCircuitElement::CustomVoltmeter{
let prev_voltage = element.print_voltage.as_ref().unwrap_or(&0f32);
print_voltage = element.drift*prev_voltage + (1f32 - element.drift) * (print_voltage + element.bias) + sample_normal(element.noise);
}
if element.circuit_element_type == SelectedCircuitElement::CustomAmmeter{
let prev_current = element.print_current.as_ref().unwrap_or(&0f32);
print_current = element.drift*prev_current + (1f32 - element.drift) * (print_current + element.bias) + sample_normal(element.noise);
}
app_storage.arr_circuit_elements[it.orig_element_index].print_voltage = Some(print_voltage);
app_storage.arr_circuit_elements[it.orig_element_index].print_current = Some(print_current);
let ce_time = app_storage.arr_circuit_elements[it.orig_element_index].time;
//Setting up current and graph storage
let a_node = app_storage.arr_circuit_elements[it.orig_element_index].unique_a_node;
let b_node = app_storage.arr_circuit_elements[it.orig_element_index].unique_b_node;
match app_storage.saved_circuit_currents.get_mut(&(a_node, b_node)){
Some(currents_times)=>{
if currents_times[0].len() > MAX_SAVED_MEASURMENTS{
currents_times[0].remove(0);
currents_times[1].remove(0);
}
currents_times[0].push(print_current);
currents_times[1].push(ce_time);
//currents_times[1].push(app_storage.sim_time);
},
None=>{}
}
match app_storage.saved_circuit_volts.get_mut(&(a_node, b_node)){
Some(volts_times)=>{
if volts_times[0].len() > MAX_SAVED_MEASURMENTS{
volts_times[0].remove(0);
volts_times[1].remove(0);
}
volts_times[0].push(print_voltage);
volts_times[1].push(ce_time);
//volts_times[1].push(app_storage.sim_time);
},
None=>{}
}
}
//println!("# of elements: {}\n", app_storage.arr_circuit_elements.len());
//for it in app_storage.arr_circuit_elements.iter(){
// println!("{:?}\n", it);
//}
//panic!();
//NOTE this is to reset circuit elements
for it in app_storage.arr_circuit_elements.iter_mut(){
it.discovered = false;
it.a_node = it.unique_a_node;
it.b_node = it.unique_b_node;
it.a_index = [None; 3];
it.b_index = [None; 3];
}
}
}
if app_storage.teacher_mode {
change_font(FONT_NOTOSANS_BOLD);
draw_string(&mut os_package.window_canvas, "TA", -1, -1, C4_WHITE, 32.0);
draw_string(&mut os_package.window_canvas, "TA", 0, 0, C4_RED, 32.0);
change_font(FONT_NOTOSANS);
}
return 0;
}
pub enum PanelContent{
Header(String),
Text(String),
Image(TGBitmap),
Question(MultiQuestion),
}
pub struct Panel{
pub contents: Vec<PanelContent>,
}
pub struct MultiQuestion{
question: String,
choices: Vec<String>,
answer_index: Option<usize>,
number_chances: usize,
answers: Vec<usize>,
}
pub fn parse_and_panel_filebuffer(buffer: &str)->(Vec<Panel>, Vec<(MessageType, String)>){
use std::fs::File;
use std::io::prelude::*;
let ( parsed_results, mut errors) = parse(buffer);
let mut panels = vec![];
for (i, it) in parsed_results.iter().enumerate(){
let mut panel = Panel{contents: vec![]};
let mut question_answer_index : Option<usize>= None;
for jt in it.contents.iter() {
match jt {
Content::Text(string)=>{
panel.contents.push(PanelContent::Text(string.to_string()));
},
Content::Header(string)=>{
panel.contents.push(PanelContent::Header(string.to_string()));
},
Content::Image(string)=>{
//TODO should we get the image here?
//TODO strip preceeding and postceeding spaces
let mut temp_string = string.to_string();
if temp_string.chars().nth(0) == Some(' '){
temp_string.remove(0);
}
if temp_string.chars().nth(temp_string.len()) == Some(' '){
let l = temp_string.len()-1;
temp_string.remove(l);
}
match File::open(temp_string){
Ok(mut f)=>{
let mut buffer = Vec::new();
f.read_to_end(&mut buffer).expect("Buffer could not be read.");
let image = stbi_load_from_memory_32bit(&buffer);
match image {
Ok(im)=>{
let mut bmp = TGBitmap{info_header: TGBitmapHeaderInfo{
header_size: 0u32,
width: im.width,
height: im.height,
planes: 1,
bit_per_pixel: 32,
compression: 0u32,
image_size: 0u32,
x_px_per_meter: 0i32,
y_px_per_meter: 0i32,
colors_used: 0u32,
colors_important: 0u32,
},
file_header: TGBitmapFileHeader::default(),
rgba: Vec::with_capacity(im.buffer.len()),
//rgba: im.buffer,
width: im.width,
height: im.height};//TODO I don't like the bit map struct
for _j in 1..(im.height+1) as usize{
let j = (im.height as usize - _j) * im.width as usize;
for _i in 0..im.width as usize{
let i = _i;
let k = (i+j)*4;
bmp.rgba.push( im.buffer[k+2] );
bmp.rgba.push( im.buffer[k+1] );
bmp.rgba.push( im.buffer[k+0] );
bmp.rgba.push( im.buffer[k+3] );
}
}
panel.contents.push(PanelContent::Image(bmp));
},
_=>{
//TODO should we do something here?
errors.push(( MessageType::Error, format!("Error: Image, {}, on panel {}, could not be opened by program.", string, i)) );
}
}
},
Err(_)=>{
},
}
},
Content::Question(string)=>{
let mut question_and_answers = MultiQuestion::new();
question_and_answers.question = string.to_string();
panel.contents.push(PanelContent::Question(question_and_answers));
question_answer_index = Some(panel.contents.len()-1);
},
Content::Answer(string, bool_)=>{
match question_answer_index{
Some(qa_idex)=> {
match &mut panel.contents[qa_idex]{
PanelContent::Question(qa)=>{
qa.choices.push(string.to_string());
let index = qa.choices.len() - 1;
if *bool_ {
qa.answer_index = Some(index);
}
},
_=>{panic!("we did something wrong with quetions.")}
}
},
None=>{}
}
},
_=>{panic!();}
}
}
for it in panel.contents.iter(){
match it {
PanelContent::Question(qa)=>{
if qa.question.len() > 0
&& qa.answer_index.is_none(){
errors.push(( MessageType::Error, format!("Error: Question in panel({}), has no correct answer.",
i)));
}
},
_=>{}
}
}
panels.push(panel);
}
return (panels, errors);
}
impl MultiQuestion{
pub fn new()->MultiQuestion{ //TODO currently we only allow for one correct answer do we want to keep this
MultiQuestion{
question: String::new(),
choices: Vec::new(),
answer_index: None,
number_chances: 3,
answers: Vec::new(),
}
}
}
//TODO move to misc tools or rendertools
pub fn generate_wrapped_strings(string: &str, font: f32, max_width: i32)->Vec<String>{
let mut strings= vec![String::new()];
let mut strings_index = 0;
for jt in string.split('\n'){
for it in jt.split(' '){
if get_advance_string(&strings[strings_index], font) + get_advance_string(it, font) < max_width - font as i32 {
} else {
strings_index += 1;
strings.push(String::new());
}
strings[strings_index].push_str(it);
strings[strings_index].push_str(" ");
}
strings_index += 1;
strings.push(String::new());
}
return strings;
}
/// Returns a rotated bmp determined by the given angle.
///
/// The angle must be in radians.
fn rotate_bmp(src_bmp: &mut TGBitmap, angle: f32)->Option<TGBitmap>{unsafe{
fn calc_xy(x: f32, y: f32, angle: f32)->(f32, f32){
let cos = angle.cos();
let sin = angle.sin();
let rt = ( x as f32 * cos + y as f32 * sin,
-x as f32 * sin + y as f32 * cos,
);
return rt;
}
{
let dst_w = (src_bmp.width as f32 * angle.cos().abs() + src_bmp.height as f32 * angle.sin().abs()).round() as isize;
let dst_h = (src_bmp.width as f32 * angle.sin().abs() + src_bmp.height as f32 * angle.cos().abs()).round() as isize;
let mut dst_bmp = TGBitmap::new(dst_w as i32, dst_h as i32);//TODO
let src_buffer = src_bmp.rgba.as_ptr();
let dst_buffer = dst_bmp.rgba.as_mut_ptr();
let w = src_bmp.width as isize;
let h = src_bmp.height as isize;
for j in 0..dst_h{
for i in 0..dst_w{
let dst_offset = 4*(i + j*dst_w) as isize;
let __x = i as f32 - w as f32/2f32;
let __y = j as f32 - h as f32/2f32;
let (mut x, mut y) = calc_xy( __x, __y, angle);
x += w as f32 / 2f32;
y += h as f32 / 2f32;
let x = x.round() as isize;
let y = y.round() as isize;
if x >= w as isize || x < 0 {
continue; }
if y >= h as isize || y < 0 {
continue; }
if x+y*w >= h*w {
continue;
}
let src_offset=4*(x+y*w as isize);
let a = *src_buffer.offset(src_offset + 3);
let r = *src_buffer.offset(src_offset + 2);
let g = *src_buffer.offset(src_offset + 1);
let b = *src_buffer.offset(src_offset + 0);
*dst_buffer.offset(dst_offset + 3) = a;
*dst_buffer.offset(dst_offset + 2) = r;
*dst_buffer.offset(dst_offset + 1) = g;
*dst_buffer.offset(dst_offset + 0) = b;
}
}
return Some(dst_bmp);
}
}}
mod parser{
//! This module a contains simple parser for the panels used by the circuit simulation.
//!
//! The parser handles a simple custom markdown format.
//! The `parser` function parses a given string.
//! The parsing occurs in a single loop, where the program iterates through the characters
//! of the string while peeking forward to determine keywords.
//! The parser returns an array of sections, and possible errors.
//! A section is a single panel unit. Rendering of a section does not occur in this
//! module.
//!
//!
//! Below are the current key words needed when working working in TA mode
//! (all keywords are indifferent to case):
//! - `#Section` This creates a new empty page
//! - `#Text` Renders text that follows the command. Text can begin on the same line. If this command
//! is not invoked no text will be displayed.
//! - `#Image` Renders image in panel. Give local path (path from the directory of executable).
//! If path is incorrect the program will render nothing.
//! - `#Question` Renders following text and primes program to receive `#AnswerCorrect`, and `#AnswerWrong`. If followed by command that is not `#AnswerCorrect` or `#AnswerWrong`, nothing will render.
//! - `#AnswerCorrect` Renders the text that follows. This will not render if `#Question` is not the `#AnswerWrong` proceeding command. Only 7 answers are allowed. If there is no correct answer neither the question or answers are rendered.
//! - `\\` Comments can be written using double back slashes.
//!
//!
//! ## Example
//! ```
//! //comments should be ignored
//! #Section
//! #Header Beginning
//! #Text
//! This is the beginning of the lab.
//! The lab is about a great many things that you will never understand.
//! Sorry.
//!
//! #Section
//! #Header Initial Questions
//! #Text
//! Lets begin with some questions.
//! Please do you best answers will be graded harshly.
//!
//! #Question
//! How large is the farm?
//!
//! #AnswerWrong Pint sized.
//! #AnswerCorrect Byte sized.
//! #AnswerWrong bit sized.
//! #AnswerWrong bite sized.
//!
//! #Section
//! #Text
//! I hope you got that anwser right.
//! LOL
//! #image screenshot.bmp
//!
//! ```
#![allow(unused)]
use crate::lab_sims::MessageType;
const EXAMPLE : &str =
"//comments should be ignored
#Section
#Header Beginning
#Text
This is the beginning of the lab.
The lab is about a great many things that you will never understand.
Sorry.
#Section
#Header Initial Questions
#Text
Lets begin with some questions.
Please do you best answers will be graded harshly.
#Question
How large is the farm?
#AnswerWrong Pint sized.
#AnswerCorrect Byte sized.
#AnswerWrong bit sized.
#AnswerWrong bite sized.
#Section
#Text
I hope you got that anwser right.
LOL
#image screenshot.bmp
";
fn peek(i: usize, buffer: &[char])->Option<char>{
//TODO
if i+1 >= buffer.len(){
return None;
} else {
return Some(buffer[i+1]);
}
return None;
}
fn peek_is_char(i: usize, buffer: &[char], character: char)->bool{
let c = peek(i, buffer);
match c {
Some(_c)=>{
if _c == character { return true; }
},
_=>{return false;}
}
return false;
}
#[derive(Debug)]
pub struct Section{
pub contents: Vec<Content>,
}
#[derive(Debug)]
pub enum Content{
Question(String),
Header(String),
Text(String),
Answer(String, bool),
Image(String),
}
pub fn parse(input: &str)->(Vec<Section>, Vec<(MessageType, String)>){//TODO maybe return errors?
use Content::*;
let mut char_arr : Vec<char> = input.chars().collect();
//NOTE strip comments
{
let mut strip_i = 0;
loop{
let _char = char_arr[strip_i];
strip_i += 1;
if strip_i >= char_arr.len(){
break;
}
if _char == '/'
&& char_arr[strip_i] == '/'{
let mut j = 0;
if strip_i >= char_arr.len(){
break;
}
'_b: loop{
if peek_is_char(strip_i + j, &char_arr, '\n'){
break '_b;
}
j += 1;
}
for _remove in (strip_i-1..strip_i+j+1).rev(){
char_arr.remove(_remove);
}
}
}
}
let mut rt = vec![];
let mut errs = vec![];
let mut i = 0;
'a: loop{
if char_arr.len() == 0{
break 'a;
}
if i >= char_arr.len(){
break 'a;
}
let _char = char_arr[i];
let mut token_buffer = "".to_string();
if _char == '/'
&& peek_is_char(i, &char_arr, '/'){
let mut j = 0;
'b: loop{
if i + j >= char_arr.len(){
break 'a;
}
if peek_is_char(i+j, &char_arr, '\n') {
i += j;
break 'b;
}
j += 1;
}
} else if _char == '\n'
&& peek_is_char(i, &char_arr, '#'){
//NOTE update token_buffer
let mut j = 2;
if i+j < char_arr.len() {
'c: loop{
if i + j >= char_arr.len(){
break 'a;
}
token_buffer.push(char_arr[i+j]);
if peek_is_char(i+j, &char_arr, ' ')
|| peek_is_char(i+j, &char_arr, '\n'){
i += j+1;
break 'c;
}
j += 1;
}
}
} else {
}
match token_buffer.to_lowercase().as_str(){
"section"=>{
rt.push(Section{contents: Vec::new()});
},
"header" | "text" | "question" =>{
if rt.len() == 0{
//TODO we need to throw a warning
i+=1;
continue 'a;
}
let mut j = 0;
let mut string = String::new();
'd: loop{
if i + j >= char_arr.len(){
let rt_index = rt.len() - 1;
match token_buffer.to_lowercase().as_str(){
"header"=>{ rt[rt_index].contents.push(Header(string)); }
"text"=>{ rt[rt_index].contents.push(Text(string)); }
"question"=>{ rt[rt_index].contents.push(Question(string)); }
_=>{ }
}
break 'a;
}
if char_arr[i+j] == '\n'
&& j == 0 {
j+=1;
continue 'd;
}
if char_arr[i+j] == ' '
&& j == 0 {
j+=1;
continue 'd;
}
if char_arr[i+j] == '\n'
&& peek_is_char( i+j, &char_arr, '#'){
i += j;
break 'd;
}
string.push(char_arr[i+j]);
j += 1;
}
let rt_index = rt.len() - 1;
match token_buffer.to_lowercase().as_str(){
"header"=>{ rt[rt_index].contents.push(Header(string)); }
"text"=>{ rt[rt_index].contents.push(Text(string)); }
"question"=>{ rt[rt_index].contents.push(Question(string)); }
_=>{ }
}
},
"image"=>{
if rt.len() == 0{
//TODO we need to throw a warning
break 'a;
}
let mut j = 0;
let mut string = String::new();
'e: loop{
if i + j >= char_arr.len(){
let rt_index = rt.len() - 1;
if string.chars().nth(0) == Some(' '){
string.remove(0);
}
if string.chars().nth(string.len()) == Some(' '){
let l = string.len()-1;
string.remove(l);
}
if !std::path::Path::new(&string).exists()
{
errs.push(( MessageType::Error, format!("Error: {} does not exist", string)));
}
rt[rt_index].contents.push(Image(string)); //TODO we could path this here?
break 'a;
}
if char_arr[i+j] == '\n'
&& j == 0 {
j+=1;
continue 'e;
}
if char_arr[i+j] == '\n'
&& j > 0{
i += j;
break 'e;
}
string.push(char_arr[i+j]);
j += 1;
}
let rt_index = rt.len() - 1;
if string.chars().nth(0) == Some(' '){
string.remove(0);
}
if string.chars().nth(string.len()) == Some(' '){
let l = string.len()-1;
string.remove(l);
}
if !std::path::Path::new(&string).exists()
{ errs.push( ( MessageType::Error, format!("Error: Image file, {}, does not exist.", string)))}
rt[rt_index].contents.push(Image(string));
},
"answercorrect" | "answerwrong"=>{
//TODO
if rt.len() == 0{
//TODO we need to throw a warning
break 'a;
}
let mut j = 0;
let mut string = String::new();
'f: loop{
if i + j >= char_arr.len(){
let rt_index = rt.len() - 1;
match token_buffer.to_lowercase().as_str(){
"answercorrect"=>{ rt[rt_index].contents.push(Answer(string, true)); }
"answerwrong"=>{ rt[rt_index].contents.push(Answer(string, false)); }
_=>{ }
}
break 'a;
}
if char_arr[i+j] == '\n'
&& j == 0 {
j+=1;
i += j;
continue 'f;
}
if char_arr[i+j] == '\n'
&& peek_is_char( i+j, &char_arr, '#'){
i += j;
break 'f;
}
string.push(char_arr[i+j]);
j += 1;
}
let rt_index = rt.len() - 1;
match token_buffer.to_lowercase().as_str(){
"answercorrect"=>{ rt[rt_index].contents.push(Answer(string, true)); }
"answerwrong"=>{ rt[rt_index].contents.push(Answer(string, false)); }
_=>{ }
}
},
_=>{ i+= 1; }
}
token_buffer.clear();//TODO
}
return (rt, errs);
}
}
pub fn draw_grid(canvas: &mut WindowCanvas, grid_size: i32, offset: [i32;2]){
let canvas_w = canvas.w;
let canvas_h = canvas.h;
for i in -offset[0]/grid_size..(canvas_w-offset[0])/grid_size{
let x = i * grid_size - 1 + offset[0];
draw_rect(canvas, [x, 0, 2, canvas_h], COLOR_GRID, true);
}
for i in -offset[1]/grid_size..(canvas_h-offset[1])/grid_size{
let y = i * grid_size - 1 + offset[1];
draw_rect(canvas, [0, y, canvas_w, 2], COLOR_GRID, true);
}
}
mod matrixmath{
//! This module is a simple linear algebra library
//! made to satisfy the requirements of this application.
//! The library does not contain all linear algebra operations, nor does it attempt to.
//! The purpose is, again, to provide functionality necessary to solve electrical circuits.
#![allow(unused)]
pub struct Matrix{
pub arr : Vec<f32>,
pub rows : usize,
pub columns : usize,
}
impl Matrix{
pub fn zeros(rows: usize, columns: usize)->Matrix{
if rows == std::usize::MAX
|| columns == std::usize::MAX{
panic!("Exceeded size limits.");
}
Matrix{
arr: vec![0.0f32; rows*columns],
rows : rows,
columns : columns,
}
}
pub fn identity(rows_columns: usize)->Matrix{
if rows_columns == std::usize::MAX {
panic!("Exceeded size limits.");
}
let mut m = Matrix::zeros(rows_columns, rows_columns);
for i in 0..rows_columns{
*m.get_element(i, i) = 1.0;
}
return m;
}
pub fn grow(&mut self, add_n_rows: usize, add_n_columns: usize){
let mut v = Matrix::zeros(self.rows+add_n_rows, self.columns+add_n_columns);
for r in 0..self.rows{
for c in 0..self.columns{
*v.get_element(r, c) = *self.get_element(r, c);
}
}
self.rows += add_n_rows;
self.columns += add_n_columns;
self.arr = v.arr;
}
//TODO might be nice to incorportate numpy style -1 symantics
pub fn get_element(&mut self, row: usize, column: usize)->&mut f32{
return &mut self.arr[column + self.columns * row];
}
pub fn multiply(&self, matrix: &Matrix)->Matrix{
if self.columns != matrix.rows
|| self.rows != matrix.columns
{ panic!("Column Row mismatch: {} {} || {} {}", self.columns, self.rows, matrix.columns, matrix.rows); }
let mut rt_matrix = Matrix::zeros(self.rows, matrix.columns);
for j in 0..rt_matrix.rows{
for i in 0..rt_matrix.columns{
let value = {
let mut temp = 0.0;
for k in 0..self.columns{
temp += self.arr[k + j*self.columns] * matrix.arr[ i + k*matrix.columns];
}
temp
};
rt_matrix.arr[ i + rt_matrix.columns*j ] = value;
}
}
return rt_matrix;
}
pub fn transpose(&self)->Matrix{
let mut rt_matrix = Matrix::zeros(self.columns, self.rows);
for j in 0..rt_matrix.rows{
for i in 0..rt_matrix.columns{
rt_matrix.arr[ i + rt_matrix.columns*j ] = self.arr[j + self.columns*i];
}
}
return rt_matrix;
}
/////////////////////////////////////////////
/* https://en.wikipedia.org/wiki/Gaussian_elimination
h := 1 /* Initialization of the pivot row */
k := 1 /* Initialization of the pivot column */
while h ≤ m and k ≤ n
/* Find the k-th pivot: */
i_max := argmax (i = h ... m, abs(A[i, k]))
if A[i_max, k] = 0
/* No pivot in this column, pass to next column */
k := k+1
else
swap rows(h, i_max)
/* Do for all rows below pivot: */
for i = h + 1 ... m:
f := A[i, k] / A[h, k]
/* Fill with zeros the lower part of pivot column: */
A[i, k] := 0
/* Do for all remaining elements in current row: */
for j = k + 1 ... n:
A[i, j] := A[i, j] - A[h, j] * f
/* Increase pivot row and column */
h := h + 1
k := k + 1
*/
pub fn gaussian_elimination(&mut self){
fn swap_rows(m1: &mut Matrix, row1: usize, row2: usize){
for i in 0..m1.columns{
let temp = m1.arr[i + m1.columns*row1];
m1.arr[i + m1.columns*row1] = m1.arr[i+m1.columns*row2];
m1.arr[i + m1.columns*row2] = temp;
}
}
let mut h = 0;
let mut k = 0;
let m = self.rows;
let n = self.columns;
while h < m && k < n {
let i_max : usize = {
let mut rt = 0;
let mut f = 0.0;
for i in h..m {
if self.arr[k + i*self.columns].abs() > f { f = self.arr[k + i*self.columns].abs(); rt = i; }
}
rt
};
if self.arr[k + i_max*self.columns] == 0.0 { k+=1; continue; }
else{
swap_rows(self, h, i_max);
for i in h+1..m{
let f = self.arr[k + i*self.columns] / self.arr[k + h*self.columns];
self.arr[k + i*self.columns] = 0.0;
for j in k+1..n{
self.arr[j + i*self.columns] = self.arr[j + i*self.columns] - self.arr[j + h*self.columns] * f;
}
}
h += 1;
k += 1;
}
}
//println!("{:?}", self);
///////////////////////////////
//TODO NEW
//remove offdiagonals
let mut minus_i = self.columns-1;
for i in (0..self.rows).rev(){
minus_i -= 1;
let minus_1 = self.columns - 1;
//NOTE not the best solution ....
if (self.arr[i*self.columns+minus_1] == self.arr[i*self.columns+minus_i]
&& self.arr[i*self.columns+minus_i] == 0f32)
|| self.arr[i*self.columns+minus_i] == 0f32{
continue;
}
//println!("{} {}", self.arr[i*self.columns+minus_1], self.arr[i*self.columns+minus_i]);
self.arr[i*self.columns+minus_1] = self.arr[i*self.columns+minus_1] / self.arr[i*self.columns+minus_i];
self.arr[i*self.columns+minus_i] = 1.0;
for j in 0..i{
self.arr[j*self.columns+minus_i] *= self.arr[i*self.columns+minus_1];
self.arr[j*self.columns+minus_1] -= self.arr[j*self.columns+minus_i];
self.arr[j*self.columns+minus_i] = 0.0;
}
}
///////////////////////
}
}
impl PartialEq for Matrix{
fn eq(&self, x: &Self)->bool{
if self.rows == x.rows
&& self.columns == x.columns {
for i in 0..self.arr.len(){
if (self.arr[i] - x.arr[i]).abs() > 0.0001 { return false; }
}
} else {
return false;
}
return true;
}
}
use std::fmt;
impl fmt::Debug for Matrix{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result{
let mut array_string = format!("Matrix rows {}, columns {} \n", self.rows, self.columns);
array_string.push('[' );
for (i, it) in self.arr.iter().enumerate(){
array_string.push_str( &((it*100f32).round()/100f32).to_string() );
array_string.push_str( ", " );
if (i+1) % self.columns == 0 && i != self.arr.len() - 1{
array_string.push( '\n' );
}
}
array_string.push( ']' );
f.write_str(&array_string)
}
/*fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Point")
.field("x", &self.x)
.field("y", &self.y)
.finish()
}*/
}
#[test]
fn gaussianelimination_test(){
let mut m1 = Matrix{
arr: vec![ 2.0, 1.0, -1.0, 8.0,
-3.0, -1.0, 2.0, -11.0,
-2.0, 1.0, 2.0, -3.0,
],
rows: 3,
columns: 4,
};
let mut m2 = Matrix{
arr: vec![ 1.0, 0.0, 0.0, 2.0,
0.0, 1.0, 0.0, 3.0,
0.0, 0.0, 1.0, -1.0,
],
rows: 3,
columns: 4,
};
m1.gaussian_elimination();
assert_eq!(m2, m1);
let mut m3 = Matrix{
arr: vec![
1.0, 1.0, 3.0,
3.0, -2.0, 4.0,
],
rows: 2,
columns: 3,
};
let mut m4 = Matrix{
arr:vec![
1.0, 0.0, 2.0,
0.0, 1.0, 1.0,
],
rows: 2,
columns: 3,
};
m3.gaussian_elimination();
assert_eq!(m4, m3);
let mut m1 = Matrix{
arr: vec![
-1.0, 1.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0, -1.0, 0.0,
0.0, 0.0, 1.0, 0.0, 0.0, 2.0,
0.0, -0.5, 0.0, 1.0, 0.0, 0.0,
],
rows: 5,
columns: 6,
};
m1.gaussian_elimination();
//let mut m = Matrix{ rows: 7, columns: 11,
// arr: vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0,
// -1.0, 1.0, 1.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, -1.0, 0.0, 0.0, 1.0, 1.0, 0.0,
// 0.0, -1.0, 0.0, 0.0, -1.0, 1.0, -1.0, 0.0, 0.0, 0.0, 0.0,
// 0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
// 0.0, 0.0, 0.0, -1.0, 1.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, 1.0, -1.0, 0.0, 0.0,
// 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, 0.0, ],
//};
//m.gaussian_elimination();
//panic!("{:?}", m);
//let mut m= Matrix{
// arr: vec![
// 1.0, 1.0, 0.0, 0.0, 3.0,
// 3.0, -2.0, 0.0, 0.0, 4.0,
// 0.0, 0.0, 5.0, 0.4, 2.0,
// 0.0, 0.0, -1.0, 3.0, 1.0,
// ],
// rows: 4,
// columns: 5,
//};
//m.gaussian_elimination();
panic!("{:?}", m);
}
#[test]
fn transpose_test(){
let m1 = Matrix{
arr: vec![1.0, 2.0],
rows: 1,
columns: 2,
};
let m2 = Matrix{
arr: vec![1.0, 2.0],
rows: 2,
columns: 1,
};
assert_eq!(m1.transpose(), m2);
let m1 = Matrix{
arr: vec![1.0, 2.0,
3.0, 4.0,
],
rows: 2,
columns: 2,
};
let m2 = Matrix{
arr: vec![1.0, 3.0,
2.0, 4.0,
],
rows: 2,
columns: 2,
};
assert_eq!(m1.transpose(), m2);
let m1 = Matrix{
arr: vec![1.0, 2.0,
3.0, 4.0,
5.0, 6.0,
],
rows: 3,
columns: 2,
};
let m2 = Matrix{
arr: vec![1.0, 3.0, 5.0,
2.0, 4.0, 6.0,
],
rows: 2,
columns: 3,
};
assert_eq!(m1.transpose(), m2);
}
#[test]
fn mult_test(){
let m1 = Matrix{
arr: vec![1.0, 2.0, 3.0],
rows:1,
columns:3,
};
let m2 = Matrix{
arr: vec![4.0, 5.0, 6.0],
rows:3,
columns:1,
};
let m3 = Matrix{
arr: vec![32.0],
rows: 1,
columns: 1,
};
let m4 = Matrix{
arr: vec![4.0, 8.0, 12.0,
5.0, 10.0, 15.0,
6.0, 12.0, 18.0],
rows: 3,
columns: 3,
};
assert_eq!(m1.multiply(&m2), m3);
assert_eq!(m2.multiply(&m1), m4);
let m5 = Matrix{
arr: vec![1.0, 2.0,
3.0, 4.0,],
rows: 2,
columns: 2,
};
let m6 = Matrix{
arr: vec![2.0, 0.0,
1.0, 2.0,],
rows: 2,
columns: 2,
};
let m7 = Matrix{
arr: vec![4.0, 4.0,
10.0, 8.0,],
rows: 2,
columns: 2,
};
let m8 = Matrix{
arr: vec![2.0, 4.0,
7.0, 10.0,],
rows: 2,
columns: 2,
};
assert_eq!(m5.multiply(&m6), m7);
assert_eq!(m6.multiply(&m5), m8);
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
struct Pair{
in_node: usize,
out_node: usize,
good: bool,
element_index: usize,
orig_element_index: usize,
}
///This function computes the currents and voltages for the user defined
///circuit.
///
///The function uses techniques defined in this paper, ["The Sparse Tableau Approach to Network Analysis and Design"](http://web.engr.oregonstate.edu/~karti/ece521/sta.pdf). The method
///discribes constructing circuit as aset of linear equations solved using Gaussian
///elimination. More detailed notes can be found in the code.
///
///For an additional resource consult the textbook "Circuit Simulation" by Farid Najim.
fn compute_circuit(graph : &mut Vec<CircuitElement>)->(Matrix, Vec<Pair>, Vec<usize>){
let rt = Matrix::zeros(0,0);
if graph[0].discovered{ //TODO not sure what this is about
return (rt, vec![], Vec::new());
}
let mut unique_nodes = vec![];
let mut unique_elements = vec![];
for it in graph.iter(){
let contains_a = unique_nodes.contains(&it.a_node);
let contains_b = unique_nodes.contains(&it.b_node);
if !contains_a{
unique_nodes.push(it.a_node)
}
if !contains_b{
unique_nodes.push(it.b_node)
}
unique_elements.push(it);
}
//Prune nodes
//TODO we should while loop this just in case there
//more nodes to be pruned after first removal
let mut element_was_removed = true;
while element_was_removed == true{
element_was_removed = false;
let mut remove = vec![];
let mut remove_element = vec![];
for (j, jt) in unique_nodes.iter().enumerate(){
let mut n = 0;
for (_, it) in unique_elements.iter().enumerate(){
if it.b_node == *jt
|| it.a_node == *jt{
n+=1;
}
}
if n < 2{
remove.push(j);
element_was_removed = true;
}
}
for it in remove.iter().rev(){
unique_nodes.remove(*it);
}
for (j, jt) in unique_elements.iter().enumerate(){
if !unique_nodes.contains(&jt.a_node)
|| !unique_nodes.contains(&jt.b_node){
remove_element.push(j);
}
}
for it in remove_element.iter().rev(){
unique_elements.remove(*it);
}
}
if unique_elements.len() < 4 {
return (rt, vec![], Vec::new());
}
let mut pairs = vec![];
for (i, it) in unique_elements.iter().enumerate(){
let mut orig_index = 0;
for (j, jt) in graph.iter().enumerate(){
if jt.a_node == it.a_node
&& jt.b_node == it.b_node {
orig_index = j;
}
}
pairs.push( Pair{in_node: it.a_node, out_node: it.b_node, good: true, element_index: i, orig_element_index: orig_index});
}
//TODO
//multi circuits do not work :(
{//NOTE prune unique_nodes
let mut bad_nodes = vec![];
for (i, it) in unique_nodes.iter().enumerate(){
let mut is_node_good = false;
for jt in pairs.iter(){
if jt.in_node == *it
|| jt.out_node == *it{
is_node_good = true;
break;
}
}
if !is_node_good {
bad_nodes.push(i);
}
}
for it in bad_nodes.iter().rev(){
unique_nodes.remove(*it);
}
}
//println!("DEF {:?}", &pairs);
//println!("DEF {}", pairs.len());
////TODO
//let mut pairs = vec![]
//for it in unique_nodes.iter(){
//}
{//NOTE Set correct circuit element direction
let mut m = Matrix::zeros(unique_nodes.len(), pairs.len());
for (i, it) in pairs.iter().enumerate(){
let in_node = match unique_nodes.binary_search(&it.in_node) {
Ok(n) => {n},
Err(_) => {
println!("There was no in_node found in unique. {:?} {} {}", it, unique_elements[it.element_index].unique_a_node, unique_elements[it.element_index].unique_b_node);
return (rt, vec![], Vec::new());
},
};
let out_node = match unique_nodes.binary_search(&it.out_node){
Ok(n) => {n},
Err(_) => {
println!("There was no out_node found in unique. {:?} {} {} | {} {}", it, unique_elements[it.element_index].unique_a_node, unique_elements[it.element_index].unique_b_node,
unique_elements[it.element_index].a_node, unique_elements[it.element_index].b_node);
return (rt, vec![], Vec::new());
},
};
*m.get_element(in_node, i) = 1.0;
*m.get_element(out_node, i) = 1.0;
}
undirected_to_directed_matrix(&mut m);
for (i, it) in pairs.iter_mut().enumerate(){
let in_node = match unique_nodes.binary_search(&it.in_node) {
Ok(n) => {n},
Err(_) => {
println!("There was no in_node found in unique. {:?} {} {}", it, unique_elements[it.element_index].unique_a_node, unique_elements[it.element_index].unique_b_node);
return (rt, vec![], Vec::new());
},
};
let out_node = match unique_nodes.binary_search(&it.out_node){
Ok(n) => {n},
Err(_) => {
println!("There was no out_node found in unique. {:?} {} {} | {} {}", it, unique_elements[it.element_index].unique_a_node, unique_elements[it.element_index].unique_b_node,
unique_elements[it.element_index].a_node, unique_elements[it.element_index].b_node);
return (rt, vec![], Vec::new());
},
};
let temp_in = it.in_node;
let temp_out = it.out_node;
if *m.get_element(in_node, i) == -1.0{
it.in_node = temp_out;
}
if *m.get_element(out_node, i) == 1.0{
it.out_node = temp_in;
}
}
}
let mut m = Matrix::zeros(unique_nodes.len(), pairs.len());
let mut z = Matrix::zeros(pairs.len(), pairs.len());
let mut y = Matrix::identity(pairs.len());
let mut s = Matrix::zeros(pairs.len(), 1);
let mut b = Matrix::zeros(s.rows,0);
let mut f = Matrix::zeros(0, 0);
let mut t = Matrix::zeros(0, 1); //TODO
for (i, it) in pairs.iter().enumerate(){
let in_node = match unique_nodes.binary_search(&it.in_node) {
Ok(n) => {n},
Err(_) => {
println!("There was no in_node found in unique. {:?} {} {}", it, unique_elements[it.element_index].unique_a_node, unique_elements[it.element_index].unique_b_node);
return (rt, vec![], Vec::new());
},
};
let out_node = match unique_nodes.binary_search(&it.out_node){
Ok(n) => {n},
Err(_) => {
println!("There was no out_node found in unique. {:?} {} {} | {} {}", it, unique_elements[it.element_index].unique_a_node, unique_elements[it.element_index].unique_b_node,
unique_elements[it.element_index].a_node, unique_elements[it.element_index].b_node);
return (rt, vec![], Vec::new());
},
};
*m.get_element(in_node, i) = 1.0;
*m.get_element(out_node, i) = -1.0;
*z.get_element(i, i) = -1.0* ( unique_elements[it.element_index].resistance + unique_elements[it.element_index].unc_resistance );
if unique_elements[it.element_index].capacitance > 0.0{ //TODO should we check circuit element type instead?
*y.get_element(i, i) = unique_elements[it.element_index].capacitance + unique_elements[it.element_index].unc_capacitance;
}
if unique_elements[it.element_index].inductance > 0.0{ //TODO should we check circuit element type instead?
*z.get_element(i, i) = unique_elements[it.element_index].inductance + unique_elements[it.element_index].unc_inductance;
*y.get_element(i, i) = 0.0;
}
*s.get_element(i, 0) = if it.in_node == unique_elements[it.element_index].a_node { unique_elements[it.element_index].voltage + unique_elements[it.element_index].unc_voltage }
else {-1.0 * (unique_elements[it.element_index].voltage + unique_elements[it.element_index].unc_voltage )};
if unique_elements[it.element_index].circuit_element_type == SelectedCircuitElement::Capacitor{
b.grow(0,1);
f.grow(1,1);
t.grow(1,0);
let _i = t.rows-1;
*t.get_element(_i, 0) = if it.in_node == unique_elements[it.element_index].a_node { unique_elements[it.element_index].charge }
else { -1f32 * unique_elements[it.element_index].charge };
*b.get_element(i, _i) = -1.0;
*f.get_element(_i, _i) = 1.0;
}
if unique_elements[it.element_index].circuit_element_type == SelectedCircuitElement::Inductor{
b.grow(0,1);
f.grow(1,1);
t.grow(1,0);
let _i = t.rows-1;
*t.get_element(_i, 0) = unique_elements[it.element_index].magnetic_flux;
*b.get_element(i, _i) = -1.0;
*f.get_element(_i, _i)= 1.0;
}
if unique_elements[it.element_index].circuit_element_type == SelectedCircuitElement::Custom
&& unique_elements[it.element_index].capacitance.abs() > 0.00001f32{
b.grow(0,1);
f.grow(1,1);
t.grow(1,0);
let _i = t.rows-1;
*t.get_element(_i, 0) = if it.in_node == unique_elements[it.element_index].a_node { unique_elements[it.element_index].charge + unique_elements[it.element_index].unc_charge }
else { -1f32 * unique_elements[it.element_index].charge + unique_elements[it.element_index].unc_charge};
*b.get_element(i, _i) = -1.0;
*f.get_element(_i, _i) = 1.0;
}
if unique_elements[it.element_index].circuit_element_type == SelectedCircuitElement::Custom
&& unique_elements[it.element_index].inductance.abs() > 0.00001f32{
b.grow(0,1);
f.grow(1,1);
t.grow(1,0);
let _i = t.rows-1;
*t.get_element(_i, 0) = unique_elements[it.element_index].magnetic_flux + unique_elements[it.element_index].unc_magnetic_flux;
*b.get_element(i, _i) = -1.0;
*f.get_element(_i, _i)= 1.0;
}
}
let mut a = Matrix::zeros(m.rows-1, m.columns);
for r in 1..m.rows{
for c in 0..m.columns{
*a.get_element(r-1, c) = *m.get_element(r, c);
}
}
{//NOTE check matrix M for consistency
for i in 0..m.columns{
let mut sum = 0.0;
for j in 0..m.rows{
sum +=*m.get_element(j, i);
}
if sum.round() != 0.0 {
println!("Matrix M is inconsistent with definition. {:?}", m);
return (rt, vec![], Vec::new());
}
}
}
// println!("m: {:?}", m);
// println!("a: {:?}", a);
// println!("z: {:?}", z);
// println!("s: {:?}", s);
let mut c_matrix = Matrix::zeros( 2*a.columns + a.rows + f.rows, 2*a.columns + a.rows + b.columns + 1 ); //OLD
{//Construct full circuit matrix
/*NOTE NEW
This is what we are trying to make:
unknowns = [ i, u, v, p ]
c_matrix = [ A, 0, 0, 0, | 0
0, I, -1*AT, 0, | 0
Z, Y, 0, B, | s
0, 0, 0, F, | t
]
We wish to formulate circuit equations in the matrix above and use
Gaussian elimination to for unknowns. We begin with matrix 'A', which
contains Kerkove current loop rules, for every vertex there must be some path
for both incoming and out going current. In the second row of c_matrix
contains rules on the conservation of voltage. 'A' is a matrix with elements
of 0 or 1. The next row is filled with matrices where are parameterized by
the characteristics of circuit elements. 'Z' is related to current, and
is where resistances might be placed. 'Y' is paired to the change in voltage
across an element, 'B' relates to stored energy (a capacitor's charge).
It is through application of unknowns on c_matrix do we retrieve the ohm's law
and the like. 'F' is paired to store energy.
Vectors 's' and 't' can be thought of has the other half of our ohm's law like
equations. 'Z', 'Y', and 'B' deliver the right side of the equation, 's' must deliver the left.
't' sets the value of energy storage variables, as fixed in time. This must be
updated externally.
*/
// write A
for r in 0..a.rows{
for c in 0..a.columns{
let r_offset = 0;
let c_offset = 0;
*c_matrix.get_element( r+r_offset, c+c_offset) = *a.get_element(r, c);
}
}
// write A^T
let mut a_t = a.transpose();
for r in 0..a_t.rows{
for c in 0..a_t.columns{
let r_offset = a.rows;
let c_offset = 2*a.columns;
*c_matrix.get_element( r+r_offset, c+c_offset) = *a_t.get_element(r, c) * -1.0 ;
}
}
// write I
let mut identity_m = Matrix::identity(a.columns);
for r in 0..identity_m.rows{
for c in 0..identity_m.columns{
let r_offset = a.rows;
let c_offset = a.columns;
*c_matrix.get_element( r+r_offset, c+c_offset) = *identity_m.get_element(r, c);
}
}
//write Z
for r in 0..z.rows{
for c in 0..z.columns{
let r_offset = a.rows + a.columns;
let c_offset = 0;
*c_matrix.get_element( r+r_offset, c+c_offset) = *z.get_element(r, c);
}
}
//write Y
//NOTE for linear resistance graphs Y is I
for r in 0..y.rows{
for c in 0..y.columns{
let r_offset = a.rows + a.columns;
let c_offset = a.columns;
*c_matrix.get_element( r+r_offset, c+c_offset) = *y.get_element(r, c);
}
}
//write B
for r in 0..b.rows{
for c in 0..b.columns{
let r_offset = a.rows + a.columns;
let c_offset = a.columns + y.columns + a.rows;
*c_matrix.get_element( r+r_offset, c+c_offset) = *b.get_element(r, c);
}
}
//write F
for r in 0..f.rows{
for c in 0..f.columns{
let r_offset = a.rows + a.columns + z.rows;
let c_offset = a.columns + y.columns + a.rows;
*c_matrix.get_element( r+r_offset, c+c_offset) = *f.get_element(r, c);
}
}
//write s
for r in 0..s.rows{
for c in 0..s.columns{
let r_offset = a.rows + a.columns;
let c_offset = 2*a.columns + a.rows + b.columns;
*c_matrix.get_element( r+r_offset, c+c_offset) = *s.get_element(r, c);
}
}
//write t
for r in 0..t.rows{
for c in 0..t.columns{
let r_offset = a.rows + a.columns + s.rows;
let c_offset = 2*a.columns + a.rows + b.columns;
*c_matrix.get_element( r+r_offset, c+c_offset) = *t.get_element(r, c);
}
}
//println!("cmatrix\n{:?}", c_matrix);
c_matrix.gaussian_elimination();
}
//println!("cmatrix\n{:?}", c_matrix);
//panic!();
return (c_matrix, pairs, unique_nodes);
}
/// Draws a graph to a given window canvas. x and y are buffers containing input data.
///
/// ## Example
/// ```
/// let x_data = [1f32,2f32,3f32,4f32,5f32];
/// let y_data = [1f32,2f32,3f32,4f32,5f32];
///
/// draw_graph(canvas, &x_data, &y_data, [10, 10, 200, 200], 5f32, 18f32);
/// ```
fn draw_graph(canvas: &mut WindowCanvas, x: &[f32], y: &[f32], rect: [i32; 4], min_x_range: f32, font_size: f32,
mouseinfo: &MouseInfo){
let _rect = [ rect[0] + font_size as i32 + 3,
rect[1] + font_size as i32 - 5,
rect[2] - font_size as i32 - 3,
rect[3] - font_size as i32 + 5,
];
draw_rect(canvas, rect, C4_CREAM, true);
draw_rect(canvas, _rect, C4_WHITE, true);
if x.len() != y.len(){
panic!("draw_graph x and y lens are not the same!");
}
let mut min_x = std::f32::MAX;
let mut max_x = std::f32::MIN;
for it in x.iter(){
if *it < min_x {
min_x = *it;
}
if *it > max_x {
max_x = *it;
}
}
let x_range = (max_x - min_x).abs().max(min_x_range);
let mut min_y = std::f32::MAX;
let mut max_y = std::f32::MIN;
for it in y.iter(){
if *it < min_y {
min_y = *it;
}
if *it > max_y {
max_y = *it;
}
}
let _y_range = (max_y - min_y).abs();
max_y += 0.25*_y_range.max(1.0);
min_y -= 0.25*_y_range.max(1.0);
let y_range = (max_y - min_y).abs().max(1.0);
for i in 0..x.len(){
let _x = (((x[i] - min_x) / x_range) * _rect[2] as f32) as i32 + _rect[0];
let _y = (((y[i] - min_y)/ y_range) * _rect[3] as f32) as i32 + _rect[1];
draw_rect(canvas, [_x-1, _y-1, 3, 3], C4_DGREY, true);
}
if x.len() > 0 {
for i in 0..4{//Y-Axis
let tick_label = (i as f32 / 4.0 ) * y_range + min_y;
let _x = rect[0]-2;
let _y = rect[1] + ((i as f32 / 4.0 ) * _rect[3] as f32) as i32;
draw_string(canvas, &format!("{:.1}", tick_label), _x, _y, C4_BLACK, font_size);
}
for i in 0..4{//X-Axis
let tick_label = (i as f32 / 4.0 ) * x_range + min_x;
let _x = rect[0] + ((i as f32 / 4.0 ) * _rect[2] as f32) as i32 + (font_size/2f32) as i32;
let _y = rect[1] - (font_size/2f32) as i32 + 2;
draw_string(canvas, &format!("{:.1}", tick_label), _x, _y, C4_BLACK, font_size);
}
}
if in_rect(mouseinfo.x, mouseinfo.y, _rect){
let _x = mouseinfo.x;
let _y = mouseinfo.y;
let g_x = (_x - _rect[0]) as f32 / (_rect[2] as f32) * x_range + min_x;
let g_y = (_y - _rect[1]) as f32 / (_rect[3] as f32) * y_range + min_y;
let _str = format!("({:.2}, {:.2})", g_x, g_y);
let _w = get_advance_string(&_str, font_size) + 4;
let _h = font_size as i32;
draw_rect(canvas, [_x, _y, _w, _h], c3_to_c4(C3_CREAM, 0.5), true);
draw_string(canvas, &_str, _x, _y, C4_BLACK, font_size);
}
}
fn generate_csv_name(filename: &str)->String{
//TODO if the saved file has many periods we may experience an error
let _filename : Vec<&str>= filename.split('.').collect();
if _filename.len() != 2 {
return filename.to_string();
}
let extension = _filename[1];
let mut files = vec![];
let iter_dir = std::fs::read_dir("./").unwrap();
for it in iter_dir{
if !it.is_ok(){ continue; }
let ref_it = it.as_ref().unwrap().path();
if !ref_it.is_file(){ continue; }
match ref_it.extension(){
Some(temp_str)=>{
if temp_str != extension { continue; }
let ref_str = ref_it.to_str().unwrap();
let mut _temp = ref_str.to_string();
_temp.remove(0);
_temp.remove(0);
files.push(_temp);
},
None=>{}
}
}
//TODO loop through files check if proposed filename is in files. If not return a new file name
let mut i = 0;
let string_filename = filename.to_string();
loop {
if i == 0 {
//loop through the thingoo
if !files.contains(&string_filename){
return string_filename;
}
} else {
let l = _filename.len();
let new_filename = format!("{}_{}.{}", _filename[0], i, _filename[l-1]);
if !files.contains(&new_filename){
return new_filename;
}
}
i += 1;
}
}
fn save_csv( filename: &str, data: &[&[f32]], data_labels: &[&str]){
use std::fs::File;
if data.len() != data_labels.len(){
println!("data and labels have different lengths");
return;
}
if data.len() == data_labels.len()
&& data.len() == 0{
println!("There is no data");
return;
}
for i in 1..data.len() {
if data[0].len() != data[i].len(){
println!("Data does not share the same length");
return;
}
}
//File stuff
let mut filebuffer = match File::create(filename){
Ok(_fb) => _fb,
Err(_s) => {
println!("BMP file could not be made. {}", _s);
return;
}
};
for label in data_labels.iter(){
write!(filebuffer, "{}, ", label);
}
write!(filebuffer, "\n");
for i in 0..data[0].len(){
for j in 0..data_labels.len(){
write!(filebuffer, "{}, ", data[j][i]);
}
write!(filebuffer, "\n");
}
}
fn save_circuit_diagram(name: &str, circuit: &[CircuitElement]){unsafe{
use std::io::prelude::*;
use std::mem::transmute;
use std::mem::size_of;
//NOTE
//save file structure
//['c''d''# of elements in circuit array']HEADER
//['circuit element type' 'orientation' 'x' 'y' 'length' 'unique_a_node' 'unique_b_node'
//'resistance' 'voltage' 'current' 'capacitance' 'inductance' 'charge' 'magnetic_flux']
let mut f = std::fs::File::create(name).expect("File could not be created.");
f.write_all(b"CD").expect("write all has been interrupted.");
f.write_all(&transmute::<u64, [u8; size_of::<u64>()]>(size_of::<CircuitElement>() as u64)).expect("write all has been interrupted.");
f.write_all(&transmute::<u64, [u8; size_of::<u64>()]>(circuit.len() as u64)).expect("write all has been interrupted.");
for it in circuit.iter(){
f.write_all( &transmute::<CircuitElement, [u8; size_of::<CircuitElement>()]>(*it) ).expect("write all has been interrupted.");
}
}}
fn load_circuit_diagram(name: &str)->Vec<CircuitElement>{unsafe{
use std::io::prelude::*;
use std::mem::{transmute, size_of};
let mut f = std::fs::File::open(name).expect("File could not be created.");
let mut file_header_buffer = [0u8;2];
f.read( &mut file_header_buffer).expect("Could not read from file.");
if file_header_buffer[0] as char == 'C'
&& file_header_buffer[1] as char == 'D'{
} else {
panic!("File type is wrong.");
}
let mut sizeof_circuit_elements = [0u8; size_of::<u64>()];
f.read(&mut sizeof_circuit_elements).expect("Could not read from file.");
let sizeof_circuit_elements = transmute::< [u8; size_of::<u64>()], u64>(sizeof_circuit_elements);
if size_of::<CircuitElement>() < sizeof_circuit_elements as usize{
println!("It is highly likely that the load has failed. Current CircitElement struct is smaller than saved struct");
}
let mut number_circuit_elements = [0u8; size_of::<u64>()];
f.read(&mut number_circuit_elements).expect("Could not read from file.");
let number_circuit_elements = transmute::< [u8; size_of::<u64>()], u64>(number_circuit_elements);
let mut rt = Vec::with_capacity(number_circuit_elements as usize);
let mut _it = vec![0u8; sizeof_circuit_elements as usize];
let mut max_id = 0;
for _ in 0..number_circuit_elements{
f.read(&mut _it).expect("Could not read from file.");
let mut element = CircuitElement::empty();
std::ptr::copy_nonoverlapping( _it.as_mut_ptr(), &mut element as *mut CircuitElement as *mut u8, sizeof_circuit_elements as usize);
if element.unique_b_node > max_id {
max_id = element.unique_b_node;
}
if element.properties_selected {
element.properties_z = get_and_update_global_properties_z();
}
rt.push(element);
}
set_unique_id(max_id+1);
return rt;
}}
#[derive(Clone)]
struct TextBox{
text_buffer: String,
text_cursor: usize,
max_char: i32,
max_render_length: i32,
text_size: f32,
x: i32,
y: i32,
text_color:[f32;4],
bg_color:[f32;4],
cursor_color:[f32;4],
omega: f32,
active: bool,
offset_x: i32,
offset_y: i32,
}
impl TextBox{
pub fn new()->TextBox{
TextBox{
text_buffer: String::new(),
text_cursor: 0,
max_char: 30,
max_render_length: 200,
text_size: 24.0,
x: 0,
y: 0,
text_color:[0.85;4],
cursor_color:[0.8;4],
bg_color:[1.0, 1.0, 1.0, 0.145],
omega: 4.0f32,
active: false,
offset_x: 0i32,
offset_y: 0i32,
}
}
pub fn update(&mut self, keyboardinfo : &KeyboardInfo, textinfo: &TextInfo, mouseinfo: &MouseInfo){
fn place_cursor(_self: &mut TextBox, mouseinfo: &MouseInfo){//Look for where to place cursor
let mut position = 0;
for (i, it) in _self.text_buffer.chars().enumerate() {
//IF mouse is between old position and new position then we place cursor
//behind the current character
let adv = get_advance(it, _self.text_size);
if i < _self.text_buffer.len() - 1 {
if mouseinfo.x >= position + _self.x + _self.offset_x + 4 && mouseinfo.x < position + adv + _self.x + _self.offset_x + 4 {
_self.text_cursor = i;
break;
}
} else {
if mouseinfo.x >= position + adv + _self.x + _self.offset_x + 4 {
_self.text_cursor = i + 1;
break;
} else if mouseinfo.x < position + adv + _self.x + _self.offset_x + 4{
_self.text_cursor = i;
break;
}
}
position += adv;
}
}
if self.active == false {
if in_rect(mouseinfo.x, mouseinfo.y,
[self.x+self.offset_x+4, self.y + self.offset_y + 4, self.max_render_length , self.text_size as i32]) &&
mouseinfo.lbutton == ButtonStatus::Down{
self.active = true;
place_cursor(self, mouseinfo);
}
return;
}
if self.active {
if in_rect(mouseinfo.x, mouseinfo.y,
[self.x+self.offset_x+4, self.y+self.offset_y + 4, self.max_render_length , self.text_size as i32]) == false &&
mouseinfo.lbutton == ButtonStatus::Down{
self.active = false;
return;
} else { //IS THIS A GOOD ELSE STATEMENT I DON'T THINK THIS MAKES SENSE
if in_rect(mouseinfo.x, mouseinfo.y,
[self.x+self.offset_x+4, self.y+self.offset_y + 4, self.max_render_length , self.text_size as i32]) &&
mouseinfo.lbutton == ButtonStatus::Down
{//Look for where to place cursor
place_cursor(self, mouseinfo);
}
for i in 0..keyboardinfo.key.len(){
if keyboardinfo.key[i] == KeyboardEnum::Enter &&
keyboardinfo.status[i] == ButtonStatus::Down {
self.active = false;
return;
}
}
}
}
let mut delete_activated = false;
for i in 0..keyboardinfo.key.len(){
if keyboardinfo.status[i] == ButtonStatus::Down{
if keyboardinfo.key[i] == KeyboardEnum::Leftarrow{
if self.text_cursor > 0 {
self.text_cursor -= 1;
}
}
if keyboardinfo.key[i] == KeyboardEnum::Rightarrow{
if (self.text_cursor as usize) < self.text_buffer.len() {
self.text_cursor += 1;
}
}
if keyboardinfo.key[i] == KeyboardEnum::Delete{
let _cursor = self.text_cursor;
delete_activated = true;
if self.text_buffer.len() > _cursor {
self.text_buffer.remove(_cursor);
}
}
}
}
for character in &textinfo.character{
let _cursor = self.text_cursor as usize;
//NOTE character with u8 of 8 is the backspace code on windows
let u8_char = *character as u8;
let mut is_backspace = u8_char == 8;
if cfg!(target_os = "macos") {
is_backspace = u8_char == 127;
}
if is_backspace && !delete_activated {
if (self.text_buffer.len() > 0)
&& _cursor > 0 {
self.text_buffer.remove(_cursor-1);
self.text_cursor -= 1;
}
} else if u8_char >= 239 || delete_activated { //This is a delete on keyboard macos
} else {
if self.text_buffer.len() < self.max_char as usize
&& u8_char != 8 {
self.text_buffer.insert(_cursor, *character);
self.text_cursor += 1;
}
}
if self.text_cursor as usize > self.text_buffer.len() {
self.text_cursor = self.text_buffer.len();
}
}
}
pub fn draw(&self, canvas: &mut WindowCanvas, time: f32){
draw_rect(canvas,
[self.x+4, self.y + 4, self.max_render_length , self.text_size as i32],
self.bg_color, true);
//draw_string(canvas, &self.text_buffer, self.x, self.y, self.text_color, self.text_size);
let mut offset = 0;
for (i, it) in self.text_buffer.chars().enumerate(){
if i >= self.max_char as _{
break;
}
offset += draw_char(canvas, it, self.x + offset, self.y, self.text_color, self.text_size);
}
if self.active {
let mut adv = 0;
let mut cursor_color = self.cursor_color;
cursor_color[3] = cursor_color[3] * ( 0.5*(self.omega*time).cos() + 0.7).min(1.0);
for (i, it) in self.text_buffer.chars().enumerate(){
if i == self.text_cursor as usize {
draw_rect(canvas, [self.x+adv+4, self.y+4, 2, self.text_size as i32],
cursor_color, true);
break;
}
adv += get_advance(it, self.text_size);
}
if self.text_buffer.len() == 0 || self.text_cursor == self.text_buffer.len(){
draw_rect(canvas, [self.x+adv+4, self.y+4, 2, self.text_size as i32],
cursor_color, true);
}
}
}
}
fn render_current_wire(bmp: &mut TGBitmap, count: f32){//NOTE ideas for showing current
let a_width = bmp.width as usize;
let a_height = bmp.height as usize;
for j in 0..a_height{
for i in 0..a_width{
let offset = 4*(j*a_width + i);
//TODO we are doing too much computation make cleaner
let color_r = 255 - ((2.0 * PI * i as f32 / a_width as f32 - count).sin().powi(2)*100f32) as u8;
let color_g = 255 - ((2.0 * PI * i as f32 / a_width as f32 - count).sin().powi(2)*255f32) as u8;
let color_b = 255 - ((2.0 * PI * i as f32 / a_width as f32 - count).sin().powi(2)*255f32) as u8;
bmp.rgba[offset + 0] = color_b;
bmp.rgba[offset + 1] = color_g;
bmp.rgba[offset + 2] = color_r;
}
}
}
fn render_grey(bmp: &mut TGBitmap){
let a_width = bmp.width as usize;
let a_height = bmp.height as usize;
let color_r = 155;
let color_g = 155;
let color_b = 155;
for j in 0..a_height{
for i in 0..a_width{
let offset = 4*(j*a_width + i);
bmp.rgba[offset + 0] = color_b;
bmp.rgba[offset + 1] = color_g;
bmp.rgba[offset + 2] = color_r;
}
}
}
fn render_pink(bmp: &mut TGBitmap){
let a_width = bmp.width as usize;
let a_height = bmp.height as usize;
let color_r = 255;
let color_g = 192;
let color_b = 203;
for j in 0..a_height{
for i in 0..a_width{
let offset = 4*(j*a_width + i);
bmp.rgba[offset + 0] = color_b;
bmp.rgba[offset + 1] = color_g;
bmp.rgba[offset + 2] = color_r;
}
}
}
fn render_red(bmp: &mut TGBitmap){
let a_width = bmp.width as usize;
let a_height = bmp.height as usize;
let color_r = 155;
let color_g = 0;
let color_b = 0;
for j in 0..a_height{
for i in 0..a_width{
let offset = 4*(j*a_width + i);
bmp.rgba[offset + 0] = color_b;
bmp.rgba[offset + 1] = color_g;
bmp.rgba[offset + 2] = color_r;
}
}
}
fn render_charge_capacitor(bmp: &mut TGBitmap, charge: f32, capacitance: f32){//NOTE ideas for showing current
//Wire
let a_width = bmp.width as usize;
let a_height = bmp.height as usize;
let x1 = [(0.375*a_width as f32) as usize, (0.45 * a_width as f32) as usize];
let x2 = [(0.575*a_width as f32) as usize, (0.65 * a_width as f32) as usize];
let max = 255f32;
let half_max_u8 = (255f32 * 0.5) as u8;
let x = -4f32 + 6f32 * charge.abs() / capacitance;
let r_color = (max / (1f32+x.exp())) as u8;
let mut color_r = 255;
let mut color_g = r_color;
let mut color_b = r_color;
let mut alt_color_r = (r_color as f32 /2f32) as u8 + half_max_u8;
let mut alt_color_g = (r_color as f32 /2f32) as u8 + half_max_u8;
let mut alt_color_b = 255;
if charge < 0f32{
color_r = alt_color_r;
color_g = alt_color_g;
color_b = 255;
alt_color_r = 255;
alt_color_g = r_color;
alt_color_b = r_color;
}
for j in 0..a_height{
for i in x1[0]..x1[1]{
let offset = 4*(j*a_width + i);
bmp.rgba[offset + 0] = color_b;
bmp.rgba[offset + 1] = color_g;
bmp.rgba[offset + 2] = color_r;
}
for i in x2[0]..x2[1]{
let offset = 4*(j*a_width + i);
bmp.rgba[offset + 0] = alt_color_b;
bmp.rgba[offset + 1] = alt_color_g;
bmp.rgba[offset + 2] = alt_color_r;
}
}
}
/// This function sets a matrix which dictates the initial direction a circuit element.
///
/// This function begins by guessing the direction of an element, then begins to correct the guess
/// using the following rules:
/// + for a given column the sum of rows must be zero
/// + for a given row the sum of the absolute value must not be 2.
/// + for a given row the sum minus the negative element value must not be 0.
fn undirected_to_directed_matrix(m : &mut Matrix){
//NOTE
//We guess the direction of each pair.
for i in 0..m.columns{
for j in (0..m.rows).rev(){
if *m.get_element(j, i) == 1f32{
*m.get_element( j, i ) = -1f32;
break;
}
}
}
for j in 0..m.rows{
let mut count = 0f32;
let mut sum = 0f32;
let mut c_index = vec![];
for i in 0..m.columns{
sum += *m.get_element(j, i);
count += (*m.get_element(j, i)).abs();
if *m.get_element(j, i) != 0f32 { c_index.push(i); }
}
if sum.abs() < count { continue; }
//flip other element
let mut change_made = false;
let mut j_index = vec![];
for _j in 0..m.rows{
if _j == j { continue; }
let mut row_interesting = false;
let mut column_of_interest = 0;
for it in c_index.iter(){
if *m.get_element(_j, *it) != 0f32 {
row_interesting = true;
column_of_interest = *it;
}
}
if !row_interesting { continue; }
j_index.push( (_j, column_of_interest) );
count = 0f32;
sum = 0f32;
for _i in 0..m.columns{
sum += *m.get_element(_j, _i);
count += (*m.get_element(_j, _i)).abs();
}
if sum as f32 - (*m.get_element(_j, column_of_interest)) * -1f32 != 0f32
&& count != 2f32{
*m.get_element(_j, column_of_interest) *=-1f32;
*m.get_element(j, column_of_interest) *=-1f32;
change_made = true;
}
}
if !change_made {
*m.get_element(j_index[1].0, j_index[1].1) *=-1f32;
*m.get_element(j, j_index[1].1) *=-1f32;
}
}
}
#[test]
fn test_undir_to_directed(){
let mut m = Matrix{
arr: vec![
1f32, 1f32, 0f32, 0f32,
1f32, 0f32, 0f32, 1f32,
0f32, 1f32, 1f32, 0f32,
0f32, 0f32, 1f32, 1f32,
],
rows: 4,
columns: 4,};
undirected_to_directed_matrix(&mut m);
let mut _m = Matrix{
arr: vec![
1f32,-1f32, 0f32, 0f32,
-1f32, 0f32, 0f32, 1f32,
0f32, 1f32,-1f32, 0f32,
0f32, 0f32, 1f32,-1f32,
],
rows: 4,
columns: 4,};
assert_eq!(m, _m);
let mut m = Matrix{
arr: vec![
1f32, 0f32, 0f32, 0f32, 0f32, 0f32, 0f32, 0f32, 1f32,
1f32, 1f32, 0f32, 1f32, 0f32, 0f32, 0f32, 0f32, 0f32,
0f32, 1f32, 1f32, 0f32, 0f32, 0f32, 0f32, 0f32, 0f32,
0f32, 0f32, 1f32, 0f32, 1f32, 0f32, 0f32, 0f32, 0f32,
0f32, 0f32, 0f32, 1f32, 1f32, 1f32, 0f32, 0f32, 0f32,
0f32, 0f32, 0f32, 0f32, 0f32, 1f32, 1f32, 0f32, 0f32,
0f32, 0f32, 0f32, 0f32, 0f32, 0f32, 1f32, 1f32, 0f32,
0f32, 0f32, 0f32, 0f32, 0f32, 0f32, 0f32, 1f32, 1f32,
],
rows: 8,
columns: 9,};
undirected_to_directed_matrix(&mut m);
let _m = Matrix{
arr: vec![
1f32, 0f32, 0f32, 0f32, 0f32, 0f32, 0f32, 0f32,-1f32,
-1f32, 1f32, 0f32, 1f32, 0f32, 0f32, 0f32, 0f32, 0f32,
0f32,-1f32, 1f32, 0f32, 0f32, 0f32, 0f32, 0f32, 0f32,
0f32, 0f32,-1f32, 0f32, 1f32, 0f32, 0f32, 0f32, 0f32,
0f32, 0f32, 0f32,-1f32,-1f32, 1f32, 0f32, 0f32, 0f32,
0f32, 0f32, 0f32, 0f32, 0f32,-1f32, 1f32, 0f32, 0f32,
0f32, 0f32, 0f32, 0f32, 0f32, 0f32,-1f32, 1f32, 0f32,
0f32, 0f32, 0f32, 0f32, 0f32, 0f32, 0f32,-1f32, 1f32,
],
rows: 8,
columns: 9,};
assert_eq!(m, _m);
let mut m = Matrix{
arr: vec![
1f32, 0f32, 0f32, 0f32, 0f32, 0f32, 0f32, 1f32, 0f32,
1f32, 1f32, 0f32, 1f32, 0f32, 0f32, 0f32, 0f32, 0f32,
0f32, 1f32, 1f32, 0f32, 0f32, 0f32, 0f32, 0f32, 0f32,
0f32, 0f32, 1f32, 0f32, 0f32, 0f32, 0f32, 0f32, 1f32,
0f32, 0f32, 0f32, 1f32, 1f32, 0f32, 0f32, 0f32, 1f32,
0f32, 0f32, 0f32, 0f32, 1f32, 1f32, 0f32, 0f32, 0f32,
0f32, 0f32, 0f32, 0f32, 0f32, 1f32, 1f32, 0f32, 0f32,
0f32, 0f32, 0f32, 0f32, 0f32, 0f32, 1f32, 1f32, 0f32,
],
rows: 8,
columns: 9,};
undirected_to_directed_matrix(&mut m);
let _m = Matrix{
arr: vec![
1f32, 0f32, 0f32, 0f32, 0f32, 0f32, 0f32,-1f32, 0f32,
-1f32, 1f32, 0f32, 1f32, 0f32, 0f32, 0f32, 0f32, 0f32,
0f32,-1f32, 1f32, 0f32, 0f32, 0f32, 0f32, 0f32, 0f32,
0f32, 0f32,-1f32, 0f32, 0f32, 0f32, 0f32, 0f32, 1f32,
0f32, 0f32, 0f32,-1f32, 1f32, 0f32, 0f32, 0f32,-1f32,
0f32, 0f32, 0f32, 0f32,-1f32, 1f32, 0f32, 0f32, 0f32,
0f32, 0f32, 0f32, 0f32, 0f32,-1f32, 1f32, 0f32, 0f32,
0f32, 0f32, 0f32, 0f32, 0f32, 0f32,-1f32, 1f32, 0f32,
],
rows: 8,
columns: 9,};
assert_eq!(m, _m);
}
const _FIXED_CHAR_BUFFER_SIZE : usize = 15;
/// TinyString is a fixed size stack allocated string struct.
///
#[derive(Clone, Copy)]
pub struct TinyString{
//NOTE
//currently struct vars are public for debugging purposed. They should not be public.
//NOTE
//This should prob be a general tool
pub cursor: usize,
pub buffer: [u8; _FIXED_CHAR_BUFFER_SIZE],
}
impl TinyString{
pub const fn new()->TinyString{
TinyString{
buffer: [std::u8::MAX; _FIXED_CHAR_BUFFER_SIZE],
cursor: 0,
}
}
pub fn len(&self)->usize{
self.cursor
}
//TODO
//check meaning of clone and copy in rust
pub fn copystr(&mut self, s: &str){
let bytes = s.as_bytes();
self.cursor = 0;
for i in 0.. bytes.len(){
if i >= _FIXED_CHAR_BUFFER_SIZE { break; }
self.buffer[i] = bytes[i];
self.cursor += 1;
}
}
#[allow(unused)]
pub fn fromstr(string: &str)->TinyString{
let mut ts = TinyString::new();
ts.copystr(string);
return ts;
}
//TODO
//check meaning of clone and copy in rust
#[allow(unused)]
pub fn copy(&mut self, s: &TinyString){
for i in 0..s.len(){
//TODO
//slow
self.buffer[i] = s.buffer[i];
}
self.cursor = s.len();
}
#[allow(unused)]
pub fn is_samestr(&self, s: &str)->bool{
let bytes = s.as_bytes();
if self.len() != bytes.len(){ return false; }
for i in 0..self.len(){
if self.buffer[i] != bytes[i]{ return false; }
}
return true;
}
pub fn is_same(&self, s: &TinyString)->bool{
if self.len() != s.len(){ return false; }
for i in 0..self.len(){
if self.buffer[i] != s.buffer[i]{ return false; }
}
return true;
}
}
impl std::cmp::PartialEq for TinyString{
fn eq(&self, other: &Self)->bool{
self.is_same(other)
}
}
impl AsRef<str> for TinyString{
fn as_ref(&self)->&str{unsafe{
//TODO
//Some times this does not work wonder if it is a save fail?
//should we breaking change things to char? I don't remeber why we didn't choose char in the first place.
match std::str::from_utf8(std::slice::from_raw_parts(self.buffer.as_ptr() , self.cursor)){
Ok(s)=> {s},
Err(s)=>{
println!("{:?}", s);
"?Error?"
}
}
}}
}
impl core::fmt::Display for TinyString{
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>)->core::fmt::Result{
core::fmt::Display::fmt(self.as_ref() ,f)
}
}
impl core::fmt::Debug for TinyString{
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>)->core::fmt::Result{
core::fmt::Debug::fmt(self.as_ref() ,f)
}
}
/// The function pulls a random number from a Gaussian distribution with a standard devivation as
/// given by the user.
fn sample_normal(std: f32)->f32{
let one_over_sqrt_2 = 0.70710678118;
let dst = Normal::new(0.0, std*one_over_sqrt_2).unwrap();
return dst.sample(&mut thread_rng());
}
#[inline]
fn edgefunction_i32(p: &[i32; 2], v0: &[i32; 2], v1: &[i32; 2])->f32{
let _p = [p[0] as f32, p[1] as f32];
let _v0 = [v0[0] as f32, v0[1] as f32];
let _v1 = [v1[0] as f32, v1[1] as f32];
edgefunction(&_p, &_v0, &_v1)
}
#[inline]
fn edgefunction(p: &[f32; 2], v0: &[f32; 2], v1: &[f32; 2])->f32{
let x0 = [p[0] - v0[0], p[1] - v0[1]];
let x1 = [v1[0] - v0[0], v1[1] - v0[1]];
return calc2d_cross_product(x0, x1);
}
#[inline]
fn calc2d_cross_product(x0: [f32; 2], x1: [f32; 2])->f32{
let cross_product = x0[0] * x1[1] - x0[1] * x1[0];
return cross_product;
}
|
//! Functions for splitting sequences into fixed-width moving windows (kmers)
//! and utilities for dealing with these kmers.
/// Returns true if the base is a unambiguous nucleic acid base (e.g. ACGT) and
/// false otherwise.
fn is_good_base(chr: u8) -> bool {
matches!(chr as char, 'a' | 'c' | 'g' | 't' | 'A' | 'C' | 'G' | 'T')
}
/// Generic moving window iterator over sequences to return k-mers
///
/// Iterator returns slices to the original data.
pub struct Kmers<'a> {
k: u8,
start_pos: usize,
buffer: &'a [u8],
}
impl<'a> Kmers<'a> {
/// Creates a new kmer-izer for a nucleotide/amino acid sequence.
pub fn new(buffer: &'a [u8], k: u8) -> Self {
Kmers {
k,
start_pos: 0,
buffer,
}
}
}
impl<'a> Iterator for Kmers<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
if self.start_pos + self.k as usize > self.buffer.len() {
return None;
}
let pos = self.start_pos;
self.start_pos += 1;
Some(&self.buffer[pos..pos + self.k as usize])
}
}
/// A kmer-izer for a nucleotide acid sequences to return canonical kmers.
///
/// Iterator returns the position of the kmer, a slice to the original data,
/// and an boolean indicating if the kmer returned is the original or the
/// reverse complement.
pub struct CanonicalKmers<'a> {
k: u8,
start_pos: usize,
buffer: &'a [u8],
rc_buffer: &'a [u8],
}
impl<'a> CanonicalKmers<'a> {
/// Creates a new iterator.
///
/// It's generally more useful to use this directly from a sequences (e.g.
/// `seq.canonical_kmers`. Requires a reference to the reverse complement
/// of the sequence it's created on, e.g.
/// ```
/// use needletail::Sequence;
/// use needletail::kmer::CanonicalKmers;
///
/// let seq = b"ACGT";
/// let rc = seq.reverse_complement();
/// let c_iter = CanonicalKmers::new(seq, &rc, 3);
/// for (pos, kmer, canonical) in c_iter {
/// // process data in here
/// }
///
/// ```
pub fn new(buffer: &'a [u8], rc_buffer: &'a [u8], k: u8) -> Self {
let mut nucl_kmers = CanonicalKmers {
k,
start_pos: 0,
buffer,
rc_buffer,
};
nucl_kmers.update_position(true);
nucl_kmers
}
fn update_position(&mut self, initial: bool) -> bool {
// check if we have enough "physical" space for one more kmer
if self.start_pos + self.k as usize > self.buffer.len() {
return false;
}
let (mut kmer_len, stop_len) = if initial {
(0, (self.k - 1) as usize)
} else {
((self.k - 1) as usize, self.k as usize)
};
while kmer_len < stop_len {
if is_good_base(self.buffer[self.start_pos + kmer_len]) {
kmer_len += 1;
} else {
kmer_len = 0;
self.start_pos += kmer_len + 1;
if self.start_pos + self.k as usize > self.buffer.len() {
return false;
}
}
}
true
}
}
impl<'a> Iterator for CanonicalKmers<'a> {
type Item = (usize, &'a [u8], bool);
fn next(&mut self) -> Option<(usize, &'a [u8], bool)> {
if !self.update_position(false) {
return None;
}
let pos = self.start_pos;
self.start_pos += 1;
let result = &self.buffer[pos..pos + self.k as usize];
let rc_buffer = self.rc_buffer;
let rc_result = &rc_buffer[rc_buffer.len() - pos - self.k as usize..rc_buffer.len() - pos];
if result < rc_result {
Some((pos, result, false))
} else {
Some((pos, rc_result, true))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sequence::Sequence;
#[test]
fn can_kmerize() {
let k_iter = Kmers::new(b"AGCT", 1);
// test general function
for (i, k) in k_iter.enumerate() {
match i {
0 => assert_eq!(k, b"A"),
1 => assert_eq!(k, b"G"),
2 => assert_eq!(k, b"C"),
3 => assert_eq!(k, b"T"),
_ => unreachable!("Too many kmers"),
}
}
// test that we handle length 2 (and don't drop Ns)
let k_iter = Kmers::new(b"AGNCT", 2);
for (i, k) in k_iter.enumerate() {
match i {
0 => assert_eq!(k, b"AG"),
1 => assert_eq!(k, b"GN"),
2 => assert_eq!(k, b"NC"),
3 => assert_eq!(k, b"CT"),
_ => unreachable!("Too many kmers"),
}
}
// test that the minimum length works
let k_iter = Kmers::new(b"AC", 2);
for k in k_iter {
assert_eq!(k, &b"AC"[..]);
}
}
#[test]
fn can_canonicalize() {
// test general function
let seq = b"AGCT";
let rc_seq = seq.reverse_complement();
let c_iter = CanonicalKmers::new(seq, &rc_seq, 1);
for (i, (_, k, is_c)) in c_iter.enumerate() {
match i {
0 => {
assert_eq!(k, b"A");
assert_eq!(is_c, false);
}
1 => {
assert_eq!(k, b"C");
assert_eq!(is_c, true);
}
2 => {
assert_eq!(k, b"C");
assert_eq!(is_c, false);
}
3 => {
assert_eq!(k, b"A");
assert_eq!(is_c, true);
}
_ => unreachable!("Too many kmers"),
}
}
let seq = b"AGCTA";
let rc_seq = seq.reverse_complement();
let c_iter = CanonicalKmers::new(seq, &rc_seq, 2);
for (i, (_, k, _)) in c_iter.enumerate() {
match i {
0 => assert_eq!(k, b"AG"),
1 => assert_eq!(k, b"GC"),
2 => assert_eq!(k, b"AG"),
3 => assert_eq!(k, b"TA"),
_ => unreachable!("Too many kmers"),
}
}
let seq = b"AGNTA";
let rc_seq = seq.reverse_complement();
let c_iter = CanonicalKmers::new(seq, &rc_seq, 2);
for (i, (ix, k, _)) in c_iter.enumerate() {
match i {
0 => {
assert_eq!(ix, 0);
assert_eq!(k, b"AG");
}
1 => {
assert_eq!(ix, 3);
assert_eq!(k, b"TA");
}
_ => unreachable!("Too many kmers"),
}
}
}
}
|
#[macro_use] extern crate lazy_static;
use std::env;
mod common;
mod day1;
mod day2;
mod day3;
mod day4;
mod day5;
mod day6;
mod day7;
mod day8;
mod day9;
mod day10;
mod day11;
mod day12;
mod day13;
mod day14;
mod day15;
mod day16;
mod day17;
mod day18;
mod day19;
mod day20;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() == 2 {
let day: &str = args[1].as_str();
match day {
"day1" => day1::run(),
"day2" => day2::run(),
"day3" => day3::run(),
"day4" => day4::run(),
"day5" => day5::run(),
"day6" => day6::run(),
"day7" => day7::run(),
"day8" => day8::run(),
"day9" => day9::run(),
"day10" => day10::run(),
"day11" => day11::run(),
"day12" => day12::run(),
"day13" => day13::run(),
"day14" => day14::run(),
"day15" => day15::run(),
"day16" => day16::run(),
"day17" => day17::run(),
"day18" => day18::run(),
"day19" => day19::run(),
"day20" => day20::run(),
_ => eprintln!("{} is not implemented", day)
}
} else {
eprintln!("Please specify the dayN to be run");
}
}
|
use chrono::{DateTime, Utc};
// Returns a Utc DateTime one billion seconds after start.
pub fn after(start: DateTime<Utc>) -> DateTime<Utc> {
let one_billion = 1_000_000_000;
let one_billion_seconds = chrono::Duration::seconds(one_billion);
return start + one_billion_seconds;
}
|
#[cfg(feature="ncollide2d")] use ncollide2d::{
bounding_volume::AABB,
shape::Cuboid
};
use crate::geom::{about_equal, Vector};
use std::cmp::{Eq, PartialEq};
#[derive(Clone, Copy, Default, Debug, Deserialize, Serialize)]
///A rectangle with a top-left position and a size
pub struct Rectangle {
///The top-left coordinate of the rectangle
pub pos: Vector,
///The width and height of the rectangle
pub size: Vector
}
impl Rectangle {
///Create a rectangle from a top-left vector and a size vector
pub fn new(pos: impl Into<Vector>, size: impl Into<Vector>) -> Rectangle {
Rectangle {
pos: pos.into(),
size: size.into()
}
}
///Create a rectangle at the origin with the given size
pub fn new_sized(size: impl Into<Vector>) -> Rectangle {
Rectangle {
pos: Vector::ZERO,
size: size.into()
}
}
#[cfg(feature="ncollide2d")]
///Create a rectangle with a given center and Cuboid from ncollide
pub fn from_cuboid(center: impl Into<Vector>, cuboid: &Cuboid<f32>) -> Rectangle {
let half_size = cuboid.half_extents().clone().into();
Rectangle::new(center.into() - half_size, half_size * 2)
}
///Convert this rect into an ncollide Cuboid2
#[cfg(feature="ncollide2d")]
pub fn into_cuboid(self) -> Cuboid<f32> {
Cuboid::new((self.size() / 2).into_vector())
}
///Convert this rect into an ncollide AABB2
#[cfg(feature="ncollide2d")]
pub fn into_aabb(self) -> AABB<f32> {
let min = self.top_left().into_point();
let max = (self.top_left() + self.size()).into_point();
AABB::new(min, max)
}
///Get the top left coordinate of the Rectangle
pub fn top_left(&self) -> Vector {
self.pos
}
///Get the x-coordinate of the Rectangle
///(The origin of a Rectangle is at the top left)
pub fn x(&self) -> f32 {
self.pos.x
}
///Get the y-coordinate of the Rectangle
///(The origin of a Rectangle is at the top left)
pub fn y(&self) -> f32 {
self.pos.y
}
///Get the size of the Rectangle
pub fn size(&self) -> Vector {
self.size
}
///Get the height of the Rectangle
pub fn height(&self) -> f32 {
self.size.y
}
///Get the width of the Rectangle
pub fn width(&self) -> f32 {
self.size.x
}
}
impl PartialEq for Rectangle {
fn eq(&self, other: &Rectangle) -> bool {
about_equal(self.x(), other.pos.x) && about_equal(self.y(), other.pos.y) && about_equal(self.width(), other.size.x)
&& about_equal(self.height(), other.size.y)
}
}
impl Eq for Rectangle {}
#[cfg(feature="ncollide2d")]
impl From<AABB<f32>> for Rectangle {
fn from(other: AABB<f32>) -> Rectangle {
let min: Vector = Clone::clone(other.mins()).into();
let max: Vector = Clone::clone(other.maxs()).into();
Rectangle::new(min, max - min)
}
}
#[cfg(test)]
mod tests {
use crate::geom::*;
#[test]
fn overlap() {
let a = &Rectangle::new_sized((32, 32));
let b = &Rectangle::new((16, 16), (32, 32));
let c = &Rectangle::new((50, 50), (5, 5));
assert!(a.overlaps(b));
assert!(!a.overlaps(c));
}
#[test]
fn contains() {
let rect = Rectangle::new_sized((32, 32));
let vec1 = Vector::new(5, 5);
let vec2 = Vector::new(33, 1);
assert!(rect.contains(vec1));
assert!(!rect.contains(vec2));
}
#[test]
fn constraint() {
let constraint = &Rectangle::new_sized((10, 10));
let a = Rectangle::new((-1, 3), (5, 5));
let b = Rectangle::new((4, 4), (8, 3));
let a = a.constrain(constraint);
assert_eq!(a.top_left(), Vector::new(0, 3));
let b = b.constrain(constraint);
assert_eq!(b.top_left(), Vector::new(2, 4));
}
#[test]
fn translate() {
let a = Rectangle::new((10, 10), (5, 5));
let v = Vector::new(1, -1);
let translated = a.translate(v);
assert_eq!(a.top_left() + v, translated.top_left());
}
}
|
extern crate serial_unix;
extern crate libc;
use std::io;
use std::path::Path;
use std::io::prelude::*;
use std::os::unix::prelude::*;
fn main() {
let mut port = serial_unix::TTYPort::open(Path::new("/dev/ttyUSB0")).unwrap();
let mut fds = vec![libc::pollfd {
fd: port.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
}];
loop {
let retval = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, 100) };
if retval < 0 {
panic!("{:?}", io::Error::last_os_error());
}
if retval > 0 && fds[0].revents & libc::POLLIN != 0 {
let mut buffer = Vec::<u8>::new();
port.read_to_end(&mut buffer).unwrap();
println!("{:?}", buffer);
}
}
}
|
// revisions: base nll
// ignore-compare-mode-nll
//[nll] compile-flags: -Z borrowck=mir
enum Ast<'a> {
Num(usize),
Add(&'a Ast<'a>, &'a Ast<'a>)
}
fn mk_add_bad1<'a,'b>(x: &'a Ast<'a>, y: &'b Ast<'b>) -> Ast<'a> {
Ast::Add(x, y)
//[base]~^ ERROR lifetime mismatch [E0623]
//[nll]~^^ ERROR lifetime may not live long enough
}
fn main() {
}
|
use serde::{Serialize, Deserialize};
use std::convert::From;
use domain_patterns::models::{Entity, AggregateRoot};
use crate::survey::{Choice, Survey, Question};
#[derive(Serialize, Deserialize)]
pub struct SurveyDTOs {
pub surveys: Vec<ListViewSurveyDTO>
}
#[derive(Serialize, Deserialize)]
pub struct ListViewSurveyDTO {
pub id: String,
pub author: String,
pub title: String,
pub category: String,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SurveyDTO {
pub id: String,
pub version: u64,
pub author: String,
pub title: String,
pub description: String,
pub created_on: i64,
pub category: String,
pub questions: Vec<QuestionDTO>,
}
#[derive(Serialize, Deserialize)]
pub struct QuestionDTO {
pub id: String,
#[serde(rename = "type")]
pub kind: String,
pub title: String,
pub choices: Vec<ChoiceDTO>
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChoiceDTO {
pub id: String,
pub content: Option<String>,
pub content_type: String,
pub title: String,
}
impl From<Survey> for SurveyDTO {
fn from(s: Survey) -> Self {
let questions: Vec<QuestionDTO> = s.questions()
.into_iter()
.map(|q| QuestionDTO::from(q))
.collect();
SurveyDTO {
id: s.id(),
version: s.version(),
author: s.author().to_string(),
title: s.title().to_string(),
description: s.description().to_string(),
created_on: s.created_on().clone(),
category: s.category().to_string(),
questions,
}
}
}
impl From<&Question> for QuestionDTO {
fn from(q: &Question) -> Self {
let choices = q.choices()
.into_iter()
.map(|c| ChoiceDTO::from(c))
.collect();
QuestionDTO {
id: q.id().to_string(),
kind: q.kind().to_string(),
title: q.title().to_string(),
choices,
}
}
}
impl From<&Choice> for ChoiceDTO {
fn from(choice: &Choice) -> Self {
let content = if let Some(c) = choice.content() {
Some(c.to_string())
} else {
None
};
ChoiceDTO {
id: choice.id().to_string(),
content,
content_type: choice.content_type().to_string(),
title: choice.title().to_string(),
}
}
}
// Same but from reference type, so needs clone.
impl From<&Survey> for SurveyDTO {
fn from(s: &Survey) -> Self {
let questions: Vec<QuestionDTO> = s.questions()
.into_iter()
.map(|q| QuestionDTO::from(q))
.collect();
SurveyDTO {
id: s.id().to_string(),
version: s.version(),
author: s.author().to_string(),
title: s.title().to_string(),
description: s.description().to_string(),
created_on: s.created_on().clone(),
category: s.category().to_string(),
questions,
}
}
}
impl SurveyDTOs {
pub fn into_bounded(mut self, lower_bound: usize, upper_bound: usize) -> Option<SurveyDTOs> {
let total = self.surveys.len();
if lower_bound > total - 1 {
None
} else {
let start = lower_bound;
let end = if upper_bound > total {
total
} else {
upper_bound
};
self.surveys = self.surveys.drain(start..end).collect();
Some(
self
)
}
}
} |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {fidl_fuchsia_io::DirectoryMarker, fidl_fuchsia_sys2 as fsys};
/// Creates a child in the specified `Realm`.
///
/// # Parameters
/// - `child_name`: The name of the child to be added.
/// - `child_url`: The component URL of the child to add.
/// - `collection_name`: The name of the collection to which the child will be added.
/// - `realm`: The `Realm` to which the child will be added.
///
/// # Returns
/// `Ok` if the child is created successfully.
pub async fn create_child_component(
child_name: &str,
child_url: &str,
collection_name: &str,
realm: &fsys::RealmProxy,
) -> Result<(), fsys::Error> {
let mut collection_ref = fsys::CollectionRef { name: collection_name.to_string() };
let child_decl = fsys::ChildDecl {
name: Some(child_name.to_string()),
url: Some(child_url.to_string()),
startup: Some(fsys::StartupMode::Lazy), // Dynamic children can only be started lazily.
};
realm
.create_child(&mut collection_ref, child_decl)
.await
.map_err(|_| fsys::Error::Internal)??;
Ok(())
}
/// Binds a child in the specified `Realm`. This call is expected to follow a matching call to
/// `create_child`.
///
/// # Parameters
/// - `child_name`: The name of the child to bind.
/// - `collection_name`: The name of collection in which the child was created.
/// - `realm`: The `Realm` the child will bound in.
///
/// # Returns
/// `Ok` if the child was bound successfully.
pub async fn bind_child_component(
child_name: &str,
collection_name: &str,
realm: &fsys::RealmProxy,
) -> Result<(), fsys::Error> {
let mut child_ref = fsys::ChildRef {
name: child_name.to_string(),
collection: Some(collection_name.to_string()),
};
let (_, server_end) =
fidl::endpoints::create_proxy::<DirectoryMarker>().map_err(|_| fsys::Error::Internal)?;
realm.bind_child(&mut child_ref, server_end).await.map_err(|_| fsys::Error::Internal)??;
Ok(())
}
/// Destroys a child in the specified `Realm`. This call is expects a matching call to have been
/// made to `create_child`.
///
/// # Parameters
/// - `child_name`: The name of the child to destroy.
/// - `collection_name`: The name of collection in which the child was created.
/// - `realm`: The `Realm` the child will bound in.
///
/// # Errors
/// Returns an error if the child was not destroyed in the realm.
pub async fn destroy_child_component(
child_name: &str,
collection_name: &str,
realm: &fsys::RealmProxy,
) -> Result<(), fsys::Error> {
let mut child_ref = fsys::ChildRef {
name: child_name.to_string(),
collection: Some(collection_name.to_string()),
};
realm.destroy_child(&mut child_ref).await.map_err(|_| fsys::Error::Internal)??;
Ok(())
}
#[cfg(test)]
mod tests {
use {
super::{bind_child_component, create_child_component, destroy_child_component},
fidl::endpoints::create_proxy_and_stream,
fidl_fuchsia_sys2 as fsys, fuchsia_async as fasync,
futures::prelude::*,
};
/// Spawns a local `fidl_fuchsia_sys2::Realm` server, and returns a proxy to the spawned server.
/// The provided `request_handler` is notified when an incoming request is received.
///
/// # Parameters
/// - `request_handler`: A function which is called with incoming requests to the spawned
/// `Realm` server.
/// # Returns
/// A `RealmProxy` to the spawned server.
fn spawn_realm_server<F: 'static>(request_handler: F) -> fsys::RealmProxy
where
F: Fn(fsys::RealmRequest) + Send,
{
let (realm_proxy, mut realm_server) = create_proxy_and_stream::<fsys::RealmMarker>()
.expect("Failed to create realm proxy and server.");
fasync::spawn(async move {
while let Some(realm_request) = realm_server.try_next().await.unwrap() {
request_handler(realm_request);
}
});
realm_proxy
}
/// Tests that creating a child results in the appropriate call to the `RealmProxy`.
#[fasync::run_singlethreaded(test)]
async fn create_child_parameters() {
let child_name = "test_child";
let child_url = "test_url";
let child_collection = "test_collection";
let realm_proxy = spawn_realm_server(move |realm_request| match realm_request {
fsys::RealmRequest::CreateChild { collection, decl, responder } => {
assert_eq!(decl.name.unwrap(), child_name);
assert_eq!(decl.url.unwrap(), child_url);
assert_eq!(&collection.name, child_collection);
let _ = responder.send(&mut Ok(()));
}
_ => {
assert!(false);
}
});
assert!(create_child_component(child_name, child_url, child_collection, &realm_proxy)
.await
.is_ok());
}
/// Tests that a success received when creating a child results in an appropriate result from
/// `create_child`.
#[fasync::run_singlethreaded(test)]
async fn create_child_success() {
let realm_proxy = spawn_realm_server(move |realm_request| match realm_request {
fsys::RealmRequest::CreateChild { collection: _, decl: _, responder } => {
let _ = responder.send(&mut Ok(()));
}
_ => {
assert!(false);
}
});
assert!(create_child_component("", "", "", &realm_proxy).await.is_ok());
}
/// Tests that an error received when creating a child results in an appropriate error from
/// `create_child`.
#[fasync::run_singlethreaded(test)]
async fn create_child_error() {
let realm_proxy = spawn_realm_server(move |realm_request| match realm_request {
fsys::RealmRequest::CreateChild { collection: _, decl: _, responder } => {
let _ = responder.send(&mut Err(fsys::Error::Internal));
}
_ => {
assert!(false);
}
});
assert!(create_child_component("", "", "", &realm_proxy).await.is_err());
}
/// Tests that `bind_child` results in the appropriate call to `RealmProxy`.
#[fasync::run_singlethreaded(test)]
async fn bind_child_parameters() {
let child_name = "test_child";
let child_collection = "test_collection";
let realm_proxy = spawn_realm_server(move |realm_request| match realm_request {
fsys::RealmRequest::BindChild { child, exposed_dir: _, responder } => {
assert_eq!(child.name, child_name);
assert_eq!(child.collection, Some(child_collection.to_string()));
let _ = responder.send(&mut Ok(()));
}
_ => {
assert!(false);
}
});
assert!(bind_child_component(child_name, child_collection, &realm_proxy).await.is_ok());
}
/// Tests that a success received when binding a child results in an appropriate result from
/// `bind_child`.
#[fasync::run_singlethreaded(test)]
async fn bind_child_success() {
let realm_proxy = spawn_realm_server(move |realm_request| match realm_request {
fsys::RealmRequest::BindChild { child: _, exposed_dir: _, responder } => {
let _ = responder.send(&mut Ok(()));
}
_ => {
assert!(false);
}
});
assert!(bind_child_component("", "", &realm_proxy).await.is_ok());
}
/// Tests that an error received when binding a child results in an appropriate error from
/// `bind_child`.
#[fasync::run_singlethreaded(test)]
async fn bind_child_error() {
let realm_proxy = spawn_realm_server(move |realm_request| match realm_request {
fsys::RealmRequest::BindChild { child: _, exposed_dir: _, responder } => {
let _ = responder.send(&mut Err(fsys::Error::Internal));
}
_ => {
assert!(false);
}
});
assert!(bind_child_component("", "", &realm_proxy).await.is_err());
}
/// Tests that `destroy_child` results in the appropriate call to `RealmProxy`.
#[fasync::run_singlethreaded(test)]
async fn destroy_child_parameters() {
let child_name = "test_child";
let child_collection = "test_collection";
let realm_proxy = spawn_realm_server(move |realm_request| match realm_request {
fsys::RealmRequest::DestroyChild { child, responder } => {
assert_eq!(child.name, child_name);
assert_eq!(child.collection, Some(child_collection.to_string()));
let _ = responder.send(&mut Ok(()));
}
_ => {
assert!(false);
}
});
assert!(destroy_child_component(child_name, child_collection, &realm_proxy).await.is_ok());
}
}
|
use super::task_data::TaskData;
#[derive(Debug)]
pub struct Task {
pub id: i64,
pub data: TaskData,
}
|
use super::*;
use crate::utils::distance_from;
use std::slice;
pub(super) struct RawValIter<T> {
pub(super) start: *const T,
pub(super) end: *const T,
}
unsafe impl<T: Send> Send for RawValIter<T> {}
unsafe impl<T: Sync> Sync for RawValIter<T> {}
impl<T> RawValIter<T> {
/// # Safety
///
/// Must remember to keep the underlying allocation alive.
pub(super) unsafe fn new(start: *mut T, len: usize) -> Self {
RawValIter {
start,
end: if mem::size_of::<T>() == 0 {
(start as usize + len) as *const _
} else if len == 0 {
start
} else {
unsafe { start.add(len) }
},
}
}
fn calculate_length(&self) -> usize {
let elem_size = mem::size_of::<T>();
let distance = self.end as usize - self.start as usize;
let stride_size = if elem_size == 0 { 1 } else { elem_size };
distance / stride_size
}
fn as_slice(&self) -> &[T] {
let len = self.calculate_length();
unsafe { ::std::slice::from_raw_parts(self.start, len) }
}
fn as_mut_slice(&mut self) -> &mut [T] {
let len = self.calculate_length();
unsafe { ::std::slice::from_raw_parts_mut(self.start as *mut T, len) }
}
}
impl<T> Iterator for RawValIter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.start == self.end {
None
} else {
unsafe {
let result = ptr::read(self.start);
self.start = if mem::size_of::<T>() == 0 {
(self.start as usize + 1) as *const _
} else {
self.start.offset(1)
};
Some(result)
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.calculate_length();
(len, Some(len))
}
}
impl<T> DoubleEndedIterator for RawValIter<T> {
fn next_back(&mut self) -> Option<T> {
if self.start == self.end {
None
} else {
unsafe {
self.end = if mem::size_of::<T>() == 0 {
(self.end as usize - 1) as *const _
} else {
self.end.offset(-1)
};
Some(ptr::read(self.end))
}
}
}
}
///////////////////////////////////////////////////
/// An Iterator returned by `<RVec<T> as IntoIterator>::into_iter`,
/// which yields all the elements from the `RVec<T>`,
/// consuming it in the process.
pub struct IntoIter<T> {
pub(super) _buf: ManuallyDrop<RVec<T>>,
pub(super) iter: RawValIter<T>,
}
impl<T> IntoIter<T> {
/// Returns a slice over the remainder of the `Vec<T>` that is being iterated over.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::RVec;
///
/// let mut iter = RVec::from(vec![0, 1, 2, 3]).into_iter();
///
/// assert_eq!(iter.as_slice(), &[0, 1, 2, 3]);
///
/// assert_eq!(iter.next(), Some(0));
/// assert_eq!(iter.as_slice(), &[1, 2, 3]);
///
/// assert_eq!(iter.next_back(), Some(3));
/// assert_eq!(iter.as_slice(), &[1, 2]);
///
/// ```
pub fn as_slice(&self) -> &[T] {
self.iter.as_slice()
}
/// Returns a mutable slice over the remainder of the `Vec<T>` that is being iterated over.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::RVec;
///
/// let mut iter = RVec::from(vec![0, 1, 2, 3]).into_iter();
///
/// assert_eq!(iter.as_mut_slice(), &mut [0, 1, 2, 3]);
///
/// assert_eq!(iter.next(), Some(0));
/// assert_eq!(iter.as_mut_slice(), &mut [1, 2, 3]);
///
/// assert_eq!(iter.next_back(), Some(3));
/// assert_eq!(iter.as_mut_slice(), &mut [1, 2]);
///
/// ```
pub fn as_mut_slice(&mut self) -> &mut [T] {
self.iter.as_mut_slice()
}
}
impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<T> DoubleEndedIterator for IntoIter<T> {
fn next_back(&mut self) -> Option<T> {
self.iter.next_back()
}
}
impl<T> Drop for IntoIter<T> {
fn drop(&mut self) {
self.by_ref().for_each(drop);
self._buf.length = 0;
unsafe { ManuallyDrop::drop(&mut self._buf) }
}
}
///////////////////////////////////////////////////
/// An Iterator returned by `RVec::drain` ,
/// which removes and yields all the elements in a range from the `RVec<T>`.
#[repr(C)]
pub struct Drain<'a, T> {
// pub(super) vec: &'a mut RVec<T>,
pub(super) allocation_start: *mut T,
pub(super) vec_len: &'a mut usize,
pub(super) iter: RawValIter<T>,
pub(super) len: usize,
pub(super) removed_start: *mut T,
pub(super) slice_len: usize,
}
impl<'a, T> Drain<'a, T> {
/// Returns a slice over the remainder of the `Vec<T>` that is being drained.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::RVec;
///
/// let mut list = (0..8).collect::<RVec<u8>>();
/// let mut iter = list.drain(3..7);
///
/// assert_eq!(iter.as_slice(), &[3, 4, 5, 6]);
///
/// assert_eq!(iter.next(), Some(3));
/// assert_eq!(iter.as_slice(), &[4, 5, 6]);
///
/// assert_eq!(iter.next(), Some(4));
/// assert_eq!(iter.as_slice(), &[5, 6]);
///
/// drop(iter);
///
/// assert_eq!(list.as_slice(), &[0, 1, 2, 7]);
///
/// ```
pub fn as_slice(&self) -> &[T] {
self.iter.as_slice()
}
/// Returns a mutable slice over the remainder of the `Vec<T>` that is being drained.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::RVec;
///
/// let mut list = (0..8).collect::<RVec<u8>>();
/// let mut iter = list.drain(3..7);
///
/// assert_eq!(iter.as_mut_slice(), &mut [3, 4, 5, 6]);
///
/// assert_eq!(iter.next(), Some(3));
/// assert_eq!(iter.as_mut_slice(), &mut [4, 5, 6]);
///
/// assert_eq!(iter.next(), Some(4));
/// assert_eq!(iter.as_mut_slice(), &mut [5, 6]);
///
/// drop(iter);
///
/// assert_eq!(list.as_slice(), &[0, 1, 2, 7]);
///
/// ```
pub fn as_mut_slice(&mut self) -> &mut [T] {
self.iter.as_mut_slice()
}
}
impl<'a, T> Iterator for Drain<'a, T> {
type Item = T;
fn next(&mut self) -> Option<T> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
fn next_back(&mut self) -> Option<T> {
self.iter.next_back()
}
}
impl<'a, T> Drop for Drain<'a, T> {
fn drop(&mut self) {
self.iter.by_ref().for_each(drop);
unsafe {
let removed_start = self.removed_start;
let removed_end = self.removed_start.offset(self.slice_len as isize);
let end_index =
distance_from(self.allocation_start, removed_start).unwrap_or(0) + self.slice_len;
ptr::copy(removed_end, removed_start, self.len - end_index);
*self.vec_len = self.len - self.slice_len;
}
}
}
///////////////////////////////////////////////////
// copy of the std library DrainFilter, without the allocator parameter.
// (from rustc 1.50.0-nightly (eb4fc71dc 2020-12-17))
#[derive(Debug)]
pub(crate) struct DrainFilter<'a, T, F>
where
F: FnMut(&mut T) -> bool,
{
// pub(super) vec: &'a mut RVec<T>,
pub(super) allocation_start: *mut T,
pub(super) vec_len: &'a mut usize,
pub(super) idx: usize,
pub(super) del: usize,
pub(super) old_len: usize,
pub(super) pred: F,
pub(super) panic_flag: bool,
}
// copy of the std library DrainFilter impl, without the allocator parameter.
// (from rustc 1.50.0-nightly (eb4fc71dc 2020-12-17))
impl<T, F> Iterator for DrainFilter<'_, T, F>
where
F: FnMut(&mut T) -> bool,
{
type Item = T;
fn next(&mut self) -> Option<T> {
unsafe {
while self.idx < self.old_len {
let i = self.idx;
let v = slice::from_raw_parts_mut(self.allocation_start, self.old_len);
self.panic_flag = true;
let drained = (self.pred)(&mut v[i]);
self.panic_flag = false;
// Update the index *after* the predicate is called. If the index
// is updated prior and the predicate panics, the element at this
// index would be leaked.
self.idx += 1;
if drained {
self.del += 1;
return Some(ptr::read(&v[i]));
} else if self.del > 0 {
let del = self.del;
let src: *const T = &v[i];
let dst: *mut T = &mut v[i - del];
ptr::copy_nonoverlapping(src, dst, 1);
}
}
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.old_len - self.idx))
}
}
// copy of the std library DrainFilter impl, without the allocator parameter.
// (from rustc 1.50.0-nightly (eb4fc71dc 2020-12-17))
impl<T, F> Drop for DrainFilter<'_, T, F>
where
F: FnMut(&mut T) -> bool,
{
fn drop(&mut self) {
struct BackshiftOnDrop<'a, 'b, T, F>
where
F: FnMut(&mut T) -> bool,
{
drain: &'b mut DrainFilter<'a, T, F>,
}
impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
where
F: FnMut(&mut T) -> bool,
{
fn drop(&mut self) {
unsafe {
if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
// This is a pretty messed up state, and there isn't really an
// obviously right thing to do. We don't want to keep trying
// to execute `pred`, so we just backshift all the unprocessed
// elements and tell the vec that they still exist. The backshift
// is required to prevent a double-drop of the last successfully
// drained item prior to a panic in the predicate.
let ptr = self.drain.allocation_start;
let src = ptr.add(self.drain.idx);
let dst = src.sub(self.drain.del);
let tail_len = self.drain.old_len - self.drain.idx;
src.copy_to(dst, tail_len);
}
*self.drain.vec_len = self.drain.old_len - self.drain.del;
}
}
}
let backshift = BackshiftOnDrop { drain: self };
// Attempt to consume any remaining elements if the filter predicate
// has not yet panicked. We'll backshift any remaining elements
// whether we've already panicked or if the consumption here panics.
if !backshift.drain.panic_flag {
backshift.drain.for_each(drop);
}
}
}
|
use super::path2::*;
use crate::snapshot::rand::Rand;
pub type Paths = Vec<Path2>;
pub trait PathsExtension {
fn smooth(&self, tightness: f32, repeats: u8) -> Paths;
fn jitter(&self, rand: &mut Rand, x_jitter: f32, y_jitter: f32) -> Paths;
fn gaussian_jitter(&self, rand: &mut Rand, x_jitter: f32, y_jitter: f32) -> Paths;
}
impl PathsExtension for Paths {
fn smooth(&self, tightness: f32, repeats: u8) -> Paths {
self.iter()
.map(|path| path.smooth(tightness, repeats))
.collect()
}
fn jitter(&self, rand: &mut Rand, x_jitter: f32, y_jitter: f32) -> Paths {
self.iter()
.map(|path| path.jitter(rand, x_jitter, y_jitter))
.collect()
}
fn gaussian_jitter(&self, rand: &mut Rand, x_jitter: f32, y_jitter: f32) -> Paths {
self.iter()
.map(|path| path.gaussian_jitter(rand, x_jitter, y_jitter))
.collect()
}
}
|
#![warn(clippy::many_single_char_names)]
fn bla() {
let a: i32;
let (b, c, d): (i32, i64, i16);
{
{
let cdefg: i32;
let blar: i32;
}
{
let e: i32;
}
{
let e: i32;
let f: i32;
}
match 5 {
1 => println!(),
e => panic!(),
}
match 5 {
1 => println!(),
_ => panic!(),
}
}
}
fn bindings(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32, h: i32) {}
fn bindings2() {
let (a, b, c, d, e, f, g, h): (bool, bool, bool, bool, bool, bool, bool, bool) = unimplemented!();
}
fn shadowing() {
let a = 0i32;
let a = 0i32;
let a = 0i32;
let a = 0i32;
let a = 0i32;
let a = 0i32;
{
let a = 0i32;
}
}
fn patterns() {
enum Z {
A(i32),
B(i32),
C(i32),
D(i32),
E(i32),
F(i32),
}
// These should not trigger a warning, since the pattern bindings are a new scope.
match Z::A(0) {
Z::A(a) => {},
Z::B(b) => {},
Z::C(c) => {},
Z::D(d) => {},
Z::E(e) => {},
Z::F(f) => {},
}
}
#[allow(clippy::many_single_char_names)]
fn issue_3198_allow_works() {
let (a, b, c, d, e) = (0, 0, 0, 0, 0);
}
fn main() {}
|
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use anyhow::*;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::term::prelude::*;
use crate::runtime::registry;
#[native_implemented::function(erlang:unregister/1)]
pub fn result(name: Term) -> exception::Result<Term> {
let atom = term_try_into_atom!(name)?;
if registry::unregister(&atom) {
Ok(true.into())
} else {
Err(anyhow!("name ({}) was not registered", name).into())
}
}
|
//! Throttle partions that receive no commits.
use std::{collections::HashMap, fmt::Display, sync::Arc, time::Duration};
use async_trait::async_trait;
use data_types::{CompactionLevel, ParquetFile, ParquetFileId, ParquetFileParams, PartitionId};
use futures::{StreamExt, TryStreamExt};
use iox_time::{Time, TimeProvider};
use parking_lot::Mutex;
use crate::{
local_scheduler::partition_done_sink::DynError, Commit, CommitError, PartitionDoneSink,
PartitionDoneSinkError, PartitionsSource,
};
/// Ensures that partitions that do not receive any commits are throttled.
///
/// This may happen because our catalog query detects that the partition receives writes but the comapctor already
/// finished all the outstandign work.
///
/// This should be used as a wrapper around the actual [`PartitionsSource`] & [`Commit`] & [`PartitionDoneSink`] and will setup of
/// the following stream layout:
///
/// ```text
/// +--------------------------------------------+
/// | |
/// | (5) |
/// | ^ |
/// | | |
/// | +.................................(4) |
/// | : ^ |
/// | V | V
/// (1)====>(2)====>[concurrent processing]---->(3)---->(6)---->(7)
/// ^ :
/// : :
/// : :
/// +...........................................+
/// ```
///
/// | Step | Name | Type | Description |
/// | ---- | --------------------- | ----------------------------------------------------------------- | ----------- |
/// | 1 | **Actual source** | `inner_source`/`T1`/[`PartitionsSource`], wrapped | This is the actual source. |
/// | 2 | **Throttling source** | [`ThrottlePartitionsSourceWrapper`], wraps `inner_source`/`T1` | Throttles partitions that do not receive any commits |
/// | 3 | **Critical section** | -- | The actual partition processing |
/// | 4 | **Throttle commit** | [`ThrottleCommitWrapper`], wraps `inner_commit`/`T2` | Observes commits. |
/// | 5 | **Actual commit** | `inner_commit`/`T2`/[`Commit`] | The actual commit implementation |
/// | 6 | **Throttle sink** | [`ThrottlePartitionDoneSinkWrapper`], wraps `inner_sink`/`T3` | Observes incoming IDs enables throttled if step (4) did not observe any commits. |
/// | 7 | **Actual sink** | `inner_sink`/`T3`/[`PartitionDoneSink`], wrapped | The actual sink. Directly receives all partitions filtered out at step 2. |
///
/// Note that partitions filtered out by [`ThrottlePartitionsSourceWrapper`] will directly be forwarded to `inner_sink`. No
/// partition is ever lost. This means that `inner_source` and `inner_sink` can perform proper accounting. The
/// concurrency of this bypass can be controlled via `bypass_concurrency`.
///
/// This setup relies on a fact that it does not process duplicate [`PartitionId`]. You may use
/// [`unique_partitions`](super::unique_partitions::unique_partitions) to achieve that.
pub(crate) fn throttle_partition<T1, T2, T3>(
source: T1,
commit: T2,
sink: T3,
time_provider: Arc<dyn TimeProvider>,
throttle_duration: Duration,
bypass_concurrency: usize,
) -> (
ThrottlePartitionsSourceWrapper<T1, T3>,
ThrottleCommitWrapper<T2>,
ThrottlePartitionDoneSinkWrapper<T3>,
)
where
T1: PartitionsSource,
T2: Commit,
T3: PartitionDoneSink,
{
let state = SharedState::default();
let inner_sink = Arc::new(sink);
let source = ThrottlePartitionsSourceWrapper {
inner_source: source,
inner_sink: Arc::clone(&inner_sink),
state: Arc::clone(&state),
time_provider: Arc::clone(&time_provider),
sink_concurrency: bypass_concurrency,
};
let commit = ThrottleCommitWrapper {
inner: commit,
state: Arc::clone(&state),
};
let sink = ThrottlePartitionDoneSinkWrapper {
inner: inner_sink,
state,
time_provider,
throttle_duration,
};
(source, commit, sink)
}
/// Error returned by throttler abstractions.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// Failed uniqueness check.
#[error("Unknown or already done partition: {0}")]
Uniqueness(PartitionId),
}
#[derive(Debug, Default)]
struct State {
// Value is "true" while compaction task is in-flight, and "false" once complete.
//
// Completed compaction tasks are removed from the map each time the source fetch()
// is called.
in_flight: HashMap<PartitionId, bool>,
throttled: HashMap<PartitionId, Time>,
}
type SharedState = Arc<Mutex<State>>;
#[derive(Debug)]
pub(crate) struct ThrottlePartitionsSourceWrapper<T1, T2>
where
T1: PartitionsSource,
T2: PartitionDoneSink,
{
inner_source: T1,
inner_sink: Arc<T2>,
state: SharedState,
time_provider: Arc<dyn TimeProvider>,
sink_concurrency: usize,
}
impl<T1, T2> Display for ThrottlePartitionsSourceWrapper<T1, T2>
where
T1: PartitionsSource,
T2: PartitionDoneSink,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "throttle({}, {})", self.inner_source, self.inner_sink)
}
}
#[async_trait]
impl<T1, T2> PartitionsSource for ThrottlePartitionsSourceWrapper<T1, T2>
where
T1: PartitionsSource,
T2: PartitionDoneSink,
{
async fn fetch(&self) -> Vec<PartitionId> {
let res = self.inner_source.fetch().await;
let (pass, throttle) = {
let mut guard = self.state.lock();
// ensure that in-flight data is non-overlapping
for id in &res {
if guard.in_flight.contains_key(id) {
drop(guard); // avoid poison
panic!("Partition already in-flight: {id}");
}
}
// clean throttled states
let now = self.time_provider.now();
guard.throttled = guard
.throttled
.iter()
.filter(|(_id, until)| **until > now)
.map(|(k, v)| (*k, *v))
.collect();
// filter output
let mut pass = Vec::with_capacity(res.len());
let mut throttle = Vec::with_capacity(res.len());
for id in res {
if guard.throttled.contains_key(&id) {
throttle.push(id);
} else {
pass.push(id);
}
}
// set up in-flight
for id in &pass {
guard.in_flight.insert(*id, false);
}
(pass, throttle)
};
// pass through the removal from tracking, since it failed in this fetch() call
let _ = futures::stream::iter(throttle)
.map(|id| self.inner_sink.record(id, Ok(())))
.buffer_unordered(self.sink_concurrency)
.try_collect::<()>()
.await;
pass
}
}
#[derive(Debug)]
pub(crate) struct ThrottleCommitWrapper<T>
where
T: Commit,
{
inner: T,
state: SharedState,
}
impl<T> Display for ThrottleCommitWrapper<T>
where
T: Commit,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "throttle({})", self.inner)
}
}
#[async_trait]
impl<T> Commit for ThrottleCommitWrapper<T>
where
T: Commit,
{
async fn commit(
&self,
partition_id: PartitionId,
delete: &[ParquetFile],
upgrade: &[ParquetFile],
create: &[ParquetFileParams],
target_level: CompactionLevel,
) -> Result<Vec<ParquetFileId>, CommitError> {
let known = {
let mut guard = self.state.lock();
match guard.in_flight.get_mut(&partition_id) {
Some(val) => {
*val = true;
true
}
None => false,
}
};
// perform check when NOT holding the mutex to not poison it
if !known {
return Err(Error::Uniqueness(partition_id).into());
}
self.inner
.commit(partition_id, delete, upgrade, create, target_level)
.await
}
}
#[derive(Debug)]
pub(crate) struct ThrottlePartitionDoneSinkWrapper<T>
where
T: PartitionDoneSink,
{
inner: Arc<T>,
state: SharedState,
throttle_duration: Duration,
time_provider: Arc<dyn TimeProvider>,
}
impl<T> Display for ThrottlePartitionDoneSinkWrapper<T>
where
T: PartitionDoneSink,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "throttle({})", self.inner)
}
}
#[async_trait]
impl<T> PartitionDoneSink for ThrottlePartitionDoneSinkWrapper<T>
where
T: PartitionDoneSink,
{
async fn record(
&self,
partition: PartitionId,
res: Result<(), DynError>,
) -> Result<(), PartitionDoneSinkError> {
let known = {
let mut guard = self.state.lock();
match guard.in_flight.remove(&partition) {
Some(val) => {
if !val {
guard
.throttled
.insert(partition, self.time_provider.now() + self.throttle_duration);
}
true
}
None => false,
}
};
// perform check when NOT holding the mutex to not poison it
if !known {
return Err(Error::Uniqueness(partition).into());
}
self.inner.record(partition, res).await
}
}
#[cfg(test)]
mod tests {
use assert_matches::assert_matches;
use iox_time::MockProvider;
use crate::{
commit::mock::CommitHistoryEntry, MockCommit, MockPartitionDoneSink, MockPartitionsSource,
};
use super::*;
#[test]
fn test_display() {
let (source, commit, sink) = throttle_partition(
MockPartitionsSource::new(vec![]),
MockCommit::new(),
MockPartitionDoneSink::new(),
Arc::new(MockProvider::new(Time::MIN)),
Duration::from_secs(0),
1,
);
assert_eq!(source.to_string(), "throttle(mock, mock)");
assert_eq!(commit.to_string(), "throttle(mock)");
assert_eq!(sink.to_string(), "throttle(mock)");
}
#[tokio::test]
async fn test_throttle() {
let inner_source = Arc::new(MockPartitionsSource::new(vec![
PartitionId::new(1),
PartitionId::new(2),
PartitionId::new(3),
PartitionId::new(4),
]));
let inner_commit = Arc::new(MockCommit::new());
let inner_sink = Arc::new(MockPartitionDoneSink::new());
let time_provider = Arc::new(MockProvider::new(Time::MIN));
let (source, commit, sink) = throttle_partition(
Arc::clone(&inner_source),
Arc::clone(&inner_commit),
Arc::clone(&inner_sink),
Arc::clone(&time_provider) as _,
Duration::from_secs(1),
1,
);
// ========== Round 1 ==========
// fetch
assert_eq!(
source.fetch().await,
vec![
PartitionId::new(1),
PartitionId::new(2),
PartitionId::new(3),
PartitionId::new(4)
],
);
assert_eq!(inner_sink.results(), HashMap::from([]),);
// commit
commit
.commit(PartitionId::new(1), &[], &[], &[], CompactionLevel::Initial)
.await
.expect("commit failed");
commit
.commit(PartitionId::new(2), &[], &[], &[], CompactionLevel::Initial)
.await
.expect("commit failed");
// record
sink.record(PartitionId::new(1), Ok(()))
.await
.expect("record failed");
sink.record(PartitionId::new(3), Ok(()))
.await
.expect("record failed");
assert_eq!(
inner_sink.results(),
HashMap::from([(PartitionId::new(1), Ok(())), (PartitionId::new(3), Ok(())),]),
);
// ========== Round 2 ==========
// need to remove partition 2 and 4 because they weren't finished yet
inner_source.set(vec![
PartitionId::new(1),
PartitionId::new(3),
PartitionId::new(5),
]);
// fetch
assert_eq!(
source.fetch().await,
vec![
// ID 1: commit in last round => pass
PartitionId::new(1),
// ID 3: no commit in last round => throttled
// ID 5: new => pass
PartitionId::new(5),
],
);
assert_eq!(
inner_sink.results(),
HashMap::from([(PartitionId::new(1), Ok(())), (PartitionId::new(3), Ok(())),]),
);
// ========== Round 3 ==========
// advance time to "unthrottle" ID 3
inner_source.set(vec![PartitionId::new(3)]);
time_provider.inc(Duration::from_secs(1));
// fetch
assert_eq!(source.fetch().await, vec![PartitionId::new(3)],);
// record
// can still finish partition 2 and 4
sink.record(PartitionId::new(2), Err(String::from("foo").into()))
.await
.expect("record failed");
sink.record(PartitionId::new(4), Err(String::from("bar").into()))
.await
.expect("record failed");
assert_eq!(
inner_sink.results(),
HashMap::from([
(PartitionId::new(1), Ok(())),
(PartitionId::new(2), Err(String::from("foo"))),
(PartitionId::new(3), Ok(())),
(PartitionId::new(4), Err(String::from("bar"))),
]),
);
// ========== Round 4 ==========
inner_source.set(vec![PartitionId::new(2), PartitionId::new(4)]);
// fetch
assert_eq!(source.fetch().await, vec![PartitionId::new(2)],);
assert_eq!(
inner_sink.results(),
HashMap::from([
(PartitionId::new(1), Ok(())),
(PartitionId::new(2), Err(String::from("foo"))),
(PartitionId::new(3), Ok(())),
(PartitionId::new(4), Ok(())),
]),
);
// commits are just forwarded to inner `Commit` impl
assert_eq!(
inner_commit.history(),
vec![
CommitHistoryEntry {
partition_id: PartitionId::new(1),
delete: vec![],
upgrade: vec![],
created: vec![],
target_level: CompactionLevel::Initial,
},
CommitHistoryEntry {
partition_id: PartitionId::new(2),
delete: vec![],
upgrade: vec![],
created: vec![],
target_level: CompactionLevel::Initial,
},
]
);
}
#[tokio::test]
async fn test_err_commit_unknown() {
let (source, commit, sink) = throttle_partition(
MockPartitionsSource::new(vec![PartitionId::new(1)]),
MockCommit::new(),
MockPartitionDoneSink::new(),
Arc::new(MockProvider::new(Time::MIN)),
Duration::from_secs(0),
1,
);
source.fetch().await;
sink.record(PartitionId::new(1), Ok(()))
.await
.expect("record failed");
assert_matches!(
commit
.commit(PartitionId::new(1), &[], &[], &[], CompactionLevel::Initial)
.await,
Err(CommitError::ThrottlerError(Error::Uniqueness(res))) if res == PartitionId::new(1)
);
}
#[tokio::test]
async fn test_panic_sink_unknown() {
let (source, _commit, sink) = throttle_partition(
MockPartitionsSource::new(vec![PartitionId::new(1)]),
MockCommit::new(),
MockPartitionDoneSink::new(),
Arc::new(MockProvider::new(Time::MIN)),
Duration::from_secs(0),
1,
);
source.fetch().await;
sink.record(PartitionId::new(1), Ok(()))
.await
.expect("record failed");
let err = sink.record(PartitionId::new(1), Ok(())).await;
assert_matches!(
err,
Err(PartitionDoneSinkError::Throttler(Error::Uniqueness(partition))) if partition == PartitionId::new(1),
"fails because partition 1 is already done"
);
}
// TODO: remove last legacy panic from scheduler
// Requires change of Scheduler.get_jobs() API to a Result<Vec<CompactionJob>>
#[tokio::test]
#[should_panic(expected = "Partition already in-flight: 1")]
async fn test_panic_duplicate_in_flight() {
let (source, _commit, _sink) = throttle_partition(
MockPartitionsSource::new(vec![PartitionId::new(1)]),
MockCommit::new(),
MockPartitionDoneSink::new(),
Arc::new(MockProvider::new(Time::MIN)),
Duration::from_secs(0),
1,
);
source.fetch().await;
source.fetch().await;
}
}
|
use std::fmt;
use std::io::{self, Write};
use super::{Block, DataFlowGraph, Function, Immediate, Inst, Value};
pub fn write_function(w: &mut dyn Write, func: &Function) -> io::Result<()> {
let is_public = func.signature.visibility.is_public();
if is_public {
write!(w, "pub ")?;
}
write!(w, "function ")?;
write_spec(w, func)?;
if func.signature.visibility.is_externally_defined() {
return Ok(());
}
writeln!(w, " {{")?;
let mut any = false;
for (block, block_data) in func.dfg.blocks() {
if any {
writeln!(w)?;
}
write_block_header(w, func, block, 4)?;
for inst in block_data.insts() {
write_instruction(w, func, inst, 4)?;
}
any = true;
}
writeln!(w, "}}")
}
fn write_spec(w: &mut dyn Write, func: &Function) -> io::Result<()> {
write!(w, "{}(", &func.signature.name)?;
let args = func
.signature
.params()
.iter()
.map(|t| t.to_string())
.collect::<Vec<String>>()
.join(", ");
let results = func
.signature
.results()
.iter()
.map(|t| t.to_string())
.collect::<Vec<String>>()
.join(", ");
write!(w, "{}) -> {} ", &args, &results)
}
fn write_arg(w: &mut dyn Write, func: &Function, arg: Value) -> io::Result<()> {
write!(w, "{}: {}", arg, func.dfg.value_type(arg))
}
pub fn write_block_header(
w: &mut dyn Write,
func: &Function,
block: Block,
indent: usize,
) -> io::Result<()> {
// The indent is for instructions, block header is 4 spaces outdented
write!(w, "{1:0$}{2}", indent - 4, "", block)?;
let mut args = func.dfg.block_params(block).iter().cloned();
match args.next() {
None => return writeln!(w, ":"),
Some(arg) => {
write!(w, "(")?;
write_arg(w, func, arg)?;
}
}
for arg in args {
write!(w, ", ")?;
write_arg(w, func, arg)?;
}
writeln!(w, "):")
}
fn write_instruction(
w: &mut dyn Write,
func: &Function,
inst: Inst,
indent: usize,
) -> io::Result<()> {
let s = String::with_capacity(16);
write!(w, "{1:0$}", indent, s)?;
let mut has_results = false;
for r in func.dfg.inst_results(inst) {
if !has_results {
has_results = true;
write!(w, "{}", r)?;
} else {
write!(w, ", {}", r)?;
}
}
if has_results {
write!(w, " = ")?
}
let opcode = func.dfg[inst].opcode();
write!(w, "{}", opcode)?;
write_operands(w, &func.dfg, inst)?;
if has_results {
write!(w, " : ")?;
for (i, v) in func.dfg.inst_results(inst).iter().enumerate() {
let t = func.dfg.value_type(*v).to_string();
if i > 0 {
write!(w, ", {}", t)?;
} else {
write!(w, "{}", t)?;
}
}
}
writeln!(w)?;
Ok(())
}
fn write_operands(w: &mut dyn Write, dfg: &DataFlowGraph, inst: Inst) -> io::Result<()> {
use crate::ir::*;
use firefly_binary::BinaryEntrySpecifier;
let pool = &dfg.value_lists;
match dfg[inst].as_ref() {
InstData::BinaryOp(BinaryOp { args, .. }) => write!(w, " {}, {}", args[0], args[1]),
InstData::BinaryOpImm(BinaryOpImm { arg, imm, .. }) => write!(w, " {}, {}", arg, imm),
InstData::UnaryOp(UnaryOp { arg, .. }) => write!(w, " {}", arg),
InstData::UnaryOpImm(UnaryOpImm { imm, .. }) => write!(w, " {}", imm),
InstData::UnaryOpConst(UnaryOpConst { imm, .. }) => write!(w, " {}", dfg.constant(*imm)),
InstData::Ret(Ret { args, .. }) => write!(w, " {}", DisplayValues(args.as_slice())),
InstData::RetImm(RetImm { arg, imm, .. }) => write!(w, " {}, {}", imm, arg),
InstData::Call(Call { args, .. }) => {
let func_data = dfg.call_signature(inst).unwrap();
write!(
w,
" {}({})",
&func_data.mfa(),
DisplayValues(args.as_slice(pool))
)
}
InstData::CallIndirect(CallIndirect { callee, args, .. }) => {
write!(w, " {:?}({})", &callee, DisplayValues(args.as_slice(pool)))
}
InstData::MakeFun(MakeFun { callee, env, .. }) => {
let sig = dfg.callee_signature(*callee);
let mfa = sig.mfa();
write!(w, " {}({})", &mfa, DisplayValues(env.as_slice(pool)))
}
InstData::CondBr(CondBr {
cond,
then_dest,
else_dest,
..
}) => {
write!(w, " {}, ", cond)?;
write!(w, "{}", then_dest.0)?;
write_block_args(w, then_dest.1.as_slice(pool))?;
write!(w, ", {}", else_dest.0)?;
write_block_args(w, else_dest.1.as_slice(pool))
}
InstData::Br(Br {
op,
destination,
args,
..
}) if *op == Opcode::Br => {
write!(w, " {}", destination)?;
write_block_args(w, args.as_slice(pool))
}
InstData::Br(Br {
destination, args, ..
}) => {
let args = args.as_slice(pool);
write!(w, " {}, {}", args[0], destination)?;
write_block_args(w, &args[1..])
}
InstData::Switch(Switch {
arg, arms, default, ..
}) => {
write!(w, " {}", arg)?;
for (value, dest) in arms.iter() {
write!(w, ", {} => {}", value, dest)?;
}
write!(w, ", {}", default)
}
InstData::PrimOp(PrimOp { args, .. }) => {
write!(w, " {}", DisplayValues(args.as_slice(pool)))
}
InstData::PrimOpImm(PrimOpImm { imm, args, .. }) => {
write!(w, " {}, {}", imm, DisplayValues(args.as_slice(pool)))
}
InstData::IsType(IsType { ty, arg, .. }) => {
write!(w, " {}, {}", arg, ty)
}
InstData::BitsMatch(BitsMatch { spec, args, .. }) => {
let values = DisplayValues(args.as_slice(pool));
match spec {
BinaryEntrySpecifier::Integer {
endianness, signed, ..
} => {
if *signed {
write!(w, ".sint.{} {}", endianness, values)
} else {
write!(w, ".uint.{} {}", endianness, values)
}
}
BinaryEntrySpecifier::Float {
endianness, unit, ..
} => {
write!(w, ".float.{}({}) {}", endianness, unit, values)
}
BinaryEntrySpecifier::Binary { unit: 8, .. } => {
write!(w, ".bytes {}", values)
}
BinaryEntrySpecifier::Binary { unit, .. } => {
write!(w, ".bits({}) {}", unit, values)
}
BinaryEntrySpecifier::Utf8 => {
write!(w, ".utf8 {}", values)
}
BinaryEntrySpecifier::Utf16 { endianness, .. } => {
write!(w, ".utf16.{} {}", endianness, values)
}
BinaryEntrySpecifier::Utf32 { endianness, .. } => {
write!(w, ".utf32.{} {}", endianness, values)
}
}
}
InstData::BitsMatchSkip(BitsMatchSkip {
spec, args, value, ..
}) => {
let values = DisplayValuesWithImmediate(args.as_slice(pool), *value);
match spec {
BinaryEntrySpecifier::Integer {
endianness, signed, ..
} => {
if *signed {
write!(w, ".sint.{} {}", endianness, values)
} else {
write!(w, ".uint.{} {}", endianness, values)
}
}
BinaryEntrySpecifier::Float {
endianness, unit, ..
} => {
write!(w, ".float.{}({}) {}", endianness, unit, values)
}
BinaryEntrySpecifier::Binary { unit: 8, .. } => {
write!(w, ".bytes {}", values)
}
BinaryEntrySpecifier::Binary { unit, .. } => {
write!(w, ".bits({}) {}", unit, values)
}
BinaryEntrySpecifier::Utf8 => {
write!(w, ".utf8 {}", values)
}
BinaryEntrySpecifier::Utf16 { endianness, .. } => {
write!(w, ".utf16.{} {}", endianness, values)
}
BinaryEntrySpecifier::Utf32 { endianness, .. } => {
write!(w, ".utf32.{} {}", endianness, values)
}
}
}
InstData::BitsPush(BitsPush { spec, args, .. }) => {
let values = DisplayValues(args.as_slice(pool));
match spec {
BinaryEntrySpecifier::Integer {
endianness,
signed,
unit,
..
} => {
if *signed {
write!(w, ".sint.{}({}) {}", endianness, unit, values)
} else {
write!(w, ".uint.{}({}) {}", endianness, unit, values)
}
}
BinaryEntrySpecifier::Float {
endianness, unit, ..
} => {
write!(w, ".float.{}({}) {}", endianness, unit, values)
}
BinaryEntrySpecifier::Binary { unit: 8, .. } => {
write!(w, ".bytes {}", values)
}
BinaryEntrySpecifier::Binary { unit, .. } => {
write!(w, ".bits({}) {}", unit, values)
}
BinaryEntrySpecifier::Utf8 => {
write!(w, ".utf8 {}", values)
}
BinaryEntrySpecifier::Utf16 { endianness, .. } => {
write!(w, ".utf16.{} {}", endianness, values)
}
BinaryEntrySpecifier::Utf32 { endianness, .. } => {
write!(w, ".utf32.{} {}", endianness, values)
}
}
}
InstData::SetElement(SetElement { index, args, .. }) => {
let argv = args.as_slice();
write!(w, " {}[{}], {}", argv[0], index, argv[1])
}
InstData::SetElementImm(SetElementImm {
arg, index, value, ..
}) => write!(w, " {}[{}], {}", arg, index, value),
}
}
fn write_block_args(w: &mut dyn Write, args: &[Value]) -> io::Result<()> {
if args.is_empty() {
Ok(())
} else {
write!(w, "({})", DisplayValues(args))
}
}
struct DisplayValues<'a>(&'a [Value]);
impl<'a> fmt::Display for DisplayValues<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, val) in self.0.iter().enumerate() {
if i == 0 {
write!(f, "{}", val)?;
} else {
write!(f, ", {}", val)?;
}
}
Ok(())
}
}
struct DisplayValuesWithImmediate<'a>(&'a [Value], Immediate);
impl<'a> fmt::Display for DisplayValuesWithImmediate<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, val) in self.0.iter().enumerate() {
if i == 0 {
write!(f, "{}", val)?;
} else {
write!(f, ", {}", val)?;
}
}
if self.0.is_empty() {
write!(f, "{}", &self.1)
} else {
write!(f, ", {}", &self.1)
}
}
}
|
use signal::Signal;
use order::OrderBuilder;
mod market_order_policy;
pub use order::policy::market_order_policy::MarketOrderPolicy;
mod simple_order_policy;
pub use order::policy::simple_order_policy::SimpleOrderPolicy;
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub enum OrderPolicyError {
IndicatorError
}
pub trait OrderPolicy {
fn create_order(&self, signal: &Signal) -> Result<OrderBuilder, OrderPolicyError>;
}
|
extern crate dashpipe;
extern crate testcontainers;
use futures::{
prelude::*,
Stream,
sync::{oneshot},
};
use std::collections::HashMap;
use dashpipe::{OutputChannel, InputChannel, NatsInput, NatsOutput};
use testcontainers::*;
use testcontainers::images::generic::{GenericImage, WaitFor};
use nitox::commands::{ConnectCommand, SubCommand, PubCommand};
use nitox::{NatsClient, NatsError, NatsClientOptions};
use prometheus::proto::MetricFamily;
#[test]
fn test_send_message(){
let docker = clients::Cli::default();
let nats_image = GenericImage::new("nats:1.4.1-linux")
.with_wait_for(WaitFor::message_on_stderr("Listening for client connections"));
let node = docker.run(nats_image);
let cluster_uri = format!("localhost:{}", node.get_host_port(4222).unwrap());
let output = NatsOutput::new(&cluster_uri, "testsubject".to_string()).expect("Unable to initialize NATS");
let connect_cmd = ConnectCommand::builder().build().unwrap();
let options = NatsClientOptions::builder()
.connect_command(connect_cmd)
.cluster_uri(cluster_uri.clone())
.build()
.unwrap();
let fut = NatsClient::from_options(options)
.and_then(|client| client.connect())
.and_then(|client| {
client
.subscribe(SubCommand::builder().subject("testsubject").build().unwrap())
.map_err(|_| NatsError::InnerBrokenChain)
.and_then(move |stream| {
output.send("hello world".to_string());
stream
.take(1)
.into_future()
.map(|(maybe_message, _)| maybe_message.unwrap())
.map_err(|_| NatsError::InnerBrokenChain)
})
});
let (tx, rx) = oneshot::channel();
let mut runtime = tokio::runtime::Runtime::new().unwrap();
runtime.spawn(fut.then(|r| tx.send(r).map_err(|e| panic!("Cannot send Result {:?}", e))));
let connection_result = rx.wait().expect("Cannot wait for a result");
let _ = runtime.shutdown_now().wait();
let msg = connection_result.unwrap();
assert_eq!(msg.payload, "hello world");
docker.stop(node.id());
docker.rm(node.id());
let families = prometheus::gather();
assert_ne!(0, families.len());
let mut worked: HashMap<String, bool> = HashMap::new();
for family in &families{
match family.get_name(){
"dashpipe_sent_messages" => {worked.insert("dashpipe_sent_messages".to_string(), true);},
"dashpipe_sent_messages_error" => {worked.insert("dashpipe_sent_messages_error".to_string(), true);},
_ => {},
}
}
assert_eq!(worked.len(), 2);
}
#[test]
fn test_receive_messages(){
let docker = clients::Cli::default();
let nats_image = GenericImage::new("nats:1.4.1-linux")
.with_wait_for(WaitFor::message_on_stderr("Listening for client connections"));
let node = docker.run(nats_image);
let cluster_uri = format!("localhost:{}", node.get_host_port(4222).unwrap());
let input : NatsInput = NatsInput::new(&cluster_uri, "receivedata".to_string(), None).expect("Unable to start NATS");
let connect_cmd = ConnectCommand::builder().build().unwrap();
let options = NatsClientOptions::builder()
.connect_command(connect_cmd)
.cluster_uri(cluster_uri.clone())
.build()
.unwrap();
let fut = NatsClient::from_options(options)
.and_then(|client| client.connect())
.map_err(|_| NatsError::InnerBrokenChain)
.and_then(|client| {
for x in 0..5 {
let pub_cmd = PubCommand::builder()
.subject("receivedata").payload(format!("hello {}", x)).build().unwrap();
client.publish(pub_cmd);
}
Ok(())
});
let mut runtime = tokio::runtime::Runtime::new().unwrap();
runtime.spawn(fut.or_else(|_|{Ok(())}));
let mut messages: Vec<String> = Vec::new();
let _ = input.start().expect("Unable to start stream")
.take(5)
.for_each(|m| {
let _ = messages.push(m);
Ok(())})
.wait();
assert_eq!(messages.len(), 5);
let worked = match messages.pop(){
Some(s) => s.starts_with("hello "),
None => false,
};
assert!(worked);
docker.stop(node.id());
docker.rm(node.id());
} |
use std::sync::Arc;
use clap_blocks::{run_config::RunConfig, socket_addr::SocketAddr};
use crate::server_type::ServerType;
/// A service that will start on the specified addresses
#[derive(Debug)]
pub struct Service {
pub http_bind_address: Option<SocketAddr>,
pub grpc_bind_address: SocketAddr,
pub server_type: Arc<dyn ServerType>,
}
impl Service {
pub fn create(server_type: Arc<dyn ServerType>, run_config: &RunConfig) -> Self {
Self {
http_bind_address: Some(run_config.http_bind_address),
grpc_bind_address: run_config.grpc_bind_address,
server_type,
}
}
pub fn create_grpc_only(server_type: Arc<dyn ServerType>, run_config: &RunConfig) -> Self {
Self {
http_bind_address: None,
grpc_bind_address: run_config.grpc_bind_address,
server_type,
}
}
}
|
//! Tree module that only preserves nodes to predetermined depth.
//! This tree always chooses the branch with the longest available "lineage".
//! When a new node is inserted and the current root is "too old", the root
//! is replaced with its child that leads to the longest branch, while
//! all other children are abandoned and removed.
//! Only dependency is std to try to minimize the dependency hell that
//! plagues seemingly every project.
use std::cmp::Eq;
use std::collections::HashMap;
use std::default::Default;
use std::fmt::{self, Debug, Display, Formatter};
use std::hash::Hash;
use std::marker::Copy;
#[derive(Clone)]
/// Internal node that serves as a "tree node".
pub struct ReorgNode<K, M> {
/// key of the node. It is used as its key or name.
key: K,
/// Index of the node in the system.
height: u64,
/// Value of the node.
value: u64,
/// key of the node that is parent to this one.
parent: K,
/// All nodes that has this node as their "parent",
children: Vec<K>,
/// Custom designated meta data
custom_meta: M,
}
impl<K: Debug, M: Debug> Display for ReorgNode<K, M> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
">Key: {:?}\n>Height: {}\n>Value: {}\n>Parent: {:?}\n>Children: {:?}\n>Custom Meta: {:?}",
self.key, self.height, self.value, self.parent, self.children, self.custom_meta
)
}
}
impl<K, M> ReorgNode<K, M> {
pub fn new(key: K, height: u64, value: u64, parent: K, custom_meta: M) -> ReorgNode<K, M> {
ReorgNode {
key,
height,
value,
parent,
children: Vec::new(),
custom_meta,
}
}
pub fn key(&self) -> &K {
&self.key
}
pub fn height(&self) -> u64 {
self.height
}
pub fn value(&self) -> u64 {
self.value
}
pub fn parent(&self) -> &K {
&self.parent
}
pub fn children(&self) -> &[K] {
&self.children
}
pub fn meta(&self) -> &M {
&self.custom_meta
}
}
impl<K: Default, M: Default> Default for ReorgNode<K, M> {
fn default() -> Self {
ReorgNode::new(K::default(), 0, 0, K::default(), M::default())
}
}
/// Main working struct of the reogranizational code body.
pub struct Organizer<K, M> {
/// The current root, or oldest node that we deal with.
root: ReorgNode<K, M>,
/// Every node currently held in the system, stored by their key as its key.
/// Does not contain the root.
nodes_by_key: HashMap<K, ReorgNode<K, M>>,
/// Every node currently held by the system, stored by their height as the key.
/// As the main functionality is to decide which branch is the longest, this
/// map has a Vec as the value field, because multiple nodes with the same
/// height are possible.
/// This map does contain the root.
nodes_by_height: HashMap<u64, Vec<K>>,
/// Buffer for node that doesn't have their parent in the system yet.
/// This might be because the nodes height is greater by multiple steps
/// than the one we currently have as head.
buffer: HashMap<K, ReorgNode<K, M>>,
/// The height of the node with currently greatest height in the system.
/// (Can also be described as the youngest or newest nodes height.)
/// (Does not include nodes in the buffer)
height: u64,
/// The predetermined depth we check the branches to. Any node older than this
/// are discarded.
allowed_depth: u64,
/// Sets the Organizer to search for the "most valuable" branches instead
/// of the longest ones. Accumulates the value fields of the nodes.
value_based: bool,
}
impl<K: Debug, M: Debug> Display for Organizer<K, M> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Root: \n{}\nNode Key Count: {}\nNode Height Count: {}\nHeight: {:?}\nAllowed Depth: {:?}",
self.root, self.nodes_by_key.len(), self.nodes_by_height.len(), self.height, self.allowed_depth)
}
}
impl<K: Default, M: Default> Default for Organizer<K, M> {
fn default() -> Self {
Organizer {
height: 0,
root: ReorgNode::default(),
nodes_by_key: HashMap::new(),
nodes_by_height: HashMap::new(),
buffer: HashMap::new(),
allowed_depth: 255,
value_based: false,
}
}
}
impl<K: Default + Eq + Hash + Clone + Debug + Copy, M: Debug + Default> Organizer<K, M> {
/// Default state constructor with predetermined max depth.
/// Examples
/// ```
/// use abandoning_reorg::Organizer;
///
/// abandoning_reorg::Organizer::new(777);
/// ```
pub fn new(allowed_depth: u64, value_based: bool) -> Organizer<K, M> {
Self {
height: 0,
root: ReorgNode::default(),
nodes_by_key: HashMap::new(),
nodes_by_height: HashMap::new(),
buffer: HashMap::new(),
allowed_depth,
value_based,
}
}
/// Constructor function that takes the first root node - possibly the genesis node -
/// and the depth we want to allow reorganization to. Stores the root node in its slot,
/// as well as by height. Root is not stored by key, only by height.
/// Examples
/// ```
/// use abandoning_reorg::Organizer;
/// use abandoning_reorg::ReorgNode;
///
/// let initial_node = ReorgNode::default();
/// Organizer::<[u8; 32], ()>::new_with(initial_node, 777);
/// ```
pub fn new_with(
root: ReorgNode<K, M>,
allowed_depth: u64,
value_based: bool,
) -> Organizer<K, M> {
let mut nodes_by_height = HashMap::new();
nodes_by_height.insert(root.height, vec![root.key]);
Self {
height: root.height,
root,
nodes_by_key: HashMap::new(),
nodes_by_height,
buffer: HashMap::new(),
allowed_depth,
value_based,
}
}
/// Init function, sets a new root.
/// Examples
/// ```
/// use abandoning_reorg::Organizer;
/// use abandoning_reorg::ReorgNode;
///
/// let initial_node = ReorgNode::default();
/// let organizer = Organizer::default;
/// organizer.init(initial_node);
/// ```
pub fn init(&mut self, first_root: ReorgNode<K, M>) {
self.height = first_root.height;
self.nodes_by_height
.insert(first_root.height, vec![first_root.key]);
self.root = first_root;
}
/// Returns the difference of height and the allowed depth to determine the highest node
/// that we allow, or zero if the number would be negative.
///
/// Examples
/// ```
/// use crate::abandoning_reorg::Organizer;
/// use crate::abandoning_reorg::ReorgNode;
///
/// let initial_node = ReorgNode::default();
/// let organizer = Organizer::<[u8; 32], ()>::new_with(initial_node, 777);
/// assert_eq!(organizer.allowed_oldest(),777);
///
/// let organizer = Organizer::<[u8; 32], ()>::default();
/// assert_eq!(organizer.allowed_oldest(), 255);
/// ```
pub fn allowed_oldest(&self) -> u64 {
self.height.saturating_sub(self.allowed_depth as u64)
}
/// Switches the Organizer to and from value searching mode.
pub fn set_value_based(&mut self, switch: bool) {
self.value_based = switch;
}
/// This function is part of the garbage collection. Deletes every node that in the branch
/// stemming from the node we designated.
pub fn delete_children(&mut self, branch_root: &K) -> Vec<ReorgNode<K, M>> {
let mut ret: Vec<ReorgNode<K, M>> = Vec::new();
// First we try to remove the designated node from the system
if let Some(removed) = self.nodes_by_key.remove(branch_root) {
// We add the removed nodes children to the list that we will remove next
let mut removeable: Vec<K> = removed.children.clone();
// We push the node into the list of nodes we will return
ret.push(removed);
// As long as there are possible nodes in this branch we repeatedly
// remove a node, if it succeeds we push its children to
// the list of removable nodes, then append the node to the return list.
while !removeable.is_empty() {
let mut remove_next = Vec::new();
for key in &removeable {
if let Some(mut removed_last) = self.nodes_by_key.remove(key) {
remove_next.append(&mut removed_last.children);
ret.push(removed_last);
}
}
removeable = remove_next;
}
}
ret
}
/// Utility function that lists node stored by their keyes. (Only prints the keyes)
pub fn list_node_keyes(&self) {
for key in self.nodes_by_key.keys() {
println!("{:?}", key)
}
}
/// Utility that prints the node stored by their keyes. (Actually displays the nodes)
pub fn list_nodes(&self) {
for node in self.nodes_by_key.values() {
println!("{}\n", node)
}
}
/// Returns the key of the node that is the immidiate child of the current root,
/// and has the longest available lineage.
/// # Panics
/// If this function call fails that means that at least one node was not stored in the memory.
pub fn find_longest_branch(&self, most_valuable: Option<bool>) -> K {
// We take the nodes that correspond to the greatest available
// height stored in the system as the heads of the tree.
// This should not fail for we always store every node by their height.
let heads = self
.nodes_by_height
.get(&self.height)
.expect("there in no node stored corresponding to the greatest logged height");
let mut lead_branches: HashMap<K, u64> = HashMap::new();
// We check each head of the tree
for head in heads {
let mut worth = 0;
let mut root = head;
// We count the lineage number of each branch from head to root
while let Some(node) = self.nodes_by_key.get(root) {
if node.parent != self.root.key {
root = &node.parent;
worth += if most_valuable.unwrap_or(self.value_based) {
node.value
} else {
1
};
} else {
// When we reached the roots immidiate child we break out of the loop
break;
}
}
// Insert the height of the branch with the branches root (the system roots child)
// as the key.
lead_branches.insert(*root, worth);
}
let (mut most_valuable_key, mut greatest_worth) = (K::default(), 0);
// After the parsed every branch corresponding to a head, we determine the longest and return
// its key
for (key, worth) in lead_branches {
if worth > greatest_worth {
greatest_worth = worth;
most_valuable_key = key;
}
}
most_valuable_key
}
/// Apply callback from given head to given root, or as long as possible.
/// If no head is supplied try to go from the highest, but only if
/// there is only one node at the greatest height,
pub fn apply_callback<T>(
&self,
head: Option<K>,
root: Option<K>,
callback: &mut dyn FnMut(&ReorgNode<K, M>) -> T,
) {
let head = match head {
Some(head) => head,
None => match self.nodes_by_height.get(&self.height) {
Some(heads) => {
if heads.len() != 1 {
return;
} else {
heads[0]
}
}
None => return,
},
};
let head_node = self
.nodes_by_key
.get(&head)
.expect("there in no node stored corresponding to the gived key");
callback(head_node);
let mut cursor = head_node.parent;
while let Some(node) = self.nodes_by_key.get(&cursor) {
match root {
Some(root_key) => {
if node.key != root_key {
cursor = node.parent
} else {
break;
}
}
None => {
cursor = node.parent;
}
}
callback(node);
}
}
/// Utility function that takes the lists of nodes stored by key and nodes stored
/// by their height, and checks for node that are only logged by height and not by key.
/// This should always only return the current root.
pub fn check_height_to_key_diff(&self) -> Vec<K> {
let mut ret = HashMap::new();
for nodes in self.nodes_by_height.values() {
for b in nodes {
ret.insert(*b, ());
}
}
for key in self.nodes_by_key.keys() {
ret.remove(key);
}
ret.keys().copied().collect::<Vec<K>>()
}
/// Main logic of the reorganizational functionality. Determines the validity of the
/// inserted node by checking its height and its parent then
/// saves it into a branch if a viable parent is present and the height is acceptable,
/// or into the buffer if parent is not present but has a good height.
/// Otherwise the node is discarded.
/// The height of the node is considered good if its greater than that of the current root.
/// Panics
/// A panic will occur if a node has a child listed that we do not have
/// stored by its key.
pub fn insert(&mut self, node: ReorgNode<K, M>, most_valuable: Option<bool>) {
// if new node older than we search, we don't care about it
if node.height <= self.allowed_oldest() {
return;
}
// if new nodes parent isn't stored already and it's height isn't greater than
// what we know the newest to be, we don't care about it
if !self.nodes_by_key.contains_key(&node.parent) && node.height <= self.height {
return;
}
// when the root nodes depth reaches the threshold we predetermined
if self.root.height == self.allowed_oldest() {
match self.root.children.len() {
0 => {}
1 => {
// In case the root has only one child, the child becomes the new node.
// If this fails that means the children of the root were already removed.
self.root = self.nodes_by_key.remove(&self.root.children[0]).unwrap();
}
_ => {
// In case the root has multiple children we determine the longest branch.
let remove = self.root.children.clone();
// We replace the current root with its child that heirs the longest lineage.
// If this fails that means that the branch has already been removed.
self.root =
self.nodes_by_key
.remove(&self.find_longest_branch(Some(
most_valuable.unwrap_or(self.value_based),
)))
.unwrap();
for dead_branch in remove {
// we delete every branch stemming from the root other than the longest one
if dead_branch != self.root.key {
self.delete_children(&dead_branch);
}
}
}
}
}
// Retrieving the inserted nodes parent to append said node to the
// parents list of children. If neither ifs trigger than parent is not part
// of the system, and we put the node into the buffer.
if let Some(parent) = self.nodes_by_key.get_mut(&node.parent) {
parent.children.push(node.key);
} else if node.parent == self.root.key {
self.root.children.push(node.key);
} else {
self.buffer.insert(node.key, node);
return;
}
// We save the node key to its height
match self.nodes_by_height.get_mut(&node.height) {
Some(has_node) => has_node.push(node.key),
None => {
self.nodes_by_height.insert(node.height, vec![node.key]);
}
};
// This is the newest node hence we take its height as the new system height
self.height = node.height;
// We save the node itself with its key as the key
self.nodes_by_key.insert(node.key, node);
// We double check for nodes that should have already been removed
self.nodes_by_key.remove(&self.root.parent);
if let Some(old_root) = self
.nodes_by_height
.remove(&(self.root.height.saturating_sub(1)))
{
for old in old_root {
self.nodes_by_key.remove(&old);
}
}
let mut reinsert = Vec::new();
let mut buffer_clear = Vec::new();
// We check the nodes in the buffer wether they have expired,
// then we check if their parents have been pushed into the system.
for (key, buffer_node) in &self.buffer {
if buffer_node.height < self.allowed_oldest() {
buffer_clear.push(*key);
continue;
}
if let Some(parent) = self.nodes_by_key.get_mut(&buffer_node.parent) {
parent.children.push(*key);
reinsert.push(*key);
}
}
// If we found the parent of a node in the buffer, we save it
for r in reinsert {
if let Some(reinsertable) = self.buffer.remove(&r) {
match self.nodes_by_height.get_mut(&reinsertable.height) {
Some(has_node) => has_node.push(r),
None => {
self.nodes_by_height.insert(reinsertable.height, vec![r]);
}
};
self.nodes_by_key.insert(r, reinsertable);
}
}
// If the node has expired we remove if from the buffer-
for bc in buffer_clear {
self.buffer.remove(&bc);
}
}
/// Getter for the keys to the nodes at the current greatest height.
pub fn highest_nodes(&self) -> &[K] {
self.nodes_by_height.get(&self.height).unwrap()
}
}
|
#[macro_use]
extern crate serde_derive;
pub mod toml_pares;
pub mod lmdb_use;
pub mod uuid_std;
pub mod serde_json_std;
pub mod scrypt_std;
#[cfg(test)]
mod tests {
use super::uuid_std;
use super::toml_pares;
use super::serde_json_std;
use super::scrypt_std;
#[test]
fn uuid_test(){
uuid_std::uuid_test();
}
#[test]
fn parse_toml(){
toml_pares::parse_toml();
assert_eq!(1,2);
}
#[test]
fn json_test(){
//serde_json_std::serde_json_test();
let f = 262144 as f32;
println!("{}",f.log2());
assert_eq!(1,2);
}
#[test]
fn scrypt_test(){
let ret = scrypt_std::test_scrypt_128();
match ret {
Ok(_)=>{
},
Err(e)=>{
println!("error:{}",e)
}
}
assert_eq!(1,2);
}
}
|
use std::alloc::Layout;
use std::backtrace::Backtrace;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::mem;
use std::ptr::NonNull;
use std::sync::Arc;
use hashbrown::HashMap;
use thiserror::Error;
use liblumen_term::{Encoding as TermEncoding, Tag};
use crate::borrow::CloneToProcess;
use crate::erts::exception::{AllocResult, InternalResult};
use crate::erts::fragment::HeapFragment;
use crate::erts::process::alloc::{Heap, TermAlloc};
use super::arch::{Repr, Word};
use super::prelude::*;
/// Represents the various conditions under which encoding can fail
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum TermEncodingError {
/// Occurs when attempting to encode an unaligned pointer
#[error("invalid attempt to encode unaligned pointer")]
InvalidAlignment,
/// Occurs when attempting to encode a value that cannot fit
/// within the encoded types valid range, e.g. an integer that
/// is too large
#[error("invalid attempt to encode a value outside the valid range")]
ValueOutOfRange,
}
/// Used to indicate that some value was not a valid encoding of a term
#[derive(Error, Debug, Clone)]
pub enum TermDecodingError {
/// Occurs primarily with header tags, as there are some combinations
/// of tag bits that are unused. Primary tags are (currently) fully
/// occupied, and so invalid tags are not representable. That may
/// change if additional representations are added that have free
/// primary tags
#[error("invalid type tag")]
InvalidTag { backtrace: Arc<Backtrace> },
/// Decoding a Term that is a move marker is considered an error,
/// code which needs to be aware of move markers should already be
/// manually checking for this possibility
#[error("tried to decode a move marker")]
MoveMarker { backtrace: Arc<Backtrace> },
/// Decoding a Term that is a none value is considered an error,
/// as this value is primarily used to indicate an error; and in cases
/// where it represents a real value (namely as a move marker), it is
/// meaningless to decode it. In all other cases, it represents uninitialized
/// memory
#[error("tried to decode a none value")]
NoneValue { backtrace: Arc<Backtrace> },
}
impl Eq for TermDecodingError {}
impl PartialEq for TermDecodingError {
fn eq(&self, other: &Self) -> bool {
mem::discriminant(self) == mem::discriminant(other)
}
}
/// This trait provides the ability to encode a type to some output encoding.
///
/// More specifically with regard to terms, it encodes immediates directly,
/// or for boxed terms, encodes the header. For boxed terms it is then
/// necessary to use the `Boxable::as_box` trait function to obtain an
/// encoded pointer when needed.
pub trait Encode<T: Encoded> {
fn encode(&self) -> InternalResult<T>;
}
/// This is a marker trait for terms which can be boxed
pub trait Boxable<T: Repr> {}
/// This is a marker trait for boxed terms which are stored as literals
pub trait Literal<T: Repr>: Boxable<T> {}
/// This trait provides functionality for obtaining a pointer to an
/// unsized type from a raw term. For example, the `Tuple` type consists
/// of an arbitrary number of `Term` elements, and as such it is a
/// dynamically sized type (i.e. `?Sized`). Raw pointers to dynamically
/// sized types cannot be constructed without a size, so the job of this
/// trait is to provide functions to determine a size automatically from
/// such terms and construct a pointer, given only a pointer to a term
/// header.
///
/// Implementors of this trait are dynamically-sized types (DSTs), and
/// as such, the rules around how you can use them are far more restrictive
/// than a typical statically sized struct. Notably, you can only ever
/// construct a reference to one, you can't create a raw pointer to one or
/// construct an instance of one directly.
///
/// Clearly this seems like a chicken and egg problem since it is mostly
/// meaningless to construct references to things you can't create in the
/// first place. So how do values to DSTs get constructed? There are a few
/// key principles:
///
/// First, consider slices; the only way to make sense of a slice as a concept
/// is to know the position where the slice starts, the size of its elements
/// and the length of the slice. Rust gives us tools to construct these given
/// a pointer with a sized element type, and the length of the slice. This is
/// part of the solution, but it doesn't answer the question of how we deal with
/// dynamically sized _structs_.
///
/// The second piece of the puzzle is structural equivalence. Consider our `Tuple`
/// type, it is a struct consisting of a header containing the arity, and then some
/// arbitrary number of elements. If we expressed it's type as `Tuple<[Term]>`, where
/// the `elements` field is given the type `[Term]`; then a value of `Tuple<[Term]>`
/// is structurally equivalent to a value of `[Tuple<Term>; 1]`. Put another way, since
/// our variable-length field occurs at the end of the struct, we're really saying
/// that the layout of `[Term; 1]` is the same as `Term`, which is intuitively obvious.
///
/// The final piece of the puzzle is given by another Rust feature: unsizing coercions.
/// When Rust sees a cast from a sized type to an unsized type, it performs an unsizing
/// coercion.
///
/// For our purposes, the coercion here is from `[T; N]` to `CustomType<T>`, which
/// is allowed when `CustomType<T>` only has a single, non-PhantomData field involving `T`.
///
/// So given a pointer to a `Tuple`, if we construct a slice of `[Term; N]` and cast it to
/// a pointer to `Tuple`, Rust performs the coercion by first filling in the fields of `Tuple`
/// from the pointed-to memory, then coercing the `[Term; N]` to `[Term]` using the address of
/// the unsized field plus the size `N` to construct the fat pointer required for the `[Term]`
/// value.
///
/// To be clear: the pointer we use to construct the `[T; N]` slice that we coerce, is a
/// pointer to memory that contains the sized fields of `CustomType<T>` _followed by_ memory that
/// contains the actual `[T; N]` value. Rust is essentially casting the pointer given by
/// adding the offset of the unsized field to the base pointer we provided, plus the size
/// `N` to coerce the sized type to the type of the unsized field. The `N` provided is
/// _not_ the total size of the struct in units of `T`, it is always the number of elements
/// contained in the unsized field.
///
/// # Caveats
///
/// - This only works for types that follow Rusts' unsized coercion rules
/// - It is necessary to know the size of the variable-length region, which is generally true
/// for the types we are using this on, thanks to storing the arity in words of all non-immediate
/// types; but it has to be in terms of the element size. For example, `HeapBin` has a slice
/// of bytes, not `Term`, and the arity of the `HeapBin` is the size in words including extra
/// fields, so if we used that arity value, we'd get completely incorrect results. In the case of
/// `HeapBin`, we actually store the binary data size in the `flags` field, so we are able to use
/// that to obtain the `N` for our `[u8; N]` slice. Just be aware that similar steps will be
/// necessary for types that have non-word-sized elements.
///
/// - [DST Coercion RFC](https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md)
/// - [Unsize Trait](http://doc.rust-lang.org/1.38.0/std/marker/trait.Unsize.html)
/// - [Coercion - Nomicon](http://doc.rust-lang.org/1.38.0/nomicon/coercions.html)
pub trait UnsizedBoxable<T: Repr>: Boxable<T> + DynamicHeader {
// The type of element contained in the dynamically sized
// area of this type. By default this is specified as `()`,
// with the assumption that elements are word-sized. For
// non-word-sized elements, this is incorrect, e.g. for binary
// data, as found in `HeapBin`
// type Element: Sized;
/// Given a pointer, this function dereferences the original term header,
/// and uses its arity value to construct a fat pointer to the real term
/// type.
///
/// The implementation for this function is auto-implemented by default,
/// but should be overridden if the number of elements in the dynamically
/// sized portion of the type are not inferred by the arity produced from
/// the header.
unsafe fn from_raw_term(ptr: *mut T) -> Boxed<Self>;
}
/// Boxable terms require a header term to be built during
/// construction of the type, which specifies the type and
/// size in words of the non-header portion of the data
/// structure.
///
/// This struct is a safe abstraction over that header to
/// ensure that architecture-specific details do not leak
/// out of the `arch` or `encoding` modules.
#[repr(transparent)]
#[derive(PartialEq, Eq)]
pub struct Header<T: ?Sized> {
value: Term,
_phantom: PhantomData<T>,
}
impl<T: ?Sized> Clone for Header<T> {
fn clone(&self) -> Self {
Self {
value: self.value,
_phantom: PhantomData,
}
}
}
impl<T: ?Sized> Copy for Header<T> {}
impl<T: Sized> Header<T> {
/// Returns the statically known base size (in bytes) of any value of type `T`
#[allow(unused)]
#[inline]
fn static_size() -> usize {
mem::size_of::<T>()
}
/// Returns the statically known base arity (in words) of any value of type `T`
#[inline]
fn static_arity() -> usize {
mem::size_of::<T>() - mem::size_of::<Self>()
}
}
impl<T: ?Sized> Header<T> {
/// Returns the size in bytes of the value this header represents, including the header
#[inline]
pub fn size(&self) -> usize {
mem::size_of::<Term>() * self.size_in_words()
}
/// Returns the size in words of the value this header represents, including the header
#[inline]
pub fn size_in_words(&self) -> usize {
self.arity() + 1
}
/// Returns the size in words of the value this header represents, not including the header
#[inline]
pub fn arity(&self) -> usize {
self.value.arity()
}
#[inline]
fn to_word_size(size: usize) -> usize {
use liblumen_core::alloc::utils::round_up_to_multiple_of;
round_up_to_multiple_of(size, mem::size_of::<Term>()) / mem::size_of::<Term>()
}
}
impl<T: ?Sized> Debug for Header<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let name = core::any::type_name::<T>();
write!(f, "Header<{}>({:#b})", name, self.value.as_usize())
}
}
const_assert_eq!(mem::size_of::<Header<usize>>(), mem::size_of::<usize>());
impl Header<Map> {
pub fn from_map(map: &HashMap<Term, Term>) -> Self {
let header_layout = Layout::new::<Self>();
let value_layout = Layout::for_value(map);
let (layout, _value_offset) = header_layout.extend(value_layout).unwrap();
// subtract the header layout size in words instead of just not including it as `extend`
// adds padding for field alignment.
let arity = Self::to_word_size(layout.size()) - Self::to_word_size(header_layout.size());
let value = Term::encode_header(arity.try_into().unwrap(), Term::HEADER_MAP);
Self {
value,
_phantom: PhantomData,
}
}
}
/// This is a marker trait for dynamically-sized types which have headers
pub trait DynamicHeader {
/// The header tag associated with this type
const TAG: Word;
/// Returns the header of this value
fn header(&self) -> Header<Self>;
}
#[macro_export]
macro_rules! impl_dynamic_header {
($typ:ty, $tag:expr) => {
impl crate::erts::term::encoding::DynamicHeader for $typ {
const TAG: crate::erts::term::arch::Word = $tag;
#[inline]
fn header(&self) -> crate::erts::term::encoding::Header<Self> {
self.header
}
}
};
}
impl<T: ?Sized + DynamicHeader> Header<T> {
pub fn from_arity(arity: usize) -> Self {
let arity = arity.try_into().unwrap();
let value = Term::encode_header(arity, T::TAG);
Self {
value,
_phantom: PhantomData,
}
}
}
/// This is a marker trait for types which have headers that can be statically derived
pub trait StaticHeader {
/// The header tag associated with this type
const TAG: Word;
/// Returns the header of this value
fn header(&self) -> Header<Self>;
}
#[macro_export]
macro_rules! impl_static_header {
($typ:ty, $tag:expr) => {
impl crate::erts::term::encoding::StaticHeader for $typ {
const TAG: crate::erts::term::arch::Word = $tag;
#[inline]
fn header(&self) -> crate::erts::term::encoding::Header<Self> {
self.header
}
}
};
}
impl<T: StaticHeader> Default for Header<T> {
fn default() -> Self {
let arity = Self::to_word_size(Self::static_arity());
let value = Term::encode_header(arity.try_into().unwrap(), T::TAG);
Self {
value,
_phantom: PhantomData,
}
}
}
/// This trait is used to implement unsafe dynamic casts from an implementation
/// of `Encoded` to some type `T`.
///
/// Currently this is used to implement `dyn_cast` from `Term` to `*const T`,
/// where `T` is typically either `Term` or `Cons`.
///
/// NOTE: Care should be taken to avoid implementing this unless absolutely necessary,
/// it is mostly intended for use cases where the type of a `Encoded` value has already been
/// validated, and we don't want to go through the `TypedTerm` machinery for some reason.
/// As a general rule, use safer methods for extracting values from an `Encoded`, as this
/// defers all safety checks to runtime when used.
pub trait Cast<T>: Encoded {
/// Perform a dynamic cast from `Self` to `T`
///
/// It is expected that implementations of this function will assert that `self` is
/// actually a value of the destination type when concrete. However, it is allowed
/// to implement this generically for pointers, but should be considered very unsafe
/// as there is no way to protect against treating some region of memory as the wrong
/// type when used in that way. Always prefer safer alternatives where possible.
fn dyn_cast(self) -> T;
}
/// This trait defines the common API for low-level term representations, i.e. `Term`.
/// It contains all common functions for working directly with encoded terms where the
/// implementation of those functions may depend on platform/architecture details.
///
/// Since terms may provide greater or fewer immediate types based on platform restrictions,
/// it is necessary for each representation to define these common functions in order to prevent
/// tying higher-level code to low-level details such as the specific bit-width of a
/// machine word.
///
/// NOTE: This trait requires that implementations implement `Copy` because higher-level code
/// currently depends on those semantics. Some functions, such as `decode`, take a reference
/// to `self` to prevent copying the original term in cases where the location in memory is
/// important. However, several functions of this trait do not, and it is assumed that those
/// functions are not dependent on a specific memory address. If that constraint is violated
/// then you may end up with a partial term which leads to out of bounds memory addresses, or
/// other undefined behavior.
pub trait Encoded: Repr + Copy {
/// Decodes `Self` into a `TypedTerm`, unless the encoded value is
/// invalid or malformed.
///
/// NOTE: Implementations should attempt to catch all possible decoding errors
/// to make this as safe as possible. The only exception to this rule should
/// be the case of decoding a pointer which can not be validated unless it
/// is dereferenced.
fn decode(&self) -> Result<TypedTerm, TermDecodingError>;
fn type_of(&self) -> Tag<<<Self as Repr>::Encoding as TermEncoding>::Type> {
Self::Encoding::type_of(self.value())
}
/// Returns `true` if the encoded value represents `NONE`
#[inline]
fn is_none(self) -> bool {
Self::Encoding::is_none(self.value())
}
/// Returns `true` if the encoded value represents a pointer to a term
#[inline]
fn is_boxed(self) -> bool {
Self::Encoding::is_boxed(self.value())
}
/// Returns `true` if the encoded value is the header of a non-immediate term
#[inline]
fn is_header(self) -> bool {
Self::Encoding::is_header(self.value())
}
/// Returns `true` if the encoded value is an immediate value
#[inline]
fn is_immediate(self) -> bool {
Self::Encoding::is_immediate(self.value())
}
/// Returns `true` if the encoded value represents a pointer to a literal value
#[inline]
fn is_literal(self) -> bool {
Self::Encoding::is_literal(self.value())
}
/// Returns `true` if the encoded value represents the empty list
#[inline]
fn is_nil(self) -> bool {
Self::Encoding::is_nil(self.value())
}
/// Returns `true` if the encoded value represents a nil or `Cons` value (empty or non-empty
/// list)
#[inline]
fn is_list(self) -> bool {
Self::Encoding::is_list(self.value())
}
/// Returns `true` if the encoded value represents a `Cons` value (non-empty list)
#[inline]
fn is_non_empty_list(self) -> bool {
Self::Encoding::is_non_empty_list(self.value())
}
/// Returns `true` if the encoded value is an atom
fn is_atom(self) -> bool {
Self::Encoding::is_atom(self.value())
}
/// Returns `true` if the encoded value is a boolean
fn is_boolean(self) -> bool {
Self::Encoding::is_boolean(self.value())
}
/// Returns `true` if the encoded value is a fixed-width integer value
fn is_smallint(self) -> bool {
Self::Encoding::is_smallint(self.value())
}
/// Returns `true` if the encoded value is the header of a arbitrary-width integer value
fn is_bigint(self) -> bool {
Self::Encoding::is_bigint(self.value())
}
/// Returns `true` if the encoded value is a pointer to a arbitrary-width integer value
fn is_boxed_bigint(self) -> bool {
Self::Encoding::is_boxed_bigint(self.value())
}
/// Returns `true` if the encoded value is an integer of either
/// fixed or arbitrary width
fn is_integer(&self) -> bool {
if self.is_smallint() {
return true;
}
match self.decode() {
Ok(TypedTerm::BigInteger(_)) => true,
_ => false,
}
}
/// Returns `true` if the encoded value is a float
///
/// NOTE: This function returns true if either the term is an immediate float,
/// or if it is the header of a packed float. It does not unwrap boxed values.
fn is_float(self) -> bool {
Self::Encoding::is_float(self.value())
}
/// Returns `true` if the encoded value is a pointer to a `Float`
fn is_boxed_float(self) -> bool {
Self::Encoding::is_boxed_float(self.value())
}
/// Returns `true` if the encoded value is either a float or integer
fn is_number(self) -> bool {
match self.decode() {
Ok(TypedTerm::SmallInteger(_))
| Ok(TypedTerm::BigInteger(_))
| Ok(TypedTerm::Float(_)) => true,
_ => false,
}
}
/// Returns `true` if the encoded value is the header of a `Tuple`
fn is_tuple(self) -> bool {
Self::Encoding::is_tuple(self.value())
}
/// Returns `true` if the encoded value is a pointer to a `Tuple`
fn is_boxed_tuple(self) -> bool {
Self::Encoding::is_boxed_tuple(self.value())
}
/// Returns `true` if the encoded value is the header of a `Map`
fn is_map(self) -> bool {
Self::Encoding::is_map(self.value())
}
/// Returns `true` if the encoded value is a pointer to a `Map`
fn is_boxed_map(self) -> bool {
Self::Encoding::is_boxed_map(self.value())
}
/// Returns `true` if the encoded value is a `Pid`
fn is_local_pid(self) -> bool {
Self::Encoding::is_local_pid(self.value())
}
/// Returns `true` if the encoded value is the header of an `ExternalPid`
fn is_remote_pid(self) -> bool {
Self::Encoding::is_remote_pid(self.value())
}
/// Returns `true` if the encoded value is a pointer to an `ExternalPid`
fn is_boxed_remote_pid(self) -> bool {
Self::Encoding::is_boxed_remote_pid(self.value())
}
/// Returns `true` if the encoded value is a `Port`
fn is_local_port(self) -> bool {
Self::Encoding::is_local_port(self.value())
}
/// Returns `true` if the encoded value is the header of an `ExternalPort`
fn is_remote_port(self) -> bool {
Self::Encoding::is_remote_port(self.value())
}
/// Returns `true` if the encoded value is a pointer to an `ExternalPort`
fn is_boxed_remote_port(self) -> bool {
Self::Encoding::is_boxed_remote_port(self.value())
}
/// Returns `true` if the encoded value is the header of a `Reference`
fn is_local_reference(self) -> bool {
Self::Encoding::is_local_reference(self.value())
}
/// Returns `true` if the encoded value is a pointer to a `Reference`
fn is_boxed_local_reference(self) -> bool {
Self::Encoding::is_boxed_local_reference(self.value())
}
/// Returns `true` if the encoded value is the header of a `ExternalReference`
fn is_remote_reference(self) -> bool {
Self::Encoding::is_remote_reference(self.value())
}
/// Returns `true` if the encoded value is a pointer to a `ExternalReference`
fn is_boxed_remote_reference(self) -> bool {
Self::Encoding::is_boxed_remote_reference(self.value())
}
/// Returns `true` if the encoded value is the header of a `Resource`
fn is_resource_reference(self) -> bool {
Self::Encoding::is_resource_reference(self.value())
}
/// Returns `true` if the encoded value is a pointer to a `Resource`
fn is_boxed_resource_reference(self) -> bool {
Self::Encoding::is_boxed_resource_reference(self.value())
}
/// Returns `true` if the encoded value is the header of a `ProcBin`
fn is_procbin(self) -> bool {
Self::Encoding::is_procbin(self.value())
}
/// Returns `true` if the encoded value is a pointer to a `ProcBin`
fn is_boxed_procbin(self) -> bool {
Self::Encoding::is_boxed_procbin(self.value())
}
/// Returns `true` if the encoded value is the header of a `HeapBin`
fn is_heapbin(self) -> bool {
Self::Encoding::is_heapbin(self.value())
}
/// Returns `true` if the encoded value is a pointer to a `HeapBin`
fn is_boxed_heapbin(self) -> bool {
Self::Encoding::is_boxed_heapbin(self.value())
}
/// Returns `true` if the encoded value is the header of a `SubBinary`
fn is_subbinary(self) -> bool {
Self::Encoding::is_subbinary(self.value())
}
/// Returns `true` if the encoded value is a pointer to a `SubBinary`
fn is_boxed_subbinary(self) -> bool {
Self::Encoding::is_boxed_subbinary(self.value())
}
/// Returns `true` if the encoded value is the header of a `MatchContext`
fn is_match_context(self) -> bool {
Self::Encoding::is_match_context(self.value())
}
/// Returns `true` if the encoded value is a pointer to a `MatchContext`
fn is_boxed_match_context(self) -> bool {
Self::Encoding::is_boxed_match_context(self.value())
}
/// Returns `true` if the encoded value is the header of a `Closure`
fn is_function(self) -> bool {
Self::Encoding::is_function(self.value())
}
/// Returns `true` if the encoded value is a pointer to a `Tuple`
fn is_boxed_function(self) -> bool {
Self::Encoding::is_boxed_function(self.value())
}
/// Returns `true` if this term is a bitstring type,
/// where the number of bits is evenly divisible by 8 (i.e. one byte)
fn is_binary(&self) -> bool {
match self.decode().expect("invalid term") {
TypedTerm::HeapBinary(_) | TypedTerm::ProcBin(_) | TypedTerm::BinaryLiteral(_) => true,
TypedTerm::SubBinary(bin) => bin.partial_byte_bit_len() == 0,
TypedTerm::MatchContext(bin) => bin.partial_byte_bit_len() == 0,
_ => false,
}
}
/// Returns `true` if this term is a bitstring type
fn is_bitstring(&self) -> bool {
match self.decode().expect("invalid term") {
TypedTerm::HeapBinary(_)
| TypedTerm::ProcBin(_)
| TypedTerm::BinaryLiteral(_)
| TypedTerm::SubBinary(_)
| TypedTerm::MatchContext(_) => true,
_ => false,
}
}
/// Returns true if this term is a pid type
fn is_pid(&self) -> bool {
if self.is_local_pid() {
return true;
}
match self.decode() {
Ok(TypedTerm::ExternalPid(_)) => true,
_ => false,
}
}
/// Returns true if this term is a port type
fn is_port(&self) -> bool {
if self.is_local_port() {
return true;
}
match self.decode() {
Ok(TypedTerm::ExternalPort(_)) => true,
_ => false,
}
}
/// Returns true if this term is a reference type
fn is_reference(&self) -> bool {
match self.decode() {
Ok(TypedTerm::Reference(_))
| Ok(TypedTerm::ExternalReference(_))
| Ok(TypedTerm::ResourceReference(_)) => true,
_ => false,
}
}
/// Returns true if this is a term that is valid for use as an argument
/// in the runtime, as a key in a datstructure, or other position in which
/// an immediate or a reference is required or desirable
fn is_valid(&self) -> bool {
Self::Encoding::is_valid(self.value())
}
/// Returns the size in bytes of the term in memory
fn sizeof(&self) -> usize {
Self::Encoding::sizeof(self.value())
}
/// Returns the arity of this term, which reflects the number of words of data
/// following this term in memory.
///
/// Returns zero for immediates/pointers
fn arity(&self) -> usize {
Self::Encoding::arity(self.value())
}
}
impl CloneToProcess for Term {
fn clone_to_process(&self, process: &crate::erts::process::Process) -> Term {
if self.is_immediate() || self.is_literal() {
*self
} else if self.is_boxed() || self.is_non_empty_list() {
// There is no need to clone the actual object to this process's heap if it is already
// there, just clone a pointer.
let ptr: *mut Term = self.dyn_cast();
if process.acquire_heap().contains(ptr) {
// Just return self
*self
} else {
// We're good to clone
let tt = self.decode().unwrap();
tt.clone_to_process(process)
}
} else {
panic!("clone_to_process called on invalid term type: {:?}", self);
}
}
fn clone_to_heap<A>(&self, heap: &mut A) -> AllocResult<Term>
where
A: ?Sized + TermAlloc,
{
if self.is_immediate() || self.is_literal() {
Ok(*self)
} else if self.is_boxed() || self.is_non_empty_list() {
// There is no need to clone the actual object to this
// heap if it is already there, just clone a pointer
let ptr: *mut Term = self.dyn_cast();
if heap.contains(ptr) {
// Just return self
Ok(*self)
} else {
// We're good to clone
let tt = self.decode().unwrap();
tt.clone_to_heap(heap)
}
} else {
panic!("clone_to_heap called on invalid term type: {:?}", self);
}
}
fn clone_to_fragment(&self) -> AllocResult<(Term, NonNull<HeapFragment>)> {
let tt = self.decode().unwrap();
tt.clone_to_fragment()
}
fn size_in_words(&self) -> usize {
if self.is_none() {
return 1;
}
let tt = self.decode().unwrap();
tt.size_in_words()
}
}
|
use anyhow::{anyhow, Context, Result};
use std::{
fs::File,
io::Write,
path::{Path, PathBuf},
};
pub fn file_name(path: &Path) -> Result<&str> {
path.file_stem()
.ok_or_else(|| anyhow!("No file stem found"))?
.to_str()
.ok_or_else(|| anyhow!("Can't convert file stem to string"))
}
pub fn combine_path(directory: &Path, file_name: &str, extension: &str) -> Result<PathBuf> {
Ok(directory.join(format!("{file_name}.{extension}")))
}
pub fn write_file(target: PathBuf, data: Vec<u8>) -> Result<File> {
let mut buffer = File::create(&target)
.with_context(|| format!("Could not create file: {}", &target.display()))?;
buffer
.write(data.as_slice())
.with_context(|| format!("Could not write data to file: {}", &target.display()))?;
Ok(buffer)
}
|
use async_trait::async_trait;
use serde::de::DeserializeOwned;
use serde::export::fmt::Display;
use serde::Serialize;
use serde_json::{Map, Value};
use rbatis_core::convert::StmtConvert;
use rbatis_core::db::DriverType;
use rbatis_core::Error;
use rbatis_core::Result;
use crate::plugin::page::{IPageRequest, Page};
use crate::rbatis::Rbatis;
use crate::sql::Date;
use crate::utils::string_util::to_snake_name;
use crate::wrapper::Wrapper;
/// DB Table model trait
pub trait CRUDEnable: Send + Sync + Serialize + DeserializeOwned {
/// your table id type,for example:
/// IdType = String
/// IdType = i32
///
type IdType: Send + Sync + DeserializeOwned + Serialize + Display;
/// get table name,default is type name for snake name
///
/// for Example: struct BizActivity{} => "biz_activity"
/// also. you can overwrite this method return ture name
///
/// impl CRUDEnable for BizActivity{
/// table_name() -> String{
/// "biz_activity".to_string()
/// }
/// }
///
///
///
#[inline]
fn table_name() -> String {
let type_name = std::any::type_name::<Self>();
let mut name = type_name.to_string();
let names: Vec<&str> = name.split("::").collect();
name = names.get(names.len() - 1).unwrap().to_string();
return to_snake_name(&name);
}
/// get table fields string
///
/// for Example:
/// "create_time,delete_flag,h5_banner_img,h5_link,id,name,pc_banner_img,pc_link,remark,sort,status,version"
///
/// you also can impl this method for static string
///
#[inline]
fn table_fields() -> String {
let bean: serde_json::Result<Self> = serde_json::from_str("{}");
if bean.is_err() {
//if json decode fail,return '*'
return " * ".to_string();
}
let v = serde_json::to_value(&bean.unwrap()).unwrap_or(serde_json::Value::Null);
if !v.is_object() {
//if json decode fail,return '*'
return " * ".to_string();
}
let m = v.as_object().unwrap();
let mut fields = String::new();
for (k, _) in m {
fields.push_str(k);
fields.push_str(",");
}
fields.pop();
return format!(" {} ", fields);
}
/// make an Map<table_field,value>
fn make_field_value_map<C>(db_type: &DriverType, arg: &C) -> Result<serde_json::Map<String, Value>>
where C: CRUDEnable {
let json = serde_json::to_value(arg).unwrap_or(serde_json::Value::Null);
if json.eq(&serde_json::Value::Null) {
return Err(Error::from("[rbaits] to_value_map() fail!"));
}
if !json.is_object() {
return Err(Error::from("[rbaits] to_value_map() fail,data is not an object!"));
}
return Ok(json.as_object().unwrap().to_owned());
}
///make fields
fn make_fields(map: &serde_json::Map<String, Value>) -> Result<String> {
let mut sql = String::new();
for (k, v) in map {
sql = sql + k.as_str() + ",";
}
sql = sql.trim_end_matches(",").to_string();
return Ok(sql);
}
///return (sql,args)
fn make_sql_arg(index: &mut usize, db_type: &DriverType, map: &serde_json::Map<String, serde_json::Value>) -> Result<(String, Vec<serde_json::Value>)> {
let mut sql = String::new();
let mut arr = vec![];
for (k, v) in map {
//date convert
if (k.contains("time") || k.contains("date")) && v.is_string() {
let (new_sql, new_value) = db_type.date_convert(v, *index)?;
sql = sql + new_sql.as_str() + ",";
arr.push(new_value);
} else {
sql = sql + db_type.stmt_convert(*index).as_str() + ",";
arr.push(v.to_owned());
}
*index += 1;
}
sql.pop();//remove ','
return Ok((sql, arr));
}
}
impl<T> CRUDEnable for Option<T> where T: CRUDEnable {
type IdType = T::IdType;
///Bean's table name
fn table_name() -> String {
T::table_name()
}
///Bean's table fields
fn table_fields() -> String {
T::table_fields()
}
///
fn make_field_value_map<C>(db_type: &DriverType, arg: &C) -> Result<Map<String, Value>> where C: CRUDEnable {
T::make_field_value_map(db_type, arg)
}
fn make_fields(map: &Map<String, Value>) -> Result<String> {
T::make_fields(map)
}
///return sql,args
fn make_sql_arg(index: &mut usize, db_type: &DriverType, map: &Map<String, Value>) -> Result<(String, Vec<Value>)> {
T::make_sql_arg(index, db_type, map)
}
}
/// fetch id value
///
/// for example:
/// impl Id for BizActivity {
/// type IdType = String;
///
/// fn get_id(&self) -> Option<Self::IdType> {
/// self.id.clone()
/// }
/// }
/// let vec = vec![BizActivity {
/// id: Some("12312".to_string())
/// }];
/// let ids = vec.to_ids();
/// println!("{:?}", ids);
///
pub trait Id {
type IdType: Send + Sync + DeserializeOwned + Serialize + Display;
fn get_id(&self) -> Option<Self::IdType>;
}
/// fetch ids, must use Id trait together
pub trait Ids<C> where C: Id {
///get ids
fn to_ids(&self) -> Vec<C::IdType>;
}
impl<C> Ids<C> for Vec<C> where C: Id {
fn to_ids(&self) -> Vec<C::IdType> {
let mut vec = vec![];
for item in self {
let id = item.get_id();
if id.is_some() {
vec.push(id.unwrap());
}
}
vec
}
}
#[async_trait]
pub trait CRUD {
/// tx_id: Transaction id,default ""
async fn save<T>(&self, tx_id: &str, entity: &T) -> Result<u64> where T: CRUDEnable;
async fn save_batch<T>(&self, tx_id: &str, entity: &[T]) -> Result<u64> where T: CRUDEnable;
async fn remove_by_wrapper<T>(&self, tx_id: &str, w: &Wrapper) -> Result<u64> where T: CRUDEnable;
async fn remove_by_id<T>(&self, tx_id: &str, id: &T::IdType) -> Result<u64> where T: CRUDEnable;
async fn remove_batch_by_id<T>(&self, tx_id: &str, ids: &[T::IdType]) -> Result<u64> where T: CRUDEnable;
async fn update_by_wrapper<T>(&self, tx_id: &str, arg: &T, w: &Wrapper) -> Result<u64> where T: CRUDEnable;
async fn update_by_id<T>(&self, tx_id: &str, arg: &T) -> Result<u64> where T: CRUDEnable;
async fn update_batch_by_id<T>(&self, tx_id: &str, ids: &[T]) -> Result<u64> where T: CRUDEnable;
async fn fetch_by_wrapper<T>(&self, tx_id: &str, w: &Wrapper) -> Result<T> where T: CRUDEnable;
async fn fetch_by_id<T>(&self, tx_id: &str, id: &T::IdType) -> Result<T> where T: CRUDEnable;
async fn fetch_page_by_wrapper<T>(&self, tx_id: &str, w: &Wrapper, page: &dyn IPageRequest) -> Result<Page<T>> where T: CRUDEnable;
///fetch all record
async fn list<T>(&self, tx_id: &str) -> Result<Vec<T>> where T: CRUDEnable;
async fn list_by_wrapper<T>(&self, tx_id: &str, w: &Wrapper) -> Result<Vec<T>> where T: CRUDEnable;
async fn list_by_ids<T>(&self, tx_id: &str, ids: &[T::IdType]) -> Result<Vec<T>> where T: CRUDEnable;
}
#[async_trait]
impl CRUD for Rbatis {
/// save one entity to database
async fn save<T>(&self, tx_id: &str, entity: &T) -> Result<u64>
where T: CRUDEnable {
let map = T::make_field_value_map(&self.driver_type()?, entity)?;
let mut index = 0;
let (values, args) = T::make_sql_arg(&mut index, &self.driver_type()?, &map)?;
let sql = format!("INSERT INTO {} ({}) VALUES ({})", T::table_name(), T::make_fields(&map)?, values);
return self.exec_prepare(tx_id, sql.as_str(), &args).await;
}
/// save batch makes many value into only one sql. make sure your data not to long!
///
/// for Example:
/// rb.save_batch(&vec![activity]);
/// [rbatis] Exec ==> INSERT INTO biz_activity (id,name,version) VALUES ( ? , ? , ?),( ? , ? , ?)
///
///
async fn save_batch<T>(&self, tx_id: &str, args: &[T]) -> Result<u64> where T: CRUDEnable {
if args.is_empty() {
return Ok(0);
}
let mut value_arr = String::new();
let mut arg_arr = vec![];
let mut fields = "".to_string();
let mut field_index = 0;
for x in args {
let map = T::make_field_value_map(&self.driver_type()?, x)?;
if fields.is_empty() {
fields = T::make_fields(&map)?;
}
let (values, args) = T::make_sql_arg(&mut field_index, &self.driver_type()?, &map)?;
value_arr = value_arr + format!("({}),", values).as_str();
for x in args {
arg_arr.push(x);
}
}
value_arr.pop();//pop ','
let sql = format!("INSERT INTO {} ({}) VALUES {}", T::table_name(), fields, value_arr);
return self.exec_prepare(tx_id, sql.as_str(), &arg_arr).await;
}
async fn remove_by_wrapper<T>(&self, tx_id: &str, arg: &Wrapper) -> Result<u64> where T: CRUDEnable {
let where_sql = arg.sql.as_str();
let mut sql = String::new();
if self.logic_plugin.is_some() {
sql = self.logic_plugin.as_ref().unwrap().create_sql(&self.driver_type()?, T::table_name().as_str(), &T::table_fields().split(",").collect(), make_where_sql(where_sql).as_str())?;
} else {
sql = format!("DELETE FROM {} {}", T::table_name(), make_where_sql(where_sql));
}
return self.exec_prepare(tx_id, sql.as_str(), &arg.args).await;
}
async fn remove_by_id<T>(&self, tx_id: &str, id: &T::IdType) -> Result<u64> where T: CRUDEnable {
let mut sql = String::new();
if self.logic_plugin.is_some() {
sql = self.logic_plugin.as_ref().unwrap().create_sql(&self.driver_type()?, T::table_name().as_str(), &T::table_fields().split(",").collect(), format!(" WHERE id = {}", id).as_str())?;
} else {
sql = format!("DELETE FROM {} WHERE id = {}", T::table_name(), id);
}
return self.exec_prepare(tx_id, sql.as_str(), &vec![]).await;
}
///remove batch id
/// for Example :
/// rb.remove_batch_by_id::<BizActivity>(&["1".to_string(),"2".to_string()]).await;
/// [rbatis] Exec ==> DELETE FROM biz_activity WHERE id IN ( ? , ? )
///
async fn remove_batch_by_id<T>(&self, tx_id: &str, ids: &[T::IdType]) -> Result<u64> where T: CRUDEnable {
if ids.is_empty() {
return Ok(0);
}
let w = Wrapper::new(&self.driver_type()?).and().in_array("id", &ids).check()?;
return self.remove_by_wrapper::<T>(tx_id, &w).await;
}
async fn update_by_wrapper<T>(&self, tx_id: &str, arg: &T, w: &Wrapper) -> Result<u64> where T: CRUDEnable {
let mut args = vec![];
let map = T::make_field_value_map(&self.driver_type()?, arg)?;
let driver_type = &self.driver_type()?;
let mut sets = String::new();
for (k, v) in map {
//filter null
if v.is_null() {
continue;
}
//filter id
if k.eq("id") {
continue;
}
sets.push_str(format!(" {} = {},", k, driver_type.stmt_convert(args.len())).as_str());
args.push(v);
}
sets.pop();
let mut wrapper = Wrapper::new(&self.driver_type()?);
wrapper.sql = format!("UPDATE {} SET {}", T::table_name(), sets);
wrapper.args = args;
if !w.sql.is_empty() {
wrapper.sql.push_str(" WHERE ");
wrapper = wrapper.right_link_wrapper(w).check()?;
}
return self.exec_prepare(tx_id, wrapper.sql.as_str(), &wrapper.args).await;
}
async fn update_by_id<T>(&self, tx_id: &str, arg: &T) -> Result<u64> where T: CRUDEnable {
let args = T::make_field_value_map(&self.driver_type()?, arg)?;
let id_field = args.get("id");
if id_field.is_none() {
return Err(Error::from("[rbaits] arg not have \"id\" field! "));
}
self.update_by_wrapper(tx_id, arg, Wrapper::new(&self.driver_type()?).eq("id", id_field.unwrap())).await
}
async fn update_batch_by_id<T>(&self, tx_id: &str, args: &[T]) -> Result<u64> where T: CRUDEnable {
let mut updates = 0;
for x in args {
updates += self.update_by_id(tx_id, x).await?
}
Ok(updates)
}
async fn fetch_by_wrapper<T>(&self, tx_id: &str, w: &Wrapper) -> Result<T> where T: CRUDEnable {
let sql = make_select_sql::<T>(&self, w)?;
return self.fetch_prepare(tx_id, sql.as_str(), &w.args).await;
}
async fn fetch_by_id<T>(&self, tx_id: &str, id: &T::IdType) -> Result<T> where T: CRUDEnable {
let w = Wrapper::new(&self.driver_type()?).eq("id", id).check()?;
return self.fetch_by_wrapper(tx_id, &w).await;
}
async fn list_by_wrapper<T>(&self, tx_id: &str, w: &Wrapper) -> Result<Vec<T>> where T: CRUDEnable {
let sql = make_select_sql::<T>(&self, w)?;
return self.fetch_prepare(tx_id, sql.as_str(), &w.args).await;
}
async fn list<T>(&self, tx_id: &str) -> Result<Vec<T>> where T: CRUDEnable {
return self.list_by_wrapper(tx_id, &Wrapper::new(&self.driver_type()?)).await;
}
async fn list_by_ids<T>(&self, tx_id: &str, ids: &[T::IdType]) -> Result<Vec<T>> where T: CRUDEnable {
let w = Wrapper::new(&self.driver_type()?).in_array("id", ids).check()?;
return self.list_by_wrapper(tx_id, &w).await;
}
async fn fetch_page_by_wrapper<T>(&self, tx_id: &str, w: &Wrapper, page: &dyn IPageRequest) -> Result<Page<T>> where T: CRUDEnable {
let sql = make_select_sql::<T>(&self, w)?;
self.fetch_page(tx_id, sql.as_str(), &w.args, page).await
}
}
fn make_where_sql(arg: &str) -> String {
let mut where_sql = arg.to_string();
where_sql = where_sql.trim_start().trim_start_matches("AND ").trim_start_matches("OR ").to_string();
format!(" WHERE {} ", where_sql)
}
fn make_select_sql<T>(rb: &Rbatis, w: &Wrapper) -> Result<String> where T: CRUDEnable {
let fields = T::table_fields();
let where_sql = String::new();
let mut sql = String::new();
if rb.logic_plugin.is_some() {
let mut where_sql = w.sql.clone();
if !where_sql.is_empty() {
where_sql = " AND ".to_string() + where_sql.as_str();
}
sql = format!("SELECT {} FROM {} WHERE {} = {} {}", fields, T::table_name(), rb.logic_plugin.as_ref().unwrap().column(), rb.logic_plugin.as_ref().unwrap().un_deleted(), where_sql);
} else {
let mut where_sql = w.sql.clone();
if !where_sql.is_empty() {
where_sql = " WHERE ".to_string() + where_sql.as_str();
}
sql = format!("SELECT {} FROM {} {}", fields, T::table_name(), where_sql);
}
Ok(sql)
}
mod test {
use chrono::{DateTime, Utc};
use fast_log::log::RuntimeType;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use serde::Serialize;
use rbatis_core::Error;
use crate::crud::{CRUD, CRUDEnable, Id, Ids};
use crate::plugin::logic_delete::RbatisLogicDeletePlugin;
use crate::plugin::page::{Page, PageRequest};
use crate::rbatis::Rbatis;
use crate::wrapper::Wrapper;
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct BizActivity {
pub id: Option<String>,
pub name: Option<String>,
pub pc_link: Option<String>,
pub h5_link: Option<String>,
pub pc_banner_img: Option<String>,
pub h5_banner_img: Option<String>,
pub sort: Option<String>,
pub status: Option<i32>,
pub remark: Option<String>,
pub create_time: Option<String>,
pub version: Option<i32>,
pub delete_flag: Option<i32>,
}
/// 必须实现 CRUDEntity接口,如果表名 不正确,可以重写 fn table_name() -> String 方法!
impl CRUDEnable for BizActivity {
type IdType = String;
}
impl Id for BizActivity {
type IdType = String;
fn get_id(&self) -> Option<Self::IdType> {
self.id.clone()
}
}
#[test]
pub fn test_ids() {
let vec = vec![BizActivity {
id: Some("12312".to_string()),
name: None,
pc_link: None,
h5_link: None,
pc_banner_img: None,
h5_banner_img: None,
sort: None,
status: Some(1),
remark: None,
create_time: Some("2020-02-09 00:00:00".to_string()),
version: Some(1),
delete_flag: Some(1),
}];
let ids = vec.to_ids();
println!("{:?}", ids);
}
#[test]
pub fn test_save() {
async_std::task::block_on(async {
let activity = BizActivity {
id: Some("12312".to_string()),
name: None,
pc_link: None,
h5_link: None,
pc_banner_img: None,
h5_banner_img: None,
sort: None,
status: Some(1),
remark: None,
create_time: Some("2020-02-09 00:00:00".to_string()),
version: Some(1),
delete_flag: Some(1),
};
fast_log::log::init_log("requests.log", &RuntimeType::Std);
let rb = Rbatis::new();
rb.link("mysql://root:123456@localhost:3306/test").await.unwrap();
let r = rb.save("", &activity).await;
if r.is_err() {
println!("{}", r.err().unwrap().to_string());
}
});
}
#[test]
pub fn test_save_batch() {
async_std::task::block_on(async {
let activity = BizActivity {
id: Some("12312".to_string()),
name: None,
pc_link: None,
h5_link: None,
pc_banner_img: None,
h5_banner_img: None,
sort: None,
status: Some(1),
remark: None,
create_time: Some("2020-02-09 00:00:00".to_string()),
version: Some(1),
delete_flag: Some(1),
};
let args = vec![activity.clone(), activity];
fast_log::log::init_log("requests.log", &RuntimeType::Std);
let rb = Rbatis::new();
rb.link("mysql://root:123456@localhost:3306/test").await.unwrap();
let r = rb.save_batch("", &args).await;
if r.is_err() {
println!("{}", r.err().unwrap().to_string());
}
});
}
#[test]
pub fn test_remove_batch_by_id() {
async_std::task::block_on(async {
fast_log::log::init_log("requests.log", &RuntimeType::Std);
let mut rb = Rbatis::new();
rb.logic_plugin = Some(Box::new(RbatisLogicDeletePlugin::new("delete_flag")));
rb.link("mysql://root:123456@localhost:3306/test").await.unwrap();
let r = rb.remove_batch_by_id::<BizActivity>("", &["1".to_string(), "2".to_string()]).await;
if r.is_err() {
println!("{}", r.err().unwrap().to_string());
}
});
}
#[test]
pub fn test_remove_by_id() {
async_std::task::block_on(async {
fast_log::log::init_log("requests.log", &RuntimeType::Std);
let mut rb = Rbatis::new();
//设置 逻辑删除插件
rb.logic_plugin = Some(Box::new(RbatisLogicDeletePlugin::new("delete_flag")));
rb.link("mysql://root:123456@localhost:3306/test").await.unwrap();
let r = rb.remove_by_id::<BizActivity>("", &"1".to_string()).await;
if r.is_err() {
println!("{}", r.err().unwrap().to_string());
}
});
}
#[test]
pub fn test_update_by_wrapper() {
async_std::task::block_on(async {
fast_log::log::init_log("requests.log", &RuntimeType::Std);
let mut rb = Rbatis::new();
//设置 逻辑删除插件
rb.logic_plugin = Some(Box::new(RbatisLogicDeletePlugin::new("delete_flag")));
rb.link("mysql://root:123456@localhost:3306/test").await.unwrap();
let activity = BizActivity {
id: Some("12312".to_string()),
name: None,
pc_link: None,
h5_link: None,
pc_banner_img: None,
h5_banner_img: None,
sort: None,
status: Some(1),
remark: None,
create_time: Some("2020-02-09 00:00:00".to_string()),
version: Some(1),
delete_flag: Some(1),
};
let w = Wrapper::new(&rb.driver_type().unwrap()).eq("id", "12312").check().unwrap();
let r = rb.update_by_wrapper("", &activity, &w).await;
if r.is_err() {
println!("{}", r.err().unwrap().to_string());
}
});
}
#[test]
pub fn test_update_by_id() {
async_std::task::block_on(async {
fast_log::log::init_log("requests.log", &RuntimeType::Std);
let mut rb = Rbatis::new();
//设置 逻辑删除插件
rb.logic_plugin = Some(Box::new(RbatisLogicDeletePlugin::new("delete_flag")));
rb.link("mysql://root:123456@localhost:3306/test").await.unwrap();
let activity = BizActivity {
id: Some("12312".to_string()),
name: None,
pc_link: None,
h5_link: None,
pc_banner_img: None,
h5_banner_img: None,
sort: None,
status: Some(1),
remark: None,
create_time: Some("2020-02-09 00:00:00".to_string()),
version: Some(1),
delete_flag: Some(1),
};
let r = rb.update_by_id("", &activity).await;
if r.is_err() {
println!("{}", r.err().unwrap().to_string());
}
});
}
#[test]
pub fn test_fetch_by_wrapper() {
async_std::task::block_on(async {
fast_log::log::init_log("requests.log", &RuntimeType::Std);
let mut rb = Rbatis::new();
//设置 逻辑删除插件
rb.logic_plugin = Some(Box::new(RbatisLogicDeletePlugin::new("delete_flag")));
rb.link("mysql://root:123456@localhost:3306/test").await.unwrap();
let w = Wrapper::new(&rb.driver_type().unwrap()).eq("id", "12312").check().unwrap();
let r: Result<BizActivity, Error> = rb.fetch_by_wrapper("", &w).await;
if r.is_err() {
println!("{}", r.err().unwrap().to_string());
}
});
}
#[test]
pub fn test_fetch_page_by_wrapper() {
async_std::task::block_on(async {
fast_log::log::init_log("requests.log", &RuntimeType::Std);
let mut rb = Rbatis::new();
//设置 逻辑删除插件
rb.logic_plugin = Some(Box::new(RbatisLogicDeletePlugin::new("delete_flag")));
rb.link("mysql://root:123456@localhost:3306/test").await.unwrap();
let w = Wrapper::new(&rb.driver_type().unwrap()).check().unwrap();
let r: Page<BizActivity> = rb.fetch_page_by_wrapper("", &w, &PageRequest::new(1, 20)).await.unwrap();
println!("{}", serde_json::to_string(&r).unwrap());
});
}
} |
/*!
RDB中各项Redis数据相关的结构体定义,以及RDB解析相关的代码在此模块下
*/
use core::result;
use std::any::Any;
use std::cmp;
use std::collections::BTreeMap;
use std::fmt::{Debug, Error, Formatter};
use std::io::{Cursor, Read, Result};
use std::sync::atomic::{AtomicBool, Ordering};
use byteorder::{BigEndian, LittleEndian, ReadBytesExt};
use log::info;
use crate::cmd::connection::SELECT;
use crate::cmd::Command;
use crate::iter::{IntSetIter, Iter, QuickListIter, SortedSetIter, StrValIter, ZipListIter, ZipMapIter};
use crate::{lzf, to_string, Event, EventHandler, ModuleParser, RDBParser};
use std::cell::RefCell;
use std::f64::{INFINITY, NAN, NEG_INFINITY};
use std::iter::FromIterator;
use std::rc::Rc;
use std::str::FromStr;
use std::sync::Arc;
/// 一些解析RDB数据的方法
pub trait RDBDecode: Read {
/// 读取redis响应中下一条数据的长度
fn read_length(&mut self) -> Result<(isize, bool)> {
let byte = self.read_u8()?;
let _type = (byte & 0xC0) >> 6;
let mut result = -1;
let mut is_encoded = false;
if _type == RDB_ENCVAL {
result = (byte & 0x3F) as isize;
is_encoded = true;
} else if _type == RDB_6BITLEN {
result = (byte & 0x3F) as isize;
} else if _type == RDB_14BITLEN {
let next_byte = self.read_u8()?;
result = (((byte as u16 & 0x3F) << 8) | next_byte as u16) as isize;
} else if byte == RDB_32BITLEN {
result = self.read_integer(4, true)?;
} else if byte == RDB_64BITLEN {
result = self.read_integer(8, true)?;
};
Ok((result, is_encoded))
}
/// 从流中读取一个Integer
fn read_integer(&mut self, size: isize, is_big_endian: bool) -> Result<isize> {
let mut buff = vec![0; size as usize];
self.read_exact(&mut buff)?;
let mut cursor = Cursor::new(&buff);
if is_big_endian {
if size == 2 {
return Ok(cursor.read_i16::<BigEndian>()? as isize);
} else if size == 4 {
return Ok(cursor.read_i32::<BigEndian>()? as isize);
} else if size == 8 {
return Ok(cursor.read_i64::<BigEndian>()? as isize);
};
} else {
if size == 2 {
return Ok(cursor.read_i16::<LittleEndian>()? as isize);
} else if size == 4 {
return Ok(cursor.read_i32::<LittleEndian>()? as isize);
} else if size == 8 {
return Ok(cursor.read_i64::<LittleEndian>()? as isize);
};
}
panic!("Invalid integer size: {}", size)
}
/// 从流中读取一个string
fn read_string(&mut self) -> Result<Vec<u8>> {
let (length, is_encoded) = self.read_length()?;
if is_encoded {
match length {
RDB_ENC_INT8 => {
let int = self.read_i8()?;
return Ok(int.to_string().into_bytes());
}
RDB_ENC_INT16 => {
let int = self.read_integer(2, false)?;
return Ok(int.to_string().into_bytes());
}
RDB_ENC_INT32 => {
let int = self.read_integer(4, false)?;
return Ok(int.to_string().into_bytes());
}
RDB_ENC_LZF => {
let (compressed_len, _) = self.read_length()?;
let (origin_len, _) = self.read_length()?;
let mut compressed = vec![0; compressed_len as usize];
self.read_exact(&mut compressed)?;
let mut origin = vec![0; origin_len as usize];
lzf::decompress(&mut compressed, compressed_len, &mut origin, origin_len);
return Ok(origin);
}
_ => panic!("Invalid string length: {}", length),
};
};
let mut buff = vec![0; length as usize];
self.read_exact(&mut buff)?;
Ok(buff)
}
/// 从流中读取一个double
fn read_double(&mut self) -> Result<f64> {
let len = self.read_u8()?;
return match len {
255 => Ok(NEG_INFINITY),
254 => Ok(INFINITY),
253 => Ok(NAN),
_ => {
let mut buff = vec![0; len as usize];
self.read_exact(&mut buff)?;
let score_str = to_string(buff);
let score = score_str.parse::<f64>().unwrap();
Ok(score)
}
};
}
}
impl<R: Read + ?Sized> RDBDecode for R {}
pub(crate) struct DefaultRDBParser {
pub(crate) running: Arc<AtomicBool>,
pub(crate) module_parser: Option<Rc<RefCell<dyn ModuleParser>>>,
}
impl RDBParser for DefaultRDBParser {
fn parse(&mut self, input: &mut dyn Read, _: i64, event_handler: &mut dyn EventHandler) -> Result<()> {
event_handler.handle(Event::RDB(Object::BOR));
let mut bytes = vec![0; 5];
// 开头5个字节: REDIS
input.read_exact(&mut bytes)?;
// 4个字节: rdb版本
input.read_exact(&mut bytes[..=3])?;
let rdb_version = String::from_utf8_lossy(&bytes[..=3]);
let rdb_version = rdb_version.parse::<isize>().unwrap();
let mut db = 0;
while self.running.load(Ordering::Relaxed) {
let mut meta = Meta {
db,
expire: None,
evict: None,
};
let data_type = input.read_u8()?;
match data_type {
RDB_OPCODE_AUX => {
let field_name = input.read_string()?;
let field_val = input.read_string()?;
let field_name = to_string(field_name);
let field_val = to_string(field_val);
info!("{}:{}", field_name, field_val);
}
RDB_OPCODE_SELECTDB => {
let (_db, _) = input.read_length()?;
meta.db = _db;
db = _db;
let cmd = SELECT { db: _db as i32 };
event_handler.handle(Event::AOF(Command::SELECT(&cmd)));
}
RDB_OPCODE_RESIZEDB => {
let (total, _) = input.read_length()?;
info!("db[{}] total keys: {}", db, total);
let (expired, _) = input.read_length()?;
info!("db[{}] expired keys: {}", db, expired);
}
RDB_OPCODE_EXPIRETIME | RDB_OPCODE_EXPIRETIME_MS => {
if data_type == RDB_OPCODE_EXPIRETIME_MS {
let expired_time = input.read_integer(8, false)?;
meta.expire = Option::Some((ExpireType::Millisecond, expired_time as i64));
} else {
let expired_time = input.read_integer(4, false)?;
meta.expire = Option::Some((ExpireType::Second, expired_time as i64));
}
let value_type = input.read_u8()?;
match value_type {
RDB_OPCODE_FREQ => {
let val = input.read_u8()?;
let value_type = input.read_u8()?;
meta.evict = Option::Some((EvictType::LFU, val as i64));
self.read_object(input, value_type, event_handler, &meta)?;
}
RDB_OPCODE_IDLE => {
let (val, _) = input.read_length()?;
let value_type = input.read_u8()?;
meta.evict = Option::Some((EvictType::LRU, val as i64));
self.read_object(input, value_type, event_handler, &meta)?;
}
_ => {
self.read_object(input, value_type, event_handler, &meta)?;
}
}
}
RDB_OPCODE_FREQ => {
let val = input.read_u8()?;
let value_type = input.read_u8()?;
meta.evict = Option::Some((EvictType::LFU, val as i64));
self.read_object(input, value_type, event_handler, &meta)?;
}
RDB_OPCODE_IDLE => {
let (val, _) = input.read_length()?;
meta.evict = Option::Some((EvictType::LRU, val as i64));
let value_type = input.read_u8()?;
self.read_object(input, value_type, event_handler, &meta)?;
}
RDB_OPCODE_MODULE_AUX => {
input.read_length()?;
self.rdb_load_check_module_value(input)?;
}
RDB_OPCODE_EOF => {
if rdb_version >= 5 {
input.read_integer(8, true)?;
}
break;
}
_ => {
self.read_object(input, data_type, event_handler, &meta)?;
}
};
}
event_handler.handle(Event::RDB(Object::EOR));
Ok(())
}
}
impl DefaultRDBParser {
// 根据传入的数据类型,从流中读取对应类型的数据
fn read_object(
&mut self, input: &mut dyn Read, value_type: u8, event_handler: &mut dyn EventHandler, meta: &Meta,
) -> Result<()> {
match value_type {
RDB_TYPE_STRING => {
let key = input.read_string()?;
let value = input.read_string()?;
event_handler.handle(Event::RDB(Object::String(KeyValue {
key: &key,
value: &value,
meta,
})));
}
RDB_TYPE_LIST | RDB_TYPE_SET => {
let key = input.read_string()?;
let (count, _) = input.read_length()?;
let mut iter = StrValIter { count, input };
let mut has_more = true;
while has_more {
let mut val = Vec::new();
for _ in 0..BATCH_SIZE {
if let Ok(next_val) = iter.next() {
val.push(next_val);
} else {
has_more = false;
break;
}
}
if !val.is_empty() {
if value_type == RDB_TYPE_LIST {
event_handler.handle(Event::RDB(Object::List(List {
key: &key,
values: &val,
meta,
})));
} else {
event_handler.handle(Event::RDB(Object::Set(Set {
key: &key,
members: &val,
meta,
})));
}
}
}
}
RDB_TYPE_ZSET => {
let key = input.read_string()?;
let (count, _) = input.read_length()?;
let mut iter = SortedSetIter { count, v: 1, input };
let mut has_more = true;
while has_more {
let mut val = Vec::new();
for _ in 0..BATCH_SIZE {
if let Ok(next_val) = iter.next() {
val.push(next_val);
} else {
has_more = false;
break;
}
}
if !val.is_empty() {
event_handler.handle(Event::RDB(Object::SortedSet(SortedSet {
key: &key,
items: &val,
meta,
})));
}
}
}
RDB_TYPE_ZSET_2 => {
let key = input.read_string()?;
let (count, _) = input.read_length()?;
let mut iter = SortedSetIter { count, v: 2, input };
let mut has_more = true;
while has_more {
let mut val = Vec::new();
for _ in 0..BATCH_SIZE {
if let Ok(next_val) = iter.next() {
val.push(next_val);
} else {
has_more = false;
break;
}
}
if !val.is_empty() {
event_handler.handle(Event::RDB(Object::SortedSet(SortedSet {
key: &key,
items: &val,
meta,
})));
}
}
}
RDB_TYPE_HASH => {
let key = input.read_string()?;
let (count, _) = input.read_length()?;
let mut iter = StrValIter {
count: count * 2,
input,
};
let mut has_more = true;
while has_more {
let mut val = Vec::new();
for _ in 0..BATCH_SIZE {
let name;
let value;
if let Ok(next_val) = iter.next() {
name = next_val;
value = iter.next().expect("missing hash field value");
val.push(Field { name, value });
} else {
has_more = false;
break;
}
}
if !val.is_empty() {
event_handler.handle(Event::RDB(Object::Hash(Hash {
key: &key,
fields: &val,
meta,
})));
}
}
}
RDB_TYPE_HASH_ZIPMAP => {
let key = input.read_string()?;
let bytes = input.read_string()?;
let cursor = &mut Cursor::new(&bytes);
cursor.set_position(1);
let mut iter = ZipMapIter { has_more: true, cursor };
let mut has_more = true;
while has_more {
let mut fields = Vec::new();
for _ in 0..BATCH_SIZE {
if let Ok(field) = iter.next() {
fields.push(field);
} else {
has_more = false;
break;
}
}
if !fields.is_empty() {
event_handler.handle(Event::RDB(Object::Hash(Hash {
key: &key,
fields: &fields,
meta,
})));
}
}
}
RDB_TYPE_LIST_ZIPLIST => {
let key = input.read_string()?;
let bytes = input.read_string()?;
let cursor = &mut Cursor::new(bytes);
// 跳过ZL_BYTES和ZL_TAIL
cursor.set_position(8);
let count = cursor.read_u16::<LittleEndian>()? as isize;
let mut iter = ZipListIter { count, cursor };
let mut has_more = true;
while has_more {
let mut val = Vec::new();
for _ in 0..BATCH_SIZE {
if let Ok(next_val) = iter.next() {
val.push(next_val);
} else {
has_more = false;
break;
}
}
if !val.is_empty() {
event_handler.handle(Event::RDB(Object::List(List {
key: &key,
values: &val,
meta,
})));
}
}
}
RDB_TYPE_HASH_ZIPLIST => {
let key = input.read_string()?;
let bytes = input.read_string()?;
let cursor = &mut Cursor::new(bytes);
// 跳过ZL_BYTES和ZL_TAIL
cursor.set_position(8);
let count = cursor.read_u16::<LittleEndian>()? as isize;
let mut iter = ZipListIter { count, cursor };
let mut has_more = true;
while has_more {
let mut val = Vec::new();
for _ in 0..BATCH_SIZE {
let name;
let value;
if let Ok(next_val) = iter.next() {
name = next_val;
value = iter.next().expect("missing hash field value");
val.push(Field { name, value });
} else {
has_more = false;
break;
}
}
if !val.is_empty() {
event_handler.handle(Event::RDB(Object::Hash(Hash {
key: &key,
fields: &val,
meta,
})));
}
}
}
RDB_TYPE_ZSET_ZIPLIST => {
let key = input.read_string()?;
let bytes = input.read_string()?;
let cursor = &mut Cursor::new(bytes);
// 跳过ZL_BYTES和ZL_TAIL
cursor.set_position(8);
let count = cursor.read_u16::<LittleEndian>()? as isize;
let mut iter = ZipListIter { count, cursor };
let mut has_more = true;
while has_more {
let mut val = Vec::new();
for _ in 0..BATCH_SIZE {
let member;
let score: f64;
if let Ok(next_val) = iter.next() {
member = next_val;
let score_str = to_string(iter.next().expect("missing sorted set element's score"));
score = score_str.parse::<f64>().unwrap();
val.push(Item { member, score });
} else {
has_more = false;
break;
}
}
if !val.is_empty() {
event_handler.handle(Event::RDB(Object::SortedSet(SortedSet {
key: &key,
items: &val,
meta,
})));
}
}
}
RDB_TYPE_SET_INTSET => {
let key = input.read_string()?;
let bytes = input.read_string()?;
let mut cursor = Cursor::new(&bytes);
let encoding = cursor.read_i32::<LittleEndian>()?;
let length = cursor.read_u32::<LittleEndian>()?;
let mut iter = IntSetIter {
encoding,
count: length as isize,
cursor: &mut cursor,
};
let mut has_more = true;
while has_more {
let mut val = Vec::new();
for _ in 0..BATCH_SIZE {
if let Ok(next_val) = iter.next() {
val.push(next_val);
} else {
has_more = false;
break;
}
}
if !val.is_empty() {
event_handler.handle(Event::RDB(Object::Set(Set {
key: &key,
members: &val,
meta,
})));
}
}
}
RDB_TYPE_LIST_QUICKLIST => {
let key = input.read_string()?;
let (count, _) = input.read_length()?;
let mut iter = QuickListIter {
len: -1,
count,
input,
cursor: Option::None,
};
let mut has_more = true;
while has_more {
let mut val = Vec::new();
for _ in 0..BATCH_SIZE {
if let Ok(next_val) = iter.next() {
val.push(next_val);
} else {
has_more = false;
break;
}
}
if !val.is_empty() {
event_handler.handle(Event::RDB(Object::List(List {
key: &key,
values: &val,
meta,
})));
}
}
}
RDB_TYPE_MODULE | RDB_TYPE_MODULE_2 => {
let key = input.read_string()?;
let (module_id, _) = input.read_length()?;
let module_id = module_id as usize;
let mut array: [char; 9] = [' '; 9];
for i in 0..array.len() {
let i1 = 10 + (array.len() - 1 - i) * 6;
let i2 = (module_id >> i1 as usize) as usize;
let i3 = i2 & 63;
let chr = MODULE_SET.get(i3).unwrap();
array[i] = *chr;
}
let module_name: String = String::from_iter(array.iter());
let module_version: usize = module_id & 1023;
if self.module_parser.is_none() && value_type == RDB_TYPE_MODULE {
panic!("MODULE {}, version {} 无法解析", module_name, module_version);
}
if let Some(parser) = &mut self.module_parser {
let module: Box<dyn Module>;
if value_type == RDB_TYPE_MODULE_2 {
module = parser.borrow_mut().parse(input, &module_name, 2);
let (len, _) = input.read_length()?;
if len != 0 {
panic!(
"module '{}' that is not terminated by EOF marker, but {}",
&module_name, len
);
}
} else {
module = parser.borrow_mut().parse(input, &module_name, module_version);
}
event_handler.handle(Event::RDB(Object::Module(key, module, meta)));
} else {
// 没有parser,并且是Module 2类型的值,那就可以直接跳过了
self.rdb_load_check_module_value(input)?;
}
}
RDB_TYPE_STREAM_LISTPACKS => {
let key = input.read_string()?;
let stream = self.read_stream_list_packs(meta, input)?;
event_handler.handle(Event::RDB(Object::Stream(key, stream)));
}
_ => panic!("unknown data type: {}", value_type),
}
Ok(())
}
fn rdb_load_check_module_value(&mut self, input: &mut dyn Read) -> Result<()> {
loop {
let (op_code, _) = input.read_length()?;
if op_code == RDB_MODULE_OPCODE_EOF {
break;
}
if op_code == RDB_MODULE_OPCODE_SINT || op_code == RDB_MODULE_OPCODE_UINT {
input.read_length()?;
} else if op_code == RDB_MODULE_OPCODE_STRING {
input.read_string()?;
} else if op_code == RDB_MODULE_OPCODE_FLOAT {
input.read_exact(&mut [0; 4])?;
} else if op_code == RDB_MODULE_OPCODE_DOUBLE {
input.read_exact(&mut [0; 8])?;
}
}
Ok(())
}
fn read_stream_list_packs<'a>(&mut self, meta: &'a Meta, input: &mut dyn Read) -> Result<Stream<'a>> {
let mut entries: BTreeMap<ID, Entry> = BTreeMap::new();
let (length, _) = input.read_length()?;
for _ in 0..length {
let raw_id = input.read_string()?;
let mut cursor = Cursor::new(&raw_id);
let ms = read_long(&mut cursor, 8, false)?;
let seq = read_long(&mut cursor, 8, false)?;
let base_id = ID { ms, seq };
let raw_list_packs = input.read_string()?;
let mut list_pack = Cursor::new(&raw_list_packs);
list_pack.set_position(6);
let count = i64::from_str(&to_string(read_list_pack_entry(&mut list_pack)?)).unwrap();
let deleted = i64::from_str(&to_string(read_list_pack_entry(&mut list_pack)?)).unwrap();
let num_fields = i32::from_str(&to_string(read_list_pack_entry(&mut list_pack)?)).unwrap();
let mut tmp_fields = Vec::with_capacity(num_fields as usize);
for _ in 0..num_fields {
tmp_fields.push(read_list_pack_entry(&mut list_pack)?);
}
read_list_pack_entry(&mut list_pack)?;
let total = count + deleted;
for _ in 0..total {
let mut fields = BTreeMap::new();
let flag = i32::from_str(&to_string(read_list_pack_entry(&mut list_pack)?)).unwrap();
let ms = i64::from_str(&to_string(read_list_pack_entry(&mut list_pack)?)).unwrap();
let seq = i64::from_str(&to_string(read_list_pack_entry(&mut list_pack)?)).unwrap();
let id = ID {
ms: ms + base_id.ms,
seq: seq + base_id.seq,
};
let deleted = (flag & 1) != 0;
if (flag & 2) != 0 {
for i in 0..num_fields {
let value = read_list_pack_entry(&mut list_pack)?;
let field = tmp_fields.get(i as usize).unwrap().to_vec();
fields.insert(field, value);
}
entries.insert(id, Entry { id, deleted, fields });
} else {
let num_fields = i32::from_str(&to_string(read_list_pack_entry(&mut list_pack)?)).unwrap();
for _ in 0..num_fields {
let field = read_list_pack_entry(&mut list_pack)?;
let value = read_list_pack_entry(&mut list_pack)?;
fields.insert(field, value);
}
entries.insert(id, Entry { id, deleted, fields });
}
read_list_pack_entry(&mut list_pack)?;
}
let end = list_pack.read_u8()?;
if end != 255 {
panic!("listpack expect 255 but {}", end);
}
}
input.read_length()?;
input.read_length()?;
input.read_length()?;
let mut groups: Vec<Group> = Vec::new();
let (count, _) = input.read_length()?;
for _ in 0..count {
let name = input.read_string()?;
let (ms, _) = input.read_length()?;
let (seq, _) = input.read_length()?;
let group_last_id = ID {
ms: ms as i64,
seq: seq as i64,
};
groups.push(Group {
name,
last_id: group_last_id,
});
let (global_pel, _) = input.read_length()?;
for _ in 0..global_pel {
read_long(input, 8, false)?;
read_long(input, 8, false)?;
input.read_integer(8, false)?;
input.read_length()?;
}
let (consumer_count, _) = input.read_length()?;
for _ in 0..consumer_count {
input.read_string()?;
input.read_integer(8, false)?;
let (pel, _) = input.read_length()?;
for _ in 0..pel {
read_long(input, 8, false)?;
read_long(input, 8, false)?;
}
}
}
Ok(Stream { entries, groups, meta })
}
}
fn read_long(input: &mut dyn Read, length: i32, little_endian: bool) -> Result<i64> {
let mut r: i64 = 0;
for i in 0..length {
let v: i64 = input.read_u8()? as i64;
if little_endian {
r |= v << (i << 3) as i64;
} else {
r = (r << 8) | v;
}
}
Ok(r)
}
fn read_list_pack_entry(input: &mut dyn Read) -> Result<Vec<u8>> {
let special = input.read_u8()? as i32;
let skip: i32;
let mut bytes;
if (special & 0x80) == 0 {
skip = 1;
let value = special & 0x7F;
let value = value.to_string();
bytes = value.into_bytes();
} else if (special & 0xC0) == 0x80 {
let len = special & 0x3F;
skip = 1 + len as i32;
bytes = vec![0; len as usize];
input.read_exact(&mut bytes)?;
} else if (special & 0xE0) == 0xC0 {
skip = 2;
let next = input.read_u8()?;
let value = (((special & 0x1F) << 8) | next as i32) << 19 >> 19;
let value = value.to_string();
bytes = value.into_bytes();
} else if (special & 0xFF) == 0xF1 {
skip = 3;
let value = input.read_i16::<LittleEndian>()?;
let value = value.to_string();
bytes = value.into_bytes();
} else if (special & 0xFF) == 0xF2 {
skip = 4;
let value = input.read_i24::<LittleEndian>()?;
let value = value.to_string();
bytes = value.into_bytes();
} else if (special & 0xFF) == 0xF3 {
skip = 5;
let value = input.read_i32::<LittleEndian>()?;
let value = value.to_string();
bytes = value.into_bytes();
} else if (special & 0xFF) == 0xF4 {
skip = 9;
let value = input.read_i64::<LittleEndian>()?;
let value = value.to_string();
bytes = value.into_bytes();
} else if (special & 0xF0) == 0xE0 {
let next = input.read_u8()?;
let len = ((special & 0x0F) << 8) | next as i32;
skip = 2 + len as i32;
bytes = vec![0; len as usize];
input.read_exact(&mut bytes)?;
} else if (special & 0xFF) == 0xF0 {
let len = input.read_u32::<BigEndian>()?;
skip = 5 + len as i32;
bytes = vec![0; len as usize];
input.read_exact(&mut bytes)?;
} else {
panic!("{}", special)
}
if skip <= 127 {
let mut buf = vec![0; 1];
input.read_exact(&mut buf)?;
} else if skip < 16383 {
let mut buf = vec![0; 2];
input.read_exact(&mut buf)?;
} else if skip < 2097151 {
let mut buf = vec![0; 3];
input.read_exact(&mut buf)?;
} else if skip < 268435455 {
let mut buf = vec![0; 4];
input.read_exact(&mut buf)?;
} else {
let mut buf = vec![0; 5];
input.read_exact(&mut buf)?;
}
Ok(bytes)
}
pub(crate) fn read_zm_len(cursor: &mut Cursor<&Vec<u8>>) -> Result<usize> {
let len = cursor.read_u8()?;
if len <= 253 {
return Ok(len as usize);
} else if len == 254 {
let value = cursor.read_u32::<BigEndian>()?;
return Ok(value as usize);
}
Ok(len as usize)
}
pub(crate) fn read_zip_list_entry(cursor: &mut Cursor<Vec<u8>>) -> Result<Vec<u8>> {
if cursor.read_u8()? >= 254 {
cursor.read_u32::<LittleEndian>()?;
}
let flag = cursor.read_u8()?;
match flag >> 6 {
0 => {
let length = flag & 0x3F;
let mut buff = vec![0; length as usize];
cursor.read_exact(&mut buff)?;
return Ok(buff);
}
1 => {
let next_byte = cursor.read_u8()?;
let length = (((flag as u16) & 0x3F) << 8) | (next_byte as u16);
let mut buff = vec![0; length as usize];
cursor.read_exact(&mut buff)?;
return Ok(buff);
}
2 => {
let length = cursor.read_u32::<BigEndian>()?;
let mut buff = vec![0; length as usize];
cursor.read_exact(&mut buff)?;
return Ok(buff);
}
_ => {}
}
return match flag {
ZIP_INT_8BIT => {
let int = cursor.read_i8()?;
Ok(int.to_string().into_bytes())
}
ZIP_INT_16BIT => {
let int = cursor.read_i16::<LittleEndian>()?;
Ok(int.to_string().into_bytes())
}
ZIP_INT_24BIT => {
let int = cursor.read_i24::<LittleEndian>()?;
Ok(int.to_string().into_bytes())
}
ZIP_INT_32BIT => {
let int = cursor.read_i32::<LittleEndian>()?;
Ok(int.to_string().into_bytes())
}
ZIP_INT_64BIT => {
let int = cursor.read_i64::<LittleEndian>()?;
Ok(int.to_string().into_bytes())
}
_ => {
let result = (flag - 0xF1) as isize;
Ok(result.to_string().into_bytes())
}
};
}
/// 封装Redis中的各种数据类型,由`RdbHandler`统一处理
#[derive(Debug)]
pub enum Object<'a> {
/// 代表Redis中的String类型数据
String(KeyValue<'a>),
/// 代表Redis中的List类型数据
List(List<'a>),
/// 代表Redis中的Set类型数据
Set(Set<'a>),
/// 代表Redis中的SortedSet类型数据
SortedSet(SortedSet<'a>),
/// 代表Redis中的Hash类型数据
Hash(Hash<'a>),
/// 代表Redis中的module, 需要额外实现Module解析器
Module(Vec<u8>, Box<dyn Module>, &'a Meta),
/// 代表Redis中的Stream类型数据
Stream(Vec<u8>, Stream<'a>),
/// 代表rdb数据解析开始
BOR,
/// 代表rdb数据解析完毕
EOR,
}
pub trait Module {
fn as_any(&self) -> &dyn Any;
}
impl Debug for dyn Module {
fn fmt(&self, _: &mut Formatter) -> result::Result<(), Error> {
unimplemented!()
}
}
/// 数据的元信息, 包括数据过期类型, 内存驱逐类型, 数据所属的db
#[derive(Debug)]
pub struct Meta {
/// 数据所属的db
pub db: isize,
/// 左为过期时间类型,右为过期时间
pub expire: Option<(ExpireType, i64)>,
/// 左为内存驱逐类型,右为被驱逐掉的值
pub evict: Option<(EvictType, i64)>,
}
/// 过期类型
#[derive(Debug)]
pub enum ExpireType {
/// 以秒计算过期时间
Second,
/// 以毫秒计算过期时间
Millisecond,
}
/// 内存驱逐类型
#[derive(Debug)]
pub enum EvictType {
/// Least Recently Used
LRU,
/// Least Frequently Used
LFU,
}
/// 代表Redis中的String类型数据
#[derive(Debug)]
pub struct KeyValue<'a> {
/// 数据的key
pub key: &'a [u8],
/// 数据的值
pub value: &'a [u8],
/// 数据的元信息
pub meta: &'a Meta,
}
/// 代表Redis中的List类型数据
#[derive(Debug)]
pub struct List<'a> {
/// 数据的key
pub key: &'a [u8],
/// Set中所有的元素
pub values: &'a [Vec<u8>],
/// 数据的元信息
pub meta: &'a Meta,
}
/// 代表Redis中的Set类型数据
#[derive(Debug)]
pub struct Set<'a> {
/// 数据的key
pub key: &'a [u8],
/// Set中所有的元素
pub members: &'a [Vec<u8>],
/// 数据的元信息
pub meta: &'a Meta,
}
/// 代表Redis中的SortedSet类型数据
#[derive(Debug)]
pub struct SortedSet<'a> {
/// 数据的key
pub key: &'a [u8],
/// SortedSet中所有的元素
pub items: &'a [Item],
/// 数据的元信息
pub meta: &'a Meta,
}
/// SortedSet中的一条元素
#[derive(Debug)]
pub struct Item {
/// 元素值
pub member: Vec<u8>,
/// 元素的排序分数
pub score: f64,
}
/// 代表Redis中的Hash类型数据
#[derive(Debug)]
pub struct Hash<'a> {
/// 数据的key
pub key: &'a [u8],
/// 数据所有的字段
pub fields: &'a [Field],
/// 数据的元信息
pub meta: &'a Meta,
}
/// Hash类型数据中的一个字段
#[derive(Debug)]
pub struct Field {
/// 字段名
pub name: Vec<u8>,
/// 字段值
pub value: Vec<u8>,
}
#[derive(Debug)]
pub struct Stream<'a> {
pub entries: BTreeMap<ID, Entry>,
pub groups: Vec<Group>,
/// 数据的元信息
pub meta: &'a Meta,
}
#[derive(Debug, Eq, Copy, Clone)]
pub struct ID {
pub ms: i64,
pub seq: i64,
}
impl ID {
pub fn to_string(&self) -> String {
format!("{}-{}", self.ms, self.seq)
}
}
impl PartialEq for ID {
fn eq(&self, other: &Self) -> bool {
self.ms == other.ms && self.seq == other.seq
}
fn ne(&self, other: &Self) -> bool {
self.ms != other.ms || self.seq != other.seq
}
}
impl PartialOrd for ID {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
fn lt(&self, other: &Self) -> bool {
match self.cmp(other) {
cmp::Ordering::Less => true,
cmp::Ordering::Equal => false,
cmp::Ordering::Greater => false,
}
}
fn le(&self, other: &Self) -> bool {
match self.cmp(other) {
cmp::Ordering::Less => true,
cmp::Ordering::Equal => true,
cmp::Ordering::Greater => false,
}
}
fn gt(&self, other: &Self) -> bool {
match self.cmp(other) {
cmp::Ordering::Less => false,
cmp::Ordering::Equal => false,
cmp::Ordering::Greater => true,
}
}
fn ge(&self, other: &Self) -> bool {
match self.cmp(other) {
cmp::Ordering::Less => false,
cmp::Ordering::Equal => true,
cmp::Ordering::Greater => true,
}
}
}
impl Ord for ID {
fn cmp(&self, other: &Self) -> cmp::Ordering {
let order = self.ms.cmp(&other.ms);
if order == cmp::Ordering::Equal {
self.seq.cmp(&other.seq)
} else {
order
}
}
}
#[derive(Debug)]
pub struct Entry {
pub id: ID,
pub deleted: bool,
pub fields: BTreeMap<Vec<u8>, Vec<u8>>,
}
#[derive(Debug)]
pub struct Group {
pub name: Vec<u8>,
pub last_id: ID,
}
/// Map object types to RDB object types.
///
pub(crate) const RDB_TYPE_STRING: u8 = 0;
pub(crate) const RDB_TYPE_LIST: u8 = 1;
pub(crate) const RDB_TYPE_SET: u8 = 2;
pub(crate) const RDB_TYPE_ZSET: u8 = 3;
pub(crate) const RDB_TYPE_HASH: u8 = 4;
/// ZSET version 2 with doubles stored in binary.
pub(crate) const RDB_TYPE_ZSET_2: u8 = 5;
pub(crate) const RDB_TYPE_MODULE: u8 = 6;
/// Module value with annotations for parsing without
/// the generating module being loaded.
pub(crate) const RDB_TYPE_MODULE_2: u8 = 7;
/// Object types for encoded objects.
///
pub(crate) const RDB_TYPE_HASH_ZIPMAP: u8 = 9;
pub(crate) const RDB_TYPE_LIST_ZIPLIST: u8 = 10;
pub(crate) const RDB_TYPE_SET_INTSET: u8 = 11;
pub(crate) const RDB_TYPE_ZSET_ZIPLIST: u8 = 12;
pub(crate) const RDB_TYPE_HASH_ZIPLIST: u8 = 13;
pub(crate) const RDB_TYPE_LIST_QUICKLIST: u8 = 14;
pub(crate) const RDB_TYPE_STREAM_LISTPACKS: u8 = 15;
/// Special RDB opcodes
///
// Module auxiliary data.
pub(crate) const RDB_OPCODE_MODULE_AUX: u8 = 247;
// LRU idle time.
pub(crate) const RDB_OPCODE_IDLE: u8 = 248;
// LFU frequency.
pub(crate) const RDB_OPCODE_FREQ: u8 = 249;
// RDB aux field.
pub(crate) const RDB_OPCODE_AUX: u8 = 250;
// Hash table resize hint.
pub(crate) const RDB_OPCODE_RESIZEDB: u8 = 251;
// Expire time in milliseconds.
pub(crate) const RDB_OPCODE_EXPIRETIME_MS: u8 = 252;
// Old expire time in seconds.
pub(crate) const RDB_OPCODE_EXPIRETIME: u8 = 253;
// DB number of the following keys.
pub(crate) const RDB_OPCODE_SELECTDB: u8 = 254;
// End of the RDB file.
pub(crate) const RDB_OPCODE_EOF: u8 = 255;
pub(crate) const RDB_MODULE_OPCODE_EOF: isize = 0;
pub(crate) const RDB_MODULE_OPCODE_SINT: isize = 1;
pub(crate) const RDB_MODULE_OPCODE_UINT: isize = 2;
pub(crate) const RDB_MODULE_OPCODE_STRING: isize = 5;
pub(crate) const RDB_MODULE_OPCODE_FLOAT: isize = 3;
pub(crate) const RDB_MODULE_OPCODE_DOUBLE: isize = 4;
pub(crate) const ZIP_INT_8BIT: u8 = 254;
pub(crate) const ZIP_INT_16BIT: u8 = 192;
pub(crate) const ZIP_INT_24BIT: u8 = 240;
pub(crate) const ZIP_INT_32BIT: u8 = 208;
pub(crate) const ZIP_INT_64BIT: u8 = 224;
/// Defines related to the dump file format. To store 32 bits lengths for short
/// keys requires a lot of space, so we check the most significant 2 bits of
/// the first byte to interpreter the length:
///
/// 00|XXXXXX => if the two MSB are 00 the len is the 6 bits of this byte
/// 01|XXXXXX XXXXXXXX => 01, the len is 14 byes, 6 bits + 8 bits of next byte
/// 10|000000 [32 bit integer] => A full 32 bit len in net byte order will follow
/// 10|000001 [64 bit integer] => A full 64 bit len in net byte order will follow
/// 11|OBKIND this means: specially encoded object will follow. The six bits
/// number specify the kind of object that follows.
/// See the RDB_ENC_* defines.
///
/// Lengths up to 63 are stored using a single byte, most DB keys, and may
/// values, will fit inside.
pub(crate) const RDB_ENCVAL: u8 = 3;
pub(crate) const RDB_6BITLEN: u8 = 0;
pub(crate) const RDB_14BITLEN: u8 = 1;
pub(crate) const RDB_32BITLEN: u8 = 0x80;
pub(crate) const RDB_64BITLEN: u8 = 0x81;
/// When a length of a string object stored on disk has the first two bits
/// set, the remaining six bits specify a special encoding for the object
/// accordingly to the following defines:
///
/// 8 bit signed integer
pub(crate) const RDB_ENC_INT8: isize = 0;
/// 16 bit signed integer
pub(crate) const RDB_ENC_INT16: isize = 1;
/// 32 bit signed integer
pub(crate) const RDB_ENC_INT32: isize = 2;
/// string compressed with FASTLZ
pub(crate) const RDB_ENC_LZF: isize = 3;
pub(crate) const BATCH_SIZE: usize = 64;
pub(crate) const MODULE_SET: [char; 64] = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_',
];
|
pub struct Solution;
impl Solution {
pub fn is_scramble(s1: String, s2: String) -> bool {
let s1 = &s1.chars().collect::<Vec<char>>();
let s2 = &s2.chars().collect::<Vec<char>>();
if !is_anagram(s1, s2) {
return false;
}
rec(s1, s2)
}
}
fn rec(s1: &[char], s2: &[char]) -> bool {
if s1 == s2 {
return true;
}
for i in 1..s1.len() {
if is_anagram(&s1[..i], &s2[..i]) && rec(&s1[..i], &s2[..i]) && rec(&s1[i..], &s2[i..]) {
return true;
}
let j = s1.len() - i;
if is_anagram(&s1[..i], &s2[j..]) && rec(&s1[..i], &s2[j..]) && rec(&s1[i..], &s2[..j]) {
return true;
}
}
false
}
fn is_anagram(s1: &[char], s2: &[char]) -> bool {
let mut s1 = s1.to_vec();
let mut s2 = s2.to_vec();
s1.sort();
s2.sort();
s1 == s2
}
#[test]
fn test0087() {
assert_eq!(
Solution::is_scramble("great".to_string(), "rgeat".to_string()),
true
);
assert_eq!(
Solution::is_scramble("great".to_string(), "rgtae".to_string()),
true
);
assert_eq!(
Solution::is_scramble("abcde".to_string(), "caebd".to_string()),
false
);
}
|
use nalgebra::Vector2;
#[derive(Clone)]
pub struct Topography {
pub height: Vec<f32>,
pub dimensions: Vector2<u32>,
}
impl Topography {
pub fn iter(&self) -> std::slice::Iter<'_, f32> {
self.height.iter()
}
pub fn flat(dimensions: Vector2<u32>) -> Self {
Self {
height: (0..dimensions.x * dimensions.y).map(|_| 0.0).collect(),
dimensions,
}
}
pub fn cone(dimensions: Vector2<u32>, center: Vector2<f32>, slope: f32) -> Self {
Self {
height: (0..dimensions.x * dimensions.y)
.map(|i| {
let pos = Vector2::new((i / dimensions.y) as f32, (i % dimensions.y) as f32);
((pos.x - center.x).powi(2) + (pos.y - center.y).powi(2)).sqrt() * slope
})
.collect(),
dimensions,
}
}
fn get(&self, index: Vector2<u32>) -> f32 {
let i = index.x * self.dimensions.y + index.y;
self.height[i as usize]
}
pub fn slope(&self, start: Vector2<u32>, end: Vector2<u32>) -> f32 {
self.get(start) - self.get(end)
}
}
|
::windows_sys::core::link ! ( "deviceaccess.dll""system" #[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"] fn CreateDeviceAccessInstance ( deviceinterfacepath : :: windows_sys::core::PCWSTR , desiredaccess : u32 , createasync : *mut ICreateDeviceAccessAsync ) -> :: windows_sys::core::HRESULT );
pub type ICreateDeviceAccessAsync = *mut ::core::ffi::c_void;
pub type IDeviceIoControl = *mut ::core::ffi::c_void;
pub type IDeviceRequestCompletionCallback = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const CLSID_DeviceIoControl: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x12d3e372_874b_457d_9fdf_73977778686c);
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const DEV_PORT_1394: u32 = 8u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const DEV_PORT_ARTI: u32 = 7u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const DEV_PORT_COM1: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const DEV_PORT_COM2: u32 = 3u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const DEV_PORT_COM3: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const DEV_PORT_COM4: u32 = 5u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const DEV_PORT_DIAQ: u32 = 6u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const DEV_PORT_MAX: u32 = 9u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const DEV_PORT_MIN: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const DEV_PORT_SIM: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const DEV_PORT_USB: u32 = 9u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_1: i32 = 1i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_10: i32 = 512i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_11: i32 = 1024i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_12: i32 = 2048i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_13: i32 = 4096i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_14: i32 = 8192i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_15: i32 = 16384i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_16: i32 = 32768i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_17: i32 = 65536i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_18: i32 = 131072i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_19: i32 = 262144i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_2: i32 = 2i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_20: i32 = 524288i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_21: i32 = 1048576i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_22: i32 = 2097152i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_23: i32 = 4194304i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_24: i32 = 8388608i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_3: i32 = 4i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_4: i32 = 8i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_5: i32 = 16i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_6: i32 = 32i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_7: i32 = 64i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_8: i32 = 128i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_9: i32 = 256i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_AUDIO_ALL: u32 = 268435456u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_BASE: i32 = 4096i32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_BOTTOM: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_CENTER: u32 = 512u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_LEFT: u32 = 256u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_MIDDLE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_RIGHT: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_TOP: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Devices_DeviceAccess\"`*"]
pub const ED_VIDEO: i32 = 33554432i32;
|
extern crate prs_util;
use std::fs::File;
use std::io::{Write, BufReader, BufWriter};
use std::env;
use prs_util::decoder::Decoder;
fn main() {
let mut args = env::args().skip(1);
let filename = args.next().unwrap();
let out_filename = args.next().unwrap();
let file = BufReader::new(File::open(filename).unwrap());
let mut decoder = Decoder::new(file);
let decoded = decoder.decode_to_vec().unwrap();
let mut out = BufWriter::new(File::create(out_filename).unwrap());
out.write_all(&decoded).unwrap();
}
|
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{Error, Field, Generics, Ident, Type};
use crate::{serde_replace, Attr, GenericsStreams, MULTIPLE_FLATTEN_ERROR};
/// Use this crate's name as log target.
const LOG_TARGET: &str = env!("CARGO_PKG_NAME");
pub fn derive_deserialize<T>(
ident: Ident,
generics: Generics,
fields: Punctuated<Field, T>,
) -> TokenStream {
// Create all necessary tokens for the implementation.
let GenericsStreams { unconstrained, constrained, phantoms } =
crate::generics_streams(&generics.params);
let FieldStreams { flatten, match_assignments } = fields_deserializer(&fields);
let visitor = format_ident!("{}Visitor", ident);
// Generate deserialization impl.
let mut tokens = quote! {
#[derive(Default)]
#[allow(non_snake_case)]
struct #visitor <#unconstrained> {
#phantoms
}
impl <'de, #constrained> serde::de::Visitor<'de> for #visitor <#unconstrained> {
type Value = #ident <#unconstrained>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a mapping")
}
fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
where
M: serde::de::MapAccess<'de>,
{
let mut config = Self::Value::default();
// Unused keys for flattening and warning.
let mut unused = toml::Table::new();
while let Some((key, value)) = map.next_entry::<String, toml::Value>()? {
match key.as_str() {
#match_assignments
_ => {
unused.insert(key, value);
},
}
}
#flatten
// Warn about unused keys.
for key in unused.keys() {
log::warn!(target: #LOG_TARGET, "Unused config key: {}", key);
}
Ok(config)
}
}
impl <'de, #constrained> serde::Deserialize<'de> for #ident <#unconstrained> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_map(#visitor :: default())
}
}
};
// Automatically implement [`alacritty_config::SerdeReplace`].
tokens.extend(serde_replace::derive_recursive(ident, generics, fields));
tokens.into()
}
// Token streams created from the fields in the struct.
#[derive(Default)]
struct FieldStreams {
match_assignments: TokenStream2,
flatten: TokenStream2,
}
/// Create the deserializers for match arms and flattened fields.
fn fields_deserializer<T>(fields: &Punctuated<Field, T>) -> FieldStreams {
let mut field_streams = FieldStreams::default();
// Create the deserialization stream for each field.
for field in fields.iter() {
if let Err(err) = field_deserializer(&mut field_streams, field) {
field_streams.flatten = err.to_compile_error();
return field_streams;
}
}
field_streams
}
/// Append a single field deserializer to the stream.
fn field_deserializer(field_streams: &mut FieldStreams, field: &Field) -> Result<(), Error> {
let ident = field.ident.as_ref().expect("unreachable tuple struct");
let literal = ident.to_string();
let mut literals = vec![literal.clone()];
// Create default stream for deserializing fields.
let mut match_assignment_stream = quote! {
match serde::Deserialize::deserialize(value) {
Ok(value) => config.#ident = value,
Err(err) => {
log::error!(
target: #LOG_TARGET,
"Config error: {}: {}",
#literal,
err.to_string().trim(),
);
},
}
};
// Iterate over all #[config(...)] attributes.
for attr in field.attrs.iter().filter(|attr| attr.path().is_ident("config")) {
let parsed = match attr.parse_args::<Attr>() {
Ok(parsed) => parsed,
Err(_) => continue,
};
match parsed.ident.as_str() {
// Skip deserialization for `#[config(skip)]` fields.
"skip" => return Ok(()),
"flatten" => {
// NOTE: Currently only a single instance of flatten is supported per struct
// for complexity reasons.
if !field_streams.flatten.is_empty() {
return Err(Error::new(attr.span(), MULTIPLE_FLATTEN_ERROR));
}
// Create the tokens to deserialize the flattened struct from the unused fields.
field_streams.flatten.extend(quote! {
// Drain unused fields since they will be used for flattening.
let flattened = std::mem::replace(&mut unused, toml::Table::new());
config.#ident = serde::Deserialize::deserialize(flattened).unwrap_or_default();
});
},
"deprecated" | "removed" => {
// Construct deprecation/removal message with optional attribute override.
let mut message = format!("Config warning: {} has been {}", literal, parsed.ident);
if let Some(warning) = parsed.param {
message = format!("{}; {}", message, warning.value());
}
// Append stream to log deprecation/removal warning.
match_assignment_stream.extend(quote! {
log::warn!(target: #LOG_TARGET, #message);
});
},
// Add aliases to match pattern.
"alias" => {
if let Some(alias) = parsed.param {
literals.push(alias.value());
}
},
_ => (),
}
}
// Create token stream for deserializing "none" string into `Option<T>`.
if let Type::Path(type_path) = &field.ty {
if type_path.path.segments.iter().last().map_or(false, |s| s.ident == "Option") {
match_assignment_stream = quote! {
if value.as_str().map_or(false, |s| s.eq_ignore_ascii_case("none")) {
config.#ident = None;
continue;
}
#match_assignment_stream
};
}
}
// Create the token stream for deserialization and error handling.
field_streams.match_assignments.extend(quote! {
#(#literals)|* => { #match_assignment_stream },
});
Ok(())
}
|
//! Pretty Capture codeframes
//!
//! Ex:
//! let raw_lines = "let a: i64 = 12;";
//! let codeframe = Codeframe::new(raw_lines, 1).set_color("red").capture();
//!
//!
//! Colors Supported
//! Black
//! Red
//! Green
//! Yellow
//! Blue
//! Magenta or (Purple)
//! Cyan
//! White
use crate::capture;
use crate::Color;
pub struct Codeframe {
color: Color,
line: i64,
raw_lines: String,
}
impl Codeframe {
pub fn new(raw_lines: String, line: i64) -> Codeframe {
Codeframe {
color: Color::Red,
line,
raw_lines,
}
}
pub fn set_color(mut self, color: Color) -> Self {
self.color = color;
self
}
pub fn capture(self) -> Option<String> {
let vec_lines = self.raw_lines.split('\n').map(|s| s.to_owned()).collect();
capture::capture_codeframe(vec_lines, self.line, self.color)
}
}
|
use crate::{DocBase, VarType};
const REMARKS: &'static str = r#"
Two args version: x is a series and y is a length.
One arg version: x is a length. Algorithm uses high as a source series.
"#;
pub fn gen_doc() -> Vec<DocBase> {
let fn_doc = DocBase {
var_type: VarType::Function,
name: "highestbars",
signatures: vec![],
description: "Highest value offset for a given number of bars back.",
example: "",
returns: "Offset to the highest bar.",
arguments: "",
remarks: REMARKS,
links: "[lowest](#fun-lowest) [highest](#fun-highest)",
};
vec![fn_doc]
}
|
//! Generated file, do not edit by hand, see `xtask/src/codegen`
use crate::{
ast::{self, support, AstChildren, AstNode},
SyntaxKind::{self, *},
SyntaxNode, SyntaxToken, T,
};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VarName {
pub(crate) syntax: SyntaxNode,
}
impl VarName {
pub fn lower_ident_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![lower_ident])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TypeName {
pub(crate) syntax: SyntaxNode,
}
impl TypeName {
pub fn cap_ident_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![cap_ident])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Path {
pub(crate) syntax: SyntaxNode,
}
impl Path {
pub fn qualifier(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn dot_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![.])
}
pub fn segment(&self) -> Option<VarName> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TypePath {
pub(crate) syntax: SyntaxNode,
}
impl TypePath {
pub fn qualifier(&self) -> Option<Path> {
support::child(&self.syntax)
}
pub fn dot_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![.])
}
pub fn segment(&self) -> Option<TypeName> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ParamList {
pub(crate) syntax: SyntaxNode,
}
impl ParamList {
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn params(&self) -> AstChildren<Param> {
support::children(&self.syntax)
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Param {
pub(crate) syntax: SyntaxNode,
}
impl ast::VarNameOwner for Param {}
impl Param {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn ty(&self) -> Option<Type> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Annotations {
pub(crate) syntax: SyntaxNode,
}
impl Annotations {
pub fn l_brack_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['['])
}
pub fn annotations(&self) -> AstChildren<Annotation> {
support::children(&self.syntax)
}
pub fn r_brack_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![']'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Type {
pub(crate) syntax: SyntaxNode,
}
impl Type {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn type_path(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn l_angle_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![<])
}
pub fn types(&self) -> AstChildren<Type> {
support::children(&self.syntax)
}
pub fn r_angle_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![>])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Annotation {
pub(crate) syntax: SyntaxNode,
}
impl Annotation {
pub fn ty(&self) -> Option<Type> {
support::child(&self.syntax)
}
pub fn colon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![:])
}
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FnExpr {
pub(crate) syntax: SyntaxNode,
}
impl ast::PureExprListOwner for FnExpr {}
impl FnExpr {
pub fn path(&self) -> Option<Path> {
support::child(&self.syntax)
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PartialFnExpr {
pub(crate) syntax: SyntaxNode,
}
impl ast::PureExprListOwner for PartialFnExpr {}
impl PartialFnExpr {
pub fn path(&self) -> Option<Path> {
support::child(&self.syntax)
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn fn_list(&self) -> Option<FnList> {
support::child(&self.syntax)
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VariadicFnExpr {
pub(crate) syntax: SyntaxNode,
}
impl ast::PureExprListOwner for VariadicFnExpr {}
impl VariadicFnExpr {
pub fn path(&self) -> Option<Path> {
support::child(&self.syntax)
}
pub fn l_brack_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['['])
}
pub fn r_brack_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![']'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConstructorExpr {
pub(crate) syntax: SyntaxNode,
}
impl ast::PureExprListOwner for ConstructorExpr {}
impl ConstructorExpr {
pub fn type_path(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UnaryExpr {
pub(crate) syntax: SyntaxNode,
}
impl UnaryExpr {
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BinaryExpr {
pub(crate) syntax: SyntaxNode,
}
impl BinaryExpr {}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NameExpr {
pub(crate) syntax: SyntaxNode,
}
impl ast::VarNameOwner for NameExpr {}
impl NameExpr {
pub fn this_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![this])
}
pub fn dot_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![.])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Literal {
pub(crate) syntax: SyntaxNode,
}
impl Literal {}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ThisExpr {
pub(crate) syntax: SyntaxNode,
}
impl ThisExpr {
pub fn this_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![this])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NullExpr {
pub(crate) syntax: SyntaxNode,
}
impl NullExpr {
pub fn null_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![null])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ImplementsExpr {
pub(crate) syntax: SyntaxNode,
}
impl ast::TypeNameOwner for ImplementsExpr {}
impl ImplementsExpr {
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn implements_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![implements])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AsExpr {
pub(crate) syntax: SyntaxNode,
}
impl ast::TypeNameOwner for AsExpr {}
impl AsExpr {
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn as_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![as])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct WhenExpr {
pub(crate) syntax: SyntaxNode,
}
impl WhenExpr {
pub fn when_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![when])
}
pub fn if_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![if])
}
pub fn condition(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn then_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![then])
}
pub fn else_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![else])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CaseExpr {
pub(crate) syntax: SyntaxNode,
}
impl CaseExpr {
pub fn case_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![case])
}
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn l_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['{'])
}
pub fn case_expr_branch(&self) -> Option<CaseExprBranch> {
support::child(&self.syntax)
}
pub fn r_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['}'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LetExpr {
pub(crate) syntax: SyntaxNode,
}
impl LetExpr {
pub fn let_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![let])
}
pub fn let_defs(&self) -> Option<LetDefs> {
support::child(&self.syntax)
}
pub fn in_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![in])
}
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ParenExpr {
pub(crate) syntax: SyntaxNode,
}
impl ParenExpr {
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PureExprList {
pub(crate) syntax: SyntaxNode,
}
impl PureExprList {
pub fn pure_exprs(&self) -> AstChildren<PureExpr> {
support::children(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FnList {
pub(crate) syntax: SyntaxNode,
}
impl FnList {
pub fn fn_list_param(&self) -> Option<FnListParam> {
support::child(&self.syntax)
}
pub fn comma_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![,])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CaseExprBranch {
pub(crate) syntax: SyntaxNode,
}
impl CaseExprBranch {
pub fn pipe_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![|])
}
pub fn pattern(&self) -> Option<Pattern> {
support::child(&self.syntax)
}
pub fn fat_arrow_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![=>])
}
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LetDefs {
pub(crate) syntax: SyntaxNode,
}
impl LetDefs {
pub fn let_def(&self) -> Option<LetDef> {
support::child(&self.syntax)
}
pub fn let_defs(&self) -> AstChildren<LetDef> {
support::children(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AnonFn {
pub(crate) syntax: SyntaxNode,
}
impl AnonFn {
pub fn param_list(&self) -> Option<ParamList> {
support::child(&self.syntax)
}
pub fn fat_arrow_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![=>])
}
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LetDef {
pub(crate) syntax: SyntaxNode,
}
impl ast::VarNameOwner for LetDef {}
impl LetDef {
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn ty(&self) -> Option<Type> {
support::child(&self.syntax)
}
pub fn eq_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![=])
}
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GetExpr {
pub(crate) syntax: SyntaxNode,
}
impl GetExpr {
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn dot_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![.])
}
pub fn get_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![get])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NewExpr {
pub(crate) syntax: SyntaxNode,
}
impl ast::PureExprListOwner for NewExpr {}
impl NewExpr {
pub fn new_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![new])
}
pub fn local_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![local])
}
pub fn class(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AsyncCallExpr {
pub(crate) syntax: SyntaxNode,
}
impl ast::VarNameOwner for AsyncCallExpr {}
impl ast::PureExprListOwner for AsyncCallExpr {}
impl AsyncCallExpr {
pub fn await_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![await])
}
pub fn callee(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn excl_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![!])
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SyncCallExpr {
pub(crate) syntax: SyntaxNode,
}
impl ast::VarNameOwner for SyncCallExpr {}
impl ast::PureExprListOwner for SyncCallExpr {}
impl SyncCallExpr {
pub fn callee(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn dot_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![.])
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct OriginalCallExpr {
pub(crate) syntax: SyntaxNode,
}
impl ast::PureExprListOwner for OriginalCallExpr {}
impl OriginalCallExpr {
pub fn core_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![core])
}
pub fn dot_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![.])
}
pub fn original_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![original])
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VarDeclStmt {
pub(crate) syntax: SyntaxNode,
}
impl ast::VarNameOwner for VarDeclStmt {}
impl VarDeclStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn ty(&self) -> Option<Type> {
support::child(&self.syntax)
}
pub fn eq_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![=])
}
pub fn expr(&self) -> Option<Expr> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AssignStmt {
pub(crate) syntax: SyntaxNode,
}
impl AssignStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn name_expr(&self) -> Option<NameExpr> {
support::child(&self.syntax)
}
pub fn eq_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![=])
}
pub fn expr(&self) -> Option<Expr> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SkipStmt {
pub(crate) syntax: SyntaxNode,
}
impl SkipStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn skip_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![skip])
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ReturnStmt {
pub(crate) syntax: SyntaxNode,
}
impl ReturnStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn return_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![return])
}
pub fn expr(&self) -> Option<Expr> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AssertStmt {
pub(crate) syntax: SyntaxNode,
}
impl AssertStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn assert_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![assert])
}
pub fn expr(&self) -> Option<Expr> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Block {
pub(crate) syntax: SyntaxNode,
}
impl Block {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn l_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['{'])
}
pub fn stmts(&self) -> AstChildren<Stmt> {
support::children(&self.syntax)
}
pub fn r_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['}'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct IfStmt {
pub(crate) syntax: SyntaxNode,
}
impl IfStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn if_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![if])
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn condition(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
pub fn else_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![else])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SwitchStmt {
pub(crate) syntax: SyntaxNode,
}
impl SwitchStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn switch_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![switch])
}
pub fn case_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![case])
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
pub fn l_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['{'])
}
pub fn case_stmt_branchs(&self) -> AstChildren<CaseStmtBranch> {
support::children(&self.syntax)
}
pub fn r_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['}'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct WhileStmt {
pub(crate) syntax: SyntaxNode,
}
impl WhileStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn while_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![while])
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn condition(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
pub fn body(&self) -> Option<Stmt> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ForeachStmt {
pub(crate) syntax: SyntaxNode,
}
impl ForeachStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn foreach_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![foreach])
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn comma_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![,])
}
pub fn in_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![in])
}
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
pub fn stmt(&self) -> Option<Stmt> {
support::child(&self.syntax)
}
pub fn any_name(&self) -> Option<AnyName> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TryCatchFinallyStmt {
pub(crate) syntax: SyntaxNode,
}
impl TryCatchFinallyStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn try_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![try])
}
pub fn stmt(&self) -> Option<Stmt> {
support::child(&self.syntax)
}
pub fn catch_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![catch])
}
pub fn l_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['{'])
}
pub fn case_stmt_branchs(&self) -> AstChildren<CaseStmtBranch> {
support::children(&self.syntax)
}
pub fn r_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['}'])
}
pub fn case_stmt_branch(&self) -> Option<CaseStmtBranch> {
support::child(&self.syntax)
}
pub fn finally_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![finally])
}
pub fn finally(&self) -> Option<Stmt> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AwaitStmt {
pub(crate) syntax: SyntaxNode,
}
impl AwaitStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn await_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![await])
}
pub fn guard(&self) -> Option<Guard> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SuspendStmt {
pub(crate) syntax: SyntaxNode,
}
impl SuspendStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn suspend_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![suspend])
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DurationStmt {
pub(crate) syntax: SyntaxNode,
}
impl DurationStmt {
pub fn duration_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![duration])
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn comma_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![,])
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
pub fn expr(&self) -> Option<Expr> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ThrowStmt {
pub(crate) syntax: SyntaxNode,
}
impl ThrowStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn throw_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![throw])
}
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DieStmt {
pub(crate) syntax: SyntaxNode,
}
impl DieStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn die_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![die])
}
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MoveCogToStmt {
pub(crate) syntax: SyntaxNode,
}
impl MoveCogToStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn movecogto_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![movecogto])
}
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExprStmt {
pub(crate) syntax: SyntaxNode,
}
impl ExprStmt {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn expr(&self) -> Option<Expr> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CaseStmtBranch {
pub(crate) syntax: SyntaxNode,
}
impl CaseStmtBranch {
pub fn pattern(&self) -> Option<Pattern> {
support::child(&self.syntax)
}
pub fn fat_arrow_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![=>])
}
pub fn stmt(&self) -> Option<Stmt> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ClaimGuard {
pub(crate) syntax: SyntaxNode,
}
impl ClaimGuard {
pub fn name_expr(&self) -> Option<NameExpr> {
support::child(&self.syntax)
}
pub fn question_mark_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![?])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DurationGuard {
pub(crate) syntax: SyntaxNode,
}
impl DurationGuard {
pub fn duration_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![duration])
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn comma_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![,])
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
pub fn expr(&self) -> Option<Expr> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExprGuard {
pub(crate) syntax: SyntaxNode,
}
impl ExprGuard {
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AndGuard {
pub(crate) syntax: SyntaxNode,
}
impl AndGuard {
pub fn left(&self) -> Option<Guard> {
support::child(&self.syntax)
}
pub fn amp_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![&])
}
pub fn right(&self) -> Option<Guard> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct WildCardPattern {
pub(crate) syntax: SyntaxNode,
}
impl WildCardPattern {
pub fn underscore_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![_])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct IntPattern {
pub(crate) syntax: SyntaxNode,
}
impl IntPattern {}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StringPattern {
pub(crate) syntax: SyntaxNode,
}
impl StringPattern {}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VarPattern {
pub(crate) syntax: SyntaxNode,
}
impl ast::VarNameOwner for VarPattern {}
impl VarPattern {}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConstructorPattern {
pub(crate) syntax: SyntaxNode,
}
impl ConstructorPattern {
pub fn type_path(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn patterns(&self) -> AstChildren<Pattern> {
support::children(&self.syntax)
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DataTypeDecl {
pub(crate) syntax: SyntaxNode,
}
impl DataTypeDecl {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn data_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![data])
}
pub fn type_path(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn generic_arg_list(&self) -> Option<GenericArgList> {
support::child(&self.syntax)
}
pub fn data_constructor_list(&self) -> Option<DataConstructorList> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GenericArgList {
pub(crate) syntax: SyntaxNode,
}
impl GenericArgList {
pub fn l_angle_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![<])
}
pub fn type_names(&self) -> AstChildren<TypeName> {
support::children(&self.syntax)
}
pub fn r_angle_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![>])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DataConstructorList {
pub(crate) syntax: SyntaxNode,
}
impl DataConstructorList {
pub fn eq_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![=])
}
pub fn data_constructors(&self) -> AstChildren<DataConstructor> {
support::children(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DataConstructor {
pub(crate) syntax: SyntaxNode,
}
impl ast::TypeNameOwner for DataConstructor {}
impl DataConstructor {
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn data_constructor_arg_list(&self) -> Option<DataConstructorArgList> {
support::child(&self.syntax)
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DataConstructorArgList {
pub(crate) syntax: SyntaxNode,
}
impl DataConstructorArgList {
pub fn data_constructor_args(&self) -> AstChildren<DataConstructorArg> {
support::children(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DataConstructorArg {
pub(crate) syntax: SyntaxNode,
}
impl ast::TypeNameOwner for DataConstructorArg {}
impl DataConstructorArg {
pub fn ty(&self) -> Option<Type> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TypeSyn {
pub(crate) syntax: SyntaxNode,
}
impl TypeSyn {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn type_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![type])
}
pub fn type_path(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn eq_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![=])
}
pub fn ty(&self) -> Option<Type> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExceptionDecl {
pub(crate) syntax: SyntaxNode,
}
impl ExceptionDecl {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn exception_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![exception])
}
pub fn type_path(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn data_constructor_arg_list(&self) -> Option<DataConstructorArgList> {
support::child(&self.syntax)
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FunctionDecl {
pub(crate) syntax: SyntaxNode,
}
impl FunctionDecl {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn def_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![def])
}
pub fn ty(&self) -> Option<Type> {
support::child(&self.syntax)
}
pub fn path(&self) -> Option<Path> {
support::child(&self.syntax)
}
pub fn generic_arg_list(&self) -> Option<GenericArgList> {
support::child(&self.syntax)
}
pub fn params(&self) -> Option<ParamList> {
support::child(&self.syntax)
}
pub fn eq_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![=])
}
pub fn builtin_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![builtin])
}
pub fn body(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ParFunctionDecl {
pub(crate) syntax: SyntaxNode,
}
impl ParFunctionDecl {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn def_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![def])
}
pub fn ty(&self) -> Option<Type> {
support::child(&self.syntax)
}
pub fn path(&self) -> Option<Path> {
support::child(&self.syntax)
}
pub fn generic_arg_list(&self) -> Option<GenericArgList> {
support::child(&self.syntax)
}
pub fn l_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['('])
}
pub fn functions(&self) -> Option<FunctionNameList> {
support::child(&self.syntax)
}
pub fn r_paren_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![')'])
}
pub fn params(&self) -> Option<ParamList> {
support::child(&self.syntax)
}
pub fn eq_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![=])
}
pub fn body(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FunctionNameList {
pub(crate) syntax: SyntaxNode,
}
impl FunctionNameList {
pub fn var_names(&self) -> AstChildren<VarName> {
support::children(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct InterfaceDecl {
pub(crate) syntax: SyntaxNode,
}
impl InterfaceDecl {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn interface_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![interface])
}
pub fn type_path(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn extends(&self) -> Option<ExtendsList> {
support::child(&self.syntax)
}
pub fn l_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['{'])
}
pub fn interface_items(&self) -> AstChildren<InterfaceItem> {
support::children(&self.syntax)
}
pub fn r_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['}'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExtendsList {
pub(crate) syntax: SyntaxNode,
}
impl ExtendsList {
pub fn type_paths(&self) -> AstChildren<TypePath> {
support::children(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct InterfaceItem {
pub(crate) syntax: SyntaxNode,
}
impl InterfaceItem {
pub fn method_sig(&self) -> Option<MethodSig> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MethodSig {
pub(crate) syntax: SyntaxNode,
}
impl ast::VarNameOwner for MethodSig {}
impl MethodSig {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn ty(&self) -> Option<Type> {
support::child(&self.syntax)
}
pub fn param_list(&self) -> Option<ParamList> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MethodDecl {
pub(crate) syntax: SyntaxNode,
}
impl MethodDecl {
pub fn method_sig(&self) -> Option<MethodSig> {
support::child(&self.syntax)
}
pub fn block(&self) -> Option<Block> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ClassDecl {
pub(crate) syntax: SyntaxNode,
}
impl ClassDecl {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn class_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![class])
}
pub fn type_path(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn param_list(&self) -> Option<ParamList> {
support::child(&self.syntax)
}
pub fn implements_list(&self) -> Option<ImplementsList> {
support::child(&self.syntax)
}
pub fn l_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['{'])
}
pub fn field_decls(&self) -> AstChildren<FieldDecl> {
support::children(&self.syntax)
}
pub fn init(&self) -> Option<Block> {
support::child(&self.syntax)
}
pub fn recover_block(&self) -> Option<RecoverBlock> {
support::child(&self.syntax)
}
pub fn trait_uses(&self) -> AstChildren<TraitUse> {
support::children(&self.syntax)
}
pub fn method_decls(&self) -> AstChildren<MethodDecl> {
support::children(&self.syntax)
}
pub fn r_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['}'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ImplementsList {
pub(crate) syntax: SyntaxNode,
}
impl ImplementsList {
pub fn implements_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![implements])
}
pub fn type_paths(&self) -> AstChildren<TypePath> {
support::children(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FieldDecl {
pub(crate) syntax: SyntaxNode,
}
impl ast::VarNameOwner for FieldDecl {}
impl FieldDecl {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn ty(&self) -> Option<Type> {
support::child(&self.syntax)
}
pub fn eq_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![=])
}
pub fn pure_expr(&self) -> Option<PureExpr> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RecoverBlock {
pub(crate) syntax: SyntaxNode,
}
impl RecoverBlock {
pub fn recover_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![recover])
}
pub fn l_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['{'])
}
pub fn case_stmt_branchs(&self) -> AstChildren<CaseStmtBranch> {
support::children(&self.syntax)
}
pub fn r_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['}'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TraitUse {
pub(crate) syntax: SyntaxNode,
}
impl TraitUse {
pub fn uses_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![uses])
}
pub fn trait_expr(&self) -> Option<TraitExpr> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Module {
pub(crate) syntax: SyntaxNode,
}
impl Module {
pub fn module_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![module])
}
pub fn type_path(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
pub fn imports(&self) -> AstChildren<Import> {
support::children(&self.syntax)
}
pub fn exports(&self) -> AstChildren<Export> {
support::children(&self.syntax)
}
pub fn decls(&self) -> AstChildren<Decl> {
support::children(&self.syntax)
}
pub fn main(&self) -> Option<Block> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StarImport {
pub(crate) syntax: SyntaxNode,
}
impl StarImport {
pub fn import_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![import])
}
pub fn star_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![*])
}
pub fn from_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![from])
}
pub fn type_path(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FromImport {
pub(crate) syntax: SyntaxNode,
}
impl FromImport {
pub fn import_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![import])
}
pub fn any_names(&self) -> AstChildren<AnyName> {
support::children(&self.syntax)
}
pub fn from_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![from])
}
pub fn type_path(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UnqualifiedImport {
pub(crate) syntax: SyntaxNode,
}
impl UnqualifiedImport {
pub fn import_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![import])
}
pub fn any_names(&self) -> AstChildren<AnyName> {
support::children(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StarExport {
pub(crate) syntax: SyntaxNode,
}
impl StarExport {
pub fn export_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![export])
}
pub fn star_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![*])
}
pub fn from_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![from])
}
pub fn from(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PartialExport {
pub(crate) syntax: SyntaxNode,
}
impl PartialExport {
pub fn export_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![export])
}
pub fn any_names(&self) -> AstChildren<AnyName> {
support::children(&self.syntax)
}
pub fn from_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![from])
}
pub fn from(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn semicolon_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![;])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TraitDecl {
pub(crate) syntax: SyntaxNode,
}
impl TraitDecl {
pub fn annotationss(&self) -> AstChildren<Annotations> {
support::children(&self.syntax)
}
pub fn trait_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![trait])
}
pub fn type_path(&self) -> Option<TypePath> {
support::child(&self.syntax)
}
pub fn eq_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![=])
}
pub fn trait_expr(&self) -> Option<TraitExpr> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TraitExpr {
pub(crate) syntax: SyntaxNode,
}
impl TraitExpr {
pub fn basic_trait_expr(&self) -> Option<BasicTraitExpr> {
support::child(&self.syntax)
}
pub fn trait_ops(&self) -> AstChildren<TraitOp> {
support::children(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TraitMethodSet {
pub(crate) syntax: SyntaxNode,
}
impl TraitMethodSet {
pub fn l_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['{'])
}
pub fn method_decls(&self) -> AstChildren<MethodDecl> {
support::children(&self.syntax)
}
pub fn r_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['}'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TraitMethod {
pub(crate) syntax: SyntaxNode,
}
impl TraitMethod {
pub fn method_decl(&self) -> Option<MethodDecl> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TraitName {
pub(crate) syntax: SyntaxNode,
}
impl ast::TypeNameOwner for TraitName {}
impl TraitName {}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TraitRemoveSig {
pub(crate) syntax: SyntaxNode,
}
impl TraitRemoveSig {
pub fn removes_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![removes])
}
pub fn method_sigs(&self) -> AstChildren<MethodSig> {
support::children(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TraitRemoveSet {
pub(crate) syntax: SyntaxNode,
}
impl TraitRemoveSet {
pub fn removes_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![removes])
}
pub fn l_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['{'])
}
pub fn method_sigs(&self) -> AstChildren<MethodSig> {
support::children(&self.syntax)
}
pub fn r_curly_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T!['}'])
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TraitAdd {
pub(crate) syntax: SyntaxNode,
}
impl TraitAdd {
pub fn adds_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![adds])
}
pub fn basic_trait_expr(&self) -> Option<BasicTraitExpr> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TraitModifies {
pub(crate) syntax: SyntaxNode,
}
impl TraitModifies {
pub fn modifies_token(&self) -> Option<SyntaxToken> {
support::token(&self.syntax, T![modifies])
}
pub fn basic_trait_expr(&self) -> Option<BasicTraitExpr> {
support::child(&self.syntax)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AnyName {
VarName(VarName),
TypeName(TypeName),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PureExpr {
FnExpr(FnExpr),
PartialFnExpr(PartialFnExpr),
VariadicFnExpr(VariadicFnExpr),
ConstructorExpr(ConstructorExpr),
UnaryExpr(UnaryExpr),
BinaryExpr(BinaryExpr),
NameExpr(NameExpr),
Literal(Literal),
ThisExpr(ThisExpr),
NullExpr(NullExpr),
ImplementsExpr(ImplementsExpr),
AsExpr(AsExpr),
WhenExpr(WhenExpr),
CaseExpr(CaseExpr),
LetExpr(LetExpr),
ParenExpr(ParenExpr),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Expr {
PureExpr(PureExpr),
EffExpr(EffExpr),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EffExpr {
GetExpr(GetExpr),
NewExpr(NewExpr),
AsyncCallExpr(AsyncCallExpr),
SyncCallExpr(SyncCallExpr),
OriginalCallExpr(OriginalCallExpr),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FnListParam {
VarName(VarName),
AnonFn(AnonFn),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Pattern {
WildCardPattern(WildCardPattern),
IntPattern(IntPattern),
StringPattern(StringPattern),
VarPattern(VarPattern),
ConstructorPattern(ConstructorPattern),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Stmt {
VarDeclStmt(VarDeclStmt),
AssignStmt(AssignStmt),
SkipStmt(SkipStmt),
ReturnStmt(ReturnStmt),
AssertStmt(AssertStmt),
Block(Block),
IfStmt(IfStmt),
SwitchStmt(SwitchStmt),
WhileStmt(WhileStmt),
ForeachStmt(ForeachStmt),
TryCatchFinallyStmt(TryCatchFinallyStmt),
AwaitStmt(AwaitStmt),
SuspendStmt(SuspendStmt),
DurationStmt(DurationStmt),
ThrowStmt(ThrowStmt),
DieStmt(DieStmt),
MoveCogToStmt(MoveCogToStmt),
ExprStmt(ExprStmt),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Guard {
ClaimGuard(ClaimGuard),
DurationGuard(DurationGuard),
ExprGuard(ExprGuard),
AndGuard(AndGuard),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Import {
StarImport(StarImport),
FromImport(FromImport),
UnqualifiedImport(UnqualifiedImport),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Export {
StarExport(StarExport),
PartialExport(PartialExport),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Decl {
DataTypeDecl(DataTypeDecl),
FunctionDecl(FunctionDecl),
ParFunctionDecl(ParFunctionDecl),
TypeSyn(TypeSyn),
ExceptionDecl(ExceptionDecl),
InterfaceDecl(InterfaceDecl),
ClassDecl(ClassDecl),
TraitDecl(TraitDecl),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum BasicTraitExpr {
TraitMethodSet(TraitMethodSet),
TraitMethod(TraitMethod),
TraitName(TraitName),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TraitOp {
TraitRemoveSig(TraitRemoveSig),
TraitRemoveSet(TraitRemoveSet),
TraitAdd(TraitAdd),
TraitModifies(TraitModifies),
}
impl AstNode for VarName {
fn can_cast(kind: SyntaxKind) -> bool {
kind == VAR_NAME
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TypeName {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TYPE_NAME
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for Path {
fn can_cast(kind: SyntaxKind) -> bool {
kind == PATH
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TypePath {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TYPE_PATH
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ParamList {
fn can_cast(kind: SyntaxKind) -> bool {
kind == PARAM_LIST
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for Param {
fn can_cast(kind: SyntaxKind) -> bool {
kind == PARAM
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for Annotations {
fn can_cast(kind: SyntaxKind) -> bool {
kind == ANNOTATIONS
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for Type {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TYPE
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for Annotation {
fn can_cast(kind: SyntaxKind) -> bool {
kind == ANNOTATION
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for FnExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == FN_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for PartialFnExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == PARTIAL_FN_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for VariadicFnExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == VARIADIC_FN_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ConstructorExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == CONSTRUCTOR_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for UnaryExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == UNARY_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for BinaryExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == BINARY_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for NameExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == NAME_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for Literal {
fn can_cast(kind: SyntaxKind) -> bool {
kind == LITERAL
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ThisExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == THIS_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for NullExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == NULL_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ImplementsExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == IMPLEMENTS_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for AsExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == AS_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for WhenExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == WHEN_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for CaseExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == CASE_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for LetExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == LET_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ParenExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == PAREN_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for PureExprList {
fn can_cast(kind: SyntaxKind) -> bool {
kind == PURE_EXPR_LIST
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for FnList {
fn can_cast(kind: SyntaxKind) -> bool {
kind == FN_LIST
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for CaseExprBranch {
fn can_cast(kind: SyntaxKind) -> bool {
kind == CASE_EXPR_BRANCH
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for LetDefs {
fn can_cast(kind: SyntaxKind) -> bool {
kind == LET_DEFS
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for AnonFn {
fn can_cast(kind: SyntaxKind) -> bool {
kind == ANON_FN
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for LetDef {
fn can_cast(kind: SyntaxKind) -> bool {
kind == LET_DEF
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for GetExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == GET_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for NewExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == NEW_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for AsyncCallExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == ASYNC_CALL_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for SyncCallExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == SYNC_CALL_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for OriginalCallExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == ORIGINAL_CALL_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for VarDeclStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == VAR_DECL_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for AssignStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == ASSIGN_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for SkipStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == SKIP_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ReturnStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == RETURN_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for AssertStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == ASSERT_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for Block {
fn can_cast(kind: SyntaxKind) -> bool {
kind == BLOCK
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for IfStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == IF_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for SwitchStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == SWITCH_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for WhileStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == WHILE_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ForeachStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == FOREACH_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TryCatchFinallyStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TRY_CATCH_FINALLY_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for AwaitStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == AWAIT_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for SuspendStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == SUSPEND_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for DurationStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == DURATION_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ThrowStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == THROW_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for DieStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == DIE_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for MoveCogToStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == MOVE_COG_TO_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ExprStmt {
fn can_cast(kind: SyntaxKind) -> bool {
kind == EXPR_STMT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for CaseStmtBranch {
fn can_cast(kind: SyntaxKind) -> bool {
kind == CASE_STMT_BRANCH
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ClaimGuard {
fn can_cast(kind: SyntaxKind) -> bool {
kind == CLAIM_GUARD
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for DurationGuard {
fn can_cast(kind: SyntaxKind) -> bool {
kind == DURATION_GUARD
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ExprGuard {
fn can_cast(kind: SyntaxKind) -> bool {
kind == EXPR_GUARD
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for AndGuard {
fn can_cast(kind: SyntaxKind) -> bool {
kind == AND_GUARD
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for WildCardPattern {
fn can_cast(kind: SyntaxKind) -> bool {
kind == WILD_CARD_PATTERN
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for IntPattern {
fn can_cast(kind: SyntaxKind) -> bool {
kind == INT_PATTERN
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for StringPattern {
fn can_cast(kind: SyntaxKind) -> bool {
kind == STRING_PATTERN
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for VarPattern {
fn can_cast(kind: SyntaxKind) -> bool {
kind == VAR_PATTERN
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ConstructorPattern {
fn can_cast(kind: SyntaxKind) -> bool {
kind == CONSTRUCTOR_PATTERN
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for DataTypeDecl {
fn can_cast(kind: SyntaxKind) -> bool {
kind == DATA_TYPE_DECL
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for GenericArgList {
fn can_cast(kind: SyntaxKind) -> bool {
kind == GENERIC_ARG_LIST
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for DataConstructorList {
fn can_cast(kind: SyntaxKind) -> bool {
kind == DATA_CONSTRUCTOR_LIST
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for DataConstructor {
fn can_cast(kind: SyntaxKind) -> bool {
kind == DATA_CONSTRUCTOR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for DataConstructorArgList {
fn can_cast(kind: SyntaxKind) -> bool {
kind == DATA_CONSTRUCTOR_ARG_LIST
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for DataConstructorArg {
fn can_cast(kind: SyntaxKind) -> bool {
kind == DATA_CONSTRUCTOR_ARG
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TypeSyn {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TYPE_SYN
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ExceptionDecl {
fn can_cast(kind: SyntaxKind) -> bool {
kind == EXCEPTION_DECL
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for FunctionDecl {
fn can_cast(kind: SyntaxKind) -> bool {
kind == FUNCTION_DECL
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ParFunctionDecl {
fn can_cast(kind: SyntaxKind) -> bool {
kind == PAR_FUNCTION_DECL
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for FunctionNameList {
fn can_cast(kind: SyntaxKind) -> bool {
kind == FUNCTION_NAME_LIST
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for InterfaceDecl {
fn can_cast(kind: SyntaxKind) -> bool {
kind == INTERFACE_DECL
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ExtendsList {
fn can_cast(kind: SyntaxKind) -> bool {
kind == EXTENDS_LIST
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for InterfaceItem {
fn can_cast(kind: SyntaxKind) -> bool {
kind == INTERFACE_ITEM
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for MethodSig {
fn can_cast(kind: SyntaxKind) -> bool {
kind == METHOD_SIG
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for MethodDecl {
fn can_cast(kind: SyntaxKind) -> bool {
kind == METHOD_DECL
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ClassDecl {
fn can_cast(kind: SyntaxKind) -> bool {
kind == CLASS_DECL
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for ImplementsList {
fn can_cast(kind: SyntaxKind) -> bool {
kind == IMPLEMENTS_LIST
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for FieldDecl {
fn can_cast(kind: SyntaxKind) -> bool {
kind == FIELD_DECL
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for RecoverBlock {
fn can_cast(kind: SyntaxKind) -> bool {
kind == RECOVER_BLOCK
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TraitUse {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TRAIT_USE
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for Module {
fn can_cast(kind: SyntaxKind) -> bool {
kind == MODULE
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for StarImport {
fn can_cast(kind: SyntaxKind) -> bool {
kind == STAR_IMPORT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for FromImport {
fn can_cast(kind: SyntaxKind) -> bool {
kind == FROM_IMPORT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for UnqualifiedImport {
fn can_cast(kind: SyntaxKind) -> bool {
kind == UNQUALIFIED_IMPORT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for StarExport {
fn can_cast(kind: SyntaxKind) -> bool {
kind == STAR_EXPORT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for PartialExport {
fn can_cast(kind: SyntaxKind) -> bool {
kind == PARTIAL_EXPORT
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TraitDecl {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TRAIT_DECL
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TraitExpr {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TRAIT_EXPR
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TraitMethodSet {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TRAIT_METHOD_SET
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TraitMethod {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TRAIT_METHOD
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TraitName {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TRAIT_NAME
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TraitRemoveSig {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TRAIT_REMOVE_SIG
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TraitRemoveSet {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TRAIT_REMOVE_SET
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TraitAdd {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TRAIT_ADD
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl AstNode for TraitModifies {
fn can_cast(kind: SyntaxKind) -> bool {
kind == TRAIT_MODIFIES
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) {
Some(Self { syntax })
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.syntax
}
}
impl From<VarName> for AnyName {
fn from(node: VarName) -> AnyName {
AnyName::VarName(node)
}
}
impl From<TypeName> for AnyName {
fn from(node: TypeName) -> AnyName {
AnyName::TypeName(node)
}
}
impl AstNode for AnyName {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
VAR_NAME | TYPE_NAME => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
VAR_NAME => AnyName::VarName(VarName { syntax }),
TYPE_NAME => AnyName::TypeName(TypeName { syntax }),
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
AnyName::VarName(it) => &it.syntax,
AnyName::TypeName(it) => &it.syntax,
}
}
}
impl From<FnExpr> for PureExpr {
fn from(node: FnExpr) -> PureExpr {
PureExpr::FnExpr(node)
}
}
impl From<PartialFnExpr> for PureExpr {
fn from(node: PartialFnExpr) -> PureExpr {
PureExpr::PartialFnExpr(node)
}
}
impl From<VariadicFnExpr> for PureExpr {
fn from(node: VariadicFnExpr) -> PureExpr {
PureExpr::VariadicFnExpr(node)
}
}
impl From<ConstructorExpr> for PureExpr {
fn from(node: ConstructorExpr) -> PureExpr {
PureExpr::ConstructorExpr(node)
}
}
impl From<UnaryExpr> for PureExpr {
fn from(node: UnaryExpr) -> PureExpr {
PureExpr::UnaryExpr(node)
}
}
impl From<BinaryExpr> for PureExpr {
fn from(node: BinaryExpr) -> PureExpr {
PureExpr::BinaryExpr(node)
}
}
impl From<NameExpr> for PureExpr {
fn from(node: NameExpr) -> PureExpr {
PureExpr::NameExpr(node)
}
}
impl From<Literal> for PureExpr {
fn from(node: Literal) -> PureExpr {
PureExpr::Literal(node)
}
}
impl From<ThisExpr> for PureExpr {
fn from(node: ThisExpr) -> PureExpr {
PureExpr::ThisExpr(node)
}
}
impl From<NullExpr> for PureExpr {
fn from(node: NullExpr) -> PureExpr {
PureExpr::NullExpr(node)
}
}
impl From<ImplementsExpr> for PureExpr {
fn from(node: ImplementsExpr) -> PureExpr {
PureExpr::ImplementsExpr(node)
}
}
impl From<AsExpr> for PureExpr {
fn from(node: AsExpr) -> PureExpr {
PureExpr::AsExpr(node)
}
}
impl From<WhenExpr> for PureExpr {
fn from(node: WhenExpr) -> PureExpr {
PureExpr::WhenExpr(node)
}
}
impl From<CaseExpr> for PureExpr {
fn from(node: CaseExpr) -> PureExpr {
PureExpr::CaseExpr(node)
}
}
impl From<LetExpr> for PureExpr {
fn from(node: LetExpr) -> PureExpr {
PureExpr::LetExpr(node)
}
}
impl From<ParenExpr> for PureExpr {
fn from(node: ParenExpr) -> PureExpr {
PureExpr::ParenExpr(node)
}
}
impl AstNode for PureExpr {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
FN_EXPR | PARTIAL_FN_EXPR | VARIADIC_FN_EXPR | CONSTRUCTOR_EXPR | UNARY_EXPR
| BINARY_EXPR | NAME_EXPR | LITERAL | THIS_EXPR | NULL_EXPR | IMPLEMENTS_EXPR
| AS_EXPR | WHEN_EXPR | CASE_EXPR | LET_EXPR | PAREN_EXPR => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
FN_EXPR => PureExpr::FnExpr(FnExpr { syntax }),
PARTIAL_FN_EXPR => PureExpr::PartialFnExpr(PartialFnExpr { syntax }),
VARIADIC_FN_EXPR => PureExpr::VariadicFnExpr(VariadicFnExpr { syntax }),
CONSTRUCTOR_EXPR => PureExpr::ConstructorExpr(ConstructorExpr { syntax }),
UNARY_EXPR => PureExpr::UnaryExpr(UnaryExpr { syntax }),
BINARY_EXPR => PureExpr::BinaryExpr(BinaryExpr { syntax }),
NAME_EXPR => PureExpr::NameExpr(NameExpr { syntax }),
LITERAL => PureExpr::Literal(Literal { syntax }),
THIS_EXPR => PureExpr::ThisExpr(ThisExpr { syntax }),
NULL_EXPR => PureExpr::NullExpr(NullExpr { syntax }),
IMPLEMENTS_EXPR => PureExpr::ImplementsExpr(ImplementsExpr { syntax }),
AS_EXPR => PureExpr::AsExpr(AsExpr { syntax }),
WHEN_EXPR => PureExpr::WhenExpr(WhenExpr { syntax }),
CASE_EXPR => PureExpr::CaseExpr(CaseExpr { syntax }),
LET_EXPR => PureExpr::LetExpr(LetExpr { syntax }),
PAREN_EXPR => PureExpr::ParenExpr(ParenExpr { syntax }),
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
PureExpr::FnExpr(it) => &it.syntax,
PureExpr::PartialFnExpr(it) => &it.syntax,
PureExpr::VariadicFnExpr(it) => &it.syntax,
PureExpr::ConstructorExpr(it) => &it.syntax,
PureExpr::UnaryExpr(it) => &it.syntax,
PureExpr::BinaryExpr(it) => &it.syntax,
PureExpr::NameExpr(it) => &it.syntax,
PureExpr::Literal(it) => &it.syntax,
PureExpr::ThisExpr(it) => &it.syntax,
PureExpr::NullExpr(it) => &it.syntax,
PureExpr::ImplementsExpr(it) => &it.syntax,
PureExpr::AsExpr(it) => &it.syntax,
PureExpr::WhenExpr(it) => &it.syntax,
PureExpr::CaseExpr(it) => &it.syntax,
PureExpr::LetExpr(it) => &it.syntax,
PureExpr::ParenExpr(it) => &it.syntax,
}
}
}
impl From<PureExpr> for Expr {
fn from(node: PureExpr) -> Expr {
Expr::PureExpr(node)
}
}
impl From<EffExpr> for Expr {
fn from(node: EffExpr) -> Expr {
Expr::EffExpr(node)
}
}
impl From<GetExpr> for EffExpr {
fn from(node: GetExpr) -> EffExpr {
EffExpr::GetExpr(node)
}
}
impl From<NewExpr> for EffExpr {
fn from(node: NewExpr) -> EffExpr {
EffExpr::NewExpr(node)
}
}
impl From<AsyncCallExpr> for EffExpr {
fn from(node: AsyncCallExpr) -> EffExpr {
EffExpr::AsyncCallExpr(node)
}
}
impl From<SyncCallExpr> for EffExpr {
fn from(node: SyncCallExpr) -> EffExpr {
EffExpr::SyncCallExpr(node)
}
}
impl From<OriginalCallExpr> for EffExpr {
fn from(node: OriginalCallExpr) -> EffExpr {
EffExpr::OriginalCallExpr(node)
}
}
impl AstNode for EffExpr {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
GET_EXPR | NEW_EXPR | ASYNC_CALL_EXPR | SYNC_CALL_EXPR | ORIGINAL_CALL_EXPR => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
GET_EXPR => EffExpr::GetExpr(GetExpr { syntax }),
NEW_EXPR => EffExpr::NewExpr(NewExpr { syntax }),
ASYNC_CALL_EXPR => EffExpr::AsyncCallExpr(AsyncCallExpr { syntax }),
SYNC_CALL_EXPR => EffExpr::SyncCallExpr(SyncCallExpr { syntax }),
ORIGINAL_CALL_EXPR => EffExpr::OriginalCallExpr(OriginalCallExpr { syntax }),
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
EffExpr::GetExpr(it) => &it.syntax,
EffExpr::NewExpr(it) => &it.syntax,
EffExpr::AsyncCallExpr(it) => &it.syntax,
EffExpr::SyncCallExpr(it) => &it.syntax,
EffExpr::OriginalCallExpr(it) => &it.syntax,
}
}
}
impl From<VarName> for FnListParam {
fn from(node: VarName) -> FnListParam {
FnListParam::VarName(node)
}
}
impl From<AnonFn> for FnListParam {
fn from(node: AnonFn) -> FnListParam {
FnListParam::AnonFn(node)
}
}
impl AstNode for FnListParam {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
VAR_NAME | ANON_FN => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
VAR_NAME => FnListParam::VarName(VarName { syntax }),
ANON_FN => FnListParam::AnonFn(AnonFn { syntax }),
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
FnListParam::VarName(it) => &it.syntax,
FnListParam::AnonFn(it) => &it.syntax,
}
}
}
impl From<WildCardPattern> for Pattern {
fn from(node: WildCardPattern) -> Pattern {
Pattern::WildCardPattern(node)
}
}
impl From<IntPattern> for Pattern {
fn from(node: IntPattern) -> Pattern {
Pattern::IntPattern(node)
}
}
impl From<StringPattern> for Pattern {
fn from(node: StringPattern) -> Pattern {
Pattern::StringPattern(node)
}
}
impl From<VarPattern> for Pattern {
fn from(node: VarPattern) -> Pattern {
Pattern::VarPattern(node)
}
}
impl From<ConstructorPattern> for Pattern {
fn from(node: ConstructorPattern) -> Pattern {
Pattern::ConstructorPattern(node)
}
}
impl AstNode for Pattern {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
WILD_CARD_PATTERN | INT_PATTERN | STRING_PATTERN | VAR_PATTERN
| CONSTRUCTOR_PATTERN => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
WILD_CARD_PATTERN => Pattern::WildCardPattern(WildCardPattern { syntax }),
INT_PATTERN => Pattern::IntPattern(IntPattern { syntax }),
STRING_PATTERN => Pattern::StringPattern(StringPattern { syntax }),
VAR_PATTERN => Pattern::VarPattern(VarPattern { syntax }),
CONSTRUCTOR_PATTERN => Pattern::ConstructorPattern(ConstructorPattern { syntax }),
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
Pattern::WildCardPattern(it) => &it.syntax,
Pattern::IntPattern(it) => &it.syntax,
Pattern::StringPattern(it) => &it.syntax,
Pattern::VarPattern(it) => &it.syntax,
Pattern::ConstructorPattern(it) => &it.syntax,
}
}
}
impl From<VarDeclStmt> for Stmt {
fn from(node: VarDeclStmt) -> Stmt {
Stmt::VarDeclStmt(node)
}
}
impl From<AssignStmt> for Stmt {
fn from(node: AssignStmt) -> Stmt {
Stmt::AssignStmt(node)
}
}
impl From<SkipStmt> for Stmt {
fn from(node: SkipStmt) -> Stmt {
Stmt::SkipStmt(node)
}
}
impl From<ReturnStmt> for Stmt {
fn from(node: ReturnStmt) -> Stmt {
Stmt::ReturnStmt(node)
}
}
impl From<AssertStmt> for Stmt {
fn from(node: AssertStmt) -> Stmt {
Stmt::AssertStmt(node)
}
}
impl From<Block> for Stmt {
fn from(node: Block) -> Stmt {
Stmt::Block(node)
}
}
impl From<IfStmt> for Stmt {
fn from(node: IfStmt) -> Stmt {
Stmt::IfStmt(node)
}
}
impl From<SwitchStmt> for Stmt {
fn from(node: SwitchStmt) -> Stmt {
Stmt::SwitchStmt(node)
}
}
impl From<WhileStmt> for Stmt {
fn from(node: WhileStmt) -> Stmt {
Stmt::WhileStmt(node)
}
}
impl From<ForeachStmt> for Stmt {
fn from(node: ForeachStmt) -> Stmt {
Stmt::ForeachStmt(node)
}
}
impl From<TryCatchFinallyStmt> for Stmt {
fn from(node: TryCatchFinallyStmt) -> Stmt {
Stmt::TryCatchFinallyStmt(node)
}
}
impl From<AwaitStmt> for Stmt {
fn from(node: AwaitStmt) -> Stmt {
Stmt::AwaitStmt(node)
}
}
impl From<SuspendStmt> for Stmt {
fn from(node: SuspendStmt) -> Stmt {
Stmt::SuspendStmt(node)
}
}
impl From<DurationStmt> for Stmt {
fn from(node: DurationStmt) -> Stmt {
Stmt::DurationStmt(node)
}
}
impl From<ThrowStmt> for Stmt {
fn from(node: ThrowStmt) -> Stmt {
Stmt::ThrowStmt(node)
}
}
impl From<DieStmt> for Stmt {
fn from(node: DieStmt) -> Stmt {
Stmt::DieStmt(node)
}
}
impl From<MoveCogToStmt> for Stmt {
fn from(node: MoveCogToStmt) -> Stmt {
Stmt::MoveCogToStmt(node)
}
}
impl From<ExprStmt> for Stmt {
fn from(node: ExprStmt) -> Stmt {
Stmt::ExprStmt(node)
}
}
impl AstNode for Stmt {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
VAR_DECL_STMT
| ASSIGN_STMT
| SKIP_STMT
| RETURN_STMT
| ASSERT_STMT
| BLOCK
| IF_STMT
| SWITCH_STMT
| WHILE_STMT
| FOREACH_STMT
| TRY_CATCH_FINALLY_STMT
| AWAIT_STMT
| SUSPEND_STMT
| DURATION_STMT
| THROW_STMT
| DIE_STMT
| MOVE_COG_TO_STMT
| EXPR_STMT => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
VAR_DECL_STMT => Stmt::VarDeclStmt(VarDeclStmt { syntax }),
ASSIGN_STMT => Stmt::AssignStmt(AssignStmt { syntax }),
SKIP_STMT => Stmt::SkipStmt(SkipStmt { syntax }),
RETURN_STMT => Stmt::ReturnStmt(ReturnStmt { syntax }),
ASSERT_STMT => Stmt::AssertStmt(AssertStmt { syntax }),
BLOCK => Stmt::Block(Block { syntax }),
IF_STMT => Stmt::IfStmt(IfStmt { syntax }),
SWITCH_STMT => Stmt::SwitchStmt(SwitchStmt { syntax }),
WHILE_STMT => Stmt::WhileStmt(WhileStmt { syntax }),
FOREACH_STMT => Stmt::ForeachStmt(ForeachStmt { syntax }),
TRY_CATCH_FINALLY_STMT => Stmt::TryCatchFinallyStmt(TryCatchFinallyStmt { syntax }),
AWAIT_STMT => Stmt::AwaitStmt(AwaitStmt { syntax }),
SUSPEND_STMT => Stmt::SuspendStmt(SuspendStmt { syntax }),
DURATION_STMT => Stmt::DurationStmt(DurationStmt { syntax }),
THROW_STMT => Stmt::ThrowStmt(ThrowStmt { syntax }),
DIE_STMT => Stmt::DieStmt(DieStmt { syntax }),
MOVE_COG_TO_STMT => Stmt::MoveCogToStmt(MoveCogToStmt { syntax }),
EXPR_STMT => Stmt::ExprStmt(ExprStmt { syntax }),
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
Stmt::VarDeclStmt(it) => &it.syntax,
Stmt::AssignStmt(it) => &it.syntax,
Stmt::SkipStmt(it) => &it.syntax,
Stmt::ReturnStmt(it) => &it.syntax,
Stmt::AssertStmt(it) => &it.syntax,
Stmt::Block(it) => &it.syntax,
Stmt::IfStmt(it) => &it.syntax,
Stmt::SwitchStmt(it) => &it.syntax,
Stmt::WhileStmt(it) => &it.syntax,
Stmt::ForeachStmt(it) => &it.syntax,
Stmt::TryCatchFinallyStmt(it) => &it.syntax,
Stmt::AwaitStmt(it) => &it.syntax,
Stmt::SuspendStmt(it) => &it.syntax,
Stmt::DurationStmt(it) => &it.syntax,
Stmt::ThrowStmt(it) => &it.syntax,
Stmt::DieStmt(it) => &it.syntax,
Stmt::MoveCogToStmt(it) => &it.syntax,
Stmt::ExprStmt(it) => &it.syntax,
}
}
}
impl From<ClaimGuard> for Guard {
fn from(node: ClaimGuard) -> Guard {
Guard::ClaimGuard(node)
}
}
impl From<DurationGuard> for Guard {
fn from(node: DurationGuard) -> Guard {
Guard::DurationGuard(node)
}
}
impl From<ExprGuard> for Guard {
fn from(node: ExprGuard) -> Guard {
Guard::ExprGuard(node)
}
}
impl From<AndGuard> for Guard {
fn from(node: AndGuard) -> Guard {
Guard::AndGuard(node)
}
}
impl AstNode for Guard {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
CLAIM_GUARD | DURATION_GUARD | EXPR_GUARD | AND_GUARD => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
CLAIM_GUARD => Guard::ClaimGuard(ClaimGuard { syntax }),
DURATION_GUARD => Guard::DurationGuard(DurationGuard { syntax }),
EXPR_GUARD => Guard::ExprGuard(ExprGuard { syntax }),
AND_GUARD => Guard::AndGuard(AndGuard { syntax }),
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
Guard::ClaimGuard(it) => &it.syntax,
Guard::DurationGuard(it) => &it.syntax,
Guard::ExprGuard(it) => &it.syntax,
Guard::AndGuard(it) => &it.syntax,
}
}
}
impl From<StarImport> for Import {
fn from(node: StarImport) -> Import {
Import::StarImport(node)
}
}
impl From<FromImport> for Import {
fn from(node: FromImport) -> Import {
Import::FromImport(node)
}
}
impl From<UnqualifiedImport> for Import {
fn from(node: UnqualifiedImport) -> Import {
Import::UnqualifiedImport(node)
}
}
impl AstNode for Import {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
STAR_IMPORT | FROM_IMPORT | UNQUALIFIED_IMPORT => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
STAR_IMPORT => Import::StarImport(StarImport { syntax }),
FROM_IMPORT => Import::FromImport(FromImport { syntax }),
UNQUALIFIED_IMPORT => Import::UnqualifiedImport(UnqualifiedImport { syntax }),
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
Import::StarImport(it) => &it.syntax,
Import::FromImport(it) => &it.syntax,
Import::UnqualifiedImport(it) => &it.syntax,
}
}
}
impl From<StarExport> for Export {
fn from(node: StarExport) -> Export {
Export::StarExport(node)
}
}
impl From<PartialExport> for Export {
fn from(node: PartialExport) -> Export {
Export::PartialExport(node)
}
}
impl AstNode for Export {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
STAR_EXPORT | PARTIAL_EXPORT => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
STAR_EXPORT => Export::StarExport(StarExport { syntax }),
PARTIAL_EXPORT => Export::PartialExport(PartialExport { syntax }),
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
Export::StarExport(it) => &it.syntax,
Export::PartialExport(it) => &it.syntax,
}
}
}
impl From<DataTypeDecl> for Decl {
fn from(node: DataTypeDecl) -> Decl {
Decl::DataTypeDecl(node)
}
}
impl From<FunctionDecl> for Decl {
fn from(node: FunctionDecl) -> Decl {
Decl::FunctionDecl(node)
}
}
impl From<ParFunctionDecl> for Decl {
fn from(node: ParFunctionDecl) -> Decl {
Decl::ParFunctionDecl(node)
}
}
impl From<TypeSyn> for Decl {
fn from(node: TypeSyn) -> Decl {
Decl::TypeSyn(node)
}
}
impl From<ExceptionDecl> for Decl {
fn from(node: ExceptionDecl) -> Decl {
Decl::ExceptionDecl(node)
}
}
impl From<InterfaceDecl> for Decl {
fn from(node: InterfaceDecl) -> Decl {
Decl::InterfaceDecl(node)
}
}
impl From<ClassDecl> for Decl {
fn from(node: ClassDecl) -> Decl {
Decl::ClassDecl(node)
}
}
impl From<TraitDecl> for Decl {
fn from(node: TraitDecl) -> Decl {
Decl::TraitDecl(node)
}
}
impl AstNode for Decl {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
DATA_TYPE_DECL | FUNCTION_DECL | PAR_FUNCTION_DECL | TYPE_SYN | EXCEPTION_DECL
| INTERFACE_DECL | CLASS_DECL | TRAIT_DECL => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
DATA_TYPE_DECL => Decl::DataTypeDecl(DataTypeDecl { syntax }),
FUNCTION_DECL => Decl::FunctionDecl(FunctionDecl { syntax }),
PAR_FUNCTION_DECL => Decl::ParFunctionDecl(ParFunctionDecl { syntax }),
TYPE_SYN => Decl::TypeSyn(TypeSyn { syntax }),
EXCEPTION_DECL => Decl::ExceptionDecl(ExceptionDecl { syntax }),
INTERFACE_DECL => Decl::InterfaceDecl(InterfaceDecl { syntax }),
CLASS_DECL => Decl::ClassDecl(ClassDecl { syntax }),
TRAIT_DECL => Decl::TraitDecl(TraitDecl { syntax }),
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
Decl::DataTypeDecl(it) => &it.syntax,
Decl::FunctionDecl(it) => &it.syntax,
Decl::ParFunctionDecl(it) => &it.syntax,
Decl::TypeSyn(it) => &it.syntax,
Decl::ExceptionDecl(it) => &it.syntax,
Decl::InterfaceDecl(it) => &it.syntax,
Decl::ClassDecl(it) => &it.syntax,
Decl::TraitDecl(it) => &it.syntax,
}
}
}
impl From<TraitMethodSet> for BasicTraitExpr {
fn from(node: TraitMethodSet) -> BasicTraitExpr {
BasicTraitExpr::TraitMethodSet(node)
}
}
impl From<TraitMethod> for BasicTraitExpr {
fn from(node: TraitMethod) -> BasicTraitExpr {
BasicTraitExpr::TraitMethod(node)
}
}
impl From<TraitName> for BasicTraitExpr {
fn from(node: TraitName) -> BasicTraitExpr {
BasicTraitExpr::TraitName(node)
}
}
impl AstNode for BasicTraitExpr {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
TRAIT_METHOD_SET | TRAIT_METHOD | TRAIT_NAME => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
TRAIT_METHOD_SET => BasicTraitExpr::TraitMethodSet(TraitMethodSet { syntax }),
TRAIT_METHOD => BasicTraitExpr::TraitMethod(TraitMethod { syntax }),
TRAIT_NAME => BasicTraitExpr::TraitName(TraitName { syntax }),
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
BasicTraitExpr::TraitMethodSet(it) => &it.syntax,
BasicTraitExpr::TraitMethod(it) => &it.syntax,
BasicTraitExpr::TraitName(it) => &it.syntax,
}
}
}
impl From<TraitRemoveSig> for TraitOp {
fn from(node: TraitRemoveSig) -> TraitOp {
TraitOp::TraitRemoveSig(node)
}
}
impl From<TraitRemoveSet> for TraitOp {
fn from(node: TraitRemoveSet) -> TraitOp {
TraitOp::TraitRemoveSet(node)
}
}
impl From<TraitAdd> for TraitOp {
fn from(node: TraitAdd) -> TraitOp {
TraitOp::TraitAdd(node)
}
}
impl From<TraitModifies> for TraitOp {
fn from(node: TraitModifies) -> TraitOp {
TraitOp::TraitModifies(node)
}
}
impl AstNode for TraitOp {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
TRAIT_REMOVE_SIG | TRAIT_REMOVE_SET | TRAIT_ADD | TRAIT_MODIFIES => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
TRAIT_REMOVE_SIG => TraitOp::TraitRemoveSig(TraitRemoveSig { syntax }),
TRAIT_REMOVE_SET => TraitOp::TraitRemoveSet(TraitRemoveSet { syntax }),
TRAIT_ADD => TraitOp::TraitAdd(TraitAdd { syntax }),
TRAIT_MODIFIES => TraitOp::TraitModifies(TraitModifies { syntax }),
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
TraitOp::TraitRemoveSig(it) => &it.syntax,
TraitOp::TraitRemoveSet(it) => &it.syntax,
TraitOp::TraitAdd(it) => &it.syntax,
TraitOp::TraitModifies(it) => &it.syntax,
}
}
}
impl std::fmt::Display for AnyName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for PureExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Expr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for EffExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for FnListParam {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Pattern {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Stmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Guard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Import {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Export {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Decl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for BasicTraitExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TraitOp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for VarName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TypeName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Path {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TypePath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ParamList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Param {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Annotations {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Type {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Annotation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for FnExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for PartialFnExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for VariadicFnExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ConstructorExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for UnaryExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for BinaryExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for NameExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Literal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ThisExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for NullExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ImplementsExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for AsExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for WhenExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for CaseExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for LetExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ParenExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for PureExprList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for FnList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for CaseExprBranch {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for LetDefs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for AnonFn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for LetDef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for GetExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for NewExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for AsyncCallExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for SyncCallExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for OriginalCallExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for VarDeclStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for AssignStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for SkipStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ReturnStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for AssertStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Block {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for IfStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for SwitchStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for WhileStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ForeachStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TryCatchFinallyStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for AwaitStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for SuspendStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for DurationStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ThrowStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for DieStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for MoveCogToStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ExprStmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for CaseStmtBranch {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ClaimGuard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for DurationGuard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ExprGuard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for AndGuard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for WildCardPattern {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for IntPattern {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for StringPattern {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for VarPattern {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ConstructorPattern {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for DataTypeDecl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for GenericArgList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for DataConstructorList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for DataConstructor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for DataConstructorArgList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for DataConstructorArg {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TypeSyn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ExceptionDecl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for FunctionDecl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ParFunctionDecl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for FunctionNameList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for InterfaceDecl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ExtendsList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for InterfaceItem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for MethodSig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for MethodDecl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ClassDecl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for ImplementsList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for FieldDecl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for RecoverBlock {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TraitUse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for Module {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for StarImport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for FromImport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for UnqualifiedImport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for StarExport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for PartialExport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TraitDecl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TraitExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TraitMethodSet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TraitMethod {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TraitName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TraitRemoveSig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TraitRemoveSet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TraitAdd {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
impl std::fmt::Display for TraitModifies {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.syntax(), f)
}
}
|
use pest::iterators::{Pair, Pairs};
use pest::Parser;
use crate::errors::{Error, Result as GuardingResult};
use crate::ast::{Expr, GuardRule, Operator, RuleAssert, RuleLevel, RuleScope};
use crate::support::str_support;
#[derive(Parser)]
#[grammar = "guarding.pest"]
struct IdentParser;
pub fn parse(code: &str) -> GuardingResult<Vec<GuardRule>> {
match IdentParser::parse(Rule::start, code) {
Err(e) => {
let fancy_e = e.renamed_rules(|rule| {
match *rule {
Rule::operator => {
format!("{:?}", rule)
}
_ => {
format!("{:?}", rule)
}
}
});
return Err(Error::msg(fancy_e));
}
Ok(pairs) => {
Ok(consume_rules_with_spans(pairs))
}
}
}
fn consume_rules_with_spans(pairs: Pairs<Rule>) -> Vec<GuardRule> {
pairs.filter(|pair| {
return pair.as_rule() == Rule::declaration;
}).map(|pair| {
let mut rule: GuardRule = Default::default();
for p in pair.into_inner() {
match p.as_rule() {
Rule::normal_rule => {
rule = parse_normal_rule(p);
}
Rule::layer_rule => {
rule = parse_layer_rule(p);
}
_ => panic!("unreachable content rule: {:?}", p.as_rule())
};
}
return rule;
})
.collect::<Vec<GuardRule>>()
}
fn parse_layer_rule(_pair: Pair<Rule>) -> GuardRule {
println!("todo: in processed");
GuardRule::default()
}
fn parse_normal_rule(pair: Pair<Rule>) -> GuardRule {
let mut guard_rule = GuardRule::default();
for p in pair.into_inner() {
match p.as_rule() {
Rule::rule_level => {
guard_rule.level = parse_rule_level(p);
}
Rule::use_symbol => {
// may be can do something, but still nothing.
}
Rule::expression => {
guard_rule.expr = parse_expr(p);
}
Rule::operator => {
guard_rule.ops = parse_operator(p);
}
Rule::assert => {
guard_rule.assert = parse_assert(p);
}
Rule::scope => {
guard_rule.scope = parse_scope(p);
}
Rule::should => {
// should do nothing
}
Rule::only => {
// should do nothing
}
_ => {
println!("implementing rule: {:?}, level: {:?}", p.as_rule(), p.as_span());
}
}
}
guard_rule
}
fn parse_rule_level(pair: Pair<Rule>) -> RuleLevel {
let level_str = pair.as_span().as_str();
match level_str {
"package" => { RuleLevel::Package }
"function" => { RuleLevel::Function }
"class" => { RuleLevel::Class }
"struct" => { RuleLevel::Struct }
&_ => { unreachable!("error rule level: {:?}", level_str) }
}
}
fn parse_operator(parent: Pair<Rule>) -> Vec<Operator> {
let mut pairs = parent.into_inner();
let mut pair = pairs.next().unwrap();
let mut operators: Vec<Operator> = vec![];
match pair.as_rule() {
Rule::op_not | Rule::op_not_symbol => {
operators.push(Operator::Not);
// get next operator
pair = pairs.next().unwrap().into_inner().next().unwrap();
}
_ => {}
}
let ops = match pair.as_rule() {
Rule::op_lte => { Operator::Lte }
Rule::op_gte => { Operator::Gte }
Rule::op_lt => { Operator::Lt }
Rule::op_gt => { Operator::Gt }
Rule::op_eq => { Operator::Eq }
Rule::op_ineq => { Operator::Ineq }
Rule::op_contains => { Operator::Contains }
Rule::op_endsWith => { Operator::Endswith }
Rule::op_startsWith => { Operator::StartsWith }
Rule::op_inside => { Operator::Inside }
Rule::op_resideIn => { Operator::ResideIn }
Rule::op_accessed => { Operator::Accessed }
Rule::op_dependBy => { Operator::DependBy }
_ => {
panic!("implementing ops: {:?}, text: {:?}", pair.as_rule(), pair.as_span())
}
};
operators.push(ops);
operators
}
fn parse_expr(parent: Pair<Rule>) -> Expr {
let mut pairs = parent.into_inner();
let pair = pairs.next().unwrap();
match pair.as_rule() {
Rule::fn_call => {
let mut call_chains: Vec<String> = vec![];
for p in pair.into_inner() {
match p.as_rule() {
Rule::identifier => {
let ident = p.as_span().as_str().to_string();
call_chains.push(ident);
}
_ => {}
};
};
return Expr::PropsCall(call_chains);
}
_ => {
panic!("implementing expr: {:?}, text: {:?}", pair.as_rule(), pair.as_span())
}
};
}
fn parse_assert(parent: Pair<Rule>) -> RuleAssert {
let mut pairs = parent.into_inner();
let pair = pairs.next().unwrap();
match pair.as_rule() {
Rule::leveled => {
let mut level = RuleLevel::Class;
let mut str = "".to_string();
for p in pair.into_inner() {
match p.as_rule() {
Rule::rule_level => {
level = parse_rule_level(p);
}
Rule::string => {
str = str_support::replace_string_markers(p.as_str());
}
_ => {}
}
}
RuleAssert::Leveled(level, str)
}
Rule::sized => {
let mut pairs = pair.into_inner();
let pair = pairs.next().unwrap();
let size: usize = pair.as_str()
.parse()
.expect("convert int error");
RuleAssert::Sized(size)
}
Rule::stringed => {
let mut pairs = pair.into_inner();
let pair = pairs.next().unwrap();
let str = str_support::replace_string_markers(pair.as_str());
RuleAssert::Stringed(str.to_string())
}
Rule::array_stringed => {
let mut array = vec![];
for p in pair.into_inner() {
match p.as_rule() {
Rule::string => {
let str = str_support::replace_string_markers(p.as_str());
array.push(str);
}
_ => {}
}
}
RuleAssert::ArrayStringed(array)
}
_ => { RuleAssert::Empty }
}
}
fn parse_scope(parent: Pair<Rule>) -> RuleScope {
let mut pairs = parent.into_inner();
let pair = pairs.next().unwrap();
match pair.as_rule() {
Rule::path_scope => {
let without_markers = str_support::replace_string_markers(pair.as_str());
let string = str_support::unescape(without_markers.as_str()).expect("incorrect string literal");
RuleScope::PathDefine(string)
}
Rule::assignable_scope => {
let string = string_from_pair(pair);
RuleScope::Assignable(string)
}
Rule::extend_scope => {
let string = string_from_pair(pair);
RuleScope::Extend(string)
}
Rule::match_scope => {
let string = string_from_pair(pair);
RuleScope::MatchRegex(string)
}
Rule::impl_scope => {
let string = string_from_pair(pair);
RuleScope::Implementation(string)
}
_ => {
println!("implementing scope: {:?}, text: {:?}", pair.as_rule(), pair.as_span());
RuleScope::All
}
}
}
fn string_from_pair(pair: Pair<Rule>) -> String {
let mut string = "".to_string();
for p in pair.into_inner() {
match p.as_rule() {
Rule::string => {
let without_markers = str_support::replace_string_markers(p.as_str());
string = str_support::unescape(without_markers.as_str()).expect("incorrect string literal");
}
_ => {}
}
}
string
}
#[cfg(test)]
mod tests {
use crate::ast::{Expr, Operator, RuleAssert, RuleLevel, RuleScope};
use crate::parser::parse;
#[test]
fn should_parse_string_assert() {
let code = "class::name contains \"Controller\";";
let rules = parse(code).unwrap();
assert_eq!(1, rules.len());
assert_eq!(RuleLevel::Class, rules[0].level);
assert_eq!(RuleScope::All, rules[0].scope);
assert_eq!(RuleAssert::Stringed("Controller".to_string()), rules[0].assert);
}
#[test]
fn should_parse_struct() {
let code = "struct::name contains \"Controller\";";
let rules = parse(code).unwrap();
assert_eq!(RuleLevel::Struct, rules[0].level);
assert_eq!(RuleAssert::Stringed("Controller".to_string()), rules[0].assert);
}
#[test]
fn should_parse_package_asset() {
let code = "class(\"..myapp..\")::function.name should contains(\"\");";
let rules = parse(code).unwrap();
assert_eq!(RuleScope::PathDefine(("..myapp..").to_string()), rules[0].scope);
let chains = vec!["function".to_string(), "name".to_string()];
assert_eq!(Expr::PropsCall(chains), rules[0].expr);
}
#[test]
fn should_parse_package_extends() {
let code = "class(extends \"Connection.class\")::name endsWith \"Connection\";";
let vec = parse(code).unwrap();
assert_eq!(1, vec[0].ops.len());
assert_eq!(Operator::Endswith, vec[0].ops[0])
}
#[test]
fn should_parse_not_symbol() {
let code = "class(extends \"Connection.class\")::name should not endsWith \"Connection\";";
let vec = parse(code).unwrap();
assert_eq!(2, vec[0].ops.len());
assert_eq!(Operator::Not, vec[0].ops[0]);
assert_eq!(Operator::Endswith, vec[0].ops[1]);
assert_eq!(RuleScope::Extend("Connection.class".to_string()), vec[0].scope);
}
#[test]
fn should_parse_sized_assert() {
let code = "class(\"..myapp..\")::function.vars.len should <= 20;";
let vec = parse(code).unwrap();
assert_eq!(RuleAssert::Sized(20), vec[0].assert);
}
#[test]
fn should_parse_package_container_scope() {
let code = "class(assignable \"EntityManager.class\") resideIn package(\"..persistence.\");";
let vec = parse(code).unwrap();
assert_eq!(RuleAssert::Leveled(RuleLevel::Package, "..persistence.".to_string()), vec[0].assert);
}
#[test]
fn should_parse_package_regex() {
let code = "package(match(\"^/app\")) endsWith \"Connection\";";
let vec = parse(code).unwrap();
assert_eq!(RuleScope::MatchRegex("^/app".to_string()), vec[0].scope);
}
#[test]
fn should_parse_array_stringed() {
let code = "class(\"..service..\") only accessed([\"..controller..\", \"..service..\"]);";
let vec = parse(code).unwrap();
let results = vec!["..controller..".to_string(), "..service..".to_string()];
assert_eq!(RuleAssert::ArrayStringed(results), vec[0].assert);
}
#[test]
fn should_parse_class_compare() {
let code = "class(\"..myapp..\")::function.name should not contains(\"\");
class(\"..myapp..\")::function.name !contains(\"\");
class(\"..myapp..\")::vars.len should <= 20;
class(\"..myapp..\")::function.vars.len should <= 20;
";
parse(code).unwrap();
}
#[test]
fn should_parse_simple_usage() {
let code = "class::name.len should < 20;
function::name.len should < 30;
";
parse(code).unwrap();
}
#[test]
fn should_parse_arrow_usage() {
let code = "class -> name.len should < 20;
function -> name.len should < 30;
";
parse(code).unwrap();
}
#[test]
fn should_parse_layer() {
let code = "layer(\"onion\")
::domainModel(\"\")
::domainService(\"\")
::applicationService(\"\")
::adapter(\"com.phodal.com\", \"zero\");
";
parse(code).unwrap();
}
#[test]
fn should_ignore_error() {
let content = "class(\"java.util.Map\") only something([\"com.phodal.pepper.refactor.staticclass\"]);";
match parse(content) {
Ok(_) => {
assert!(false);
}
Err(err) => {
let string = format!("{:?}", err);
assert!(string.contains("^---"));
}
}
}
#[test]
fn should_ignore_comments() {
let code = "// path: src/*
";
parse(code).unwrap();
}
} |
use simple_gl::storage::buffer::*;
use crate::{Vector2, clamp};
use anyhow::Result;
pub struct World {
pub vbo: VboBuffer<[f32; 2], DynamicBuffer>,
pub avbo: VboBuffer<f32, DynamicBuffer>,
pub vao: Vao,
pub ebo: EboBuffer<u32, StaticBuffer>,
vert_count: u32,
xcount: usize,
ycount: usize
}
impl World {
pub fn new(
width: f32,
height: f32,
xcount: usize,
ycount: usize
) -> Result<World> {
// GENERATE VERTICIES
let mut verticies = Vec::new();
let mut amounts = Vec::new();
for ix in 0..(ycount + 1) {
let y = ix as f32 / ycount as f32;
for iy in 0..(xcount + 1) {
let x = iy as f32 / xcount as f32;
let mut amount = 0f32;
if ix == iy {
amount = 1.0;
}
verticies.push([(x*2. - 1.) * width, (1. - y*2.) * height]);
amounts.push(amount);
}
}
// GENERATE INDEX INTO VERTICIES
let xwidth: usize = xcount + 1;
let mut index: Vec<u32> = Vec::new();
for iy in 0..ycount {
for ix in 0..xcount {
index.push((ix + iy * xwidth) as u32);
index.push(((ix + 1) + iy * xwidth) as u32);
index.push(((ix + 1) + (iy + 1) * xwidth) as u32);
index.push((ix + (iy + 1) * xwidth) as u32);
}
}
// CREATE VBO
let mut vbo = VboBuffer::new(
&verticies
);
let mut avbo = VboBuffer::new(
&amounts
);
//CREATE VAO
let mut vao = Vao::new(Format::LinesAdj, 2);
vao.bind_vbo(
0,
&mut vbo
)?;
vao.bind_vbo(
1,
&mut avbo
)?;
// CREATE EBO
let ebo = EboBuffer::new(
&index
);
Ok(World {
vbo,
avbo,
vao,
ebo,
vert_count: index.len() as u32,
xcount,
ycount
})
}
pub fn add(&mut self, pos: Vector2, amount: f32) {
let pos0 = Vector2::new(pos.index(0).floor(), pos.index(1).floor());
let pos1 = pos0 + Vector2::new(1., 0.);
let pos2 = pos0 + Vector2::new(0., 1.);
let pos3 = pos0 + Vector2::new(1., 1.);
let max_dist: f32 = 45f32.sin() * 2.;
let ratio0 = 1. - (pos.metric_distance(&pos0) / max_dist);
let ratio1 = 1. - (pos.metric_distance(&pos1) / max_dist);
let ratio2 = 1. - (pos.metric_distance(&pos2) / max_dist);
let ratio3 = 1. - (pos.metric_distance(&pos3) / max_dist);
let index0 = (pos0.index(0) + pos0.index(1) * (self.xcount + 1) as f32) as usize;
let index1 = index0 + 1;
let index2 = index0 + 1 + self.xcount;
let index3 = index0 + 2 + self.xcount;
let mut avbo = self.avbo.write();
let map = &mut *avbo;
map[index0] = clamp(0., 1., map[index0] + amount * ratio0);
map[index1] = clamp(0., 1., map[index1] + amount * ratio1);
map[index2] = clamp(0., 1., map[index2] + amount * ratio2);
map[index3] = clamp(0., 1., map[index3] + amount * ratio3);
}
pub fn draw(&mut self) {
self.ebo.bind();
self.vao.bind();
self.vao.draw_elements(self.vert_count, Primitive::UInt, 0);
}
} |
use ctor::ctor;
use libc::{c_char, c_int};
use std::ffi::CStr;
#[ctor]
unsafe fn ctor() {
kernaux_sys::assert_cb = Some(assert_cb);
}
unsafe extern "C" fn assert_cb(
file: *const c_char,
line: c_int,
msg: *const c_char,
) {
let file = CStr::from_ptr(file).to_str().unwrap();
let msg = CStr::from_ptr(msg).to_str().unwrap();
panic!("{}:{}:{}", file, line, msg);
}
#[cfg(test)]
mod tests {
use std::ffi::CString;
#[test]
#[should_panic(expected = "foo.rs:123:bar")]
fn default() {
let file = CString::new("foo.rs").unwrap();
let msg = CString::new("bar").unwrap();
unsafe { kernaux_sys::assert_do(file.as_ptr(), 123, msg.as_ptr()) }
}
}
|
use parity_wasm::builder::*;
use parity_wasm::elements::{
ExportEntry, External, GlobalEntry, ImportEntry, Instruction, Instructions, Internal,
MemoryType, Module,
};
use std::cell::Cell;
use parity_wasm::{builder, elements, serialize};
use wasmer_runtime::memory::Atomic;
use wasmer_runtime::{
func, imports, instantiate, memory::MemoryView, units::Pages, Ctx, Export, Instance, Value,
};
use wasmer_runtime_core::import::LikeNamespace;
use wabt;
pub struct TransferContract {}
#[rustfmt::skip]
impl TransferContract {
pub fn compile() -> Vec<u8> {
let mut module_builder = ModuleBuilder::new();
let reserved_memory = MemoryBuilder::new().with_min(1).with_max(None).build();
module_builder.push_memory(reserved_memory);
let export_mem = ExportEntry::new("req_mem".to_string(), Internal::Memory(0));
module_builder.push_export(export_mem);
let module: Module = module_builder.build();
let wasm = parity_wasm::serialize(module).unwrap();
wasm
}
pub fn instantiate(wasm: &[u8]) -> Instance {
let imports = imports! { };
let instance = instantiate(&wasm, &imports).unwrap();
instance
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_compile_transfer_contract() {
let wasm = TransferContract::compile();
// pretty printing
let wast = wabt::wasm2wat(&wasm).unwrap();
println!("{}", wast);
let mut instance = TransferContract::instantiate(&wasm);
let ctx = instance.context_mut();
for cell in ctx.memory(0).view()[0..3].iter() {
cell.set(0xA);
}
}
}
|
pub use super::rasterizationorderamd::*;
|
// 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::convert::Infallible;
use std::future::Future;
use std::net::SocketAddr;
use axum::body::Bytes;
use axum::body::Full;
use axum::extract::Extension;
use axum::handler::get;
use axum::http::Response;
use axum::response::Html;
use axum::response::IntoResponse;
use axum::AddExtensionLayer;
use axum::Router;
use common_base::tokio;
use common_base::tokio::task::JoinHandle;
use common_exception::ErrorCode;
use common_exception::Result;
use futures::future::AbortHandle;
use futures::future::AbortRegistration;
use futures::future::Abortable;
use futures::StreamExt;
use hyper::server::conn::Http;
use metrics_exporter_prometheus::PrometheusBuilder;
use metrics_exporter_prometheus::PrometheusHandle;
use tokio_stream::wrappers::TcpListenerStream;
use crate::servers::server::ListeningStream;
use crate::servers::Server;
pub struct MetricService {
join_handle: Option<JoinHandle<()>>,
abort_handle: AbortHandle,
abort_registration: Option<AbortRegistration>,
}
pub struct MetricTemplate {
prom: PrometheusHandle,
}
impl IntoResponse for MetricTemplate {
type Body = Full<Bytes>;
type BodyError = Infallible;
fn into_response(self) -> Response<Self::Body> {
Html(self.prom.render()).into_response()
}
}
pub async fn metric_handler(prom_extension: Extension<PrometheusHandle>) -> MetricTemplate {
let prom = prom_extension.0;
MetricTemplate { prom }
}
// build axum router for metric server
macro_rules! build_router {
($prometheus: expr) => {
Router::new()
.route("/", get(metric_handler))
.layer(AddExtensionLayer::new($prometheus.clone()))
};
}
impl MetricService {
pub fn create() -> Box<dyn Server> {
let (abort_handle, registration) = AbortHandle::new_pair();
Box::new(MetricService {
abort_handle,
abort_registration: Some(registration),
join_handle: None,
})
}
fn create_prometheus_handle() -> Result<PrometheusHandle> {
let builder = PrometheusBuilder::new();
let prometheus_recorder = builder.build();
let prometheus_handle = prometheus_recorder.handle();
match metrics::set_boxed_recorder(Box::new(prometheus_recorder)) {
Ok(_) => Ok(prometheus_handle),
Err(error) => Err(ErrorCode::InitPrometheusFailure(format!(
"Cannot init prometheus recorder. cause: {}",
error
))),
}
}
async fn listener_tcp(socket: SocketAddr) -> Result<(TcpListenerStream, SocketAddr)> {
let listener = tokio::net::TcpListener::bind(socket).await?;
let listener_addr = listener.local_addr()?;
Ok((TcpListenerStream::new(listener), listener_addr))
}
// TODO(zhihanz) add TLS config for metric server
fn listen_loop(
&self,
stream: ListeningStream,
handler: PrometheusHandle,
) -> impl Future<Output = ()> {
let app = build_router!(handler);
stream.for_each(move |accept_socket| {
let app = app.clone();
async move {
match accept_socket {
Err(error) => log::error!("Broken http connection: {}", error),
Ok(socket) => {
tokio::spawn(async move {
Http::new().serve_connection(socket, app).await.unwrap();
});
}
};
}
})
}
}
#[async_trait::async_trait]
impl Server for MetricService {
async fn shutdown(&mut self) {
self.abort_handle.abort();
if let Some(join_handle) = self.join_handle.take() {
if let Err(error) = join_handle.await {
log::error!(
"Unexpected error during shutdown Http API handler. cause {}",
error
);
}
}
}
async fn start(&mut self, listening: SocketAddr) -> Result<SocketAddr> {
match self.abort_registration.take() {
None => Err(ErrorCode::LogicalError("Http Service already running.")),
Some(registration) => {
let handle = MetricService::create_prometheus_handle()?;
let (stream, listener) = Self::listener_tcp(listening).await?;
let stream = Abortable::new(stream, registration);
self.join_handle = Some(tokio::spawn(self.listen_loop(stream, handle)));
Ok(listener)
}
}
}
}
|
use std::cmp::max;
use std::borrow::Cow;
static DFA: [u16; 33840] = include!("EN_dfa.in");
static RAW: [u8; 1964] = include!("EN_raw.in");
pub fn detect(content: &str) -> Vec<u8> {
let mut result: Vec<u8> = vec![0; content.len() + 1];
let mut cursor: usize = 184;
let content = content
.as_bytes()
.iter()
.map(|&x| match x {
0x41...0x5A => (x as usize + 32) << 2,
0x61...0x7A => (x as usize) << 2,
_ => unreachable!(),
})
.chain([184].iter().cloned())
.enumerate();
for (idx, chr) in content {
loop {
let offset: usize = DFA[cursor] as usize + chr;
if offset < 33840 && (DFA[offset + 1] as usize) == cursor {
cursor = offset;
break;
}
cursor = DFA[cursor + 2] as usize;
}
if DFA[cursor + 3] != 0 {
let data_idx: usize = (DFA[cursor + 3] as usize) >> 4;
let data_len: usize = (DFA[cursor + 3] as usize) & 0b1111;
for i in 0..data_len {
let p = RAW[data_idx + i];
if p != 0 {
let g = idx + i + 2 - data_len;
result[g] = max(result[g], p);
}
}
}
}
result
}
pub fn hyphen<'a, S: AsRef<str>>(content: S) -> Cow<'a, str> {
let length = content.as_ref().len();
if length < 5 {
return Cow::Owned(content.as_ref().to_string())
}
let points = detect(content.as_ref().to_lowercase());
let mut result = String::with_capacity(length * 3 / 2);
for (i, chr) in content.as_ref().chars().enumerate() {
result.push(chr);
if i > 0 && i < length - 3 && points[i+2] & 1 != 0 {
result.push('\u{00AD}')
}
}
Cow::Owned(result)
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 alloc::vec::Vec;
use alloc::boxed::Box;
use alloc::collections::btree_map::BTreeMap;
use super::super::task::*;
use super::super::qlib::common::*;
use super::super::qlib::linux_def::*;
use super::super::qlib::linux::time::*;
use super::super::SignalDef::*;
use super::super::syscalls::syscalls::*;
use super::super::kernel::waiter::*;
use super::super::kernel::timer::*;
use super::super::fs::file::*;
use super::super::threadmgr::task_syscall::*;
// fileCap is the maximum allowable files for poll & select.
pub const FILE_CAP : i32 = 1024 * 1024;
// SELECT_READ_EVENTS is analogous to the Linux kernel's
// fs/select.c:POLLIN_SET.
pub const SELECT_READ_EVENTS : i16 = (LibcConst::EPOLLIN | LibcConst::EPOLLHUP | LibcConst::EPOLLERR) as i16;
// SELECT_WRITE_EVENTS is analogous to the Linux kernel's
// fs/select.c:POLLOUT_SET.
pub const SELECT_WRITE_EVENTS : i16 = (LibcConst::EPOLLOUT | LibcConst::EPOLLERR) as i16;
// SELECT_EXCEPT_EVENTS is analogous to the Linux kernel's
// fs/select.c:POLLEX_SET.
pub const SELECT_EXCEPT_EVENTS : i16 = (LibcConst::EPOLLPRI) as i16;
pub const TIMEOUT_PROCESS_TIME : i64 = 30_000;
pub fn DoSelect(task: &Task, nfds: i32, readfds: u64, writefds: u64, exceptfds: u64, timeout: i64) -> Result<i64> {
if nfds == 0 {
super::super::taskMgr::Yield();
if timeout == 0 {
return Ok(0)
}
let (_remain, res) = task.blocker.BlockWithMonoTimeout(false, Some(timeout));
match res {
Err(Error::SysError(SysErr::ETIMEDOUT)) => {
return Ok(0)
}
Err(Error::ErrInterrupted) => {
return Err(Error::SysError(SysErr::ERESTARTNOHAND));
}
Err(e) => {
return Err(e)
}
Ok(()) => return Ok(0)
};
}
if nfds < 0 || nfds > FILE_CAP {
return Err(Error::SysError(SysErr::EINVAL))
}
// Capture all the provided input vectors.
let byteCount = ((nfds + 7) / 8) as usize;
let bitsPartial = (nfds % 8) as usize;
let mut r = Vec::with_capacity(byteCount);
let mut w = Vec::with_capacity(byteCount);
let mut e = Vec::with_capacity(byteCount);
if readfds != 0 {
r = task.CopyInVec::<u8>(readfds, byteCount)?;
if bitsPartial != 0 {
r[byteCount-1] &= !(0xff << bitsPartial)
}
} else {
for _i in 0..byteCount {
r.push(0)
}
}
if writefds != 0 {
w = task.CopyInVec::<u8>(writefds, byteCount)?;
if bitsPartial != 0 {
w[byteCount-1] &= !(0xff << bitsPartial)
}
} else {
for _i in 0..byteCount {
w.push(0)
}
}
if exceptfds != 0 {
e = task.CopyInVec::<u8>(exceptfds, byteCount)?;
if bitsPartial != 0 {
e[byteCount-1] &= !(0xff << bitsPartial)
}
} else {
for _i in 0..byteCount {
e.push(0)
}
}
let mut fdcnt = 0;
for i in 0..byteCount {
let mut v = r[i] | w[i] | e[i];
while v != 0 {
v &= v-1;
fdcnt += 1;
}
}
// Build the PollFD array.
let mut pfd = Vec::with_capacity(fdcnt);
let mut fd : i32 = 0;
for i in 0..byteCount {
let rv = r[i];
let wv = w[i];
let ev = e[i];
let v = rv | wv | ev;
let mut m : u8 = 1;
for _j in 0..8 {
if (v & m) != 0 {
// Make sure the fd is valid and decrement the reference
// immediately to ensure we don't leak. Note, another thread
// might be about to close fd. This is racy, but that's
// OK. Linux is racy in the same way.
let _file = task.GetFile(fd)?;
let mut mask : i16 = 0;
if rv & m !=0 {
mask |= SELECT_READ_EVENTS;
}
if wv & m != 0 {
mask |= SELECT_WRITE_EVENTS;
}
if ev & m != 0 {
mask |= SELECT_EXCEPT_EVENTS;
}
pfd.push(PollFd {
fd: fd,
events: mask,
revents: 0,
})
}
fd += 1;
m <<= 1;
}
}
// Do the syscall, then count the number of bits set.
let (_, res) = PollBlock(task, &mut pfd, timeout);
match res {
Err(_) => return Err(Error::SysError(SysErr::EINTR)),
Ok(_) => (),
}
// r, w, and e are currently event mask bitsets; unset bits corresponding
// to events that *didn't* occur.
let mut bitSetCount = 0;
for idx in 0..pfd.len() {
let events = pfd[idx].revents;
let i = (pfd[idx].fd / 8) as usize;
let j = (pfd[idx].fd % 8) as usize;
let m : u8 = 1 << j;
if r[i] & m != 0 {
if (events & SELECT_READ_EVENTS) != 0 {
bitSetCount += 1;
} else {
r[i] &= !m;
}
}
if w[i] & m != 0 {
if (events & SELECT_WRITE_EVENTS) != 0 {
bitSetCount += 1;
} else {
w[i] &= !m;
}
}
if e[i] & m != 0 {
if (events & SELECT_EXCEPT_EVENTS) != 0 {
bitSetCount += 1;
} else {
w[i] &= !m;
}
}
}
// Copy updated vectors back.
if readfds != 0 {
task.CopyOutSlice(&r, readfds, byteCount)?;
}
if writefds != 0 {
task.CopyOutSlice(&w, writefds, byteCount)?;
}
if exceptfds != 0 {
task.CopyOutSlice(&e, exceptfds, byteCount)?;
}
return Ok(bitSetCount)
}
pub fn PollBlock(task: &Task, pfd: &mut [PollFd], timeout: i64) -> (Duration, Result<usize>) {
// no fd to wait, just a nansleep
if pfd.len() == 0 {
if timeout == 0 {
return (0, Ok(0))
}
let timeout = if timeout >= 0 {
timeout
} else {
core::i64::MAX //if pfd is empty, timeout < 0, needs to wait forever
};
let (remain, res) = task.blocker.BlockWithMonoTimeout(false, Some(timeout));
match res {
Err(Error::SysError(SysErr::ETIMEDOUT)) => {
return (0, Ok(0))
}
Err(e) => {
return (remain, Err(e))
}
Ok(()) => return (remain, Ok(0))
};
}
let mut timeout = timeout;
let general = task.blocker.generalEntry.clone();
let mut n = 0;
//info!("PollBlock 1, pfd is {:?}", pfd);
// map <File -> (Mask, Readiness)>
let mut waits = BTreeMap::new();
for i in 0..pfd.len() {
match task.GetFile(pfd[i].fd) {
Err(_) => {
pfd[i].revents = PollConst::POLLNVAL as i16;
},
Ok(f) => {
match waits.get_mut(&f) {
None => {
let r = f.Readiness(task, EventMaskFromLinux(pfd[i].events as u32));
pfd[i].revents = ToLinux(r) as i16 & pfd[i].events;
waits.insert(f, (pfd[i].events, r));
}
Some(t) => {
(*t).0 |= pfd[i].events;
pfd[i].revents = (*t).1 as i16 & pfd[i].events;
}
}
}
};
if pfd[i].revents != 0 {
n += 1;
}
}
if n > 0 {
return (timeout, Ok(n))
}
for (f, (mask, _)) in waits.iter() {
f.EventRegister(task, &general, EventMaskFromLinux(*mask as u32));
}
defer!(
for f in waits.keys() {
f.EventUnregister(task, &general);
}
);
if timeout == 0 {
return (timeout, Ok(n));
}
while n == 0 {
// before we got notified, we have to count how many files are ready in case
// there is ready when we register the event. If none,
// then this was a spurious notification, and we just go back
// to sleep with the remaining timeout.
for i in 0..pfd.len() {
match task.GetFile(pfd[i].fd) {
Err(_) => (),
Ok(f) => {
let r = f.Readiness(task, EventMaskFromLinux(pfd[i].events as u32));
let rl = ToLinux(r) as i16 & pfd[i].events;
if rl != 0 {
pfd[i].revents = rl;
n += 1;
}
}
};
}
if n > 0 {
break;
}
let (timeoutTmp, res) = if timeout > 0 {
task.blocker.BlockWithMonoTimeout(true, Some(timeout))
} else {
task.blocker.BlockWithMonoTimeout(true, None)
};
timeout = timeoutTmp;
match res {
Err(Error::SysError(SysErr::ETIMEDOUT)) => {
return (0, Ok(0))
}
Err(e) => {
return (timeout, Err(e))
}
Ok(()) => (),
};
}
return (timeout, Ok(n))
}
pub fn InitReadiness(task: &Task, pfd: &mut PollFd, files: &mut Vec<Option<File>>, entry: &WaitEntry) {
if pfd.fd < 0 {
pfd.revents = 0;
files.push(None);
return
}
let file = match task.GetFile(pfd.fd) {
Err(_) => {
pfd.revents = PollConst::POLLNVAL as i16;
files.push(None);
return
}
Ok(f) => f,
};
file.EventRegister(task, &entry, EventMaskFromLinux(pfd.events as u32));
files.push(Some(file.clone()));
let r = file.Readiness(task, EventMaskFromLinux(pfd.events as u32));
pfd.revents = ToLinux(r) as i16 & pfd.events;
}
pub fn SysSelect(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let nfds = args.arg0 as i32;
let readfds = args.arg1 as u64;
let writefds = args.arg2 as u64;
let exceptfds = args.arg3 as u64;
let timeValAddr = args.arg4 as u64;
// Use a negative Duration to indicate "no timeout".
let mut timeout = -1 as Duration;
if timeValAddr != 0 {
let timeval : Timeval = task.CopyInObj(timeValAddr)?;
if timeval.Sec < 0 || timeval.Usec < 0 {
return Err(Error::SysError(SysErr::EINVAL))
}
timeout = timeval.ToDuration();
if timeout <= TIMEOUT_PROCESS_TIME {
timeout = 0;
}
}
let startNs = MonotonicNow();
let res = DoSelect(task, nfds, readfds, writefds, exceptfds, timeout);
CopyOutTimevalRemaining(task, startNs, timeout, timeValAddr)?;
match res {
Err(Error::SysError(SysErr::EINTR)) => return Err(Error::SysError(SysErr::ERESTARTNOHAND)),
Err(e) => return Err(e),
Ok(n) => return Ok(n),
}
}
pub fn SysPSelect(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let nfds = args.arg0 as i32;
let readfds = args.arg1 as u64;
let writefds = args.arg2 as u64;
let exceptfds = args.arg3 as u64;
let timespecAddr = args.arg4 as u64;
let maskWithSizeAddr = args.arg5 as u64;
// Use a negative Duration to indicate "no timeout".
let timeout = CopyTimespecIntoDuration(task, timespecAddr)?;
let startNs = MonotonicNow();
if maskWithSizeAddr != 0 {
let (maskAddr, size) = CopyInSigSetWithSize(task, maskWithSizeAddr)?;
if maskAddr != 0 {
let mask = CopyInSigSet(task, maskAddr, size)?;
let thread = task.Thread();
let oldmask = thread.SignalMask();
thread.SetSignalMask(mask);
thread.SetSavedSignalMask(oldmask);
}
}
let res = DoSelect(task, nfds, readfds, writefds, exceptfds, timeout);
CopyOutTimespecRemaining(task, startNs, timeout, timespecAddr)?;
match res {
Err(Error::SysError(SysErr::EINTR)) => return Err(Error::SysError(SysErr::ERESTARTSYS)),
Err(e) => return Err(e),
Ok(n) => return Ok(n),
}
}
// Poll implements linux syscall poll(2).
pub fn SysPoll(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let pfdAddr = args.arg0 as u64;
let nfds = args.arg1 as u32; // poll(2) uses unsigned long.
let timeout = args.arg2 as i32 as i64 * MILLISECOND;
let n = Poll(task, pfdAddr, nfds, timeout)?;
return Ok(n)
}
// Ppoll implements linux syscall ppoll(2).
pub fn SysPpoll(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let pfdAddr = args.arg0 as u64;
let nfds = args.arg1 as u32; // poll(2) uses unsigned long.
let timespecAddr = args.arg2 as u64;
let maskAddr = args.arg3 as u64;
let maskSize = args.arg4 as u32;
let timeout = CopyTimespecIntoDuration(task, timespecAddr)?;
let startNs = MonotonicNow();
if maskAddr != 0 {
let mask = CopyInSigSet(task, maskAddr, maskSize as usize)?;
let thread = task.Thread();
let oldmask = thread.SignalMask();
thread.SetSignalMask(mask);
thread.SetSavedSignalMask(oldmask);
}
let (_remain, res) = DoPoll(task, pfdAddr, nfds, timeout);
CopyOutTimespecRemaining(task, startNs, timeout, timespecAddr)?;
// doPoll returns EINTR if interrupted, but ppoll is normally restartable
// if interrupted by something other than a signal handled by the
// application (i.e. returns ERESTARTNOHAND). However, if
// copyOutTimespecRemaining failed, then the restarted ppoll would use the
// wrong timeout, so the error should be left as EINTR.
//
// Note that this means that if err is nil but copyErr is not, copyErr is
// ignored. This is consistent with Linux.
match res {
Err(Error::SysError(SysErr::EINTR)) => return Err(Error::SysError(SysErr::ERESTARTNOHAND)),
Err(e) => return Err(e),
Ok(n) => return Ok(n as i64),
}
}
pub struct PollRestartBlock {
pub pfdAddr: u64,
pub nfds: u32,
pub timeout: Duration,
}
impl SyscallRestartBlock for PollRestartBlock {
fn Restart(&self, task: &mut Task) -> Result<i64> {
return Poll(task, self.pfdAddr, self.nfds, self.timeout)
}
}
pub fn Poll(task: &mut Task, pfdAddr: u64, nfds: u32, timeout: Duration) -> Result<i64> {
if nfds > 4096 {
// linux support poll max 4096 fds
return Err(Error::SysError(SysErr::EINVAL))
}
let (remain, res) = DoPoll(task, pfdAddr, nfds, timeout);
match res {
Err(Error::SysError(SysErr::EINTR)) => {
let b = Box::new(PollRestartBlock {
pfdAddr: pfdAddr,
nfds: nfds,
timeout: remain,
});
task.SetSyscallRestartBlock(b);
return Err(Error::SysError(SysErr::ERESTART_RESTARTBLOCK));
}
Err(e) => {
return Err(e)
}
Ok(n) => return Ok(n as i64)
}
}
pub fn DoPoll(task: &Task, addr: u64, nfds: u32, timeout: Duration) -> (Duration, Result<usize>) {
//todo: handle fileCap
if (nfds as i32) < 0 {
return (0, Err(Error::SysError(SysErr::EINVAL)))
}
let mut pfd : Vec<PollFd> = if addr != 0 {
match task.CopyInVec(addr, nfds as usize) {
Err(e) => {
return (timeout, Err(e))
},
Ok(pfd) => pfd,
}
} else {
if nfds > 0 {
return (timeout, Err(Error::SysError(SysErr::EFAULT)))
}
Vec::new()
};
//info!("DoPoll pfd is {:?}", pfd);
// Compatibility warning: Linux adds POLLHUP and POLLERR just before
// polling, in fs/select.c:do_pollfd(). Since pfd is copied out after
// polling, changing event masks here is an application-visible difference.
// (Linux also doesn't copy out event masks at all, only revents.)
for i in 0..pfd.len() {
pfd[i].events |= (LibcConst::EPOLLHUP | LibcConst::EPOLLERR) as i16;
}
// Do the syscall, then count the number of bits set.
let (remainingTimeout, res) = PollBlock(task, &mut pfd, timeout);
let n = match res {
Err(_) => return (remainingTimeout, Err(Error::SysError(SysErr::EINTR))),
Ok(n) => n,
};
// The poll entries are copied out regardless of whether
// any are set or not. This aligns with the Linux behavior.
if nfds > 0 {
match task.CopyOutSlice(&pfd, addr, pfd.len()) {
Err(e) => return (remainingTimeout, Err(e)),
Ok(()) => (),
}
}
return (remainingTimeout, Ok(n))
}
pub fn CopyOutTimevalRemaining(task: &Task, startNs: i64, timeout: Duration, timeValAddr: u64) -> Result<()> {
if timeout < 0 {
return Ok(())
}
let remaining = TimeoutRemain(task, startNs, timeout);
let tvRemaining = Timeval::FromNs(remaining);
//let timeval : &mut Timeval = task.GetTypeMut(timeValAddr)?;
//*timeval = tvRemaining;
task.CopyOutObj(&tvRemaining, timeValAddr)?;
return Ok(())
}
pub fn CopyOutTimespecRemaining(task: &Task, startNs: i64, timeout: Duration, timespecAddr: u64) -> Result<()> {
if timeout < 0 {
return Ok(())
}
let remaining = TimeoutRemain(task, startNs, timeout);
let tsRemaining = Timespec::FromNs(remaining);
//let ts : &mut Timespec = task.GetTypeMut(timespecAddr)?;
//*ts = tsRemaining;
task.CopyOutObj(&tsRemaining, timespecAddr)?;
return Ok(())
}
pub fn TimeoutRemain(_task: &Task, startNs: i64, timeout: Duration) -> Duration {
let now = MonotonicNow();
let remaining = timeout - (now - startNs);
if remaining < 0 {
return 0
}
return remaining;
}
pub fn CopyTimespecIntoDuration(task: &Task, timespecAddr: u64) -> Result<Duration> {
let mut timeout = -1 as Duration;
if timespecAddr != 0 {
let timespec : Timespec = task.CopyInObj(timespecAddr)?;
if !timespec.IsValid() {
return Err(Error::SysError(SysErr::EINVAL))
}
timeout = timespec.ToDuration()?;
if timeout <= TIMEOUT_PROCESS_TIME {
timeout = 0;
}
}
return Ok(timeout);
} |
//! Module for custom CBC solver based on the one from `lp_modeler`.
use uuid::Uuid;
use std::collections::HashMap;
use std::fs;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::PathBuf;
use std::process::Command;
use std::sync;
use std::time::Duration;
use lp_modeler::dsl::LpProblem;
use lp_modeler::format::lp_format::LpFileFormat;
use lp_modeler::solvers::Status;
/// Errors used when running the solver.
#[derive(thiserror::Error, Debug)]
#[allow(missing_docs)]
pub enum Error {
#[error("The solver has timed out in {0:#?}")]
Timeout(Duration),
#[error("Could not write to {file}: {source}")]
WriteModel { source: io::Error, file: PathBuf },
#[error("Error executing solver: {0}")]
SolverCommand(String),
#[error("Error reading command: {0}")]
ReadSolution(String),
}
/// This is a copy of `lp_modeler::CbcSolver` that supports running the solver with timeout.
pub struct TimeoutCbcSolver {
command_name: String,
temp_solution_file: String,
}
impl Default for TimeoutCbcSolver {
fn default() -> Self {
Self {
command_name: "cbc".to_string(),
temp_solution_file: format!("{}.sol", Uuid::new_v4().to_string()),
}
}
}
impl TimeoutCbcSolver {
fn read_solution(&self) -> Result<(Status, HashMap<String, bool>), String> {
fn read_specific_solution(f: &File) -> Result<(Status, HashMap<String, bool>), String> {
let mut vars_value: HashMap<_, _> = HashMap::new();
let mut file = BufReader::new(f);
let mut buffer = String::new();
let _ = file.read_line(&mut buffer);
let status = if let Some(status_line) = buffer.split_whitespace().next() {
match status_line.split_whitespace().next() {
Some("Optimal") => Status::Optimal,
// Infeasible status is either "Infeasible" or "Integer infeasible"
Some("Infeasible") | Some("Integer") => Status::Infeasible,
Some("Unbounded") => Status::Unbounded,
// "Stopped" can be "on time", "on iterations", "on difficulties" or "on ctrl-c"
Some("Stopped") => Status::SubOptimal,
_ => Status::NotSolved,
}
} else {
return Err("Incorrect solution format".to_string());
};
for line in file.lines() {
let l = line.unwrap();
let mut result_line: Vec<_> = l.split_whitespace().collect();
if result_line[0] == "**" {
result_line.remove(0);
};
if result_line.len() == 4 {
match result_line[2].parse::<bool>() {
Ok(n) => {
vars_value.insert(result_line[1].to_string(), n);
}
Err(e) => return Err(e.to_string()),
}
} else {
return Err("Incorrect solution format".to_string());
}
}
Ok((status, vars_value))
}
match File::open(&self.temp_solution_file) {
Ok(f) => {
let res = read_specific_solution(&f)?;
let _ = fs::remove_file(&self.temp_solution_file);
Ok(res)
}
Err(_) => Err("Cannot open file".to_string()),
}
}
/// Attempts at solving the problem in `timeout` time.
///
/// # Errors
///
/// Error is returned if reading from or writing to temporary files fails,
/// or when the `timeout` is reached.
pub fn run(
&self,
problem: &LpProblem,
timeout: Duration,
) -> Result<(Status, HashMap<String, bool>), Error> {
let file_model = &format!("{}.lp", problem.unique_name);
problem
.write_lp(file_model)
.map_err(|e| Error::WriteModel {
source: e,
file: PathBuf::from(file_model),
})?;
let mut child = Command::new(&self.command_name)
.arg(file_model)
.arg("solve")
.arg("solution")
.arg(&self.temp_solution_file)
.spawn()
.map_err(|e| Error::SolverCommand(e.to_string()))?;
let (tx, rx) = sync::mpsc::channel::<()>();
std::thread::spawn(move || {
std::thread::sleep(timeout);
// If it couldn't be sent, `rx` is already closed and therefore solution already found.
let _ = tx.send(());
});
loop {
if let Some(status) = child
.try_wait()
.map_err(|_| Error::SolverCommand("Error attempting to wait".into()))?
{
return if status.success() {
self.read_solution().map_err(Error::ReadSolution)
} else {
Err(Error::SolverCommand(status.to_string()))
};
}
if rx.try_recv().is_ok() {
let _ = child.kill();
return Err(Error::Timeout(timeout));
}
std::thread::sleep(Duration::from_secs(1));
}
}
}
|
pub fn find_matches(content: &str, pattern: &str, mut writter: impl std::io::Write) {
for line in content.lines() {
if line.contains(pattern) {
writeln!(writter, "{}", line);
}
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use failure::Error;
use serde_json::Value;
use std::sync::Arc;
use crate::factory_store::facade::FactoryStoreFacade;
use crate::factory_store::types::FactoryStoreMethod;
/// Takes JSON-RPC method command and forwards to corresponding FactoryStoreProvider FIDL methods.
pub async fn factory_store_method_to_fidl(
method_name: String,
args: Value,
facade: Arc<FactoryStoreFacade>,
) -> Result<Value, Error> {
match method_name.parse()? {
FactoryStoreMethod::ReadFile => facade.read_file(args).await,
FactoryStoreMethod::ListFiles => facade.list_files(args).await,
}
}
|
#![feature(test)]
extern crate test;
extern crate rfc3986;
use test::Bencher;
use rfc3986::uri::Uri;
#[bench]
fn benchmark_url_parsing(b: &mut Bencher) {
b.iter(|| {
Uri::from_str(
"https://username:password@github.com/path/to?query=foo#fragment"
)
});
}
|
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
mod csm;
mod device;
mod epoll_handler;
mod packet;
mod unix;
pub use self::defs::uapi::VIRTIO_ID_VSOCK as TYPE_VSOCK;
pub use self::defs::EVENT_COUNT as VSOCK_EVENTS_COUNT;
pub use self::device::Vsock;
pub use self::unix::{Error as VsockUnixBackendError, VsockUnixBackend};
use std::os::unix::io::RawFd;
use std::sync::mpsc;
use vm_memory::GuestMemoryError;
use super::super::EpollHandler;
use super::EpollConfigConstructor;
use packet::VsockPacket;
mod defs {
use crate::DeviceEventT;
/// RX queue event: the driver added available buffers to the RX queue.
pub const RXQ_EVENT: DeviceEventT = 0;
/// TX queue event: the driver added available buffers to the RX queue.
pub const TXQ_EVENT: DeviceEventT = 1;
/// Event queue event: the driver added available buffers to the event queue.
pub const EVQ_EVENT: DeviceEventT = 2;
/// Backend event: the backend needs a kick.
pub const BACKEND_EVENT: DeviceEventT = 3;
/// Total number of events known to the vsock epoll handler.
pub const EVENT_COUNT: usize = 4;
/// Number of virtio queues.
pub const NUM_QUEUES: usize = 3;
/// Virtio queue sizes, in number of descriptor chain heads.
/// There are 3 queues for a virtio device (in this order): RX, TX, Event
pub const QUEUE_SIZES: &[u16] = &[256; NUM_QUEUES];
/// Max vsock packet data/buffer size.
pub const MAX_PKT_BUF_SIZE: usize = 64 * 1024;
pub mod uapi {
/// Virtio feature flags.
/// Defined in `/include/uapi/linux/virtio_config.h`.
///
/// The device processes available buffers in the same order in which the device
/// offers them.
pub const VIRTIO_F_IN_ORDER: usize = 35;
/// The device conforms to the virtio spec version 1.0.
pub const VIRTIO_F_VERSION_1: u32 = 32;
/// Virtio vsock device ID.
/// Defined in `include/uapi/linux/virtio_ids.h`.
pub const VIRTIO_ID_VSOCK: u32 = 19;
/// Vsock packet operation IDs.
/// Defined in `/include/uapi/linux/virtio_vsock.h`.
///
/// Connection request.
pub const VSOCK_OP_REQUEST: u16 = 1;
/// Connection response.
pub const VSOCK_OP_RESPONSE: u16 = 2;
/// Connection reset.
pub const VSOCK_OP_RST: u16 = 3;
/// Connection clean shutdown.
pub const VSOCK_OP_SHUTDOWN: u16 = 4;
/// Connection data (read/write).
pub const VSOCK_OP_RW: u16 = 5;
/// Flow control credit update.
pub const VSOCK_OP_CREDIT_UPDATE: u16 = 6;
/// Flow control credit update request.
pub const VSOCK_OP_CREDIT_REQUEST: u16 = 7;
/// Vsock packet flags.
/// Defined in `/include/uapi/linux/virtio_vsock.h`.
///
/// Valid with a VSOCK_OP_SHUTDOWN packet: the packet sender will receive no more data.
pub const VSOCK_FLAGS_SHUTDOWN_RCV: u32 = 1;
/// Valid with a VSOCK_OP_SHUTDOWN packet: the packet sender will send no more data.
pub const VSOCK_FLAGS_SHUTDOWN_SEND: u32 = 2;
/// Vsock packet type.
/// Defined in `/include/uapi/linux/virtio_vsock.h`.
///
/// Stream / connection-oriented packet (the only currently valid type).
pub const VSOCK_TYPE_STREAM: u16 = 1;
pub const VSOCK_HOST_CID: u64 = 2;
}
}
#[derive(Debug)]
pub enum VsockError {
/// The vsock data/buffer virtio descriptor length is smaller than expected.
BufDescTooSmall,
/// The vsock data/buffer virtio descriptor is expected, but missing.
BufDescMissing,
/// Chained GuestMemory error.
GuestMemory(GuestMemoryError),
/// Bounds check failed on guest memory pointer.
GuestMemoryBounds,
/// The vsock header descriptor length is too small.
HdrDescTooSmall(u32),
/// The vsock header `len` field holds an invalid value.
InvalidPktLen(u32),
/// A data fetch was attempted when no data was available.
NoData,
/// A data buffer was expected for the provided packet, but it is missing.
PktBufMissing,
/// Encountered an unexpected write-only virtio descriptor.
UnreadableDescriptor,
/// Encountered an unexpected read-only virtio descriptor.
UnwritableDescriptor,
}
type Result<T> = std::result::Result<T, VsockError>;
pub struct EpollConfig {
rxq_token: u64,
txq_token: u64,
evq_token: u64,
backend_token: u64,
epoll_raw_fd: RawFd,
sender: mpsc::Sender<Box<dyn EpollHandler>>,
}
impl EpollConfigConstructor for EpollConfig {
fn new(
first_token: u64,
epoll_raw_fd: RawFd,
sender: mpsc::Sender<Box<dyn EpollHandler>>,
) -> Self {
EpollConfig {
rxq_token: first_token + u64::from(defs::RXQ_EVENT),
txq_token: first_token + u64::from(defs::TXQ_EVENT),
evq_token: first_token + u64::from(defs::EVQ_EVENT),
backend_token: first_token + u64::from(defs::BACKEND_EVENT),
epoll_raw_fd,
sender,
}
}
}
/// A passive, event-driven object, that needs to be notified whenever an epoll-able event occurs.
/// An event-polling control loop will use `get_polled_fd()` and `get_polled_evset()` to query
/// the listener for the file descriptor and the set of events it's interested in. When such an
/// event occurs, the control loop will route the event to the listener via `notify()`.
pub trait VsockEpollListener {
/// Get the file descriptor the listener needs polled.
fn get_polled_fd(&self) -> RawFd;
/// Get the set of events for which the listener wants to be notified.
fn get_polled_evset(&self) -> epoll::Events;
/// Notify the listener that one ore more events have occurred.
fn notify(&mut self, evset: epoll::Events);
}
/// Any channel that handles vsock packet traffic: sending and receiving packets. Since we're
/// implementing the device model here, our responsibility is to always process the sending of
/// packets (i.e. the TX queue). So, any locally generated data, addressed to the driver (e.g.
/// a connection response or RST), will have to be queued, until we get to processing the RX queue.
///
/// Note: `recv_pkt()` and `send_pkt()` are named analogous to `Read::read()` and `Write::write()`,
/// respectively. I.e.
/// - `recv_pkt(&mut pkt)` will read data from the channel, and place it into `pkt`; and
/// - `send_pkt(&pkt)` will fetch data from `pkt`, and place it into the channel.
pub trait VsockChannel {
/// Read/receive an incoming packet from the channel.
fn recv_pkt(&mut self, pkt: &mut VsockPacket) -> Result<()>;
/// Write/send a packet through the channel.
fn send_pkt(&mut self, pkt: &VsockPacket) -> Result<()>;
/// Checks whether there is pending incoming data inside the channel, meaning that a subsequent
/// call to `recv_pkt()` won't fail.
fn has_pending_rx(&self) -> bool;
}
/// The vsock backend, which is basically an epoll-event-driven vsock channel, that needs to be
/// sendable through a mpsc channel (the latter due to how `vmm::EpollContext` works).
/// Currently, the only implementation we have is `crate::virtio::unix::muxer::VsockMuxer`, which
/// translates guest-side vsock connections to host-side Unix domain socket connections.
pub trait VsockBackend: VsockChannel + VsockEpollListener + Send {}
#[cfg(test)]
mod tests {
use super::epoll_handler::VsockEpollHandler;
use super::packet::VSOCK_PKT_HDR_SIZE;
use super::*;
use std::os::unix::io::AsRawFd;
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
use utils::eventfd::EventFd;
use crate::virtio::queue::tests::VirtQueue as GuestQ;
use crate::virtio::{VIRTQ_DESC_F_NEXT, VIRTQ_DESC_F_WRITE};
use vm_memory::{GuestAddress, GuestMemory};
pub struct TestBackend {
pub evfd: EventFd,
pub rx_err: Option<VsockError>,
pub tx_err: Option<VsockError>,
pub pending_rx: bool,
pub rx_ok_cnt: usize,
pub tx_ok_cnt: usize,
pub evset: Option<epoll::Events>,
}
impl TestBackend {
pub fn new() -> Self {
Self {
evfd: EventFd::new(libc::EFD_NONBLOCK).unwrap(),
rx_err: None,
tx_err: None,
pending_rx: false,
rx_ok_cnt: 0,
tx_ok_cnt: 0,
evset: None,
}
}
pub fn set_rx_err(&mut self, err: Option<VsockError>) {
self.rx_err = err;
}
pub fn set_tx_err(&mut self, err: Option<VsockError>) {
self.tx_err = err;
}
pub fn set_pending_rx(&mut self, prx: bool) {
self.pending_rx = prx;
}
}
impl VsockChannel for TestBackend {
fn recv_pkt(&mut self, _pkt: &mut VsockPacket) -> Result<()> {
let cool_buf = [0xDu8, 0xE, 0xA, 0xD, 0xB, 0xE, 0xE, 0xF];
match self.rx_err.take() {
None => {
if let Some(buf) = _pkt.buf_mut() {
for i in 0..buf.len() {
buf[i] = cool_buf[i % cool_buf.len()];
}
}
self.rx_ok_cnt += 1;
Ok(())
}
Some(e) => Err(e),
}
}
fn send_pkt(&mut self, _pkt: &VsockPacket) -> Result<()> {
match self.tx_err.take() {
None => {
self.tx_ok_cnt += 1;
Ok(())
}
Some(e) => Err(e),
}
}
fn has_pending_rx(&self) -> bool {
self.pending_rx
}
}
impl VsockEpollListener for TestBackend {
fn get_polled_fd(&self) -> RawFd {
self.evfd.as_raw_fd()
}
fn get_polled_evset(&self) -> epoll::Events {
epoll::Events::EPOLLIN
}
fn notify(&mut self, evset: epoll::Events) {
self.evset = Some(evset);
}
}
impl VsockBackend for TestBackend {}
pub struct TestContext {
pub cid: u64,
pub mem: GuestMemory,
pub mem_size: usize,
pub device: Vsock<TestBackend>,
// This needs to live here, so that sending the handler, at device activation, works.
_handler_receiver: mpsc::Receiver<Box<dyn EpollHandler>>,
}
impl TestContext {
pub fn new() -> Self {
const CID: u64 = 52;
const MEM_SIZE: usize = 1024 * 1024 * 128;
let (sender, _handler_receiver) = mpsc::channel();
Self {
cid: CID,
mem: GuestMemory::new(&[(GuestAddress(0), MEM_SIZE)]).unwrap(),
mem_size: MEM_SIZE,
device: Vsock::new(
CID,
EpollConfig::new(0, epoll::create(true).unwrap(), sender),
TestBackend::new(),
)
.unwrap(),
_handler_receiver,
}
}
pub fn create_epoll_handler_context(&self) -> EpollHandlerContext {
const QSIZE: u16 = 2;
let guest_rxvq = GuestQ::new(GuestAddress(0x0010_0000), &self.mem, QSIZE as u16);
let guest_txvq = GuestQ::new(GuestAddress(0x0020_0000), &self.mem, QSIZE as u16);
let guest_evvq = GuestQ::new(GuestAddress(0x0030_0000), &self.mem, QSIZE as u16);
let rxvq = guest_rxvq.create_queue();
let txvq = guest_txvq.create_queue();
let evvq = guest_evvq.create_queue();
// Set up one available descriptor in the RX queue.
guest_rxvq.dtable[0].set(
0x0040_0000,
VSOCK_PKT_HDR_SIZE as u32,
VIRTQ_DESC_F_WRITE | VIRTQ_DESC_F_NEXT,
1,
);
guest_rxvq.dtable[1].set(0x0040_1000, 4096, VIRTQ_DESC_F_WRITE, 0);
guest_rxvq.avail.ring[0].set(0);
guest_rxvq.avail.idx.set(1);
// Set up one available descriptor in the TX queue.
guest_txvq.dtable[0].set(0x0050_0000, VSOCK_PKT_HDR_SIZE as u32, VIRTQ_DESC_F_NEXT, 1);
guest_txvq.dtable[1].set(0x0050_1000, 4096, 0, 0);
guest_txvq.avail.ring[0].set(0);
guest_txvq.avail.idx.set(1);
EpollHandlerContext {
guest_rxvq,
guest_txvq,
guest_evvq,
handler: VsockEpollHandler {
rxvq,
rxvq_evt: EventFd::new(libc::EFD_NONBLOCK).unwrap(),
txvq,
txvq_evt: EventFd::new(libc::EFD_NONBLOCK).unwrap(),
evvq,
evvq_evt: EventFd::new(libc::EFD_NONBLOCK).unwrap(),
cid: self.cid,
mem: self.mem.clone(),
interrupt_status: Arc::new(AtomicUsize::new(0)),
interrupt_evt: EventFd::new(libc::EFD_NONBLOCK).unwrap(),
backend: TestBackend::new(),
},
}
}
}
pub struct EpollHandlerContext<'a> {
pub handler: VsockEpollHandler<TestBackend>,
pub guest_rxvq: GuestQ<'a>,
pub guest_txvq: GuestQ<'a>,
pub guest_evvq: GuestQ<'a>,
}
impl<'a> EpollHandlerContext<'a> {
pub fn signal_txq_event(&mut self) {
self.handler.txvq_evt.write(1).unwrap();
self.handler
.handle_event(defs::TXQ_EVENT, epoll::Events::EPOLLIN)
.unwrap();
}
pub fn signal_rxq_event(&mut self) {
self.handler.rxvq_evt.write(1).unwrap();
self.handler
.handle_event(defs::RXQ_EVENT, epoll::Events::EPOLLIN)
.unwrap();
}
}
}
|
/**
* Ownership Rules:
*
* 1) Each value has a variable which is its owner
* 2) There can only be one owner at any given time
* 3) When the owner goes out of scope, the value will be dropped
*
* Borrowing Rules:
*
* 1) Allowed infinite borrows for read-only access and borrowing will last until the end of scope
* 2) Read-only borrows make the original data immutable for their duration
* 3) Only allowed to pass one borrow at a time for write access/mutability
*/
fn main() {
// For primitive type -> copy
// bool, character, numbers,
let a = 10;
let b = a; // copy
let c = a; // copy
println!("a: {} b: {} c: {}", a, b, c);
// Dynamic heap type
let s = String::from("String");
let y = s;
// -> this is impossible since value of s moved to y
// ownership in Rust means only one reference can own a piece of data at a time
// println!("{}", s);
println!("{}", y);
// on the other hand, next code is possible since it passes reference
// so ownership hasn't changed
let z = &y;
println!("{}", y);
println!("{}", z);
}
|
use crate::{
error::AppError,
models::{entry, tag},
state::AppState,
views::entry::view,
};
use axum::{
extract::{Path, State},
response::Response,
};
use sea_orm::{entity::prelude::*, query::*};
use std::sync::Arc;
pub async fn entry(
State(app_state): State<Arc<AppState>>,
Path((category, slug)): Path<(String, String)>,
) -> Result<Response, AppError> {
let content_type = "text/html; charset=utf-8".to_string();
let results = entry::Entity::find()
.filter(
Condition::all()
.add(entry::Column::Slug.eq(slug))
.add(entry::Column::Category.eq(category)),
)
.find_with_related(tag::Entity)
.all(&app_state.database)
.await?;
view(app_state, results, None, content_type, true).await
}
|
use super::downcast::downcast_pf;
use super::error::RuntimeErr;
use super::pine_ref::PineRef;
use super::primitive::{Bool, Color, Float, Int, NA};
use super::ref_data::RefData;
use super::traits::{
Arithmetic, Category, ComplexType, DataType, Negative, PineFrom, PineStaticType, PineType,
SecondType,
};
use std::cmp::{Ordering, PartialEq, PartialOrd};
use std::convert::{From, Into};
use std::fmt::Debug;
use std::marker::PhantomData;
use std::mem;
#[derive(Debug)]
pub struct Series<'a, D: Clone + Debug + 'a> {
current: D,
history: Vec<D>,
phantom: PhantomData<&'a D>,
}
impl<'a, D: Default + Clone + Debug + 'a> Clone for Series<'a, D> {
fn clone(&self) -> Self {
Series {
current: self.current.clone(),
history: vec![],
phantom: PhantomData,
}
}
}
impl<'a, D: Default + Clone + Debug + 'a> From<D> for Series<'a, D> {
fn from(input: D) -> Self {
Series {
current: input,
history: vec![],
phantom: PhantomData,
}
}
}
impl<'a, D: Clone + Debug + 'a> Into<Vec<D>> for Series<'a, D> {
fn into(self) -> Vec<D> {
self.history
}
}
impl<'a, D: Default + PineType<'a> + Clone + Debug + 'a> Series<'a, D> {
pub fn new() -> Series<'a, D> {
Series {
current: D::default(),
history: vec![],
phantom: PhantomData,
}
}
pub fn from_vec(history: Vec<D>) -> Series<'a, D> {
Series {
current: D::default(),
history,
phantom: PhantomData,
}
}
pub fn from_cur_history(current: D, history: Vec<D>) -> Series<'a, D> {
Series {
current,
history,
phantom: PhantomData,
}
}
pub fn index(&self, i: usize) -> Result<Series<'a, D>, RuntimeErr> {
let len = self.history.len();
let val = match i {
// m if m < 0 => Err(SeriesErr::Negative),
0 => self.current.clone(),
m if m >= 1 && m <= len => self.history[(len - i) as usize].clone(),
_ => D::default(),
};
Ok(Series::from(val))
}
pub fn index_value(&self, i: usize) -> Result<D, RuntimeErr> {
let len = self.history.len();
let val = match i {
// m if m < 0 => Err(SeriesErr::Negative),
0 => self.current.clone(),
m if m >= 1 && len >= 1 && m <= len => self.history[(len - i) as usize].clone(),
_ => D::default(),
};
Ok(val)
}
pub fn at(&self, i: usize) -> D {
let len = self.history.len();
match i {
// m if m < 0 => Err(SeriesErr::Negative),
0 => self.current.clone(),
m if m >= 1 && len >= 1 && m <= len => self.history[(len - i) as usize].clone(),
_ => D::default(),
}
}
pub fn update(&mut self, current: D) {
self.current = current;
}
pub fn commit(&mut self) {
self.history
.push(mem::replace(&mut self.current, D::default()));
}
pub fn update_commit(&mut self, current: D) {
self.update(current);
self.commit();
}
pub fn roll_back(&mut self) {
if !self.history.is_empty() {
self.history.pop().unwrap();
}
}
pub fn get_current(&self) -> D {
self.current.clone()
}
pub fn get_history(&self) -> &Vec<D> {
&self.history
}
pub fn move_history(&mut self) -> Vec<D> {
mem::replace(&mut self.history, vec![])
}
}
impl<'a, D: PineStaticType + Clone + Debug + 'a> PineStaticType for Series<'a, D> {
fn static_type() -> (DataType, SecondType) {
(<D as PineStaticType>::static_type().0, SecondType::Series)
}
}
impl<'a, D: PineStaticType + PineType<'a> + Default + Clone + Debug + 'a> PineType<'a>
for Series<'a, D>
{
fn get_type(&self) -> (DataType, SecondType) {
(<D as PineStaticType>::static_type().0, SecondType::Series)
}
fn category(&self) -> Category {
Category::Complex
}
fn copy(&self) -> PineRef<'a> {
PineRef::new_rc(self.clone())
}
}
impl<'a, D> PineFrom<'a, Series<'a, D>> for Series<'a, D>
where
D: Default + PineStaticType + PartialEq + Clone + Debug + PineType<'a> + PineFrom<'a, D> + 'a,
{
fn explicity_from(t: PineRef<'a>) -> Result<RefData<Series<'a, D>>, RuntimeErr> {
let data_type = <D as PineStaticType>::static_type().0;
match t.get_type() {
(d, SecondType::Series) if data_type == d => Ok(downcast_pf::<Series<D>>(t).unwrap()),
(d, SecondType::Simple) if data_type == d => Ok(RefData::new_rc(Series {
current: downcast_pf::<D>(t).unwrap().into_inner(),
history: vec![],
phantom: PhantomData,
})),
(DataType::Int, SecondType::Series) => {
let series: RefData<Series<Int>> = Series::explicity_from(t)?;
let val: RefData<D> = D::explicity_from(PineRef::new(series.get_current()))?;
Ok(RefData::new_rc(Series::from(val.into_inner())))
}
(DataType::Int, SecondType::Simple) => Ok(RefData::new_rc(Series::from(
D::explicity_from(t)?.into_inner(),
))),
(DataType::Float, SecondType::Series) => {
let series: RefData<Series<Float>> = Series::explicity_from(t)?;
let val: RefData<D> = D::explicity_from(PineRef::new(series.get_current()))?;
Ok(RefData::new_rc(Series::from(val.into_inner())))
}
(DataType::Float, SecondType::Simple) => Ok(RefData::new_rc(Series::from(
D::explicity_from(t)?.into_inner(),
))),
(DataType::Bool, SecondType::Series) => {
let series: RefData<Series<Bool>> = Series::explicity_from(t)?;
let val: RefData<D> = D::explicity_from(PineRef::new(series.get_current()))?;
Ok(RefData::new_rc(Series::from(val.into_inner())))
}
(DataType::Bool, SecondType::Simple) => Ok(RefData::new_rc(Series::from(
D::explicity_from(t)?.into_inner(),
))),
(DataType::NA, _) => Ok(RefData::new_rc(Series::from(
D::explicity_from(PineRef::new_box(NA))?.into_inner(),
))),
(DataType::Color, SecondType::Series) => {
let series: RefData<Series<Color>> = Series::explicity_from(t)?;
let val: RefData<D> = D::explicity_from(PineRef::new(series.get_current()))?;
Ok(RefData::new_rc(Series::from(val.into_inner())))
}
(DataType::Color, SecondType::Simple) => Ok(RefData::new_rc(Series::from(
D::explicity_from(t)?.into_inner(),
))),
(DataType::String, SecondType::Series) => {
let series: RefData<Series<String>> = Series::explicity_from(t)?;
let val: RefData<D> = D::explicity_from(PineRef::new(series.get_current()))?;
Ok(RefData::new_rc(Series::from(val.into_inner())))
}
(DataType::String, SecondType::Simple) => Ok(RefData::new_rc(Series::from(
D::explicity_from(t)?.into_inner(),
))),
_ => Err(RuntimeErr::UnknownRuntimeErr),
}
}
fn implicity_from(t: PineRef<'a>) -> Result<RefData<Series<'a, D>>, RuntimeErr> {
let data_type = <D as PineStaticType>::static_type().0;
match t.get_type() {
(d, SecondType::Series) if data_type == d => Ok(downcast_pf::<Series<D>>(t).unwrap()),
(d, SecondType::Simple) if data_type == d => Ok(RefData::new_rc(Series {
current: downcast_pf::<D>(t).unwrap().into_inner(),
history: vec![],
phantom: PhantomData,
})),
(DataType::Int, SecondType::Series) => {
let series: RefData<Series<Int>> = Series::implicity_from(t)?;
let val: RefData<D> = D::implicity_from(PineRef::new(series.get_current()))?;
Ok(RefData::new_rc(Series::from(val.into_inner())))
}
(DataType::Int, SecondType::Simple) => Ok(RefData::new_rc(Series::from(
D::implicity_from(t)?.into_inner(),
))),
(DataType::Float, SecondType::Series) => {
let series: RefData<Series<Float>> = Series::implicity_from(t)?;
let val: RefData<D> = D::implicity_from(PineRef::new(series.get_current()))?;
Ok(RefData::new_rc(Series::from(val.into_inner())))
}
(DataType::Float, SecondType::Simple) => Ok(RefData::new_rc(Series::from(
D::implicity_from(t)?.into_inner(),
))),
(DataType::Bool, SecondType::Series) => {
let series: RefData<Series<Bool>> = Series::implicity_from(t)?;
let val: RefData<D> = D::implicity_from(PineRef::new(series.get_current()))?;
Ok(RefData::new_rc(Series::from(val.into_inner())))
}
(DataType::Bool, SecondType::Simple) => Ok(RefData::new_rc(Series::from(
D::implicity_from(t)?.into_inner(),
))),
(DataType::NA, _) => Ok(RefData::new_rc(Series::from(
D::implicity_from(PineRef::new_box(NA))?.into_inner(),
))),
(DataType::Color, SecondType::Series) => {
let series: RefData<Series<Color>> = Series::implicity_from(t)?;
let val: RefData<D> = D::implicity_from(PineRef::new(series.get_current()))?;
Ok(RefData::new_rc(Series::from(val.into_inner())))
}
(DataType::Color, SecondType::Simple) => Ok(RefData::new_rc(Series::from(
D::implicity_from(t)?.into_inner(),
))),
(DataType::String, SecondType::Series) => {
let series: RefData<Series<String>> = Series::implicity_from(t)?;
let val: RefData<D> = D::implicity_from(PineRef::new(series.get_current()))?;
Ok(RefData::new_rc(Series::from(val.into_inner())))
}
(DataType::String, SecondType::Simple) => Ok(RefData::new_rc(Series::from(
D::implicity_from(t)?.into_inner(),
))),
_ => Err(RuntimeErr::UnknownRuntimeErr),
}
}
}
impl<'a, D: Clone + Negative<D> + Debug + 'a> Negative<Series<'a, D>> for Series<'a, D> {
fn negative(mut self) -> Series<'a, D> {
self.current = self.current.negative();
self
}
}
impl<'a, D: Clone + Arithmetic + Debug + 'a> Arithmetic for Series<'a, D> {
fn add(mut self, other: Self) -> Self {
self.current = self.current.add(other.current);
self
}
fn minus(mut self, other: Self) -> Self {
self.current = self.current.minus(other.current);
self
}
fn mul(mut self, other: Self) -> Self {
self.current = self.current.mul(other.current);
self
}
fn div(mut self, other: Self) -> Self {
self.current = self.current.div(other.current);
self
}
fn rem(mut self, other: Self) -> Self {
self.current = self.current.rem(other.current);
self
}
}
impl<'a, D: PartialOrd + Clone + Debug + 'a> PartialOrd for Series<'a, D> {
fn partial_cmp(&self, other: &Series<'a, D>) -> Option<Ordering> {
self.current.partial_cmp(&other.current)
}
}
impl<'a, D: PartialEq + Clone + Debug + 'a> PartialEq for Series<'a, D> {
fn eq(&self, other: &Self) -> bool {
self.current.eq(&other.current) && self.history.eq(&other.history)
}
}
impl<'a, D: Clone + Debug + 'a> ComplexType for Series<'a, D> {}
#[cfg(test)]
mod tests {
use super::super::primitive::Int;
use super::*;
#[test]
fn series_test() {
let int: Int = Some(1);
let mut series: Series<Int> = Series::from(int);
assert_eq!(series.index(0), Ok(Series::from(Some(1))));
series.update(Some(2));
assert_eq!(series.index(0), Ok(Series::from(Some(2))));
series.commit();
assert_eq!(series.history, vec![Some(2)]);
assert_eq!(series.current, None);
series.roll_back();
assert_eq!(series.history, vec![]);
}
#[test]
fn int_series_test() {
let int: Int = Some(1);
// implicity converter
// Int => Series<Int>
let series: RefData<Series<Int>> = Series::implicity_from(PineRef::new(int)).unwrap();
assert_eq!(series.get_current(), int);
// Series<Int> => Series<Int>
let series2: RefData<Series<Int>> =
Series::implicity_from(PineRef::new(Series::from(Some(1)))).unwrap();
assert_eq!(series2.get_current(), int);
// NA => Series<Int>
let series3: RefData<Series<Int>> = Series::implicity_from(PineRef::new(NA)).unwrap();
assert_eq!(series3.get_current(), None);
// explicity converter
// Int => Series<Int>
let series4: RefData<Series<Int>> = Series::explicity_from(PineRef::new(int)).unwrap();
assert_eq!(series4.get_current(), int);
// Series<Int> => Series<Int>
let series5: RefData<Series<Int>> =
Series::explicity_from(PineRef::new(Series::from(Some(1)))).unwrap();
assert_eq!(series5.get_current(), int);
// NA => Series<Int>
let series6: RefData<Series<Int>> = Series::explicity_from(PineRef::new(NA)).unwrap();
assert_eq!(series6.get_current(), None);
// Float => Series<Int>
let series7: RefData<Series<Int>> =
Series::explicity_from(PineRef::new(Some(1f64))).unwrap();
assert_eq!(series7.get_current(), Some(1));
// Float => Series<Int>
let series8: RefData<Series<Int>> = Series::explicity_from(series7.into_pf()).unwrap();
assert_eq!(series8.get_current(), Some(1));
}
#[test]
fn float_series_test() {
// implicity converter
{
// Float => Series<Float>
let series: RefData<Series<Float>> =
Series::implicity_from(PineRef::new(Some(1f64))).unwrap();
assert_eq!(series.get_current(), Some(1f64));
// Series<Float> => Series<Float>
let series2: RefData<Series<Float>> =
Series::implicity_from(PineRef::new(Series::from(Some(1f64)))).unwrap();
assert_eq!(series2.get_current(), Some(1f64));
// Int => Series<Float>
let series3: RefData<Series<Float>> =
Series::implicity_from(PineRef::new(Some(1))).unwrap();
assert_eq!(series3.get_current(), Some(1f64));
// Series<Int> => Series<Float>
let series4: RefData<Series<Float>> =
Series::implicity_from(PineRef::new(Series::from(Some(1)))).unwrap();
assert_eq!(series4.get_current(), Some(1f64));
// NA => Series<Float>
let series5: RefData<Series<Float>> = Series::implicity_from(PineRef::new(NA)).unwrap();
assert_eq!(series5.get_current(), None);
}
// explicity converter
{
// Float => Series<Float>
let series: RefData<Series<Float>> =
Series::explicity_from(PineRef::new(Some(1f64))).unwrap();
assert_eq!(series.get_current(), Some(1f64));
// Series<Float> => Series<Float>
let series2: RefData<Series<Float>> =
Series::explicity_from(PineRef::new(Series::from(Some(1f64)))).unwrap();
assert_eq!(series2.get_current(), Some(1f64));
// Int => Series<Float>
let series3: RefData<Series<Float>> =
Series::explicity_from(PineRef::new(Some(1))).unwrap();
assert_eq!(series3.get_current(), Some(1f64));
// Series<Int> => Series<Float>
let series4: RefData<Series<Float>> =
Series::explicity_from(PineRef::new(Series::from(Some(1)))).unwrap();
assert_eq!(series4.get_current(), Some(1f64));
// NA => Series<Float>
let series5: RefData<Series<Float>> = Series::explicity_from(PineRef::new(NA)).unwrap();
assert_eq!(series5.get_current(), None);
}
}
#[test]
fn bool_series_test() {
// implicity converter
{
// Bool => Series<Bool>
let series: RefData<Series<Bool>> = Series::implicity_from(PineRef::new(true)).unwrap();
assert_eq!(series.get_current(), true);
// Series<Bool> => Series<Bool>
let series: RefData<Series<Bool>> =
Series::implicity_from(PineRef::new(Series::from(true))).unwrap();
assert_eq!(series.get_current(), true);
// Float => Series<Bool>
let series: RefData<Series<Bool>> =
Series::implicity_from(PineRef::new(Some(1f64))).unwrap();
assert_eq!(series.get_current(), true);
// Series<Float> => Series<Bool>
let series2: RefData<Series<Bool>> =
Series::implicity_from(PineRef::new(Series::from(Some(1f64)))).unwrap();
assert_eq!(series2.get_current(), true);
// Int => Series<Bool>
let series3: RefData<Series<Bool>> =
Series::implicity_from(PineRef::new(Some(1))).unwrap();
assert_eq!(series3.get_current(), true);
// Series<Int> => Series<Bool>
let series4: RefData<Series<Bool>> =
Series::implicity_from(PineRef::new(Series::from(Some(1)))).unwrap();
assert_eq!(series4.get_current(), true);
// NA => Series<Bool>
let series5: RefData<Series<Bool>> = Series::implicity_from(PineRef::new(NA)).unwrap();
assert_eq!(series5.get_current(), false);
}
// explicity converter
{
// Bool => Series<Bool>
let series: RefData<Series<Bool>> = Series::explicity_from(PineRef::new(true)).unwrap();
assert_eq!(series.get_current(), true);
// Series<Bool> => Series<Bool>
let series: RefData<Series<Bool>> =
Series::explicity_from(PineRef::new(Series::from(true))).unwrap();
assert_eq!(series.get_current(), true);
// Float => Series<Bool>
let series: RefData<Series<Bool>> =
Series::explicity_from(PineRef::new(Some(1f64))).unwrap();
assert_eq!(series.get_current(), true);
// Series<Float> => Series<Bool>
let series2: RefData<Series<Bool>> =
Series::explicity_from(PineRef::new(Series::from(Some(1f64)))).unwrap();
assert_eq!(series2.get_current(), true);
// Int => Series<Bool>
let series3: RefData<Series<Bool>> =
Series::explicity_from(PineRef::new(Some(1))).unwrap();
assert_eq!(series3.get_current(), true);
// Series<Int> => Series<Bool>
let series4: RefData<Series<Bool>> =
Series::explicity_from(PineRef::new(Series::from(Some(1)))).unwrap();
assert_eq!(series4.get_current(), true);
// NA => Series<Bool>
let series5: RefData<Series<Bool>> = Series::explicity_from(PineRef::new(NA)).unwrap();
assert_eq!(series5.get_current(), false);
}
}
}
|
pub struct Solution;
impl Solution {
pub fn can_construct(ransom_note: String, magazine: String) -> bool {
let mut count = [0; 26];
for b in magazine.bytes() {
count[(b - b'a') as usize] += 1;
}
for b in ransom_note.bytes() {
count[(b - b'a') as usize] -= 1;
if count[(b - b'a') as usize] < 0 {
return false;
}
}
true
}
}
#[test]
fn test0383() {
fn case(ransom_note: &str, magazine: &str, want: bool) {
let got = Solution::can_construct(ransom_note.to_string(), magazine.to_string());
assert_eq!(got, want);
}
case("a", "b", false);
case("aa", "bb", false);
case("aa", "aab", true);
}
|
mod lb110;
mod lighting;
pub use self::lb110::LB110;
use crate::bulb::lighting::HSV;
use crate::cloud::{Cloud, CloudInfo};
use crate::config::Config;
use crate::device::Device;
use crate::emeter::{DayStats, Emeter, MonthStats, RealtimeStats};
use crate::error::Result;
use crate::sys::Sys;
use crate::sysinfo::SysInfo;
use crate::time::{DeviceTime, DeviceTimeZone, Time};
use crate::wlan::{AccessPoint, Wlan};
use std::fmt;
use std::net::IpAddr;
use std::time::Duration;
/// A TP-Link Smart Bulb.
///
/// # Examples
///
/// ```no_run
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
///
/// bulb.turn_on()?;
/// assert_eq!(bulb.is_on()?, true);
///
/// bulb.turn_off()?;
/// assert_eq!(bulb.is_on()?, false);
///
/// Ok(())
/// }
/// ```
pub struct Bulb<T> {
device: T,
}
impl<T: Device> Bulb<T> {
/// Turns on the bulb.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// bulb.turn_on()?;
/// assert_eq!(bulb.is_on()?, true);
/// # Ok(())
/// # }
/// ```
pub fn turn_on(&mut self) -> Result<()> {
self.device.turn_on()
}
/// Turns off the bulb.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// bulb.turn_off()?;
/// assert_eq!(bulb.is_on()?, false);
/// # Ok(())
/// # }
/// ```
pub fn turn_off(&mut self) -> Result<()> {
self.device.turn_off()
}
}
impl<T: Sys> Bulb<T> {
/// Reboots the bulb after the given duration. In case when
/// the delay duration is not provided, the bulb is set to
/// reboot after a default delay of 1 second.
///
/// # Examples
/// Reboots the bulb after a delay of 3 seconds.
///
/// ```no_run
/// use std::time::Duration;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// bulb.reboot(Some(Duration::from_secs(3)))?;
/// # Ok(())
/// # }
/// ```
///
/// Reboots the bulb after 1 second.
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// bulb.reboot(None)?;
/// # Ok(())
/// # }
/// ```
pub fn reboot(&mut self, delay: Option<Duration>) -> Result<()> {
self.device.reboot(delay)
}
/// Factory resets the bulb after the given duration. In case when the delay
/// duration is not provided, the bulb is set to reset after a default delay
/// of 1 second.
///
/// # Examples
/// Factory resets the bulb after a delay for 3 seconds.
///
/// ```no_run
/// use std::time::Duration;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// bulb.factory_reset(Some(Duration::from_secs(3)))?;
/// # Ok(())
/// # }
/// ```
///
/// Factory resets the bulb after 1 second.
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// bulb.factory_reset(None)?;
/// # Ok(())
/// # }
/// ```
pub fn factory_reset(&mut self, delay: Option<Duration>) -> Result<()> {
self.device.factory_reset(delay)
}
}
impl<T: Time> Bulb<T> {
/// Returns the current date and time of the device without the timezone.
/// To get the device timezone, use [`timezone`] method.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let device_time = bulb.time()?;
/// println!("{}", device_time); // e.g. `2020-04-08 22:29:07`
/// # Ok(())
/// # }
/// ```
///
/// [`timezone`]: #method.timezone
pub fn time(&mut self) -> Result<DeviceTime> {
self.device.time()
}
/// Returns the current timezone of the device.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// bulb.timezone()?;
/// # Ok(())
/// # }
/// ```
pub fn timezone(&mut self) -> Result<DeviceTimeZone> {
self.device.timezone()
}
}
impl<T: Cloud> Bulb<T> {
pub fn get_cloud_info(&mut self) -> Result<CloudInfo> {
self.device.get_cloud_info()
}
pub fn bind(&mut self, username: &str, password: &str) -> Result<()> {
self.device.bind(username, password)
}
pub fn unbind(&mut self) -> Result<()> {
self.device.unbind()
}
pub fn get_firmware_list(&mut self) -> Result<Vec<String>> {
self.device.get_firmware_list()
}
pub fn set_server_url(&mut self, url: &str) -> Result<()> {
self.device.set_server_url(url)
}
}
impl<T: Wlan> Bulb<T> {
pub fn get_scan_info(
&mut self,
refresh: bool,
timeout: Option<Duration>,
) -> Result<Vec<AccessPoint>> {
self.device.get_scan_info(refresh, timeout)
}
}
impl<T: Emeter> Bulb<T> {
pub fn get_emeter_realtime(&mut self) -> Result<RealtimeStats> {
self.device.get_emeter_realtime()
}
pub fn get_emeter_month_stats(&mut self, year: u32) -> Result<MonthStats> {
self.device.get_emeter_month_stats(year)
}
pub fn get_emeter_day_stats(&mut self, month: u32, year: u32) -> Result<DayStats> {
self.device.get_emeter_day_stats(month, year)
}
pub fn erase_emeter_stats(&mut self) -> Result<()> {
self.device.erase_emeter_stats()
}
}
impl<T: SysInfo> Bulb<T> {
/// Returns the bulb's system information.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let sysinfo = bulb.sysinfo()?;
/// # Ok(())
/// # }
/// ```
pub fn sysinfo(&mut self) -> Result<T::Info> {
self.device.sysinfo()
}
}
impl Bulb<LB110> {
/// Creates a new Bulb instance from the given local address.
///
/// # Examples
///
/// ```no_run
/// let bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// ```
pub fn new<A>(host: A) -> Bulb<LB110>
where
A: Into<IpAddr>,
{
Bulb {
device: LB110::new(host),
}
}
pub fn with_config(config: Config) -> Bulb<LB110> {
Bulb {
device: LB110::with_config(config),
}
}
/// Returns the software version of the device.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let sw_ver = bulb.sw_ver()?;
/// # Ok(())
/// # }
/// ```
pub fn sw_ver(&mut self) -> Result<String> {
self.device.sw_ver()
}
/// Returns the hardware version of the device.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let hw_ver = bulb.hw_ver()?;
/// # Ok(())
/// # }
/// ```
pub fn hw_ver(&mut self) -> Result<String> {
self.device.hw_ver()
}
/// Returns the model of the device.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let model = bulb.model()?;
/// # Ok(())
/// # }
/// ```
pub fn model(&mut self) -> Result<String> {
self.device.model()
}
/// Returns the name (alias) of the device.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let alias = bulb.alias()?;
/// # Ok(())
/// # }
/// ```
pub fn alias(&mut self) -> Result<String> {
self.device.alias()
}
/// Returns the mac address of the device.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let mac_address = bulb.mac_address()?;
/// # Ok(())
/// # }
/// ```
pub fn mac_address(&mut self) -> Result<String> {
self.device.mac_address()
}
/// Returns whether the bulb supports brightness changes.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let is_dimmable = bulb.is_dimmable()?;
/// # Ok(())
/// # }
/// ```
pub fn is_dimmable(&mut self) -> Result<bool> {
self.device.is_dimmable()
}
/// Returns whether the bulb supports color changes.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let is_color = bulb.is_color()?;
/// # Ok(())
/// # }
/// ```
pub fn is_color(&mut self) -> Result<bool> {
self.device.is_color()
}
/// Returns whether the bulb supports color temperature changes.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let is_variable_color_temp = bulb.is_variable_color_temp()?;
/// # Ok(())
/// # }
/// ```
pub fn is_variable_color_temp(&mut self) -> Result<bool> {
self.device.is_variable_color_temp()
}
/// Returns the Wi-Fi signal strength (rssi) of the device.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let rssi = bulb.rssi()?;
/// # Ok(())
/// # }
/// ```
pub fn rssi(&mut self) -> Result<i64> {
self.device.rssi()
}
/// Returns whether the device is currently switched on.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let is_on = bulb.is_on()?;
/// # Ok(())
/// # }
/// ```
pub fn is_on(&mut self) -> Result<bool> {
self.device.is_on()
}
/// Returns the current HSV (Hue, Saturation, Value) state of the bulb.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let hsv = bulb.hsv()?;
///
/// let hue = hsv.hue(); // degrees (0-360)
/// let saturation = hsv.saturation(); // % (0-100)
/// let brightness = hsv.value(); // % (0-100)
/// # Ok(())
/// # }
/// ```
pub fn hsv(&mut self) -> Result<HSV> {
self.device.hsv()
}
/// Sets HSV (Hue, Saturation, Value) state of the bulb.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// if let Err(e) = bulb.set_hsv(270, 55, 90) {
/// eprintln!("error setting hsv: {}", e);
/// }
/// # Ok(())
/// # }
/// ```
pub fn set_hsv(&mut self, hue: u32, saturation: u32, value: u32) -> Result<()> {
self.device.set_hsv(hue, saturation, value)
}
/// Returns whether the device supports `emeter` stats.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// let has_emeter = bulb.has_emeter()?;
/// # Ok(())
/// # }
/// ```
pub fn has_emeter(&mut self) -> Result<bool> {
self.device.has_emeter()
}
/// Sets the hue of the bulb, if the bulb supports color changes.
/// Hue is color portion of the HSV model which is expressed as a
/// number from 0 to 360 degrees.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// bulb.set_hue(140)?;
/// # Ok(())
/// # }
/// ```
pub fn set_hue(&mut self, hue: u32) -> Result<()> {
self.device.set_hue(hue)
}
/// Returns the hue value (expressed as a number from 0 to 360 degrees)
/// of the bulb, if the bulb supports color changes.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// println!("hue: {}", bulb.hue()?);
/// # Ok(())
/// # }
/// ```
pub fn hue(&mut self) -> Result<u32> {
self.device.hue()
}
/// Sets the % saturation of the bulb, if the bulb supports color changes.
/// Saturation determines the amount of gray in a particular color and is
/// expressed as a number from 0 to 100 percent.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// bulb.set_saturation(70)?;
/// # Ok(())
/// # }
/// ```
pub fn set_saturation(&mut self, saturation: u32) -> Result<()> {
self.device.set_saturation(saturation)
}
/// Returns the current % saturation of the bulb, if the bulb supports
/// color changes.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// println!("% saturation: {}", bulb.saturation()?);
/// # Ok(())
/// # }
/// ```
pub fn saturation(&mut self) -> Result<u32> {
self.device.saturation()
}
/// Sets the % brightness of the bulb, if the bulb supports brightness changes.
/// Brightness determines the intensity of the color and is expressed
/// as a number from 0 to 100 percent.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// bulb.set_brightness(30)?;
/// # Ok(())
/// # }
/// ```
pub fn set_brightness(&mut self, brightness: u32) -> Result<()> {
self.device.set_brightness(brightness)
}
/// Returns the current % brightness of the bulb, if the bulb supports
/// brightness changes.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// println!("% brightness: {}", bulb.brightness()?);
/// # Ok(())
/// # }
/// ```
pub fn brightness(&mut self) -> Result<u32> {
self.device.brightness()
}
/// Sets the color temperature of the bulb, if the bulb supports color
/// changes.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// bulb.set_color_temp(2400)?;
/// # Ok(())
/// # }
/// ```
pub fn set_color_temp(&mut self, color_temp: u32) -> Result<()> {
self.device.set_color_temp(color_temp)
}
/// Returns the current color temperature of the bulb.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut bulb = tplink::Bulb::new([192, 168, 1, 101]);
/// println!("color temperature: {}", bulb.color_temp()?);
/// # Ok(())
/// # }
/// ```
pub fn color_temp(&mut self) -> Result<u32> {
self.device.color_temp()
}
}
impl<T: fmt::Debug> fmt::Debug for Bulb<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.device.fmt(f)
}
}
|
use crate::id;
use crate::stake_state::{StakeAccount, StakeState};
use bincode::deserialize;
use log::*;
use serde_derive::{Deserialize, Serialize};
use morgan_interface::account::KeyedAccount;
use morgan_interface::instruction::{AccountMeta, Instruction, InstructionError};
use morgan_interface::pubkey::Pubkey;
use morgan_interface::system_instruction;
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub enum StakeInstruction {
/// Initialize the stake account as a Delegate account.
///
/// Expects 2 Accounts:
/// 0 - payer (TODO unused/remove)
/// 1 - Delegate StakeAccount to be initialized
InitializeDelegate,
// Initialize the stake account as a MiningPool account
///
/// Expects 2 Accounts:
/// 0 - payer (TODO unused/remove)
/// 1 - MiningPool StakeAccount to be initialized
InitializeMiningPool,
/// `Delegate` or `Assign` a stake account to a particular node
///
/// Expects 3 Accounts:
/// 0 - payer (TODO unused/remove)
/// 1 - Delegate StakeAccount to be updated
/// 2 - VoteAccount to which this Stake will be delegated
DelegateStake,
/// Redeem credits in the stake account
///
/// Expects 4 Accounts:
/// 0 - payer (TODO unused/remove)
/// 1 - MiningPool Stake Account to redeem credits from
/// 2 - Delegate StakeAccount to be updated
/// 3 - VoteAccount to which the Stake is delegated
RedeemVoteCredits,
}
pub fn create_delegate_account(
from_pubkey: &Pubkey,
staker_pubkey: &Pubkey,
difs: u64,
) -> Vec<Instruction> {
vec![
system_instruction::create_account(
from_pubkey,
staker_pubkey,
difs,
std::mem::size_of::<StakeState>() as u64,
&id(),
),
Instruction::new(
id(),
&StakeInstruction::InitializeDelegate,
vec![
AccountMeta::new(*from_pubkey, true),
AccountMeta::new(*staker_pubkey, false),
],
),
]
}
pub fn create_mining_pool_account(
from_pubkey: &Pubkey,
staker_pubkey: &Pubkey,
difs: u64,
) -> Vec<Instruction> {
vec![
system_instruction::create_account(
from_pubkey,
staker_pubkey,
difs,
std::mem::size_of::<StakeState>() as u64,
&id(),
),
Instruction::new(
id(),
&StakeInstruction::InitializeMiningPool,
vec![
AccountMeta::new(*from_pubkey, true),
AccountMeta::new(*staker_pubkey, false),
],
),
]
}
pub fn redeem_vote_credits(
from_pubkey: &Pubkey,
mining_pool_pubkey: &Pubkey,
stake_pubkey: &Pubkey,
vote_pubkey: &Pubkey,
) -> Instruction {
let account_metas = vec![
AccountMeta::new(*from_pubkey, true),
AccountMeta::new(*mining_pool_pubkey, false),
AccountMeta::new(*stake_pubkey, false),
AccountMeta::new(*vote_pubkey, false),
];
Instruction::new(id(), &StakeInstruction::RedeemVoteCredits, account_metas)
}
pub fn delegate_stake(
from_pubkey: &Pubkey,
stake_pubkey: &Pubkey,
vote_pubkey: &Pubkey,
) -> Instruction {
let account_metas = vec![
AccountMeta::new(*from_pubkey, true),
AccountMeta::new(*stake_pubkey, true),
AccountMeta::new(*vote_pubkey, false),
];
Instruction::new(id(), &StakeInstruction::DelegateStake, account_metas)
}
pub fn process_instruction(
_program_id: &Pubkey,
keyed_accounts: &mut [KeyedAccount],
data: &[u8],
_tick_height: u64,
) -> Result<(), InstructionError> {
morgan_logger::setup();
trace!("process_instruction: {:?}", data);
trace!("keyed_accounts: {:?}", keyed_accounts);
if keyed_accounts.len() < 2 {
Err(InstructionError::InvalidInstructionData)?;
}
// 0th index is the account who paid for the transaction
// TODO: Remove the 0th index from the instruction. The stake program doesn't care who paid.
let (me, rest) = &mut keyed_accounts.split_at_mut(2);
let me = &mut me[1];
// TODO: data-driven unpack and dispatch of KeyedAccounts
match deserialize(data).map_err(|_| InstructionError::InvalidInstructionData)? {
StakeInstruction::InitializeMiningPool => {
if !rest.is_empty() {
Err(InstructionError::InvalidInstructionData)?;
}
me.initialize_mining_pool()
}
StakeInstruction::InitializeDelegate => {
if !rest.is_empty() {
Err(InstructionError::InvalidInstructionData)?;
}
me.initialize_delegate()
}
StakeInstruction::DelegateStake => {
if rest.len() != 1 {
Err(InstructionError::InvalidInstructionData)?;
}
let vote = &rest[0];
me.delegate_stake(vote)
}
StakeInstruction::RedeemVoteCredits => {
if rest.len() != 2 {
Err(InstructionError::InvalidInstructionData)?;
}
let (stake, vote) = rest.split_at_mut(1);
let stake = &mut stake[0];
let vote = &mut vote[0];
me.redeem_vote_credits(stake, vote)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use bincode::serialize;
use morgan_interface::account::Account;
fn process_instruction(instruction: &Instruction) -> Result<(), InstructionError> {
let mut accounts = vec![];
for _ in 0..instruction.accounts.len() {
accounts.push(Account::default());
}
{
let mut keyed_accounts: Vec<_> = instruction
.accounts
.iter()
.zip(accounts.iter_mut())
.map(|(meta, account)| KeyedAccount::new(&meta.pubkey, meta.is_signer, account))
.collect();
super::process_instruction(
&Pubkey::default(),
&mut keyed_accounts,
&instruction.data,
0,
)
}
}
#[test]
fn test_stake_process_instruction() {
assert_eq!(
process_instruction(&redeem_vote_credits(
&Pubkey::default(),
&Pubkey::default(),
&Pubkey::default(),
&Pubkey::default()
)),
Err(InstructionError::InvalidAccountData),
);
assert_eq!(
process_instruction(&delegate_stake(
&Pubkey::default(),
&Pubkey::default(),
&Pubkey::default()
)),
Err(InstructionError::InvalidAccountData),
);
}
#[test]
fn test_stake_process_instruction_decode_bail() {
// these will not call stake_state, have bogus contents
// gets the first check
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [KeyedAccount::new(
&Pubkey::default(),
false,
&mut Account::default(),
)],
&serialize(&StakeInstruction::DelegateStake).unwrap(),
0,
),
Err(InstructionError::InvalidInstructionData),
);
// gets the sub-check for number of args
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [
KeyedAccount::new(&Pubkey::default(), true, &mut Account::default()),
KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()),
],
&serialize(&StakeInstruction::DelegateStake).unwrap(),
0,
),
Err(InstructionError::InvalidInstructionData),
);
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [
KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()),
KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()),
KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()),
],
&serialize(&StakeInstruction::RedeemVoteCredits).unwrap(),
0,
),
Err(InstructionError::InvalidInstructionData),
);
// gets the check in delegate_stake
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [
KeyedAccount::new(&Pubkey::default(), true, &mut Account::default()), // from
KeyedAccount::new(&Pubkey::default(), true, &mut Account::default()),
KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()),
],
&serialize(&StakeInstruction::DelegateStake).unwrap(),
0,
),
Err(InstructionError::InvalidAccountData),
);
// gets the check in redeem_vote_credits
assert_eq!(
super::process_instruction(
&Pubkey::default(),
&mut [
KeyedAccount::new(&Pubkey::default(), true, &mut Account::default()), // from
KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()),
KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()),
KeyedAccount::new(&Pubkey::default(), false, &mut Account::default()),
],
&serialize(&StakeInstruction::RedeemVoteCredits).unwrap(),
0,
),
Err(InstructionError::InvalidAccountData),
);
}
}
|
#[doc = "Reader of register SMPR1"]
pub type R = crate::R<u32, super::SMPR1>;
#[doc = "Writer for register SMPR1"]
pub type W = crate::W<u32, super::SMPR1>;
#[doc = "Register SMPR1 `reset()`'s with value 0"]
impl crate::ResetValue for super::SMPR1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Channel 9 sampling time selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum SMP9_A {
#[doc = "0: 2.5 ADC clock cycles"]
CYCLES2_5 = 0,
#[doc = "1: 6.5 ADC clock cycles"]
CYCLES6_5 = 1,
#[doc = "2: 12.5 ADC clock cycles"]
CYCLES12_5 = 2,
#[doc = "3: 24.5 ADC clock cycles"]
CYCLES24_5 = 3,
#[doc = "4: 47.5 ADC clock cycles"]
CYCLES47_5 = 4,
#[doc = "5: 92.5 ADC clock cycles"]
CYCLES92_5 = 5,
#[doc = "6: 247.5 ADC clock cycles"]
CYCLES247_5 = 6,
#[doc = "7: 640.5 ADC clock cycles"]
CYCLES640_5 = 7,
}
impl From<SMP9_A> for u8 {
#[inline(always)]
fn from(variant: SMP9_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `SMP9`"]
pub type SMP9_R = crate::R<u8, SMP9_A>;
impl SMP9_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SMP9_A {
match self.bits {
0 => SMP9_A::CYCLES2_5,
1 => SMP9_A::CYCLES6_5,
2 => SMP9_A::CYCLES12_5,
3 => SMP9_A::CYCLES24_5,
4 => SMP9_A::CYCLES47_5,
5 => SMP9_A::CYCLES92_5,
6 => SMP9_A::CYCLES247_5,
7 => SMP9_A::CYCLES640_5,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `CYCLES2_5`"]
#[inline(always)]
pub fn is_cycles2_5(&self) -> bool {
*self == SMP9_A::CYCLES2_5
}
#[doc = "Checks if the value of the field is `CYCLES6_5`"]
#[inline(always)]
pub fn is_cycles6_5(&self) -> bool {
*self == SMP9_A::CYCLES6_5
}
#[doc = "Checks if the value of the field is `CYCLES12_5`"]
#[inline(always)]
pub fn is_cycles12_5(&self) -> bool {
*self == SMP9_A::CYCLES12_5
}
#[doc = "Checks if the value of the field is `CYCLES24_5`"]
#[inline(always)]
pub fn is_cycles24_5(&self) -> bool {
*self == SMP9_A::CYCLES24_5
}
#[doc = "Checks if the value of the field is `CYCLES47_5`"]
#[inline(always)]
pub fn is_cycles47_5(&self) -> bool {
*self == SMP9_A::CYCLES47_5
}
#[doc = "Checks if the value of the field is `CYCLES92_5`"]
#[inline(always)]
pub fn is_cycles92_5(&self) -> bool {
*self == SMP9_A::CYCLES92_5
}
#[doc = "Checks if the value of the field is `CYCLES247_5`"]
#[inline(always)]
pub fn is_cycles247_5(&self) -> bool {
*self == SMP9_A::CYCLES247_5
}
#[doc = "Checks if the value of the field is `CYCLES640_5`"]
#[inline(always)]
pub fn is_cycles640_5(&self) -> bool {
*self == SMP9_A::CYCLES640_5
}
}
#[doc = "Write proxy for field `SMP9`"]
pub struct SMP9_W<'a> {
w: &'a mut W,
}
impl<'a> SMP9_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SMP9_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "2.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles2_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES2_5)
}
#[doc = "6.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles6_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES6_5)
}
#[doc = "12.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles12_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES12_5)
}
#[doc = "24.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles24_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES24_5)
}
#[doc = "47.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles47_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES47_5)
}
#[doc = "92.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles92_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES92_5)
}
#[doc = "247.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles247_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES247_5)
}
#[doc = "640.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles640_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES640_5)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 27)) | (((value as u32) & 0x07) << 27);
self.w
}
}
#[doc = "Channel 8 sampling time selection"]
pub type SMP8_A = SMP9_A;
#[doc = "Reader of field `SMP8`"]
pub type SMP8_R = crate::R<u8, SMP9_A>;
#[doc = "Write proxy for field `SMP8`"]
pub struct SMP8_W<'a> {
w: &'a mut W,
}
impl<'a> SMP8_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SMP8_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "2.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles2_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES2_5)
}
#[doc = "6.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles6_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES6_5)
}
#[doc = "12.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles12_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES12_5)
}
#[doc = "24.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles24_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES24_5)
}
#[doc = "47.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles47_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES47_5)
}
#[doc = "92.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles92_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES92_5)
}
#[doc = "247.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles247_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES247_5)
}
#[doc = "640.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles640_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES640_5)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 24)) | (((value as u32) & 0x07) << 24);
self.w
}
}
#[doc = "Channel 7 sampling time selection"]
pub type SMP7_A = SMP9_A;
#[doc = "Reader of field `SMP7`"]
pub type SMP7_R = crate::R<u8, SMP9_A>;
#[doc = "Write proxy for field `SMP7`"]
pub struct SMP7_W<'a> {
w: &'a mut W,
}
impl<'a> SMP7_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SMP7_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "2.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles2_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES2_5)
}
#[doc = "6.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles6_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES6_5)
}
#[doc = "12.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles12_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES12_5)
}
#[doc = "24.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles24_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES24_5)
}
#[doc = "47.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles47_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES47_5)
}
#[doc = "92.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles92_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES92_5)
}
#[doc = "247.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles247_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES247_5)
}
#[doc = "640.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles640_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES640_5)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 21)) | (((value as u32) & 0x07) << 21);
self.w
}
}
#[doc = "Channel 6 sampling time selection"]
pub type SMP6_A = SMP9_A;
#[doc = "Reader of field `SMP6`"]
pub type SMP6_R = crate::R<u8, SMP9_A>;
#[doc = "Write proxy for field `SMP6`"]
pub struct SMP6_W<'a> {
w: &'a mut W,
}
impl<'a> SMP6_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SMP6_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "2.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles2_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES2_5)
}
#[doc = "6.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles6_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES6_5)
}
#[doc = "12.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles12_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES12_5)
}
#[doc = "24.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles24_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES24_5)
}
#[doc = "47.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles47_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES47_5)
}
#[doc = "92.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles92_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES92_5)
}
#[doc = "247.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles247_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES247_5)
}
#[doc = "640.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles640_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES640_5)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 18)) | (((value as u32) & 0x07) << 18);
self.w
}
}
#[doc = "Channel 5 sampling time selection"]
pub type SMP5_A = SMP9_A;
#[doc = "Reader of field `SMP5`"]
pub type SMP5_R = crate::R<u8, SMP9_A>;
#[doc = "Write proxy for field `SMP5`"]
pub struct SMP5_W<'a> {
w: &'a mut W,
}
impl<'a> SMP5_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SMP5_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "2.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles2_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES2_5)
}
#[doc = "6.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles6_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES6_5)
}
#[doc = "12.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles12_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES12_5)
}
#[doc = "24.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles24_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES24_5)
}
#[doc = "47.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles47_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES47_5)
}
#[doc = "92.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles92_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES92_5)
}
#[doc = "247.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles247_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES247_5)
}
#[doc = "640.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles640_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES640_5)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 15)) | (((value as u32) & 0x07) << 15);
self.w
}
}
#[doc = "Channel 4 sampling time selection"]
pub type SMP4_A = SMP9_A;
#[doc = "Reader of field `SMP4`"]
pub type SMP4_R = crate::R<u8, SMP9_A>;
#[doc = "Write proxy for field `SMP4`"]
pub struct SMP4_W<'a> {
w: &'a mut W,
}
impl<'a> SMP4_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SMP4_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "2.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles2_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES2_5)
}
#[doc = "6.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles6_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES6_5)
}
#[doc = "12.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles12_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES12_5)
}
#[doc = "24.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles24_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES24_5)
}
#[doc = "47.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles47_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES47_5)
}
#[doc = "92.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles92_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES92_5)
}
#[doc = "247.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles247_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES247_5)
}
#[doc = "640.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles640_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES640_5)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 12)) | (((value as u32) & 0x07) << 12);
self.w
}
}
#[doc = "Channel 3 sampling time selection"]
pub type SMP3_A = SMP9_A;
#[doc = "Reader of field `SMP3`"]
pub type SMP3_R = crate::R<u8, SMP9_A>;
#[doc = "Write proxy for field `SMP3`"]
pub struct SMP3_W<'a> {
w: &'a mut W,
}
impl<'a> SMP3_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SMP3_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "2.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles2_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES2_5)
}
#[doc = "6.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles6_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES6_5)
}
#[doc = "12.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles12_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES12_5)
}
#[doc = "24.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles24_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES24_5)
}
#[doc = "47.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles47_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES47_5)
}
#[doc = "92.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles92_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES92_5)
}
#[doc = "247.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles247_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES247_5)
}
#[doc = "640.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles640_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES640_5)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 9)) | (((value as u32) & 0x07) << 9);
self.w
}
}
#[doc = "Channel 2 sampling time selection"]
pub type SMP2_A = SMP9_A;
#[doc = "Reader of field `SMP2`"]
pub type SMP2_R = crate::R<u8, SMP9_A>;
#[doc = "Write proxy for field `SMP2`"]
pub struct SMP2_W<'a> {
w: &'a mut W,
}
impl<'a> SMP2_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SMP2_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "2.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles2_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES2_5)
}
#[doc = "6.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles6_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES6_5)
}
#[doc = "12.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles12_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES12_5)
}
#[doc = "24.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles24_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES24_5)
}
#[doc = "47.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles47_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES47_5)
}
#[doc = "92.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles92_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES92_5)
}
#[doc = "247.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles247_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES247_5)
}
#[doc = "640.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles640_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES640_5)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 6)) | (((value as u32) & 0x07) << 6);
self.w
}
}
#[doc = "Channel 1 sampling time selection"]
pub type SMP1_A = SMP9_A;
#[doc = "Reader of field `SMP1`"]
pub type SMP1_R = crate::R<u8, SMP9_A>;
#[doc = "Write proxy for field `SMP1`"]
pub struct SMP1_W<'a> {
w: &'a mut W,
}
impl<'a> SMP1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SMP1_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "2.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles2_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES2_5)
}
#[doc = "6.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles6_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES6_5)
}
#[doc = "12.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles12_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES12_5)
}
#[doc = "24.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles24_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES24_5)
}
#[doc = "47.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles47_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES47_5)
}
#[doc = "92.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles92_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES92_5)
}
#[doc = "247.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles247_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES247_5)
}
#[doc = "640.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles640_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES640_5)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 3)) | (((value as u32) & 0x07) << 3);
self.w
}
}
#[doc = "Addition of one clock cycle to the sampling time\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SMPPLUS_A {
#[doc = "0: 2.5 in SMPR remains 2.5 cycles"]
NORMAL = 0,
#[doc = "1: 2.5 in SMPR becomes 3.5 cycles"]
PLUS1 = 1,
}
impl From<SMPPLUS_A> for bool {
#[inline(always)]
fn from(variant: SMPPLUS_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `SMPPLUS`"]
pub type SMPPLUS_R = crate::R<bool, SMPPLUS_A>;
impl SMPPLUS_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SMPPLUS_A {
match self.bits {
false => SMPPLUS_A::NORMAL,
true => SMPPLUS_A::PLUS1,
}
}
#[doc = "Checks if the value of the field is `NORMAL`"]
#[inline(always)]
pub fn is_normal(&self) -> bool {
*self == SMPPLUS_A::NORMAL
}
#[doc = "Checks if the value of the field is `PLUS1`"]
#[inline(always)]
pub fn is_plus1(&self) -> bool {
*self == SMPPLUS_A::PLUS1
}
}
#[doc = "Write proxy for field `SMPPLUS`"]
pub struct SMPPLUS_W<'a> {
w: &'a mut W,
}
impl<'a> SMPPLUS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SMPPLUS_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "2.5 in SMPR remains 2.5 cycles"]
#[inline(always)]
pub fn normal(self) -> &'a mut W {
self.variant(SMPPLUS_A::NORMAL)
}
#[doc = "2.5 in SMPR becomes 3.5 cycles"]
#[inline(always)]
pub fn plus1(self) -> &'a mut W {
self.variant(SMPPLUS_A::PLUS1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
#[doc = "Channel 0 sampling time selection"]
pub type SMP0_A = SMP9_A;
#[doc = "Reader of field `SMP0`"]
pub type SMP0_R = crate::R<u8, SMP9_A>;
#[doc = "Write proxy for field `SMP0`"]
pub struct SMP0_W<'a> {
w: &'a mut W,
}
impl<'a> SMP0_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SMP0_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "2.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles2_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES2_5)
}
#[doc = "6.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles6_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES6_5)
}
#[doc = "12.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles12_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES12_5)
}
#[doc = "24.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles24_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES24_5)
}
#[doc = "47.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles47_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES47_5)
}
#[doc = "92.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles92_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES92_5)
}
#[doc = "247.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles247_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES247_5)
}
#[doc = "640.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles640_5(self) -> &'a mut W {
self.variant(SMP9_A::CYCLES640_5)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07);
self.w
}
}
impl R {
#[doc = "Bits 27:29 - Channel 9 sampling time selection"]
#[inline(always)]
pub fn smp9(&self) -> SMP9_R {
SMP9_R::new(((self.bits >> 27) & 0x07) as u8)
}
#[doc = "Bits 24:26 - Channel 8 sampling time selection"]
#[inline(always)]
pub fn smp8(&self) -> SMP8_R {
SMP8_R::new(((self.bits >> 24) & 0x07) as u8)
}
#[doc = "Bits 21:23 - Channel 7 sampling time selection"]
#[inline(always)]
pub fn smp7(&self) -> SMP7_R {
SMP7_R::new(((self.bits >> 21) & 0x07) as u8)
}
#[doc = "Bits 18:20 - Channel 6 sampling time selection"]
#[inline(always)]
pub fn smp6(&self) -> SMP6_R {
SMP6_R::new(((self.bits >> 18) & 0x07) as u8)
}
#[doc = "Bits 15:17 - Channel 5 sampling time selection"]
#[inline(always)]
pub fn smp5(&self) -> SMP5_R {
SMP5_R::new(((self.bits >> 15) & 0x07) as u8)
}
#[doc = "Bits 12:14 - Channel 4 sampling time selection"]
#[inline(always)]
pub fn smp4(&self) -> SMP4_R {
SMP4_R::new(((self.bits >> 12) & 0x07) as u8)
}
#[doc = "Bits 9:11 - Channel 3 sampling time selection"]
#[inline(always)]
pub fn smp3(&self) -> SMP3_R {
SMP3_R::new(((self.bits >> 9) & 0x07) as u8)
}
#[doc = "Bits 6:8 - Channel 2 sampling time selection"]
#[inline(always)]
pub fn smp2(&self) -> SMP2_R {
SMP2_R::new(((self.bits >> 6) & 0x07) as u8)
}
#[doc = "Bits 3:5 - Channel 1 sampling time selection"]
#[inline(always)]
pub fn smp1(&self) -> SMP1_R {
SMP1_R::new(((self.bits >> 3) & 0x07) as u8)
}
#[doc = "Bit 31 - Addition of one clock cycle to the sampling time"]
#[inline(always)]
pub fn smpplus(&self) -> SMPPLUS_R {
SMPPLUS_R::new(((self.bits >> 31) & 0x01) != 0)
}
#[doc = "Bits 0:2 - Channel 0 sampling time selection"]
#[inline(always)]
pub fn smp0(&self) -> SMP0_R {
SMP0_R::new((self.bits & 0x07) as u8)
}
}
impl W {
#[doc = "Bits 27:29 - Channel 9 sampling time selection"]
#[inline(always)]
pub fn smp9(&mut self) -> SMP9_W {
SMP9_W { w: self }
}
#[doc = "Bits 24:26 - Channel 8 sampling time selection"]
#[inline(always)]
pub fn smp8(&mut self) -> SMP8_W {
SMP8_W { w: self }
}
#[doc = "Bits 21:23 - Channel 7 sampling time selection"]
#[inline(always)]
pub fn smp7(&mut self) -> SMP7_W {
SMP7_W { w: self }
}
#[doc = "Bits 18:20 - Channel 6 sampling time selection"]
#[inline(always)]
pub fn smp6(&mut self) -> SMP6_W {
SMP6_W { w: self }
}
#[doc = "Bits 15:17 - Channel 5 sampling time selection"]
#[inline(always)]
pub fn smp5(&mut self) -> SMP5_W {
SMP5_W { w: self }
}
#[doc = "Bits 12:14 - Channel 4 sampling time selection"]
#[inline(always)]
pub fn smp4(&mut self) -> SMP4_W {
SMP4_W { w: self }
}
#[doc = "Bits 9:11 - Channel 3 sampling time selection"]
#[inline(always)]
pub fn smp3(&mut self) -> SMP3_W {
SMP3_W { w: self }
}
#[doc = "Bits 6:8 - Channel 2 sampling time selection"]
#[inline(always)]
pub fn smp2(&mut self) -> SMP2_W {
SMP2_W { w: self }
}
#[doc = "Bits 3:5 - Channel 1 sampling time selection"]
#[inline(always)]
pub fn smp1(&mut self) -> SMP1_W {
SMP1_W { w: self }
}
#[doc = "Bit 31 - Addition of one clock cycle to the sampling time"]
#[inline(always)]
pub fn smpplus(&mut self) -> SMPPLUS_W {
SMPPLUS_W { w: self }
}
#[doc = "Bits 0:2 - Channel 0 sampling time selection"]
#[inline(always)]
pub fn smp0(&mut self) -> SMP0_W {
SMP0_W { w: self }
}
}
|
#![deny(rustdoc::broken_intra_doc_links, rustdoc::bare_urls, rust_2018_idioms)]
// `clippy::use_self` is deliberately excluded from the lints this crate uses.
// See <https://github.com/rust-lang/rust-clippy/issues/6902>.
#![warn(
missing_copy_implementations,
missing_debug_implementations,
missing_docs,
clippy::explicit_iter_loop,
clippy::clone_on_ref_ptr,
// See https://github.com/influxdata/influxdb_iox/pull/1671
clippy::future_not_send,
clippy::todo,
clippy::dbg_macro,
unused_crate_dependencies
)]
//! # influxdb2_client
//!
//! This is a Rust client to InfluxDB using the [2.0 API][2api].
//!
//! [2api]: https://v2.docs.influxdata.com/v2.0/reference/api/
//!
//! ## Work Remaining
//!
//! - Query
//! - optional sync client
//! - Influx 1.x API?
//! - Other parts of the API
//! - Pick the best name to use on crates.io and publish
//!
//! ## Quick start
//!
//! This example creates a client to an InfluxDB server running at `http://localhost:8888`, creates
//! a bucket with the name "mybucket" in the organization with name "myorg" and
//! ID "0000111100001111", builds two points, and writes the points to the
//! bucket.
//!
//! ```
//! async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use influxdb2_client::Client;
//! use influxdb2_client::models::{DataPoint, PostBucketRequest};
//! use futures::stream;
//!
//! let org = "myorg";
//! let org_id = "0000111100001111";
//! let bucket = "mybucket";
//!
//! let client = Client::new("http://localhost:8888", "some-token");
//!
//! client.create_bucket(
//! Some(PostBucketRequest::new(org_id.to_string(), bucket.to_string()))
//! ).await?;
//!
//! let points = vec![
//! DataPoint::builder("cpu")
//! .tag("host", "server01")
//! .field("usage", 0.5)
//! .build()?,
//! DataPoint::builder("cpu")
//! .tag("host", "server01")
//! .tag("region", "us-west")
//! .field("usage", 0.87)
//! .build()?,
//! ];
//!
//! client.write(org, bucket, stream::iter(points)).await?;
//! Ok(())
//! }
//! ```
// Workaround for "unused crate" lint false positives.
#[cfg(test)]
use once_cell as _;
#[cfg(test)]
use parking_lot as _;
#[cfg(test)]
use test_helpers as _;
use reqwest::Method;
use snafu::Snafu;
/// Errors that occur while making requests to the Influx server.
#[derive(Debug, Snafu)]
pub enum RequestError {
/// While making a request to the Influx server, the underlying `reqwest`
/// library returned an error that was not an HTTP 400 or 500.
#[snafu(display("Error while processing the HTTP request: {}", source))]
ReqwestProcessing {
/// The underlying error object from `reqwest`.
source: reqwest::Error,
},
/// The underlying `reqwest` library returned an HTTP error with code 400
/// (meaning a client error) or 500 (meaning a server error).
#[snafu(display("HTTP request returned an error: {}, `{}`", status, text))]
Http {
/// The `StatusCode` returned from the request
status: reqwest::StatusCode,
/// Any text data returned from the request
text: String,
},
/// While serializing data as JSON to send in a request, the underlying
/// `serde_json` library returned an error.
#[snafu(display("Error while serializing to JSON: {}", source))]
Serializing {
/// The underlying error object from `serde_json`.
source: serde_json::error::Error,
},
/// While deserializing the response as JSON, something went wrong.
#[snafu(display("Could not deserialize as JSON. Error: {source}\nText: `{text}`"))]
DeserializingJsonResponse {
/// The text of the response
text: String,
/// The underlying error object from serde
source: serde_json::Error,
},
/// Something went wrong getting the raw bytes of the response
#[snafu(display("Could not get response bytes: {source}"))]
ResponseBytes {
/// The underlying error object from reqwest
source: reqwest::Error,
},
/// Something went wrong converting the raw bytes of the response to a UTF-8 string
#[snafu(display("Invalid UTF-8: {source}"))]
ResponseString {
/// The underlying error object from std
source: std::string::FromUtf8Error,
},
}
/// Client to a server supporting the InfluxData 2.0 API.
#[derive(Debug, Clone)]
pub struct Client {
/// The base URL this client sends requests to
pub url: String,
auth_header: Option<String>,
reqwest: reqwest::Client,
jaeger_debug_header: Option<String>,
}
impl Client {
/// Default [jaeger debug header](Self::with_jaeger_debug) that should work in many
/// environments.
pub const DEFAULT_JAEGER_DEBUG_HEADER: &'static str = "jaeger-debug-id";
/// Create a new client pointing to the URL specified in
/// `protocol://server:port` format and using the specified token for
/// authorization.
///
/// # Example
///
/// ```
/// let client = influxdb2_client::Client::new("http://localhost:8888", "my-token");
/// ```
pub fn new(url: impl Into<String>, auth_token: impl Into<String>) -> Self {
let token = auth_token.into();
let auth_header = if token.is_empty() {
None
} else {
Some(format!("Token {token}"))
};
Self {
url: url.into(),
auth_header,
reqwest: reqwest::Client::builder()
.connection_verbose(true)
.build()
.expect("reqwest::Client should have built"),
jaeger_debug_header: None,
}
}
/// Enable generation of jaeger debug headers with the given header name.
pub fn with_jaeger_debug(self, header: String) -> Self {
Self {
jaeger_debug_header: Some(header),
..self
}
}
/// Consolidate common request building code
fn request(&self, method: Method, url: &str) -> reqwest::RequestBuilder {
let mut req = self.reqwest.request(method, url);
if let Some(auth) = &self.auth_header {
req = req.header("Authorization", auth);
}
if let Some(header) = &self.jaeger_debug_header {
req = req.header(header, format!("influxdb_client-{}", uuid::Uuid::new_v4()));
}
req
}
}
pub mod common;
pub mod api;
pub mod models;
|
// Copyright (c) 2020 Sam Blenny
// SPDX-License-Identifier: Apache-2.0 OR MIT
//
#![no_std]
extern crate blitstr;
use blitstr::FrBuf;
static mut FB: FrBuf = blitstr::new_fr_buf();
/// For building wasm32 no_std, add panic handler and functions to let
/// javascript check shared buffer pointers. This panic handler conflicts with
/// test panic handler and therefore cannot be included during `cargo test`.
#[cfg(target_arch = "wasm32")]
pub mod no_std_bindings;
/// Initialize screen
#[no_mangle]
pub extern "C" fn init() {
// Show sample text
blitstr::demo::sample_text(unsafe { &mut FB });
blitstr::demo::goose_poem(unsafe { &mut FB });
}
/// Export pointer to frame buffer shared memory for javascript + wasm32
#[no_mangle]
pub extern "C" fn frame_buf_ptr() -> *const u32 {
unsafe { FB.as_ptr() }
}
|
#[doc = "Reader of register MPCBB2_LCKVTR1"]
pub type R = crate::R<u32, super::MPCBB2_LCKVTR1>;
#[doc = "Writer for register MPCBB2_LCKVTR1"]
pub type W = crate::W<u32, super::MPCBB2_LCKVTR1>;
#[doc = "Register MPCBB2_LCKVTR1 `reset()`'s with value 0"]
impl crate::ResetValue for super::MPCBB2_LCKVTR1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `LCKSB0`"]
pub type LCKSB0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB0`"]
pub struct LCKSB0_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `LCKSB1`"]
pub type LCKSB1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB1`"]
pub struct LCKSB1_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `LCKSB2`"]
pub type LCKSB2_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB2`"]
pub struct LCKSB2_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB2_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `LCKSB3`"]
pub type LCKSB3_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB3`"]
pub struct LCKSB3_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB3_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `LCKSB4`"]
pub type LCKSB4_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB4`"]
pub struct LCKSB4_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB4_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `LCKSB5`"]
pub type LCKSB5_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB5`"]
pub struct LCKSB5_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB5_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `LCKSB6`"]
pub type LCKSB6_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB6`"]
pub struct LCKSB6_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB6_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `LCKSB7`"]
pub type LCKSB7_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB7`"]
pub struct LCKSB7_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB7_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `LCKSB8`"]
pub type LCKSB8_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB8`"]
pub struct LCKSB8_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB8_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `LCKSB9`"]
pub type LCKSB9_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB9`"]
pub struct LCKSB9_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB9_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `LCKSB10`"]
pub type LCKSB10_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB10`"]
pub struct LCKSB10_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB10_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `LCKSB11`"]
pub type LCKSB11_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB11`"]
pub struct LCKSB11_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB11_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `LCKSB12`"]
pub type LCKSB12_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB12`"]
pub struct LCKSB12_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB12_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `LCKSB13`"]
pub type LCKSB13_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB13`"]
pub struct LCKSB13_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB13_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `LCKSB14`"]
pub type LCKSB14_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB14`"]
pub struct LCKSB14_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB14_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reader of field `LCKSB15`"]
pub type LCKSB15_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB15`"]
pub struct LCKSB15_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB15_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Reader of field `LCKSB16`"]
pub type LCKSB16_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB16`"]
pub struct LCKSB16_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB16_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `LCKSB17`"]
pub type LCKSB17_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB17`"]
pub struct LCKSB17_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB17_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `LCKSB18`"]
pub type LCKSB18_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB18`"]
pub struct LCKSB18_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB18_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `LCKSB19`"]
pub type LCKSB19_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB19`"]
pub struct LCKSB19_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB19_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Reader of field `LCKSB20`"]
pub type LCKSB20_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB20`"]
pub struct LCKSB20_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB20_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Reader of field `LCKSB21`"]
pub type LCKSB21_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB21`"]
pub struct LCKSB21_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB21_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "Reader of field `LCKSB22`"]
pub type LCKSB22_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB22`"]
pub struct LCKSB22_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB22_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "Reader of field `LCKSB23`"]
pub type LCKSB23_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB23`"]
pub struct LCKSB23_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB23_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "Reader of field `LCKSB24`"]
pub type LCKSB24_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB24`"]
pub struct LCKSB24_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB24_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `LCKSB25`"]
pub type LCKSB25_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB25`"]
pub struct LCKSB25_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB25_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Reader of field `LCKSB26`"]
pub type LCKSB26_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB26`"]
pub struct LCKSB26_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB26_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "Reader of field `LCKSB27`"]
pub type LCKSB27_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB27`"]
pub struct LCKSB27_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB27_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "Reader of field `LCKSB28`"]
pub type LCKSB28_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB28`"]
pub struct LCKSB28_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB28_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "Reader of field `LCKSB29`"]
pub type LCKSB29_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB29`"]
pub struct LCKSB29_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB29_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
#[doc = "Reader of field `LCKSB30`"]
pub type LCKSB30_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB30`"]
pub struct LCKSB30_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB30_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Reader of field `LCKSB31`"]
pub type LCKSB31_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LCKSB31`"]
pub struct LCKSB31_W<'a> {
w: &'a mut W,
}
impl<'a> LCKSB31_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 0 - LCKSB0"]
#[inline(always)]
pub fn lcksb0(&self) -> LCKSB0_R {
LCKSB0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - LCKSB1"]
#[inline(always)]
pub fn lcksb1(&self) -> LCKSB1_R {
LCKSB1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - LCKSB2"]
#[inline(always)]
pub fn lcksb2(&self) -> LCKSB2_R {
LCKSB2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - LCKSB3"]
#[inline(always)]
pub fn lcksb3(&self) -> LCKSB3_R {
LCKSB3_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - LCKSB4"]
#[inline(always)]
pub fn lcksb4(&self) -> LCKSB4_R {
LCKSB4_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - LCKSB5"]
#[inline(always)]
pub fn lcksb5(&self) -> LCKSB5_R {
LCKSB5_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - LCKSB6"]
#[inline(always)]
pub fn lcksb6(&self) -> LCKSB6_R {
LCKSB6_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - LCKSB7"]
#[inline(always)]
pub fn lcksb7(&self) -> LCKSB7_R {
LCKSB7_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - LCKSB8"]
#[inline(always)]
pub fn lcksb8(&self) -> LCKSB8_R {
LCKSB8_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - LCKSB9"]
#[inline(always)]
pub fn lcksb9(&self) -> LCKSB9_R {
LCKSB9_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - LCKSB10"]
#[inline(always)]
pub fn lcksb10(&self) -> LCKSB10_R {
LCKSB10_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - LCKSB11"]
#[inline(always)]
pub fn lcksb11(&self) -> LCKSB11_R {
LCKSB11_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - LCKSB12"]
#[inline(always)]
pub fn lcksb12(&self) -> LCKSB12_R {
LCKSB12_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - LCKSB13"]
#[inline(always)]
pub fn lcksb13(&self) -> LCKSB13_R {
LCKSB13_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - LCKSB14"]
#[inline(always)]
pub fn lcksb14(&self) -> LCKSB14_R {
LCKSB14_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - LCKSB15"]
#[inline(always)]
pub fn lcksb15(&self) -> LCKSB15_R {
LCKSB15_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - LCKSB16"]
#[inline(always)]
pub fn lcksb16(&self) -> LCKSB16_R {
LCKSB16_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - LCKSB17"]
#[inline(always)]
pub fn lcksb17(&self) -> LCKSB17_R {
LCKSB17_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - LCKSB18"]
#[inline(always)]
pub fn lcksb18(&self) -> LCKSB18_R {
LCKSB18_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - LCKSB19"]
#[inline(always)]
pub fn lcksb19(&self) -> LCKSB19_R {
LCKSB19_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 20 - LCKSB20"]
#[inline(always)]
pub fn lcksb20(&self) -> LCKSB20_R {
LCKSB20_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 21 - LCKSB21"]
#[inline(always)]
pub fn lcksb21(&self) -> LCKSB21_R {
LCKSB21_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - LCKSB22"]
#[inline(always)]
pub fn lcksb22(&self) -> LCKSB22_R {
LCKSB22_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 23 - LCKSB23"]
#[inline(always)]
pub fn lcksb23(&self) -> LCKSB23_R {
LCKSB23_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 24 - LCKSB24"]
#[inline(always)]
pub fn lcksb24(&self) -> LCKSB24_R {
LCKSB24_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 25 - LCKSB25"]
#[inline(always)]
pub fn lcksb25(&self) -> LCKSB25_R {
LCKSB25_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 26 - LCKSB26"]
#[inline(always)]
pub fn lcksb26(&self) -> LCKSB26_R {
LCKSB26_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 27 - LCKSB27"]
#[inline(always)]
pub fn lcksb27(&self) -> LCKSB27_R {
LCKSB27_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 28 - LCKSB28"]
#[inline(always)]
pub fn lcksb28(&self) -> LCKSB28_R {
LCKSB28_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - LCKSB29"]
#[inline(always)]
pub fn lcksb29(&self) -> LCKSB29_R {
LCKSB29_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 30 - LCKSB30"]
#[inline(always)]
pub fn lcksb30(&self) -> LCKSB30_R {
LCKSB30_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - LCKSB31"]
#[inline(always)]
pub fn lcksb31(&self) -> LCKSB31_R {
LCKSB31_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - LCKSB0"]
#[inline(always)]
pub fn lcksb0(&mut self) -> LCKSB0_W {
LCKSB0_W { w: self }
}
#[doc = "Bit 1 - LCKSB1"]
#[inline(always)]
pub fn lcksb1(&mut self) -> LCKSB1_W {
LCKSB1_W { w: self }
}
#[doc = "Bit 2 - LCKSB2"]
#[inline(always)]
pub fn lcksb2(&mut self) -> LCKSB2_W {
LCKSB2_W { w: self }
}
#[doc = "Bit 3 - LCKSB3"]
#[inline(always)]
pub fn lcksb3(&mut self) -> LCKSB3_W {
LCKSB3_W { w: self }
}
#[doc = "Bit 4 - LCKSB4"]
#[inline(always)]
pub fn lcksb4(&mut self) -> LCKSB4_W {
LCKSB4_W { w: self }
}
#[doc = "Bit 5 - LCKSB5"]
#[inline(always)]
pub fn lcksb5(&mut self) -> LCKSB5_W {
LCKSB5_W { w: self }
}
#[doc = "Bit 6 - LCKSB6"]
#[inline(always)]
pub fn lcksb6(&mut self) -> LCKSB6_W {
LCKSB6_W { w: self }
}
#[doc = "Bit 7 - LCKSB7"]
#[inline(always)]
pub fn lcksb7(&mut self) -> LCKSB7_W {
LCKSB7_W { w: self }
}
#[doc = "Bit 8 - LCKSB8"]
#[inline(always)]
pub fn lcksb8(&mut self) -> LCKSB8_W {
LCKSB8_W { w: self }
}
#[doc = "Bit 9 - LCKSB9"]
#[inline(always)]
pub fn lcksb9(&mut self) -> LCKSB9_W {
LCKSB9_W { w: self }
}
#[doc = "Bit 10 - LCKSB10"]
#[inline(always)]
pub fn lcksb10(&mut self) -> LCKSB10_W {
LCKSB10_W { w: self }
}
#[doc = "Bit 11 - LCKSB11"]
#[inline(always)]
pub fn lcksb11(&mut self) -> LCKSB11_W {
LCKSB11_W { w: self }
}
#[doc = "Bit 12 - LCKSB12"]
#[inline(always)]
pub fn lcksb12(&mut self) -> LCKSB12_W {
LCKSB12_W { w: self }
}
#[doc = "Bit 13 - LCKSB13"]
#[inline(always)]
pub fn lcksb13(&mut self) -> LCKSB13_W {
LCKSB13_W { w: self }
}
#[doc = "Bit 14 - LCKSB14"]
#[inline(always)]
pub fn lcksb14(&mut self) -> LCKSB14_W {
LCKSB14_W { w: self }
}
#[doc = "Bit 15 - LCKSB15"]
#[inline(always)]
pub fn lcksb15(&mut self) -> LCKSB15_W {
LCKSB15_W { w: self }
}
#[doc = "Bit 16 - LCKSB16"]
#[inline(always)]
pub fn lcksb16(&mut self) -> LCKSB16_W {
LCKSB16_W { w: self }
}
#[doc = "Bit 17 - LCKSB17"]
#[inline(always)]
pub fn lcksb17(&mut self) -> LCKSB17_W {
LCKSB17_W { w: self }
}
#[doc = "Bit 18 - LCKSB18"]
#[inline(always)]
pub fn lcksb18(&mut self) -> LCKSB18_W {
LCKSB18_W { w: self }
}
#[doc = "Bit 19 - LCKSB19"]
#[inline(always)]
pub fn lcksb19(&mut self) -> LCKSB19_W {
LCKSB19_W { w: self }
}
#[doc = "Bit 20 - LCKSB20"]
#[inline(always)]
pub fn lcksb20(&mut self) -> LCKSB20_W {
LCKSB20_W { w: self }
}
#[doc = "Bit 21 - LCKSB21"]
#[inline(always)]
pub fn lcksb21(&mut self) -> LCKSB21_W {
LCKSB21_W { w: self }
}
#[doc = "Bit 22 - LCKSB22"]
#[inline(always)]
pub fn lcksb22(&mut self) -> LCKSB22_W {
LCKSB22_W { w: self }
}
#[doc = "Bit 23 - LCKSB23"]
#[inline(always)]
pub fn lcksb23(&mut self) -> LCKSB23_W {
LCKSB23_W { w: self }
}
#[doc = "Bit 24 - LCKSB24"]
#[inline(always)]
pub fn lcksb24(&mut self) -> LCKSB24_W {
LCKSB24_W { w: self }
}
#[doc = "Bit 25 - LCKSB25"]
#[inline(always)]
pub fn lcksb25(&mut self) -> LCKSB25_W {
LCKSB25_W { w: self }
}
#[doc = "Bit 26 - LCKSB26"]
#[inline(always)]
pub fn lcksb26(&mut self) -> LCKSB26_W {
LCKSB26_W { w: self }
}
#[doc = "Bit 27 - LCKSB27"]
#[inline(always)]
pub fn lcksb27(&mut self) -> LCKSB27_W {
LCKSB27_W { w: self }
}
#[doc = "Bit 28 - LCKSB28"]
#[inline(always)]
pub fn lcksb28(&mut self) -> LCKSB28_W {
LCKSB28_W { w: self }
}
#[doc = "Bit 29 - LCKSB29"]
#[inline(always)]
pub fn lcksb29(&mut self) -> LCKSB29_W {
LCKSB29_W { w: self }
}
#[doc = "Bit 30 - LCKSB30"]
#[inline(always)]
pub fn lcksb30(&mut self) -> LCKSB30_W {
LCKSB30_W { w: self }
}
#[doc = "Bit 31 - LCKSB31"]
#[inline(always)]
pub fn lcksb31(&mut self) -> LCKSB31_W {
LCKSB31_W { w: self }
}
}
|
extern crate jlib;
use jlib::api::ledger_closed::api::request;
use jlib::api::ledger_closed::data::{LedgerClosedResponse, LedgerClosedSideKick};
use jlib::api::config::Config;
pub static TEST_SERVER: &'static str = "ws://101.200.176.249:5040";
fn main() {
let config = Config::new(TEST_SERVER, true);
request(config, |x| match x {
Ok(response) => {
let res: LedgerClosedResponse = response;
println!("----------------------------------------------------------------------------------");
println!("last closed ledger info : ");
println!("-- ledger hash : {}", &res.ledger_hash);
println!("-- ledger index: {}", &res.ledger_index);
println!("----------------------------------------------------------------------------------");
},
Err(e) => {
let err: LedgerClosedSideKick = e;
println!("{:?}", err);
}
});
}
|
use crate::mastermind::*;
use std::{
convert::TryInto,
io::{self, Write},
};
pub fn run(len: u32) -> Result<(), io::Error> {
let len_usize: usize = len.try_into().unwrap();
let mut game = MasterMind::new(len_usize);
game.print_welcome();
loop {
println!();
print!("Enter your guess: ");
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
match game.to_mastermind_colors(&input) {
Ok(combination) => {
let res = game.guess(&combination);
print!("Try N°{}: ", game.tries);
MasterMind::fancy_print_guess(&res.guess);
println!("{} good, {} wrong", res.good, res.wrong);
if res.valid {
break;
}
}
Err(e) => println!("{}", e),
}
}
println!();
println!("Congratulation! Your beat the MasterMind!");
Ok(())
}
|
use fraction::ToPrimitive;
use crate::{io::*, gp::*, enums::*, track::*};
/// Equalizer found in master effect and track effect.
///
/// Attribute :attr:`RSEEqualizer.knobs` is a list of values in range from -6.0 to 5.9. Master effect has 10 knobs, track effect has 3
/// knobs. Gain is a value in range from -6.0 to 5.9 which can be found in both master and track effects and is named as "PRE" in Guitar Pro 5.
#[derive(Debug,Clone)]
pub struct RseEqualizer {
pub knobs: Vec<f32>,
pub gain: f32,
}
impl Default for RseEqualizer {fn default() -> Self { RseEqualizer { knobs: Vec::with_capacity(10), gain:0.0 }}}
/// Master effect as seen in "Score information"
#[derive(Debug,Clone)]
pub struct RseMasterEffect {
pub volume: f32,
pub reverb: f32,
pub equalizer: RseEqualizer,
}
impl Default for RseMasterEffect { fn default() -> Self { RseMasterEffect {volume:0.0, reverb:0.0, equalizer:RseEqualizer{knobs:vec![0.0;10], ..Default::default()} }}}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RseInstrument {
pub instrument: i16,
pub unknown: i16,
pub sound_bank: i16,
pub effect_number: i16,
pub effect_category: String,
pub effect: String,
}
impl Default for RseInstrument { fn default() -> Self { RseInstrument { instrument:-1, unknown:-1, sound_bank:-1, effect_number:-1, effect_category:String::new(), effect:String::new()}}}
#[derive(Debug,Clone)]
pub struct TrackRse {
pub instrument: RseInstrument,
pub equalizer: RseEqualizer,
pub humanize: u8,
pub auto_accentuation: Accentuation,
}
impl Default for TrackRse { fn default() -> Self { TrackRse {instrument:RseInstrument::default(), humanize:0, auto_accentuation: Accentuation::None, equalizer:RseEqualizer{knobs:vec![0.0;3], ..Default::default()} }}}
impl Song {
/// Read RSE master effect. Persistence of RSE master effect was introduced in Guitar Pro 5.1. It is read as:
/// - Master volume: `int`. Values are in range from 0 to 200.
/// - 10-band equalizer. See `read_equalizer()`.
pub(crate) fn read_rse_master_effect(&self, data: &[u8], seek: &mut usize) -> RseMasterEffect {
let mut me = RseMasterEffect::default();
if self.version.number > (5,0,0) {
me.volume = read_int(data, seek).to_f32().unwrap();
read_int(data, seek); //???
me.equalizer = self.read_rse_equalizer(data, seek, 11);
//println!("read_rse_master_effect(): {:?}", me);
}
me
}
/// Read equalizer values. Equalizers are used in RSE master effect and Track RSE. They consist of *n* `SignedBytes <signed-byte>` for each *n* bands and one `signed-byte` for gain (PRE) fader.
/// Volume values are stored as opposite to actual value. See `unpack_volume_value()`.
fn read_rse_equalizer(&self, data: &[u8], seek: &mut usize, knobs: u8) -> RseEqualizer {
let mut e = RseEqualizer::default();
for _ in 0..knobs {e.knobs.push(self.unpack_volume_value(read_signed_byte(data, seek)));} //knobs = list(map(self.unpackVolumeValue, self.readSignedByte(count=knobsNumber)))
e //return gp.RSEEqualizer(knobs=knobs[:-1], gain=knobs[-1])
}
/// Unpack equalizer volume value. Equalizer volumes are float but stored as `SignedBytes <signed-byte>`.
fn unpack_volume_value(&self, value: i8) -> f32 { -value.to_f32().unwrap() / 10.0 }
/// Read track RSE. In GuitarPro 5.1 track RSE is read as follows:
/// - Humanize: :`byte`.
/// - Unknown space: 6 `Ints <int>`.
/// - RSE instrument. See `readRSEInstrument`.
/// - 3-band track equalizer. See `read_equalizer()`.
/// - RSE instrument effect. See `read_rse_instrument_effect()`.
pub(crate) fn read_track_rse(&mut self, data: &[u8], seek: &mut usize, track: &mut Track) {
track.rse.humanize = read_byte(data, seek);
//println!("read_track_rse(), humanize: {} \t\t seek: {}", track.rse.humanize, *seek);
*seek += 12; //read_int(data, seek); read_int(data, seek); read_int(data, seek); //??? 4 bytes*3 //*seek += 12;
*seek += 12; //???
track.rse.instrument = self.read_rse_instrument(data, seek);
if self.version.number > (5,0,0) {
track.rse.equalizer = self.read_rse_equalizer(data, seek, 4);
self.read_rse_instrument_effect(data, seek, &mut track.rse.instrument);
}
}
/// Read RSE instrument.
/// - MIDI instrument number: `int`.
/// - Unknown `int`.
/// - Sound bank: `int`.
/// - Effect number: `int`. Vestige of Guitar Pro 5.0 format.
pub(crate) fn read_rse_instrument(&mut self, data: &[u8], seek: &mut usize) -> RseInstrument {
let mut instrument = RseInstrument{instrument: read_int(data, seek).to_i16().unwrap(), ..Default::default()};
instrument.unknown = read_int(data, seek).to_i16().unwrap(); //??? mostly 1
instrument.sound_bank = read_int(data, seek).to_i16().unwrap();
//println!("read_rse_instrument(), instrument: {} {} {} \t\t seek: {}", instrument.instrument, instrument.unknown, instrument.sound_bank, *seek);
if self.version.number == (5,0,0) {
instrument.effect_number = read_short(data, seek);
*seek += 1;
} else {instrument.effect_number = read_int(data, seek).to_i16().unwrap();}
//println!("read_rse_instrument(), instrument.effect_number: {} \t\t seek: {}", instrument.effect_number, *seek);
instrument
}
/// Read RSE instrument effect name. This feature was introduced in Guitar Pro 5.1.
/// - Effect name: `int-byte-size-string`.
/// - Effect category: `int-byte-size-string`.
pub(crate) fn read_rse_instrument_effect(&mut self, data: &[u8], seek: &mut usize, instrument: &mut RseInstrument) {
if self.version.number > (5,0,0) {
instrument.effect = read_int_byte_size_string(data, seek);
instrument.effect_category = read_int_byte_size_string(data, seek);
}
}
pub(crate) fn write_rse_master_effect(&self, data: &mut Vec<u8>) {
write_i32(data, if self.master_effect.volume == 0.0 {100} else {self.master_effect.volume.ceil().to_i32().unwrap()});
write_i32(data, 0); //reverb?
self.write_equalizer(data, &self.master_effect.equalizer);
}
fn write_equalizer(&self, data: &mut Vec<u8>, equalizer: &RseEqualizer) {
for i in 0..equalizer.knobs.len() { write_signed_byte(data, self.pack_volume_value(equalizer.knobs[i])); }
write_signed_byte(data, self.pack_volume_value(equalizer.gain));
}
fn pack_volume_value(&self, value: f32) -> i8 {
(-value * 10f32).round().to_i8().unwrap() //int(-round(value, 1) * 10)
}
pub(crate) fn write_master_reverb(&self, data: &mut Vec<u8>) {
write_i32(data, self.master_effect.reverb.to_i32().unwrap());
}
pub(crate) fn write_track_rse(&self, data: &mut Vec<u8>, rse: &TrackRse, version: &(u8,u8,u8)) {
write_byte(data, rse.humanize);
write_i32(data, 0); write_i32(data, 0); write_i32(data, 100);
write_placeholder_default(data, 12);
self.write_rse_instrument(data, &rse.instrument, version);
if version > &(5,0,0) {
self.write_equalizer(data, &rse.equalizer);
self.write_rse_instrument_effect(data, &rse.instrument);
}
}
pub(crate) fn write_rse_instrument(&self, data: &mut Vec<u8>, instrument: &RseInstrument, version: &(u8,u8,u8)) {
write_i32(data, instrument.instrument.to_i32().unwrap());
write_i32(data, instrument.unknown.to_i32().unwrap());
write_i32(data, instrument.sound_bank.to_i32().unwrap());
if version == &(5,0,0) {
write_i16(data, instrument.effect_number);
write_placeholder_default(data, 1);
} else {write_i32(data, instrument.effect_number.to_i32().unwrap());}
}
pub(crate) fn write_rse_instrument_effect(&self, data: &mut Vec<u8>, instrument: &RseInstrument) { //version>5.0.0
write_int_byte_size_string(data, &instrument.effect);
write_int_byte_size_string(data, &instrument.effect_category);
}
}
|
use std::convert::From;
use clap::ArgMatches;
impl Default for Diff2HtmlConfig {
fn default() -> Diff2HtmlConfig {
Diff2HtmlConfig {
input: "command".to_owned(),
output: "stdout".to_owned(),
diff: "smartword".to_owned(),
style: "line".to_owned(),
synchronized_scroll: "enabled".to_owned(),
summary: "closed".to_owned(),
matching: "none".to_owned(),
match_words_threshold: 0.25f64,
matching_max_comparisons: 2500,
file: None,
format: "html".to_owned(),
is_combined: false,
max_line_length_highlight: 10000,
word_by_word: true,
char_by_char: false,
trail: None,
}
}
}
#[derive(Clone)]
pub struct Diff2HtmlConfig {
pub input: String,
pub output: String,
pub diff: String,
pub style: String,
pub synchronized_scroll: String,
pub summary: String,
pub matching: String,
pub match_words_threshold: f64,
pub matching_max_comparisons: usize,
pub file: Option<String>,
pub format: String,
pub is_combined: bool,
pub max_line_length_highlight: usize,
pub word_by_word: bool,
pub char_by_char: bool,
pub trail: Option<Vec<String>>,
}
impl<'a> From<ArgMatches<'a>> for Diff2HtmlConfig {
fn from(matches: ArgMatches<'a>) -> Diff2HtmlConfig {
let mut config = Diff2HtmlConfig::default();
// input
if let Some(input) = matches.value_of("input") {
config.input = input.to_owned();
}
// file
if let Some(file) = matches.value_of("file") {
config.file = Some(file.to_owned());
}
// format
if let Some(format) = matches.value_of("format") {
config.format = format.to_owned();
}
// output
if let Some(output) = matches.value_of("output") {
config.output = output.to_owned();
}
// diff
if let Some(diff) = matches.value_of("diff") {
config.diff = diff.to_owned();
}
// style
if let Some(style) = matches.value_of("style") {
config.style = style.to_owned();
}
// synchronized_scroll
if let Some(synchronized_scroll) = matches.value_of("synchronized_scroll") {
config.synchronized_scroll = synchronized_scroll.to_owned();
}
// summary
if let Some(summary) = matches.value_of("summary") {
config.summary = summary.to_owned();
}
// matching
if let Some(matching) = matches.value_of("matching") {
config.matching = matching.to_owned();
}
// match_words_threshold
if let Some(match_words_threshold) = matches.value_of("match_words_threshold") {
config.match_words_threshold = match_words_threshold
.parse()
.expect("Match words threshold is not in float format.");
}
// matching_max_comparisons
if let Some(matching_max_comparisons) = matches.value_of("matching_max_comparisons") {
config.matching_max_comparisons = matching_max_comparisons
.parse()
.expect("Match words threshold is not in unsigned integer format.");
}
config.trail = matches
.values_of("trail")
.map(|v| v.map(|v| v.to_owned()).collect());
config
}
}
|
use {
crate::{
app::AppContext,
},
std::path::Path,
syntect::{
easy::HighlightLines,
parsing::SyntaxSet,
highlighting::ThemeSet,
},
};
/// wrap heavy to initialize syntect things
pub struct Syntaxer {
pub syntax_set: SyntaxSet,
pub theme_set: ThemeSet,
}
impl Default for Syntaxer {
fn default() -> Self {
Self {
syntax_set: SyntaxSet::load_defaults_nonewlines(),
theme_set: ThemeSet::load_defaults(),
}
}
}
impl Syntaxer {
pub fn highlighter_for<'s, 'p>(
&'s self,
path: &'p Path,
con: &AppContext,
) -> Option<HighlightLines<'s>> {
path.extension()
.and_then(|e| e.to_str())
.and_then(|ext| self.syntax_set.find_syntax_by_extension(ext))
.map(|syntax| {
// some OK themes:
// "base16-ocean.dark"
// "Solarized (dark)"
// "base16-eighties.dark"
// "base16-mocha.dark"
let theme = con.syntax_theme.as_ref()
.and_then(|key| self.theme_set.themes.get(key))
.or_else(|| self.theme_set.themes.get("base16-mocha.dark"))
.unwrap_or_else(|| self.theme_set.themes.iter().next().unwrap().1);
HighlightLines::new(syntax, theme)
})
}
}
|
//! This module contains structs and functions that handle event input.
//!
//! There are three basic structs defined by this module
//! they are `KeyboardInfo`, `MouseInfo`, and `TextInfo`.
//! `KeyboardInfo` holds current keyboard events.
//! `MouseInfo` holds current mouse events.
//! `TextInfo` holds the most recent character, as defined by the operating system.
//!
#![allow(unused)]
#[cfg(target_os = "windows")]
use winapi::um::winuser::*;//{MSG, VK_*};
#[cfg(target_os = "linux")]
use crate::x11::xlib::KeySym;
#[cfg(target_os = "linux")]
use crate::x11::keysym::*;
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum ButtonStatus{
Up,
Down
}
impl Default for ButtonStatus{
fn default()->ButtonStatus{
ButtonStatus::Up
}
}
/// MouseInfo is designed to interface with a standard two button plus middle wheel mouse.
///
/// MouseInfo is to be filled out by the operating system specific modules.
/// A basic left click example is given below.
/// ## Example
/// ```
/// ...
/// let mut mouseinfo = MouseInfo::new();
/// {//Get events
/// ...
/// }
///
/// let left_button_clicked = mouseinfo.lclicked();
/// if left_button_clicked {
/// //Do things when left button is clicked.
/// }
/// ```
#[derive(Debug)]
pub struct MouseInfo{
pub x: i32,
pub y: i32,
pub delta_x: i32,
pub delta_y: i32,
pub lbutton: ButtonStatus,
pub old_lbutton: ButtonStatus,
pub double_lbutton: bool,
pub rbutton: ButtonStatus,
pub old_rbutton: ButtonStatus,
pub wheel: isize,
pub wheel_delta: i32,
}
impl MouseInfo{
pub fn new()->MouseInfo{
MouseInfo{
x: 0,
y: 0,
delta_x: 0,
delta_y: 0,
lbutton: ButtonStatus::Up,
old_lbutton: ButtonStatus::Up,
double_lbutton: false,
rbutton: ButtonStatus::Up,
old_rbutton: ButtonStatus::Up,
wheel: 0,
wheel_delta: 0,
}
}
pub fn lclicked(&self)->bool{
return self.lbutton == ButtonStatus::Up && self.old_lbutton == ButtonStatus::Down ;
}
pub fn rclicked(&self)->bool{
return self.rbutton == ButtonStatus::Up && self.old_rbutton == ButtonStatus::Down ;
}
}
#[derive(PartialEq, Debug)]
pub enum KeyboardEnum{
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
N1, N2, N3, N4, N5, N6, N7, N8, N9, N0,
Pad1, Pad2, Pad3, Pad4, Pad5, Pad6, Pad7, Pad8, Pad9, Pad0,
F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
Lctrl, Rctrl, Ctrl,
Lshift, Rshift, Shift,
_Fn,
Cmd,
Tab,
Space,
Rightarrow,
Leftarrow,
Uparrow,
Downarrow,
Enter,
Delete,
Backspace,
Default
}
/// TextInfo is contains utf-8 compatible character and associated time steps.
///
/// TextInfo is to be filled by operating system modules.
pub struct TextInfo{
pub character: Vec<char>,
pub timing: Vec<i32>
}
/// KeyboardInfo is contains keyboard button status.
///
/// KeyboardInfo is to be filled by operating system modules.
pub struct KeyboardInfo{
pub key: Vec<KeyboardEnum>,
pub status: Vec<ButtonStatus>,
}
macro_rules! update_down{
($bool:tt, $m:tt, $x:expr, $y:tt, $keyboardinfo:tt) => {
if $m == $x {
$keyboardinfo.key.push($y);
if $bool {
$keyboardinfo.status.push(ButtonStatus::Down);
} else {
$keyboardinfo.status.push(ButtonStatus::Up);
}
}
}
}
pub struct KeyMessageMacOS{
pub keycode: usize,
pub keydown: usize, //1 is down, 2 is up, zero is bull
}
impl KeyboardInfo{
pub fn is_key_released(&self, key: KeyboardEnum)->bool{
for (i, it) in self.key.iter().enumerate(){
if *it == key
&& self.status[i] == ButtonStatus::Up{
return true;
}
}
return false;
}
pub fn is_key_pressed(&self, key: KeyboardEnum)->bool{
for (i, it) in self.key.iter().enumerate(){
if *it == key
&& self.status[i] == ButtonStatus::Down{
return true;
}
}
return false;
}
#[cfg(target_os = "windows")]
pub fn update_keyboardinfo_windows(&mut self, message: &MSG){
//NOTE
//Becareful with KeyboardEnum! There are many single character values in the enum
use KeyboardEnum::*;
use ButtonStatus::*;
if message.message == WM_KEYDOWN || message.message == WM_KEYUP{
let is_down = message.message == WM_KEYDOWN;
let message_wparam = message.wParam;
update_down!(is_down, message_wparam, VK_LEFT as usize , Leftarrow, self);
update_down!(is_down, message_wparam, VK_RIGHT as usize , Rightarrow, self);
update_down!(is_down, message_wparam, VK_UP as usize , Uparrow, self);
update_down!(is_down, message_wparam, VK_DOWN as usize , Downarrow, self);
update_down!(is_down, message_wparam, VK_SPACE as usize , Space, self);
update_down!(is_down, message_wparam, VK_RETURN as usize , Enter, self);
update_down!(is_down, message_wparam, VK_DELETE as usize , Delete, self);
update_down!(is_down, message_wparam, VK_LSHIFT as usize , Lshift, self); //NOTE doesn't work(not with my keyboard atleast) 10/23/2020
update_down!(is_down, message_wparam, VK_RSHIFT as usize , Rshift, self); //NOTE doesn't work(not with my keyboard atleast) 10/23/2020
update_down!(is_down, message_wparam, VK_SHIFT as usize , Shift, self);
update_down!(is_down, message_wparam, VK_LCONTROL as usize , Lctrl, self); //NOTE doesn't work(not with my keyboard atleast) 10/23/2020
update_down!(is_down, message_wparam, VK_RCONTROL as usize , Rctrl, self); //NOTE doesn't work(not with my keyboard atleast) 10/23/2020
update_down!(is_down, message_wparam, VK_CONTROL as usize , Ctrl, self);
update_down!(is_down, message_wparam, VK_TAB as usize , Tab, self);
update_down!(is_down, message_wparam, VK_F1 as usize , F1, self);
update_down!(is_down, message_wparam, VK_F2 as usize , F2, self);
update_down!(is_down, message_wparam, VK_F3 as usize , F3, self);
update_down!(is_down, message_wparam, VK_F4 as usize , F4, self);
update_down!(is_down, message_wparam, VK_F5 as usize , F5, self);
update_down!(is_down, message_wparam, VK_F6 as usize , F6, self);
update_down!(is_down, message_wparam, VK_F7 as usize , F7, self);
update_down!(is_down, message_wparam, VK_F8 as usize , F8, self);
update_down!(is_down, message_wparam, VK_F9 as usize , F9, self);
update_down!(is_down, message_wparam, VK_F10 as usize , F10, self);//NOTE doesn't seem to work
update_down!(is_down, message_wparam, VK_F11 as usize , F11, self);//NOTE doesn't seem to work
update_down!(is_down, message_wparam, VK_F12 as usize , F12, self);//NOTE doesn't seem to work
update_down!(is_down, message_wparam, VK_NUMPAD0 as usize , Pad0, self);
update_down!(is_down, message_wparam, VK_NUMPAD1 as usize , Pad1, self);
update_down!(is_down, message_wparam, VK_NUMPAD2 as usize , Pad2, self);
update_down!(is_down, message_wparam, VK_NUMPAD3 as usize , Pad3, self);
update_down!(is_down, message_wparam, VK_NUMPAD4 as usize , Pad4, self);
update_down!(is_down, message_wparam, VK_NUMPAD5 as usize , Pad5, self);
update_down!(is_down, message_wparam, VK_NUMPAD6 as usize , Pad6, self);
update_down!(is_down, message_wparam, VK_NUMPAD7 as usize , Pad7, self);
update_down!(is_down, message_wparam, VK_NUMPAD8 as usize , Pad8, self);
update_down!(is_down, message_wparam, VK_NUMPAD9 as usize , Pad9, self);
update_down!(is_down, message_wparam, 0x30usize , N0, self);
update_down!(is_down, message_wparam, 0x31usize , N1, self);
update_down!(is_down, message_wparam, 0x32usize , N2, self);
update_down!(is_down, message_wparam, 0x33usize , N3, self);
update_down!(is_down, message_wparam, 0x34usize , N4, self);
update_down!(is_down, message_wparam, 0x35usize , N5, self);
update_down!(is_down, message_wparam, 0x36usize , N6, self);
update_down!(is_down, message_wparam, 0x37usize , N7, self);
update_down!(is_down, message_wparam, 0x38usize , N8, self);
update_down!(is_down, message_wparam, 0x39usize , N9, self);
update_down!(is_down, message_wparam, 0x41usize , A, self);
update_down!(is_down, message_wparam, 0x42usize , B, self);
update_down!(is_down, message_wparam, 0x43usize , C, self);
update_down!(is_down, message_wparam, 0x44usize , D, self);
update_down!(is_down, message_wparam, 0x45usize , E, self);
update_down!(is_down, message_wparam, 0x46usize , F, self);
update_down!(is_down, message_wparam, 0x47usize , G, self);
update_down!(is_down, message_wparam, 0x48usize , H, self);
update_down!(is_down, message_wparam, 0x49usize , I, self);
update_down!(is_down, message_wparam, 0x4Ausize , J, self);
update_down!(is_down, message_wparam, 0x4Busize , K, self);
update_down!(is_down, message_wparam, 0x4Cusize , L, self);
update_down!(is_down, message_wparam, 0x4Dusize , M, self);
update_down!(is_down, message_wparam, 0x4Eusize , N, self);
update_down!(is_down, message_wparam, 0x4Fusize , O, self);
update_down!(is_down, message_wparam, 0x50usize , P, self);
update_down!(is_down, message_wparam, 0x51usize , Q, self);
update_down!(is_down, message_wparam, 0x52usize , R, self);
update_down!(is_down, message_wparam, 0x53usize , S, self);
update_down!(is_down, message_wparam, 0x54usize , T, self);
update_down!(is_down, message_wparam, 0x55usize , U, self);
update_down!(is_down, message_wparam, 0x56usize , V, self);
update_down!(is_down, message_wparam, 0x57usize , W, self);
update_down!(is_down, message_wparam, 0x58usize , X, self);
update_down!(is_down, message_wparam, 0x59usize , Y, self);
update_down!(is_down, message_wparam, 0x5Ausize , Z, self);
}
}
#[cfg(target_os = "macos")]
pub fn update_keyboardinfo_macos(&mut self, message: KeyMessageMacOS){ //TODO should have a special struct for this so that it's easier to fix
//NOTE
//Becareful with KeyboardEnum! There are many single character values in the enum
use KeyboardEnum::*;
use ButtonStatus::*;
if message.keydown == 1 || message.keydown == 2{
//if message.wParam == winapi::um::winuser::VK_LEFT as usize{
let is_down = message.keydown == 1;
let message_wparam = message.keycode;
update_down!(is_down, message_wparam, 0x7B , Leftarrow, self);
update_down!(is_down, message_wparam, 0x7C , Rightarrow, self);
update_down!(is_down, message_wparam, 0x7E , Uparrow, self);
update_down!(is_down, message_wparam, 0x7D , Downarrow, self);
update_down!(is_down, message_wparam, 0x31 , Space, self);
update_down!(is_down, message_wparam, 0x24 , Enter, self);
update_down!(is_down, message_wparam, 117 , Delete, self);
update_down!(is_down, message_wparam, 51 , Backspace, self);
update_down!(is_down, message_wparam, 0x38 , Shift, self);
//update_down!(is_down, message_wparam, VK_LSHIFT as usize , Lshift, self);
//update_down!(is_down, message_wparam, VK_RSHIFT as usize , Rshift, self);
update_down!(is_down, message_wparam, 0x3B , Ctrl, self);
//update_down!(is_down, message_wparam, VK_LCONTROL as usize , Lctrl, self);
//update_down!(is_down, message_wparam, VK_RCONTROL as usize , Rctrl, self);
update_down!(is_down, message_wparam, 0x30 , Tab, self);
//update_down!(is_down, message_wparam, VK_F1 as usize , F1, self);
//update_down!(is_down, message_wparam, VK_F2 as usize , F2, self);
//update_down!(is_down, message_wparam, VK_F3 as usize , F3, self);
//update_down!(is_down, message_wparam, VK_F4 as usize , F4, self);
//update_down!(is_down, message_wparam, VK_F5 as usize , F5, self);
//update_down!(is_down, message_wparam, VK_F6 as usize , F6, self);
//update_down!(is_down, message_wparam, VK_F7 as usize , F7, self);
//update_down!(is_down, message_wparam, VK_F8 as usize , F8, self);
//update_down!(is_down, message_wparam, VK_F9 as usize , F9, self);
//update_down!(is_down, message_wparam, VK_F10 as usize , F10, self);
//update_down!(is_down, message_wparam, VK_F11 as usize , F11, self);
//update_down!(is_down, message_wparam, VK_F12 as usize , F12, self);
//update_down!(is_down, message_wparam, VK_NUMPAD0 as usize , Pad0, self);
//update_down!(is_down, message_wparam, VK_NUMPAD1 as usize , Pad1, self);
//update_down!(is_down, message_wparam, VK_NUMPAD2 as usize , Pad2, self);
//update_down!(is_down, message_wparam, VK_NUMPAD3 as usize , Pad3, self);
//update_down!(is_down, message_wparam, VK_NUMPAD4 as usize , Pad4, self);
//update_down!(is_down, message_wparam, VK_NUMPAD5 as usize , Pad5, self);
//update_down!(is_down, message_wparam, VK_NUMPAD6 as usize , Pad6, self);
//update_down!(is_down, message_wparam, VK_NUMPAD7 as usize , Pad7, self);
//update_down!(is_down, message_wparam, VK_NUMPAD8 as usize , Pad8, self);
//update_down!(is_down, message_wparam, VK_NUMPAD9 as usize , Pad9, self);
//update_down!(is_down, message_wparam, 0x30usize , N0, self);
//update_down!(is_down, message_wparam, 0x31usize , N1, self);
//update_down!(is_down, message_wparam, 0x32usize , N2, self);
//update_down!(is_down, message_wparam, 0x33usize , N3, self);
//update_down!(is_down, message_wparam, 0x34usize , N4, self);
//update_down!(is_down, message_wparam, 0x35usize , N5, self);
//update_down!(is_down, message_wparam, 0x36usize , N6, self);
//update_down!(is_down, message_wparam, 0x37usize , N7, self);
//update_down!(is_down, message_wparam, 0x38usize , N8, self);
//update_down!(is_down, message_wparam, 0x39usize , N9, self);
update_down!(is_down, message_wparam, 0x00usize , A, self);
update_down!(is_down, message_wparam, 0x0Busize , B, self);
update_down!(is_down, message_wparam, 0x08usize , C, self);
update_down!(is_down, message_wparam, 0x02usize , D, self);
update_down!(is_down, message_wparam, 0x0Eusize , E, self);
update_down!(is_down, message_wparam, 0x03usize , F, self);
update_down!(is_down, message_wparam, 0x05usize , G, self);
update_down!(is_down, message_wparam, 0x04usize , H, self);
update_down!(is_down, message_wparam, 0x22usize , I, self);
update_down!(is_down, message_wparam, 0x26usize , J, self);
update_down!(is_down, message_wparam, 0x28usize , K, self);
update_down!(is_down, message_wparam, 0x25usize , L, self);
update_down!(is_down, message_wparam, 0x2Eusize , M, self);
update_down!(is_down, message_wparam, 0x2Dusize , N, self);
update_down!(is_down, message_wparam, 0x1Fusize , O, self);
update_down!(is_down, message_wparam, 0x23usize , P, self);
update_down!(is_down, message_wparam, 0x0Cusize , Q, self);
update_down!(is_down, message_wparam, 0x0Fusize , R, self);
update_down!(is_down, message_wparam, 0x01usize , S, self);
update_down!(is_down, message_wparam, 0x11usize , T, self);
update_down!(is_down, message_wparam, 0x20usize , U, self);
update_down!(is_down, message_wparam, 0x09usize , V, self);
update_down!(is_down, message_wparam, 0x0Dusize , W, self);
update_down!(is_down, message_wparam, 0x07usize , X, self);
update_down!(is_down, message_wparam, 0x10usize , Y, self);
update_down!(is_down, message_wparam, 0x06usize , Z, self);
}
}
#[cfg(target_os = "linux")]
pub fn update_keyboardinfo_linux(&mut self, message: KeySym, keystatus: bool){ //TODO should have a special struct for this so that it's easier to fix
//NOTE
//Becareful with KeyboardEnum! There are many single character values in the enum
use KeyboardEnum::*;
use ButtonStatus::*;
let is_down = keystatus;
let message_wparam = message;
update_down!(is_down, message_wparam, XK_Left as u64, Leftarrow, self);
update_down!(is_down, message_wparam, XK_Right as u64 , Rightarrow, self);
update_down!(is_down, message_wparam, XK_Up as u64 , Uparrow, self);
update_down!(is_down, message_wparam, XK_Down as u64 , Downarrow, self);
update_down!(is_down, message_wparam, XK_space as u64 , Space, self);
update_down!(is_down, message_wparam, XK_Return as u64 , Enter, self);
update_down!(is_down, message_wparam, XK_Delete as u64 , Delete, self);
update_down!(is_down, message_wparam, XK_Shift_L as u64 , Lshift, self);
update_down!(is_down, message_wparam, XK_Shift_R as u64 , Rshift, self);
update_down!(is_down, message_wparam, XK_Shift_L as u64 , Shift, self);
update_down!(is_down, message_wparam, XK_Shift_R as u64 , Shift, self);
update_down!(is_down, message_wparam, XK_Control_L as u64 , Lctrl, self);
update_down!(is_down, message_wparam, XK_Control_R as u64 , Rctrl, self);
update_down!(is_down, message_wparam, XK_Control_L as u64 , Ctrl, self);
update_down!(is_down, message_wparam, XK_Control_R as u64 , Ctrl, self);
update_down!(is_down, message_wparam, XK_Tab as u64 , Tab, self);
update_down!(is_down, message_wparam, XK_F1 as u64 , F1, self);
update_down!(is_down, message_wparam, XK_F2 as u64 , F2, self);
update_down!(is_down, message_wparam, XK_F3 as u64 , F3, self);
update_down!(is_down, message_wparam, XK_F4 as u64 , F4, self);
update_down!(is_down, message_wparam, XK_F5 as u64 , F5, self);
update_down!(is_down, message_wparam, XK_F6 as u64 , F6, self);
update_down!(is_down, message_wparam, XK_F7 as u64 , F7, self);
//update_down!(is_down, message_wparam, VK_F8 as usize , F8, self);
//update_down!(is_down, message_wparam, VK_F9 as usize , F9, self);
//update_down!(is_down, message_wparam, VK_F10 as usize , F10, self);
//update_down!(is_down, message_wparam, VK_F11 as usize , F11, self);
//update_down!(is_down, message_wparam, VK_F12 as usize , F12, self);
//update_down!(is_down, message_wparam, VK_NUMPAD0 as usize , Pad0, self);
//update_down!(is_down, message_wparam, VK_NUMPAD1 as usize , Pad1, self);
//update_down!(is_down, message_wparam, VK_NUMPAD2 as usize , Pad2, self);
//update_down!(is_down, message_wparam, VK_NUMPAD3 as usize , Pad3, self);
//update_down!(is_down, message_wparam, VK_NUMPAD4 as usize , Pad4, self);
//update_down!(is_down, message_wparam, VK_NUMPAD5 as usize , Pad5, self);
//update_down!(is_down, message_wparam, VK_NUMPAD6 as usize , Pad6, self);
//update_down!(is_down, message_wparam, VK_NUMPAD7 as usize , Pad7, self);
//update_down!(is_down, message_wparam, VK_NUMPAD8 as usize , Pad8, self);
//update_down!(is_down, message_wparam, VK_NUMPAD9 as usize , Pad9, self);
//update_down!(is_down, message_wparam, 0x30usize , N0, self);
//update_down!(is_down, message_wparam, 0x31usize , N1, self);
//update_down!(is_down, message_wparam, 0x32usize , N2, self);
//update_down!(is_down, message_wparam, 0x33usize , N3, self);
//update_down!(is_down, message_wparam, 0x34usize , N4, self);
//update_down!(is_down, message_wparam, 0x35usize , N5, self);
//update_down!(is_down, message_wparam, 0x36usize , N6, self);
//update_down!(is_down, message_wparam, 0x37usize , N7, self);
//update_down!(is_down, message_wparam, 0x38usize , N8, self);
//update_down!(is_down, message_wparam, 0x39usize , N9, self);
update_down!(is_down, message_wparam, XK_a as u64 , A, self);
update_down!(is_down, message_wparam, XK_b as u64 , B, self);
update_down!(is_down, message_wparam, XK_c as u64 , C, self);
update_down!(is_down, message_wparam, XK_d as u64 , D, self);
update_down!(is_down, message_wparam, XK_e as u64 , E, self);
update_down!(is_down, message_wparam, XK_f as u64 , F, self);
update_down!(is_down, message_wparam, XK_g as u64 , G, self);
update_down!(is_down, message_wparam, XK_h as u64 , H, self);
update_down!(is_down, message_wparam, XK_i as u64 , I, self);
update_down!(is_down, message_wparam, XK_j as u64 , J, self);
update_down!(is_down, message_wparam, XK_k as u64 , K, self);
update_down!(is_down, message_wparam, XK_l as u64 , L, self);
update_down!(is_down, message_wparam, XK_m as u64 , M, self);
update_down!(is_down, message_wparam, XK_n as u64 , N, self);
update_down!(is_down, message_wparam, XK_o as u64 , O, self);
update_down!(is_down, message_wparam, XK_p as u64 , P, self);
update_down!(is_down, message_wparam, XK_q as u64 , Q, self);
update_down!(is_down, message_wparam, XK_r as u64 , R, self);
update_down!(is_down, message_wparam, XK_s as u64 , S, self);
update_down!(is_down, message_wparam, XK_t as u64 , T, self);
update_down!(is_down, message_wparam, XK_u as u64 , U, self);
update_down!(is_down, message_wparam, XK_v as u64 , V, self);
update_down!(is_down, message_wparam, XK_w as u64 , W, self);
update_down!(is_down, message_wparam, XK_x as u64 , X, self);
update_down!(is_down, message_wparam, XK_y as u64 , Y, self);
update_down!(is_down, message_wparam, XK_z as u64 , Z, self);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.