text stringlengths 8 4.13M |
|---|
pub mod any_series;
pub mod context;
pub mod data_src;
pub mod error_format;
pub mod exp;
pub mod function;
pub mod instance_caller;
pub mod op;
pub mod output;
pub mod runtime_convert;
pub mod statement;
pub use any_series::*;
pub use context::*;
pub use data_src::*;
pub use error_format::*;
pub use output::*;
// use crate::ast::stat_expr_types::Block;
// use crate::types::PineRef;
// use context::{Context, ContextType, PineRuntimeError, Runner, VarOperate};
// use std::collections::HashMap;
// pub fn run<'a>(
// blk: &'a Block<'a>,
// vars: HashMap<&'a str, PineRef<'a>>,
// ) -> Result<(), PineRuntimeError> {
// let mut context = Context::new(None, ContextType::Normal);
// for (k, v) in vars.into_iter() {
// context.create_var(k, v);
// }
// blk.run(&mut context)?;
// Ok(())
// }
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::IRQ_FLAG {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `GFLAG0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GFLAG0R {
#[doc = "No pending interrupt. Writing a zero is equivalent to no operation."]
NO_PENDING_INTERRUPT,
#[doc = "Pending interrupt. The interrupt is pending because TIMER0 has reached the end of the time interval. If the INTEN bit in the CONTROL0 register is also set to 1, the interrupt for timer channel 0 and the global interrupt are raised. Writing a 1 to this bit clears the interrupt request."]
PENDING_INTERRUPT_T,
}
impl GFLAG0R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GFLAG0R::NO_PENDING_INTERRUPT => false,
GFLAG0R::PENDING_INTERRUPT_T => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GFLAG0R {
match value {
false => GFLAG0R::NO_PENDING_INTERRUPT,
true => GFLAG0R::PENDING_INTERRUPT_T,
}
}
#[doc = "Checks if the value of the field is `NO_PENDING_INTERRUPT`"]
#[inline]
pub fn is_no_pending_interrupt(&self) -> bool {
*self == GFLAG0R::NO_PENDING_INTERRUPT
}
#[doc = "Checks if the value of the field is `PENDING_INTERRUPT_T`"]
#[inline]
pub fn is_pending_interrupt_t(&self) -> bool {
*self == GFLAG0R::PENDING_INTERRUPT_T
}
}
#[doc = "Possible values of the field `GFLAG1`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GFLAG1R {
#[doc = "No pending interrupt. Writing a zero is equivalent to no operation."]
NO_PENDING_INTERRUPT,
#[doc = "Pending interrupt. The interrupt is pending because TIMER1 has reached the end of the time interval. If the INTEN bit in the CONTROL1 register is also set to 1, the interrupt for timer channel 1 and the global interrupt are raised. Writing a 1 to this bit clears the interrupt request."]
PENDING_INTERRUPT_T,
}
impl GFLAG1R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GFLAG1R::NO_PENDING_INTERRUPT => false,
GFLAG1R::PENDING_INTERRUPT_T => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GFLAG1R {
match value {
false => GFLAG1R::NO_PENDING_INTERRUPT,
true => GFLAG1R::PENDING_INTERRUPT_T,
}
}
#[doc = "Checks if the value of the field is `NO_PENDING_INTERRUPT`"]
#[inline]
pub fn is_no_pending_interrupt(&self) -> bool {
*self == GFLAG1R::NO_PENDING_INTERRUPT
}
#[doc = "Checks if the value of the field is `PENDING_INTERRUPT_T`"]
#[inline]
pub fn is_pending_interrupt_t(&self) -> bool {
*self == GFLAG1R::PENDING_INTERRUPT_T
}
}
#[doc = "Possible values of the field `GFLAG2`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GFLAG2R {
#[doc = "No pending interrupt. Writing a zero is equivalent to no operation."]
NO_PENDING_INTERRUPT,
#[doc = "Pending interrupt. The interrupt is pending because TIMER2 has reached the end of the time interval. If the INTEN bit in the CONTROL2 register is also set to 1, the interrupt for timer channel 2 and the global interrupt are raised. Writing a 1 to this bit clears the interrupt request."]
PENDING_INTERRUPT_T,
}
impl GFLAG2R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GFLAG2R::NO_PENDING_INTERRUPT => false,
GFLAG2R::PENDING_INTERRUPT_T => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GFLAG2R {
match value {
false => GFLAG2R::NO_PENDING_INTERRUPT,
true => GFLAG2R::PENDING_INTERRUPT_T,
}
}
#[doc = "Checks if the value of the field is `NO_PENDING_INTERRUPT`"]
#[inline]
pub fn is_no_pending_interrupt(&self) -> bool {
*self == GFLAG2R::NO_PENDING_INTERRUPT
}
#[doc = "Checks if the value of the field is `PENDING_INTERRUPT_T`"]
#[inline]
pub fn is_pending_interrupt_t(&self) -> bool {
*self == GFLAG2R::PENDING_INTERRUPT_T
}
}
#[doc = "Possible values of the field `GFLAG3`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GFLAG3R {
#[doc = "No pending interrupt. Writing a zero is equivalent to no operation."]
NO_PENDING_INTERRUPT,
#[doc = "Pending interrupt. The interrupt is pending because TIMER3 has reached the end of the time interval. If the INTEN bit in the CONTROL3 register is also set to 1, the interrupt for timer channel 3 and the global interrupt are raised. Writing a 1 to this bit clears the interrupt request."]
PENDING_INTERRUPT_T,
}
impl GFLAG3R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GFLAG3R::NO_PENDING_INTERRUPT => false,
GFLAG3R::PENDING_INTERRUPT_T => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GFLAG3R {
match value {
false => GFLAG3R::NO_PENDING_INTERRUPT,
true => GFLAG3R::PENDING_INTERRUPT_T,
}
}
#[doc = "Checks if the value of the field is `NO_PENDING_INTERRUPT`"]
#[inline]
pub fn is_no_pending_interrupt(&self) -> bool {
*self == GFLAG3R::NO_PENDING_INTERRUPT
}
#[doc = "Checks if the value of the field is `PENDING_INTERRUPT_T`"]
#[inline]
pub fn is_pending_interrupt_t(&self) -> bool {
*self == GFLAG3R::PENDING_INTERRUPT_T
}
}
#[doc = "Values that can be written to the field `GFLAG0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GFLAG0W {
#[doc = "No pending interrupt. Writing a zero is equivalent to no operation."]
NO_PENDING_INTERRUPT,
#[doc = "Pending interrupt. The interrupt is pending because TIMER0 has reached the end of the time interval. If the INTEN bit in the CONTROL0 register is also set to 1, the interrupt for timer channel 0 and the global interrupt are raised. Writing a 1 to this bit clears the interrupt request."]
PENDING_INTERRUPT_T,
}
impl GFLAG0W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GFLAG0W::NO_PENDING_INTERRUPT => false,
GFLAG0W::PENDING_INTERRUPT_T => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GFLAG0W<'a> {
w: &'a mut W,
}
impl<'a> _GFLAG0W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GFLAG0W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "No pending interrupt. Writing a zero is equivalent to no operation."]
#[inline]
pub fn no_pending_interrupt(self) -> &'a mut W {
self.variant(GFLAG0W::NO_PENDING_INTERRUPT)
}
#[doc = "Pending interrupt. The interrupt is pending because TIMER0 has reached the end of the time interval. If the INTEN bit in the CONTROL0 register is also set to 1, the interrupt for timer channel 0 and the global interrupt are raised. Writing a 1 to this bit clears the interrupt request."]
#[inline]
pub fn pending_interrupt_t(self) -> &'a mut W {
self.variant(GFLAG0W::PENDING_INTERRUPT_T)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GFLAG1`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GFLAG1W {
#[doc = "No pending interrupt. Writing a zero is equivalent to no operation."]
NO_PENDING_INTERRUPT,
#[doc = "Pending interrupt. The interrupt is pending because TIMER1 has reached the end of the time interval. If the INTEN bit in the CONTROL1 register is also set to 1, the interrupt for timer channel 1 and the global interrupt are raised. Writing a 1 to this bit clears the interrupt request."]
PENDING_INTERRUPT_T,
}
impl GFLAG1W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GFLAG1W::NO_PENDING_INTERRUPT => false,
GFLAG1W::PENDING_INTERRUPT_T => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GFLAG1W<'a> {
w: &'a mut W,
}
impl<'a> _GFLAG1W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GFLAG1W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "No pending interrupt. Writing a zero is equivalent to no operation."]
#[inline]
pub fn no_pending_interrupt(self) -> &'a mut W {
self.variant(GFLAG1W::NO_PENDING_INTERRUPT)
}
#[doc = "Pending interrupt. The interrupt is pending because TIMER1 has reached the end of the time interval. If the INTEN bit in the CONTROL1 register is also set to 1, the interrupt for timer channel 1 and the global interrupt are raised. Writing a 1 to this bit clears the interrupt request."]
#[inline]
pub fn pending_interrupt_t(self) -> &'a mut W {
self.variant(GFLAG1W::PENDING_INTERRUPT_T)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GFLAG2`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GFLAG2W {
#[doc = "No pending interrupt. Writing a zero is equivalent to no operation."]
NO_PENDING_INTERRUPT,
#[doc = "Pending interrupt. The interrupt is pending because TIMER2 has reached the end of the time interval. If the INTEN bit in the CONTROL2 register is also set to 1, the interrupt for timer channel 2 and the global interrupt are raised. Writing a 1 to this bit clears the interrupt request."]
PENDING_INTERRUPT_T,
}
impl GFLAG2W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GFLAG2W::NO_PENDING_INTERRUPT => false,
GFLAG2W::PENDING_INTERRUPT_T => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GFLAG2W<'a> {
w: &'a mut W,
}
impl<'a> _GFLAG2W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GFLAG2W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "No pending interrupt. Writing a zero is equivalent to no operation."]
#[inline]
pub fn no_pending_interrupt(self) -> &'a mut W {
self.variant(GFLAG2W::NO_PENDING_INTERRUPT)
}
#[doc = "Pending interrupt. The interrupt is pending because TIMER2 has reached the end of the time interval. If the INTEN bit in the CONTROL2 register is also set to 1, the interrupt for timer channel 2 and the global interrupt are raised. Writing a 1 to this bit clears the interrupt request."]
#[inline]
pub fn pending_interrupt_t(self) -> &'a mut W {
self.variant(GFLAG2W::PENDING_INTERRUPT_T)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GFLAG3`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GFLAG3W {
#[doc = "No pending interrupt. Writing a zero is equivalent to no operation."]
NO_PENDING_INTERRUPT,
#[doc = "Pending interrupt. The interrupt is pending because TIMER3 has reached the end of the time interval. If the INTEN bit in the CONTROL3 register is also set to 1, the interrupt for timer channel 3 and the global interrupt are raised. Writing a 1 to this bit clears the interrupt request."]
PENDING_INTERRUPT_T,
}
impl GFLAG3W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GFLAG3W::NO_PENDING_INTERRUPT => false,
GFLAG3W::PENDING_INTERRUPT_T => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GFLAG3W<'a> {
w: &'a mut W,
}
impl<'a> _GFLAG3W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GFLAG3W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "No pending interrupt. Writing a zero is equivalent to no operation."]
#[inline]
pub fn no_pending_interrupt(self) -> &'a mut W {
self.variant(GFLAG3W::NO_PENDING_INTERRUPT)
}
#[doc = "Pending interrupt. The interrupt is pending because TIMER3 has reached the end of the time interval. If the INTEN bit in the CONTROL3 register is also set to 1, the interrupt for timer channel 3 and the global interrupt are raised. Writing a 1 to this bit clears the interrupt request."]
#[inline]
pub fn pending_interrupt_t(self) -> &'a mut W {
self.variant(GFLAG3W::PENDING_INTERRUPT_T)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - Monitors the interrupt flag of TIMER0."]
#[inline]
pub fn gflag0(&self) -> GFLAG0R {
GFLAG0R::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 1 - Monitors the interrupt flag of TIMER1."]
#[inline]
pub fn gflag1(&self) -> GFLAG1R {
GFLAG1R::_from({
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 2 - Monitors the interrupt flag of TIMER2."]
#[inline]
pub fn gflag2(&self) -> GFLAG2R {
GFLAG2R::_from({
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 3 - Monitors the interrupt flag of TIMER3."]
#[inline]
pub fn gflag3(&self) -> GFLAG3R {
GFLAG3R::_from({
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Monitors the interrupt flag of TIMER0."]
#[inline]
pub fn gflag0(&mut self) -> _GFLAG0W {
_GFLAG0W { w: self }
}
#[doc = "Bit 1 - Monitors the interrupt flag of TIMER1."]
#[inline]
pub fn gflag1(&mut self) -> _GFLAG1W {
_GFLAG1W { w: self }
}
#[doc = "Bit 2 - Monitors the interrupt flag of TIMER2."]
#[inline]
pub fn gflag2(&mut self) -> _GFLAG2W {
_GFLAG2W { w: self }
}
#[doc = "Bit 3 - Monitors the interrupt flag of TIMER3."]
#[inline]
pub fn gflag3(&mut self) -> _GFLAG3W {
_GFLAG3W { w: self }
}
}
|
use serde::{Deserialize, Serialize};
#[repr(C)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CodeAnnotation {
pub name: String,
pub key_values: Vec<AnnotationKeyValue>
}
#[repr(C)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AnnotationKeyValue {
pub key: String,
pub values: Vec<AnnotationKeyValue>
}
|
pub mod dialog_ffi;
mod dialog_future;
use dialog_ffi::IDialog;
use dialog_future::{multiple_return_future, single_return_future};
use crate::backend::DialogFutureType;
use crate::FileDialog;
use crate::FileHandle;
use std::path::PathBuf;
use winapi::shared::winerror::HRESULT;
use super::utils::init_com;
//
// File Picker
//
use crate::backend::FilePickerDialogImpl;
impl FilePickerDialogImpl for FileDialog {
fn pick_file(self) -> Option<PathBuf> {
fn run(opt: FileDialog) -> Result<PathBuf, HRESULT> {
init_com(|| {
let dialog = IDialog::build_pick_file(&opt)?;
dialog.show()?;
dialog.get_result()
})?
}
run(self).ok()
}
fn pick_files(self) -> Option<Vec<PathBuf>> {
fn run(opt: FileDialog) -> Result<Vec<PathBuf>, HRESULT> {
init_com(|| {
let dialog = IDialog::build_pick_files(&opt)?;
dialog.show()?;
dialog.get_results()
})?
}
run(self).ok()
}
}
use crate::backend::AsyncFilePickerDialogImpl;
impl AsyncFilePickerDialogImpl for FileDialog {
fn pick_file_async(self) -> DialogFutureType<Option<FileHandle>> {
let ret = single_return_future(move || IDialog::build_pick_file(&self));
Box::pin(ret)
}
fn pick_files_async(self) -> DialogFutureType<Option<Vec<FileHandle>>> {
let ret = multiple_return_future(move || IDialog::build_pick_files(&self));
Box::pin(ret)
}
}
//
// Folder Picker
//
use crate::backend::FolderPickerDialogImpl;
impl FolderPickerDialogImpl for FileDialog {
fn pick_folder(self) -> Option<PathBuf> {
fn run(opt: FileDialog) -> Result<PathBuf, HRESULT> {
init_com(|| {
let dialog = IDialog::build_pick_folder(&opt)?;
dialog.show()?;
dialog.get_result()
})?
}
run(self).ok()
}
}
use crate::backend::AsyncFolderPickerDialogImpl;
impl AsyncFolderPickerDialogImpl for FileDialog {
fn pick_folder_async(self) -> DialogFutureType<Option<FileHandle>> {
let ret = single_return_future(move || IDialog::build_pick_folder(&self));
Box::pin(ret)
}
}
//
// File Save
//
use crate::backend::FileSaveDialogImpl;
impl FileSaveDialogImpl for FileDialog {
fn save_file(self) -> Option<PathBuf> {
fn run(opt: FileDialog) -> Result<PathBuf, HRESULT> {
init_com(|| {
let dialog = IDialog::build_save_file(&opt)?;
dialog.show()?;
dialog.get_result()
})?
}
run(self).ok()
}
}
use crate::backend::AsyncFileSaveDialogImpl;
impl AsyncFileSaveDialogImpl for FileDialog {
fn save_file_async(self) -> DialogFutureType<Option<FileHandle>> {
let ret = single_return_future(move || IDialog::build_save_file(&self));
Box::pin(ret)
}
}
|
use super::{Node, Segment};
use std::cmp::min;
/// Defines something that may be interpolated
#[derive(Debug, PartialEq)]
pub enum Interpolatable {
String(String),
Interpolated(Vec<Node>),
}
impl From<Vec<Segment>> for Interpolatable {
fn from(item: Vec<Segment>) -> Self {
let mut tokens: Vec<Node> = vec![];
let mut string = String::new();
let mut interpolated = false;
for part in item {
match part {
Segment::Char(c) => string.push(c),
Segment::String(s) => string.push_str(&s),
Segment::Expr(t) => {
if !string.is_empty() {
tokens.push(Node::Segment(Segment::String(string.clone())));
string.clear();
}
tokens.push(*t);
interpolated = true;
}
}
}
if interpolated {
if !string.is_empty() {
tokens.push(Node::Segment(Segment::String(string.clone())));
}
Self::Interpolated(tokens)
} else {
Self::String(string)
}
}
}
impl Interpolatable {
/// Strips leading indentation from the content according to the rules for squiggly heredocs
pub fn to_unindented(self) -> Self {
match self {
Self::Interpolated(tokens) => Self::Interpolated(Self::unindent_tokens(tokens)),
Self::String(string) => {
let mut tokens =
Self::unindent_tokens(vec![Node::Segment(Segment::String(string))]);
if let Node::Segment(Segment::String(string)) = tokens.remove(0) {
Self::String(string)
} else {
unreachable!()
}
}
}
}
fn unindent_tokens(mut tokens: Vec<Node>) -> Vec<Node> {
let mut after_newline = true;
let mut indentation = usize::MAX;
// Determine the indentation level
for t in &tokens {
if let Node::Segment(Segment::String(string)) = t {
for line in string.lines() {
let mut whitespace = 0usize;
if after_newline {
for c in line.chars() {
match c {
' ' | '\t' => whitespace += 1,
_ => {
// Short-circuit if no adjustments are needed
if whitespace == 0 {
return tokens;
}
indentation = min(indentation, whitespace);
break;
}
}
}
};
after_newline = true;
}
} else {
after_newline = false;
}
}
// Return if no adjustments need to be made
if indentation == usize::MAX {
return tokens;
}
// Adjust the indentation of string segments accordingly
after_newline = true;
let mut whitespace = indentation;
for t in &mut tokens {
if let Node::Segment(Segment::String(ref mut string)) = t {
let mut new_string = String::new();
for c in string.chars() {
match c {
' ' | '\t' => {
if after_newline && whitespace > 0 {
whitespace -= 1;
continue;
}
new_string.push(c);
}
'\n' => {
after_newline = true;
whitespace = indentation;
new_string.push(c);
}
_ => {
after_newline = false;
new_string.push(c);
}
};
}
*string = new_string;
} else {
after_newline = false;
}
}
tokens
}
}
|
// 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::BTreeMap;
use common_catalog::plan::DataSourcePlan;
use common_catalog::plan::InternalColumn;
use common_exception::Result;
use common_expression::types::DataType;
use common_expression::types::NumberDataType;
use common_expression::DataBlock;
use common_expression::DataField;
use common_expression::DataSchemaRef;
use common_expression::DataSchemaRefExt;
use common_expression::FieldIndex;
use common_expression::RemoteExpr;
use common_expression::Scalar;
use common_functions::BUILTIN_FUNCTIONS;
use common_meta_app::schema::TableInfo;
use crate::executor::explain::PlanStatsInfo;
use crate::optimizer::ColumnSet;
use crate::plans::JoinType;
use crate::plans::RuntimeFilterId;
use crate::ColumnBinding;
use crate::IndexType;
pub type ColumnID = String;
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct TableScan {
/// A unique id of operator in a `PhysicalPlan` tree.
/// Only used for display.
pub plan_id: u32,
pub name_mapping: BTreeMap<String, IndexType>,
pub source: Box<DataSourcePlan>,
/// Only used for display
pub table_index: IndexType,
pub stat_info: Option<PlanStatsInfo>,
pub internal_column: Option<BTreeMap<FieldIndex, InternalColumn>>,
}
impl TableScan {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
let mut fields = Vec::with_capacity(self.name_mapping.len());
let schema = self.source.schema();
for (name, id) in self.name_mapping.iter() {
let orig_field = schema.field_with_name(name)?;
let data_type = DataType::from(orig_field.data_type());
fields.push(DataField::new(&id.to_string(), data_type));
}
Ok(DataSchemaRefExt::create(fields))
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Filter {
/// A unique id of operator in a `PhysicalPlan` tree.
/// Only used for display.
pub plan_id: u32,
pub input: Box<PhysicalPlan>,
// Assumption: expression's data type must be `DataType::Boolean`.
pub predicates: Vec<RemoteExpr>,
/// Only used for explain
pub stat_info: Option<PlanStatsInfo>,
}
impl Filter {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
self.input.output_schema()
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Project {
/// A unique id of operator in a `PhysicalPlan` tree.
/// Only used for display.
pub plan_id: u32,
pub input: Box<PhysicalPlan>,
pub projections: Vec<usize>,
/// Only used for display
pub columns: ColumnSet,
pub stat_info: Option<PlanStatsInfo>,
}
impl Project {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
let input_schema = self.input.output_schema()?;
let mut fields = Vec::new();
for i in self.projections.iter() {
fields.push(input_schema.field(*i).clone());
}
Ok(DataSchemaRefExt::create(fields))
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct EvalScalar {
/// A unique id of operator in a `PhysicalPlan` tree.
/// Only used for display.
pub plan_id: u32,
pub input: Box<PhysicalPlan>,
pub exprs: Vec<(RemoteExpr, IndexType)>,
/// Only used for explain
pub stat_info: Option<PlanStatsInfo>,
}
impl EvalScalar {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
let input_schema = self.input.output_schema()?;
let mut fields = input_schema.fields().clone();
for (expr, index) in self.exprs.iter() {
let name = index.to_string();
let data_type = expr.as_expr(&BUILTIN_FUNCTIONS).data_type().clone();
fields.push(DataField::new(&name, data_type));
}
Ok(DataSchemaRefExt::create(fields))
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ProjectSet {
/// A unique id of operator in a `PhysicalPlan` tree.
/// Only used for display.
pub plan_id: u32,
pub input: Box<PhysicalPlan>,
pub srf_exprs: Vec<(RemoteExpr, IndexType)>,
/// Only used for explain
pub stat_info: Option<PlanStatsInfo>,
}
impl ProjectSet {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
let input_schema = self.input.output_schema()?;
let mut fields = input_schema.fields().clone();
fields.extend(self.srf_exprs.iter().map(|(srf, index)| {
DataField::new(
&index.to_string(),
srf.as_expr(&BUILTIN_FUNCTIONS).data_type().clone(),
)
}));
Ok(DataSchemaRefExt::create(fields))
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AggregateExpand {
/// A unique id of operator in a `PhysicalPlan` tree.
/// Only used for display.
pub plan_id: u32,
pub input: Box<PhysicalPlan>,
pub group_bys: Vec<IndexType>,
pub grouping_id_index: IndexType,
pub grouping_sets: Vec<Vec<IndexType>>,
/// Only used for explain
pub stat_info: Option<PlanStatsInfo>,
}
impl AggregateExpand {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
let input_schema = self.input.output_schema()?;
let mut output_fields = input_schema.fields().clone();
for group_by in self
.group_bys
.iter()
.filter(|&index| *index != self.grouping_id_index)
{
// All group by columns will wrap nullable.
let i = input_schema.index_of(&group_by.to_string())?;
let f = &mut output_fields[i];
*f = DataField::new(f.name(), f.data_type().wrap_nullable())
}
output_fields.push(DataField::new(
&self.grouping_id_index.to_string(),
DataType::Number(NumberDataType::UInt32),
));
Ok(DataSchemaRefExt::create(output_fields))
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AggregatePartial {
/// A unique id of operator in a `PhysicalPlan` tree.
/// Only used for display.
pub plan_id: u32,
pub input: Box<PhysicalPlan>,
pub group_by: Vec<IndexType>,
pub agg_funcs: Vec<AggregateFunctionDesc>,
/// Only used for explain
pub stat_info: Option<PlanStatsInfo>,
}
impl AggregatePartial {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
let input_schema = self.input.output_schema()?;
let mut fields = Vec::with_capacity(self.agg_funcs.len() + self.group_by.len());
for agg in self.agg_funcs.iter() {
fields.push(DataField::new(
&agg.output_column.to_string(),
DataType::String,
));
}
if !self.group_by.is_empty() {
let method = DataBlock::choose_hash_method_with_types(
&self
.group_by
.iter()
.map(|index| {
Ok(input_schema
.field_with_name(&index.to_string())?
.data_type()
.clone())
})
.collect::<Result<Vec<_>>>()?,
)?;
fields.push(DataField::new("_group_by_key", method.data_type()));
}
Ok(DataSchemaRefExt::create(fields))
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AggregateFinal {
/// A unique id of operator in a `PhysicalPlan` tree.
/// Only used for display.
pub plan_id: u32,
pub input: Box<PhysicalPlan>,
pub group_by: Vec<IndexType>,
pub agg_funcs: Vec<AggregateFunctionDesc>,
pub before_group_by_schema: DataSchemaRef,
pub limit: Option<usize>,
/// Only used for explain
pub stat_info: Option<PlanStatsInfo>,
}
impl AggregateFinal {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
let mut fields = Vec::with_capacity(self.agg_funcs.len() + self.group_by.len());
for agg in self.agg_funcs.iter() {
let data_type = agg.sig.return_type.clone();
fields.push(DataField::new(&agg.output_column.to_string(), data_type));
}
for id in self.group_by.iter() {
let data_type = self
.before_group_by_schema
.field_with_name(&id.to_string())?
.data_type()
.clone();
fields.push(DataField::new(&id.to_string(), data_type));
}
Ok(DataSchemaRefExt::create(fields))
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Sort {
/// A unique id of operator in a `PhysicalPlan` tree.
/// Only used for display.
pub plan_id: u32,
pub input: Box<PhysicalPlan>,
pub order_by: Vec<SortDesc>,
// limit = Limit.limit + Limit.offset
pub limit: Option<usize>,
/// Only used for explain
pub stat_info: Option<PlanStatsInfo>,
}
impl Sort {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
self.input.output_schema()
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Limit {
/// A unique id of operator in a `PhysicalPlan` tree.
/// Only used for display.
pub plan_id: u32,
pub input: Box<PhysicalPlan>,
pub limit: Option<usize>,
pub offset: usize,
/// Only used for explain
pub stat_info: Option<PlanStatsInfo>,
}
impl Limit {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
self.input.output_schema()
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct HashJoin {
/// A unique id of operator in a `PhysicalPlan` tree.
/// Only used for display.
pub plan_id: u32,
pub build: Box<PhysicalPlan>,
pub probe: Box<PhysicalPlan>,
pub build_keys: Vec<RemoteExpr>,
pub probe_keys: Vec<RemoteExpr>,
pub non_equi_conditions: Vec<RemoteExpr>,
pub join_type: JoinType,
pub marker_index: Option<IndexType>,
pub from_correlated_subquery: bool,
// It means that join has a corresponding runtime filter
pub contain_runtime_filter: bool,
/// Only used for explain
pub stat_info: Option<PlanStatsInfo>,
}
impl HashJoin {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
let mut fields = self.probe.output_schema()?.fields().clone();
match self.join_type {
JoinType::Left | JoinType::Single => {
for field in self.build.output_schema()?.fields() {
fields.push(DataField::new(
field.name().as_str(),
field.data_type().wrap_nullable(),
));
}
}
JoinType::Right => {
fields.clear();
for field in self.probe.output_schema()?.fields() {
fields.push(DataField::new(
field.name().as_str(),
field.data_type().wrap_nullable(),
));
}
for field in self.build.output_schema()?.fields() {
fields.push(DataField::new(
field.name().as_str(),
field.data_type().clone(),
));
}
}
JoinType::Full => {
fields.clear();
for field in self.probe.output_schema()?.fields() {
fields.push(DataField::new(
field.name().as_str(),
field.data_type().wrap_nullable(),
));
}
for field in self.build.output_schema()?.fields() {
fields.push(DataField::new(
field.name().as_str(),
field.data_type().wrap_nullable(),
));
}
}
JoinType::LeftSemi | JoinType::LeftAnti => {
// Do nothing
}
JoinType::RightSemi | JoinType::RightAnti => {
fields.clear();
fields = self.build.output_schema()?.fields().clone();
}
JoinType::LeftMark | JoinType::RightMark => {
fields.clear();
let outer_table = if self.join_type == JoinType::RightMark {
&self.probe
} else {
&self.build
};
fields = outer_table.output_schema()?.fields().clone();
let name = if let Some(idx) = self.marker_index {
idx.to_string()
} else {
"marker".to_string()
};
fields.push(DataField::new(
name.as_str(),
DataType::Nullable(Box::new(DataType::Boolean)),
));
}
_ => {
for field in self.build.output_schema()?.fields() {
fields.push(DataField::new(
field.name().as_str(),
field.data_type().clone(),
));
}
}
}
Ok(DataSchemaRefExt::create(fields))
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Exchange {
pub input: Box<PhysicalPlan>,
pub kind: FragmentKind,
pub keys: Vec<RemoteExpr>,
}
impl Exchange {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
self.input.output_schema()
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ExchangeSource {
/// Output schema of exchanged data
pub schema: DataSchemaRef,
/// Fragment ID of source fragment
pub source_fragment_id: usize,
pub query_id: String,
}
impl ExchangeSource {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
Ok(self.schema.clone())
}
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum FragmentKind {
// Init-partition
Init,
// Partitioned by hash
Normal,
// Broadcast
Expansive,
Merge,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ExchangeSink {
pub input: Box<PhysicalPlan>,
/// Input schema of exchanged data
pub schema: DataSchemaRef,
pub kind: FragmentKind,
pub keys: Vec<RemoteExpr>,
/// Fragment ID of sink fragment
pub destination_fragment_id: usize,
/// Addresses of destination nodes
pub destinations: Vec<String>,
pub query_id: String,
}
impl ExchangeSink {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
Ok(self.schema.clone())
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct UnionAll {
/// A unique id of operator in a `PhysicalPlan` tree.
/// Only used for display.
pub plan_id: u32,
pub left: Box<PhysicalPlan>,
pub right: Box<PhysicalPlan>,
pub pairs: Vec<(String, String)>,
pub schema: DataSchemaRef,
/// Only used for explain
pub stat_info: Option<PlanStatsInfo>,
}
impl UnionAll {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
Ok(self.schema.clone())
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DistributedInsertSelect {
pub input: Box<PhysicalPlan>,
pub catalog: String,
pub table_info: TableInfo,
pub insert_schema: DataSchemaRef,
pub select_schema: DataSchemaRef,
pub select_column_bindings: Vec<ColumnBinding>,
pub cast_needed: bool,
}
impl DistributedInsertSelect {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
Ok(DataSchemaRefExt::create(vec![
DataField::new("seg_loc", DataType::String),
DataField::new("seg_info", DataType::String),
]))
}
}
// Build runtime predicate data from join build side
// Then pass it to runtime filter on join probe side
// It's the children of join node
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct RuntimeFilterSource {
/// A unique id of operator in a `PhysicalPlan` tree.
/// Only used for display.
pub plan_id: u32,
pub left_side: Box<PhysicalPlan>,
pub right_side: Box<PhysicalPlan>,
pub left_runtime_filters: BTreeMap<RuntimeFilterId, RemoteExpr>,
pub right_runtime_filters: BTreeMap<RuntimeFilterId, RemoteExpr>,
}
impl RuntimeFilterSource {
pub fn output_schema(&self) -> Result<DataSchemaRef> {
self.left_side.output_schema()
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum PhysicalPlan {
TableScan(TableScan),
Filter(Filter),
Project(Project),
EvalScalar(EvalScalar),
ProjectSet(ProjectSet),
AggregateExpand(AggregateExpand),
AggregatePartial(AggregatePartial),
AggregateFinal(AggregateFinal),
Sort(Sort),
Limit(Limit),
HashJoin(HashJoin),
Exchange(Exchange),
UnionAll(UnionAll),
RuntimeFilterSource(RuntimeFilterSource),
/// For insert into ... select ... in cluster
DistributedInsertSelect(Box<DistributedInsertSelect>),
/// Synthesized by fragmenter
ExchangeSource(ExchangeSource),
ExchangeSink(ExchangeSink),
}
impl PhysicalPlan {
pub fn is_distributed_plan(&self) -> bool {
self.children().any(|child| child.is_distributed_plan())
|| matches!(
self,
Self::ExchangeSource(_) | Self::ExchangeSink(_) | Self::Exchange(_)
)
}
pub fn output_schema(&self) -> Result<DataSchemaRef> {
match self {
PhysicalPlan::TableScan(plan) => plan.output_schema(),
PhysicalPlan::Filter(plan) => plan.output_schema(),
PhysicalPlan::Project(plan) => plan.output_schema(),
PhysicalPlan::EvalScalar(plan) => plan.output_schema(),
PhysicalPlan::AggregateExpand(plan) => plan.output_schema(),
PhysicalPlan::AggregatePartial(plan) => plan.output_schema(),
PhysicalPlan::AggregateFinal(plan) => plan.output_schema(),
PhysicalPlan::Sort(plan) => plan.output_schema(),
PhysicalPlan::Limit(plan) => plan.output_schema(),
PhysicalPlan::HashJoin(plan) => plan.output_schema(),
PhysicalPlan::Exchange(plan) => plan.output_schema(),
PhysicalPlan::ExchangeSource(plan) => plan.output_schema(),
PhysicalPlan::ExchangeSink(plan) => plan.output_schema(),
PhysicalPlan::UnionAll(plan) => plan.output_schema(),
PhysicalPlan::DistributedInsertSelect(plan) => plan.output_schema(),
PhysicalPlan::ProjectSet(plan) => plan.output_schema(),
PhysicalPlan::RuntimeFilterSource(plan) => plan.output_schema(),
}
}
pub fn name(&self) -> String {
match self {
PhysicalPlan::TableScan(_) => "TableScan".to_string(),
PhysicalPlan::Filter(_) => "Filter".to_string(),
PhysicalPlan::Project(_) => "Project".to_string(),
PhysicalPlan::EvalScalar(_) => "EvalScalar".to_string(),
PhysicalPlan::AggregateExpand(_) => "AggregateExpand".to_string(),
PhysicalPlan::AggregatePartial(_) => "AggregatePartial".to_string(),
PhysicalPlan::AggregateFinal(_) => "AggregateFinal".to_string(),
PhysicalPlan::Sort(_) => "Sort".to_string(),
PhysicalPlan::Limit(_) => "Limit".to_string(),
PhysicalPlan::HashJoin(_) => "HashJoin".to_string(),
PhysicalPlan::Exchange(_) => "Exchange".to_string(),
PhysicalPlan::UnionAll(_) => "UnionAll".to_string(),
PhysicalPlan::DistributedInsertSelect(_) => "DistributedInsertSelect".to_string(),
PhysicalPlan::ExchangeSource(_) => "Exchange Source".to_string(),
PhysicalPlan::ExchangeSink(_) => "Exchange Sink".to_string(),
PhysicalPlan::ProjectSet(_) => "Unnest".to_string(),
PhysicalPlan::RuntimeFilterSource(_) => "RuntimeFilterSource".to_string(),
}
}
pub fn children<'a>(&'a self) -> Box<dyn Iterator<Item = &'a PhysicalPlan> + 'a> {
match self {
PhysicalPlan::TableScan(_) => Box::new(std::iter::empty()),
PhysicalPlan::Filter(plan) => Box::new(std::iter::once(plan.input.as_ref())),
PhysicalPlan::Project(plan) => Box::new(std::iter::once(plan.input.as_ref())),
PhysicalPlan::EvalScalar(plan) => Box::new(std::iter::once(plan.input.as_ref())),
PhysicalPlan::AggregateExpand(plan) => Box::new(std::iter::once(plan.input.as_ref())),
PhysicalPlan::AggregatePartial(plan) => Box::new(std::iter::once(plan.input.as_ref())),
PhysicalPlan::AggregateFinal(plan) => Box::new(std::iter::once(plan.input.as_ref())),
PhysicalPlan::Sort(plan) => Box::new(std::iter::once(plan.input.as_ref())),
PhysicalPlan::Limit(plan) => Box::new(std::iter::once(plan.input.as_ref())),
PhysicalPlan::HashJoin(plan) => Box::new(
std::iter::once(plan.probe.as_ref()).chain(std::iter::once(plan.build.as_ref())),
),
PhysicalPlan::Exchange(plan) => Box::new(std::iter::once(plan.input.as_ref())),
PhysicalPlan::ExchangeSource(_) => Box::new(std::iter::empty()),
PhysicalPlan::ExchangeSink(plan) => Box::new(std::iter::once(plan.input.as_ref())),
PhysicalPlan::UnionAll(plan) => Box::new(
std::iter::once(plan.left.as_ref()).chain(std::iter::once(plan.right.as_ref())),
),
PhysicalPlan::DistributedInsertSelect(plan) => {
Box::new(std::iter::once(plan.input.as_ref()))
}
PhysicalPlan::ProjectSet(plan) => Box::new(std::iter::once(plan.input.as_ref())),
PhysicalPlan::RuntimeFilterSource(plan) => Box::new(
std::iter::once(plan.left_side.as_ref())
.chain(std::iter::once(plan.right_side.as_ref())),
),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct AggregateFunctionDesc {
pub sig: AggregateFunctionSignature,
pub output_column: IndexType,
pub args: Vec<usize>,
pub arg_indices: Vec<IndexType>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct AggregateFunctionSignature {
pub name: String,
pub args: Vec<DataType>,
pub params: Vec<Scalar>,
pub return_type: DataType,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct SortDesc {
pub asc: bool,
pub nulls_first: bool,
pub order_by: IndexType,
}
|
//! https://github.com/lumen/otp/tree/lumen/lib/megaco/src/app
use super::*;
test_compiles_lumen_otp!(megaco);
fn includes() -> Vec<&'static str> {
let includes = super::includes();
// includes.push("lib/inets/src/http_client");
includes
}
fn relative_directory_path() -> PathBuf {
super::relative_directory_path().join("app")
}
|
use crate::{map_unit_fn::OPTION_MAP_UNIT_FN, matches::MATCH_AS_REF};
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::higher::IfLetOrMatch;
use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
use clippy_utils::ty::{is_type_diagnostic_item, peel_mid_ty_refs_is_mutable};
use clippy_utils::{
can_move_expr_to_closure, in_constant, is_else_clause, is_lang_ctor, is_lint_allowed, path_to_local_id,
peel_hir_expr_refs, peel_hir_expr_while, CaptureKind,
};
use rustc_ast::util::parser::PREC_POSTFIX;
use rustc_errors::Applicability;
use rustc_hir::LangItem::{OptionNone, OptionSome};
use rustc_hir::{
def::Res, Arm, BindingAnnotation, Block, Expr, ExprKind, HirId, Mutability, Pat, PatKind, Path, QPath,
};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::{sym, SyntaxContext};
declare_clippy_lint! {
/// ### What it does
/// Checks for usages of `match` which could be implemented using `map`
///
/// ### Why is this bad?
/// Using the `map` method is clearer and more concise.
///
/// ### Example
/// ```rust
/// match Some(0) {
/// Some(x) => Some(x + 1),
/// None => None,
/// };
/// ```
/// Use instead:
/// ```rust
/// Some(0).map(|x| x + 1);
/// ```
#[clippy::version = "1.52.0"]
pub MANUAL_MAP,
style,
"reimplementation of `map`"
}
declare_lint_pass!(ManualMap => [MANUAL_MAP]);
impl LateLintPass<'_> for ManualMap {
#[allow(clippy::too_many_lines)]
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
let (scrutinee, then_pat, then_body, else_pat, else_body) = match IfLetOrMatch::parse(cx, expr) {
Some(IfLetOrMatch::IfLet(scrutinee, pat, body, Some(r#else))) => (scrutinee, pat, body, None, r#else),
Some(IfLetOrMatch::Match(
scrutinee,
[arm1 @ Arm { guard: None, .. }, arm2 @ Arm { guard: None, .. }],
_,
)) => (scrutinee, arm1.pat, arm1.body, Some(arm2.pat), arm2.body),
_ => return,
};
if in_external_macro(cx.sess(), expr.span) || in_constant(cx, expr.hir_id) {
return;
}
let (scrutinee_ty, ty_ref_count, ty_mutability) =
peel_mid_ty_refs_is_mutable(cx.typeck_results().expr_ty(scrutinee));
if !(is_type_diagnostic_item(cx, scrutinee_ty, sym::Option)
&& is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::Option))
{
return;
}
let expr_ctxt = expr.span.ctxt();
let (some_expr, some_pat, pat_ref_count, is_wild_none) = match (
try_parse_pattern(cx, then_pat, expr_ctxt),
else_pat.map_or(Some(OptionPat::Wild), |p| try_parse_pattern(cx, p, expr_ctxt)),
) {
(Some(OptionPat::Wild), Some(OptionPat::Some { pattern, ref_count })) if is_none_expr(cx, then_body) => {
(else_body, pattern, ref_count, true)
},
(Some(OptionPat::None), Some(OptionPat::Some { pattern, ref_count })) if is_none_expr(cx, then_body) => {
(else_body, pattern, ref_count, false)
},
(Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::Wild)) if is_none_expr(cx, else_body) => {
(then_body, pattern, ref_count, true)
},
(Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::None)) if is_none_expr(cx, else_body) => {
(then_body, pattern, ref_count, false)
},
_ => return,
};
// Top level or patterns aren't allowed in closures.
if matches!(some_pat.kind, PatKind::Or(_)) {
return;
}
let some_expr = match get_some_expr(cx, some_expr, expr_ctxt) {
Some(expr) => expr,
None => return,
};
// These two lints will go back and forth with each other.
if cx.typeck_results().expr_ty(some_expr) == cx.tcx.types.unit
&& !is_lint_allowed(cx, OPTION_MAP_UNIT_FN, expr.hir_id)
{
return;
}
// `map` won't perform any adjustments.
if !cx.typeck_results().expr_adjustments(some_expr).is_empty() {
return;
}
// Determine which binding mode to use.
let explicit_ref = some_pat.contains_explicit_ref_binding();
let binding_ref = explicit_ref.or_else(|| (ty_ref_count != pat_ref_count).then(|| ty_mutability));
let as_ref_str = match binding_ref {
Some(Mutability::Mut) => ".as_mut()",
Some(Mutability::Not) => ".as_ref()",
None => "",
};
match can_move_expr_to_closure(cx, some_expr) {
Some(captures) => {
// Check if captures the closure will need conflict with borrows made in the scrutinee.
// TODO: check all the references made in the scrutinee expression. This will require interacting
// with the borrow checker. Currently only `<local>[.<field>]*` is checked for.
if let Some(binding_ref_mutability) = binding_ref {
let e = peel_hir_expr_while(scrutinee, |e| match e.kind {
ExprKind::Field(e, _) | ExprKind::AddrOf(_, _, e) => Some(e),
_ => None,
});
if let ExprKind::Path(QPath::Resolved(None, Path { res: Res::Local(l), .. })) = e.kind {
match captures.get(l) {
Some(CaptureKind::Value | CaptureKind::Ref(Mutability::Mut)) => return,
Some(CaptureKind::Ref(Mutability::Not)) if binding_ref_mutability == Mutability::Mut => {
return;
},
Some(CaptureKind::Ref(Mutability::Not)) | None => (),
}
}
}
},
None => return,
};
let mut app = Applicability::MachineApplicable;
// Remove address-of expressions from the scrutinee. Either `as_ref` will be called, or
// it's being passed by value.
let scrutinee = peel_hir_expr_refs(scrutinee).0;
let (scrutinee_str, _) = snippet_with_context(cx, scrutinee.span, expr_ctxt, "..", &mut app);
let scrutinee_str =
if scrutinee.span.ctxt() == expr.span.ctxt() && scrutinee.precedence().order() < PREC_POSTFIX {
format!("({})", scrutinee_str)
} else {
scrutinee_str.into()
};
let body_str = if let PatKind::Binding(annotation, id, some_binding, None) = some_pat.kind {
match can_pass_as_func(cx, id, some_expr) {
Some(func) if func.span.ctxt() == some_expr.span.ctxt() => {
snippet_with_applicability(cx, func.span, "..", &mut app).into_owned()
},
_ => {
if path_to_local_id(some_expr, id)
&& !is_lint_allowed(cx, MATCH_AS_REF, expr.hir_id)
&& binding_ref.is_some()
{
return;
}
// `ref` and `ref mut` annotations were handled earlier.
let annotation = if matches!(annotation, BindingAnnotation::Mutable) {
"mut "
} else {
""
};
format!(
"|{}{}| {}",
annotation,
some_binding,
snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
)
},
}
} else if !is_wild_none && explicit_ref.is_none() {
// TODO: handle explicit reference annotations.
format!(
"|{}| {}",
snippet_with_context(cx, some_pat.span, expr_ctxt, "..", &mut app).0,
snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
)
} else {
// Refutable bindings and mixed reference annotations can't be handled by `map`.
return;
};
span_lint_and_sugg(
cx,
MANUAL_MAP,
expr.span,
"manual implementation of `Option::map`",
"try this",
if else_pat.is_none() && is_else_clause(cx.tcx, expr) {
format!("{{ {}{}.map({}) }}", scrutinee_str, as_ref_str, body_str)
} else {
format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str)
},
app,
);
}
}
// Checks whether the expression could be passed as a function, or whether a closure is needed.
// Returns the function to be passed to `map` if it exists.
fn can_pass_as_func(cx: &LateContext<'tcx>, binding: HirId, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
match expr.kind {
ExprKind::Call(func, [arg])
if path_to_local_id(arg, binding) && cx.typeck_results().expr_adjustments(arg).is_empty() =>
{
Some(func)
},
_ => None,
}
}
enum OptionPat<'a> {
Wild,
None,
Some {
// The pattern contained in the `Some` tuple.
pattern: &'a Pat<'a>,
// The number of references before the `Some` tuple.
// e.g. `&&Some(_)` has a ref count of 2.
ref_count: usize,
},
}
// Try to parse into a recognized `Option` pattern.
// i.e. `_`, `None`, `Some(..)`, or a reference to any of those.
fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
fn f(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
match pat.kind {
PatKind::Wild => Some(OptionPat::Wild),
PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt),
PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone) => Some(OptionPat::None),
PatKind::TupleStruct(ref qpath, [pattern], _)
if is_lang_ctor(cx, qpath, OptionSome) && pat.span.ctxt() == ctxt =>
{
Some(OptionPat::Some { pattern, ref_count })
},
_ => None,
}
}
f(cx, pat, 0, ctxt)
}
// Checks for an expression wrapped by the `Some` constructor. Returns the contained expression.
fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ctxt: SyntaxContext) -> Option<&'tcx Expr<'tcx>> {
// TODO: Allow more complex expressions.
match expr.kind {
ExprKind::Call(
Expr {
kind: ExprKind::Path(ref qpath),
..
},
[arg],
) if ctxt == expr.span.ctxt() && is_lang_ctor(cx, qpath, OptionSome) => Some(arg),
ExprKind::Block(
Block {
stmts: [],
expr: Some(expr),
..
},
_,
) => get_some_expr(cx, expr, ctxt),
_ => None,
}
}
// Checks for the `None` value.
fn is_none_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
match expr.kind {
ExprKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
ExprKind::Block(
Block {
stmts: [],
expr: Some(expr),
..
},
_,
) => is_none_expr(cx, expr),
_ => false,
}
}
|
//! A flat representation of memory provided by lifters, typically used in a
//! read-only fashion
//!
//! This memory model implements the `TranslationMemory` trait, allowing lifters
//! to use it to lift instructions.
use crate::architecture::Endian;
use crate::executor;
use crate::il;
use crate::memory::MemoryPermissions;
use crate::translator::TranslationMemory;
use crate::Error;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::ops::Bound::Included;
/// A section of backed memory. Essentially a vector of type `u8` with
/// permissions.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Section {
data: Vec<u8>,
permissions: MemoryPermissions,
}
impl Section {
/// Create a new memory section.
pub fn new(data: Vec<u8>, permissions: MemoryPermissions) -> Section {
Section { data, permissions }
}
/// Get this memory section's data.
pub fn data(&self) -> &[u8] {
&self.data
}
/// Get the length of this memory section.
pub fn len(&self) -> usize {
self.data.len()
}
/// Return `true` if the data field is empty, `false` otherwise.
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// Get the permissions of this memory section.
pub fn permissions(&self) -> MemoryPermissions {
self.permissions
}
/// Truncate the data of this memory section.
fn truncate(&mut self, size: usize) {
self.data.truncate(size);
}
}
/// A simple memory model, containing permissioned sections of type `u8`.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Memory {
endian: Endian,
sections: BTreeMap<u64, Section>,
}
impl Memory {
/// Create a new backed memory module with the given endianness.
pub fn new(endian: Endian) -> Memory {
Memory {
endian,
sections: BTreeMap::new(),
}
}
/// Get the sections in this memory module.
pub fn sections(&self) -> &BTreeMap<u64, Section> {
&self.sections
}
/// Get the permissions at the given address.
pub fn permissions(&self, address: u64) -> Option<MemoryPermissions> {
self.section_address(address).map(|section_address| {
self.sections
.get(§ion_address)
.unwrap_or_else(|| {
panic!(
"Failed to get section at 0x{:x} in \
backing::Memory::permissions()",
section_address
)
})
.permissions()
})
}
/// Get the `u8` value at the given address.
pub fn get8(&self, address: u64) -> Option<u8> {
self.section_address_offset(address)
.map(|(address, offset)| {
*self
.sections
.get(&address)
.unwrap_or_else(|| {
panic!(
"Failed to get section at 0x{:x} in \
backing::Memory::permissions()",
address
)
})
.data()
.get(offset)
.unwrap_or_else(|| {
panic!(
"Failed to get offset 0x{:x} from 0x{:x} in \
backing::Memory::permissions()",
offset, address
)
})
})
}
/// Set the 32-bit value at the given address, allowing the memory model
/// to account for the underlying endianness.
pub fn set32(&mut self, address: u64, value: u32) -> Result<(), Error> {
let (section_address, offset) = self
.section_address_offset(address)
.unwrap_or_else(|| panic!("Address 0x{:x} has no section", address));
let section = self.sections.get_mut(§ion_address).unwrap();
if offset + 4 > section.len() {
return Err(Error::Custom(format!(
"Section at 0x{:x} is of size {}, and not big \
enough to hold 32-bit value",
section_address,
section.len()
)));
}
match self.endian {
Endian::Big => {
*section.data.get_mut(offset).unwrap() = (value >> 24) as u8;
*section.data.get_mut(offset + 1).unwrap() = (value >> 16) as u8;
*section.data.get_mut(offset + 2).unwrap() = (value >> 8) as u8;
*section.data.get_mut(offset + 3).unwrap() = (value) as u8;
}
Endian::Little => {
*section.data.get_mut(offset).unwrap() = (value) as u8;
*section.data.get_mut(offset + 1).unwrap() = (value >> 8) as u8;
*section.data.get_mut(offset + 2).unwrap() = (value >> 16) as u8;
*section.data.get_mut(offset + 3).unwrap() = (value >> 24) as u8;
}
}
Ok(())
}
/// Get the 32-bit value at the given address, allowing the memory model to
/// account for the underlying endianness.
pub fn get32(&self, address: u64) -> Option<u32> {
let (section_address, offset) = match self.section_address_offset(address) {
Some((section_address, offset)) => (section_address, offset),
None => return None,
};
let section = self.sections.get(§ion_address).unwrap();
if offset + 4 > section.len() {
return None;
}
Some(match self.endian {
Endian::Big => {
(section.data[offset] as u32) << 24
| (section.data[offset + 1] as u32) << 16
| (section.data[offset + 2] as u32) << 8
| (section.data[offset + 3] as u32)
}
Endian::Little => {
(section.data[offset] as u32)
| (section.data[offset + 1] as u32) << 8
| (section.data[offset + 2] as u32) << 16
| (section.data[offset + 3] as u32) << 24
}
})
}
/// Get a constant value up to a certain number of bits
pub fn get(&self, address: u64, bits: usize) -> Option<il::Constant> {
if bits % 8 > 0 || bits == 0 {
return None;
}
let mut value = il::expr_const(self.get8(address)? as u64, bits);
match self.endian {
Endian::Big => {
for i in 1..(bits / 8) {
value = il::Expression::or(
il::Expression::shl(value, il::expr_const(8, bits)).unwrap(),
il::expr_const(self.get8(address + i as u64).unwrap() as u64, bits),
)
.unwrap();
}
Some(executor::eval(&value).unwrap())
}
Endian::Little => {
for i in 1..(bits / 8) {
value = il::Expression::or(
il::Expression::shl(
il::expr_const(self.get8(address + i as u64).unwrap() as u64, bits),
il::expr_const((i * 8) as u64, bits),
)
.unwrap(),
value,
)
.unwrap();
}
Some(executor::eval(&value).unwrap())
}
}
}
/// Set the memory at the given address, and give that memory the given
/// permissions.
///
/// This takes care of the underlying memory sections automatically.
pub fn set_memory(&mut self, address: u64, data: Vec<u8>, permissions: MemoryPermissions) {
// All overlapping memory sections need to be adjusted
// Start by collecting addresses and lengths
let als = self
.sections
.iter()
.map(|(address, section)| (*address, section.len()))
.collect::<Vec<(u64, usize)>>();
// Adjust overlapping memory sections
for al in als {
let (a, l) = (al.0, al.1 as u64);
if a < address && a + l > address {
if a + l <= address + data.len() as u64 {
let new_length = (address - a) as usize;
self.sections
.get_mut(&a)
.unwrap_or_else(|| {
panic!(
"Failed to get section 0x{:x} in \
backing::Memory::set_memory(). This should never \
happen.",
a
)
})
.truncate(new_length);
} else {
let offset = address + data.len() as u64 - a;
let split = self
.sections
.get_mut(&a)
.unwrap_or_else(|| {
panic!(
"Failed to get section 0x{:x} in \
backing::Memory::set_memory(). This should \
never happen.",
a
)
})
.data
.split_off(offset as usize);
let permissions = self
.sections
.get(&a)
.unwrap_or_else(|| {
panic!(
"Failed to get section 0x{:x} in \
backing::Memory::set_memory(). This should \
never happen.",
a
)
})
.permissions();
self.sections.insert(
address + data.len() as u64,
Section::new(split, permissions),
);
let new_length = (address - a) as usize;
self.sections.get_mut(&a).unwrap().truncate(new_length);
}
} else if a >= address && a + l <= address + data.len() as u64 {
if self.sections.get(&a).is_none() {
panic!(
"About to remove 0x{:x} from sections in \
backing::Memory::set_memory, but address does not
exist",
a
);
}
self.sections.remove(&a);
} else if a >= address
&& a < address + data.len() as u64
&& a + l > address + data.len() as u64
{
let offset = address + data.len() as u64 - a;
let data_len = self.sections.get(&a).unwrap().data.len() as u64;
if offset > data_len {
panic!("offset 0x{:x} is > data.len() 0x{:x}", offset, data_len);
}
let split = self
.sections
.get_mut(&a)
.unwrap()
.data
.split_off(offset as usize);
let permissions = self
.sections
.get(&a)
.unwrap_or_else(|| {
panic!(
"Failed to get section for 0x{:x} while updating \
permissions in backing::Memory::set_memory(). \
This should never happen.",
a
)
})
.permissions();
self.sections.remove(&a);
self.sections.insert(
address + data.len() as u64,
Section::new(split, permissions),
);
}
}
self.sections
.insert(address, Section::new(data, permissions));
}
fn section_address(&self, address: u64) -> Option<u64> {
let mut sections = self.sections.range((Included(0), Included(address)));
if let Some((section_address, section)) = sections.next_back() {
if *section_address <= address && *section_address + section.len() as u64 > address {
return Some(*section_address);
}
}
None
}
fn section_address_offset(&self, address: u64) -> Option<(u64, usize)> {
self.section_address(address)
.map(|section_address| (section_address, (address - section_address) as usize))
}
}
impl TranslationMemory for Memory {
fn get_u8(&self, address: u64) -> Option<u8> {
self.get8(address)
}
fn permissions(&self, address: u64) -> Option<MemoryPermissions> {
self.permissions(address)
}
}
|
use super::{
and::And, or::Or, passthrough::Passthrough, ActiveFilter, DynamicFilter, FilterResult,
GroupMatcher, LayoutFilter,
};
use crate::internals::{query::view::Fetch, storage::component::ComponentTypeId, world::WorldId};
/// A filter which negates `F`.
#[derive(Debug, Clone, Default)]
pub struct Not<F> {
pub(super) filter: F,
}
impl<F> ActiveFilter for Not<F> {}
impl<F> GroupMatcher for Not<F> {
fn can_match_group() -> bool {
false
}
fn group_components() -> Vec<ComponentTypeId> {
vec![]
}
}
impl<F: LayoutFilter> LayoutFilter for Not<F> {
fn matches_layout(&self, components: &[ComponentTypeId]) -> FilterResult {
match self.filter.matches_layout(components) {
FilterResult::Match(success) => FilterResult::Match(!success),
FilterResult::Defer => FilterResult::Defer,
}
}
}
impl<F: DynamicFilter> DynamicFilter for Not<F> {
fn prepare(&mut self, world: WorldId) {
self.filter.prepare(world);
}
fn matches_archetype<T: Fetch>(&mut self, fetch: &T) -> FilterResult {
match self.filter.matches_archetype(fetch) {
FilterResult::Match(success) => FilterResult::Match(!success),
FilterResult::Defer => FilterResult::Defer,
}
}
}
impl<'a, F, Rhs: ActiveFilter> std::ops::BitAnd<Rhs> for Not<F> {
type Output = And<(Self, Rhs)>;
#[inline]
fn bitand(self, rhs: Rhs) -> Self::Output {
And {
filters: (self, rhs),
}
}
}
impl<'a, F> std::ops::BitAnd<Passthrough> for Not<F> {
type Output = Self;
#[inline]
fn bitand(self, _: Passthrough) -> Self::Output {
self
}
}
impl<'a, F, Rhs: ActiveFilter> std::ops::BitOr<Rhs> for Not<F> {
type Output = Or<(Self, Rhs)>;
#[inline]
fn bitor(self, rhs: Rhs) -> Self::Output {
Or {
filters: (self, rhs),
}
}
}
impl<'a, F> std::ops::BitOr<Passthrough> for Not<F> {
type Output = Self;
#[inline]
fn bitor(self, _: Passthrough) -> Self::Output {
self
}
}
|
//! Implementations of the callbacks exposed by wlc.
//! These functions are the main entry points into Way Cooler from user action.
use rustwlc::handle::{WlcOutput, WlcView};
use rustwlc::types::*;
use super::keys;
use super::layout::{lock_tree, try_lock_tree, TreeError};
use super::lua;
use ::modes::{write_current_mode, read_current_mode};
// NOTE That we don't hold the mode lock long, because wlc uses
// an immediate mode and it's possible to hold the lock twice
// if we don't copy the mode struct out.
pub extern fn output_created(output: WlcOutput) -> bool {
trace!("output_created: {:?}: {}", output, output.get_name());
let mut mode = read_current_mode().clone();
mode.output_created(output)
}
pub extern fn output_destroyed(output: WlcOutput) {
trace!("output_destroyed: {:?}", output);
let mut mode = read_current_mode().clone();
mode.output_destroyed(output)
}
pub extern fn output_focus(output: WlcOutput, focused: bool) {
trace!("output_focus: {:?} focus={}", output, focused);
let mut mode = read_current_mode().clone();
mode.output_focused(output, focused)
}
pub extern fn output_resolution(output: WlcOutput,
old_size_ptr: &Size, new_size_ptr: &Size) {
trace!("output_resolution: {:?} from {:?} to {:?}",
output, *old_size_ptr, *new_size_ptr);
let mut mode = read_current_mode().clone();
mode.output_resolution(output, *old_size_ptr, *new_size_ptr)
}
pub extern fn post_render(output: WlcOutput) {
let mut mode = read_current_mode().clone();
mode.output_render_post(output)
}
pub extern fn view_created(view: WlcView) -> bool {
trace!("view_created: {:?}: \"{}\"", view, view.get_title());
let mut mode;
let res;
{
mode = read_current_mode().clone();
res = mode.view_created(view);
}
*write_current_mode() = mode;
res
}
pub extern fn view_destroyed(view: WlcView) {
trace!("view_destroyed: {:?}", view);
let mut mode;
{
mode = read_current_mode().clone();
mode.view_destroyed(view);
}
*write_current_mode() = mode;
}
pub extern fn view_focus(current: WlcView, focused: bool) {
trace!("view_focus: {:?} {}", current, focused);
let mut mode = read_current_mode().clone();
mode.view_focused(current, focused);
}
pub extern fn view_props_changed(view: WlcView, prop: ViewPropertyType) {
trace!("view_props_changed for view {:?}: {:?}", view, prop);
let mut mode = read_current_mode().clone();
mode.view_props_changed(view, prop)
}
pub extern fn view_move_to_output(current: WlcView,
o1: WlcOutput, o2: WlcOutput) {
trace!("view_move_to_output: {:?}, {:?}, {:?}", current, o1, o2);
let mut mode = read_current_mode().clone();
mode.view_moved_to_output(current, o1, o2)
}
pub extern fn view_request_state(view: WlcView, state: ViewState, toggle: bool) {
trace!("Setting {:?} to state {:?}", view, state);
let mut mode = read_current_mode().clone();
mode.view_request_state(view, state, toggle)
}
pub extern fn view_request_move(view: WlcView, dest: &Point) {
trace!("View {:?} request to move to {:?}", view, dest);
let mut mode = read_current_mode().clone();
mode.view_request_move(view, *dest)
}
pub extern fn view_request_resize(view: WlcView, edge: ResizeEdge, point: &Point) {
trace!("View {:?} request resize w/ edge {:?} to point {:?}",
view, edge, point);
let mut mode = read_current_mode().clone();
mode.view_request_resize(view, edge, *point)
}
pub extern fn view_request_geometry(view: WlcView, geometry: &Geometry) {
trace!("View {:?} requested geometry {:?}", view, geometry);
let mut mode = read_current_mode().clone();
mode.view_request_geometry(view, *geometry)
}
pub extern fn keyboard_key(view: WlcView, time: u32, mods: &KeyboardModifiers,
key: u32, state: KeyState) -> bool {
let mut mode = read_current_mode().clone();
mode.on_keyboard_key(view, time, *mods, key, state)
}
pub extern fn pointer_button(view: WlcView, time: u32,
mods: &KeyboardModifiers, button: u32,
state: ButtonState, point: &Point) -> bool {
let mut mode = read_current_mode().clone();
mode.on_pointer_button(view, time, *mods, button, state, *point)
}
pub extern fn pointer_scroll(view: WlcView, time: u32,
mods_ptr: &KeyboardModifiers, axis: ScrollAxis,
heights: [f64; 2]) -> bool {
let mut mode = read_current_mode().clone();
mode.on_pointer_scroll(view, time, *mods_ptr, axis, heights)
}
pub extern fn pointer_motion(view: WlcView, time: u32, x: f64, y: f64) -> bool {
let mut mode = read_current_mode().clone();
mode.on_pointer_motion(view, time, x, y)
}
pub extern fn compositor_ready() {
info!("Preparing compositor!");
lua::on_compositor_ready();
keys::init();
}
pub extern fn compositor_terminating() {
info!("Compositor terminating!");
lua::send(lua::LuaQuery::Terminate).ok();
if let Ok(mut tree) = try_lock_tree() {
tree.destroy_tree().unwrap_or_else(|err|
error!("Could not destroy tree: {:#?}", err)
)
}
}
pub extern fn view_pre_render(view: WlcView) {
if let Ok(mut tree) = lock_tree() {
tree.render_borders(view).unwrap_or_else(|err| {
match err {
// TODO Only filter if background or bar
TreeError::ViewNotFound(_) => {},
err => warn!("Error while rendering borders: {:?}", err)
}
})
}
}
pub fn init() {
use rustwlc::callback;
callback::output_created(output_created);
callback::output_destroyed(output_destroyed);
callback::output_focus(output_focus);
callback::output_resolution(output_resolution);
callback::output_render_post(post_render);
callback::view_created(view_created);
callback::view_destroyed(view_destroyed);
callback::view_focus(view_focus);
callback::view_move_to_output(view_move_to_output);
callback::view_request_geometry(view_request_geometry);
callback::view_request_state(view_request_state);
callback::view_request_move(view_request_move);
callback::view_request_resize(view_request_resize);
callback::view_properties_changed(view_props_changed);
callback::keyboard_key(keyboard_key);
callback::pointer_button(pointer_button);
callback::pointer_scroll(pointer_scroll);
callback::pointer_motion_v2(pointer_motion);
callback::compositor_ready(compositor_ready);
callback::compositor_terminate(compositor_terminating);
callback::view_render_pre(view_pre_render);
trace!("Registered wlc callbacks");
}
|
extern crate hyper;
extern crate serde;
extern crate serde_json;
use hyper::Server;
use hyper::server::Request;
use hyper::server::Response;
use hyper::header::Headers;
use hyper::header::Server as ServerHeader;
use hyper::header::ContentType;
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
struct PingResponse {
success: bool,
message: String,
}
impl serde::Serialize for PingResponse {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
serializer.serialize_struct("PingResponse", PingResponseMapVisitor {
value: self,
state: 0,
})
}
}
struct PingResponseMapVisitor<'a> {
value: &'a PingResponse,
state: u8,
}
impl<'a> serde::ser::MapVisitor for PingResponseMapVisitor<'a> {
fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error>
where S: serde::Serializer
{
match self.state {
0 => {
self.state += 1;
Ok(Some(try!(serializer.serialize_struct_elt("success", &self.value.success))))
}
1 => {
self.state += 1;
Ok(Some(try!(serializer.serialize_struct_elt("message", &self.value.message))))
}
_ => {
Ok(None)
}
}
}
}
fn handle_root(_: Request, res: Response) {
let mut headers = Headers::new();
headers.set(ServerHeader("hyper/0.8.0".to_owned()));
headers.set(
ContentType(
Mime(TopLevel::Application, SubLevel::Json, vec![(Attr::Charset, Value::Utf8)])
)
);
let response_message = "It worked!".to_string();
let ping_resp = PingResponse { success: true, message: response_message };
let serialized_ping_resp = serde_json::to_string(&ping_resp).unwrap();
res.send(serialized_ping_resp.as_bytes()).unwrap(); /* here need serialized_ping_resp to be binary */
}
fn main() {
//let host = "127.0.0.1".to_string();
//let port = "43110";
//let hostport = host + ":" + port;
//println!("Started on host={} port={}", host, port);
//Server::http(hostport).unwrap().handle(handle_root).unwrap();
Server::http("127.0.0.1:43110").unwrap().handle(handle_root).unwrap();
}
|
use challenges::random_bytes;
use cipher::{cbc::AES_128_CBC, Cipher};
fn main() {
println!("🔓 Challenge 27");
let key = Key::new();
key_recovery_attack(&key);
}
fn key_recovery_attack(key: &Key) {
let pt_0 = b"yellow submarine".to_vec();
let pt_1_2 = b"1234567890abcdef1234567890abcdef".to_vec();
let ct = key.encryption_oracle(&[pt_0.clone(), pt_1_2].concat());
let mut tampered_ct = vec![];
tampered_ct.extend_from_slice(&ct[..16]); // prefixed iv
tampered_ct.extend_from_slice(&ct[16..32]); // C1
tampered_ct.extend_from_slice(&[0 as u8; 16]); // 0
tampered_ct.extend_from_slice(&ct[16..32]); // C1
tampered_ct.extend_from_slice(&ct[48..]); // second last and padding block
if let Err(decrypted_pt) = key.decryption_oracle(&tampered_ct) {
let iv = xor::xor(&pt_0, &decrypted_pt[32..48]).unwrap();
println!("Ah! The key is recovered: {:?}", iv);
}
}
struct Key(Vec<u8>);
impl Key {
pub fn new() -> Key {
let key = random_bytes(16);
println!("Whisper: key is {:?}", key);
Key(key)
}
pub fn encryption_oracle(&self, input: &[u8]) -> Vec<u8> {
// quote out specical character ('=' and ';') in the input
// by replace them with "%3d" and "%3b" respectively
let mut cleaned_input: Vec<u8> = vec![];
for byte in input.iter() {
match byte {
b';' => cleaned_input.extend_from_slice(b"%3b"),
b'=' => cleaned_input.extend_from_slice(b"%3d"),
_ => cleaned_input.push(*byte),
};
}
// NOTE: this is where we feed key into CBC as its iv
let cbc_cipher = AES_128_CBC::from_iv(&self.0);
cbc_cipher.encrypt(&self.0, &cleaned_input)
}
// returns true (which pass the admin=true test) or Error with invalid plaintext `Vec<u8>`
pub fn decryption_oracle(&self, ct: &[u8]) -> Result<bool, Vec<u8>> {
let cbc_cipher = AES_128_CBC::from_iv(&self.0);
let pt = cbc_cipher.decrypt(&self.0, ct);
if String::from_utf8(pt.clone()).is_err() {
return Err(pt);
}
Ok(pt.windows(11).any(|x| x == b";admin=true"))
}
}
|
pub mod caputre_packets;
pub mod crypt;
pub mod decrypter;
pub mod mem;
mod packet;
use std::sync::mpsc::{channel, Receiver};
use std::time::Instant;
pub use packet::Direction;
pub use packet::PoePacket;
#[derive(Debug)]
pub enum Error {
NoKey,
KeyWrongSize,
KeyDiffer,
WrongKey,
NoPermission,
PNetError,
UnexpectedPacket,
StateBroke,
CanNotDeserialize,
}
pub enum Control {
Shutdown,
KeyPair([u8; 32], [u8; 8], [u8; 8]),
}
pub fn decrypted_stream() -> Receiver<PoePacket> {
let (packet_tx, packet_rx) = channel();
let packet = encrypted_stream().unwrap();
std::thread::Builder::new()
.name("decrypted_stream thread".to_string())
.spawn(move || {
let mut session = crypt::Session::new();
loop {
let mut packet_message = packet.recv();
match packet_message {
Ok(ref mut packet) => {
let mut tries = 0;
'inner: loop {
let result = session.process(packet);
match result {
Ok(()) => {
packet_tx.send(packet.clone()).unwrap();
break;
}
Err(Error::NoKey) | Err(Error::WrongKey) => {
let start = Instant::now();
// search memory for key
let pid = mem::get_process_pid("PathOfExile_x64.exe");
let prog = mem::ProcessMemory::new(pid);
let tmp_keys = prog.search(&b"expand 32-byte k"[..], 64, 1024);
let mut keys = Vec::new();
for key in tmp_keys {
let mut buffer = [0u8; 64];
buffer.copy_from_slice(&key[..64]);
keys.push(buffer);
}
let duration = start.elapsed();
log::info!("Time elapsed while searching keys: {:?}", duration);
for i in 0..keys.len() / 2 {
if tries <= i {
let key1 = &keys.get(i * 2);
let key2 = &keys.get(i * 2 + 1);
match (key1, key2) {
(Some(key1), Some(key2)) => {
match session.add_keypair(&key1[..], &key2[..])
{
Ok(()) => {
tries += 1;
continue 'inner;
}
Err(_) => {}
}
}
_ => {}
}
}
}
panic!("could not find key");
}
Err(e) => {
panic!("Error: {:?}", e);
}
}
}
}
Err(e) => {
log::warn!("Error: {}", e);
break;
}
}
}
})
.unwrap();
packet_rx
}
// returns handles, sender to shutdown threads and receiver to get packets
pub fn encrypted_stream() -> Result<Receiver<packet::PoePacket>, Error> {
let (capture_tx, capture_rx) = channel();
let (packet_tx, packet_rx) = channel();
// TODO: Arc::new(AtomicBool::new(false)); to stop capture threads
caputre_packets::capture_from_interface(capture_tx)?;
Ok(packet_rx)
}
|
// xfail-stage0
// -*- rust -*-
use std;
import std._uint;
fn main() {
check (_uint.next_power_of_two(0u) == 0u);
check (_uint.next_power_of_two(1u) == 1u);
check (_uint.next_power_of_two(2u) == 2u);
check (_uint.next_power_of_two(3u) == 4u);
check (_uint.next_power_of_two(4u) == 4u);
check (_uint.next_power_of_two(5u) == 8u);
check (_uint.next_power_of_two(6u) == 8u);
check (_uint.next_power_of_two(7u) == 8u);
check (_uint.next_power_of_two(8u) == 8u);
check (_uint.next_power_of_two(9u) == 16u);
check (_uint.next_power_of_two(10u) == 16u);
check (_uint.next_power_of_two(11u) == 16u);
check (_uint.next_power_of_two(12u) == 16u);
check (_uint.next_power_of_two(13u) == 16u);
check (_uint.next_power_of_two(14u) == 16u);
check (_uint.next_power_of_two(15u) == 16u);
check (_uint.next_power_of_two(16u) == 16u);
check (_uint.next_power_of_two(17u) == 32u);
check (_uint.next_power_of_two(18u) == 32u);
check (_uint.next_power_of_two(19u) == 32u);
check (_uint.next_power_of_two(20u) == 32u);
check (_uint.next_power_of_two(21u) == 32u);
check (_uint.next_power_of_two(22u) == 32u);
check (_uint.next_power_of_two(23u) == 32u);
check (_uint.next_power_of_two(24u) == 32u);
check (_uint.next_power_of_two(25u) == 32u);
check (_uint.next_power_of_two(26u) == 32u);
check (_uint.next_power_of_two(27u) == 32u);
check (_uint.next_power_of_two(28u) == 32u);
check (_uint.next_power_of_two(29u) == 32u);
check (_uint.next_power_of_two(30u) == 32u);
check (_uint.next_power_of_two(31u) == 32u);
check (_uint.next_power_of_two(32u) == 32u);
check (_uint.next_power_of_two(33u) == 64u);
check (_uint.next_power_of_two(34u) == 64u);
check (_uint.next_power_of_two(35u) == 64u);
check (_uint.next_power_of_two(36u) == 64u);
check (_uint.next_power_of_two(37u) == 64u);
check (_uint.next_power_of_two(38u) == 64u);
check (_uint.next_power_of_two(39u) == 64u);
}
|
use super::*;
use proptest::strategy::Strategy;
#[test]
fn without_big_integer_returns_true() {
run!(
|arc_process| {
(
strategy::term::integer::big(arc_process.clone()),
strategy::term(arc_process.clone())
.prop_filter("Right must not be a big integer", |v| !v.is_boxed_bigint()),
)
},
|(left, right)| {
prop_assert_eq!(result(left, right), true.into());
Ok(())
},
);
}
#[test]
fn with_same_big_integer_returns_false() {
run!(
|arc_process| strategy::term::integer::big(arc_process.clone()),
|operand| {
prop_assert_eq!(result(operand, operand), false.into());
Ok(())
},
);
}
#[test]
fn with_different_big_integer_right_returns_true() {
run!(
|arc_process| {
(
strategy::term::integer::big(arc_process.clone()),
strategy::term::integer::big(arc_process.clone()),
)
.prop_filter("Right and left must be different", |(left, right)| {
left != right
})
},
|(left, right)| {
prop_assert_eq!(result(left, right), true.into());
Ok(())
},
);
}
|
pub use self::static_prop_dict::StaticPropDict;
pub use self::game::*;
mod static_prop_dict;
mod game;
|
//! This crate provides barebone, slice-based parsers for extracting [request
//! line](https://tools.ietf.org/html/rfc7230#section-3.1.1) components and [header
//! fields](https://tools.ietf.org/html/rfc7230#section-3.2) from HTTP requests.
//!
//! In general, components are extracted along defined delimiters, but further processing
//! and syntax validation is left to higher layers.
//!
//! ## Example
//!
//! ```rust
//! use uhttp_request::{RequestLine, Headers};
//!
//! let req = b"GET /abc?k=v HTTP/1.1\r\nHost: example.com\r\nAccept: text/*\r\n\r\nbody";
//!
//! let (reqline, rest) = RequestLine::new(req).unwrap();
//! assert_eq!(reqline.method, "GET");
//! assert_eq!(reqline.target, "/abc?k=v");
//! assert_eq!(reqline.version, "HTTP/1.1");
//!
//! let mut headers = Headers::new(rest);
//!
//! let h = headers.next().unwrap().unwrap();
//! assert_eq!(h.name, "Host");
//! assert_eq!(h.val, b" example.com");
//!
//! let h = headers.next().unwrap().unwrap();
//! assert_eq!(h.name, "Accept");
//! assert_eq!(h.val, b" text/*");
//!
//! assert!(headers.next().is_none());
//!
//! let rest = headers.into_inner();
//! assert_eq!(rest, b"body");
//! ```
#![feature(field_init_shorthand)]
#![feature(conservative_impl_trait)]
extern crate memchr;
use memchr::memchr;
/// Errors that may occur when processing request header.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum Error {
/// Unexpected EOF.
Partial,
/// Malformed syntax.
Syntax,
}
/// Specialized result using custom `Error`.
pub type Result<T> = std::result::Result<T, Error>;
/// A "Request-Line" [RFC7230§3.1.1] that begins an HTTP request.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct RequestLine<'a> {
/// Request method on target resource.
///
/// This is guaranteed to be free of spaces but is not guaranteed to be free of other
/// whitespace or otherwise syntactically correct.
pub method: &'a str,
/// Target resource of request.
///
/// This is guaranteed to be free of spaces but is not guaranteed to be free of other
/// whitespace or otherwise syntactically correct.
pub target: &'a str,
/// HTTP protocol version of request.
///
/// This is guaranteed to be free of spaces but is not guaranteed to be free of other
/// whitespace or otherwise syntactically correct.
pub version: &'a str,
}
impl<'a> RequestLine<'a> {
/// Try to parse the given bytes into `RequestLine` components.
///
/// On success, return `Ok((rl, rest))`, where `rl` is the `RequestLine` and `rest` is
/// a slice that begins directly after the Request-Line terminating CRLF.
pub fn new(buf: &'a [u8]) -> Result<(Self, &'a [u8])> {
// Ignore leading empty lines [RFC7230§3.5].
let start = skip_empty_lines(buf)?;
// Retrieve contents of initial line and split by spaces.
let (line, rest) = next_line(start)?;
let line = std::str::from_utf8(line).map_err(|_| Error::Syntax)?;
let mut chunks = line.split(' ');
let method = chunks.next().ok_or(Error::Syntax)?;
let target = chunks.next().ok_or(Error::Syntax)?;
let version = chunks.next().ok_or(Error::Syntax)?;
if chunks.next().is_some() {
return Err(Error::Syntax);
}
Ok((RequestLine { method, target, version }, rest))
}
}
/// An HTTP request header field [RFC7230§3.2].
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub struct Header<'a> {
/// Header name, with surrounding whitespace trimmed.
///
/// This is not guaranteed to be free of internal whitespace or otherwise
/// syntactically correct.
pub name: &'a str,
/// Raw header value.
pub val: &'a [u8],
}
/// Iterator over all header fields in a request.
pub struct Headers<'a>(&'a [u8]);
impl<'a> Headers<'a> {
/// Create a new `Headers` iterator over the given bytes, which must begin directly
/// after the Request-Line CRLF.
pub fn new(s: &'a [u8]) -> Self {
Headers(s)
}
/// Retrieve the remaining bytes that haven't been processed.
///
/// If called after the last yielded header, this slice will contain the beginning of
/// the request body.
pub fn into_inner(self) -> &'a [u8] { self.0 }
}
impl<'a> Iterator for Headers<'a> {
type Item = Result<Header<'a>>;
fn next(&mut self) -> Option<Self::Item> {
let (line, rest) = match next_line(self.0) {
Ok(x) => x,
Err(e) => return Some(Err(e)),
};
self.0 = rest;
// Headers are terminated by an empty line [RFC7230§3].
if line.is_empty() {
return None;
}
let (name, val) = match memchr(b':', line) {
Some(idx) => line.split_at(idx),
None => return Some(Err(Error::Syntax)),
};
let name = match std::str::from_utf8(name) {
Ok(s) => s.trim(),
Err(_) => return Some(Err(Error::Syntax)),
};
// Name must be nonempty [RFC7230§3.2].
if name.is_empty() {
return Some(Err(Error::Syntax));
}
// Skip past ':'.
let val = &val[1..];
Some(Ok(Header { name, val }))
}
}
/// Consume CRLFs until the first non-CRLF character, returning a slice beginning at that
/// character.
fn skip_empty_lines<'a>(mut bytes: &'a [u8]) -> Result<&'a [u8]> {
loop {
match check_crlf(bytes) {
Ok(rest) => bytes = rest,
Err(Error::Partial) => return Err(Error::Partial),
Err(Error::Syntax) => return Ok(bytes),
}
}
}
/// Retrieve the next chunk in the request, up to and not including the nearest CRLF.
fn next_line<'a>(bytes: &'a [u8]) -> Result<(&'a [u8], &'a [u8])> {
let (line, rest) = match memchr(b'\r', bytes) {
Some(idx) => bytes.split_at(idx),
None => return Err(Error::Partial),
};
let rest = check_crlf(rest)?;
Ok((line, rest))
}
/// Check if the given slice begins with CRLF and, if it does, return the slice
/// immediately after.
fn check_crlf<'a>(bytes: &'a [u8]) -> Result<&'a [u8]> {
if bytes.len() < 2 {
Err(Error::Partial)
} else if bytes.starts_with(&b"\r\n"[..]) {
// Skip over CRLF.
Ok(&bytes[2..])
} else {
Err(Error::Syntax)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_request_line() {
// Some testcases from httparse, MIT Copyright (c) 2015 Sean McArthur.
let (req, rest) = RequestLine::new(b"GET / HTTP/1.1\r\n\r\n").unwrap();
assert_eq!(req.method, "GET");
assert_eq!(req.target, "/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(rest, &b"\r\n"[..]);
let (req, rest) = RequestLine::new(
b"GET / HTTP/1.1\r\nHost: foo.com\r\nCookie: \r\n\r\n"
).unwrap();
assert_eq!(req.method, "GET");
assert_eq!(req.target, "/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(rest, &b"Host: foo.com\r\nCookie: \r\n\r\n"[..]);
let (req, rest) = RequestLine::new(
b"GET / HTTP/1.1\r\nA: A\r\nB: B\r\nC: C\r\nD: D\r\n\r\n"
).unwrap();
assert_eq!(req.method, "GET");
assert_eq!(req.target, "/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(rest, &b"A: A\r\nB: B\r\nC: C\r\nD: D\r\n\r\n"[..]);
let (req, rest) = RequestLine::new(
b"GET / HTTP/1.1\r\nHost: foo.com\r\nUser-Agent: \xe3\x81\xb2\xe3/1.0\r\n\r\n",
).unwrap();
assert_eq!(req.method, "GET");
assert_eq!(req.target, "/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(rest, &b"Host: foo.com\r\nUser-Agent: \xe3\x81\xb2\xe3/1.0\r\n\r\n"[..]);
let (req, rest) = RequestLine::new(b"GET / HTTP/1.1\r\n\r").unwrap();
assert_eq!(req.method, "GET");
assert_eq!(req.target, "/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(rest, &b"\r"[..]);
assert_eq!(RequestLine::new(&b"GET / HTTP/1.1\nHost: foo.bar\n\n"[..]),
Err(Error::Partial));
let (req, rest) = RequestLine::new(&b"\r\n\r\nGET / HTTP/1.1\r\n\r\n"[..]).unwrap();
assert_eq!(req.method, "GET");
assert_eq!(req.target, "/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(rest, &b"\r\n"[..]);
assert_eq!(RequestLine::new(&b"\n\nGET / HTTP/1.1\n\n"[..]), Err(Error::Partial));
assert_eq!(RequestLine::new(&b"GET\n/ HTTP/1.1\r\nHost: foo.bar\r\n\r\n"[..]),
Err(Error::Syntax));
let (req, rest) = RequestLine::new(b"\n\n\nGET / HTTP/1.1\r\n\n").unwrap();
assert_eq!(req.method, "\n\n\nGET");
assert_eq!(req.target, "/");
assert_eq!(req.version, "HTTP/1.1");
assert_eq!(rest, &b"\n"[..]);
let (req, rest) = RequestLine::new(b"\r\n\nGET / H\tTTP/1.1\r\n\n").unwrap();
assert_eq!(req.method, "\nGET");
assert_eq!(req.target, "/");
assert_eq!(req.version, "H\tTTP/1.1");
assert_eq!(rest, &b"\n"[..]);
assert_eq!(RequestLine::new(b"\r\n\rGET / HTTP/1.1\r\n\n"), Err(Error::Syntax));
assert_eq!(RequestLine::new(b"GET /some path/ HTTP/1.1\r\n\r"), Err(Error::Syntax));
assert_eq!(RequestLine::new(b"GET\r\n"), Err(Error::Syntax));
assert_eq!(RequestLine::new(b"GET /\r\n"), Err(Error::Syntax));
assert_eq!(RequestLine::new(b"GET / HTTP/1.1 \r\n"), Err(Error::Syntax));
assert_eq!(RequestLine::new(b"GET / \r\n"), Err(Error::Syntax));
assert_eq!(RequestLine::new(b"GET / HTTP/1.1"), Err(Error::Partial));
assert_eq!(RequestLine::new(b"GET / HTTP/1.1\r"), Err(Error::Partial));
assert_eq!(RequestLine::new(b"GET / HTTP/1.1\n"), Err(Error::Partial));
}
#[test]
fn test_headers() {
let mut h = Headers::new(
b"Content-Type: text/html\r\nContent-Length: 1337\r\n\r\nbody text"
);
let n = h.next().unwrap().unwrap();
assert_eq!(n.name, "Content-Type");
assert_eq!(n.val, b" text/html");
let n = h.next().unwrap().unwrap();
assert_eq!(n.name, "Content-Length");
assert_eq!(n.val, b" 1337");
assert!(h.next().is_none());
assert_eq!(h.into_inner(), b"body text");
let mut h = Headers::new(
b" Content-Type \t\t: text/html\r\n\r\nbody text"
);
let n = h.next().unwrap().unwrap();
assert_eq!(n.name, "Content-Type");
assert_eq!(n.val, b" text/html");
assert!(h.next().is_none());
assert_eq!(h.into_inner(), b"body text");
let mut h = Headers::new(
b"\tContent-Type \t\t: text/html\r\n\r\n"
);
let n = h.next().unwrap().unwrap();
assert_eq!(n.name, "Content-Type");
assert_eq!(n.val, b" text/html");
assert!(h.next().is_none());
assert_eq!(h.into_inner(), b"");
let mut h = Headers::new(
b" Content-Type \t\t: text/html\n"
);
let n = h.next().unwrap();
assert_eq!(n, Err(Error::Partial));
}
#[test]
fn test_skip_empty_lines() {
assert_eq!(skip_empty_lines(b"GET"), Ok(&b"GET"[..]));
assert_eq!(skip_empty_lines(b"\r\n\r\nGET"), Ok(&b"GET"[..]));
assert_eq!(skip_empty_lines(b"\r\n\rGET"), Ok(&b"\rGET"[..]));
assert_eq!(skip_empty_lines(b"\nGET"), Ok(&b"\nGET"[..]));
}
#[test]
fn test_next_line() {
assert_eq!(next_line(b"abc\r\ndef"), Ok((&b"abc"[..], &b"def"[..])));
assert_eq!(next_line(b"abc def\r\nghi"), Ok((&b"abc def"[..], &b"ghi"[..])));
assert_eq!(next_line(b"abc\r\n"), Ok((&b"abc"[..], &b""[..])));
assert_eq!(next_line(b"abc"), Err(Error::Partial));
assert_eq!(next_line(b"abc\n"), Err(Error::Partial));
assert_eq!(next_line(b"\r\ndef"), Ok((&b""[..], &b"def"[..])));
assert_eq!(next_line(b""), Err(Error::Partial));
}
#[test]
fn test_check_crlf() {
assert_eq!(check_crlf(b"\r\nabc"), Ok(&b"abc"[..]));
assert_eq!(check_crlf(b"\r"), Err(Error::Partial));
assert_eq!(check_crlf(b""), Err(Error::Partial));
assert_eq!(check_crlf(b"\n"), Err(Error::Partial));
assert_eq!(check_crlf(b"\nabc"), Err(Error::Syntax));
assert_eq!(check_crlf(b"abc\r\n"), Err(Error::Syntax));
}
}
|
#[doc = "Reader of register PRUART"]
pub type R = crate::R<u32, super::PRUART>;
#[doc = "Reader of field `R0`"]
pub type R0_R = crate::R<bool, bool>;
#[doc = "Reader of field `R1`"]
pub type R1_R = crate::R<bool, bool>;
#[doc = "Reader of field `R2`"]
pub type R2_R = crate::R<bool, bool>;
#[doc = "Reader of field `R3`"]
pub type R3_R = crate::R<bool, bool>;
#[doc = "Reader of field `R4`"]
pub type R4_R = crate::R<bool, bool>;
#[doc = "Reader of field `R5`"]
pub type R5_R = crate::R<bool, bool>;
#[doc = "Reader of field `R6`"]
pub type R6_R = crate::R<bool, bool>;
#[doc = "Reader of field `R7`"]
pub type R7_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - UART Module 0 Peripheral Ready"]
#[inline(always)]
pub fn r0(&self) -> R0_R {
R0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - UART Module 1 Peripheral Ready"]
#[inline(always)]
pub fn r1(&self) -> R1_R {
R1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - UART Module 2 Peripheral Ready"]
#[inline(always)]
pub fn r2(&self) -> R2_R {
R2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - UART Module 3 Peripheral Ready"]
#[inline(always)]
pub fn r3(&self) -> R3_R {
R3_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - UART Module 4 Peripheral Ready"]
#[inline(always)]
pub fn r4(&self) -> R4_R {
R4_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - UART Module 5 Peripheral Ready"]
#[inline(always)]
pub fn r5(&self) -> R5_R {
R5_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - UART Module 6 Peripheral Ready"]
#[inline(always)]
pub fn r6(&self) -> R6_R {
R6_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - UART Module 7 Peripheral Ready"]
#[inline(always)]
pub fn r7(&self) -> R7_R {
R7_R::new(((self.bits >> 7) & 0x01) != 0)
}
}
|
use super::simple8b;
use integer_encoding::*;
use std::error::Error;
// Encoding describes the type of encoding used by an encoded timestamp block.
enum Encoding {
Uncompressed = 0,
Simple8b = 1,
Rle = 2,
}
/// encode encodes a vector of signed integers into a slice of bytes.
///
/// To maximise compression, the provided vector should be sorted in ascending
/// order. First deltas between the integers are determined, then further
/// encoding is potentially carried out. If all the deltas are the same the
/// block can be encoded using RLE. If not, as long as the deltas are not bigger
/// than simple8b::MAX_VALUE they can be encoded using simple8b.
pub fn encode(src: &[i64], dst: &mut Vec<u8>) -> Result<(), Box<dyn Error>> {
dst.clear(); // reset buffer.
if src.is_empty() {
return Ok(());
}
let mut max: u64 = 0;
let mut deltas = i64_to_u64_vector(src);
if deltas.len() > 1 {
for i in (1..deltas.len()).rev() {
deltas[i] = deltas[i].wrapping_sub(deltas[i - 1]);
if deltas[i] > max {
max = deltas[i];
}
}
let mut use_rle = true;
for i in 2..deltas.len() {
if deltas[1] != deltas[i] {
use_rle = false;
break;
}
}
// Encode with RLE if possible.
if use_rle {
encode_rle(deltas[0], deltas[1], deltas.len() as u64, dst);
// 4 high bits of first byte used for the encoding type
dst[0] |= (Encoding::Rle as u8) << 4;
return Ok(());
}
}
// write block uncompressed
if max > simple8b::MAX_VALUE {
let cap = 1 + (deltas.len() * 8); // 8 bytes per value plus header byte
if dst.capacity() < cap {
dst.reserve_exact(cap - dst.capacity());
}
dst.push((Encoding::Uncompressed as u8) << 4);
for delta in &deltas {
dst.extend_from_slice(&delta.to_be_bytes());
}
return Ok(());
}
// Compress with simple8b
// First find the divisor for the deltas.
let mut div: u64 = 1_000_000_000_000;
for delta in deltas.iter().skip(1) {
if div <= 1 {
break;
}
while div > 1 && delta % div != 0 {
div /= 10;
}
}
if div > 1 {
// apply only if expense of division is warranted
for delta in deltas.iter_mut().skip(1) {
*delta /= div
}
}
// first 4 high bits used for encoding type
dst.push((Encoding::Simple8b as u8) << 4);
dst[0] |= ((div as f64).log10()) as u8; // 4 low bits used for log10 divisor
dst.extend_from_slice(&deltas[0].to_be_bytes()); // encode first value
simple8b::encode(&deltas[1..], dst)
}
// i64_to_u64_vector converts a Vec<i64> to Vec<u64>.
// TODO(edd): this is expensive as it copies. There are cheap
// but unsafe alternatives to look into such as std::mem::transmute
fn i64_to_u64_vector(src: &[i64]) -> Vec<u64> {
src.iter().map(|x| *x as u64).collect::<Vec<u64>>()
}
// encode_rle encodes the value v, delta and count into dst.
//
// v should be the first element of a sequence, delta the difference that each
// value in the sequence differs by, and count the total number of values in the
// sequence.
fn encode_rle(v: u64, delta: u64, count: u64, dst: &mut Vec<u8>) {
use super::MAX_VAR_INT_64;
// Keep a byte back for the scaler.
dst.push(0);
let mut n = 1;
// write the first value in as a byte array.
dst.extend_from_slice(&v.to_be_bytes());
n += 8;
// check delta's divisor
let mut div: u64 = 1_000_000_000_000;
while div > 1 && delta % div != 0 {
div /= 10;
}
if dst.len() <= n + MAX_VAR_INT_64 {
dst.resize(n + MAX_VAR_INT_64, 0);
}
// 4 low bits are the log10 divisor.
if div > 1 {
// calculate and store the number of trailing 0s in the divisor.
// e.g., 100_000 would be stored as 5.
let scaler = ((div as f64).log10()) as u8;
assert!(scaler <= 15);
dst[0] |= scaler; // Set the scaler on low 4 bits of first byte.
n += (delta / div).encode_var(&mut dst[n..]);
} else {
n += delta.encode_var(&mut dst[n..]);
}
if dst.len() - n <= MAX_VAR_INT_64 {
dst.resize(n + MAX_VAR_INT_64, 0);
}
// finally, encode the number of times the delta is repeated.
n += count.encode_var(&mut dst[n..]);
dst.truncate(n);
}
/// decode decodes a slice of bytes encoded using encode back into a
/// vector of signed integers.
pub fn decode(src: &[u8], dst: &mut Vec<i64>) -> Result<(), Box<dyn Error>> {
if src.is_empty() {
return Ok(());
}
let encoding = &src[0] >> 4;
match encoding {
encoding if encoding == Encoding::Uncompressed as u8 => {
decode_uncompressed(&src[1..], dst) // first byte not used
}
encoding if encoding == Encoding::Rle as u8 => decode_rle(src, dst),
encoding if encoding == Encoding::Simple8b as u8 => decode_simple8b(src, dst),
_ => Err(From::from("invalid block encoding")),
}
}
// decode_uncompressed writes the binary encoded values in src into dst.
fn decode_uncompressed(src: &[u8], dst: &mut Vec<i64>) -> Result<(), Box<dyn Error>> {
if src.is_empty() || src.len() & 0x7 != 0 {
return Err(From::from("invalid uncompressed block length"));
}
let count = src.len() / 8;
if dst.capacity() < count {
dst.reserve_exact(count - dst.capacity());
}
let mut i = 0;
let mut prev = 0;
let mut buf: [u8; 8] = [0; 8];
while i < src.len() {
buf.copy_from_slice(&src[i..i + 8]);
prev += i64::from_be_bytes(buf);
dst.push(prev); // N.B - signed integer...
i += 8;
}
Ok(())
}
// decode_rle decodes an RLE encoded slice containing only unsigned into the
// destination vector.
fn decode_rle(src: &[u8], dst: &mut Vec<i64>) -> Result<(), Box<dyn Error>> {
if src.len() < 9 {
return Err(From::from("not enough data to decode using RLE"));
}
// calculate the scaler from the lower 4 bits of the first byte.
let scaler = 10_u64.pow((src[0] & 0b0000_1111) as u32);
let mut i = 1;
// TODO(edd): this should be possible to do in-place without copy.
let mut a: [u8; 8] = [0; 8];
a.copy_from_slice(&src[i..i + 8]);
i += 8;
let (mut delta, n) = u64::decode_var(&src[i..]).ok_or("unable to decode delta")?;
i += n;
delta *= scaler;
let (count, _n) = usize::decode_var(&src[i..]).ok_or("unable to decode count")?;
if dst.capacity() < count {
dst.reserve_exact(count - dst.capacity());
}
let mut first = i64::from_be_bytes(a);
for _ in 0..count {
dst.push(first);
first = first.wrapping_add(delta as i64);
}
Ok(())
}
fn decode_simple8b(src: &[u8], dst: &mut Vec<i64>) -> Result<(), Box<dyn Error>> {
if src.len() < 9 {
return Err(From::from("not enough data to decode packed timestamp"));
}
let scaler = 10_u64.pow((src[0] & 0b0000_1111) as u32);
// TODO(edd): pre-allocate res by counting bytes in encoded slice?
let mut res = vec![];
let mut buf: [u8; 8] = [0; 8];
buf.copy_from_slice(&src[1..9]);
dst.push(i64::from_be_bytes(buf));
simple8b::decode(&src[9..], &mut res);
let mut next = dst[dst.len() - 1];
if scaler > 1 {
// TODO(edd): fix this. It's copying, which is slowwwwwwwww.
for v in &res {
next += (v * scaler) as i64;
dst.push(next);
}
return Ok(());
}
// TODO(edd): fix this. It's copying, which is slowwwwwwwww.
for v in &res {
next += *v as i64;
dst.push(next);
}
Ok(())
}
#[cfg(test)]
#[allow(clippy::unreadable_literal)]
mod tests {
use super::*;
#[test]
fn encode_no_values() {
let src: Vec<i64> = vec![];
let mut dst = vec![];
// check for error
encode(&src, &mut dst).expect("failed to encode src");
// verify encoded no values.
assert_eq!(dst.len(), 0);
}
#[test]
fn encode_uncompressed() {
let src: Vec<i64> = vec![-1000, 0, simple8b::MAX_VALUE as i64, 213123421];
let mut dst = vec![];
let exp = src.clone();
encode(&src, &mut dst).expect("failed to encode");
// verify uncompressed encoding used
assert_eq!(&dst[0] >> 4, Encoding::Uncompressed as u8);
let mut got = vec![];
decode(&dst, &mut got).expect("failed to decode");
// verify got same values back
assert_eq!(got, exp);
}
#[test]
fn encode_rle() {
struct Test {
name: String,
input: Vec<i64>,
}
let tests = vec![
Test {
name: String::from("no delta positive"),
input: vec![123; 8],
},
Test {
name: String::from("no delta negative"),
input: vec![-2398749823764923; 10000],
},
Test {
name: String::from("no delta negative"),
input: vec![-345632452354; 1000],
},
Test {
name: String::from("delta positive 1"),
input: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
},
Test {
name: String::from("delta positive 2000"),
input: vec![100, 2100, 4100, 6100, 8100, 10100, 12100, 14100],
},
Test {
name: String::from("delta negative"),
input: vec![-350, -200, -50],
},
Test {
name: String::from("delta mixed"),
input: vec![-35000, -5000, 25000, 55000],
},
Test {
name: String::from("delta descending"),
input: vec![100, 50, 0, -50, -100, -150],
},
];
for test in tests {
let mut dst = vec![];
let src = test.input.clone();
let exp = test.input;
encode(&src, &mut dst).expect("failed to encode");
// verify RLE encoding used
assert_eq!(&dst[0] >> 4, Encoding::Rle as u8);
let mut got = vec![];
decode(&dst, &mut got).expect("failed to decode");
// verify got same values back
assert_eq!(got, exp, "{}", test.name);
}
}
#[test]
fn encode_simple8b() {
struct Test {
name: String,
input: Vec<i64>,
}
let tests = vec![
Test {
name: String::from("positive"),
input: vec![1, 11, 3124, 123543256, 2398567984273478],
},
Test {
name: String::from("negative"),
input: vec![-109290, -1234, -123, -12],
},
Test {
name: String::from("mixed"),
input: vec![-109290, -1234, -123, -12, 0, 0, 0, 1234, 44444, 4444444],
},
];
for test in tests {
let mut dst = vec![];
let src = test.input.clone();
let exp = test.input;
encode(&src, &mut dst).expect("failed to encode");
// verify Simple8b encoding used
assert_eq!(&dst[0] >> 4, Encoding::Simple8b as u8);
let mut got = vec![];
decode(&dst, &mut got).expect("failed to decode");
// verify got same values back
assert_eq!(got, exp, "{}", test.name);
}
}
}
|
mod decoder;
fn main() {
let decoder = decoder::Decoder;
let mut harness = toml_test_harness::DecoderHarness::new(decoder);
harness
.ignore([
"valid/spec/float-0.toml", // Test issue; `Decoder` turns `6.626e-34` into `0.0`
// Unreleased
"valid/string/escape-esc.toml",
"valid/string/hex-escape.toml",
"valid/datetime/no-seconds.toml",
"valid/inline-table/newline.toml",
])
.unwrap();
harness.test();
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! sled_key_space defines several key-value types to be used in sled::Tree, as an raft storage impl.
use std::fmt::Debug;
use std::fmt::Display;
use std::ops::Bound;
use std::ops::RangeBounds;
use anyerror::AnyError;
use sled::IVec;
use crate::SledBytesError;
use crate::SledOrderedSerde;
use crate::SledSerde;
/// Defines a key space in sled::Tree that has its own key value type.
/// And a prefix that is used to distinguish keys from different spaces in a SledTree.
pub trait SledKeySpace {
/// Prefix is a unique u8 that is prepended before the serialized key, to identify a namespace in sled::Tree.
const PREFIX: u8;
/// The for human name of this key-value type.
const NAME: &'static str;
/// Type for key.
type K: SledOrderedSerde + Display + Debug;
/// Type for value.
type V: SledSerde + Debug;
fn serialize_key(k: &Self::K) -> Result<sled::IVec, SledBytesError> {
let b = <Self::K as SledOrderedSerde>::ser(k)?;
let x = b.as_ref();
let mut buf = Vec::with_capacity(1 + x.len());
buf.push(Self::PREFIX);
buf.extend_from_slice(x);
Ok(buf.into())
}
fn deserialize_key<T: AsRef<[u8]>>(iv: T) -> Result<Self::K, SledBytesError> {
let b = iv.as_ref();
if b[0] != Self::PREFIX {
return Err(SledBytesError::new(&AnyError::error("invalid prefix")));
}
<Self::K as SledOrderedSerde>::de(&b[1..])
}
fn serialize_value(v: &Self::V) -> Result<sled::IVec, SledBytesError> {
v.ser()
}
fn deserialize_value<T: AsRef<[u8]>>(iv: T) -> Result<Self::V, SledBytesError> {
Self::V::de(iv)
}
/// Convert range of user key to range of sled::IVec for query.
fn serialize_range<R>(range: &R) -> Result<(Bound<IVec>, Bound<IVec>), SledBytesError>
where R: RangeBounds<Self::K> {
let s = range.start_bound();
let e = range.end_bound();
let s = Self::serialize_bound(s, "left")?;
let e = Self::serialize_bound(e, "right")?;
Ok((s, e))
}
/// Convert user key range bound to sled::IVec bound.
/// A u8 prefix is prepended to the bound value and an open bound is converted to a namespaced bound.
/// E.g., use the [PREFIX] as the left side closed bound,
/// and use the [PREFIX+1] as the right side open bound.
fn serialize_bound(v: Bound<&Self::K>, dir: &str) -> Result<Bound<sled::IVec>, SledBytesError> {
let res = match v {
Bound::Included(v) => Bound::Included(Self::serialize_key(v)?),
Bound::Excluded(v) => Bound::Excluded(Self::serialize_key(v)?),
Bound::Unbounded => {
if dir == "left" {
Bound::Included(IVec::from(&[Self::PREFIX]))
} else {
Bound::Excluded(IVec::from(&[Self::PREFIX + 1]))
}
}
};
Ok(res)
}
}
|
use std::f64::NAN;
pub fn pli_eq(x0: f64, dx: f64, y: Box<[f64]>) -> Box<dyn Fn(f64)->f64> {
return Box::new(move |x: f64| -> f64 {
let k = ((x-x0)/dx) as usize;
let y1 = match y.get(k) {Some(value)=>*value, None=>return NAN};
let y2 = match y.get(k+1) {Some(value)=>*value, None=>return NAN};
let m = (y2-y1)/dx;
return m*(x-x0-(k as f64)*dx)+y1;
});
}
|
use std::fs::File;
use std::io::{ErrorKind, Read};
use std::env;
use std::path::Path;
mod meta;
mod parser;
mod render;
fn main() {
let args: Vec<_> = env::args().collect();
let program = args[0].clone();
let mut opts = getopts::Options::new();
opts.optopt("o", "output", "output dir", "output dir");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(_) => {
println!("{}", opts.short_usage(&program));
return;
}
};
let output_file_path = matches.opt_str("o");
let source_files = matches.free;
for src in source_files {
let path = Path::new(&src);
let file = File::open(&path);
let mut input = match file {
Ok(f) => f,
Err(error) => match error.kind() {
ErrorKind::NotFound => panic!("File not found"),
other_error => panic!("There was a problem opening the file: {:?}", other_error),
},
};
let mut text = String::new();
let _ = input.read_to_string(&mut text);
let tokens = parser::tokenize(text);
let members = parser::parse_file(&tokens);
print!("{:#?}", &members);
match &output_file_path{
Some(of) => render::export(&members, &format!("{}{}{}.csv", of, std::path::MAIN_SEPARATOR, path.file_name().unwrap().to_str().unwrap())),
None => render::export(&members, &format!("{}.csv", src))
}
}
}
|
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
use std::collections::HashMap;
use std::io::{copy, Read, stdout};
use reqwest::RequestBuilder;
#[derive(Debug, Deserialize)]
struct Move {
name: String,
}
#[derive(Debug, Deserialize)]
struct PokemonMove {
#[serde(rename = "move")]
move_: Move,
}
#[derive(Debug, Deserialize)]
struct Pokemon {
id: i32,
name: String,
height: i32,
weight: i32,
moves: Vec<PokemonMove>,
}
fn main() {
println!("24 Days of Rust vol. 2 - reqwest");
let mut response =
reqwest::blocking::get("https://httpbin.org/status/418").expect("Failed to send request");
println!("{}", response.status());
for header in response.headers().iter() {
println!("{}", header.0);
}
let mut buf = String::new();
response.read_to_string(&mut buf).expect(
"Failed to read response",
);
println!("{}", buf);
copy(&mut response, &mut stdout()).expect("Failed to read response");
let client = reqwest::blocking::Client::new();
let mut params = HashMap::new();
params.insert("name", "Sir Lancelot");
params.insert("quest", "to seek the Holy Grail");
params.insert("favorite_colour", "blue");
let mut response = client
.post("https://httpbin.org/post")
.form(¶ms)
.send()
.expect("Failed to send request");
let mut buf = String::new();
response.read_to_string(&mut buf).expect(
"Failed to read response",
);
println!("{}", buf);
let mut response = client
.request(reqwest::Method::PUT, "https://httpbin.org/put")
.json(¶ms)
.send()
.expect("Failed to send request");
let mut buf = String::new();
response.read_to_string(&mut buf).expect(
"Failed to read response",
);
println!("{}", buf);
// let response = client
// .get("https://httpbin.org/basic-auth/user/passwd")
// .send()
// .expect("Failed to send request");
// println!("{}", response.status());
//
// let credentials = Basic {
// username: "user".to_string(),
// password: Some("passwd".to_string()),
// };
//
// let response = client
// .get("https://httpbin.org/basic-auth/user/passwd")
// .send()
// .expect("Failed to send request");
// println!("{}", response.status());
let mut response = client
.get("http://pokeapi.co/api/v2/pokemon/111")
.send()
.expect("Failed to send request");
if let Ok(pokemon) = response.json::<Pokemon>() {
println!("{:#?}", pokemon);
}
}
|
//! EV3 specific features
use std::fs;
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt;
use std::fs::File;
use std::os::unix::io::AsRawFd;
use std::path::Path;
use std::rc::Rc;
use crate::driver::DRIVER_PATH;
use crate::utils::OrErr;
use crate::{Attribute, Ev3Result};
/// Color type.
pub type Color = (u8, u8);
/// The led's on top of the EV3 brick.
#[derive(Debug, Clone)]
pub struct Led {
left_red: Attribute,
left_green: Attribute,
right_red: Attribute,
right_green: Attribute,
}
impl Led {
/// Led off.
pub const COLOR_OFF: Color = (0, 0);
/// Led color red
pub const COLOR_RED: Color = (255, 0);
/// Led color green.
pub const COLOR_GREEN: Color = (0, 255);
/// Led color amber.
pub const COLOR_AMBER: Color = (255, 255);
/// Led color orange.
pub const COLOR_ORANGE: Color = (255, 128);
/// LED color yellow.
pub const COLOR_YELLOW: Color = (25, 255);
/// Create a new instance of the `Led` struct.
pub fn new() -> Ev3Result<Led> {
let mut left_red_name = String::new();
let mut left_green_name = String::new();
let mut right_red_name = String::new();
let mut right_green_name = String::new();
let paths = fs::read_dir(Path::new(DRIVER_PATH).join("leds"))?;
for path in paths {
let file_name = path?.file_name();
let name = file_name.to_str().or_err()?.to_owned();
if name.contains(":brick-status") || name.contains(":ev3dev") {
if name.contains("led0:") || name.contains("left:") {
if name.contains("red:") {
left_red_name = name;
} else if name.contains("green:") {
left_green_name = name
}
} else if name.contains("led1:") || name.contains("right:") {
if name.contains("red:") {
right_red_name = name
} else if name.contains("green:") {
right_green_name = name
}
}
}
}
let left_red = Attribute::from_sys_class("leds", left_red_name.as_str(), "brightness")?;
let left_green = Attribute::from_sys_class("leds", left_green_name.as_str(), "brightness")?;
let right_red = Attribute::from_sys_class("leds", right_red_name.as_str(), "brightness")?;
let right_green =
Attribute::from_sys_class("leds", right_green_name.as_str(), "brightness")?;
Ok(Led {
left_red,
left_green,
right_red,
right_green,
})
}
/// Returns the current red value of the left led.
fn get_left_red(&self) -> Ev3Result<u8> {
self.left_red.get()
}
/// Sets the red value of the left led.
fn set_left_red(&self, brightness: u8) -> Ev3Result<()> {
self.left_red.set(brightness)
}
/// Returns the current green value of the left led.
fn get_left_green(&self) -> Ev3Result<u8> {
self.left_green.get()
}
/// Sets the green value of the left led.
fn set_left_green(&self, brightness: u8) -> Ev3Result<()> {
self.left_green.set(brightness)
}
/// Returns the current red value of the right led.
fn get_right_red(&self) -> Ev3Result<u8> {
self.right_red.get()
}
/// Sets the red value of the right led.
fn set_right_red(&self, brightness: u8) -> Ev3Result<()> {
self.right_red.set(brightness)
}
/// Returns the current green value of the right led.
fn get_right_green(&self) -> Ev3Result<u8> {
self.right_green.get()
}
/// Sets the green value of the right led.
fn set_right_green(&self, brightness: u8) -> Ev3Result<()> {
self.right_green.set(brightness)
}
/// Returns the current color value of the left led.
pub fn get_left_color(&self) -> Ev3Result<Color> {
let red = self.get_left_red()?;
let green = self.get_left_green()?;
Ok((red, green))
}
/// Sets the color value of the left led.
pub fn set_left_color(&self, color: Color) -> Ev3Result<()> {
self.set_left_red(color.0)?;
self.set_left_green(color.1)
}
/// Returns the current color value of the right led.
pub fn get_right_color(&self) -> Ev3Result<Color> {
let red = self.get_right_red()?;
let green = self.get_right_green()?;
Ok((red, green))
}
/// Sets the color value of the right led.
pub fn set_right_color(&self, color: Color) -> Ev3Result<()> {
self.set_right_red(color.0)?;
self.set_right_green(color.1)
}
/// Returns the color value of both leds or `None` if they are different.
pub fn get_color(&self) -> Ev3Result<Option<Color>> {
let left = self.get_left_color()?;
let right = self.get_right_color()?;
if left.0 == right.0 && left.1 == right.1 {
Ok(Some(left))
} else {
Ok(None)
}
}
/// Sets the color value of both leds.
pub fn set_color(&self, color: Color) -> Ev3Result<()> {
self.set_left_color(color)?;
self.set_right_color(color)
}
}
const KEY_BUF_LEN: usize = 96;
const EVIOCGKEY: u32 = 2_153_792_792;
/// Helper struct for ButtonFileHandler.
struct FileMapEntry {
pub file: File,
pub buffer_cache: [u8; KEY_BUF_LEN],
}
// Manually implement Debug cause `buffer_cache` does not implement Debug.
impl fmt::Debug for FileMapEntry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FileMapEntry")
.field("file", &self.file)
.finish()
}
}
/// Helper struct for ButtonFileHandler.
#[derive(Debug)]
struct ButtonMapEntry {
pub file_name: String,
pub key_code: u32,
}
/// This implementation depends on the availability of the EVIOCGKEY ioctl
/// to be able to read the button state buffer. See Linux kernel source
/// in /include/uapi/linux/input.h for details.
#[derive(Debug)]
struct ButtonFileHandler {
file_map: HashMap<String, FileMapEntry>,
button_map: HashMap<String, ButtonMapEntry>,
pressed_buttons: HashSet<String>,
}
impl ButtonFileHandler {
/// Create a new instance.
fn new() -> Self {
ButtonFileHandler {
file_map: HashMap::new(),
button_map: HashMap::new(),
pressed_buttons: HashSet::new(),
}
}
/// Add a button the the file handler.
fn add_button(&mut self, name: &str, file_name: &str, key_code: u32) -> Ev3Result<()> {
if !self.file_map.contains_key(file_name) {
let file = File::open(file_name)?;
let buffer_cache = [0u8; KEY_BUF_LEN];
self.file_map
.insert(file_name.to_owned(), FileMapEntry { file, buffer_cache });
}
self.button_map.insert(
name.to_owned(),
ButtonMapEntry {
file_name: file_name.to_owned(),
key_code,
},
);
Ok(())
}
fn get_pressed_buttons(&self) -> HashSet<String> {
self.pressed_buttons.clone()
}
/// Check if a button is pressed.
fn get_button_state(&self, name: &str) -> bool {
self.pressed_buttons.contains(name)
}
/// Check for currently pressed buttons. If the new state differs from the
/// old state, call the appropriate button event handlers.
fn process(&mut self) {
for entry in self.file_map.values_mut() {
unsafe {
libc::ioctl(
entry.file.as_raw_fd(),
(EVIOCGKEY as i32).try_into().unwrap(),
&mut entry.buffer_cache,
);
}
}
self.pressed_buttons.clear();
for (
btn_name,
ButtonMapEntry {
file_name,
key_code,
},
) in self.button_map.iter()
{
let buffer = &self.file_map[file_name].buffer_cache;
if (buffer[(key_code / 8) as usize] & 1 << (key_code % 8)) != 0 {
self.pressed_buttons.insert(btn_name.to_owned());
}
}
}
}
/// Ev3 brick button handler. Opens the corresponding `/dev/input` file handlers.
///
/// This implementation depends on the availability of the EVIOCGKEY ioctl
/// to be able to read the button state buffer. See Linux kernel source
/// in /include/uapi/linux/input.h for details.
///
/// ```no_run
/// use ev3dev_lang_rust::Button;
/// use std::thread;
/// use std::time::Duration;
///
/// # fn main() -> ev3dev_lang_rust::Ev3Result<()> {
/// let button = Button::new()?;
///
/// loop {
/// button.process();
///
/// println!("Is 'up' pressed: {}", button.is_up());
/// println!("Pressed buttons: {:?}", button.get_pressed_buttons());
///
/// thread::sleep(Duration::from_millis(100));
/// }
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Button {
button_handler: Rc<RefCell<ButtonFileHandler>>,
}
impl Button {
/// Ev3 brick button handler. Opens the corresponding `/dev/input` file handlers.
pub fn new() -> Ev3Result<Self> {
let mut handler = ButtonFileHandler::new();
handler.add_button("up", "/dev/input/by-path/platform-gpio_keys-event", 103)?;
handler.add_button("down", "/dev/input/by-path/platform-gpio_keys-event", 108)?;
handler.add_button("left", "/dev/input/by-path/platform-gpio_keys-event", 105)?;
handler.add_button("right", "/dev/input/by-path/platform-gpio_keys-event", 106)?;
handler.add_button("enter", "/dev/input/by-path/platform-gpio_keys-event", 28)?;
handler.add_button(
"backspace",
"/dev/input/by-path/platform-gpio_keys-event",
14,
)?;
Ok(Self {
button_handler: Rc::new(RefCell::new(handler)),
})
}
/// Check for currently pressed buttons. If the new state differs from the
/// old state, call the appropriate button event handlers.
pub fn process(&self) {
self.button_handler.borrow_mut().process()
}
/// Get all pressed buttons by name.
pub fn get_pressed_buttons(&self) -> HashSet<String> {
self.button_handler.borrow().get_pressed_buttons()
}
/// Check if 'up' button is pressed.
pub fn is_up(&self) -> bool {
self.button_handler.borrow().get_button_state("up")
}
/// Check if 'down' button is pressed.
pub fn is_down(&self) -> bool {
self.button_handler.borrow().get_button_state("down")
}
/// Check if 'left' button is pressed.
pub fn is_left(&self) -> bool {
self.button_handler.borrow().get_button_state("left")
}
/// Check if 'right' button is pressed.
pub fn is_right(&self) -> bool {
self.button_handler.borrow().get_button_state("right")
}
/// Check if 'enter' button is pressed.
pub fn is_enter(&self) -> bool {
self.button_handler.borrow().get_button_state("enter")
}
/// Check if 'backspace' button is pressed.
pub fn is_backspace(&self) -> bool {
self.button_handler.borrow().get_button_state("backspace")
}
}
|
use anyhow::{bail, Result};
use serde::Deserialize;
use serde_json::Value;
use tokio::sync::OnceCell;
use tracing::info;
static CACHED_KEYS: OnceCell<Vec<Jwk>> = OnceCell::const_new();
#[derive(Debug, Deserialize)]
pub struct Jwk {
pub kid: String,
pub e: String,
pub n: String,
}
pub async fn keys() -> Result<&'static Vec<Jwk>> {
Ok(CACHED_KEYS.get_or_try_init(fetch_keys).await?)
}
async fn fetch_keys() -> Result<Vec<Jwk>> {
info!("fetching jwk");
let client = reqwest::Client::builder().use_rustls_tls().build()?;
let url = std::env::var("JWKS_URL")?;
let res = client.get(url).send().await?;
let jwk_text = res.text().await?;
let keys_value = match serde_json::from_str::<Value>(&jwk_text)? {
serde_json::Value::Object(mut obj) => match obj.get_mut("keys") {
Some(val) => val.take(),
None => bail!("no keys found in JWK JSON"),
},
_ => bail!("JWK is not a mapping for keys"),
};
let keys: Vec<Jwk> = serde_json::from_value(keys_value)?;
Ok(keys)
}
|
use std::env;
use actix_identity::{Identity, IdentityPolicy, IdentityService};
use actix_web::{
dev::{ServiceRequest, ServiceResponse},
error,
};
use chrono::{Duration, Utc};
use futures_util::future::{ok, Ready};
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize};
use errors::Error;
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum Role {
Player,
Owner,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct PrivateClaim {
pub id: i32,
pub user_name: String,
pub game_id: i32,
pub role: Role,
exp: i64,
}
impl PrivateClaim {
pub fn new(id: i32, user_name: String, game_id: i32, role: Role) -> Self {
PrivateClaim {
id,
user_name,
game_id,
role,
exp: (Utc::now() + Duration::hours(3)).timestamp(),
}
}
pub fn set_exp(&mut self, exp: i64) {
self.exp = exp;
}
}
pub struct AuthHeaderIdentityPolicy;
impl AuthHeaderIdentityPolicy {
fn new() -> Self {
AuthHeaderIdentityPolicy {}
}
}
impl IdentityPolicy for AuthHeaderIdentityPolicy {
type Future = Ready<Result<Option<String>, error::Error>>;
type ResponseFuture = Ready<Result<(), error::Error>>;
fn from_request(&self, request: &mut ServiceRequest) -> Self::Future {
let mut token: Option<String> = None;
let auth_token = request.headers().get("Authorization");
if let Some(auth_token) = auth_token {
let token_string = auth_token.to_str();
if let Ok(token_string) = token_string {
token = Some(String::from(token_string).replace("Bearer ", ""));
}
}
ok(token)
}
fn to_response<B>(
&self,
_identity: Option<String>,
_changed: bool,
_response: &mut ServiceResponse<B>,
) -> Self::ResponseFuture {
ok(())
}
}
pub fn create_jwt(private_claim: PrivateClaim) -> Result<String, Error> {
let encoding_key = EncodingKey::from_secret(&env::var("JWT_KEY").unwrap().as_ref());
encode(&Header::default(), &private_claim, &encoding_key)
.map_err(|e| Error::CannotEncodeJwtToken(e.to_string()))
}
pub fn decode_jwt(token: &str) -> Result<PrivateClaim, Error> {
let jwt_key = env::var("JWT_KEY").unwrap();
let decoding_key = DecodingKey::from_secret(&jwt_key.as_ref());
decode::<PrivateClaim>(token, &decoding_key, &Validation::default())
.map(|data| data.claims)
.map_err(|e| Error::CannotDecodeJwtToken(e.to_string()))
}
pub fn get_identity_service() -> IdentityService<AuthHeaderIdentityPolicy> {
IdentityService::new(AuthHeaderIdentityPolicy::new())
}
pub fn get_claim_from_identity(id: Identity) -> Result<(PrivateClaim, String), Error> {
if let Some(token) = id.identity() {
let claim = decode_jwt(&token)?;
return Ok((claim, token));
}
Err(Error::Unauthorized)
}
pub fn identity_matches_game_id(id: Identity, game_id: i32) -> Result<(), Error> {
let (claim, _) = get_claim_from_identity(id)?;
if game_id != claim.game_id {
return Err(Error::Forbidden);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::{create_jwt, decode_jwt, PrivateClaim, Role};
#[test]
fn test_creates_jwt() {
let private_claim = PrivateClaim::new(1, "agmcleod".to_string(), 1, Role::Player);
let jwt = create_jwt(private_claim);
assert!(jwt.is_ok());
}
#[test]
fn test_decodes_jwt() {
let private_claim = PrivateClaim::new(1, "agmcleod".to_string(), 2, Role::Owner);
let jwt = create_jwt(private_claim.clone()).unwrap();
let decoded = decode_jwt(&jwt).unwrap();
assert_eq!(private_claim, decoded);
}
}
|
fn main() {
let x = true;
assert!(x);
let a = 3;
let b = 1+2;
assert_eq!(a, b);
} |
pub use self::file::*;
pub use self::memory::memory_stream::MemoryStream;
pub use self::stream_rw::stream_reader::StreamReader;
pub use self::stream_rw::stream_writer::StreamWriter;
use std::error::Error;
use StreamError;
use StreamErrorKind;
pub mod file;
pub mod memory;
pub mod stream_rw;
// Specifies the position in a stream to use for seeking.
pub enum SeekOrigin {
///
/// Specifies the beginning of a stream.
///
Begin = 0,
///
///
/// Specifies the current position within a stream.
Current = 1,
///
///
/// Specifies the end of a stream.
End = 2,
}
pub trait Stream {
///
/// copy current stream to target stream
/// # Examples
///```rust
/// use iostream::io::*;
/// use std::fs::File;
///
/// let mut ms = MemoryStream::new();
/// let data:[u8;50]=[54;50];
/// ms.write(&data,0,50).unwrap();
///
/// let mut fs=File::open_fs("c.data",FileMode::CreateNew,FileAccess::ReadWrite).unwrap();
/// ms.copy_to(&mut fs);
/// ```
fn copy_to(&mut self, target: &mut dyn Stream) -> Result<(), Box<dyn Error>> {
if !self.can_read() {
StreamError::from_str("the current stream cannot read")?
}
if !target.can_write() {
StreamError::from_str("the target stream cannot read")?
}
let _potion = self.position();
self.set_position(0)?;
const LENGTH: usize = 1024;
let mut buffs: [u8; LENGTH] = [0; LENGTH];
loop {
let result = self.read(&mut buffs, 0, LENGTH);
match result {
Ok(size) => {
if size == 0 {
break;
} else {
let mut lp = target.write(&buffs, 0, size)?;
while lp < size {
let have = size - lp;
lp = target.write(&buffs, lp, have)?;
}
}
}
Err(e) => {
if let StreamErrorKind::End = e.err_type {
break;
} else {
return Err(Box::new(e));
}
}
}
}
target.flush()?;
self.set_position(_potion)?;
Ok(())
}
/// gets or sets the position within the current stream
fn set_position(&mut self, _potion: u64) -> Result<(), Box<dyn Error>>;
/// The current position within the stream.
fn position(&mut self) -> u64;
/// A long value representing the length of the stream in bytes.
fn length(&mut self) -> u64;
/// Sets the length of this stream to the given value.
fn set_length(&mut self, len:u64) -> Result<(), Box<dyn Error>>;
/// gets a value indicating whether the current stream supports writing.
/// true if the stream supports writing; otherwise, false.
fn can_write(&mut self) -> bool;
/// gets a value indicating whether the current stream supports reading.
/// true if the stream supports reading; otherwise, false.
fn can_read(&mut self) -> bool;
/// gets a value indicating whether the current stream supports seeking.
fn can_seek(&mut self) -> bool;
/// When overridden in a derived class, reads a sequence of bytes from the current
/// stream and advances the position within the stream by the number of bytes read.
fn read_all(&mut self, buf: &mut Vec<u8>) -> Result<usize, StreamError>;
/// reads a sequence of bytes from the current
/// stream and advances the position within the stream by the number of bytes read.
fn read(&mut self, buf: &mut [u8], offset: usize, count: usize) -> Result<usize, StreamError>;
/// Reads a byte from the stream and advances the position within the stream by one
/// byte, or Err returns -1 if at the end of the stream.
fn read_byte(&mut self) -> Result<u8, StreamError>;
/// sets the position within the current stream.
fn seek(&mut self, offset: i64, origin: SeekOrigin) -> Result<u64, Box<dyn Error>>;
/// writes a sequence of all bytes to the current stream
fn write_all(&mut self, buf: &[u8]) -> Result<(), Box<dyn Error>>;
/// writes a sequence of bytes to the current
/// stream and advances the current position within this stream by the number of
/// bytes written.
fn write(&mut self, buf: &[u8], offset: usize, count: usize) -> Result<usize, Box<dyn Error>>;
/// clears all buffers for this stream and causes
/// any buffered data to be written to the underlying device.
fn flush(&mut self) -> Result<(), Box<dyn Error>>;
}
|
mod atom;
mod id;
use std::sync::Arc;
use proptest::arbitrary::any;
use proptest::strategy::{BoxedStrategy, Strategy};
use liblumen_alloc::erts::Node;
use crate::runtime::distribution::nodes;
pub fn external() -> BoxedStrategy<Arc<Node>> {
(id::external(), atom::external(), any::<u32>())
.prop_map(|(id, atom, creation)| {
let arc_node = Arc::new(Node::new(id, atom, creation));
nodes::insert(arc_node.clone());
arc_node
})
.boxed()
}
fn id() -> BoxedStrategy<usize> {
any::<usize>().boxed()
}
|
//! ```elixir
//! # label 6
//! # pushed to stack: (parent, reference_child)
//! # returned form call: {:ok, new_child}
//! # full stack: ({:ok, new_child}, parent, reference_child)
//! # returns: {:ok, inserted_child}
//! {:ok, inserted_child} = Lumen.Web.insert_before(parent, new_child, reference_child)
//! ```
use std::convert::TryInto;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
#[native_implemented::label]
fn result(process: &Process, ok_new_child: Term, parent: Term, reference_child: Term) -> Term {
assert!(
ok_new_child.is_boxed_tuple(),
"ok_new_child ({:?}) is not a tuple",
ok_new_child
);
let ok_new_child_tuple: Boxed<Tuple> = ok_new_child.try_into().unwrap();
assert_eq!(ok_new_child_tuple.len(), 2);
assert_eq!(ok_new_child_tuple[0], Atom::str_to_term("ok"));
let new_child = ok_new_child_tuple[1];
assert!(new_child.is_boxed_resource_reference());
assert!(parent.is_boxed_resource_reference());
assert!(reference_child.is_boxed_resource_reference());
process.queue_frame_with_arguments(
liblumen_web::node::insert_before_3::frame()
.with_arguments(false, &[parent, new_child, reference_child]),
);
Term::NONE
}
|
#![cfg_attr(feature = "microbit", no_std)]
#![cfg_attr(feature = "microbit", no_main)]
#![macro_use]
#![allow(incomplete_features)]
#![feature(generic_associated_types)]
#![feature(const_fn_fn_ptr_basics)]
#![feature(type_alias_impl_trait)]
#![feature(concat_idents)]
mod app;
mod device;
use device::*;
use embassy::executor::Spawner;
cfg_if::cfg_if! {
if #[cfg(feature = "wasm")] {
use wasm_bindgen::prelude::*;
use drogue_wasm::*;
type BUTTON = WebButton;
type LED = WebLed;
#[embassy::main]
async fn main(spawner: Spawner) {
wasm_logger::init(wasm_logger::Config::default());
static mut INPUT1: InputPin = InputPin::new();
static mut OUTPUT1: OutputPin = OutputPin::new();
static mut OUTPUT2: OutputPin = OutputPin::new();
// Configure HTML elements
unsafe {
INPUT1.configure("button");
OUTPUT1.configure("led1", |value| LedColor::Red + value );
OUTPUT2.configure("led2", |value| LedColor::Green + value );
}
let button = WebButton::new(unsafe { &INPUT1 });
let led1 = WebLed::new(unsafe { &OUTPUT1 });
let led2 = WebLed::new(unsafe { &OUTPUT2 });
MyDevice::start(button, led1, led2, spawner).await;
}
} else if #[cfg(feature = "microbit")] {
use panic_probe as _;
use rtt_logger::RTTLogger;
use rtt_target::rtt_init_print;
use log::LevelFilter;
use embedded_hal::digital::v2::OutputPin;
use embassy_nrf::{
gpio::{AnyPin, Input, Level, Output, OutputDrive, Pin, Pull},
gpiote::PortInput,
peripherals::{P0_14},
Peripherals,
};
use embassy::{time::Duration, util::Forever};
use drogue_device::{
*,
drivers::led::matrix::*,
actors::led::matrix::*,
};
static LOGGER: RTTLogger = RTTLogger::new(LevelFilter::Trace);
static MATRIX: Forever<ActorContext<'static, LedMatrixActor<Output<'static, AnyPin>, 5, 5>, 10>> = Forever::new();
type BUTTON = PortInput<'static, P0_14>;
type LED = MatrixOutput;
#[embassy::main]
async fn main(spawner: Spawner, p: Peripherals) {
rtt_init_print!();
log::set_logger(&LOGGER).unwrap();
log::set_max_level(log::LevelFilter::Trace);
let output_pin = |pin: AnyPin| {
Output::new(pin, Level::Low, OutputDrive::Standard)
};
// LED Matrix
let rows = [
output_pin(p.P0_21.degrade()),
output_pin(p.P0_22.degrade()),
output_pin(p.P0_15.degrade()),
output_pin(p.P0_24.degrade()),
output_pin(p.P0_19.degrade()),
];
let cols = [
output_pin(p.P0_28.degrade()),
output_pin(p.P0_11.degrade()),
output_pin(p.P0_31.degrade()),
output_pin(p.P1_05.degrade()),
output_pin(p.P0_30.degrade()),
];
let matrix = LedMatrix::new(rows, cols);
let matrix = MATRIX.put(ActorContext::new(LedMatrixActor::new(Duration::from_millis(1000 / 200), matrix)));
let matrix = matrix.mount((), spawner);
let button = PortInput::new(Input::new(p.P0_14, Pull::Up));
let led1 = MatrixOutput::new(matrix.clone(), 0, 0);
let led2 = MatrixOutput::new(matrix.clone(), 4, 4);
MyDevice::start(button, led1, led2, spawner).await;
}
pub struct MatrixOutput {
matrix: Address<'static, LedMatrixActor<Output<'static, AnyPin>, 5, 5>>,
row: usize,
col: usize,
}
impl MatrixOutput {
pub fn new(address: Address<'static, LedMatrixActor<Output<'static, AnyPin>, 5, 5>>, row: usize, col: usize) -> Self {
Self {
matrix: address,
row,
col,
}
}
}
impl OutputPin for MatrixOutput {
type Error = ();
fn set_low(&mut self) -> Result<(), ()> {
self.matrix.notify(MatrixCommand::Off(self.row, self.col)).unwrap();
Ok(())
}
fn set_high(&mut self) -> Result<(), ()> {
self.matrix.notify(MatrixCommand::On(self.row, self.col)).unwrap();
Ok(())
}
}
}
}
|
fn main() {
let a = -121;
println!("{:?}", is_palindrom(a));
}
fn is_palindrom(x: i32) -> bool {
x.to_string() == x.to_string().chars().rev().collect::<String>()
}
|
use std::ffi::c_void;
use std::mem;
use std::ptr::NonNull;
use liblumen_alloc::erts::exception::InternalResult;
use liblumen_alloc::erts::term::prelude::*;
use liblumen_alloc::erts::Process;
use super::{atom, small_integer};
use liblumen_alloc::erts::apply::find_symbol;
use liblumen_alloc::ModuleFunctionArity;
pub fn decode<'a>(
process: &Process,
safe: bool,
bytes: &'a [u8],
) -> InternalResult<(Term, &'a [u8])> {
let (module, after_module_bytes) = atom::decode_tagged(safe, bytes)?;
let (function, after_function_bytes) = atom::decode_tagged(safe, after_module_bytes)?;
let (arity, after_arity_bytes) = small_integer::decode_tagged_u8(after_function_bytes)?;
let module_function_arity = ModuleFunctionArity {
module,
function,
arity,
};
let option_native = find_symbol(&module_function_arity).map(|dynamic_callee| unsafe {
let ptr = mem::transmute::<_, *mut c_void>(dynamic_callee);
NonNull::new_unchecked(ptr)
});
let closure = process.export_closure(module, function, arity, option_native);
Ok((closure, after_arity_bytes))
}
|
#[doc = "Reader of register CONF0R"]
pub type R = crate::R<u32, super::CONF0R>;
#[doc = "Writer for register CONF0R"]
pub type W = crate::W<u32, super::CONF0R>;
#[doc = "Register CONF0R `reset()`'s with value 0"]
impl crate::ResetValue for super::CONF0R {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `COMMON0`"]
pub type COMMON0_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `COMMON0`"]
pub struct COMMON0_W<'a> {
w: &'a mut W,
}
impl<'a> COMMON0_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 << 30)) | (((value as u32) & 0x03) << 30);
self.w
}
}
#[doc = "Reader of field `SE0`"]
pub type SE0_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SE0`"]
pub struct SE0_W<'a> {
w: &'a mut W,
}
impl<'a> SE0_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 << 26)) | (((value as u32) & 0x03) << 26);
self.w
}
}
#[doc = "Reader of field `GAIN0`"]
pub type GAIN0_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `GAIN0`"]
pub struct GAIN0_W<'a> {
w: &'a mut W,
}
impl<'a> GAIN0_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 20)) | (((value as u32) & 0x07) << 20);
self.w
}
}
#[doc = "Reader of field `OFFSET0`"]
pub type OFFSET0_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `OFFSET0`"]
pub struct OFFSET0_W<'a> {
w: &'a mut W,
}
impl<'a> OFFSET0_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0fff) | ((value as u32) & 0x0fff);
self.w
}
}
impl R {
#[doc = "Bits 30:31 - Common mode for configuration 0"]
#[inline(always)]
pub fn common0(&self) -> COMMON0_R {
COMMON0_R::new(((self.bits >> 30) & 0x03) as u8)
}
#[doc = "Bits 26:27 - Single-ended mode for configuration 0"]
#[inline(always)]
pub fn se0(&self) -> SE0_R {
SE0_R::new(((self.bits >> 26) & 0x03) as u8)
}
#[doc = "Bits 20:22 - Gain setting for configuration 0"]
#[inline(always)]
pub fn gain0(&self) -> GAIN0_R {
GAIN0_R::new(((self.bits >> 20) & 0x07) as u8)
}
#[doc = "Bits 0:11 - Twelve-bit calibration offset for configuration 0"]
#[inline(always)]
pub fn offset0(&self) -> OFFSET0_R {
OFFSET0_R::new((self.bits & 0x0fff) as u16)
}
}
impl W {
#[doc = "Bits 30:31 - Common mode for configuration 0"]
#[inline(always)]
pub fn common0(&mut self) -> COMMON0_W {
COMMON0_W { w: self }
}
#[doc = "Bits 26:27 - Single-ended mode for configuration 0"]
#[inline(always)]
pub fn se0(&mut self) -> SE0_W {
SE0_W { w: self }
}
#[doc = "Bits 20:22 - Gain setting for configuration 0"]
#[inline(always)]
pub fn gain0(&mut self) -> GAIN0_W {
GAIN0_W { w: self }
}
#[doc = "Bits 0:11 - Twelve-bit calibration offset for configuration 0"]
#[inline(always)]
pub fn offset0(&mut self) -> OFFSET0_W {
OFFSET0_W { w: self }
}
}
|
use clippy_utils::diagnostics::span_lint_and_help;
use rustc_hir::{HirId, Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::Const;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// Displays a warning when a struct with a trailing zero-sized array is declared without a `repr` attribute.
///
/// ### Why is this bad?
/// Zero-sized arrays aren't very useful in Rust itself, so such a struct is likely being created to pass to C code or in some other situation where control over memory layout matters (for example, in conjuction with manual allocation to make it easy to compute the offset of the array). Either way, `#[repr(C)]` (or another `repr` attribute) is needed.
///
/// ### Example
/// ```rust
/// struct RarelyUseful {
/// some_field: u32,
/// last: [u32; 0],
/// }
/// ```
///
/// Use instead:
/// ```rust
/// #[repr(C)]
/// struct MoreOftenUseful {
/// some_field: usize,
/// last: [u32; 0],
/// }
/// ```
#[clippy::version = "1.58.0"]
pub TRAILING_EMPTY_ARRAY,
nursery,
"struct with a trailing zero-sized array but without `#[repr(C)]` or another `repr` attribute"
}
declare_lint_pass!(TrailingEmptyArray => [TRAILING_EMPTY_ARRAY]);
impl<'tcx> LateLintPass<'tcx> for TrailingEmptyArray {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
if is_struct_with_trailing_zero_sized_array(cx, item) && !has_repr_attr(cx, item.hir_id()) {
span_lint_and_help(
cx,
TRAILING_EMPTY_ARRAY,
item.span,
"trailing zero-sized array in a struct which is not marked with a `repr` attribute",
None,
&format!(
"consider annotating `{}` with `#[repr(C)]` or another `repr` attribute",
cx.tcx.def_path_str(item.def_id.to_def_id())
),
);
}
}
}
fn is_struct_with_trailing_zero_sized_array(cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) -> bool {
if_chain! {
// First check if last field is an array
if let ItemKind::Struct(data, _) = &item.kind;
if let Some(last_field) = data.fields().last();
if let rustc_hir::TyKind::Array(_, length) = last_field.ty.kind;
// Then check if that that array zero-sized
let length_ldid = cx.tcx.hir().local_def_id(length.hir_id);
let length = Const::from_anon_const(cx.tcx, length_ldid);
let length = length.try_eval_usize(cx.tcx, cx.param_env);
if let Some(length) = length;
then {
length == 0
} else {
false
}
}
}
fn has_repr_attr(cx: &LateContext<'_>, hir_id: HirId) -> bool {
cx.tcx.hir().attrs(hir_id).iter().any(|attr| attr.has_name(sym::repr))
}
|
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use anyhow::bail;
use filetime::{set_file_times, FileTime};
const ABOUT: &'static str = "
szip compresses and decompresses data in the Snappy format.
szip works similarly to gzip. It takes files as parameters, compresses them to
a new file with a .sz extension, and removes the original. File access and
modification times are preserved.
Alternatively, data can be sent on stdin and its compressed form will be sent
to stdout.
The -d (short for --decompress) flag changes the mode from compression to
decompression.
The --raw flag can be used for compressing/decompressing the raw Snappy format.
Note that this requires reading the entire input/output into memory. In
general, you shouldn't use this flag unless you have a specific need to.
";
fn app() -> clap::App<'static, 'static> {
use clap::{crate_authors, crate_version, App, Arg};
App::new("szip")
.about(ABOUT)
.author(crate_authors!())
.version(crate_version!())
.max_term_width(100)
.arg(
Arg::with_name("paths")
.help("A list of file paths to compress (or decompress)."),
)
.arg(
Arg::with_name("decompress")
.long("decompress")
.short("d")
.help("Decompress data (default is compression)."),
)
.arg(Arg::with_name("force").long("force").short("f").help(
"Force (de)compression even if the corresponding \
output file already exists.",
))
.arg(
Arg::with_name("keep").long("keep").short("k").help(
"Keep (don't delete) input files during (de)compression.",
),
)
.arg(
Arg::with_name("raw")
.long("raw")
.short("r")
.help("Use the \"raw\" Snappy format (no framing)."),
)
}
fn main() -> anyhow::Result<()> {
let args = Args::parse()?;
if args.paths.is_empty() {
let stdin = io::stdin();
let mut stdin = stdin.lock();
let stdout = io::stdout();
let mut stdout = stdout.lock();
if args.decompress {
args.decompress(&mut stdin, &mut stdout)?;
} else {
args.compress(&mut stdin, &mut stdout)?;
}
} else {
for p in &args.paths {
if let Err(err) = args.do_file(p) {
writeln!(
&mut std::io::stderr(),
"{}: {:?}",
p.display(),
err
)?;
}
}
}
Ok(())
}
#[derive(Debug)]
struct Args {
paths: Vec<PathBuf>,
decompress: bool,
force: bool,
keep: bool,
raw: bool,
}
impl Args {
fn parse() -> anyhow::Result<Args> {
let parsed = app().get_matches();
let paths = parsed
.values_of_os("paths")
.map(|paths| paths.into_iter().map(PathBuf::from).collect())
.unwrap_or(vec![]);
Ok(Args {
paths,
decompress: parsed.is_present("decompress"),
force: parsed.is_present("force"),
keep: parsed.is_present("keep"),
raw: parsed.is_present("raw"),
})
}
fn do_file(&self, old_path: &Path) -> anyhow::Result<()> {
let old_md = old_path.metadata()?;
if old_md.is_dir() {
bail!("is a directory");
}
let new_path = self.new_path(old_path)?;
if !self.force && new_path.exists() {
bail!("skipping, file already exists: {}", new_path.display());
}
let old_file = io::BufReader::new(File::open(old_path)?);
let new_file = io::BufWriter::new(File::create(&new_path)?);
if self.decompress {
self.decompress(old_file, new_file)?;
} else {
self.compress(old_file, new_file)?;
}
let last_access = FileTime::from_last_access_time(&old_md);
let last_mod = FileTime::from_last_modification_time(&old_md);
set_file_times(new_path, last_access, last_mod)?;
if !self.keep {
fs::remove_file(old_path)?;
}
Ok(())
}
fn new_path(&self, old_path: &Path) -> anyhow::Result<PathBuf> {
let name = match old_path.file_name() {
None => bail!("missing file name"),
Some(name) => name,
};
if self.decompress {
let name = name.to_string_lossy();
if name.len() <= 3 || !name.ends_with(".sz") {
bail!("skipping uncompressed file");
}
Ok(old_path
.with_file_name(format!("{}", &name[0..name.len() - 3])))
} else {
let name = name.to_string_lossy();
if name.ends_with(".sz") {
bail!("skipping compressed file");
}
Ok(old_path.with_file_name(format!("{}.sz", name)))
}
}
fn compress<R: Read, W: Write>(
&self,
mut src: R,
mut dst: W,
) -> anyhow::Result<()> {
if self.raw {
// Read the entire src into memory and compress it.
let mut buf = Vec::with_capacity(10 * (1 << 20));
src.read_to_end(&mut buf)?;
let compressed = snap::raw::Encoder::new().compress_vec(&buf)?;
dst.write_all(&compressed)?;
} else {
let mut dst = snap::write::FrameEncoder::new(dst);
io::copy(&mut src, &mut dst)?;
}
Ok(())
}
fn decompress<R: Read, W: Write>(
&self,
mut src: R,
mut dst: W,
) -> anyhow::Result<()> {
if self.raw {
// Read the entire src into memory and decompress it.
let mut buf = Vec::with_capacity(10 * (1 << 20));
src.read_to_end(&mut buf)?;
let decompressed =
snap::raw::Decoder::new().decompress_vec(&buf)?;
dst.write_all(&decompressed)?;
} else {
let mut src = snap::read::FrameDecoder::new(src);
io::copy(&mut src, &mut dst)?;
}
Ok(())
}
}
|
pub struct Solution;
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: List,
}
type List = Option<Box<ListNode>>;
impl Solution {
pub fn remove_elements(head: List, val: i32) -> List {
let mut head = head;
let mut cur = &mut head;
while cur.is_some() {
if cur.as_ref().unwrap().val == val {
*cur = cur.take().unwrap().next.take();
} else {
cur = &mut cur.as_mut().unwrap().next;
}
}
head
}
}
#[test]
fn test0202() {
fn case(nums: &[i32], val: i32, want: &[i32]) {
let head = list_from_slice(nums);
let want = list_from_slice(want);
let got = Solution::remove_elements(head, val);
assert_eq!(got, want);
}
fn list_from_slice(nums: &[i32]) -> List {
let mut head = None;
let mut cur = &mut head;
for &num in nums {
*cur = Some(Box::new(ListNode {
val: num,
next: None,
}));
cur = &mut cur.as_mut().unwrap().next;
}
head
}
case(&[1, 2, 6, 3, 4, 5, 6], 6, &[1, 2, 3, 4, 5]);
}
|
//
// mod.rs
// Copyright (C) 2019 Malcolm Ramsay <malramsay64@gmail.com>
// Distributed under terms of the MIT license.
//
pub mod atom2;
pub mod atom2_ops;
pub mod line2;
pub mod line2_ops;
pub mod lj2;
pub mod lj2_ops;
pub use atom2::Atom2;
pub use line2::Line2;
pub use lj2::LJ2;
|
#![recursion_limit = "256"]
#[macro_use]
extern crate stdweb;
use crate::components::svgmap::SVGMap;
use crate::data::input::SCENARIO;
use crate::data::schema::SchemaData;
use crate::engine::worker::{Worker, WorkerRequest, WorkerResponse};
use crate::sections::appbar::AppBar;
use crate::sections::infopanel::InfoPanel;
use crate::timeout::create_timeout;
use ron::de::from_str;
use std::collections::HashMap;
use std::time::Duration;
use yew::prelude::*;
use yew::services::ConsoleService;
mod components;
mod data;
mod engine;
mod map;
mod sections;
mod timeout;
pub struct Model {
console: ConsoleService,
link: ComponentLink<Self>,
context: Box<dyn Bridge<Worker>>,
task_count: usize,
worker_count: usize,
data: SchemaData,
zoom: bool,
day: usize,
}
pub enum Msg {
ContextMsg(WorkerResponse),
RequestNewSchedule,
ZoomChanged,
DayChanged(usize),
}
pub const NBSP: char = '\u{00a0}';
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, mut link: ComponentLink<Self>) -> Self {
// Set up the worker thread
let callback = link.send_back(Msg::ContextMsg);
// Create initial object with empty values, we do this to get access to the console.log
let mut obj = Model {
console: ConsoleService::new(),
link,
context: Worker::bridge(callback), // Connected! :tada:
task_count: 0,
worker_count: 0,
data: SchemaData { activity: HashMap::new(), resource: HashMap::new(), route: Vec::new(), allocation: HashMap::new(), status: None },
zoom: true,
day: 0,
};
// Create schema
obj.console.log("Loading schema data");
obj.data = match from_str(SCENARIO) {
Ok(x) => x,
Err(e) => {
obj.console.log(&format!("Failed to load config: {}", e));
obj.data
}
};
obj.console.log(&format!("Creating schedule for {} resources and {} activities", obj.data.resource.len(), obj.data.activity.len()));
obj.task_count = obj.data.activity.len();
obj.worker_count = obj.data.resource.len();
// Our model defines the state
obj
}
fn mounted(&mut self) -> ShouldRender {
// Request the data to be scheduled
(*self.context).send(WorkerRequest::Schedule(self.data.clone()));
false
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::ContextMsg(response) => match response {
WorkerResponse::Scheduled(sd) => {
self.data = sd;
if self.data.status.as_ref().unwrap().changed {
self.console.log("New plan returned from scheduler!");
}
// Request another reschedule, we want to do this forever to show the improving schedule
// We wait a little while so we don't swamp the main thread
// Unfortunately it CAN'T run on another thread yet
let callback = self.link.send_back(|_| Msg::RequestNewSchedule);
create_timeout(Duration::from_millis(250), callback);
// Ask for a redraw
return true;
}
},
Msg::RequestNewSchedule => {
(*self.context).send(WorkerRequest::Schedule(self.data.clone()));
return false;
}
Msg::ZoomChanged => {
self.zoom = !self.zoom;
return true;
}
Msg::DayChanged(day) => {
self.day = day;
return true;
}
}
}
fn view(&self) -> Html<Self> {
let status = self.data.status.as_ref().unwrap();
html! {
<div class="mdc-typography",>
<div class="full",>
<AppBar: title="Cognito iQ Web Scheduler", />
<InfoPanel: num_jobs={&self.task_count},
num_workers={&self.worker_count},
dist={status.distance},
value={status.value},
travel_time={status.travel_time},
quality={status.quality},
zoom_changed=|_| Msg::ZoomChanged day_changed=|day| Msg::DayChanged(day),/>
<div class="centre-all",>
<SVGMap: data={&self.data}, zoom={&self.zoom}, background="#121212", day={&self.day} />
</div>
</div>
</div>
}
}
}
fn main() {
yew::start_app::<Model>();
}
|
use std::sync::Arc;
use proptest::strategy::{BoxedStrategy, Strategy};
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
pub fn with_arity(arc_process: Arc<Process>, arity: u8) -> BoxedStrategy<Term> {
(
super::super::module_atom(),
super::index(),
super::old_unique(),
super::unique(),
super::creator(),
)
.prop_map(move |(module, index, old_unique, unique, creator)| {
arc_process.anonymous_closure_with_env_from_slice(
module,
index,
old_unique,
unique,
arity,
None,
creator,
&[],
)
})
.boxed()
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - MPCBB control register"]
pub mpcbb1_cr: MPCBB1_CR,
_reserved1: [u8; 12usize],
#[doc = "0x10 - MPCBB control register"]
pub mpcbb1_lckvtr1: MPCBB1_LCKVTR1,
#[doc = "0x14 - MPCBB control register"]
pub mpcbb1_lckvtr2: MPCBB1_LCKVTR2,
_reserved3: [u8; 232usize],
#[doc = "0x100 - MPCBBx vector register"]
pub mpcbb1_vctr0: MPCBB1_VCTR0,
#[doc = "0x104 - MPCBBx vector register"]
pub mpcbb1_vctr1: MPCBB1_VCTR1,
#[doc = "0x108 - MPCBBx vector register"]
pub mpcbb1_vctr2: MPCBB1_VCTR2,
#[doc = "0x10c - MPCBBx vector register"]
pub mpcbb1_vctr3: MPCBB1_VCTR3,
#[doc = "0x110 - MPCBBx vector register"]
pub mpcbb1_vctr4: MPCBB1_VCTR4,
#[doc = "0x114 - MPCBBx vector register"]
pub mpcbb1_vctr5: MPCBB1_VCTR5,
#[doc = "0x118 - MPCBBx vector register"]
pub mpcbb1_vctr6: MPCBB1_VCTR6,
#[doc = "0x11c - MPCBBx vector register"]
pub mpcbb1_vctr7: MPCBB1_VCTR7,
#[doc = "0x120 - MPCBBx vector register"]
pub mpcbb1_vctr8: MPCBB1_VCTR8,
#[doc = "0x124 - MPCBBx vector register"]
pub mpcbb1_vctr9: MPCBB1_VCTR9,
#[doc = "0x128 - MPCBBx vector register"]
pub mpcbb1_vctr10: MPCBB1_VCTR10,
#[doc = "0x12c - MPCBBx vector register"]
pub mpcbb1_vctr11: MPCBB1_VCTR11,
#[doc = "0x130 - MPCBBx vector register"]
pub mpcbb1_vctr12: MPCBB1_VCTR12,
#[doc = "0x134 - MPCBBx vector register"]
pub mpcbb1_vctr13: MPCBB1_VCTR13,
#[doc = "0x138 - MPCBBx vector register"]
pub mpcbb1_vctr14: MPCBB1_VCTR14,
#[doc = "0x13c - MPCBBx vector register"]
pub mpcbb1_vctr15: MPCBB1_VCTR15,
#[doc = "0x140 - MPCBBx vector register"]
pub mpcbb1_vctr16: MPCBB1_VCTR16,
#[doc = "0x144 - MPCBBx vector register"]
pub mpcbb1_vctr17: MPCBB1_VCTR17,
#[doc = "0x148 - MPCBBx vector register"]
pub mpcbb1_vctr18: MPCBB1_VCTR18,
#[doc = "0x14c - MPCBBx vector register"]
pub mpcbb1_vctr19: MPCBB1_VCTR19,
#[doc = "0x150 - MPCBBx vector register"]
pub mpcbb1_vctr20: MPCBB1_VCTR20,
#[doc = "0x154 - MPCBBx vector register"]
pub mpcbb1_vctr21: MPCBB1_VCTR21,
#[doc = "0x158 - MPCBBx vector register"]
pub mpcbb1_vctr22: MPCBB1_VCTR22,
#[doc = "0x15c - MPCBBx vector register"]
pub mpcbb1_vctr23: MPCBB1_VCTR23,
#[doc = "0x160 - MPCBBx vector register"]
pub mpcbb1_vctr24: MPCBB1_VCTR24,
#[doc = "0x164 - MPCBBx vector register"]
pub mpcbb1_vctr25: MPCBB1_VCTR25,
#[doc = "0x168 - MPCBBx vector register"]
pub mpcbb1_vctr26: MPCBB1_VCTR26,
#[doc = "0x16c - MPCBBx vector register"]
pub mpcbb1_vctr27: MPCBB1_VCTR27,
#[doc = "0x170 - MPCBBx vector register"]
pub mpcbb1_vctr28: MPCBB1_VCTR28,
#[doc = "0x174 - MPCBBx vector register"]
pub mpcbb1_vctr29: MPCBB1_VCTR29,
#[doc = "0x178 - MPCBBx vector register"]
pub mpcbb1_vctr30: MPCBB1_VCTR30,
#[doc = "0x17c - MPCBBx vector register"]
pub mpcbb1_vctr31: MPCBB1_VCTR31,
#[doc = "0x180 - MPCBBx vector register"]
pub mpcbb1_vctr32: MPCBB1_VCTR32,
#[doc = "0x184 - MPCBBx vector register"]
pub mpcbb1_vctr33: MPCBB1_VCTR33,
#[doc = "0x188 - MPCBBx vector register"]
pub mpcbb1_vctr34: MPCBB1_VCTR34,
#[doc = "0x18c - MPCBBx vector register"]
pub mpcbb1_vctr35: MPCBB1_VCTR35,
#[doc = "0x190 - MPCBBx vector register"]
pub mpcbb1_vctr36: MPCBB1_VCTR36,
#[doc = "0x194 - MPCBBx vector register"]
pub mpcbb1_vctr37: MPCBB1_VCTR37,
#[doc = "0x198 - MPCBBx vector register"]
pub mpcbb1_vctr38: MPCBB1_VCTR38,
#[doc = "0x19c - MPCBBx vector register"]
pub mpcbb1_vctr39: MPCBB1_VCTR39,
#[doc = "0x1a0 - MPCBBx vector register"]
pub mpcbb1_vctr40: MPCBB1_VCTR40,
#[doc = "0x1a4 - MPCBBx vector register"]
pub mpcbb1_vctr41: MPCBB1_VCTR41,
#[doc = "0x1a8 - MPCBBx vector register"]
pub mpcbb1_vctr42: MPCBB1_VCTR42,
#[doc = "0x1ac - MPCBBx vector register"]
pub mpcbb1_vctr43: MPCBB1_VCTR43,
#[doc = "0x1b0 - MPCBBx vector register"]
pub mpcbb1_vctr44: MPCBB1_VCTR44,
#[doc = "0x1b4 - MPCBBx vector register"]
pub mpcbb1_vctr45: MPCBB1_VCTR45,
#[doc = "0x1b8 - MPCBBx vector register"]
pub mpcbb1_vctr46: MPCBB1_VCTR46,
#[doc = "0x1bc - MPCBBx vector register"]
pub mpcbb1_vctr47: MPCBB1_VCTR47,
#[doc = "0x1c0 - MPCBBx vector register"]
pub mpcbb1_vctr48: MPCBB1_VCTR48,
#[doc = "0x1c4 - MPCBBx vector register"]
pub mpcbb1_vctr49: MPCBB1_VCTR49,
#[doc = "0x1c8 - MPCBBx vector register"]
pub mpcbb1_vctr50: MPCBB1_VCTR50,
#[doc = "0x1cc - MPCBBx vector register"]
pub mpcbb1_vctr51: MPCBB1_VCTR51,
#[doc = "0x1d0 - MPCBBx vector register"]
pub mpcbb1_vctr52: MPCBB1_VCTR52,
#[doc = "0x1d4 - MPCBBx vector register"]
pub mpcbb1_vctr53: MPCBB1_VCTR53,
#[doc = "0x1d8 - MPCBBx vector register"]
pub mpcbb1_vctr54: MPCBB1_VCTR54,
#[doc = "0x1dc - MPCBBx vector register"]
pub mpcbb1_vctr55: MPCBB1_VCTR55,
#[doc = "0x1e0 - MPCBBx vector register"]
pub mpcbb1_vctr56: MPCBB1_VCTR56,
#[doc = "0x1e4 - MPCBBx vector register"]
pub mpcbb1_vctr57: MPCBB1_VCTR57,
#[doc = "0x1e8 - MPCBBx vector register"]
pub mpcbb1_vctr58: MPCBB1_VCTR58,
#[doc = "0x1ec - MPCBBx vector register"]
pub mpcbb1_vctr59: MPCBB1_VCTR59,
#[doc = "0x1f0 - MPCBBx vector register"]
pub mpcbb1_vctr60: MPCBB1_VCTR60,
#[doc = "0x1f4 - MPCBBx vector register"]
pub mpcbb1_vctr61: MPCBB1_VCTR61,
#[doc = "0x1f8 - MPCBBx vector register"]
pub mpcbb1_vctr62: MPCBB1_VCTR62,
#[doc = "0x1fc - MPCBBx vector register"]
pub mpcbb1_vctr63: MPCBB1_VCTR63,
}
#[doc = "MPCBB control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_cr](mpcbb1_cr) module"]
pub type MPCBB1_CR = crate::Reg<u32, _MPCBB1_CR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_CR;
#[doc = "`read()` method returns [mpcbb1_cr::R](mpcbb1_cr::R) reader structure"]
impl crate::Readable for MPCBB1_CR {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_cr::W](mpcbb1_cr::W) writer structure"]
impl crate::Writable for MPCBB1_CR {}
#[doc = "MPCBB control register"]
pub mod mpcbb1_cr;
#[doc = "MPCBB control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_lckvtr1](mpcbb1_lckvtr1) module"]
pub type MPCBB1_LCKVTR1 = crate::Reg<u32, _MPCBB1_LCKVTR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_LCKVTR1;
#[doc = "`read()` method returns [mpcbb1_lckvtr1::R](mpcbb1_lckvtr1::R) reader structure"]
impl crate::Readable for MPCBB1_LCKVTR1 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_lckvtr1::W](mpcbb1_lckvtr1::W) writer structure"]
impl crate::Writable for MPCBB1_LCKVTR1 {}
#[doc = "MPCBB control register"]
pub mod mpcbb1_lckvtr1;
#[doc = "MPCBB control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_lckvtr2](mpcbb1_lckvtr2) module"]
pub type MPCBB1_LCKVTR2 = crate::Reg<u32, _MPCBB1_LCKVTR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_LCKVTR2;
#[doc = "`read()` method returns [mpcbb1_lckvtr2::R](mpcbb1_lckvtr2::R) reader structure"]
impl crate::Readable for MPCBB1_LCKVTR2 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_lckvtr2::W](mpcbb1_lckvtr2::W) writer structure"]
impl crate::Writable for MPCBB1_LCKVTR2 {}
#[doc = "MPCBB control register"]
pub mod mpcbb1_lckvtr2;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr0](mpcbb1_vctr0) module"]
pub type MPCBB1_VCTR0 = crate::Reg<u32, _MPCBB1_VCTR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR0;
#[doc = "`read()` method returns [mpcbb1_vctr0::R](mpcbb1_vctr0::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR0 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr0::W](mpcbb1_vctr0::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR0 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr0;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr1](mpcbb1_vctr1) module"]
pub type MPCBB1_VCTR1 = crate::Reg<u32, _MPCBB1_VCTR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR1;
#[doc = "`read()` method returns [mpcbb1_vctr1::R](mpcbb1_vctr1::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR1 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr1::W](mpcbb1_vctr1::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR1 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr1;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr2](mpcbb1_vctr2) module"]
pub type MPCBB1_VCTR2 = crate::Reg<u32, _MPCBB1_VCTR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR2;
#[doc = "`read()` method returns [mpcbb1_vctr2::R](mpcbb1_vctr2::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR2 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr2::W](mpcbb1_vctr2::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR2 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr2;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr3](mpcbb1_vctr3) module"]
pub type MPCBB1_VCTR3 = crate::Reg<u32, _MPCBB1_VCTR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR3;
#[doc = "`read()` method returns [mpcbb1_vctr3::R](mpcbb1_vctr3::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR3 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr3::W](mpcbb1_vctr3::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR3 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr3;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr4](mpcbb1_vctr4) module"]
pub type MPCBB1_VCTR4 = crate::Reg<u32, _MPCBB1_VCTR4>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR4;
#[doc = "`read()` method returns [mpcbb1_vctr4::R](mpcbb1_vctr4::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR4 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr4::W](mpcbb1_vctr4::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR4 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr4;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr5](mpcbb1_vctr5) module"]
pub type MPCBB1_VCTR5 = crate::Reg<u32, _MPCBB1_VCTR5>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR5;
#[doc = "`read()` method returns [mpcbb1_vctr5::R](mpcbb1_vctr5::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR5 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr5::W](mpcbb1_vctr5::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR5 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr5;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr6](mpcbb1_vctr6) module"]
pub type MPCBB1_VCTR6 = crate::Reg<u32, _MPCBB1_VCTR6>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR6;
#[doc = "`read()` method returns [mpcbb1_vctr6::R](mpcbb1_vctr6::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR6 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr6::W](mpcbb1_vctr6::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR6 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr6;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr7](mpcbb1_vctr7) module"]
pub type MPCBB1_VCTR7 = crate::Reg<u32, _MPCBB1_VCTR7>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR7;
#[doc = "`read()` method returns [mpcbb1_vctr7::R](mpcbb1_vctr7::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR7 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr7::W](mpcbb1_vctr7::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR7 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr7;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr8](mpcbb1_vctr8) module"]
pub type MPCBB1_VCTR8 = crate::Reg<u32, _MPCBB1_VCTR8>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR8;
#[doc = "`read()` method returns [mpcbb1_vctr8::R](mpcbb1_vctr8::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR8 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr8::W](mpcbb1_vctr8::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR8 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr8;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr9](mpcbb1_vctr9) module"]
pub type MPCBB1_VCTR9 = crate::Reg<u32, _MPCBB1_VCTR9>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR9;
#[doc = "`read()` method returns [mpcbb1_vctr9::R](mpcbb1_vctr9::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR9 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr9::W](mpcbb1_vctr9::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR9 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr9;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr10](mpcbb1_vctr10) module"]
pub type MPCBB1_VCTR10 = crate::Reg<u32, _MPCBB1_VCTR10>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR10;
#[doc = "`read()` method returns [mpcbb1_vctr10::R](mpcbb1_vctr10::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR10 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr10::W](mpcbb1_vctr10::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR10 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr10;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr11](mpcbb1_vctr11) module"]
pub type MPCBB1_VCTR11 = crate::Reg<u32, _MPCBB1_VCTR11>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR11;
#[doc = "`read()` method returns [mpcbb1_vctr11::R](mpcbb1_vctr11::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR11 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr11::W](mpcbb1_vctr11::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR11 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr11;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr12](mpcbb1_vctr12) module"]
pub type MPCBB1_VCTR12 = crate::Reg<u32, _MPCBB1_VCTR12>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR12;
#[doc = "`read()` method returns [mpcbb1_vctr12::R](mpcbb1_vctr12::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR12 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr12::W](mpcbb1_vctr12::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR12 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr12;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr13](mpcbb1_vctr13) module"]
pub type MPCBB1_VCTR13 = crate::Reg<u32, _MPCBB1_VCTR13>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR13;
#[doc = "`read()` method returns [mpcbb1_vctr13::R](mpcbb1_vctr13::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR13 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr13::W](mpcbb1_vctr13::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR13 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr13;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr14](mpcbb1_vctr14) module"]
pub type MPCBB1_VCTR14 = crate::Reg<u32, _MPCBB1_VCTR14>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR14;
#[doc = "`read()` method returns [mpcbb1_vctr14::R](mpcbb1_vctr14::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR14 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr14::W](mpcbb1_vctr14::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR14 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr14;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr15](mpcbb1_vctr15) module"]
pub type MPCBB1_VCTR15 = crate::Reg<u32, _MPCBB1_VCTR15>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR15;
#[doc = "`read()` method returns [mpcbb1_vctr15::R](mpcbb1_vctr15::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR15 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr15::W](mpcbb1_vctr15::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR15 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr15;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr16](mpcbb1_vctr16) module"]
pub type MPCBB1_VCTR16 = crate::Reg<u32, _MPCBB1_VCTR16>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR16;
#[doc = "`read()` method returns [mpcbb1_vctr16::R](mpcbb1_vctr16::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR16 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr16::W](mpcbb1_vctr16::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR16 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr16;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr17](mpcbb1_vctr17) module"]
pub type MPCBB1_VCTR17 = crate::Reg<u32, _MPCBB1_VCTR17>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR17;
#[doc = "`read()` method returns [mpcbb1_vctr17::R](mpcbb1_vctr17::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR17 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr17::W](mpcbb1_vctr17::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR17 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr17;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr18](mpcbb1_vctr18) module"]
pub type MPCBB1_VCTR18 = crate::Reg<u32, _MPCBB1_VCTR18>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR18;
#[doc = "`read()` method returns [mpcbb1_vctr18::R](mpcbb1_vctr18::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR18 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr18::W](mpcbb1_vctr18::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR18 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr18;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr19](mpcbb1_vctr19) module"]
pub type MPCBB1_VCTR19 = crate::Reg<u32, _MPCBB1_VCTR19>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR19;
#[doc = "`read()` method returns [mpcbb1_vctr19::R](mpcbb1_vctr19::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR19 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr19::W](mpcbb1_vctr19::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR19 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr19;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr20](mpcbb1_vctr20) module"]
pub type MPCBB1_VCTR20 = crate::Reg<u32, _MPCBB1_VCTR20>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR20;
#[doc = "`read()` method returns [mpcbb1_vctr20::R](mpcbb1_vctr20::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR20 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr20::W](mpcbb1_vctr20::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR20 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr20;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr21](mpcbb1_vctr21) module"]
pub type MPCBB1_VCTR21 = crate::Reg<u32, _MPCBB1_VCTR21>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR21;
#[doc = "`read()` method returns [mpcbb1_vctr21::R](mpcbb1_vctr21::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR21 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr21::W](mpcbb1_vctr21::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR21 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr21;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr22](mpcbb1_vctr22) module"]
pub type MPCBB1_VCTR22 = crate::Reg<u32, _MPCBB1_VCTR22>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR22;
#[doc = "`read()` method returns [mpcbb1_vctr22::R](mpcbb1_vctr22::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR22 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr22::W](mpcbb1_vctr22::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR22 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr22;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr23](mpcbb1_vctr23) module"]
pub type MPCBB1_VCTR23 = crate::Reg<u32, _MPCBB1_VCTR23>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR23;
#[doc = "`read()` method returns [mpcbb1_vctr23::R](mpcbb1_vctr23::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR23 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr23::W](mpcbb1_vctr23::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR23 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr23;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr24](mpcbb1_vctr24) module"]
pub type MPCBB1_VCTR24 = crate::Reg<u32, _MPCBB1_VCTR24>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR24;
#[doc = "`read()` method returns [mpcbb1_vctr24::R](mpcbb1_vctr24::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR24 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr24::W](mpcbb1_vctr24::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR24 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr24;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr25](mpcbb1_vctr25) module"]
pub type MPCBB1_VCTR25 = crate::Reg<u32, _MPCBB1_VCTR25>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR25;
#[doc = "`read()` method returns [mpcbb1_vctr25::R](mpcbb1_vctr25::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR25 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr25::W](mpcbb1_vctr25::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR25 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr25;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr26](mpcbb1_vctr26) module"]
pub type MPCBB1_VCTR26 = crate::Reg<u32, _MPCBB1_VCTR26>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR26;
#[doc = "`read()` method returns [mpcbb1_vctr26::R](mpcbb1_vctr26::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR26 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr26::W](mpcbb1_vctr26::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR26 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr26;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr27](mpcbb1_vctr27) module"]
pub type MPCBB1_VCTR27 = crate::Reg<u32, _MPCBB1_VCTR27>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR27;
#[doc = "`read()` method returns [mpcbb1_vctr27::R](mpcbb1_vctr27::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR27 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr27::W](mpcbb1_vctr27::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR27 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr27;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr28](mpcbb1_vctr28) module"]
pub type MPCBB1_VCTR28 = crate::Reg<u32, _MPCBB1_VCTR28>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR28;
#[doc = "`read()` method returns [mpcbb1_vctr28::R](mpcbb1_vctr28::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR28 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr28::W](mpcbb1_vctr28::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR28 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr28;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr29](mpcbb1_vctr29) module"]
pub type MPCBB1_VCTR29 = crate::Reg<u32, _MPCBB1_VCTR29>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR29;
#[doc = "`read()` method returns [mpcbb1_vctr29::R](mpcbb1_vctr29::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR29 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr29::W](mpcbb1_vctr29::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR29 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr29;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr30](mpcbb1_vctr30) module"]
pub type MPCBB1_VCTR30 = crate::Reg<u32, _MPCBB1_VCTR30>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR30;
#[doc = "`read()` method returns [mpcbb1_vctr30::R](mpcbb1_vctr30::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR30 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr30::W](mpcbb1_vctr30::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR30 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr30;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr31](mpcbb1_vctr31) module"]
pub type MPCBB1_VCTR31 = crate::Reg<u32, _MPCBB1_VCTR31>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR31;
#[doc = "`read()` method returns [mpcbb1_vctr31::R](mpcbb1_vctr31::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR31 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr31::W](mpcbb1_vctr31::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR31 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr31;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr32](mpcbb1_vctr32) module"]
pub type MPCBB1_VCTR32 = crate::Reg<u32, _MPCBB1_VCTR32>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR32;
#[doc = "`read()` method returns [mpcbb1_vctr32::R](mpcbb1_vctr32::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR32 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr32::W](mpcbb1_vctr32::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR32 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr32;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr33](mpcbb1_vctr33) module"]
pub type MPCBB1_VCTR33 = crate::Reg<u32, _MPCBB1_VCTR33>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR33;
#[doc = "`read()` method returns [mpcbb1_vctr33::R](mpcbb1_vctr33::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR33 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr33::W](mpcbb1_vctr33::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR33 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr33;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr34](mpcbb1_vctr34) module"]
pub type MPCBB1_VCTR34 = crate::Reg<u32, _MPCBB1_VCTR34>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR34;
#[doc = "`read()` method returns [mpcbb1_vctr34::R](mpcbb1_vctr34::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR34 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr34::W](mpcbb1_vctr34::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR34 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr34;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr35](mpcbb1_vctr35) module"]
pub type MPCBB1_VCTR35 = crate::Reg<u32, _MPCBB1_VCTR35>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR35;
#[doc = "`read()` method returns [mpcbb1_vctr35::R](mpcbb1_vctr35::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR35 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr35::W](mpcbb1_vctr35::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR35 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr35;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr36](mpcbb1_vctr36) module"]
pub type MPCBB1_VCTR36 = crate::Reg<u32, _MPCBB1_VCTR36>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR36;
#[doc = "`read()` method returns [mpcbb1_vctr36::R](mpcbb1_vctr36::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR36 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr36::W](mpcbb1_vctr36::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR36 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr36;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr37](mpcbb1_vctr37) module"]
pub type MPCBB1_VCTR37 = crate::Reg<u32, _MPCBB1_VCTR37>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR37;
#[doc = "`read()` method returns [mpcbb1_vctr37::R](mpcbb1_vctr37::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR37 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr37::W](mpcbb1_vctr37::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR37 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr37;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr38](mpcbb1_vctr38) module"]
pub type MPCBB1_VCTR38 = crate::Reg<u32, _MPCBB1_VCTR38>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR38;
#[doc = "`read()` method returns [mpcbb1_vctr38::R](mpcbb1_vctr38::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR38 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr38::W](mpcbb1_vctr38::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR38 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr38;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr39](mpcbb1_vctr39) module"]
pub type MPCBB1_VCTR39 = crate::Reg<u32, _MPCBB1_VCTR39>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR39;
#[doc = "`read()` method returns [mpcbb1_vctr39::R](mpcbb1_vctr39::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR39 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr39::W](mpcbb1_vctr39::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR39 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr39;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr40](mpcbb1_vctr40) module"]
pub type MPCBB1_VCTR40 = crate::Reg<u32, _MPCBB1_VCTR40>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR40;
#[doc = "`read()` method returns [mpcbb1_vctr40::R](mpcbb1_vctr40::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR40 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr40::W](mpcbb1_vctr40::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR40 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr40;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr41](mpcbb1_vctr41) module"]
pub type MPCBB1_VCTR41 = crate::Reg<u32, _MPCBB1_VCTR41>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR41;
#[doc = "`read()` method returns [mpcbb1_vctr41::R](mpcbb1_vctr41::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR41 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr41::W](mpcbb1_vctr41::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR41 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr41;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr42](mpcbb1_vctr42) module"]
pub type MPCBB1_VCTR42 = crate::Reg<u32, _MPCBB1_VCTR42>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR42;
#[doc = "`read()` method returns [mpcbb1_vctr42::R](mpcbb1_vctr42::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR42 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr42::W](mpcbb1_vctr42::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR42 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr42;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr43](mpcbb1_vctr43) module"]
pub type MPCBB1_VCTR43 = crate::Reg<u32, _MPCBB1_VCTR43>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR43;
#[doc = "`read()` method returns [mpcbb1_vctr43::R](mpcbb1_vctr43::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR43 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr43::W](mpcbb1_vctr43::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR43 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr43;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr44](mpcbb1_vctr44) module"]
pub type MPCBB1_VCTR44 = crate::Reg<u32, _MPCBB1_VCTR44>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR44;
#[doc = "`read()` method returns [mpcbb1_vctr44::R](mpcbb1_vctr44::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR44 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr44::W](mpcbb1_vctr44::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR44 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr44;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr45](mpcbb1_vctr45) module"]
pub type MPCBB1_VCTR45 = crate::Reg<u32, _MPCBB1_VCTR45>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR45;
#[doc = "`read()` method returns [mpcbb1_vctr45::R](mpcbb1_vctr45::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR45 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr45::W](mpcbb1_vctr45::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR45 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr45;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr46](mpcbb1_vctr46) module"]
pub type MPCBB1_VCTR46 = crate::Reg<u32, _MPCBB1_VCTR46>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR46;
#[doc = "`read()` method returns [mpcbb1_vctr46::R](mpcbb1_vctr46::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR46 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr46::W](mpcbb1_vctr46::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR46 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr46;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr47](mpcbb1_vctr47) module"]
pub type MPCBB1_VCTR47 = crate::Reg<u32, _MPCBB1_VCTR47>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR47;
#[doc = "`read()` method returns [mpcbb1_vctr47::R](mpcbb1_vctr47::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR47 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr47::W](mpcbb1_vctr47::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR47 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr47;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr48](mpcbb1_vctr48) module"]
pub type MPCBB1_VCTR48 = crate::Reg<u32, _MPCBB1_VCTR48>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR48;
#[doc = "`read()` method returns [mpcbb1_vctr48::R](mpcbb1_vctr48::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR48 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr48::W](mpcbb1_vctr48::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR48 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr48;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr49](mpcbb1_vctr49) module"]
pub type MPCBB1_VCTR49 = crate::Reg<u32, _MPCBB1_VCTR49>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR49;
#[doc = "`read()` method returns [mpcbb1_vctr49::R](mpcbb1_vctr49::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR49 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr49::W](mpcbb1_vctr49::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR49 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr49;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr50](mpcbb1_vctr50) module"]
pub type MPCBB1_VCTR50 = crate::Reg<u32, _MPCBB1_VCTR50>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR50;
#[doc = "`read()` method returns [mpcbb1_vctr50::R](mpcbb1_vctr50::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR50 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr50::W](mpcbb1_vctr50::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR50 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr50;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr51](mpcbb1_vctr51) module"]
pub type MPCBB1_VCTR51 = crate::Reg<u32, _MPCBB1_VCTR51>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR51;
#[doc = "`read()` method returns [mpcbb1_vctr51::R](mpcbb1_vctr51::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR51 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr51::W](mpcbb1_vctr51::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR51 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr51;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr52](mpcbb1_vctr52) module"]
pub type MPCBB1_VCTR52 = crate::Reg<u32, _MPCBB1_VCTR52>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR52;
#[doc = "`read()` method returns [mpcbb1_vctr52::R](mpcbb1_vctr52::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR52 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr52::W](mpcbb1_vctr52::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR52 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr52;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr53](mpcbb1_vctr53) module"]
pub type MPCBB1_VCTR53 = crate::Reg<u32, _MPCBB1_VCTR53>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR53;
#[doc = "`read()` method returns [mpcbb1_vctr53::R](mpcbb1_vctr53::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR53 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr53::W](mpcbb1_vctr53::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR53 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr53;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr54](mpcbb1_vctr54) module"]
pub type MPCBB1_VCTR54 = crate::Reg<u32, _MPCBB1_VCTR54>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR54;
#[doc = "`read()` method returns [mpcbb1_vctr54::R](mpcbb1_vctr54::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR54 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr54::W](mpcbb1_vctr54::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR54 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr54;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr55](mpcbb1_vctr55) module"]
pub type MPCBB1_VCTR55 = crate::Reg<u32, _MPCBB1_VCTR55>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR55;
#[doc = "`read()` method returns [mpcbb1_vctr55::R](mpcbb1_vctr55::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR55 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr55::W](mpcbb1_vctr55::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR55 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr55;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr56](mpcbb1_vctr56) module"]
pub type MPCBB1_VCTR56 = crate::Reg<u32, _MPCBB1_VCTR56>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR56;
#[doc = "`read()` method returns [mpcbb1_vctr56::R](mpcbb1_vctr56::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR56 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr56::W](mpcbb1_vctr56::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR56 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr56;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr57](mpcbb1_vctr57) module"]
pub type MPCBB1_VCTR57 = crate::Reg<u32, _MPCBB1_VCTR57>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR57;
#[doc = "`read()` method returns [mpcbb1_vctr57::R](mpcbb1_vctr57::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR57 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr57::W](mpcbb1_vctr57::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR57 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr57;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr58](mpcbb1_vctr58) module"]
pub type MPCBB1_VCTR58 = crate::Reg<u32, _MPCBB1_VCTR58>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR58;
#[doc = "`read()` method returns [mpcbb1_vctr58::R](mpcbb1_vctr58::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR58 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr58::W](mpcbb1_vctr58::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR58 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr58;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr59](mpcbb1_vctr59) module"]
pub type MPCBB1_VCTR59 = crate::Reg<u32, _MPCBB1_VCTR59>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR59;
#[doc = "`read()` method returns [mpcbb1_vctr59::R](mpcbb1_vctr59::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR59 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr59::W](mpcbb1_vctr59::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR59 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr59;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr60](mpcbb1_vctr60) module"]
pub type MPCBB1_VCTR60 = crate::Reg<u32, _MPCBB1_VCTR60>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR60;
#[doc = "`read()` method returns [mpcbb1_vctr60::R](mpcbb1_vctr60::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR60 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr60::W](mpcbb1_vctr60::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR60 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr60;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr61](mpcbb1_vctr61) module"]
pub type MPCBB1_VCTR61 = crate::Reg<u32, _MPCBB1_VCTR61>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR61;
#[doc = "`read()` method returns [mpcbb1_vctr61::R](mpcbb1_vctr61::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR61 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr61::W](mpcbb1_vctr61::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR61 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr61;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr62](mpcbb1_vctr62) module"]
pub type MPCBB1_VCTR62 = crate::Reg<u32, _MPCBB1_VCTR62>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR62;
#[doc = "`read()` method returns [mpcbb1_vctr62::R](mpcbb1_vctr62::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR62 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr62::W](mpcbb1_vctr62::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR62 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr62;
#[doc = "MPCBBx vector register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mpcbb1_vctr63](mpcbb1_vctr63) module"]
pub type MPCBB1_VCTR63 = crate::Reg<u32, _MPCBB1_VCTR63>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPCBB1_VCTR63;
#[doc = "`read()` method returns [mpcbb1_vctr63::R](mpcbb1_vctr63::R) reader structure"]
impl crate::Readable for MPCBB1_VCTR63 {}
#[doc = "`write(|w| ..)` method takes [mpcbb1_vctr63::W](mpcbb1_vctr63::W) writer structure"]
impl crate::Writable for MPCBB1_VCTR63 {}
#[doc = "MPCBBx vector register"]
pub mod mpcbb1_vctr63;
|
// Copyright 2015 MaidSafe.net limited
// This MaidSafe Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
// By contributing code to the MaidSafe Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0, found in the root
// directory of this project at LICENSE, COPYING and CONTRIBUTOR respectively and also
// available at: http://www.maidsafe.net/licenses
// Unless required by applicable law or agreed to in writing, the MaidSafe Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, either express or implied.
// See the Licences for the specific language governing permissions and limitations relating to
// use of the MaidSafe
// Software.
use types::{Authority, DhtId, DestinationAddress};
use super::{Action, RoutingError};
pub trait Facade : Sync + Send {
/// if reply is data then we send back the response message (ie get_response )
fn handle_get(&mut self,
type_id: u64,
our_authority: Authority,
from_authority: Authority,
from_address: DhtId,
data: Vec<u8>)
-> Result<Action, RoutingError>;
/// data: Vec<u8> is serialised maidsafe_types::Payload which holds typetag and content
fn handle_put(&mut self,
our_authority: Authority,
from_authority: Authority,
from_address: DhtId,
dest_address: DestinationAddress,
data: Vec<u8>)
-> Result<Action, RoutingError>;
fn handle_post(&mut self,
our_authority: Authority,
from_authority: Authority,
from_address: DhtId,
data: Vec<u8>)
-> Result<Action, RoutingError>;
fn handle_get_response(&mut self,
from_address: DhtId,
response: Result<Vec<u8>,
RoutingError>);
fn handle_put_response(&mut self,
from_authority: Authority,
from_address: DhtId,
response: Result<Vec<u8>,
RoutingError>);
fn handle_post_response(&mut self,
from_authority: Authority,
from_address: DhtId,
response: Result<Vec<u8>,
RoutingError>);
fn add_node(&mut self, node: DhtId);
fn drop_node(&mut self, node: DhtId);
}
#[test]
fn dummy() {
}
|
// 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::encoding::OutOfLine,
fidl_fuchsia_net_policy::{ObserverRequest, ObserverRequestStream},
fidl_fuchsia_net_stack::StackProxy,
fuchsia_syslog::fx_log_err,
fuchsia_zircon as zx,
futures::lock::Mutex,
futures::prelude::*,
std::collections::HashMap,
std::sync::Arc,
};
pub async fn serve_fidl_requests(
stack: StackProxy,
stream: ObserverRequestStream,
_interface_ids: Arc<Mutex<HashMap<String, u64>>>,
) -> Result<(), fidl::Error> {
stream
.try_for_each(|req| {
async {
match req {
ObserverRequest::ListInterfaces { responder } => {
let mut ifaces = stack.list_interfaces().await?;
responder.send(&mut ifaces.iter_mut(), zx::sys::ZX_OK)
}
ObserverRequest::GetInterfaceInfo { name, responder } => {
let mut ifaces = stack.list_interfaces().await?;
ifaces.retain(|i| i.properties.name == name);
let (mut result, status) = if ifaces.len() == 0 {
(None, zx::sys::ZX_ERR_NOT_FOUND)
} else if ifaces.len() == 1 {
(ifaces.pop(), zx::sys::ZX_OK)
} else {
fx_log_err!("{} nics have the same name {}", ifaces.len(), name);
(None, zx::sys::ZX_ERR_INTERNAL)
};
responder.send(result.as_mut().map(OutOfLine), status)
}
}
}
})
.await
}
#[cfg(test)]
mod tests {
use super::*;
use {
fidl::endpoints::create_proxy,
fidl_fuchsia_net_policy::{ObserverMarker, ObserverProxy},
fidl_fuchsia_net_stack::{
AdministrativeStatus, InterfaceAddress, InterfaceInfo, InterfaceProperties,
PhysicalStatus, StackMarker, StackRequest, StackRequestStream,
},
fuchsia_async as fasync,
futures::task::Poll,
pin_utils::pin_mut,
std::boxed::Box,
};
const ID1: u64 = 1;
const ID2: u64 = 2;
const NAME1: &str = "lo";
const NAME2: &str = "eth";
fn build_interface_properties(name: String) -> InterfaceProperties {
InterfaceProperties {
name: name,
topopath: "/all/the/way/home".to_owned(),
filepath: "/dev/class/ethernet/123".to_owned(),
mac: Some(Box::new(fidl_fuchsia_hardware_ethernet::MacAddress {
octets: [0, 1, 2, 255, 254, 253],
})),
mtu: 1500,
features: 2,
administrative_status: AdministrativeStatus::Enabled,
physical_status: PhysicalStatus::Up,
addresses: vec![InterfaceAddress {
ip_address: fidl_fuchsia_net::IpAddress::Ipv4(fidl_fuchsia_net::Ipv4Address {
addr: [1, 1, 1, 1],
}),
prefix_len: 4,
}],
}
}
fn build_interface_info(id: u64, name: String) -> InterfaceInfo {
InterfaceInfo { id: id, properties: build_interface_properties(name) }
}
fn setup_interface_tests() -> (fasync::Executor, impl Future, ObserverProxy, StackRequestStream)
{
let exec = fasync::Executor::new().expect("failed to create an executor");
// Set up mock stack fidl server.
let (stack_proxy, stack_server) =
create_proxy::<StackMarker>().expect("failed to create stack fidl");
let stack_stream =
stack_server.into_stream().expect("failed to create a stack request stream.");
// Set up real Observer fidl server and client.
let (observer_proxy, observer_server) =
create_proxy::<ObserverMarker>().expect("failed to create observer fidl");
let observer_stream =
observer_server.into_stream().expect("failed to create an observer request stream.");
// Create and initialize interface_ids
let mut interface_ids = HashMap::new();
interface_ids.insert(NAME1.to_owned(), ID1);
interface_ids.insert(NAME2.to_owned(), ID2);
let interface_ids = Arc::new(Mutex::new(interface_ids));
let observer_service_task =
serve_fidl_requests(stack_proxy, observer_stream, interface_ids)
.unwrap_or_else(|e| fx_log_err!("failed to serve observer FIDL call: {}", e));
(exec, observer_service_task, observer_proxy, stack_stream)
}
#[test]
fn list_interfaces_test() {
let (mut exec, observer_service_task, observer_proxy, mut stack_stream) =
setup_interface_tests();
// Call observer FIDL call.
let client_fut = observer_proxy.list_interfaces();
// Let observer client run to stall.
pin_mut!(client_fut);
assert!(exec.run_until_stalled(&mut client_fut).is_pending());
// Let observer server run to stall.
pin_mut!(observer_service_task);
assert!(exec.run_until_stalled(&mut observer_service_task).is_pending());
// Let stack server run to stall and check that we got an appropriate FIDL call.
let event = match exec.run_until_stalled(&mut stack_stream.next()) {
Poll::Ready(Some(Ok(req))) => req,
_ => panic!("Expected a stack fidl call, but there is none!"),
};
match event {
StackRequest::ListInterfaces { responder } => {
responder
.send(&mut vec![build_interface_info(ID2, NAME2.to_string())].iter_mut())
.expect("failed to send list interface response");
}
_ => panic!("Unexpected stack call!"),
};
assert!(exec.run_until_stalled(&mut observer_service_task).is_pending());
// Let observer client run until ready, and check that we got an expected response.
let (infos, status) = match exec.run_until_stalled(&mut client_fut) {
Poll::Ready(Ok(req)) => req,
other => panic!("Expected a response from observer fidl call, but got {:?}!", other),
};
assert_eq!(zx::sys::ZX_OK, status);
assert_eq!(vec![build_interface_info(ID2, NAME2.to_string())], infos);
}
#[test]
fn get_interface_info_test() {
let (mut exec, observer_service_task, observer_proxy, mut stack_stream) =
setup_interface_tests();
// Call observer FIDL call.
let client_fut = observer_proxy.get_interface_info(NAME2);
// Let observer client run to stall.
pin_mut!(client_fut);
assert!(exec.run_until_stalled(&mut client_fut).is_pending());
// Let observer server run to stall.
pin_mut!(observer_service_task);
assert!(exec.run_until_stalled(&mut observer_service_task).is_pending());
// Let stack server run to stall and check that we got an appropriate FIDL call.
let event = match exec.run_until_stalled(&mut stack_stream.next()) {
Poll::Ready(Some(Ok(req))) => req,
_ => panic!("Expected a stack fidl call, but there is none!"),
};
match event {
StackRequest::ListInterfaces { responder } => {
responder
.send(&mut vec![build_interface_info(ID2, NAME2.to_string())].iter_mut())
.expect("failed to send list interface response");
}
_ => panic!("Unexpected stack call!"),
};
assert!(exec.run_until_stalled(&mut observer_service_task).is_pending());
// Let observer client run until ready, and check that we got an expected response.
let (response, status) = match exec.run_until_stalled(&mut client_fut) {
Poll::Ready(Ok(req)) => req,
other => panic!("Expected a response from observer fidl call, but got {:?}", other),
};
assert_eq!(zx::sys::ZX_OK, status);
assert_eq!(build_interface_info(ID2, NAME2.to_string()), *response.unwrap());
}
#[test]
fn get_interface_info_not_found_test() {
let (mut exec, observer_service_task, observer_proxy, mut stack_stream) =
setup_interface_tests();
// Call observer FIDL call.
let client_fut = observer_proxy.get_interface_info("unknown");
// Let observer client run to stall.
pin_mut!(client_fut);
assert!(exec.run_until_stalled(&mut client_fut).is_pending());
// Let observer server run to stall.
pin_mut!(observer_service_task);
assert!(exec.run_until_stalled(&mut observer_service_task).is_pending());
// Let stack server run to stall and check that we got an appropriate FIDL call.
let event = match exec.run_until_stalled(&mut stack_stream.next()) {
Poll::Ready(Some(Ok(req))) => req,
_ => panic!("Expected a stack fidl call, but there is none!"),
};
match event {
StackRequest::ListInterfaces { responder } => {
responder
.send(&mut vec![build_interface_info(ID2, NAME2.to_string())].iter_mut())
.expect("failed to send list interface response");
}
_ => panic!("Unexpected stack call: {:?}", event),
};
assert!(exec.run_until_stalled(&mut observer_service_task).is_pending());
// Let observer client run to stall and check that we got an expected response.
let (_response, status) = match exec.run_until_stalled(&mut client_fut) {
Poll::Ready(Ok(req)) => req,
other => panic!("Expected a response from observer fidl call, but got {:?}", other),
};
assert_eq!(zx::Status::NOT_FOUND.into_raw(), status);
}
}
|
use std::collections::HashSet;
fn main() {
let n = read::<usize>();
let s = read::<String>();
let s = s.as_bytes();
let mut k = Vec::<usize>::new();
for i in 2..n {
let mut kind = HashSet::<u8>::new();
for ss in s.iter().skip(i) {
kind.insert(*ss);
}
k.push(kind.len());
}
let mut comp = HashSet::<[u8; 2]>::new();
let mut ans = 0;
for i in 0..n {
for j in i + 1..n {
if comp.contains(&[s[i], s[j]]) {
continue;
} else {
comp.insert([s[i], s[j]]);
ans += if j != n - 1 { k[j - 1] } else { 0 };
}
}
}
println!("{}", ans);
}
#[allow(dead_code)]
fn read<T: std::str::FromStr>() -> T {
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok();
s.trim().parse().ok().unwrap()
}
#[allow(dead_code)]
fn read_vec<T: std::str::FromStr>() -> Vec<T> {
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok();
s.trim()
.split_whitespace()
.map(|e| e.parse().ok().unwrap())
.collect()
}
#[allow(dead_code)]
fn read_vec2<T: std::str::FromStr>(n: u32) -> Vec<Vec<T>> {
(0..n).map(|_| read_vec()).collect()
}
|
use libc::{abort, c_char, c_int, exit, pid_t, EAGAIN};
use std::ffi::CStr;
use wasmer_runtime_core::Instance;
pub extern "C" fn abort_with_message(message: &str) {
debug!("emscripten::abort_with_message");
println!("{}", message);
_abort();
}
pub extern "C" fn _abort() {
debug!("emscripten::_abort");
unsafe {
abort();
}
}
pub extern "C" fn _fork(_instance: &mut Instance) -> pid_t {
debug!("emscripten::_fork");
// unsafe {
// fork()
// }
-1
}
pub extern "C" fn _exit(status: c_int, _instance: &mut Instance) -> ! {
debug!("emscripten::_exit {}", status);
unsafe { exit(status) }
}
pub extern "C" fn em_abort(message: u32, instance: &mut Instance) {
debug!("emscripten::em_abort {}", message);
let message_addr = instance.memory_offset_addr(0, message as usize) as *mut c_char;
unsafe {
let message = CStr::from_ptr(message_addr)
.to_str()
.unwrap_or("Unexpected abort");
abort_with_message(message);
}
}
pub extern "C" fn abort_stack_overflow() {
debug!("emscripten::abort_stack_overflow");
// TODO: Message incomplete. Need to finish em runtime data first
abort_with_message("Stack overflow! Attempted to allocate some bytes on the stack");
}
pub extern "C" fn _llvm_trap() {
debug!("emscripten::_llvm_trap");
abort_with_message("abort!");
}
pub extern "C" fn _system() -> c_int {
debug!("emscripten::_system");
// TODO: May need to change this Em impl to a working version
eprintln!("Can't call external programs");
return EAGAIN;
}
pub extern "C" fn _popen() -> c_int {
debug!("emscripten::_popen");
// TODO: May need to change this Em impl to a working version
eprintln!("Missing function: popen");
unsafe {
abort();
}
}
|
#![deny(warnings)]
#![deny(missing_docs)]
//! A real-time graphing experiment.
//!
//! rt-graph uses GTK (via the gtk-rs Rust bindings) for its UI and is
//! designed to be embedded into any gtk::Container in your
//! application.
#[macro_use]
extern crate derive_builder;
#[macro_use]
extern crate log;
use std::fmt::Debug;
mod graph;
pub use graph::{Config, ConfigBuilder, Graph, PointStyle, View, ViewMode};
mod graph_with_controls;
pub use graph_with_controls::GraphWithControls;
mod null_data_source;
pub use null_data_source::NullDataSource;
pub mod observable_value;
mod signal;
pub use signal::Signal;
mod store;
use store::Store;
mod test_data_generator;
pub use test_data_generator::TestDataGenerator;
/// Represents an error that could occur using the crate
#[derive(Debug)]
pub enum Error {
/// An error described by a `String`.
String(String),
}
/// Represents either a value or an error from the crate.
pub type Result<T> = std::result::Result<T, Error>;
/// A point in time when a data point was emitted.
pub type Time = u32;
/// The value of a data point
pub type Value = u16;
/// A data point on a graph.
#[derive(Debug, Clone)]
pub struct Point {
/// The time when this data point was emitted.
pub t: Time,
/// The values this point holds.
pub vs: Vec<Value>,
}
impl Point {
/// Return the time when this data point was emitted.
pub fn t(&self) -> Time {
self.t
}
/// Return the values that this point holds.
pub fn vals(&self) -> &[Value] {
&self.vs
}
}
/// A color in RGB format.
///
/// The tuple values are the red, green, and blue components of the
/// color respectively.
#[derive(Clone, Copy)]
pub struct Color(pub u8, pub u8, pub u8);
impl Color {
/// Create a color from red, green, and blue components.
pub fn from_rgb(r: u8, g: u8, b: u8) -> Color {
Color(r, g, b)
}
/// Return the red component of the `Color`.
pub fn r(&self) -> u8 {
self.0
}
/// Return the green component of the `Color`.
pub fn g(&self) -> u8 {
self.1
}
/// Return the blue component of the `Color`.
pub fn b(&self) -> u8 {
self.2
}
}
#[cfg(test)]
mod color_tests {
use super::Color;
#[test]
fn values() {
let c = Color::from_rgb(10, 20, 30);
assert_eq!(c.r(), 10);
assert_eq!(c.g(), 20);
assert_eq!(c.b(), 30);
}
}
/// Implement this to get your own data into a `Graph`.
pub trait DataSource: Debug + Send {
/// Return whatever points you have available when this method is called.
///
/// Each point must have a `t` field greater than the previous point.
///
/// Each point must have a `vs` field with length equal to the
/// value returned by `get_num_values`.
///
/// This is currently called once a frame.
fn get_data(&mut self) -> Result<Vec<Point>>;
/// The number of values that each Point will have.
fn get_num_values(&self) -> Result<usize>;
/// Return the colors you want to use to display each value of the graph.
///
/// Some sample colors are returned by default.
///
/// If you don't supply enough colors for the number of values
/// returned, these colors will be repeated.
fn get_colors(&self) -> Result<Vec<Color>> {
Ok(vec![Color(255u8, 0u8, 0u8),
Color(0u8, 255u8, 0u8),
Color(0u8, 0u8, 255u8)
])
}
}
|
//! Publications ページ
use yew::prelude::*;
pub struct Publications {}
impl Component for Publications {
type Message = ();
type Properties = ();
fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self {
Self {}
}
fn update(&mut self, _: Self::Message) -> ShouldRender {
false
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
html! {
<>
<h2>{"国際学会"}</h2>
<ul>
<li>
{"Multi-layered Graph Representation Learning with Edge Restructured Pooling"}<br/>
{"Atsushi Miyamoto, Koji Fukuda, and "}
<strong>{"Yicheng Du"}</strong><br/>
{"ECML-PKDD 2019 Workshop (Graph Embedding and Mining) "}
<a href="https://github.com/gem-ecmlpkdd/gem-ecmlpkdd.github.io/raw/ae2663929a12dad8aa7982a598ddf8d0adc3a05e/papers/GEM2019_paper_14.pdf">{"[PDF]"}</a>
</li>
<li>
{"Semi-supervised Multichannel Speech Separation Based on a Phone- and Speaker-Aware Deep Generative Model of Speech Spectrograms"}<br/>
<strong>{"Yicheng Du"}</strong>
{", Kouhei Sekiguchi, Yoshiaki Bando, Aditya Arie Nugraha, Mathieu Fontaine, Kazuyoshi Yoshii, and Tatsuya Kawahara"}<br/>
{"EUSIPCO 2020 "}
<a href="https://ieeexplore.ieee.org/document/9287464">{"[IEEE Xplore]"}</a>
<a href="https://www.eurasip.org/Proceedings/Eusipco/Eusipco2020/pdfs/0000870.pdf">{"[PDF]"}</a>
</li>
<li>
{"Computationally-Efficient Overdetermined Blind Source Separation Based on Iterative Source Steering"}<br/>
<strong>{"Yicheng Du"}</strong>
{", Robin Scheibler, Masahito Togami, Kazuyoshi Yoshii, and Tatsuya Kawahara"}<br/>
{"ICASSP 2021 (Under review)"}
</li>
</ul>
<h2>{"国内学会"}</h2>
<ul>
<li>
{"話者・音素特徴に基づくマルチチャネル音声分離"}<br/>
<strong>{"Yicheng Du,"}</strong>
{"關口航平,坂東宜昭,Aditya Arie Nugraha,吉井和佳"}<br/>
{"情報処理学会全国大会 (学生奨励賞受賞)"}
</li>
</ul>
</>
}
}
}
|
// 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 carnelian::{
App, AppAssistant, Color, Label, Paint, Point, Rect, Size, ViewAssistant, ViewAssistantContext,
ViewAssistantPtr,
};
use failure::Error;
use fidl_fuchsia_ui_gfx as gfx;
use fidl_fuchsia_ui_input::{InputEvent::Pointer, PointerEvent, PointerEventPhase};
use fuchsia_scenic::{EntityNode, Material, Rectangle, SessionPtr, ShapeNode};
use std::any::Any;
/// enum that defines all messages sent with `App::send_message` that
/// the button view assistant will understand and process.
pub enum ButtonMessages {
Pressed,
}
// Utility routine to create the FontDescription structure that
// canvas wants for filling text.
fn set_node_color(session: &SessionPtr, node: &ShapeNode, color: &Color) {
let material = Material::new(session.clone());
material.set_color(color.make_color_rgba());
node.set_material(&material);
}
struct ButtonAppAssistant;
impl AppAssistant for ButtonAppAssistant {
fn setup(&mut self) -> Result<(), Error> {
Ok(())
}
fn create_view_assistant(&mut self, session: &SessionPtr) -> Result<ViewAssistantPtr, Error> {
Ok(Box::new(ButtonViewAssistant::new(session)?))
}
}
struct Button {
label: Label,
background_node: ShapeNode,
container: EntityNode,
bounds: Rect,
bg_color: Color,
bg_color_active: Color,
fg_color: Color,
tracking: bool,
active: bool,
}
impl Button {
pub fn new(session: &SessionPtr, text: &str) -> Result<Button, Error> {
let mut button = Button {
label: Label::new(session, text)?,
background_node: ShapeNode::new(session.clone()),
container: EntityNode::new(session.clone()),
bounds: Rect::zero(),
fg_color: Color::white(),
bg_color: Color::from_hash_code("#404040")?,
bg_color_active: Color::from_hash_code("#808080")?,
tracking: false,
active: false,
};
// set up the button background
button.container.add_child(&button.background_node);
set_node_color(session, &button.background_node, &button.bg_color);
// Add the label
button.container.add_child(button.label.node());
Ok(button)
}
pub fn update(&mut self, context: &ViewAssistantContext) -> Result<(), Error> {
// set up paint with different backgrounds depending on whether the button
// is active. The active state is true when a pointer has gone down in the
// button's bounds and the pointer has not moved outside the bounds since.
let paint = Paint {
fg: self.fg_color,
bg: if self.active { self.bg_color_active } else { self.bg_color },
};
// center the button in the Scenic view by translating the
// container node. All child nodes will be positioned relative
// to this container
let center_x = context.size.width * 0.5;
let center_y = context.size.height * 0.5;
// pick font size and padding based on the available space
let min_dimension = context.size.width.min(context.size.height);
let font_size = (min_dimension / 5.0).ceil().min(64.0) as u32;
let padding = (min_dimension / 20.0).ceil().max(8.0);
self.container.set_translation(center_x, center_y, 0.0);
set_node_color(context.session, &self.background_node, &paint.bg);
// calculate button size based on label's text size
// plus padding.
let button_size = self.label.dimensions(font_size);
let button_w = button_size.width + 2.0 * padding;
let button_h = button_size.height + 2.0 * padding;
// record bounds for hit testing
self.bounds = Rect::new(
Point::new(center_x - button_w / 2.0, center_y - button_h / 2.0),
Size::new(button_w, button_h),
)
.round_out();
self.background_node.set_shape(&Rectangle::new(
context.session.clone(),
self.bounds.size.width,
self.bounds.size.height,
));
self.label.update(font_size, &paint)?;
Ok(())
}
pub fn node(&mut self) -> &EntityNode {
&self.container
}
pub fn handle_pointer_event(
&mut self,
context: &mut ViewAssistantContext,
pointer_event: &PointerEvent,
) {
// TODO: extend this to support multiple pointers
match pointer_event.phase {
PointerEventPhase::Down => {
self.active = self.bounds.contains(&Point::new(pointer_event.x, pointer_event.y));
self.tracking = self.active;
}
PointerEventPhase::Add => {}
PointerEventPhase::Hover => {}
PointerEventPhase::Move => {
if self.tracking {
self.active =
self.bounds.contains(&Point::new(pointer_event.x, pointer_event.y));
}
}
PointerEventPhase::Up => {
if self.active {
context.queue_message(&ButtonMessages::Pressed);
}
self.tracking = false;
self.active = false;
}
PointerEventPhase::Remove => {
self.active = false;
self.tracking = false;
}
PointerEventPhase::Cancel => {
self.active = false;
self.tracking = false;
}
}
}
}
struct ButtonViewAssistant {
background_node: ShapeNode,
indicator: ShapeNode,
button: Button,
red_light: bool,
}
impl ButtonViewAssistant {
fn new(session: &SessionPtr) -> Result<ButtonViewAssistant, Error> {
Ok(ButtonViewAssistant {
background_node: ShapeNode::new(session.clone()),
indicator: ShapeNode::new(session.clone()),
button: Button::new(&session, "Touch Me")?,
red_light: false,
})
}
fn handle_pointer_event(
&mut self,
context: &mut ViewAssistantContext,
pointer_event: &PointerEvent,
) {
self.button.handle_pointer_event(context, pointer_event);
}
}
impl ViewAssistant for ButtonViewAssistant {
// Called once by Carnelian when the view is first created. Good for setup
// that isn't concerned with the size of the view.
fn setup(&mut self, context: &ViewAssistantContext) -> Result<(), Error> {
// Let scenic know we're interested in changes to metrics for this node.
context.import_node.resource().set_event_mask(gfx::METRICS_EVENT_MASK);
context.import_node.add_child(&self.background_node);
set_node_color(context.session, &self.background_node, &Color::from_hash_code("#b7410e")?);
context.import_node.add_child(&self.indicator);
context.import_node.add_child(self.button.node());
Ok(())
}
// Called by Carnelian when the view is resized, after input events are processed
// or if sent an explicit Update message.
fn update(&mut self, context: &ViewAssistantContext) -> Result<(), Error> {
// Position and size the background
let center_x = context.size.width * 0.5;
let center_y = context.size.height * 0.5;
self.background_node.set_shape(&Rectangle::new(
context.session.clone(),
context.size.width,
context.size.height,
));
self.background_node.set_translation(center_x, center_y, 0.0);
// Position and size the indicator
let indicator_y = context.size.height / 5.0;
let indicator_size = context.size.height.min(context.size.width) / 8.0;
self.indicator.set_shape(&Rectangle::new(
context.session.clone(),
indicator_size,
indicator_size,
));
self.indicator.set_translation(center_x, indicator_y, -5.0);
let indicator_color = if self.red_light {
Color::from_hash_code("#ff0000")?
} else {
Color::from_hash_code("#00ff00")?
};
set_node_color(context.session, &self.indicator, &indicator_color);
// Update and position the button
self.button.update(context)?;
self.button.node().set_translation(center_x, center_y, 0.0);
Ok(())
}
fn handle_message(&mut self, _: &dyn Any) {
// TODO: downcast the message to ensure that it is
// ButtonMessages::Pressed.
self.red_light = !self.red_light;
}
fn handle_input_event(
&mut self,
context: &mut ViewAssistantContext,
event: &fidl_fuchsia_ui_input::InputEvent,
) -> Result<(), Error> {
match event {
Pointer(pointer_event) => {
self.handle_pointer_event(context, &pointer_event);
}
_ => (),
}
Ok(())
}
}
fn main() -> Result<(), Error> {
let assistant = ButtonAppAssistant {};
App::run(Box::new(assistant))
}
|
// RGB standard library
// Written in 2020 by
// Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.
use core::ops::Neg;
use num_derive::{FromPrimitive, ToPrimitive};
use num_traits::ToPrimitive;
use lnpbp::rgb::schema::{
script, AssignmentAction, Bits, DataFormat, DiscreteFiniteFieldFormat, GenesisSchema,
Occurences, Schema, StateFormat, StateSchema, TransitionSchema,
};
use crate::error::ServiceErrorDomain;
use crate::type_map;
#[derive(Debug, Display, Error, From)]
#[display_from(Debug)]
pub enum SchemaError {
#[derive_from(core::option::NoneError)]
NotAllFieldsPresent,
WrongSchemaId,
}
impl From<SchemaError> for ServiceErrorDomain {
fn from(err: SchemaError) -> Self {
ServiceErrorDomain::Schema(format!("{}", err))
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, Display, ToPrimitive, FromPrimitive)]
#[display_from(Debug)]
#[repr(u16)]
pub enum FieldType {
Ticker = 0,
Name = 1,
Description = 2,
TotalSupply = 3,
IssuedSupply = 4,
DustLimit = 5,
Precision = 6,
PruneProof = 7,
Timestamp = 8,
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, Display, ToPrimitive, FromPrimitive)]
#[display_from(Debug)]
#[repr(u16)]
pub enum AssignmentsType {
Issue = 0,
Assets = 1,
Prune = 2,
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, Display, ToPrimitive, FromPrimitive)]
#[display_from(Debug)]
#[repr(u16)]
pub enum TransitionType {
Issue = 0,
Transfer = 1,
Prune = 2,
}
pub fn schema() -> Schema {
Schema {
field_types: type_map! {
// Rational: if we will use just 26 letters of English alphabet (and
// we are not limited by them), we will have 26^8 possible tickers,
// i.e. > 208 trillions, which is sufficient amount
FieldType::Ticker => DataFormat::String(8),
FieldType::Name => DataFormat::String(256),
// Description may contain URL, text or text representation of
// Ricardian contract. We use all available size, in case the
// contract is long. If the contract still doesn't fit, a hash or
// URL should be used instead, pointing to the full contract text
FieldType::Description => DataFormat::String(core::u16::MAX),
FieldType::TotalSupply => DataFormat::Unsigned(Bits::Bit64, 0, core::u64::MAX as u128),
FieldType::Precision => DataFormat::Unsigned(Bits::Bit8, 0, 18u128),
FieldType::IssuedSupply => DataFormat::Unsigned(Bits::Bit64, 0, core::u64::MAX as u128),
FieldType::DustLimit => DataFormat::Unsigned(Bits::Bit64, 0, core::u64::MAX as u128),
FieldType::PruneProof => DataFormat::Bytes(core::u16::MAX),
// While UNIX timestamps allow negative numbers; in context of RGB Schema, assets
// can't be issued in the past before RGB or Bitcoin even existed; so we prohibit
// all the dates before RGB release
// TODO: Update lower limit with the first RGB release
// Current lower time limit is 07/04/2020 @ 1:54pm (UTC)
FieldType::Timestamp => DataFormat::Integer(Bits::Bit64, 1593870844, core::i64::MAX as i128)
},
assignment_types: type_map! {
AssignmentsType::Issue => StateSchema {
format: StateFormat::Declarative,
abi: bmap! {
AssignmentAction::Validate => script::Procedure::Standard(script::StandardProcedure::IssueControl)
}
},
AssignmentsType::Assets => StateSchema {
format: StateFormat::DiscreteFiniteField(DiscreteFiniteFieldFormat::Unsigned64bit),
abi: bmap! {
AssignmentAction::Validate => script::Procedure::Standard(script::StandardProcedure::ConfidentialAmount)
}
},
AssignmentsType::Prune => StateSchema {
format: StateFormat::Declarative,
abi: bmap! {
AssignmentAction::Validate => script::Procedure::Standard(script::StandardProcedure::Prunning)
}
}
},
genesis: GenesisSchema {
metadata: type_map! {
FieldType::Ticker => Occurences::Once,
FieldType::Name => Occurences::Once,
FieldType::Description => Occurences::NoneOrOnce,
FieldType::TotalSupply => Occurences::Once,
FieldType::IssuedSupply => Occurences::Once,
FieldType::DustLimit => Occurences::NoneOrOnce,
FieldType::Precision => Occurences::Once,
FieldType::Timestamp => Occurences::Once
},
defines: type_map! {
AssignmentsType::Issue => Occurences::NoneOrOnce,
AssignmentsType::Assets => Occurences::NoneOrUpTo(None),
AssignmentsType::Prune => Occurences::NoneOrUpTo(None)
},
abi: bmap! {},
},
transitions: type_map! {
TransitionType::Issue => TransitionSchema {
metadata: type_map! {
FieldType::IssuedSupply => Occurences::Once
},
closes: type_map! {
AssignmentsType::Issue => Occurences::Once
},
defines: type_map! {
AssignmentsType::Issue => Occurences::NoneOrOnce,
AssignmentsType::Prune => Occurences::NoneOrUpTo(None),
AssignmentsType::Assets => Occurences::NoneOrUpTo(None)
},
abi: bmap! {}
},
TransitionType::Transfer => TransitionSchema {
metadata: type_map! {},
closes: type_map! {
AssignmentsType::Assets => Occurences::OnceOrUpTo(None)
},
defines: type_map! {
AssignmentsType::Assets => Occurences::NoneOrUpTo(None)
},
abi: bmap! {}
},
TransitionType::Prune => TransitionSchema {
metadata: type_map! {
FieldType::PruneProof => Occurences::NoneOrUpTo(None)
},
closes: type_map! {
AssignmentsType::Prune => Occurences::OnceOrUpTo(None),
AssignmentsType::Assets => Occurences::OnceOrUpTo(None)
},
defines: type_map! {
AssignmentsType::Prune => Occurences::NoneOrUpTo(None),
AssignmentsType::Assets => Occurences::NoneOrUpTo(None)
},
abi: bmap! {}
}
},
}
}
impl Neg for FieldType {
type Output = usize;
fn neg(self) -> Self::Output {
self.to_usize().unwrap()
}
}
impl Neg for AssignmentsType {
type Output = usize;
fn neg(self) -> Self::Output {
self.to_usize().unwrap()
}
}
impl Neg for TransitionType {
type Output = usize;
fn neg(self) -> Self::Output {
self.to_usize().unwrap()
}
}
|
use syn::export::{Span, ToTokens};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{parenthesized, token, Error, Ident, ImplItemMethod, Token};
pub struct CallbackArgs {
#[allow(dead_code)]
paren_token: token::Paren,
args: Punctuated<Ident, Token![,]>,
}
impl Parse for CallbackArgs {
fn parse(input: ParseStream) -> syn::Result<Self> {
let content;
Ok(Self {
paren_token: parenthesized!(content in input),
args: content.parse_terminated(Ident::parse)?,
})
}
}
/// Parses attributes searching for `#[callback_args(arg0, arg1)]` marker attribute.
/// If found returns a vector of identities `arg0`, `arg1`, etc.
pub fn parse_args(method: &ImplItemMethod) -> syn::Result<Option<Vec<String>>> {
let attributes = &method.attrs;
let mut res = None;
for attr in attributes {
if attr.path.to_token_stream().to_string().as_str() == "callback_args" {
if res.is_some() {
return Err(Error::new(
Span::call_site(),
"Only one #[callback_args(...)] attribute is allowed per method.",
));
}
let parsed: CallbackArgs = syn::parse2(attr.tokens.clone())?;
if parsed.args.is_empty() {
return Err(Error::new(
Span::call_site(),
"#[callback_args(...)] should use at least one argument.",
));
}
res = Some(parsed.args.iter().map(|arg| arg.to_string()).collect());
}
}
Ok(res)
}
#[cfg(test)]
mod tests {
use super::parse_args;
use quote::quote;
use syn::ImplItemMethod;
#[test]
fn standard() {
let method: ImplItemMethod = syn::parse2(quote! {
#[some_attribute0 tokens ? & hello]
#[callback_args(arg0, arg1)]
#[some_attribute1 tokens ->]
fn simple_function() {
}
})
.unwrap();
let actual = parse_args(&method).unwrap();
let expected = Some(vec!["arg0".to_string(), "arg1".to_string()]);
assert_eq!(actual, expected);
}
#[test]
fn one_arg() {
let method: ImplItemMethod = syn::parse2(quote! {
#[callback_args(arg0)]
fn simple_function() {
}
})
.unwrap();
let actual = parse_args(&method).unwrap();
let expected = Some(vec!["arg0".to_string()]);
assert_eq!(actual, expected);
}
}
|
// 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 super::super::futex::*;
use super::entry::*;
use super::*;
#[derive(Default)]
pub struct WaitList {
head: Option<WaitEntry>,
tail: Option<WaitEntry>,
}
impl WaitList {
//remove all of the wait entries
pub fn Reset(&mut self) {
let mut cur = self.head.clone();
self.head = None;
self.tail = None;
while cur.is_some() {
let tmp = cur.clone().unwrap();
let next = tmp.lock().next.clone();
tmp.Reset();
cur = next;
}
}
pub fn Empty(&self) -> bool {
return self.head.is_none()
}
pub fn Front(&self) -> Option<WaitEntry> {
return self.head.clone();
}
pub fn Back(&self) -> Option<WaitEntry> {
return self.tail.clone();
}
pub fn PushFront(&mut self, e: &WaitEntry) {
assert!(e.InitState(), "waitlist PushFront WaitEntry is not in init statue");
//e.Reset();
if self.head.is_none() {
//empty
self.head = Some(e.clone());
self.tail = Some(e.clone())
} else {
let head = self.head.clone().unwrap();
e.lock().next = Some(head.clone());
head.lock().prev = Some(e.clone());
self.head = Some(e.clone());
}
}
pub fn PushBack(&mut self, e: &WaitEntry) {
assert!(e.InitState(), "waitlist PushBack WaitEntry is not in init statue");
//e.Reset();
if self.head.is_none() {
//empty
self.head = Some(e.clone());
self.tail = Some(e.clone())
} else {
let tail = self.tail.clone().unwrap();
e.lock().prev = Some(tail.clone());
tail.lock().next = Some(e.clone());
self.tail = Some(e.clone());
}
}
pub fn RemoveAll(&mut self) {
self.Reset();
}
pub fn Remove(&mut self, e: &WaitEntry) {
if e.lock().prev.is_none() {
//head
self.head = e.lock().next.clone();
} else {
let lock = e.lock();
lock.prev.clone().unwrap().lock().next = lock.next.clone();
}
if e.lock().next.is_none() {
//tail
self.tail = e.lock().prev.clone();
} else {
let lock = e.lock();
lock.next.clone().unwrap().lock().prev = lock.prev.clone();
}
e.Reset();
}
// for futex, wakeLocked wakes up to n waiters matching the bitmask at the addr for this
// queue and returns the number of waiters woken.
// unlike Notify, Wake will remove the trigged waitentry
pub fn WakeLocked(&mut self, mask: EventMask, n: i32) -> i32 {
let q = self;
let mut done = 0;
let mut entry = q.Front();
while entry.is_some() && done < n {
let tmp = entry.clone().unwrap();
entry = tmp.lock().next.clone();
/*let triggered = tmp.Notify(mask);
if triggered {
done += 1;
q.Remove(&tmp)
}
tmp.lock().key = Key::default();*/
if q.WakeWaiterLocked(&tmp, mask) {
done += 1;
}
}
return done;
}
pub fn WakeWaiterLocked(&mut self, w: &WaitEntry, mask: EventMask) -> bool {
let triggered = w.Notify(mask);
if triggered {
self.Remove(&w)
}
w.lock().context.ThreadContext().key = Key::default();
return triggered;
}
// requeueLocked takes n waiters from the waitlist and moves them to naddr on the
// waitlist "to".
pub fn RequeueLocked(&mut self, to: &mut Self, nKey: &Key, n: i32) -> i32 {
let mut done = 0;
let mut w = self.Front();
while w.is_some() && done < n {
let tmp = w.clone().unwrap();
let requeued = tmp.clone();
w = tmp.lock().next.clone();
self.Remove(&requeued);
to.PushBack(&requeued);
requeued.lock().context.ThreadContext().key = *nKey;
done += 1;
}
return done;
}
}
|
mod compilation;
pub use compilation::WasmCompilation;
mod hostcall;
pub use hostcall::Hostcall;
mod event_processing;
pub use event_processing::EventProcessing;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum State {
Beginning,
Cached,
Completed,
}
impl State {
/// Cheaply turn into a `&'static str` so you don't need to format it for metrics.
pub fn as_const_str(&self) -> &'static str {
match self {
State::Beginning => BEGINNING,
State::Completed => COMPLETED,
State::Cached => CACHED,
}
}
}
const BEGINNING: &str = "beginning";
const COMPLETED: &str = "completed";
const CACHED: &str = "cached";
|
use proconio::input;
fn main() {
input! {
n: usize,
m: usize,
mut a: [usize; n],
};
a.sort();
let mut b = a.clone();
b.extend(a.clone());
// eprintln!("{:?}", b);
let mut sums = Vec::new();
let mut last = 0;
for i in 0..n {
if i < last {
continue;
}
// eprintln!("last = {}, {:?}", last, &b[last..]);
assert_eq!(i, last);
let mut s = b[i];
last += 1;
while last < b.len()
&& last - i < n
&& (b[last - 1] == b[last] || (b[last - 1] + 1) % m == b[last])
{
s += b[last];
last += 1;
}
sums.push(s);
}
let total = a.iter().sum::<usize>();
let max = sums.iter().max().copied().unwrap();
assert!(total >= max);
let ans = total - max;
println!("{}", ans);
}
|
//! Capstone-based translator for 32-bit x86.
use crate::il::*;
use crate::translator::x86::mode::Mode;
use crate::translator::{unhandled_intrinsic, BlockTranslationResult, Options};
use crate::Error;
use falcon_capstone::{capstone, capstone_sys};
use crate::translator::x86::semantics::Semantics;
fn ensure_block_instruction(control_flow_graph: &mut ControlFlowGraph) -> Result<(), Error> {
let head_block_num_instructions = control_flow_graph
.block(control_flow_graph.entry().unwrap())?
.instructions()
.len();
if head_block_num_instructions == 0 {
let head_index = control_flow_graph.entry().unwrap();
control_flow_graph.block_mut(head_index)?.nop();
}
Ok(())
}
pub(crate) fn translate_block(
mode: Mode,
bytes: &[u8],
address: u64,
options: &Options,
) -> Result<BlockTranslationResult, Error> {
let cs = match mode {
Mode::X86 => capstone::Capstone::new(capstone::cs_arch::CS_ARCH_X86, capstone::CS_MODE_32),
Mode::Amd64 => {
capstone::Capstone::new(capstone::cs_arch::CS_ARCH_X86, capstone::CS_MODE_64)
}
}?;
cs.option(
capstone::cs_opt_type::CS_OPT_DETAIL,
capstone::cs_opt_value::CS_OPT_ON,
)
.unwrap();
// A vec which holds each lifted instruction in this block.
let mut block_graphs: Vec<(u64, ControlFlowGraph)> = Vec::new();
// the length of this block in bytes
let mut length: usize = 0;
let mut successors = Vec::new();
let mut offset: usize = 0;
loop {
/* We must have at least 16 bytes left in the buffer. */
// if bytes.len() - offset < 16 {
// successors.push((address + offset as u64, None));
// break;
// }
let disassembly_range = (offset)..bytes.len();
let disassembly_bytes = bytes.get(disassembly_range).unwrap();
let instructions = match cs.disasm(disassembly_bytes, address + offset as u64, 1) {
Ok(instructions) => instructions,
Err(e) => match e.code() {
// We can reach this in a couple of circumstances.
// One circumstance is there isn't enough data in disassembly_bytes
// to disassemble the next instruction, in which case we need to return
// and let the translator give us more bytes.
//
// Another case is just capstone has gone bonkers. In this case, return
// a DisassemblyFailure error.
//
// We can tell the difference based on offset. If it's non-zero, first
// case. If zero, second case.
capstone_sys::cs_err::CS_ERR_OK => {
if offset == 0 {
return Err(Error::DisassemblyFailure);
}
successors.push((address + offset as u64, None));
break;
}
_ => return Err(Error::CapstoneError),
},
};
if instructions.count() == 0 {
return Err("Capstone failed to disassemble any instruction".into());
}
let instruction = instructions.get(0).unwrap();
if let capstone::InstrIdArch::X86(instruction_id) = instruction.id {
let semantics = Semantics::new(&mode, &instruction);
let mut instruction_graph = ControlFlowGraph::new();
match instruction_id {
capstone::x86_insn::X86_INS_ADC => semantics.adc(&mut instruction_graph),
capstone::x86_insn::X86_INS_ADD => semantics.add(&mut instruction_graph),
capstone::x86_insn::X86_INS_AND => semantics.and(&mut instruction_graph),
capstone::x86_insn::X86_INS_BSF => semantics.bsf(&mut instruction_graph),
capstone::x86_insn::X86_INS_BSR => semantics.bsr(&mut instruction_graph),
capstone::x86_insn::X86_INS_BSWAP => semantics.bswap(&mut instruction_graph),
capstone::x86_insn::X86_INS_BT => semantics.bt(&mut instruction_graph),
capstone::x86_insn::X86_INS_BTC => semantics.btc(&mut instruction_graph),
capstone::x86_insn::X86_INS_BTR => semantics.bts(&mut instruction_graph),
capstone::x86_insn::X86_INS_BTS => semantics.btr(&mut instruction_graph),
capstone::x86_insn::X86_INS_CALL => semantics.call(&mut instruction_graph),
capstone::x86_insn::X86_INS_CBW => semantics.cbw(&mut instruction_graph),
capstone::x86_insn::X86_INS_CDQ => semantics.cdq(&mut instruction_graph),
capstone::x86_insn::X86_INS_CDQE => semantics.cdqe(&mut instruction_graph),
capstone::x86_insn::X86_INS_CLC => semantics.clc(&mut instruction_graph),
capstone::x86_insn::X86_INS_CLD => semantics.cld(&mut instruction_graph),
capstone::x86_insn::X86_INS_CLI => semantics.cli(&mut instruction_graph),
capstone::x86_insn::X86_INS_CMC => semantics.cmc(&mut instruction_graph),
capstone::x86_insn::X86_INS_CMOVA
| capstone::x86_insn::X86_INS_CMOVAE
| capstone::x86_insn::X86_INS_CMOVB
| capstone::x86_insn::X86_INS_CMOVBE
| capstone::x86_insn::X86_INS_CMOVE
| capstone::x86_insn::X86_INS_CMOVG
| capstone::x86_insn::X86_INS_CMOVGE
| capstone::x86_insn::X86_INS_CMOVL
| capstone::x86_insn::X86_INS_CMOVLE
| capstone::x86_insn::X86_INS_CMOVNE
| capstone::x86_insn::X86_INS_CMOVNO
| capstone::x86_insn::X86_INS_CMOVNP
| capstone::x86_insn::X86_INS_CMOVNS
| capstone::x86_insn::X86_INS_CMOVO
| capstone::x86_insn::X86_INS_CMOVP
| capstone::x86_insn::X86_INS_CMOVS => semantics.cmovcc(&mut instruction_graph),
capstone::x86_insn::X86_INS_CMP => semantics.cmp(&mut instruction_graph),
capstone::x86_insn::X86_INS_CMPSB => semantics.cmpsb(&mut instruction_graph),
capstone::x86_insn::X86_INS_CMPXCHG => semantics.cmpxchg(&mut instruction_graph),
capstone::x86_insn::X86_INS_CWD => semantics.cwd(&mut instruction_graph),
capstone::x86_insn::X86_INS_CWDE => semantics.cwde(&mut instruction_graph),
capstone::x86_insn::X86_INS_DEC => semantics.dec(&mut instruction_graph),
capstone::x86_insn::X86_INS_DIV => semantics.div(&mut instruction_graph),
capstone::x86_insn::X86_INS_HLT => semantics.nop(&mut instruction_graph),
capstone::x86_insn::X86_INS_IDIV => semantics.idiv(&mut instruction_graph),
capstone::x86_insn::X86_INS_IMUL => semantics.imul(&mut instruction_graph),
capstone::x86_insn::X86_INS_INC => semantics.inc(&mut instruction_graph),
capstone::x86_insn::X86_INS_INT => semantics.int(&mut instruction_graph),
// conditional jumps will only emit a brc if the destination is undetermined at
// translation time
capstone::x86_insn::X86_INS_JA
| capstone::x86_insn::X86_INS_JAE
| capstone::x86_insn::X86_INS_JB
| capstone::x86_insn::X86_INS_JBE
| capstone::x86_insn::X86_INS_JCXZ
| capstone::x86_insn::X86_INS_JECXZ
| capstone::x86_insn::X86_INS_JE
| capstone::x86_insn::X86_INS_JG
| capstone::x86_insn::X86_INS_JGE
| capstone::x86_insn::X86_INS_JL
| capstone::x86_insn::X86_INS_JLE
| capstone::x86_insn::X86_INS_JNE
| capstone::x86_insn::X86_INS_JNO
| capstone::x86_insn::X86_INS_JNP
| capstone::x86_insn::X86_INS_JNS
| capstone::x86_insn::X86_INS_JO
| capstone::x86_insn::X86_INS_JP
| capstone::x86_insn::X86_INS_JS => semantics.cjmp(&mut instruction_graph),
// unconditional jumps will only emit a brc if the destination is undetermined at
// translation time
capstone::x86_insn::X86_INS_JMP => semantics.jmp(&mut instruction_graph),
capstone::x86_insn::X86_INS_LEA => semantics.lea(&mut instruction_graph),
capstone::x86_insn::X86_INS_LEAVE => semantics.leave(&mut instruction_graph),
capstone::x86_insn::X86_INS_LODSB => semantics.lodsb(&mut instruction_graph),
capstone::x86_insn::X86_INS_LODSD => semantics.lodsd(&mut instruction_graph),
capstone::x86_insn::X86_INS_LOOP => semantics.loop_(&mut instruction_graph),
capstone::x86_insn::X86_INS_LOOPE => semantics.loop_(&mut instruction_graph),
capstone::x86_insn::X86_INS_LOOPNE => semantics.loop_(&mut instruction_graph),
capstone::x86_insn::X86_INS_MOVHPD => semantics.movhpd(&mut instruction_graph),
capstone::x86_insn::X86_INS_MOVLPD => semantics.movlpd(&mut instruction_graph),
capstone::x86_insn::X86_INS_MOV
| capstone::x86_insn::X86_INS_MOVABS
| capstone::x86_insn::X86_INS_MOVAPS
| capstone::x86_insn::X86_INS_MOVAPD
| capstone::x86_insn::X86_INS_MOVDQA
| capstone::x86_insn::X86_INS_MOVDQU
| capstone::x86_insn::X86_INS_MOVNTI
| capstone::x86_insn::X86_INS_MOVUPS => semantics.mov(&mut instruction_graph),
capstone::x86_insn::X86_INS_MOVQ => semantics.movq(&mut instruction_graph),
capstone::x86_insn::X86_INS_MOVSB
| capstone::x86_insn::X86_INS_MOVSW
| capstone::x86_insn::X86_INS_MOVSD
| capstone::x86_insn::X86_INS_MOVSQ => semantics.movs(&mut instruction_graph),
capstone::x86_insn::X86_INS_MOVSX => semantics.movsx(&mut instruction_graph),
capstone::x86_insn::X86_INS_MOVSXD => semantics.movsx(&mut instruction_graph),
capstone::x86_insn::X86_INS_MOVD | capstone::x86_insn::X86_INS_MOVZX => {
semantics.movzx(&mut instruction_graph)
}
capstone::x86_insn::X86_INS_MUL => semantics.mul(&mut instruction_graph),
capstone::x86_insn::X86_INS_NEG => semantics.neg(&mut instruction_graph),
capstone::x86_insn::X86_INS_NOP => semantics.nop(&mut instruction_graph),
capstone::x86_insn::X86_INS_NOT => semantics.not(&mut instruction_graph),
capstone::x86_insn::X86_INS_OR => semantics.or(&mut instruction_graph),
capstone::x86_insn::X86_INS_PADDQ => semantics.paddq(&mut instruction_graph),
capstone::x86_insn::X86_INS_PAUSE => semantics.nop(&mut instruction_graph),
capstone::x86_insn::X86_INS_PCMPEQB => semantics.pcmpeqb(&mut instruction_graph),
capstone::x86_insn::X86_INS_PCMPEQD => semantics.pcmpeqd(&mut instruction_graph),
capstone::x86_insn::X86_INS_PMOVMSKB => semantics.pmovmskb(&mut instruction_graph),
capstone::x86_insn::X86_INS_PMINUB => semantics.pminub(&mut instruction_graph),
capstone::x86_insn::X86_INS_POP => semantics.pop(&mut instruction_graph),
capstone::x86_insn::X86_INS_POR => semantics.por(&mut instruction_graph),
capstone::x86_insn::X86_INS_PREFETCHT0 => semantics.nop(&mut instruction_graph),
capstone::x86_insn::X86_INS_PREFETCHT1 => semantics.nop(&mut instruction_graph),
capstone::x86_insn::X86_INS_PREFETCHT2 => semantics.nop(&mut instruction_graph),
capstone::x86_insn::X86_INS_PREFETCHNTA => semantics.nop(&mut instruction_graph),
capstone::x86_insn::X86_INS_PSHUFD => semantics.pshufd(&mut instruction_graph),
capstone::x86_insn::X86_INS_PSLLDQ => semantics.pslldq(&mut instruction_graph),
capstone::x86_insn::X86_INS_PSRLDQ => semantics.psrldq(&mut instruction_graph),
capstone::x86_insn::X86_INS_PSUBB => semantics.psubb(&mut instruction_graph),
capstone::x86_insn::X86_INS_PSUBQ => semantics.psubq(&mut instruction_graph),
capstone::x86_insn::X86_INS_PUNPCKLBW => {
semantics.punpcklbw(&mut instruction_graph)
}
capstone::x86_insn::X86_INS_PUNPCKLWD => {
semantics.punpcklwd(&mut instruction_graph)
}
capstone::x86_insn::X86_INS_PUSH => semantics.push(&mut instruction_graph),
capstone::x86_insn::X86_INS_PXOR => semantics.pxor(&mut instruction_graph),
capstone::x86_insn::X86_INS_RET => semantics.ret(&mut instruction_graph),
capstone::x86_insn::X86_INS_ROL => semantics.rol(&mut instruction_graph),
capstone::x86_insn::X86_INS_ROR => semantics.ror(&mut instruction_graph),
capstone::x86_insn::X86_INS_SAHF => semantics.sahf(&mut instruction_graph),
capstone::x86_insn::X86_INS_SAR => semantics.sar(&mut instruction_graph),
capstone::x86_insn::X86_INS_SBB => semantics.sbb(&mut instruction_graph),
capstone::x86_insn::X86_INS_SCASB => semantics.scasb(&mut instruction_graph),
capstone::x86_insn::X86_INS_SCASW => semantics.scasw(&mut instruction_graph),
capstone::x86_insn::X86_INS_SETAE
| capstone::x86_insn::X86_INS_SETA
| capstone::x86_insn::X86_INS_SETBE
| capstone::x86_insn::X86_INS_SETB
| capstone::x86_insn::X86_INS_SETE
| capstone::x86_insn::X86_INS_SETGE
| capstone::x86_insn::X86_INS_SETG
| capstone::x86_insn::X86_INS_SETLE
| capstone::x86_insn::X86_INS_SETL
| capstone::x86_insn::X86_INS_SETNE
| capstone::x86_insn::X86_INS_SETNO
| capstone::x86_insn::X86_INS_SETNP
| capstone::x86_insn::X86_INS_SETNS
| capstone::x86_insn::X86_INS_SETO
| capstone::x86_insn::X86_INS_SETP
| capstone::x86_insn::X86_INS_SETS => semantics.setcc(&mut instruction_graph),
capstone::x86_insn::X86_INS_SHL => semantics.shl(&mut instruction_graph),
capstone::x86_insn::X86_INS_SHR => semantics.shr(&mut instruction_graph),
capstone::x86_insn::X86_INS_SHLD => semantics.shld(&mut instruction_graph),
capstone::x86_insn::X86_INS_SHRD => semantics.shrd(&mut instruction_graph),
capstone::x86_insn::X86_INS_STC => semantics.stc(&mut instruction_graph),
capstone::x86_insn::X86_INS_STD => semantics.std(&mut instruction_graph),
capstone::x86_insn::X86_INS_STI => semantics.sti(&mut instruction_graph),
capstone::x86_insn::X86_INS_STOSB => semantics.stos(&mut instruction_graph),
capstone::x86_insn::X86_INS_STOSW => semantics.stos(&mut instruction_graph),
capstone::x86_insn::X86_INS_STOSD => semantics.stos(&mut instruction_graph),
capstone::x86_insn::X86_INS_STOSQ => semantics.stos(&mut instruction_graph),
capstone::x86_insn::X86_INS_SUB => semantics.sub(&mut instruction_graph),
capstone::x86_insn::X86_INS_SYSCALL => semantics.syscall(&mut instruction_graph),
capstone::x86_insn::X86_INS_SYSENTER => semantics.sysenter(&mut instruction_graph),
capstone::x86_insn::X86_INS_TEST => semantics.test(&mut instruction_graph),
capstone::x86_insn::X86_INS_WAIT => semantics.nop(&mut instruction_graph),
capstone::x86_insn::X86_INS_UD2 => semantics.ud2(&mut instruction_graph),
capstone::x86_insn::X86_INS_XADD => semantics.xadd(&mut instruction_graph),
capstone::x86_insn::X86_INS_XCHG => semantics.xchg(&mut instruction_graph),
capstone::x86_insn::X86_INS_XOR => semantics.xor(&mut instruction_graph),
_ => {
if options.unsupported_are_intrinsics() {
unhandled_intrinsic(&mut instruction_graph, &instruction)
} else {
return Err(Error::Custom(format!(
"Unhandled instruction {} {} at 0x{:x}",
instruction.mnemonic, instruction.op_str, instruction.address
)));
}
}
}?;
let detail = semantics.details()?;
if detail
.prefix
.contains(&(capstone_sys::x86_prefix::X86_PREFIX_REP as u8))
{
semantics.rep_prefix(&mut instruction_graph)?;
}
if detail
.prefix
.contains(&(capstone_sys::x86_prefix::X86_PREFIX_REPNE as u8))
{
semantics.repne_prefix(&mut instruction_graph)?;
}
length += instruction.size as usize;
// instructions that terminate blocks
match instruction_id {
// conditional branching instructions
capstone::x86_insn::X86_INS_JA
| capstone::x86_insn::X86_INS_JAE
| capstone::x86_insn::X86_INS_JB
| capstone::x86_insn::X86_INS_JBE
| capstone::x86_insn::X86_INS_JCXZ
| capstone::x86_insn::X86_INS_JECXZ
| capstone::x86_insn::X86_INS_JE
| capstone::x86_insn::X86_INS_JG
| capstone::x86_insn::X86_INS_JGE
| capstone::x86_insn::X86_INS_JL
| capstone::x86_insn::X86_INS_JLE
| capstone::x86_insn::X86_INS_JNO
| capstone::x86_insn::X86_INS_JNE
| capstone::x86_insn::X86_INS_JNP
| capstone::x86_insn::X86_INS_JNS
| capstone::x86_insn::X86_INS_JO
| capstone::x86_insn::X86_INS_JP
| capstone::x86_insn::X86_INS_JS => {
ensure_block_instruction(&mut instruction_graph)?;
instruction_graph.set_address(Some(instruction.address));
block_graphs.push((instruction.address, instruction_graph));
let condition = semantics.cc_condition()?;
successors.push((
address + length as u64,
Some(Expression::cmpeq(condition.clone(), expr_const(0, 1))?),
));
let operand = semantics.details()?.operands[0];
if operand.type_ == capstone_sys::x86_op_type::X86_OP_IMM {
successors.push((operand.imm() as u64, Some(condition)));
}
break;
}
capstone::x86_insn::X86_INS_LOOP
| capstone::x86_insn::X86_INS_LOOPE
| capstone::x86_insn::X86_INS_LOOPNE => {
ensure_block_instruction(&mut instruction_graph)?;
instruction_graph.set_address(Some(instruction.address));
block_graphs.push((instruction.address, instruction_graph));
let condition = semantics.loop_condition()?;
successors.push((
address + length as u64,
Some(Expression::cmpeq(condition.clone(), expr_const(0, 1))?),
));
let operand = semantics.details()?.operands[0];
if operand.type_ == capstone_sys::x86_op_type::X86_OP_IMM {
successors.push((operand.imm() as u64, Some(condition)));
}
break;
}
// non-conditional branching instructions
capstone::x86_insn::X86_INS_JMP => {
ensure_block_instruction(&mut instruction_graph)?;
instruction_graph.set_address(Some(instruction.address));
block_graphs.push((instruction.address, instruction_graph));
let operand = semantics.details()?.operands[0];
if operand.type_ == capstone_sys::x86_op_type::X86_OP_IMM {
successors.push((operand.imm() as u64, None));
}
break;
}
// instructions without successors
capstone::x86_insn::X86_INS_HLT | capstone::x86_insn::X86_INS_RET => {
ensure_block_instruction(&mut instruction_graph)?;
instruction_graph.set_address(Some(instruction.address));
block_graphs.push((instruction.address, instruction_graph));
break;
}
_ => {
instruction_graph.set_address(Some(instruction.address));
block_graphs.push((instruction.address, instruction_graph));
}
}
} else {
return Err(Error::Custom("not an x86 instruction".to_string()));
}
offset += instruction.size as usize;
}
Ok(BlockTranslationResult::new(
block_graphs,
address,
length,
successors,
))
}
|
use quirc::client::*;
fn main() {
println!("Hello, world!");
let _client = Client::connect(String::from("localhost:6667"), String::from("quirc-bot"));
}
|
use crate::algebra::linear::{Scalar, Vector};
use fructose::algebra::lattice::Lattice;
use fructose::operators::{
ClosedAdd, ClosedDiv, ClosedMul, ClosedNeg, ClosedOps, ClosedRem, ClosedSub,
};
use fructose::properties::helpers::identity::{One, Zero};
use fructose::properties::helpers::sign::Signed;
use std::alloc::Layout;
use std::fmt::{Display, Formatter};
use std::ops::{
Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Rem, RemAssign, Sub,
SubAssign,
};
use std::str::FromStr;
pub type SquareMatrix<T, const N: usize> = Matrix<T, { N }, { N }>;
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Matrix<T, const M: usize, const N: usize> {
pub data: [[T; M]; N],
}
impl<T: Default + Copy, const M: usize, const N: usize> Default for Matrix<T, { M }, { N }> {
#[inline]
fn default() -> Self {
Self {
data: [[T::default(); M]; N],
}
}
}
impl<T: Display, const M: usize, const N: usize> Display for Matrix<T, { M }, { N }> {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut string = String::new();
for m in 0..M {
&string.push_str("|");
for n in 0..N {
if n == N - 1 {
&string.push_str(&format!("{}", self[[m, n]]));
break;
}
&string.push_str(&format!("{} ", self[[m, n]]));
}
&string.push_str("|\n");
}
write!(f, "{}", string)
}
}
impl<T, const M: usize, const N: usize> Matrix<T, { M }, { N }> {
#[inline]
pub const fn new(data: [[T; M]; N]) -> Self {
Self { data }
}
#[inline]
pub const fn len(&self) -> usize {
M * N
}
#[inline]
pub const fn size(&self) -> (usize, usize) {
(M, N)
}
#[inline]
pub fn layout() -> Layout {
Layout::from_size_align(std::mem::size_of::<Self>(), std::mem::align_of::<[T; M]>())
.unwrap()
}
#[inline]
pub fn as_array(&self) -> &[T; N] {
use std::convert::TryInto;
self.as_slice().try_into().unwrap()
}
#[inline]
pub fn as_array_mut(&mut self) -> &mut [T; N] {
use std::convert::TryInto;
self.as_slice_mut().try_into().unwrap()
}
#[inline]
pub fn as_slice(&self) -> &[T] {
// this is safe because the underlying data structure of a matrix has length M * N
unsafe { std::slice::from_raw_parts(self as *const Self as *const T, M * N) }
}
#[inline]
pub fn as_slice_mut(&mut self) -> &mut [T] {
unsafe { std::slice::from_raw_parts_mut(self as *mut Self as *mut T, M * N) }
}
#[inline]
pub const fn as_ptr(&self) -> *const T {
self as *const Self as *const T
}
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut T {
self as *mut Self as *mut T
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
unsafe {
std::slice::from_raw_parts(
self as *const Self as *const u8,
M * N * std::mem::size_of::<Self>(),
)
}
}
}
impl<T: Default + Copy, const M: usize, const N: usize> Matrix<T, { M }, { N }> {
#[inline]
pub fn to_vectors(&self) -> [Vector<T, { M }>; { N }] {
let mut vectors = [Vector::default(); N];
for n in 0..N {
let vec = Vector::from(self.data[n]);
vectors[0] = vec;
}
vectors
}
}
impl<T: Scalar, const M: usize, const N: usize> Matrix<T, { M }, { N }> {
#[inline]
pub fn broadcast(value: T) -> Self {
Self {
data: [[value; M]; N],
}
}
#[inline]
pub fn map<F: Fn(T) -> T>(&self, f: F) -> Self {
let mut vector = *self;
vector
.data
.iter_mut()
.for_each(|e| e.iter_mut().for_each(|e| *e = f(*e)));
vector
}
#[inline]
pub fn apply<F: Fn(T) -> T>(&mut self, f: F) {
self.data
.iter_mut()
.for_each(|e| e.iter_mut().for_each(|e| *e = f(*e)));
}
}
impl<T: Scalar + Signed, const M: usize, const N: usize> Matrix<T, { M }, { N }> {
#[inline]
pub fn abs(&mut self) {
self.data
.iter_mut()
.for_each(|e| e.iter_mut().for_each(|e| *e = e.abs()));
}
// I can't find a good name for this, expect a rename in the future
#[inline]
pub fn abs_copy(&self) -> Self {
let mut vec = *self;
vec.abs();
vec
}
}
impl<T: Scalar + Lattice, const M: usize, const N: usize> Matrix<T, { M }, { N }> {
#[inline]
pub fn clamp(&mut self, min: Self, max: Self) {
for j in 0..M {
for i in 0..N {
self[[j, i]] = *self[[j, i]]
.partial_min(&min[[j, i]])
.unwrap()
.partial_max(&max[[j, i]])
.unwrap()
}
}
}
#[inline]
pub fn clamped(&self, min: Self, max: Self) -> Self {
let mut mat = *self;
mat.clamp(min, max);
mat
}
/// returns a new VecN' with each component having the bigger number from either VecN1 or VecN2
#[inline]
pub fn max_by_component(&self, other: &Self) -> Self {
let mut mat = *self;
for j in 0..M {
for i in 0..N {
mat[[j, i]] = *self[[j, i]].partial_max(&other[[j, i]]).unwrap();
}
}
mat
}
/// returns a new VecN' with each component having the smaller number from either VecN1 or VecN2
#[inline]
pub fn min_by_component(&self, other: &Self) -> Self {
let mut mat = *self;
for j in 0..M {
for i in 0..N {
mat[[j, i]] = *self[[j, i]].partial_min(&other[[j, i]]).unwrap();
}
}
mat
}
}
impl<T: Scalar + Zero + One + ClosedOps, const M: usize> SquareMatrix<T, { M }> {
#[inline]
pub fn mul_identity() -> Self {
let mut mat = Self::zero();
for m in 0..M {
mat[[m, m]] = T::one();
}
mat
}
#[inline]
pub fn determinant(&self) -> T {
match M {
0 => T::one(),
1 => self[[0, 0]],
2 => self[[0, 0]] * self[[1, 1]] - self[[1, 0]] * self[[1, 0]],
3 => {
let e11 = self[[0, 0]];
let e12 = self[[0, 1]];
let e13 = self[[0, 2]];
let e21 = self[[1, 0]];
let e22 = self[[1, 1]];
let e23 = self[[1, 2]];
let e31 = self[[2, 0]];
let e32 = self[[2, 1]];
let e33 = self[[2, 2]];
let minor_1 = e22 * e33 - e32 * e23;
let minor_2 = e21 * e33 - e31 * e23;
let minor_3 = e21 * e32 - e31 * e22;
e11 * minor_1 - e12 * minor_2 + e13 * minor_3
}
_ => {
unimplemented!("TODO: Add LU Decomposition")
}
}
}
}
impl<T, const M: usize, const N: usize> Index<[usize; 2]> for Matrix<T, { M }, { N }> {
type Output = T;
fn index(&self, index: [usize; 2]) -> &Self::Output {
&self.data[index[1]][index[0]]
}
}
impl<T, const M: usize, const N: usize> IndexMut<[usize; 2]> for Matrix<T, { M }, { N }> {
fn index_mut(&mut self, index: [usize; 2]) -> &mut Self::Output {
&mut self.data[index[1]][index[0]]
}
}
impl<T: Scalar + ClosedAdd, const M: usize, const N: usize> Add for Matrix<T, { M }, { N }> {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
let mut mat = Matrix::default();
for m in 0..M {
for n in 0..N {
mat[[m, n]] = self[[m, n]] + rhs[[m, n]];
}
}
mat
}
}
impl<T: Scalar + ClosedAdd, const M: usize, const N: usize> AddAssign for Matrix<T, { M }, { N }> {
#[inline]
fn add_assign(&mut self, rhs: Self) {
for m in 0..M {
for n in 0..N {
self[[m, n]] += rhs[[m, n]];
}
}
}
}
impl<T: Scalar + ClosedSub, const M: usize, const N: usize> Sub for Matrix<T, { M }, { N }> {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
let mut mat = Matrix::default();
for m in 0..M {
for n in 0..N {
mat[[m, n]] = self[[m, n]] - rhs[[m, n]];
}
}
mat
}
}
impl<T: Scalar + ClosedSub, const M: usize, const N: usize> SubAssign for Matrix<T, { M }, { N }> {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
for m in 0..M {
for n in 0..N {
self[[m, n]] -= rhs[[m, n]];
}
}
}
}
impl<T: Scalar + ClosedMul + ClosedAdd, const M: usize, const N: usize, const P: usize>
Mul<Matrix<T, { N }, { P }>> for Matrix<T, { M }, { N }>
{
type Output = Matrix<T, { M }, { P }>;
#[inline]
fn mul(self, rhs: Matrix<T, { N }, { P }>) -> Self::Output {
let mut mat = Matrix::default();
for m in 0..M {
for p in 0..P {
for n in 0..N {
mat[[m, p]] += self[[m, n]] * rhs[[n, p]];
}
}
}
mat
}
}
impl<T: Scalar + ClosedMul, const M: usize, const N: usize> Mul<T> for Matrix<T, { M }, { N }> {
type Output = Self;
fn mul(self, rhs: T) -> Self::Output {
let mut mat = self;
for m in 0..M {
for n in 0..N {
mat[[m, n]] *= rhs
}
}
self
}
}
impl<T: Scalar + ClosedMul, const M: usize, const N: usize> MulAssign<T>
for Matrix<T, { M }, { N }>
{
fn mul_assign(&mut self, rhs: T) {
for m in 0..M {
for n in 0..N {
self[[m, n]] *= rhs
}
}
}
}
impl<T: Scalar + ClosedDiv, const M: usize, const N: usize> Div<T> for Matrix<T, { M }, { N }> {
type Output = Self;
fn div(self, rhs: T) -> Self::Output {
let mut mat = self;
for m in 0..M {
for n in 0..N {
mat[[m, n]] /= rhs
}
}
self
}
}
impl<T: Scalar + ClosedDiv, const M: usize, const N: usize> DivAssign<T>
for Matrix<T, { M }, { N }>
{
fn div_assign(&mut self, rhs: T) {
for m in 0..M {
for n in 0..N {
self[[m, n]] /= rhs
}
}
}
}
impl<T: Scalar + ClosedNeg, const M: usize, const N: usize> Neg for Matrix<T, { M }, { N }> {
type Output = Self;
fn neg(self) -> Self::Output {
let mut mat = self;
for m in 0..M {
for n in 0..N {
mat[[m, n]] = -mat[[m, n]]
}
}
mat
}
}
impl<T: Scalar + ClosedRem, const M: usize, const N: usize> Rem<T> for Matrix<T, { M }, { N }> {
type Output = Self;
fn rem(self, rhs: T) -> Self::Output {
let mut mat = self;
for m in 0..M {
for n in 0..N {
mat[[m, n]] %= rhs;
}
}
mat
}
}
impl<T: Scalar + ClosedRem, const M: usize, const N: usize> RemAssign<T>
for Matrix<T, { M }, { N }>
{
fn rem_assign(&mut self, rhs: T) {
for m in 0..M {
for n in 0..N {
self[[m, n]] %= rhs;
}
}
}
}
// // this sadly doesnt work really
// // TODO: number conversion
// impl<T: Default + Copy, const M: usize, const N: usize> Matrix<T, { M }, { N }> {
// #[inline]
// pub fn to_other_type<U: Default + Copy + CastInts>(&self) -> Matrix<U, { M }, { N }> {
// let mut mat = Matrix::default();
//
// for m in 0..M {
// for n in 0..N {
// mat[[m, n]] = U::try_from(self[[m, n]]).unwrap_or_default()
// }
// }
//
// mat
// }
// }
impl<T: FromStr + Default + Copy, const M: usize, const N: usize> From<String>
for Matrix<T, { M }, { N }>
{
fn from(rhs: String) -> Self {
let mut mat = Matrix::default();
rhs.split(";").into_iter().enumerate().for_each(|(n, col)| {
col.split(" ").into_iter().enumerate().for_each(|(m, val)| {
mat[[m, n]] = val.to_string().parse().unwrap_or_else(|t| T::default())
})
});
mat
}
}
#[cfg(test)]
mod mat_tests {
use crate::algebra::linear::{Matrix, Vector};
#[test]
fn parse() {
let vec_string = String::from("2 3 -5");
let mat_string = String::from("2 3;-1 4;0 -2");
let vec = Vector::<i32, 3>::from(vec_string);
let mat = Matrix::<i32, 2, 3>::from(mat_string);
assert_eq!(vec, Vector::new([[2, 3, -5]]));
assert_eq!(mat, Matrix::new([[2, 3], [-1, 4], [0, -2]]));
}
}
|
use std::env;
use std::time::{Duration, Instant};
use crate::contributor::Contributor;
use crate::pension::Pension;
use crate::pensioner::Pensioner;
use crate::types::*;
use crate::user::User;
pub mod contributor;
pub mod doneuser;
pub mod pension;
pub mod pensioner;
pub mod types;
pub mod user;
pub mod calculations;
pub trait PensionSimulation {
fn name(&mut self) -> String {
let args: Vec<String> = env::args().collect();
(&args[0]).to_string() //.split(r"\").collect().reverse()[0]
}
fn new_contributors(&mut self, period: Period) -> u64 {
match period {
1 => 10,
_ => 0
}
}
fn should_retire(&mut self, contributor: &Contributor, _period: Period) -> bool {
contributor.contributions.len() == 480
}
fn should_contribute(&mut self, _contributor: &Contributor, _period: Period) -> Option<Unit> {
Some(1.0)
}
fn should_claim_pension(&mut self, _pensioner: &Pensioner, _period: Period) -> bool {
true
}
fn should_print(&mut self, _period: Period) -> bool {
true
}
}
pub fn simulate<T>(mut simulation: T) -> Result<(), String> where T: PensionSimulation {
println!("Pension {}", simulation.name());
let start = Instant::now();
let mut users: Vec<User> = vec![];
let mut pension = Pension::new();
//let mut pension_exporter = PensionCsvExporter::new();
loop {
pension.start_new_period();
// 1. Create new contributors
add_new_contributor(&mut simulation, &mut pension, &mut users);
// 2. Retire all selected contributors so they become pensioners
users = retire_contributor(&mut simulation, &mut pension, users);
// 3. Let all selected contributors pay into the pension system
contribute(&mut simulation, &mut pension, &mut users);
// 4. Payout pensions to all selected pensioners
claim_pensions(&mut simulation, &mut pension, &mut users);
// 5. Calculate and distribute DPT based on their contribution
// of the current period
claim_dpts(&mut simulation, &mut pension, &mut users)?;
// 6. Remove all pensioners from the system who got their complete pension
users = remove_done_pensioners(&mut pension, users);
// 7. Log state after period is done
if simulation.should_print(pension.period) {
print(&pension, &users);
}
//pension_exporter.add_pension(&pension);
//pension_exporter.add_users(&pension);
// 8. Repeat until all users retired and got their complete pension
// TODO: Implement PartialEq?
if users.iter().all(|user| {
match user.to_done_user() {
Some(_) => true,
None => false
}
}) {
break;
}
}
let res = users.iter()
.filter_map(|user| user.to_done_user())
.fold((0, 0), |(pos, neg), done_user| {
let pensioner = &done_user.pensioner;
let contributor = &pensioner.contributor;
let diff = (contributor.wallet() + pensioner.total_pension()) - 10000000.0;
if diff >= 0.0 {
(pos + 1, neg)
} else {
(pos, neg + 1)
}
});
println!("Res: {:?}", res);
let duration: Duration = start.elapsed();
println!("Time elapsed: {:?}", duration);
//println!("{:?}", pension);
//
//pension_exporter.export_pensions(format!("{}-pensions.csv", simulation.name().to_lowercase()));
//pension_exporter.export_users(format!("{}-users.csv", simulation.name().to_lowercase()));
Ok(())
}
fn add_new_contributor<T>(simulation: &mut T, pension: &mut Pension, users: &mut Vec<User>) where T: PensionSimulation {
for _ in 0..simulation.new_contributors(pension.period) {
let new_user = User::new();
match &new_user {
User::Contributor(contributor) => pension.join(contributor),
_ => panic!("user is not a contributor")
}
users.push(new_user);
}
}
fn retire_contributor<T>(simulation: &mut T, pension: &mut Pension, users: Vec<User>) -> Vec<User> where T: PensionSimulation {
users.into_iter()
.map(|user| {
match user {
User::Contributor(contributor) => {
if simulation.should_retire(&contributor, pension.period) {
pension.retire(contributor)
} else {
User::Contributor(contributor)
}
}
_ => user
}
})
.collect()
}
fn remove_done_pensioners(pension: &mut Pension, users: Vec<User>) -> Vec<User> {
users.into_iter()
.map(|user| {
match user {
User::Pensioner(pensioner) => pension.try_finish(pensioner),
_ => user
}
})
.collect()
}
fn contribute<T>(simulation: &mut T, pension: &mut Pension, users: &mut Vec<User>) where T: PensionSimulation {
users.iter_mut()
.filter_map(|user| user.to_contributor_mut())
.for_each(|contributor| {
if let Some(contribution) = simulation.should_contribute(contributor, pension.period) {
match pension.contribute(contributor, contribution) {
Err(err) => panic!(err),
_ => (),
}
}
});
}
fn claim_pensions<T>(simulation: &mut T, pension: &mut Pension, users: &mut Vec<User>) where T: PensionSimulation {
let period = pension.period;
users.iter_mut()
.filter_map(|user| user.to_pensioner_mut())
.filter(|pensioner| simulation.should_claim_pension(pensioner, period))
.for_each(|pensioner| {
match pension.claim_pension(pensioner) {
Err(err) => panic!(err),
_ => (),
}
});
}
fn claim_dpts<T>(_simulation: &mut T, pension: &mut Pension, users: &mut Vec<User>) -> Result<(), String> where T: PensionSimulation {
// TODO: Logically I think this should happen as step 4 and the name of
// the method should reflect what it does.
pension.prepare_claim_dpt(users)?;
users.iter_mut()
.filter_map(|user| user.to_contributor_mut())
.for_each(|contributor| {
match pension.claim_dpt(contributor) {
Err(err) => panic!(err),
_ => (),
}
});
Ok(())
}
pub fn print(pension: &Pension, users: &[User]) {
let contributor_count = users
.iter()
.filter_map(|user| user.to_contributor())
.count();
let pensioner_count = users
.iter()
.filter_map(|user| user.to_pensioner())
.count();
let done_count = users
.iter()
.filter_map(|user| user.to_done_user())
.count();
println!("Period: {}, Total Eth: {}, Total Contributions Eth: {}, Total Pension Eth: {}, Total Laggards: {}",
pension.period, pension.savings_total, pension.contributions_total, pension.pensions_total, pension.laggards_total);
println!("Total DPT: {}, Total Contributor: {}, Total Pensioner: {}, Total Done: {}, CCV: {}",
pension.dpt_total, contributor_count, pensioner_count, done_count, pension.current_contribution_value);
for user in users {
match user {
User::Contributor(contributor) => {
let last_dpt = match contributor.dpts.get(&pension.period) {
Some(dpt) => format!("{}", dpt),
None => "0".to_string()
};
let diff = contributor.wallet() - 10000000.0;
println!("User: {:2}, Status: {:>11}, Wallet: {}, Pension: {:16.12}, Pension Months Allowed: {:3}, Pensions Months Received: {:3}, AVG: {:6.3}, DIFF: {:6.3}, DPT: {:14.10} + ({})",
contributor.id(), "Contributor", contributor.wallet(), 0, contributor.allowed_pension_periods(),
0, 0, diff, contributor.dpt_total(), last_dpt);
}
User::Pensioner(pensioner) => {
let contributor = &pensioner.contributor;
let avg = pensioner.total_pension() / pensioner.pension_periods() as f64;
let diff = (contributor.wallet() + pensioner.total_pension()) - 10000000.0;
println!("User: {:2}, Status: {:>11}, Wallet: {}, Pension: {:16.12}, Pension Months Allowed: {:3}, Pensions Months Received: {:3}, AVG: {:6.3}, DIFF: {:6.3}, DPT: {:14.10}",
contributor.id(), "Pensioner", contributor.wallet(), pensioner.total_pension(),
contributor.allowed_pension_periods(), pensioner.pension_periods(), avg, diff, contributor.dpt_total());
}
User::Done(done_user) => {
let pensioner = &done_user.pensioner;
let contributor = &pensioner.contributor;
let avg = pensioner.total_pension() / pensioner.pension_periods() as f64;
let diff = (contributor.wallet() + pensioner.total_pension()) - 10000000.0;
println!("User: {:2}, Status: {:>11}, Wallet: {}, Pension: {:16.12}, Pension Months Allowed: {:3}, Pensions Months Received: {:3}, AVG: {:6.3}, DIFF: {:6.3}, DPT: {:14.10}",
contributor.id(), "Done", contributor.wallet(), pensioner.total_pension(),
contributor.allowed_pension_periods(), pensioner.pension_periods(), avg, diff, contributor.dpt_total());
}
}
}
println!();
println!("-------------------------");
println!();
}
//#[cfg(test)]
//mod tests {
// use crate::*;
// use crate::pension::Pension;
//
// #[test]
// fn create_users() {
// let mut pension = Pension::new();
// pension.create_users(5);
//
// assert_eq!(pension.users.len(), 5);
// }
//
// #[test]
// fn add_amount(){
// let mut pension = Pension::new();
// pension.add_amount(100.0);
// assert_eq!(pension.total_eth, 100.0);
// assert_eq!(pension.total_month_eth, 100.0);
// }
//
// #[test]
// fn payout(){
// let mut pension = Pension::new();
// pension.create_users(10);
// pension.current_period = 1;
// pension.payout();
//
// }
// #[test]
// fn start_should_create_init_dpt_bonus(){
// let mut pension = Pension::new();
// pension.start_new_period();
// assert_eq!(pension.current_dpt_bonus, 1.5);
// }
// #[test]
// fn start_should_create_a_new_period() {
// let mut pension = Pension::new();
// assert!(pension.period == 0);
// pension.start_new_period();
// assert!(pension.period > 0);
// }
//
//} |
use std::sync::Arc;
use futures_core::future::BoxFuture;
use crate::connection::ConnectionSource;
use crate::cursor::Cursor;
use crate::executor::Execute;
use crate::pool::Pool;
use crate::postgres::protocol::{DataRow, Message, ReadyForQuery, RowDescription};
use crate::postgres::row::Statement;
use crate::postgres::{PgArguments, PgConnection, PgRow, Postgres};
pub struct PgCursor<'c, 'q> {
source: ConnectionSource<'c, PgConnection>,
query: Option<(&'q str, Option<PgArguments>)>,
statement: Arc<Statement>,
}
impl crate::cursor::private::Sealed for PgCursor<'_, '_> {}
impl<'c, 'q> Cursor<'c, 'q> for PgCursor<'c, 'q> {
type Database = Postgres;
#[doc(hidden)]
fn from_pool<E>(pool: &Pool<PgConnection>, query: E) -> Self
where
Self: Sized,
E: Execute<'q, Postgres>,
{
Self {
source: ConnectionSource::Pool(pool.clone()),
statement: Arc::default(),
query: Some(query.into_parts()),
}
}
#[doc(hidden)]
fn from_connection<E>(conn: &'c mut PgConnection, query: E) -> Self
where
Self: Sized,
E: Execute<'q, Postgres>,
{
Self {
source: ConnectionSource::ConnectionRef(conn),
statement: Arc::default(),
query: Some(query.into_parts()),
}
}
fn next(&mut self) -> BoxFuture<crate::Result<Option<PgRow<'_>>>> {
Box::pin(next(self))
}
}
async fn next<'a, 'c: 'a, 'q: 'a>(
cursor: &'a mut PgCursor<'c, 'q>,
) -> crate::Result<Option<PgRow<'a>>> {
let mut conn = cursor.source.resolve().await?;
// The first time [next] is called we need to actually execute our
// contained query. We guard against this happening on _all_ next calls
// by using [Option::take] which replaces the potential value in the Option with `None
if let Some((query, arguments)) = cursor.query.take() {
let statement = conn.run(query, arguments).await?;
// If there is a statement ID, this is a non-simple or prepared query
if let Some(statement) = statement {
// A prepared statement will re-use the previous column map
cursor.statement = Arc::clone(&conn.cache_statement[&statement]);
}
// A non-prepared query must be described each time
// We wait until we hit a RowDescription
}
loop {
match conn.stream.receive().await? {
// Indicates that a phase of the extended query flow has completed
// We as SQLx don't generally care as long as it is happening
Message::ParseComplete | Message::BindComplete => {}
// Indicates that _a_ query has finished executing
Message::CommandComplete => {}
// Indicates that all queries have finished executing
Message::ReadyForQuery => {
// TODO: How should we handle an ERROR status form ReadyForQuery
let _ready = ReadyForQuery::read(conn.stream.buffer())?;
conn.is_ready = true;
break;
}
Message::RowDescription => {
// NOTE: This is only encountered for unprepared statements
let rd = RowDescription::read(conn.stream.buffer())?;
cursor.statement = Arc::new(
conn.parse_row_description(rd, Default::default(), None, false)
.await?,
);
}
Message::DataRow => {
let data = DataRow::read(conn.stream.buffer(), &mut conn.current_row_values)?;
return Ok(Some(PgRow {
statement: Arc::clone(&cursor.statement),
data,
}));
}
message => {
return Err(protocol_err!("next: unexpected message: {:?}", message).into());
}
}
}
Ok(None)
}
|
use actix::{Actor, Context, Handler, System};
use actix_derive::{Message, MessageResponse};
#[derive(MessageResponse)]
struct Added(usize);
#[derive(Message)]
#[rtype(result = "Added")]
struct Sum(usize, usize);
#[derive(Default)]
struct Adder;
impl Actor for Adder {
type Context = Context<Self>;
}
impl Handler<Sum> for Adder {
type Result = <Sum as actix::Message>::Result;
fn handle(&mut self, msg: Sum, _: &mut Self::Context) -> Added {
Added(msg.0 + msg.1)
}
}
#[test]
fn test_message() {
System::new().block_on(async {
let addr = Adder::start_default();
let res = addr.send(Sum(3, 5)).await.unwrap();
assert_eq!(res.0, 8);
});
}
|
use std::{
collections::{HashMap, HashSet},
hash::BuildHasherDefault,
ops::{Deref, DerefMut, Index, IndexMut},
sync::atomic::{AtomicU64, Ordering},
};
use archetype::ArchetypeIndex;
use component::{Component, ComponentTypeId};
use downcast_rs::{impl_downcast, Downcast};
use crate::internals::hash::ComponentTypeIdHasher;
pub mod archetype;
pub mod component;
pub mod group;
pub mod index;
pub mod packed;
pub mod slicevec;
/// Contains information about the type of a component.
#[derive(Copy, Clone, PartialEq)]
pub struct ComponentMeta {
size: usize,
align: usize,
drop_fn: Option<fn(*mut u8)>,
}
impl ComponentMeta {
/// Returns the component meta of component type `T`.
pub fn of<T: Component>() -> Self {
ComponentMeta {
size: std::mem::size_of::<T>(),
align: std::mem::align_of::<T>(),
drop_fn: if std::mem::needs_drop::<T>() {
Some(|ptr| unsafe { std::ptr::drop_in_place(ptr as *mut T) })
} else {
None
},
}
}
/// Returns the size of the component.
pub fn size(&self) -> usize {
self.size
}
/// Returns the alignment of the component.
pub fn align(&self) -> usize {
self.align
}
/// Drops the component.
///
/// # Safety
/// The caller must ensure that the memory location refered to by `value` is
/// not accessed again before it is re-initialized.
pub unsafe fn drop(&self, value: *mut u8) {
if let Some(drop_fn) = self.drop_fn {
drop_fn(value)
}
}
}
/// The index of a component within an archetype.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct ComponentIndex(pub(crate) usize);
/// A world epoch. Epochs are incremented each time a world is packed, and are used
/// by the packing heuristics as a measure of age.
pub type Epoch = u64;
/// The version of a component slice. Versions are incremented when the sliace is
/// accessed mutably.
pub type Version = u64;
static COMPONENT_VERSION: AtomicU64 = AtomicU64::new(0);
pub(crate) fn next_component_version() -> u64 {
COMPONENT_VERSION.fetch_add(1, Ordering::SeqCst)
}
/// A storage location for component data slices. Each component storage may hold one slice for
/// each archetype inserted into the storage. The type of component stored is not known statically.
pub trait UnknownComponentStorage: Downcast + Send + Sync {
/// Notifies the storage of the start of a new epoch.
fn increment_epoch(&mut self);
/// Inserts a new empty component slice for an archetype into this storage.
fn insert_archetype(&mut self, archetype: ArchetypeIndex, index: Option<usize>);
/// Moves an archetype's component slice to a new storage.
fn transfer_archetype(
&mut self,
src_archetype: ArchetypeIndex,
dst_archetype: ArchetypeIndex,
dst: &mut dyn UnknownComponentStorage,
);
/// Moves a component to a new storage.
fn transfer_component(
&mut self,
src_archetype: ArchetypeIndex,
src_component: ComponentIndex,
dst_archetype: ArchetypeIndex,
dst: &mut dyn UnknownComponentStorage,
);
/// Moves a component from one archetype to another.
fn move_component(
&mut self,
source: ArchetypeIndex,
index: ComponentIndex,
dst: ArchetypeIndex,
);
/// Removes a component from an archetype slice, swapping it with the last component in the slice.
fn swap_remove(&mut self, archetype: ArchetypeIndex, index: ComponentIndex);
/// Packs archetype slices.
fn pack(&mut self, epoch_threshold: Epoch) -> usize;
/// A heuristic estimating cache misses for an iteration through all components due to archetype fragmentation.
fn fragmentation(&self) -> f32;
/// Returns the component metadata.
fn element_vtable(&self) -> ComponentMeta;
/// Returns a pointer to the given archetype's component slice.
fn get_raw(&self, archetype: ArchetypeIndex) -> Option<(*const u8, usize)>;
/// Returns a pointer to the given archetype's component slice.
///
/// # Safety
/// The caller is responsible for ensuring that they have exclusive access to the given archetype's slice.
unsafe fn get_mut_raw(&self, archetype: ArchetypeIndex) -> Option<(*mut u8, usize)>;
/// Writes new components into the given archetype's component slice via a memcopy.
///
/// # Safety
/// `ptr` must point to a valid array of the correct component type of length at least as long as `len`.
/// The data in this array will be memcopied into the world's internal storage.
/// If the component type is not `Copy`, then the caller must ensure that the memory
/// copied is not accessed until it is re-initialized. It is recommended to immediately
/// `std::mem::forget` the source after calling `extend_memcopy_raw`.
unsafe fn extend_memcopy_raw(&mut self, archetype: ArchetypeIndex, ptr: *const u8, len: usize);
/// Ensures that the given spare capacity is available for component insertions. This is a performance hint and
/// should not be required before `extend_memcopy` is called.
fn ensure_capacity(&mut self, archetype: ArchetypeIndex, space: usize);
}
impl_downcast!(UnknownComponentStorage);
/// An accessor for a shared slice reference of components for a single archetype.
pub struct ComponentSlice<'a, T: Component> {
pub(crate) components: &'a [T],
pub(crate) version: &'a Version,
}
impl<'a, T: Component> ComponentSlice<'a, T> {
pub(crate) fn new(components: &'a [T], version: &'a Version) -> Self {
Self {
components,
version,
}
}
/// Converts this slice into its inner value.
pub fn into_slice(self) -> &'a [T] {
self.components
}
}
impl<'a, T: Component> From<ComponentSlice<'a, T>> for &'a [T] {
fn from(slice: ComponentSlice<'a, T>) -> Self {
slice.components
}
}
impl<'a, T: Component> Deref for ComponentSlice<'a, T> {
type Target = [T];
fn deref(&self) -> &Self::Target {
&self.components
}
}
impl<'a, T: Component> Index<ComponentIndex> for ComponentSlice<'a, T> {
type Output = T;
fn index(&self, index: ComponentIndex) -> &Self::Output {
&self.components[index.0]
}
}
/// An accessor for a mutable slice reference of components for a single archetype.
pub struct ComponentSliceMut<'a, T: Component> {
// todo would be better if these were private and we controlled version increments more centrally
pub(crate) components: &'a mut [T],
pub(crate) version: &'a mut Version,
}
impl<'a, T: Component> ComponentSliceMut<'a, T> {
pub(crate) fn new(components: &'a mut [T], version: &'a mut Version) -> Self {
Self {
components,
version,
}
}
/// Converts this slice into its inner value.
/// This increments the slice's version.
pub fn into_slice(self) -> &'a mut [T] {
*self.version = next_component_version();
self.components
}
}
impl<'a, T: Component> Deref for ComponentSliceMut<'a, T> {
type Target = [T];
fn deref(&self) -> &Self::Target {
&self.components
}
}
impl<'a, T: Component> Index<ComponentIndex> for ComponentSliceMut<'a, T> {
type Output = T;
fn index(&self, index: ComponentIndex) -> &Self::Output {
&self.components[index.0]
}
}
impl<'a, T: Component> IndexMut<ComponentIndex> for ComponentSliceMut<'a, T> {
fn index_mut(&mut self, index: ComponentIndex) -> &mut Self::Output {
&mut self.components[index.0]
}
}
/// A storage location for component data slices. Each component storage may hold once slice for
/// each archetype inserted into the storage.
pub trait ComponentStorage<'a, T: Component>: UnknownComponentStorage + Default {
/// An iterator of shared archetype slice references.
type Iter: Iterator<Item = ComponentSlice<'a, T>>;
/// An iterator of mutable archetype slice references.
type IterMut: Iterator<Item = ComponentSliceMut<'a, T>>;
/// Returns the number of archetype slices stored.
fn len(&self) -> usize;
/// Returns `true` if the storage contains no archetypes.
fn is_empty(&self) -> bool {
self.len() == 0
}
/// Copies new components into the specified archetype slice.
///
/// # Safety
/// The components located at `ptr` are memcopied into the storage. If `T` is not `Copy`, then the
/// previous memory location should no longer be accessed.
unsafe fn extend_memcopy(&mut self, archetype: ArchetypeIndex, ptr: *const T, len: usize);
/// Gets the component slice for the specified archetype.
fn get(&'a self, archetype: ArchetypeIndex) -> Option<ComponentSlice<'a, T>>;
/// Gets a mutable component slice for the specified archetype.
///
/// # Safety
/// Ensure that the requested archetype slice is not concurrently borrowed anywhere else such that memory
/// is not mutably aliased.
unsafe fn get_mut(&'a self, archetype: ArchetypeIndex) -> Option<ComponentSliceMut<'a, T>>;
/// Iterates through all archetype component slices.
fn iter(&'a self, start_inclusive: usize, end_exclusive: usize) -> Self::Iter;
/// Iterates through all mutable archetype component slices.
///
/// # Safety
/// Ensure that all requested archetype slices are not concurrently borrowed anywhere else such that memory
/// is not mutably aliased.
unsafe fn iter_mut(&'a self, start_inclusive: usize, end_exclusive: usize) -> Self::IterMut;
}
/// Contains the storages for all component types in a world.
#[derive(Default)]
pub struct Components {
storages: HashMap<
ComponentTypeId,
Box<dyn UnknownComponentStorage>,
BuildHasherDefault<ComponentTypeIdHasher>,
>,
}
impl Components {
/// Gets or inserts the storage for the given component type.
pub fn get_or_insert_with<F>(
&mut self,
type_id: ComponentTypeId,
mut create: F,
) -> &mut dyn UnknownComponentStorage
where
F: FnMut() -> Box<dyn UnknownComponentStorage>,
{
let cell = self.storages.entry(type_id).or_insert_with(|| create());
cell.deref_mut()
}
/// Returns the storage for the given component type.
pub fn get(&self, type_id: ComponentTypeId) -> Option<&dyn UnknownComponentStorage> {
self.storages.get(&type_id).map(|cell| cell.deref())
}
/// Returns the storage for the given component type.
pub fn get_downcast<T: Component>(&self) -> Option<&T::Storage> {
let type_id = ComponentTypeId::of::<T>();
self.get(type_id).and_then(|storage| storage.downcast_ref())
}
/// Returns the storage for the given component type.
pub fn get_mut(
&mut self,
type_id: ComponentTypeId,
) -> Option<&mut dyn UnknownComponentStorage> {
self.storages.get_mut(&type_id).map(|cell| cell.deref_mut())
}
/// Returns the storage for the given component type.
pub fn get_downcast_mut<T: Component>(&mut self) -> Option<&mut T::Storage> {
let type_id = ComponentTypeId::of::<T>();
self.get_mut(type_id)
.and_then(|storage| storage.downcast_mut())
}
/// Returns a writer for writing to multiple component storages.
pub fn get_multi_mut(&mut self) -> MultiMut {
MultiMut::new(self)
}
/// Repacks all component storages.
pub fn pack(&mut self, options: &PackOptions) {
let mut total_moved_bytes = 0;
for storage in self.iter_storages_mut() {
if storage.fragmentation() >= options.fragmentation_threshold {
total_moved_bytes += storage.pack(options.stability_threshold);
}
if total_moved_bytes >= options.maximum_iteration_size {
break;
}
}
for storage in self.iter_storages_mut() {
storage.increment_epoch();
}
}
fn iter_storages_mut(&mut self) -> impl Iterator<Item = &mut dyn UnknownComponentStorage> {
self.storages.iter_mut().map(|(_, cell)| cell.deref_mut())
}
}
impl std::fmt::Debug for Components {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list().entries(self.storages.keys()).finish()
}
}
/// Describes how to perform a component pack operation.
#[derive(Copy, Clone, Debug)]
pub struct PackOptions {
/// The number of frames that an archetype has to remain stable before it
/// will be considered a candidate for packing.
pub stability_threshold: u64,
/// The estimated number of cache misses due to fragmentation per entity
/// that would be saved by a repack before a component storage may consider
/// repacking itself.
pub fragmentation_threshold: f32,
/// The target maximum number of entities to move during a repack before
/// the pack is halted.
pub maximum_iteration_size: usize,
}
impl PackOptions {
/// Force a repack.
pub fn force() -> Self {
Self {
stability_threshold: 0,
fragmentation_threshold: 0.0,
maximum_iteration_size: usize::MAX,
}
}
}
impl Default for PackOptions {
fn default() -> Self {
Self {
stability_threshold: 120,
fragmentation_threshold: 1.0 / 64.0,
maximum_iteration_size: 4 * 1024 * 1024,
}
}
}
/// Provides mutable access to multiple different component storages from a single world.
pub struct MultiMut<'a> {
components: &'a mut Components,
#[cfg(debug_assertions)]
claimed: HashSet<ComponentTypeId, BuildHasherDefault<ComponentTypeIdHasher>>,
}
impl<'a> MultiMut<'a> {
fn new(components: &'a mut Components) -> Self {
Self {
components,
#[cfg(debug_assertions)]
claimed: HashSet::default(),
}
}
/// Claims exclusive access to a component storage.
///
/// # Safety
/// The caller must ensure that each component type is only claimed once, as doing otherwise
/// may result in mutable aliases of the component storage. This is validated in debug builds.
pub unsafe fn claim<T: Component>(&mut self) -> Option<&'a mut T::Storage> {
let type_id = ComponentTypeId::of::<T>();
#[cfg(debug_assertions)]
{
assert!(!self.claimed.contains(&type_id));
self.claimed.insert(type_id);
}
// Self::extend_lifetime extends the local borrow up to 'a.
// This is highly unsafe as it would allow aliasing a mutable borrow
// by calling claim() multiple times for the same component.
// However, the caller is responsible for not doing this as part of claim's safety rules.
// We validate this in debug builds.
self.components
.storages
.get_mut(&type_id)
.and_then(|cell| Self::extend_lifetime(cell).downcast_mut())
}
/// Claims exclusive access to a component storage.
///
/// # Safety
/// The caller must ensure that each component type is only claimed once, as doing otherwise
/// may result in mutable aliases of the component storage. This is validated in debug builds.
pub unsafe fn claim_unknown(
&mut self,
type_id: ComponentTypeId,
) -> Option<&'a mut dyn UnknownComponentStorage> {
#[cfg(debug_assertions)]
{
assert!(!self.claimed.contains(&type_id));
self.claimed.insert(type_id);
}
// Self::extend_lifetime extends the local borrow up to 'a.
// This is highly unsafe as it would allow aliasing a mutable borrow
// by calling claim_unknown() multiple times for the same component.
// However, the caller is responsible for not doing this as part of claim_unknown's safety rules.
// We validate this in debug builds.
self.components
.storages
.get_mut(&type_id)
.map(|cell| Self::extend_lifetime(cell).deref_mut())
}
unsafe fn extend_lifetime<'b, T>(value: &'b mut T) -> &'a mut T {
std::mem::transmute::<&'b mut T, &'a mut T>(value)
}
}
|
#![warn(clippy::pedantic)]
use failure::Error;
use fnv::FnvHashSet as HashSet;
use hyper;
use ini::Ini;
use lazy_static::lazy_static;
use mozlz4::decompress;
use rayon::{prelude::*, ThreadPoolBuilder};
use regex::Regex;
use reqwest::{
blocking::{Client, Response},
header::{self, HeaderMap, HeaderValue},
StatusCode,
};
use select::{
document::Document,
predicate::{Attr, Class, Name, Predicate},
};
use serde_json;
use structopt::StructOpt;
use toml;
use std::{
cell::RefCell,
env,
error::Error as StdError,
fmt::{self, Display, Formatter},
fs::{self, File},
io::{self, Cursor, Read},
path::{Path, PathBuf},
str::FromStr,
sync::{
mpsc::{self, Receiver, RecvError, RecvTimeoutError, Sender, TryRecvError},
Mutex,
},
thread,
time::{Duration, SystemTime},
};
#[cfg(debug_assertions)]
macro_rules! debug {
($x:expr) => {
dbg!($x)
};
}
#[cfg(not(debug_assertions))]
macro_rules! debug {
($x:expr) => {
#[allow(path_statements)]
{
$x
}
};
}
lazy_static! {
static ref INVALID_CHARS: HashSet<u8> = {
let mut byteset = HashSet::default();
let invalid_chars;
#[cfg(windows)]
{
invalid_chars = br#"<>:"/\|?*"#;
}
#[cfg(unix)]
{
invalid_chars = b"/";
}
for &b in invalid_chars {
byteset.insert(b);
}
byteset
};
static ref ECODE_509: HeaderValue = HeaderValue::from_static(r#""48fb95b9-6ff2""#);
static ref LAST_REQUEST: Mutex<SystemTime> = Mutex::new(SystemTime::now());
static ref GALLERY_URL_RE: Regex =
Regex::new(r"https?://(?:www\.)?e[-x]hentai\.org/g/\w+/\w+/?").unwrap();
static ref GALLERY_PAGE_RE: Regex = Regex::new(r"[?&]p=(\d+)").unwrap();
static ref PAGE_NUM_RE: Regex = Regex::new(r"Showing \d+ - \d+ of (\d+) images").unwrap();
static ref FILENAME_RE: Regex = Regex::new(r"(.*) :: \d+ x").unwrap();
static ref ONCLICK_NL_RE: Regex = Regex::new(r"[\d-]+").unwrap();
}
thread_local! {
static CHANNEL: RefCell<(RespTx, BytesRx)> = RefCell::new(get_worker());
}
type RespTx = Sender<Message>;
type RespRx = Receiver<Message>;
type BytesTx = Sender<io::Result<Vec<u8>>>;
type BytesRx = Receiver<io::Result<Vec<u8>>>;
type Cmd = Box<dyn Fn(&Downloader, &str) -> Result<Action, Error>>;
fn worker_task(resp_rx: &RespRx, bytes_tx: &BytesTx) {
loop {
match resp_rx.recv() {
Ok(Message::Start(img_resp, content_length)) => {
let mut img_resp = *img_resp;
let mut image = vec![0; content_length];
let mut total_bytes = 0;
loop {
match resp_rx.try_recv() {
Ok(Message::Start(..)) => {
unreachable!("received two start messages in a row")
}
Ok(Message::Stop) => break,
Err(TryRecvError::Empty) => {
match img_resp.read(&mut image[total_bytes..]) {
Ok(0) => thread::sleep(Duration::from_millis(100)),
Ok(num_bytes) => {
total_bytes += num_bytes;
if total_bytes >= content_length {
let _ = bytes_tx.send(Ok(image));
break;
}
}
Err(e) => {
let _ = bytes_tx.send(Err(e));
break;
}
}
}
Err(TryRecvError::Disconnected) => return,
}
}
}
Ok(Message::Stop) => {}
Err(RecvError) => return,
}
}
}
fn get_worker() -> (RespTx, BytesRx) {
debug!(format!(
"Creating new worker for thread {:?}",
std::thread::current().id()
));
let (resp_tx, resp_rx) = mpsc::channel();
let (bytes_tx, bytes_rx) = mpsc::channel();
thread::spawn(move || worker_task(&resp_rx, &bytes_tx));
(resp_tx, bytes_rx)
}
fn create_or_touch_dir<P>(path: P) -> io::Result<()>
where
P: AsRef<Path>,
{
match fs::create_dir(&path) {
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
let mut tmp_path = PathBuf::from(path.as_ref());
tmp_path.push(".exhentai-dl.tml");
match File::create(&tmp_path) {
Ok(_) => {
fs::remove_file(&tmp_path)?;
Ok(())
}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
fs::remove_file(&tmp_path)?;
Ok(())
}
Err(e) => Err(e),
}?;
Err(e)
}
result => result,
}
}
fn get_loadfail_link(link: &str, doc: &Document) -> Result<String, Error> {
let loadfail = doc
.find(Attr("id", "loadfail"))
.next()
.ok_or_else(|| ProgramError::new("no loadfail on page"))?;
let onclick = loadfail
.attr("onclick")
.ok_or_else(|| ProgramError::new("loadfail missing onclick"))?;
let code = &ONCLICK_NL_RE
.captures(onclick)
.ok_or_else(|| ProgramError::new("onclick missing nl code"))?[0];
let sep = link
.bytes()
.rev()
.take_while(|&b| b != b'/')
.find(|&b| b == b'?')
.map_or('?', |_| '&');
Ok(format!("{}{}nl={}", link, sep, code))
}
enum Message {
Start(Box<Response>, usize),
Stop,
}
#[derive(Debug)]
struct ProgramError {
message: String,
}
impl ProgramError {
fn new<S: Into<String>>(message: S) -> Self {
Self {
message: message.into(),
}
}
}
impl Display for ProgramError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str(&self.message)
}
}
impl StdError for ProgramError {}
#[derive(StructOpt)]
#[structopt(author, name = "exhentai")]
struct Exhentai {
#[structopt(short = "p", long)]
/// Prefix image filenames with page numbers
paginate: bool,
#[structopt(short = "t", long, default_value = "8")]
/// Number of concurrent requests to make at a time
threads: usize,
#[structopt(short = "d", long, default_value = "100")]
/// Delay between requests in milliseconds
delay: usize,
#[structopt(subcommand)]
cmd: Option<Command>,
#[structopt(short = "c", long, default_value = "update")]
/// What to do if a gallery is already present. Options are update, skip, and abort.
on_conflict: OnConflict,
urls: Vec<String>,
}
#[derive(StructOpt)]
enum Command {
/// Download the gallery from each given exhentai gallery link
Gallery { urls: Vec<String> },
/// Download each gallery entry from each given exhentai search link
Search {
#[structopt(short = "P", long)]
num_pages: Option<usize>,
urls: Vec<String>,
},
/// Download each exhentai gallery currently open in Firefox
Tabs,
}
enum OnConflict {
Abort,
Skip,
Update,
}
#[must_use]
enum Action {
Continue,
Abort,
}
impl FromStr for OnConflict {
type Err = ProgramError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"abort" => Ok(Self::Abort),
"skip" => Ok(Self::Skip),
"update" => Ok(Self::Update),
_ => Err(ProgramError::new(format!(
r#""{}" is not a recognized action "#,
s
))),
}
}
}
struct Downloader {
client: Client,
paginate: bool,
num_pages: Option<usize>,
delay: Duration,
on_conflict: OnConflict,
}
impl Downloader {
fn new(
headers: HeaderMap,
paginate: bool,
num_pages: Option<usize>,
delay: Duration,
on_conflict: OnConflict,
) -> Self {
Self {
client: Client::builder()
.timeout(None)
.default_headers(headers)
.user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0")
.build()
.expect("failed to build client"),
paginate,
delay,
num_pages,
on_conflict,
}
}
fn download_gallery(&self, url: &str) -> Result<Action, Error> {
let resp = self.get(url)?;
let mut root = Document::from(resp.text()?.as_str());
let title_bytes: Vec<u8> = root
.find(Attr("id", "gn"))
.next()
.ok_or_else(|| {
ProgramError::new(format!(
"{} does not appear to be exhentai compatible.",
url
))
})?
.text()
.bytes()
.filter(|b| !INVALID_CHARS.contains(b))
.collect();
let title;
#[cfg(windows)]
{
title = String::from_utf8(title_bytes)?
.trim_end_matches('.')
.to_string();
}
#[cfg(unix)]
{
title = String::from_utf8(title_bytes)?;
}
match create_or_touch_dir(&title) {
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
match self.on_conflict {
OnConflict::Abort => return Ok(Action::Abort),
OnConflict::Update => {}
OnConflict::Skip => return Ok(Action::Continue),
}
Ok(())
}
res => res,
}?;
let start_page: usize = GALLERY_PAGE_RE
.captures(url)
.map_or(Ok(0), |m| m[1].parse())?;
println!("Downloading {}", &title);
let mut links: Vec<String> = Vec::new();
let num_digits = if self.paginate {
let num_images_text = root
.find(Class("gpc"))
.next()
.ok_or_else(|| ProgramError::new("no element with class gpc"))?
.text();
let num_pages: f64 = PAGE_NUM_RE
.captures(&num_images_text)
.ok_or_else(|| ProgramError::new("failed to capture number of pages"))?[1]
.parse()?;
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
{
Some((num_pages.log10().floor() + 1.) as usize)
}
} else {
None
};
for page in start_page.. {
println!("Scanning album page {}", page + 1);
let mut count = 0;
links.extend(
root.find(
Attr("id", "gdt")
.child(Class("gdtm"))
.child(Name("div"))
.child(Name("a")),
)
.filter_map(|node| {
count += 1;
node.attr("href").map(Into::into)
}),
);
if count == 0 {
eprintln!("No images found on the page.")
}
if let Some(next_page) = root.find(Name("a")).find_map(|node| {
node.attr("href")
.and_then(|href| if node.text() == ">" { Some(href) } else { None })
}) {
root = Document::from(self.get(next_page)?.text()?.as_str());
} else {
break;
}
}
let offset = 40 * start_page + 1;
let results: Vec<Result<(), Error>> = links
.into_par_iter()
.enumerate()
.map(|(page, link)| self.download_page(&link, &title, page + offset, num_digits))
.collect();
for result in results {
result?
}
Ok(Action::Continue)
}
fn download_page(
&self,
url: &str,
title: &str,
page_num: usize,
num_digits: Option<usize>,
) -> Result<(), Error> {
let resp = self.get(url)?;
let root = Document::from(resp.text()?.as_str());
let elem_text: String = root
.find(Attr("id", "i4").child(Name("div")))
.next()
.ok_or_else(|| ProgramError::new("no element with id i4"))?
.text();
let mut filename: String = FILENAME_RE
.captures(&elem_text)
.ok_or_else(|| ProgramError::new("failed to capture filename"))?[1]
.into();
if let Some(width) = num_digits {
filename = format!("{:0width$}_{}", page_num, filename, width = width);
}
let file_exists = fs::read_dir(title)?.filter_map(Result::ok).any(|item| {
item.file_name()
.into_string()
.expect("failed to get string from filename")
.to_lowercase()
== filename.to_lowercase()
});
if file_exists {
println!("Page {} skipped", page_num);
return Ok(());
}
let mut img_link: String = root
.find(Name("a"))
.filter_map(|elem| elem.attr("href"))
.find(|href| href.contains("fullimg.php"))
.or_else(|| -> Option<&str> { root.find(Attr("id", "img")).next()?.attr("src") })
.ok_or_else(|| ProgramError::new("Page missing img element"))?
.into();
let mut wait_time: usize = 0;
let mut content_length: usize = 0;
CHANNEL.with::<_, Result<(), Error>>(|channel| {
let mut channel = channel.borrow_mut();
loop {
let (tx, rx) = (&channel.0, &channel.1);
let img_resp = self.get(&img_link)?;
if wait_time == 0 {
content_length = img_resp.headers()["Content-Length"].to_str()?.parse()?;
wait_time = content_length / 64_000 + 1;
}
let _ = tx.send(Message::Start(Box::new(img_resp), content_length));
match rx.recv_timeout(Duration::from_secs(wait_time as u64)) {
Ok(Ok(bytes)) => {
let mut img_file = File::create(Path::new(title).join(&filename))?;
let mut cursor = Cursor::new(bytes);
io::copy(&mut cursor, &mut img_file)?;
break;
}
Ok(Err(e)) => {
eprintln!("Unexpected error:\n{:#?}", e);
println!("Page {} not saved", page_num);
return Ok(());
}
Err(RecvTimeoutError::Timeout) => {
let _ = tx.send(Message::Stop);
let new_channel = get_worker();
*channel = new_channel;
wait_time *= 2;
eprintln!(
"Page {} failed to load, retrying with a timeout of {} seconds.",
page_num, wait_time
);
img_link = get_loadfail_link(&img_link, &root)?;
}
Err(RecvTimeoutError::Disconnected) => {
unreachable!("worker thread disconnected")
}
};
}
println!("Page {} [{}] saved", page_num, &filename);
Ok(())
})
}
fn download_search(&self, url: &str) -> Result<Action, Error> {
let num_pages = self.num_pages.unwrap_or(usize::max_value());
let resp = self.get(url)?;
let mut root = Document::from(resp.text()?.as_str());
for _ in 0..num_pages {
for gallery_elem in root.find(Class("glink")) {
let gallery_link = gallery_elem
.parent()
.ok_or_else(|| ProgramError::new("glink had no parent"))?
.attr("href")
.ok_or_else(|| ProgramError::new("Gallery link had no href"))?;
if let Action::Abort = self.download_gallery(gallery_link)? {
return Ok(Action::Abort);
}
}
if let Some(next_page) = root.find(Name("a")).find_map(|node| {
node.attr("href")
.and_then(|href| if node.text() == ">" { Some(href) } else { None })
}) {
root = Document::from(self.get(next_page)?.text()?.as_str());
} else {
break;
}
}
Ok(Action::Continue)
}
fn get(&self, url: &str) -> Result<Response, Error> {
loop {
let mut last_request = LAST_REQUEST.lock().expect("last request mutex poisoned");
let diff = SystemTime::now()
.duration_since(*last_request)
.unwrap_or_default();
if diff < self.delay {
drop(last_request);
let to_sleep = self.delay - diff;
thread::sleep(to_sleep);
} else {
*last_request = SystemTime::now();
break;
}
}
self.client
.get(debug!(url))
.send()
.and_then(Response::error_for_status)
// TODO this fails to catch certain errors
.or_else(|e| match e.status() {
Some(StatusCode::REQUEST_TIMEOUT) => {
eprintln!("Request timeout, retrying...");
self.get(url)
}
Some(StatusCode::SERVICE_UNAVAILABLE) => {
eprintln!("Service unavailable, waiting 10 seconds and then retrying...");
thread::sleep(Duration::from_secs(10));
self.get(url)
}
_ => {
if let Some(source) = e.source() {
if let Some(hyper_err) = StdError::downcast_ref::<hyper::Error>(source) {
if hyper_err.is_incomplete_message() {
eprintln!("Incomplete request, retrying...");
self.get(url)
} else if hyper_err.is_closed() {
eprintln!("Channel closed, retrying...");
self.get(url)
} else if hyper_err.is_connect() {
eprintln!("Error connecting, retrying.");
self.get(url)
} else if let Some(inner) = hyper_err.source() {
if let Some(ioerr) = inner.downcast_ref::<io::Error>() {
match ioerr.kind() {
io::ErrorKind::TimedOut => {
eprintln!("IO timeout, retrying...");
self.get(url)
}
io::ErrorKind::NotConnected
| io::ErrorKind::ConnectionReset => {
eprintln!("Connection reset, retrying...");
self.get(url)
}
other => {
eprintln!("Unmatched IO error kind {:?}", other);
Err(e.into())
}
}
} else {
eprintln!("Hyper error source unmatched.");
eprintln!("{:#?}", e);
Err(e.into())
}
} else {
eprintln!("Hyper error no source.");
eprintln!("{:#?}", e);
Err(e.into())
}
} else {
eprintln!("Source was not a hyper error.");
eprintln!("{:?}", e);
Err(e.into())
}
} else {
eprintln!("Error without source.");
eprintln!("{:?}", e);
Err(e.into())
}
}
})
.map_err(Error::from)
.and_then(|resp| {
if resp.headers().get("etag") == Some(&ECODE_509) {
//TODO improve
eprintln!("Got bandwidth error, waiting 30 seconds and then retrying...");
let mut last_request =
LAST_REQUEST.lock().expect("last request mutex poisoned");
*last_request += Duration::from_secs(30);
drop(last_request);
self.get(url)
} else {
Ok(resp)
}
})
}
}
fn load_cookies() -> Result<toml::Value, Error> {
let mut input = String::new();
let mut file = File::open("cookies.toml")?;
file.read_to_string(&mut input)?;
input.parse().map_err(Error::from)
}
fn get_firefox_tabs() -> Result<Vec<String>, Error> {
let mut urls = Vec::new();
let firefox_data_path;
#[cfg(windows)]
{
firefox_data_path = PathBuf::from(env::var("APPDATA")?)
.join("Mozilla")
.join("Firefox");
}
#[cfg(unix)]
{
#[cfg(target_os = "macos")]
{
unimplemented!("unsupported operating system")
}
#[cfg(not(target_os = "macos"))]
{
firefox_data_path = PathBuf::from(env::var("HOME")?)
.join(".mozilla")
.join("firefox");
}
}
let inifile = Ini::load_from_file(firefox_data_path.join("profiles.ini"))?;
let mut profiles = vec![];
for idx in 0.. {
if let Some(profile) = inifile.section(Some(format!("Profile{}", idx))) {
profiles.push(firefox_data_path.join(&profile["Path"]));
} else {
break;
}
}
let session_path = profiles
.into_iter()
.map(|path| path.join("sessionstore-backups").join("recovery.jsonlz4"))
.filter(|path| path.exists())
.max_by_key(|path| {
fs::metadata(path)
.expect("Failed to get session metadata")
.modified()
.expect("Failed to get session modified time")
})
.ok_or_else(|| ProgramError::new("No profiles in profile dir"))?;
let mut session_file = File::open(session_path)?;
let mut buf = Vec::new();
session_file.read_to_end(&mut buf)?;
let data: serde_json::Value = serde_json::from_str(&String::from_utf8(
decompress(buf).map_err(|_| ProgramError::new("Failed to decompress session data"))?,
)?)?;
let windows = data
.get("windows")
.ok_or_else(|| ProgramError::new("Session had no windows"))?
.as_array()
.ok_or_else(|| ProgramError::new("Session windows was not an array"))?;
for window in windows {
let tabs = window
.get("tabs")
.ok_or_else(|| ProgramError::new("Session window had no tabs"))?
.as_array()
.ok_or_else(|| ProgramError::new("Session tabs was not an array"))?;
for tab in tabs {
let entries = tab
.get("entries")
.ok_or_else(|| ProgramError::new("Session tab had no entries"))?
.as_array()
.ok_or_else(|| ProgramError::new("Session tab entries was not an array"))?;
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
let index = tab
.get("index")
.ok_or_else(|| ProgramError::new("Session tab had no index"))?
.as_i64()
.ok_or_else(|| ProgramError::new("Session tab index was not a number"))?
as usize
- 1;
let current_entry = entries.get(index);
if let Some(entry) = current_entry {
let url = entry
.get("url")
.ok_or_else(|| ProgramError::new("Session entry had no url"))?
.as_str()
.ok_or_else(|| ProgramError::new("Session entry url was not a string"))?
.to_string();
let is_gallery: bool = GALLERY_URL_RE.is_match(&url);
if is_gallery {
urls.push(url);
}
}
}
}
Ok(urls)
}
fn build_dl(
paginate: bool,
num_pages: Option<usize>,
delay: Duration,
on_conflict: OnConflict,
) -> Result<Downloader, String> {
let mut cookies = String::new();
if let Ok(config) = load_cookies() {
for key in &["ipb_member_id", "ipb_pass_hash", "igneous"] {
if let Some(value) = config.get(key) {
if let Some(value) = value.as_str() {
cookies.push_str(key);
cookies.push('=');
cookies.push_str(value);
cookies.push(';');
} else {
return Err(format!(r#"Failed to parse cookie value for key "{}""#, key));
}
} else {
return Err(format!(r#"Missing key "{}" in cookies.toml!"#, key));
}
}
} else {
return Err("Could not find cookies.toml!".into());
}
let mut headers = HeaderMap::new();
headers.insert(
header::COOKIE,
HeaderValue::from_str(&cookies).expect("failed to construct cookie header"),
);
headers.insert(
header::ACCEPT_ENCODING,
HeaderValue::from_static("compress, gzip, deflate, br"),
);
Ok(Downloader::new(
headers,
paginate,
num_pages,
delay,
on_conflict,
))
}
fn main() -> Result<(), Error> {
let exhentai = Exhentai::from_args();
let delay = Duration::from_millis(exhentai.delay as u64);
let num_pages = if let Some(Command::Search { num_pages, .. }) = exhentai.cmd {
num_pages
} else {
None
};
let dl = match build_dl(exhentai.paginate, num_pages, delay, exhentai.on_conflict) {
Ok(dl) => dl,
Err(msg) => {
eprintln!("{}", msg);
return Ok(());
}
};
ThreadPoolBuilder::new()
.num_threads(exhentai.threads)
.build_global()?;
let (cmd, urls): (Cmd, Vec<String>) = match exhentai.cmd {
Some(Command::Gallery { urls }) => (Box::new(Downloader::download_gallery), urls),
Some(Command::Search { urls, .. }) => (Box::new(Downloader::download_search), urls),
Some(Command::Tabs) => (Box::new(Downloader::download_gallery), get_firefox_tabs()?),
None => (Box::new(Downloader::download_gallery), exhentai.urls),
};
for url in urls {
if let Action::Abort = cmd(&dl, &url)? {
break;
}
}
Ok(())
}
|
pub use io_uring_callback::IoUring;
/// A provider of an io_uring singleton.
///
/// This helper trait is intended to decouple the user of an IoUring instance
/// (here, a Socket instance) from the creater of an singleton of IoUring (e.g., a runtime).
/// And it frees each instance of a user type from storing their own reference to an io_uring
/// singleton---this info is embedded inside the type, not instances. This is a big win for
/// memory efficiency.
pub trait IoUringProvider: 'static + Send + Sync {
type Instance: std::ops::Deref<Target = IoUring>;
fn get_instance() -> Self::Instance;
}
|
use rustc::middle::{ty, def};
use rustc::middle::ty::MethodCall;
use syntax::{ast, ast_util, ast_map};
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::visit;
use syntax::visit::Visitor;
use std::fmt;
use std::mem::replace;
use std::collections::BTreeMap;
fn type_is_unsafe_function(ty: ty::Ty) -> bool {
match ty.sty {
ty::ty_bare_fn(_, ref f) => f.unsafety == ast::Unsafety::Unsafe,
_ => false,
}
}
pub struct NodeInfo {
pub span: Span,
pub is_fn: bool,
pub compiler: bool,
pub ffi: Vec<Span>,
pub raw_deref: Vec<Span>,
pub static_mut: Vec<Span>,
pub unsafe_call: Vec<Span>,
pub transmute: Vec<Span>,
pub transmute_imm_to_mut: Vec<Span>,
// these are only picked up with written in unsafe blocks, but *const
// as *mut is legal anywhere.
pub cast_raw_ptr_const_to_mut: Vec<Span>,
pub asm: Vec<Span>,
}
impl NodeInfo {
fn new(span: Span, is_fn: bool, compiler: bool) -> NodeInfo {
NodeInfo {
span: span,
is_fn: is_fn,
compiler: compiler,
ffi: Vec::new(),
raw_deref: Vec::new(),
static_mut: Vec::new(),
unsafe_call: Vec::new(),
transmute: Vec::new(),
transmute_imm_to_mut: Vec::new(),
cast_raw_ptr_const_to_mut: Vec::new(),
asm: Vec::new()
}
}
}
impl fmt::Debug for NodeInfo {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut first = true;
macro_rules! p ( ($fmt: tt, $name: ident) => {
if !self.$name.is_empty() {
if !first {
try!(write!(fmt, ", "));
} else {
first = false
}
try!(write!(fmt, concat!("{} ", $fmt), self.$name.len()))
}
});
p!("asm", asm);
p!("deref", raw_deref);
p!("ffi", ffi);
p!("static mut", static_mut);
p!("transmute", transmute);
p!("transmute & to &mut", transmute_imm_to_mut);
p!("cast *const to *mut", cast_raw_ptr_const_to_mut);
p!("unsafe call", unsafe_call);
// silence dead assign warning
if first {}
Ok(())
}
}
pub struct UnsafeVisitor<'tcx, 'a: 'tcx> {
tcx: &'tcx ty::ctxt<'a>,
/// Whether we're in an unsafe context.
node_info: Option<(ast::NodeId, NodeInfo)>,
pub unsafes: BTreeMap<ast::NodeId, NodeInfo>,
}
impl<'tcx, 'a> UnsafeVisitor<'tcx, 'a> {
pub fn new(tcx: &'tcx ty::ctxt<'a>) -> UnsafeVisitor<'tcx, 'a> {
UnsafeVisitor {
tcx: tcx,
node_info: None,
unsafes: BTreeMap::new(),
}
}
pub fn check_crate(&mut self, krate: &ast::Crate) {
visit::walk_crate(self, krate)
}
fn info<'b>(&'b mut self) -> &'b mut NodeInfo {
&mut self.node_info.as_mut().unwrap().1
}
fn check_ptr_cast(&mut self, span: Span, from: &ast::Expr, to: &ast::Expr) -> bool {
let from_ty = ty::expr_ty(self.tcx, from);
let to_ty = ty::expr_ty(self.tcx, to);
match (&from_ty.sty, &to_ty.sty) {
(&ty::ty_rptr(_, ty::mt { mutbl: ast::MutImmutable, .. }),
&ty::ty_rptr(_, ty::mt { mutbl: ast::MutMutable, .. })) => {
self.info().transmute_imm_to_mut.push(span);
true
}
(&ty::ty_ptr(ty::mt { mutbl: ast::MutImmutable, .. }),
&ty::ty_ptr(ty::mt { mutbl: ast::MutMutable, .. })) => {
self.info().cast_raw_ptr_const_to_mut.push(span);
true
}
_ => {
false
}
}
}
}
impl<'tcx,'a,'b> Visitor<'a> for UnsafeVisitor<'tcx,'b> {
fn visit_fn(&mut self, fn_kind: visit::FnKind<'a>, fn_decl: &'a ast::FnDecl,
block: &ast::Block, span: Span, node_id: ast::NodeId) {
let (is_item_fn, is_unsafe_fn) = match fn_kind {
visit::FkItemFn(_, _, fn_style, _, _) =>
(true, fn_style == ast::Unsafety::Unsafe),
visit::FkMethod(_, sig, _) =>
(true, sig.unsafety == ast::Unsafety::Unsafe),
_ => (false, false),
};
let old_node_info = if is_unsafe_fn {
replace(&mut self.node_info, Some((node_id, NodeInfo::new(span, true, false))))
} else if is_item_fn {
replace(&mut self.node_info, None)
} else {
None
};
visit::walk_fn(self, fn_kind, fn_decl, block, span);
match replace(&mut self.node_info, old_node_info) {
Some((id, info)) => assert!(self.unsafes.insert(id, info).is_none()),
//Some((id, info)) => { self.unsafes.insert(id, info); }
None => {}
}
}
fn visit_block(&mut self, block: &'a ast::Block) {
let (old_node_info, inserted) = match block.rules {
ast::DefaultBlock => (None, false),
ast::UnsafeBlock(source) => {
let compiler = source == ast::CompilerGenerated;
if self.node_info.is_none() || compiler {
(replace(&mut self.node_info,
Some((block.id, NodeInfo::new(block.span, false, compiler)))),
true)
} else {
(None, false)
}
}
};
visit::walk_block(self, block);
if inserted {
match replace(&mut self.node_info, old_node_info) {
Some((id, info)) => assert!(self.unsafes.insert(id, info).is_none()),
//Some((id, info)) => { self.unsafes.insert(id, info); }
None => {}
}
}
}
fn visit_expr(&mut self, expr: &'a ast::Expr) {
if self.node_info.is_some() {
match expr.node {
ast::ExprMethodCall(_, _, _) => {
let method_call = MethodCall::expr(expr.id);
let base_type = self.tcx.method_map.borrow()[&method_call].ty;
if type_is_unsafe_function(base_type) {
self.info().unsafe_call.push(expr.span)
}
}
ast::ExprCall(ref base, ref args) => {
match (&base.node, &**args) {
(&ast::ExprPath(_, ref p), [ref arg])
// ew, but whatever.
if p.segments.last().unwrap().identifier.name ==
token::intern("transmute") => {
if !self.check_ptr_cast(expr.span, &**arg, expr) {
// not a */& -> *mut/&mut cast.
self.info().transmute.push(expr.span)
}
}
_ => {
let is_ffi = match self.tcx.def_map.borrow().get(&base.id) {
Some(&def::PathResolution { base_def: def::DefFn(did, _), .. }) => {
// cross-crate calls are always
// just unsafe calls.
ast_util::is_local(did) &&
match self.tcx.map.get(did.node) {
ast_map::NodeForeignItem(_) => true,
_ => false
}
}
_ => false
};
if is_ffi {
self.info().ffi.push(expr.span)
} else {
let base_type = ty::node_id_to_type(self.tcx, base.id);
if type_is_unsafe_function(base_type) {
self.info().unsafe_call.push(expr.span)
}
}
}
}
}
ast::ExprUnary(ast::UnDeref, ref base) => {
let base_type = ty::node_id_to_type(self.tcx, base.id);
match base_type.sty {
ty::ty_ptr(_) => {
self.info().raw_deref.push(expr.span)
}
_ => {}
}
}
ast::ExprInlineAsm(..) => {
self.info().asm.push(expr.span)
}
ast::ExprPath(..) => {
match ty::resolve_expr(self.tcx, expr) {
def::DefStatic(_, true) => {
self.info().static_mut.push(expr.span)
}
_ => {}
}
}
ast::ExprCast(ref from, _) => {
self.check_ptr_cast(expr.span, &**from, expr);
}
_ => {}
}
}
visit::walk_expr(self, expr);
}
}
|
use std::cmp;
use std::collections::HashMap;
mod utils;
fn main() {
let data = utils::load_input("./data/day_10.txt").unwrap();
let mut nbs: Vec<u32> = data.lines().map(|nb| nb.parse().unwrap()).collect();
nbs.push(0);
nbs.sort_unstable();
nbs.push(nbs.last().unwrap() + 3);
let mut diff: (u32, u32) = (0, 0);
let mut nb_prev: u32 = 0;
for nb in nbs.iter() {
if nb_prev + 1 == *nb {
diff.0 += 1;
}
if nb_prev + 3 == *nb {
diff.1 += 1;
}
nb_prev = *nb;
}
println!("Answer 1/2: {}", diff.0 * diff.1);
println!(
"Answer 2/2: {}",
count_combinations(0, &mut HashMap::new(), &nbs)
);
}
fn count_combinations(i: usize, memo: &mut HashMap<usize, usize>, nbs: &[u32]) -> usize {
if i == nbs.len() - 1 {
return 1; // 1 path has been found
}
if let Some(&count) = memo.get(&i) {
return count;
}
let mut count: usize = 0;
let i_next = i + 1;
let i_next_end = cmp::min(nbs.len(), i + 4);
// explore the three path
for (j, nb) in nbs[i_next..i_next_end].iter().enumerate() {
if nb - nbs[i] <= 3 {
count += count_combinations(i_next + j, memo, nbs);
}
}
memo.insert(i, count);
count
}
|
extern crate csv;
extern crate rustc_serialize;
extern crate image;
extern crate num;
mod color_calc;
mod eq;
mod fileformat;
mod image_create;
pub use eq::mandelbrot_divergence;
pub use fileformat::parse_frame;
pub use image_create::gen_png;
pub use image_create::write_png;
pub use image_create::Frame;
pub use image_create::get_pixel_values;
|
use crate::types::{HitRecord, Hitable, Material, Ray, Vec3};
pub struct Sphere {
center: Vec3,
radius: f64,
material: Option<Box<dyn Material>>,
}
impl Sphere {
pub fn new(center: Vec3, radius: f64) -> Self {
Self {
center,
radius,
material: None,
}
}
pub fn with_material(center: Vec3, radius: f64, material: Box<dyn Material>) -> Self {
Self {
center,
radius,
material: Some(material),
}
}
}
impl Hitable for Sphere {
fn hit(&self, ray: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> {
let oc = ray.origin() - self.center;
let a = ray.direction().dot(&ray.direction());
let b = oc.dot(&ray.direction());
let c = oc.dot(&oc) - self.radius * self.radius;
// The discriminant is calculated using b^2 - 4 * a * c
// but in this specific case, If we put the equation in the
// formula to find quadratic roots, We can get this shorter
// formula to find the discriminant.
// Check this for detailed proof
// https://vchizhov.github.io/resources/ray%20tracing/ray%20tracing%20tutorial%20series%20vchizhov/ray_casting/part1/intersecting_a_sphere.md.html#appendix
let discriminant = b * b - a * c;
let discriminant_root = discriminant.sqrt();
if discriminant > 0.0 {
let root = (-b - discriminant_root) / a;
if root < t_max && root > t_min {
let p = ray.point_at_parameter(root);
return Some(HitRecord {
t: root,
p,
normal: (p - self.center) / self.radius,
material: self.material.as_ref(),
});
}
let root = (-b + discriminant_root) / a;
if root < t_max && root > t_min {
let p = ray.point_at_parameter(root);
return Some(HitRecord {
t: root,
p,
normal: (p - self.center) / self.radius,
material: self.material.as_ref(),
});
}
}
None
}
}
|
use std::io::prelude::*;
use std::str::FromStr;
fn ans( i : Vec<f64> ) -> (f64,f64) {
let a = i[0];
let b = i[1];
let c = i[2];
let d = i[3];
let e = i[4];
let f = i[5];
let x = ( (c*e - b*f) / (a*e - b*d) * 1000.0).round() / 1000.0;
let y = ( (c*d - a*f) / (b*d - a*e) * 1000.0).round() / 1000.0;
(x,y)
}
fn main() {
let stdin = std::io::stdin();
for line in stdin.lock().lines() {
let d : Vec<f64> = line.unwrap().split_whitespace().map(|x| f64::from_str(x).unwrap()).collect();
let (x,y) = ans(d);
println!("{:.3} {:.3}",x,y);
}
}
|
#![allow(dead_code)]
#[cxx::bridge]
mod ffi {
extern "Rust" {
type MultiCxx2Thing;
fn another_new_thing(id: i64) -> Box<MultiCxx2Thing>;
fn another_print_thing(thing: Box<MultiCxx2Thing>);
fn another_print_thing_ref(thing: &Box<MultiCxx2Thing>);
}
}
use super::thing;
#[repr(C)]
pub struct MultiCxx2Thing(pub thing::Thing);
pub fn another_new_thing(id: i64) -> Box<MultiCxx2Thing> {
Box::new(MultiCxx2Thing(thing::another_new_thing(id)))
}
pub fn another_print_thing_ref(thing: &Box<MultiCxx2Thing>) -> () {
println!("I am thing {}", (*thing).0.id)
}
pub fn another_print_thing(thing: Box<MultiCxx2Thing>) -> () {
println!("I am thing {}", (*thing).0.id)
}
|
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::convert::TryInto;
use cosmwasm_std::{Addr, Binary, Coin, StdError, StdResult, Timestamp, Uint128};
use cw721::{Expiration, OwnerOfResponse};
use cw721_base::msg::{ExecuteMsg as CW721ExecuteMsg, QueryMsg as CW721QueryMsg};
use cw721_base::state::Approval;
// ----------------- begin CW721 ^0.9.2 shim ----------------- //
// adapted from: https://github.com/CosmWasm/cw-nfts/blob/5e1e72a3682f988d4504b94f2e203dd4a5a99ad9/contracts/cw721-metadata-onchain/src/lib.rs#L7-L26
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug, Default)]
pub struct Cw721Trait {
pub display_type: Option<String>,
pub trait_type: String,
pub value: String,
}
// see: https://docs.opensea.io/docs/metadata-standards
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug, Default)]
pub struct Cw721Metadata {
pub image: Option<String>,
pub image_data: Option<String>,
pub external_url: Option<String>,
pub description: Option<String>,
pub name: Option<String>,
pub attributes: Option<Vec<Cw721Trait>>,
pub background_color: Option<String>,
pub animation_url: Option<String>,
pub youtube_url: Option<String>,
}
// adapted from: https://github.com/CosmWasm/cw-nfts/blob/5e1e72a3682f988d4504b94f2e203dd4a5a99ad9/packages/cw721/src/query.rs#L93-L109
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct Cw721NftInfoResponse {
/// Universal resource identifier for this NFT
/// Should point to a JSON file that conforms to the ERC721
/// Metadata JSON Schema
pub token_uri: Option<String>,
/// You can add any custom metadata here when you extend cw721-base
pub extension: Cw721Metadata,
}
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct Cw721AllNftInfoResponse {
/// Who can transfer the token
pub access: OwnerOfResponse,
/// Data on the token itself,
pub info: Cw721NftInfoResponse,
}
// ----------------- end CW721 ^0.9.2 shim----------------- //
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct Config {
/// If true, then anyone can mint an xyz token. If false, then only the
/// contract owner is authorized to mint.
pub public_minting_enabled: bool,
/// The maximum value of a coordinate in any dimension. The minimum
/// will be set to the negation of this value.
pub max_coordinate_value: i64,
/// The maximum allowed number of xyz tokens
pub token_supply: u64,
/// The maximum number of tokens a particular wallet can hold
pub wallet_limit: u32,
/// The price to mint a new xyz (doesn't apply to the contract owner)
pub mint_fee: Coin,
/// The time it takes to initiate a move. To get overall move time:
/// base_move_nanos + move_nanos_per_step * distance
pub base_move_nanos: u64,
/// The move travel time per marginal step taken, where a
/// step is a one-dimensional coordinate increment or decrement.
pub move_nanos_per_step: u64,
/// The base fee to initiate a move. To get overall move fee:
/// base_move_fee.amount + move_fee_per_step * distance
pub base_move_fee: Coin,
/// The increase in move fee price per marginal step taken, where
/// a step is a one-dimensional coordinate increment or decrement.
/// Assumed to be in the denom associated with base_move_fee.
pub move_fee_per_step: Uint128,
}
impl Config {
pub fn get_move_fee(&self, start: Coordinates, end: Coordinates) -> Coin {
let distance = start.distance(end) as u128;
let move_fee_amount =
self.base_move_fee.amount.u128() + self.move_fee_per_step.u128() * distance;
Coin::new(move_fee_amount, &self.base_move_fee.denom)
}
pub fn get_move_nanos(&self, start: Coordinates, end: Coordinates) -> u64 {
let distance = start.distance(end) as u64;
self.base_move_nanos + self.move_nanos_per_step * distance
}
pub fn check_bounds(&self, coords: Coordinates) -> StdResult<()> {
let min_coordinate_value = -self.max_coordinate_value;
if vec![coords.x, coords.y, coords.z]
.iter()
.any(|c| c < &min_coordinate_value || c > &self.max_coordinate_value)
{
let error = StdError::generic_err(format!(
"coordinate values must be between {} and {}",
min_coordinate_value, self.max_coordinate_value
));
return Err(error);
}
Ok(())
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema, Copy)]
pub struct Coordinates {
pub x: i64,
pub y: i64,
pub z: i64,
}
impl Coordinates {
pub fn to_bytes(&self) -> Vec<u8> {
vec![
self.x.to_be_bytes(),
self.y.to_be_bytes(),
self.z.to_be_bytes(),
]
.concat()
}
pub fn distance(&self, other: Self) -> u64 {
let distance =
(self.x - other.x).abs() + (self.y - other.y).abs() + (self.z - other.z).abs();
// the distance will always be positive, since it's a sum of absolute values
distance.try_into().unwrap()
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema, Copy)]
pub struct XyzExtension {
pub coordinates: Coordinates,
pub prev_coordinates: Option<Coordinates>,
pub arrival: Timestamp,
}
impl XyzExtension {
pub fn has_arrived(&self, current_time: Timestamp) -> bool {
self.arrival <= current_time
}
pub fn as_traits(&self) -> Vec<Cw721Trait> {
vec![
Cw721Trait {
display_type: None,
trait_type: "x".to_string(),
value: self.coordinates.x.to_string(),
},
Cw721Trait {
display_type: None,
trait_type: "y".to_string(),
value: self.coordinates.y.to_string(),
},
Cw721Trait {
display_type: None,
trait_type: "z".to_string(),
value: self.coordinates.z.to_string(),
},
]
}
}
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct XyzTokenInfo {
pub owner: Addr,
pub approvals: Vec<Approval>,
pub name: String,
pub description: String,
pub image: Option<String>,
pub extension: XyzExtension,
}
impl XyzTokenInfo {
pub fn as_cw721_nft_info(&self) -> Cw721NftInfoResponse {
Cw721NftInfoResponse {
token_uri: None,
extension: Cw721Metadata {
name: Some(self.name.clone()),
image: Some(self.base64_token_image()),
description: Some(self.description.clone()),
attributes: Some(self.extension.as_traits()),
image_data: None,
external_url: None,
animation_url: None,
background_color: None,
youtube_url: None,
},
}
}
pub fn base64_token_image(&self) -> String {
base64_token_image(&self.extension.coordinates)
}
}
pub fn base64_token_image(coords: &Coordinates) -> String {
let svg = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 240 240"><g class="container"><rect style="width:240px;height:240px;fill:#000;"/><text x="120" y="120" dominant-baseline="middle" text-anchor="middle" style="fill:#fff;font-family:serif;font-size:16px;text-align:center;">[{}, {}, {}]</text></g></svg>"#,
coords.x, coords.y, coords.z
);
let base64_uri = format!("data:image/svg+xml;base64,{}", base64::encode(svg));
base64_uri
}
pub fn full_token_id(numeric_token_id: String) -> StdResult<String> {
// make sure the string is an integer
numeric_token_id
.parse::<u64>()
.map_err(|_| StdError::generic_err("expected numeric token identifier"))?;
Ok(format!("xyz #{}", numeric_token_id))
}
pub fn numeric_token_id(full_token_id: String) -> StdResult<String> {
if !full_token_id.starts_with("xyz #") {
return Err(StdError::generic_err(
"expected full token identifier, like 'xyz #123'",
));
}
Ok(full_token_id.trim_start_matches("xyz #").to_string())
}
/// This overrides the ExecuteMsg enum defined in cw721-base
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub struct InstantiateMsg {
pub captcha_public_key: String,
pub config: Config,
}
/// This overrides the ExecuteMsg enum defined in cw721-base
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
/// Mint a new NFT for the message sender with the given set of coordinates and signature
/// from the recaptcha verifier lambda function.
Mint {
coordinates: Coordinates,
captcha_signature: String,
},
/// Move an existing NFT to the given set of coordinates.
Move {
token_id: String,
coordinates: Coordinates,
},
/// Update token minting and supply configuration.
UpdateConfig {
config: Config,
},
/// Update public key used for captcha verification.
UpdateCaptchaPublicKey {
public_key: String,
},
/// Withdraw from current contract balance to owner address.
Withdraw {
amount: Vec<Coin>,
},
/// BELOW ARE COPIED FROM CW721-BASE
TransferNft {
recipient: String,
token_id: String,
},
SendNft {
contract: String,
token_id: String,
msg: Binary,
},
Approve {
spender: String,
token_id: String,
expires: Option<Expiration>,
},
Revoke {
spender: String,
token_id: String,
},
ApproveAll {
operator: String,
expires: Option<Expiration>,
},
RevokeAll {
operator: String,
},
}
impl From<ExecuteMsg> for CW721ExecuteMsg<XyzExtension> {
fn from(msg: ExecuteMsg) -> CW721ExecuteMsg<XyzExtension> {
match msg {
ExecuteMsg::TransferNft {
recipient,
token_id,
} => CW721ExecuteMsg::TransferNft {
recipient,
token_id,
},
ExecuteMsg::SendNft {
contract,
token_id,
msg,
} => CW721ExecuteMsg::SendNft {
contract,
token_id,
msg,
},
ExecuteMsg::Approve {
spender,
token_id,
expires,
} => CW721ExecuteMsg::Approve {
spender,
token_id,
expires,
},
ExecuteMsg::Revoke { spender, token_id } => {
CW721ExecuteMsg::Revoke { spender, token_id }
}
ExecuteMsg::ApproveAll { operator, expires } => {
CW721ExecuteMsg::ApproveAll { operator, expires }
}
ExecuteMsg::RevokeAll { operator } => CW721ExecuteMsg::RevokeAll { operator },
_ => panic!("cannot covert {:?} to CW721ExecuteMsg", msg),
}
}
}
/// This overrides the ExecuteMsg enum defined in cw721-base
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
/// Returns the current contract config
/// Return type: Config
Config {},
/// Returns the currently configured captcha public key
CaptchaPublicKey {},
/// Returns all tokens owned by the given address, [] if unset.
/// Return type: XyzTokensResponse.
XyzTokens {
owner: String,
start_after: Option<String>,
limit: Option<u32>,
},
/// Lists all token_ids controlled by the contract.
/// Return type: XyzTokensResponse.
AllXyzTokens {
start_after: Option<String>,
limit: Option<u32>,
},
/// Returns metadata about one particular token, based on *ERC721 Metadata JSON Schema*
/// but directly from the contract: XyzTokenInfo.
XyzNftInfo {
token_id: String,
},
/// Returns metadata about the token associated with the given coordinates, if any.
/// Return type: XyzTokenInfo.
XyzNftInfoByCoords {
coordinates: Coordinates,
},
/// Returns the number of tokens owned by the given address
/// Return type: NumTokensResponse
NumTokensForOwner {
owner: String,
},
/// Calculates the price to move the given token to the given coordinate.
/// Return type: MoveParamsResponse
MoveParams {
token_id: String,
coordinates: Coordinates,
},
// BELOW ARE COPIED FROM CW721-BASE
OwnerOf {
token_id: String,
include_expired: Option<bool>,
},
ApprovedForAll {
owner: String,
include_expired: Option<bool>,
start_after: Option<String>,
limit: Option<u32>,
},
NumTokens {},
ContractInfo {},
NftInfo {
token_id: String,
},
AllNftInfo {
token_id: String,
include_expired: Option<bool>,
},
Tokens {
owner: String,
start_after: Option<String>,
limit: Option<u32>,
},
AllTokens {
start_after: Option<String>,
limit: Option<u32>,
},
}
impl From<QueryMsg> for CW721QueryMsg {
fn from(msg: QueryMsg) -> CW721QueryMsg {
match msg {
QueryMsg::XyzTokens {
owner,
start_after,
limit,
} => CW721QueryMsg::Tokens {
owner,
start_after,
limit,
},
QueryMsg::AllXyzTokens { start_after, limit } => {
CW721QueryMsg::AllTokens { start_after, limit }
}
QueryMsg::XyzNftInfo { token_id } => CW721QueryMsg::NftInfo { token_id },
QueryMsg::OwnerOf {
token_id,
include_expired,
} => CW721QueryMsg::OwnerOf {
token_id,
include_expired,
},
QueryMsg::ApprovedForAll {
owner,
include_expired,
start_after,
limit,
} => CW721QueryMsg::ApprovedForAll {
owner,
include_expired,
start_after,
limit,
},
QueryMsg::NumTokens {} => CW721QueryMsg::NumTokens {},
QueryMsg::ContractInfo {} => CW721QueryMsg::ContractInfo {},
QueryMsg::NftInfo { token_id } => CW721QueryMsg::NftInfo { token_id },
QueryMsg::AllNftInfo {
token_id,
include_expired,
} => CW721QueryMsg::AllNftInfo {
token_id,
include_expired,
},
QueryMsg::Tokens {
owner,
start_after,
limit,
} => CW721QueryMsg::Tokens {
owner,
start_after,
limit,
},
QueryMsg::AllTokens { start_after, limit } => {
CW721QueryMsg::AllTokens { start_after, limit }
}
_ => panic!("cannot covert {:?} to CW721QueryMsg", msg),
}
}
}
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct XyzTokensResponse {
pub tokens: Vec<XyzTokenInfo>,
}
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct MoveParamsResponse {
pub fee: Coin,
pub duration_nanos: u64,
}
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub struct MigrateMsg {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn xyz_token_info_as_cw721_nft_info() {
let info = XyzTokenInfo {
name: "xyz #1".to_string(),
owner: Addr::unchecked("test owner"),
description: "test description".to_string(),
image: None,
approvals: vec![],
extension: XyzExtension {
coordinates: Coordinates { x: 1, y: 2, z: 3 },
prev_coordinates: None,
arrival: Timestamp::from_nanos(1),
},
};
assert_eq!(
info.as_cw721_nft_info(),
Cw721NftInfoResponse {
token_uri: None,
extension: Cw721Metadata {
name: Some("xyz #1".to_string()),
description: Some("test description".to_string()),
image: Some("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHByZXNlcnZlQXNwZWN0UmF0aW89InhNaW5ZTWluIG1lZXQiIHZpZXdCb3g9IjAgMCAyNDAgMjQwIj48ZyBjbGFzcz0iY29udGFpbmVyIj48cmVjdCBzdHlsZT0id2lkdGg6MjQwcHg7aGVpZ2h0OjI0MHB4O2ZpbGw6IzAwMDsiLz48dGV4dCB4PSIxMjAiIHk9IjEyMCIgZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgc3R5bGU9ImZpbGw6I2ZmZjtmb250LWZhbWlseTpzZXJpZjtmb250LXNpemU6MTZweDt0ZXh0LWFsaWduOmNlbnRlcjsiPlsxLCAyLCAzXTwvdGV4dD48L2c+PC9zdmc+".to_string()),
attributes: Some(vec![
Cw721Trait {
display_type: None,
trait_type: "x".to_string(),
value: "1".to_string(),
},
Cw721Trait {
display_type: None,
trait_type: "y".to_string(),
value: "2".to_string(),
},
Cw721Trait {
display_type: None,
trait_type: "z".to_string(),
value: "3".to_string(),
},
]),
image_data: None,
animation_url: None,
youtube_url: None,
external_url: None,
background_color: None
}
}
)
}
}
|
extern crate cursive;
use cursive::Cursive;
use cursive::views::TextView;
fn main() {
let mut siv = Cursive::new();
siv.add_layer(TextView::new("Hello World!\nPress q to quit."));
siv.add_global_callback('q', |s| s.quit());
siv.run();
println!("Hello, world!");
}
|
use rustc_codegen_ssa::traits::PreDefineMethods;
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
use rustc_middle::mir::mono::{Linkage, Visibility};
use rustc_middle::ty::{self, Instance, TypeFoldable};
use rustc_middle::ty::layout::FnAbiExt;
use rustc_span::def_id::DefId;
use rustc_target::abi::LayoutOf;
use rustc_target::abi::call::FnAbi;
use crate::base;
use crate::context::CodegenCx;
use crate::type_of::LayoutGccExt;
impl<'gcc, 'tcx> PreDefineMethods<'tcx> for CodegenCx<'gcc, 'tcx> {
fn predefine_static(&self, def_id: DefId, linkage: Linkage, visibility: Visibility, symbol_name: &str) {
let attrs = self.tcx.codegen_fn_attrs(def_id);
let instance = Instance::mono(self.tcx, def_id);
let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
let gcc_type = self.layout_of(ty).gcc_type(self, true);
let is_tls = attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL);
let global = self.define_global(symbol_name, gcc_type, is_tls, attrs.link_section).unwrap_or_else(|| {
self.sess().span_fatal(
self.tcx.def_span(def_id),
&format!("symbol `{}` is already defined", symbol_name),
)
});
// TODO
/*unsafe {
llvm::LLVMRustSetLinkage(global, base::linkage_to_llvm(linkage));
llvm::LLVMRustSetVisibility(global, base::visibility_to_llvm(visibility));
}*/
self.instances.borrow_mut().insert(instance, global);
}
fn predefine_fn(&self, instance: Instance<'tcx>, linkage: Linkage, visibility: Visibility, symbol_name: &str) {
assert!(!instance.substs.needs_infer() && !instance.substs.has_param_types_or_consts());
let fn_abi = FnAbi::of_instance(self, instance, &[]);
self.linkage.set(base::linkage_to_gcc(linkage));
let decl = self.declare_fn(symbol_name, &fn_abi);
let attrs = self.tcx.codegen_fn_attrs(instance.def_id());
// TODO: call set_link_section() to allow initializing argc/argv.
//base::set_link_section(decl, &attrs);
/*if linkage == Linkage::LinkOnceODR || linkage == Linkage::WeakODR {
llvm::SetUniqueComdat(self.llmod, decl);
}*/
//debug!("predefine_fn: instance = {:?}", instance);
// TODO: use inline attribute from there in linkage.set() above:
//attributes::from_fn_attrs(self, decl, instance);
//self.instances.borrow_mut().insert(instance, decl);
}
}
|
pub mod background;
pub mod border;
pub mod graphical;
pub mod label;
pub mod scroll;
pub mod text_block;
pub mod text_box;
|
use amethyst::{
assets::Handle,
core::Transform,
ecs::{Component, DenseVecStorage},
prelude::{Builder, WorldExt},
renderer::{SpriteRender, SpriteSheet},
shred::World,
};
use crate::settings::{ARENA_HEIGHT, ARENA_WIDTH, PADDLE_HEIGHT, PADDLE_WIDTH};
/// Enum used to identify the left/right paddles.
#[derive(PartialEq, Eq, Debug)]
pub enum Side {
Left,
Right,
}
/// Paddle component struct.
#[derive(Debug)]
pub struct Paddle {
pub side: Side,
pub width: f32,
pub height: f32,
}
impl Paddle {
fn new(side: Side) -> Paddle {
Paddle {
side,
width: PADDLE_WIDTH,
height: PADDLE_HEIGHT,
}
}
}
// This adds the 'Component' behavior to the Paddle
impl Component for Paddle {
type Storage = DenseVecStorage<Self>; // Component<Paddle>
}
/// Creates the left and right paddles at their starting position and attaches them
/// to the World object.
pub fn initialize_paddles(world: &mut World, sprite_sheet_handle: Handle<SpriteSheet>) {
let mut left_paddle_transform = Transform::default();
let mut right_paddle_transform = Transform::default();
let starting_y = ARENA_HEIGHT / 2.0;
// SpriteRender is a component that is a 'slice' of a spritesheet
let paddle_left = SpriteRender::new(sprite_sheet_handle, 0); // paddle is the first sprite
let paddle_right = paddle_left.clone();
// coordinate transforms to position the paddles
left_paddle_transform.set_translation_xyz(PADDLE_WIDTH * 0.5, starting_y, 0.0);
right_paddle_transform.set_translation_xyz(ARENA_WIDTH - PADDLE_WIDTH * 0.5, starting_y, 0.0);
// left paddle creation
world
.create_entity()
.with(Paddle::new(Side::Left)) // component used in ReadStorage
.with(paddle_left)
.with(left_paddle_transform)
.build();
// right paddle creation (entity + component<state> in ECS)
world
.create_entity()
.with(Paddle::new(Side::Right))
.with(paddle_right) // sprite renderer
.with(right_paddle_transform)
.build();
}
|
//! This module fixes the incorrect handling of fixed values in the schema
use crate::schema_registry::SRCError;
use avro_rs::schema::{RecordField, UnionSchema};
use avro_rs::types::{ToAvro, Value};
use avro_rs::Schema;
use std::collections::HashMap;
pub trait FixedFixer {
fn fix_fixed(self, schema: &Schema) -> Result<Self, SRCError>
where
Self: std::marker::Sized;
fn fix_fixed_fixed(self, size: usize) -> Result<Self, SRCError>
where
Self: std::marker::Sized;
fn fix_fixed_union(self, schema: &UnionSchema) -> Result<Self, SRCError>
where
Self: std::marker::Sized;
fn fix_fixed_array(self, schema: &Schema) -> Result<Self, SRCError>
where
Self: std::marker::Sized;
fn fix_fixed_map(self, schema: &Schema) -> Result<Self, SRCError>
where
Self: std::marker::Sized;
fn fix_fixed_record(self, schema: &[RecordField]) -> Result<Self, SRCError>
where
Self: std::marker::Sized;
}
fn vec_to_fixed(vec: Vec<Value>) -> Result<Value, SRCError> {
let mut errors: Vec<Value> = vec![];
let mut hits: Vec<u8> = vec![];
vec.iter().for_each(|part| match part {
Value::Int(v) => {
if *v >= 0 && *v <= 255 {
hits.push((v & 0xff) as u8)
} else {
errors.push(Value::Int(*v))
}
}
other => errors.push(other.clone()),
});
if errors.is_empty() {
Ok(Value::Fixed(vec.len(), hits))
} else {
Err(SRCError::non_retryable_from_err(
format!(
"Found non-int values and/or ints that can't be converted to bytes: {:#?}",
errors
),
"could not fix fixed",
))
}
}
impl FixedFixer for Value {
/// Will go through the schema and value, and convert arrays of the correct size to fixed
/// equivalents in order to fix serialization for structs.
fn fix_fixed(self, schema: &Schema) -> Result<Self, SRCError> {
match *schema {
Schema::Fixed { size, .. } => self.fix_fixed_fixed(size),
Schema::Union(ref inner) => self.fix_fixed_union(inner),
Schema::Array(ref inner) => self.fix_fixed_array(inner),
Schema::Map(ref inner) => self.fix_fixed_map(inner),
Schema::Record { ref fields, .. } => self.fix_fixed_record(fields),
_ => Ok(self),
}
}
fn fix_fixed_fixed(self, size: usize) -> Result<Self, SRCError> {
match self {
Value::Fixed(n, bytes) => {
if n == size {
Ok(Value::Fixed(n, bytes))
} else {
Err(SRCError::non_retryable_from_err(
format!("Fixed size mismatch, {} expected, got {}", size, n),
"could not fix fixed",
))
}
}
Value::Array(vec) => {
if vec.len() == size {
vec_to_fixed(vec)
} else {
Err(SRCError::non_retryable_from_err(
format!("Array size mismatch, {} expected, got {}", size, vec.len()),
"could not fix fixed",
))
}
}
other => Err(SRCError::non_retryable_from_err(
format!("Fixed or vector expected, got {:?}", other),
"could not fix fixed",
)),
}
}
fn fix_fixed_union(self, schema: &UnionSchema) -> Result<Self, SRCError> {
let v = match self {
// Both are unions case.
Value::Union(v) => *v,
// Reader is a union, but writer is not.
v => v,
};
// Find the first match in the reader schema.
let (_, inner) = schema.find_schema(&v).ok_or_else(|| {
SRCError::non_retryable_from_err(
"Could not find matching type in union",
"could not fix fixed",
)
})?;
v.fix_fixed(inner)
}
fn fix_fixed_array(self, schema: &Schema) -> Result<Self, SRCError> {
match self {
Value::Array(items) => Ok(Value::Array(
items
.into_iter()
.map(|item| item.fix_fixed(schema))
.collect::<Result<Vec<_>, _>>()?,
)),
other => Err(SRCError::non_retryable_from_err(
format!("Array({:?}) expected, got {:?}", schema, other),
"could not fix fixed",
)),
}
}
fn fix_fixed_map(self, schema: &Schema) -> Result<Self, SRCError> {
match self {
Value::Map(items) => Ok(Value::Map(
items
.into_iter()
.map(|(key, value)| value.fix_fixed(schema).map(|value| (key, value)))
.collect::<Result<HashMap<_, _>, _>>()?,
)),
other => Err(SRCError::non_retryable_from_err(
format!("Map({:?}) expected, got {:?}", schema, other),
"could not fix fixed",
)),
}
}
fn fix_fixed_record(self, fields: &[RecordField]) -> Result<Self, SRCError> {
let mut items = match self {
Value::Map(items) => Ok(items),
Value::Record(fields) => Ok(fields.into_iter().collect::<HashMap<_, _>>()),
other => Err(SRCError::non_retryable_from_err(
format!("Record({:?}) expected, got {:?}", fields, other),
"Error creating record",
)),
}?;
let new_fields = fields
.iter()
.map(|field| {
let value = match items.remove(&field.name) {
Some(value) => value,
None => match field.default {
Some(ref value) => value.clone().avro(),
_ => {
return Err(SRCError::non_retryable_from_err(
format!("missing field {} in record", field.name),
"error fixing record",
))
}
},
};
value
.fix_fixed(&field.schema)
.map(|value| (field.name.clone(), value))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Value::Record(new_fields))
}
}
|
use crate::{instruction::Instruction, registers::Registers};
use failure::{bail, format_err, Error};
use hashbrown::HashSet;
use std::path;
#[derive(Debug, Default)]
pub struct Device {
/// If the device is halted.
pub halted: bool,
/// Loaded instructions.
pub instructions: Vec<Instruction>,
pub registers: Registers,
/// Count of number of instructions that has been executed.
pub count: usize,
/// Unique instructions that has been run.
pub unique: HashSet<usize>,
}
impl Device {
/// Load a program from the specified path.
pub fn load_path(&mut self, path: impl AsRef<path::Path>) -> Result<(), Error> {
use std::{fs::File, io::Read};
let mut f = File::open(path.as_ref())?;
let mut input = String::new();
f.read_to_string(&mut input)?;
self.load(input.lines())
}
/// Load a program.
pub fn load<'a>(&mut self, input: impl Iterator<Item = &'a str>) -> Result<(), Error> {
self.reset();
self.instructions.clear();
for line in input {
if line.starts_with("#ip") {
let ip = line
.split(" ")
.nth(1)
.ok_or_else(|| format_err!("expected argument to `#ip`"))
.and_then(|arg| {
str::parse(arg).map_err(|e| format_err!("bad argument to `#ip`: {}", e))
})?;
self.registers.ip = ip;
continue;
}
let inst = match Instruction::decode(line) {
Some(inst) => inst,
None => {
bail!("bad instruction: {}", line);
}
};
self.instructions.push(inst);
}
Ok(())
}
pub fn step(&mut self) -> Result<(), Error> {
let Device {
ref instructions,
ref mut registers,
..
} = *self;
let ip = registers.ip()?;
let inst = match instructions.get(ip) {
Some(inst) => inst,
None => {
self.halted = true;
return Ok(());
}
};
registers.last_ip = Some(registers.ip()?);
inst.op_code.apply(registers, &inst.inputs, inst.output)?;
*registers.ip_mut()? += 1;
self.unique.insert(ip);
self.count += 1;
Ok(())
}
/// Clear all temporary state for the device.
///
/// Temporary state keeps track of things that has been modified.
pub fn clear(&mut self) {
self.registers.clear();
}
pub fn reset(&mut self) {
self.halted = false;
self.count = 0;
self.unique.clear();
self.registers.reset();
}
}
|
use super::widget::Widget;
use std::borrow::Cow;
use tui::{
backend::CrosstermBackend,
layout::{Alignment, Rect},
widgets::{Block, Borders, Paragraph, Text},
Frame,
};
/// A widget showing the current status of the emulator (running, ...)
pub struct Status {
status: &'static str,
}
impl Status {
pub fn new() -> Self {
Self { status: "Idle" }
}
pub fn set_status(&mut self, status: &'static str) {
self.status = status;
}
}
impl Widget for Status {
fn refresh(&mut self, _: &crate::cpu::CPU) {}
fn draw(
&mut self,
f: &mut Frame<CrosstermBackend<std::io::Stdout>>,
chunk: Rect,
_: &crate::cpu::CPU,
) {
let text = &[Text::Raw(Cow::Borrowed(self.status))];
let paragraph = Paragraph::new(text.iter())
.block(Block::default().borders(Borders::NONE))
.alignment(Alignment::Right);
f.render_widget(paragraph, chunk);
}
fn select(&mut self) {}
fn deselect(&mut self) {}
fn is_selected(&self) -> bool {
false
}
}
|
use core::fmt;
use std::{collections::HashSet, cmp::{min, max}};
fn main() {
let mut input = include_str!("input").split("\r\n\r\n");
let mut paper: Paper = input.next().unwrap().parse().unwrap();
let mut folds = input.next().unwrap().lines().map(|s| {
let line = s.split(" ").last().unwrap();
let mut split = line.split("=");
(split.next().unwrap(), split.next().unwrap().parse::<i32>().unwrap())
});
paper.fold(folds.next().unwrap());
println!("Part one: {}", paper.count_dots());
for line in folds { paper.fold(line); }
println!("Part two: \n {}", paper);
}
struct Paper(HashSet<(i32, i32)>);
impl Paper {
fn count_dots(&self) -> usize {
self.0.len()
}
fn fold(&mut self, line: (&str, i32)) {
// How to make into_iter() work here
self.0 = self.0.iter().map(|(x,y)| {
match line.0 {
"x" => (fold(*x, line.1), *y),
"y" => (*x, fold(*y, line.1)),
_ => panic!("dfasda")
}
}).collect();
}
}
impl fmt::Display for Paper {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (min_x, max_x, min_y, max_y) = self.0.iter().fold((i32::MAX, i32::MIN, i32::MAX, i32::MIN), |acc, coor| {
(min(coor.0, acc.0), max(coor.0, acc.1), min(coor.1, acc.2), max(coor.1, acc.3))
});
let mut display = vec![vec![" "; (max_x - min_x) as usize + 1]; (max_y - min_y) as usize + 1];
for (x, y) in self.0.iter() {
display[(y - min_y) as usize][(x - min_x) as usize] = "#";
}
write!(f, "{}", display.into_iter().map(|s| s.join("")).collect::<Vec<_>>().join("\n"))
}
}
impl std::str::FromStr for Paper {
type Err = &'static str;
fn from_str<'a>(s: &'a str) -> Result<Self, Self::Err> {
Ok(Self(s.lines().map(|s| {
let mut split = s.split(",");
(split.next().unwrap().parse::<i32>().unwrap(), split.next().unwrap().parse::<i32>().unwrap())
}).collect()))
}
}
fn fold(position: i32, line: i32) -> i32 {
if position > line { return 2*line - position; }
position
} |
/*
Utility functions
Warning: some of these functions are Linux-specific.
*/
use chrono::offset::Local;
use nix::sys::wait::{waitpid, WaitStatus};
use nix::unistd::{fork, ForkResult};
use rand::Rng;
use std::boxed::Box;
use std::fmt::Debug;
use std::fs::{File, OpenOptions};
use std::io::{self, prelude::*, BufReader, Result};
use std::process::exit;
use std::str::FromStr;
use std::string::String;
use std::thread;
use std::time::{Duration, SystemTime};
/*
Related to time
*/
pub fn time_since(t: SystemTime) -> Duration {
// Note: this function may panic in case of clock drift
t.elapsed().unwrap()
}
pub fn div_durations(d1: Duration, d2: Duration) -> u128 {
((d1.as_nanos() as f64) / (d2.as_nanos() as f64)) as u128
}
pub fn nanos_timestamp(t: SystemTime) -> u128 {
// Note: this function may panic in case of clock drift
t.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_nanos()
}
pub fn current_datetime_str() -> String {
let out = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
println!("Current Datetime: {:?}", out);
out
}
pub fn sleep_for_secs(s: u64) {
thread::sleep(Duration::from_secs(s));
}
/*
For stdin input
*/
pub fn get_input<T>(msg: &str) -> T
where
T: FromStr,
<T as FromStr>::Err: Debug,
{
println!("{}", msg);
let mut input_text = String::new();
io::stdin().read_line(&mut input_text).expect("failed to read from stdin");
input_text.trim().parse::<T>().expect("not an integer")
}
/*
File handling
*/
// pub fn vec_to_file<T>(v: Vec<T>, filename: &str)
// where
// T: std::fmt::Debug,
// {
// // This function may panic due to multiple reasons
// let mut file =
// OpenOptions::new().create(true).write(true).open(filename).unwrap();
//
// for item in v {
// writeln!(file, "{:?}", item).unwrap();
// }
// }
// Run a closure for each line in a file
fn for_each_line_do<F>(filepath: &str, mut closure: F) -> Result<()>
where
F: FnMut(usize, &str) -> Result<()>, // line number, line
{
let file = File::open(filepath)?;
let reader = BufReader::new(file);
for (line_number, line) in reader.lines().enumerate() {
closure(line_number, &line.unwrap())?;
}
Result::Ok(())
}
// From a file create a new one where each line is replaced using a given function
pub fn replace_lines_in_file<F>(
in_filepath: &str,
out_filepath: &str,
closure: F,
) -> Result<()>
where
F: Fn(usize, &str) -> String,
{
let mut out_file =
OpenOptions::new().create(true).write(true).open(out_filepath)?;
for_each_line_do(in_filepath, move |line_number, line| {
writeln!(out_file, "{}", closure(line_number, line))
})
}
// Find a line in filepath equal to text and return the line number.
// Otherwise, return an error.
// Warning: line numbering starts from 0!
pub fn match_line_in_file(text: &str, filepath: &str) -> Result<usize> {
let file = File::open(filepath)?;
let reader = BufReader::new(file);
for (line_number, line) in reader.lines().enumerate() {
if line.unwrap() == text {
return Result::Ok(line_number);
}
}
Result::Err(io::Error::new(
io::ErrorKind::Other,
format!("text {} not found in file {}", text, filepath),
))
}
pub fn first_line_in_file(filepath: &str) -> String {
let file = File::open(filepath).unwrap_or_else(|err| {
panic!("couldn't open file {}: {}", filepath, err);
});
let reader = BufReader::new(file);
let line = reader.lines().next().unwrap_or_else(|| {
panic!("couldn't get line bc the file had no lines? {}", filepath);
});
line.unwrap_or_else(|err| {
panic!("getting first line in file failed: {}! {}", filepath, err);
})
}
/*
String manipulation
*/
// Very bad function -- leaks the string memory :)
// Only use for e.g. command line arguments where it won't happen repeatedly.
pub fn string_to_static_str(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
/*
Random number generation
*/
pub fn rand_range(a: u64, b: u64) -> u64 {
rand::thread_rng().gen_range(a, b)
}
pub fn rand_bool(p: f64) -> bool {
rand::thread_rng().gen::<f64>() < p
}
/*
Process management
*/
// Run a function as a separate process.
// If it crashes or is terminated, finish gracefully.
// This function may panic if the system calls fail or the process
// has an unexpected result (e.g. stopped, continued, nonzero exit code).
pub fn run_as_process<Out, F: FnOnce() -> Out>(func: F) {
match unsafe { fork() } {
Ok(ForkResult::Parent { child, .. }) => {
println!("[parent] running in subprocess PID: {}", child);
match waitpid(child, None) {
Ok(WaitStatus::Exited(pid, code)) => {
debug_assert!(child == pid);
if code != 0 {
println!("[parent] non-zero exit code! {}", code);
}
}
Ok(WaitStatus::Signaled(pid, signal, code)) => {
debug_assert!(child == pid);
println!(
"[parent] process killed! signal {}, exit code {}",
signal, code
);
}
Ok(status) => panic!(
"[parent] Error: unexpected child process status! {:?}",
status
),
Err(err) => panic!("[parent] Error: waitpid failed! {}", err),
}
}
Ok(ForkResult::Child) => {
// println!("[child] starting");
func();
// println!("[child] exiting");
exit(0)
}
Err(err) => panic!("[parent] Error: fork failed! {}", err),
}
}
|
use enigo::*;
use rand::*;
use std::thread::sleep;
use std::time::Duration;
fn main() {
let mut enigo = Enigo::new();
loop {
let mut rng = rand::thread_rng();
let random_time = rng.gen_range(0, 20);
let x = rng.gen_range(300, 2200);
let y = rng.gen_range(150, 1400);
sleep(Duration::new(random_time, 0));
enigo.mouse_move_to(x, y);
let random_time = rng.gen_range(0, 10);
let x = rng.gen_range(300, 2200);
let y = rng.gen_range(150, 1400);
sleep(Duration::new(random_time, 0));
enigo.mouse_move_to(x, y);
}
}
|
use std::cmp;
use std::fmt;
use super::*;
use super::pop_count_sum;
#[inline]
fn upper_block_len(n: usize) -> usize {
(n / (64 << 20)) + 1
}
#[inline]
fn lower_block_len(n: usize) -> usize {
(n / (4 * 8)) + 1
}
#[inline]
fn to_lower_elem(l1: u64, u0: u64, u1: u64, u2: u64) -> u64 {
let l2_0 = u0 << 32;
let l2_1 = u1 << 42;
let l2_2 = u2 << 52;
l1 | l2_0 | l2_1 | l2_2
}
#[inline]
fn from_lower_elem(u: u64) -> (u64, u64, u64, u64) {
let l1 = from_lower_l1(u);
let (l2_0, l2_1, l2_2) = from_lower_l2(u);
(l1, l2_0, l2_1, l2_2)
}
#[inline]
fn from_lower_l1(u: u64) -> u64 {
u & 0b_1111111111111111_1111111111111111
}
#[inline]
fn from_lower_l2(u: u64) -> (u64, u64, u64) {
((u & (0b_1111111111 << 32)) >> 32,
(u & (0b_1111111111 << 42)) >> 42,
(u & (0b_1111111111 << 52)) >> 52)
}
// TODO: sample index
pub struct Poppy<T: BitWise> {
pub packed_bits: Vec<T>,
// Lookup in this index is independent of the lookup in the L1L2 index,
// so operations can be issued in parallel.
// Index 0: cumulative absolute counts
upper_block: Vec<u64>,
// Storing the Index1-Index2 entries in an interleaved form
// ==> one cache miss to access L1 + L2
// ( 2 bits (padding)
// , 10 bits (L2_2)
// , 10 bits (L2_1)
// , 10 bits (L2_0)
// , 32 bits (L1)
// ) = 64bits
// Index 1: cumulative relative counts
// Index 2: non-cumulative relative counts
lower_block: Vec<u64>,
pop_counted: u64,
}
impl fmt::Debug for Poppy<u64> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let lbs = &self.lower_block;
write!(f,
"Poppy({}) {:?}\n{:?}\n...\n{:?}",
self.pop_count(),
self.upper_block,
(&lbs[..])
.iter()
.take(3)
.map(|&u| from_lower_elem(u))
.collect::<Vec<(u64, u64, u64, u64)>>(),
(&lbs[..])
.iter()
.skip(lbs.len().checked_sub(0).unwrap_or(0))
.map(|&u| from_lower_elem(u))
.collect::<Vec<(u64, u64, u64, u64)>>())
}
}
impl Poppy<u64> {
pub fn from_bits(packed: &[u64]) -> Self {
let packed_len = packed.len();
let mut ubs = vec![0; upper_block_len(packed_len)];
let mut lbs = vec![0; lower_block_len(packed_len)];
let pop_count_block = |i| {
if i >= packed_len {
0
} else {
pop_count_sum(&packed[i..cmp::min((i + 8), packed_len)])
}
};
let mut idx = 0;
let mut acc = 0;
let mut pre = 0;
loop {
if idx > packed_len {
break;
}
let q0 = idx / (64 << 20);
let r0 = idx % (64 << 20);
let q1 = idx / 32;
let n = if r0 == 0 {
ubs[q0] = acc;
acc
} else {
pre
};
let l1 = acc - n;
let l2_0 = pop_count_block(idx + 8 * 0);
let l2_1 = pop_count_block(idx + 8 * 1);
let l2_2 = pop_count_block(idx + 8 * 2);
let l2_3 = pop_count_block(idx + 8 * 3);
let l1l2 = to_lower_elem(l1, l2_0, l2_1, l2_2);
lbs[q1] = l1l2;
idx += 8 * 4;
acc += l2_0 + l2_1 + l2_2 + l2_3;
pre = n;
}
Poppy {
packed_bits: packed.to_vec(),
upper_block: ubs,
lower_block: lbs,
pop_counted: acc,
}
}
}
impl Access<Bit> for Poppy<u64> {
fn size(&self) -> usize {
self.packed_bits.len() * 64
}
fn get(&self, i: usize) -> Option<Bit> {
let q = i / 64;
let r = i % 64;
self.packed_bits
.get(q)
.and_then(|b| b.get(r))
}
}
impl PopCount for Poppy<u64> {
fn pop_count(&self) -> usize {
self.pop_counted as usize
}
}
impl BitRank for Poppy<u64> {
fn rank1(&self, ix: usize) -> usize {
debug_assert!(ix <= self.size());
let rank_upper = self.upper_block
.get(ix / (64 << 26))
.unwrap();
let q1 = ix / 2048;
let r1 = ix % 2048;
let q2 = r1 / 512;
let r2 = r1 % 512;
let l1l2 = self.lower_block.get(q1).unwrap();
let rank_accum = from_lower_l1(l1l2);
let (c1, c2, c3) = from_lower_l2(l1l2);
let rank_lower = match q2 {
0 => 0,
1 => c1,
2 => c1 + c2,
_ => c1 + c2 + c3,
};
let rank_slice = {
let bits = q1 * 2048 + q2 * 512;
let skip = bits / 64;
let q3 = r2 / 64;
let r3 = r2 % 64;
let rank_word = match r2 {
0 => None,
_ => {
self.packed_bits
.get(skip + q3)
.map(|w| w.rank1(r3))
}
};
let sum = pop_count_sum(&self.packed_bits[skip..(skip + q3)]);
let cnt = rank_word.unwrap_or(0) as u64;
sum + cnt
};
(rank_upper + rank_accum + rank_lower + rank_slice) as usize
}
}
impl BitSelect1 for Poppy<u64> {
fn select1(&self, c: usize) -> usize {
debug_assert!(c < self.pop_count());
let ublen = self.upper_block.len();
let lblen = self.lower_block.len();
let c0 = c as u64;
let (ub_idx, l0) = self.upper_block
.search_value(0, ublen, |v| c0 < v);
let c1 = c0 - l0;
let (lb_idx, (l1, l2_0, l2_1, l2_2)) = {
let step = (64 << 20) / 32;
let skip = ub_idx * step;
let min_idx = cmp::min(skip, lblen - 1);
let max_idx = cmp::min(min_idx + step, lblen);
let (ix, l1l2) = {
self.lower_block
.search_value(min_idx, max_idx, |v| c1 < from_lower_l1(v))
};
(ix, from_lower_elem(l1l2))
};
let c2 = c1 - l1;
let (bb_idx, c3) =
(|| {
if c2 < l2_0 {
return (0, c2);
}
let c3_0 = c2 - l2_0;
if c3_0 < l2_1 {
return (1, c3_0);
}
let c3_1 = c3_0 - l2_1;
if c3_1 < l2_2 {
return (2, c3_1);
}
let c3_2 = c3_1 - l2_2;
return (3, c3_2);
})();
let (word, bits) =
(|| {
let mi = lb_idx * 32 + bb_idx * 8;
let to = cmp::min(mi + 8, self.packed_bits.len());
let mut idx = 0;
let mut sel = 0;
let mut rem = c3 as usize;
for (i, &u) in (&self.packed_bits[mi..to]).iter().enumerate() {
let p = u.pop_count();
if rem < p {
idx = i;
sel = u.select1(rem);
break;
}
rem -= p;
}
return (idx, sel);
})();
lb_idx * 2048 + bb_idx * 512 + word * 64 + bits
}
}
|
use fraction::ToPrimitive;
use crate::io::*;
pub const DURATION_QUARTER_TIME: i64 = 960;
//pub const DURATION_WHOLE: u8 = 1;
//pub const DURATION_HALF: u8 = 2;
pub const DURATION_QUARTER: u8 = 4;
pub const DURATION_EIGHTH: u8 = 8;
pub const DURATION_SIXTEENTH: u8 = 16;
pub const DURATION_THIRTY_SECOND: u8 = 32;
pub const DURATION_SIXTY_FOURTH: u8 = 64;
pub const DURATION_HUNDRED_TWENTY_EIGHTH: u8 = 128;
/// A time signature
#[derive(Debug,Clone, PartialEq,Eq)]
pub struct TimeSignature {
pub numerator: i8,
pub denominator: Duration,
pub beams: Vec<u8>,
}
impl Default for TimeSignature {
fn default() -> Self { TimeSignature { numerator: 4, denominator:Duration::default(), beams: vec![2,2,2,2]}}
}
pub const KEY_SIGNATURES: [&str; 34] = ["F♭ major", "C♭ major", "G♭ major", "D♭ major", "A♭ major", "E♭ major", "B♭ major",
"F major", "C major", "G major", "D major", "A major", "E major", "B major",
"F# major", "C# major", "G# major",
"D♭ minor", "A♭ minor", "E♭ minor", "B♭ minor",
"F minor", "C minor", "G minor", "D minor", "A minor", "E minor", "B minor",
"F# minor", "C# minor", "G# minor", "D# minor", "A# minor", "E# minor"];
#[derive(Debug,Clone,Default,PartialEq,Eq)]
pub struct KeySignature {
pub key: i8,
pub is_minor: bool,
}
//impl Default for KeySignature { fn default() -> Self { KeySignature { key: 0, is_minor: false, }} }
impl std::fmt::Display for KeySignature {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let index: usize = if self.is_minor {(23i8 + self.key).to_usize().unwrap()} else {(8i8 + self.key).to_usize().unwrap()};
write!(f, "{}", KEY_SIGNATURES[index])
}
}
const SUPPORTED_TUPLETS: [(u8, u8); 10] = [(1,1), (3,2), (5,4), (6,4), (7,4), (9,8), (10,8), (11,8), (12,8), (13,8)];
#[derive(Debug,Clone,PartialEq,Eq)]
pub struct Duration {
pub value:u16,
pub dotted: bool,
pub double_dotted:bool,
/// The time resulting with a 64th note and a 3/2 tuplet
pub min_time: u8,
//Tuplet division type
pub tuplet_enters:u8, pub tuplet_times:u8
}
impl Default for Duration {
fn default() -> Self { Duration {
value: DURATION_QUARTER.to_u16().unwrap(), dotted: false, double_dotted: false,
tuplet_enters:1, tuplet_times:1,
min_time: 0
}}
}
impl Duration {
//fn convert_time(&self, time: u64) -> u64 { time * self.division_times as u64 / self.division_enters as u64 }
pub(crate) fn is_supported(&self) -> bool { SUPPORTED_TUPLETS.contains(&(self.tuplet_enters, self.tuplet_times))}
pub(crate) fn convert_time(&self, time: u32) -> u32 {
let result = fraction::Fraction::new(time * self.tuplet_enters.to_u32().unwrap(), self.tuplet_times.to_u32().unwrap());
if *result.denom().unwrap() == 1 {(*result.numer().unwrap()).to_u32().unwrap()}
else {result.trunc().to_u32().unwrap()}
}
pub(crate) fn time(&self) -> u32 {
let mut result = (f64::from(DURATION_QUARTER_TIME.to_i32().unwrap()) * 4f64 / f64::from(self.value)).trunc();
//println!("\tDuration.time(): result: {}", result);
if self.dotted { result += (result/2f64).trunc(); }
//if self.dotted { result += (result/4f64).trunc() * 3f64; }
//println!("\tDuration.time(): result: {}", result);
self.convert_time(result.to_u32().unwrap())
}
pub(crate) fn _index(&self) -> u8 {
let mut index = 0u8;
let mut value = self.value;
loop {
value >>= 1;
if value > 0 {index += 1;}
else {break;}
}
index
}
pub(crate) fn is_default_tuplet(&self) -> bool { self.tuplet_times == 1 && self.tuplet_enters == 1}
//@classmethod def fromFraction(cls, frac): return cls(frac.denominator, frac.numerator)
pub(crate) fn write_duration(&self, data: &mut Vec<u8>, flags: u8) {
let value = (16 - self.value.leading_zeros()).to_i8().unwrap() - 3; //value = duration.value.bit_length() - 3
write_signed_byte(data, value);
if (flags & 0x20) == 0x20 {
if !self.is_supported() {return;}
write_i32(data, self.tuplet_enters.to_i32().unwrap()); //write iTuplet
}
}
}
/// Read beat duration.
/// Duration is composed of byte signifying duration and an integer that maps to `Tuplet`. The byte maps to following values:
///
/// * *-2*: whole note
/// * *-1*: half note
/// * *0*: quarter note
/// * *1*: eighth note
/// * *2*: sixteenth note
/// * *3*: thirty-second note
///
/// If flag at *0x20* is true, the tuplet is read
pub(crate) fn read_duration(data: &[u8], seek: &mut usize, flags: u8) -> Duration {
//println!("read_duration()");
let mut d = Duration{value: 1 << (read_signed_byte(data, seek) + 2), ..Default::default()};
//let b = read_signed_byte(data, seek); println!("B: {}", b); d.value = 1 << (b + 2);
d.dotted = (flags & 0x01) == 0x01;
if (flags & 0x20) == 0x20 {
let i_tuplet = read_int(data, seek);
if i_tuplet == 3 {d.tuplet_enters = 3; d.tuplet_times = 2;}
else if i_tuplet == 5 {d.tuplet_enters = 5; d.tuplet_times = 4;}
else if i_tuplet == 6 {d.tuplet_enters = 6; d.tuplet_times = 4;}
else if i_tuplet == 7 {d.tuplet_enters = 7; d.tuplet_times = 4;}
else if i_tuplet == 9 {d.tuplet_enters = 9; d.tuplet_times = 8;}
else if i_tuplet == 10 {d.tuplet_enters = 10; d.tuplet_times = 8;}
else if i_tuplet == 11 {d.tuplet_enters = 11; d.tuplet_times = 8;}
else if i_tuplet == 12 {d.tuplet_enters = 12; d.tuplet_times = 8;}
else if i_tuplet == 13 {d.tuplet_enters = 13; d.tuplet_times = 8;}
}
d
}
/*/// A *n:m* tuplet.
#[derive(Clone)]
struct Tuplet {
enters: u8,
times: u8,
}*/
/*impl Default for Tuplet { fn default() -> Self { Tuplet { enters: 1, times: 1 }}}
impl Tuplet {
fn is_supported(self) -> bool { SUPPORTED_TUPLETS.contains(&(self.enters, self.times)) }
fn convert_time(self) -> u8 {
let result = fraction::Fraction::new(self.enters, self.times);
if result.denom().expect("Cannot get fraction denominator") == &1 {1}
else {result.to_u8().expect("Cannot get fraction result")}
}
}*/
/* Enum ?: const KEY_F_MAJOR_FLAT: (i8, bool) = (-8, false);
const KEY_C_MAJOR_FLAT: (i8, bool) = (-7, false);
const KEY_G_MAJOR_FLAT: (i8, bool) = (-6, false);
const KEY_D_MAJOR_FLAT: (i8, bool) = (-5, false);
const KEY_A_MAJOR_FLAT: (i8, bool) = (-4, false);
const KEY_E_MAJOR_FLAT: (i8, bool) = (-3, false);
const KEY_B_MAJOR_FLAT: (i8, bool) = (-2, false);
const KEY_F_MAJOR: (i8, bool) = (-1, false);
const KEY_C_MAJOR: (i8, bool) = (0, false);
const KEY_G_MAJOR: (i8, bool) = (1, false);
const KEY_D_MAJOR: (i8, bool) = (2, false);
const KEY_A_MAJOR: (i8, bool) = (3, false);
const KEY_E_MAJOR: (i8, bool) = (4, false);
const KEY_B_MAJOR: (i8, bool) = (5, false);
const KEY_F_MAJOR_SHARP: (i8, bool) = (6, false);
const KEY_C_MAJOR_SHARP: (i8, bool) = (7, false);
const KEY_G_MAJOR_SHARP: (i8, bool) = (8, false);
const KEY_D_MINOR_FLAT: (i8, bool) = (-8, true);
const KEY_A_MINOR_FLAT: (i8, bool) = (-7, true);
const KEY_E_MINOR_FLAT: (i8, bool) = (-6, true);
const KEY_B_MINOR_FLAT: (i8, bool) = (-5, true);
const KEY_F_MINOR: (i8, bool) = (-4, true);
const KEY_C_MINOR: (i8, bool) = (-3, true);
const KEY_G_MINOR: (i8, bool) = (-2, true);
const KEY_D_MINOR: (i8, bool) = (-1, true);
const KEY_A_MINOR: (i8, bool) = (0, true);
const KEY_E_MINOR: (i8, bool) = (1, true);
const KEY_B_MINOR: (i8, bool) = (2, true);
const KEY_F_MINOR_SHARP: (i8, bool) = (3, true);
const KEY_C_MINOR_SHARP: (i8, bool) = (4, true);
const KEY_G_MINOR_SHARP: (i8, bool) = (5, true);
const KEY_D_MINOR_SHARP: (i8, bool) = (6, true);
const KEY_A_MINOR_SHARP: (i8, bool) = (7, true);
const KEY_E_MINOR_SHARP: (i8, bool) = (8, true);*/
|
mod camera;
mod hittable;
mod ray;
mod aabb;
mod bvh;
pub mod materials;
pub mod models;
pub mod textures;
pub use camera::Camera;
pub use hittable::HitRecord;
pub use hittable::Hittable;
pub use ray::Ray;
pub use aabb::Aabb;
pub use bvh::Bvh;
|
mod othermain;
fn main() {
println!("0xff")
} |
// 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::rc::Rc;
use common_exception::Result;
use crate::optimizer::cascades::tasks::SharedCounter;
use crate::optimizer::cascades::CascadesOptimizer;
use crate::optimizer::rule::TransformResult;
use crate::optimizer::RuleFactory;
use crate::optimizer::RuleID;
use crate::IndexType;
#[derive(Debug)]
pub struct ApplyRuleTask {
pub rule_id: RuleID,
pub target_group_index: IndexType,
pub m_expr_index: IndexType,
pub parent: Option<Rc<SharedCounter>>,
}
impl ApplyRuleTask {
pub fn new(rule_id: RuleID, target_group_index: IndexType, m_expr_index: IndexType) -> Self {
Self {
rule_id,
target_group_index,
m_expr_index,
parent: None,
}
}
pub fn with_parent(
rule_id: RuleID,
target_group_index: IndexType,
m_expr_index: IndexType,
parent: &Rc<SharedCounter>,
) -> Self {
let mut task = Self::new(rule_id, target_group_index, m_expr_index);
parent.inc();
task.parent = Some(parent.clone());
task
}
pub fn execute(self, optimizer: &mut CascadesOptimizer) -> Result<()> {
let group = optimizer.memo.group(self.target_group_index)?;
let m_expr = group.m_expr(self.m_expr_index)?;
let mut state = TransformResult::new();
let rule = RuleFactory::create_rule(self.rule_id, optimizer.metadata.clone())?;
m_expr.apply_rule(&optimizer.memo, &rule, &mut state)?;
optimizer.insert_from_transform_state(self.target_group_index, state)?;
if let Some(parent) = self.parent {
parent.dec();
}
Ok(())
}
}
|
// 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.
/// Registration.
///
/// An implementor of this 'wires together' an application that uses event poll.
pub trait Registration: Sized + Send + Sync + ArenasRegistration + ReactorsRegistration + MessageHandlersRegistration<MessageHandlerArguments=AdaptedReactorsRegistrar, E=String, Arguments=AdaptedReactorsRegistrar> + 'static
{
}
|
pub mod decisiondatafetcher;
|
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkSparseImageFormatProperties2KHR {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub properties: VkSparseImageFormatProperties,
}
impl VkSparseImageFormatProperties2KHR {
pub fn new(properties: VkSparseImageFormatProperties) -> Self {
VkSparseImageFormatProperties2KHR {
sType: VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2_KHR,
pNext: ptr::null(),
properties,
}
}
}
|
use std::{iter::Cycle, vec::IntoIter};
use amethyst::{
assets::{AssetStorage, Loader},
audio::{output::Output, OggFormat, Source, SourceHandle},
prelude::WorldExt,
shred::World,
};
use crate::settings::{BOUNCE_SFX, MUSIC_TRACKS, SCORE_SFX};
pub struct Sounds {
pub score_sfx: SourceHandle,
pub bounce_sfx: SourceHandle,
}
pub struct Music {
pub tracks: Cycle<IntoIter<SourceHandle>>,
}
// Loads an audio asset file and returns a handle (fd) to it.
fn load_audio_file(sound_file_path: &str, asset_loader: &Loader, world: &World) -> SourceHandle {
let storage = world.read_resource();
asset_loader.load(sound_file_path, OggFormat, (), &storage)
}
// Adds the Sounds and Music resources to the World entity which can be fetched later.
pub fn initialize_audio(world: &mut World) {
let (sounds, music) = {
// immutable borrow ends in this block scope
let asset_loader = world.read_resource::<Loader>();
let sounds = Sounds {
score_sfx: load_audio_file(SCORE_SFX, &asset_loader, world),
bounce_sfx: load_audio_file(BOUNCE_SFX, &asset_loader, world),
};
// load each file track from the MUSIC_TRACKS str slice
let music_tracks = MUSIC_TRACKS
.iter()
.map(|track_file| load_audio_file(track_file, &asset_loader, world))
.collect::<Vec<_>>()
.into_iter()
.cycle();
let music = Music {
tracks: music_tracks,
};
(sounds, music)
};
world.insert(sounds);
world.insert(music);
}
// Plays the bounce sfx.
pub fn play_bounce_sfx(
sounds: &Sounds,
asset_storage: &AssetStorage<Source>,
output: Option<&Output>,
) {
if let Some(ref output) = output.as_ref() {
if let Some(sfx) = asset_storage.get(&sounds.bounce_sfx) {
output.play_once(sfx, 1.0);
}
}
}
|
use rusoto_s3::S3Client;
use crate::s3::S3Filesystem;
#[derive(Default)]
pub struct S3FilesystemBuilder {
bucket: Option<String>,
client: Option<S3Client>,
prefix: Option<String>,
acl: Option<String>,
cache_control: Option<String>,
content_type: Option<String>,
}
impl S3FilesystemBuilder {
pub fn new() -> Self {
Self {
..Default::default()
}
}
pub fn with_bucket(mut self, value: String) -> S3FilesystemBuilder {
self.bucket = Some(value);
self
}
pub fn with_s3_client(mut self, value: S3Client) -> S3FilesystemBuilder {
self.client = Some(value);
self
}
pub fn with_prefix(mut self, value: String) -> S3FilesystemBuilder {
self.prefix = Some(value);
self
}
pub fn with_acl(mut self, value: String) -> S3FilesystemBuilder {
self.acl = Some(value);
self
}
pub fn with_cache_control(mut self, value: String) -> S3FilesystemBuilder {
self.cache_control = Some(value);
self
}
pub fn with_content_type(mut self, value: String) -> S3FilesystemBuilder {
self.content_type = Some(value);
self
}
pub fn into_boxed(self) -> Box<S3Filesystem> {
Box::new(self.into())
}
}
impl Into<S3Filesystem> for S3FilesystemBuilder {
fn into(self) -> S3Filesystem {
S3Filesystem::new(
self.bucket.unwrap(),
self.client.unwrap(),
self.prefix,
self.acl,
self.cache_control,
self.content_type,
)
}
}
|
#[cfg(feature = "codegen")]
mod tests {
use std::fmt::Debug;
use legion::{
storage::Component, system, systems::CommandBuffer, world::SubWorld, Entity, Schedule,
};
#[test]
fn empty() {
#[system(for_each)]
fn for_each(_: &Entity) {}
Schedule::builder().add_system(for_each_system()).build();
}
#[test]
fn with_resource() {
#[system(for_each)]
fn for_each(_: &Entity, #[resource] _: &usize) {}
Schedule::builder().add_system(for_each_system()).build();
}
#[test]
fn with_mut_resource() {
#[system(for_each)]
fn for_each(_: &Entity, #[resource] _: &mut usize) {}
Schedule::builder().add_system(for_each_system()).build();
}
#[test]
fn with_world() {
#[system(for_each)]
fn for_each(_: &Entity, _: &SubWorld) {}
Schedule::builder().add_system(for_each_system()).build();
}
#[test]
fn with_mut_world() {
#[system(for_each)]
fn for_each(_: &Entity, _: &mut SubWorld) {}
Schedule::builder().add_system(for_each_system()).build();
}
#[test]
fn with_cmd() {
#[system(for_each)]
fn for_each(_: &Entity, _: &CommandBuffer) {}
Schedule::builder().add_system(for_each_system()).build();
}
#[test]
fn with_mut_cmd() {
#[system(for_each)]
fn for_each(_: &Entity, _: &mut CommandBuffer) {}
Schedule::builder().add_system(for_each_system()).build();
}
#[test]
fn with_components() {
#[system(for_each)]
fn for_each(a: &f32, b: &mut usize) {
println!("{:?} {:?}", a, b);
}
Schedule::builder().add_system(for_each_system()).build();
}
#[test]
fn with_generics() {
#[system(for_each)]
fn for_each<T: Component + Debug>(t: &T) {
println!("{:?}", t);
}
Schedule::builder()
.add_system(for_each_system::<usize>())
.build();
}
}
|
use crate::ast;
use crate::{Spanned, ToTokens};
/// An index get operation `<target>[<index>]`.
#[derive(Debug, Clone, PartialEq, Eq, ToTokens, Spanned)]
pub struct ExprIndex {
/// Attributes associated with expression.
#[rune(iter)]
pub attributes: Vec<ast::Attribute>,
/// The target of the index set.
pub target: ast::Expr,
/// The opening bracket.
pub open: T!['['],
/// The indexing expression.
pub index: ast::Expr,
/// The closening bracket.
pub close: T![']'],
}
expr_parse!(Index, ExprIndex, "index expression");
|
use std::{env, process};
use getopts::Options;
pub use print_queue::queue;
pub use print_queue::user;
use user::create_uid_username_mapping;
/// Display usage information. Used for handling the "-h" or "--help" flags if passed, or if the Slack
/// API key was not given, as that is a _required_ command line argument.
fn usage(program: &str, opts: Options) {
let desc = format!(
"Queue \u{2014} a Slack bot to keep track of who is using a 3D \
printer\nUsage:\n\t{} (-k api-KEY | --key API-KEY>) [-f FILE | --file FILE] [-h | --help]",
program
);
print!("{}", opts.usage(&desc));
}
/// Entry point for the Slack bot.
fn main() -> Result<(), slack::error::Error> {
let mut args = env::args();
let program = args
.next()
.expect("Program name was not passed to command line arguments");
let mut opts = Options::new();
opts.optopt("k", "key", "Slack bot API key", "API-KEY");
opts.optopt(
"f",
"file",
"name of the backup file to use; will be created if empty",
"FILE",
);
opts.optflag("h", "", "show a one-line usage summary");
opts.optflag("", "help", "display this help message and exit");
let matches = match opts.parse(args) {
Ok(m) => m,
Err(f) => {
eprintln!("{}", f.to_string());
usage(&program, opts);
process::exit(-3);
}
};
// Exit immediately if -h or --help is passed
if matches.opt_present("h") {
println!("{}", opts.short_usage(&program));
return Ok(());
} else if matches.opt_present("help") {
usage(&program, opts);
return Ok(());
}
let api_key = match matches.opt_str("key") {
Some(api_key) => api_key,
None => {
eprintln!("Required option \'key\' missing");
usage(&program, opts);
process::exit(-1);
}
};
let users = match create_uid_username_mapping(api_key.as_str()) {
Ok(u) => u,
Err(e) => {
eprintln!("{}", e);
process::exit(-2);
}
};
// Only run the following in debug (i.e. not release) mode
if cfg!(debug_assertions) {
println!("{:#?}", users);
println!("Number of members: {:?}", users.len());
}
let mut queue = match matches.opt_str("f") {
Some(file) => queue::Queue::from_file(&users, file),
None => queue::Queue::new(&users),
};
slack::RtmClient::login_and_run(&api_key, &mut queue)
}
|
use crate::{
math::{Size, Vector2},
widgets::{TypedWidget, Widget},
Backend,
};
pub mod click;
/// A Controller is a bit of logic that reacts to a specific Event type.
pub trait Controller<T, W: Widget<T>> {
type Event;
type Reaction;
fn event(
&mut self,
child: &mut W,
origin: Vector2,
size: Size,
data: &mut T,
event: Self::Event,
) -> Option<Self::Reaction>;
}
impl<T, W: Widget<T>, C: Controller<T, W>> Controller<T, W> for Box<C> {
type Event = C::Event;
type Reaction = C::Reaction;
fn event(
&mut self,
child: &mut W,
origin: Vector2,
size: Size,
data: &mut T,
event: Self::Event,
) -> Option<Self::Reaction> {
self.as_mut().event(child, origin, size, data, event)
}
}
pub trait TypedController<T, W: TypedWidget<T, B>, B: Backend>:
sealed::InnerTypedController<T, W, B>
{
fn event(
&mut self,
child: &mut W,
origin: Vector2,
size: Size,
data: &mut T,
event: B::Event,
) -> Option<B::EventReaction>;
}
impl<T, W: TypedWidget<T, B>, B: Backend, C> TypedController<T, W, B> for C
where
C: sealed::InnerTypedController<T, W, B>,
{
fn event(
&mut self,
child: &mut W,
origin: Vector2,
size: Size,
data: &mut T,
event: B::Event,
) -> Option<B::EventReaction> {
sealed::InnerTypedController::<T, W, B>::event(self, child, origin, size, data, event)
}
}
mod sealed {
use super::{Controller, TransformEvent};
use crate::{
math::{Size, Vector2},
widgets::{TypedWidget, Widget},
Backend,
};
pub trait InnerTypedController<T, W: TypedWidget<T, B>, B: Backend> {
fn event(
&mut self,
child: &mut W,
origin: Vector2,
size: Size,
data: &mut T,
event: B::Event,
) -> Option<B::EventReaction>;
}
impl<T, W: TypedWidget<T, B> + Widget<T>, B: Backend, C> InnerTypedController<T, W, B> for C
where
C: Controller<T, W>,
B::Event: TransformEvent<C::Event>,
B::EventReaction: From<C::Reaction>,
{
fn event(
&mut self,
child: &mut W,
origin: Vector2,
size: Size,
data: &mut T,
event: B::Event,
) -> Option<B::EventReaction> {
event.transform_event().and_then(|event| {
Controller::event(self, child, origin, size, data, event)
.map(|reaction| reaction.into())
})
}
}
}
pub trait TransformEvent<Event> {
fn transform_event(self) -> Option<Event>;
}
impl<T> TransformEvent<T> for T {
fn transform_event(self) -> Option<T> {
Some(self)
}
}
|
mod widgets;
extern crate regex;
extern crate simplelog;
extern crate crossterm;
use std::collections::HashMap;
use std::fs::File;
use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender};
use std::thread;
use simplelog::*;
use log::info;
use crate::runner::TaskRunner;
use crate::tasks::Layout;
use std::thread::JoinHandle;
use crate::crossterm_backend::CrossTermUiContext;
mod tasks;
mod executable_command;
mod runner;
mod crossterm_backend;
pub type TaskId = String;
pub struct Channel<T> {
pub tx: Sender<T>,
pub rx: Receiver<T>
}
impl<T> Channel<T> {
pub fn new(tx: Sender<T>, rx: Receiver<T>) -> Channel<T> {
Channel { tx, rx }
}
pub fn from(tuple: (Sender<T>, Receiver<T>)) -> Channel<T> {
Channel::new(tuple.0, tuple.1)
}
}
fn main() {
init_logging();
let config = tasks::load_task_config().unwrap();
let layout = config.layout;
let system_command_channel = Channel::from(mpsc::channel());
let task_running_channel = Channel::from(mpsc::channel());
let mut runner = TaskRunner::new(config.tasks, system_command_channel.tx.clone(), task_running_channel.rx);
thread::spawn( move || { runner.run(); });
launch_crossterm(layout,
system_command_channel.rx,
system_command_channel.tx,
task_running_channel.tx.clone()).join().unwrap_or({});
}
fn launch_crossterm(layout: Layout,
command_receiver: Receiver<HashMap<String, String>>,
command_sender: Sender<HashMap<String, String>>,
task_sender: Sender<String>) -> JoinHandle<()> {
thread::spawn(move || {
info!("Setting up crossterm!");
let mut ctx = CrossTermUiContext::new(layout, command_receiver, command_sender, task_sender);
ctx.run_ui_loop();
})
}
fn init_logging() {
CombinedLogger::init(
vec![
WriteLogger::new(LevelFilter::Info, Config::default(), File::create("log/flux.log").unwrap()),
]
).unwrap();
}
|
extern crate proc_macro;
extern crate syn;
#[macro_use] extern crate quote;
use proc_macro::TokenStream;
#[proc_macro_derive(AnnounceDrop)]
pub fn announce_drop(input: TokenStream) -> TokenStream {
let source = input.to_string();
let ast = syn::parse_derive_input(&source).unwrap();
let name = &ast.ident;
let call_name = name.to_string();
quote!(
impl Drop for #name {
fn drop(&mut self) {
println!("{} dropped", #call_name);
}
}
).parse().unwrap()
}
|
use std::fs::File;
use std::io::{self, prelude::*, BufReader};
use std::str::FromStr;
use std::num::ParseIntError;
use std::fs;
#[derive(Debug,PartialEq)]
enum Tile {
Tree,
Empty
}
#[derive(Debug)]
struct ForestMap {
tiles: Vec<Vec<Tile>>,
}
impl FromStr for ForestMap {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut tiles : Vec<Vec<Tile>> = Vec::new();
for line in s.lines(){
let mut line_vec : Vec<Tile> = Vec::new();
for c in line.chars(){
line_vec.push(
match c {
'#' => Tile::Tree,
'.' => Tile::Empty,
_ => unreachable!()
}
)
}
tiles.push(line_vec);
}
Ok(
ForestMap {
tiles
}
)
}
}
impl ForestMap {
fn iter(&self,slope_x:usize,slope_y:usize) -> ForestSlopeIterator {
ForestSlopeIterator {
map: self,
current_x:0,
current_y:0,
slope_x,
slope_y
}
}
}
struct ForestSlopeIterator<'a> {
map: &'a ForestMap,
current_x: usize,
current_y: usize,
slope_x: usize,
slope_y: usize
}
impl<'a> Iterator for ForestSlopeIterator<'a> {
type Item = &'a Tile;
fn next(&mut self) -> Option<&'a Tile> {
self.current_x += self.slope_x;
self.current_y += self.slope_y;
if self.current_y >= self.map.tiles.len() {
return None;
}
let row = &self.map.tiles[self.current_y];
let tile = &row[self.current_x % row.len()];
Some(tile)
}
}
fn main() -> io::Result<()> {
let map: ForestMap = ForestMap::from_str(&fs::read_to_string("input.txt")?).unwrap();
//Puzzle 1
// let tree_count: usize = map.iter(3, 1)
// .filter(|tile| tile == &&Tile::Tree )
// .count();
// println!("{:?}",tree_count);
//Ok(())
// puzzle 2
let slopes = vec![(1,1),(3,1),(5,1),(7,1),(1,2)];
let mut result = 1;
for slope in slopes {
let tree_count: usize = map.iter(slope.0, slope.1)
.filter(|tile| tile == &&Tile::Tree )
.count();
println!("{},{},{}",slope.0,slope.1,tree_count);
result *= tree_count;
}
println!("{}",result);
Ok(())
} |
use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Mutex;
use failure::Error;
use log::*;
use serde;
use crate::protocol::browser::methods::GetVersion;
pub use crate::protocol::browser::methods::VersionInformationReturnObject;
use crate::protocol::target::methods::{CreateTarget, SetDiscoverTargets};
use crate::protocol::{self, Event};
pub use process::LaunchOptionsBuilder;
use process::{LaunchOptions, Process};
use std::time::Duration;
pub use tab::Tab;
use transport::Transport;
use waiting_helpers::{wait_for, WaitOptions};
mod process;
pub mod tab;
mod transport;
mod waiting_helpers;
/// A handle to an instance of Chrome / Chromium, which wraps a WebSocket connection to its debugging port.
///
///
/// Most of your actual "driving" (e.g. clicking, typing, navigating) will be via instances of [Tab](../tab/struct.Tab.html), which are accessible via methods such as `get_tabs`.
///
/// With the default [LaunchOptions](../process/LaunchOptions.struct.html), your locally
/// installed copy of Chrome launches in headless mode. You can provide your own binary
/// by creating LaunchOptions with a custom `path` field.
///
/// ```rust
/// # use failure::Error;
/// # fn main() -> Result<(), Error> {
/// #
/// use headless_chrome::{Browser, LaunchOptionsBuilder};
/// let browser = Browser::new(LaunchOptionsBuilder::default().build().unwrap())?;
/// let first_tab = browser.wait_for_initial_tab()?;
/// assert_eq!("about:blank", first_tab.get_url());
/// #
/// # Ok(())
/// # }
/// ```
///
/// While the Chrome DevTools Protocl (CDTP) does define some methods in a
/// ["Browser" domain](https://chromedevtools.github.io/devtools-protocol/tot/Browser)
/// (such as for resizing the window in non-headless mode), we currently don't implement those.
pub struct Browser {
_process: Process,
transport: Arc<Transport>,
tabs: Arc<Mutex<Vec<Arc<Tab>>>>,
}
impl Browser {
/// Launch a new Chrome browser.
///
/// The browser will have its user data (aka "profile") directory stored in a temporary directory.
/// The browser process will be killed when this struct is dropped.
pub fn new(launch_options: LaunchOptions) -> Result<Self, Error> {
let process = Process::new(launch_options)?;
let transport = Arc::new(Transport::new(process.debug_ws_url.clone())?);
trace!("created transport");
let tabs = Arc::new(Mutex::new(vec![]));
let browser = Self {
_process: process,
tabs,
transport,
};
let incoming_events_rx = browser.transport.listen_to_browser_events();
browser.handle_browser_level_events(incoming_events_rx);
trace!("created browser event listener");
// so we get events like 'targetCreated' and 'targetDestroyed'
trace!("Calling set discover");
browser.call_method(SetDiscoverTargets { discover: true })?;
browser.wait_for_initial_tab()?;
Ok(browser)
}
/// The tabs are behind an `Arc` and `Mutex` because they're accessible from multiple threads
/// (including the one that handles incoming protocol events about new or changed tabs).
pub fn get_tabs(&self) -> Arc<Mutex<Vec<Arc<Tab>>>> {
Arc::clone(&self.tabs)
}
/// Chrome always launches with at least one tab. The reason we have to 'wait' is because information
/// about that tab isn't available *immediately* after starting the process. Tabs are behind `Arc`s
/// because they each have their own thread which handles events and method responses directed to them.
pub fn wait_for_initial_tab(&self) -> Result<Arc<Tab>, Error> {
wait_for(
|| self.tabs.lock().unwrap().first().map(|tab| Arc::clone(tab)),
WaitOptions {
timeout_ms: 5000,
sleep_ms: 10,
},
)
}
/// Create a new tab and return a handle to it.
///
/// ```rust
/// # use failure::Error;
/// # fn main() -> Result<(), Error> {
/// #
/// # use headless_chrome::{Browser, LaunchOptionsBuilder};
/// # let browser = Browser::new(LaunchOptionsBuilder::default().build().unwrap())?;
/// let first_tab = browser.wait_for_initial_tab()?;
/// let new_tab = browser.new_tab()?;
/// let num_tabs = browser.get_tabs().lock().unwrap().len();
/// assert_eq!(2, num_tabs);
/// #
/// # Ok(())
/// # }
/// ```
///
/// Currently does not support creating the tab in a new "browser context", aka an incognito
/// window.
pub fn new_tab(&self) -> Result<Arc<Tab>, Error> {
let create_target = CreateTarget {
url: "about:blank",
width: None,
height: None,
browser_context_id: None,
enable_begin_frame_control: None,
};
let target_id = self.call_method(create_target)?.target_id;
wait_for(
|| {
let tabs = self.tabs.lock().unwrap();
tabs.iter()
.find(|tab| *tab.get_target_id() == target_id)
.map(|tab_ref| Arc::clone(tab_ref))
},
WaitOptions {
timeout_ms: 5000,
sleep_ms: 10,
},
)
}
/// Get version information
///
/// ```rust
/// # use failure::Error;
/// # fn main() -> Result<(), Error> {
/// #
/// # use headless_chrome::{Browser, LaunchOptionsBuilder};
/// # let browser = Browser::new(LaunchOptionsBuilder::default().build().unwrap())?;
/// let version_info = browser.get_version()?;
/// println!("User-Agent is `{}`", version_info.user_agent);
/// #
/// # Ok(())
/// # }
/// ```
pub fn get_version(&self) -> Result<VersionInformationReturnObject, Error> {
self.call_method(GetVersion {})
}
fn handle_browser_level_events(&self, events_rx: mpsc::Receiver<Event>) {
let tabs = Arc::clone(&self.tabs);
let transport = Arc::clone(&self.transport);
std::thread::spawn(move || {
trace!("Starting browser's event handling loop");
loop {
match events_rx.recv_timeout(Duration::from_millis(20_000)) {
Err(_) => {
break;
}
Ok(event) => {
match event {
Event::TargetCreated(ev) => {
let target_info = ev.params.target_info;
trace!("Target created: {:?}", target_info);
if target_info.target_type.is_page() {
match Tab::new(target_info, Arc::clone(&transport)) {
Ok(new_tab) => {
tabs.lock().unwrap().push(Arc::new(new_tab));
}
Err(_tab_creation_err) => {
error!("Failed to create a handle to new tab");
break;
}
}
}
}
Event::TargetInfoChanged(ev) => {
let target_info = ev.params.target_info;
trace!("Target info changed: {:?}", target_info);
if target_info.target_type.is_page() {
let locked_tabs = tabs.lock().unwrap();
let updated_tab = locked_tabs
.iter()
.find(|tab| *tab.get_target_id() == target_info.target_id)
.expect("got TargetInfoChanged event about a tab not in our list");
updated_tab.update_target_info(target_info);
}
}
Event::TargetDestroyed(ev) => {
trace!("Target destroyed: {:?}", ev.params.target_id);
}
_ => {}
}
}
}
}
trace!("Finished browser's event handling loop");
});
}
/// Call a browser method.
///
/// See the `cdtp` module documentation for available methods.
fn call_method<C>(&self, method: C) -> Result<C::ReturnObject, Error>
where
C: protocol::Method + serde::Serialize,
{
self.transport.call_method_on_browser(method)
}
#[allow(dead_code)]
#[cfg(test)]
pub(crate) fn process(&self) -> &Process {
#[allow(clippy::used_underscore_binding)]
&self._process
}
}
|
use regex::{mod, Regex};
use std::io::File;
use std::collections::HashMap;
use std::fmt::{mod, Show, Formatter};
use std::from_str::FromStr;
macro_rules! opt_chain {
($str: expr => $($wrapper: ident)|*) => {
None
$(.or_else(|| from_str($str).map($wrapper)))*
}
}
#[deriving(Clone)]
struct Variable {
name: String
}
impl FromStr for Variable {
fn from_str(x: &str) -> Option<Variable> {
if x.starts_with("@") {
Some(Variable { name: x.slice_from(1).to_string() })
} else {
None
}
}
}
impl Show for Variable {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
try!("@".fmt(f));
self.name.fmt(f)
}
}
#[deriving(Clone)]
struct Constant {
name: String
}
impl FromStr for Constant {
fn from_str(x: &str) -> Option<Constant> {
if x.starts_with("$") {
Some(Constant { name: x.slice_from(1).to_string() })
} else {
None
}
}
}
impl Show for Constant {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
try!("$".fmt(f));
self.name.fmt(f)
}
}
#[deriving(Clone)]
struct Label {
name: String
}
impl FromStr for Label {
fn from_str(x: &str) -> Option<Label> {
Some(Label { name: x.to_string() })
}
}
impl Show for Label {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.name.fmt(f)
}
}
#[deriving(Clone)]
enum GPRegister {
A, B, C, D, E, F, G, H
}
impl FromStr for GPRegister {
fn from_str(x: &str) -> Option<GPRegister> {
Some(match x {
"a" => A,
"b" => B,
"c" => C,
"d" => D,
"e" => E,
"f" => F,
"g" => G,
"h" => H,
_ => return None
})
}
}
impl Show for GPRegister {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
(match *self {
A => "a", B => "b", C => "c", D => "d",
E => "e", F => "f", G => "g", H => "h"
}).fmt(f)
}
}
#[deriving(Clone)]
enum Address {
AddrReg(GPRegister),
AddrConst(u8)
}
impl FromStr for Address {
fn from_str(x: &str) -> Option<Address> {
if x.starts_with("[") && x.ends_with("]") {
let inner = x.slice(1, x.len() - 1);
opt_chain!(inner => AddrReg | AddrConst)
} else {
None
}
}
}
impl Show for Address {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
try!("[".fmt(f));
try!(match *self {
AddrReg(ref r) => r.fmt(f),
AddrConst(ref c) => c.fmt(f),
})
"]".fmt(f)
}
}
#[deriving(Clone)]
enum Writable {
WrReg(GPRegister),
WrAddr(Address),
WrVariable(Variable),
WrPC,
}
impl FromStr for Writable {
fn from_str(x: &str) -> Option<Writable> {
if x == "pc" {
Some(WrPC)
} else {
opt_chain!(x => WrReg | WrAddr | WrVariable)
}
}
}
impl Show for Writable {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self {
WrReg(ref r) => r.fmt(f),
WrAddr(ref a) => a.fmt(f),
WrVariable(ref v) => v.fmt(f),
WrPC => "pc".fmt(f)
}
}
}
#[deriving(Clone)]
enum Readable {
ReWr(Writable),
ReVariableAddr(Variable),
ReConst(u8),
ReConstant(Constant),
ReLabel(Label)
}
impl FromStr for Readable {
fn from_str(x: &str) -> Option<Readable> {
if x.starts_with("&") {
from_str(x.slice_from(1).trim()).map(ReVariableAddr)
} else {
opt_chain!(x => ReWr | ReConst | ReConstant | ReLabel)
}
}
}
impl Show for Readable {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self {
ReWr(ref w) => w.fmt(f),
ReConst(ref c) => c.fmt(f),
ReConstant(ref c) => c.fmt(f),
ReVariableAddr(ref v) => {
try!("&".fmt(f));
v.fmt(f)
}
ReLabel(ref l) => l.fmt(f),
}
}
}
#[deriving(Clone)]
enum Interrupt {
IntLit(u8),
IntConstant(Constant)
}
impl FromStr for Interrupt {
fn from_str(x: &str) -> Option<Interrupt> {
opt_chain!(x => IntLit | IntConstant)
}
}
impl Show for Interrupt {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self {
IntLit(ref l) => l.fmt(f),
IntConstant(ref c) => c.fmt(f)
}
}
}
#[deriving(Clone)]
enum PositionOrLabel {
Pos(u8),
PosLabel(Label)
}
impl PositionOrLabel {
fn into_readable(self) -> Readable {
match self {
Pos(x) => ReConst(x),
PosLabel(l) => ReLabel(l)
}
}
}
impl FromStr for PositionOrLabel {
fn from_str(x: &str) -> Option<PositionOrLabel> {
opt_chain!(x => Pos | PosLabel)
}
}
impl Show for PositionOrLabel {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self {
Pos(ref c) => c.fmt(f),
PosLabel(ref s) => s.fmt(f)
}
}
}
#[deriving(Clone)]
#[allow(non_camel_case_types)]
enum Instruction {
MOV(Writable, Readable),
INC(Writable),
DEC(Writable),
ADD(Writable, Readable),
SUB(Writable, Readable),
MUL(Writable, Readable),
DIV(Writable, Readable),
AND(Writable, Readable),
OR(Writable, Readable),
XOR(Writable, Readable),
JLT(PositionOrLabel, Readable, Readable),
JEQ(PositionOrLabel, Readable, Readable),
JGT(PositionOrLabel, Readable, Readable),
INT(Interrupt),
HLT,
PUSH(Readable),
POP(Writable),
JUMP(PositionOrLabel),
CALL(PositionOrLabel),
CALL_RET_TO(PositionOrLabel, PositionOrLabel),
RETURN,
DEBUG
}
impl FromStr for Instruction {
fn from_str(x: &str) -> Option<Instruction> {
let mut words = x.split(|c: char| c == ',' || c.is_whitespace()).filter(|s| !s.is_empty());
let first = match words.next() {
Some(f) => f,
None => return None
};
macro_rules! opt_ap {
(: $var: ident $($name: ident)*) => {
$var(
$(match words.next().and_then(from_str) {
Some($name) => $name,
None => return None
}),*)
};
($var: ident 0) => {
$var
};
($var: ident 1) => {
opt_ap!(: $var x)
};
($var: ident 2) => {
opt_ap!(: $var x y)
};
($var: ident 3) => {
opt_ap!(: $var x y z)
}
};
macro_rules! parse {
($($name: pat => $ctor:ident($num:tt)),*) => {
match first {
$($name => opt_ap!($ctor $num),)*
_ => return None
}
}
}
Some(parse! {
"mov" => MOV(2),
"inc" => INC(1),
"dec" => DEC(1),
"add" => ADD(2),
"sub" => SUB(2),
"mul" => MUL(2),
"div" => DIV(2),
"and" => ADD(2),
"or" => OR(2),
"xor" => XOR(2),
"jlt" => JLT(3),
"jeq" => JEQ(3),
"jgt" => JGT(3),
"int" => INT(1),
"hlt" => HLT(0),
"push" => PUSH(1),
"pop" => POP(1),
"call" => CALL(1),
"call-ret-to" => CALL_RET_TO(2),
"jump" => JUMP(1),
"return" => RETURN(0),
"debug" => DEBUG(0)
})
}
}
impl Show for Instruction {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
macro_rules! show_work {
($string: expr $x:ident $($xs:ident)*) => {
{
try!($string.fmt(f));
try!(" ".fmt(f));
try!($x.fmt(f));
$(
try!(", ".fmt(f));
try!($xs.fmt(f));
)*
}
}
}
macro_rules! show {
($($name: ident($($x:ident),+) => $shown: expr),*) => {
match *self {
$($name($(ref $x),+) => show_work!($shown $($x)+),)*
// special case because lazy.
HLT => try!("hlt".fmt(f)),
RETURN => try!("return".fmt(f)),
DEBUG => try!("debug".fmt(f))
}
}
}
show! {
MOV(x,y) => "mov",
INC(x) => "inc",
DEC(x) => "dec",
ADD(x,y) => "add",
SUB(x,y) => "sub",
MUL(x,y) => "mul",
DIV(x,y) => "div",
AND(x,y) => "and",
OR(x,y) => "or",
XOR(x,y) => "xor",
JLT(x,y,z) => "jlt",
JEQ(x,y,z) => "jeq",
JGT(x,y,z) => "jgt",
INT(x) => "int",
PUSH(x) => "push",
POP(x) => "pop",
CALL(x) => "call",
CALL_RET_TO(x,y) => "call-ret-to",
JUMP(x) => "lab"
}
Ok(())
}
}
#[deriving(Clone)]
enum LabelOrInstruction {
Inst(Instruction),
Label(Label)
}
enum BinOp {
BMov, BAdd, BSub, BMul, BDiv, BAnd, BOr, BXor
}
impl BinOp {
fn construct(&self, lhs: Writable, rhs: Readable) -> Instruction {
(match *self {
BMov => MOV, BAdd => ADD, BSub => SUB, BMul => MUL,
BDiv => DIV, BAnd => AND, BOr => OR, BXor => XOR
})(lhs, rhs)
}
}
impl FromStr for BinOp {
fn from_str(x: &str) -> Option<BinOp> {
Some(match x {
"=" => BMov,
"+=" => BAdd,
"-=" => BSub,
"*=" => BMul,
"/=" => BDiv,
"&=" => BAnd,
"|=" => BOr,
"^=" => BXor,
_ => return None
})
}
}
impl FromStr for LabelOrInstruction {
fn from_str(x: &str) -> Option<LabelOrInstruction> {
let mut w = x.words();
match (w.next(), w.next()) {
(Some(lab), None) if lab.ends_with(":") => {
Some(Label(Label { name: lab.slice_to(lab.len() - 1).to_string() }))
}
_ => from_str(x).map(Inst)
}
}
}
pub fn parse(code: &str) -> (Vec<LabelOrInstruction>,
HashMap<String, u8>,
HashMap<String, u8>) {
static INCLUDES: Regex = regex!("include\\s*\"([^\"]*)\"");
let code = INCLUDES.replace_all(code.as_slice(), |captures: ®ex::Captures| {
let filename = captures.at(1);
// errors, what errors?
File::open(&Path::new(filename)).unwrap().read_to_string().unwrap()
});
static COMMENTS: Regex = regex!(";.*");
let code = COMMENTS.replace_all(code.as_slice(), "");
static OPERATORS: Regex = regex!(r"[+*/&^|-]?=");
let code = OPERATORS.replace_all(code.as_slice(), " $0 ");
let mut variables = HashMap::new();
let mut variable_index = 0u8;
let mut constants = HashMap::new();
let mut parsed = vec![];
let mut lines = code.as_slice().lines_any();
let mut initial = true;
for line in lines {
let line = line.trim();
if line.is_empty() { continue }
let mut w = line.words();
match (w.next(), w.next(), w.next(), w.next()) {
(Some("decl"), Some(var), None, _) => {
if initial {
assert!(variables.insert(var.to_string(), variable_index),
"duplicated decl of variable {}: {}", var, line);
variable_index += 1
} else {
fail!("decls only allowed at the top of a file: {}", line)
}
continue
}
(Some("const"), Some(name), Some(value), None) => {
match from_str::<u8>(value) {
Some(v) => assert!(constants.insert(name.to_string(), v),
"duplicated constant {}: {}", name, line),
None => fail!("constant with invalid value {}: {}", name, line)
}
continue
}
(Some(lhs), Some(op), Some(rhs), None) => {
match (from_str(lhs), from_str::<BinOp>(op), from_str(rhs)) {
(Some(l), Some(b_op), Some(r)) => {
parsed.push(Inst(b_op.construct(l, r)));
continue
}
_ => {}
}
}
_ => {}
}
initial = false;
match from_str::<LabelOrInstruction>(line) {
Some(x) => parsed.push(x),
None => fail!("could not parse {}", line)
}
}
(parsed, variables, constants)
}
trait Resolve {
fn resolve(&self,
code: &Instruction,
variables: &HashMap<String, u8>,
constants: &HashMap<String, u8>,
labels: &HashMap<String, u8>) -> Self;
}
fn resolve_variable(var: &Variable,
code: &Instruction,
variables: &HashMap<String, u8>) -> u8 {
match variables.find(&var.name) {
Some(&val) => val,
None => fail!("unknown variable {}: {}", *var, *code)
}
}
impl Resolve for Writable {
fn resolve(&self,
code: &Instruction,
variables: &HashMap<String, u8>,
_constants: &HashMap<String, u8>,
_labels: &HashMap<String, u8>) -> Writable {
match *self {
WrAddr(_) | WrReg(_) | WrPC => self.clone(),
WrVariable(ref name) => WrAddr(AddrConst(resolve_variable(name, code, variables)))
}
}
}
fn resolve_label(lab: &Label,
code: &Instruction,
labels: &HashMap<String, u8>) -> u8 {
match labels.find(&lab.name) {
Some(&val) => val,
None => fail!("unknown label {}: {}", lab.name, *code)
}
}
impl Resolve for Readable {
fn resolve(&self,
code: &Instruction,
variables: &HashMap<String, u8>,
constants: &HashMap<String, u8>,
labels: &HashMap<String, u8>) -> Readable {
match *self {
ReConst(_) => self.clone(),
ReWr(ref w) => ReWr(w.resolve(code, variables, constants, labels)),
ReVariableAddr(ref v) => ReConst(resolve_variable(v, code, variables)),
ReLabel(ref l) => ReConst(resolve_label(l, code, labels)),
ReConstant(ref name) => {
match constants.find(&name.name) {
Some(&val) => ReConst(val),
None => fail!("unknown constant {}: {}", *name, *code)
}
}
}
}
}
impl Resolve for PositionOrLabel {
fn resolve(&self,
code: &Instruction,
_variables: &HashMap<String, u8>,
_constants: &HashMap<String, u8>,
labels: &HashMap<String, u8>) -> PositionOrLabel {
match *self {
Pos(x) => Pos(x),
PosLabel(ref name) => Pos(resolve_label(name, code, labels))
}
}
}
impl Resolve for Interrupt {
fn resolve(&self,
code: &Instruction,
_variables: &HashMap<String, u8>,
constants: &HashMap<String, u8>,
_labels: &HashMap<String, u8>) -> Interrupt {
// allow this to be naturally used in the generic macro below
match *self {
IntLit(x) => IntLit(x),
IntConstant(ref name) => {
match constants.find(&name.name) {
Some(&val) => IntLit(val),
None => fail!("unknown constant {}: {}", *name, *code)
}
}
}
}
}
pub fn compile(code: &[LabelOrInstruction],
variables: &HashMap<String, u8>, constants: &HashMap<String, u8>)
-> Vec<Instruction> {
// initialise the stack pointer
let mut no_sugar = vec![Inst(MOV(WrReg(H), ReConst(255)))];
for thing in code.iter() {
match *thing {
Label(_) => no_sugar.push(thing.clone()),
Inst(ref i) => desugar(i.clone(), &mut no_sugar)
}
}
let mut labels = HashMap::new();
let mut index = 0u;
for thing in no_sugar.iter() {
match *thing {
Label(ref name) => {
assert!(labels.insert(name.to_string(), index as u8),
"duplicated label {}", name)
}
Inst(_) => index += 1,
}
}
assert!(variables.len() <= 256, "program has {} variables, limit is 256", variables.len());
let mut ret = vec![];
for thing in no_sugar.iter() {
let inst = match *thing {
Label(_) => continue,
Inst(ref inst) => inst
};
macro_rules! resolve {
($($name: ident($($x:ident),+)),*) => {
match *inst {
$($name($(ref $x),+) => {
$name($($x.resolve(inst, variables, constants, &labels) ),*)
})*
// special case because lazy.
HLT => HLT,
RETURN => RETURN,
DEBUG => DEBUG,
}
}
}
let resolved = resolve! {
MOV(x,y),
INC(x),
DEC(x),
ADD(x,y),
SUB(x,y),
MUL(x,y),
DIV(x,y),
AND(x,y),
OR(x,y),
XOR(x,y),
JLT(x,y,z),
JEQ(x,y,z),
JGT(x,y,z),
INT(x),
PUSH(x),
POP(x),
CALL(x),
CALL_RET_TO(x,y),
JUMP(lab)
};
ret.push(resolved);
}
assert!(ret.len() <= 256, "program has {} instructions, limit is 256", ret.len());
ret
}
static CURR_STACK: Writable = WrAddr(AddrReg(H));
static CURR_STACK_R: Readable = ReWr(CURR_STACK);
fn desugar(inst: Instruction, asm: &mut Vec<LabelOrInstruction>) {
macro_rules! desugar {
($arg: expr) => { desugar($arg, asm) }
}
macro_rules! inst {
($arg: expr) => { asm.push(Inst($arg)) }
}
match inst {
PUSH(val) => {
// [h] = val
// dec h
inst!(MOV(CURR_STACK.clone(), val));
inst!(DEC(WrReg(H)));
}
POP(val) => {
// inc h
// val = [h]
inst!(INC(WrReg(H)));
inst!(MOV(val, CURR_STACK_R.clone()));
}
JUMP(lab) => {
inst!(MOV(WrPC, lab.into_readable()))
}
CALL(lab) => {
let ret_label = Label { name: format!("ret-label-{}", asm.len()) };
desugar!(CALL_RET_TO(lab, PosLabel(ret_label.clone())));
asm.push(Label(ret_label));
}
CALL_RET_TO(func, lab) => {
desugar!(PUSH(lab.into_readable()));
desugar!(JUMP(func));
}
RETURN => {
desugar!(POP(WrPC))
}
DEBUG => {
inst!(INT(IntLit(8)))
}
_ => inst!(inst.clone())
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.