text stringlengths 8 4.13M |
|---|
pub mod codegen;
pub mod helpers;
pub mod lexer;
pub mod logger;
pub mod master;
pub mod parser;
pub mod typecheck;
#[macro_use]
extern crate clap;
use clap::App;
use inkwell::context::Context;
fn main() {
let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();
let filename = matches.value_of("entry").unwrap();
let context = Context::create();
let contents = helpers::read_file(filename);
let mut master = master::Master::new(&context);
master.add_file(filename, &contents[..]);
}
|
#![allow(dead_code)]
#![allow(non_camel_case_types)]
extern crate pcap;
use pcap::Packet;
use std::path::Path;
use std::ffi::CString;
use libc::{c_int, c_uint, c_char, c_uchar, timeval};
#[repr(C)]
#[derive(Copy, Clone)]
pub struct pcap_pkthdr {
pub ts: timeval,
pub caplen: c_uint,
pub len: c_uint,
}
pub enum pcap_t { }
pub enum pcap_dumper_t { }
extern "C" {
pub fn pcap_dump_open(arg1: *mut pcap_t, arg2: *const c_char) -> *mut pcap_dumper_t;
pub fn pcap_open_dead(arg1: c_int, arg2: c_int) -> *mut pcap_t;
pub fn pcap_dump(arg1: *mut c_uchar, arg2: *const pcap_pkthdr, arg3: *const c_uchar) -> ();
pub fn pcap_dump_close(arg1: *mut pcap_dumper_t) -> ();
pub fn pcap_geterr(arg1: *mut pcap_t) -> *mut c_char;
}
/// Abstraction for writing pcap savefiles, which can be read afterwards via `Capture::from_file()`.
pub struct Savefile {
ptr_pcap_t: Unique<pcap_t>,
ptr_pcap_dumper_t: Unique<pcap_dumper_t>,
}
impl Savefile {
pub fn write(&mut self, packet: &Packet) {
unsafe {
pcap_dump(*self.ptr_pcap_dumper_t as _,
mem::transmute::<_, &pcap_pkthdr>(packet.header),
packet.data.as_ptr());
}
}
pub fn new<P: AsRef<Path>>(path: P) -> Savefile {
let name = CString::new(path.as_ref().to_str().unwrap()).unwrap();
unsafe {
let ptr_pcap_t = pcap_open_dead(1, 65535).as_mut().unwrap();
let ptr_pcap_dumper_t = pcap_dump_open(ptr_pcap_t, name.as_ptr());
Savefile {
ptr_pcap_t: Unique::new(ptr_pcap_t),
ptr_pcap_dumper_t: Unique::new( ptr_pcap_dumper_t )
}
}
}
pub fn null() -> Savefile {
unsafe {
Savefile {
ptr_pcap_t: Unique::new(std::ptr::null_mut()),
ptr_pcap_dumper_t: Unique::new(std::ptr::null_mut())
}
}
}
}
impl Drop for Savefile {
fn drop(&mut self) {
unsafe { pcap_dump_close(*self.ptr_pcap_dumper_t) }
}
}
// pcap/src/unique.rs
use std::fmt;
use std::mem;
use std::marker::PhantomData;
use std::ops::Deref;
pub struct Unique<T: ?Sized> {
pointer: *const T,
_marker: PhantomData<T>,
}
unsafe impl<T: Send + ?Sized> Send for Unique<T> {}
unsafe impl<T: Sync + ?Sized> Sync for Unique<T> {}
impl<T: ?Sized> Unique<T> {
pub unsafe fn new(ptr: *mut T) -> Unique<T> {
Unique {
pointer: ptr,
_marker: PhantomData,
}
}
pub unsafe fn get(&self) -> &T {
&*self.pointer
}
pub unsafe fn get_mut(&mut self) -> &mut T {
&mut ***self
}
}
impl<T: ?Sized> Deref for Unique<T> {
type Target = *mut T;
#[inline]
fn deref(&self) -> &*mut T {
unsafe { mem::transmute(&self.pointer) }
}
}
impl<T> fmt::Pointer for Unique<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Pointer::fmt(&self.pointer, f)
}
}
|
//! Jobs.
use std::{future::Future, sync::Arc};
use async_std::task;
/// Job context, that handles state
#[derive(Debug)]
pub struct JobContext<State> {
state: Arc<State>,
}
impl<State> JobContext<State> {
pub(crate) fn new(state: Arc<State>) -> Self {
Self { state }
}
/// Access app-global state
pub fn state(&self) -> &State {
&self.state
}
}
/// Job trait for handling background tasks.
pub trait Job<State>: 'static + Send + Sync {
/// Asynchronously execute job.
fn handle(&self, ctx: JobContext<State>);
}
impl<State, F, Fut> Job<State> for F
where
F: Fn(JobContext<State>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
fn handle(&self, ctx: JobContext<State>) {
let fut = (self)(ctx);
task::spawn(async move {
fut.await;
});
}
}
|
//! Helpers to generate code from an IR instance and fully specified decisions.
mod cfg;
mod dimension;
mod function;
pub mod llir;
mod name_map;
mod printer;
mod size;
mod variable;
pub use self::cfg::Cfg;
pub use self::dimension::{Dimension, InductionLevel, InductionVar};
pub use self::function::*;
pub use self::name_map::{Interner, NameGenerator, NameMap, Operand};
pub use self::printer::{IdentDisplay, InstPrinter, Printer};
pub use self::size::Size;
pub use self::variable::Variable;
// TODO(cleanup): refactor function
// - extend instructions with additional information: vector factor, flag, instantiated dims
// TODO(cleanup): refactor namer
|
use neon::{
context::Context,
handle::Handle,
prelude::*,
result::Throw,
types::{JsArray, JsNull, JsObject, JsUndefined, JsValue},
};
use std::collections::HashMap;
pub fn is_null_or_undefined<'a, U: Value + 'a>(handle: Handle<'a, U>) -> bool {
handle.is_a::<JsNull>() || handle.is_a::<JsUndefined>()
}
pub fn get_bool<'a, C: Context<'a>, E: From<Throw>>(
cx: &mut C,
obj: Handle<'a, JsObject>,
property: &str,
) -> Result<Option<bool>, E> {
let property_value = obj.get(cx, property)?;
let value = if is_null_or_undefined(property_value) {
None
} else {
Some(
property_value
.downcast_or_throw::<JsBoolean, C>(cx)?
.value(),
)
};
Ok(value)
}
fn js_string_to_string<'a, C: Context<'a>, E: From<Throw>>(
cx: &mut C,
js_string: &Handle<JsValue>,
) -> Result<String, E> {
Ok(js_string.downcast_or_throw::<JsString, C>(cx)?.value())
}
fn js_array_to_vec_of_str<'a, C: Context<'a>, E: From<Throw>>(
cx: &mut C,
arr: Handle<'a, JsArray>,
) -> Result<Vec<String>, E> {
let mut vec_of_strings = vec![];
for js_string in arr.to_vec(cx)?.iter() {
vec_of_strings.push(js_string_to_string(cx, js_string)?);
}
Ok(vec_of_strings)
}
pub fn get_vec_of_strings<'a, C: Context<'a>, E: From<Throw>>(
cx: &mut C,
obj: Handle<'a, JsObject>,
property: &str,
) -> Result<Option<Vec<String>>, E> {
let property_value = obj.get(cx, property)?;
if is_null_or_undefined(property_value) {
return Ok(None);
}
let js_array = property_value.downcast_or_throw::<JsArray, C>(cx)?;
let value = js_array_to_vec_of_str(cx, js_array)?;
Ok(Some(value))
}
pub fn get_hashmap_of_strings<'a, C: Context<'a>, E: From<Throw>>(
cx: &mut C,
obj: Handle<'a, JsObject>,
property: &str,
) -> Result<Option<HashMap<String, String>>, E> {
let property_value = obj.get(cx, property)?;
if is_null_or_undefined(property_value) {
return Ok(None);
}
let js_object = property_value.downcast_or_throw::<JsObject, C>(cx)?;
let js_array = js_object.get_own_property_names(cx)?;
let value_keys = js_array_to_vec_of_str(cx, js_array)?;
let mut value = HashMap::new();
for value_property in value_keys.iter() {
let js_string = js_object.get(cx, value_property.as_ref())?;
let string = js_string_to_string(cx, &js_string)?;
value.insert(value_property.clone(), string);
}
Ok(Some(value))
}
|
use std::borrow::Cow;
use std::ffi::CStr;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::sync::Arc;
use vulkano::descriptor::descriptor::{DescriptorDesc, ShaderStages};
use vulkano::descriptor::pipeline_layout::{PipelineLayoutDesc, PipelineLayoutDescPcRange};
use vulkano::device::Device;
use vulkano::format::Format;
use vulkano::pipeline::shader::{
GraphicsEntryPoint, GraphicsShaderType, ShaderInterfaceDef, ShaderInterfaceDefEntry,
ShaderModule,
};
#[derive(Default, Copy, Clone)]
pub struct Vertex {
pub position: [f32; 2],
pub color: [f32; 3],
}
vulkano::impl_vertex!(Vertex, position, color);
pub fn open(path: &Path, device: Arc<Device>) -> Arc<ShaderModule> {
let mut f = File::open(path).expect(&format!("Shader not found: {:#?}", path));
let mut buf = Vec::with_capacity(50);
f.read_to_end(&mut buf).unwrap();
unsafe { ShaderModule::new(device, &buf) }.unwrap()
}
pub struct VertInput;
#[derive(Debug, Copy, Clone)]
pub struct VertInputIter(u16);
unsafe impl ShaderInterfaceDef for VertInput {
type Iter = VertInputIter;
fn elements(&self) -> VertInputIter {
VertInputIter(0)
}
}
impl Iterator for VertInputIter {
type Item = ShaderInterfaceDefEntry;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
// There are things to consider when giving out entries:
// * There must be only one entry per one location, you can't have
// `color' and `position' entries both at 0..1 locations. They also
// should not overlap.
// * Format of each element must be no larger than 128 bits.
if self.0 == 0 {
self.0 += 1;
return Some(ShaderInterfaceDefEntry {
location: 1..2,
format: Format::R32G32B32Sfloat,
name: Some(Cow::Borrowed("color")),
});
}
if self.0 == 1 {
self.0 += 1;
return Some(ShaderInterfaceDefEntry {
location: 0..1,
format: Format::R32G32Sfloat,
name: Some(Cow::Borrowed("position")),
});
}
None
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
// We must return exact number of entries left in iterator.
let len = (2 - self.0) as usize;
(len, Some(len))
}
}
impl ExactSizeIterator for VertInputIter {}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct VertOutput;
unsafe impl ShaderInterfaceDef for VertOutput {
type Iter = VertOutputIter;
fn elements(&self) -> VertOutputIter {
VertOutputIter(0)
}
}
// This structure will tell Vulkan how output entries (those passed to next
// stage) of our vertex shader look like.
#[derive(Debug, Copy, Clone)]
pub struct VertOutputIter(u16);
impl Iterator for VertOutputIter {
type Item = ShaderInterfaceDefEntry;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.0 == 0 {
self.0 += 1;
return Some(ShaderInterfaceDefEntry {
location: 0..1,
format: Format::R32G32B32Sfloat,
name: Some(Cow::Borrowed("v_color")),
});
}
None
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = (1 - self.0) as usize;
(len, Some(len))
}
}
impl ExactSizeIterator for VertOutputIter {}
// This structure describes layout of this stage.
#[derive(Debug, Copy, Clone)]
pub struct VertLayout(ShaderStages);
unsafe impl PipelineLayoutDesc for VertLayout {
// Number of descriptor sets it takes.
fn num_sets(&self) -> usize {
0
}
// Number of entries (bindings) in each set.
fn num_bindings_in_set(&self, _set: usize) -> Option<usize> {
None
}
// Descriptor descriptions.
fn descriptor(&self, _set: usize, _binding: usize) -> Option<DescriptorDesc> {
None
}
// Number of push constants ranges (think: number of push constants).
fn num_push_constants_ranges(&self) -> usize {
0
}
// Each push constant range in memory.
fn push_constants_range(&self, _num: usize) -> Option<PipelineLayoutDescPcRange> {
None
}
}
// Same as with our vertex shader, but for fragment one instead.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct FragInput;
unsafe impl ShaderInterfaceDef for FragInput {
type Iter = FragInputIter;
fn elements(&self) -> FragInputIter {
FragInputIter(0)
}
}
#[derive(Debug, Copy, Clone)]
pub struct FragInputIter(u16);
impl Iterator for FragInputIter {
type Item = ShaderInterfaceDefEntry;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.0 == 0 {
self.0 += 1;
return Some(ShaderInterfaceDefEntry {
location: 0..1,
format: Format::R32G32B32Sfloat,
name: Some(Cow::Borrowed("v_color")),
});
}
None
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = (1 - self.0) as usize;
(len, Some(len))
}
}
impl ExactSizeIterator for FragInputIter {}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct FragOutput;
unsafe impl ShaderInterfaceDef for FragOutput {
type Iter = FragOutputIter;
fn elements(&self) -> FragOutputIter {
FragOutputIter(0)
}
}
#[derive(Debug, Copy, Clone)]
pub struct FragOutputIter(u16);
impl Iterator for FragOutputIter {
type Item = ShaderInterfaceDefEntry;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
// Note that color fragment color entry will be determined
// automatically by Vulkano.
if self.0 == 0 {
self.0 += 1;
return Some(ShaderInterfaceDefEntry {
location: 0..1,
format: Format::R32G32B32A32Sfloat,
name: Some(Cow::Borrowed("f_color")),
});
}
None
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = (1 - self.0) as usize;
(len, Some(len))
}
}
impl ExactSizeIterator for FragOutputIter {}
// Layout same as with vertex shader.
#[derive(Debug, Copy, Clone)]
pub struct FragLayout(ShaderStages);
unsafe impl PipelineLayoutDesc for FragLayout {
fn num_sets(&self) -> usize {
0
}
fn num_bindings_in_set(&self, _set: usize) -> Option<usize> {
None
}
fn descriptor(&self, _set: usize, _binding: usize) -> Option<DescriptorDesc> {
None
}
fn num_push_constants_ranges(&self) -> usize {
0
}
fn push_constants_range(&self, _num: usize) -> Option<PipelineLayoutDescPcRange> {
None
}
}
pub fn get_entry_fragment(
shader: &ShaderModule,
) -> GraphicsEntryPoint<'_, (), FragInput, FragOutput, FragLayout> {
unsafe {
shader.graphics_entry_point(
CStr::from_bytes_with_nul_unchecked(b"main\0"),
FragInput,
FragOutput,
FragLayout(ShaderStages {
fragment: true,
..ShaderStages::none()
}),
GraphicsShaderType::Fragment,
)
}
}
pub fn get_entry_vertex(
shader: &ShaderModule,
) -> GraphicsEntryPoint<'_, (), VertInput, VertOutput, VertLayout> {
unsafe {
shader.graphics_entry_point(
CStr::from_bytes_with_nul_unchecked(b"main\0"),
VertInput,
VertOutput,
VertLayout(ShaderStages {
vertex: true,
..ShaderStages::none()
}),
GraphicsShaderType::Vertex,
)
}
}
|
extern crate chrono;
use self::chrono::prelude::{DateTime, Utc};
pub mod source;
use symbol::SymbolId;
#[derive(PartialEq, Clone, Debug)]
pub struct Ohlcv {
symbol_id: SymbolId,
datetime: DateTime<Utc>,
open: f64,
high: f64,
low: f64,
close: f64,
volume: u32
}
impl Ohlcv {
pub fn new(symbol_id: SymbolId, datetime: DateTime<Utc>, open: f64, high: f64, low: f64, close: f64, volume: u32) -> Ohlcv {
Ohlcv {
symbol_id,
datetime,
open,
high,
low,
close,
volume
}
}
pub fn symbol_id(&self) -> &SymbolId {
&self.symbol_id
}
pub fn datetime(&self) -> &DateTime<Utc> {
&self.datetime
}
pub fn open(&self) -> f64 {
self.open
}
pub fn high(&self) -> f64 {
self.high
}
pub fn low(&self) -> f64 {
self.low
}
pub fn close(&self) -> f64 {
self.close
}
pub fn volume(&self) -> u32 {
self.volume
}
}
|
// 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.
use std::marker::PhantomData;
use std::time::Instant;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::types::number::*;
use common_expression::types::DataType;
use common_expression::types::ValueType;
use common_expression::Column;
use common_expression::HashMethod;
use common_expression::HashMethodFixedKeys;
use common_expression::HashMethodKeysU128;
use common_expression::HashMethodKeysU256;
use common_expression::HashMethodSerializer;
use common_expression::HashMethodSingleString;
use common_expression::KeysState;
use common_hashtable::FastHash;
use common_hashtable::HashMap;
use common_hashtable::HashtableEntryMutRefLike;
use common_hashtable::HashtableEntryRefLike;
use common_hashtable::HashtableLike;
use common_hashtable::LookupHashMap;
use common_hashtable::PartitionedHashMap;
use common_hashtable::ShortStringHashMap;
use common_hashtable::StringHashMap;
use ethnum::U256;
use tracing::info;
use super::aggregator_keys_builder::LargeFixedKeysColumnBuilder;
use super::aggregator_keys_iter::LargeFixedKeysColumnIter;
use super::BUCKETS_LG2;
use crate::pipelines::processors::transforms::group_by::aggregator_groups_builder::FixedKeysGroupColumnsBuilder;
use crate::pipelines::processors::transforms::group_by::aggregator_groups_builder::GroupColumnsBuilder;
use crate::pipelines::processors::transforms::group_by::aggregator_groups_builder::SerializedKeysGroupColumnsBuilder;
use crate::pipelines::processors::transforms::group_by::aggregator_keys_builder::FixedKeysColumnBuilder;
use crate::pipelines::processors::transforms::group_by::aggregator_keys_builder::KeysColumnBuilder;
use crate::pipelines::processors::transforms::group_by::aggregator_keys_builder::StringKeysColumnBuilder;
use crate::pipelines::processors::transforms::group_by::aggregator_keys_iter::FixedKeysColumnIter;
use crate::pipelines::processors::transforms::group_by::aggregator_keys_iter::KeysColumnIter;
use crate::pipelines::processors::transforms::group_by::aggregator_keys_iter::SerializedKeysColumnIter;
use crate::pipelines::processors::transforms::group_by::Area;
use crate::pipelines::processors::transforms::group_by::ArenaHolder;
use crate::pipelines::processors::transforms::HashTableCell;
use crate::pipelines::processors::transforms::PartitionedHashTableDropper;
use crate::pipelines::processors::AggregatorParams;
// Provide functions for all HashMethod to help implement polymorphic group by key
//
// When we want to add new HashMethod, we need to add the following components
// - HashMethod, more information in [HashMethod] trait
// - AggregatorState, more information in [AggregatorState] trait
// - KeysColumnBuilder, more information in [KeysColumnBuilder] trait
// - PolymorphicKeysHelper, more information in following comments
//
// For example:
//
// use bumpalo::Bump;
// use databend_query::common::HashTable;
// use common_expression::HashMethodSerializer;
// use databend_query::pipelines::processors::transforms::group_by::PolymorphicKeysHelper;
// use databend_query::pipelines::processors::transforms::group_by::aggregator_state::SerializedKeysAggregatorState;
// use databend_query::pipelines::processors::transforms::group_by::aggregator_keys_builder::StringKeysColumnBuilder;
//
// impl PolymorphicKeysHelper<HashMethodSerializer> for HashMethodSerializer {
// type State = SerializedKeysAggregatorState;
// fn aggregate_state(&self) -> Self::State {
// SerializedKeysAggregatorState {
// keys_area: Bump::new(),
// state_area: Bump::new(),
// data_state_map: HashTable::create(),
// }
// }
//
// type ColumnBuilder = StringKeysColumnBuilder;
// fn state_array_builder(&self, capacity: usize) -> Self::ColumnBuilder {
// StringKeysColumnBuilder {
// inner_builder: MutableStringColumn::with_capacity(capacity),
// }
// }
// }
//
pub trait PolymorphicKeysHelper<Method: HashMethod>: Send + Sync + 'static {
const SUPPORT_PARTITIONED: bool;
type HashTable<T: Send + Sync + 'static>: HashtableLike<Key = Method::HashKey, Value = T>
+ Send
+ Sync
+ 'static;
fn create_hash_table<T: Send + Sync + 'static>(&self) -> Result<Self::HashTable<T>>;
type ColumnBuilder<'a>: KeysColumnBuilder<T = &'a Method::HashKey>
where
Self: 'a,
Method: 'a;
fn keys_column_builder(
&self,
capacity: usize,
value_capacity: usize,
) -> Self::ColumnBuilder<'_>;
type KeysColumnIter: KeysColumnIter<Method::HashKey>;
fn keys_iter_from_column(&self, column: &Column) -> Result<Self::KeysColumnIter>;
type GroupColumnsBuilder<'a>: GroupColumnsBuilder<T = &'a Method::HashKey>
where
Self: 'a,
Method: 'a;
fn group_columns_builder(
&self,
capacity: usize,
_data_capacity: usize,
params: &AggregatorParams,
) -> Self::GroupColumnsBuilder<'_>;
fn get_hash(&self, v: &Method::HashKey) -> u64;
}
impl PolymorphicKeysHelper<HashMethodFixedKeys<u8>> for HashMethodFixedKeys<u8> {
const SUPPORT_PARTITIONED: bool = false;
type HashTable<T: Send + Sync + 'static> = LookupHashMap<u8, 256, T>;
fn create_hash_table<T: Send + Sync + 'static>(&self) -> Result<Self::HashTable<T>> {
Ok(LookupHashMap::create(Default::default()))
}
type ColumnBuilder<'a> = FixedKeysColumnBuilder<'a, u8>;
fn keys_column_builder(&self, capacity: usize, _: usize) -> FixedKeysColumnBuilder<u8> {
FixedKeysColumnBuilder::<u8> {
_t: Default::default(),
inner_builder: Vec::with_capacity(capacity),
}
}
type KeysColumnIter = FixedKeysColumnIter<u8>;
fn keys_iter_from_column(&self, column: &Column) -> Result<Self::KeysColumnIter> {
FixedKeysColumnIter::create(&UInt8Type::try_downcast_column(column).ok_or_else(|| {
ErrorCode::IllegalDataType("Illegal data type for FixedKeysColumnIter<u8>".to_string())
})?)
}
type GroupColumnsBuilder<'a> = FixedKeysGroupColumnsBuilder<'a, u8>;
fn group_columns_builder(
&self,
capacity: usize,
_data_capacity: usize,
params: &AggregatorParams,
) -> FixedKeysGroupColumnsBuilder<u8> {
FixedKeysGroupColumnsBuilder::<u8>::create(capacity, params)
}
fn get_hash(&self, v: &u8) -> u64 {
v.fast_hash()
}
}
impl PolymorphicKeysHelper<HashMethodFixedKeys<u16>> for HashMethodFixedKeys<u16> {
const SUPPORT_PARTITIONED: bool = false;
type HashTable<T: Send + Sync + 'static> = LookupHashMap<u16, 65536, T>;
fn create_hash_table<T: Send + Sync + 'static>(&self) -> Result<Self::HashTable<T>> {
Ok(LookupHashMap::create(Default::default()))
}
type ColumnBuilder<'a> = FixedKeysColumnBuilder<'a, u16>;
fn keys_column_builder(&self, capacity: usize, _: usize) -> FixedKeysColumnBuilder<u16> {
FixedKeysColumnBuilder::<u16> {
_t: Default::default(),
inner_builder: Vec::with_capacity(capacity),
}
}
type KeysColumnIter = FixedKeysColumnIter<u16>;
fn keys_iter_from_column(&self, column: &Column) -> Result<Self::KeysColumnIter> {
FixedKeysColumnIter::create(&UInt16Type::try_downcast_column(column).ok_or_else(|| {
ErrorCode::IllegalDataType("Illegal data type for FixedKeysColumnIter<u16>".to_string())
})?)
}
type GroupColumnsBuilder<'a> = FixedKeysGroupColumnsBuilder<'a, u16>;
fn group_columns_builder(
&self,
capacity: usize,
_data_capacity: usize,
params: &AggregatorParams,
) -> FixedKeysGroupColumnsBuilder<u16> {
FixedKeysGroupColumnsBuilder::<u16>::create(capacity, params)
}
fn get_hash(&self, v: &u16) -> u64 {
v.fast_hash()
}
}
impl PolymorphicKeysHelper<HashMethodFixedKeys<u32>> for HashMethodFixedKeys<u32> {
const SUPPORT_PARTITIONED: bool = true;
type HashTable<T: Send + Sync + 'static> = HashMap<u32, T>;
fn create_hash_table<T: Send + Sync + 'static>(&self) -> Result<Self::HashTable<T>> {
Ok(HashMap::new())
}
type ColumnBuilder<'a> = FixedKeysColumnBuilder<'a, u32>;
fn keys_column_builder(&self, capacity: usize, _: usize) -> FixedKeysColumnBuilder<u32> {
FixedKeysColumnBuilder::<u32> {
_t: Default::default(),
inner_builder: Vec::with_capacity(capacity),
}
}
type KeysColumnIter = FixedKeysColumnIter<u32>;
fn keys_iter_from_column(&self, column: &Column) -> Result<Self::KeysColumnIter> {
FixedKeysColumnIter::create(&UInt32Type::try_downcast_column(column).ok_or_else(|| {
ErrorCode::IllegalDataType("Illegal data type for FixedKeysColumnIter<u32>".to_string())
})?)
}
type GroupColumnsBuilder<'a> = FixedKeysGroupColumnsBuilder<'a, u32>;
fn group_columns_builder(
&self,
capacity: usize,
_data_capacity: usize,
params: &AggregatorParams,
) -> FixedKeysGroupColumnsBuilder<u32> {
FixedKeysGroupColumnsBuilder::<u32>::create(capacity, params)
}
fn get_hash(&self, v: &u32) -> u64 {
v.fast_hash()
}
}
impl PolymorphicKeysHelper<HashMethodFixedKeys<u64>> for HashMethodFixedKeys<u64> {
const SUPPORT_PARTITIONED: bool = true;
type HashTable<T: Send + Sync + 'static> = HashMap<u64, T>;
fn create_hash_table<T: Send + Sync + 'static>(&self) -> Result<Self::HashTable<T>> {
Ok(HashMap::new())
}
type ColumnBuilder<'a> = FixedKeysColumnBuilder<'a, u64>;
fn keys_column_builder(&self, capacity: usize, _: usize) -> FixedKeysColumnBuilder<u64> {
FixedKeysColumnBuilder::<u64> {
_t: Default::default(),
inner_builder: Vec::with_capacity(capacity),
}
}
type KeysColumnIter = FixedKeysColumnIter<u64>;
fn keys_iter_from_column(&self, column: &Column) -> Result<Self::KeysColumnIter> {
FixedKeysColumnIter::create(&UInt64Type::try_downcast_column(column).ok_or_else(|| {
ErrorCode::IllegalDataType("Illegal data type for FixedKeysColumnIter<u64>".to_string())
})?)
}
type GroupColumnsBuilder<'a> = FixedKeysGroupColumnsBuilder<'a, u64>;
fn group_columns_builder(
&self,
capacity: usize,
_data_capacity: usize,
params: &AggregatorParams,
) -> FixedKeysGroupColumnsBuilder<u64> {
FixedKeysGroupColumnsBuilder::<u64>::create(capacity, params)
}
fn get_hash(&self, v: &u64) -> u64 {
v.fast_hash()
}
}
impl PolymorphicKeysHelper<HashMethodKeysU128> for HashMethodKeysU128 {
const SUPPORT_PARTITIONED: bool = true;
type HashTable<T: Send + Sync + 'static> = HashMap<u128, T>;
fn create_hash_table<T: Send + Sync + 'static>(&self) -> Result<Self::HashTable<T>> {
Ok(HashMap::new())
}
type ColumnBuilder<'a> = LargeFixedKeysColumnBuilder<'a, u128>;
fn keys_column_builder(&self, capacity: usize, _: usize) -> LargeFixedKeysColumnBuilder<u128> {
LargeFixedKeysColumnBuilder {
values: Vec::with_capacity(capacity * 16),
_t: PhantomData,
}
}
type KeysColumnIter = LargeFixedKeysColumnIter<u128>;
fn keys_iter_from_column(&self, column: &Column) -> Result<Self::KeysColumnIter> {
let buffer = column
.as_decimal()
.and_then(|c| c.as_decimal128())
.ok_or_else(|| {
ErrorCode::IllegalDataType(
"Illegal data type for LargeFixedKeysColumnIter<u128>".to_string(),
)
})?;
let buffer = unsafe { std::mem::transmute(buffer.0.clone()) };
LargeFixedKeysColumnIter::create(buffer)
}
type GroupColumnsBuilder<'a> = FixedKeysGroupColumnsBuilder<'a, u128>;
fn group_columns_builder(
&self,
capacity: usize,
_data_capacity: usize,
params: &AggregatorParams,
) -> FixedKeysGroupColumnsBuilder<u128> {
FixedKeysGroupColumnsBuilder::create(capacity, params)
}
fn get_hash(&self, v: &u128) -> u64 {
v.fast_hash()
}
}
impl PolymorphicKeysHelper<HashMethodKeysU256> for HashMethodKeysU256 {
const SUPPORT_PARTITIONED: bool = true;
type HashTable<T: Send + Sync + 'static> = HashMap<U256, T>;
fn create_hash_table<T: Send + Sync + 'static>(&self) -> Result<Self::HashTable<T>> {
Ok(HashMap::new())
}
type ColumnBuilder<'a> = LargeFixedKeysColumnBuilder<'a, U256>;
fn keys_column_builder(&self, capacity: usize, _: usize) -> LargeFixedKeysColumnBuilder<U256> {
LargeFixedKeysColumnBuilder {
values: Vec::with_capacity(capacity * 32),
_t: PhantomData,
}
}
type KeysColumnIter = LargeFixedKeysColumnIter<U256>;
fn keys_iter_from_column(&self, column: &Column) -> Result<Self::KeysColumnIter> {
let buffer = column
.as_decimal()
.and_then(|c| c.as_decimal256())
.ok_or_else(|| {
ErrorCode::IllegalDataType(
"Illegal data type for LargeFixedKeysColumnIter<u128>".to_string(),
)
})?;
let buffer = unsafe { std::mem::transmute(buffer.0.clone()) };
LargeFixedKeysColumnIter::create(buffer)
}
type GroupColumnsBuilder<'a> = FixedKeysGroupColumnsBuilder<'a, U256>;
fn group_columns_builder(
&self,
capacity: usize,
_data_capacity: usize,
params: &AggregatorParams,
) -> FixedKeysGroupColumnsBuilder<U256> {
FixedKeysGroupColumnsBuilder::create(capacity, params)
}
fn get_hash(&self, v: &U256) -> u64 {
v.fast_hash()
}
}
impl PolymorphicKeysHelper<HashMethodSingleString> for HashMethodSingleString {
const SUPPORT_PARTITIONED: bool = true;
type HashTable<T: Send + Sync + 'static> = ShortStringHashMap<[u8], T>;
fn create_hash_table<T: Send + Sync + 'static>(&self) -> Result<Self::HashTable<T>> {
Ok(ShortStringHashMap::new())
}
type ColumnBuilder<'a> = StringKeysColumnBuilder<'a>;
fn keys_column_builder(
&self,
capacity: usize,
value_capacity: usize,
) -> StringKeysColumnBuilder<'_> {
StringKeysColumnBuilder::create(capacity, value_capacity)
}
type KeysColumnIter = SerializedKeysColumnIter;
fn keys_iter_from_column(&self, column: &Column) -> Result<Self::KeysColumnIter> {
SerializedKeysColumnIter::create(column.as_string().ok_or_else(|| {
ErrorCode::IllegalDataType("Illegal data type for SerializedKeysColumnIter".to_string())
})?)
}
type GroupColumnsBuilder<'a> = SerializedKeysGroupColumnsBuilder<'a>;
fn group_columns_builder(
&self,
capacity: usize,
data_capacity: usize,
params: &AggregatorParams,
) -> SerializedKeysGroupColumnsBuilder<'_> {
SerializedKeysGroupColumnsBuilder::create(capacity, data_capacity, params)
}
fn get_hash(&self, v: &[u8]) -> u64 {
v.fast_hash()
}
}
impl PolymorphicKeysHelper<HashMethodSerializer> for HashMethodSerializer {
const SUPPORT_PARTITIONED: bool = true;
type HashTable<T: Send + Sync + 'static> = StringHashMap<[u8], T>;
fn create_hash_table<T: Send + Sync + 'static>(&self) -> Result<Self::HashTable<T>> {
Ok(StringHashMap::new())
}
type ColumnBuilder<'a> = StringKeysColumnBuilder<'a>;
fn keys_column_builder(
&self,
capacity: usize,
value_capacity: usize,
) -> StringKeysColumnBuilder<'_> {
StringKeysColumnBuilder::create(capacity, value_capacity)
}
type KeysColumnIter = SerializedKeysColumnIter;
fn keys_iter_from_column(&self, column: &Column) -> Result<Self::KeysColumnIter> {
SerializedKeysColumnIter::create(column.as_string().ok_or_else(|| {
ErrorCode::IllegalDataType("Illegal data type for SerializedKeysColumnIter".to_string())
})?)
}
type GroupColumnsBuilder<'a> = SerializedKeysGroupColumnsBuilder<'a>;
fn group_columns_builder(
&self,
capacity: usize,
data_capacity: usize,
params: &AggregatorParams,
) -> SerializedKeysGroupColumnsBuilder<'_> {
SerializedKeysGroupColumnsBuilder::create(capacity, data_capacity, params)
}
fn get_hash(&self, v: &[u8]) -> u64 {
v.fast_hash()
}
}
#[derive(Clone)]
pub struct PartitionedHashMethod<Method: HashMethodBounds> {
pub(crate) method: Method,
}
impl<Method: HashMethodBounds> PartitionedHashMethod<Method> {
pub fn create(method: Method) -> PartitionedHashMethod<Method> {
PartitionedHashMethod::<Method> { method }
}
pub fn convert_hashtable<T>(
method: &Method,
mut cell: HashTableCell<Method, T>,
) -> Result<HashTableCell<PartitionedHashMethod<Method>, T>>
where
T: Copy + Send + Sync + 'static,
Self: PolymorphicKeysHelper<PartitionedHashMethod<Method>>,
{
let instant = Instant::now();
let partitioned_method = Self::create(method.clone());
let mut partitioned_hashtable = partitioned_method.create_hash_table()?;
unsafe {
for item in cell.hashtable.iter() {
match partitioned_hashtable.insert_and_entry(item.key()) {
Ok(mut entry) => {
*entry.get_mut() = *item.get();
}
Err(mut entry) => {
*entry.get_mut() = *item.get();
}
};
}
}
info!(
"Convert to Partitioned HashTable elapsed: {:?}",
instant.elapsed()
);
let arena = std::mem::replace(&mut cell.arena, Area::create());
cell.arena_holders.push(ArenaHolder::create(Some(arena)));
let temp_values = cell.temp_values.to_vec();
let arena_holders = cell.arena_holders.to_vec();
let _old_dropper = cell._dropper.clone().unwrap();
let _new_dropper = PartitionedHashTableDropper::<Method, T>::create(_old_dropper);
// TODO(winter): No idea(may memory leak).
// We need to ensure that the following two lines of code are atomic.
// take_old_dropper before create new HashTableCell - may memory leak
// create new HashTableCell before take_old_dropper - may double free memory
let _old_dropper = cell._dropper.take();
let mut cell = HashTableCell::create(partitioned_hashtable, _new_dropper);
cell.temp_values = temp_values;
cell.arena_holders = arena_holders;
Ok(cell)
}
}
impl<Method: HashMethodBounds> HashMethod for PartitionedHashMethod<Method> {
type HashKey = Method::HashKey;
type HashKeyIter<'a> = Method::HashKeyIter<'a> where Self: 'a;
fn name(&self) -> String {
format!("Partitioned{}", self.method.name())
}
fn build_keys_state(
&self,
group_columns: &[(Column, DataType)],
rows: usize,
) -> Result<KeysState> {
self.method.build_keys_state(group_columns, rows)
}
fn build_keys_iter<'a>(&self, keys_state: &'a KeysState) -> Result<Self::HashKeyIter<'a>> {
self.method.build_keys_iter(keys_state)
}
}
impl<Method> PolymorphicKeysHelper<PartitionedHashMethod<Method>> for PartitionedHashMethod<Method>
where
Self: HashMethod<HashKey = Method::HashKey>,
Method: HashMethod + PolymorphicKeysHelper<Method>,
{
// Partitioned cannot be recursive
const SUPPORT_PARTITIONED: bool = false;
type HashTable<T: Send + Sync + 'static> =
PartitionedHashMap<Method::HashTable<T>, BUCKETS_LG2>;
fn create_hash_table<T: Send + Sync + 'static>(&self) -> Result<Self::HashTable<T>> {
let buckets = (1 << BUCKETS_LG2) as usize;
let mut tables = Vec::with_capacity(buckets);
for _index in 0..buckets {
tables.push(self.method.create_hash_table()?);
}
Ok(PartitionedHashMap::<_, BUCKETS_LG2>::create(tables))
}
type ColumnBuilder<'a> = Method::ColumnBuilder<'a> where Self: 'a, PartitionedHashMethod<Method>: 'a;
fn keys_column_builder(
&self,
capacity: usize,
value_capacity: usize,
) -> Self::ColumnBuilder<'_> {
self.method.keys_column_builder(capacity, value_capacity)
}
type KeysColumnIter = Method::KeysColumnIter;
fn keys_iter_from_column(&self, column: &Column) -> Result<Self::KeysColumnIter> {
self.method.keys_iter_from_column(column)
}
type GroupColumnsBuilder<'a> = Method::GroupColumnsBuilder<'a> where Self: 'a, PartitionedHashMethod<Method>: 'a;
fn group_columns_builder(
&self,
capacity: usize,
data_capacity: usize,
params: &AggregatorParams,
) -> Self::GroupColumnsBuilder<'_> {
self.method
.group_columns_builder(capacity, data_capacity, params)
}
fn get_hash(&self, v: &Method::HashKey) -> u64 {
self.method.get_hash(v)
}
}
pub trait HashMethodBounds: HashMethod + PolymorphicKeysHelper<Self> {}
impl<T: HashMethod + PolymorphicKeysHelper<T>> HashMethodBounds for T {}
|
//! A `Retry-After` header implementation for Hyper
//!
//! This crate's repo is located at https://github.com/jwilm/retry-after.
//!
//! # Examples
//!
//! ```
//! extern crate chrono;
//! extern crate retry_after;
//!
//! use chrono::{Duration, UTC};
//! use retry_after::RetryAfter;
//!
//! # fn main() {
//! // Create a RetryAfter::Delay header
//! let retry_after_delay = RetryAfter::Delay(Duration::seconds(300));
//!
//! // Create a RetryAfter::DateTime header
//! let retry_after_dt = RetryAfter::DateTime(UTC::now() + Duration::seconds(300));
//! # }
//! ```
//!
//! For more examples, please see the _examples_ directory at the crate root.
//!
extern crate chrono;
extern crate hyper;
use std::fmt;
use chrono::{UTC, TimeZone, DateTime};
use hyper::header::{Header, HeaderFormat};
/// Retry-After header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.1.3)
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum RetryAfter {
/// Retry after this duration has elapsed
///
/// This can be coupled with a response time header to produce a DateTime.
Delay(chrono::Duration),
/// Retry after the given DateTime
DateTime(chrono::DateTime<UTC>),
}
impl Header for RetryAfter {
fn header_name() -> &'static str {
"Retry-After"
}
fn parse_header(raw: &[Vec<u8>]) -> hyper::Result<RetryAfter> {
if raw.len() == 0 {
return Err(hyper::Error::Header);
}
let line = &raw[0];
let utf8_str = match ::std::str::from_utf8(line) {
Ok(utf8_str) => utf8_str,
Err(_) => return Err(hyper::Error::Header),
};
// Try and parse it as an integer, first.
if let Ok(seconds) = utf8_str.parse::<i64>() {
return Ok(RetryAfter::Delay(chrono::Duration::seconds(seconds)));
}
// Now, try and parse it as a DateTime.
if let Ok(datetime) = parse_http_date(utf8_str) {
return Ok(RetryAfter::DateTime(datetime));
}
Err(hyper::Error::Header)
}
}
impl HeaderFormat for RetryAfter {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
RetryAfter::Delay(ref duration) => {
write!(f, "{}", duration.num_seconds())
},
RetryAfter::DateTime(ref datetime) => {
// According to RFC7231, the sender of an HTTP-date must use the RFC1123 format.
// http://tools.ietf.org/html/rfc7231#section-7.1.1.1
write!(f, "{}", datetime.format(RFC1123_FMT).to_string())
}
}
}
}
static RFC850_FMT: &'static str = "%A, %d-%b-%y %T GMT";
static RFC1123_FMT: &'static str = "%a, %d %b %Y %T GMT";
static ASCTIME_FMT: &'static str = "%a %b %e %T %Y";
/// Parse an HTTP-date
///
/// HTTP/1.1 servers must return HTTP-dates using RFC1123 format for Retry-After. For compatibility
/// with HTTP/1.0 servers, RFC850 and ASCTIME formats are supported as well.
fn parse_http_date(raw: &str) -> Result<DateTime<UTC>, &'static str> {
if let Ok(dt) = UTC.datetime_from_str(raw, RFC1123_FMT) {
Ok(dt)
} else if let Ok(dt) = UTC.datetime_from_str(raw, RFC850_FMT) {
Ok(dt)
} else if let Ok(dt) = UTC.datetime_from_str(raw, ASCTIME_FMT) {
Ok(dt)
} else {
Err("Could not parse.")
}
}
#[cfg(test)]
mod tests {
extern crate httparse;
use hyper::header::{Header, Headers};
use chrono::{self, UTC, TimeZone, Duration};
use super::{RFC850_FMT, RFC1123_FMT, ASCTIME_FMT};
use super::RetryAfter;
macro_rules! test_parse_format {
($name:ident, $fmt:ident, $dt_str:expr) => {
#[test]
fn $name() {
let dt = UTC.ymd(1994, 11, 6).and_hms(8, 49, 37);
// Check that the format is what we expect
assert_eq!(dt.format($fmt).to_string(), $dt_str);
// Check that it parses correctly
assert_eq!(Ok(dt), UTC.datetime_from_str($dt_str, $fmt));
}
}
}
test_parse_format!(parse_rfc1123, RFC1123_FMT, "Sun, 06 Nov 1994 08:49:37 GMT");
test_parse_format!(parse_rfc850, RFC850_FMT, "Sunday, 06-Nov-94 08:49:37 GMT");
test_parse_format!(parse_asctime, ASCTIME_FMT, "Sun Nov 6 08:49:37 1994");
#[test]
fn header_name_regression() {
assert_eq!(RetryAfter::header_name(), "Retry-After");
}
#[test]
fn parse_delay() {
let delay_raw = [b"1234".to_vec()];
let retry_after = RetryAfter::parse_header(&delay_raw).unwrap();
assert_eq!(RetryAfter::Delay(chrono::Duration::seconds(1234)), retry_after);
}
macro_rules! test_retry_after_datetime {
($name:ident, $bytes:expr) => {
#[test]
fn $name() {
let raw = [$bytes.to_vec()];
let dt = UTC.ymd(1994, 11, 6).and_hms(8, 49, 37);
let retry_after = RetryAfter::parse_header(&raw).expect("parse_header ok");
assert_eq!(RetryAfter::DateTime(dt), retry_after);
}
}
}
test_retry_after_datetime!(header_parse_rfc1123, b"Sun, 06 Nov 1994 08:49:37 GMT");
test_retry_after_datetime!(header_parse_rfc850, b"Sunday, 06-Nov-94 08:49:37 GMT");
test_retry_after_datetime!(header_parse_asctime, b"Sun Nov 6 08:49:37 1994");
#[test]
fn hyper_headers_from_raw_delay() {
let raw = [httparse::Header {
name: "Retry-After",
value: b"300",
}];
let headers = Headers::from_raw(&raw).unwrap();
let retry_after = headers.get::<RetryAfter>().unwrap();
assert_eq!(retry_after, &RetryAfter::Delay(Duration::seconds(300)));
}
#[test]
fn hyper_headers_from_raw_datetime() {
let raw = [httparse::Header {
name: "Retry-After",
value: b"Sun, 06 Nov 1994 08:49:37 GMT",
}];
let headers = Headers::from_raw(&raw).unwrap();
let retry_after = headers.get::<RetryAfter>().unwrap();
let expected = UTC.ymd(1994, 11, 6).and_hms(8, 49, 37);
assert_eq!(retry_after, &RetryAfter::DateTime(expected));
}
}
|
use smithay::{
backend::input::{
AbsolutePositionEvent, Axis, AxisSource, ButtonState, Event, InputBackend, InputEvent,
KeyState, KeyboardKeyEvent, PointerAxisEvent, PointerButtonEvent, PointerMotionEvent,
},
input::{
keyboard::{keysyms, FilterResult},
pointer::{AxisFrame, ButtonEvent, Focus, GrabStartData, MotionEvent, RelativeMotionEvent},
},
reexports::wayland_server::protocol::wl_surface::WlSurface,
utils::{Logical, Point, SERIAL_COUNTER},
};
use crate::{
backend::UdevData,
grabs::{resize_grab::ResizeEdge, MoveSurfaceGrab, ResizeSurfaceGrab},
handlers::keybindings::{self, KeyAction},
state::Corrosion,
CorrosionConfig,
};
impl Corrosion<UdevData> {
pub fn process_input_event<I: InputBackend>(&mut self, event: InputEvent<I>) {
match event {
InputEvent::Keyboard { event, .. } => {
let serial = SERIAL_COUNTER.next_serial();
let time = Event::time_msec(&event);
let press_state = event.state();
let action = self.seat.get_keyboard().unwrap().input::<KeyAction, _>(
self,
event.key_code(),
press_state,
serial,
time,
|_, modifier, handle| {
let action: KeyAction;
if keybindings::get_mod_key_and_compare(modifier)
&& press_state == KeyState::Pressed
{
// our shitty keybindings
// TODO: get rid of this shit
let corrosion_config = CorrosionConfig::new();
let defaults = corrosion_config.get_defaults();
if handle.modified_sym() == keysyms::KEY_h | keysyms::KEY_H {
tracing::info!("running wofi");
let launcher = &defaults.launcher;
action = KeyAction::_Launcher(launcher.to_string());
} else if handle.modified_sym() == keysyms::KEY_q | keysyms::KEY_Q {
tracing::info!("Quitting");
action = KeyAction::Quit;
} else if handle.modified_sym() == keysyms::KEY_Return {
tracing::info!("spawn terminal");
let terminal = &defaults.terminal;
action = KeyAction::Spawn(terminal.to_string());
} else if handle.modified_sym() == keysyms::KEY_x | keysyms::KEY_X {
// TODO: make it so you can close windows
action = KeyAction::_CloseWindow;
} else if (keysyms::KEY_XF86Switch_VT_1..=keysyms::KEY_XF86Switch_VT_12)
.contains(&handle.modified_sym())
{
action = KeyAction::VTSwitch(
(handle.modified_sym() - keysyms::KEY_XF86Switch_VT_1 + 1)
as i32,
)
} else {
return FilterResult::Forward;
}
} else {
return FilterResult::Forward;
}
FilterResult::Intercept(action)
},
);
if let Some(action) = action {
self.parse_keybindings(action);
}
}
InputEvent::PointerMotion { event } => {
let serial = SERIAL_COUNTER.next_serial();
self.pointer_location += event.delta();
self.pointer_location = self.clamp_coords(self.pointer_location);
let surface_under = self.surface_under_pointer(&self.seat.get_pointer().unwrap());
if let Some(pointer) = self.seat.get_pointer() {
pointer.motion(
self,
surface_under.clone(),
&MotionEvent {
location: self.pointer_location,
serial,
time: event.time_msec(),
},
);
pointer.relative_motion(
self,
surface_under.clone(),
&RelativeMotionEvent {
delta: event.delta(),
delta_unaccel: event.delta_unaccel(),
utime: event.time(),
},
)
}
}
InputEvent::PointerMotionAbsolute { event, .. } => {
let serial = SERIAL_COUNTER.next_serial();
let max_x = self.space.outputs().fold(0, |acc, o| {
acc + self.space.output_geometry(o).unwrap().size.w
});
let max_h_output = self
.space
.outputs()
.max_by_key(|o| self.space.output_geometry(o).unwrap().size.h)
.unwrap();
let max_y = self.space.output_geometry(max_h_output).unwrap().size.h;
self.pointer_location.x = event.x_transformed(max_x);
self.pointer_location.y = event.y_transformed(max_y);
// clamp to screen limits
self.pointer_location = self.clamp_coords(self.pointer_location);
let under = self.surface_under_pointer(&self.seat.get_pointer().unwrap());
if let Some(ptr) = self.seat.get_pointer() {
ptr.motion(
self,
under,
&MotionEvent {
location: self.pointer_location,
serial,
time: event.time_msec(),
},
);
}
}
InputEvent::PointerButton { event, .. } => {
let pointer = self.seat.get_pointer().unwrap();
let keyboard = self.seat.get_keyboard().unwrap();
let serial = SERIAL_COUNTER.next_serial();
let button = event.button_code();
let button_state = event.state();
if ButtonState::Pressed == button_state && !pointer.is_grabbed() {
if let Some((window, _loc)) = self
.space
.element_under(pointer.current_location())
.map(|(w, l)| (w.clone(), l))
{
self.space.raise_element(&window, true);
keyboard.set_focus(
self,
Some(window.toplevel().wl_surface().clone()),
serial,
);
self.space.elements().for_each(|window| {
window.toplevel().send_configure();
});
// Check for compositor initiated move grab
if self.seat.get_keyboard().unwrap().modifier_state().logo {
let start_data = GrabStartData {
focus: None,
button,
location: pointer.current_location(),
};
let initial_window_location =
self.space.element_location(&window).unwrap();
let edges = ResizeEdge::all();
let initial_rect = &window.geometry();
match button {
0x110 => {
let move_grab = MoveSurfaceGrab {
start_data,
window,
initial_window_location,
};
pointer.set_grab(self, move_grab, serial, Focus::Clear);
}
0x111 => {
let resize_grab = ResizeSurfaceGrab::start(
start_data,
window,
edges,
*initial_rect,
);
pointer.set_grab(self, resize_grab, serial, Focus::Clear);
}
_ => (),
}
};
} else if let Some((window, _loc)) = self.surface_under_pointer(&pointer) {
keyboard.set_focus(self, Some(window), serial);
} else {
self.space.elements().for_each(|window| {
window.set_activated(false);
window.toplevel().send_configure();
});
keyboard.set_focus(self, Option::<WlSurface>::None, serial);
}
};
pointer.button(
self,
&ButtonEvent {
button,
state: button_state,
serial,
time: event.time_msec(),
},
);
}
InputEvent::PointerAxis { event, .. } => {
let source = event.source();
let horizontal_amount = event
.amount(Axis::Horizontal)
.unwrap_or_else(|| event.amount_discrete(Axis::Horizontal).unwrap() * 3.0);
let vertical_amount = event
.amount(Axis::Vertical)
.unwrap_or_else(|| event.amount_discrete(Axis::Vertical).unwrap() * 3.0);
let horizontal_amount_discrete = event.amount_discrete(Axis::Horizontal);
let vertical_amount_discrete = event.amount_discrete(Axis::Vertical);
let mut frame = AxisFrame::new(event.time_msec()).source(source);
if horizontal_amount != 0.0 {
frame = frame.value(Axis::Horizontal, horizontal_amount);
if let Some(discrete) = horizontal_amount_discrete {
frame = frame.discrete(Axis::Horizontal, discrete as i32);
}
} else if source == AxisSource::Finger {
frame = frame.stop(Axis::Horizontal);
}
if vertical_amount != 0.0 {
frame = frame.value(Axis::Vertical, vertical_amount);
if let Some(discrete) = vertical_amount_discrete {
frame = frame.discrete(Axis::Vertical, discrete as i32);
}
} else if source == AxisSource::Finger {
frame = frame.stop(Axis::Vertical);
}
self.seat.get_pointer().unwrap().axis(self, frame);
}
_ => {}
}
}
fn clamp_coords(&self, pos: Point<f64, Logical>) -> Point<f64, Logical> {
if self.space.outputs().next().is_none() {
return pos;
}
let (pos_x, pos_y) = pos.into();
let max_x = self.space.outputs().fold(0, |acc, o| {
acc + self.space.output_geometry(o).unwrap().size.w
});
let clamped_x = pos_x.max(0.0).min(max_x as f64);
let max_y = self
.space
.outputs()
.find(|o| {
let geo = self.space.output_geometry(o).unwrap();
geo.contains((clamped_x as i32, 0))
})
.map(|o| self.space.output_geometry(o).unwrap().size.h);
if let Some(max_y) = max_y {
let clamped_y = pos_y.max(0.0).min(max_y as f64);
(clamped_x, clamped_y).into()
} else {
(clamped_x, pos_y).into()
}
}
}
|
use std::error;
use std::fmt;
use std::io;
// https://github.com/CommonWA/cwa-spec/blob/master/errors.md
pub const UNKNOWN: i32 = -1;
pub const INVALID_ARGUMENT: i32 = -2;
pub const PERMISSION_DENIED: i32 = -3;
pub const NOT_FOUND: i32 = -4;
pub const EOF: i32 = -5;
/// An error abstraction, all of the following values are copied from the spec at:
/// https://github.com/CommonWA/cwa-spec/blob/master/errors.md
#[repr(i32)]
#[derive(Debug)]
pub enum Error {
Unknown = UNKNOWN,
InvalidArgument = INVALID_ARGUMENT,
PermissionDenied = PERMISSION_DENIED,
NotFound = NOT_FOUND,
EOF = EOF,
}
impl Error {
pub fn check(n: i32) -> Result<i32, Error> {
match n {
n if n >= 0 => Ok(n),
INVALID_ARGUMENT => Err(Error::InvalidArgument),
PERMISSION_DENIED => Err(Error::PermissionDenied),
NOT_FOUND => Err(Error::NotFound),
EOF => Err(Error::EOF),
_ => Err(Error::Unknown),
}
}
}
/// pretty-print the error using Debug-derived code
/// XXX(Xe): is this a mistake?
impl self::fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl self::error::Error for Error {}
pub fn check_io(error: i32) -> Result<i32, io::ErrorKind> {
match error {
n if n >= 0 => Ok(n),
INVALID_ARGUMENT => Err(io::ErrorKind::InvalidInput),
PERMISSION_DENIED => Err(io::ErrorKind::PermissionDenied),
NOT_FOUND => Err(io::ErrorKind::NotFound),
EOF => Err(io::ErrorKind::UnexpectedEof),
_ => Err(io::ErrorKind::Other),
}
}
|
use std::collections::HashMap;
use std::io;
fn solver(n: u64, p: u64, q: u64, cache: &mut HashMap<u64, u64>) -> u64 {
if n == 0 {
return 1;
}
if cache.contains_key(&n) {
return *cache.get(&n).unwrap();
}
let a_p = solver(n / p, p, q, cache);
let a_q = solver(n / q, p, q, cache);
cache.insert(n, a_p + a_q);
*cache.get(&n).unwrap()
}
fn main() {
let mut cache = HashMap::new();
let mut input = String::new();
io::stdin().read_line(&mut input).expect("error");
let input: Vec<u64> = input
.split_whitespace()
.map(|x| x.parse().unwrap())
.collect();
cache.insert(0, 1);
println!("{}", solver(input[0], input[1], input[2], &mut cache));
}
|
use game::{MAX_MOVES, Game};
pub struct Solver {
game: Game,
min_dist: i32
// TODO priority queue
}
impl Solver {
pub fn new(game: Game) -> Solver {
Solver {
game,
min_dist: MAX_MOVES
}
}
} |
use crate::window::{Window, Geometry};
use crate::stack::Stack;
use std::fmt::Debug;
mod fullscreen;
mod tall;
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Layout {
Tall,
FullScreen,
}
impl Layout {
pub fn handle_layout<W>(&self, view: &Geometry, windows: Stack<Window<W>>) -> Stack<Window<W>> {
match self {
Layout::Tall => tall::handle_layout(view, windows),
Layout::FullScreen => fullscreen::handle_layout(view, windows),
}
}
}
impl From<&str> for Layout {
fn from(display: &str) -> Self {
match display {
"tall" => Layout::Tall,
"fullscreen" => Layout::FullScreen,
_ => panic!("Invalid layout {}", display)
}
}
}
|
use std::sync::Arc;
use sqlx::mysql::*;
use sqlx::Pool;
pub async fn new_connection_pool() -> sqlx::Result<Arc<Pool<MySql>>> {
let pool = MySqlPoolOptions::new()
.max_connections(5)
.connect("mysql://root:rootpassword@localhost:3306").await?;
Ok(Arc::new(pool ))
} |
pub trait Form {
fn html(&self) -> Vec<u8>;
} |
use std::collections::HashMap;
fn main() {
let lines = include_str!("input.txt").lines().collect::<Vec<_>>();
println!("Day 3 part 1: {}", overlapper(&lines[..]));
println!("Day 3 part 2: {}", not_overlapper(&lines[..]).unwrap().id);
}
struct Spec {
id: u32,
start: (u32, u32),
size: (u32, u32)
}
fn spec_parser(spec_string: &str) -> Spec {
let numbers = spec_string.split(['#', '@', ',', ':', 'x'].as_ref()).skip(1)
.map(|s| -> u32 {s.trim().parse().unwrap()}).collect::<Vec<_>>();
return match numbers.as_slice() {
[id, start_x, start_y, size_x, size_y] => Ok(Spec { id: *id, start: (*start_x, *start_y), size: (*size_x, *size_y)}),
_ => Err("Could not parse spec")
}.unwrap()
}
fn cells(spec: &Spec) -> Vec<(u32, u32)> {
let mut vector = Vec::new();
for x in spec.start.0..spec.start.0 + spec.size.0 {
for y in spec.start.1..spec.start.1 + spec.size.1 {
vector.push((x, y));
}
}
vector
}
fn gridder(spec_strings: &[&str]) -> HashMap<(u32, u32), usize> {
let mut claimed = HashMap::new();
for spec_string in spec_strings {
let spec = spec_parser(spec_string);
for cell in cells(&spec) {
match claimed.get(&cell) {
Some(&num) => claimed.insert(cell, num + 1),
_ => claimed.insert(cell, 1)
};
}
}
claimed
}
fn overlapper(spec_strings: &[&str]) -> usize {
let claimed = gridder(spec_strings);
let mut num_overlapped: usize = 0;
for (_cell, num) in claimed {
if num > 1 {
num_overlapped += 1
}
}
num_overlapped
}
fn not_overlapper(spec_strings: &[&str]) -> Option<Spec> {
let claimed = gridder(spec_strings);
for spec_string in spec_strings {
let spec = spec_parser(spec_string);
if cells(&spec).iter().all(|cell| claimed.get(cell).unwrap_or(&0) <= &1) {
return Some(spec);
}
}
None
}
#[test]
fn given_zeros_spec_gives_zeros() {
let spec = spec_parser(&"#0 @ 0,0: 0x0");
assert_eq!(spec.id, 0);
assert_eq!(spec.start, (0, 0));
assert_eq!(spec.size, (0, 0));
}
#[test]
fn given_nonzero_single_digit_id() {
assert_eq!(spec_parser(&"#1 @ 0,0: 0x0").id, 1);
}
#[test]
fn given_nonzero_multi_digit_id() {
assert_eq!(spec_parser(&"#123 @ 0,0: 0x0").id, 123);
}
#[test]
fn given_nonzero_multi_digit_start_x() {
assert_eq!(spec_parser(&"#123 @ 456,0: 0x0").start.0, 456);
}
#[test]
fn given_nonzero_multi_digit_start_y() {
assert_eq!(spec_parser(&"#123 @ 456,789: 0x0").start.1, 789);
}
#[test]
fn given_nonzero_multi_digit_size_x() {
assert_eq!(spec_parser(&"#123 @ 456,789: 123x0").size.0, 123);
}
#[test]
fn given_nonzero_multi_digit_size_y() {
assert_eq!(spec_parser(&"#123 @ 456,789: 123x456").size.1, 456);
}
#[test]
fn cells_given_1x1_at_0_0() {
assert_eq!(cells(&Spec { id: 0, start: (0, 0), size: (1, 1)}), vec![(0, 0)])
}
#[test]
fn cells_given_2x2_at_0_0() {
let c = cells(&Spec { id: 0, start: (0, 0), size: (2, 2)});
assert!(c.contains(&(0, 0)));
assert!(c.contains(&(0, 1)));
assert!(c.contains(&(1, 0)));
assert!(c.contains(&(1, 1)));
}
#[test]
fn cells_given_1x1_at_1_3() {
assert_eq!(cells(&Spec { id: 0, start: (1, 3), size: (1, 1)}), vec![(1, 3)]);
}
#[test]
fn overlapper_given_example() {
assert_eq!(overlapper(&["#1 @ 1,3: 4x4", "#2 @ 3,1: 4x4", "#3 @ 5,5: 2x2"]), 4);
}
#[test]
fn not_overlapper_given_example() {
assert_eq!(not_overlapper(&["#1 @ 1,3: 4x4", "#2 @ 3,1: 4x4", "#3 @ 5,5: 2x2"]).unwrap().id, 3);
}
// working, but worse
#[allow(dead_code)]
fn spec_parser_first_attempt(spec_string: &str) -> Spec {
let mut whitespace_split = spec_string.split_whitespace();
let id = whitespace_split.next().unwrap().chars().skip(1).collect::<String>().to_string().parse().unwrap();
let rest_of_string = whitespace_split.collect::<String>().to_string();
let mut string_iter = rest_of_string.chars();
let start_x = string_iter.by_ref().skip_while(|c| *c != '@').skip(1).take_while(|c| *c != ',').collect::<String>().parse().unwrap();
let start_y = string_iter.by_ref().take_while(|c| *c != ':').collect::<String>().parse().unwrap();
let size_x = string_iter.by_ref().take_while(|c| *c != 'x').collect::<String>().parse().unwrap();
let size_y = string_iter.by_ref().collect::<String>().parse().unwrap();
Spec {
id: id,
start: (start_x, start_y),
size: (size_x, size_y)
}
}
#[allow(dead_code)]
fn spec_parser_second_attempt(spec_string: &str) -> Spec {
let mut parts = spec_string.split(['#', '@', ',', ':', 'x'].as_ref()).skip(1);
let id = parts.next().unwrap().trim().parse().unwrap();
let start_x = parts.next().unwrap().trim().parse().unwrap();
let start_y = parts.next().unwrap().trim().parse().unwrap();
let size_x = parts.next().unwrap().trim().parse().unwrap();
let size_y = parts.next().unwrap().trim().parse().unwrap();
Spec {
id: id,
start: (start_x, start_y),
size: (size_x, size_y)
}
} |
#[doc = "Reader of register AHBRSTR"]
pub type R = crate::R<u32, super::AHBRSTR>;
#[doc = "Writer for register AHBRSTR"]
pub type W = crate::W<u32, super::AHBRSTR>;
#[doc = "Register AHBRSTR `reset()`'s with value 0"]
impl crate::ResetValue for super::AHBRSTR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `FSMCRST`"]
pub type FSMCRST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FSMCRST`"]
pub struct FSMCRST_W<'a> {
w: &'a mut W,
}
impl<'a> FSMCRST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Reader of field `DMA2RST`"]
pub type DMA2RST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMA2RST`"]
pub struct DMA2RST_W<'a> {
w: &'a mut W,
}
impl<'a> DMA2RST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Reader of field `DMA1RST`"]
pub type DMA1RST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMA1RST`"]
pub struct DMA1RST_W<'a> {
w: &'a mut W,
}
impl<'a> DMA1RST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `FLITFRST`"]
pub type FLITFRST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FLITFRST`"]
pub struct FLITFRST_W<'a> {
w: &'a mut W,
}
impl<'a> FLITFRST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Reader of field `CRCRST`"]
pub type CRCRST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CRCRST`"]
pub struct CRCRST_W<'a> {
w: &'a mut W,
}
impl<'a> CRCRST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `GPIOGRST`"]
pub type GPIOGRST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `GPIOGRST`"]
pub struct GPIOGRST_W<'a> {
w: &'a mut W,
}
impl<'a> GPIOGRST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `GPIOFRST`"]
pub type GPIOFRST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `GPIOFRST`"]
pub struct GPIOFRST_W<'a> {
w: &'a mut W,
}
impl<'a> GPIOFRST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `GPIOHRST`"]
pub type GPIOHRST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `GPIOHRST`"]
pub struct GPIOHRST_W<'a> {
w: &'a mut W,
}
impl<'a> GPIOHRST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `GPIOERST`"]
pub type GPIOERST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `GPIOERST`"]
pub struct GPIOERST_W<'a> {
w: &'a mut W,
}
impl<'a> GPIOERST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `GPIODRST`"]
pub type GPIODRST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `GPIODRST`"]
pub struct GPIODRST_W<'a> {
w: &'a mut W,
}
impl<'a> GPIODRST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `GPIOCRST`"]
pub type GPIOCRST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `GPIOCRST`"]
pub struct GPIOCRST_W<'a> {
w: &'a mut W,
}
impl<'a> GPIOCRST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `GPIOBRST`"]
pub type GPIOBRST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `GPIOBRST`"]
pub struct GPIOBRST_W<'a> {
w: &'a mut W,
}
impl<'a> GPIOBRST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `GPIOARST`"]
pub type GPIOARST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `GPIOARST`"]
pub struct GPIOARST_W<'a> {
w: &'a mut W,
}
impl<'a> GPIOARST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 30 - FSMC reset"]
#[inline(always)]
pub fn fsmcrst(&self) -> FSMCRST_R {
FSMCRST_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 25 - DMA2 reset"]
#[inline(always)]
pub fn dma2rst(&self) -> DMA2RST_R {
DMA2RST_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 24 - DMA1 reset"]
#[inline(always)]
pub fn dma1rst(&self) -> DMA1RST_R {
DMA1RST_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 15 - FLITF reset"]
#[inline(always)]
pub fn flitfrst(&self) -> FLITFRST_R {
FLITFRST_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 12 - CRC reset"]
#[inline(always)]
pub fn crcrst(&self) -> CRCRST_R {
CRCRST_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 7 - IO port G reset"]
#[inline(always)]
pub fn gpiogrst(&self) -> GPIOGRST_R {
GPIOGRST_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 6 - IO port F reset"]
#[inline(always)]
pub fn gpiofrst(&self) -> GPIOFRST_R {
GPIOFRST_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 5 - IO port H reset"]
#[inline(always)]
pub fn gpiohrst(&self) -> GPIOHRST_R {
GPIOHRST_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 4 - IO port E reset"]
#[inline(always)]
pub fn gpioerst(&self) -> GPIOERST_R {
GPIOERST_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 3 - IO port D reset"]
#[inline(always)]
pub fn gpiodrst(&self) -> GPIODRST_R {
GPIODRST_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 2 - IO port C reset"]
#[inline(always)]
pub fn gpiocrst(&self) -> GPIOCRST_R {
GPIOCRST_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1 - IO port B reset"]
#[inline(always)]
pub fn gpiobrst(&self) -> GPIOBRST_R {
GPIOBRST_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0 - IO port A reset"]
#[inline(always)]
pub fn gpioarst(&self) -> GPIOARST_R {
GPIOARST_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 30 - FSMC reset"]
#[inline(always)]
pub fn fsmcrst(&mut self) -> FSMCRST_W {
FSMCRST_W { w: self }
}
#[doc = "Bit 25 - DMA2 reset"]
#[inline(always)]
pub fn dma2rst(&mut self) -> DMA2RST_W {
DMA2RST_W { w: self }
}
#[doc = "Bit 24 - DMA1 reset"]
#[inline(always)]
pub fn dma1rst(&mut self) -> DMA1RST_W {
DMA1RST_W { w: self }
}
#[doc = "Bit 15 - FLITF reset"]
#[inline(always)]
pub fn flitfrst(&mut self) -> FLITFRST_W {
FLITFRST_W { w: self }
}
#[doc = "Bit 12 - CRC reset"]
#[inline(always)]
pub fn crcrst(&mut self) -> CRCRST_W {
CRCRST_W { w: self }
}
#[doc = "Bit 7 - IO port G reset"]
#[inline(always)]
pub fn gpiogrst(&mut self) -> GPIOGRST_W {
GPIOGRST_W { w: self }
}
#[doc = "Bit 6 - IO port F reset"]
#[inline(always)]
pub fn gpiofrst(&mut self) -> GPIOFRST_W {
GPIOFRST_W { w: self }
}
#[doc = "Bit 5 - IO port H reset"]
#[inline(always)]
pub fn gpiohrst(&mut self) -> GPIOHRST_W {
GPIOHRST_W { w: self }
}
#[doc = "Bit 4 - IO port E reset"]
#[inline(always)]
pub fn gpioerst(&mut self) -> GPIOERST_W {
GPIOERST_W { w: self }
}
#[doc = "Bit 3 - IO port D reset"]
#[inline(always)]
pub fn gpiodrst(&mut self) -> GPIODRST_W {
GPIODRST_W { w: self }
}
#[doc = "Bit 2 - IO port C reset"]
#[inline(always)]
pub fn gpiocrst(&mut self) -> GPIOCRST_W {
GPIOCRST_W { w: self }
}
#[doc = "Bit 1 - IO port B reset"]
#[inline(always)]
pub fn gpiobrst(&mut self) -> GPIOBRST_W {
GPIOBRST_W { w: self }
}
#[doc = "Bit 0 - IO port A reset"]
#[inline(always)]
pub fn gpioarst(&mut self) -> GPIOARST_W {
GPIOARST_W { w: self }
}
}
|
/*
* Advent of Code 2019 - Day 1
*
* --- Part One ---
* The Elves quickly load you into a spacecraft and prepare to launch.
*
* At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of
* fuel required yet.
* Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module,
* take its mass, divide by three, round down, and subtract 2.
*
* For example:
*
* For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
* For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
* For a mass of 1969, the fuel required is 654.
* For a mass of 100756, the fuel required is 33583.
* The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed
* for the mass of each module (your puzzle input), then add together all the fuel values.
*
* What is the sum of the fuel requirements for all of the modules on your spacecraft?
*
* To begin, get your puzzle input [see input.txt].
*
* --- Part Two ---
* During the second Go / No Go poll, the Elf in charge of the Rocket Equation Double-Checker stops the launch sequence.
* Apparently, you forgot to include additional fuel for the fuel you just added.
*
* Fuel itself requires fuel just like a module - take its mass, divide by three, round down, and subtract 2. However,
* that fuel also requires fuel, and that fuel requires fuel, and so on. Any mass that would require negative fuel
* should instead be treated as if it requires zero fuel; the remaining mass, if any, is instead handled by wishing
* really hard, which has no mass and is outside the scope of this calculation.
*
* So, for each module mass, calculate its fuel and add it to the total.
* Then, treat the fuel amount you just calculated as the input mass and repeat the process, continuing until a fuel
* requirement is zero or negative. For example:
*
* A module of mass 14 requires 2 fuel. This fuel requires no further fuel (2 divided by 3 and rounded down is 0, which
* would call for a negative fuel), so the total fuel required is still just 2.
* At first, a module of mass 1969 requires 654 fuel. Then, this fuel requires 216 more fuel (654 / 3 - 2). 216 then
* requires 70 more fuel, which requires 21 fuel, which requires 5 fuel, which requires no further fuel. So, the total
* fuel required for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966.
* The fuel required by a module of mass 100756 and its fuel is:
* 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346.
*
* What is the sum of the fuel requirements for all of the modules on your spacecraft when also taking into account the
* mass of the added fuel? (Calculate the fuel requirements for each module separately, then add them all up at the end.)
*/
/*
* Learning Rust
*
* Printing - https://doc.rust-lang.org/stable/rust-by-example/hello/print.html
* Comments - https://doc.rust-lang.org/stable/rust-by-example/hello/comment.html
* Functions - https://doc.rust-lang.org/stable/rust-by-example/fn.html
* Closures - https://doc.rust-lang.org/rust-by-example/fn/closures.html
* File I/O - https://doc.rust-lang.org/stable/rust-by-example/std_misc/file/open.html
* Iterators - https://doc.rust-lang.org/std/iter/trait.Iterator.html
* Collections - https://doc.rust-lang.org/std/collections/index.html
* Result - https://doc.rust-lang.org/std/result/
* Option and Unwrap - https://doc.rust-lang.org/stable/rust-by-example/error/option_unwrap.html
*/
use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
fn lines_from_file(path: impl AsRef<Path>) -> Vec<String> {
// Learning Rust: match is an expression
let file = match File::open(path) {
Err(why) => panic!("Failed to open file: {}", why.description()),
Ok(file) => file,
};
let reader = BufReader::new(file);
// Learning Rust: lines returns an iterator over all lines; collect turns the iter into a collection
// Learning Rust: 'Result' must be handled - unwrap, expect, match or ?
// Learning Rust: return by omitting ';'
reader.lines()
.map(|line| line.expect("Could not parse line"))
.collect()
}
fn strings_to_ints(strings: Vec<String>) -> Vec<i32> {
// Learning Rust: turbofish syntax to help determine type
strings.iter().map(|string| string.parse::<i32>().unwrap()).collect()
}
fn parse_inputs(path: impl AsRef<Path>) -> Vec<i32> {
strings_to_ints(lines_from_file(path))
}
fn calculate_fuel(mass: i32) -> i32 {
mass / 3 - 2
}
fn calculate_fuel_recursive(fuel_mass: i32) -> i32 {
let recursive_fuel_mass = calculate_fuel(fuel_mass);
if recursive_fuel_mass < 0 { return fuel_mass };
fuel_mass + calculate_fuel_recursive(recursive_fuel_mass)
}
/*
* Main -
* Load input file
* Parse input file - one module mass per line
* For each module mass, calculate fuel
* fuel per module = floor(module mass / 3) - 2
* Sum all calculated fuel
*/
fn main() {
let inputs_filename = "input.txt";
let masses = parse_inputs(inputs_filename);
// --- Part One ---
let test_case_inputs = vec![12, 14, 1969, 100756];
let test_case_results = vec![2, 2, 654, 33583];
println!("Calculating total test case fuel requirements (non-recursive)...");
for it in test_case_inputs.iter().zip(test_case_results.iter()) {
let (input, result) = it;
let calc = calculate_fuel(*input);
let pass = calc - result == 0;
// Learning Rust: ternary
println!("- {} - For a mass of {}, got {} / {}", (if pass { "PASS" } else { "FAIL "}), input, calc, *result);
}
println!();
let fuel_per_mass: Vec<i32> = masses.iter().map(|it| calculate_fuel(*it)).collect();
let fuel_total: i32 = fuel_per_mass.iter().sum();
println!("Calculated fuel total (non-recursive): {}\n", fuel_total);
// --- Part Two ---
let test_case_results_recursive = vec![2, 2, 966, 50346];
println!("Calculating total test case fuel requirements (recursive)...");
for it in test_case_inputs.iter().zip(test_case_results_recursive.iter()) {
let (input, result) = it;
let calc = calculate_fuel_recursive(calculate_fuel(*input));
let pass = calc - result == 0;
// Learning Rust: ternary
println!("- {} - For a mass of {}, got {} / {}", (if pass { "PASS" } else { "FAIL "}), input, calc, *result);
}
println!();
let fuel_per_mass_recursive: Vec<i32> = masses.iter().map(|it| calculate_fuel_recursive(calculate_fuel(*it))).collect();
let fuel_total_recursive: i32 = fuel_per_mass_recursive.iter().sum();
println!("Calculated fuel total (recursive): {}", fuel_total_recursive);
} |
pub trait SessionApplication {
fn set_windowmanager();
fn set_config();
fn startup();
fn load_enviromentsettings();
fn load_keyboardsettings();
fn load_mousesettings();
}
|
//! Eval utilities
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use crate::{errors::OnChainError, Memory};
use bigint::{Gas, M256, U256};
#[cfg(not(feature = "std"))]
use core::cmp::min;
#[cfg(feature = "std")]
use std::cmp::min;
pub fn l64(gas: Gas) -> Gas {
gas - gas / Gas::from(64u64)
}
pub fn check_range(start: U256, len: U256) -> Result<(), OnChainError> {
if M256::from(start) + M256::from(len) < M256::from(start) {
Err(OnChainError::InvalidRange)
} else {
Ok(())
}
}
pub fn copy_from_memory<M: Memory>(memory: &M, start: U256, len: U256) -> Vec<u8> {
let mut result: Vec<u8> = Vec::new();
let mut i = start;
while i < start + len {
result.push(memory.read_raw(i));
i = i + U256::from(1u64);
}
result
}
pub fn copy_into_memory<M: Memory>(memory: &mut M, values: &[u8], start: U256, value_start: U256, len: U256) {
let value_len = U256::from(values.len());
let mut i = start;
let mut j = value_start;
while i < start + len {
if j < value_len {
let ju: usize = j.as_usize();
memory.write_raw(i, values[ju]).unwrap();
j = j + U256::from(1u64);
} else {
memory.write_raw(i, 0u8).unwrap();
}
i = i + U256::from(1u64);
}
}
pub fn copy_into_memory_apply<M: Memory>(memory: &mut M, values: &[u8], start: U256, len: U256) {
let value_len = U256::from(values.len());
let actual_len = min(len, value_len);
let mut i = start;
let mut j = 0;
while i < start + actual_len {
memory.write_raw(i, values[j]).unwrap();
i = i + U256::from(1u64);
j += 1;
}
}
|
fn main() {
delimit("creating a new vector (rare)");
let v: Vec<i32> = Vec::new();
println!("{:?}", v);
delimit("creating a vector more common (with `vec!` macro)");
let mut v = vec![1, 2, 3];
println!("{:?}", v);
for i in 4..10 {
v.push(i);
}
delimit("reading elements in a vector");
// 1. indexing syntax
let third: &i32 = &v[2];
println!("the third element is {} (using indexing)", third);
// 2. get method (this gives us an `Option<&T>`)
match v.get(2) {
Some(third) => println!("the third element is {} (using get)", third),
None => println!("there is no third element (using get method)"),
}
let v = vec![1, 2, 3, 4, 5, 6];
let does_not_exist = v.get(100);
println!(
"attempting to access the 100th indexed value {:?}",
does_not_exist
);
// results in panic
//let does_not_exist = &v[100];
//println!("attempting to access the 100th indexed value {}", does_not_exist);
let mut v = vec![1, 2, 3, 4, 5, 6];
let first = v[0];
v.push(6);
println!("the first element is: {}", first);
delimit("iterating over values in a a vector");
let v = vec![100, 32, 57];
for i in &v {
println!("{}", i);
}
delimit("using an enum to store multiple types (like a named tuple w/ type checking)");
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from("foobar")),
SpreadsheetCell::Float(10.12),
];
println!("spreadsheet row: {:#?}", row);
delimit("appending to a string");
let mut s1 = String::from("foo");
let s2 = "bar";
s1.push_str(s2);
println!("s1 is {}", s1);
println!("s2 is {}", s2);
delimit("appending a single character to a string");
let mut s1 = String::from("foo");
s1.push('l'); // single quote
println!("{}", s1); // "fool"
delimit("concatenation with the + operator or the format! macro");
let s1 = String::from("Hello, ");
let s2 = String::from("word!");
let s3 = s1 + &s2;
println!("concatenation using + (with s1 moved): {}", s3);
delimit("string slicing (avoid indexing into string)");
let hello = "Здравствуйте";
let s = &hello[0..4];
println!("s: {}", s); // Зд (because each of those chars is two bytes)
delimit("### hash maps ###");
delimit("creating a new hash map");
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("blue"), 10);
scores.insert(String::from("yellow"), 50);
println!("current scores: {:#?}", scores);
delimit("construct hash map from vector");
let teams = vec![String::from("blue"), String::from("yellow")];
let initial_scores = vec![10, 50];
// `collect` can collect into any number of dat structures, so a type annotation is needed here
let scores: HashMap<_, _> = teams.into_iter().zip(initial_scores.into_iter()).collect();
println!("current scores: {:#?}", scores);
delimit("ownership");
delimit("values that implement the `Copy` trait are copied");
let field_name = String::from("favorite color");
let field_value = String::from("blue");
let mut map = HashMap::new();
map.insert(field_name, field_value);
println!("map: {:#?}", map);
delimit("values that don't implement the `Copy` trait are moved");
delimit("accessing values in a hash map");
let mut scores = HashMap::new();
scores.insert(String::from("blue"), 10);
scores.insert(String::from("yellow"), 50);
let team_name = String::from("blue");
println!("team score: {}", scores.get(&team_name).unwrap());
delimit("iterating over the key-value pairs");
for (team, score) in &scores {
println!("team {}: {}", team, score);
}
delimit("updating a map");
println!("overwrite an existing value");
scores.insert(String::from("blue"), 10);
scores.insert(String::from("blue"), 25);
let team = String::from("blue");
println!(
"overwriting an existing value: {}",
scores.get(&team).unwrap()
);
delimit("inserting a value only if key doesn't already exist using `or_insert`");
scores = HashMap::new();
scores.insert(String::from("blue"), 10);
scores.entry(String::from("yellow")).or_insert(50);
scores.entry(String::from("blue")).or_insert(50);
println!("{:?}", scores);
delimit("updating a value based on old value");
let text = "hello world wonderful world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
}
fn delimit(msg: &str) {
println!("\n--- {} ---", msg);
}
#[derive(Debug)]
enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
|
extern crate sdl2;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use crate::grid::Grid;
use crate::renderer::Renderer;
use crate::row::Row;
use crate::events;
use crate::cell::Cell;
#[allow(dead_code)]
const BLACK: sdl2::pixels::Color = Color::RGB(0, 0, 0);
const WHITE: sdl2::pixels::Color = Color::RGB(255, 255, 255);
const RED: sdl2::pixels::Color = Color::RGB(255, 0, 0);
const ORANGE: sdl2::pixels::Color = Color::RGB(253, 166, 47);
const BLUE: sdl2::pixels::Color = Color::RGB(0, 0, 255);
pub struct Sdl2Renderer {
rows: usize,
cell_width: u32,
cell_height: u32,
canvas: sdl2::render::WindowCanvas,
event_pump: sdl2::EventPump,
previous_rows: Vec<Row>,
}
impl Sdl2Renderer {
pub fn new(
title: &str,
width: u32,
height: u32,
rows: usize,
cell_width: u32,
cell_height: u32,
) -> Result<Sdl2Renderer, String> {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let window = video_subsystem
.window(title, width, height)
.position_centered()
.opengl()
.build()
.map_err(|e| e.to_string())?;
let mut canvas = window.into_canvas().build().map_err(|e| e.to_string())?;
canvas.set_draw_color(Color::RGB(0, 0, 0));
canvas.clear();
let event_pump = sdl_context.event_pump()?;
Ok(Sdl2Renderer {
rows: rows,
cell_height: cell_height,
cell_width: cell_width,
canvas: canvas,
event_pump: event_pump,
previous_rows: Vec::new(),
})
}
fn render_cell(&mut self, cell: Cell, col: usize, row: usize) {
if cell.value == 1 {
self.canvas.set_draw_color(BLUE);
match self.canvas.fill_rect(sdl2::rect::Rect::new(
(self.cell_width as i32) * (col as i32),
(self.cell_height as i32) * (row as i32),
self.cell_width,
self.cell_height,
)) {
Err(e) => panic!("Error rendering rect: {}", e),
_ => {}
}
} else if cell.value == 2 {
self.canvas.set_draw_color(RED);
match self.canvas.fill_rect(sdl2::rect::Rect::new(
(self.cell_width as i32) * (col as i32),
(self.cell_height as i32) * (row as i32),
self.cell_width,
self.cell_height,
)) {
Err(e) => panic!("Error rendering rect: {}", e),
_ => {}
}
} else if cell.value == 3 {
self.canvas.set_draw_color(ORANGE);
match self.canvas.fill_rect(sdl2::rect::Rect::new(
(self.cell_width as i32) * (col as i32),
(self.cell_height as i32) * (row as i32),
self.cell_width,
self.cell_height,
)) {
Err(e) => panic!("Error rendering rect: {}", e),
_ => {}
}
}
}
}
impl Renderer for Sdl2Renderer {
fn render(&mut self, row: &Row) {
self.previous_rows.push(row.clone());
if self.previous_rows.len() >= self.rows {
self.previous_rows.remove(0);
}
for row in 0..self.previous_rows.len() {
for col in 0..self.previous_rows[row].cells.len() {
self.render_cell(self.previous_rows[row].cells[col], col, row);
}
}
}
fn render_grid(&mut self, grid: &Grid) {
for row in grid.rows.iter().enumerate() {
for cell in row.1.cells.iter().enumerate() {
self.render_cell(*cell.1, cell.0, row.0);
}
}
}
fn get_events(&mut self) -> Vec<events::Event>
{
let mut events : Vec<events::Event> = Vec::new();
for event in self.event_pump.poll_iter() {
match event {
Event::Quit { .. }
| Event::KeyDown {
keycode: Some(Keycode::Escape),
..
} => events.push(events::Event::QUIT),
Event::KeyDown {
keycode: Some(Keycode::P),
..
} => events.push(events::Event::PAUSE),
_ => {}
}
}
events
}
fn begin_render(&mut self) -> bool {
self.canvas.set_draw_color(BLACK);
self.canvas.clear();
false
}
fn end_render(&mut self) {
self.canvas.present();
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::sync::Arc;
use spin::Mutex;
use alloc::collections::btree_map::BTreeMap;
use alloc::string::String;
use alloc::string::ToString;
use core::any::Any;
use core::ops::Deref;
use super::super::super::qlib::common::*;
use super::super::super::qlib::linux_def::*;
use super::super::super::qlib::auth::*;
use super::super::super::qlib::device::*;
use super::super::super::qlib::task_mgr::*;
use super::super::super::fs::fsutil::file::*;
use super::super::super::fs::dentry::*;
use super::super::super::task::*;
use super::super::super::kernel::kernel::*;
use super::super::super::kernel::waiter::*;
use super::super::host::hostinodeop::*;
use super::super::attr::*;
use super::super::file::*;
use super::super::flags::*;
use super::super::dirent::*;
use super::super::mount::*;
use super::super::inode::*;
use super::super::ramfs::dir::*;
use super::super::ramfs::symlink::*;
use super::super::super::threadmgr::pid_namespace::*;
use super::inode::*;
use super::symlink_proc::*;
use super::dir_proc::*;
use super::sys::sys::*;
use super::uptime::*;
use super::cpuinfo::*;
use super::filesystems::*;
use super::loadavg::*;
use super::mounts::*;
use super::stat::*;
pub struct ProcNodeInternal {
pub kernel: Kernel,
pub pidns: PIDNamespace,
pub cgroupControllers: Arc<Mutex<BTreeMap<String, String>>>,
}
#[derive(Clone)]
pub struct ProcNode(Arc<Mutex<ProcNodeInternal>>);
impl Deref for ProcNode {
type Target = Arc<Mutex<ProcNodeInternal>>;
fn deref(&self) -> &Arc<Mutex<ProcNodeInternal>> {
&self.0
}
}
impl DirDataNode for ProcNode {
fn Lookup(&self, d: &Dir, task: &Task, dir: &Inode, name: &str) -> Result<Dirent> {
let err = match d.Lookup(task, dir, name) {
Ok(dirent) => return Ok(dirent),
Err(e) => e,
};
let tid = match name.parse::<i32>() {
Ok(tid) => tid,
_ => return Err(err)
};
let otherThread = match self.lock().pidns.TaskWithID(tid) {
None => return Err(err),
Some(t) => t,
};
let otherTask = TaskId::New(otherThread.lock().taskId).GetTask();
let ms = dir.lock().MountSource.clone();
let td = self.NewTaskDir(&otherTask, &otherThread, &ms, true);
return Ok(Dirent::New(&td, name))
}
fn GetFile(&self, d: &Dir, _task: &Task, _dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> {
let p = DirNode {
dir: d.clone(),
data: self.clone()
};
return Ok(File::New(dirent, &flags, RootProcFile{
iops: p,
}))
}
}
pub fn NewProc(task: &Task, msrc: &Arc<Mutex<MountSource>>, cgroupControllers: BTreeMap<String, String>) -> Inode {
let mut contents = BTreeMap::new();
let kernel = GetKernel();
let pidns = kernel.RootPIDNamespace();
contents.insert("cpuinfo".to_string(), NewCPUInfo(task, msrc));
contents.insert("filesystems".to_string(), NewFileSystem(task, msrc));
contents.insert("loadavg".to_string(), NewLoadAvg(task, msrc));
contents.insert("mounts".to_string(), NewMounts(task, msrc));
contents.insert("self".to_string(), NewProcessSelf(task, &pidns, msrc));
contents.insert("stat".to_string(), NewStatData(task, msrc));
contents.insert("thread-self".to_string(), NewThreadSelf(task, &pidns, msrc));
contents.insert("uptime".to_string(), NewUptime(task, msrc));
contents.insert("sys".to_string(), NewSys(task, msrc));
let iops = Dir::New(task, contents, &ROOT_OWNER, &FilePermissions::FromMode(FileMode(0o0555)));
let kernel = GetKernel();
let pidns = kernel.RootPIDNamespace();
let proc = ProcNodeInternal {
kernel: kernel,
pidns: pidns,
cgroupControllers: Arc::new(Mutex::new(cgroupControllers)),
};
let p = DirNode {
dir: iops,
data: ProcNode(Arc::new(Mutex::new(proc)))
};
return NewProcInode(&Arc::new(p), msrc, InodeType::SpecialDirectory, None)
}
pub struct ProcessSelfNode {
pub pidns: PIDNamespace,
}
impl ReadLinkNode for ProcessSelfNode {
fn ReadLink(&self, _link: &Symlink, task: &Task, _dir: &Inode) -> Result<String> {
let thread = task.Thread();
let tg = thread.ThreadGroup();
let tgid = self.pidns.IDOfThreadGroup(&tg);
let str = format!("{}", tgid);
return Ok(str)
}
fn GetLink(&self, link: &Symlink, task: &Task, dir: &Inode) -> Result<Dirent> {
return link.GetLink(task, dir);
}
}
pub fn NewProcessSelf(task: &Task, pidns: &PIDNamespace, msrc: &Arc<Mutex<MountSource>>) -> Inode {
let node = ProcessSelfNode {
pidns: pidns.clone(),
};
return SymlinkNode::New(task, msrc, node, None)
}
pub struct ThreadSelfNode {
pub pidns: PIDNamespace,
}
impl ReadLinkNode for ThreadSelfNode {
fn ReadLink(&self, _link: &Symlink, task: &Task, _dir: &Inode) -> Result<String> {
let thread = task.Thread();
let tg = thread.ThreadGroup();
let tgid = self.pidns.IDOfThreadGroup(&tg);
let tid = self.pidns.IDOfTask(&thread);
let str = format!("{}/task/{}", tgid, tid);
return Ok(str)
}
fn GetLink(&self, link: &Symlink, task: &Task, dir: &Inode) -> Result<Dirent> {
return link.GetLink(task, dir);
}
}
pub fn NewThreadSelf(task: &Task, pidns: &PIDNamespace, msrc: &Arc<Mutex<MountSource>>) -> Inode {
let node = ThreadSelfNode {
pidns: pidns.clone(),
};
return SymlinkNode::New(task, msrc, node, None)
}
pub struct RootProcFile {
pub iops: DirNode<ProcNode>,
}
impl Waitable for RootProcFile {}
impl SpliceOperations for RootProcFile {}
impl FileOperations for RootProcFile {
fn as_any(&self) -> &Any {
return self
}
fn FopsType(&self) -> FileOpsType {
return FileOpsType::RootProcFile
}
fn Seekable(&self) -> bool {
return true;
}
fn Seek(&self, task: &Task, f: &File, whence: i32, current: i64, offset: i64) -> Result<i64> {
return SeekWithDirCursor(task, f, whence, current, offset, None)
}
fn ReadAt(&self, _task: &Task, _f: &File, _dsts: &mut [IoVec], _offset: i64, _blocking: bool) -> Result<i64> {
return Err(Error::SysError(SysErr::ENOSYS))
}
fn WriteAt(&self, _task: &Task, _f: &File, _srcs: &[IoVec], _offset: i64, _blocking: bool) -> Result<i64> {
return Err(Error::SysError(SysErr::ENOSYS))
}
fn Append(&self, _task: &Task, _f: &File, _srcs: &[IoVec]) -> Result<(i64, i64)> {
return Err(Error::SysError(SysErr::ENOSYS))
}
fn Fsync(&self, _task: &Task, _f: &File, _start: i64, _end: i64, _syncType: SyncType) -> Result<()> {
return Ok(())
}
fn Flush(&self, _task: &Task, _f: &File) -> Result<()> {
return Ok(())
}
fn Ioctl(&self, _task: &Task, _f: &File, _fd: i32, _request: u64, _val: u64) -> Result<()> {
return Err(Error::SysError(SysErr::ENOTTY))
}
fn UnstableAttr(&self, task: &Task, f: &File) -> Result<UnstableAttr> {
let inode = f.Dirent.Inode().clone();
return inode.UnstableAttr(task);
}
fn Mappable(&self) -> Result<HostInodeOp> {
return Err(Error::SysError(SysErr::ENODEV))
}
fn ReadDir(&self, task: &Task, _f: &File, offset: i64, serializer: &mut DentrySerializer) -> Result<i64> {
let mut dirCtx = DirCtx {
Serializer: serializer,
DirCursor: "".to_string(),
};
// Get normal directory contents from ramfs dir.
let mut map = self.iops.dir.Children();
let kernel = task.Thread().lock().k.clone();
let root = kernel.RootDir();
let (dot, dotdot) = root.GetDotAttrs(&root);
map.insert(".".to_string(), dot);
map.insert("..".to_string(), dotdot);
let pidns = self.iops.data.lock().pidns.clone();
for tg in &pidns.ThreadGroups() {
if tg.Leader().is_some() {
let name = format!("{}", tg.ID());
map.insert(name, DentAttr::GenericDentAttr(InodeType::SpecialDirectory, &PROC_DEVICE));
}
}
if offset > map.len() as i64 {
return Ok(offset)
}
let mut cnt = 0;
for (name, entry) in &map {
if cnt >= offset {
dirCtx.DirEmit(task, name, entry)?
}
cnt += 1;
}
return Ok(map.len() as i64)
}
fn IterateDir(&self, _task: &Task, _d: &Dirent, _dirCtx: &mut DirCtx, _offset: i32) -> (i32, Result<i64>) {
return (0, Err(Error::SysError(SysErr::ENOTDIR)))
}
}
impl SockOperations for RootProcFile {}
|
//! The compile-time representation of Piccolo code.
//!
//! Opcode bytes are currently unstable. Operands are little-endian.
//!
//! Index means the index in the chunk's constant table, and slot means the
//! index from the bottom of the call frame on the [`Machine`] stack.
//!
//! | Opcode | Operands | Byte |
//! |-------------------|---------------------------|--------|
//! | `Pop` | | `0x00` |
//! | `Return` | | `0x01` |
//! | <b>Constants</b> | | |
//! | `Constant` | index into constant table | `0x02` |
//! | `Nil` | | `0x03` |
//! | `True` | | `0x04` |
//! | `False` | | `0x05` |
//! | <b>Math</b> | | |
//! | `Negate` | | `0x06` |
//! | `Not` | | `0x07` |
//! | `Add` | | `0x08` |
//! | `Subtract` | | `0x09` |
//! | `Multiply` | | `0x0a` |
//! | `Divide` | | `0x0b` |
//! | `Modulo` | | `0x0c` |
//! | <b>Comparison</b> | | |
//! | `Equal` | | `0x0d` |
//! | `Greater` | | `0x0e` |
//! | `Less` | | `0x0f` |
//! | `GreaterEqual` | | `0x10` |
//! | `LessEqual` | | `0x11` |
//! | <b>Variables</b> | | |
//! | `GetLocal` | slot on stack | `0x12` |
//! | `SetLocal` | slot on stack | `0x13` |
//! | `GetGlobal` | index into constant table | `0x14` |
//! | `SetGlobal` | index into constant table | `0x15` |
//! | `DeclareGlobal` | index into constant table | `0x16` |
//! | <b>Jumps</b> | | |
//! | `Jump` | forward offset | `0x17` |
//! | `JumpFalse` | forward offset | `0x18` |
//! | `JumpTrue` | forward offset | `0x19` |
//! | `Loop` | backward offset | `0x1A` |
//! | <b>Misc</b> | | |
//! | `Assert` | | `0xff` |
//!
//! [`Machine`]: ../vm/struct.Machine.html
macro_rules! opcodes {
($name:ident => $($op:ident = $num:expr,)*) => {
/// Enum of Piccolo opcodes.
#[derive(Debug, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum $name {
$($op = $num,)*
}
impl Into<u8> for $name {
fn into(self) -> u8 {
match self {
$($name::$op => $num,)*
}
}
}
impl From<u8> for $name {
fn from(v: u8) -> $name {
match v {
$($num => $name::$op,)*
_ => panic!("{} does not correspond to any opcode in {}", v, stringify!($name))
}
}
}
};
}
opcodes!(Opcode =>
Pop = 0x00,
Return = 0x01,
Constant = 0x02,
Nil = 0x03,
True = 0x04,
False = 0x05,
Negate = 0x06,
Not = 0x07,
Add = 0x08,
Subtract = 0x09,
Multiply = 0x0a,
Divide = 0x0b,
Modulo = 0x0c,
Equal = 0x0d,
Greater = 0x0e,
Less = 0x0f,
GreaterEqual = 0x10,
LessEqual = 0x11,
GetLocal = 0x12,
SetLocal = 0x13,
GetGlobal = 0x14,
SetGlobal = 0x15,
DeclareGlobal = 0x16,
JumpForward = 0x17,
JumpFalse = 0x18,
JumpTrue = 0x19,
JumpBack = 0x1a,
BitAnd = 0x1b,
BitOr = 0x1c,
BitXor = 0x1d,
ShiftLeft = 0x1e,
ShiftRight = 0x1f,
Assert = 0xff,
);
pub(crate) fn op_len(op: Opcode) -> usize {
match op {
Opcode::Constant
| Opcode::GetLocal
| Opcode::SetLocal
| Opcode::GetGlobal
| Opcode::SetGlobal
| Opcode::DeclareGlobal
| Opcode::JumpForward
| Opcode::JumpFalse
| Opcode::JumpTrue
| Opcode::JumpBack => 3,
_ => 1,
}
}
|
use binary_search::BinarySearch;
use input_i_scanner::InputIScanner;
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
macro_rules! scan {
(($($t: ty),+)) => {
($(scan!($t)),+)
};
($t: ty) => {
_i_i.scan::<$t>() as $t
};
(($($t: ty),+); $n: expr) => {
std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>()
};
($t: ty; $n: expr) => {
std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>()
};
}
let n = scan!(usize);
let a = scan!(u32; n);
let b = scan!(u32; n);
let c = scan!(u32; n);
let mut a = a;
let mut c = c;
a.sort();
c.sort();
let mut ans = 0;
for b in b {
let a = a.lower_bound(&b);
let c = n - c.upper_bound(&b);
ans += a * c;
}
println!("{}", ans);
}
|
//! This module contains definitions for Timeseries specific Grouping
//! and Aggregate functions in IOx, designed to be compatible with
//! InfluxDB classic
use datafusion::prelude::Expr;
use snafu::Snafu;
use crate::window;
#[allow(missing_docs)]
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display(
"Aggregate not yet supported {}. See https://github.com/influxdata/influxdb_iox/issues/480",
agg
))]
AggregateNotSupported { agg: String },
}
#[allow(missing_docs)]
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, Clone, PartialEq, Eq, Copy)]
/// TimeSeries specific aggregates or selector functions
///
/// Aggregates are as in typical databases: they combine a column of
/// data into a single scalar values by some arithemetic calculation.
///
/// Selector_functions are similar to aggregates in that reduce a
/// column of data into a single row by *selecting* a single row. In
/// other words, they can return the timestamp value from the
/// associated row in addition to its value.
pub enum Aggregate {
/// Aggregate: the sum of all values in the column
Sum,
/// Aggregate: the total number of column values
Count,
/// Selector: Selects the minimum value of a column and the
/// associated timestamp. In the case of multiple rows with the
/// same min value, the earliest timestamp is used
Min,
/// Selector: Selects the maximum value of a column and the
/// associated timestamp. In the case of multiple rows with the
/// same max value, the earliest timestamp is used
Max,
/// Selector: Selects the value of a column with the minimum
/// timestamp and the associated timestamp. In the case of
/// multiple rows with the min timestamp, one is abritrarily
/// chosen
First,
/// Selector: Selects the value of a column with the minimum
/// timestamp and the associated timestamp. In the case of
/// multiple rows with the min timestamp, one is abritrarily
/// chosen
Last,
/// Aggregate: Average (geometric mean) column's value
Mean,
/// No grouping is applied
None,
}
/// Represents some duration in time
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum WindowDuration {
/// Variable sized window,
Variable { months: i64, negative: bool },
/// fixed size, in nanoseconds
Fixed { nanoseconds: i64 },
}
impl Aggregate {
/// Create the appropriate DataFusion expression for this aggregate
pub fn to_datafusion_expr(self, input: Expr) -> Result<Expr> {
use datafusion::prelude::{avg, count, max, min, sum};
match self {
Self::Sum => Ok(sum(input)),
Self::Count => Ok(count(input)),
Self::Min => Ok(min(input)),
Self::Max => Ok(max(input)),
Self::First => AggregateNotSupportedSnafu { agg: "First" }.fail(),
Self::Last => AggregateNotSupportedSnafu { agg: "Last" }.fail(),
Self::Mean => Ok(avg(input)),
Self::None => AggregateNotSupportedSnafu { agg: "None" }.fail(),
}
}
}
impl WindowDuration {
/// Does this duration represent 0 nanoseconds?
pub fn empty() -> Self {
Self::Fixed { nanoseconds: 0 }
}
/// Create a duration from nanoseconds
pub fn from_nanoseconds(nanoseconds: i64) -> Self {
Self::Fixed { nanoseconds }
}
/// Create a duration from a number of months
pub fn from_months(months: i64, negative: bool) -> Self {
Self::Variable { months, negative }
}
}
// Translation to the structures for the underlying window
// implementation
impl From<&WindowDuration> for window::Duration {
fn from(window_duration: &WindowDuration) -> Self {
match window_duration {
WindowDuration::Variable { months, negative } => {
Self::from_months_with_negative(*months, *negative)
}
WindowDuration::Fixed { nanoseconds } => Self::from_nsecs(*nanoseconds),
}
}
}
|
pub fn first_word(s: String) -> String {
let bytes = s.as_bytes();
let mut idx = 0;
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
idx = i;
break;
}
}
println!("idx={}", idx);
slice_demo();
s[idx..].to_string()
}
fn slice_demo() {
let s = String::from("hello world");
let mut hello = &s[0..5];
let world = &s[6..11];
println!("hello={} world={}", hello, world);
hello = "xxx";
println!("hello={} world={}", hello, world);
let a = [1, 2, 3, 4, 5];
for (i, v) in a.iter().enumerate() {
println!("i={} v={}", i, v)
}
let sub = &a[1..3];
for v in sub.iter() {
println!("v={}", v);
}
}
|
pub mod ant_ai;
pub mod random_move;
pub mod random_patrolling;
pub mod rat_ai;
pub mod spawning_equipment;
pub mod spawning_fruit;
|
use std::fs;
use std::io;
use stemmer::Stemmer;
use std::collections::HashMap;
fn main() {
println!("1. Read file and converted to lower case\n************");
let mut text = readfile().unwrap();
println!("{:#?}",text);
text = text.to_lowercase(); // converted to lower casse
println!("\n\n2. Tokenization and Stemming\n************");
let mut words:Vec <String> = Vec::new();
let mut stemmer = Stemmer::new("english").unwrap();
for word in text.split_whitespace() {
let s : String = stemmer.stem_str(word).to_owned();
words.push(s);
}
println!("{:?}",words);
println!("{:?}",word_count(&mut words));
//println!("{:?}",stop_word(&mut words));
}
// fn stop_word (list : &mut[String]) -> Vec<String> {
// let stop_words:Vec <String> = vec!["is".to_string(),"the".to_string(),"are".to_string(),"i".to_string(),"on".to_string(),"it".to_string(),"a".to_string(),"of".to_string(),"in".to_string()];
// let mut words:Vec <String> = Vec::new();
// for k in list {
// for l in &stop_words {
// if k==l {
// println!("{},{}",k,l);
// }
// else {
// words.push(k.to_string());
// }
// }
// }
// words
// }
//Word Counting
fn word_count(list: &mut [String]) -> HashMap <String,u32> {
println!("\n\nEach Word Count\n********************");
let mut map: HashMap<String,u32> = HashMap::new();
for word in list.iter() {
let count = map.entry(word.to_string()).or_insert(0);
*count += 1;
}
map
}
fn readfile() -> Result<String, io::Error> {
//let mut reader = String::new(); //created a string that will possess content of file.
fs::read_to_string("file.txt") //file read here
}
// fn main () {
// let mut v = vec![1,2,4];
// let mut m = vec![1,4,5,6,7,8,9,0,1,2,3];
// for word in v.iter() {
// for word1 in m.iter() {
// if word != word1 {
// println!("{},{}",word,word1);
// }
// }
// }
// } |
// Applies Horner's rule to exponentiation
// Computes a^n by the left-to-right binary exponentiation algorithm
// Input: A number a and a list b(n) of binary digits b_I, ..., b_0
// in the binary expansion of a positive integer n
// Output: The value of a^n
fn lr_binary_exponentiation(a: u8, b: &[u8]) -> u64 {
let mut product: u64 = a as u64;
let i = b.len();
for j in 0..(i - 1) {
product = product * product;
if b[i - 1 - j] == 1 {
product = product * (a as u64);
}
}
product
}
fn main() {
let b = [1, 1, 0, 1];
println!("Value of 5^13 (LR): {}", lr_binary_exponentiation(5, &b));
}
|
mod error;
use gstreamer::glib::{g_print, g_printerr};
use gstreamer::prelude::*;
use gstreamer::query::Seeking;
use gstreamer::*;
#[derive(Default)]
struct CustomData {
playing: bool, /* Are we in the PLAYING state? */
terminate: bool, /* Should we terminate execution? */
seek_enabled: bool, /* Is seeking enabled for this media? */
seek_done: bool, /* Have we performed the seek already? */
duration: Option<ClockTime>, /* How long does this media last, in nanoseconds */
}
fn main() -> Result<(), error::Error> {
/* Initialize GStreamer */
init()?;
let mut data = CustomData::default();
/* Create the elements */
let playbin = ElementFactory::make("playbin").name("playbin").build()?;
/* Set the URI to play */
playbin.set_property(
"uri",
"https://www.freedesktop.org/software/gstreamer-sdk/data/media/sintel_trailer-480p.webm",
);
/* Start playing */
playbin
.set_state(State::Playing)
.map_err(|_| "Unable to set the pipeline to the playing state.")?;
/* Listen to the bus */
let bus = playbin.bus().unwrap();
while !data.terminate {
if let Some(msg) = bus.timed_pop_filtered(
Some(ClockTime::from_mseconds(100)),
&[
MessageType::StateChanged,
MessageType::Error,
MessageType::Eos,
MessageType::DurationChanged,
],
) {
handle_message(&mut data, &playbin, msg);
} else {
/* We got no message, this means the timeout expired */
if data.playing {
if let Some(current) = playbin.query_position::<ClockTime>() {
/* If we didn't know it yet, query the stream duration */
if data.duration.is_none() {
data.duration = playbin.query_duration();
g_printerr!("Could not query current duration.\n");
}
/* Print current position and total duration */
g_print!("Position {} / {}\r", current, data.duration.unwrap());
/* If seeking is enabled, we have not done it yet, and the time is right, seek */
if data.seek_enabled && !data.seek_done && current > ClockTime::from_seconds(10)
{
g_print!("\nReached 10s, performing seek...\n");
playbin.seek_simple(
SeekFlags::FLUSH | SeekFlags::KEY_UNIT,
ClockTime::from_seconds(30),
)?;
data.seek_done = true;
}
} else {
g_printerr!("Could not query current position.\n");
}
}
}
}
/* Free resources */
playbin.set_state(State::Null)?;
Ok(())
}
fn handle_message(data: &mut CustomData, playbin: &Element, msg: Message) {
match msg.view() {
MessageView::Error(err) => {
let src_name = err.src().map(|src| src.name()).unwrap_or_else(|| "".into());
g_printerr!(
"Error received from element {}: {}\n",
src_name,
err.error()
);
g_printerr!(
"Debugging information: {}\n",
err.debug().unwrap_or_else(|| "".into())
);
data.terminate = true;
}
MessageView::Eos(_) => {
g_print!("\nnEnd-Of-Stream reached.\n");
data.terminate = true;
}
MessageView::DurationChanged(_) => {
/* The duration has changed, mark the current one as invalid */
data.duration = ClockTime::NONE;
}
MessageView::StateChanged(msg) => {
if msg
.src()
.map(|src| src.as_object_ref() == playbin.as_object_ref())
.unwrap_or(false)
{
let new_state = msg.current();
g_print!(
"Pipeline state changed from {:?} to {:?}:\n",
msg.old(),
new_state
);
/* Remember whether we are in the PLAYING state or not */
data.playing = new_state == State::Playing;
if data.playing {
/* We just moved to PLAYING. Check if seeking is possible */
let mut query = Seeking::new(Format::Time);
if playbin.query(query.query_mut()) {
let (seek_enabled, start, end) = query.result();
data.seek_enabled = seek_enabled;
if data.seek_enabled {
g_print!("Seeking is ENABLED from {} to {}\n", start, end);
} else {
g_print!("Seeking is DISABLED for this stream.\n");
}
} else {
g_printerr!("Seeking query failed.\n");
}
}
}
}
_ => {
g_printerr!("Unexpected message received.\n");
panic!();
}
}
}
|
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
extern crate hack_assembler;
pub use hack_assembler::lexer;
fn test_file_read_token_stream_integ(path: &Path) {
let display = path.display();
let mut file = match File::open(&path) {
Err(why) => panic!("failed to open {}: {}", display, why.description()),
Ok(file) => file,
};
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) => panic!("failed to read {}: {}", display, why.description()),
Ok(_) => {
print!("{} contains:\n{}----------\n", display, s);
let mut cs = s.chars();
loop {
let tok = lexer::next_token(&mut cs);
println!("Got token: {}", tok);
if tok.kind == lexer::TokenKind::TokenEOF {
break;
}
}
}
}
}
#[test] #[ignore]
fn test_add() {
let path = Path::new("./tests/data/Add.asm");
test_file_read_token_stream_integ(path);
}
#[test] #[ignore]
fn test_max() {
let path = Path::new("./tests/data/Max.asm");
test_file_read_token_stream_integ(path);
}
#[test] #[ignore]
fn test_rect() {
let path = Path::new("./tests/data/Rect.asm");
test_file_read_token_stream_integ(path);
}
#[test] #[ignore]
fn test_pong() {
let path = Path::new("./tests/data/Pong.asm");
test_file_read_token_stream_integ(path);
}
#[test] #[ignore]
fn test_max_no_symbols() {
let path = Path::new("./tests/data/MaxL.asm");
test_file_read_token_stream_integ(path);
}
#[test] #[ignore]
fn test_pong_no_symbols() {
let path = Path::new("./tests/data/PongL.asm");
test_file_read_token_stream_integ(path);
}
#[test] #[ignore]
fn test_rect_no_symbols() {
let path = Path::new("./tests/data/RectL.asm");
test_file_read_token_stream_integ(path);
} |
use std::time::{SystemTime, Duration};
use segment::Metric;
// Define a metric..
#[derive(Metric)]
#[segment(measurement="cpuinfo")]
pub struct CpuInfo {
#[segment(time)]
timestamp: Duration,
#[segment(tag)]
descr: & 'static str,
#[segment(tag, rename="Host")]
host: String,
#[segment(tag)]
cpuid: u32,
#[segment(field, rename="system")]
sys_time: u64,
#[segment(field, rename="user")]
usr_time: u64,
#[segment(field, rename="idle")]
idl_time: u64,
#[segment(field, rename="load")]
system_load: f32,
#[segment(field)]
some_str: & 'static str,
}
fn main() {
let m = CpuInfo{
timestamp: match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(d) => d,
Err(_) => panic!("Unable to get current time, as duration"),
},
host: "myhost".to_string(),
descr: "a wonderful, tag",
cpuid: 0,
sys_time: 124,
usr_time: 256,
idl_time: 0,
system_load: 0.75,
some_str: "\"foo,bar\"",
};
println!("Time: {:?}", m.time());
println!("Tags:");
for t in m.tags() {
println!(" - \"{}\" = \"{}\"", t.name, t.value);
}
println!("Fields:");
for f in m.fields() {
println!(" - \"{}\" = {}", f.name, f.value.to_string());
}
let mut s = String::with_capacity(64);
m.build(&mut s);
println!("Line Proto: '{}'", s);
}
|
#[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::PRESETCTRL {
#[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 `SPI0_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SPI0_RST_NR {
#[doc = "Assert the SPI0 reset."]
ASSERT_THE_SPI0_RESE,
#[doc = "Clear the SPI0 reset."]
CLEAR_THE_SPI0_RESET,
}
impl SPI0_RST_NR {
#[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 {
SPI0_RST_NR::ASSERT_THE_SPI0_RESE => false,
SPI0_RST_NR::CLEAR_THE_SPI0_RESET => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> SPI0_RST_NR {
match value {
false => SPI0_RST_NR::ASSERT_THE_SPI0_RESE,
true => SPI0_RST_NR::CLEAR_THE_SPI0_RESET,
}
}
#[doc = "Checks if the value of the field is `ASSERT_THE_SPI0_RESE`"]
#[inline]
pub fn is_assert_the_spi0_rese(&self) -> bool {
*self == SPI0_RST_NR::ASSERT_THE_SPI0_RESE
}
#[doc = "Checks if the value of the field is `CLEAR_THE_SPI0_RESET`"]
#[inline]
pub fn is_clear_the_spi0_reset(&self) -> bool {
*self == SPI0_RST_NR::CLEAR_THE_SPI0_RESET
}
}
#[doc = "Possible values of the field `SPI1_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SPI1_RST_NR {
#[doc = "Assert the SPI1 reset."]
ASSERT_THE_SPI1_RESE,
#[doc = "Clear the SPI1 reset."]
CLEAR_THE_SPI1_RESET,
}
impl SPI1_RST_NR {
#[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 {
SPI1_RST_NR::ASSERT_THE_SPI1_RESE => false,
SPI1_RST_NR::CLEAR_THE_SPI1_RESET => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> SPI1_RST_NR {
match value {
false => SPI1_RST_NR::ASSERT_THE_SPI1_RESE,
true => SPI1_RST_NR::CLEAR_THE_SPI1_RESET,
}
}
#[doc = "Checks if the value of the field is `ASSERT_THE_SPI1_RESE`"]
#[inline]
pub fn is_assert_the_spi1_rese(&self) -> bool {
*self == SPI1_RST_NR::ASSERT_THE_SPI1_RESE
}
#[doc = "Checks if the value of the field is `CLEAR_THE_SPI1_RESET`"]
#[inline]
pub fn is_clear_the_spi1_reset(&self) -> bool {
*self == SPI1_RST_NR::CLEAR_THE_SPI1_RESET
}
}
#[doc = "Possible values of the field `UARTFRG_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum UARTFRG_RST_NR {
#[doc = "Assert the UARTFRG reset."]
ASSERT_THE_UARTFRG_R,
#[doc = "Clear the UARTFRG reset."]
CLEAR_THE_UARTFRG_RE,
}
impl UARTFRG_RST_NR {
#[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 {
UARTFRG_RST_NR::ASSERT_THE_UARTFRG_R => false,
UARTFRG_RST_NR::CLEAR_THE_UARTFRG_RE => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> UARTFRG_RST_NR {
match value {
false => UARTFRG_RST_NR::ASSERT_THE_UARTFRG_R,
true => UARTFRG_RST_NR::CLEAR_THE_UARTFRG_RE,
}
}
#[doc = "Checks if the value of the field is `ASSERT_THE_UARTFRG_R`"]
#[inline]
pub fn is_assert_the_uartfrg_r(&self) -> bool {
*self == UARTFRG_RST_NR::ASSERT_THE_UARTFRG_R
}
#[doc = "Checks if the value of the field is `CLEAR_THE_UARTFRG_RE`"]
#[inline]
pub fn is_clear_the_uartfrg_re(&self) -> bool {
*self == UARTFRG_RST_NR::CLEAR_THE_UARTFRG_RE
}
}
#[doc = "Possible values of the field `USART0_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum USART0_RST_NR {
#[doc = "Assert the USART0 reset."]
ASSERT_THE_USART0_RE,
#[doc = "Clear the USART0 reset."]
CLEAR_THE_USART0_RES,
}
impl USART0_RST_NR {
#[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 {
USART0_RST_NR::ASSERT_THE_USART0_RE => false,
USART0_RST_NR::CLEAR_THE_USART0_RES => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> USART0_RST_NR {
match value {
false => USART0_RST_NR::ASSERT_THE_USART0_RE,
true => USART0_RST_NR::CLEAR_THE_USART0_RES,
}
}
#[doc = "Checks if the value of the field is `ASSERT_THE_USART0_RE`"]
#[inline]
pub fn is_assert_the_usart0_re(&self) -> bool {
*self == USART0_RST_NR::ASSERT_THE_USART0_RE
}
#[doc = "Checks if the value of the field is `CLEAR_THE_USART0_RES`"]
#[inline]
pub fn is_clear_the_usart0_res(&self) -> bool {
*self == USART0_RST_NR::CLEAR_THE_USART0_RES
}
}
#[doc = "Possible values of the field `UART1_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum UART1_RST_NR {
#[doc = "Assert the UART reset."]
ASSERT_THE_UART_RESE,
#[doc = "Clear the UART1 reset."]
CLEAR_THE_UART1_RESE,
}
impl UART1_RST_NR {
#[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 {
UART1_RST_NR::ASSERT_THE_UART_RESE => false,
UART1_RST_NR::CLEAR_THE_UART1_RESE => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> UART1_RST_NR {
match value {
false => UART1_RST_NR::ASSERT_THE_UART_RESE,
true => UART1_RST_NR::CLEAR_THE_UART1_RESE,
}
}
#[doc = "Checks if the value of the field is `ASSERT_THE_UART_RESE`"]
#[inline]
pub fn is_assert_the_uart_rese(&self) -> bool {
*self == UART1_RST_NR::ASSERT_THE_UART_RESE
}
#[doc = "Checks if the value of the field is `CLEAR_THE_UART1_RESE`"]
#[inline]
pub fn is_clear_the_uart1_rese(&self) -> bool {
*self == UART1_RST_NR::CLEAR_THE_UART1_RESE
}
}
#[doc = "Possible values of the field `UART2_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum UART2_RST_NR {
#[doc = "Assert the UART2 reset."]
ASSERT_THE_UART2_RES,
#[doc = "Clear the UART2 reset."]
CLEAR_THE_UART2_RESE,
}
impl UART2_RST_NR {
#[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 {
UART2_RST_NR::ASSERT_THE_UART2_RES => false,
UART2_RST_NR::CLEAR_THE_UART2_RESE => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> UART2_RST_NR {
match value {
false => UART2_RST_NR::ASSERT_THE_UART2_RES,
true => UART2_RST_NR::CLEAR_THE_UART2_RESE,
}
}
#[doc = "Checks if the value of the field is `ASSERT_THE_UART2_RES`"]
#[inline]
pub fn is_assert_the_uart2_res(&self) -> bool {
*self == UART2_RST_NR::ASSERT_THE_UART2_RES
}
#[doc = "Checks if the value of the field is `CLEAR_THE_UART2_RESE`"]
#[inline]
pub fn is_clear_the_uart2_rese(&self) -> bool {
*self == UART2_RST_NR::CLEAR_THE_UART2_RESE
}
}
#[doc = "Possible values of the field `I2C_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum I2C_RST_NR {
#[doc = "Assert the I2C reset."]
ASSERT_THE_I2C_RESET,
#[doc = "Clear the I2C reset."]
CLEAR_THE_I2C_RESET_,
}
impl I2C_RST_NR {
#[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 {
I2C_RST_NR::ASSERT_THE_I2C_RESET => false,
I2C_RST_NR::CLEAR_THE_I2C_RESET_ => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> I2C_RST_NR {
match value {
false => I2C_RST_NR::ASSERT_THE_I2C_RESET,
true => I2C_RST_NR::CLEAR_THE_I2C_RESET_,
}
}
#[doc = "Checks if the value of the field is `ASSERT_THE_I2C_RESET`"]
#[inline]
pub fn is_assert_the_i2c_reset(&self) -> bool {
*self == I2C_RST_NR::ASSERT_THE_I2C_RESET
}
#[doc = "Checks if the value of the field is `CLEAR_THE_I2C_RESET_`"]
#[inline]
pub fn is_clear_the_i2c_reset_(&self) -> bool {
*self == I2C_RST_NR::CLEAR_THE_I2C_RESET_
}
}
#[doc = "Possible values of the field `MRT_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MRT_RST_NR {
#[doc = "Assert the MRT reset."]
ASSERT_THE_MRT_RESET,
#[doc = "Clear the MRT reset."]
CLEAR_THE_MRT_RESET_,
}
impl MRT_RST_NR {
#[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 {
MRT_RST_NR::ASSERT_THE_MRT_RESET => false,
MRT_RST_NR::CLEAR_THE_MRT_RESET_ => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> MRT_RST_NR {
match value {
false => MRT_RST_NR::ASSERT_THE_MRT_RESET,
true => MRT_RST_NR::CLEAR_THE_MRT_RESET_,
}
}
#[doc = "Checks if the value of the field is `ASSERT_THE_MRT_RESET`"]
#[inline]
pub fn is_assert_the_mrt_reset(&self) -> bool {
*self == MRT_RST_NR::ASSERT_THE_MRT_RESET
}
#[doc = "Checks if the value of the field is `CLEAR_THE_MRT_RESET_`"]
#[inline]
pub fn is_clear_the_mrt_reset_(&self) -> bool {
*self == MRT_RST_NR::CLEAR_THE_MRT_RESET_
}
}
#[doc = "Possible values of the field `SCT_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SCT_RST_NR {
#[doc = "Assert the SCT reset."]
ASSERT_THE_SCT_RESET,
#[doc = "Clear the SCT reset."]
CLEAR_THE_SCT_RESET_,
}
impl SCT_RST_NR {
#[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 {
SCT_RST_NR::ASSERT_THE_SCT_RESET => false,
SCT_RST_NR::CLEAR_THE_SCT_RESET_ => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> SCT_RST_NR {
match value {
false => SCT_RST_NR::ASSERT_THE_SCT_RESET,
true => SCT_RST_NR::CLEAR_THE_SCT_RESET_,
}
}
#[doc = "Checks if the value of the field is `ASSERT_THE_SCT_RESET`"]
#[inline]
pub fn is_assert_the_sct_reset(&self) -> bool {
*self == SCT_RST_NR::ASSERT_THE_SCT_RESET
}
#[doc = "Checks if the value of the field is `CLEAR_THE_SCT_RESET_`"]
#[inline]
pub fn is_clear_the_sct_reset_(&self) -> bool {
*self == SCT_RST_NR::CLEAR_THE_SCT_RESET_
}
}
#[doc = "Possible values of the field `WKT_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WKT_RST_NR {
#[doc = "Assert the WKT reset."]
ASSERT_THE_WKT_RESET,
#[doc = "Clear the WKT reset."]
CLEAR_THE_WKT_RESET_,
}
impl WKT_RST_NR {
#[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 {
WKT_RST_NR::ASSERT_THE_WKT_RESET => false,
WKT_RST_NR::CLEAR_THE_WKT_RESET_ => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> WKT_RST_NR {
match value {
false => WKT_RST_NR::ASSERT_THE_WKT_RESET,
true => WKT_RST_NR::CLEAR_THE_WKT_RESET_,
}
}
#[doc = "Checks if the value of the field is `ASSERT_THE_WKT_RESET`"]
#[inline]
pub fn is_assert_the_wkt_reset(&self) -> bool {
*self == WKT_RST_NR::ASSERT_THE_WKT_RESET
}
#[doc = "Checks if the value of the field is `CLEAR_THE_WKT_RESET_`"]
#[inline]
pub fn is_clear_the_wkt_reset_(&self) -> bool {
*self == WKT_RST_NR::CLEAR_THE_WKT_RESET_
}
}
#[doc = "Possible values of the field `GPIO_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO_RST_NR {
#[doc = "Assert the GPIO reset."]
ASSERT_THE_GPIO_RESE,
#[doc = "Clear the GPIO reset."]
CLEAR_THE_GPIO_RESET,
}
impl GPIO_RST_NR {
#[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 {
GPIO_RST_NR::ASSERT_THE_GPIO_RESE => false,
GPIO_RST_NR::CLEAR_THE_GPIO_RESET => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO_RST_NR {
match value {
false => GPIO_RST_NR::ASSERT_THE_GPIO_RESE,
true => GPIO_RST_NR::CLEAR_THE_GPIO_RESET,
}
}
#[doc = "Checks if the value of the field is `ASSERT_THE_GPIO_RESE`"]
#[inline]
pub fn is_assert_the_gpio_rese(&self) -> bool {
*self == GPIO_RST_NR::ASSERT_THE_GPIO_RESE
}
#[doc = "Checks if the value of the field is `CLEAR_THE_GPIO_RESET`"]
#[inline]
pub fn is_clear_the_gpio_reset(&self) -> bool {
*self == GPIO_RST_NR::CLEAR_THE_GPIO_RESET
}
}
#[doc = "Possible values of the field `FLASH_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_RST_NR {
#[doc = "Assert the flash controller reset."]
ASSERT_THE_FLASH_CON,
#[doc = "Clear the flash controller reset."]
CLEAR_THE_FLASH_CONT,
}
impl FLASH_RST_NR {
#[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 {
FLASH_RST_NR::ASSERT_THE_FLASH_CON => false,
FLASH_RST_NR::CLEAR_THE_FLASH_CONT => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> FLASH_RST_NR {
match value {
false => FLASH_RST_NR::ASSERT_THE_FLASH_CON,
true => FLASH_RST_NR::CLEAR_THE_FLASH_CONT,
}
}
#[doc = "Checks if the value of the field is `ASSERT_THE_FLASH_CON`"]
#[inline]
pub fn is_assert_the_flash_con(&self) -> bool {
*self == FLASH_RST_NR::ASSERT_THE_FLASH_CON
}
#[doc = "Checks if the value of the field is `CLEAR_THE_FLASH_CONT`"]
#[inline]
pub fn is_clear_the_flash_cont(&self) -> bool {
*self == FLASH_RST_NR::CLEAR_THE_FLASH_CONT
}
}
#[doc = "Possible values of the field `ACMP_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ACMP_RST_NR {
#[doc = "Assert the analog comparator reset."]
ASSERT_THE_ANALOG_CO,
#[doc = "Clear the analog comparator controller reset."]
CLEAR_THE_ANALOG_COM,
}
impl ACMP_RST_NR {
#[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 {
ACMP_RST_NR::ASSERT_THE_ANALOG_CO => false,
ACMP_RST_NR::CLEAR_THE_ANALOG_COM => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> ACMP_RST_NR {
match value {
false => ACMP_RST_NR::ASSERT_THE_ANALOG_CO,
true => ACMP_RST_NR::CLEAR_THE_ANALOG_COM,
}
}
#[doc = "Checks if the value of the field is `ASSERT_THE_ANALOG_CO`"]
#[inline]
pub fn is_assert_the_analog_co(&self) -> bool {
*self == ACMP_RST_NR::ASSERT_THE_ANALOG_CO
}
#[doc = "Checks if the value of the field is `CLEAR_THE_ANALOG_COM`"]
#[inline]
pub fn is_clear_the_analog_com(&self) -> bool {
*self == ACMP_RST_NR::CLEAR_THE_ANALOG_COM
}
}
#[doc = "Values that can be written to the field `SPI0_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SPI0_RST_NW {
#[doc = "Assert the SPI0 reset."]
ASSERT_THE_SPI0_RESE,
#[doc = "Clear the SPI0 reset."]
CLEAR_THE_SPI0_RESET,
}
impl SPI0_RST_NW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
SPI0_RST_NW::ASSERT_THE_SPI0_RESE => false,
SPI0_RST_NW::CLEAR_THE_SPI0_RESET => true,
}
}
}
#[doc = r" Proxy"]
pub struct _SPI0_RST_NW<'a> {
w: &'a mut W,
}
impl<'a> _SPI0_RST_NW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: SPI0_RST_NW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Assert the SPI0 reset."]
#[inline]
pub fn assert_the_spi0_rese(self) -> &'a mut W {
self.variant(SPI0_RST_NW::ASSERT_THE_SPI0_RESE)
}
#[doc = "Clear the SPI0 reset."]
#[inline]
pub fn clear_the_spi0_reset(self) -> &'a mut W {
self.variant(SPI0_RST_NW::CLEAR_THE_SPI0_RESET)
}
#[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 `SPI1_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SPI1_RST_NW {
#[doc = "Assert the SPI1 reset."]
ASSERT_THE_SPI1_RESE,
#[doc = "Clear the SPI1 reset."]
CLEAR_THE_SPI1_RESET,
}
impl SPI1_RST_NW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
SPI1_RST_NW::ASSERT_THE_SPI1_RESE => false,
SPI1_RST_NW::CLEAR_THE_SPI1_RESET => true,
}
}
}
#[doc = r" Proxy"]
pub struct _SPI1_RST_NW<'a> {
w: &'a mut W,
}
impl<'a> _SPI1_RST_NW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: SPI1_RST_NW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Assert the SPI1 reset."]
#[inline]
pub fn assert_the_spi1_rese(self) -> &'a mut W {
self.variant(SPI1_RST_NW::ASSERT_THE_SPI1_RESE)
}
#[doc = "Clear the SPI1 reset."]
#[inline]
pub fn clear_the_spi1_reset(self) -> &'a mut W {
self.variant(SPI1_RST_NW::CLEAR_THE_SPI1_RESET)
}
#[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 `UARTFRG_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum UARTFRG_RST_NW {
#[doc = "Assert the UARTFRG reset."]
ASSERT_THE_UARTFRG_R,
#[doc = "Clear the UARTFRG reset."]
CLEAR_THE_UARTFRG_RE,
}
impl UARTFRG_RST_NW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
UARTFRG_RST_NW::ASSERT_THE_UARTFRG_R => false,
UARTFRG_RST_NW::CLEAR_THE_UARTFRG_RE => true,
}
}
}
#[doc = r" Proxy"]
pub struct _UARTFRG_RST_NW<'a> {
w: &'a mut W,
}
impl<'a> _UARTFRG_RST_NW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: UARTFRG_RST_NW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Assert the UARTFRG reset."]
#[inline]
pub fn assert_the_uartfrg_r(self) -> &'a mut W {
self.variant(UARTFRG_RST_NW::ASSERT_THE_UARTFRG_R)
}
#[doc = "Clear the UARTFRG reset."]
#[inline]
pub fn clear_the_uartfrg_re(self) -> &'a mut W {
self.variant(UARTFRG_RST_NW::CLEAR_THE_UARTFRG_RE)
}
#[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 `USART0_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum USART0_RST_NW {
#[doc = "Assert the USART0 reset."]
ASSERT_THE_USART0_RE,
#[doc = "Clear the USART0 reset."]
CLEAR_THE_USART0_RES,
}
impl USART0_RST_NW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
USART0_RST_NW::ASSERT_THE_USART0_RE => false,
USART0_RST_NW::CLEAR_THE_USART0_RES => true,
}
}
}
#[doc = r" Proxy"]
pub struct _USART0_RST_NW<'a> {
w: &'a mut W,
}
impl<'a> _USART0_RST_NW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: USART0_RST_NW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Assert the USART0 reset."]
#[inline]
pub fn assert_the_usart0_re(self) -> &'a mut W {
self.variant(USART0_RST_NW::ASSERT_THE_USART0_RE)
}
#[doc = "Clear the USART0 reset."]
#[inline]
pub fn clear_the_usart0_res(self) -> &'a mut W {
self.variant(USART0_RST_NW::CLEAR_THE_USART0_RES)
}
#[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
}
}
#[doc = "Values that can be written to the field `UART1_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum UART1_RST_NW {
#[doc = "Assert the UART reset."]
ASSERT_THE_UART_RESE,
#[doc = "Clear the UART1 reset."]
CLEAR_THE_UART1_RESE,
}
impl UART1_RST_NW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
UART1_RST_NW::ASSERT_THE_UART_RESE => false,
UART1_RST_NW::CLEAR_THE_UART1_RESE => true,
}
}
}
#[doc = r" Proxy"]
pub struct _UART1_RST_NW<'a> {
w: &'a mut W,
}
impl<'a> _UART1_RST_NW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: UART1_RST_NW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Assert the UART reset."]
#[inline]
pub fn assert_the_uart_rese(self) -> &'a mut W {
self.variant(UART1_RST_NW::ASSERT_THE_UART_RESE)
}
#[doc = "Clear the UART1 reset."]
#[inline]
pub fn clear_the_uart1_rese(self) -> &'a mut W {
self.variant(UART1_RST_NW::CLEAR_THE_UART1_RESE)
}
#[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 = 4;
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 `UART2_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum UART2_RST_NW {
#[doc = "Assert the UART2 reset."]
ASSERT_THE_UART2_RES,
#[doc = "Clear the UART2 reset."]
CLEAR_THE_UART2_RESE,
}
impl UART2_RST_NW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
UART2_RST_NW::ASSERT_THE_UART2_RES => false,
UART2_RST_NW::CLEAR_THE_UART2_RESE => true,
}
}
}
#[doc = r" Proxy"]
pub struct _UART2_RST_NW<'a> {
w: &'a mut W,
}
impl<'a> _UART2_RST_NW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: UART2_RST_NW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Assert the UART2 reset."]
#[inline]
pub fn assert_the_uart2_res(self) -> &'a mut W {
self.variant(UART2_RST_NW::ASSERT_THE_UART2_RES)
}
#[doc = "Clear the UART2 reset."]
#[inline]
pub fn clear_the_uart2_rese(self) -> &'a mut W {
self.variant(UART2_RST_NW::CLEAR_THE_UART2_RESE)
}
#[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 = 5;
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 `I2C_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum I2C_RST_NW {
#[doc = "Assert the I2C reset."]
ASSERT_THE_I2C_RESET,
#[doc = "Clear the I2C reset."]
CLEAR_THE_I2C_RESET_,
}
impl I2C_RST_NW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
I2C_RST_NW::ASSERT_THE_I2C_RESET => false,
I2C_RST_NW::CLEAR_THE_I2C_RESET_ => true,
}
}
}
#[doc = r" Proxy"]
pub struct _I2C_RST_NW<'a> {
w: &'a mut W,
}
impl<'a> _I2C_RST_NW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: I2C_RST_NW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Assert the I2C reset."]
#[inline]
pub fn assert_the_i2c_reset(self) -> &'a mut W {
self.variant(I2C_RST_NW::ASSERT_THE_I2C_RESET)
}
#[doc = "Clear the I2C reset."]
#[inline]
pub fn clear_the_i2c_reset_(self) -> &'a mut W {
self.variant(I2C_RST_NW::CLEAR_THE_I2C_RESET_)
}
#[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 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `MRT_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MRT_RST_NW {
#[doc = "Assert the MRT reset."]
ASSERT_THE_MRT_RESET,
#[doc = "Clear the MRT reset."]
CLEAR_THE_MRT_RESET_,
}
impl MRT_RST_NW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
MRT_RST_NW::ASSERT_THE_MRT_RESET => false,
MRT_RST_NW::CLEAR_THE_MRT_RESET_ => true,
}
}
}
#[doc = r" Proxy"]
pub struct _MRT_RST_NW<'a> {
w: &'a mut W,
}
impl<'a> _MRT_RST_NW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: MRT_RST_NW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Assert the MRT reset."]
#[inline]
pub fn assert_the_mrt_reset(self) -> &'a mut W {
self.variant(MRT_RST_NW::ASSERT_THE_MRT_RESET)
}
#[doc = "Clear the MRT reset."]
#[inline]
pub fn clear_the_mrt_reset_(self) -> &'a mut W {
self.variant(MRT_RST_NW::CLEAR_THE_MRT_RESET_)
}
#[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 = 7;
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 `SCT_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SCT_RST_NW {
#[doc = "Assert the SCT reset."]
ASSERT_THE_SCT_RESET,
#[doc = "Clear the SCT reset."]
CLEAR_THE_SCT_RESET_,
}
impl SCT_RST_NW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
SCT_RST_NW::ASSERT_THE_SCT_RESET => false,
SCT_RST_NW::CLEAR_THE_SCT_RESET_ => true,
}
}
}
#[doc = r" Proxy"]
pub struct _SCT_RST_NW<'a> {
w: &'a mut W,
}
impl<'a> _SCT_RST_NW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: SCT_RST_NW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Assert the SCT reset."]
#[inline]
pub fn assert_the_sct_reset(self) -> &'a mut W {
self.variant(SCT_RST_NW::ASSERT_THE_SCT_RESET)
}
#[doc = "Clear the SCT reset."]
#[inline]
pub fn clear_the_sct_reset_(self) -> &'a mut W {
self.variant(SCT_RST_NW::CLEAR_THE_SCT_RESET_)
}
#[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 = 8;
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 `WKT_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WKT_RST_NW {
#[doc = "Assert the WKT reset."]
ASSERT_THE_WKT_RESET,
#[doc = "Clear the WKT reset."]
CLEAR_THE_WKT_RESET_,
}
impl WKT_RST_NW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
WKT_RST_NW::ASSERT_THE_WKT_RESET => false,
WKT_RST_NW::CLEAR_THE_WKT_RESET_ => true,
}
}
}
#[doc = r" Proxy"]
pub struct _WKT_RST_NW<'a> {
w: &'a mut W,
}
impl<'a> _WKT_RST_NW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: WKT_RST_NW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Assert the WKT reset."]
#[inline]
pub fn assert_the_wkt_reset(self) -> &'a mut W {
self.variant(WKT_RST_NW::ASSERT_THE_WKT_RESET)
}
#[doc = "Clear the WKT reset."]
#[inline]
pub fn clear_the_wkt_reset_(self) -> &'a mut W {
self.variant(WKT_RST_NW::CLEAR_THE_WKT_RESET_)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 9;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO_RST_NW {
#[doc = "Assert the GPIO reset."]
ASSERT_THE_GPIO_RESE,
#[doc = "Clear the GPIO reset."]
CLEAR_THE_GPIO_RESET,
}
impl GPIO_RST_NW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO_RST_NW::ASSERT_THE_GPIO_RESE => false,
GPIO_RST_NW::CLEAR_THE_GPIO_RESET => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO_RST_NW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO_RST_NW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO_RST_NW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Assert the GPIO reset."]
#[inline]
pub fn assert_the_gpio_rese(self) -> &'a mut W {
self.variant(GPIO_RST_NW::ASSERT_THE_GPIO_RESE)
}
#[doc = "Clear the GPIO reset."]
#[inline]
pub fn clear_the_gpio_reset(self) -> &'a mut W {
self.variant(GPIO_RST_NW::CLEAR_THE_GPIO_RESET)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 10;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `FLASH_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_RST_NW {
#[doc = "Assert the flash controller reset."]
ASSERT_THE_FLASH_CON,
#[doc = "Clear the flash controller reset."]
CLEAR_THE_FLASH_CONT,
}
impl FLASH_RST_NW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
FLASH_RST_NW::ASSERT_THE_FLASH_CON => false,
FLASH_RST_NW::CLEAR_THE_FLASH_CONT => true,
}
}
}
#[doc = r" Proxy"]
pub struct _FLASH_RST_NW<'a> {
w: &'a mut W,
}
impl<'a> _FLASH_RST_NW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: FLASH_RST_NW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Assert the flash controller reset."]
#[inline]
pub fn assert_the_flash_con(self) -> &'a mut W {
self.variant(FLASH_RST_NW::ASSERT_THE_FLASH_CON)
}
#[doc = "Clear the flash controller reset."]
#[inline]
pub fn clear_the_flash_cont(self) -> &'a mut W {
self.variant(FLASH_RST_NW::CLEAR_THE_FLASH_CONT)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 11;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `ACMP_RST_N`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ACMP_RST_NW {
#[doc = "Assert the analog comparator reset."]
ASSERT_THE_ANALOG_CO,
#[doc = "Clear the analog comparator controller reset."]
CLEAR_THE_ANALOG_COM,
}
impl ACMP_RST_NW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
ACMP_RST_NW::ASSERT_THE_ANALOG_CO => false,
ACMP_RST_NW::CLEAR_THE_ANALOG_COM => true,
}
}
}
#[doc = r" Proxy"]
pub struct _ACMP_RST_NW<'a> {
w: &'a mut W,
}
impl<'a> _ACMP_RST_NW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: ACMP_RST_NW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Assert the analog comparator reset."]
#[inline]
pub fn assert_the_analog_co(self) -> &'a mut W {
self.variant(ACMP_RST_NW::ASSERT_THE_ANALOG_CO)
}
#[doc = "Clear the analog comparator controller reset."]
#[inline]
pub fn clear_the_analog_com(self) -> &'a mut W {
self.variant(ACMP_RST_NW::CLEAR_THE_ANALOG_COM)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - SPI0 reset control"]
#[inline]
pub fn spi0_rst_n(&self) -> SPI0_RST_NR {
SPI0_RST_NR::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 1 - SPI1 reset control"]
#[inline]
pub fn spi1_rst_n(&self) -> SPI1_RST_NR {
SPI1_RST_NR::_from({
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 2 - UART fractional baud rate generator (UARTFRG) reset control"]
#[inline]
pub fn uartfrg_rst_n(&self) -> UARTFRG_RST_NR {
UARTFRG_RST_NR::_from({
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 3 - USART0 reset control"]
#[inline]
pub fn usart0_rst_n(&self) -> USART0_RST_NR {
USART0_RST_NR::_from({
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 4 - U1ART1 reset control"]
#[inline]
pub fn uart1_rst_n(&self) -> UART1_RST_NR {
UART1_RST_NR::_from({
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 5 - UART2 reset control"]
#[inline]
pub fn uart2_rst_n(&self) -> UART2_RST_NR {
UART2_RST_NR::_from({
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 6 - I2C reset control"]
#[inline]
pub fn i2c_rst_n(&self) -> I2C_RST_NR {
I2C_RST_NR::_from({
const MASK: bool = true;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 7 - Multi-rate timer (MRT) reset control"]
#[inline]
pub fn mrt_rst_n(&self) -> MRT_RST_NR {
MRT_RST_NR::_from({
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 8 - SCT reset control"]
#[inline]
pub fn sct_rst_n(&self) -> SCT_RST_NR {
SCT_RST_NR::_from({
const MASK: bool = true;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 9 - Self wake-up timer (WKT) reset control"]
#[inline]
pub fn wkt_rst_n(&self) -> WKT_RST_NR {
WKT_RST_NR::_from({
const MASK: bool = true;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 10 - GPIO and GPIO pin interrupt reset control"]
#[inline]
pub fn gpio_rst_n(&self) -> GPIO_RST_NR {
GPIO_RST_NR::_from({
const MASK: bool = true;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 11 - Flash controller reset control"]
#[inline]
pub fn flash_rst_n(&self) -> FLASH_RST_NR {
FLASH_RST_NR::_from({
const MASK: bool = true;
const OFFSET: u8 = 11;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 12 - Analog comparator reset control"]
#[inline]
pub fn acmp_rst_n(&self) -> ACMP_RST_NR {
ACMP_RST_NR::_from({
const MASK: bool = true;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 8191 }
}
#[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 - SPI0 reset control"]
#[inline]
pub fn spi0_rst_n(&mut self) -> _SPI0_RST_NW {
_SPI0_RST_NW { w: self }
}
#[doc = "Bit 1 - SPI1 reset control"]
#[inline]
pub fn spi1_rst_n(&mut self) -> _SPI1_RST_NW {
_SPI1_RST_NW { w: self }
}
#[doc = "Bit 2 - UART fractional baud rate generator (UARTFRG) reset control"]
#[inline]
pub fn uartfrg_rst_n(&mut self) -> _UARTFRG_RST_NW {
_UARTFRG_RST_NW { w: self }
}
#[doc = "Bit 3 - USART0 reset control"]
#[inline]
pub fn usart0_rst_n(&mut self) -> _USART0_RST_NW {
_USART0_RST_NW { w: self }
}
#[doc = "Bit 4 - U1ART1 reset control"]
#[inline]
pub fn uart1_rst_n(&mut self) -> _UART1_RST_NW {
_UART1_RST_NW { w: self }
}
#[doc = "Bit 5 - UART2 reset control"]
#[inline]
pub fn uart2_rst_n(&mut self) -> _UART2_RST_NW {
_UART2_RST_NW { w: self }
}
#[doc = "Bit 6 - I2C reset control"]
#[inline]
pub fn i2c_rst_n(&mut self) -> _I2C_RST_NW {
_I2C_RST_NW { w: self }
}
#[doc = "Bit 7 - Multi-rate timer (MRT) reset control"]
#[inline]
pub fn mrt_rst_n(&mut self) -> _MRT_RST_NW {
_MRT_RST_NW { w: self }
}
#[doc = "Bit 8 - SCT reset control"]
#[inline]
pub fn sct_rst_n(&mut self) -> _SCT_RST_NW {
_SCT_RST_NW { w: self }
}
#[doc = "Bit 9 - Self wake-up timer (WKT) reset control"]
#[inline]
pub fn wkt_rst_n(&mut self) -> _WKT_RST_NW {
_WKT_RST_NW { w: self }
}
#[doc = "Bit 10 - GPIO and GPIO pin interrupt reset control"]
#[inline]
pub fn gpio_rst_n(&mut self) -> _GPIO_RST_NW {
_GPIO_RST_NW { w: self }
}
#[doc = "Bit 11 - Flash controller reset control"]
#[inline]
pub fn flash_rst_n(&mut self) -> _FLASH_RST_NW {
_FLASH_RST_NW { w: self }
}
#[doc = "Bit 12 - Analog comparator reset control"]
#[inline]
pub fn acmp_rst_n(&mut self) -> _ACMP_RST_NW {
_ACMP_RST_NW { w: self }
}
}
|
use core::ops::Add;
use num_traits::FromPrimitive;
pub type Coord = i32;
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub struct Pos {
pub x: Coord,
pub y: Coord,
}
#[derive(Copy, Clone)]
pub enum ShiftDir {
Left,
Right,
}
/// Number of clockwise rotations
#[derive(Copy, Clone, PartialEq, Debug, FromPrimitive)]
pub enum Rotations {
Zero,
One,
Two,
Three,
}
#[derive(Copy, Clone)]
pub enum RotateDir {
CW,
CCW,
}
pub fn p<T: Into<Coord>>(x: T, y: T) -> Pos {
Pos::new(x, y)
}
impl Pos {
pub fn new<T: Into<Coord>>(x: T, y: T) -> Pos {
Pos {
x: x.into(),
y: y.into(),
}
}
}
impl Add<Pos> for Pos {
type Output = Pos;
fn add(self, other: Pos) -> Pos {
Pos::new(self.x + other.x, self.y + other.y)
}
}
impl Add<ShiftDir> for Pos {
type Output = Pos;
fn add(self, other: ShiftDir) -> Pos {
Pos::new(
self.x
+ match other {
ShiftDir::Left => -1,
ShiftDir::Right => 1,
},
self.y,
)
}
}
impl Add<RotateDir> for Rotations {
type Output = Self;
fn add(self, other: RotateDir) -> Self {
let delta = match other {
RotateDir::CW => 1,
RotateDir::CCW => 3,
};
Rotations::from_i32((self as i32 + delta) % 4).expect("Unexpected rotation count")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn add_pos() {
assert_eq!(p(1, 2) + p(3, 4), p(4, 6));
}
#[test]
fn shift_pos() {
assert_eq!(p(4, 8) + ShiftDir::Left, p(3, 8));
assert_eq!(p(4, 8) + ShiftDir::Right, p(5, 8));
}
#[test]
fn add_rotations() {
assert_eq!(Rotations::Two, Rotations::One + RotateDir::CW);
assert_eq!(Rotations::Three, Rotations::Zero + RotateDir::CCW);
assert_eq!(Rotations::Zero, Rotations::Three + RotateDir::CW);
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::string::ToString;
use alloc::vec::Vec;
use core::ptr;
use alloc::sync::Arc;
use spin::RwLock;
use core::mem;
use alloc::boxed::Box;
use lazy_static::lazy_static;
use super::arch::x86_64::arch_x86::*;
use super::qlib::linux_def::*;
use super::qlib::common::*;
use super::SignalDef::*;
use super::*;
use super::vcpu::*;
use super::qlib::auth::*;
use super::qlib::task_mgr::*;
use super::qlib::perf_tunning::*;
use super::kernel::time::*;
use super::syscalls::*;
use super::qlib::usage::io::*;
use super::fs::dirent::*;
use super::kernel::uts_namespace::*;
use super::kernel::ipc_namespace::*;
use super::kernel::fd_table::*;
use super::threadmgr::task_exit::*;
use super::threadmgr::task_block::*;
use super::threadmgr::task_syscall::*;
use super::threadmgr::task_sched::*;
use super::threadmgr::thread::*;
use super::kernel::waiter::*;
use super::kernel::futex::*;
use super::kernel::kernel::GetKernelOption;
use super::memmgr::mm::*;
use super::perflog::*;
use super::fs::file::*;
use super::fs::mount::*;
use super::kernel::fs_context::*;
use super::asm::*;
use super::qlib::SysCallID;
const DEFAULT_STACK_SIZE: usize = MemoryDef::DEFAULT_STACK_SIZE as usize;
pub const DEFAULT_STACK_PAGES: u64 = DEFAULT_STACK_SIZE as u64 / (4 * 1024);
pub const DEFAULT_STACK_MAST: u64 = !(DEFAULT_STACK_SIZE as u64 - 1);
lazy_static! {
pub static ref DUMMY_TASK : RwLock<Task> = RwLock::new(Task::DummyTask());
}
pub struct TaskStore {}
impl TaskStore {
pub fn New() -> Self {
return TaskStore {}
}
pub fn CreateTask(runFn: TaskFn, para: *const u8, kernel: bool) -> TaskId {
let t = Task::Create(runFn, para, kernel);
return TaskId::New(t.taskId);
}
pub fn CreateFromThread() -> TaskId {
let t = Task::CreateFromThread();
return TaskId::New(t.taskId);
}
}
impl TaskId {
#[inline]
pub fn GetTask(&self) -> &'static mut Task {
return unsafe { &mut *(self.Addr() as *mut Task) };
}
}
#[derive(Debug, Default)]
#[repr(C)]
pub struct Context {
pub rsp: u64,
pub r15: u64,
pub r14: u64,
pub r13: u64,
pub r12: u64,
pub rbx: u64,
pub rbp: u64,
pub rdi: u64,
pub ready: u64,
pub fs: u64,
pub gs: u64,
pub X86fpstate: Box<X86fpstate>,
pub sigFPState: Vec<Box<X86fpstate>>,
}
impl Context {
pub fn New() -> Self {
return Self {
ready: 1,
..Default::default()
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum TaskState {
Running,
Ready,
Waiting,
Done,
Saving,
}
fn guard() {}
pub type TaskFn = fn(*const u8);
#[derive(Debug, Copy, Clone, Default)]
#[repr(C)]
pub struct TidInfo {
pub set_child_tid: u64,
pub clear_child_tid: Option<u64>,
pub robust_list_head: u64,
}
#[derive(Debug)]
pub struct Guard(u64);
impl Default for Guard {
fn default() -> Self {
return Self(Self::MAGIC_GUILD)
}
}
impl Guard {
const MAGIC_GUILD: u64 = 0x1234567890abcd;
pub fn Check(&self) {
assert!(self.0==Self::MAGIC_GUILD)
}
}
impl Drop for Task {
fn drop(&mut self) {
info!("Task::Drop...");
}
}
#[repr(C)]
pub struct Task {
pub context: Context,
pub taskId: u64,
// job queue id
pub queueId: usize,
pub mm: MemoryManager,
pub tidInfo: TidInfo,
pub isWaitThread: bool,
pub signalStack: SignalStack,
pub creds: Credentials,
pub utsns: UTSNamespace,
pub ipcns: IPCNamespace,
pub fdTbl: FDTable,
pub fsContext: FSContext,
pub mountNS: MountNs,
pub blocker: Blocker,
pub thread: Option<Thread>,
pub haveSyscallReturn: bool,
pub syscallRestartBlock: Option<Box<SyscallRestartBlock>>,
pub futexMgr: FutexMgr,
pub ioUsage: IO,
pub sched: TaskSchedInfo,
pub iovs: Vec<IoVec>,
pub perfcounters: Option<Arc<Counters>>,
pub guard: Guard,
//check whether the stack overflow
}
unsafe impl Sync for Task {}
impl Task {
pub fn Check(&self) {
self.guard.Check();
}
//clean object on stack
pub fn SetDummy(&mut self) {
let dummyTask = DUMMY_TASK.read();
self.mm = dummyTask.mm.clone();
self.mountNS = dummyTask.mountNS.clone();
self.creds = dummyTask.creds.clone();
self.utsns = dummyTask.utsns.clone();
self.ipcns = dummyTask.ipcns.clone();
self.fsContext = dummyTask.fsContext.clone();
self.fdTbl = dummyTask.fdTbl.clone();
self.blocker = dummyTask.blocker.clone();
self.thread = None;
self.syscallRestartBlock = None;
self.futexMgr = dummyTask.futexMgr.clone();
self.perfcounters = None;
self.ioUsage = dummyTask.ioUsage.clone();
}
pub fn SaveFp(&self) {
self.context.X86fpstate.SaveFp();
}
pub fn RestoreFp(&self) {
self.context.X86fpstate.RestoreFp();
}
pub fn DummyTask() -> Self {
let creds = Credentials::default();
let userns = creds.lock().UserNamespace.clone();
return Task {
context: Context::default(),
taskId: 0,
queueId: 0,
//mm: MemoryMgr::default(),
mm: MemoryManager::Init(true),
tidInfo: Default::default(),
isWaitThread: false,
signalStack: Default::default(),
mountNS: MountNs::default(),
creds: creds.clone(),
utsns: UTSNamespace::New("".to_string(), "".to_string(), userns.clone()),
ipcns: IPCNamespace::New(&userns),
fsContext: FSContext::default(),
fdTbl: FDTable::default(),
blocker: Blocker::default(),
thread: None,
haveSyscallReturn: false,
syscallRestartBlock: None,
futexMgr: FUTEX_MGR.clone(),
ioUsage: IO::default(),
sched: TaskSchedInfo::default(),
iovs: Vec::new(),
perfcounters: None,
guard: Guard::default(),
}
}
pub fn AccountTaskEnter(&self, state: SchedState) {
//print!("AccountTaskEnter current task is {:x}", self.taskId);
if self.taskId == CPULocal::WaitTask() {
return
}
let kernel = match GetKernelOption() {
None => return, //kernel is not initialized
Some(k) => k,
};
let now = kernel.CPUClockNow();
let mut t = self.sched.lock();
//info!("AccountTaskEnter[{:x}] current state is {:?} -> {:?}, address is {:x}",
// self.taskId, t.State, state, &t.State as * const _ as u64);
let current = t.State;
match current {
SchedState::RunningSys => {
t.SysTicks += now - t.Timestamp;
}
SchedState::Nonexistent => {}
SchedState::Stopped => {}
_ => {
panic!("AccountTaskEnter: Task[{:x}] switching from state {:?} (expected {:?}) to {:?}",
self.taskId, t.State, SchedState::RunningSys, state)
}
}
t.Timestamp = now;
t.State = state;
}
pub fn AccountTaskLeave(&self, state: SchedState) {
//print!("AccountTaskLeave current task is {:x}, state is {:?}", self.taskId, state);
if self.taskId == CPULocal::WaitTask() {
return
}
let kernel = match GetKernelOption() {
None => return, //kernel is not initialized
Some(k) => k,
};
let now = kernel.CPUClockNow();
let mut t = self.sched.lock();
//info!("AccountTaskLeave[{:x}] current state is {:?} -> {:?}, address is {:x}",
// self.taskId, t.State, SchedState::RunningSys, &t.State as * const _ as u64);
if t.State != state &&
t.State != SchedState::Nonexistent &&
// when doing clone, there is no good way to change new thread stat to runapp. todo: fix this
t.State != SchedState::RunningSys {
panic!("AccountTaskLeave: Task[{:x}] switching from state {:?} (expected {:?}) to {:?}",
self.taskId, t.State, SchedState::RunningSys, state)
}
if state == SchedState::RunningApp {
t.UserTicks += now - t.Timestamp
}
t.Timestamp = now;
t.State = SchedState::RunningSys;
}
// doStop is called to block until the task is not stopped.
pub fn DoStop(&self) {
let thread = match &self.thread {
None => return,
Some(t) => t.clone(),
};
if thread.lock().stopCount.Count() == 0 {
return
}
let stopCount = thread.lock().stopCount.clone();
self.AccountTaskEnter(SchedState::Stopped);
self.blocker.WaitGroupWait(self, &stopCount);
self.AccountTaskLeave(SchedState::Stopped)
}
pub fn SetSyscallRestartBlock(&mut self, b: Box<SyscallRestartBlock>) {
self.syscallRestartBlock = Some(b)
}
pub fn TakeSyscallRestartBlock(&mut self) -> Option<Box<SyscallRestartBlock>> {
return self.syscallRestartBlock.take();
}
pub fn IsChrooted(&self) -> bool {
let kernel = self.Thread().lock().k.clone();
let realRoot = kernel.RootDir();
let root = self.fsContext.RootDirectory();
return root != realRoot;
}
pub fn Root(&self) -> Dirent {
return self.fsContext.RootDirectory();
}
pub fn Workdir(&self) -> Dirent {
return self.fsContext.WorkDirectory();
}
pub fn Umask(&self) -> u32 {
return self.fsContext.Umask();
}
pub fn Creds(&self) -> Credentials {
return self.creds.clone();
}
pub fn GetFile(&self, fd: i32) -> Result<File> {
match self.fdTbl.lock().Get(fd) {
Err(e) => return Err(e),
Ok(f) => return Ok(f.0),
}
}
pub fn GetDescriptor(&self, fd: i32) -> Result<(File, FDFlags)> {
match self.fdTbl.lock().Get(fd) {
Err(e) => return Err(e),
Ok(f) => return Ok((f.0, f.1)),
}
}
pub fn GetFileAll(&self, fd: i32) -> Result<(File, FDFlags)> {
return self.fdTbl.lock().Get(fd);
}
pub fn SetFlags(&self, fd: i32, flags: &FDFlags) -> Result<()> {
return self.fdTbl.lock().SetFlags(fd, flags);
}
pub fn NewFDs(&mut self, fd: i32, file: &[File], flags: &FDFlags) -> Result<Vec<i32>> {
return self.fdTbl.lock().NewFDs(fd, file, flags)
}
pub fn NewFDAt(&mut self, fd: i32, file: &File, flags: &FDFlags) -> Result<()> {
return self.fdTbl.lock().NewFDAt(fd, file, flags)
}
pub fn FileOwner(&self) -> FileOwner {
let creds = self.creds.lock();
let ret = FileOwner {
UID: creds.EffectiveKUID.clone(),
GID: creds.EffectiveKGID.clone(),
};
return ret;
}
pub fn NewStdFds(&mut self, stdfds: &[i32], isTTY: bool) -> Result<()> {
for i in 0..stdfds.len() {
let file = self.NewFileFromHostFd(i as i32, stdfds[i], isTTY)?;
file.flags.lock().0.NonBlocking = false; //need to clean the stdio nonblocking
}
return Ok(())
}
pub fn NewFileFromHostFd(&mut self, fd: i32, hostfd: i32, isTTY: bool) -> Result<File> {
let fileOwner = self.FileOwner();
let file = File::NewFileFromFd(self, hostfd, &fileOwner, isTTY)?;
self.NewFDAt(fd, &Arc::new(file.clone()), &FDFlags::default())?;
return Ok(file);
}
pub fn NewFDFromHostFd(&mut self, hostfd: i32, isTTY: bool, wouldBlock: bool) -> Result<i32> {
let fileOwner = self.FileOwner();
let file = File::NewFileFromFd(self, hostfd, &fileOwner, isTTY)?;
file.flags.lock().0.NonBlocking = !wouldBlock;
let fds = self.NewFDs(0, &[file.clone()], &FDFlags::default())?;
return Ok(fds[0]);
}
pub fn NewFDFrom(&self, fd: i32, file: &File, flags: &FDFlags) -> Result<i32> {
//let fds = self.fdTbl.lock().NewFDs(fd, vec![file.clone()], flags)?;
//return Ok(fds[0])
return self.fdTbl.lock().NewFDFrom(fd, file, flags)
}
pub fn RemoveFile(&self, fd: i32) -> Result<File> {
match self.fdTbl.lock().Remove(fd) {
None => return Err(Error::SysError(SysErr::EBADF)),
Some(f) => {
return Ok(f)
},
}
}
pub fn Dup(&mut self, oldfd: u64) -> i64 {
match self.fdTbl.lock().Dup(oldfd as i32) {
Ok(fd) => fd as i64,
Err(Error::SysError(e)) => -e as i64,
Err(e) => panic!("unsupport error {:?}", e),
}
}
pub fn Dup2(&mut self, oldfd: u64, newfd: u64) -> i64 {
match self.fdTbl.lock().Dup2(oldfd as i32, newfd as i32) {
Ok(fd) => fd as i64,
Err(Error::SysError(e)) => -e as i64,
Err(e) => panic!("unsupport error {:?}", e),
}
}
pub fn Dup3(&mut self, oldfd: u64, newfd: u64, flags: u64) -> i64 {
match self.fdTbl.lock().Dup3(oldfd as i32, newfd as i32, flags as i32) {
Ok(fd) => fd as i64,
Err(Error::SysError(e)) => -e as i64,
Err(e) => panic!("unsupport error {:?}", e),
}
}
#[inline(always)]
pub fn TaskId() -> TaskId {
//let rsp: u64;
//unsafe { llvm_asm!("mov %rsp, $0" : "=r" (rsp) ) };
let rsp = GetRsp();
return TaskId::New(rsp & DEFAULT_STACK_MAST);
}
#[inline(always)]
pub fn GetPtr(&self) -> &'static mut Task {
return unsafe {
&mut *(self.taskId as *mut Task)
}
}
#[inline(always)]
pub fn GetMut(&self) -> &'static mut Task {
return unsafe {
&mut *(self.taskId as *mut Task)
}
}
#[inline(always)]
pub fn GetKernelSp(&self) -> u64 {
return self.taskId + DEFAULT_STACK_SIZE as u64 - 0x10;
}
#[inline(always)]
pub fn GetPtRegs(&self) -> &'static mut PtRegs {
//let addr = self.kernelsp - mem::size_of::<PtRegs>() as u64;
let addr = self.GetKernelSp() - mem::size_of::<PtRegs>() as u64;
return unsafe {
&mut *(addr as *mut PtRegs)
}
}
#[inline(always)]
pub fn SetReturn(&self, val: u64) {
let pt = self.GetPtRegs();
pt.rax = val;
}
#[inline(always)]
pub fn Return(&self) -> u64 {
return self.GetPtRegs().rax
}
const SYSCALL_WIDTH: u64 = 2;
pub fn RestartSyscall(&self) {
let pt = self.GetPtRegs();
pt.rcx -= Self::SYSCALL_WIDTH;
pt.rax = pt.orig_rax;
}
pub fn RestartSyscallWithRestartBlock(&self) {
let pt = self.GetPtRegs();
pt.rcx -= Self::SYSCALL_WIDTH;
pt.rax = SysCallID::sys_restart_syscall as u64;
}
#[inline]
pub fn RealTimeNow() -> Time {
let clock = REALTIME_CLOCK.clone();
return clock.Now();
}
#[inline]
pub fn MonoTimeNow() -> Time {
let clock = MONOTONIC_CLOCK.clone();
return clock.Now();
}
pub fn Now(&self) -> Time {
return Self::RealTimeNow();
}
#[inline(always)]
pub fn Current() -> &'static mut Task {
//let rsp: u64;
//unsafe { llvm_asm!("mov %rsp, $0" : "=r" (rsp) ) };
let rsp = GetRsp();
return Self::GetTask(rsp);
}
#[inline(always)]
pub fn GetTask(addr: u64) -> &'static mut Task {
let addr = addr & DEFAULT_STACK_MAST;
unsafe {
return &mut *(addr as *mut Task);
}
}
pub fn GetTaskIdQ(&self) -> TaskIdQ {
return TaskIdQ::New(self.taskId, self.queueId as u64)
}
pub fn Create(runFn: TaskFn, para: *const u8, kernel: bool) -> &'static mut Self {
//let s_ptr = pa.Alloc(DEFAULT_STACK_PAGES).unwrap() as *mut u8;
let s_ptr = KERNEL_STACK_ALLOCATOR.Allocate().unwrap() as *mut u8;
let size = DEFAULT_STACK_SIZE;
let mut ctx = Context::New();
unsafe {
//ptr::write(s_ptr.offset((size - 24) as isize) as *mut u64, guard as u64);
ptr::write(s_ptr.offset((size - 32) as isize) as *mut u64, runFn as u64);
ctx.rsp = s_ptr.offset((size - 32) as isize) as u64;
ctx.rdi = para as u64;
}
//put Task on the task as Linux
let taskPtr = s_ptr as *mut Task;
unsafe {
let creds = Credentials::default();
let userns = creds.lock().UserNamespace.clone();
ptr::write(taskPtr, Task {
context: ctx,
taskId: s_ptr as u64,
queueId: 0,
mm: MemoryManager::Init(kernel),
tidInfo: Default::default(),
isWaitThread: false,
signalStack: Default::default(),
mountNS: MountNs::default(),
creds: creds.clone(),
utsns: UTSNamespace::New("".to_string(), "".to_string(), userns.clone()),
ipcns: IPCNamespace::New(&userns),
fsContext: FSContext::default(),
fdTbl: FDTable::default(),
blocker: Blocker::New(s_ptr as u64),
thread: None,
haveSyscallReturn: false,
syscallRestartBlock: None,
futexMgr: FUTEX_MGR.Fork(),
ioUsage: DUMMY_TASK.read().ioUsage.clone(),
sched: TaskSchedInfo::default(),
iovs: Vec::with_capacity(4),
perfcounters: Some(THREAD_COUNTS.lock().NewCounters()),
guard: Guard::default(),
});
let new = &mut *taskPtr;
new.PerfGoto(PerfType::Blocked);
new.PerfGoto(PerfType::Kernel);
return &mut (*taskPtr)
}
}
pub fn Thread(&self) -> Thread {
match self.thread.clone() {
None => panic!("Task::Thread panic..."),
Some(t) => t,
}
}
// Wait waits for an event from a thread group that is a child of t's thread
// group, or a task in such a thread group, or a task that is ptraced by t,
// subject to the options specified in opts.
pub fn Wait(&self, opts: &WaitOptions) -> Result<WaitResult> {
if opts.BlockInterruptErr.is_none() {
return self.Thread().waitOnce(opts);
}
let tg = self.Thread().lock().tg.clone();
let queue = tg.lock().eventQueue.clone();
queue.EventRegister(self, &self.blocker.generalEntry, opts.Events);
defer!(queue.EventUnregister(self, &self.blocker.generalEntry));
loop {
match self.Thread().waitOnce(opts) {
Ok(wr) => {
return Ok(wr);
}
Err(Error::ErrNoWaitableEvent) => {}
Err(e) => {
return Err(e)
}
};
match self.blocker.BlockGeneral() {
Err(Error::ErrInterrupted) => {
return Err(opts.BlockInterruptErr.clone().unwrap());
}
_ => (),
}
}
}
pub fn Exit(&mut self) {
self.blocker.Drop();
self.ExitWithCode(ExitStatus::default());
}
pub fn ExitWithCode(&mut self, _exitCode: ExitStatus) {
if self.isWaitThread {
panic!("Exit from wait thread!")
}
match self.tidInfo.clear_child_tid {
None => {
//println!("there is no clear_child_tid");
}
Some(addr) => {
self.CopyOutObj(&(0 as i32), addr).ok();
}
}
}
pub fn CreateFromThread() -> &'static mut Self {
let baseStackAddr = Self::TaskId().Addr();
let taskPtr = baseStackAddr as *mut Task;
unsafe {
let creds = Credentials::default();
let userns = creds.lock().UserNamespace.clone();
let dummyTask = DUMMY_TASK.read();
ptr::write(taskPtr, Task {
context: Context::New(),
taskId: baseStackAddr,
queueId: 0,
//mm: MemoryManager::Init(), //
mm: dummyTask.mm.clone(),
tidInfo: Default::default(),
isWaitThread: true,
signalStack: Default::default(),
mountNS: MountNs::default(),
creds: creds.clone(),
utsns: UTSNamespace::New("".to_string(), "".to_string(), userns.clone()),
ipcns: IPCNamespace::New(&userns),
fsContext: FSContext::default(),
fdTbl: FDTable::default(),
blocker: Blocker::New(baseStackAddr),
thread: None,
haveSyscallReturn: false,
syscallRestartBlock: None,
futexMgr: FUTEX_MGR.clone(),
ioUsage: dummyTask.ioUsage.clone(),
sched: TaskSchedInfo::default(),
iovs: Vec::new(),
perfcounters: None,
guard: Guard::default(),
});
return &mut (*taskPtr)
}
}
#[inline]
pub fn SwitchPageTable(&self) {
let root = self.mm.GetRoot();
super::qlib::pagetable::PageTables::Switch(root);
}
pub fn SetKernelPageTable() {
KERNEL_PAGETABLE.SwitchTo();
}
#[inline]
pub fn SetFS(&self) {
SetFs(self.context.fs);
}
#[inline]
pub fn GetContext(&self) -> u64 {
return (&self.context as *const Context) as u64;
}
//todo: remove this
pub fn Open(&mut self, fileName: u64, flags: u64, _mode: u64) -> i64 {
//todo: mode?
match sys_file::openAt(self, ATType::AT_FDCWD, fileName, flags as u32) {
Ok(fd) => return fd as i64,
Err(Error::SysError(e)) => return -e as i64,
_ => panic!("Open get unknown failure"),
}
}
pub fn SignalStack(&self) -> SignalStack {
let mut alt = self.signalStack;
if self.OnSignalStack(&alt) {
alt.flags |= SignalStack::FLAG_ON_STACK
}
return alt
}
pub fn OnSignalStack(&self, alt: &SignalStack) -> bool {
let sp = self.GetPtRegs().rsp;
return alt.Contains(sp)
}
pub fn SetSignalStack(&mut self, alt: SignalStack) -> bool {
let mut alt = alt;
if self.OnSignalStack(&self.signalStack) {
return false; //I am on the signal stack, can't change
}
if !alt.IsEnable() {
self.signalStack = SignalStack {
flags: SignalStack::FLAG_DISABLE,
..Default::default()
}
} else {
alt.flags &= SignalStack::FLAG_DISABLE;
self.signalStack = alt;
}
return true;
}
// CloneSignalStack sets the task-private signal stack.
//
// This value may not be changed if the task is currently executing on the
// signal stack, i.e. if t.onSignalStack returns true. In this case, this
// function will return false. Otherwise, true is returned.
pub fn CloneSignalStack(&self) -> SignalStack {
let mut alt = self.signalStack;
let mut ret = SignalStack::default();
// Check that we're not executing on the stack.
if self.OnSignalStack(&alt) {
return ret;
}
if alt.flags & SignalStack::FLAG_DISABLE != 0 {
// Don't record anything beyond the flags.
ret = SignalStack {
flags: SignalStack::FLAG_DISABLE,
..Default::default()
};
} else {
// Mask out irrelevant parts: only disable matters.
alt.flags &= SignalStack::FLAG_DISABLE;
ret = alt;
}
return ret;
}
}
|
use core::JsRuntime;
fn main() {
let mut runtime = JsRuntime::new(Default::default());
runtime
.execute(
"<init>",
r#"
const toLog = [
SharedArrayBuffer,
ArrayBuffer,
Float64Array,
WebAssembly,
eval,
Math,
RegExp,
Atomics,
BigInt,
Date,
JSON,
Map,
Reflect,
];
toLog.forEach((item) => {
runtime.print(item);
runtime.print("\n");
});
"#,
)
.unwrap();
} |
use std::{error::Error, io, path::Path};
use serde::{Serialize, Deserialize};
pub const DEFAULT_CONFIG_PATH: &str = "./config.json";
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum DownloadQuality {
Raw,
Full,
Regular,
Small,
Thumb
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Config {
pub repeat_secs: u64,
pub update_interval: u64,
pub quality: DownloadQuality,
pub unsplash_access_key: Option<String>,
pub openweather_access_key: Option<String>,
pub city_weather: String,
pub disable_cache: bool
}
impl Config {
pub fn from_path(path: &str) -> Result<Config, Box<dyn Error>> {
let path = Path::new(path);
if path.exists() {
return Ok(serde_json::from_str(&std::fs::read_to_string(&path)?)?)
}
let config = Config {
repeat_secs: 1,
update_interval: 3600,
quality: DownloadQuality::Full,
unsplash_access_key: None,
openweather_access_key: None,
city_weather: String::from("Dublin"),
disable_cache: true
};
let config_str = serde_json::to_string(&config)?;
std::fs::write(path, config_str)?;
Ok(config)
}
pub fn save(&self) -> Result<(), io::Error> {
let config_str = serde_json::to_string(self)?;
std::fs::write(DEFAULT_CONFIG_PATH, config_str)?;
Ok(())
}
}
|
/*
* Open Service Cloud API
*
* Open Service Cloud API to manage different backend cloud services.
*
* The version of the OpenAPI document: 0.0.3
* Contact: wanghui71leon@gmail.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudServerResourceFragmentFlavor {
#[serde(rename = "id", skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "name", skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "disk", skip_serializing_if = "Option::is_none")]
pub disk: Option<String>,
#[serde(rename = "vcpus", skip_serializing_if = "Option::is_none")]
pub vcpus: Option<String>,
#[serde(rename = "ram", skip_serializing_if = "Option::is_none")]
pub ram: Option<String>,
}
impl CloudServerResourceFragmentFlavor {
pub fn new() -> CloudServerResourceFragmentFlavor {
CloudServerResourceFragmentFlavor {
id: None,
name: None,
disk: None,
vcpus: None,
ram: None,
}
}
}
|
#[doc = "Reader of register M4FDRL"]
pub type R = crate::R<u32, super::M4FDRL>;
#[doc = "Writer for register M4FDRL"]
pub type W = crate::W<u32, super::M4FDRL>;
#[doc = "Register M4FDRL `reset()`'s with value 0"]
impl crate::ResetValue for super::M4FDRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `FDATAH`"]
pub type FDATAH_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `FDATAH`"]
pub struct FDATAH_W<'a> {
w: &'a mut W,
}
impl<'a> FDATAH_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:31 - Failing data high (64-bit memory)"]
#[inline(always)]
pub fn fdatah(&self) -> FDATAH_R {
FDATAH_R::new((self.bits & 0xffff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:31 - Failing data high (64-bit memory)"]
#[inline(always)]
pub fn fdatah(&mut self) -> FDATAH_W {
FDATAH_W { w: self }
}
}
|
use sqlx::{postgres::PgDone, PgPool};
use crate::application::dtos::answer_question_dto::AnswerQuestionData;
pub async fn insert(pool: &PgPool, answer: &AnswerQuestionData) -> Result<PgDone, sqlx::Error> {
sqlx::query_file!(
"src/infrastructure/repositories/sql/insert_student_answer.sql",
answer.id_student,
answer.id_question,
answer.id_answer,
answer.id_student_exam
)
.execute(pool)
.await
}
|
use std::cmp::Ordering;
use std::collections::VecDeque;
use std::f32::consts::PI;
use std::fs::File;
use std::io::{BufRead, BufReader, Error as IOError};
use std::ops::{Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Sub, SubAssign};
use sdl2::{keyboard::Keycode, pixels::Color, rect::Point, render::Canvas, video::Window};
use smallvec::SmallVec;
use snafu::Snafu;
use super::sdl_ext::{fill_polygon, Pt};
const FAR: f32 = 1000.0;
const NEAR: f32 = 0.1;
static UP: Vec3D = Vec3D::new(0.0, 1.0, 0.0);
static TARGET: Vec3D = Vec3D::new(0.0, 0.0, 1.0);
static PLANE_P: Vec3D = Vec3D::new(0.0, 0.0, 0.1);
static PLANE_N: Vec3D = Vec3D::new(0.0, 0.0, 1.0);
static OFFSET_VIEW: Vec3D = Vec3D::new(1.0, 1.0, 0.0);
#[derive(Debug, Snafu)]
pub(crate) enum WorldError {
#[snafu(display("IO Error: {}", e))]
IO { e: IOError },
#[snafu(display("SDL Error: {}", msg))]
SDL { msg: String },
#[snafu(display("Cannot parse object file: {}", msg))]
Parsing { msg: String },
}
impl WorldError {
fn sdl_error(msg: impl Into<String>) -> Self {
WorldError::SDL { msg: msg.into() }
}
fn parsing(msg: impl Into<String>) -> Self {
WorldError::Parsing { msg: msg.into() }
}
}
impl From<IOError> for WorldError {
fn from(from: IOError) -> Self {
WorldError::IO { e: from }
}
}
#[derive(Debug)]
pub(crate) struct World {
mesh_cube: Mesh,
triangles_to_raster: Vec<Triangle>,
triangles_to_clip: VecDeque<Triangle>,
camera: Vec3D,
look_dir: Vec3D,
yaw: f32,
yaw_diff: f32,
direction_of_travel: Vec3D,
theta: f32,
}
impl World {
pub(crate) fn new() -> Result<Self, WorldError> {
let mesh_cube = Mesh::from_object_file("mountains.obj")?;
Ok(World {
mesh_cube,
triangles_to_raster: Vec::new(),
triangles_to_clip: VecDeque::new(),
camera: Vec3D::default(),
look_dir: Vec3D::default(),
yaw: 0.0,
yaw_diff: 0.0,
direction_of_travel: Vec3D::default(),
theta: 0.0,
})
}
pub(crate) fn handle_key(&mut self, keycode: Keycode, elapsed_time: f32) {
match keycode {
Keycode::Up => {
let up = UP * (32.0 * elapsed_time);
self.direction_of_travel += up;
}
Keycode::Down => {
let up = UP * (32.0 * elapsed_time);
self.direction_of_travel -= up;
}
Keycode::Left => {
let left = (self.look_dir * Mat4x4::rotation_y(PI / 2.0)).normalise()
* (32.0 * elapsed_time);
self.direction_of_travel -= left;
}
Keycode::Right => {
let left = (self.look_dir * Mat4x4::rotation_y(PI / 2.0)).normalise()
* (32.0 * elapsed_time);
self.direction_of_travel += left;
}
Keycode::W => {
let forward = self.look_dir * (32.0 * elapsed_time);
self.direction_of_travel += forward;
}
Keycode::S => {
let forward = self.look_dir * (32.0 * elapsed_time);
self.direction_of_travel -= forward;
}
Keycode::A => self.yaw_diff -= 2.0 * elapsed_time,
Keycode::D => self.yaw_diff += 2.0 * elapsed_time,
_ => (),
}
}
pub(crate) fn do_tick(
&mut self,
canvas: &mut Canvas<Window>,
_elapsed_time: f32,
) -> Result<(), WorldError> {
let window = canvas.window();
let (window_width, window_height) = window.size();
let aspect_ratio = window_height as f32 / window_width as f32;
self.camera += self.direction_of_travel;
self.direction_of_travel *= 0.9;
self.yaw += self.yaw_diff;
self.yaw_diff *= 0.9;
let mat_proj = Mat4x4::projection(60.0, aspect_ratio, NEAR, FAR);
let mat_rot_z = Mat4x4::rotation_z(self.theta / 2.0);
let mat_rot_x = Mat4x4::rotation_x(self.theta);
let mat_trans = Mat4x4::translation(0.0, 0.0, 5.0);
let mat_world = mat_rot_z * mat_rot_x;
let mat_world = mat_world * mat_trans;
let mat_camera_rot = Mat4x4::rotation_y(self.yaw);
self.look_dir = TARGET * mat_camera_rot;
let target = self.camera + self.look_dir;
let mat_camera = self.camera.point_at(&target, &UP);
let mat_view = mat_camera.quick_inverse();
self.triangles_to_raster.clear();
for tri in self.mesh_cube.0.iter() {
let mut tri_transformed =
Triangle::new(tri[0] * mat_world, tri[1] * mat_world, tri[2] * mat_world);
let line_1 = tri_transformed[1] - tri_transformed[0];
let line_2 = tri_transformed[2] - tri_transformed[0];
let normal = line_1.cross_product(&line_2).normalise();
let camera_ray = tri_transformed[0] - self.camera;
if normal.dot_product(&camera_ray) < 0.0 {
let light_direction = Vec3D::new(0.0, 1.0, -1.0).normalise();
let mut dp = light_direction.dot_product(&normal);
if dp < 0.1 {
dp = 0.1
}
tri_transformed.col = (255.0 * dp) as u8;
tri_transformed[0] *= mat_view;
tri_transformed[1] *= mat_view;
tri_transformed[2] *= mat_view;
let clipped_triangles = tri_transformed.clip_against_plane(&PLANE_P, &PLANE_N);
for mut clipped_tri in clipped_triangles {
clipped_tri[0] *= mat_proj;
clipped_tri[1] *= mat_proj;
clipped_tri[2] *= mat_proj;
clipped_tri[0] = clipped_tri[0] / clipped_tri[0].w;
clipped_tri[1] = clipped_tri[1] / clipped_tri[1].w;
clipped_tri[2] = clipped_tri[2] / clipped_tri[2].w;
clipped_tri[0].x *= -1.0;
clipped_tri[1].x *= -1.0;
clipped_tri[2].x *= -1.0;
clipped_tri[0].y *= -1.0;
clipped_tri[1].y *= -1.0;
clipped_tri[2].y *= -1.0;
clipped_tri[0] += OFFSET_VIEW;
clipped_tri[1] += OFFSET_VIEW;
clipped_tri[2] += OFFSET_VIEW;
clipped_tri[0].x *= 0.5 * window_width as f32;
clipped_tri[0].y *= 0.5 * window_height as f32;
clipped_tri[1].x *= 0.5 * window_width as f32;
clipped_tri[1].y *= 0.5 * window_height as f32;
clipped_tri[2].x *= 0.5 * window_width as f32;
clipped_tri[2].y *= 0.5 * window_height as f32;
self.triangles_to_raster.push(clipped_tri);
}
}
}
self.triangles_to_raster.sort_by(|t1, t2| {
let z1 = (t1[0].z + t1[1].z + t1[2].z) / 3.0;
let z2 = (t2[0].z + t2[1].z + t2[2].z) / 3.0;
z2.partial_cmp(&z1).unwrap_or(Ordering::Equal)
});
for tri in self.triangles_to_raster.drain(..) {
self.triangles_to_clip.push_back(tri);
let mut new_triangles = 1;
for p in 0..4 {
while new_triangles > 0 {
let test = self
.triangles_to_clip
.pop_front()
.expect("Already tested for...");
new_triangles -= 1;
let (plane_p, plane_n) = match p {
0 => (Vec3D::new(0.0, 0.0, 0.0), Vec3D::new(0.0, 1.0, 0.0)),
1 => (
Vec3D::new(0.0, window_height as f32 - 1.0, 0.0),
Vec3D::new(0.0, -1.0, 0.0),
),
2 => (Vec3D::new(0.0, 0.0, 0.0), Vec3D::new(1.0, 0.0, 0.0)),
3 => (
Vec3D::new(window_width as f32 - 1.0, 0.0, 0.0),
Vec3D::new(-1.0, 0.0, 0.0),
),
_x => unreachable!(),
};
self.triangles_to_clip
.extend(test.clip_against_plane(&plane_p, &plane_n));
}
new_triangles = self.triangles_to_clip.len();
}
for tri in self.triangles_to_clip.drain(..) {
tri.fill(canvas)?;
}
}
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
struct Vec3D {
x: f32,
y: f32,
z: f32,
w: f32,
}
impl Vec3D {
const fn new(x: f32, y: f32, z: f32) -> Self {
Vec3D { x, y, z, w: 0.0 }
}
fn len(&self) -> f32 {
self.dot_product(self).sqrt()
}
fn normalise(&self) -> Vec3D {
let l = self.len();
Vec3D::new(self.x / l, self.y / l, self.z / l)
}
fn dot_product(&self, other: &Vec3D) -> f32 {
self.x * other.x + self.y * other.y + self.z * other.z
}
fn cross_product(&self, other: &Vec3D) -> Vec3D {
Vec3D::new(
self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x,
)
}
fn point_at(&self, target: &Vec3D, up: &Vec3D) -> Mat4x4 {
let new_forward = (*target - *self).normalise();
let a = new_forward * up.dot_product(&new_forward);
let new_up = *up - a;
let new_right = new_up.cross_product(&new_forward);
let mut m = Mat4x4::default();
m[0][0] = new_right.x;
m[0][1] = new_right.y;
m[0][2] = new_right.z;
m[0][3] = 0.0;
m[1][0] = new_up.x;
m[1][1] = new_up.y;
m[1][2] = new_up.z;
m[1][3] = 0.0;
m[2][0] = new_forward.x;
m[2][1] = new_forward.y;
m[2][2] = new_forward.z;
m[2][3] = 0.0;
m[3][0] = self.x;
m[3][1] = self.y;
m[3][2] = self.z;
m[3][3] = 1.0;
m
}
}
fn intersect_plane(
plane_p: &Vec3D,
plane_n: &Vec3D,
line_start: &Vec3D,
line_end: &Vec3D,
) -> Vec3D {
let plane_n = plane_n.normalise();
let plane_d = -plane_n.dot_product(plane_p);
let ad = line_start.dot_product(&plane_n);
let bd = line_end.dot_product(&plane_n);
let t = (-plane_d - ad) / (bd - ad);
let line_start_to_end = *line_end - *line_start;
let line_to_intersect = line_start_to_end * t;
*line_start + line_to_intersect
}
impl Default for Vec3D {
fn default() -> Self {
Vec3D {
x: 0.0,
y: 0.0,
z: 0.0,
w: 1.0,
}
}
}
impl Mul<Mat4x4> for Vec3D {
type Output = Vec3D;
fn mul(self, rhs: Mat4x4) -> Self::Output {
let x = self.x * rhs[0][0] + self.y * rhs[1][0] + self.z * rhs[2][0] + rhs[3][0];
let y = self.x * rhs[0][1] + self.y * rhs[1][1] + self.z * rhs[2][1] + rhs[3][1];
let z = self.x * rhs[0][2] + self.y * rhs[1][2] + self.z * rhs[2][2] + rhs[3][2];
let w = self.x * rhs[0][3] + self.y * rhs[1][3] + self.z * rhs[2][3] + rhs[3][3];
Vec3D { x, y, z, w }
}
}
impl MulAssign<Mat4x4> for Vec3D {
fn mul_assign(&mut self, rhs: Mat4x4) {
let x = self.x * rhs[0][0] + self.y * rhs[1][0] + self.z * rhs[2][0] + rhs[3][0];
let y = self.x * rhs[0][1] + self.y * rhs[1][1] + self.z * rhs[2][1] + rhs[3][1];
let z = self.x * rhs[0][2] + self.y * rhs[1][2] + self.z * rhs[2][2] + rhs[3][2];
let w = self.x * rhs[0][3] + self.y * rhs[1][3] + self.z * rhs[2][3] + rhs[3][3];
self.x = x;
self.y = y;
self.z = z;
self.w = w;
}
}
impl Add<Vec3D> for Vec3D {
type Output = Vec3D;
fn add(self, rhs: Vec3D) -> Self::Output {
Vec3D::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
}
}
impl AddAssign<Vec3D> for Vec3D {
fn add_assign(&mut self, rhs: Vec3D) {
self.x += rhs.x;
self.y += rhs.y;
self.z += rhs.z;
}
}
impl Sub<Vec3D> for Vec3D {
type Output = Vec3D;
fn sub(self, rhs: Vec3D) -> Self::Output {
Vec3D::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
}
}
impl SubAssign<Vec3D> for Vec3D {
fn sub_assign(&mut self, rhs: Vec3D) {
self.x -= rhs.x;
self.y -= rhs.y;
self.z -= rhs.z;
}
}
impl Mul<f32> for Vec3D {
type Output = Vec3D;
fn mul(self, rhs: f32) -> Self::Output {
Vec3D::new(self.x * rhs, self.y * rhs, self.z * rhs)
}
}
impl MulAssign<f32> for Vec3D {
fn mul_assign(&mut self, rhs: f32) {
self.x *= rhs;
self.y *= rhs;
self.z *= rhs;
self.w = 0.0;
}
}
impl Div<f32> for Vec3D {
type Output = Vec3D;
fn div(self, rhs: f32) -> Self::Output {
Vec3D::new(self.x / rhs, self.y / rhs, self.z / rhs)
}
}
impl DivAssign<f32> for Vec3D {
fn div_assign(&mut self, rhs: f32) {
self.x /= rhs;
self.y /= rhs;
self.z /= rhs;
}
}
#[derive(Debug, Clone, Copy, Default)]
struct Triangle {
p: [Vec3D; 3],
col: u8,
}
impl Triangle {
fn new(a: Vec3D, b: Vec3D, c: Vec3D) -> Self {
Triangle {
p: [a, b, c],
..Default::default()
}
}
#[allow(dead_code)]
fn draw(&self, canvas: &mut Canvas<Window>) -> Result<(), WorldError> {
canvas.set_draw_color(Color::RGB(255, self.col, self.col));
let points = [
Point::new(self[0].x as i32, self[0].y as i32),
Point::new(self[1].x as i32, self[1].y as i32),
Point::new(self[2].x as i32, self[2].y as i32),
Point::new(self[0].x as i32, self[0].y as i32),
];
canvas
.draw_lines(&points[..])
.map_err(|e| WorldError::sdl_error(format!("Cannot draw lines: {}", e)))
}
fn fill(&self, canvas: &mut Canvas<Window>) -> Result<(), WorldError> {
canvas.set_draw_color(Color::RGB(self.col, self.col, self.col));
let points = [
Pt::new(self[0].x as i32, self[0].y as i32),
Pt::new(self[1].x as i32, self[1].y as i32),
Pt::new(self[2].x as i32, self[2].y as i32),
Pt::new(self[0].x as i32, self[0].y as i32),
];
fill_polygon(canvas, &points[..])
.map_err(|e| WorldError::sdl_error(format!("Cannot fill polygon: {}", e)))
}
fn clip_against_plane(&self, plane_p: &Vec3D, plane_n: &Vec3D) -> SmallVec<[Triangle; 2]> {
let plane_n = plane_n.normalise();
let dist = |p: &Vec3D| {
plane_n.x * p.x + plane_n.y * p.y + plane_n.z * p.z - plane_n.dot_product(plane_p)
};
let mut inside_points = SmallVec::<[&Vec3D; 3]>::new();
let mut outside_points = SmallVec::<[&Vec3D; 3]>::new();
for idx in 0..3 {
let d = dist(&self[idx]);
if d >= 0.0 {
inside_points.push(&self[idx])
} else {
outside_points.push(&self[idx])
}
}
let inside_points_count = inside_points.len();
let outside_points_count = outside_points.len();
let mut result = SmallVec::new();
if inside_points_count == 0 {
return result;
}
if inside_points_count == 3 {
result.push(*self);
return result;
}
if inside_points_count == 1 && outside_points_count == 2 {
let mut tri = *self;
tri[0] = *inside_points[0];
tri[1] = intersect_plane(plane_p, &plane_n, &inside_points[0], &outside_points[0]);
tri[2] = intersect_plane(plane_p, &plane_n, &inside_points[0], &outside_points[1]);
result.push(tri);
return result;
}
if inside_points_count == 2 && outside_points_count == 1 {
let mut tri_1 = *self;
let mut tri_2 = *self;
tri_1[0] = *inside_points[0];
tri_1[1] = *inside_points[1];
tri_1[2] = intersect_plane(plane_p, &plane_n, &inside_points[0], &outside_points[0]);
tri_2[0] = *inside_points[1];
tri_2[1] = tri_1[2];
tri_2[2] = intersect_plane(plane_p, &plane_n, &inside_points[1], &outside_points[0]);
result.push(tri_1);
result.push(tri_2);
return result;
}
unreachable!()
}
}
impl Index<usize> for Triangle {
type Output = Vec3D;
fn index(&self, index: usize) -> &Self::Output {
&self.p[index]
}
}
impl IndexMut<usize> for Triangle {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.p[index]
}
}
impl Mul<Mat4x4> for Triangle {
type Output = Triangle;
fn mul(self, rhs: Mat4x4) -> Self::Output {
Triangle::new(self[0] * rhs, self[1] * rhs, self[2] * rhs)
}
}
#[derive(Debug)]
struct Mesh(Vec<Triangle>);
impl Mesh {
fn from_object_file(filename: &str) -> Result<Self, WorldError> {
let file = File::open(filename)?;
let mut verts = Vec::new();
let mut triangles = Vec::new();
for line in BufReader::new(file).lines() {
let line = line?;
let parse_float = |s: &str| {
s.parse()
.map_err(|e| WorldError::parsing(format!("Cannot parse {}, {}", line, e)))
};
let parse_int = |s: &str| {
s.parse::<usize>()
.map_err(|e| WorldError::parsing(format!("Cannot parse {}, {}", line, e)))
};
let mut split_line = line.split(' ');
match (
split_line.next(),
split_line.next(),
split_line.next(),
split_line.next(),
) {
(Some("#"), _, _, _) => (),
(Some("v"), Some(v1), Some(v2), Some(v3)) => verts.push(Vec3D::new(
parse_float(v1)?,
parse_float(v2)?,
parse_float(v3)?,
)),
(Some("s"), _, _, _) => (),
(Some("f"), Some(f1), Some(f2), Some(f3)) => triangles.push(Triangle::new(
verts[parse_int(f1)? - 1],
verts[parse_int(f2)? - 1],
verts[parse_int(f3)? - 1],
)),
_ => {
return Err(WorldError::parsing(format!(
"Object file not in correct format: {}",
line
)))
}
}
}
Ok(Mesh(triangles))
}
}
#[derive(Debug, Copy, Clone, Default)]
struct Mat4x4([[f32; 4]; 4]);
impl Mat4x4 {
fn rotation_x(angle_rad: f32) -> Self {
let mut m = Mat4x4::default();
m[0][0] = 1.0;
m[1][1] = angle_rad.cos();
m[1][2] = angle_rad.sin();
m[2][1] = -angle_rad.sin();
m[2][2] = angle_rad.cos();
m[3][3] = 1.0;
m
}
fn rotation_y(angle_rad: f32) -> Self {
let mut m = Mat4x4::default();
m[0][0] = angle_rad.cos();
m[0][2] = angle_rad.sin();
m[2][0] = -angle_rad.sin();
m[1][1] = 1.0;
m[2][2] = angle_rad.cos();
m[3][3] = 1.0;
m
}
fn rotation_z(angle_rad: f32) -> Self {
let mut m = Mat4x4::default();
m[0][0] = angle_rad.cos();
m[0][1] = angle_rad.sin();
m[1][0] = -angle_rad.sin();
m[1][1] = angle_rad.cos();
m[2][2] = 1.0;
m[3][3] = 1.0;
m
}
fn translation(x: f32, y: f32, z: f32) -> Self {
let mut m = Mat4x4::default();
m[0][0] = 1.0;
m[1][1] = 1.0;
m[2][2] = 1.0;
m[3][3] = 1.0;
m[3][0] = x;
m[3][1] = y;
m[3][2] = z;
m
}
fn projection(fov_degrees: f32, aspect_ratio: f32, near: f32, far: f32) -> Self {
let fov_rad = 1.0 / (fov_degrees * 0.5 / 180.0 * PI).tan();
let mut m = Mat4x4::default();
m[0][0] = aspect_ratio * fov_rad;
m[1][1] = fov_rad;
m[2][2] = far / (far - near);
m[3][2] = (-far * near) / (far - near);
m[2][3] = 1.0;
m[3][3] = 0.0;
m
}
fn quick_inverse(&self) -> Self {
let mut m = Mat4x4::default();
m[0][0] = self[0][0];
m[0][1] = self[1][0];
m[0][2] = self[2][0];
m[0][3] = 0.0;
m[1][0] = self[0][1];
m[1][1] = self[1][1];
m[1][2] = self[2][1];
m[1][3] = 0.0;
m[2][0] = self[0][2];
m[2][1] = self[1][2];
m[2][2] = self[2][2];
m[2][3] = 0.0;
m[3][0] = -(self[3][0] * m[0][0] + self[3][1] * m[1][0] + self[3][2] * m[2][0]);
m[3][1] = -(self[3][0] * m[0][1] + self[3][1] * m[1][1] + self[3][2] * m[2][1]);
m[3][2] = -(self[3][0] * m[0][2] + self[3][1] * m[1][2] + self[3][2] * m[2][2]);
m[3][3] = 1.0;
m
}
}
impl Index<usize> for Mat4x4 {
type Output = [f32; 4];
fn index(&self, index: usize) -> &Self::Output {
&self.0[index]
}
}
impl IndexMut<usize> for Mat4x4 {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.0[index]
}
}
impl Mul<Mat4x4> for Mat4x4 {
type Output = Mat4x4;
fn mul(self, rhs: Mat4x4) -> Self::Output {
let mut m = Mat4x4::default();
for c in 0..4 {
for r in 0..4 {
m[r][c] = self[r][0] * rhs[0][c]
+ self[r][1] * rhs[1][c]
+ self[r][2] * rhs[2][c]
+ self[r][3] * rhs[3][c];
}
}
m
}
}
|
use amethyst::{
ecs::prelude::*,
renderer::Rgba,
};
use amethyst_imgui::imgui;
use crate::Inspect;
impl<'a> Inspect<'a> for Rgba {
type SystemData = (ReadStorage<'a, Self>, Read<'a, LazyUpdate>);
const CAN_ADD: bool = true;
fn inspect((storage, lazy): &mut Self::SystemData, entity: Entity, ui: &imgui::Ui<'_>) {
let me = if let Some(x) = storage.get(entity) {
x
} else {
return;
};
let mut v: [f32; 4] = [me.0, me.1, me.2, me.3];
ui.drag_float4(imgui::im_str!("colour tint##rgba{:?}", entity), &mut v)
.speed(0.005)
.build();
if *me != Rgba::from(v) {
lazy.insert(entity, Rgba::from(v));
}
}
fn add((_storage, lazy): &mut Self::SystemData, entity: Entity) {
lazy.insert(entity, amethyst::renderer::Rgba::white());
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qjsonvalue.h
// dst-file: /src/core/qjsonvalue.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
use super::qjsonobject::*; // 773
use super::qstring::*; // 773
use super::qjsonarray::*; // 773
use super::qvariant::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QJsonValueRefPtr_Class_Size() -> c_int;
fn QJsonValuePtr_Class_Size() -> c_int;
fn QJsonValue_Class_Size() -> c_int;
// proto: QJsonObject QJsonValue::toObject();
fn C_ZNK10QJsonValue8toObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QJsonValue::isDouble();
fn C_ZNK10QJsonValue8isDoubleEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QJsonValue::QJsonValue(const QString & s);
fn C_ZN10QJsonValueC2ERK7QString(arg0: *mut c_void) -> u64;
// proto: int QJsonValue::toInt(int defaultValue);
fn C_ZNK10QJsonValue5toIntEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int;
// proto: QJsonArray QJsonValue::toArray();
fn C_ZNK10QJsonValue7toArrayEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QJsonValue::isArray();
fn C_ZNK10QJsonValue7isArrayEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QJsonValue::QJsonValue(const char * s);
fn C_ZN10QJsonValueC2EPKc(arg0: *mut c_char) -> u64;
// proto: QString QJsonValue::toString(const QString & defaultValue);
fn C_ZNK10QJsonValue8toStringERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: double QJsonValue::toDouble(double defaultValue);
fn C_ZNK10QJsonValue8toDoubleEd(qthis: u64 /* *mut c_void*/, arg0: c_double) -> c_double;
// proto: void QJsonValue::~QJsonValue();
fn C_ZN10QJsonValueD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QVariant QJsonValue::toVariant();
fn C_ZNK10QJsonValue9toVariantEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QJsonValue::isObject();
fn C_ZNK10QJsonValue8isObjectEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: static QJsonValue QJsonValue::fromVariant(const QVariant & variant);
fn C_ZN10QJsonValue11fromVariantERK8QVariant(arg0: *mut c_void) -> *mut c_void;
// proto: bool QJsonValue::toBool(bool defaultValue);
fn C_ZNK10QJsonValue6toBoolEb(qthis: u64 /* *mut c_void*/, arg0: c_char) -> c_char;
// proto: void QJsonValue::QJsonValue(double n);
fn C_ZN10QJsonValueC2Ed(arg0: c_double) -> u64;
// proto: bool QJsonValue::isBool();
fn C_ZNK10QJsonValue6isBoolEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QJsonValue::QJsonValue(bool b);
fn C_ZN10QJsonValueC2Eb(arg0: c_char) -> u64;
// proto: bool QJsonValue::isUndefined();
fn C_ZNK10QJsonValue11isUndefinedEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QJsonValue::isNull();
fn C_ZNK10QJsonValue6isNullEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QJsonValue::isString();
fn C_ZNK10QJsonValue8isStringEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QJsonValue::QJsonValue(int n);
fn C_ZN10QJsonValueC2Ei(arg0: c_int) -> u64;
// proto: void QJsonValue::QJsonValue(qint64 n);
fn C_ZN10QJsonValueC2Ex(arg0: c_longlong) -> u64;
fn QJsonValueRef_Class_Size() -> c_int;
// proto: QJsonArray QJsonValueRef::toArray();
fn C_ZNK13QJsonValueRef7toArrayEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QJsonObject QJsonValueRef::toObject();
fn C_ZNK13QJsonValueRef8toObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QJsonValueRef::isBool();
fn C_ZNK13QJsonValueRef6isBoolEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QJsonValueRef::isDouble();
fn C_ZNK13QJsonValueRef8isDoubleEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: double QJsonValueRef::toDouble();
fn C_ZNK13QJsonValueRef8toDoubleEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: bool QJsonValueRef::toBool(bool defaultValue);
fn C_ZNK13QJsonValueRef6toBoolEb(qthis: u64 /* *mut c_void*/, arg0: c_char) -> c_char;
// proto: double QJsonValueRef::toDouble(double defaultValue);
fn C_ZNK13QJsonValueRef8toDoubleEd(qthis: u64 /* *mut c_void*/, arg0: c_double) -> c_double;
// proto: bool QJsonValueRef::toBool();
fn C_ZNK13QJsonValueRef6toBoolEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QVariant QJsonValueRef::toVariant();
fn C_ZNK13QJsonValueRef9toVariantEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QString QJsonValueRef::toString(const QString & defaultValue);
fn C_ZNK13QJsonValueRef8toStringERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: bool QJsonValueRef::isObject();
fn C_ZNK13QJsonValueRef8isObjectEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QJsonValueRef::isString();
fn C_ZNK13QJsonValueRef8isStringEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QString QJsonValueRef::toString();
fn C_ZNK13QJsonValueRef8toStringEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QJsonValueRef::toInt(int defaultValue);
fn C_ZNK13QJsonValueRef5toIntEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int;
// proto: bool QJsonValueRef::isArray();
fn C_ZNK13QJsonValueRef7isArrayEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QJsonValueRef::isNull();
fn C_ZNK13QJsonValueRef6isNullEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: int QJsonValueRef::toInt();
fn C_ZNK13QJsonValueRef5toIntEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: bool QJsonValueRef::isUndefined();
fn C_ZNK13QJsonValueRef11isUndefinedEv(qthis: u64 /* *mut c_void*/) -> c_char;
} // <= ext block end
// body block begin =>
// class sizeof(QJsonValueRefPtr)=16
#[derive(Default)]
pub struct QJsonValueRefPtr {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QJsonValuePtr)=24
#[derive(Default)]
pub struct QJsonValuePtr {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QJsonValue)=24
#[derive(Default)]
pub struct QJsonValue {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QJsonValueRef)=16
#[derive(Default)]
pub struct QJsonValueRef {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QJsonValueRefPtr {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QJsonValueRefPtr {
return QJsonValueRefPtr{qclsinst: qthis, ..Default::default()};
}
}
impl /*struct*/ QJsonValuePtr {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QJsonValuePtr {
return QJsonValuePtr{qclsinst: qthis, ..Default::default()};
}
}
impl /*struct*/ QJsonValue {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QJsonValue {
return QJsonValue{qclsinst: qthis, ..Default::default()};
}
}
// proto: QJsonObject QJsonValue::toObject();
impl /*struct*/ QJsonValue {
pub fn toObject<RetType, T: QJsonValue_toObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toObject(self);
// return 1;
}
}
pub trait QJsonValue_toObject<RetType> {
fn toObject(self , rsthis: & QJsonValue) -> RetType;
}
// proto: QJsonObject QJsonValue::toObject();
impl<'a> /*trait*/ QJsonValue_toObject<QJsonObject> for () {
fn toObject(self , rsthis: & QJsonValue) -> QJsonObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue8toObjectEv()};
let mut ret = unsafe {C_ZNK10QJsonValue8toObjectEv(rsthis.qclsinst)};
let mut ret1 = QJsonObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QJsonValue::isDouble();
impl /*struct*/ QJsonValue {
pub fn isDouble<RetType, T: QJsonValue_isDouble<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isDouble(self);
// return 1;
}
}
pub trait QJsonValue_isDouble<RetType> {
fn isDouble(self , rsthis: & QJsonValue) -> RetType;
}
// proto: bool QJsonValue::isDouble();
impl<'a> /*trait*/ QJsonValue_isDouble<i8> for () {
fn isDouble(self , rsthis: & QJsonValue) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue8isDoubleEv()};
let mut ret = unsafe {C_ZNK10QJsonValue8isDoubleEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QJsonValue::QJsonValue(const QString & s);
impl /*struct*/ QJsonValue {
pub fn new<T: QJsonValue_new>(value: T) -> QJsonValue {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QJsonValue_new {
fn new(self) -> QJsonValue;
}
// proto: void QJsonValue::QJsonValue(const QString & s);
impl<'a> /*trait*/ QJsonValue_new for (&'a QString) {
fn new(self) -> QJsonValue {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QJsonValueC2ERK7QString()};
let ctysz: c_int = unsafe{QJsonValue_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN10QJsonValueC2ERK7QString(arg0)};
let rsthis = QJsonValue{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: int QJsonValue::toInt(int defaultValue);
impl /*struct*/ QJsonValue {
pub fn toInt<RetType, T: QJsonValue_toInt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toInt(self);
// return 1;
}
}
pub trait QJsonValue_toInt<RetType> {
fn toInt(self , rsthis: & QJsonValue) -> RetType;
}
// proto: int QJsonValue::toInt(int defaultValue);
impl<'a> /*trait*/ QJsonValue_toInt<i32> for (Option<i32>) {
fn toInt(self , rsthis: & QJsonValue) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue5toIntEi()};
let arg0 = (if self.is_none() {0} else {self.unwrap()}) as c_int;
let mut ret = unsafe {C_ZNK10QJsonValue5toIntEi(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: QJsonArray QJsonValue::toArray();
impl /*struct*/ QJsonValue {
pub fn toArray<RetType, T: QJsonValue_toArray<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toArray(self);
// return 1;
}
}
pub trait QJsonValue_toArray<RetType> {
fn toArray(self , rsthis: & QJsonValue) -> RetType;
}
// proto: QJsonArray QJsonValue::toArray();
impl<'a> /*trait*/ QJsonValue_toArray<QJsonArray> for () {
fn toArray(self , rsthis: & QJsonValue) -> QJsonArray {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue7toArrayEv()};
let mut ret = unsafe {C_ZNK10QJsonValue7toArrayEv(rsthis.qclsinst)};
let mut ret1 = QJsonArray::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QJsonValue::isArray();
impl /*struct*/ QJsonValue {
pub fn isArray<RetType, T: QJsonValue_isArray<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isArray(self);
// return 1;
}
}
pub trait QJsonValue_isArray<RetType> {
fn isArray(self , rsthis: & QJsonValue) -> RetType;
}
// proto: bool QJsonValue::isArray();
impl<'a> /*trait*/ QJsonValue_isArray<i8> for () {
fn isArray(self , rsthis: & QJsonValue) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue7isArrayEv()};
let mut ret = unsafe {C_ZNK10QJsonValue7isArrayEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QJsonValue::QJsonValue(const char * s);
impl<'a> /*trait*/ QJsonValue_new for (&'a String) {
fn new(self) -> QJsonValue {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QJsonValueC2EPKc()};
let ctysz: c_int = unsafe{QJsonValue_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.as_ptr() as *mut c_char;
let qthis: u64 = unsafe {C_ZN10QJsonValueC2EPKc(arg0)};
let rsthis = QJsonValue{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QString QJsonValue::toString(const QString & defaultValue);
impl /*struct*/ QJsonValue {
pub fn toString<RetType, T: QJsonValue_toString<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toString(self);
// return 1;
}
}
pub trait QJsonValue_toString<RetType> {
fn toString(self , rsthis: & QJsonValue) -> RetType;
}
// proto: QString QJsonValue::toString(const QString & defaultValue);
impl<'a> /*trait*/ QJsonValue_toString<QString> for (Option<&'a QString>) {
fn toString(self , rsthis: & QJsonValue) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue8toStringERK7QString()};
let arg0 = (if self.is_none() {QString::new(()).qclsinst} else {self.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZNK10QJsonValue8toStringERK7QString(rsthis.qclsinst, arg0)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: double QJsonValue::toDouble(double defaultValue);
impl /*struct*/ QJsonValue {
pub fn toDouble<RetType, T: QJsonValue_toDouble<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toDouble(self);
// return 1;
}
}
pub trait QJsonValue_toDouble<RetType> {
fn toDouble(self , rsthis: & QJsonValue) -> RetType;
}
// proto: double QJsonValue::toDouble(double defaultValue);
impl<'a> /*trait*/ QJsonValue_toDouble<f64> for (Option<f64>) {
fn toDouble(self , rsthis: & QJsonValue) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue8toDoubleEd()};
let arg0 = (if self.is_none() {0 as f64} else {self.unwrap()}) as c_double;
let mut ret = unsafe {C_ZNK10QJsonValue8toDoubleEd(rsthis.qclsinst, arg0)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QJsonValue::~QJsonValue();
impl /*struct*/ QJsonValue {
pub fn free<RetType, T: QJsonValue_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QJsonValue_free<RetType> {
fn free(self , rsthis: & QJsonValue) -> RetType;
}
// proto: void QJsonValue::~QJsonValue();
impl<'a> /*trait*/ QJsonValue_free<()> for () {
fn free(self , rsthis: & QJsonValue) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QJsonValueD2Ev()};
unsafe {C_ZN10QJsonValueD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QVariant QJsonValue::toVariant();
impl /*struct*/ QJsonValue {
pub fn toVariant<RetType, T: QJsonValue_toVariant<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toVariant(self);
// return 1;
}
}
pub trait QJsonValue_toVariant<RetType> {
fn toVariant(self , rsthis: & QJsonValue) -> RetType;
}
// proto: QVariant QJsonValue::toVariant();
impl<'a> /*trait*/ QJsonValue_toVariant<QVariant> for () {
fn toVariant(self , rsthis: & QJsonValue) -> QVariant {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue9toVariantEv()};
let mut ret = unsafe {C_ZNK10QJsonValue9toVariantEv(rsthis.qclsinst)};
let mut ret1 = QVariant::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QJsonValue::isObject();
impl /*struct*/ QJsonValue {
pub fn isObject<RetType, T: QJsonValue_isObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isObject(self);
// return 1;
}
}
pub trait QJsonValue_isObject<RetType> {
fn isObject(self , rsthis: & QJsonValue) -> RetType;
}
// proto: bool QJsonValue::isObject();
impl<'a> /*trait*/ QJsonValue_isObject<i8> for () {
fn isObject(self , rsthis: & QJsonValue) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue8isObjectEv()};
let mut ret = unsafe {C_ZNK10QJsonValue8isObjectEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: static QJsonValue QJsonValue::fromVariant(const QVariant & variant);
impl /*struct*/ QJsonValue {
pub fn fromVariant_s<RetType, T: QJsonValue_fromVariant_s<RetType>>( overload_args: T) -> RetType {
return overload_args.fromVariant_s();
// return 1;
}
}
pub trait QJsonValue_fromVariant_s<RetType> {
fn fromVariant_s(self ) -> RetType;
}
// proto: static QJsonValue QJsonValue::fromVariant(const QVariant & variant);
impl<'a> /*trait*/ QJsonValue_fromVariant_s<QJsonValue> for (&'a QVariant) {
fn fromVariant_s(self ) -> QJsonValue {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QJsonValue11fromVariantERK8QVariant()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN10QJsonValue11fromVariantERK8QVariant(arg0)};
let mut ret1 = QJsonValue::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QJsonValue::toBool(bool defaultValue);
impl /*struct*/ QJsonValue {
pub fn toBool<RetType, T: QJsonValue_toBool<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toBool(self);
// return 1;
}
}
pub trait QJsonValue_toBool<RetType> {
fn toBool(self , rsthis: & QJsonValue) -> RetType;
}
// proto: bool QJsonValue::toBool(bool defaultValue);
impl<'a> /*trait*/ QJsonValue_toBool<i8> for (Option<i8>) {
fn toBool(self , rsthis: & QJsonValue) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue6toBoolEb()};
let arg0 = (if self.is_none() {false as i8} else {self.unwrap()}) as c_char;
let mut ret = unsafe {C_ZNK10QJsonValue6toBoolEb(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QJsonValue::QJsonValue(double n);
impl<'a> /*trait*/ QJsonValue_new for (f64) {
fn new(self) -> QJsonValue {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QJsonValueC2Ed()};
let ctysz: c_int = unsafe{QJsonValue_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self as c_double;
let qthis: u64 = unsafe {C_ZN10QJsonValueC2Ed(arg0)};
let rsthis = QJsonValue{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: bool QJsonValue::isBool();
impl /*struct*/ QJsonValue {
pub fn isBool<RetType, T: QJsonValue_isBool<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isBool(self);
// return 1;
}
}
pub trait QJsonValue_isBool<RetType> {
fn isBool(self , rsthis: & QJsonValue) -> RetType;
}
// proto: bool QJsonValue::isBool();
impl<'a> /*trait*/ QJsonValue_isBool<i8> for () {
fn isBool(self , rsthis: & QJsonValue) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue6isBoolEv()};
let mut ret = unsafe {C_ZNK10QJsonValue6isBoolEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QJsonValue::QJsonValue(bool b);
impl<'a> /*trait*/ QJsonValue_new for (i8) {
fn new(self) -> QJsonValue {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QJsonValueC2Eb()};
let ctysz: c_int = unsafe{QJsonValue_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self as c_char;
let qthis: u64 = unsafe {C_ZN10QJsonValueC2Eb(arg0)};
let rsthis = QJsonValue{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: bool QJsonValue::isUndefined();
impl /*struct*/ QJsonValue {
pub fn isUndefined<RetType, T: QJsonValue_isUndefined<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isUndefined(self);
// return 1;
}
}
pub trait QJsonValue_isUndefined<RetType> {
fn isUndefined(self , rsthis: & QJsonValue) -> RetType;
}
// proto: bool QJsonValue::isUndefined();
impl<'a> /*trait*/ QJsonValue_isUndefined<i8> for () {
fn isUndefined(self , rsthis: & QJsonValue) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue11isUndefinedEv()};
let mut ret = unsafe {C_ZNK10QJsonValue11isUndefinedEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QJsonValue::isNull();
impl /*struct*/ QJsonValue {
pub fn isNull<RetType, T: QJsonValue_isNull<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isNull(self);
// return 1;
}
}
pub trait QJsonValue_isNull<RetType> {
fn isNull(self , rsthis: & QJsonValue) -> RetType;
}
// proto: bool QJsonValue::isNull();
impl<'a> /*trait*/ QJsonValue_isNull<i8> for () {
fn isNull(self , rsthis: & QJsonValue) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue6isNullEv()};
let mut ret = unsafe {C_ZNK10QJsonValue6isNullEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QJsonValue::isString();
impl /*struct*/ QJsonValue {
pub fn isString<RetType, T: QJsonValue_isString<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isString(self);
// return 1;
}
}
pub trait QJsonValue_isString<RetType> {
fn isString(self , rsthis: & QJsonValue) -> RetType;
}
// proto: bool QJsonValue::isString();
impl<'a> /*trait*/ QJsonValue_isString<i8> for () {
fn isString(self , rsthis: & QJsonValue) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QJsonValue8isStringEv()};
let mut ret = unsafe {C_ZNK10QJsonValue8isStringEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QJsonValue::QJsonValue(int n);
impl<'a> /*trait*/ QJsonValue_new for (i32) {
fn new(self) -> QJsonValue {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QJsonValueC2Ei()};
let ctysz: c_int = unsafe{QJsonValue_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self as c_int;
let qthis: u64 = unsafe {C_ZN10QJsonValueC2Ei(arg0)};
let rsthis = QJsonValue{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QJsonValue::QJsonValue(qint64 n);
impl<'a> /*trait*/ QJsonValue_new for (i64) {
fn new(self) -> QJsonValue {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QJsonValueC2Ex()};
let ctysz: c_int = unsafe{QJsonValue_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self as c_longlong;
let qthis: u64 = unsafe {C_ZN10QJsonValueC2Ex(arg0)};
let rsthis = QJsonValue{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
impl /*struct*/ QJsonValueRef {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QJsonValueRef {
return QJsonValueRef{qclsinst: qthis, ..Default::default()};
}
}
// proto: QJsonArray QJsonValueRef::toArray();
impl /*struct*/ QJsonValueRef {
pub fn toArray<RetType, T: QJsonValueRef_toArray<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toArray(self);
// return 1;
}
}
pub trait QJsonValueRef_toArray<RetType> {
fn toArray(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: QJsonArray QJsonValueRef::toArray();
impl<'a> /*trait*/ QJsonValueRef_toArray<QJsonArray> for () {
fn toArray(self , rsthis: & QJsonValueRef) -> QJsonArray {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef7toArrayEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef7toArrayEv(rsthis.qclsinst)};
let mut ret1 = QJsonArray::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QJsonObject QJsonValueRef::toObject();
impl /*struct*/ QJsonValueRef {
pub fn toObject<RetType, T: QJsonValueRef_toObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toObject(self);
// return 1;
}
}
pub trait QJsonValueRef_toObject<RetType> {
fn toObject(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: QJsonObject QJsonValueRef::toObject();
impl<'a> /*trait*/ QJsonValueRef_toObject<QJsonObject> for () {
fn toObject(self , rsthis: & QJsonValueRef) -> QJsonObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef8toObjectEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef8toObjectEv(rsthis.qclsinst)};
let mut ret1 = QJsonObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QJsonValueRef::isBool();
impl /*struct*/ QJsonValueRef {
pub fn isBool<RetType, T: QJsonValueRef_isBool<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isBool(self);
// return 1;
}
}
pub trait QJsonValueRef_isBool<RetType> {
fn isBool(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: bool QJsonValueRef::isBool();
impl<'a> /*trait*/ QJsonValueRef_isBool<i8> for () {
fn isBool(self , rsthis: & QJsonValueRef) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef6isBoolEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef6isBoolEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QJsonValueRef::isDouble();
impl /*struct*/ QJsonValueRef {
pub fn isDouble<RetType, T: QJsonValueRef_isDouble<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isDouble(self);
// return 1;
}
}
pub trait QJsonValueRef_isDouble<RetType> {
fn isDouble(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: bool QJsonValueRef::isDouble();
impl<'a> /*trait*/ QJsonValueRef_isDouble<i8> for () {
fn isDouble(self , rsthis: & QJsonValueRef) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef8isDoubleEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef8isDoubleEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: double QJsonValueRef::toDouble();
impl /*struct*/ QJsonValueRef {
pub fn toDouble<RetType, T: QJsonValueRef_toDouble<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toDouble(self);
// return 1;
}
}
pub trait QJsonValueRef_toDouble<RetType> {
fn toDouble(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: double QJsonValueRef::toDouble();
impl<'a> /*trait*/ QJsonValueRef_toDouble<f64> for () {
fn toDouble(self , rsthis: & QJsonValueRef) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef8toDoubleEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef8toDoubleEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: bool QJsonValueRef::toBool(bool defaultValue);
impl /*struct*/ QJsonValueRef {
pub fn toBool<RetType, T: QJsonValueRef_toBool<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toBool(self);
// return 1;
}
}
pub trait QJsonValueRef_toBool<RetType> {
fn toBool(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: bool QJsonValueRef::toBool(bool defaultValue);
impl<'a> /*trait*/ QJsonValueRef_toBool<i8> for (i8) {
fn toBool(self , rsthis: & QJsonValueRef) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef6toBoolEb()};
let arg0 = self as c_char;
let mut ret = unsafe {C_ZNK13QJsonValueRef6toBoolEb(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: double QJsonValueRef::toDouble(double defaultValue);
impl<'a> /*trait*/ QJsonValueRef_toDouble<f64> for (f64) {
fn toDouble(self , rsthis: & QJsonValueRef) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef8toDoubleEd()};
let arg0 = self as c_double;
let mut ret = unsafe {C_ZNK13QJsonValueRef8toDoubleEd(rsthis.qclsinst, arg0)};
return ret as f64; // 1
// return 1;
}
}
// proto: bool QJsonValueRef::toBool();
impl<'a> /*trait*/ QJsonValueRef_toBool<i8> for () {
fn toBool(self , rsthis: & QJsonValueRef) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef6toBoolEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef6toBoolEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QVariant QJsonValueRef::toVariant();
impl /*struct*/ QJsonValueRef {
pub fn toVariant<RetType, T: QJsonValueRef_toVariant<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toVariant(self);
// return 1;
}
}
pub trait QJsonValueRef_toVariant<RetType> {
fn toVariant(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: QVariant QJsonValueRef::toVariant();
impl<'a> /*trait*/ QJsonValueRef_toVariant<QVariant> for () {
fn toVariant(self , rsthis: & QJsonValueRef) -> QVariant {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef9toVariantEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef9toVariantEv(rsthis.qclsinst)};
let mut ret1 = QVariant::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QString QJsonValueRef::toString(const QString & defaultValue);
impl /*struct*/ QJsonValueRef {
pub fn toString<RetType, T: QJsonValueRef_toString<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toString(self);
// return 1;
}
}
pub trait QJsonValueRef_toString<RetType> {
fn toString(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: QString QJsonValueRef::toString(const QString & defaultValue);
impl<'a> /*trait*/ QJsonValueRef_toString<QString> for (&'a QString) {
fn toString(self , rsthis: & QJsonValueRef) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef8toStringERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK13QJsonValueRef8toStringERK7QString(rsthis.qclsinst, arg0)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QJsonValueRef::isObject();
impl /*struct*/ QJsonValueRef {
pub fn isObject<RetType, T: QJsonValueRef_isObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isObject(self);
// return 1;
}
}
pub trait QJsonValueRef_isObject<RetType> {
fn isObject(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: bool QJsonValueRef::isObject();
impl<'a> /*trait*/ QJsonValueRef_isObject<i8> for () {
fn isObject(self , rsthis: & QJsonValueRef) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef8isObjectEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef8isObjectEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QJsonValueRef::isString();
impl /*struct*/ QJsonValueRef {
pub fn isString<RetType, T: QJsonValueRef_isString<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isString(self);
// return 1;
}
}
pub trait QJsonValueRef_isString<RetType> {
fn isString(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: bool QJsonValueRef::isString();
impl<'a> /*trait*/ QJsonValueRef_isString<i8> for () {
fn isString(self , rsthis: & QJsonValueRef) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef8isStringEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef8isStringEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QString QJsonValueRef::toString();
impl<'a> /*trait*/ QJsonValueRef_toString<QString> for () {
fn toString(self , rsthis: & QJsonValueRef) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef8toStringEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef8toStringEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QJsonValueRef::toInt(int defaultValue);
impl /*struct*/ QJsonValueRef {
pub fn toInt<RetType, T: QJsonValueRef_toInt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toInt(self);
// return 1;
}
}
pub trait QJsonValueRef_toInt<RetType> {
fn toInt(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: int QJsonValueRef::toInt(int defaultValue);
impl<'a> /*trait*/ QJsonValueRef_toInt<i32> for (i32) {
fn toInt(self , rsthis: & QJsonValueRef) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef5toIntEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK13QJsonValueRef5toIntEi(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: bool QJsonValueRef::isArray();
impl /*struct*/ QJsonValueRef {
pub fn isArray<RetType, T: QJsonValueRef_isArray<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isArray(self);
// return 1;
}
}
pub trait QJsonValueRef_isArray<RetType> {
fn isArray(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: bool QJsonValueRef::isArray();
impl<'a> /*trait*/ QJsonValueRef_isArray<i8> for () {
fn isArray(self , rsthis: & QJsonValueRef) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef7isArrayEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef7isArrayEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QJsonValueRef::isNull();
impl /*struct*/ QJsonValueRef {
pub fn isNull<RetType, T: QJsonValueRef_isNull<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isNull(self);
// return 1;
}
}
pub trait QJsonValueRef_isNull<RetType> {
fn isNull(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: bool QJsonValueRef::isNull();
impl<'a> /*trait*/ QJsonValueRef_isNull<i8> for () {
fn isNull(self , rsthis: & QJsonValueRef) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef6isNullEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef6isNullEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: int QJsonValueRef::toInt();
impl<'a> /*trait*/ QJsonValueRef_toInt<i32> for () {
fn toInt(self , rsthis: & QJsonValueRef) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef5toIntEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef5toIntEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: bool QJsonValueRef::isUndefined();
impl /*struct*/ QJsonValueRef {
pub fn isUndefined<RetType, T: QJsonValueRef_isUndefined<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isUndefined(self);
// return 1;
}
}
pub trait QJsonValueRef_isUndefined<RetType> {
fn isUndefined(self , rsthis: & QJsonValueRef) -> RetType;
}
// proto: bool QJsonValueRef::isUndefined();
impl<'a> /*trait*/ QJsonValueRef_isUndefined<i8> for () {
fn isUndefined(self , rsthis: & QJsonValueRef) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QJsonValueRef11isUndefinedEv()};
let mut ret = unsafe {C_ZNK13QJsonValueRef11isUndefinedEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// <= body block end
|
pub type ITpmVirtualSmartCardManager = *mut ::core::ffi::c_void;
pub type ITpmVirtualSmartCardManager2 = *mut ::core::ffi::c_void;
pub type ITpmVirtualSmartCardManager3 = *mut ::core::ffi::c_void;
pub type ITpmVirtualSmartCardManagerStatusCallback = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const RemoteTpmVirtualSmartCardManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x152ea2a8_70dc_4c59_8b2a_32aa3ca0dcac);
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSC_DEFAULT_ADMIN_ALGORITHM_ID: u32 = 130u32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TpmVirtualSmartCardManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x16a18e86_7f6e_4c20_ad89_4ffc0db7a96a);
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub type TPMVSCMGR_ERROR = i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_IMPERSONATION: TPMVSCMGR_ERROR = 0i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_PIN_COMPLEXITY: TPMVSCMGR_ERROR = 1i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_READER_COUNT_LIMIT: TPMVSCMGR_ERROR = 2i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_TERMINAL_SERVICES_SESSION: TPMVSCMGR_ERROR = 3i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_VTPMSMARTCARD_INITIALIZE: TPMVSCMGR_ERROR = 4i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_VTPMSMARTCARD_CREATE: TPMVSCMGR_ERROR = 5i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_VTPMSMARTCARD_DESTROY: TPMVSCMGR_ERROR = 6i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_VGIDSSIMULATOR_INITIALIZE: TPMVSCMGR_ERROR = 7i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_VGIDSSIMULATOR_CREATE: TPMVSCMGR_ERROR = 8i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_VGIDSSIMULATOR_DESTROY: TPMVSCMGR_ERROR = 9i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_VGIDSSIMULATOR_WRITE_PROPERTY: TPMVSCMGR_ERROR = 10i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_VGIDSSIMULATOR_READ_PROPERTY: TPMVSCMGR_ERROR = 11i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_VREADER_INITIALIZE: TPMVSCMGR_ERROR = 12i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_VREADER_CREATE: TPMVSCMGR_ERROR = 13i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_VREADER_DESTROY: TPMVSCMGR_ERROR = 14i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_GENERATE_LOCATE_READER: TPMVSCMGR_ERROR = 15i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_GENERATE_FILESYSTEM: TPMVSCMGR_ERROR = 16i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_CARD_CREATE: TPMVSCMGR_ERROR = 17i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_ERROR_CARD_DESTROY: TPMVSCMGR_ERROR = 18i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub type TPMVSCMGR_STATUS = i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_VTPMSMARTCARD_INITIALIZING: TPMVSCMGR_STATUS = 0i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_VTPMSMARTCARD_CREATING: TPMVSCMGR_STATUS = 1i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_VTPMSMARTCARD_DESTROYING: TPMVSCMGR_STATUS = 2i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_VGIDSSIMULATOR_INITIALIZING: TPMVSCMGR_STATUS = 3i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_VGIDSSIMULATOR_CREATING: TPMVSCMGR_STATUS = 4i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_VGIDSSIMULATOR_DESTROYING: TPMVSCMGR_STATUS = 5i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_VREADER_INITIALIZING: TPMVSCMGR_STATUS = 6i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_VREADER_CREATING: TPMVSCMGR_STATUS = 7i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_VREADER_DESTROYING: TPMVSCMGR_STATUS = 8i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_GENERATE_WAITING: TPMVSCMGR_STATUS = 9i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_GENERATE_AUTHENTICATING: TPMVSCMGR_STATUS = 10i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_GENERATE_RUNNING: TPMVSCMGR_STATUS = 11i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_CARD_CREATED: TPMVSCMGR_STATUS = 12i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSCMGR_STATUS_CARD_DESTROYED: TPMVSCMGR_STATUS = 13i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub type TPMVSC_ATTESTATION_TYPE = i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSC_ATTESTATION_NONE: TPMVSC_ATTESTATION_TYPE = 0i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSC_ATTESTATION_AIK_ONLY: TPMVSC_ATTESTATION_TYPE = 1i32;
#[doc = "*Required features: `\"Win32_Security_Tpm\"`*"]
pub const TPMVSC_ATTESTATION_AIK_AND_CERTIFICATE: TPMVSC_ATTESTATION_TYPE = 2i32;
|
extern crate gl;
extern crate glutin;
extern crate graphics;
extern crate rand;
use std::ptr;
use std::mem;
use std::iter::repeat;
use std::str;
use std::ffi::CString;
use gl::types::*;
use glutin::VirtualKeyCode;
use graphics::{Mesh, Vector3, Matrix4, Quaternion};
use rand::distributions::{IndependentSample, Range};
fn check_gl_error(msg: &str) {
unsafe {
if gl::GetError() != 0 {
panic!("OpenGL Error: {}", msg)
}
}
}
fn check_shader_error(shader: GLuint) {
let mut result: i32 = 0;
unsafe {
gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut result);
if result == 0 {
println!("Shader compilation failed.");
}
let mut info_log_len = 0;
gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut info_log_len);
if info_log_len > 0 {
let mut chars_written = 0;
let info_log: String = repeat(' ').take(info_log_len as usize).collect();
let c_str = CString::new(info_log.as_bytes()).unwrap();
gl::GetShaderInfoLog(
shader,
info_log_len,
&mut chars_written,
c_str.as_ptr() as *mut _,
);
let bytes = c_str.as_bytes();
let bytes = &bytes[..bytes.len() - 1];
panic!(
"Shader compilation failed: {}",
str::from_utf8(bytes).unwrap()
);
}
}
}
fn main() {
let events_loop = glutin::EventsLoop::new();
let window = glutin::WindowBuilder::new()
.with_title("Graphics Example".to_string())
.with_dimensions(1280, 720)
.with_vsync()
.with_multisampling(16)
.build(&events_loop)
.unwrap();
unsafe { window.make_current() }.unwrap();
gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
// Setup shader program
let shader_handle: u32;
let position_attrib: i32;
let normal_attrib: i32;
let model_matrix_uniform: i32;
let view_matrix_uniform: i32;
let projection_matrix_uniform: i32;
unsafe {
shader_handle = gl::CreateProgram();
let vertex_handle = gl::CreateShader(gl::VERTEX_SHADER);
let fragment_handle = gl::CreateShader(gl::FRAGMENT_SHADER);
gl::ShaderSource(vertex_handle, 1, [VERTEX_SHADER.as_ptr() as *const _].as_ptr(), ptr::null());
gl::ShaderSource(fragment_handle, 1, [FRAGMENT_SHADER.as_ptr() as *const _].as_ptr(), ptr::null());
gl::CompileShader(vertex_handle);
gl::CompileShader(fragment_handle);
check_shader_error(vertex_handle);
check_shader_error(fragment_handle);
gl::AttachShader(shader_handle, vertex_handle);
gl::AttachShader(shader_handle, fragment_handle);
gl::LinkProgram(shader_handle);
// Check the compilation
check_gl_error("Shader Compilation");
model_matrix_uniform = gl::GetUniformLocation(shader_handle, b"in_model_matrix\0".as_ptr() as *const _);
view_matrix_uniform = gl::GetUniformLocation(shader_handle, b"in_view_matrix\0".as_ptr() as *const _);
projection_matrix_uniform = gl::GetUniformLocation(shader_handle, b"in_projection_matrix\0".as_ptr() as *const _);
position_attrib = gl::GetAttribLocation(shader_handle, b"in_position\0".as_ptr() as *const _);
normal_attrib = gl::GetAttribLocation(shader_handle, b"in_normal\0".as_ptr() as *const _);
check_gl_error("Attrib Location");
}
// Buffers
let mut vertex_buffer_handle: u32;
let mut vertex_array_handle: u32;
unsafe {
vertex_buffer_handle = mem::uninitialized();
gl::GenBuffers(1, &mut vertex_buffer_handle);
vertex_array_handle = mem::uninitialized();
gl::GenVertexArrays(1, &mut vertex_array_handle);
gl::BindVertexArray(vertex_array_handle);
gl::BindBuffer(gl::ARRAY_BUFFER, vertex_buffer_handle);
gl::EnableVertexAttribArray(position_attrib as u32);
gl::VertexAttribPointer(position_attrib as u32, 3, gl::FLOAT, gl::FALSE, 6 * mem::size_of::<f32>() as i32, ptr::null());
gl::EnableVertexAttribArray(normal_attrib as u32);
gl::VertexAttribPointer(normal_attrib as u32, 3, gl::FLOAT, gl::FALSE, 6 * mem::size_of::<f32>() as i32, (3 * mem::size_of::<f32>()) as *const () as *const _);
check_gl_error("Buffers");
}
// Mesh
let mut mesh_list: Vec<Mesh> = Vec::new();
let between = Range::new(-5., 5.);
let mut rng = rand::thread_rng();
for _ in 0..1000 {
let x = between.ind_sample(&mut rng);
let y = between.ind_sample(&mut rng);
let z = between.ind_sample(&mut rng);
let sz = 0.5;
mesh_list.push(Mesh::new_box(&Vector3::new(x, y, z), sz, sz, sz));
}
let mut points: Vec<f32> = Vec::new();
for mesh in &mesh_list {
let mut vertex_points = mesh.to_vertex_data();
points.append(&mut vertex_points);
}
unsafe {
gl::BindVertexArray(vertex_array_handle);
gl::BindBuffer(gl::ARRAY_BUFFER, vertex_buffer_handle);
gl::BufferData(gl::ARRAY_BUFFER, (points.len() * mem::size_of::<f32>()) as isize, points.as_ptr() as *const _, gl::STATIC_DRAW);
}
let mut mouse_x = 0;
let mut mouse_y = 0;
let mut camera_position = Vector3::new(0., 0., -10.);
let mut time = 0.0;
let mut running = true;
events_loop.run_forever(|event| {
time += 0.01;
match event {
glutin::Event::WindowEvent { event, .. } => {
match event {
glutin::WindowEvent::KeyboardInput(glutin::ElementState::Pressed, _, code, _) => {
let key = code.unwrap();
match key {
VirtualKeyCode::W => { camera_position.z += 0.1; }
VirtualKeyCode::S => { camera_position.z -= 0.1; }
VirtualKeyCode::A => { camera_position.x -= 0.1; }
VirtualKeyCode::D => { camera_position.x += 0.1; }
VirtualKeyCode::Q => { camera_position.y += 0.1; }
VirtualKeyCode::E => { camera_position.y -= 0.1; }
_ => {}
}
println!("Camera: {:?}", camera_position);
}
glutin::WindowEvent::MouseMoved(x, y) => {
mouse_x = x;
mouse_y = y;
}
glutin::WindowEvent::Closed => { events_loop.interrupt(); running = false; },
_ => (),
}
}
}
if !running { return; }
unsafe {
gl::ClearColor(0.95, 0.95, 0.95, 1.0);
gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
check_gl_error("Clear");
gl::Enable(gl::DEPTH_TEST);
//gl::Enable(gl::CULL_FACE);
gl::UseProgram(shader_handle);
let model_matrix = Matrix4::rotate_y_matrix(0.);
gl::UniformMatrix4fv(model_matrix_uniform, 1, gl::FALSE, model_matrix.m.as_ptr());
let (wx, wy) = window.get_inner_size_pixels().unwrap();
let window_width = wx as f32;
let window_height = wy as f32;
let cx = ((mouse_x as f32 / window_width) - 0.5) * 2.;
let cy = ((mouse_y as f32 / window_height) - 0.5) * 2.;
// http://in2gpu.com/2016/02/26/opengl-fps-camera/
let camera_pitch = -cy;
let camera_yaw = cx;
let q_pitch = Quaternion::with_angle_axis(camera_pitch, &Vector3::new(1., 0., 0.));
let q_yaw = Quaternion::with_angle_axis(camera_yaw, &Vector3::new(0., 1., 0.));
let orientation = q_pitch * q_yaw;
//orientation = orientation.normalize();
let camera_rotate = orientation.to_matrix();
let eye = camera_position;
let target = Vector3::new(cx.sin(), cy, cx.cos());
//let target = Vector3::new(0.0, 0.0, 0.0);
let up = Vector3::new(0.0, 1.0, 0.0);
let camera1 = Matrix4::translate_matrix(camera_position.x, camera_position.y, camera_position.z);
let camera2 = camera_rotate;
let camera = camera1 * camera2;
gl::UniformMatrix4fv(view_matrix_uniform, 1, gl::FALSE, camera.m.as_ptr());
let factor = window_width / window_height;
let scene_width = 1.0;
let scene_height = scene_width * factor;
let projection = Matrix4::perspective_matrix(-scene_width, scene_width, -scene_height, scene_height, 0.01, 2000.)
.inverse()
.unwrap();
gl::UniformMatrix4fv(projection_matrix_uniform, 1, gl::FALSE, projection.m.as_ptr());
gl::DrawArrays(gl::TRIANGLES, 0, points.len() as i32 / 3 as i32);
//gl::PolygonMode(gl::FRONT_AND_BACK, gl::LINE);
//gl::DrawArrays(gl::TRIANGLES, 0, points.len() as i32 / 3 as i32);
//gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL);
check_gl_error("DrawArrays");
}
window.swap_buffers().unwrap();
});
//let poly = Mesh::new_polygon(8, 10.);
//println!("Poly: {}", poly.vertices.len());
}
const VERTEX_SHADER: &'static [u8] = b"
#version 150
#define PI 3.14159265359
#define saturate(a) clamp( a, 0.0, 1.0 )
uniform mat4 in_model_matrix;
uniform mat4 in_view_matrix;
uniform mat4 in_projection_matrix;
in vec3 in_position;
in vec3 in_normal;
out vec3 frag_color;
void main() {
vec3 light_direction = vec3(-30., -30., -100.);
vec3 light_color = vec3(0.8, 0.8, 0.82);
float light_intensity = 0.1;
frag_color = vec3( 0.0 );
float dir = dot(in_normal, light_direction);
//light_color = PI * light_color;
frag_color += saturate(dir) * light_color;
gl_Position = in_projection_matrix * in_view_matrix * in_model_matrix * vec4(in_position, 1.0);
}
\0";
const FRAGMENT_SHADER: &'static [u8] = b"
#version 150
in vec3 frag_color;
out vec4 out_color;
void main() {
out_color = vec4(frag_color, 1.0);
}
\0";
|
// Copyright 2017 Dasein Phaos aka. Luxko
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! texture sampling schemes
use super::*;
/// describes a static sampler
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct StaticSamplerDesc {
/// filtering method
pub filter: Filter,
/// address mode for `u` outside [0, 1]
pub address_u: TextureAddressMode,
/// address mode for `v` outside [0, 1]
pub address_v: TextureAddressMode,
/// address mode for `w` outside [0, 1]
pub address_w: TextureAddressMode,
/// mipmap level bias
pub mip_bias: f32,
/// claming value for anisotropic filters, valid between [1..16]
pub max_anisotropy: u32,
/// function used to compare sampled data against existing sampled data
pub comparison_func: ComparisonFunc,
/// border color to use if address mod is `BORDER`
pub border_color: BorderColor,
/// lower end of the mipmap level to clamp access to
pub min_lod: f32,
/// higher end of the mipmap level to clamp access to
pub max_lod: f32,
/// shader register
pub shader_register: u32,
/// register space
pub register_space: u32,
}
impl StaticSamplerDesc {
/// construct a new description with the given filter and default options
#[inline]
pub fn new(filter: Filter, shader_register: u32, register_space: u32) -> StaticSamplerDesc {
StaticSamplerDesc{
filter, address_u: Default::default(),
address_v: Default::default(),
address_w: Default::default(),
mip_bias: 0.0f32,
max_anisotropy: 1,
comparison_func: ComparisonFunc::ALWAYS,
border_color: Default::default(),
min_lod: 0.0f32,
max_lod: 1.0f32,
shader_register,
register_space,
}
}
}
bitflags!{
/// filtering options for texture sampling. [more info](https://msdn.microsoft.com/library/windows/desktop/dn770367(v=vs.85).aspx)
#[repr(C)]
pub struct Filter: u32 {
const MIN_MAG_MIP_POINT = 0;
const MIN_MAG_POINT_MIP_LINEAR = 0x1;
const MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4;
const MIN_POINT_MAG_MIP_LINEAR = 0x5;
const MIN_LINEAR_MAG_MIP_POINT = 0x10;
const MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11;
const MIN_MAG_LINEAR_MIP_POINT = 0x14;
const MIN_MAG_MIP_LINEAR = 0x15;
const ANISOTROPIC = 0x55;
const COMPARISON_MIN_MAG_MIP_POINT = 0x80;
const COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81;
const COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84;
const COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85;
const COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90;
const COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91;
const COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94;
const COMPARISON_MIN_MAG_MIP_LINEAR = 0x95;
const COMPARISON_ANISOTROPIC = 0xd5;
const MINIMUM_MIN_MAG_MIP_POINT = 0x100;
const MINIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x101;
const MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x104;
const MINIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x105;
const MINIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x110;
const MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x111;
const MINIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x114;
const MINIMUM_MIN_MAG_MIP_LINEAR = 0x115;
const MINIMUM_ANISOTROPIC = 0x155;
const MAXIMUM_MIN_MAG_MIP_POINT = 0x180;
const MAXIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x181;
const MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x184;
const MAXIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x185;
const MAXIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x190;
const MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x191;
const MAXIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x194;
const MAXIMUM_MIN_MAG_MIP_LINEAR = 0x195;
const MAXIMUM_ANISOTROPIC = 0x1d5;
}
}
bitflags!{
/// texture addressing modes when coordinates outside normalized boundary
#[repr(C)]
pub struct TextureAddressMode: u32 {
/// tile at every integer junction, essentially repeating the textures
const WRAP = 1;
/// filp at every integer junction
const MIRROR = 2;
/// clamp to values at normalized boundary
const CLAMP = 3;
/// set to a "border color"
const BORDER = 4;
/// take the absolution value of texture coordinates, then clamp to the boundary
const MIRROR_ONCE = 5;
}
}
impl Default for TextureAddressMode {
#[inline]
fn default() -> Self {
TextureAddressMode::WRAP
}
}
bitflags!{
/// border colors
#[repr(C)]
pub struct BorderColor: u32 {
const TRANSPARENT_BLACK = 0;
const OPAQUE_BLACK = BorderColor::TRANSPARENT_BLACK.bits + 1;
const OPAQUE_WHITE = BorderColor::OPAQUE_BLACK.bits + 1;
}
}
impl Default for BorderColor {
#[inline]
fn default() -> BorderColor {
BorderColor::TRANSPARENT_BLACK
}
}
|
#[derive(Clone)]
pub struct Serial {
interrupt: u8,
sb: u8,
sc: u8,
}
impl Serial {
pub fn init() -> Self {
Self {
interrupt: 0,
sb: 0,
sc: 0,
}
}
}
impl Serial {
pub fn step(&mut self, cycles: usize) {
// TODO: idk
}
pub fn get_interrupt(&mut self) -> u8 {
let ret = self.interrupt;
self.interrupt = 0;
ret
}
}
impl Serial {
pub fn read_io_byte(&self, idx: u16) -> u8 {
match idx {
0xff01 => self.sb,
0xff02 => self.sc,
_ => {
//println!("Unhandled Serial Read from Address [{:#04x?}]", idx);
0
}
}
}
pub fn write_io_byte(&mut self, idx: u16, val: u8) {
match idx {
0xff01 => self.sb = val,
0xff02 => self.sc = val,
_ => {
println!("Unhandled Serial Read from Address [{:#04x?}] [{:#02x?}]", idx, val);
}
}
}
} |
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! General comments on the build system:
//!
//! The Rust Build System is an alternative build system for building
//! the Rust compiler. It is written in Rust and is managed as a
//! Cargo package, `build-rust`. The user will initiate the build
//! process by running `cargo run`, under its manifest directory.
//!
//! The build process starts with Cargo invoking a small build script,
//! `build.rs`, located at the same directory as the package manifest.
//! This script will collect the triple of the build machine and
//! the path to the manifest directory, and then generate a file
//! `build_env.rs`, which will be included into `configure.rs`.
//!
//! The next stage of the build process starts in module `configure`.
//! The build system will invoke `configure::configure()`, which will
//! parse the command line arguments, inspect the build environment
//! (for instance, check the availability of the required build
//! programs), and then return a ConfigArgs object which encapsulates
//! the information collected. Future build processes will read this
//! object instead of poking the build environment directly.
//!
//! Because the configure step may fail (for instance, it may be
//! unable to find the required build program), the `configure()`
//! returns type `BuildState<T>` where `T` equals `ConfigArgs`.
//! `BuildState<T>` is a wrapper around the `Result<T, E>` which is
//! used to indicate the success/failure state of a function.
//! For details, see `mod build_state`.
//!
//! The build system will then download the stage0 snapshot,
//! configure and build LLVM, invoke the appropriate toolchain to
//! build runtime libraries, and then finally boostrap a working stage2
//! rustc. For details of these steps, see the respective modules for
//! more comments.
extern crate regex;
#[macro_use]
mod build_state;
mod cmd_args;
mod configure;
mod snapshot;
mod llvm;
mod rt;
mod rust;
mod cc;
mod log;
use build_state::*;
use configure::{ConfigArgs, configure};
use llvm::{build_llvm, configure_llvm};
use rt::build_native_libs;
use rust::build_rust;
use snapshot::download_stage0_snapshot;
fn make(args : &ConfigArgs) -> BuildState<()> {
let dl = download_stage0_snapshot(args);
if !args.no_reconfigure_llvm() {
try!(configure_llvm(args));
}
if !args.no_rebuild_llvm() {
try!(build_llvm(args));
}
if !args.no_bootstrap() {
try!(build_native_libs(args));
}
try!(dl.recv().unwrap()); // we need to wait for stage0 download
try!(build_rust(args));
continue_build()
}
fn run() -> BuildState<()> {
let config_args = try!(configure());
try!(make(&config_args));
success_stop()
}
fn main() {
let result : BuildState<()> = run();
match result {
Err(ExitStatus::MsgStop(e)) => println!("{}", e),
Err(ExitStatus::ErrStop(e)) => println!("Build failed: {}", e),
_ => println!("Build successful."),
}
}
|
// Copyright 2023 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.
mod serde_meta;
mod transform_aggregate_serializer;
mod transform_aggregate_spill_writer;
mod transform_deserializer;
mod transform_group_by_serializer;
mod transform_group_by_spill_writer;
mod transform_scatter_aggregate_serializer;
mod transform_scatter_aggregate_spill_writer;
mod transform_scatter_group_by_serializer;
mod transform_scatter_group_by_spill_writer;
mod transform_spill_reader;
pub use serde_meta::AggregateSerdeMeta;
pub use serde_meta::BUCKET_TYPE;
pub use serde_meta::SPILLED_TYPE;
pub use transform_aggregate_serializer::TransformAggregateSerializer;
pub use transform_aggregate_spill_writer::TransformAggregateSpillWriter;
pub use transform_deserializer::TransformAggregateDeserializer;
pub use transform_deserializer::TransformGroupByDeserializer;
pub use transform_group_by_serializer::TransformGroupBySerializer;
pub use transform_group_by_spill_writer::TransformGroupBySpillWriter;
pub use transform_scatter_aggregate_serializer::TransformScatterAggregateSerializer;
pub use transform_scatter_aggregate_spill_writer::TransformScatterAggregateSpillWriter;
pub use transform_scatter_group_by_serializer::TransformScatterGroupBySerializer;
pub use transform_scatter_group_by_spill_writer::TransformScatterGroupBySpillWriter;
pub use transform_spill_reader::TransformAggregateSpillReader;
pub use transform_spill_reader::TransformGroupBySpillReader;
|
use projecteuler::partition;
static COINS: &[usize] = &[1, 2, 5, 10, 20, 50, 100, 200];
fn main() {
//dbg!(binomial::binomial_coefficient(100, 50));
dbg!(solve(20));
dbg!(solve(200));
//dbg!(solve(200));
}
fn solve(n: usize) -> usize {
partition::partition_into(n, COINS)
}
|
use std::iter::FromIterator;
use rustc_serialize::json::{Json, ToJson};
pub struct Post {
pub title: String,
pub body: String
}
impl ToJson for Post {
fn to_json(&self) -> Json {
Json::Object(FromIterator::from_iter(vec![
("title".to_owned(), self.title.to_json()),
("body".to_owned(), self.body.to_json()),
]))
}
}
|
use std::io;
fn main() {
let mut total_fuel_req = 0;
let mut total_fuel_req_incl_extra_fuel = 0;
println!("Write each mass on a new line, and finish with an empty line when done.");
loop {
match read_mass() {
Some(num) => {
total_fuel_req += calculate_fuel_requirement(num);
total_fuel_req_incl_extra_fuel += calculate_fuel_requirement_incl_extra_fuel(num)
},
None => break
}
}
println!("The total fuel requirement is {}.", total_fuel_req);
println!("The total fuel requirement (including extra fuel) is {}.", total_fuel_req_incl_extra_fuel);
}
fn read_mass() -> Option<u32>
{
let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
match line.trim().parse() {
Ok(num) => Some(num),
_ => None
}
}
fn calculate_fuel_requirement(mass: u32) -> u32 {
mass / 3 - 2
}
fn calculate_fuel_requirement_incl_extra_fuel(mass: u32) -> u32 {
if mass <= 8 // this means no additional mass
{
return 0;
}
let tmp = mass / 3 - 2;
return tmp + calculate_fuel_requirement_incl_extra_fuel(tmp)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tst() {
assert_eq!(0, calculate_fuel_requirement(8));
assert_eq!(1, calculate_fuel_requirement(9));
assert_eq!(2, calculate_fuel_requirement(12));
assert_eq!(2, calculate_fuel_requirement(14));
assert_eq!(654, calculate_fuel_requirement(1969));
assert_eq!(33583, calculate_fuel_requirement(100756));
}
} |
pub mod anoncreds;
pub mod crypto;
pub mod ledger;
pub mod pool;
pub mod signus;
pub mod wallet; |
/// 虚拟队列相关实现
/// ref: https://github.com/rcore-os/virtio-drivers/blob/master/src/queue.rs
/// thanks!
use volatile::Volatile;
use bitflags::bitflags;
use core::{mem::size_of, sync::atomic::{fence, Ordering}};
use core::ptr::NonNull;
use crate::util::align_up_page;
use super::dma::DMA;
use super::mmio::VirtIOHeader;
use super::config::*;
use super::*;
type AvailableRing = Ring<Volatile<u16>>;
type UsedRing = Ring<UsedElement>;
/// Virtio 中的虚拟队列接口,前后端通信的桥梁
///
/// unsafe:
/// 这里用了 NonNull,不确定在多个硬件线程的情况下是否安全
/// 为了通过编译,手动实现了 Send 和 Sync Trait
/// todo: 检查这里的安全性
#[repr(C)]
pub struct VirtQueue {
/// DMA 空间
dma: DMA,
/// 描述符表
descriptor_table: NonNull<[Descriptor]>,
/// 可用环
avail_ring: NonNull<AvailableRing>,
/// 已用环
used_ring: NonNull<UsedRing>,
/// 虚拟队列索引值
/// 一个虚拟设备实现可能有多个虚拟队列
queue_index: u32,
/// 虚拟队列长度
queue_size: u16,
/// 已经使用的描述符数目
used_num: u16,
/// 空闲描述符链表头
/// 初始时所有描述符通过 next 指针依次相连形成空闲链表
free_desc_head: u16,
/// 可用环的索引值
avail_index: u16,
/// 设备上次已取的已用环元素的位置
last_used_index: u16
}
impl VirtQueue {
pub fn new(
header: &mut VirtIOHeader, index: usize, size: u16
) -> Result<Self> {
if header.queue_used(index as u32) {
return Err(VirtIOError::QueueInUsed(index));
}
if !size.is_power_of_two() || header.max_queue_size() < size as u32 {
return Err(VirtIOError::InvalidParameter);
}
let queue_layout = VirtQueueMemLayout::new(size);
let dma = DMA::new(queue_layout.mem_size / PAGE_SIZE)?;
println!("[virtio] DMA address: {:#x}", dma.start_physical_address());
// 在 MMIO 接口中设置虚拟队列的相关信息
header.queue_set(
index as u32, size as u32, PAGE_SIZE as u32, dma.ppn() as u32
);
// 描述符表起始地址
let desc_table = unsafe {
core::slice::from_raw_parts_mut(dma.start_virtual_address() as *mut Descriptor, size as usize)
};
// 将空描述符连成链表
for i in 0..(size - 1) {
desc_table[i as usize].next.write(i + 1);
}
let descriptor_table = NonNull::new(desc_table).unwrap();
let avail_ring = NonNull::new(
unsafe { &mut *((dma.start_virtual_address() + queue_layout.avail_ring_offset) as *mut AvailableRing) }
).unwrap();
let used_ring = NonNull::new(
unsafe { &mut *((dma.start_virtual_address() + queue_layout.used_ring_offset) as *mut UsedRing) }
).unwrap();
Ok(VirtQueue {
dma,
descriptor_table,
avail_ring,
used_ring,
queue_size: size,
queue_index: index as u32,
used_num: 0,
free_desc_head: 0,
avail_index: 0,
last_used_index: 0
})
}
pub async fn async_new(
header: &mut VirtIOHeader, index: usize, size: u16
) -> Result<VirtQueue> {
if header.queue_used(index as u32) {
return Err(VirtIOError::QueueInUsed(index));
}
if !size.is_power_of_two() || header.max_queue_size() < size as u32 {
return Err(VirtIOError::InvalidParameter);
}
let queue_layout = VirtQueueMemLayout::new(size);
let dma = DMA::alloc(queue_layout.mem_size / PAGE_SIZE).await;
println!("[virtio] DMA address: {:#x}", dma.start_physical_address());
// 在 MMIO 接口中设置虚拟队列的相关信息
header.queue_set(
index as u32, size as u32, PAGE_SIZE as u32, dma.ppn() as u32
);
// 描述符表起始地址
let desc_table = unsafe {
core::slice::from_raw_parts_mut(dma.start_virtual_address() as *mut Descriptor, size as usize)
};
// 将空描述符连成链表
for i in 0..(size - 1) {
desc_table[i as usize].next.write(i + 1);
}
let descriptor_table = NonNull::new(desc_table).unwrap();
let avail_ring = NonNull::new(
unsafe { &mut *((dma.start_virtual_address() + queue_layout.avail_ring_offset) as *mut AvailableRing) }
).unwrap();
let used_ring = NonNull::new(
unsafe { &mut *((dma.start_virtual_address() + queue_layout.used_ring_offset) as *mut UsedRing) }
).unwrap();
Ok(VirtQueue {
dma,
descriptor_table,
avail_ring,
used_ring,
queue_size: size,
queue_index: index as u32,
used_num: 0,
free_desc_head: 0,
avail_index: 0,
last_used_index: 0
})
}
/// 添加 buffers 到虚拟队列,返回一个 token
pub fn add_buf(&mut self, inputs: &[&[u8]], outputs: &[&mut [u8]]) -> Result<u16> {
if inputs.is_empty() && outputs.is_empty() {
return Err(VirtIOError::InvalidParameter);
}
if inputs.len() + outputs.len() + self.used_num as usize > self.queue_size as usize {
// buffer 数量溢出
return Err(VirtIOError::Overflow);
}
// 从空闲描述符表中分配描述符
let head = self.free_desc_head;
let mut tail = self.free_desc_head;
let mut self_free_desc_head = self.free_desc_head;
let descriptor_table = unsafe { self.descriptor_table.as_mut() };
inputs.iter().for_each(|input| {
let desc = &mut descriptor_table[self_free_desc_head as usize];
// 将 buffer 的信息写入描述符
desc.set_buf(input);
// 设置描述符的标识位
desc.flags.write(DescriptorFlags::NEXT);
tail = self_free_desc_head;
self_free_desc_head = desc.next.read();
});
self.free_desc_head = self_free_desc_head;
outputs.iter().for_each(|output| {
let desc = &mut descriptor_table[self_free_desc_head as usize];
desc.set_buf(output);
desc.flags.write(DescriptorFlags::NEXT | DescriptorFlags::WRITE);
tail = self_free_desc_head;
self_free_desc_head = desc.next.read();
});
self.free_desc_head = self_free_desc_head;
// 清除描述符链的最后一个元素的 next 指针
{
let desc = &mut descriptor_table[tail as usize];
let mut flags = desc.flags.read();
flags.remove(DescriptorFlags::NEXT);
desc.flags.write(flags);
}
// 更新已使用描述符数目
self.used_num += (inputs.len() + outputs.len()) as u16;
// 将描述符链的头部放入可用环中
let avail_ring = unsafe { self.avail_ring.as_mut() };
let avail_slot = self.avail_index & (self.queue_size - 1);
avail_ring.ring[avail_slot as usize].write(head);
// write barrier(内存屏障操作?)
fence(Ordering::SeqCst);
// 更新可用环的头部
self.avail_index = self.avail_index.wrapping_add(1);
avail_ring.idx.write(self.avail_index);
Ok(head)
}
/// 是否可以从可用环中弹出没处理的项
pub fn can_pop(&self) -> bool {
let used_ring = unsafe { self.used_ring.as_ref() };
self.last_used_index != used_ring.idx.read()
}
/// 可用的空闲描述符数量
pub fn free_desc_num(&self) -> usize {
(self.queue_size - self.used_num) as usize
}
/// 回收描述符
/// 该方法将会把需要回收的描述符链放到空闲描述符链的头部
fn recycle_descriptors(&mut self, mut head: u16) {
let origin_desc_head = self.free_desc_head;
self.free_desc_head = head;
let descriptor_table = unsafe { self.descriptor_table.as_mut() };
loop {
let desc = &mut descriptor_table[head as usize];
let flags = desc.flags.read();
if flags.contains(DescriptorFlags::NEXT) {
head = desc.next.read();
self.used_num -= 1;
} else {
desc.next.write(origin_desc_head);
self.used_num -= 1;
return;
}
}
}
/// 从已用环中弹出一个 token,并返回长度
/// ref: linux virtio_ring.c virtqueue_get_buf_ctx
pub fn pop_used(&mut self) -> Result<(u16, u32)> {
if !self.can_pop() {
return Err(VirtIOError::UsedRingNotReady);
}
// read barrier
fence(Ordering::SeqCst);
let used_ring = unsafe { self.used_ring.as_mut() };
let last_used_slot = self.last_used_index & (self.queue_size - 1);
let index = used_ring.ring[last_used_slot as usize].id.read() as u16;
let len = used_ring.ring[last_used_slot as usize].len.read();
self.recycle_descriptors(index);
self.last_used_index = self.last_used_index.wrapping_add(1);
Ok((index, len))
}
/// 从已用环中取出下一个 token,但不弹出
pub fn next_used(&self) -> Result<(u16, u32)> {
if !self.can_pop() {
return Err(VirtIOError::UsedRingNotReady);
}
// read barrier
fence(Ordering::SeqCst);
let used_ring = unsafe { self.used_ring.as_ref() };
let last_used_slot = self.last_used_index & (self.queue_size - 1);
let index = used_ring.ring[last_used_slot as usize].id.read() as u16;
let len = used_ring.ring[last_used_slot as usize].len.read();
Ok((index, len))
}
pub fn descriptor(&self, index: usize) -> Descriptor {
unsafe { self.descriptor_table.as_ref()[index].clone() }
}
pub fn print_desc_table(&self) {
unsafe {
self.descriptor_table.as_ref().iter().for_each(|desc| {
println!("{:#x?}", desc);
});
}
}
}
/// todo: unsafe
unsafe impl Send for VirtQueue {}
unsafe impl Sync for VirtQueue {}
/// 虚拟队列内存布局信息
struct VirtQueueMemLayout {
/// 可用环地址偏移
avail_ring_offset: usize,
/// 已用环地址偏移
used_ring_offset: usize,
/// 总大小
mem_size: usize
}
impl VirtQueueMemLayout {
fn new(queue_size: u16) -> Self {
assert!(
queue_size.is_power_of_two(),
"[virtio] queue size must be a power off 2"
);
let q_size = queue_size as usize;
let descriptors_size = size_of::<Descriptor>() * q_size;
let avail_ring_size = size_of::<u16>() * (3 + q_size);
let used_ring_size = size_of::<u16>() * 3 + size_of::<UsedElement>() * q_size;
VirtQueueMemLayout {
avail_ring_offset: descriptors_size,
used_ring_offset: align_up_page(descriptors_size + avail_ring_size),
mem_size: align_up_page(descriptors_size + avail_ring_size) + align_up_page(used_ring_size)
}
}
}
/// 描述符
#[repr(C, align(16))]
#[derive(Debug)]
pub struct Descriptor {
/// buffer 的物理地址
pub paddr: Volatile<u64>,
/// buffer 的长度
len: Volatile<u32>,
/// 标识
flags: Volatile<DescriptorFlags>,
/// 下一个描述符的指针
next: Volatile<u16>
}
impl Clone for Descriptor {
fn clone(&self) -> Self {
Self {
paddr : Volatile::<u64>::new(self.paddr.read()),
len : Volatile::<u32>::new(self.len.read()),
flags : Volatile::<DescriptorFlags>::new(self.flags.read()),
next : Volatile::<u16>::new(self.next.read()),
}
}
}
impl Descriptor {
/// 把特定 buffer 的信息写入到描述符
fn set_buf(&mut self, buf: &[u8]) {
let buf_paddr = unsafe {
virtio_virt_to_phys(buf.as_ptr() as usize) as u64
};
self.paddr.write(buf_paddr);
self.len.write(buf.len() as u32);
}
}
bitflags! {
/// 描述符的标识
struct DescriptorFlags: u16 {
const NEXT = 1;
const WRITE = 2;
const INDIRECT = 4;
}
}
/// 环
/// 通过泛型对可用环和已用环进行统一抽象
#[repr(C)]
#[derive(Debug)]
pub struct Ring<Entry: Sized> {
/// 与通知机制相关
flags: Volatile<u16>,
idx: Volatile<u16>,
pub ring: [Entry; VIRT_QUEUE_SIZE],
// unused
event: Volatile<u16>
}
/// 已用环中的项
#[repr(C)]
#[derive(Debug)]
pub struct UsedElement {
id: Volatile<u32>,
len: Volatile<u32>
}
extern "C" {
fn virtio_virt_to_phys(vaddr: usize) -> usize;
} |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type AttributedNetworkUsage = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct CellularApnAuthenticationType(pub i32);
impl CellularApnAuthenticationType {
pub const None: Self = Self(0i32);
pub const Pap: Self = Self(1i32);
pub const Chap: Self = Self(2i32);
pub const Mschapv2: Self = Self(3i32);
}
impl ::core::marker::Copy for CellularApnAuthenticationType {}
impl ::core::clone::Clone for CellularApnAuthenticationType {
fn clone(&self) -> Self {
*self
}
}
pub type CellularApnContext = *mut ::core::ffi::c_void;
pub type ConnectionCost = *mut ::core::ffi::c_void;
pub type ConnectionProfile = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct ConnectionProfileDeleteStatus(pub i32);
impl ConnectionProfileDeleteStatus {
pub const Success: Self = Self(0i32);
pub const DeniedByUser: Self = Self(1i32);
pub const DeniedBySystem: Self = Self(2i32);
pub const UnknownError: Self = Self(3i32);
}
impl ::core::marker::Copy for ConnectionProfileDeleteStatus {}
impl ::core::clone::Clone for ConnectionProfileDeleteStatus {
fn clone(&self) -> Self {
*self
}
}
pub type ConnectionProfileFilter = *mut ::core::ffi::c_void;
pub type ConnectionSession = *mut ::core::ffi::c_void;
pub type ConnectivityInterval = *mut ::core::ffi::c_void;
pub type DataPlanStatus = *mut ::core::ffi::c_void;
pub type DataPlanUsage = *mut ::core::ffi::c_void;
pub type DataUsage = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct DataUsageGranularity(pub i32);
impl DataUsageGranularity {
pub const PerMinute: Self = Self(0i32);
pub const PerHour: Self = Self(1i32);
pub const PerDay: Self = Self(2i32);
pub const Total: Self = Self(3i32);
}
impl ::core::marker::Copy for DataUsageGranularity {}
impl ::core::clone::Clone for DataUsageGranularity {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct DomainConnectivityLevel(pub i32);
impl DomainConnectivityLevel {
pub const None: Self = Self(0i32);
pub const Unauthenticated: Self = Self(1i32);
pub const Authenticated: Self = Self(2i32);
}
impl ::core::marker::Copy for DomainConnectivityLevel {}
impl ::core::clone::Clone for DomainConnectivityLevel {
fn clone(&self) -> Self {
*self
}
}
pub type IPInformation = *mut ::core::ffi::c_void;
pub type LanIdentifier = *mut ::core::ffi::c_void;
pub type LanIdentifierData = *mut ::core::ffi::c_void;
pub type NetworkAdapter = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct NetworkAuthenticationType(pub i32);
impl NetworkAuthenticationType {
pub const None: Self = Self(0i32);
pub const Unknown: Self = Self(1i32);
pub const Open80211: Self = Self(2i32);
pub const SharedKey80211: Self = Self(3i32);
pub const Wpa: Self = Self(4i32);
pub const WpaPsk: Self = Self(5i32);
pub const WpaNone: Self = Self(6i32);
pub const Rsna: Self = Self(7i32);
pub const RsnaPsk: Self = Self(8i32);
pub const Ihv: Self = Self(9i32);
pub const Wpa3: Self = Self(10i32);
pub const Wpa3Enterprise192Bits: Self = Self(10i32);
pub const Wpa3Sae: Self = Self(11i32);
pub const Owe: Self = Self(12i32);
pub const Wpa3Enterprise: Self = Self(13i32);
}
impl ::core::marker::Copy for NetworkAuthenticationType {}
impl ::core::clone::Clone for NetworkAuthenticationType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct NetworkConnectivityLevel(pub i32);
impl NetworkConnectivityLevel {
pub const None: Self = Self(0i32);
pub const LocalAccess: Self = Self(1i32);
pub const ConstrainedInternetAccess: Self = Self(2i32);
pub const InternetAccess: Self = Self(3i32);
}
impl ::core::marker::Copy for NetworkConnectivityLevel {}
impl ::core::clone::Clone for NetworkConnectivityLevel {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct NetworkCostType(pub i32);
impl NetworkCostType {
pub const Unknown: Self = Self(0i32);
pub const Unrestricted: Self = Self(1i32);
pub const Fixed: Self = Self(2i32);
pub const Variable: Self = Self(3i32);
}
impl ::core::marker::Copy for NetworkCostType {}
impl ::core::clone::Clone for NetworkCostType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct NetworkEncryptionType(pub i32);
impl NetworkEncryptionType {
pub const None: Self = Self(0i32);
pub const Unknown: Self = Self(1i32);
pub const Wep: Self = Self(2i32);
pub const Wep40: Self = Self(3i32);
pub const Wep104: Self = Self(4i32);
pub const Tkip: Self = Self(5i32);
pub const Ccmp: Self = Self(6i32);
pub const WpaUseGroup: Self = Self(7i32);
pub const RsnUseGroup: Self = Self(8i32);
pub const Ihv: Self = Self(9i32);
pub const Gcmp: Self = Self(10i32);
pub const Gcmp256: Self = Self(11i32);
}
impl ::core::marker::Copy for NetworkEncryptionType {}
impl ::core::clone::Clone for NetworkEncryptionType {
fn clone(&self) -> Self {
*self
}
}
pub type NetworkItem = *mut ::core::ffi::c_void;
pub type NetworkSecuritySettings = *mut ::core::ffi::c_void;
pub type NetworkStateChangeEventDetails = *mut ::core::ffi::c_void;
pub type NetworkStatusChangedEventHandler = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct NetworkTypes(pub u32);
impl NetworkTypes {
pub const None: Self = Self(0u32);
pub const Internet: Self = Self(1u32);
pub const PrivateNetwork: Self = Self(2u32);
}
impl ::core::marker::Copy for NetworkTypes {}
impl ::core::clone::Clone for NetworkTypes {
fn clone(&self) -> Self {
*self
}
}
pub type NetworkUsage = *mut ::core::ffi::c_void;
#[repr(C)]
pub struct NetworkUsageStates {
pub Roaming: TriStates,
pub Shared: TriStates,
}
impl ::core::marker::Copy for NetworkUsageStates {}
impl ::core::clone::Clone for NetworkUsageStates {
fn clone(&self) -> Self {
*self
}
}
pub type ProviderNetworkUsage = *mut ::core::ffi::c_void;
pub type ProxyConfiguration = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct RoamingStates(pub u32);
impl RoamingStates {
pub const None: Self = Self(0u32);
pub const NotRoaming: Self = Self(1u32);
pub const Roaming: Self = Self(2u32);
}
impl ::core::marker::Copy for RoamingStates {}
impl ::core::clone::Clone for RoamingStates {
fn clone(&self) -> Self {
*self
}
}
pub type RoutePolicy = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct TriStates(pub i32);
impl TriStates {
pub const DoNotCare: Self = Self(0i32);
pub const No: Self = Self(1i32);
pub const Yes: Self = Self(2i32);
}
impl ::core::marker::Copy for TriStates {}
impl ::core::clone::Clone for TriStates {
fn clone(&self) -> Self {
*self
}
}
pub type WlanConnectionProfileDetails = *mut ::core::ffi::c_void;
pub type WwanConnectionProfileDetails = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct WwanDataClass(pub u32);
impl WwanDataClass {
pub const None: Self = Self(0u32);
pub const Gprs: Self = Self(1u32);
pub const Edge: Self = Self(2u32);
pub const Umts: Self = Self(4u32);
pub const Hsdpa: Self = Self(8u32);
pub const Hsupa: Self = Self(16u32);
pub const LteAdvanced: Self = Self(32u32);
pub const Cdma1xRtt: Self = Self(65536u32);
pub const Cdma1xEvdo: Self = Self(131072u32);
pub const Cdma1xEvdoRevA: Self = Self(262144u32);
pub const Cdma1xEvdv: Self = Self(524288u32);
pub const Cdma3xRtt: Self = Self(1048576u32);
pub const Cdma1xEvdoRevB: Self = Self(2097152u32);
pub const CdmaUmb: Self = Self(4194304u32);
pub const Custom: Self = Self(2147483648u32);
}
impl ::core::marker::Copy for WwanDataClass {}
impl ::core::clone::Clone for WwanDataClass {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct WwanNetworkIPKind(pub i32);
impl WwanNetworkIPKind {
pub const None: Self = Self(0i32);
pub const Ipv4: Self = Self(1i32);
pub const Ipv6: Self = Self(2i32);
pub const Ipv4v6: Self = Self(3i32);
pub const Ipv4v6v4Xlat: Self = Self(4i32);
}
impl ::core::marker::Copy for WwanNetworkIPKind {}
impl ::core::clone::Clone for WwanNetworkIPKind {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct WwanNetworkRegistrationState(pub i32);
impl WwanNetworkRegistrationState {
pub const None: Self = Self(0i32);
pub const Deregistered: Self = Self(1i32);
pub const Searching: Self = Self(2i32);
pub const Home: Self = Self(3i32);
pub const Roaming: Self = Self(4i32);
pub const Partner: Self = Self(5i32);
pub const Denied: Self = Self(6i32);
}
impl ::core::marker::Copy for WwanNetworkRegistrationState {}
impl ::core::clone::Clone for WwanNetworkRegistrationState {
fn clone(&self) -> Self {
*self
}
}
|
use super::xloc::*;
use super::VarResult;
use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType};
use crate::helper::err_msgs::*;
use crate::helper::str_replace;
use crate::helper::{
move_element, pine_ref_to_bool, pine_ref_to_color, pine_ref_to_f64, pine_ref_to_i64,
pine_ref_to_string,
};
use crate::runtime::context::{downcast_ctx, Ctx};
use crate::runtime::output::{OutputData, OutputInfo, PlotInfo, StrOptionsData};
use crate::types::{
downcast_pf, Bool, Callable, CallableFactory, CallableObject, Category, Color, ComplexType,
DataType, Float, Int, ParamCollectCall, PineClass, PineFrom, PineRef, PineStaticType, PineType,
RefData, RuntimeErr, SecondType, Series, SeriesCall, SimpleType, NA,
};
use std::cell::{Ref, RefCell};
use std::collections::BTreeMap;
use std::fmt;
use std::mem;
use std::ops::Deref;
use std::rc::Rc;
pub type PerLabelItem = Rc<RefCell<Option<PerLabel>>>;
const LABEL_STYLE_NONE: &'static str = "none";
const LABEL_STYLE_XCROSS: &'static str = "xcross";
const LABEL_STYLE_CROSS: &'static str = "cross";
const LABEL_STYLE_TRIANGLEUP: &'static str = "triangleup";
const LABEL_STYLE_TRIANGLEDOWN: &'static str = "triangledown";
const LABEL_STYLE_FLAG: &'static str = "flag";
const LABEL_STYLE_CIRCLE: &'static str = "circle";
const LABEL_STYLE_ARROWUP: &'static str = "arrowup";
const LABEL_STYLE_ARROWDOWN: &'static str = "arrowdown";
const LABEL_STYLE_LABELUP: &'static str = "labelup";
const LABEL_STYLE_LABELDOWN: &'static str = "labeldown";
const LABEL_STYLE_LABELLEFT: &'static str = "labelleft";
const LABEL_STYLE_LABELRIGHT: &'static str = "labelright";
const LABEL_STYLE_LABELCENTER: &'static str = "labelcenter";
const LABEL_STYLE_SQUARE: &'static str = "square";
const LABEL_STYLE_DIAMOND: &'static str = "diamond";
#[derive(Clone, Copy, Debug)]
pub enum StyleEnum {
None = 0,
Xcross = 1,
Cross = 2,
Triangleup = 3,
Triangledown = 4,
Flag = 5,
Circle = 6,
Arrowup = 7,
Arrowdown = 8,
Labelup = 9,
Labeldown = 10,
Labelleft = 11,
Labelright = 12,
Labelcenter = 13,
Square = 14,
Diamond = 15,
}
impl StyleEnum {
fn from_str(s: &str) -> Result<StyleEnum, RuntimeErr> {
match s {
LABEL_STYLE_NONE => Ok(StyleEnum::None),
LABEL_STYLE_XCROSS => Ok(StyleEnum::Xcross),
LABEL_STYLE_CROSS => Ok(StyleEnum::Cross),
LABEL_STYLE_TRIANGLEUP => Ok(StyleEnum::Triangleup),
LABEL_STYLE_TRIANGLEDOWN => Ok(StyleEnum::Triangledown),
LABEL_STYLE_FLAG => Ok(StyleEnum::Flag),
LABEL_STYLE_CIRCLE => Ok(StyleEnum::Circle),
LABEL_STYLE_ARROWUP => Ok(StyleEnum::Arrowup),
LABEL_STYLE_ARROWDOWN => Ok(StyleEnum::Arrowdown),
LABEL_STYLE_LABELUP => Ok(StyleEnum::Labelup),
LABEL_STYLE_LABELDOWN => Ok(StyleEnum::Labeldown),
LABEL_STYLE_LABELLEFT => Ok(StyleEnum::Labelleft),
LABEL_STYLE_LABELRIGHT => Ok(StyleEnum::Labelright),
LABEL_STYLE_LABELCENTER => Ok(StyleEnum::Labelcenter),
LABEL_STYLE_SQUARE => Ok(StyleEnum::Square),
LABEL_STYLE_DIAMOND => Ok(StyleEnum::Diamond),
_ => Err(RuntimeErr::InvalidParameters(str_replace(
INVALID_VALS,
vec![String::from("style")],
))),
}
}
fn from_pf<'a>(s: Option<PineRef<'a>>) -> Result<StyleEnum, RuntimeErr> {
match pine_ref_to_string(s) {
None => Ok(StyleEnum::None),
Some(s) => StyleEnum::from_str(&s[..]),
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum XLocEnum {
BarIndex = 0,
BarTime = 1,
}
impl XLocEnum {
fn from_str(s: &str) -> Result<XLocEnum, RuntimeErr> {
match s {
XLOC_BAR_INDEX => Ok(XLocEnum::BarIndex),
XLOC_BAR_TIME => Ok(XLocEnum::BarTime),
_ => Err(RuntimeErr::InvalidParameters(str_replace(
INVALID_VALS,
vec![String::from("xloc")],
))),
}
}
fn from_pf<'a>(s: Option<PineRef<'a>>) -> Result<XLocEnum, RuntimeErr> {
match pine_ref_to_string(s) {
None => Ok(XLocEnum::BarIndex),
Some(s) => XLocEnum::from_str(&s[..]),
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum YLocEnum {
Price = 0,
Abovebar = 1,
Belowbar = 2,
}
impl YLocEnum {
fn from_str(s: &str) -> Result<YLocEnum, RuntimeErr> {
match s {
"price" => Ok(YLocEnum::Price),
"abovebar" => Ok(YLocEnum::Abovebar),
"belowbar" => Ok(YLocEnum::Belowbar),
_ => Err(RuntimeErr::InvalidParameters(str_replace(
INVALID_VALS,
vec![String::from("yloc")],
))),
}
}
fn from_pf<'a>(s: Option<PineRef<'a>>) -> Result<YLocEnum, RuntimeErr> {
match pine_ref_to_string(s) {
None => Ok(YLocEnum::Price),
Some(s) => YLocEnum::from_str(&s[..]),
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum SizeEnum {
Auto = 0,
Huge = 1,
Large = 2,
Normal = 3,
Small = 4,
Tiny = 5,
}
impl SizeEnum {
fn from_str(s: &str) -> Result<SizeEnum, RuntimeErr> {
match s {
"auto" => Ok(SizeEnum::Auto),
"huge" => Ok(SizeEnum::Huge),
"large" => Ok(SizeEnum::Large),
"normal" => Ok(SizeEnum::Normal),
"small" => Ok(SizeEnum::Small),
"tiny" => Ok(SizeEnum::Tiny),
_ => Err(RuntimeErr::InvalidParameters(str_replace(
INVALID_VALS,
vec![String::from("size")],
))),
}
}
fn from_pf<'a>(s: Option<PineRef<'a>>) -> Result<SizeEnum, RuntimeErr> {
match pine_ref_to_string(s) {
None => Ok(SizeEnum::Auto),
Some(s) => SizeEnum::from_str(&s[..]),
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum TextAlignEnum {
Left = 0,
Center = 1,
Right = 2,
}
impl TextAlignEnum {
fn from_str(s: &str) -> Result<TextAlignEnum, RuntimeErr> {
match s {
"left" => Ok(TextAlignEnum::Left),
"center" => Ok(TextAlignEnum::Center),
"right" => Ok(TextAlignEnum::Right),
_ => Err(RuntimeErr::InvalidParameters(str_replace(
INVALID_VALS,
vec![String::from("textalign")],
))),
}
}
fn from_pf<'a>(s: Option<PineRef<'a>>) -> Result<TextAlignEnum, RuntimeErr> {
match pine_ref_to_string(s) {
None => Ok(TextAlignEnum::Left),
Some(s) => TextAlignEnum::from_str(&s[..]),
}
}
}
fn is_label_na<'a>(val: Option<PineRef<'a>>) -> bool {
if val.is_none() {
return true;
}
match PerLabelItem::implicity_from(val.unwrap()) {
Ok(res) => {
let item: &PerLabelItem = res.deref();
item.borrow().is_none()
}
Err(_) => true,
}
}
fn pine_ref_to_label<'a>(val: Option<PineRef<'a>>) -> PerLabelItem {
if val.is_none() {
return Rc::new(RefCell::new(None));
}
match PerLabelItem::implicity_from(val.unwrap()) {
Ok(res) => res.into_inner(),
Err(_) => Rc::new(RefCell::new(None)),
}
}
// The label definition that represent every label object.
#[derive(Debug, Clone, PartialEq)]
pub struct PerLabel {
// x, y, text, xloc, yloc, color, style, textcolor, size, textalign
x: Int,
y: Float,
text: Option<String>,
xloc: i32,
yloc: i32,
color: Option<String>,
style: i32,
textcolor: Option<String>,
size: i32,
textalign: i32,
}
impl PerLabel {
pub fn new() -> PerLabel {
PerLabel {
x: None,
y: None,
text: None,
xloc: 0,
yloc: 0,
color: None,
style: 0,
textcolor: None,
size: 0,
textalign: 0,
}
}
}
impl PineStaticType for PerLabelItem {
fn static_type() -> (DataType, SecondType) {
(DataType::Label, SecondType::Simple)
}
}
impl<'a> PineFrom<'a, PerLabelItem> for PerLabelItem {
fn implicity_from(t: PineRef<'a>) -> Result<RefData<PerLabelItem>, RuntimeErr> {
match t.get_type() {
(DataType::Label, SecondType::Simple) => Ok(downcast_pf::<PerLabelItem>(t).unwrap()),
(DataType::Label, SecondType::Series) => {
let f: RefData<Series<PerLabelItem>> =
downcast_pf::<Series<PerLabelItem>>(t).unwrap();
Ok(RefData::new(f.get_current()))
}
(DataType::NA, _) => Ok(RefData::new(Rc::new(RefCell::new(None)))),
_ => Err(RuntimeErr::UnknownRuntimeErr),
}
}
}
impl<'a> PineType<'a> for PerLabelItem {
fn get_type(&self) -> (DataType, SecondType) {
(DataType::Line, SecondType::Simple)
}
fn copy(&self) -> PineRef<'a> {
PineRef::new(self.clone())
}
}
impl<'a> SimpleType for PerLabelItem {}
// The label invocation that create new LineInfo object
#[derive(Debug)]
struct LineFromNaVal<'a> {
labels: RefData<Series<'a, PerLabelItem>>,
}
impl<'a> Clone for LineFromNaVal<'a> {
fn clone(&self) -> Self {
LineFromNaVal {
labels: RefData::clone(&self.labels),
}
}
}
impl<'a> LineFromNaVal<'a> {
fn new() -> LineFromNaVal<'a> {
LineFromNaVal {
labels: RefData::new(Series::from(Rc::new(RefCell::new(None)))),
}
}
}
impl<'a> SeriesCall<'a> for LineFromNaVal<'a> {
fn step(
&mut self,
_context: &mut dyn Ctx<'a>,
mut p: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
if p.len() == 1 {
let v = mem::replace(&mut p[0], None);
match is_label_na(v.clone()) {
true => Ok(RefData::clone(&self.labels).into_pf()),
false => Ok(Series::<'a, PerLabelItem>::implicity_from(v.unwrap())
.unwrap()
.into_pf()),
}
} else {
move_tuplet!((x, y, text, xloc, yloc, color, style, textcolor, size, textalign) = p);
let label = PerLabel {
x: pine_ref_to_i64(x),
y: pine_ref_to_f64(y),
text: pine_ref_to_string(text),
xloc: XLocEnum::from_pf(xloc)? as i32,
yloc: YLocEnum::from_pf(yloc)? as i32,
color: pine_ref_to_color(color),
style: StyleEnum::from_pf(style)? as i32,
textcolor: pine_ref_to_color(textcolor),
size: SizeEnum::from_pf(size)? as i32,
textalign: TextAlignEnum::from_pf(textalign)? as i32,
};
self.labels.update(Rc::new(RefCell::new(Some(label))));
Ok(RefData::clone(&self.labels).into_pf())
}
}
fn copy(&self) -> Box<dyn SeriesCall<'a> + 'a> {
Box::new(self.clone())
}
}
fn delete_func<'a>(
_context: &mut dyn Ctx<'a>,
mut param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
let id = mem::replace(&mut param[0], None);
let label = pine_ref_to_label(id);
label.replace(None);
Ok(PineRef::new(NA))
}
fn get_val_func<'a, T: Default + Clone + fmt::Debug + PineType<'a> + PineStaticType + 'a>(
_context: &mut dyn Ctx<'a>,
mut param: Vec<Option<PineRef<'a>>>,
func: impl Fn(&PerLabel) -> T,
) -> Result<PineRef<'a>, RuntimeErr> {
let id = mem::replace(&mut param[0], None);
let label = pine_ref_to_label(id);
match unsafe { label.as_ptr().as_ref().unwrap() } {
None => Ok(PineRef::new(NA)),
Some(v) => Ok(PineRef::new(Series::from(func(v)))),
}
}
fn get_x_func<'a>(
_context: &mut dyn Ctx<'a>,
param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
get_val_func(_context, param, |v| v.x)
}
fn get_y_func<'a>(
_context: &mut dyn Ctx<'a>,
param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
get_val_func(_context, param, |v| v.y)
}
fn get_text_func<'a>(
_context: &mut dyn Ctx<'a>,
param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
get_val_func(_context, param, |v| {
v.text.clone().unwrap_or(String::from(""))
})
}
fn set_val_func<'a>(
_context: &mut dyn Ctx<'a>,
mut param: Vec<Option<PineRef<'a>>>,
mut func: impl FnMut(&mut PerLabel, Option<PineRef<'a>>) -> Result<(), RuntimeErr>,
) -> Result<PineRef<'a>, RuntimeErr> {
let id = mem::replace(&mut param[0], None);
let val = mem::replace(&mut param[1], None);
let label = pine_ref_to_label(id);
if label.borrow_mut().is_none() {
*label.borrow_mut() = Some(PerLabel::new());
}
func(label.borrow_mut().as_mut().unwrap(), val);
Ok(PineRef::new(NA))
}
fn set_x_func<'a>(
_c: &mut dyn Ctx<'a>,
p: Vec<Option<PineRef<'a>>>,
_f: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
set_val_func(_c, p, |l, v| {
l.x = pine_ref_to_i64(v);
Ok(())
})
}
fn set_y_func<'a>(
_context: &mut dyn Ctx<'a>,
param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
set_val_func(_context, param, |l, v| {
l.y = pine_ref_to_f64(v);
Ok(())
})
}
fn set_color_func<'a>(
_context: &mut dyn Ctx<'a>,
param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
set_val_func(_context, param, |l, v| {
l.color = pine_ref_to_color(v);
Ok(())
})
}
fn set_size_func<'a>(
_context: &mut dyn Ctx<'a>,
param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
set_val_func(_context, param, |l, v| {
l.size = SizeEnum::from_pf(v)? as i32;
Ok(())
})
}
fn set_style_func<'a>(
_context: &mut dyn Ctx<'a>,
param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
set_val_func(_context, param, |l, v| {
l.style = StyleEnum::from_pf(v)? as i32;
Ok(())
})
}
fn set_textalign_func<'a>(
_context: &mut dyn Ctx<'a>,
param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
set_val_func(_context, param, |l, v| {
l.textalign = TextAlignEnum::from_pf(v)? as i32;
Ok(())
})
}
fn set_text_func<'a>(
_context: &mut dyn Ctx<'a>,
param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
set_val_func(_context, param, |l, v| {
l.text = pine_ref_to_string(v);
Ok(())
})
}
fn set_textcolor_func<'a>(
_context: &mut dyn Ctx<'a>,
param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
set_val_func(_context, param, |l, v| {
l.textcolor = pine_ref_to_color(v);
Ok(())
})
}
fn set_xloc_func<'a>(
_context: &mut dyn Ctx<'a>,
mut param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
move_tuplet!((id, x, xloc) = param);
let label = pine_ref_to_label(id);
if label.borrow_mut().is_none() {
*label.borrow_mut() = Some(PerLabel::new());
}
let mut li = label.borrow_mut();
li.as_mut().unwrap().x = pine_ref_to_i64(x);
li.as_mut().unwrap().xloc = XLocEnum::from_pf(xloc)? as i32;
Ok(PineRef::new(NA))
}
fn set_yloc_func<'a>(
_context: &mut dyn Ctx<'a>,
param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
set_val_func(_context, param, |l, v| {
l.yloc = YLocEnum::from_pf(v)? as i32;
Ok(())
})
}
fn set_xy_func<'a>(
_context: &mut dyn Ctx<'a>,
mut param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
move_tuplet!((id, x, y) = param);
let label = pine_ref_to_label(id);
if label.borrow_mut().is_none() {
*label.borrow_mut() = Some(PerLabel::new());
}
let mut li = label.borrow_mut();
li.as_mut().unwrap().x = pine_ref_to_i64(x);
li.as_mut().unwrap().y = pine_ref_to_f64(y);
Ok(PineRef::new(NA))
}
struct PlotProps;
impl<'a> PineClass<'a> for PlotProps {
fn custom_type(&self) -> &str {
"label"
}
fn get(&self, _ctx: &mut dyn Ctx<'a>, name: &str) -> Result<PineRef<'a>, RuntimeErr> {
match name {
"new" => Ok(PineRef::new(CallableFactory::new(|| {
Callable::new(None, Some(Box::new(LineFromNaVal::new())))
}))),
"delete" => Ok(PineRef::new(Callable::new(Some(delete_func), None))),
"get_x" => Ok(PineRef::new(Callable::new(Some(get_x_func), None))),
"get_y" => Ok(PineRef::new(Callable::new(Some(get_y_func), None))),
"get_text" => Ok(PineRef::new(Callable::new(Some(get_text_func), None))),
"set_x" => Ok(PineRef::new(Callable::new(Some(set_x_func), None))),
"set_y" => Ok(PineRef::new(Callable::new(Some(set_y_func), None))),
"set_xy" => Ok(PineRef::new(Callable::new(Some(set_xy_func), None))),
"set_color" => Ok(PineRef::new(Callable::new(Some(set_color_func), None))),
"set_size" => Ok(PineRef::new(Callable::new(Some(set_size_func), None))),
"set_style" => Ok(PineRef::new(Callable::new(Some(set_style_func), None))),
"set_text" => Ok(PineRef::new(Callable::new(Some(set_text_func), None))),
"set_textalign" => Ok(PineRef::new(Callable::new(Some(set_textalign_func), None))),
"set_textcolor" => Ok(PineRef::new(Callable::new(Some(set_textcolor_func), None))),
"set_xloc" => Ok(PineRef::new(Callable::new(Some(set_xloc_func), None))),
"set_yloc" => Ok(PineRef::new(Callable::new(Some(set_yloc_func), None))),
"style_none" => Ok(PineRef::new(String::from(LABEL_STYLE_NONE))),
"style_arrowdown" => Ok(PineRef::new(String::from(LABEL_STYLE_ARROWDOWN))),
"style_arrowup" => Ok(PineRef::new(String::from(LABEL_STYLE_ARROWUP))),
"style_circle" => Ok(PineRef::new(String::from(LABEL_STYLE_CIRCLE))),
"style_cross" => Ok(PineRef::new(String::from(LABEL_STYLE_CROSS))),
"style_diamond" => Ok(PineRef::new(String::from(LABEL_STYLE_DIAMOND))),
"style_flag" => Ok(PineRef::new(String::from(LABEL_STYLE_FLAG))),
"style_label_center" => Ok(PineRef::new(String::from(LABEL_STYLE_LABELCENTER))),
"style_label_down" => Ok(PineRef::new(String::from(LABEL_STYLE_LABELDOWN))),
"style_label_left" => Ok(PineRef::new(String::from(LABEL_STYLE_LABELLEFT))),
"style_label_right" => Ok(PineRef::new(String::from(LABEL_STYLE_LABELRIGHT))),
"style_label_up" => Ok(PineRef::new(String::from(LABEL_STYLE_LABELUP))),
"style_square" => Ok(PineRef::new(String::from(LABEL_STYLE_SQUARE))),
"style_triangledown" => Ok(PineRef::new(String::from(LABEL_STYLE_TRIANGLEDOWN))),
"style_triangleup" => Ok(PineRef::new(String::from(LABEL_STYLE_TRIANGLEUP))),
"style_xcross" => Ok(PineRef::new(String::from(LABEL_STYLE_XCROSS))),
_ => Err(RuntimeErr::NotImplement(str_replace(
NO_FIELD_IN_OBJECT,
vec![String::from(name), String::from("plot")],
))),
}
}
fn copy(&self) -> Box<dyn PineClass<'a> + 'a> {
Box::new(PlotProps)
}
}
pub const VAR_NAME: &'static str = "label";
pub fn declare_var<'a>() -> VarResult<'a> {
let value = PineRef::new(CallableObject::new(Box::new(PlotProps), || {
Callable::new(None, Some(Box::new(LineFromNaVal::new())))
}));
let func_type = FunctionTypes(vec![FunctionType::new((
vec![("x", SyntaxType::Simple(SimpleSyntaxType::Na))],
SyntaxType::ObjectClass("label"),
))]);
let mut obj_type = BTreeMap::new();
obj_type.insert(
"delete",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![("id", SyntaxType::ObjectClass("label"))],
SyntaxType::Void,
))]))),
);
obj_type.insert(
"new",
// x, y, text, xloc, yloc, color, style, textcolor, size, textalign
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![
("x", SyntaxType::int_series()),
("y", SyntaxType::float_series()),
("text", SyntaxType::string_series()),
("xloc", SyntaxType::string_series()),
("yloc", SyntaxType::string_series()),
("color", SyntaxType::color_series()),
("style", SyntaxType::string_series()),
("textcolor", SyntaxType::color_series()),
("size", SyntaxType::string_series()),
("textalign", SyntaxType::string_series()),
],
SyntaxType::ObjectClass("label"),
))]))),
);
obj_type.insert(
"get_x",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![("id", SyntaxType::ObjectClass("label"))],
SyntaxType::int_series(),
))]))),
);
obj_type.insert(
"get_y",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![("id", SyntaxType::ObjectClass("label"))],
SyntaxType::float_series(),
))]))),
);
obj_type.insert(
"get_text",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![("id", SyntaxType::ObjectClass("label"))],
SyntaxType::string_series(),
))]))),
);
obj_type.insert(
"set_x",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![
("id", SyntaxType::ObjectClass("label")),
("x", SyntaxType::int_series()),
],
SyntaxType::Void,
))]))),
);
obj_type.insert(
"set_y",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![
("id", SyntaxType::ObjectClass("label")),
("x", SyntaxType::float_series()),
],
SyntaxType::Void,
))]))),
);
obj_type.insert(
"set_xy",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![
("id", SyntaxType::ObjectClass("label")),
("x", SyntaxType::int_series()),
("y", SyntaxType::float_series()),
],
SyntaxType::Void,
))]))),
);
obj_type.insert(
"set_color",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![
("id", SyntaxType::ObjectClass("label")),
("color", SyntaxType::color_series()),
],
SyntaxType::Void,
))]))),
);
obj_type.insert(
"set_size",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![
("id", SyntaxType::ObjectClass("label")),
("size", SyntaxType::string_series()),
],
SyntaxType::Void,
))]))),
);
obj_type.insert(
"set_style",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![
("id", SyntaxType::ObjectClass("label")),
("style", SyntaxType::string_series()),
],
SyntaxType::Void,
))]))),
);
obj_type.insert(
"set_text",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![
("id", SyntaxType::ObjectClass("label")),
("text", SyntaxType::string_series()),
],
SyntaxType::Void,
))]))),
);
obj_type.insert(
"set_textalign",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![
("id", SyntaxType::ObjectClass("label")),
("textalign", SyntaxType::string_series()),
],
SyntaxType::Void,
))]))),
);
obj_type.insert(
"set_textcolor",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![
("id", SyntaxType::ObjectClass("label")),
("textcolor", SyntaxType::color_series()),
],
SyntaxType::Void,
))]))),
);
obj_type.insert(
"set_xloc",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![
("id", SyntaxType::ObjectClass("label")),
("x", SyntaxType::int_series()),
("xloc", SyntaxType::string_series()),
],
SyntaxType::Void,
))]))),
);
obj_type.insert(
"set_yloc",
SyntaxType::Function(Rc::new(FunctionTypes(vec![FunctionType::new((
vec![
("id", SyntaxType::ObjectClass("label")),
("yloc", SyntaxType::string_series()),
],
SyntaxType::Void,
))]))),
);
obj_type.insert("style_none", SyntaxType::string());
obj_type.insert("style_arrowdown", SyntaxType::string());
obj_type.insert("style_arrowup", SyntaxType::string());
obj_type.insert("style_circle", SyntaxType::string());
obj_type.insert("style_cross", SyntaxType::string());
obj_type.insert("style_diamond", SyntaxType::string());
obj_type.insert("style_flag", SyntaxType::string());
obj_type.insert("style_label_center", SyntaxType::string());
obj_type.insert("style_label_down", SyntaxType::string());
obj_type.insert("style_label_left", SyntaxType::string());
obj_type.insert("style_label_right", SyntaxType::string());
obj_type.insert("style_label_up", SyntaxType::string());
obj_type.insert("style_square", SyntaxType::string());
obj_type.insert("style_triangledown", SyntaxType::string());
obj_type.insert("style_triangleup", SyntaxType::string());
obj_type.insert("style_xcross", SyntaxType::string());
let syntax_type = SyntaxType::ObjectFunction(Rc::new(obj_type), Rc::new(func_type));
VarResult::new(value, syntax_type, VAR_NAME)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::runtime::{AnySeries, NoneCallback};
use crate::{LibInfo, PineParser, PineRunner};
#[test]
fn label_capture_test() {
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))],
);
let src = "label(na)\nx = label(na)\nx2 = if true\n label(na)\nelse\n label(na)";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner.runl(&vec![], 2, None).unwrap();
assert_eq!(runner.get_context().get_shapes().len(), 3);
}
#[test]
fn label_new_capture_test() {
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))],
);
let src = "label.new(1, 2)\nx = label.new(1, 2)\n";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner.runl(&vec![], 2, None).unwrap();
assert_eq!(runner.get_context().get_shapes().len(), 2);
}
#[test]
fn label_test() {
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))],
);
let src = "x = label(na)\nlabel y = label(na)\nlabel x2 = label.new(1, 2)";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner.runl(&vec![], 2, None).unwrap();
}
#[test]
fn label_create_test() {
use crate::ast::stat_expr_types::VarIndex;
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))],
);
let src = "x = label(na)\nx := label.new(1, 2)";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner.runl(&vec![], 2, None).unwrap();
assert_eq!(runner.get_context().get_shapes().len(), 1);
let result = runner.get_context().move_var(VarIndex::new(0, 0)).unwrap();
let mut label = PerLabel::new();
label.x = Some(1i64);
label.y = Some(2f64);
assert_eq!(
Series::implicity_from(result).unwrap(),
RefData::new(Series::from_vec(vec![
Rc::new(RefCell::new(Some(label.clone()))),
Rc::new(RefCell::new(Some(label.clone()))),
]))
);
}
#[test]
fn label_delete_test() {
use crate::ast::stat_expr_types::VarIndex;
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))],
);
let src = "x = label(na)\nx := label.new(1, 2)\nlabel.delete(x[1])";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner.runl(&vec![], 2, None).unwrap();
assert_eq!(runner.get_context().get_shapes().len(), 1);
let result = runner.get_context().move_var(VarIndex::new(0, 0)).unwrap();
let mut label = PerLabel::new();
label.x = Some(1i64);
label.y = Some(2f64);
assert_eq!(
Series::implicity_from(result).unwrap(),
RefData::new(Series::from_vec(vec![
Rc::new(RefCell::new(None)),
Rc::new(RefCell::new(Some(label)))
]))
);
}
#[test]
fn label_get_test() {
use crate::ast::stat_expr_types::VarIndex;
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))],
);
let src = r#"
x = label.new(1, 2, "hello")
x1 = label.get_x(x)
x2 = label.get_y(x)
x3 = label.get_text(x)
"#;
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner.runl(&vec![], 2, None).unwrap();
assert_eq!(runner.get_context().get_shapes().len(), 1);
assert_eq!(
runner.get_context().move_var(VarIndex::new(1, 0)),
Some(PineRef::new(Series::from_vec(vec![Some(1i64), Some(1i64)])))
);
assert_eq!(
runner.get_context().move_var(VarIndex::new(2, 0)),
Some(PineRef::new(Series::from_vec(vec![Some(2f64), Some(2f64)])))
);
assert_eq!(
runner.get_context().move_var(VarIndex::new(3, 0)),
Some(PineRef::new(Series::from_vec(vec![
String::from("hello"),
String::from("hello"),
])))
);
}
#[test]
fn label_set_test() {
use crate::ast::stat_expr_types::VarIndex;
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))],
);
let src = r#"
x = label.new(1, 2)
label.set_x(x, int(close))
label.set_y(x, close + 10)
label.set_color(x, #ffffff)
label.set_size(x, "auto")
label.set_style(x, "none")
label.set_text(x, "hello")
label.set_textalign(x, "left")
label.set_textcolor(x, #111111)
"#;
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner
.run(
&vec![(
"close",
AnySeries::from_float_vec(vec![Some(1f64), Some(2f64)]),
)],
None,
)
.unwrap();
assert_eq!(runner.get_context().get_shapes().len(), 1);
let result = runner.get_context().move_var(VarIndex::new(0, 0)).unwrap();
let mut label1 = PerLabel::new();
label1.x = Some(1i64);
label1.y = Some(11f64);
label1.text = Some(String::from("hello"));
label1.color = Some(String::from("#ffffff"));
label1.size = 0;
label1.style = 0;
label1.textalign = 0;
label1.textcolor = Some(String::from("#111111"));
let mut label2 = label1.clone();
label2.x = Some(2i64);
label2.y = Some(12f64);
assert_eq!(
Series::implicity_from(result).unwrap(),
RefData::new(Series::from_vec(vec![
Rc::new(RefCell::new(Some(label1))),
Rc::new(RefCell::new(Some(label2)))
]))
);
}
#[test]
fn label_set2_test() {
use crate::ast::stat_expr_types::VarIndex;
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))],
);
let src = r#"
x = label.new(1, 2)
label.set_xy(x, 3, 4)
label.set_xloc(x, 8, "bar_time")
label.set_yloc(x, "abovebar")
"#;
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner
.run(
&vec![(
"close",
AnySeries::from_float_vec(vec![Some(1f64), Some(2f64)]),
)],
None,
)
.unwrap();
assert_eq!(runner.get_context().get_shapes().len(), 1);
let result = runner.get_context().move_var(VarIndex::new(0, 0)).unwrap();
let mut label1 = PerLabel::new();
label1.x = Some(8i64);
label1.y = Some(4f64);
label1.xloc = XLocEnum::BarTime as i32;
label1.yloc = YLocEnum::Abovebar as i32;
assert_eq!(
Series::implicity_from(result).unwrap(),
RefData::new(Series::from_vec(vec![
Rc::new(RefCell::new(Some(label1.clone()))),
Rc::new(RefCell::new(Some(label1.clone())))
]))
);
}
#[test]
fn label_style_test() {
use crate::ast::stat_expr_types::VarIndex;
use crate::runtime::VarOperate;
use crate::types::{downcast_pf, Tuple};
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::float_series())],
);
let src = r"m = [
label.style_none, label.style_arrowdown, label.style_arrowup, label.style_circle,
label.style_cross, label.style_diamond, label.style_flag, label.style_label_center,
label.style_label_down, label.style_label_left, label.style_label_right, label.style_label_up,
label.style_square, label.style_triangledown, label.style_triangleup, label.style_xcross
]";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner
.run(
&vec![("close", AnySeries::from_float_vec(vec![Some(1f64)]))],
None,
)
.unwrap();
let tuple_res =
downcast_pf::<Tuple>(runner.get_context().move_var(VarIndex::new(0, 0)).unwrap());
let tuple_vec = tuple_res.unwrap().into_inner().0;
assert_eq!(
tuple_vec,
vec![
"none",
"arrowdown",
"arrowup",
"circle",
"cross",
"diamond",
"flag",
"labelcenter",
"labeldown",
"labelleft",
"labelright",
"labelup",
"square",
"triangledown",
"triangleup",
"xcross"
]
.iter()
.map(|&s| PineRef::new_rc(String::from(s)))
.collect::<Vec<_>>()
);
}
}
|
//! The main user interface from which the user will define systems to create.
//! They can also access and modify the `DataBase` of components to use in their
//! systems.
#[macro_use] mod utils;
mod edit_component;
mod edit_database;
use super::Config;
use error::{GrafenCliError, Result, UIErrorKind, UIResult};
use output;
use ui::utils::{MenuResult, YesOrNo,
get_value_from_user, get_value_or_default_from_user, get_coord_from_user,
get_position_from_user, remove_items, reorder_list, select_command,
select_direction, select_item};
use grafen::coord::{Coord, Translate};
use grafen::database::*;
use grafen::read_conf::{ConfType, ReadConf};
use grafen::surface::LatticeType;
use grafen::system::*;
use grafen::volume::{FillType, Volume};
use std::path::Path;
/// Loop over a menu in which the user can define the system which will be created, etc.
///
/// The idea of this interface is relatively simple:
///
/// 1. The user reads or constructs a `DataBase` of residue (`Residue`)
/// and component (`ComponentEntry`) definitions.
/// 2. Using these construct the actual components which make up the system.
/// 3. Modifies or transforms these components by copying, translating, rotating etc.
/// 4. Finally saves the full system to disk.
pub fn user_menu(config: Config) -> Result<()> {
let mut system = System {
title: config.title,
output_path: config.output_path,
database: config.database,
components: config.components,
};
create_menu![
@pre: { system.print_state() };
AddComponent, "Construct a component" => {
create_component(&mut system)
},
EditComponent, "Edit or clone a component" => {
edit_component::user_menu(&mut system.components)
},
RemoveItems, "Remove a component from the list" => {
remove_items(&mut system.components).map(|_| None)
},
ReorderList, "Reorder list of components" => {
reorder_list(&mut system.components).map(|_| None)
},
EditDatabase, "Edit the database of residue and object definitions" => {
edit_database::user_menu(&mut system.database)
},
SaveSystem, "Save the constructed components to disk as a system" => {
output::write_gromos(&system).map(|_| "Saved system to disk".to_string().into())
},
Quit, "Quit the program" => {
return Ok(());
}
];
}
/// Prompt the user to select a defined component from the `DataBase`, then create it.
fn create_component(system: &mut System) -> MenuResult {
let component = select_item(&system.database.component_defs, Some("Available components"))?
.clone();
match fill_component(component, system.database.path.as_ref()) {
Ok(filled) => {
system.components.push(filled);
Ok(Some("Added component to system".to_string()))
},
Err(err) => Err(err),
}
}
use std::path::PathBuf;
/// Ask the user for information about the selected component, then return the constructed object.
fn fill_component(component: ComponentEntry, database_path: Option<&PathBuf>)
-> Result<ComponentEntry> {
match component {
ComponentEntry::VolumeCuboid(mut conf) => {
let position = get_position_from_user(Some("0 0 0"))?;
let length = get_value_from_user::<f64>("Length ΔX (nm)")?;
let width = get_value_from_user::<f64>("Width ΔY (nm)")?;
let height = get_value_from_user::<f64>("Height ΔZ (nm)")?;
let fill_type = select_num_coords_or_density_with_default(conf.density)?;
conf.origin = position;
conf.size = Coord::new(length, width, height);
Ok(ComponentEntry::from(conf.fill(fill_type)))
},
ComponentEntry::VolumeCylinder(mut conf) => {
conf.origin = get_position_from_user(Some("0 0 0"))?;
conf.radius = get_value_from_user::<f64>("Radius (nm)")?;
conf.height = get_value_from_user::<f64>("Height (nm)")?;
let fill_type = select_num_coords_or_density_with_default(conf.density)?;
Ok(ComponentEntry::from(conf.fill(fill_type)))
},
ComponentEntry::SurfaceSheet(mut conf) => {
conf.origin = get_position_from_user(Some("0 0 0"))?;
conf.length = get_value_from_user::<f64>("Length ΔX (nm)")?;
conf.width = get_value_from_user::<f64>("Width ΔY (nm)")?;
match conf.lattice {
LatticeType::BlueNoise { ref mut number } => {
*number = get_value_from_user::<u64>("Number of residues")?;
},
_ => (),
}
Ok(
ComponentEntry::from(
conf.construct().map_err(|_| {
UIErrorKind::from("Could not construct sheet")
})?
).with_pbc()
)
},
ComponentEntry::SurfaceCuboid(mut conf) => {
conf.origin = get_position_from_user(Some("0 0 0"))?;
let length = get_value_from_user::<f64>("Length ΔX (nm)")?;
let width = get_value_from_user::<f64>("Width ΔY (nm)")?;
let height = get_value_from_user::<f64>("Height ΔZ (nm)")?;
conf.size = Coord::new(length, width, height);
Ok(ComponentEntry::from(conf.construct().map_err(|_| {
UIErrorKind::from("Could not construct cuboid surface")
})?
))
},
ComponentEntry::SurfaceCylinder(mut conf) => {
conf.origin = get_position_from_user(Some("0 0 0"))?;
conf.radius = get_value_from_user::<f64>("Radius (nm)")?;
conf.height = get_value_from_user::<f64>("Height (nm)")?;
Ok(ComponentEntry::from(conf.construct().map_err(|_|
UIErrorKind::from("Could not construct cylinder")
)?))
},
ComponentEntry::ConfigurationFile(conf) => {
let default_volume = conf.volume_type.clone();
let origin = get_position_from_user(Some("0 0 0"))?;
let to_volume = match default_volume {
ConfType::Cuboid { origin: _, size: default_size } => {
let (x, y, z) = default_size.to_tuple();
let size = get_coord_from_user(
"Size (x y z nm)", Some(&format!("{} {} {}", x, y, z)))?;
ConfType::Cuboid { origin, size }
},
ConfType::Cylinder { origin: _, radius, height, normal } => {
let radius = get_value_or_default_from_user::<f64>(
"Radius (nm)", &format!("{}", radius))?;
let height = get_value_or_default_from_user::<f64>(
"Height (nm)", &format!("{}", height))?;
let normal = select_direction(Some("Select normal"), Some(normal))?;
ConfType::Cylinder { origin, radius, height, normal }
},
};
// If the path is relative, it is relative to the database location.
// Construct the full path.
let path = if conf.path.is_absolute() {
conf.path
} else {
database_path
.and_then(|db_path| db_path.parent())
.map(|db_dir| PathBuf::from(db_dir))
// If the database has no path, it has to be relative to
// the current directory. Join with an empty path.
.unwrap_or(PathBuf::new())
.join(conf.path)
};
let mut new_conf = read_configuration(&path)?;
new_conf.description = conf.description;
new_conf.reconstruct(to_volume);
// Make sure that the origin is adjusted to that desired by the user.
let displayed_origin = new_conf.get_displayed_origin();
new_conf.translate_in_place(origin - displayed_origin);
Ok(ComponentEntry::from(new_conf))
},
}
}
pub fn read_configuration(path: &Path) -> Result<ReadConf> {
match path.to_str() {
Some(p) => eprint!("Reading configuration at '{}' ... ", p),
None => eprint!("Reading configuration with a non-utf8 path ... "),
}
let conf = ReadConf::from_gromos87(&path)
.map_err(|err| GrafenCliError::ReadConfError(format!("Failed! {}.", err)))?;
eprintln!("Done! Read {} atoms.", conf.num_atoms());
Ok(conf)
}
fn select_num_coords_or_density_with_default(default_density: Option<f64>) -> UIResult<FillType> {
match default_density {
Some(density) => {
let (commands, item_texts) = create_menu_items![
(YesOrNo::Yes, "Yes"),
(YesOrNo::No, "No")
];
eprintln!("Use default density for component ({})?", density);
let command = select_command(item_texts, commands)?;
match command {
YesOrNo::Yes => Ok(FillType::Density(density)),
YesOrNo::No => select_num_coords_or_density(),
}
},
None => {
select_num_coords_or_density()
},
}
}
fn select_num_coords_or_density() -> UIResult<FillType> {
create_menu![
@pre: { };
Density, "Use density" => {
let density = get_value_from_user::<f64>("Density (1/nm^3)")?;
if density > 0.0 {
return Ok(FillType::Density(density));
} else {
Err(GrafenCliError::ConstructError("Invalid density: it must be positive".into()))
}
},
NumCoords, "Use a specific number of residues" => {
let num_coords = get_value_from_user::<u64>("Number of residues")?;
return Ok(FillType::NumCoords(num_coords));
}
];
}
|
use super::VarResult;
use crate::ast::stat_expr_types::VarIndex;
use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType};
use crate::helper::err_msgs::*;
use crate::helper::str_replace;
use crate::helper::{
move_element, pine_ref_to_bool, pine_ref_to_f64, pine_ref_to_f64_series, pine_ref_to_i64,
require_param,
};
use crate::runtime::context::{downcast_ctx, Ctx};
use crate::runtime::InputSrc;
use crate::types::{
downcast_pf_ref, int2float, Arithmetic, Callable, CallableFactory, Evaluate, EvaluateVal,
Float, Int, ParamCollectCall, PineRef, RuntimeErr, Series, SeriesCall, NA,
};
use std::rc::Rc;
#[derive(Debug, Clone, PartialEq)]
struct AlmaVal;
impl<'a> SeriesCall<'a> for AlmaVal {
fn step(
&mut self,
_ctx: &mut dyn Ctx<'a>,
mut param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
move_tuplet!((series, length, offset, sigma) = param);
let series = require_param("series", pine_ref_to_f64_series(series))?;
let length = require_param("length", pine_ref_to_f64(length))?;
let offset = require_param("offset", pine_ref_to_f64(offset))?;
let sigma = require_param("sigma", pine_ref_to_f64(sigma))?;
if length < 1f64 {
return Err(RuntimeErr::InvalidParameters(str_replace(
GE_1,
vec![String::from("length")],
)));
}
// m = floor(offset * (windowsize - 1))
let m = (offset * (length - 1f64)).floor();
// s = windowsize / sigma
let s = length / sigma;
// norm = 0.0
// sum = 0.0
// for i = 0 to windowsize - 1
// weight = exp(-1 * pow(i - m, 2) / (2 * pow(s, 2)))
// norm := norm + weight
// sum := sum + series[windowsize - i - 1] * weight
// sum / norm
let mut norm = 0f64;
let mut sum = 0f64;
for i in 0..length as usize {
let weight = ((-1f64 * (i as f64 - m).powi(2)) / (2f64 * s.powi(2))).exp();
norm += weight;
match series.index_value(length as usize - i - 1)? {
Some(val) => {
sum += val * weight;
}
None => {
return Ok(PineRef::new_rc(Series::from(Float::from(None))));
}
}
}
Ok(PineRef::new(Series::from(Some(sum / norm))))
}
fn copy(&self) -> Box<dyn SeriesCall<'a> + 'a> {
Box::new(self.clone())
}
}
pub const VAR_NAME: &'static str = "alma";
pub fn declare_var<'a>() -> VarResult<'a> {
let value = PineRef::new(CallableFactory::new(|| {
Callable::new(
None,
Some(Box::new(ParamCollectCall::new_with_caller(Box::new(
AlmaVal,
)))),
)
}));
let func_type = FunctionTypes(vec![FunctionType::new((
vec![
("series", SyntaxType::float_series()),
("length", SyntaxType::float()),
("offset", SyntaxType::float()),
("sigma", SyntaxType::float()),
],
SyntaxType::float_series(),
))]);
let syntax_type = SyntaxType::Function(Rc::new(func_type));
VarResult::new(value, syntax_type, VAR_NAME)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ast::syntax_type::SyntaxType;
use crate::runtime::VarOperate;
use crate::runtime::{AnySeries, NoneCallback};
use crate::types::Series;
use crate::{LibInfo, PineParser, PineRunner};
// use crate::libs::{floor, exp, };
#[test]
fn alma_test() {
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::float_series())],
);
let src = "alma(close, 9, 0.85, 6)";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner
.run(
&vec![(
"close",
AnySeries::from_float_vec(vec![Some(10f64), Some(20f64)]),
)],
None,
)
.unwrap();
}
#[test]
fn alma_len_err_test() {
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::float_series())],
);
let src = "alma(close, -9, 0.85, 6)";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
assert!(runner
.run(
&vec![(
"close",
AnySeries::from_float_vec(vec![Some(10f64), Some(20f64)]),
)],
None,
)
.is_err());
}
}
|
use std::ops::{Deref, DerefMut};
use async_trait::async_trait;
use polars_core::frame::DataFrame;
use tokio::task::spawn_blocking;
use tonic::codec::CompressionEncoding;
use tonic::transport::Channel;
use tracing::{span, Instrument, Level};
use crate::api::click_house_client::ClickHouseClient;
pub use crate::api::{QueryInfo, Result as QueryResult};
use crate::arrow_integration::serialize_for_clickhouse;
pub use self::error::Error;
// for downstream dependency management
pub mod api;
mod arrow_integration;
mod error;
pub mod export;
pub const DEFAULT_MAX_MESSAGE_SIZE: usize = 100 * 1024 * 1024;
/// Client.
///
/// Pre-configures the underlying gprc service to use transport compression
#[derive(Clone, Debug)]
pub struct Client(ClickHouseClient<Channel>);
impl Client {
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
where
D: TryInto<tonic::transport::Endpoint>,
D::Error: Into<tonic::codegen::StdError>,
{
Self::connect_with_max_message_size(dst, DEFAULT_MAX_MESSAGE_SIZE).await
}
pub async fn connect_with_max_message_size<D>(
dst: D,
max_message_size: usize,
) -> Result<Self, tonic::transport::Error>
where
D: TryInto<tonic::transport::Endpoint>,
D::Error: Into<tonic::codegen::StdError>,
{
let channel = tonic::transport::Endpoint::new(dst)?.connect().await?;
let cc = ClickHouseClient::new(channel)
.max_decoding_message_size(max_message_size)
.max_encoding_message_size(max_message_size);
Ok(cc.into())
}
fn preconfigure_queryinfo(&self, query_info: &mut QueryInfo) {
query_info.transport_compression_type = "gzip".to_string()
}
}
impl From<ClickHouseClient<Channel>> for Client {
fn from(cc: ClickHouseClient<Channel>) -> Self {
let cc = cc
.accept_compressed(CompressionEncoding::Gzip)
.send_compressed(CompressionEncoding::Gzip);
Self(cc)
}
}
impl Deref for Client {
type Target = ClickHouseClient<Channel>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Client {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<Client> for ClickHouseClient<Channel> {
fn from(c: Client) -> Self {
c.0
}
}
#[async_trait]
pub trait ArrowInterface {
/// execute the query, check the response for errors and return as a rust `Result` type.
async fn execute_query_checked(&mut self, q: QueryInfo) -> Result<QueryResult, Error>;
async fn execute_into_dataframe(&mut self, mut q: QueryInfo) -> Result<DataFrame, Error>;
async fn insert_dataframe<S1, S2>(
&mut self,
database_name: S1,
table_name: S2,
mut df: DataFrame,
) -> Result<(), Error>
where
S1: AsRef<str> + Send,
S2: AsRef<str> + Send;
}
#[async_trait]
impl ArrowInterface for Client {
async fn execute_query_checked(&mut self, mut q: QueryInfo) -> Result<QueryResult, Error> {
let span = span!(
Level::DEBUG,
"Executing checked query",
query = q.query.as_str()
);
self.preconfigure_queryinfo(&mut q);
let response = self.execute_query(q).instrument(span).await?.into_inner();
match response.exception {
Some(ex) => Err(Error::ClickhouseException(ClickhouseException {
name: ex.name,
display_text: ex.display_text,
stack_trace: ex.stack_trace,
})),
None => Ok(response),
}
}
async fn execute_into_dataframe(&mut self, mut q: QueryInfo) -> Result<DataFrame, Error> {
q.output_format = "Arrow".to_string();
q.send_output_columns = true;
self.preconfigure_queryinfo(&mut q);
let response = self.execute_query_checked(q).await?;
spawn_blocking(move || response.try_into()).await?
}
async fn insert_dataframe<S1, S2>(
&mut self,
database_name: S1,
table_name: S2,
mut df: DataFrame,
) -> Result<(), Error>
where
S1: AsRef<str> + Send,
S2: AsRef<str> + Send,
{
let input_data = spawn_blocking(move || serialize_for_clickhouse(&mut df)).await??;
let mut q = QueryInfo {
query: format!("insert into {} FORMAT Arrow", table_name.as_ref()),
database: database_name.as_ref().to_string(),
input_data,
..Default::default()
};
self.preconfigure_queryinfo(&mut q);
self.execute_query_checked(q).await?;
Ok(())
}
}
#[derive(Debug)]
pub struct ClickhouseException {
pub name: String,
pub display_text: String,
pub stack_trace: String,
}
impl ToString for ClickhouseException {
fn to_string(&self) -> String {
format!("{}: {}", self.name, self.display_text)
}
}
|
#[doc = "Reader of register UR17"]
pub type R = crate::R<u32, super::UR17>;
#[doc = "Reader of field `IO_HSLV`"]
pub type IO_HSLV_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - I/O high speed / low voltage"]
#[inline(always)]
pub fn io_hslv(&self) -> IO_HSLV_R {
IO_HSLV_R::new((self.bits & 0x01) != 0)
}
}
|
//! To run this code, clone the rusty_engine repository and run the command:
//!
//! cargo run --release --example sfx
//! This is an example of playing a sound effect preset. For playing your own sound effect file,
//! please see the `sound` example.
use rusty_engine::prelude::*;
fn main() {
let mut game = Game::new();
let msg = game.add_text(
"msg",
"You can play sound effect presets that are included in the asset pack. For example:",
);
msg.translation.y = 50.0;
let msg2 = game.add_text(
"msg2",
"engine.audio_manager.play_sfx(SfxPreset::Jingle1, 1.0);",
);
msg2.translation.y = -50.0;
msg2.font = "font/FiraMono-Medium.ttf".to_string();
game.audio_manager.play_sfx(SfxPreset::Jingle1, 1.0);
game.run(());
}
|
use input_i_scanner::InputIScanner;
use mod_int::ModInt998244353;
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
macro_rules! scan {
(($($t: ty),+)) => {
($(scan!($t)),+)
};
($t: ty) => {
_i_i.scan::<$t>() as $t
};
(($($t: ty),+); $n: expr) => {
std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>()
};
($t: ty; $n: expr) => {
std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>()
};
}
type Mint = ModInt998244353;
let zero = Mint::new(0);
let one = Mint::new(1);
let (h, w, k) = scan!((u32, u32, usize));
let (x1, y1, x2, y2) = scan!((u32, u32, u32, u32));
let (mut xy, mut ay, mut xb, mut ab) = match (x1 == x2, y1 == y2) {
(true, true) => (one, zero, zero, zero),
(true, false) => (zero, zero, one, zero),
(false, true) => (zero, one, zero, zero),
(false, false) => (zero, zero, zero, one),
};
for _ in 0..k {
let (n_xy, n_ay, n_xb, n_ab) = {
(
ay + xb,
xy * (h - 1) + ay * (h - 2) + ab,
xy * (w - 1) + xb * (w - 2) + ab,
ay * (w - 1) + xb * (h - 1) + ab * (h - 2) + ab * (w - 2),
)
};
xy = n_xy;
ay = n_ay;
xb = n_xb;
ab = n_ab;
}
println!("{}", xy.val());
}
|
use measured_response::MeasuredResponse;
use arrayvec::ArrayVec;
const LAST_REQUEST_STORAGE_SIZE: usize = 10;
pub struct Summary {
pub total_requests: u64,
total_success: u64,
last_requests: ArrayVec<[MeasuredResponse; LAST_REQUEST_STORAGE_SIZE]>,
}
impl Default for Summary {
fn default() -> Summary {
Summary::new()
}
}
impl Summary {
pub fn new() -> Summary {
Summary {
total_requests: 0,
total_success: 0,
last_requests: ArrayVec::<[MeasuredResponse; LAST_REQUEST_STORAGE_SIZE]>::new(),
}
}
pub fn total_success(&self) -> u64 {
self.total_success
}
pub fn total_failure(&self) -> u64 {
self.total_requests - self.total_success
}
pub fn total_percentual_success(&self) -> f64 {
let scaled_value = self.total_success() as f64 * 100.0;
scaled_value / self.total_requests as f64
}
pub fn total_percentual_failure(&self) -> f64 {
let scaled_value = self.total_failure() as f64 * 100.0;
scaled_value / self.total_requests as f64
}
pub fn push(&mut self, response: MeasuredResponse) {
self.total_requests += 1;
if response.is_success() {
self.total_success += 1;
}
self.last_requests.insert(0, response);
}
pub fn last_requests(&self) -> &[MeasuredResponse] {
&self.last_requests
}
}
#[test]
fn it_should_increase_the_count_of_requests() {
let mut summary = Summary::new();
summary.push(MeasuredResponse::default());
assert_eq!(1, summary.total_requests);
summary.push(MeasuredResponse::default());
assert_eq!(2, summary.total_requests);
}
#[test]
fn it_should_calculate_the_failures_count() {
let mut summary = Summary::new();
summary.push(MeasuredResponse::default());
assert_eq!(0, summary.total_failure());
assert_eq!(0.0, summary.total_percentual_failure());
summary.push(MeasuredResponse::empty_failure());
assert_eq!(1, summary.total_failure());
assert_eq!(50.0, summary.total_percentual_failure());
}
#[test]
fn it_should_calculate_the_success_count() {
let mut summary = Summary::new();
summary.push(MeasuredResponse::default());
assert_eq!(1, summary.total_success());
assert_eq!(100.0, summary.total_percentual_success());
summary.push(MeasuredResponse::empty_failure());
assert_eq!(1, summary.total_success());
assert_eq!(50.0, summary.total_percentual_success());
}
#[test]
fn it_should_store_the_last_few_requests() {
let mut summary = Summary::new();
for _ in 0..10 {
summary.push(MeasuredResponse::default());
}
summary.push(MeasuredResponse::empty_failure());
assert_eq!(summary.last_requests(),
&[MeasuredResponse::empty_failure(),
MeasuredResponse::default(),
MeasuredResponse::default(),
MeasuredResponse::default(),
MeasuredResponse::default(),
MeasuredResponse::default(),
MeasuredResponse::default(),
MeasuredResponse::default(),
MeasuredResponse::default(),
MeasuredResponse::default()]);
}
|
use backend::x86::x86function::X86Function;
use backend::x86::x86instr::X86Instr;
use backend::x86::x86register::X86Register;
use backend::MachinePrg;
#[derive(Debug)]
pub struct X86Prg {
pub functions: Vec<X86Function>,
}
impl MachinePrg<X86Register, X86Instr, X86Function> for X86Prg {
fn functions(&self) -> &Vec<X86Function> {
&self.functions
}
fn functions_mut(&mut self) -> &mut Vec<X86Function> {
&mut self.functions
}
}
|
use super::core_namespace::*;
use super::super::error::*;
use super::super::symbol::*;
use super::super::notebook::*;
use super::super::script_type_description::*;
use gluon::vm::api::*;
use desync::Desync;
use futures::*;
use std::sync::*;
///
/// Provides notebook functionality for a Gluon script host
///
pub struct GluonScriptNotebook {
/// The namespace that this notebook represents
namespace: Arc<Desync<GluonScriptNamespace>>
}
impl GluonScriptNotebook {
///
/// Creates a new notebook from a core
///
pub (crate) fn new(namespace: Arc<Desync<GluonScriptNamespace>>) -> GluonScriptNotebook {
GluonScriptNotebook { namespace }
}
}
impl FloScriptNotebook for GluonScriptNotebook {
/// The type of the stream used to receive updates from this notebook
type UpdateStream = Box<dyn Stream<Item=NotebookUpdate, Error=()>+Send>;
/// Retrieves a stream of updates for this notebook
fn updates(&self) -> Self::UpdateStream {
unimplemented!()
}
/// Retrieves a notebook containing the symbols in the specified namespace
fn namespace(&self, symbol: FloScriptSymbol) -> Option<Self> {
self.namespace.sync(move |core| {
core.get_namespace(symbol)
})
.map(|namespace| GluonScriptNotebook::new(namespace))
}
/// Attaches an input stream to an input symbol. This will replace any existing input stream for that symbol if there is one.
fn attach_input<InputStream: 'static+Stream<Error=()>+Send>(&self, symbol: FloScriptSymbol, input: InputStream) -> FloScriptResult<()>
where InputStream::Item: ScriptType {
self.namespace.sync(move |core| {
core.attach_input(symbol, input)
})
}
/// Creates an output stream to receive the results from a script associated with the specified symbol
fn receive_output<OutputItem: 'static+ScriptType>(&self, symbol: FloScriptSymbol) -> FloScriptResult<Box<dyn Stream<Item=OutputItem, Error=()>+Send>>
where OutputItem: for<'vm, 'value> Getable<'vm, 'value> + VmType + Send + 'static,
<OutputItem as VmType>::Type: Sized {
self.namespace.sync(move |core| {
core.read_stream(symbol)
})
}
/// Receives the output stream for the specified symbol as a state stream (which will only return the most recently available symbol when polled)
fn receive_output_state<OutputItem: 'static+ScriptType>(&self, symbol: FloScriptSymbol) -> FloScriptResult<Box<dyn Stream<Item=OutputItem, Error=()>+Send>>
where OutputItem: for<'vm, 'value> Getable<'vm, 'value> + VmType + Send + 'static,
<OutputItem as VmType>::Type: Sized {
self.namespace.sync(move |core| {
core.read_state_stream(symbol)
})
}
}
|
use std::io;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::time::Duration;
fn handle_client(mut stream: TcpStream) {
io::copy(&mut stream.try_clone().unwrap(), &mut stream);
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:12345").unwrap();
for stream in listener.incoming() {
match stream {
Err(e) => println!("failed: {}", e),
Ok(stream) => {
thread::spawn(move || handle_client(stream));
}
}
}
}
|
// Copyright (c) 2020 DarkWeb Design
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// https://www.php.net/manual/en/ref.strings.php
/// Split a string by a string.
///
/// # Description
///
/// Returns an vec of strings, each of which is a substring of string formed by splitting it on
/// boundaries formed by the string delimiter.
///
/// # Parameters
///
/// **limit**
///
/// If limit is set and positive, the returned vec will contain a maximum of limit elements with the
/// last element containing the rest of string.
///
/// If the limit parameter is negative, all components except the last -limit are returned.
///
/// If the limit parameter is zero, then this is treated as 1.
///
/// # Examples
///
/// Example #1 explode() examples
///
/// ```
/// use phpify::string::explode;
///
/// let pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
/// let pieces = explode(" ", pizza, std::isize::MAX).unwrap();
///
/// assert_eq!(pieces, ["piece1", "piece2", "piece3", "piece4", "piece5", "piece6"]);
/// ```
///
/// ```
/// use phpify::string::explode;
///
/// let data = "foo:*:1023:1000::/home/foo:/bin/sh";
/// let elements = explode(":", data, std::isize::MAX).unwrap();
///
/// assert_eq!(elements[0], "foo".to_string());
/// assert_eq!(elements[1], "*".to_string());
/// ```
///
/// Example #2 explode() return examples
///
/// ```
/// use phpify::string::explode;
///
/// let input1 = "hello";
/// let input2 = "hello,there";
/// let input3 = ",";
///
/// assert_eq!(explode(",", input1, std::isize::MAX).unwrap(), ["hello"]);
/// assert_eq!(explode(",", input2, std::isize::MAX).unwrap(), ["hello", "there"]);
/// assert_eq!(explode(",", input3, std::isize::MAX).unwrap(), ["", ""]);
/// ```
///
/// Example #3 limit parameter examples
///
/// ```
/// use phpify::string::explode;
///
/// let str = "one|two|three|four";
///
/// assert_eq!(explode("|", str, 2).unwrap(), ["one", "two|three|four"]);
/// assert_eq!(explode("|", str, -1).unwrap(), ["one", "two", "three"]);
/// ```
pub fn explode<D, S>(delimiter: D, string: S, limit: isize) -> Option<Vec<String>>
where
D: AsRef<str>,
S: AsRef<str> {
let delimiter = delimiter.as_ref();
let string = string.as_ref();
if delimiter.is_empty() {
return None;
}
if limit == 0 || limit == 1 {
return Some(vec![string.to_string()]);
}
let vec: Vec<String> = string.split(delimiter).map(String::from).collect();
let vec_length = vec.len() as isize;
if limit > vec_length {
return Some(vec);
}
if limit > 0 {
let (left, right) = vec.split_at(limit as usize - 1);
let mut vec = left.to_vec();
vec.push(right.join(delimiter));
return Some(vec);
}
if limit < 0 {
if limit <= (0 - vec_length) {
return Some(vec![]);
}
let (left, _right) = vec.split_at((vec_length + limit) as usize);
let vec = left.to_vec();
return Some(vec);
}
Some(vec)
}
#[cfg(test)]
mod tests {
use crate::string::explode;
#[test]
fn test() {
assert_eq!(explode("|", "one|two|three", 3), Some(vec!["one".to_string(), "two".to_string(), "three".to_string()]));
assert_eq!(explode("|", "one|two|three", 1), Some(vec!["one|two|three".to_string()]));
assert_eq!(explode("|", "one|two|three", 2), Some(vec!["one".to_string(), "two|three".to_string()]));
assert_eq!(explode("|", "one|two|three", -1), Some(vec!["one".to_string(), "two".to_string()]));
assert_eq!(explode("|", "one|two|three", -3), Some(vec![]));
assert_eq!(explode(",", "one|two|three", 1), Some(vec!["one|two|three".to_string()]));
assert_eq!(explode("", "one|two|three", 3), None);
}
}
|
mod bonus;
pub use self::bonus::Bonus;
use std::sync::Arc;
use types::{ClapItem, Score};
/// [`BonusMatcher`] only tweaks the match score.
#[derive(Debug, Clone, Default)]
pub struct BonusMatcher {
bonuses: Vec<Bonus>,
}
impl BonusMatcher {
pub fn new(bonuses: Vec<Bonus>) -> Self {
Self { bonuses }
}
/// Returns the sum of bonus score.
pub fn calc_item_bonus(
&self,
item: &Arc<dyn ClapItem>,
base_score: Score,
base_indices: &[usize],
) -> Score {
self.bonuses
.iter()
.map(|b| b.item_bonus_score(item, base_score, base_indices))
.sum()
}
/// Returns the sum of bonus score.
pub fn calc_text_bonus(
&self,
bonus_text: &str,
base_score: Score,
base_indices: &[usize],
) -> Score {
self.bonuses
.iter()
.map(|b| b.text_bonus_score(bonus_text, base_score, base_indices))
.sum()
}
}
|
// Copyright (c) 2018-2022 Ministerio de Fomento
// Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC)
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Author(s): Rafael Villar Burke <pachi@ietcc.csic.es>,
// Daniel Jiménez González <dani@ietcc.csic.es>,
// Marta Sorribes Gil <msorribes@ietcc.csic.es>
/*!
Factores de paso (weighting factors)
====================================
Define el tipo Factors (lista de Factores + Metadatos).
*/
use std::collections::HashSet;
use std::fmt;
use std::str;
use serde::{Deserialize, Serialize};
use crate::{
error::{EpbdError, Result},
types::{Carrier, Dest, Factor, Meta, MetaVec, RenNrenCo2, Source, Step},
Components,
};
// --------------------------- Factors
/// Lista de factores de paso con sus metadatos
///
/// List of weighting factors bundled with its metadata
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Factors {
/// Weighting factors list
pub wmeta: Vec<Meta>,
/// Metadata
pub wdata: Vec<Factor>,
}
impl Factors {
/// Find weighting factor
///
/// * `fp_cr` - weighting factor list for a given energy carrier where search is done
/// * `source` - match this energy source (`RED`, `INSITU`, `COGEN`)
/// * `dest` - match this energy destination (use)
/// * `step` - match this calculation step
pub fn find(&self, cr: Carrier, source: Source, dest: Dest, step: Step) -> Result<RenNrenCo2> {
self.wdata
.iter()
.find(|fp| {
fp.carrier == cr && fp.source == source && fp.dest == dest && fp.step == step
})
.map(|fp| fp.factors())
.ok_or_else(|| {
EpbdError::MissingFactor(format!("'{}, {}, {}, {}'", cr, source, dest, step))
})
}
/// Actualiza o establece valores de un factor de paso
pub fn update_wfactor(
&mut self,
carrier: Carrier,
source: Source,
dest: Dest,
step: Step,
values: RenNrenCo2,
comment: &str,
) {
if let Some(factor) = self.wdata.iter_mut().find(|f| {
f.carrier == carrier && f.source == source && f.step == step && f.dest == dest
}) {
factor.set_values(&values);
} else {
self.wdata
.push(Factor::new(carrier, source, dest, step, values, comment));
};
}
/// Asegura que existe un factor de paso. Si ya existe no se modifica
pub fn ensure_wfactor(
&mut self,
carrier: Carrier,
source: Source,
dest: Dest,
step: Step,
values: RenNrenCo2,
comment: &str,
) {
if !self
.wdata
.iter()
.any(|f| f.carrier == carrier && f.source == source && f.step == step && f.dest == dest)
{
self.wdata
.push(Factor::new(carrier, source, dest, step, values, comment));
};
}
/// Actualiza los factores definibles por el usuario (cogen_to_grid, cogen_to_nepb, red1 y red2)
pub fn set_user_wfactors(mut self, user: UserWF<Option<RenNrenCo2>>) -> Self {
use Carrier::{RED1, RED2};
use Dest::SUMINISTRO;
use Source::RED;
use Step::A;
[
(RED1, RED, SUMINISTRO, A, user.red1, "Factor de usuario"),
(RED2, RED, SUMINISTRO, A, user.red2, "Factor de usuario"),
]
.iter()
.for_each(|(carrier, source, dest, step, uservalue, comment)| {
if let Some(value) = *uservalue {
self.update_wfactor(*carrier, *source, *dest, *step, value, comment)
}
});
self
}
/// Asegura consistencia de factores de paso definidos y deduce algunos de los que falten.
///
/// Realiza los siguientes pasos:
/// - asegura definición de factores de producción in situ
/// - asegura definición de factores desde la red para todos los vectores
/// - asegura que factor paso A para suministro de cogeneración es 0.0 (se considera en vector sourceal)
/// - asegura definición de factores a la red para vectores con exportación
/// - asegura que existe RED1 | RED2 en suministro
///
/// TODO: refactorizar moviendo algunos métodos a trait CteFactorsExt
pub fn normalize(mut self, defaults: &UserWF<RenNrenCo2>) -> Result<Self> {
use Carrier::*;
use Dest::*;
use Source::*;
use Step::*;
// Vectores existentes
let wf_carriers: HashSet<_> = self.wdata.iter().map(|f| f.carrier).collect();
// Asegura que existe EAMBIENTE, INSITU, SUMINISTRO, A, 1.0, 0.0
self.update_wfactor(
EAMBIENTE,
INSITU,
SUMINISTRO,
A,
RenNrenCo2::new(1.0, 0.0, 0.0),
"Recursos usados para obtener energía ambiente",
);
// Asegura que existe EAMBIENTE, RED, SUMINISTRO, A, 1.0, 0.0
self.update_wfactor(
EAMBIENTE,
RED,
SUMINISTRO,
A,
RenNrenCo2::new(1.0, 0.0, 0.0),
"Recursos usados para obtener energía ambiente (red ficticia)",
);
// Asegura que existe TERMOSOLAR, INSITU, SUMINISTRO, A, 1.0, 0.0
self.update_wfactor(
TERMOSOLAR,
INSITU,
SUMINISTRO,
A,
RenNrenCo2::new(1.0, 0.0, 0.0),
"Recursos usados para obtener energía solar térmica",
);
// Asegura que existe TERMOSOLAR, RED, SUMINISTRO, A, 1.0, 0.0
self.update_wfactor(
TERMOSOLAR,
RED,
SUMINISTRO,
A,
RenNrenCo2::new(1.0, 0.0, 0.0),
"Recursos usados para obtener energía solar térmica (red ficticia)",
);
// Asegura que existe ELECTRICIDAD, INSITU, SUMINISTRO, A, 1.0, 0.0 si hay ELECTRICIDAD
if wf_carriers.contains(&ELECTRICIDAD) {
self.update_wfactor(
ELECTRICIDAD,
INSITU,
SUMINISTRO,
A,
RenNrenCo2::new(1.0, 0.0, 0.0),
"Recursos usados para generar electricidad in situ",
);
}
// Asegura definición de factores de red para todos los vectores energéticos
let has_grid_factors_for_all_carriers = wf_carriers.iter().all(|&c| {
self.wdata.iter().any(|f| {
f.carrier == c
&& f.source == Source::RED
&& f.dest == Dest::SUMINISTRO
&& f.step == Step::A
})
});
if !has_grid_factors_for_all_carriers {
return Err(EpbdError::MissingFactor(
"Factores de red VECTOR, INSITU, SUMINISTRO, A, fren?, fnren?".into(),
));
}
// // En paso A, el factor SUMINISTRO de cogeneración es 0.0, 0.0 ya que el impacto se tiene en cuenta en el suministro del vector de generación
// self.update_wfactor(
// ELECTRICIDAD,
// COGEN,
// SUMINISTRO,
// A,
// RenNrenCo2::new(0.0, 0.0, 0.0),
// "Factor de paso generado (el impacto de la cogeneración se tiene en cuenta en el vector de suministro)",
// );
// Asegura que todos los vectores con exportación tienen factores de paso a la red y a usos no EPB
let exp_carriers = [
(Carrier::ELECTRICIDAD, Source::INSITU),
// (Carrier::ELECTRICIDAD, Source::COGEN),
(Carrier::EAMBIENTE, Source::INSITU),
(Carrier::TERMOSOLAR, Source::INSITU),
];
for (c, s) in &exp_carriers {
// Asegura que existe VECTOR, SRC, A_RED | A_NEPB, A, ren, nren
let fp_a_input = self
.wdata
.iter()
.find(|f| {
f.carrier == *c
&& f.source == *s
&& f.step == Step::A
&& f.dest == Dest::SUMINISTRO
})
.map(|f| f.factors());
if let Some(factors) = fp_a_input {
// VECTOR, SRC, A_RED, A, ren, nren === VECTOR, SRC, SUMINISTRO, A, ren, nren
self.ensure_wfactor(
*c,
*s,
A_RED,
A,
factors,
"Recursos usados para producir la energía exportada a la red",
);
// VECTOR, SRC, A_NEPB, A, ren, nren == VECTOR, SRC, SUMINISTRO, A, ren, nren
self.ensure_wfactor(
*c,
*s,
A_NEPB,
A,
factors,
"Recursos usados para producir la energía exportada a usos no EPB",
);
}
// Asegura que existe VECTOR, SRC, A_RED | A_NEPB, B, ren, nren
let fp_a_red_input = self
.wdata
.iter()
.find(|f| {
f.carrier == *c
&& f.source == Source::RED
&& f.dest == Dest::SUMINISTRO
&& f.step == Step::A
})
.map(|f| f.factors());
if let Some(factors) = fp_a_red_input {
// VECTOR, SRC, A_RED, B, ren, nren == VECTOR, RED, SUMINISTRO, A, ren, nren
self.ensure_wfactor(
*c,
*s,
A_RED,
B,
factors,
"Recursos ahorrados a la red por la energía producida in situ y exportada a la red",
);
// VECTOR, SRC, A_NEPB, B, ren, nren == VECTOR, RED, SUMINISTRO, A, ren, nren
self.ensure_wfactor(
*c,
*s,
A_NEPB,
B,
factors,
"Recursos ahorrados a la red por la energía producida in situ y exportada a usos no EPB",
);
} else {
return Err(EpbdError::MissingFactor(format!("{}, SUMINISTRO, A", c)));
}
}
// Asegura que existe RED1 | RED2, RED, SUMINISTRO, A, ren, nren
self.ensure_wfactor(
RED1,
RED,
SUMINISTRO,
A,
defaults.red1,
"Recursos usados para suministrar energía de la red de distrito 1 (definible por el usuario)",
);
self.ensure_wfactor(
RED2,
RED,
SUMINISTRO,
A,
defaults.red2,
"Recursos usados para suministrar energía de la red de distrito 2 (definible por el usuario)",
);
Ok(self)
}
/// Elimina factores de paso no usados en los datos de vectores energéticos.
///
/// Elimina los factores:
/// - de vectores que no aparecen en los datos
/// - de cogeneración si no hay cogeneración
/// - para exportación a usos no EPB si no se aparecen en los datos
/// - de electricidad in situ si no aparece una producción de ese tipo
pub fn strip(mut self, components: &Components) -> Self {
let wf_carriers = components.available_carriers();
// Mantenemos factores para todos los vectores usados
self.wdata.retain(|f| wf_carriers.contains(&f.carrier));
// Mantenemos factores para cogeneración sólo si hay cogeneración
let has_cogen = components.data.iter().any(|c| c.is_cogen_pr());
self.wdata
.retain(|f| f.source != Source::COGEN || has_cogen);
// Mantenemos factores a usos no EPB si hay uso de no EPB
let has_nepb = components.data.iter().any(|c| c.is_nepb_use());
self.wdata.retain(|f| f.dest != Dest::A_NEPB || has_nepb);
// Mantenemos factores de electricidad in situ si no hay producción de ese tipo
let has_elec_onsite = components
.data
.iter()
.any(|c| c.is_electricity() && c.is_onsite_pr());
self.wdata.retain(|f| {
f.carrier != Carrier::ELECTRICIDAD || f.source != Source::INSITU || has_elec_onsite
});
self
}
/// Convierte factores de paso con perímetro "distant" a factores de paso "nearby".
///
/// Los elementos que tiene origen en la RED (!= INSITU, != COGEN)
/// y no están en la lista nearby_list cambian sus factores de paso
/// de forma que ren' = 0 y nren' = ren + nren.
/// **ATENCIÓN**: ¡¡La producción eléctrica de la cogeneración entra con (factores ren:0, nren:0)!!
pub fn to_nearby(&self, nearby_list: &[Carrier]) -> Self {
let wmeta = self.wmeta.clone();
let mut wdata: Vec<Factor> = Vec::new();
for f in self.wdata.iter().cloned() {
if f.source == Source::INSITU
|| f.source == Source::COGEN
|| nearby_list.contains(&f.carrier)
{
wdata.push(f)
} else {
wdata.push(Factor::new(
f.carrier,
f.source,
f.dest,
f.step,
RenNrenCo2::new(0.0, f.ren + f.nren, f.co2), // ¿Esto es lo que tiene más sentido?
format!("Perímetro nearby: {}", f.comment),
))
}
}
let mut factors = Factors { wmeta, wdata };
factors.set_meta("CTE_PERIMETRO", "NEARBY");
factors
}
/// Incorpora factores de exportación de la electricidad cogenerada
///
/// Devuelve a definición de los factores de exportación a NEPB y RED (paso A y paso B),
/// para la electricidad cogenerada, que pueden ser agregados directamente a Factors.wdata
///
/// También devuelve las estructuras de datos de los factores de exportación paso A
/// para el perímetro distante y próximo, para facilitar el cálculo de RER_nrb
#[allow(non_snake_case)]
pub(crate) fn add_cgn_factors(&mut self, components: &Components) -> Result<()> {
let fP_exp_el_cgn_A = match self.compute_cgn_exp_fP_A(components, false)? {
Some(fP) => fP,
_ => return Ok(()),
};
// Factores derivados para el paso A (recursos usados)
let factor_input_A = Factor::new(
Carrier::ELECTRICIDAD,
Source::COGEN,
Dest::SUMINISTRO,
Step::A,
fP_exp_el_cgn_A,
"Recursos usados para el suministrar electricidad cogenerada (calculado)",
);
// Factores derivados para el paso A (recursos usados)
let factor_to_nepb_A = Factor::new(
Carrier::ELECTRICIDAD,
Source::COGEN,
Dest::A_NEPB,
Step::A,
fP_exp_el_cgn_A,
"Recursos usados para la exportación a usos no EPB (calculado)",
);
let factor_to_grid_A = Factor::new(
Carrier::ELECTRICIDAD,
Source::COGEN,
Dest::A_RED,
Step::A,
fP_exp_el_cgn_A,
"Recursos usados para la exportación a la red (calculado)",
);
// Factores derivados para el paso B (recursos ahorrados a la red, iguales al paso A de red)
let fP_el_grid_A = self.find(
Carrier::ELECTRICIDAD,
Source::RED,
Dest::SUMINISTRO,
Step::A,
)?;
let factor_to_nepb_B = Factor::new(
Carrier::ELECTRICIDAD,
Source::COGEN,
Dest::A_NEPB,
Step::B,
fP_el_grid_A,
"Recursos ahorrados a la red por la exportación a usos no EPB (calculado)",
);
let factor_to_grid_B = Factor::new(
Carrier::ELECTRICIDAD,
Source::COGEN,
Dest::A_RED,
Step::B,
fP_el_grid_A,
"Recursos ahorrados a la red por la exportación a la red (calculado)",
);
// Incorporamos los factores a wfactors
self.wdata.push(factor_input_A);
self.wdata.push(factor_to_nepb_A);
self.wdata.push(factor_to_grid_A);
self.wdata.push(factor_to_nepb_B);
self.wdata.push(factor_to_grid_B);
Ok(())
}
#[allow(non_snake_case)]
pub(crate) fn compute_cgn_exp_fP_A(
&self,
components: &Components,
only_nearby: bool,
) -> Result<Option<RenNrenCo2>> {
// Si hay producción eléctrica
// Calcula f_exp_pr_el_A_chp_t = suma (E_in_t * f_in_t) / pr_el_chp_t
use crate::types::Energy;
use crate::vecops::vecvecsum;
use std::collections::HashMap;
let mut prod = Vec::<f32>::new();
let mut used = HashMap::<Carrier, Vec<f32>>::new();
for c in &components.data {
match c {
Energy::Used(e) if c.is_cogen_use() => {
used.entry(e.carrier)
.and_modify(|item| *item = vecvecsum(item, &e.values))
.or_insert_with(|| e.values.clone());
}
Energy::Prod(e) if c.is_cogen_pr() => {
prod = if prod.is_empty() {
e.values.clone()
} else {
vecvecsum(&prod, &e.values)
}
}
_ => continue,
}
}
if prod.is_empty() {
return Ok(None);
}
if used.is_empty() {
return Err(EpbdError::WrongInput(
"No se han definido los consumos para la cogeneración".into(),
));
};
let mut fP_exp_el_cgn_A = RenNrenCo2::default();
for (carrier, used_t) in used {
if only_nearby && !carrier.is_nearby() {
continue;
}
let fP_A_cr = self.find(carrier, Source::RED, Dest::SUMINISTRO, Step::A)?;
let used_prod_ratio_sum = used_t
.iter()
.zip(prod.iter())
.map(|(us, pr)| if *pr > 0.0 { us / pr } else { 0.0 })
.sum::<f32>();
fP_exp_el_cgn_A += fP_A_cr * used_prod_ratio_sum;
}
Ok(Some(fP_exp_el_cgn_A))
}
}
impl MetaVec for Factors {
fn get_metavec(&self) -> &Vec<Meta> {
&self.wmeta
}
fn get_mut_metavec(&mut self) -> &mut Vec<Meta> {
&mut self.wmeta
}
}
impl fmt::Display for Factors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let metalines = self
.wmeta
.iter()
.map(|v| format!("{}", v))
.collect::<Vec<_>>()
.join("\n");
let datalines = self
.wdata
.iter()
.map(|v| format!("{}", v))
.collect::<Vec<_>>()
.join("\n");
write!(f, "{}\n{}", metalines, datalines)
}
}
impl str::FromStr for Factors {
type Err = EpbdError;
fn from_str(s: &str) -> std::result::Result<Factors, Self::Err> {
let lines: Vec<&str> = s.lines().map(str::trim).collect();
let metalines = lines
.iter()
.filter(|l| l.starts_with("#META") || l.starts_with("#CTE_"));
let datalines = lines
.iter()
.filter(|l| !(l.starts_with('#') || l.starts_with("vector,") || l.is_empty()));
let wmeta = metalines
.map(|e| e.parse())
.collect::<Result<Vec<Meta>>>()?;
let wdata = datalines
.map(|e| e.parse())
.collect::<Result<Vec<Factor>>>()?;
Ok(Factors { wmeta, wdata })
}
}
/// Estructura para definir valores por defecto y valores de usuario
#[derive(Debug, Copy, Clone)]
pub struct UserWF<T = RenNrenCo2> {
/// Factores de paso de redes de distrito 1.
/// RED1, RED, SUMINISTRO, A, ren, nren
pub red1: T,
/// Factores de paso de redes de distrito 2.
/// RED2, RED, SUMINISTRO, A, ren, nren
pub red2: T,
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn tfactors() {
let tfactors1 = "#META CTE_FUENTE: RITE2014
#META CTE_FUENTE_COMENTARIO: Factores de paso del documento reconocido del IDAE de 20/07/2014
ELECTRICIDAD, RED, SUMINISTRO, A, 0.414, 1.954, 0.331 # Recursos usados para suministrar electricidad (peninsular) desde la red
ELECTRICIDAD, INSITU, SUMINISTRO, A, 1.000, 0.000, 0.000 # Recursos usados para producir electricidad in situ";
// roundtrip building from/to string
assert_eq!(tfactors1.parse::<Factors>().unwrap().to_string(), tfactors1);
}
#[test]
fn set_user_factors() {
let tfactors1 = "#META CTE_FUENTE: RITE2014
#META CTE_FUENTE_COMENTARIO: Factores de paso del documento reconocido del IDAE de 20/07/2014
ELECTRICIDAD, RED, SUMINISTRO, A, 0.414, 1.954, 0.331 # Recursos usados para suministrar electricidad (peninsular) desde la red
ELECTRICIDAD, INSITU, SUMINISTRO, A, 1.000, 0.000, 0.000 # Recursos usados para producir electricidad in situ
".parse::<Factors>().unwrap();
let tfactorsres = "#META CTE_FUENTE: RITE2014
#META CTE_FUENTE_COMENTARIO: Factores de paso del documento reconocido del IDAE de 20/07/2014
ELECTRICIDAD, RED, SUMINISTRO, A, 0.414, 1.954, 0.331 # Recursos usados para suministrar electricidad (peninsular) desde la red
ELECTRICIDAD, INSITU, SUMINISTRO, A, 1.000, 0.000, 0.000 # Recursos usados para producir electricidad in situ
RED1, RED, SUMINISTRO, A, 0.100, 0.125, 0.500 # Factor de usuario
RED2, RED, SUMINISTRO, A, 0.125, 0.100, 0.500 # Factor de usuario";
assert_eq!(
tfactors1
.set_user_wfactors(UserWF {
red1: Some(RenNrenCo2::new(0.1, 0.125, 0.5)),
red2: Some(RenNrenCo2::new(0.125, 0.1, 0.5)),
})
.to_string(),
tfactorsres
);
}
#[test]
fn normalize_and_strip() {
let tfactors = "#META CTE_FUENTE: RITE2014
#META CTE_FUENTE_COMENTARIO: Factores de paso del documento reconocido del IDAE de 20/07/2014
ELECTRICIDAD, RED, SUMINISTRO, A, 0.414, 1.954, 0.331 # Recursos usados para suministrar electricidad (peninsular) desde la red
ELECTRICIDAD, INSITU, SUMINISTRO, A, 1.000, 0.000, 0.000 # Recursos usados para producir electricidad in situ
".parse::<Factors>().unwrap();
let tfactors_normalized_str = "#META CTE_FUENTE: RITE2014
#META CTE_FUENTE_COMENTARIO: Factores de paso del documento reconocido del IDAE de 20/07/2014
ELECTRICIDAD, RED, SUMINISTRO, A, 0.414, 1.954, 0.331 # Recursos usados para suministrar electricidad (peninsular) desde la red
ELECTRICIDAD, INSITU, SUMINISTRO, A, 1.000, 0.000, 0.000 # Recursos usados para producir electricidad in situ
EAMBIENTE, INSITU, SUMINISTRO, A, 1.000, 0.000, 0.000 # Recursos usados para obtener energía ambiente
EAMBIENTE, RED, SUMINISTRO, A, 1.000, 0.000, 0.000 # Recursos usados para obtener energía ambiente (red ficticia)
TERMOSOLAR, INSITU, SUMINISTRO, A, 1.000, 0.000, 0.000 # Recursos usados para obtener energía solar térmica
TERMOSOLAR, RED, SUMINISTRO, A, 1.000, 0.000, 0.000 # Recursos usados para obtener energía solar térmica (red ficticia)
ELECTRICIDAD, INSITU, A_RED, A, 1.000, 0.000, 0.000 # Recursos usados para producir la energía exportada a la red
ELECTRICIDAD, INSITU, A_NEPB, A, 1.000, 0.000, 0.000 # Recursos usados para producir la energía exportada a usos no EPB
ELECTRICIDAD, INSITU, A_RED, B, 0.414, 1.954, 0.331 # Recursos ahorrados a la red por la energía producida in situ y exportada a la red
ELECTRICIDAD, INSITU, A_NEPB, B, 0.414, 1.954, 0.331 # Recursos ahorrados a la red por la energía producida in situ y exportada a usos no EPB
EAMBIENTE, INSITU, A_RED, A, 1.000, 0.000, 0.000 # Recursos usados para producir la energía exportada a la red
EAMBIENTE, INSITU, A_NEPB, A, 1.000, 0.000, 0.000 # Recursos usados para producir la energía exportada a usos no EPB
EAMBIENTE, INSITU, A_RED, B, 1.000, 0.000, 0.000 # Recursos ahorrados a la red por la energía producida in situ y exportada a la red
EAMBIENTE, INSITU, A_NEPB, B, 1.000, 0.000, 0.000 # Recursos ahorrados a la red por la energía producida in situ y exportada a usos no EPB
TERMOSOLAR, INSITU, A_RED, A, 1.000, 0.000, 0.000 # Recursos usados para producir la energía exportada a la red
TERMOSOLAR, INSITU, A_NEPB, A, 1.000, 0.000, 0.000 # Recursos usados para producir la energía exportada a usos no EPB
TERMOSOLAR, INSITU, A_RED, B, 1.000, 0.000, 0.000 # Recursos ahorrados a la red por la energía producida in situ y exportada a la red
TERMOSOLAR, INSITU, A_NEPB, B, 1.000, 0.000, 0.000 # Recursos ahorrados a la red por la energía producida in situ y exportada a usos no EPB
RED1, RED, SUMINISTRO, A, 0.000, 1.300, 0.300 # Recursos usados para suministrar energía de la red de distrito 1 (definible por el usuario)
RED2, RED, SUMINISTRO, A, 0.000, 1.300, 0.300 # Recursos usados para suministrar energía de la red de distrito 2 (definible por el usuario)";
let tcomps = "CONSUMO, ILU, ELECTRICIDAD, 1 # Solo consume electricidad de red"
.parse::<Components>()
.unwrap();
let tfactors_normalized_stripped_str = "#META CTE_FUENTE: RITE2014
#META CTE_FUENTE_COMENTARIO: Factores de paso del documento reconocido del IDAE de 20/07/2014
ELECTRICIDAD, RED, SUMINISTRO, A, 0.414, 1.954, 0.331 # Recursos usados para suministrar electricidad (peninsular) desde la red";
let tfactors_normalized = tfactors
.normalize(&UserWF {
red1: RenNrenCo2 {
ren: 0.0,
nren: 1.3,
co2: 0.3,
},
red2: RenNrenCo2 {
ren: 0.0,
nren: 1.3,
co2: 0.3,
},
})
.unwrap();
let tfactors_normalized_stripped = tfactors_normalized.clone().strip(&tcomps);
assert_eq!(tfactors_normalized.to_string(), tfactors_normalized_str);
assert_eq!(
tfactors_normalized_stripped.to_string(),
tfactors_normalized_stripped_str
);
}
}
|
//! Crds Gossip Pull overlay
//! This module implements the anti-entropy protocol for the network.
//!
//! The basic strategy is as follows:
//! 1. Construct a bloom filter of the local data set
//! 2. Randomly ask a node on the network for data that is not contained in the bloom filter.
//!
//! Bloom filters have a false positive rate. Each requests uses a different bloom filter
//! with random hash functions. So each subsequent request will have a different distribution
//! of false positives.
use crate::connectionInfo::ContactInfo;
use crate::connectionInfoTable::Crds;
use crate::gossip::{get_stake, get_weight, CRDS_GOSSIP_BLOOM_SIZE};
use crate::gossipErrorType::CrdsGossipError;
use crate::propagationValue::{CrdsValue, CrdsValueLabel};
use crate::packet::BLOB_DATA_SIZE;
use bincode::serialized_size;
use hashbrown::HashMap;
use rand;
use rand::distributions::{Distribution, WeightedIndex};
use morgan_runtime::bloom::Bloom;
use morgan_interface::hash::Hash;
use morgan_interface::pubkey::Pubkey;
use std::cmp;
use std::collections::VecDeque;
pub const CRDS_GOSSIP_PULL_CRDS_TIMEOUT_MS: u64 = 15000;
#[derive(Clone)]
pub struct CrdsGossipPull {
/// timestamp of last request
pub pull_request_time: HashMap<Pubkey, u64>,
/// hash and insert time
purged_values: VecDeque<(Hash, u64)>,
/// max bytes per message
pub max_bytes: usize,
pub crds_timeout: u64,
}
impl Default for CrdsGossipPull {
fn default() -> Self {
Self {
purged_values: VecDeque::new(),
pull_request_time: HashMap::new(),
max_bytes: BLOB_DATA_SIZE,
crds_timeout: CRDS_GOSSIP_PULL_CRDS_TIMEOUT_MS,
}
}
}
impl CrdsGossipPull {
/// generate a random request
pub fn new_pull_request(
&self,
crds: &Crds,
self_id: &Pubkey,
now: u64,
stakes: &HashMap<Pubkey, u64>,
) -> Result<(Pubkey, Bloom<Hash>, CrdsValue), CrdsGossipError> {
let options = self.pull_options(crds, &self_id, now, stakes);
if options.is_empty() {
return Err(CrdsGossipError::NoPeers);
}
let filter = self.build_crds_filter(crds);
let index = WeightedIndex::new(options.iter().map(|weighted| weighted.0)).unwrap();
let random = index.sample(&mut rand::thread_rng());
let self_info = crds
.lookup(&CrdsValueLabel::ContactInfo(*self_id))
.unwrap_or_else(|| panic!("self_id invalid {}", self_id));
Ok((options[random].1.id, filter, self_info.clone()))
}
fn pull_options<'a>(
&self,
crds: &'a Crds,
self_id: &Pubkey,
now: u64,
stakes: &HashMap<Pubkey, u64>,
) -> Vec<(f32, &'a ContactInfo)> {
crds.table
.values()
.filter_map(|v| v.value.contact_info())
.filter(|v| v.id != *self_id && ContactInfo::is_valid_address(&v.gossip))
.map(|item| {
let max_weight = f32::from(u16::max_value()) - 1.0;
let req_time: u64 = *self.pull_request_time.get(&item.id).unwrap_or(&0);
let since = ((now - req_time) / 1024) as u32;
let stake = get_stake(&item.id, stakes);
let weight = get_weight(max_weight, since, stake);
(weight, item)
})
.collect()
}
/// time when a request to `from` was initiated
/// This is used for weighted random selection during `new_pull_request`
/// It's important to use the local nodes request creation time as the weight
/// instead of the response received time otherwise failed nodes will increase their weight.
pub fn mark_pull_request_creation_time(&mut self, from: &Pubkey, now: u64) {
self.pull_request_time.insert(*from, now);
}
/// Store an old hash in the purged values set
pub fn record_old_hash(&mut self, hash: Hash, timestamp: u64) {
self.purged_values.push_back((hash, timestamp))
}
/// process a pull request and create a response
pub fn process_pull_request(
&mut self,
crds: &mut Crds,
caller: CrdsValue,
mut filter: Bloom<Hash>,
now: u64,
) -> Vec<CrdsValue> {
let rv = self.filter_crds_values(crds, &mut filter);
let key = caller.label().pubkey();
let old = crds.insert(caller, now);
if let Some(val) = old.ok().and_then(|opt| opt) {
self.purged_values
.push_back((val.value_hash, val.local_timestamp))
}
crds.update_record_timestamp(&key, now);
rv
}
/// process a pull response
pub fn process_pull_response(
&mut self,
crds: &mut Crds,
from: &Pubkey,
response: Vec<CrdsValue>,
now: u64,
) -> usize {
let mut failed = 0;
for r in response {
let owner = r.label().pubkey();
let old = crds.insert(r, now);
failed += old.is_err() as usize;
old.ok().map(|opt| {
crds.update_record_timestamp(&owner, now);
opt.map(|val| {
self.purged_values
.push_back((val.value_hash, val.local_timestamp))
})
});
}
crds.update_record_timestamp(from, now);
failed
}
/// build a filter of the current crds table
pub fn build_crds_filter(&self, crds: &Crds) -> Bloom<Hash> {
let num = cmp::max(
CRDS_GOSSIP_BLOOM_SIZE,
crds.table.values().count() + self.purged_values.len(),
);
let mut bloom = Bloom::random(num, 0.1, 4 * 1024 * 8 - 1);
for v in crds.table.values() {
bloom.add(&v.value_hash);
}
for (value_hash, _insert_timestamp) in &self.purged_values {
bloom.add(value_hash);
}
bloom
}
/// filter values that fail the bloom filter up to max_bytes
fn filter_crds_values(&self, crds: &Crds, filter: &mut Bloom<Hash>) -> Vec<CrdsValue> {
let mut max_bytes = self.max_bytes as isize;
let mut ret = vec![];
for v in crds.table.values() {
if filter.contains(&v.value_hash) {
continue;
}
max_bytes -= serialized_size(&v.value).unwrap() as isize;
if max_bytes < 0 {
break;
}
ret.push(v.value.clone());
}
ret
}
/// Purge values from the crds that are older then `active_timeout`
/// The value_hash of an active item is put into self.purged_values queue
pub fn purge_active(&mut self, crds: &mut Crds, self_id: &Pubkey, min_ts: u64) {
let old = crds.find_old_labels(min_ts);
let mut purged: VecDeque<_> = old
.iter()
.filter(|label| label.pubkey() != *self_id)
.filter_map(|label| {
let rv = crds
.lookup_versioned(label)
.map(|val| (val.value_hash, val.local_timestamp));
crds.remove(label);
rv
})
.collect();
self.purged_values.append(&mut purged);
}
/// Purge values from the `self.purged_values` queue that are older then purge_timeout
pub fn purge_purged(&mut self, min_ts: u64) {
let cnt = self
.purged_values
.iter()
.take_while(|v| v.1 < min_ts)
.count();
self.purged_values.drain(..cnt);
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::connectionInfo::ContactInfo;
#[test]
fn test_new_pull_with_stakes() {
let mut crds = Crds::default();
let mut stakes = HashMap::new();
let node = CrdsGossipPull::default();
let me = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
crds.insert(me.clone(), 0).unwrap();
for i in 1..=30 {
let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
let id = entry.label().pubkey();
crds.insert(entry.clone(), 0).unwrap();
stakes.insert(id, i * 100);
}
let now = 1024;
let mut options = node.pull_options(&crds, &me.label().pubkey(), now, &stakes);
assert!(!options.is_empty());
options.sort_by(|(weight_l, _), (weight_r, _)| weight_r.partial_cmp(weight_l).unwrap());
// check that the highest stake holder is also the heaviest weighted.
assert_eq!(
*stakes.get(&options.get(0).unwrap().1.id).unwrap(),
3000_u64
);
}
#[test]
fn test_new_pull_request() {
let mut crds = Crds::default();
let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
let id = entry.label().pubkey();
let node = CrdsGossipPull::default();
assert_eq!(
node.new_pull_request(&crds, &id, 0, &HashMap::new()),
Err(CrdsGossipError::NoPeers)
);
crds.insert(entry.clone(), 0).unwrap();
assert_eq!(
node.new_pull_request(&crds, &id, 0, &HashMap::new()),
Err(CrdsGossipError::NoPeers)
);
let new = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
crds.insert(new.clone(), 0).unwrap();
let req = node.new_pull_request(&crds, &id, 0, &HashMap::new());
let (to, _, self_info) = req.unwrap();
assert_eq!(to, new.label().pubkey());
assert_eq!(self_info, entry);
}
#[test]
fn test_new_mark_creation_time() {
let mut crds = Crds::default();
let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
let node_pubkey = entry.label().pubkey();
let mut node = CrdsGossipPull::default();
crds.insert(entry.clone(), 0).unwrap();
let old = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
crds.insert(old.clone(), 0).unwrap();
let new = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
crds.insert(new.clone(), 0).unwrap();
// set request creation time to max_value
node.mark_pull_request_creation_time(&new.label().pubkey(), u64::max_value());
// odds of getting the other request should be 1 in u64::max_value()
for _ in 0..10 {
let req = node.new_pull_request(&crds, &node_pubkey, u64::max_value(), &HashMap::new());
let (to, _, self_info) = req.unwrap();
assert_eq!(to, old.label().pubkey());
assert_eq!(self_info, entry);
}
}
#[test]
fn test_process_pull_request() {
let mut node_crds = Crds::default();
let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
let node_pubkey = entry.label().pubkey();
let node = CrdsGossipPull::default();
node_crds.insert(entry.clone(), 0).unwrap();
let new = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
node_crds.insert(new.clone(), 0).unwrap();
let req = node.new_pull_request(&node_crds, &node_pubkey, 0, &HashMap::new());
let mut dest_crds = Crds::default();
let mut dest = CrdsGossipPull::default();
let (_, filter, caller) = req.unwrap();
let rsp = dest.process_pull_request(&mut dest_crds, caller.clone(), filter, 1);
assert!(rsp.is_empty());
assert!(dest_crds.lookup(&caller.label()).is_some());
assert_eq!(
dest_crds
.lookup_versioned(&caller.label())
.unwrap()
.insert_timestamp,
1
);
assert_eq!(
dest_crds
.lookup_versioned(&caller.label())
.unwrap()
.local_timestamp,
1
);
}
#[test]
fn test_process_pull_request_response() {
let mut node_crds = Crds::default();
let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
let node_pubkey = entry.label().pubkey();
let mut node = CrdsGossipPull::default();
node_crds.insert(entry.clone(), 0).unwrap();
let new = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
node_crds.insert(new.clone(), 0).unwrap();
let mut dest = CrdsGossipPull::default();
let mut dest_crds = Crds::default();
let new_id = Pubkey::new_rand();
let new = CrdsValue::ContactInfo(ContactInfo::new_localhost(&new_id, 1));
dest_crds.insert(new.clone(), 0).unwrap();
// node contains a key from the dest node, but at an older local timestamp
let same_key = CrdsValue::ContactInfo(ContactInfo::new_localhost(&new_id, 0));
assert_eq!(same_key.label(), new.label());
assert!(same_key.wallclock() < new.wallclock());
node_crds.insert(same_key.clone(), 0).unwrap();
assert_eq!(
node_crds
.lookup_versioned(&same_key.label())
.unwrap()
.local_timestamp,
0
);
let mut done = false;
for _ in 0..30 {
// there is a chance of a false positive with bloom filters
let req = node.new_pull_request(&node_crds, &node_pubkey, 0, &HashMap::new());
let (_, filter, caller) = req.unwrap();
let rsp = dest.process_pull_request(&mut dest_crds, caller, filter, 0);
// if there is a false positive this is empty
// prob should be around 0.1 per iteration
if rsp.is_empty() {
continue;
}
assert_eq!(rsp.len(), 1);
let failed = node.process_pull_response(&mut node_crds, &node_pubkey, rsp, 1);
assert_eq!(failed, 0);
assert_eq!(
node_crds
.lookup_versioned(&new.label())
.unwrap()
.local_timestamp,
1
);
// verify that the whole record was updated for dest since this is a response from dest
assert_eq!(
node_crds
.lookup_versioned(&same_key.label())
.unwrap()
.local_timestamp,
1
);
done = true;
break;
}
assert!(done);
}
#[test]
fn test_gossip_purge() {
let mut node_crds = Crds::default();
let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
let node_label = entry.label();
let node_pubkey = node_label.pubkey();
let mut node = CrdsGossipPull::default();
node_crds.insert(entry.clone(), 0).unwrap();
let old = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
node_crds.insert(old.clone(), 0).unwrap();
let value_hash = node_crds.lookup_versioned(&old.label()).unwrap().value_hash;
//verify self is valid
assert_eq!(node_crds.lookup(&node_label).unwrap().label(), node_label);
// purge
node.purge_active(&mut node_crds, &node_pubkey, 1);
//verify self is still valid after purge
assert_eq!(node_crds.lookup(&node_label).unwrap().label(), node_label);
assert_eq!(node_crds.lookup_versioned(&old.label()), None);
assert_eq!(node.purged_values.len(), 1);
for _ in 0..30 {
// there is a chance of a false positive with bloom filters
// assert that purged value is still in the set
// chance of 30 consecutive false positives is 0.1^30
let filter = node.build_crds_filter(&node_crds);
assert!(filter.contains(&value_hash));
}
// purge the value
node.purge_purged(1);
assert_eq!(node.purged_values.len(), 0);
}
}
|
use std::error::Error;
use std::fs::metadata;
use std::path::Path;
use colored::*;
use log::*;
use tokio::process::Command;
use crate::ext::rust::PathExt;
use crate::stack::parser::AWSService;
const LOCALSTACK_S3_ENDPOINT: &str = "http://localhost:4572";
pub async fn wait_for_it() -> Result<(), Box<dyn Error>> {
let mut ready: bool = false;
while !ready {
warn!("waiting for localstack's s3 to be ready..");
let cmd = Command::new("aws")
.arg("s3")
.arg("ls")
.args(&["--endpoint-url", LOCALSTACK_S3_ENDPOINT])
.status()
.await?;
if cmd.success() {
ready = true;
}
}
Ok(())
}
pub async fn deploy((name, service): (String, AWSService)) {
match service {
AWSService::S3 {
bucket,
recreate,
files,
} => {
info!("deploying s3 service '{}'", name.yellow());
if recreate {
Command::new("aws")
.arg("s3")
.arg("rb")
.arg("--force")
.arg(format!("s3://{}", bucket))
.args(&["--endpoint-url", LOCALSTACK_S3_ENDPOINT])
.status()
.await
.expect("failed to remove s3 bucket");
}
Command::new("aws")
.arg("s3")
.arg("mb")
.arg(format!("s3://{}", bucket))
.args(&["--endpoint-url", LOCALSTACK_S3_ENDPOINT])
.status()
.await
.expect("failed to create s3 bucket");
for file in files {
if Path::new(&file).does_not_exist() {
warn!("file '{}' does not exist, skip..", file.yellow());
continue;
}
let cmd = if metadata(&file).unwrap().is_dir() {
"sync"
} else {
"cp"
};
Command::new("aws")
.arg("s3")
.arg(cmd)
.arg(&file)
.arg(format!("s3://{}/{}", bucket, file))
.args(&["--endpoint-url", LOCALSTACK_S3_ENDPOINT])
.status()
.await
.expect("failed to copy/sync file to s3 bucket");
}
}
_ => (),
}
}
|
use winit::event::{VirtualKeyCode, ScanCode};
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub enum KeyCode {
Esc,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Num0,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
PrintScreen,
ScrollLock,
/// Pause or Break
Pause,
/// ` or ~
Grave,
/// - or _
Minus,
/// = or +
Equals,
/// [ or {
LBracket,
/// ] or }
RBracket,
/// \ or |
Backslash,
/// ; or :
Semicolon,
/// ' or "
Apostrophe,
/// , or <
Comma,
/// . or >
Period,
/// / or ?
Slash,
Tab,
CapsLock,
LShift,
RShift,
LCtrl,
RCtrl,
/// or left option on macOS
LAlt,
/// or right option on macOs
RAlt,
/// or left command on macOS
LWin,
/// or right command on macOS
RWin,
/// or delete on macOS
Backspace,
/// or return on macOS
Enter,
Space,
Menu,
Insert,
Delete,
Home,
End,
PageUp,
PageDown,
Up,
Down,
Left,
Right,
NumLock,
NumpadSlash,
NumpadMultiply,
NumpadMinus,
NumpadDecimal,
NumpadAdd,
NumpadEnter,
Numpad0,
Numpad1,
Numpad2,
Numpad3,
Numpad4,
Numpad5,
Numpad6,
Numpad7,
Numpad8,
Numpad9,
Other(u32),
}
impl From<(Option<VirtualKeyCode>, ScanCode)> for KeyCode {
fn from((key_code, scan_code): (Option<VirtualKeyCode>, ScanCode)) -> Self {
match key_code {
Some(key_code) => {
match key_code {
VirtualKeyCode::Key1 => KeyCode::Num1,
VirtualKeyCode::Key2 => KeyCode::Num2,
VirtualKeyCode::Key3 => KeyCode::Num3,
VirtualKeyCode::Key4 => KeyCode::Num4,
VirtualKeyCode::Key5 => KeyCode::Num5,
VirtualKeyCode::Key6 => KeyCode::Num6,
VirtualKeyCode::Key7 => KeyCode::Num7,
VirtualKeyCode::Key8 => KeyCode::Num8,
VirtualKeyCode::Key9 => KeyCode::Num9,
VirtualKeyCode::Key0 => KeyCode::Num0,
VirtualKeyCode::A => KeyCode::A,
VirtualKeyCode::B => KeyCode::B,
VirtualKeyCode::C => KeyCode::C,
VirtualKeyCode::D => KeyCode::D,
VirtualKeyCode::E => KeyCode::E,
VirtualKeyCode::F => KeyCode::F,
VirtualKeyCode::G => KeyCode::G,
VirtualKeyCode::H => KeyCode::H,
VirtualKeyCode::I => KeyCode::I,
VirtualKeyCode::J => KeyCode::J,
VirtualKeyCode::K => KeyCode::K,
VirtualKeyCode::L => KeyCode::L,
VirtualKeyCode::M => KeyCode::M,
VirtualKeyCode::N => KeyCode::N,
VirtualKeyCode::O => KeyCode::O,
VirtualKeyCode::P => KeyCode::P,
VirtualKeyCode::Q => KeyCode::Q,
VirtualKeyCode::R => KeyCode::R,
VirtualKeyCode::S => KeyCode::S,
VirtualKeyCode::T => KeyCode::T,
VirtualKeyCode::U => KeyCode::U,
VirtualKeyCode::V => KeyCode::V,
VirtualKeyCode::W => KeyCode::W,
VirtualKeyCode::X => KeyCode::X,
VirtualKeyCode::Y => KeyCode::Y,
VirtualKeyCode::Z => KeyCode::Z,
VirtualKeyCode::Escape => KeyCode::Esc,
VirtualKeyCode::F1 => KeyCode::F1,
VirtualKeyCode::F2 => KeyCode::F2,
VirtualKeyCode::F3 => KeyCode::F3,
VirtualKeyCode::F4 => KeyCode::F4,
VirtualKeyCode::F5 => KeyCode::F5,
VirtualKeyCode::F6 => KeyCode::F6,
VirtualKeyCode::F7 => KeyCode::F7,
VirtualKeyCode::F8 => KeyCode::F8,
VirtualKeyCode::F9 => KeyCode::F9,
VirtualKeyCode::F10 => KeyCode::F10,
VirtualKeyCode::F11 => KeyCode::F11,
VirtualKeyCode::F12 => KeyCode::F12,
VirtualKeyCode::F13 => KeyCode::F13,
VirtualKeyCode::F14 => KeyCode::F14,
VirtualKeyCode::F15 => KeyCode::F15,
VirtualKeyCode::F16 => KeyCode::F16,
VirtualKeyCode::F17 => KeyCode::F17,
VirtualKeyCode::F18 => KeyCode::F18,
VirtualKeyCode::F19 => KeyCode::F19,
VirtualKeyCode::F20 => KeyCode::F20,
VirtualKeyCode::F21 => KeyCode::F21,
VirtualKeyCode::F22 => KeyCode::F22,
VirtualKeyCode::F23 => KeyCode::F23,
VirtualKeyCode::F24 => KeyCode::F24,
VirtualKeyCode::Snapshot => KeyCode::PrintScreen,
VirtualKeyCode::Scroll => KeyCode::ScrollLock,
VirtualKeyCode::Pause => KeyCode::Pause,
VirtualKeyCode::Insert => KeyCode::Insert,
VirtualKeyCode::Home => KeyCode::Home,
VirtualKeyCode::Delete => KeyCode::Delete,
VirtualKeyCode::End => KeyCode::End,
VirtualKeyCode::PageDown => KeyCode::PageDown,
VirtualKeyCode::PageUp => KeyCode::PageUp,
VirtualKeyCode::Left => KeyCode::Left,
VirtualKeyCode::Up => KeyCode::Up,
VirtualKeyCode::Right => KeyCode::Right,
VirtualKeyCode::Down => KeyCode::Down,
VirtualKeyCode::Back => KeyCode::Backspace,
VirtualKeyCode::Return => KeyCode::Enter,
VirtualKeyCode::Space => KeyCode::Space,
VirtualKeyCode::Compose => KeyCode::Other(scan_code),
VirtualKeyCode::Caret => KeyCode::Other(scan_code),
VirtualKeyCode::Numlock => KeyCode::NumLock,
VirtualKeyCode::Numpad0 => KeyCode::Numpad0,
VirtualKeyCode::Numpad1 => KeyCode::Numpad1,
VirtualKeyCode::Numpad2 => KeyCode::Numpad2,
VirtualKeyCode::Numpad3 => KeyCode::Numpad3,
VirtualKeyCode::Numpad4 => KeyCode::Numpad4,
VirtualKeyCode::Numpad5 => KeyCode::Numpad5,
VirtualKeyCode::Numpad6 => KeyCode::Numpad6,
VirtualKeyCode::Numpad7 => KeyCode::Numpad7,
VirtualKeyCode::Numpad8 => KeyCode::Numpad8,
VirtualKeyCode::Numpad9 => KeyCode::Numpad9,
VirtualKeyCode::AbntC1 => KeyCode::Other(scan_code),
VirtualKeyCode::AbntC2 => KeyCode::Other(scan_code),
VirtualKeyCode::Add => KeyCode::NumpadAdd,
VirtualKeyCode::Apostrophe => KeyCode::Apostrophe,
VirtualKeyCode::Apps => KeyCode::Menu,
VirtualKeyCode::At => KeyCode::Other(scan_code),
VirtualKeyCode::Ax => KeyCode::Other(scan_code),
VirtualKeyCode::Backslash => KeyCode::Backslash,
VirtualKeyCode::Calculator => KeyCode::Other(scan_code),
VirtualKeyCode::Capital => KeyCode::CapsLock,
VirtualKeyCode::Colon => KeyCode::Other(scan_code),
VirtualKeyCode::Comma => KeyCode::Comma,
VirtualKeyCode::Convert => KeyCode::Other(scan_code),
VirtualKeyCode::Decimal => KeyCode::NumpadDecimal,
VirtualKeyCode::Divide => KeyCode::NumpadSlash,
VirtualKeyCode::Equals => KeyCode::Equals,
VirtualKeyCode::Grave => KeyCode::Grave,
VirtualKeyCode::Kana => KeyCode::Other(scan_code),
VirtualKeyCode::Kanji => KeyCode::Other(scan_code),
VirtualKeyCode::LAlt => KeyCode::LAlt,
VirtualKeyCode::LBracket => KeyCode::LBracket,
VirtualKeyCode::LControl => KeyCode::LCtrl,
VirtualKeyCode::LShift => KeyCode::LShift,
VirtualKeyCode::LWin => KeyCode::LWin,
VirtualKeyCode::Mail => KeyCode::Other(scan_code),
VirtualKeyCode::MediaSelect => KeyCode::Other(scan_code),
VirtualKeyCode::MediaStop => KeyCode::Other(scan_code),
VirtualKeyCode::Minus => KeyCode::Minus,
VirtualKeyCode::Multiply => KeyCode::NumpadMultiply,
VirtualKeyCode::Mute => KeyCode::Other(scan_code),
VirtualKeyCode::MyComputer => KeyCode::Other(scan_code),
VirtualKeyCode::NavigateForward => KeyCode::Other(scan_code),
VirtualKeyCode::NavigateBackward => KeyCode::Other(scan_code),
VirtualKeyCode::NextTrack => KeyCode::Other(scan_code),
VirtualKeyCode::NoConvert => KeyCode::Other(scan_code),
VirtualKeyCode::NumpadComma => KeyCode::Other(scan_code),
VirtualKeyCode::NumpadEnter => KeyCode::NumpadEnter,
VirtualKeyCode::NumpadEquals => KeyCode::Other(scan_code),
VirtualKeyCode::OEM102 => KeyCode::Other(scan_code),
VirtualKeyCode::Period => KeyCode::Period,
VirtualKeyCode::PlayPause => KeyCode::Other(scan_code),
VirtualKeyCode::Power => KeyCode::Other(scan_code),
VirtualKeyCode::PrevTrack => KeyCode::Other(scan_code),
VirtualKeyCode::RAlt => KeyCode::RAlt,
VirtualKeyCode::RBracket => KeyCode::RBracket,
VirtualKeyCode::RControl => KeyCode::RCtrl,
VirtualKeyCode::RShift => KeyCode::RShift,
VirtualKeyCode::RWin => KeyCode::RWin,
VirtualKeyCode::Semicolon => KeyCode::Semicolon,
VirtualKeyCode::Slash => KeyCode::Slash,
VirtualKeyCode::Sleep => KeyCode::Other(scan_code),
VirtualKeyCode::Stop => KeyCode::Other(scan_code),
VirtualKeyCode::Subtract => KeyCode::NumpadMinus,
VirtualKeyCode::Sysrq => KeyCode::Other(scan_code),
VirtualKeyCode::Tab => KeyCode::Tab,
VirtualKeyCode::Underline => KeyCode::Other(scan_code),
VirtualKeyCode::Unlabeled => KeyCode::Other(scan_code),
VirtualKeyCode::VolumeDown => KeyCode::Other(scan_code),
VirtualKeyCode::VolumeUp => KeyCode::Other(scan_code),
VirtualKeyCode::Wake => KeyCode::Other(scan_code),
VirtualKeyCode::WebBack => KeyCode::Other(scan_code),
VirtualKeyCode::WebFavorites => KeyCode::Other(scan_code),
VirtualKeyCode::WebForward => KeyCode::Other(scan_code),
VirtualKeyCode::WebHome => KeyCode::Other(scan_code),
VirtualKeyCode::WebRefresh => KeyCode::Other(scan_code),
VirtualKeyCode::WebSearch => KeyCode::Other(scan_code),
VirtualKeyCode::WebStop => KeyCode::Other(scan_code),
VirtualKeyCode::Yen => KeyCode::Other(scan_code),
VirtualKeyCode::Copy => KeyCode::Other(scan_code),
VirtualKeyCode::Paste => KeyCode::Other(scan_code),
VirtualKeyCode::Cut => KeyCode::Other(scan_code),
}
}
None => KeyCode::Other(scan_code),
}
}
}
|
use std::io::{BufRead, BufReader, Error, ErrorKind};
use std::process::{Command, Stdio};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::thread;
use crate::line_details::{LineDetails, parse_line};
const QUIT_MESSAGE: &'static str = "QUIT_TASK";
pub fn process_files(num_workers: usize, directory: &str, ignore_list: Vec<String>) -> Result<(), Error> {
// We want a number of workers to handle the filenames
let mut workers = Vec::new();
// One channel to send lines down - another to send parsed results down
let (line_sender, line_receiver) = channel::<(String, String)>();
let (result_sender, result_receiver) = channel::<LineDetails>();
// We maintain a channel for each worker which we send it file names down.
let mut worker_channels = Vec::new();
for i in 0..num_workers {
let (sender, receiver) = channel::<String>();
worker_channels.push(sender);
// clone the channel we'll send lines to the worker on
let line_sender_clone = line_sender.clone();
let worker = thread::spawn(move || {
blame_files(i, receiver, line_sender_clone);
});
// Save the worker so we can join to it later
workers.push(worker);
}
// Fire off all the messages to these worker channels
generate_file_messages(worker_channels, directory, ignore_list)?;
// Start a thread to parse all the returned lines
let details_parser = thread::spawn(move || {
find_oldest_line(line_receiver, result_sender);
});
// Join on all the threads - wait for them to be done blaming.
for worker in workers {
worker.join().unwrap();
}
// Close the original result sender - this will tell our thread processing into LineDetails
// that it is done and it can finish
line_sender.send((QUIT_MESSAGE.to_string(), QUIT_MESSAGE.to_string())).unwrap();
details_parser.join().unwrap();
// This is a list of potential results the last one will be the earliest.
let result = result_receiver.iter().last().unwrap();
println!("Oldest record found.");
println!("{}", result);
Ok(())
}
fn blame_files(thread_id: usize, receiver: Receiver<String>, transmitter: Sender<(String, String)>) {
for message in receiver {
if message == QUIT_MESSAGE.to_string() {
println!("Thread {} quitting.", thread_id);
break;
}
println!("Thread {}, blaming file: {}", thread_id, message);
match message {
message => {
// -l is for the long commit reference
// -f to always show the file name of where the code came from (movement tracking)
// -M and -C are related to tracking down code movements to the original commit
// rather than just the latest that touched them
let git_blame_output = Command::new("git")
.args(&["blame", "-l", "-f", "-M", "-C", &message])
.output().unwrap();
git_blame_output.stdout
.lines()
.filter_map(|line| line.ok())
.for_each(|line| {
transmitter.send((line, message.clone())).unwrap();
});
}
};
}
// we need to tell the main thread which is parsing these messages
// that we are done - so drop our copy of the transmitter.
drop(transmitter);
}
fn generate_file_messages(worker_channels: Vec::<Sender<String>>, directory: &str, ignore_list: Vec<String>) -> Result<(), Error> {
let num_workers = worker_channels.len();
// Get a list of every file that git tracks
let gitls_stdout = Command::new("git")
.args(&["ls-tree", "-r", "--name-only", "HEAD", directory])
.stdout(Stdio::piped())
.spawn()?
.stdout
.ok_or_else(|| Error::new(ErrorKind::Other,"Could not capture standard output."))?;
// For each one run a git blame on it.
let reader = BufReader::new(gitls_stdout);
let mut round_robin = 0;
let mut count = 0;
reader
.lines()
.filter_map(|line| line.ok())
.filter(|line| {
!ignore_list.contains(line)
})
.for_each(|file_name| {
// get the current worker
let message_sender = worker_channels.get(round_robin).unwrap();
message_sender.send(file_name).unwrap();
count += 1;
round_robin = (round_robin + 1) % num_workers;
});
println!("Found {} files to blame.", count);
// We send an end message down the queues so that the thread knows to quit
for sender in worker_channels {
sender.send(QUIT_MESSAGE.to_string()).unwrap();
}
Ok(())
}
fn find_oldest_line(line_receiver: Receiver<(String, String)>, result_sender: Sender<LineDetails>) {
let mut oldest_line_so_far = LineDetails::default();
for message in line_receiver {
if message.0 == QUIT_MESSAGE.to_string() {
println!("Line parser thread quitting.");
break;
}
match parse_line(&message.0, &message.1) {
Some(details) => {
if details.datetime < oldest_line_so_far.datetime {
oldest_line_so_far = details;
result_sender.send(oldest_line_so_far.clone()).unwrap();
}
},
None => panic!("Could not create details from line: {}, in file: {}", message.0, message.1),
}
};
}
|
#![allow(dead_code)]
use std::{
error::Error as ErrorTrait,
fmt::{self, Debug, Display},
};
#[allow(unused_imports)]
pub use abi_stable_shared::test_utils::{must_panic, ShouldHavePanickedAt, ThreadError};
//////////////////////////////////////////////////////////////////
/// Checks that `left` and `right` produce the exact same Display and Debug output.
pub fn check_formatting_equivalence<T, U>(left: &T, right: &U)
where
T: Debug + Display + ?Sized,
U: Debug + Display + ?Sized,
{
assert_eq!(format!("{:?}", left), format!("{:?}", right));
assert_eq!(format!("{:#?}", left), format!("{:#?}", right));
assert_eq!(format!("{}", left), format!("{}", right));
assert_eq!(format!("{:#}", left), format!("{:#}", right));
}
/// Returns the address this dereferences to.
pub fn deref_address<D>(ptr: &D) -> usize
where
D: ::std::ops::Deref,
{
(&**ptr) as *const _ as *const u8 as usize
}
//////////////////////////////////////////////////////////////////
/// A wrapper type which uses `T`'s Display formatter in its Debug impl
#[repr(transparent)]
#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, StableAbi)]
pub struct AlwaysDisplay<T>(pub T);
impl<T> Display for AlwaysDisplay<T>
where
T: Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt(&self.0, f)
}
}
impl<T> Debug for AlwaysDisplay<T>
where
T: Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt(&self.0, f)
}
}
//////////////////////////////////////////////////////////////////
macro_rules! if_impls_impls {
($($const:ident, $trait:path);* $(;)*) => {
pub trait GetImplsHelper {
$(const $const: bool = false;)*
}
impl<T> GetImplsHelper for T {}
pub struct GetImpls<S>(S);
$(
impl<S> GetImpls<S>
where
S: $trait
{
pub const $const: bool = true;
}
)*
};
}
if_impls_impls! {
IMPLS_SEND, Send;
IMPLS_SYNC, Sync;
IMPLS_UNPIN, Unpin;
IMPLS_CLONE, Clone;
IMPLS_DISPLAY, std::fmt::Display;
IMPLS_DEBUG, std::fmt::Debug;
IMPLS_SERIALIZE, serde::Serialize;
IMPLS_EQ, std::cmp::Eq;
IMPLS_PARTIAL_EQ, std::cmp::PartialEq;
IMPLS_ORD, std::cmp::Ord;
IMPLS_PARTIAL_ORD, std::cmp::PartialOrd;
IMPLS_HASH, std::hash::Hash;
IMPLS_DESERIALIZE, serde::Deserialize<'static>;
IMPLS_ITERATOR, Iterator;
IMPLS_DOUBLE_ENDED_ITERATOR, DoubleEndedIterator;
IMPLS_FMT_WRITE, std::fmt::Write;
IMPLS_IO_WRITE, std::io::Write;
IMPLS_IO_SEEK, std::io::Seek;
IMPLS_IO_READ, std::io::Read;
IMPLS_IO_BUF_READ, std::io::BufRead;
IMPLS_ERROR, std::error::Error;
}
//////////////////////////////////////////////////////////////////
#[derive(Clone)]
pub struct Stringy {
pub str: String,
}
impl Stringy {
pub fn new<S>(str: S) -> Self
where
S: Into<String>,
{
Stringy { str: str.into() }
}
}
impl Debug for Stringy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Debug::fmt(&self.str, f)
}
}
impl Display for Stringy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt(&self.str, f)
}
}
impl ErrorTrait for Stringy {}
|
#![allow(bad_style)]
extern crate gdi32;
extern crate winapi;
extern crate user32;
extern crate kernel32;
extern crate winmm;
pub mod window;
pub mod input;
pub mod file;
pub trait ToCU16Str {
fn to_c_u16(&self) -> Vec<u16>;
}
impl<'a> ToCU16Str for &'a str {
fn to_c_u16(&self) -> Vec<u16> {
self.encode_utf16().chain(Some(0).into_iter()).collect()
}
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct DetectedFace(pub ::windows::core::IInspectable);
impl DetectedFace {
#[cfg(feature = "Graphics_Imaging")]
pub fn FaceBox(&self) -> ::windows::core::Result<super::super::Graphics::Imaging::BitmapBounds> {
let this = self;
unsafe {
let mut result__: super::super::Graphics::Imaging::BitmapBounds = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Graphics::Imaging::BitmapBounds>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for DetectedFace {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.FaceAnalysis.DetectedFace;{8200d454-66bc-34df-9410-e89400195414})");
}
unsafe impl ::windows::core::Interface for DetectedFace {
type Vtable = IDetectedFace_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8200d454_66bc_34df_9410_e89400195414);
}
impl ::windows::core::RuntimeName for DetectedFace {
const NAME: &'static str = "Windows.Media.FaceAnalysis.DetectedFace";
}
impl ::core::convert::From<DetectedFace> for ::windows::core::IUnknown {
fn from(value: DetectedFace) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&DetectedFace> for ::windows::core::IUnknown {
fn from(value: &DetectedFace) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for DetectedFace {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a DetectedFace {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<DetectedFace> for ::windows::core::IInspectable {
fn from(value: DetectedFace) -> Self {
value.0
}
}
impl ::core::convert::From<&DetectedFace> for ::windows::core::IInspectable {
fn from(value: &DetectedFace) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for DetectedFace {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a DetectedFace {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for DetectedFace {}
unsafe impl ::core::marker::Sync for DetectedFace {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct FaceDetector(pub ::windows::core::IInspectable);
impl FaceDetector {
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Graphics_Imaging"))]
pub fn DetectFacesAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Graphics::Imaging::SoftwareBitmap>>(&self, image: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVector<DetectedFace>>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), image.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVector<DetectedFace>>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Graphics_Imaging"))]
pub fn DetectFacesWithSearchAreaAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Graphics::Imaging::SoftwareBitmap>, Param1: ::windows::core::IntoParam<'a, super::super::Graphics::Imaging::BitmapBounds>>(&self, image: Param0, searcharea: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVector<DetectedFace>>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), image.into_param().abi(), searcharea.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVector<DetectedFace>>>(result__)
}
}
#[cfg(feature = "Graphics_Imaging")]
pub fn MinDetectableFaceSize(&self) -> ::windows::core::Result<super::super::Graphics::Imaging::BitmapSize> {
let this = self;
unsafe {
let mut result__: super::super::Graphics::Imaging::BitmapSize = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Graphics::Imaging::BitmapSize>(result__)
}
}
#[cfg(feature = "Graphics_Imaging")]
pub fn SetMinDetectableFaceSize<'a, Param0: ::windows::core::IntoParam<'a, super::super::Graphics::Imaging::BitmapSize>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Graphics_Imaging")]
pub fn MaxDetectableFaceSize(&self) -> ::windows::core::Result<super::super::Graphics::Imaging::BitmapSize> {
let this = self;
unsafe {
let mut result__: super::super::Graphics::Imaging::BitmapSize = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Graphics::Imaging::BitmapSize>(result__)
}
}
#[cfg(feature = "Graphics_Imaging")]
pub fn SetMaxDetectableFaceSize<'a, Param0: ::windows::core::IntoParam<'a, super::super::Graphics::Imaging::BitmapSize>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn CreateAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<FaceDetector>> {
Self::IFaceDetectorStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<FaceDetector>>(result__)
})
}
#[cfg(all(feature = "Foundation_Collections", feature = "Graphics_Imaging"))]
pub fn GetSupportedBitmapPixelFormats() -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<super::super::Graphics::Imaging::BitmapPixelFormat>> {
Self::IFaceDetectorStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<super::super::Graphics::Imaging::BitmapPixelFormat>>(result__)
})
}
#[cfg(feature = "Graphics_Imaging")]
pub fn IsBitmapPixelFormatSupported(bitmappixelformat: super::super::Graphics::Imaging::BitmapPixelFormat) -> ::windows::core::Result<bool> {
Self::IFaceDetectorStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), bitmappixelformat, &mut result__).from_abi::<bool>(result__)
})
}
pub fn IsSupported() -> ::windows::core::Result<bool> {
Self::IFaceDetectorStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
})
}
pub fn IFaceDetectorStatics<R, F: FnOnce(&IFaceDetectorStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<FaceDetector, IFaceDetectorStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for FaceDetector {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.FaceAnalysis.FaceDetector;{16b672dc-fe6f-3117-8d95-c3f04d51630c})");
}
unsafe impl ::windows::core::Interface for FaceDetector {
type Vtable = IFaceDetector_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x16b672dc_fe6f_3117_8d95_c3f04d51630c);
}
impl ::windows::core::RuntimeName for FaceDetector {
const NAME: &'static str = "Windows.Media.FaceAnalysis.FaceDetector";
}
impl ::core::convert::From<FaceDetector> for ::windows::core::IUnknown {
fn from(value: FaceDetector) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&FaceDetector> for ::windows::core::IUnknown {
fn from(value: &FaceDetector) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for FaceDetector {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a FaceDetector {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<FaceDetector> for ::windows::core::IInspectable {
fn from(value: FaceDetector) -> Self {
value.0
}
}
impl ::core::convert::From<&FaceDetector> for ::windows::core::IInspectable {
fn from(value: &FaceDetector) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for FaceDetector {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a FaceDetector {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for FaceDetector {}
unsafe impl ::core::marker::Sync for FaceDetector {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct FaceTracker(pub ::windows::core::IInspectable);
impl FaceTracker {
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))]
pub fn ProcessNextFrameAsync<'a, Param0: ::windows::core::IntoParam<'a, super::VideoFrame>>(&self, videoframe: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVector<DetectedFace>>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), videoframe.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVector<DetectedFace>>>(result__)
}
}
#[cfg(feature = "Graphics_Imaging")]
pub fn MinDetectableFaceSize(&self) -> ::windows::core::Result<super::super::Graphics::Imaging::BitmapSize> {
let this = self;
unsafe {
let mut result__: super::super::Graphics::Imaging::BitmapSize = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Graphics::Imaging::BitmapSize>(result__)
}
}
#[cfg(feature = "Graphics_Imaging")]
pub fn SetMinDetectableFaceSize<'a, Param0: ::windows::core::IntoParam<'a, super::super::Graphics::Imaging::BitmapSize>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Graphics_Imaging")]
pub fn MaxDetectableFaceSize(&self) -> ::windows::core::Result<super::super::Graphics::Imaging::BitmapSize> {
let this = self;
unsafe {
let mut result__: super::super::Graphics::Imaging::BitmapSize = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Graphics::Imaging::BitmapSize>(result__)
}
}
#[cfg(feature = "Graphics_Imaging")]
pub fn SetMaxDetectableFaceSize<'a, Param0: ::windows::core::IntoParam<'a, super::super::Graphics::Imaging::BitmapSize>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn CreateAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<FaceTracker>> {
Self::IFaceTrackerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<FaceTracker>>(result__)
})
}
#[cfg(all(feature = "Foundation_Collections", feature = "Graphics_Imaging"))]
pub fn GetSupportedBitmapPixelFormats() -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<super::super::Graphics::Imaging::BitmapPixelFormat>> {
Self::IFaceTrackerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<super::super::Graphics::Imaging::BitmapPixelFormat>>(result__)
})
}
#[cfg(feature = "Graphics_Imaging")]
pub fn IsBitmapPixelFormatSupported(bitmappixelformat: super::super::Graphics::Imaging::BitmapPixelFormat) -> ::windows::core::Result<bool> {
Self::IFaceTrackerStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), bitmappixelformat, &mut result__).from_abi::<bool>(result__)
})
}
pub fn IsSupported() -> ::windows::core::Result<bool> {
Self::IFaceTrackerStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
})
}
pub fn IFaceTrackerStatics<R, F: FnOnce(&IFaceTrackerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<FaceTracker, IFaceTrackerStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for FaceTracker {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.FaceAnalysis.FaceTracker;{6ba67d8c-a841-4420-93e6-2420a1884fcf})");
}
unsafe impl ::windows::core::Interface for FaceTracker {
type Vtable = IFaceTracker_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6ba67d8c_a841_4420_93e6_2420a1884fcf);
}
impl ::windows::core::RuntimeName for FaceTracker {
const NAME: &'static str = "Windows.Media.FaceAnalysis.FaceTracker";
}
impl ::core::convert::From<FaceTracker> for ::windows::core::IUnknown {
fn from(value: FaceTracker) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&FaceTracker> for ::windows::core::IUnknown {
fn from(value: &FaceTracker) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for FaceTracker {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a FaceTracker {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<FaceTracker> for ::windows::core::IInspectable {
fn from(value: FaceTracker) -> Self {
value.0
}
}
impl ::core::convert::From<&FaceTracker> for ::windows::core::IInspectable {
fn from(value: &FaceTracker) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for FaceTracker {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a FaceTracker {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for FaceTracker {}
unsafe impl ::core::marker::Sync for FaceTracker {}
#[repr(transparent)]
#[doc(hidden)]
pub struct IDetectedFace(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IDetectedFace {
type Vtable = IDetectedFace_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8200d454_66bc_34df_9410_e89400195414);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDetectedFace_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Graphics::Imaging::BitmapBounds) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IFaceDetector(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IFaceDetector {
type Vtable = IFaceDetector_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x16b672dc_fe6f_3117_8d95_c3f04d51630c);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFaceDetector_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Graphics_Imaging"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, image: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Graphics_Imaging")))] usize,
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Graphics_Imaging"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, image: ::windows::core::RawPtr, searcharea: super::super::Graphics::Imaging::BitmapBounds, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Graphics_Imaging")))] usize,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Graphics::Imaging::BitmapSize) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Graphics::Imaging::BitmapSize) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Graphics::Imaging::BitmapSize) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Graphics::Imaging::BitmapSize) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IFaceDetectorStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IFaceDetectorStatics {
type Vtable = IFaceDetectorStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbc042d67_9047_33f6_881b_6746c1b218b8);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFaceDetectorStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation_Collections", feature = "Graphics_Imaging"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Graphics_Imaging")))] usize,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bitmappixelformat: super::super::Graphics::Imaging::BitmapPixelFormat, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IFaceTracker(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IFaceTracker {
type Vtable = IFaceTracker_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6ba67d8c_a841_4420_93e6_2420a1884fcf);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFaceTracker_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, videoframe: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Graphics::Imaging::BitmapSize) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Graphics::Imaging::BitmapSize) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Graphics::Imaging::BitmapSize) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Graphics::Imaging::BitmapSize) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IFaceTrackerStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IFaceTrackerStatics {
type Vtable = IFaceTrackerStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe9629198_1801_3fa5_932e_31d767af6c4d);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFaceTrackerStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation_Collections", feature = "Graphics_Imaging"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Graphics_Imaging")))] usize,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bitmappixelformat: super::super::Graphics::Imaging::BitmapPixelFormat, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
|
// More convoluted in real life, does not matter here
use std::fmt::{self, Display, Formatter};
#[derive(Copy, Clone, Default, Debug)]
pub struct Foreground(pub u8, pub u8, pub u8);
#[derive(Copy, Clone, Default, Debug)]
pub struct Background(pub u8, pub u8, pub u8);
#[derive(Copy, Clone, Debug)]
pub enum Weight {
Bold,
Normal,
}
#[derive(Copy, Clone, Default, Debug)]
pub struct Style {
pub foreground: Foreground,
pub weight: Weight,
}
impl Default for Weight {
fn default() -> Self {
Weight::Normal
}
}
impl Display for Foreground {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "\x1B[38;2;{};{};{}m", self.0, self.1, self.2)
}
}
impl Display for Background {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "\x1B[48;2;{};{};{}m", self.0, self.1, self.2)
}
}
impl Display for Weight {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Weight::Bold => write!(f, "\x1B[1m"),
Weight::Normal => write!(f, "\x1B[22m"),
}
}
}
impl Display for Style {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}{}", self.foreground, self.weight)
}
}
|
//! https://github.com/lumen/otp/tree/lumen/lib/megaco/src/binary
use super::*;
test_compiles_lumen_otp!(megaco_ber_encoder imports "lib/megaco/src/binary/megaco_binary_encoder_lib");
test_compiles_lumen_otp!(megaco_binary_encoder imports "lib/megaco/src/binary/megaco_binary_encoder_lib");
test_compiles_lumen_otp!(megaco_binary_encoder_lib);
test_compiles_lumen_otp!(megaco_binary_name_resolver_v1);
test_compiles_lumen_otp!(megaco_binary_name_resolver_v2);
test_compiles_lumen_otp!(megaco_binary_name_resolver_v3);
test_compiles_lumen_otp!(megaco_binary_term_id);
test_compiles_lumen_otp!(megaco_binary_term_id_gen);
test_compiles_lumen_otp!(megaco_binary_transformer_v1);
test_compiles_lumen_otp!(megaco_binary_transformer_v2);
test_compiles_lumen_otp!(megaco_binary_transformer_v3);
test_compiles_lumen_otp!(megaco_per_encoder imports "lib/megaco/src/binary/megaco_binary_encoder_lib");
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("binary")
}
|
use mod_int::ModInt998244353;
use proconio::input;
fn main() {
input! {
n: usize,
m: usize,
k: usize,
};
type Mint = ModInt998244353;
let mut dp = vec![Mint::new(0); m + 1];
for i in 1..=m {
dp[i] = Mint::new(1);
}
for _ in 1..n {
let mut nxt = vec![Mint::new(0); m + 1];
for i in 1..=m {
// i - k >= 1
if i >= k + 1 {
nxt[1] += dp[i];
// i - k + 1 <= m
if i + 1 <= m + k {
nxt[i - k + 1] -= dp[i];
}
}
if 1 < i + k && i + k <= m {
nxt[i + k] += dp[i];
}
}
for i in 2..=m {
nxt[i] = nxt[i] + nxt[i - 1];
}
dp = nxt;
}
let mut ans = Mint::new(0);
for i in 1..=m {
ans += dp[i];
}
println!("{}", ans.val());
}
|
use failure::Error;
use regex::RegexSet;
use serde_yaml;
use std::fs::File;
use std::io::Read;
#[derive(Debug, Deserialize, PartialOrd, Ord, Eq, PartialEq, Clone)]
pub struct Customer {
pub name: String,
job_pattern: String,
}
#[derive(Debug, Deserialize, PartialEq)]
pub struct Set {
customers: Vec<Customer>,
}
impl Set {
pub fn load(path: &str) -> Result<Self, Error> {
let mut content = String::new();
File::open(path)?.read_to_string(&mut content)?;
Ok(serde_yaml::from_str(&content)?)
}
pub fn get(&self, n: usize) -> Option<&Customer> {
self.customers.get(n)
}
pub fn job_patterns(&self) -> Result<RegexSet, Error> {
Ok(RegexSet::new(
self.customers
.iter()
.map(|c| c.job_pattern.clone())
.collect::<Vec<_>>(),
)?)
}
}
|
//! Implementation of the table gRPC service
#![deny(
rustdoc::broken_intra_doc_links,
rustdoc::bare_urls,
rust_2018_idioms,
missing_debug_implementations,
unreachable_pub
)]
#![warn(
missing_docs,
clippy::todo,
clippy::dbg_macro,
clippy::clone_on_ref_ptr,
clippy::future_not_send,
clippy::todo,
clippy::dbg_macro,
unused_crate_dependencies
)]
#![allow(clippy::missing_docs_in_private_items)]
// Workaround for "unused crate" lint false positives.
use workspace_hack as _;
use std::sync::Arc;
use data_types::{
partition_template::TablePartitionTemplateOverride, NamespaceName, Table as CatalogTable,
};
use generated_types::influxdata::iox::table::v1::*;
use iox_catalog::interface::{Catalog, SoftDeletedRows};
use observability_deps::tracing::{debug, info, warn};
use tonic::{Request, Response, Status};
/// Implementation of the table gRPC service
#[derive(Debug)]
pub struct TableService {
/// Catalog.
catalog: Arc<dyn Catalog>,
}
impl TableService {
/// Create a new `TableService` instance
pub fn new(catalog: Arc<dyn Catalog>) -> Self {
Self { catalog }
}
}
#[tonic::async_trait]
impl table_service_server::TableService for TableService {
// create a table
async fn create_table(
&self,
request: Request<CreateTableRequest>,
) -> Result<Response<CreateTableResponse>, Status> {
let mut repos = self.catalog.repositories().await;
let CreateTableRequest {
name,
namespace,
partition_template,
} = request.into_inner();
let namespace_name = NamespaceName::try_from(namespace)
.map_err(|e| Status::invalid_argument(e.to_string()))?;
debug!(%name, %namespace_name, "Creating table");
let namespace = repos
.namespaces()
.get_by_name(&namespace_name, SoftDeletedRows::ExcludeDeleted)
.await
.map_err(|e| Status::internal(e.to_string()))?
.ok_or_else(|| {
Status::not_found(format!(
"Could not find a namespace with name {namespace_name}"
))
})?;
let table = repos
.tables()
.create(
&name,
TablePartitionTemplateOverride::try_new(
partition_template,
&namespace.partition_template,
)
.map_err(|v| Status::invalid_argument(v.to_string()))?,
namespace.id,
)
.await
.map_err(|e| {
warn!(error=%e, %name, "failed to create table");
match e {
iox_catalog::interface::Error::TableNameExists { name, .. } => {
Status::already_exists(format!(
"A table with the name `{name}` already exists \
in the namespace `{}`",
namespace.name
))
}
other => Status::internal(other.to_string()),
}
})?;
info!(
%name,
table_id = %table.id,
partition_template = ?table.partition_template,
"created table"
);
Ok(Response::new(table_to_create_response_proto(table)))
}
}
fn table_to_create_response_proto(table: CatalogTable) -> CreateTableResponse {
CreateTableResponse {
table: Some(Table {
id: table.id.get(),
name: table.name.clone(),
namespace_id: table.namespace_id.get(),
}),
}
}
#[cfg(test)]
mod tests {
use data_types::{partition_template::NamespacePartitionTemplateOverride, TableId};
use generated_types::influxdata::iox::{
partition_template::v1::{template_part, PartitionTemplate, TemplatePart},
table::v1::table_service_server::TableService as _,
};
use iox_catalog::{mem::MemCatalog, test_helpers::arbitrary_namespace};
use tonic::Code;
use super::*;
#[tokio::test]
async fn test_basic_happy_path() {
let catalog: Arc<dyn Catalog> =
Arc::new(MemCatalog::new(Arc::new(metric::Registry::default())));
let handler = TableService::new(Arc::clone(&catalog));
let namespace = arbitrary_namespace(&mut *catalog.repositories().await, "grapes").await;
let table_name = "varietals";
let request = CreateTableRequest {
name: table_name.into(),
namespace: namespace.name.clone(),
partition_template: None,
};
let created_table = handler
.create_table(Request::new(request))
.await
.unwrap()
.into_inner()
.table
.unwrap();
assert!(created_table.id > 0);
assert_eq!(created_table.name, table_name);
assert_eq!(created_table.namespace_id, namespace.id.get());
// The default template doesn't use any tag values, so no columns need to be created.
let table_columns = catalog
.repositories()
.await
.columns()
.list_by_table_id(TableId::new(created_table.id))
.await
.unwrap();
assert!(table_columns.is_empty());
}
#[tokio::test]
async fn creating_same_table_twice_fails() {
let catalog: Arc<dyn Catalog> =
Arc::new(MemCatalog::new(Arc::new(metric::Registry::default())));
let handler = TableService::new(Arc::clone(&catalog));
let namespace = arbitrary_namespace(&mut *catalog.repositories().await, "grapes").await;
let table_name = "varietals";
let request = CreateTableRequest {
name: table_name.into(),
namespace: namespace.name.clone(),
partition_template: None,
};
let created_table = handler
.create_table(Request::new(request.clone()))
.await
.unwrap()
.into_inner()
.table
.unwrap();
// First creation attempt succeeds
assert!(created_table.id > 0);
assert_eq!(created_table.name, table_name);
assert_eq!(created_table.namespace_id, namespace.id.get());
// Trying to create a table in the same namespace with the same name fails with an "already
// exists" error
let error = handler
.create_table(Request::new(request))
.await
.unwrap_err();
assert_eq!(error.code(), Code::AlreadyExists);
assert_eq!(
error.message(),
"A table with the name `varietals` already exists in the namespace `grapes`"
);
let all_tables = catalog.repositories().await.tables().list().await.unwrap();
assert_eq!(all_tables.len(), 1);
}
#[tokio::test]
async fn nonexistent_namespace_errors() {
let catalog: Arc<dyn Catalog> =
Arc::new(MemCatalog::new(Arc::new(metric::Registry::default())));
let handler = TableService::new(Arc::clone(&catalog));
let table_name = "varietals";
let request = CreateTableRequest {
name: table_name.into(),
namespace: "does_not_exist".into(),
partition_template: None,
};
let error = handler
.create_table(Request::new(request))
.await
.unwrap_err();
assert_eq!(error.code(), Code::NotFound);
assert_eq!(
error.message(),
"Could not find a namespace with name does_not_exist"
);
let all_tables = catalog.repositories().await.tables().list().await.unwrap();
assert!(all_tables.is_empty());
}
#[tokio::test]
async fn custom_table_template_using_tags_creates_tag_columns() {
let catalog: Arc<dyn Catalog> =
Arc::new(MemCatalog::new(Arc::new(metric::Registry::default())));
let handler = TableService::new(Arc::clone(&catalog));
let namespace = arbitrary_namespace(&mut *catalog.repositories().await, "grapes").await;
let table_name = "varietals";
let request = CreateTableRequest {
name: table_name.into(),
namespace: namespace.name.clone(),
partition_template: Some(PartitionTemplate {
parts: vec![
TemplatePart {
part: Some(template_part::Part::TagValue("color".into())),
},
TemplatePart {
part: Some(template_part::Part::TagValue("tannins".into())),
},
TemplatePart {
part: Some(template_part::Part::TimeFormat("%Y".into())),
},
],
}),
};
let created_table = handler
.create_table(Request::new(request))
.await
.unwrap()
.into_inner()
.table
.unwrap();
assert!(created_table.id > 0);
assert_eq!(created_table.name, table_name);
assert_eq!(created_table.namespace_id, namespace.id.get());
let table_columns = catalog
.repositories()
.await
.columns()
.list_by_table_id(TableId::new(created_table.id))
.await
.unwrap();
assert_eq!(table_columns.len(), 2);
assert!(table_columns.iter().all(|c| c.is_tag()));
let mut column_names: Vec<_> = table_columns.iter().map(|c| &c.name).collect();
column_names.sort();
assert_eq!(column_names, &["color", "tannins"])
}
#[tokio::test]
async fn custom_namespace_template_using_tags_creates_tag_columns() {
let catalog: Arc<dyn Catalog> =
Arc::new(MemCatalog::new(Arc::new(metric::Registry::default())));
let handler = TableService::new(Arc::clone(&catalog));
let namespace_name = NamespaceName::new("grapes").unwrap();
let namespace = catalog
.repositories()
.await
.namespaces()
.create(
&namespace_name,
Some(
NamespacePartitionTemplateOverride::try_from(PartitionTemplate {
parts: vec![
TemplatePart {
part: Some(template_part::Part::TagValue("color".into())),
},
TemplatePart {
part: Some(template_part::Part::TagValue("tannins".into())),
},
TemplatePart {
part: Some(template_part::Part::TimeFormat("%Y".into())),
},
],
})
.unwrap(),
),
None,
None,
)
.await
.unwrap();
let table_name = "varietals";
let request = CreateTableRequest {
name: table_name.into(),
namespace: namespace.name.clone(),
partition_template: None,
};
let created_table = handler
.create_table(Request::new(request))
.await
.unwrap()
.into_inner()
.table
.unwrap();
assert!(created_table.id > 0);
assert_eq!(created_table.name, table_name);
assert_eq!(created_table.namespace_id, namespace.id.get());
let table_columns = catalog
.repositories()
.await
.columns()
.list_by_table_id(TableId::new(created_table.id))
.await
.unwrap();
assert_eq!(table_columns.len(), 2);
assert!(table_columns.iter().all(|c| c.is_tag()));
let mut column_names: Vec<_> = table_columns.iter().map(|c| &c.name).collect();
column_names.sort();
assert_eq!(column_names, &["color", "tannins"])
}
#[tokio::test]
async fn invalid_custom_table_template_returns_error() {
let catalog: Arc<dyn Catalog> =
Arc::new(MemCatalog::new(Arc::new(metric::Registry::default())));
let handler = TableService::new(Arc::clone(&catalog));
let namespace = arbitrary_namespace(&mut *catalog.repositories().await, "grapes").await;
let table_name = "varietals";
let request = CreateTableRequest {
name: table_name.into(),
namespace: namespace.name.clone(),
partition_template: Some(PartitionTemplate { parts: vec![] }),
};
let error = handler
.create_table(Request::new(request))
.await
.unwrap_err();
assert_eq!(error.code(), Code::InvalidArgument);
assert_eq!(
error.message(),
"Custom partition template must have at least one part"
);
let all_tables = catalog.repositories().await.tables().list().await.unwrap();
assert!(all_tables.is_empty());
}
}
|
#![no_std]
#[macro_use]
extern crate crypto_tests;
extern crate kuznyechik;
use crypto_tests::block_cipher::{BlockCipherTest, encrypt_decrypt};
#[test]
fn kuznyechik() {
let tests = new_block_cipher_tests!("1");
encrypt_decrypt::<kuznyechik::Kuznyechik>(&tests);
}
|
// 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.
use std::str::FromStr;
use common_exception::ErrorCode;
use common_exception::Result;
use sha2::Digest;
use sha2::Sha256;
const NO_PASSWORD_STR: &str = "no_password";
const SHA256_PASSWORD_STR: &str = "sha256_password";
const DOUBLE_SHA1_PASSWORD_STR: &str = "double_sha1_password";
const JWT_AUTH_STR: &str = "jwt";
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Eq, PartialEq)]
pub enum AuthType {
NoPassword,
Sha256Password,
DoubleSha1Password,
JWT,
}
impl std::str::FromStr for AuthType {
type Err = ErrorCode;
fn from_str(s: &str) -> Result<Self> {
match s {
SHA256_PASSWORD_STR => Ok(AuthType::Sha256Password),
DOUBLE_SHA1_PASSWORD_STR => Ok(AuthType::DoubleSha1Password),
NO_PASSWORD_STR => Ok(AuthType::NoPassword),
JWT_AUTH_STR => Ok(AuthType::JWT),
_ => Err(ErrorCode::InvalidAuthInfo(AuthType::bad_auth_types(s))),
}
}
}
impl AuthType {
pub fn to_str(&self) -> &str {
match self {
AuthType::NoPassword => NO_PASSWORD_STR,
AuthType::Sha256Password => SHA256_PASSWORD_STR,
AuthType::DoubleSha1Password => DOUBLE_SHA1_PASSWORD_STR,
AuthType::JWT => JWT_AUTH_STR,
}
}
fn bad_auth_types(s: &str) -> String {
let all = vec![
NO_PASSWORD_STR,
SHA256_PASSWORD_STR,
DOUBLE_SHA1_PASSWORD_STR,
JWT_AUTH_STR,
];
let all = all
.iter()
.map(|s| format!("'{}'", s))
.collect::<Vec<_>>()
.join("|");
format!("Expected auth type {}, found: {}", all, s)
}
pub fn get_password_type(self) -> Option<PasswordHashMethod> {
match self {
AuthType::Sha256Password => Some(PasswordHashMethod::Sha256),
AuthType::DoubleSha1Password => Some(PasswordHashMethod::DoubleSha1),
_ => None,
}
}
}
#[derive(
serde::Serialize, serde::Deserialize, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Default,
)]
pub enum AuthInfo {
#[default]
None,
Password {
hash_value: Vec<u8>,
hash_method: PasswordHashMethod,
},
JWT,
}
fn calc_sha1(v: &[u8]) -> [u8; 20] {
let mut m = ::sha1::Sha1::new();
m.update(v);
m.finalize().into()
}
fn double_sha1(v: &[u8]) -> [u8; 20] {
calc_sha1(&calc_sha1(v)[..])
}
impl AuthInfo {
pub fn new(auth_type: AuthType, auth_string: &Option<String>) -> Result<AuthInfo> {
match auth_type {
AuthType::NoPassword => Ok(AuthInfo::None),
AuthType::JWT => Ok(AuthInfo::JWT),
AuthType::Sha256Password | AuthType::DoubleSha1Password => match auth_string {
Some(p) => {
let method = auth_type.get_password_type().unwrap();
Ok(AuthInfo::Password {
hash_value: method.hash(p.as_bytes()),
hash_method: method,
})
}
None => Err(ErrorCode::InvalidAuthInfo("need password".to_string())),
},
}
}
pub fn create(auth_type: &Option<String>, auth_string: &Option<String>) -> Result<AuthInfo> {
let default = AuthType::DoubleSha1Password;
let auth_type = auth_type
.clone()
.map(|s| AuthType::from_str(&s))
.transpose()?
.unwrap_or(default);
AuthInfo::new(auth_type, auth_string)
}
pub fn create2(auth_type: &Option<AuthType>, auth_string: &Option<String>) -> Result<AuthInfo> {
let default = AuthType::DoubleSha1Password;
let auth_type = auth_type.clone().unwrap_or(default);
AuthInfo::new(auth_type, auth_string)
}
pub fn alter(
&self,
auth_type: &Option<String>,
auth_string: &Option<String>,
) -> Result<AuthInfo> {
let old_auth_type = self.get_type();
let new_auth_type = auth_type
.clone()
.map(|s| AuthType::from_str(&s))
.transpose()?
.unwrap_or(old_auth_type);
AuthInfo::new(new_auth_type, auth_string)
}
pub fn alter2(
&self,
auth_type: &Option<AuthType>,
auth_string: &Option<String>,
) -> Result<AuthInfo> {
let old_auth_type = self.get_type();
let new_auth_type = auth_type.clone().unwrap_or(old_auth_type);
AuthInfo::new(new_auth_type, auth_string)
}
pub fn get_type(&self) -> AuthType {
match self {
AuthInfo::None => AuthType::NoPassword,
AuthInfo::JWT => AuthType::JWT,
AuthInfo::Password {
hash_value: _,
hash_method: t,
} => match t {
PasswordHashMethod::Sha256 => AuthType::Sha256Password,
PasswordHashMethod::DoubleSha1 => AuthType::DoubleSha1Password,
},
}
}
pub fn get_auth_string(&self) -> String {
match self {
AuthInfo::Password {
hash_value: p,
hash_method: t,
} => t.to_string(p),
AuthInfo::None | AuthInfo::JWT => "".to_string(),
}
}
pub fn get_password(&self) -> Option<Vec<u8>> {
match self {
AuthInfo::Password {
hash_value: p,
hash_method: _,
} => Some(p.to_vec()),
_ => None,
}
}
pub fn get_password_type(&self) -> Option<PasswordHashMethod> {
match self {
AuthInfo::Password {
hash_value: _,
hash_method: t,
} => Some(*t),
_ => None,
}
}
fn restore_sha1_mysql(salt: &[u8], input: &[u8], user_password_hash: &[u8]) -> Result<Vec<u8>> {
// SHA1( password ) XOR SHA1( "20-bytes random data from server" <concat> SHA1( SHA1( password ) ) )
let mut m = sha1::Sha1::new();
m.update(salt);
m.update(user_password_hash);
let result: [u8; 20] = m.finalize().into();
if input.len() != result.len() {
return Err(ErrorCode::SHA1CheckFailed("SHA1 check failed"));
}
let mut s = Vec::with_capacity(result.len());
for i in 0..result.len() {
s.push(input[i] ^ result[i]);
}
Ok(s)
}
pub fn auth_mysql(&self, password_input: &[u8], salt: &[u8]) -> Result<bool> {
match self {
AuthInfo::None => Ok(true),
AuthInfo::Password {
hash_value: p,
hash_method: t,
} => match t {
PasswordHashMethod::DoubleSha1 => {
let password_sha1 = AuthInfo::restore_sha1_mysql(salt, password_input, p)?;
Ok(*p == calc_sha1(&password_sha1))
}
PasswordHashMethod::Sha256 => Err(ErrorCode::AuthenticateFailure(
"login with sha256_password user for mysql protocol not supported yet.",
)),
},
_ => Err(ErrorCode::AuthenticateFailure(format!(
"user require auth type {}",
self.get_type().to_str()
))),
}
}
}
#[derive(
serde::Serialize,
serde::Deserialize,
Clone,
Copy,
Debug,
Eq,
PartialEq,
Ord,
PartialOrd,
num_derive::FromPrimitive,
Default,
)]
pub enum PasswordHashMethod {
DoubleSha1 = 1,
#[default]
Sha256 = 2,
}
impl PasswordHashMethod {
pub fn hash(self, user_input: &[u8]) -> Vec<u8> {
match self {
PasswordHashMethod::DoubleSha1 => double_sha1(user_input).to_vec(),
PasswordHashMethod::Sha256 => Sha256::digest(user_input).to_vec(),
}
}
fn to_string(self, hash_value: &[u8]) -> String {
hex::encode(hash_value)
}
}
|
use std::process::Command;
fn main() {
let mut child = Command::new("sleep").arg("4").spawn().unwrap();
let _result = child.wait().unwrap();
println!("reached end of first batch");
let mut child2 = Command::new("sleep").arg("4").spawn().unwrap();
let _result2 = child2.wait().unwrap();
println!("reached end of main");
}
|
fn main() {
let program: Vec<&str> = include_str!("./input.txt").lines().collect();
run_program(program[0]);
}
fn run_program(program: &str) -> isize {
let mut positions: Vec<isize> = program.split(",").map(|x| x.parse().unwrap()).collect();
let mut instruction_ptr = 0;
while instruction_ptr < positions.len() {
let instruction = positions[instruction_ptr];
let opcode = parse_opcode(instruction);
match opcode.op {
Op::Add => {
let param1 = get_param_value(opcode.param1, positions[instruction_ptr+1], &positions);
let param2 = get_param_value(opcode.param2, positions[instruction_ptr+2], &positions);
let param3 = positions[instruction_ptr+3];
positions[param3 as usize] = param1 + param2;
instruction_ptr += 4;
},
Op::Multiply => {
let param1 = get_param_value(opcode.param1, positions[instruction_ptr+1], &positions);
let param2 = get_param_value(opcode.param2, positions[instruction_ptr+2], &positions);
let param3 = positions[instruction_ptr+3];
positions[param3 as usize] = param1 * param2;
instruction_ptr += 4;
},
Op::Input => {
let param1 = positions[instruction_ptr+1];
let input = 5;
println!("Input: {}", input);
positions[param1 as usize] = input;
instruction_ptr += 2;
},
Op::Print => {
let param1 = get_param_value(opcode.param1, positions[instruction_ptr+1], &positions);
println!("Print: {}", param1);
instruction_ptr += 2;
},
Op::JumpTrue => {
let param1 = get_param_value(opcode.param1, positions[instruction_ptr+1], &positions);
let param2 = get_param_value(opcode.param2, positions[instruction_ptr+2], &positions);
if param1 > 0 {
instruction_ptr = param2 as usize;
} else {
instruction_ptr += 3;
}
},
Op::JumpFalse => {
let param1 = get_param_value(opcode.param1, positions[instruction_ptr+1], &positions);
let param2 = get_param_value(opcode.param2, positions[instruction_ptr+2], &positions);
if param1 == 0 {
instruction_ptr = param2 as usize;
} else {
instruction_ptr += 3;
}
},
Op::LessThan => {
let param1 = get_param_value(opcode.param1, positions[instruction_ptr+1], &positions);
let param2 = get_param_value(opcode.param2, positions[instruction_ptr+2], &positions);
let param3 = positions[instruction_ptr+3] as usize;
if param1 < param2 {
positions[param3] = 1;
} else {
positions[param3] = 0;
}
instruction_ptr += 4;
},
Op::GreaterThan => {
let param1 = get_param_value(opcode.param1, positions[instruction_ptr+1], &positions);
let param2 = get_param_value(opcode.param2, positions[instruction_ptr+2], &positions);
let param3 = positions[instruction_ptr+3] as usize;
if param1 == param2 {
positions[param3] = 1;
} else {
positions[param3] = 0;
}
instruction_ptr += 4;
},
Op::Halt => {
println!("done");
break;
}
}
}
positions[0]
}
#[derive(Debug)]
enum Op {
Add = 1,
Multiply = 2,
Input = 3,
Print = 4,
JumpTrue = 5,
JumpFalse= 6,
LessThan = 7,
GreaterThan = 8,
Halt = 99
}
#[derive(Debug)]
enum ParamMode { Position = 0, Immediate = 1 }
#[derive(Debug)]
struct Opcode {
op: Op,
param1: ParamMode,
param2: ParamMode,
param3: ParamMode,
}
fn parse_opcode(opcode: isize) -> Opcode {
let mut operation = Opcode { op: Op::Halt, param1: ParamMode::Position, param2: ParamMode::Position, param3: ParamMode::Position};
let digits: Vec<u32> = opcode.to_string().chars().map(|x| x.to_digit(10).unwrap()).collect();
let fill_amount = 5 - digits.len();
let filler = vec![0;fill_amount];
let codes = [filler, digits].concat();
operation.op = parse_op(codes[3], codes[4]);
operation.param1 = parse_param(codes[2]);
operation.param2 = parse_param(codes[1]);
operation.param3 = parse_param(codes[0]);
operation
}
fn parse_op(d1: u32, d2: u32) -> Op {
let code = (d1 * 10) + d2;
return match code {
1 => Op::Add,
2 => Op::Multiply,
3 => Op::Input,
4 => Op::Print,
5 => Op::JumpTrue,
6 => Op::JumpFalse,
7 => Op::LessThan,
8 => Op::GreaterThan,
99 => Op::Halt,
_ => panic!("Uknown")
}
}
fn parse_param(param: u32) -> ParamMode {
return match param {
0 => ParamMode::Position,
1 => ParamMode::Immediate,
_ => panic!("Uknown")
}
}
fn get_param_value(param: ParamMode, value: isize, positions: &Vec<isize>) -> isize {
return match param {
ParamMode::Position => positions[value as usize],
ParamMode::Immediate => value
}
}
|
//! Asynchronous ARDOP TNC Interface
use std::convert::Into;
use std::fmt;
use std::net::SocketAddr;
use std::string::String;
use std::sync::Arc;
use std::time::Duration;
use async_std::prelude::FutureExt;
use futures::lock::Mutex;
use super::{DiscoveredPeer, PingAck, PingFailedReason, TncResult};
use crate::arq::{ArqStream, ConnectionFailedReason};
use crate::protocol::command;
use crate::protocol::command::Command;
use crate::tncio::asynctnc::{AsyncTncTcp, ConnectionInfoOrPeerDiscovery};
/// TNC Interface
///
/// See the [module-level](index.html) documentation
/// for examples and usage details.
pub struct ArdopTnc {
inner: Arc<Mutex<AsyncTncTcp>>,
mycall: String,
clear_time: Duration,
clear_max_wait: Duration,
}
/// Result of [`ArdopTnc::listen_monitor()`](../tnc/struct.ArdopTnc.html#method.listen_monitor)
///
/// This value indicates either the
/// * completion of an inbound ARQ connection; or
/// * discovery of a remote peer, via its transmissions
pub enum ListenMonitor {
/// ARQ Connection
Connection(ArqStream),
/// Heard callsign
PeerDiscovery(DiscoveredPeer),
}
impl ArdopTnc {
/// Connect to an ARDOP TNC
///
/// Returns a future which will connect to an ARDOP TNC
/// and initialize it.
///
/// # Parameters
/// - `addr`: Network address of the ARDOP TNC's control port.
/// - `mycall`: The formally-assigned callsign for your station.
/// Legitimate call signs include from 3 to 7 ASCII characters
/// (A-Z, 0-9) followed by an optional "`-`" and an SSID of
/// `-0` to `-15` or `-A` to `-Z`. An SSID of `-0` is treated
/// as no SSID.
///
/// # Returns
/// A new `ArdopTnc`, or an error if the connection or
/// initialization step fails.
pub async fn new<S>(addr: &SocketAddr, mycall: S) -> TncResult<Self>
where
S: Into<String>,
{
let mycall = mycall.into();
let mycall2 = mycall.clone();
let tnc = AsyncTncTcp::new(addr, mycall2).await?;
let inner = Arc::new(Mutex::new(tnc));
Ok(ArdopTnc {
inner,
mycall,
clear_time: DEFAULT_CLEAR_TIME,
clear_max_wait: DEFAULT_CLEAR_MAX_WAIT,
})
}
/// Get this station's callsign
///
/// # Returns
/// The formally assigned callsign for this station.
pub fn mycall(&self) -> &String {
&self.mycall
}
/// Returns configured clear time
///
/// The *clear time* is the duration that the RF channel must
/// be sensed as clear before an outgoing transmission will be
/// allowed to proceed.
///
/// See [`set_clear_time()`](#method.set_clear_time).
pub fn clear_time(&self) -> &Duration {
&self.clear_time
}
/// Returns configured maximum clear waiting time
///
/// Caps the maximum amount of time that a transmitting
/// Future, such as [`connect()`](#method.connect) or
/// [`ping()`](#method.ping), will spend waiting for the
/// channel to become clear.
///
/// If the channel does not become clear within this
/// Duration, then a `TimedOut` error is raised.
///
/// See [`set_clear_max_wait()`](#method.set_clear_max_wait).
pub fn clear_max_wait(&self) -> &Duration {
&self.clear_max_wait
}
/// Returns configured clear time
///
/// The *clear time* is the duration that the RF channel must
/// be sensed as clear before an outgoing transmission will be
/// allowed to proceed.
///
/// You should **ALWAYS** allow the busy-detection logic ample
/// time to declare that the channel is clear of any other
/// communications. The busy detector's sensitivity may be adjusted
/// via [`set_busydet()`](#method.set_busydet) if it is too sensitive
/// for your RF environment.
///
/// If you need to send a *DISTRESS* or *EMERGENCY* signal, you may
/// set `tm` to zero to disable the busy-detection logic entirely.
///
/// # Parameters
/// - `tm`: New clear time.
pub fn set_clear_time(&mut self, tm: Duration) {
self.clear_time = tm;
}
/// Returns configured maximum clear waiting time
///
/// Caps the maximum amount of time that a transmitting
/// Future, such as [`connect()`](#method.connect) or
/// [`ping()`](#method.ping), will spend waiting for the
/// channel to become clear.
///
/// If the channel does not become clear within this
/// Duration, then a `TimedOut` error is raised.
///
/// # Parameters
/// - `tm`: New timeout for clear-channel waiting. `tm`
/// must be at least the
/// [`clear_time()`](#method.clear_time).
pub fn set_clear_max_wait(&mut self, tm: Duration) {
self.clear_max_wait = tm;
}
/// Ping a remote `target` peer
///
/// When run, this future will
///
/// 1. Wait for a clear channel
/// 2. Send an outgoing `PING` request
/// 3. Wait for a reply or for the ping timeout to elapse
/// 4. Complete with the ping result
///
/// # Parameters
/// - `target`: Peer callsign, with optional `-SSID` portion
/// - `attempts`: Number of ping packets to send before
/// giving up
///
/// # Return
/// The outer result contains failures related to the local
/// TNC connection.
///
/// The inner result is the success or failure of the round-trip
/// ping. If the ping succeeds, returns an `Ok(PingAck)`
/// with the response from the remote peer. If the ping fails,
/// returns `Err(PingFailedReason)`. Errors include:
///
/// * `Busy`: The RF channel was busy during the ping attempt,
/// and no ping was sent.
/// * `NoAnswer`: The remote peer did not answer.
pub async fn ping<S>(
&mut self,
target: S,
attempts: u16,
) -> TncResult<Result<PingAck, PingFailedReason>>
where
S: Into<String>,
{
let mut tnc = self.inner.lock().await;
tnc.ping(
target,
attempts,
self.clear_time.clone(),
self.clear_max_wait.clone(),
)
.await
}
/// Dial a remote `target` peer
///
/// When run, this future will
///
/// 1. Wait for a clear channel.
/// 2. Make an outgoing `ARQCALL` to the designated callsign
/// 3. Wait for a connection to either complete or fail
/// 4. Successful connections will return an
/// [`ArqStream`](../arq/struct.ArqStream.html).
///
/// # Parameters
/// - `target`: Peer callsign, with optional `-SSID` portion
/// - `bw`: ARQ bandwidth to use
/// - `bw_forced`: If false, will potentially negotiate for a
/// *lower* bandwidth than `bw` with the remote peer. If
/// true, the connection will be made at `bw` rate---or not
/// at all.
/// - `attempts`: Number of connection attempts to make
/// before giving up
///
/// # Return
/// The outer result contains failures related to the local
/// TNC connection.
///
/// The inner result contains failures related to the RF
/// connection. If the connection attempt succeeds, returns
/// a new [`ArqStream`](../arq/struct.ArqStream.html) that
/// can be used like an asynchronous `TcpStream`.
pub async fn connect<S>(
&mut self,
target: S,
bw: u16,
bw_forced: bool,
attempts: u16,
) -> TncResult<Result<ArqStream, ConnectionFailedReason>>
where
S: Into<String>,
{
let mut tnc = self.inner.lock().await;
match tnc
.connect(
target,
bw,
bw_forced,
attempts,
self.clear_time.clone(),
self.clear_max_wait.clone(),
)
.await?
{
Ok(nfo) => Ok(Ok(ArqStream::new(self.inner.clone(), nfo))),
Err(e) => Ok(Err(e)),
}
}
/// Listen for incoming connections
///
/// When run, this future will wait for the TNC to accept
/// an incoming connection to `MYCALL` or one of `MYAUX`.
/// When a connection is accepted, the future will resolve
/// to an [`ArqStream`](../arq/struct.ArqStream.html).
///
/// # Parameters
/// - `bw`: Maximum ARQ bandwidth to use
/// - `bw_forced`: If false, will potentially negotiate for a
/// *lower* bandwidth than `bw` with the remote peer. If
/// true, the connection will be made at `bw` rate---or not
/// at all.
/// - `timeout`: Return a `TimedOut` error if no incoming
/// connection is received within the `timeout`. A timeout of
/// "zero" will wait forever.
///
/// # Return
/// The result contains failures related to the local TNC
/// connection.
///
/// Connections which fail during the setup phase
/// will not be reported to the application. Unless the local
/// TNC fails, or the timeout elapses, this method will not fail.
///
/// An expired timeout will return a
/// [`TncError::TimedOut`](enum.TncError.html#variant.TimedOut).
pub async fn listen(
&mut self,
bw: u16,
bw_forced: bool,
timeout: Duration,
) -> TncResult<ArqStream> {
let mut tnc = self.inner.lock().await;
let nfo = if timeout > Duration::from_nanos(0) {
tnc.listen(bw, bw_forced).timeout(timeout).await??
} else {
tnc.listen(bw, bw_forced).await?
};
Ok(ArqStream::new(self.inner.clone(), nfo))
}
/// Passively monitor for band activity
///
/// When run, the TNC will listen passively for peers which
/// announce themselves via:
///
/// * ID Frames (`IDF`)
/// * Pings
///
/// The TNC has no memory of discovered stations and will
/// return a result every time it hears one.
///
/// # Parameters
/// - `timeout`: Return a `TimedOut` error if no activity is
/// detected within the `timeout`. A timeout of
/// "zero" will wait forever.
///
/// # Return
/// The result contains failures related to the local TNC
/// connection.
///
/// Unless the local TNC fails, or the timeout elapses, this method
/// will not fail. If a peer is discovered, a
/// [`DiscoveredPeer`](struct.DiscoveredPeer.html)
/// is returned.
pub async fn monitor(&mut self, timeout: Duration) -> TncResult<DiscoveredPeer> {
let mut tnc = self.inner.lock().await;
if timeout > Duration::from_nanos(0) {
tnc.monitor().timeout(timeout).await?
} else {
tnc.monitor().await
}
}
/// Listen for incoming connections or for band activity
///
/// This method combines [`listen()`](#method.listen) and
/// [`monitor()`](#method.monitor). The TNC will listen for
/// the next inbound ARQ connection OR for band activity and
/// return the first it finds.
///
/// The incoming connection may be directed at either `MYCALL`
/// or any of `MYAUX`.
///
/// Band activity will be reported from any available source.
/// At present, these sources are available:
///
/// * ID Frames
/// * Ping requests
///
/// # Parameters
/// - `bw`: Maximum ARQ bandwidth to use. Only applies to
/// incoming connections—not peer discoveries.
/// - `bw_forced`: If false, will potentially negotiate for a
/// *lower* bandwidth than `bw` with the remote peer. If
/// true, the connection will be made at `bw` rate---or not
/// at all.
/// - `timeout`: Return a `TimedOut` error if no activity or
/// connection is detected within the `timeout`. A timeout of
/// "zero" will wait forever.
///
/// # Return
/// The result contains failures related to the local TNC
/// connection. The result will also error if the timeout
/// expires.
///
/// Connections which fail during the setup phase
/// will not be reported to the application.
pub async fn listen_monitor(
&mut self,
bw: u16,
bw_forced: bool,
timeout: Duration,
) -> TncResult<ListenMonitor> {
let mut tnc = self.inner.lock().await;
let res = if timeout > Duration::from_nanos(0) {
tnc.listen_monitor(bw, bw_forced).timeout(timeout).await??
} else {
tnc.listen_monitor(bw, bw_forced).await?
};
match res {
ConnectionInfoOrPeerDiscovery::Connection(nfo) => Ok(ListenMonitor::Connection(
ArqStream::new(self.inner.clone(), nfo),
)),
ConnectionInfoOrPeerDiscovery::PeerDiscovery(peer) => {
Ok(ListenMonitor::PeerDiscovery(peer))
}
}
}
/// Send ID frame
///
/// Sends an ID frame immediately, followed by a CW ID
/// (if `ArdopTnc::set_cwid()` is set)
///
/// Completion of this future does not indicate that the
/// ID frame has actually been completely transmitted.
///
/// # Return
/// An empty if an ID frame was/will be sent, or some `TncError`
/// if an ID frame will not be sent.
pub async fn sendid(&mut self) -> TncResult<()> {
self.command(command::sendid()).await?;
info!("Transmitting ID frame: {}", self.mycall);
Ok(())
}
/// Start a two-tone test
///
/// Send 5 second two-tone burst, at the normal leader
/// amplitude. May be used in adjusting drive level to
/// the radio.
///
/// Completion of this future does not indicate that the
/// two-tone test has actually been completed.
///
/// # Return
/// An empty if an two-tone test sequence be sent, or some
/// `TncError` if the test cannot be performed.
pub async fn twotonetest(&mut self) -> TncResult<()> {
self.command(command::twotonetest()).await?;
info!("Transmitting two-tone test");
Ok(())
}
/// Set ARQ connection timeout
///
/// Set the ARQ Timeout in seconds. If no data has flowed in the
/// channel in `timeout` seconds, the link is declared dead. A `DISC`
/// command is sent and a reset to the `DISC` state is initiated.
///
/// If either end of the ARQ session hits it’s `ARQTIMEOUT` without
/// data flow the link will automatically be terminated.
///
/// # Parameters
/// - `timeout`: ARQ timeout period, in seconds (30 -- 600)
///
/// # Return
/// An empty on success or a `TncError` if the command could not
/// be completed for any reason, including timeouts.
pub async fn set_arqtimeout(&mut self, timeout: u16) -> TncResult<()> {
self.command(command::arqtimeout(timeout)).await
}
/// Busy detector threshold value
///
/// Sets the current Busy detector threshold value (default = 5). The
/// default value should be sufficient for most installations. Lower
/// values will make the busy detector more sensitive; the channel will
/// be declared busy *more frequently*. Higher values may be used for
/// high-noise environments.
///
/// # Parameters
/// - `level`: Busy detector threshold (0 -- 10). A value of 0 will disable
/// the busy detector (not recommended).
///
/// # Return
/// An empty on success or a `TncError` if the command could not
/// be completed for any reason, including timeouts.
pub async fn set_busydet(&mut self, level: u16) -> TncResult<()> {
self.command(command::busydet(level)).await
}
/// Send CW after ID frames
///
/// Set to true to send your callsign in morse code (CW), as station ID,
/// at the end of every ID frame. In many regions, a CW ID is always
/// sufficient to meet station ID requirements. Some regions may
/// require it.
///
/// # Parameters
/// - `cw`: Send CW ID with ARDOP digital ID frames
///
/// # Return
/// An empty on success or a `TncError` if the command could not
/// be completed for any reason, including timeouts.
pub async fn set_cwid(&mut self, set_cwid: bool) -> TncResult<()> {
self.command(command::cwid(set_cwid)).await
}
/// Set your station's grid square
///
/// Sets the 4, 6, or 8-character Maidenhead Grid Square for your
/// station. A correct grid square is useful for studying and
/// logging RF propagation-and for bragging rights.
///
/// Your grid square will be sent in ID frames.
///
/// # Parameters
/// - `grid`: Your grid square (4, 6, or 8-characters).
///
/// # Return
/// An empty on success or a `TncError` if the command could not
/// be completed for any reason, including timeouts.
pub async fn set_gridsquare<S>(&mut self, grid: S) -> TncResult<()>
where
S: Into<String>,
{
self.command(command::gridsquare(grid)).await
}
/// Leader tone duration
///
/// Sets the leader length in ms. (Default is 160 ms). Rounded to
/// the nearest 20 ms. Note for VOX keying or some SDR radios the
/// leader may have to be extended for reliable decoding.
///
/// # Parameters
/// - `duration`: Leader tone duration, milliseconds
///
/// # Return
/// An empty on success or a `TncError` if the command could not
/// be completed for any reason, including timeouts.
pub async fn set_leader(&mut self, duration: u16) -> TncResult<()> {
self.command(command::leader(duration)).await
}
/// Set your station's auxiliary callsigns
///
/// `MYAUX` is only used for `LISTEN`ing, and it will not be used for
/// connect requests.
///
/// Legitimate call signs include from 3 to 7 ASCII characters (A-Z, 0-9)
/// followed by an optional "`-`" and an SSID of `-0` to `-15` or `-A`
/// to `-Z`. An SSID of `-0` is treated as no SSID.
///
/// # Parameters:
/// - `aux`: Vector of auxiliary callsigns. If empty, all aux callsigns
/// will be removed.
///
/// # Return
/// An empty on success or a `TncError` if the command could not
/// be completed for any reason, including timeouts.
pub async fn set_myaux(&mut self, aux: Vec<String>) -> TncResult<()> {
self.command(command::myaux(aux)).await
}
/// Query TNC version
///
/// Queries the ARDOP TNC software for its version number.
/// The format of the version number is unspecified and may
/// be empty.
///
/// # Return
/// Version string, or an error if the version string could
/// not be retrieved.
pub async fn version(&mut self) -> TncResult<String> {
let mut tnc = self.inner.lock().await;
tnc.version().await
}
/// Gets the control connection timeout value
///
/// Commands sent via the `command()` method will
/// timeout if either the send or receive takes
/// longer than `timeout`.
///
/// Timeouts cause `TncError::IoError`s of kind
/// `io::ErrorKind::TimedOut`. Control timeouts
/// usually indicate a serious problem with the ARDOP
/// TNC or its connection.
///
/// # Returns
/// Current timeout value
pub async fn control_timeout(&self) -> Duration {
self.inner.lock().await.control_timeout().clone()
}
/// Sets timeout for the control connection
///
/// Commands sent via the `command()` method will
/// timeout if either the send or receive takes
/// longer than `timeout`.
///
/// Timeouts cause `TncError::IoError`s of kind
/// `io::ErrorKind::TimedOut`. Control timeouts
/// usually indicate a serious problem with the ARDOP
/// TNC or its connection.
///
/// # Parameters
/// - `timeout`: New command timeout value
pub async fn set_control_timeout(&mut self, timeout: Duration) {
let mut tnc = self.inner.lock().await;
tnc.set_control_timeout(timeout)
}
// Send a command to the TNC and await the response
//
// A future which will send the given command and wait
// for a success or failure response. The waiting time
// is upper-bounded by AsyncTnc's `control_timeout()`
// value.
//
// # Parameters
// - `cmd`: The Command to send
//
// # Returns
// An empty on success or a `TncError`.
async fn command<F>(&mut self, cmd: Command<F>) -> TncResult<()>
where
F: fmt::Display,
{
let mut tnc = self.inner.lock().await;
tnc.command(cmd).await
}
}
const DEFAULT_CLEAR_TIME: Duration = Duration::from_secs(10);
const DEFAULT_CLEAR_MAX_WAIT: Duration = Duration::from_secs(90);
|
#[doc = "Reader of register SR"]
pub type R = crate::R<u32, super::SR>;
#[doc = "Writer for register SR"]
pub type W = crate::W<u32, super::SR>;
#[doc = "Register SR `reset()`'s with value 0"]
impl crate::ResetValue for super::SR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Capture/compare 2 overcapture flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CC2OF_A {
#[doc = "1: The counter value has been captured in TIMx_CCRx register while CCxIF flag was already set"]
OVERCAPTURE = 1,
}
impl From<CC2OF_A> for bool {
#[inline(always)]
fn from(variant: CC2OF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `CC2OF`"]
pub type CC2OF_R = crate::R<bool, CC2OF_A>;
impl CC2OF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<bool, CC2OF_A> {
use crate::Variant::*;
match self.bits {
true => Val(CC2OF_A::OVERCAPTURE),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `OVERCAPTURE`"]
#[inline(always)]
pub fn is_overcapture(&self) -> bool {
*self == CC2OF_A::OVERCAPTURE
}
}
#[doc = "Capture/compare 2 overcapture flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CC2OF_AW {
#[doc = "0: Clear flag"]
CLEAR = 0,
}
impl From<CC2OF_AW> for bool {
#[inline(always)]
fn from(variant: CC2OF_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `CC2OF`"]
pub struct CC2OF_W<'a> {
w: &'a mut W,
}
impl<'a> CC2OF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CC2OF_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clear flag"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(CC2OF_AW::CLEAR)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Capture/Compare 1 overcapture flag"]
pub type CC1OF_A = CC2OF_A;
#[doc = "Reader of field `CC1OF`"]
pub type CC1OF_R = crate::R<bool, CC2OF_A>;
#[doc = "Capture/Compare 1 overcapture flag"]
pub type CC1OF_AW = CC2OF_AW;
#[doc = "Write proxy for field `CC1OF`"]
pub struct CC1OF_W<'a> {
w: &'a mut W,
}
impl<'a> CC1OF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CC1OF_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clear flag"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(CC2OF_AW::CLEAR)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Trigger interrupt flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TIF_A {
#[doc = "0: No trigger event occurred"]
NOTRIGGER = 0,
#[doc = "1: Trigger interrupt pending"]
TRIGGER = 1,
}
impl From<TIF_A> for bool {
#[inline(always)]
fn from(variant: TIF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TIF`"]
pub type TIF_R = crate::R<bool, TIF_A>;
impl TIF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TIF_A {
match self.bits {
false => TIF_A::NOTRIGGER,
true => TIF_A::TRIGGER,
}
}
#[doc = "Checks if the value of the field is `NOTRIGGER`"]
#[inline(always)]
pub fn is_no_trigger(&self) -> bool {
*self == TIF_A::NOTRIGGER
}
#[doc = "Checks if the value of the field is `TRIGGER`"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == TIF_A::TRIGGER
}
}
#[doc = "Trigger interrupt flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TIF_AW {
#[doc = "0: Clear flag"]
CLEAR = 0,
}
impl From<TIF_AW> for bool {
#[inline(always)]
fn from(variant: TIF_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `TIF`"]
pub struct TIF_W<'a> {
w: &'a mut W,
}
impl<'a> TIF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIF_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clear flag"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(TIF_AW::CLEAR)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Capture/Compare 2 interrupt flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CC2IF_A {
#[doc = "1: If CC1 is an output: The content of the counter TIMx_CNT matches the content of the TIMx_CCR1 register. If CC1 is an input: The counter value has been captured in TIMx_CCR1 register."]
MATCH = 1,
}
impl From<CC2IF_A> for bool {
#[inline(always)]
fn from(variant: CC2IF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `CC2IF`"]
pub type CC2IF_R = crate::R<bool, CC2IF_A>;
impl CC2IF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<bool, CC2IF_A> {
use crate::Variant::*;
match self.bits {
true => Val(CC2IF_A::MATCH),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `MATCH`"]
#[inline(always)]
pub fn is_match_(&self) -> bool {
*self == CC2IF_A::MATCH
}
}
#[doc = "Capture/Compare 2 interrupt flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CC2IF_AW {
#[doc = "0: Clear flag"]
CLEAR = 0,
}
impl From<CC2IF_AW> for bool {
#[inline(always)]
fn from(variant: CC2IF_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `CC2IF`"]
pub struct CC2IF_W<'a> {
w: &'a mut W,
}
impl<'a> CC2IF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CC2IF_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clear flag"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(CC2IF_AW::CLEAR)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Capture/compare 1 interrupt flag"]
pub type CC1IF_A = CC2IF_A;
#[doc = "Reader of field `CC1IF`"]
pub type CC1IF_R = crate::R<bool, CC2IF_A>;
#[doc = "Capture/compare 1 interrupt flag"]
pub type CC1IF_AW = CC2IF_AW;
#[doc = "Write proxy for field `CC1IF`"]
pub struct CC1IF_W<'a> {
w: &'a mut W,
}
impl<'a> CC1IF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CC1IF_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clear flag"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(CC2IF_AW::CLEAR)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Update interrupt flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum UIF_A {
#[doc = "0: No update occurred"]
CLEAR = 0,
#[doc = "1: Update interrupt pending."]
UPDATEPENDING = 1,
}
impl From<UIF_A> for bool {
#[inline(always)]
fn from(variant: UIF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `UIF`"]
pub type UIF_R = crate::R<bool, UIF_A>;
impl UIF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> UIF_A {
match self.bits {
false => UIF_A::CLEAR,
true => UIF_A::UPDATEPENDING,
}
}
#[doc = "Checks if the value of the field is `CLEAR`"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == UIF_A::CLEAR
}
#[doc = "Checks if the value of the field is `UPDATEPENDING`"]
#[inline(always)]
pub fn is_update_pending(&self) -> bool {
*self == UIF_A::UPDATEPENDING
}
}
#[doc = "Write proxy for field `UIF`"]
pub struct UIF_W<'a> {
w: &'a mut W,
}
impl<'a> UIF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: UIF_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "No update occurred"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(UIF_A::CLEAR)
}
#[doc = "Update interrupt pending."]
#[inline(always)]
pub fn update_pending(self) -> &'a mut W {
self.variant(UIF_A::UPDATEPENDING)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 10 - Capture/compare 2 overcapture flag"]
#[inline(always)]
pub fn cc2of(&self) -> CC2OF_R {
CC2OF_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 9 - Capture/Compare 1 overcapture flag"]
#[inline(always)]
pub fn cc1of(&self) -> CC1OF_R {
CC1OF_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 6 - Trigger interrupt flag"]
#[inline(always)]
pub fn tif(&self) -> TIF_R {
TIF_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 2 - Capture/Compare 2 interrupt flag"]
#[inline(always)]
pub fn cc2if(&self) -> CC2IF_R {
CC2IF_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1 - Capture/compare 1 interrupt flag"]
#[inline(always)]
pub fn cc1if(&self) -> CC1IF_R {
CC1IF_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0 - Update interrupt flag"]
#[inline(always)]
pub fn uif(&self) -> UIF_R {
UIF_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 10 - Capture/compare 2 overcapture flag"]
#[inline(always)]
pub fn cc2of(&mut self) -> CC2OF_W {
CC2OF_W { w: self }
}
#[doc = "Bit 9 - Capture/Compare 1 overcapture flag"]
#[inline(always)]
pub fn cc1of(&mut self) -> CC1OF_W {
CC1OF_W { w: self }
}
#[doc = "Bit 6 - Trigger interrupt flag"]
#[inline(always)]
pub fn tif(&mut self) -> TIF_W {
TIF_W { w: self }
}
#[doc = "Bit 2 - Capture/Compare 2 interrupt flag"]
#[inline(always)]
pub fn cc2if(&mut self) -> CC2IF_W {
CC2IF_W { w: self }
}
#[doc = "Bit 1 - Capture/compare 1 interrupt flag"]
#[inline(always)]
pub fn cc1if(&mut self) -> CC1IF_W {
CC1IF_W { w: self }
}
#[doc = "Bit 0 - Update interrupt flag"]
#[inline(always)]
pub fn uif(&mut self) -> UIF_W {
UIF_W { w: self }
}
}
|
extern crate std;
extern crate eventual;
extern crate cql;
use std::borrow::Cow;
use std::io::Write;
use cql::*;
use self::eventual::{Future,Async};
use std::thread;
use std::time::Duration;
use std::io::{self, Read};
#[macro_use]
macro_rules! assert_response(
($resp:expr) => (
if match $resp.opcode { cql::OpcodeResponse::OpcodeError => true, _ => false } {
panic!("Test failed at assertion: {}",
match $resp.body { cql::CqlResponseBody::ResponseError(_, message) => message, _ => Cow::Borrowed("Ooops!")});
}
);
);
macro_rules! try_test(
($call: expr, $msg: expr) => {
match $call {
Ok(val) => val,
Err(ref err) => panic!("Test failed at library call: {}", err.description())
};
}
);
pub fn to_hex_string(bytes: &Vec<u8>) -> String {
let strs: Vec<String> = bytes.iter()
.map(|b| format!("{:02X}", b))
.collect();
strs.connect(" ")
}
fn show_options(){
println!("");
println!("");
println!("Enter any option");
println!("Options: ");
println!("");
print!("\tshow info");
println!("\tShow information about the cluster");
print!("\tlatency aware");
println!("\tApply load balancing 'latency aware' policy");
print!("\tround robin");
println!("\tApply load balancing 'round robin ' policy");
print!("\tend");
println!("\t\tEnd the test");
println!("");
println!("");
}
#[test]
fn test_events() {
let ip = "172.17.0.2";
let port = "9042";
let ip_port = ip.to_string()+":"+port;
println!("Connecting to {:?}",ip_port);
let mut cluster = Cluster::new();
let mut response = try_test!(cluster.connect_cluster(ip_port.parse().ok().expect("Couldn't parse address")),
"Error connecting to cluster");
//println!("Result: {:?}", response);
//assert_response!(response);
show_options();
let mut input = read_string().unwrap();
let mut end = false;
while !end {
match input.as_str() {
"show info\n" => cluster.show_cluster_information(),
"end\n" => {
println!("Ending program..");
end = true;
},
"latency aware\n" => {
cluster.set_load_balancing(BalancerType::LatencyAware,Duration::from_secs(1));
println!("Latency aware policy applied.");
},
"round robin\n" => {
cluster.set_load_balancing(BalancerType::RoundRobin,Duration::from_secs(1));
println!("Round robin policy appield.");
},
_ => println!("Unknown option: {:?}",input),
}
if(!end){
show_options();
input = read_string().unwrap();
}
}
}
fn read_string() -> io::Result<String> {
let mut buffer = String::new();
try!(io::stdin().read_line(&mut buffer));
Ok(buffer)
}
|
fn main() {
let foo = [2, 5, 1, 2, 3, 4, 7, 7, 6];
let mut left = 0;
let mut right = foo.len() - 1;
let mut i = 0;
let mut lim = 0;
let mut sum = 0;
while i < foo.len() {
if foo[left] > foo[i] {
break;
} else {
left = i;
}
i += 1;
}
i = foo.len() - 1;
while i > 0 {
if foo[right] > foo[i] {
break;
} else {
right = i;
}
i -= 1;
}
if foo[left] < foo[right] {
lim = foo[left];
} else {
lim = foo[right];
}
for i in left..right + 1 {
if foo[i] < lim {
sum += lim - foo[i];
}
}
println!("{}", sum);
}
|
use ws::{connect, CloseCode};
use std::rc::Rc;
use std::cell::Cell;
use serde_json::{Value};
use crate::api::config::Config;
use crate::api::payment::data::*;
use crate::api::message::memo::*;
use crate::api::message::amount::Amount;
use hex;
use crate::api::message::local_sign_tx::{LocalSignTx};
use crate::base::local_sign::sign_tx::{SignTx};
use crate::base::misc::util::{
downcast_to_string,
check_address, check_secret, check_amount,
};
use crate::api::utils::cast::get_account_sequence;
pub fn request<F>(config: Config, account: String, secret: String, to: String, amount: Amount, memo: Option<String>, op: F)
where F: Fn(Result<TransactionTxResponse, PaymentSideKick>) {
if check_address(&account).is_none() {
panic!("invalid account.");
}
if check_secret(&secret).is_none() {
panic!("invalid secret");
}
if check_address(&to).is_none() {
panic!("invalid destination.");
}
// if check_amount(&amount) == false {
// panic!("invalid Amount.");
// }
let info = Rc::new(Cell::new(String::new()));
let from_rc = Rc::new(Cell::new(String::from(account.as_str())));
let secret_rc = Rc::new(Cell::new(String::from(secret.as_str())));
let to_rc = Rc::new(Cell::new(to));
let amount_rc = Rc::new(Cell::new(amount));
let memo_rc = Rc::new(Cell::new(None));
// Get Account Seq
let seq_rc = get_account_sequence(&config, account.clone());
if memo.is_some() {
let upper_hex_memo = hex::encode(&memo.unwrap()).to_ascii_uppercase();
let memos = MemosBuilder::new( upper_hex_memo ).build();
memo_rc.set(Some(vec![memos]));
}
connect(config.addr, |out| {
let copy = info.clone();
let from = from_rc.clone();
let secret = secret_rc.clone();
let to = to_rc.clone();
let amount = amount_rc.clone();
let memo = memo_rc.clone();
let sequence = seq_rc;
let tx_json = TxJson::new(from.take(), to.take(), amount.take(), sequence, memo.take());
if config.local_sign {
let blob = SignTx::with_params(sequence, &secret.take()).pay(&tx_json);
if let Ok(command) = LocalSignTx::new(blob).to_string() {
out.send(command).unwrap()
}
} else {
if let Ok(command) = TransactionTx::new(secret.take(), tx_json).to_string() {
println!("command: {:?}", command);
out.send(command).unwrap()
}
}
move |msg: ws::Message| {
let c = msg.as_text()?;
println!("msg: {:?}", c);
copy.set(c.to_string());
out.close(CloseCode::Normal)
}
}).unwrap();
let resp = downcast_to_string(info);
if let Ok(x) = serde_json::from_str(&resp) as Result<Value, serde_json::error::Error> {
if let Some(status) = x["status"].as_str() {
if status == "success" {
let x: String = x["result"].to_string();
if let Ok(v) = serde_json::from_str(&x) as Result<TransactionTxResponse, serde_json::error::Error> {
op(Ok(v))
}
} else {
if let Ok(v) = serde_json::from_str(&x.to_string()) as Result<PaymentSideKick, serde_json::error::Error> {
op(Err(v))
}
}
}
}
}
|
use std::io::prelude::*;
use std::net::TcpStream;
use std::net::TcpListener;
extern crate rust_web_server;
use rust_web_server::ThreadPool;
extern crate num_cpus;
static TEMPLATE: &[u8] = include_bytes!("../template.html");
fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
let pool = ThreadPool::new(num_cpus::get() * 2);
println!("Module path {} listening, {}", module_path!(), file!());
for stream in listener.incoming() {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream)
});
}
}
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 512];
stream.read(&mut buffer).unwrap();
let response = "HTTP/1.1 200 OK\r\n\r\n".as_bytes();
stream.write(response).unwrap();
stream.write(TEMPLATE).unwrap();
stream.flush().unwrap();
} |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "Win32_Management_MobileDeviceManagementRegistration")]
pub mod MobileDeviceManagementRegistration;
|
use num;
use num::Num;
use std::ops::Add;
use std::ops::AddAssign;
use std::ops::Div;
use std::ops::DivAssign;
use std::ops::Index;
use std::ops::IndexMut;
use std::ops::Mul;
use std::ops::MulAssign;
use std::ops::Sub;
use std::ops::SubAssign;
use crate::math;
use crate::types::{Float, Int};
use num::Integer;
use num::NumCast;
use num::One;
use num::Signed;
use num::ToPrimitive;
use num::Zero;
use std::ops::Neg;
use std::ops::Rem;
use crate::geometry::vector::Cross;
use crate::geometry::vector::Dot;
use crate::geometry::vector::Length;
use crate::types::to_float;
use crate::types::Number;
pub struct ParseVectorError;
//fn to_float<T: Copy + ToPrimitive>(x: T) -> Float {
// x.to_f64().unwrap()
//}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Vector2<T> {
pub x: T,
pub y: T,
}
impl<T> Vector2<T>
where
T: Number,
{
pub fn new(x: T, y: T) -> Self {
Vector2 { x, y }
}
pub fn is_negative(&self) -> Vector2<bool> {
Vector2 {
x: self.x < T::zero(),
y: self.y < T::zero(),
}
}
pub fn normalize(v: Self) -> Vector2<Float> {
v.normalized()
}
pub fn normalized(&self) -> Vector2<Float> {
let mul = to_float(1.0) / self.length();
Vector2 {
x: self.x.to_float() * mul,
y: self.y.to_float() * mul,
}
}
}
impl<T> Length<T> for Vector2<T>
where
T: Number,
{
fn length_squared(&self) -> T {
self.x * self.x + self.y * self.y
}
fn length(&self) -> Float {
to_float(self.length_squared()).sqrt()
}
}
impl<T: Add<Output = T>> Add for Vector2<T> {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl<T: Add<Output = T> + Copy> Add<T> for Vector2<T> {
type Output = Self;
fn add(self, other: T) -> Self {
Self {
x: self.x + other,
y: self.y + other,
}
}
}
impl<T: AddAssign + Copy> AddAssign<Self> for Vector2<T> {
fn add_assign(&mut self, other: Self) {
self.x += other.x;
self.y += other.y;
}
}
impl<T: AddAssign + Copy> AddAssign<T> for Vector2<T> {
fn add_assign(&mut self, other: T) {
self.x += other;
self.y += other;
}
}
//impl<T: Div<Output=T> + Copy> Div<T> for Vector2<T> {
// type Output = Self;
//
// fn div(self, other: T) -> Self {
// Self {
// x: self.x / other,
// y: self.y / other,
// }
// }
//}
impl<T> Div<T> for Vector2<T>
where
T: Num + ToPrimitive + Copy + Div<Output = T> + Mul<Output = T>,
{
type Output = Self;
fn div(self, rhs: T) -> Self {
let inv = (T::one() / rhs) as T;
Self {
x: self.x * inv,
y: self.y * inv,
}
}
}
impl<T> Div for Vector2<T>
where
T: Div<Output = T> + Copy,
{
type Output = Self;
fn div(self, rhs: Self) -> Self {
Self {
x: self.x / rhs.x,
y: self.y / rhs.y,
}
}
}
impl<T: DivAssign + Copy> DivAssign<T> for Vector2<T> {
fn div_assign(&mut self, other: T) {
self.x /= other;
self.y /= other;
}
}
impl<T> Dot<T> for Vector2<T>
where
T: Number,
{
fn dot(&self, other: &Self) -> T {
self.x * other.x + self.y * other.y
}
fn abs_dot(&self, other: &Self) -> T {
self.dot(other).abs()
}
}
//impl<I: Integer + Copy, F: Float + Copy> From<Vector2<I>> for Vector2<F> {
// fn from(v: Vector2<I>) -> Self {
// Self {
// x: v.x as F,
// y: v.y as F,
// }
// }
//}
impl<T> Index<i32> for Vector2<T> {
type Output = T;
fn index(&self, index: i32) -> &T {
match index {
0 => &self.x,
1 => &self.y,
_ => panic!("index out of range"),
}
}
}
impl<T> IndexMut<i32> for Vector2<T> {
fn index_mut(&mut self, index: i32) -> &mut T {
match index {
0 => &mut self.x,
1 => &mut self.y,
_ => panic!("index out of range"),
}
}
}
impl<T: Mul<Output = T> + Copy> Mul for Vector2<T> {
type Output = Self;
fn mul(self, rhs: Self) -> Self {
Self {
x: self.x * rhs.x,
y: self.y * rhs.y,
}
}
}
impl<T: Mul<Output = T> + Copy> Mul<T> for Vector2<T> {
type Output = Self;
fn mul(self, rhs: T) -> Self {
Self {
x: self.x * rhs,
y: self.y * rhs,
}
}
}
impl<T: Neg<Output = T> + Copy> Neg for Vector2<T> {
type Output = Self;
fn neg(self) -> Self {
Self {
x: self.x.neg(),
y: self.y.neg(),
}
}
}
impl<T: Num + Copy> Num for Vector2<T> {
type FromStrRadixErr = ParseVectorError;
fn from_str_radix(str: &str, radix: u32) -> Result<Self, ParseVectorError> {
Err(ParseVectorError)
}
}
impl<T: One + Copy> One for Vector2<T> {
fn one() -> Self {
Self {
x: T::one(),
y: T::one(),
}
}
}
impl<T: MulAssign + Copy> MulAssign<T> for Vector2<T> {
fn mul_assign(&mut self, rhs: T) {
self.x *= rhs;
self.y *= rhs;
}
}
impl<T: Rem<Output = T> + Copy> Rem for Vector2<T> {
type Output = Self;
fn rem(self, rhs: Self) -> Self::Output {
Self {
x: self.x % rhs.x,
y: self.y % rhs.y,
}
}
}
impl<T: Signed + Copy> Signed for Vector2<T> {
fn abs(&self) -> Self {
Self {
x: self.x.abs(),
y: self.y.abs(),
}
}
fn abs_sub(&self, other: &Self) -> Self {
Self {
x: self.x.abs_sub(&other.x),
y: self.y.abs_sub(&other.y),
}
}
fn signum(&self) -> Self {
Self {
x: self.x.signum(),
y: self.y.signum(),
}
}
fn is_positive(&self) -> bool {
self.x.is_positive() && self.y.is_positive()
}
fn is_negative(&self) -> bool {
self.x.is_negative() && self.y.is_negative()
}
}
impl<T: Sub<Output = T> + Copy> Sub<Self> for Vector2<T> {
type Output = Self;
fn sub(self, rhs: Self) -> Self {
Self {
x: self.x - rhs.x,
y: self.y - rhs.y,
}
}
}
impl<T: Sub<Output = T> + Copy> Sub<T> for Vector2<T> {
type Output = Self;
fn sub(self, rhs: T) -> Self {
Self {
x: self.x - rhs,
y: self.y - rhs,
}
}
}
impl<T: SubAssign + Copy> SubAssign<T> for Vector2<T> {
fn sub_assign(&mut self, rhs: T) {
self.x -= rhs;
self.y -= rhs;
}
}
impl<T: Zero + Copy> Zero for Vector2<T> {
fn zero() -> Self {
Self {
x: T::zero(),
y: T::zero(),
}
}
fn is_zero(&self) -> bool {
self.x.is_zero() && self.y.is_zero()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn length_squared() {
let v = Vector2::new(3, 4);
assert_eq!(v.length_squared(), 25)
}
#[test]
fn length() {
let v = Vector2::new(3, 4);
assert_eq!(v.length(), 5.0)
}
#[test]
fn add() {
assert_eq!(Vector2::new(1, 2) + Vector2::new(1, 2), Vector2::new(2, 4));
assert_eq!(Vector2::new(1, 2) + 2, Vector2::new(3, 4));
}
#[test]
fn add_assign() {
let mut v = Vector2::new(1, 2);
v += 5;
assert_eq!(v, Vector2::new(6, 7));
v += Vector2::new(1, 1);
assert_eq!(v, Vector2::new(7, 8));
}
#[test]
fn div() {
assert_eq!(Vector2::new(4.0, 8.0) / 2.0, Vector2::new(2.0, 4.0));
}
#[test]
fn div_assign() {
let mut v = Vector2::new(25, 50);
v /= 5;
assert_eq!(v, Vector2::new(5, 10));
}
#[test]
fn add_scalar() {
assert_eq!(Vector2::new(1, 2) + 5, Vector2::new(6, 7));
}
#[test]
fn index() {
let v = Vector2::new(1, 2);
assert_eq!(v[0], 1);
assert_eq!(v[1], 2);
}
#[test]
fn index_mut() {
let mut v = Vector2::new(1, 2);
let mut x = v[0];
let mut y = v[1];
x = 5;
y = 10;
assert_eq!(v[0], 1);
assert_eq!(v[1], 2);
v[0] = 3;
assert_eq!(v[0], 3);
}
#[test]
fn is_negative() {
let v = Vector2::new(-1, 1);
let is_neg = v.is_negative();
assert_eq!(is_neg.x, true);
assert_eq!(is_neg.y, false);
}
#[test]
fn mul() {
let v = Vector2::new(1, 2);
assert_eq!(v * 5, Vector2::new(5, 10));
}
#[test]
fn mul_assign() {
let mut v = Vector2::new(1, 2);
v *= 5;
assert_eq!(v, Vector2::new(5, 10));
}
#[test]
fn sub() {
let v = Vector2::new(1, 2);
assert_eq!(v - 5, Vector2::new(-4, -3));
assert_eq!(v - Vector2::new(1, 2), Vector2::new(0, 0));
}
#[test]
fn sub_assign() {
let mut v = Vector2::new(1, 2);
v -= 5;
assert_eq!(v, Vector2::new(-4, -3));
}
}
|
fn main() {
let numbers: Vec<i32> = (1..1000).collect();
let sum: i32 = numbers.iter().filter(|x| *x % 3 == 0 || *x % 5 == 0).sum();
println!("{:#?}", sum);
} |
//!Operaciones aceptadas por la virtual machine
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::io;
use crate::operation::Operation;
use crate::instruction::Instruction;
#[derive(Debug, Clone, Copy)]
struct Numeric {
v:usize,
s:usize
}
#[derive(Debug)]
struct Memory<'a> {
accumulator:Numeric,
counter:usize,
map:&'a BTreeMap<usize, Instruction>,
mem:HashMap<usize, Numeric>
}
impl Memory<'_> {
fn new <'a>(map:&'a BTreeMap<usize, Instruction>) ->Memory {
Memory {
accumulator: Numeric {v:0, s:0},
counter:1,
map:map,
mem:HashMap::new()
}
}
fn next(&mut self) -> Operation {
self.map[&self.counter].operation.clone()
}
fn read(&mut self) -> bool {
let mut buffer = String::new();
match io::stdin().read_line(&mut buffer) {
Ok(_) => {
let key = self.map[&self.counter].pointer;
let string:String = String::from(buffer.get(0..(buffer.len()-2)).unwrap());
let mut value:i32 = string.parse::<i32>().unwrap();
let signed:usize = if value < 0 { 1 } else { 0 };
value *= if value < 0 { -1 } else { 1 };
self.mem.insert(
key,
Numeric{
v: value as usize,
s: signed
}
);
self.counter +=1;
return true;
},
Err(err) => println!("err: {}", err)
}
false
}
fn write(&mut self) -> bool {
let key = self.map[&self.counter].pointer;
match self.mem.get(&key) {
Some(numeric) => {
let num:i32 = (numeric.v as i32) * (if numeric.s == 0 { 1 } else { -1 });
println!("{}", num);
self.counter += 1;
return true;
},
None => println!("err: key: {:?} value no exist.", key)
}
false
}
fn load(&mut self) -> bool {
let dir = self.map[&self.counter].pointer;
match self.mem.get(&dir) {
Some(numeric) => {
self.accumulator = numeric.clone();
self.counter += 1;
return true;
},
None => println!("error: load value in pos {}", dir)
}
false
}
fn store(&mut self) -> bool {
let dir = self.map[&self.counter].pointer;
match self.mem.get(&dir) {
Some(_) => {
*self.mem.get_mut(&dir).unwrap() = self.accumulator;
self.accumulator = Numeric { v:0, s:0 };
},
None => {self.mem.insert(dir, self.accumulator);}
}
self.counter += 1;
true
}
fn operation(&mut self, ope:&Operation) -> bool {
let dir = self.map[&self.counter].pointer;
match self.mem.get(&dir) {
Some(numeric) => {
let v0:i32 = (self.accumulator.v as i32) * (if self.accumulator.s == 0 { 1 } else { -1 });
let v1:i32 = (numeric.v as i32) * (if numeric.s == 0 { 1 } else { -1 });
let mut result:i32;
match ope {
Operation::Add => result = v0 + v1,
Operation::Sub => result = v0 - v1,
Operation::Div => {
if v1 == 0 {
println!("error: division for zero: {}", v1);
return false;
}
result = v0 / v1;
},
Operation::Mul => result = v0 * v1,
_ => { return false }
}
let signed:usize = if result < 0 { 1 } else { 0 };
result *= if result < 0 { -1 } else { 1 };
self.accumulator = Numeric {
v: result as usize,
s: signed
};
self.counter +=1;
return true;
},
None => println!("error: operation {:?}", ope)
}
false
}
fn jump(&mut self) -> bool {
match self.map.get(&self.counter) {
Some(inst) => {
self.counter = inst.pointer;
return true;
},
None => {
println!("error: jump.");
return false;
}
}
}
fn jump_neg(&mut self) -> bool {
match self.map.get(&self.counter) {
Some(instr) => {
let value:i32 = (self.accumulator.v as i32) * if self.accumulator.s == 0 { 1 } else { -1 };
self.counter = if value < 0 { instr.pointer } else { self.counter+1 };
return true;
},
None => {
println!("error: jump_zero.");
return false;
}
}
}
fn jump_zero(&mut self) -> bool {
match self.map.get(&self.counter) {
Some(instr) => {
self.counter = if self.accumulator.v == 0 { instr.pointer } else { self.counter+1 };
return true;
},
None => {
println!("error: jump_zero.");
return false;
}
}
}
}
pub fn run<'a>(map:&'a BTreeMap<usize, Instruction>) {
let mut memory = Memory::new(&map);
let mut is_running = true;
while is_running {
match memory.next() {
Operation::Read => is_running = memory.read(),
Operation::Write => is_running = memory.write(),
Operation::Load => is_running = memory.load(),
Operation::Store => is_running = memory.store(),
Operation::Add => is_running = memory.operation(&Operation::Add),
Operation::Sub => is_running = memory.operation(&Operation::Sub),
Operation::Div => is_running = memory.operation(&Operation::Div),
Operation::Mul => is_running = memory.operation(&Operation::Mul),
Operation::Jump => is_running = memory.jump(),
Operation::JumpNeg => is_running = memory.jump_neg(),
Operation::JumpZero => is_running = memory.jump_zero(),
Operation::Stop => is_running = false
}
}
}
|
// UnionFind
// QuickFind: uses n-length array as network model. elements p and q are connected if they share
// the same array value
// It is SLOW: it takes a quadratic (N^2) array accesses to produce produce N unions of N nodes.
struct QuickFind(Vec<u32>);
impl QuickFind {
fn new(n: u32) -> QuickFind {
QuickFind((0..n).collect())
}
fn is_connected(&self, p: usize, q: usize) -> bool {
println!("{:?}", self.0);
self.0[p] == self.0[q]
}
fn connect(&mut self, p: usize, q: usize) {
let mut new_vec: Vec<u32> = vec!();
let target_group = self.0[p];
let replacement_group = self.0[q];
for current_group_id in &self.0 {
if current_group_id == &target_group {
new_vec.push(replacement_group);
} else {
new_vec.push(*current_group_id)
}
}
self.0 = new_vec;
}
fn number_of_groups(&self) -> usize {
let mut x = self.0.clone();
x.sort();
x.dedup();
x.len()
}
}
#[cfg(test)]
mod TestQuickFind {
use super::*;
#[test]
fn is_unconnected_at_initialisaton() {
let qf = QuickFind::new(2);
assert_eq!(qf.is_connected(0, 1), false)
}
#[test]
fn is_reflexive() {
let qf = QuickFind::new(2);
assert_eq!(qf.is_connected(0, 0), true);
assert_eq!(qf.is_connected(1, 1), true);
}
#[test]
fn can_connect_single_node() {
let mut qf = QuickFind::new(2);
qf.connect(0, 1);
assert_eq!(qf.is_connected(0,1), true);
}
#[test]
fn doesnt_connect_everything() {
let mut qf = QuickFind::new(3);
qf.connect(0, 1);
assert_eq!(qf.is_connected(0,1), true);
assert_eq!(qf.is_connected(0,2), false);
assert_eq!(qf.is_connected(1,2), false);
}
#[test]
fn connects_transitively() {
let mut qf = QuickFind::new(2);
qf.connect(0,1);
assert_eq!(qf.is_connected(0,1), true);
assert_eq!(qf.is_connected(1,0), true);
}
#[test]
fn connects_across_unions() {
let mut qf = QuickFind::new(3);
qf.connect(0,1);
qf.connect(1,2);
assert_eq!(qf.is_connected(0,2), true);
}
#[test]
fn can_count_unconnected_groups() {
let mut qf = QuickFind::new(3);
assert_eq!(qf.number_of_groups(), 3);
}
#[test]
fn can_count_connected_groups() {
let mut qf = QuickFind::new(3);
assert_eq!(qf.number_of_groups(), 3);
qf.connect(0,1);
assert_eq!(qf.number_of_groups(), 2);
qf.connect(0,2);
assert_eq!(qf.number_of_groups(), 1);
}
#[test]
fn long_test() {
let mut qf = QuickFind::new(10);
qf.connect(4,3);
qf.connect(3,8);
qf.connect(6,5);
qf.connect(9,4);
qf.connect(2,1);
assert_eq!(qf.is_connected(0,7), false);
assert_eq!(qf.is_connected(8,9), true);
qf.connect(5,0);
qf.connect(7,2);
qf.connect(6,1);
qf.connect(1,0);
assert_eq!(qf.is_connected(0,7), true);
}
}
// QuickUnion
// 'lazy' approach
// same struct, different interpretation, a forest interpretation. Each node, represented by its array position, contains a
// reference to its parent node
// Faster than quickfind but still too slow. The trees get too tall and then find gets too
// expensive
struct QuickUnion(Vec<usize>);
impl QuickUnion {
fn new(n: usize) -> QuickUnion {
QuickUnion((0..n).collect())
}
fn is_connected(&self, p: usize, q: usize) -> bool {
self.find_top_of_tree(p) == self.find_top_of_tree(q)
}
fn connect(&mut self, p: usize, q: usize) {
let top_parent_of_p = self.find_top_of_tree(p);
self.0[top_parent_of_p] = self.find_top_of_tree(q);
}
fn find_top_of_tree(&self, p: usize) -> usize {
let mut current_node = p;
while self.0[current_node] != current_node {
current_node = self.0[current_node];
}
current_node
}
fn number_of_groups(&self) -> usize {
0
}
}
#[cfg(test)]
mod TestQuickUnion {
use super::*;
#[test]
fn is_unconnected_at_initialisaton() {
let qf = QuickUnion::new(2);
assert_eq!(qf.is_connected(0, 1), false)
}
#[test]
fn is_reflexive() {
let qf = QuickUnion::new(2);
assert_eq!(qf.is_connected(0, 0), true);
assert_eq!(qf.is_connected(1, 1), true);
}
#[test]
fn can_connect_single_node() {
let mut qf = QuickUnion::new(2);
qf.connect(0, 1);
assert_eq!(qf.is_connected(0,1), true);
}
#[test]
fn doesnt_connect_everything() {
let mut qf = QuickUnion::new(3);
qf.connect(0, 1);
assert_eq!(qf.is_connected(0,1), true);
assert_eq!(qf.is_connected(0,2), false);
assert_eq!(qf.is_connected(1,2), false);
}
#[test]
fn connects_transitively() {
let mut qf = QuickUnion::new(2);
qf.connect(0,1);
assert_eq!(qf.is_connected(0,1), true);
assert_eq!(qf.is_connected(1,0), true);
}
#[test]
fn connects_across_unions() {
let mut qf = QuickUnion::new(3);
qf.connect(0,1);
qf.connect(1,2);
assert_eq!(qf.is_connected(0,2), true);
}
//#[test]
fn can_count_unconnected_groups() {
let mut qf = QuickUnion::new(3);
assert_eq!(qf.number_of_groups(), 3);
}
//#[test]
fn can_count_connected_groups() {
let mut qf = QuickUnion::new(3);
assert_eq!(qf.number_of_groups(), 3);
qf.connect(0,1);
assert_eq!(qf.number_of_groups(), 2);
qf.connect(0,2);
assert_eq!(qf.number_of_groups(), 1);
}
#[test]
fn long_test() {
let mut qf = QuickUnion::new(10);
qf.connect(4,3);
qf.connect(3,8);
qf.connect(6,5);
qf.connect(9,4);
qf.connect(2,1);
assert_eq!(qf.is_connected(0,7), false);
assert_eq!(qf.is_connected(8,9), true);
qf.connect(5,0);
qf.connect(7,2);
qf.connect(6,1);
qf.connect(1,0);
assert_eq!(qf.is_connected(0,7), true);
}
}
// WeightedQuickUnion
//
// improvement 1: we saw having tall trees made this ineffecient for find. So always attach the
// root of smaller tree to root of larger tree, not the other way around.
// find is proportional to depths of p and q, union is constant time.
// Depth of any node x is at most lg N (log base 2)
// Proof: depth of x increases by 1 when tree T1 containing x is merged into another tree T2
// Size of tree containing x at least doubles
// size of tree containing x can double at most lg N times
//
// improvement 2: path compression: as you scan up the tree, why not set the parent of each
// examined node to the root. Or more simply, but sligtly less effectively
// set every node in the path to its grandparent
// it was proved that any sequence of M union-find ops on N nodes will touch the array at most
// N+Mlg*N times. (lg*N is the number of times you have to take the lgN to get 1 - called the
// iterated log function - in practice think of it as 'a number less than 5')
// This means the algorithm is practically linear time in the real world. Not quite in theory -
// there is provably no linear time algo for union find
pub struct WeightedQuickUnion{
pub parent_of: Vec<usize>,
sizes: Vec<usize>,
}
impl WeightedQuickUnion {
pub fn new(n: usize) -> WeightedQuickUnion {
WeightedQuickUnion{
parent_of: (0..n).collect(),
sizes: vec![1; n],
}
}
fn find_top_of_tree(&mut self, p: usize) -> usize {
let mut current_node = p;
while self.parent_of[current_node] != current_node {
// improvement 2 is here
self.parent_of[current_node] = self.parent_of[self.parent_of[current_node]];
current_node = self.parent_of[current_node];
}
current_node
}
pub fn is_connected(&mut self, p: usize, q: usize) -> bool {
self.find_top_of_tree(p) == self.find_top_of_tree(q)
}
pub fn connect(&mut self, p: usize, q: usize) {
let top_parent_of_p = self.find_top_of_tree(p);
let top_parent_of_q = self.find_top_of_tree(q);
// improvement 1 here
let p_bigger_than_q = self.sizes[top_parent_of_p] > self.sizes[top_parent_of_q];
// initially I thought you should be checking for depth here, not overall tree size, but
// that isn't correct. The goal for each union is to minimise the total increase in depth
// for each node in each tree. The depth for each node will be increasing by 1 for every node in
// the tree that is attached, and by 0 for each node in the tree that is attached to. So by
// attaching the tree with the less number of nodes, you are minimising the overall depth
// increase
if p_bigger_than_q {
self.parent_of[top_parent_of_q] = top_parent_of_p;
self.sizes[top_parent_of_p] = self.sizes[top_parent_of_p] + self.sizes[top_parent_of_q]
} else {
self.parent_of[top_parent_of_p] = top_parent_of_q;
self.sizes[top_parent_of_q] = self.sizes[top_parent_of_q] + self.sizes[top_parent_of_p]
}
println!("connected node {} with node {}", p, q);
}
fn number_of_groups(&self) -> usize {
0
}
}
#[cfg(test)]
mod TestWeightedQuickUnion {
use super::*;
#[test]
fn is_unconnected_at_initialisaton() {
let mut qf = WeightedQuickUnion::new(2);
assert_eq!(qf.is_connected(0, 1), false)
}
#[test]
fn is_reflexive() {
let mut qf = WeightedQuickUnion::new(2);
assert_eq!(qf.is_connected(0, 0), true);
assert_eq!(qf.is_connected(1, 1), true);
}
#[test]
fn can_connect_single_node() {
let mut qf = WeightedQuickUnion::new(2);
qf.connect(0, 1);
assert_eq!(qf.is_connected(0,1), true);
}
#[test]
fn doesnt_connect_everything() {
let mut qf = WeightedQuickUnion::new(3);
qf.connect(0, 1);
assert_eq!(qf.is_connected(0,1), true);
assert_eq!(qf.is_connected(0,2), false);
assert_eq!(qf.is_connected(1,2), false);
}
#[test]
fn connects_transitively() {
let mut qf = WeightedQuickUnion::new(2);
qf.connect(0,1);
assert_eq!(qf.is_connected(0,1), true);
assert_eq!(qf.is_connected(1,0), true);
}
#[test]
fn connects_across_unions() {
let mut qf = WeightedQuickUnion::new(3);
qf.connect(0,1);
qf.connect(1,2);
assert_eq!(qf.is_connected(0,2), true);
}
#[test]
fn long_test() {
let mut qf = WeightedQuickUnion::new(10);
qf.connect(4,3);
qf.connect(3,8);
qf.connect(6,5);
qf.connect(9,4);
qf.connect(2,1);
assert_eq!(qf.is_connected(0,7), false);
assert_eq!(qf.is_connected(8,9), true);
qf.connect(5,0);
qf.connect(7,2);
qf.connect(6,1);
qf.connect(1,0);
assert_eq!(qf.is_connected(0,7), true);
}
}
// summary of dynamic connectivity problem / union find problem:
// Alg | worst case time
// Quick Find | M N
// Quick Union | M N
// Weighted QU | N + MlgN
// QU + Path Com| N + MlgN
// WQU+PC | N + Mlg*N
//
// 10^9 unions on 10^9 objects - QF takes 30 years, WQUPC takes 6 seconds. Picking the right
// algorithm is important
|
use super::Command;
use clap::ArgMatches;
use colored::*;
use log::info;
use std::io::{self, Write};
use std::process;
use termion::clear;
use termion::event::Key;
use termion::input::TermRead;
use termion::raw::IntoRawMode;
struct Entry<'a>(&'a Command, usize);
pub fn run(matches: &ArgMatches, commands: &[Command]) {
let keywords: Vec<String> = matches
.values_of("keywords")
.unwrap()
.map(|k| k.to_owned())
.collect();
info!(
"Searching for command with these keywords: {}",
keywords.join(" ")
);
let mut entries: Vec<Entry> = Vec::new();
for c in commands {
let mut count = 0;
for k in &c.keywords {
count += if keywords.contains(k) { 1 } else { 0 };
}
if count != 0 {
info!("Command ID {} has {} common keywords", c.id, count);
entries.push(Entry(c, count));
}
}
if entries.is_empty() {
println!("{}", "No commands found!".bold().red());
process::exit(0);
}
info!("Sorting entries");
entries.sort_by(|a, b| {
if a.1 != b.1 {
a.1.cmp(&b.1).reverse()
} else {
a.0.id.cmp(&b.0.id)
}
});
let mut stdout = io::stdout().into_raw_mode().unwrap();
let mut index = 0;
loop {
write!(
stdout,
"\r{}[{}/{}] {} ({} {} {} {})",
clear::CurrentLine,
index + 1,
entries.len(),
entries[index].0.command,
"\u{2190}".bold().red(),
"\u{2191}".bold().blue(),
"\u{2193}".bold().blue(),
"\u{2192}".bold().green(),
)
.unwrap();
stdout.flush().unwrap();
match io::stdin().keys().nth(0).unwrap().unwrap() {
Key::Right => {
writeln!(stdout, "\r").unwrap();
let split: Vec<&str> = entries[index].0.command.split(' ').collect();
let mut cmd = process::Command::new(split[0]);
for item in split.iter().skip(1) {
cmd.arg(item);
}
drop(stdout);
info!("Exiting raw mode");
info!("Spawning process");
cmd.spawn().unwrap().wait().unwrap();
print!("\r");
break;
}
Key::Up => {
index = if index == 0 {
entries.len() - 1
} else {
index - 1
}
}
Key::Down => {
index = if index == entries.len() - 1 {
0
} else {
index + 1
}
}
Key::Left => {
write!(stdout, "\r\n{}\r\n", "Aborting!".bold().red()).unwrap();
break;
}
_ => (),
}
}
}
|
// Built-in imports
use std::fmt;
// External uses
use num::BigUint;
use web3::types::H256;
// Workspace uses
use models::node::tx::{ChangePubKey, PackedEthSignature};
use models::node::{AccountId, Address, Nonce, PrivateKey, PubKeyHash, Token, Transfer, Withdraw};
use crate::error::SignerError;
fn signing_failed_error(err: impl ToString) -> SignerError {
SignerError::SigningFailed(err.to_string())
}
pub struct Signer {
pub pubkey_hash: PubKeyHash,
pub address: Address,
pub(crate) private_key: PrivateKey,
pub(crate) eth_private_key: Option<H256>,
pub(crate) account_id: Option<AccountId>,
}
impl fmt::Debug for Signer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut pk_contents = Vec::new();
self.private_key
.write(&mut pk_contents)
.expect("Failed writing the private key contents");
f.debug_struct("Signer")
.field("pubkey_hash", &self.pubkey_hash)
.field("address", &self.address)
.finish()
}
}
impl Signer {
pub fn new(private_key: PrivateKey, address: Address, eth_private_key: Option<H256>) -> Self {
let pubkey_hash = PubKeyHash::from_privkey(&private_key);
Self {
private_key,
pubkey_hash,
address,
eth_private_key,
account_id: None,
}
}
pub fn pubkey_hash(&self) -> &PubKeyHash {
&self.pubkey_hash
}
pub fn set_account_id(&mut self, account_id: Option<AccountId>) {
self.account_id = account_id;
}
pub fn get_account_id(&self) -> Option<AccountId> {
self.account_id
}
pub fn sign_change_pubkey_tx(
&self,
nonce: Nonce,
auth_onchain: bool,
) -> Result<ChangePubKey, SignerError> {
let account_id = self.account_id.ok_or(SignerError::NoSigningKey)?;
let eth_signature = if auth_onchain {
None
} else {
let eth_private_key = self
.eth_private_key
.ok_or(SignerError::MissingEthPrivateKey)?;
let sign_bytes =
ChangePubKey::get_eth_signed_data(account_id, nonce, &self.pubkey_hash)
.map_err(signing_failed_error)?;
let eth_signature = PackedEthSignature::sign(ð_private_key, &sign_bytes)
.map_err(signing_failed_error)?;
Some(eth_signature)
};
let change_pubkey = ChangePubKey {
account_id,
account: self.address,
new_pk_hash: self.pubkey_hash.clone(),
nonce,
eth_signature,
};
if !auth_onchain {
assert!(
change_pubkey.verify_eth_signature() == Some(self.address),
"eth signature is incorrect"
);
}
Ok(change_pubkey)
}
pub fn sign_transfer(
&self,
token: Token,
amount: BigUint,
fee: BigUint,
to: Address,
nonce: Nonce,
) -> Result<(Transfer, Option<PackedEthSignature>), SignerError> {
let account_id = self.account_id.ok_or(SignerError::NoSigningKey)?;
let transfer = Transfer::new_signed(
account_id,
self.address,
to,
token.id,
amount,
fee,
nonce,
&self.private_key,
)
.map_err(signing_failed_error)?;
let eth_signature = self
.eth_private_key
.map(|pk| {
let msg = transfer.get_ethereum_sign_message(&token.symbol, token.decimals);
PackedEthSignature::sign(&pk, msg.as_bytes())
})
.transpose()
.map_err(signing_failed_error)?;
Ok((transfer, eth_signature))
}
pub fn sign_withdraw(
&self,
token: Token,
amount: BigUint,
fee: BigUint,
eth_address: Address,
nonce: Nonce,
) -> Result<(Withdraw, Option<PackedEthSignature>), SignerError> {
let account_id = self.account_id.ok_or(SignerError::NoSigningKey)?;
let withdraw = Withdraw::new_signed(
account_id,
self.address,
eth_address,
token.id,
amount,
fee,
nonce,
&self.private_key,
)
.map_err(signing_failed_error)?;
let eth_signature = self
.eth_private_key
.map(|pk| {
let msg = withdraw.get_ethereum_sign_message(&token.symbol, token.decimals);
PackedEthSignature::sign(&pk, msg.as_bytes())
})
.transpose()
.map_err(signing_failed_error)?;
Ok((withdraw, eth_signature))
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.