text stringlengths 8 4.13M |
|---|
pub use self::device::Device;
pub use self::device::Adapter;
pub use self::device::AdapterType;
pub use self::instance::Instance;
pub use self::surface::Surface;
pub use self::surface::Swapchain;
pub use self::surface::SwapchainError;
pub use self::surface::WSIFence;
pub use self::command::CommandBuffer;
pub use self::command::CommandBufferType;
pub use self::command::InnerCommandBufferProvider;
pub use self::buffer::Buffer;
pub use self::buffer::MappedBuffer;
pub use self::buffer::MutMappedBuffer;
pub use self::buffer::BufferUsage;
pub use self::buffer::BufferInfo;
pub use self::command::Queue;
pub use self::device::MemoryUsage;
pub use self::format::Format;
pub use self::pipeline::*;
pub use self::texture::Texture;
pub use self::texture::TextureInfo;
pub use self::texture::TextureUsage;
pub use self::renderpass::*;
pub use self::command::Viewport;
pub use self::command::Scissor;
pub use self::command::Barrier;
pub use self::backend::Backend;
pub use self::command::BindingFrequency;
pub use self::command::PipelineBinding;
pub use self::command::RenderPassBeginInfo;
pub use self::command::RenderPassAttachment;
pub use self::command::RenderPassAttachmentView;
pub use self::command::BarrierSync;
pub use self::command::BarrierAccess;
pub use self::command::IndexFormat;
pub use self::command::BarrierTextureRange;
pub use self::command::FenceRef;
pub use self::sync::FenceValuePair;
pub use self::surface::PreparedBackBuffer;
pub use self::texture::{
TextureView, TextureViewInfo, Filter, AddressMode,
SamplerInfo, TextureLayout, TextureDimension
};
pub use self::sync::Fence;
pub use self::rt::{AccelerationStructure, AccelerationStructureSizes,
BottomLevelAccelerationStructureInfo, TopLevelAccelerationStructureInfo,
AccelerationStructureInstance, AccelerationStructureMeshRange,
RayTracingPipelineInfo
};
pub use self::device::WHOLE_BUFFER;
mod device;
mod instance;
mod surface;
mod command;
mod buffer;
mod format;
mod pipeline;
mod texture;
mod renderpass;
mod backend;
mod sync;
mod resource;
mod rt;
// TODO: find a better place for this
pub trait Resettable {
fn reset(&mut self);
}
|
// 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>
//! Vectores energéticos
use std::fmt;
use std::str;
use serde::{Deserialize, Serialize};
use super::ProdSource;
use crate::error::EpbdError;
/// Vector energético (energy carrier).
#[allow(non_camel_case_types)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum Carrier {
/// Environment thermal energy (from heat pumps and other)
EAMBIENTE,
/// Biofuel
BIOCARBURANTE,
/// Biomass
BIOMASA,
/// Densified biomass (pellets)
BIOMASADENSIFICADA,
/// Coal
CARBON,
/// Electricity
ELECTRICIDAD,
/// Natural gas
GASNATURAL,
/// Diesel oil
GASOLEO,
/// LPG - Liquefied petroleum gas
GLP,
/// Generic energy carrier 1
RED1,
/// Generic energy carrier 2
RED2,
/// Thermal energy from solar collectors
TERMOSOLAR,
}
/// TODO: La clasificación de los vectores en función del perímetro debería hacerse
/// TODO: en la propia definición de esos vectores
impl Carrier {
/// Vectores considerados dentro del perímetro NEARBY (a excepción de la ELECTRICIDAD in situ).
pub const NRBY: [Carrier; 6] = [
Carrier::BIOMASA,
Carrier::BIOMASADENSIFICADA,
Carrier::RED1,
Carrier::RED2,
Carrier::EAMBIENTE,
Carrier::TERMOSOLAR,
]; // Ver B.23. Solo biomasa sólida
/// Vectores considerados dentro del perímetro ONSITE (a excepción de la ELECTRICIDAD in situ).
pub const ONST: [Carrier; 2] = [Carrier::EAMBIENTE, Carrier::TERMOSOLAR];
/// Is this a carrier from the onsite or nearby perimeter?
pub fn is_nearby(&self) -> bool {
Carrier::NRBY.contains(self)
}
/// Is this a carrier from the onsite perimeter?
pub fn is_onsite(&self) -> bool {
Carrier::ONST.contains(self)
}
}
impl str::FromStr for Carrier {
type Err = EpbdError;
fn from_str(s: &str) -> Result<Carrier, Self::Err> {
match s {
"EAMBIENTE" => Ok(Carrier::EAMBIENTE),
"BIOCARBURANTE" => Ok(Carrier::BIOCARBURANTE),
"BIOMASA" => Ok(Carrier::BIOMASA),
"BIOMASADENSIFICADA" => Ok(Carrier::BIOMASADENSIFICADA),
"CARBON" => Ok(Carrier::CARBON),
"ELECTRICIDAD" => Ok(Carrier::ELECTRICIDAD),
"GASNATURAL" => Ok(Carrier::GASNATURAL),
"GASOLEO" => Ok(Carrier::GASOLEO),
"GLP" => Ok(Carrier::GLP),
"RED1" => Ok(Carrier::RED1),
"RED2" => Ok(Carrier::RED2),
"TERMOSOLAR" => Ok(Carrier::TERMOSOLAR),
_ => Err(EpbdError::ParseError(s.into())),
}
}
}
impl std::fmt::Display for Carrier {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl std::convert::From<ProdSource> for Carrier {
fn from(value: ProdSource) -> Self {
match value {
ProdSource::EL_INSITU => Carrier::ELECTRICIDAD,
ProdSource::EL_COGEN => Carrier::ELECTRICIDAD,
ProdSource::TERMOSOLAR => Carrier::TERMOSOLAR,
ProdSource::EAMBIENTE => Carrier::EAMBIENTE,
}
}
} |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[doc(hidden)]
pub struct IVariablePhotoCapturedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVariablePhotoCapturedEventArgs {
type Vtable = IVariablePhotoCapturedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd1eb4c5c_1b53_4e4a_8b5c_db7887ac949b);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVariablePhotoCapturedEventArgs_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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IVariablePhotoSequenceCapture(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVariablePhotoSequenceCapture {
type Vtable = IVariablePhotoSequenceCapture_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd0112d1d_031e_4041_a6d6_bd742476a8ee);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVariablePhotoSequenceCapture_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(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(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(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IVariablePhotoSequenceCapture2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVariablePhotoSequenceCapture2 {
type Vtable = IVariablePhotoSequenceCapture2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfe2c62bc_50b0_43e3_917c_e3b92798942f);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVariablePhotoSequenceCapture2_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,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct VariablePhotoCapturedEventArgs(pub ::windows::core::IInspectable);
impl VariablePhotoCapturedEventArgs {
pub fn Frame(&self) -> ::windows::core::Result<super::CapturedFrame> {
let this = self;
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::CapturedFrame>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn CaptureTimeOffset(&self) -> ::windows::core::Result<super::super::super::Foundation::TimeSpan> {
let this = self;
unsafe {
let mut result__: super::super::super::Foundation::TimeSpan = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::TimeSpan>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn UsedFrameControllerIndex(&self) -> ::windows::core::Result<super::super::super::Foundation::IReference<u32>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IReference<u32>>(result__)
}
}
pub fn CapturedFrameControlValues(&self) -> ::windows::core::Result<super::CapturedFrameControlValues> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::CapturedFrameControlValues>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for VariablePhotoCapturedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Capture.Core.VariablePhotoCapturedEventArgs;{d1eb4c5c-1b53-4e4a-8b5c-db7887ac949b})");
}
unsafe impl ::windows::core::Interface for VariablePhotoCapturedEventArgs {
type Vtable = IVariablePhotoCapturedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd1eb4c5c_1b53_4e4a_8b5c_db7887ac949b);
}
impl ::windows::core::RuntimeName for VariablePhotoCapturedEventArgs {
const NAME: &'static str = "Windows.Media.Capture.Core.VariablePhotoCapturedEventArgs";
}
impl ::core::convert::From<VariablePhotoCapturedEventArgs> for ::windows::core::IUnknown {
fn from(value: VariablePhotoCapturedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&VariablePhotoCapturedEventArgs> for ::windows::core::IUnknown {
fn from(value: &VariablePhotoCapturedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for VariablePhotoCapturedEventArgs {
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 VariablePhotoCapturedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<VariablePhotoCapturedEventArgs> for ::windows::core::IInspectable {
fn from(value: VariablePhotoCapturedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&VariablePhotoCapturedEventArgs> for ::windows::core::IInspectable {
fn from(value: &VariablePhotoCapturedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for VariablePhotoCapturedEventArgs {
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 VariablePhotoCapturedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for VariablePhotoCapturedEventArgs {}
unsafe impl ::core::marker::Sync for VariablePhotoCapturedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct VariablePhotoSequenceCapture(pub ::windows::core::IInspectable);
impl VariablePhotoSequenceCapture {
#[cfg(feature = "Foundation")]
pub fn StartAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
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::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn StopAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
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::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn FinishAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn PhotoCaptured<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<VariablePhotoSequenceCapture, VariablePhotoCapturedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemovePhotoCaptured<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn Stopped<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<VariablePhotoSequenceCapture, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveStopped<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn UpdateSettingsAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = &::windows::core::Interface::cast::<IVariablePhotoSequenceCapture2>(self)?;
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::super::Foundation::IAsyncAction>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for VariablePhotoSequenceCapture {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Capture.Core.VariablePhotoSequenceCapture;{d0112d1d-031e-4041-a6d6-bd742476a8ee})");
}
unsafe impl ::windows::core::Interface for VariablePhotoSequenceCapture {
type Vtable = IVariablePhotoSequenceCapture_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd0112d1d_031e_4041_a6d6_bd742476a8ee);
}
impl ::windows::core::RuntimeName for VariablePhotoSequenceCapture {
const NAME: &'static str = "Windows.Media.Capture.Core.VariablePhotoSequenceCapture";
}
impl ::core::convert::From<VariablePhotoSequenceCapture> for ::windows::core::IUnknown {
fn from(value: VariablePhotoSequenceCapture) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&VariablePhotoSequenceCapture> for ::windows::core::IUnknown {
fn from(value: &VariablePhotoSequenceCapture) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for VariablePhotoSequenceCapture {
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 VariablePhotoSequenceCapture {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<VariablePhotoSequenceCapture> for ::windows::core::IInspectable {
fn from(value: VariablePhotoSequenceCapture) -> Self {
value.0
}
}
impl ::core::convert::From<&VariablePhotoSequenceCapture> for ::windows::core::IInspectable {
fn from(value: &VariablePhotoSequenceCapture) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for VariablePhotoSequenceCapture {
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 VariablePhotoSequenceCapture {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
|
use std::collections::HashMap;
use std::io::{self, Read};
fn get_input() -> u32 {
let mut data = String::new();
io::stdin().read_to_string(&mut data).expect("Couldn't read stdin");
data.trim().parse().expect("Bad input")
}
fn layer(cell: u32) -> u32 {
(((cell - 1) as f64).sqrt().floor() as u32 + 1) / 2
}
fn solve1(cell: u32) -> u32 {
if cell == 1 { return 0; }
let layer = layer(cell);
println!("Layer: {}", layer);
let layer_base = layer * layer;
let layer_side = layer * 2 + 1;
println!("Layer side: {}", layer_side);
let layer_wobble = (layer_side + 1) / 2;
println!("Layer wobble: {}", layer_wobble);
let offset_in_layer = cell - layer_base - 1;
println!("Offset in layer: {}", offset_in_layer);
let offset_from_bottom_right = offset_in_layer + 1;
println!("Offset from bottom right: {}", offset_from_bottom_right);
let wobbled_offset = offset_from_bottom_right % 2 * layer_wobble;
println!("Wobbled offset: {}", wobbled_offset);
let offset_from_center = offset_from_bottom_right % ((layer_side + 1) / 2);
println!("Offset from center: {}", offset_from_center);
layer + offset_from_center
}
fn solve2(threshold: u32) -> u32 {
// We're just going to brute-force this.
let mut memory = HashMap::new();
memory.insert((0, 0), 1);
let mut ring = 1;
loop {
for i in get_indices(ring) {
let value = sum_around(&memory, i);
if value > threshold {
return value;
}
memory.insert(i, value);
}
ring += 1;
}
}
fn get_indices(ring: i32) -> Vec<(i32, i32)> {
let side = ring * 2 + 1;
let slides = [(( ring, -ring), ( 0, 1)),
(( ring, ring), (-1, 0)),
((-ring, ring), ( 0, -1)),
((-ring, -ring), ( 1, 0))];
let mut result = vec![];
for &(mut pos, stride) in slides.into_iter() {
for _ in 1..side { // want one less iteration than side length
pos.0 += stride.0;
pos.1 += stride.1;
result.push(pos);
}
}
result
}
fn sum_around(memory: &HashMap<(i32, i32), u32>, index: (i32, i32)) -> u32 {
indices_around(index).into_iter()
.flat_map(|i| memory.get(i))
.fold(0, |sum, v| sum + v)
}
fn indices_around(index: (i32, i32)) -> [(i32, i32); 8] {
let (x, y) = index;
[(x-1, y+1), (x , y+1), (x+1, y+1),
(x-1, y ), (x+1, y ),
(x-1, y-1), (x , y-1), (x+1, y-1)]
}
fn main() {
let data = get_input();
println!("Solution Part A: {}", solve1(data));
println!("Solution Part B: {}", solve2(data));
}
#[cfg(test)]
mod tests {
use super::solve1;
use super::solve2;
#[test] #[ignore]
fn check1() {
assert_eq!(0, solve1(1));
assert_eq!(1, solve1(2));
assert_eq!(2, solve1(3));
assert_eq!(1, solve1(4));
assert_eq!(2, solve1(5));
assert_eq!(1, solve1(6));
assert_eq!(2, solve1(7));
assert_eq!(1, solve1(8));
assert_eq!(2, solve1(9));
assert_eq!(3, solve1(10));
assert_eq!(2, solve1(11));
assert_eq!(3, solve1(12));
assert_eq!(4, solve1(13));
assert_eq!(3, solve1(14));
assert_eq!(2, solve1(15));
assert_eq!(3, solve1(16));
assert_eq!(4, solve1(17));
assert_eq!(3, solve1(18));
assert_eq!(2, solve1(19));
assert_eq!(3, solve1(20));
assert_eq!(4, solve1(21));
assert_eq!(3, solve1(22));
assert_eq!(2, solve1(23));
assert_eq!(3, solve1(24));
assert_eq!(4, solve1(25));
assert_eq!(5, solve1(26));
assert_eq!(4, solve1(27));
assert_eq!(3, solve1(28));
assert_eq!(4, solve1(29));
assert_eq!(5, solve1(30));
assert_eq!(6, solve1(30));
assert_eq!(5, solve1(30));
}
#[test]
fn check2() {
assert_eq!(4, solve2(3));
assert_eq!(10, solve2(9));
assert_eq!(11, solve2(10));
assert_eq!(54, solve2(26));
assert_eq!(59, solve2(58));
assert_eq!(147, solve2(142));
assert_eq!(304, solve2(147));
}
} |
extern crate nalgebra as na;
extern crate piston_window;
extern crate itertools;
#[macro_use]
pub mod traits;
pub mod objects;
fn main() {
}
|
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, Default)]
pub enum Edition {
E2015,
E2018,
#[default]
E2021,
}
impl FromStr for Edition {
type Err = Box<dyn std::error::Error>;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"2015" => Ok(Edition::E2015),
"2018" => Ok(Edition::E2018),
"2021" => Ok(Edition::E2021),
_ => Err("Unknown edition".into()),
}
}
}
impl std::fmt::Display for Edition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Edition::E2015 => write!(f, "2015"),
Edition::E2018 => write!(f, "2018"),
Edition::E2021 => write!(f, "2021"),
}
}
}
|
fn rle_init() {}
|
use winapi::um::winuser::RAWHID;
use winapi::shared::hidpi::{PHIDP_PREPARSED_DATA, HidP_Input, HidP_GetUsageValue, HIDP_STATUS_SUCCESS, HIDP_STATUS_INCOMPATIBLE_REPORT_ID, HidP_GetUsages};
use winapi::shared::hidusage::USAGE;
use winapi::shared::ntdef::{PCHAR, ULONG, LONG};
use event::RawEvent;
use devices::{JoystickState, HatSwitch, JoystickInfo};
use std::mem::transmute;
use std::mem;
pub unsafe fn garbage_vec<T>(size: usize) -> Vec<T>{
let mut v = Vec::with_capacity(size);
v.set_len(size);
v
}
pub fn process_joystick_data(raw_data: &RAWHID, id: usize, hid_info: &mut JoystickInfo
) -> Vec<RawEvent> {
let mut output: Vec<RawEvent> = Vec::new();
unsafe {
let mut button_states: Vec<bool> = vec![];
if let Some(button_caps) = hid_info.button_caps.iter().nth(0) {
let number_of_buttons: ULONG =
(button_caps.u.Range().UsageMax - button_caps.u.Range().UsageMin + 1) as ULONG;
let mut usage: Vec<USAGE> = garbage_vec(number_of_buttons as usize);
let mut number_of_presses: ULONG = number_of_buttons;
assert!(
HidP_GetUsages(HidP_Input,
button_caps.UsagePage,
0,
usage.as_mut_ptr(),
&mut number_of_presses,
hid_info.preparsed_data.as_mut_ptr() as PHIDP_PREPARSED_DATA,
transmute::<_, PCHAR>(raw_data.bRawData.as_ptr()),
raw_data.dwSizeHid
) == HIDP_STATUS_SUCCESS
);
button_states = vec![false; number_of_buttons as usize];
for i in 0..number_of_presses as usize {
button_states[(usage[i] - button_caps.u.Range().UsageMin) as usize] = true;
}
}
let vec_value_caps = hid_info.value_caps.clone();
let mut axis_states = hid_info.state.axis_states.clone();
let mut raw_axis_states = hid_info.state.raw_axis_states.clone();
let mut hatswitch: Option<HatSwitch> = None;
let mut value: ULONG = mem::uninitialized();
let mut derived_value: f64;
for value_caps in vec_value_caps {
let usage_index = value_caps.u.Range().UsageMin;
let mut logical_max = value_caps.LogicalMax;
let mut logical_min = value_caps.LogicalMin;
// Xbox Axes
if logical_max == -1 && logical_min == 0 && hid_info.is_360_controller
{
logical_max = 65535;
logical_min = 0;
}
let usage_value_result = HidP_GetUsageValue(
HidP_Input,
value_caps.UsagePage,
0,
usage_index,
&mut value,
hid_info.preparsed_data.as_mut_ptr() as PHIDP_PREPARSED_DATA,
transmute::<_, PCHAR>(raw_data.bRawData.as_ptr()),
raw_data.dwSizeHid,
);
// If the usage does not match the usage page reported by the device we ignore the result
// (see https://github.com/Jonesey13/multiinput-rust/issues/3)
assert!(
(usage_value_result == HIDP_STATUS_SUCCESS) || (usage_value_result == HIDP_STATUS_INCOMPATIBLE_REPORT_ID)
);
if value as i32 > logical_max {
derived_value = (value as i32 - (logical_max - logical_min + 1)) as f64;
}
else {
derived_value = value as f64;
}
derived_value
= 2f64 * (derived_value - logical_min as f64) /
(logical_max - logical_min) as f64 - 1f64;
if usage_index == 0x30 {
axis_states.x = Some(derived_value);
raw_axis_states.x = value;
}
if usage_index == 0x31 {
axis_states.y = Some(-derived_value);
raw_axis_states.y = value;
}
if usage_index == 0x32 {
axis_states.z = Some(-derived_value);
raw_axis_states.z = value;
}
if usage_index == 0x33 {
axis_states.rx = Some(derived_value);
raw_axis_states.rx = value;
}
if usage_index == 0x34 {
axis_states.ry = Some(derived_value);
raw_axis_states.ry = value;
}
if usage_index == 0x35 {
axis_states.rz = Some(derived_value);
raw_axis_states.rz = value;
}
if usage_index == 0x36 {
axis_states.slider = Some(derived_value);
raw_axis_states.slider = value;
}
if usage_index == 0x39 {
hatswitch = match value as LONG - value_caps.LogicalMin {
0 => Some(HatSwitch::Up),
1 => Some(HatSwitch::UpRight),
2 => Some(HatSwitch::Right),
3 => Some(HatSwitch::DownRight),
4 => Some(HatSwitch::Down),
5 => Some(HatSwitch::DownLeft),
6 => Some(HatSwitch::Left),
7 => Some(HatSwitch::UpLeft),
_ => Some(HatSwitch::Center),
};
}
}
let newstate = JoystickState{ button_states: button_states,
axis_states: axis_states,
hatswitch: hatswitch,
raw_axis_states: raw_axis_states,};
let new_events = hid_info.state.compare_states(newstate.clone(), id);
output.extend(new_events);
hid_info.state = newstate;
}
output
}
|
//! Provides utilities for operating on the filesystem.
use std::fs::{self, create_dir_all, File};
use std::io::{self, ErrorKind};
use std::path::{Path, PathBuf};
use notion_fail::{ExitCode, FailExt, Fallible, NotionFail, ResultExt};
pub fn touch(path: &Path) -> Fallible<File> {
if !path.is_file() {
let basedir = path.parent().unwrap();
create_dir_all(basedir).unknown()?;
File::create(path).unknown()?;
}
File::open(path).unknown()
}
#[derive(Debug, Fail, NotionFail)]
#[fail(display = "Could not create directory {}: {}", dir, error)]
#[notion_fail(code = "FileSystemError")]
pub(crate) struct CreateDirError {
pub(crate) dir: String,
pub(crate) error: String,
}
impl CreateDirError {
pub(crate) fn for_dir(dir: String) -> impl FnOnce(&io::Error) -> CreateDirError {
move |error| CreateDirError {
dir,
error: error.to_string(),
}
}
}
#[derive(Debug, Fail, NotionFail)]
#[fail(display = "`path` internal error")]
#[notion_fail(code = "UnknownError")]
pub(crate) struct PathInternalError;
/// This creates the parent directory of the input path, assuming the input path is a file.
pub fn ensure_containing_dir_exists<P: AsRef<Path>>(path: &P) -> Fallible<()> {
if let Some(dir) = path.as_ref().parent() {
fs::create_dir_all(dir)
.with_context(CreateDirError::for_dir(dir.to_string_lossy().to_string()))
} else {
// this was called for a file with no parent directory
throw!(PathInternalError.unknown());
}
}
/// Reads a file, if it exists.
pub fn read_file_opt(path: &PathBuf) -> io::Result<Option<String>> {
let result: io::Result<String> = fs::read_to_string(path);
match result {
Ok(string) => Ok(Some(string)),
Err(error) => match error.kind() {
ErrorKind::NotFound => Ok(None),
_ => Err(error),
},
}
}
|
pub mod combinators;
pub mod modes;
pub mod random;
pub mod loading;
mod builder_ext;
mod plugin;
pub use builder_ext::*;
pub use plugin::*;
game_lib::fix_bevy_derive!(game_lib::bevy);
|
use text_grid::*;
#[test]
fn column_u8() {
struct Source {
a: u8,
b: u8,
}
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column("a", |x| x.a);
f.column("b", |x| x.b);
}
}
do_test(
vec![Source { a: 100, b: 200 }, Source { a: 1, b: 2 }],
r"
a | b |
-----|-----|
100 | 200 |
1 | 2 |
",
);
}
#[test]
fn column_u8_ref() {
struct Source {
a: u8,
b: u8,
}
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column("a", |x| x.a);
f.column("b", |x| &x.b);
}
}
do_test(
vec![Source { a: 100, b: 200 }, Source { a: 1, b: 2 }],
r"
a | b |
-----|-----|
100 | 200 |
1 | 2 |
",
);
}
#[test]
fn column_str() {
struct Source<'s> {
s: &'s str,
}
impl<'s> CellsSource for Source<'s> {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column("a", |x| x.s);
}
}
do_test(
vec![Source { s: "aaa" }, Source { s: "bbb" }],
r"
a |
-----|
aaa |
bbb |
",
);
}
#[test]
fn column_static_str() {
struct Source {
a: u8,
b: u8,
}
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column("a", |x| x.a);
f.column("p", |_| "xxx");
f.column("b", |x| x.b);
}
}
do_test(
vec![Source { a: 100, b: 200 }, Source { a: 1, b: 2 }],
r"
a | p | b |
-----|-----|-----|
100 | xxx | 200 |
1 | xxx | 2 |
",
);
}
#[test]
fn column_group() {
struct Source {
a: u8,
b: u8,
}
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column_with("g", |f| {
f.column("a", |x| x.a);
f.column("b", |x| x.b);
})
}
}
do_test(
vec![Source { a: 100, b: 200 }, Source { a: 1, b: 2 }],
r"
g |
-----------|
a | b |
-----|-----|
100 | 200 |
1 | 2 |
",
);
}
#[test]
fn column_group_differing_level() {
struct Source {
a: u32,
b_1: u32,
b_2: u32,
}
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column("a", |s| s.a);
f.column_with("b", |f| {
f.column("1", |s| s.b_1);
f.column("2", |s| s.b_2);
});
}
}
do_test(
vec![
Source {
a: 300,
b_1: 10,
b_2: 20,
},
Source {
a: 300,
b_1: 1,
b_2: 500,
},
],
r"
a | b |
-----|----------|
| 1 | 2 |
-----|----|-----|
300 | 10 | 20 |
300 | 1 | 500 |",
);
}
#[test]
fn column_group_differing_level_2() {
struct Source {
a: u32,
b_1: u32,
b_2: u32,
c_1: u32,
c_2: u32,
}
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column("a", |s| s.a);
f.column_with("b", |f| {
f.column("1", |s| s.b_1);
f.column("2", |s| s.b_2);
});
f.column_with("c", |f| {
f.content(|s| s.c_1);
f.content(|s| s.c_2);
});
}
}
do_test(
vec![
Source {
a: 300,
b_1: 10,
b_2: 20,
c_1: 5,
c_2: 6,
},
Source {
a: 300,
b_1: 1,
b_2: 500,
c_1: 7,
c_2: 8,
},
],
r"
a | b | c |
-----|----------|----|
| 1 | 2 | |
-----|----|-----|----|
300 | 10 | 20 | 56 |
300 | 1 | 500 | 78 |",
);
}
#[test]
fn column_multipart() {
struct Source {
a: u8,
b: u8,
}
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column_with("g", |f| {
f.content(|x| x.a);
f.content(|x| x.b);
})
}
}
do_test(
vec![Source { a: 10, b: 200 }, Source { a: 1, b: 2 }],
r"
g |
-------|
10200 |
1 2 |
",
);
}
#[test]
fn column_cell_by() {
struct Source {
a: f64,
b: u32,
}
use std::fmt::*;
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column("a", |&x| cell_by(move |f| write!(f, "{:.2}", x.a)).right());
f.column("b", |&x| x.b);
}
}
do_test(
vec![Source { a: 10.0, b: 30 }, Source { a: 1.22, b: 40 }],
r"
a | b |
-------|----|
10.00 | 30 |
1.22 | 40 |
",
);
}
#[test]
fn column_cell_macro() {
struct Source {
a: f64,
b: u32,
}
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column("a", |&x| cell!("{:.2}", x.a).right());
f.column("b", |&x| x.b);
}
}
do_test(
vec![Source { a: 10.0, b: 30 }, Source { a: 1.22, b: 40 }],
r"
a | b |
-------|----|
10.00 | 30 |
1.22 | 40 |
",
);
}
#[test]
fn map() {
struct Source {
a: u8,
b: u8,
}
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.map(|x| x.a).column("a", |&x| x);
f.map(|x| x.b).column("b", |&x| x);
}
}
do_test(
vec![Source { a: 100, b: 200 }, Source { a: 1, b: 2 }],
r"
a | b |
-----|-----|
100 | 200 |
1 | 2 |
",
);
}
#[test]
fn map_ref() {
struct Source {
a: u8,
b: u8,
}
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.map(|x| &x.a).column("a", |&x| x);
f.map(|x| &x.b).column("b", |&x| x);
}
}
do_test(
vec![Source { a: 100, b: 200 }, Source { a: 1, b: 2 }],
r"
a | b |
-----|-----|
100 | 200 |
1 | 2 |
",
);
}
#[test]
fn impl_debug() {
struct Source {
a: u8,
b: u8,
}
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column("a", |x| x.a);
f.column("b", |x| x.b);
}
}
let mut g = Grid::new();
g.push(&Source { a: 100, b: 200 });
g.push(&Source { a: 1, b: 2 });
let d = format!("{:?}", g);
let e = r"
a | b |
-----|-----|
100 | 200 |
1 | 2 |
";
assert_eq!(d.trim(), e.trim());
}
#[test]
fn with_schema() {
struct MyGridSchema {
len: usize,
}
impl GridSchema for MyGridSchema {
type Source = [u32];
fn fmt(&self, f: &mut CellsFormatter<&[u32]>) {
for i in 0..self.len {
f.column(i, |s| s[i]);
}
}
}
let mut g = Grid::new_with_schema(MyGridSchema { len: 3 });
g.push(&[1, 2, 3]);
g.push(&[4, 5, 6]);
let d = format!("{:?}", g);
let e = r"
0 | 1 | 2 |
---|---|---|
1 | 2 | 3 |
4 | 5 | 6 |
";
assert_eq!(d.trim(), e.trim());
}
#[test]
fn right() {
let s = grid_schema::<&str>(|f| f.column("x", |&x| cell(x).right()));
do_test_with_schema(
vec!["a", "ab", "abc"],
&s,
r"
x |
-----|
a |
ab |
abc |",
);
}
#[test]
fn baseline() {
struct Source {
a: f64,
b: String,
}
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.column("a", |x| x.a);
f.column("b", |x| cell(&x.b).baseline("-"));
}
}
do_test(
vec![
Source {
a: 100.1,
b: "1-2345".into(),
},
Source {
a: 10.123,
b: "1234-5".into(),
},
],
r"
a | b |
---------|-----------|
100.1 | 1-2345 |
10.123 | 1234-5 |",
);
}
#[test]
fn root_content() {
struct Source {
a: u32,
b: u32,
}
impl CellsSource for Source {
fn fmt(f: &mut CellsFormatter<&Self>) {
f.content(|x| x.a);
f.content(|_| " ");
f.content(|x| x.b);
}
}
do_test(
vec![Source { a: 10, b: 1 }, Source { a: 30, b: 100 }],
r"
10 1 |
30 100 |",
);
}
#[test]
fn disparate_column_count() {
let rows = vec![vec![1, 2, 3], vec![1, 2], vec![1, 2, 3, 4]];
let max_colunm_count = rows.iter().map(|r| r.len()).max().unwrap_or(0);
let schema = grid_schema::<Vec<u32>>(move |f| {
for i in 0..max_colunm_count {
f.column(i, |x| x.get(i));
}
});
let mut g = Grid::new_with_schema(schema);
g.extend(rows);
assert_eq!(format!("\n{g}"), OUTPUT);
const OUTPUT: &str = r"
0 | 1 | 2 | 3 |
---|---|---|---|
1 | 2 | 3 | |
1 | 2 | | |
1 | 2 | 3 | 4 |
";
}
#[test]
fn extend() {
let mut g: Grid<u32> = Grid::new();
let items = vec![1, 2, 3];
g.extend(&items);
g.extend(items);
}
#[test]
fn cell_ref() {
let _ = grid_schema(|f: &mut CellsFormatter<&String>| {
// f.column("x", |x| cell!("__{}__", x)); // BAD
f.column("x", |&x| cell!("__{}__", x)); // GOOD
});
}
#[test]
fn cells_e() {
let s = grid_schema::<f64>(|f| {
f.column("", |&x| cell!("{x:e}"));
f.column("e", |&x| cells_e!("{x:e}"));
f.column(".2e", |&x| cells_e!("{x:.2e}"));
f.column("E", |&x| cells_e!("{x:E}"));
f.column("debug", |&x| cells_e!("{x:?}"));
});
do_test_with_schema(
vec![1.0, 0.95, 123.45, 0.000001, 1.0e-20, 10000000000.0],
s,
r"
| e | .2e | E | debug |
----------|--------------|------------|--------------|----------------------|
1e0 | 1 e 0 | 1.00 e 0 | 1 E 0 | 1.0 |
9.5e-1 | 9.5 e -1 | 9.50 e -1 | 9.5 E -1 | 0.95 |
1.2345e2 | 1.2345 e 2 | 1.23 e 2 | 1.2345 E 2 | 123.45 |
1e-6 | 1 e -6 | 1.00 e -6 | 1 E -6 | 1 e -6 |
1e-20 | 1 e -20 | 1.00 e -20 | 1 E -20 | 1 e -20 |
1e10 | 1 e 10 | 1.00 e 10 | 1 E 10 | 10000000000.0 |
",
);
}
#[test]
fn empty_group() {
let s = grid_schema::<()>(|f| {
f.column_with("header", |_| {});
f.column("1", |_| cell(1));
});
do_test_with_schema(
vec![()],
s,
r"
1 |
---|
1 |
",
);
}
#[test]
fn result() {
do_test(
vec![Ok(["a", "b"]), Err("********")],
r"
0 | 1 |
-----|----|
a | b |
******** |
",
);
}
#[track_caller]
fn do_test<T: CellsSource>(s: Vec<T>, e: &str) {
do_test_with_schema(s, DefaultGridSchema::default(), e);
}
#[track_caller]
fn do_test_with_schema<T>(s: Vec<T>, schema: impl GridSchema<Source = T>, e: &str) {
let mut g = Grid::new_with_schema(schema);
for s in s {
g.push(&s);
}
let a = format!("{}", g);
let e = e.trim_matches('\n');
let a = a.trim_matches('\n');
assert!(a == e, "\nexpected :\n{}\nactual :\n{}\n", e, a);
}
|
extern crate num_bigint;
extern crate num_traits;
extern crate hex;
extern crate rand;
extern crate openssl;
mod dh;
use num_bigint::{BigUint};
use num_bigint::*;
use num_traits::*;
use openssl::symm::{decrypt, Cipher, Crypter,encrypt};
use num_bigint::Sign::*;
use dh::*;
fn main() {
let mut alice = Dh::new();
let mut bob = Dh::new();
let mut m = DhMitm::new();
let a = alice.start_exchange();
let a_m = m.forward_start(a.0,a.1,a.2);
let b = bob.reply(a_m.0,a_m.1,a_m.2);
let b_m = m.forward_reply(b);
alice.other_key_update(b_m);
let message = b"This layer is not secure";
println!("message: {:?}",message);
let ciphertext = alice.aes_cbc_from_key(message);
let decrypt = m.crack_message(&ciphertext);
println!("decrypted: {:?}",decrypt);
}
|
use crate::protocol::parts::option_part::{OptionId, OptionPart};
use crate::protocol::parts::option_value::OptionValue;
// The part is sent from the client to signal whether the implicit LOB
// streaming is started so that the server does not commit the current
// transaction even with auto-commit on while LOB streaming (really??).
pub type LobFlags = OptionPart<LobFlagsId>;
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum LobFlagsId {
ImplicitStreaming, // 0 // BOOL // The implicit streaming has been started.
__Unexpected__(u8),
}
impl OptionId<LobFlagsId> for LobFlagsId {
fn to_u8(&self) -> u8 {
match *self {
Self::ImplicitStreaming => 0,
Self::__Unexpected__(val) => val,
}
}
fn from_u8(val: u8) -> Self {
match val {
0 => Self::ImplicitStreaming,
val => {
warn!("Unsupported value for LobFlagsId received: {}", val);
Self::__Unexpected__(val)
}
}
}
fn part_type(&self) -> &'static str {
"LobFlags"
}
}
impl LobFlags {
pub fn for_implicit_streaming() -> Self {
let mut lob_flags = Self::default();
lob_flags.insert(LobFlagsId::ImplicitStreaming, OptionValue::BOOLEAN(true));
lob_flags
}
}
|
use std::sync::{Arc, RwLock};
use resources::*;
use sop::TweenState;
use state::*;
use storyboard::*;
use tween::*;
pub fn move_camera_to_tile(tile_x: usize, tile_y: usize, duration: f32) -> Story {
Story::Start(Box::new(MoveCameraToTile::new(tile_x, tile_y, duration)))
}
pub struct MoveCameraToTile {
start_tile_x: usize,
start_tile_y: usize,
end_tile_x: usize,
end_tile_y: usize,
duration: f32,
t: Arc<RwLock<f32>>,
}
impl MoveCameraToTile {
pub fn new(tile_x: usize, tile_y: usize, duration: f32) -> Self {
MoveCameraToTile {
start_tile_x: 0,
start_tile_y: 0,
end_tile_x: tile_x,
end_tile_y: tile_y,
duration,
t: Arc::new(RwLock::new(0.0)),
}
}
}
impl State<StoryboardContext> for MoveCameraToTile {
fn state_name(&self) -> String {
format!("MoveCameraToTile {},{}", self.end_tile_x, self.end_tile_y)
}
fn on_start(&mut self, ctx: StateData<StoryboardContext>) -> StoryTrans {
let state = &mut *ctx.data.state.borrow_mut();
let camera = state.world.specs_world.write_resource::<Camera>();
let current_map = state.world.specs_world.read_resource::<CurrentMap>();
let mut maps = state.world.specs_world.write_resource::<Maps>();
let map = maps.0.get_mut(¤t_map.0).unwrap();
let (x, y) = map.point_to_tile(camera.0.x, camera.0.y);
self.start_tile_x = x;
self.start_tile_y = y;
let t = self.t.clone();
let tween = Box::new(TweenState {
tween: Tween::new(0.0, 1.0, self.duration),
tween_fn: TweenFn::EaseInQuad,
apply_fn: move |value| {
*t.write().unwrap() = value;
},
});
return Trans::Push(tween);
}
fn update(&mut self, _dt: f32, ctx: StateData<StoryboardContext>) -> StoryTrans {
let state = &mut *ctx.data.state.borrow_mut();
let mut camera = state.world.specs_world.write_resource::<Camera>();
let current_map = state.world.specs_world.read_resource::<CurrentMap>();
let mut maps = state.world.specs_world.write_resource::<Maps>();
let map = maps.0.get_mut(¤t_map.0).unwrap();
let t = *self.t.read().unwrap();
let (tx, ty) = map.tile_dimensions();
let x =
(self.start_tile_x * tx as usize) as f32 + t * (self.end_tile_x * tx as usize) as f32;
let y =
(self.start_tile_y * ty as usize) as f32 + t * (self.end_tile_y * ty as usize) as f32;
camera.0.x = x;
camera.0.y = y;
map.camera = camera.0.clone();
if t >= 1.0 {
return Trans::Pop;
}
Trans::None
}
}
|
#[derive(Default)]
pub struct ResetLevel(pub bool);
|
#![deny(warnings)]
use clap::{App, Arg};
use ipmpsc::{Receiver, SharedRingBuffer};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let matches = App::new("ipmpsc-send")
.about("ipmpsc sender example")
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.arg(
Arg::with_name("map file")
.help(
"File to use for shared memory ring buffer. \
This file will be cleared if it already exists or created if it doesn't.",
)
.required(true),
)
.arg(
Arg::with_name("zero copy")
.long("zero-copy")
.help("Use zero-copy deserialization"),
)
.get_matches();
let map_file = matches.value_of("map file").unwrap();
let mut rx = Receiver::new(SharedRingBuffer::create(map_file, 32 * 1024)?);
let zero_copy = matches.is_present("zero copy");
println!(
"Ready! Now run `cargo run --example ipmpsc-send {}` in another terminal.",
map_file
);
loop {
if zero_copy {
println!("received {:?}", rx.zero_copy_context().recv::<&str>()?);
} else {
println!("received {:?}", rx.recv::<String>()?);
}
}
}
|
#![allow(unused)]
use std::f32::{consts::TAU, EPSILON};
// work around cargo bug
use crate::{
position::{SignedTilePosition, WorldCoords},
TilePosition,
};
pub fn floats_equal(f1: f32, f2: f32) -> bool {
(f1 - f2).abs() < EPSILON
}
#[allow(
clippy::as_conversions,
clippy::cast_precision_loss,
clippy::cast_possible_truncation
)]
pub fn round(n: f32, decimals: usize) -> f32 {
let factor = 10_u64.pow(decimals as u32) as f64;
((f64::from(n) * factor).round() / factor) as f32
}
pub fn round_wc(wc: &WorldCoords) -> WorldCoords {
let WorldCoords { x, y, tile_size } = wc;
WorldCoords::new(round(*x, 3), round(*y, 3), *tile_size)
}
pub fn round_tp(tp: &TilePosition) -> TilePosition {
let TilePosition { x, y, rel_x, rel_y } = tp;
TilePosition {
x: *x,
y: *y,
rel_x: round(*rel_x, 3),
rel_y: round(*rel_y, 3),
}
}
#[cfg(test)]
pub fn round_otp(tp: Option<TilePosition>) -> Option<TilePosition> {
let TilePosition { x, y, rel_x, rel_y } = tp?;
Some(TilePosition {
x,
y,
rel_x: round(rel_x, 3),
rel_y: round(rel_y, 3),
})
}
pub fn round_stp(stp: &SignedTilePosition) -> SignedTilePosition {
let SignedTilePosition { x, y, rel_x, rel_y } = stp;
SignedTilePosition {
x: *x,
y: *y,
rel_x: round(*rel_x, 3),
rel_y: round(*rel_y, 3),
}
}
#[cfg(test)]
pub fn round_ostp(tp: Option<SignedTilePosition>) -> Option<SignedTilePosition> {
let SignedTilePosition { x, y, rel_x, rel_y } = tp?;
Some(SignedTilePosition {
x,
y,
rel_x: round(rel_x, 3),
rel_y: round(rel_y, 3),
})
}
|
use std::error::Error;
use tokio::sync::oneshot;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let (tx, rx) = oneshot::channel();
tokio::spawn(async move {
if let Err(_) = tx.send("abc") {
println!("failed send");
}
});
let r = rx.await?;
println!("received = {}", r);
Ok(())
}
|
//! A provider of ordered timestamps, exposed as a [`SequenceNumber`].
use std::sync::atomic::{AtomicU64, Ordering};
use crossbeam_utils::CachePadded;
use data_types::SequenceNumber;
/// A concurrency-safe provider of totally ordered [`SequenceNumber`] values.
///
/// Given a single [`TimestampOracle`] instance, the [`SequenceNumber`] values
/// returned by calling [`TimestampOracle::next()`] are guaranteed to be totally
/// ordered and consecutive.
///
/// No ordering exists across independent [`TimestampOracle`] instances.
#[derive(Debug)]
pub(crate) struct TimestampOracle(CachePadded<AtomicU64>);
impl TimestampOracle {
/// Construct a [`TimestampOracle`] that returns values starting from
/// `last_value + 1`.
pub(crate) fn new(last_value: u64) -> Self {
Self(CachePadded::new(AtomicU64::new(last_value + 1)))
}
/// Obtain the next [`SequenceNumber`].
pub(crate) fn next(&self) -> SequenceNumber {
// Correctness:
//
// A relaxed atomic store has a consistent modification order, with two
// racing threads calling fetch_add resolving into a defined ordering of
// one having called before the other. This ordering will never change
// or diverge between threads.
let v = self.0.fetch_add(1, Ordering::Relaxed);
SequenceNumber::new(v)
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
/// Ensure the next value read from a newly initialised [`TimestampOracle`]
/// is always one greater than the init value.
///
/// This ensures that a total ordering is derived even if a caller provides
/// the last actual value, or the next expected value (at the expense of a
/// possible gap in the sequence). This helps avoid off-by-one bugs in the
/// caller.
#[test]
fn test_init_next_val() {
let oracle = TimestampOracle::new(41);
assert_eq!(oracle.next().get(), 42);
}
/// A property test ensuring that for N threads competing to sequence M
/// operations, a total order of operations is derived from consecutive
/// timestamps returned by a single [`TimestampOracle`] instance.
#[test]
#[allow(clippy::needless_collect)]
fn test_concurrency() {
// The number of threads that will race to obtain N_SEQ each.
const N_THREADS: usize = 10;
// The number of SequenceNumber timestamps each thread will acquire.
const N_SEQ: usize = 100;
// The init value for the TimestampOracle
const LAST_VALUE: usize = 0;
// The total number of SequenceNumber to be acquired in this test.
const TOTAL_SEQ: usize = N_SEQ * N_THREADS;
let oracle = Arc::new(TimestampOracle::new(LAST_VALUE as u64));
let barrier = Arc::new(std::sync::Barrier::new(N_THREADS));
// Spawn the desired number of threads, synchronise their starting
// point, and then race them to obtain TOTAL_SEQ number of timestamps.
//
// Each thread returns an vector of the timestamp values it acquired.
let handles = (0..N_THREADS)
.map(|_| {
let oracle = Arc::clone(&oracle);
let barrier = Arc::clone(&barrier);
std::thread::spawn(move || {
barrier.wait(); // synchronise start time
(0..N_SEQ).map(|_| oracle.next().get()).collect::<Vec<_>>()
})
})
.collect::<Vec<_>>();
// Collect all the timestamps from all the threads
let mut timestamps = handles
.into_iter()
.flat_map(|h| h.join().expect("thread panic"))
.collect::<Vec<_>>();
// Sort the timestamps
timestamps.sort_unstable();
// Assert the complete set of values from the expected range appear,
// unduplicated, and totally ordered.
let expected = (LAST_VALUE + 1)..TOTAL_SEQ + 1;
timestamps
.into_iter()
.zip(expected)
.for_each(|(got, want)| assert_eq!(got, want as u64));
}
}
|
use juniper::{GraphQLInputObject, GraphQLObject};
#[derive(GraphQLInputObject)]
struct ObjB {
id: i32,
}
#[derive(GraphQLObject)]
struct ObjA {
id: ObjB,
}
fn main() {}
|
//! Integration tests
pub mod health;
pub mod helpers;
pub mod user;
|
use bytes::{Bytes, BytesMut};
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use data_types::{NamespaceId, TableId};
use dml::DmlWrite;
use generated_types::influxdata::pbdata::v1::DatabaseBatch;
use mutable_batch::MutableBatch;
use mutable_batch_lp::lines_to_batches;
use mutable_batch_tests::benchmark_lp;
use prost::Message;
fn generate_pbdata_bytes() -> Vec<(String, (usize, Bytes))> {
benchmark_lp()
.into_iter()
.map(|(bench, lp)| {
let batches = lines_to_batches(&lp, 0).unwrap();
let data = batches
.into_iter()
.enumerate()
.map(|(idx, (_table_name, batch))| (TableId::new(idx as _), batch))
.collect();
let write = DmlWrite::new(
NamespaceId::new(42),
data,
"bananas".into(),
Default::default(),
);
let database_batch = mutable_batch_pb::encode::encode_write(42, &write);
let mut bytes = BytesMut::new();
database_batch.encode(&mut bytes).unwrap();
(bench, (lp.len(), bytes.freeze()))
})
.collect()
}
pub fn write_pb(c: &mut Criterion) {
let mut group = c.benchmark_group("write_pb");
for (bench, (lp_bytes, pbdata_bytes)) in generate_pbdata_bytes() {
group.throughput(Throughput::Bytes(lp_bytes as u64));
group.bench_function(BenchmarkId::from_parameter(bench), |b| {
b.iter(|| {
let mut batch = MutableBatch::new();
let database_batch = DatabaseBatch::decode(pbdata_bytes.clone()).unwrap();
assert_eq!(database_batch.table_batches.len(), 1);
mutable_batch_pb::decode::write_table_batch(
&mut batch,
&database_batch.table_batches[0],
)
.unwrap();
});
});
}
group.finish();
}
criterion_group!(benches, write_pb);
criterion_main!(benches);
|
use super::{Array, Index, Length, Slice};
use crate::htab;
use std::borrow::Borrow;
use std::collections::hash_map::RandomState;
use std::marker::PhantomData;
use std::{hash, iter};
struct Field<Q: ?Sized>(PhantomData<fn(&Q) -> &Q>);
impl<K: Borrow<Q>, Q: ?Sized + Eq + hash::Hash> htab::Field<K> for Field<Q> {
type Type = Q;
#[inline]
fn eq(c: &K, v: &Q) -> bool {
*c.borrow() == *v
}
#[inline]
fn hash<S: hash::BuildHasher>(hs: &S, v: &Q) -> u64 {
htab::hash(hs, v)
}
}
#[derive(Clone)]
pub struct ISet<I: Index, K, S = RandomState>(htab::HTab<K, S>, PhantomData<fn() -> I>);
pub enum ISetEntry<'a, I: Index, K, S> {
Vacant(ISetVacant<'a, I, K, S>),
Occupied(ISetOccupied<'a, I, K, S>),
}
pub struct ISetOccupied<'a, I: Index, K, S>(htab::Occupied<'a, K, S>, PhantomData<fn() -> I>);
pub struct ISetVacant<'a, I: Index, K, S>(htab::Vacant<'a, K, S>, PhantomData<fn() -> I>);
impl<'a, I: Index, K, S> ISetOccupied<'a, I, K, S> {
#[inline]
pub fn get(&self) -> &K {
self.0.get()
}
#[inline]
pub fn index(&self) -> I {
unsafe { I::from_usize_unchecked(self.0.index()) }
}
}
impl<'a, I: Index, K: Eq + hash::Hash, S: hash::BuildHasher + Default> ISetVacant<'a, I, K, S> {
#[inline]
pub fn insert(self, k: K) -> ISetOccupied<'a, I, K, S> {
let _ = I::from_usize(self.0.htab().len() + 1);
ISetOccupied(self.0.insert(k), PhantomData)
}
}
impl<I: Index, K, S: Default> ISet<I, K, S> {
#[inline]
pub fn new() -> Self {
ISet(htab::HTab::new(), PhantomData)
}
}
impl<I: Index, K, S: Default> Default for ISet<I, K, S> {
#[inline(always)]
fn default() -> Self {
Self::new()
}
}
impl<I: Index, K, S> ISet<I, K, S> {
#[inline(always)]
pub fn len(&self) -> Length<I> {
Length::new(self.0.len())
}
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[inline(always)]
pub fn values(&self) -> &Slice<I, K> {
Slice::at(&*self.0.values())
}
#[inline(always)]
pub fn at(&self, i: I) -> &K {
&self.values()[i]
}
#[inline(always)]
pub fn into_values(self) -> Array<I, K> {
Array::new_vec(self.0.into_values())
}
}
impl<I: Index, K: Eq + hash::Hash, S: hash::BuildHasher> ISet<I, K, S> {
#[inline]
pub fn get<'a, Q: ?Sized + Eq + hash::Hash>(&'a self, k: &Q) -> Option<I>
where
K: Borrow<Q>,
{
Some(unsafe { I::from_usize_unchecked(self.0.find::<Field<Q>>(k)?.0) })
}
#[inline]
pub fn entry<'a, Q: ?Sized + Eq + hash::Hash>(&'a mut self, k: &Q) -> ISetEntry<'a, I, K, S>
where
K: Borrow<Q>,
{
match self.0.entry::<Field<Q>>(k) {
htab::Entry::Vacant(e) => ISetEntry::Vacant(ISetVacant(e, PhantomData)),
htab::Entry::Occupied(e) => ISetEntry::Occupied(ISetOccupied(e, PhantomData)),
}
}
}
impl<I: Index, K: Eq + hash::Hash, S: hash::BuildHasher + Default> ISet<I, K, S> {
#[inline]
pub fn check_insert(&mut self, k: K) -> Result<I, I> {
match self.entry(&k) {
ISetEntry::Vacant(e) => Ok(e.insert(k).index()),
ISetEntry::Occupied(e) => Err(e.index()),
}
}
#[inline]
pub fn check_clone_insert(&mut self, k: &K) -> Result<I, I>
where
K: Clone,
{
match self.entry(k) {
ISetEntry::Vacant(e) => Ok(e.insert(k.clone()).index()),
ISetEntry::Occupied(e) => Err(e.index()),
}
}
#[inline]
pub fn insert(&mut self, k: K) -> I {
match self.check_insert(k) {
Ok(i) => i,
Err(i) => i,
}
}
pub fn singleton(k: K) -> Self {
let mut r = ISet::new();
r.insert(k);
r
}
}
impl<I: Index, K: Eq + hash::Hash, S: hash::BuildHasher + Default> iter::FromIterator<K>
for ISet<I, K, S>
{
fn from_iter<T: IntoIterator<Item = K>>(iter: T) -> Self {
let mut r = ISet::new();
for v in iter {
r.insert(v);
}
r
}
}
|
use std::{fmt::Write, sync::Arc};
use crate::{
extensions::{Extension, ExtensionContext, ExtensionFactory, NextExecute, NextParseQuery},
parser::types::{ExecutableDocument, OperationType, Selection},
PathSegment, Response, ServerResult, Variables,
};
/// Logger extension
#[cfg_attr(docsrs, doc(cfg(feature = "log")))]
pub struct Logger;
impl ExtensionFactory for Logger {
fn create(&self) -> Arc<dyn Extension> {
Arc::new(LoggerExtension)
}
}
struct LoggerExtension;
#[async_trait::async_trait]
impl Extension for LoggerExtension {
async fn parse_query(
&self,
ctx: &ExtensionContext<'_>,
query: &str,
variables: &Variables,
next: NextParseQuery<'_>,
) -> ServerResult<ExecutableDocument> {
let document = next.run(ctx, query, variables).await?;
let is_schema = document
.operations
.iter()
.filter(|(_, operation)| operation.node.ty == OperationType::Query)
.any(|(_, operation)| operation.node.selection_set.node.items.iter().any(|selection| matches!(&selection.node, Selection::Field(field) if field.node.name.node == "__schema")));
if !is_schema {
log::info!(
target: "async-graphql",
"[Execute] {}", ctx.stringify_execute_doc(&document, variables)
);
}
Ok(document)
}
async fn execute(
&self,
ctx: &ExtensionContext<'_>,
operation_name: Option<&str>,
next: NextExecute<'_>,
) -> Response {
let resp = next.run(ctx, operation_name).await;
if resp.is_err() {
for err in &resp.errors {
if !err.path.is_empty() {
let mut path = String::new();
for (idx, s) in err.path.iter().enumerate() {
if idx > 0 {
path.push('.');
}
match s {
PathSegment::Index(idx) => {
let _ = write!(&mut path, "{}", idx);
}
PathSegment::Field(name) => {
let _ = write!(&mut path, "{}", name);
}
}
}
log::info!(
target: "async-graphql",
"[Error] path={} message={}", path, err.message,
);
} else {
log::info!(
target: "async-graphql",
"[Error] message={}", err.message,
);
}
}
}
resp
}
}
|
use parser::ArgumentParser;
use super::Store;
use super::{StoreTrue, StoreFalse};
use test_parser::{check_ok};
fn store_true(args: &[&str]) -> bool {
let mut verbose = false;
{
let mut ap = ArgumentParser::new();
ap.refer(&mut verbose)
.add_option(&["-t", "--true"], StoreTrue,
"Store true action");
check_ok(&ap, args);
}
return verbose;
}
#[test]
fn test_store_true() {
assert!(!store_true(&["./argparse_test"]));
assert!(store_true(&["./argparse_test", "--true"]));
}
fn store_false(args: &[&str]) -> bool {
let mut verbose = true;
{
let mut ap = ArgumentParser::new();
ap.refer(&mut verbose)
.add_option(&["-f", "--false"], StoreFalse,
"Store false action");
check_ok(&ap, args);
}
return verbose;
}
#[test]
fn test_store_false() {
assert!(store_false(&["./argparse_test"]));
assert!(!store_false(&["./argparse_test", "--false"]));
}
fn store_bool(args: &[&str]) -> bool {
let mut verbose = false;
{
let mut ap = ArgumentParser::new();
ap.refer(&mut verbose)
.add_option(&["-f", "--false"], StoreFalse,
"Store false action")
.add_option(&["-t", "--true"], StoreTrue,
"Store false action");
check_ok(&ap, args);
}
return verbose;
}
#[test]
fn test_bool() {
assert!(!store_bool(&["./argparse_test"]));
assert!(store_bool(&["./argparse_test", "-t"]));
assert!(!store_bool(&["./argparse_test", "-f"]));
assert!(store_bool(&["./argparse_test", "-fft"]));
assert!(!store_bool(&["./argparse_test", "-fffft", "-f"]));
assert!(store_bool(&["./argparse_test", "--false", "-fffft", "-f",
"--true"]));
}
fn set_bool(args: &[&str]) -> bool {
let mut verbose = false;
{
let mut ap = ArgumentParser::new();
ap.refer(&mut verbose)
.add_option(&["-s", "--set"], Store,
"Set boolean value");
check_ok(&ap, args);
}
return verbose;
}
#[test]
fn test_set_bool() {
assert!(!set_bool(&["./argparse_test"]));
assert!(set_bool(&["./argparse_test", "-strue"]));
assert!(!set_bool(&["./argparse_test", "-sfalse"]));
// Unfortunately other values do not work
}
#[test]
#[should_panic(expected="Bad value yes")]
fn test_bad_bools1() {
assert!(!set_bool(&["./argparse_test", "-syes"]));
}
#[test]
#[should_panic(expected="Bad value no")]
fn test_bad_bools2() {
assert!(!set_bool(&["./argparse_test", "-sno"]));
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::ime::{Ime, ImeState};
use failure::ResultExt;
use fidl::endpoints::{ClientEnd, RequestStream, ServerEnd};
use fidl_fuchsia_ui_input as uii;
use fuchsia_syslog::fx_log_err;
use futures::prelude::*;
use parking_lot::Mutex;
use std::sync::{Arc, Weak};
pub struct ImeServiceState {
pub keyboard_visible: bool,
pub active_ime: Option<Weak<Mutex<ImeState>>>,
pub visibility_listeners: Vec<uii::ImeVisibilityServiceControlHandle>,
}
/// The internal state of the IMEService, usually held behind an Arc<Mutex>
/// so it can be accessed from multiple places.
impl ImeServiceState {
pub fn update_keyboard_visibility(&mut self, visible: bool) {
self.keyboard_visible = visible;
self.visibility_listeners.retain(|listener| {
// drop listeners if they error on send
listener.send_on_keyboard_visibility_changed(visible).is_ok()
});
}
}
/// The ImeService is a central, discoverable service responsible for creating new IMEs when a new
/// text field receives focus. It also advertises the ImeVisibilityService, which allows a client
/// (usually a soft keyboard container) to receive updates when the keyboard has been requested to
/// be shown or hidden.
#[derive(Clone)]
pub struct ImeService(Arc<Mutex<ImeServiceState>>);
impl ImeService {
pub fn new() -> ImeService {
ImeService(Arc::new(Mutex::new(ImeServiceState {
keyboard_visible: false,
active_ime: None,
visibility_listeners: Vec::new(),
})))
}
/// Only updates the keyboard visibility if IME passed in is active
pub fn update_keyboard_visibility_from_ime(
&self,
check_ime: &Arc<Mutex<ImeState>>,
visible: bool,
) {
let mut state = self.0.lock();
let active_ime_weak = match &state.active_ime {
Some(val) => val,
None => return,
};
let active_ime = match active_ime_weak.upgrade() {
Some(val) => val,
None => return,
};
if Arc::ptr_eq(check_ime, &active_ime) {
state.update_keyboard_visibility(visible);
}
}
fn get_input_method_editor(
&mut self,
keyboard_type: uii::KeyboardType,
action: uii::InputMethodAction,
initial_state: uii::TextInputState,
client: ClientEnd<uii::InputMethodEditorClientMarker>,
editor: ServerEnd<uii::InputMethodEditorMarker>,
) {
if let Ok(client_proxy) = client.into_proxy() {
let ime = Ime::new(keyboard_type, action, initial_state, client_proxy, self.clone());
let mut state = self.0.lock();
state.active_ime = Some(ime.downgrade());
if let Ok(chan) = fuchsia_async::Channel::from_channel(editor.into_channel()) {
ime.bind_ime(chan);
}
}
}
pub fn show_keyboard(&self) {
self.0.lock().update_keyboard_visibility(true);
}
pub fn hide_keyboard(&self) {
self.0.lock().update_keyboard_visibility(false);
}
fn inject_input(&mut self, event: uii::InputEvent) {
let ime = {
let state = self.0.lock();
let active_ime_weak = match state.active_ime {
Some(ref v) => v,
None => return, // no currently active IME
};
match Ime::upgrade(active_ime_weak) {
Some(active_ime) => active_ime,
None => return, // IME no longer exists
}
};
ime.inject_input(event);
}
pub fn bind_ime_service(&self, chan: fuchsia_async::Channel) {
let mut self_clone = self.clone();
fuchsia_async::spawn(
async move {
let mut stream = uii::ImeServiceRequestStream::from_channel(chan);
while let Some(msg) = await!(stream.try_next())
.context("error reading value from IME service request stream")?
{
match msg {
uii::ImeServiceRequest::GetInputMethodEditor {
keyboard_type,
action,
initial_state,
client,
editor,
..
} => {
self_clone.get_input_method_editor(
keyboard_type,
action,
initial_state,
client,
editor,
);
}
uii::ImeServiceRequest::ShowKeyboard { .. } => {
self_clone.show_keyboard();
}
uii::ImeServiceRequest::HideKeyboard { .. } => {
self_clone.hide_keyboard();
}
uii::ImeServiceRequest::InjectInput { event, .. } => {
self_clone.inject_input(event);
}
}
}
Ok(())
}
.unwrap_or_else(|e: failure::Error| fx_log_err!("{:?}", e)),
);
}
pub fn bind_ime_visibility_service(&self, chan: fuchsia_async::Channel) {
let self_clone = self.clone();
fuchsia_async::spawn(
async move {
let stream = uii::ImeVisibilityServiceRequestStream::from_channel(chan);
let control_handle = stream.control_handle();
let mut state = self_clone.0.lock();
if control_handle
.send_on_keyboard_visibility_changed(state.keyboard_visible)
.is_ok()
{
state.visibility_listeners.push(control_handle);
}
Ok(())
}
.unwrap_or_else(|e: failure::Error| fx_log_err!("{:?}", e)),
);
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::ime::{HID_USAGE_KEY_ENTER, HID_USAGE_KEY_LEFT};
use crate::test_helpers::default_state;
use fidl;
use fidl_fuchsia_ui_input as uii;
use fuchsia_async as fasync;
use pin_utils::pin_mut;
fn async_service_test<T, F>(test_fn: T)
where
T: FnOnce(uii::ImeServiceProxy, uii::ImeVisibilityServiceProxy) -> F,
F: Future,
{
let mut executor = fasync::Executor::new()
.expect("Creating fuchsia_async executor for IME service tests failed");
let ime_service = ImeService::new();
let ime_service_proxy = {
let (service_proxy, service_server_end) =
fidl::endpoints::create_proxy::<uii::ImeServiceMarker>().unwrap();
let chan = fasync::Channel::from_channel(service_server_end.into_channel()).unwrap();
ime_service.bind_ime_service(chan);
service_proxy
};
let visibility_service_proxy = {
let (service_proxy, service_server_end) =
fidl::endpoints::create_proxy::<uii::ImeVisibilityServiceMarker>().unwrap();
let chan = fasync::Channel::from_channel(service_server_end.into_channel()).unwrap();
ime_service.bind_ime_visibility_service(chan);
service_proxy
};
let done = test_fn(ime_service_proxy, visibility_service_proxy);
pin_mut!(done);
// this will return a non-ready future if the tests stall
let res = executor.run_until_stalled(&mut done);
assert!(res.is_ready());
}
fn bind_ime_for_test(
ime_service: &uii::ImeServiceProxy,
) -> (uii::InputMethodEditorProxy, uii::InputMethodEditorClientRequestStream) {
let (ime_proxy, ime_server_end) =
fidl::endpoints::create_proxy::<uii::InputMethodEditorMarker>().unwrap();
let (editor_client_end, editor_request_stream) =
fidl::endpoints::create_request_stream().unwrap();
ime_service
.get_input_method_editor(
uii::KeyboardType::Text,
uii::InputMethodAction::Done,
&mut default_state(),
editor_client_end,
ime_server_end,
)
.unwrap();
(ime_proxy, editor_request_stream)
}
fn simulate_keypress(ime_service: &uii::ImeServiceProxy, code_point: u32, hid_usage: u32) {
ime_service
.inject_input(&mut uii::InputEvent::Keyboard(uii::KeyboardEvent {
event_time: 0,
device_id: 0,
phase: uii::KeyboardEventPhase::Pressed,
hid_usage: hid_usage,
code_point: code_point,
modifiers: 0,
}))
.unwrap();
ime_service
.inject_input(&mut uii::InputEvent::Keyboard(uii::KeyboardEvent {
event_time: 0,
device_id: 0,
phase: uii::KeyboardEventPhase::Released,
hid_usage: hid_usage,
code_point: code_point,
modifiers: 0,
}))
.unwrap();
}
#[test]
fn test_visibility_service_sends_updates() {
async_service_test(|ime_service, visibility_service| {
async move {
let mut ev_stream = visibility_service.take_event_stream();
// expect initial update with current status
let msg = await!(ev_stream.try_next())
.expect("expected working event stream")
.expect("visibility service should have sent message");
let uii::ImeVisibilityServiceEvent::OnKeyboardVisibilityChanged { visible } = msg;
assert_eq!(visible, false);
// expect asking for keyboard to reclose results in another message
ime_service.hide_keyboard().unwrap();
let msg = await!(ev_stream.try_next())
.expect("expected working event stream")
.expect("visibility service should have sent message");
let uii::ImeVisibilityServiceEvent::OnKeyboardVisibilityChanged { visible } = msg;
assert_eq!(visible, false);
// expect asking for keyboard to to open in another message
ime_service.show_keyboard().unwrap();
let msg = await!(ev_stream.try_next())
.expect("expected working event stream")
.expect("visibility service should have sent message");
let uii::ImeVisibilityServiceEvent::OnKeyboardVisibilityChanged { visible } = msg;
assert_eq!(visible, true);
// expect asking for keyboard to close/open from IME works
let (ime, _editor_stream) = bind_ime_for_test(&ime_service);
ime.hide().unwrap();
let msg = await!(ev_stream.try_next())
.expect("expected working event stream")
.expect("visibility service should have sent message");
let uii::ImeVisibilityServiceEvent::OnKeyboardVisibilityChanged { visible } = msg;
assert_eq!(visible, false);
ime.show().unwrap();
let msg = await!(ev_stream.try_next())
.expect("expected working event stream")
.expect("visibility service should have sent message");
let uii::ImeVisibilityServiceEvent::OnKeyboardVisibilityChanged { visible } = msg;
assert_eq!(visible, true);
}
});
}
#[test]
fn test_inject_input_updates_ime() {
async_service_test(|ime_service, _visibility_service| {
async move {
// expect asking for keyboard to close/open from IME works
let (_ime, mut editor_stream) = bind_ime_for_test(&ime_service);
// type 'a'
simulate_keypress(&ime_service, 'a'.into(), 0);
let msg = await!(editor_stream.try_next())
.expect("expected working event stream")
.expect("ime should have sent message");
if let uii::InputMethodEditorClientRequest::DidUpdateState {
state, event: _, ..
} = msg
{
assert_eq!(state.text, "a");
assert_eq!(state.selection.base, 1);
assert_eq!(state.selection.extent, 1);
} else {
panic!("request should be DidUpdateState");
}
// press left arrow
simulate_keypress(&ime_service, 0, HID_USAGE_KEY_LEFT);
let msg = await!(editor_stream.try_next())
.expect("expected working event stream")
.expect("ime should have sent message");
if let uii::InputMethodEditorClientRequest::DidUpdateState {
state, event: _, ..
} = msg
{
assert_eq!(state.text, "a");
assert_eq!(state.selection.base, 0);
assert_eq!(state.selection.extent, 0);
} else {
panic!("request should be DidUpdateState");
}
}
});
}
#[test]
fn test_inject_input_sends_action() {
async_service_test(|ime_service, _visibility_service| {
async move {
let (_ime, mut editor_stream) = bind_ime_for_test(&ime_service);
simulate_keypress(&ime_service, 0, HID_USAGE_KEY_ENTER);
let msg = await!(editor_stream.try_next())
.expect("expected working event stream")
.expect("ime should have sent message");
if let uii::InputMethodEditorClientRequest::OnAction { action, .. } = msg {
assert_eq!(action, uii::InputMethodAction::Done);
} else {
panic!("request should be OnAction");
}
}
})
}
}
|
use crate::clockin::{ClockAction, LineClockAction};
use crate::s_time::STime;
use gobble::*;
parser! {
(Date->(usize,usize,Option<isize>))
(common::UInt,last(ws__('/'),common::UInt),maybe(last(ws__('/'),common::Int)))
}
parser! {
(StrVal -> String)
or(common::Quoted,common::Ident)
}
parser! {
(Comment ->())
('#',Any.except("\n\r,").istar()).ig()
}
pub fn next_<P: Parser>(p: P) -> impl Parser<Out = P::Out> {
sep_star(", \t\n\r".istar(), Comment).ig_then(p)
}
parser! {
(ToEnd->()),
(" ,\t\n\r".istar(),eoi).ig()
}
parser! {
(STIME -> STime),
(common::Int, ":", common::Int).map(|(a, _, b)| STime::new(a, b))
}
pub fn line_clock_actions() -> impl Parser<Out = Vec<LineClockAction>> {
star_until_ig(
next_((line_col, ClockACTION)).map(|((line, col), action)| LineClockAction {
line,
col,
action,
}),
ToEnd,
)
}
parser! {
(Group->ClockAction)
(
'$',
StrVal,
ws__('['),
star_until_ig(next_(StrVal), next_("]")),
)
.map(|(_, k, _, v)| ClockAction::DefGroup(k, v))
}
parser! {
(ClockACTION -> ClockAction)
or!(
//handle tags
('_', StrVal).map(|(_, s)| ClockAction::AddTag(s)),
("__", maybe(StrVal)).map(|(_, os)| ClockAction::ClearTags(os)),
//handle time
('-', STIME).map(|(_, t)| ClockAction::Out(t)),
Date.map(|(d, m, yop)| ClockAction::SetDate(d, m, yop)),
(STIME, maybe(('-', STIME))).map(|(i, op)| match op {
Some((_, out)) => ClockAction::InOut(i, out),
None => ClockAction::In(i),
}),
('=', StrVal, ws__(':'), common::Int).map(|(_, k, _, v)| ClockAction::SetNum(k, v)),
Group,
(StrVal, maybe((ws__('='), common::Int))).map(|(k, set)| match set {
Some((_, v)) => ClockAction::SetNum(k, v),
None => ClockAction::SetJob(k),
}),
)
}
#[cfg(test)]
pub mod test {
use super::*;
#[test]
pub fn str_val_parses_dashes() {
assert_eq!(StrVal.parse_s("hello "), Ok("hello".to_string()));
assert_eq!(StrVal.parse_s("hel_p_me@52"), Ok("hel_p_me".to_string()));
assert_eq!(
StrVal.parse_s(r#""hello\tworld"poo "#),
Ok("hello\tworld".to_string())
);
assert!(StrVal.parse_s("_hello").is_err());
}
}
|
/*
Copyright 2020 Timo Saarinen
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
use super::*;
/// GSA - GNSS dilution of position (DOP) and active satellites
#[derive(Clone, Debug, PartialEq)]
pub struct GsaData {
/// Navigation system
pub source: NavigationSystem,
/// Mode 1: true = automatic, false = manual
pub mode1_automatic: Option<bool>,
/// Mode 2, fix type:
pub mode2_3d: Option<GsaFixMode>,
/// PRN numbers used (space for 12)
pub prn_numbers: Vec<u8>,
/// Position (3D) dilution of precision
pub pdop: Option<f64>,
/// Horizontal dilution of precision
pub hdop: Option<f64>,
/// Vertical dilution of precision
pub vdop: Option<f64>,
}
/// GSA position fix type
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GsaFixMode {
/// No fix.
NotAvailable,
/// 2D fix.
Fix2D,
/// 3d fix.
Fix3D,
}
impl std::fmt::Display for GsaFixMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
GsaFixMode::NotAvailable => write!(f, "no available"),
GsaFixMode::Fix2D => write!(f, "2D fix"),
GsaFixMode::Fix3D => write!(f, "3D fix"),
}
}
}
// -------------------------------------------------------------------------------------------------
/// xxGSA: GPS DOP and active satellites
pub(crate) fn handle(
sentence: &str,
nav_system: NavigationSystem,
) -> Result<ParsedMessage, ParseError> {
let split: Vec<&str> = sentence.split(',').collect();
Ok(ParsedMessage::Gsa(GsaData {
source: nav_system,
mode1_automatic: {
let s = split.get(1).unwrap_or(&"");
match *s {
"M" => Some(false),
"A" => Some(true),
"" => None,
_ => {
return Err(format!("Invalid GPGSA mode: {}", s).into());
}
}
},
mode2_3d: {
let s = split.get(2).unwrap_or(&"");
match *s {
"1" => Some(GsaFixMode::NotAvailable),
"2" => Some(GsaFixMode::Fix2D),
"3" => Some(GsaFixMode::Fix3D),
"" => None,
_ => {
return Err(format!("Invalid GPGSA fix type: {}", s).into());
}
}
},
prn_numbers: {
let mut v = Vec::with_capacity(12);
for i in 3..15 {
if split.get(i).unwrap_or(&"") != &"" {
if let Some(val) = pick_number_field(&split, i)? {
v.push(val);
}
}
}
v
},
pdop: pick_number_field(&split, 15)?,
hdop: pick_number_field(&split, 16)?,
vdop: pick_number_field(&split, 17)?,
}))
}
// -------------------------------------------------------------------------------------------------
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_gpgsa() {
let mut p = NmeaParser::new();
match p.parse_sentence("$GPGSA,A,3,19,28,14,18,27,22,31,39,,,,,1.7,1.0,1.3*34") {
Ok(ps) => {
match ps {
// The expected result
ParsedMessage::Gsa(gsa) => {
assert_eq!(gsa.mode1_automatic, Some(true));
assert_eq!(gsa.mode2_3d, Some(GsaFixMode::Fix3D));
assert_eq!(gsa.prn_numbers, vec![19, 28, 14, 18, 27, 22, 31, 39]);
assert_eq!(gsa.pdop, Some(1.7));
assert_eq!(gsa.hdop, Some(1.0));
assert_eq!(gsa.vdop, Some(1.3));
}
ParsedMessage::Incomplete => {
assert!(false);
}
_ => {
assert!(false);
}
}
}
Err(e) => {
assert_eq!(e.to_string(), "OK");
}
}
}
}
|
use rustc_hash::FxHashSet as HashSet;
pub const INPUT: &str = include_str!("../input.txt");
type Position = (i32, i32, i32);
pub fn parse_input(input: &str) -> HashSet<Position> {
let values = input
.trim()
.split(['\n', ','])
.map(|s| s.parse().unwrap())
.collect::<Vec<_>>();
values.chunks_exact(3).map(|c| (c[0], c[1], c[2])).collect()
}
pub fn part_one(positions: &HashSet<Position>) -> usize {
positions
.iter()
.flat_map(|&(x, y, z)| {
[
(x + 1, y, z),
(x - 1, y, z),
(x, y + 1, z),
(x, y - 1, z),
(x, y, z + 1),
(x, y, z - 1),
]
})
.filter(|p| !positions.contains(p))
.count()
}
pub fn part_two(positions: &HashSet<Position>) -> usize {
let min_x = positions.iter().map(|&(x, _, _)| x).min().unwrap();
let max_x = positions.iter().map(|&(x, _, _)| x).max().unwrap();
let x_bounds = min_x - 1..=max_x + 1;
let min_y = positions.iter().map(|&(_, y, _)| y).min().unwrap();
let max_y = positions.iter().map(|&(_, y, _)| y).max().unwrap();
let y_bounds = min_y - 1..=max_y + 1;
let min_z = positions.iter().map(|&(_, _, z)| z).min().unwrap();
let max_z = positions.iter().map(|&(_, _, z)| z).max().unwrap();
let z_bounds = min_z - 1..=max_z + 1;
let start_position = (max_x + 1, max_y, max_z);
let mut surface_area = 0;
let mut stack = vec![start_position];
let mut seen = HashSet::default();
while let Some((x, y, z)) = stack.pop() {
let adjacent_positions = [
(x + 1, y, z),
(x - 1, y, z),
(x, y + 1, z),
(x, y - 1, z),
(x, y, z + 1),
(x, y, z - 1),
];
let iter = adjacent_positions.into_iter().filter(|(x, y, z)| {
x_bounds.contains(x) && y_bounds.contains(y) && z_bounds.contains(z)
});
for p in iter {
if positions.contains(&p) {
surface_area += 1;
} else if !seen.contains(&p) {
stack.push(p);
seen.insert(p);
}
}
}
surface_area
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_part_one() {
let positions = parse_input(INPUT);
assert_eq!(part_one(&positions), 3586);
}
#[test]
fn test_part_two() {
let positions = parse_input(INPUT);
assert_eq!(part_two(&positions), 2072);
}
}
|
pub fn init_logging(modules: &[&str]) {
let mut logger = env_logger::Builder::new();
logger.format(|buffer, record: &log::Record| {
use std::io::Write;
use env_logger::fmt::Color;
let mut prefix_style = buffer.style();
let prefix;
match record.level() {
log::Level::Trace => {
prefix = "Trace: ";
prefix_style.set_bold(true);
}
log::Level::Debug => {
prefix = "";
}
log::Level::Info => {
prefix = "";
}
log::Level::Warn => {
prefix = "Warning: ";
prefix_style.set_color(Color::Yellow).set_bold(true);
}
log::Level::Error => {
prefix = "Error: ";
prefix_style.set_color(Color::Red).set_bold(true);
}
};
writeln!(
buffer,
"{}{}",
prefix_style.value(prefix),
record.args()
)
});
for module in modules {
logger.filter_module(module, log::LevelFilter::Info);
}
logger.init();
}
|
use std::net::UdpSocket as UdpSocketStd;
use tokio::net::UdpSocket as UdpSocketTokio;
use std::net::SocketAddr;
use tokio::reactor::Handle;
use std::io;
use super::TIMEOUT;
use std::time::Duration;
pub async fn udp_get(addr: &SocketAddr, data: Vec<u8>)
-> io::Result<Vec<u8>> {
let uss = UdpSocketStd::bind("0.0.0.0:0")?;
uss.set_read_timeout(Some(Duration::from_secs(TIMEOUT)))?;
let ust = UdpSocketTokio::from_std(
uss, &Handle::default())?;
let (sock, mut buf) = await!(ust.send_dgram(data, addr))?;
buf.resize(998, 0);
let buf = vec![0; 998];
let (_sock, mut buf,nb,_a) = await!(sock.recv_dgram(buf))?;
buf.truncate(nb);
Ok(buf)
}
|
use crate::engine::messaging::messages::EntitySnapshot;
use std::collections::VecDeque;
use itertools::{diff_with, Diff};
const SNAPSHOT_HISTORY_MAX_SIZE: usize = 64;
pub struct SnapshotHistory {
history: VecDeque<SnapshotData>,
ack_baseline: Option<SnapshotData>,
}
struct SnapshotData {
pub entity_data: Vec<EntitySnapshot>,
pub frame: u32,
}
impl SnapshotHistory {
pub fn new() -> Self {
Self {
history: VecDeque::with_capacity(SNAPSHOT_HISTORY_MAX_SIZE),
ack_baseline: None,
}
}
pub fn encode_delta(
&mut self,
frame: u32,
entities: &[EntitySnapshot],
) -> Option<(u32, Vec<EntitySnapshot>)> {
if self.history.len() == SNAPSHOT_HISTORY_MAX_SIZE {
drop(self.history.pop_front());
self.ack_baseline = None;
}
let output = if let Some(baseline) = &self.ack_baseline {
let mut out = Vec::<EntitySnapshot>::new();
let mut base_iter = baseline.entity_data.iter();
let mut next_iter = entities.iter();
while let Some(diff) = diff_with(base_iter, next_iter, |base, next| base == next) {
match diff {
Diff::FirstMismatch(_len, i, j) => {
//Mismatch found at index
let (i_val, i_iter) = i.into_parts();
let (j_val, j_iter) = j.into_parts();
out.push(get_entity_delta(i_val.unwrap(), j_val.unwrap()));
base_iter = i_iter;
next_iter = j_iter;
}
Diff::Shorter(_len, _i) => {
// TODO: Do we need this?
// Next contains less elementas than baseline
break;
}
Diff::Longer(_len, j) => {
// Next contains more elements than baseline
for snapshot in j {
out.push(snapshot.clone());
}
break;
}
}
}
Some((baseline.frame, out))
} else {
// We dont have a baseline, so just send a full snapshot
None
};
self.history.push_back(SnapshotData {
entity_data: entities.to_vec(),
frame,
});
output
}
pub fn ack_baseline(&mut self, frame: u32) {
if let Some(baseline) = &self.ack_baseline {
if frame <= baseline.frame {
// Early out for out-of-order packet
return;
}
let drain_amount = (frame - baseline.frame) - 1;
self.history.drain(0..drain_amount as usize);
} else {
while let Some(popped) = self.history.front() {
if popped.frame == frame {
break;
} else {
self.history.pop_front();
}
}
}
self.ack_baseline = self.history.pop_front();
}
}
fn get_entity_delta(baseline: &EntitySnapshot, next: &EntitySnapshot) -> EntitySnapshot {
EntitySnapshot {
replication_id: next.replication_id,
rotation: get_delta_field(&baseline.rotation, &next.rotation),
x: get_delta_field(&baseline.x, &next.x),
y: get_delta_field(&baseline.y, &next.y),
energy: get_delta_field(&baseline.energy, &next.energy),
health: get_delta_field(&baseline.health, &next.health),
entity_type: get_delta_field(&baseline.entity_type, &next.entity_type),
}
}
fn get_delta_field<T: PartialEq + Clone>(base: &Option<T>, next: &Option<T>) -> Option<T> {
match (base, next) {
(Some(b), Some(n)) => {
if b != n {
Some(n.clone())
} else {
None
}
}
(None, Some(n)) => Some(n.clone()),
_ => None,
}
}
|
#[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::_2_CTL {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct PWM_2_CTL_ENABLER {
bits: bool,
}
impl PWM_2_CTL_ENABLER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_ENABLEW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_ENABLEW<'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 &= !(1 << 0);
self.w.bits |= ((value as u32) & 1) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_2_CTL_MODER {
bits: bool,
}
impl PWM_2_CTL_MODER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_MODEW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_MODEW<'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 &= !(1 << 1);
self.w.bits |= ((value as u32) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_2_CTL_DEBUGR {
bits: bool,
}
impl PWM_2_CTL_DEBUGR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_DEBUGW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_DEBUGW<'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 &= !(1 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_2_CTL_LOADUPDR {
bits: bool,
}
impl PWM_2_CTL_LOADUPDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_LOADUPDW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_LOADUPDW<'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 &= !(1 << 3);
self.w.bits |= ((value as u32) & 1) << 3;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_2_CTL_CMPAUPDR {
bits: bool,
}
impl PWM_2_CTL_CMPAUPDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_CMPAUPDW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_CMPAUPDW<'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 &= !(1 << 4);
self.w.bits |= ((value as u32) & 1) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_2_CTL_CMPBUPDR {
bits: bool,
}
impl PWM_2_CTL_CMPBUPDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_CMPBUPDW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_CMPBUPDW<'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 &= !(1 << 5);
self.w.bits |= ((value as u32) & 1) << 5;
self.w
}
}
#[doc = "Possible values of the field `PWM_2_CTL_GENAUPD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_2_CTL_GENAUPDR {
#[doc = "Immediate"]
PWM_2_CTL_GENAUPD_I,
#[doc = "Locally Synchronized"]
PWM_2_CTL_GENAUPD_LS,
#[doc = "Globally Synchronized"]
PWM_2_CTL_GENAUPD_GS,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl PWM_2_CTL_GENAUPDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
PWM_2_CTL_GENAUPDR::PWM_2_CTL_GENAUPD_I => 0,
PWM_2_CTL_GENAUPDR::PWM_2_CTL_GENAUPD_LS => 2,
PWM_2_CTL_GENAUPDR::PWM_2_CTL_GENAUPD_GS => 3,
PWM_2_CTL_GENAUPDR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> PWM_2_CTL_GENAUPDR {
match value {
0 => PWM_2_CTL_GENAUPDR::PWM_2_CTL_GENAUPD_I,
2 => PWM_2_CTL_GENAUPDR::PWM_2_CTL_GENAUPD_LS,
3 => PWM_2_CTL_GENAUPDR::PWM_2_CTL_GENAUPD_GS,
i => PWM_2_CTL_GENAUPDR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_GENAUPD_I`"]
#[inline(always)]
pub fn is_pwm_2_ctl_genaupd_i(&self) -> bool {
*self == PWM_2_CTL_GENAUPDR::PWM_2_CTL_GENAUPD_I
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_GENAUPD_LS`"]
#[inline(always)]
pub fn is_pwm_2_ctl_genaupd_ls(&self) -> bool {
*self == PWM_2_CTL_GENAUPDR::PWM_2_CTL_GENAUPD_LS
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_GENAUPD_GS`"]
#[inline(always)]
pub fn is_pwm_2_ctl_genaupd_gs(&self) -> bool {
*self == PWM_2_CTL_GENAUPDR::PWM_2_CTL_GENAUPD_GS
}
}
#[doc = "Values that can be written to the field `PWM_2_CTL_GENAUPD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_2_CTL_GENAUPDW {
#[doc = "Immediate"]
PWM_2_CTL_GENAUPD_I,
#[doc = "Locally Synchronized"]
PWM_2_CTL_GENAUPD_LS,
#[doc = "Globally Synchronized"]
PWM_2_CTL_GENAUPD_GS,
}
impl PWM_2_CTL_GENAUPDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
PWM_2_CTL_GENAUPDW::PWM_2_CTL_GENAUPD_I => 0,
PWM_2_CTL_GENAUPDW::PWM_2_CTL_GENAUPD_LS => 2,
PWM_2_CTL_GENAUPDW::PWM_2_CTL_GENAUPD_GS => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_GENAUPDW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_GENAUPDW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWM_2_CTL_GENAUPDW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Immediate"]
#[inline(always)]
pub fn pwm_2_ctl_genaupd_i(self) -> &'a mut W {
self.variant(PWM_2_CTL_GENAUPDW::PWM_2_CTL_GENAUPD_I)
}
#[doc = "Locally Synchronized"]
#[inline(always)]
pub fn pwm_2_ctl_genaupd_ls(self) -> &'a mut W {
self.variant(PWM_2_CTL_GENAUPDW::PWM_2_CTL_GENAUPD_LS)
}
#[doc = "Globally Synchronized"]
#[inline(always)]
pub fn pwm_2_ctl_genaupd_gs(self) -> &'a mut W {
self.variant(PWM_2_CTL_GENAUPDW::PWM_2_CTL_GENAUPD_GS)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 6);
self.w.bits |= ((value as u32) & 3) << 6;
self.w
}
}
#[doc = "Possible values of the field `PWM_2_CTL_GENBUPD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_2_CTL_GENBUPDR {
#[doc = "Immediate"]
PWM_2_CTL_GENBUPD_I,
#[doc = "Locally Synchronized"]
PWM_2_CTL_GENBUPD_LS,
#[doc = "Globally Synchronized"]
PWM_2_CTL_GENBUPD_GS,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl PWM_2_CTL_GENBUPDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
PWM_2_CTL_GENBUPDR::PWM_2_CTL_GENBUPD_I => 0,
PWM_2_CTL_GENBUPDR::PWM_2_CTL_GENBUPD_LS => 2,
PWM_2_CTL_GENBUPDR::PWM_2_CTL_GENBUPD_GS => 3,
PWM_2_CTL_GENBUPDR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> PWM_2_CTL_GENBUPDR {
match value {
0 => PWM_2_CTL_GENBUPDR::PWM_2_CTL_GENBUPD_I,
2 => PWM_2_CTL_GENBUPDR::PWM_2_CTL_GENBUPD_LS,
3 => PWM_2_CTL_GENBUPDR::PWM_2_CTL_GENBUPD_GS,
i => PWM_2_CTL_GENBUPDR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_GENBUPD_I`"]
#[inline(always)]
pub fn is_pwm_2_ctl_genbupd_i(&self) -> bool {
*self == PWM_2_CTL_GENBUPDR::PWM_2_CTL_GENBUPD_I
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_GENBUPD_LS`"]
#[inline(always)]
pub fn is_pwm_2_ctl_genbupd_ls(&self) -> bool {
*self == PWM_2_CTL_GENBUPDR::PWM_2_CTL_GENBUPD_LS
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_GENBUPD_GS`"]
#[inline(always)]
pub fn is_pwm_2_ctl_genbupd_gs(&self) -> bool {
*self == PWM_2_CTL_GENBUPDR::PWM_2_CTL_GENBUPD_GS
}
}
#[doc = "Values that can be written to the field `PWM_2_CTL_GENBUPD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_2_CTL_GENBUPDW {
#[doc = "Immediate"]
PWM_2_CTL_GENBUPD_I,
#[doc = "Locally Synchronized"]
PWM_2_CTL_GENBUPD_LS,
#[doc = "Globally Synchronized"]
PWM_2_CTL_GENBUPD_GS,
}
impl PWM_2_CTL_GENBUPDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
PWM_2_CTL_GENBUPDW::PWM_2_CTL_GENBUPD_I => 0,
PWM_2_CTL_GENBUPDW::PWM_2_CTL_GENBUPD_LS => 2,
PWM_2_CTL_GENBUPDW::PWM_2_CTL_GENBUPD_GS => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_GENBUPDW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_GENBUPDW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWM_2_CTL_GENBUPDW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Immediate"]
#[inline(always)]
pub fn pwm_2_ctl_genbupd_i(self) -> &'a mut W {
self.variant(PWM_2_CTL_GENBUPDW::PWM_2_CTL_GENBUPD_I)
}
#[doc = "Locally Synchronized"]
#[inline(always)]
pub fn pwm_2_ctl_genbupd_ls(self) -> &'a mut W {
self.variant(PWM_2_CTL_GENBUPDW::PWM_2_CTL_GENBUPD_LS)
}
#[doc = "Globally Synchronized"]
#[inline(always)]
pub fn pwm_2_ctl_genbupd_gs(self) -> &'a mut W {
self.variant(PWM_2_CTL_GENBUPDW::PWM_2_CTL_GENBUPD_GS)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 8);
self.w.bits |= ((value as u32) & 3) << 8;
self.w
}
}
#[doc = "Possible values of the field `PWM_2_CTL_DBCTLUPD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_2_CTL_DBCTLUPDR {
#[doc = "Immediate"]
PWM_2_CTL_DBCTLUPD_I,
#[doc = "Locally Synchronized"]
PWM_2_CTL_DBCTLUPD_LS,
#[doc = "Globally Synchronized"]
PWM_2_CTL_DBCTLUPD_GS,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl PWM_2_CTL_DBCTLUPDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
PWM_2_CTL_DBCTLUPDR::PWM_2_CTL_DBCTLUPD_I => 0,
PWM_2_CTL_DBCTLUPDR::PWM_2_CTL_DBCTLUPD_LS => 2,
PWM_2_CTL_DBCTLUPDR::PWM_2_CTL_DBCTLUPD_GS => 3,
PWM_2_CTL_DBCTLUPDR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> PWM_2_CTL_DBCTLUPDR {
match value {
0 => PWM_2_CTL_DBCTLUPDR::PWM_2_CTL_DBCTLUPD_I,
2 => PWM_2_CTL_DBCTLUPDR::PWM_2_CTL_DBCTLUPD_LS,
3 => PWM_2_CTL_DBCTLUPDR::PWM_2_CTL_DBCTLUPD_GS,
i => PWM_2_CTL_DBCTLUPDR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_DBCTLUPD_I`"]
#[inline(always)]
pub fn is_pwm_2_ctl_dbctlupd_i(&self) -> bool {
*self == PWM_2_CTL_DBCTLUPDR::PWM_2_CTL_DBCTLUPD_I
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_DBCTLUPD_LS`"]
#[inline(always)]
pub fn is_pwm_2_ctl_dbctlupd_ls(&self) -> bool {
*self == PWM_2_CTL_DBCTLUPDR::PWM_2_CTL_DBCTLUPD_LS
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_DBCTLUPD_GS`"]
#[inline(always)]
pub fn is_pwm_2_ctl_dbctlupd_gs(&self) -> bool {
*self == PWM_2_CTL_DBCTLUPDR::PWM_2_CTL_DBCTLUPD_GS
}
}
#[doc = "Values that can be written to the field `PWM_2_CTL_DBCTLUPD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_2_CTL_DBCTLUPDW {
#[doc = "Immediate"]
PWM_2_CTL_DBCTLUPD_I,
#[doc = "Locally Synchronized"]
PWM_2_CTL_DBCTLUPD_LS,
#[doc = "Globally Synchronized"]
PWM_2_CTL_DBCTLUPD_GS,
}
impl PWM_2_CTL_DBCTLUPDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
PWM_2_CTL_DBCTLUPDW::PWM_2_CTL_DBCTLUPD_I => 0,
PWM_2_CTL_DBCTLUPDW::PWM_2_CTL_DBCTLUPD_LS => 2,
PWM_2_CTL_DBCTLUPDW::PWM_2_CTL_DBCTLUPD_GS => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_DBCTLUPDW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_DBCTLUPDW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWM_2_CTL_DBCTLUPDW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Immediate"]
#[inline(always)]
pub fn pwm_2_ctl_dbctlupd_i(self) -> &'a mut W {
self.variant(PWM_2_CTL_DBCTLUPDW::PWM_2_CTL_DBCTLUPD_I)
}
#[doc = "Locally Synchronized"]
#[inline(always)]
pub fn pwm_2_ctl_dbctlupd_ls(self) -> &'a mut W {
self.variant(PWM_2_CTL_DBCTLUPDW::PWM_2_CTL_DBCTLUPD_LS)
}
#[doc = "Globally Synchronized"]
#[inline(always)]
pub fn pwm_2_ctl_dbctlupd_gs(self) -> &'a mut W {
self.variant(PWM_2_CTL_DBCTLUPDW::PWM_2_CTL_DBCTLUPD_GS)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 10);
self.w.bits |= ((value as u32) & 3) << 10;
self.w
}
}
#[doc = "Possible values of the field `PWM_2_CTL_DBRISEUPD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_2_CTL_DBRISEUPDR {
#[doc = "Immediate"]
PWM_2_CTL_DBRISEUPD_I,
#[doc = "Locally Synchronized"]
PWM_2_CTL_DBRISEUPD_LS,
#[doc = "Globally Synchronized"]
PWM_2_CTL_DBRISEUPD_GS,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl PWM_2_CTL_DBRISEUPDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
PWM_2_CTL_DBRISEUPDR::PWM_2_CTL_DBRISEUPD_I => 0,
PWM_2_CTL_DBRISEUPDR::PWM_2_CTL_DBRISEUPD_LS => 2,
PWM_2_CTL_DBRISEUPDR::PWM_2_CTL_DBRISEUPD_GS => 3,
PWM_2_CTL_DBRISEUPDR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> PWM_2_CTL_DBRISEUPDR {
match value {
0 => PWM_2_CTL_DBRISEUPDR::PWM_2_CTL_DBRISEUPD_I,
2 => PWM_2_CTL_DBRISEUPDR::PWM_2_CTL_DBRISEUPD_LS,
3 => PWM_2_CTL_DBRISEUPDR::PWM_2_CTL_DBRISEUPD_GS,
i => PWM_2_CTL_DBRISEUPDR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_DBRISEUPD_I`"]
#[inline(always)]
pub fn is_pwm_2_ctl_dbriseupd_i(&self) -> bool {
*self == PWM_2_CTL_DBRISEUPDR::PWM_2_CTL_DBRISEUPD_I
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_DBRISEUPD_LS`"]
#[inline(always)]
pub fn is_pwm_2_ctl_dbriseupd_ls(&self) -> bool {
*self == PWM_2_CTL_DBRISEUPDR::PWM_2_CTL_DBRISEUPD_LS
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_DBRISEUPD_GS`"]
#[inline(always)]
pub fn is_pwm_2_ctl_dbriseupd_gs(&self) -> bool {
*self == PWM_2_CTL_DBRISEUPDR::PWM_2_CTL_DBRISEUPD_GS
}
}
#[doc = "Values that can be written to the field `PWM_2_CTL_DBRISEUPD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_2_CTL_DBRISEUPDW {
#[doc = "Immediate"]
PWM_2_CTL_DBRISEUPD_I,
#[doc = "Locally Synchronized"]
PWM_2_CTL_DBRISEUPD_LS,
#[doc = "Globally Synchronized"]
PWM_2_CTL_DBRISEUPD_GS,
}
impl PWM_2_CTL_DBRISEUPDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
PWM_2_CTL_DBRISEUPDW::PWM_2_CTL_DBRISEUPD_I => 0,
PWM_2_CTL_DBRISEUPDW::PWM_2_CTL_DBRISEUPD_LS => 2,
PWM_2_CTL_DBRISEUPDW::PWM_2_CTL_DBRISEUPD_GS => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_DBRISEUPDW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_DBRISEUPDW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWM_2_CTL_DBRISEUPDW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Immediate"]
#[inline(always)]
pub fn pwm_2_ctl_dbriseupd_i(self) -> &'a mut W {
self.variant(PWM_2_CTL_DBRISEUPDW::PWM_2_CTL_DBRISEUPD_I)
}
#[doc = "Locally Synchronized"]
#[inline(always)]
pub fn pwm_2_ctl_dbriseupd_ls(self) -> &'a mut W {
self.variant(PWM_2_CTL_DBRISEUPDW::PWM_2_CTL_DBRISEUPD_LS)
}
#[doc = "Globally Synchronized"]
#[inline(always)]
pub fn pwm_2_ctl_dbriseupd_gs(self) -> &'a mut W {
self.variant(PWM_2_CTL_DBRISEUPDW::PWM_2_CTL_DBRISEUPD_GS)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 12);
self.w.bits |= ((value as u32) & 3) << 12;
self.w
}
}
#[doc = "Possible values of the field `PWM_2_CTL_DBFALLUPD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_2_CTL_DBFALLUPDR {
#[doc = "Immediate"]
PWM_2_CTL_DBFALLUPD_I,
#[doc = "Locally Synchronized"]
PWM_2_CTL_DBFALLUPD_LS,
#[doc = "Globally Synchronized"]
PWM_2_CTL_DBFALLUPD_GS,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl PWM_2_CTL_DBFALLUPDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
PWM_2_CTL_DBFALLUPDR::PWM_2_CTL_DBFALLUPD_I => 0,
PWM_2_CTL_DBFALLUPDR::PWM_2_CTL_DBFALLUPD_LS => 2,
PWM_2_CTL_DBFALLUPDR::PWM_2_CTL_DBFALLUPD_GS => 3,
PWM_2_CTL_DBFALLUPDR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> PWM_2_CTL_DBFALLUPDR {
match value {
0 => PWM_2_CTL_DBFALLUPDR::PWM_2_CTL_DBFALLUPD_I,
2 => PWM_2_CTL_DBFALLUPDR::PWM_2_CTL_DBFALLUPD_LS,
3 => PWM_2_CTL_DBFALLUPDR::PWM_2_CTL_DBFALLUPD_GS,
i => PWM_2_CTL_DBFALLUPDR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_DBFALLUPD_I`"]
#[inline(always)]
pub fn is_pwm_2_ctl_dbfallupd_i(&self) -> bool {
*self == PWM_2_CTL_DBFALLUPDR::PWM_2_CTL_DBFALLUPD_I
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_DBFALLUPD_LS`"]
#[inline(always)]
pub fn is_pwm_2_ctl_dbfallupd_ls(&self) -> bool {
*self == PWM_2_CTL_DBFALLUPDR::PWM_2_CTL_DBFALLUPD_LS
}
#[doc = "Checks if the value of the field is `PWM_2_CTL_DBFALLUPD_GS`"]
#[inline(always)]
pub fn is_pwm_2_ctl_dbfallupd_gs(&self) -> bool {
*self == PWM_2_CTL_DBFALLUPDR::PWM_2_CTL_DBFALLUPD_GS
}
}
#[doc = "Values that can be written to the field `PWM_2_CTL_DBFALLUPD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_2_CTL_DBFALLUPDW {
#[doc = "Immediate"]
PWM_2_CTL_DBFALLUPD_I,
#[doc = "Locally Synchronized"]
PWM_2_CTL_DBFALLUPD_LS,
#[doc = "Globally Synchronized"]
PWM_2_CTL_DBFALLUPD_GS,
}
impl PWM_2_CTL_DBFALLUPDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
PWM_2_CTL_DBFALLUPDW::PWM_2_CTL_DBFALLUPD_I => 0,
PWM_2_CTL_DBFALLUPDW::PWM_2_CTL_DBFALLUPD_LS => 2,
PWM_2_CTL_DBFALLUPDW::PWM_2_CTL_DBFALLUPD_GS => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_DBFALLUPDW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_DBFALLUPDW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWM_2_CTL_DBFALLUPDW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Immediate"]
#[inline(always)]
pub fn pwm_2_ctl_dbfallupd_i(self) -> &'a mut W {
self.variant(PWM_2_CTL_DBFALLUPDW::PWM_2_CTL_DBFALLUPD_I)
}
#[doc = "Locally Synchronized"]
#[inline(always)]
pub fn pwm_2_ctl_dbfallupd_ls(self) -> &'a mut W {
self.variant(PWM_2_CTL_DBFALLUPDW::PWM_2_CTL_DBFALLUPD_LS)
}
#[doc = "Globally Synchronized"]
#[inline(always)]
pub fn pwm_2_ctl_dbfallupd_gs(self) -> &'a mut W {
self.variant(PWM_2_CTL_DBFALLUPDW::PWM_2_CTL_DBFALLUPD_GS)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 14);
self.w.bits |= ((value as u32) & 3) << 14;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_2_CTL_FLTSRCR {
bits: bool,
}
impl PWM_2_CTL_FLTSRCR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_FLTSRCW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_FLTSRCW<'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 &= !(1 << 16);
self.w.bits |= ((value as u32) & 1) << 16;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_2_CTL_MINFLTPERR {
bits: bool,
}
impl PWM_2_CTL_MINFLTPERR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_MINFLTPERW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_MINFLTPERW<'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 &= !(1 << 17);
self.w.bits |= ((value as u32) & 1) << 17;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_2_CTL_LATCHR {
bits: bool,
}
impl PWM_2_CTL_LATCHR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_2_CTL_LATCHW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_2_CTL_LATCHW<'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 &= !(1 << 18);
self.w.bits |= ((value as u32) & 1) << 18;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - PWM Block Enable"]
#[inline(always)]
pub fn pwm_2_ctl_enable(&self) -> PWM_2_CTL_ENABLER {
let bits = ((self.bits >> 0) & 1) != 0;
PWM_2_CTL_ENABLER { bits }
}
#[doc = "Bit 1 - Counter Mode"]
#[inline(always)]
pub fn pwm_2_ctl_mode(&self) -> PWM_2_CTL_MODER {
let bits = ((self.bits >> 1) & 1) != 0;
PWM_2_CTL_MODER { bits }
}
#[doc = "Bit 2 - Debug Mode"]
#[inline(always)]
pub fn pwm_2_ctl_debug(&self) -> PWM_2_CTL_DEBUGR {
let bits = ((self.bits >> 2) & 1) != 0;
PWM_2_CTL_DEBUGR { bits }
}
#[doc = "Bit 3 - Load Register Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_loadupd(&self) -> PWM_2_CTL_LOADUPDR {
let bits = ((self.bits >> 3) & 1) != 0;
PWM_2_CTL_LOADUPDR { bits }
}
#[doc = "Bit 4 - Comparator A Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_cmpaupd(&self) -> PWM_2_CTL_CMPAUPDR {
let bits = ((self.bits >> 4) & 1) != 0;
PWM_2_CTL_CMPAUPDR { bits }
}
#[doc = "Bit 5 - Comparator B Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_cmpbupd(&self) -> PWM_2_CTL_CMPBUPDR {
let bits = ((self.bits >> 5) & 1) != 0;
PWM_2_CTL_CMPBUPDR { bits }
}
#[doc = "Bits 6:7 - PWMnGENA Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_genaupd(&self) -> PWM_2_CTL_GENAUPDR {
PWM_2_CTL_GENAUPDR::_from(((self.bits >> 6) & 3) as u8)
}
#[doc = "Bits 8:9 - PWMnGENB Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_genbupd(&self) -> PWM_2_CTL_GENBUPDR {
PWM_2_CTL_GENBUPDR::_from(((self.bits >> 8) & 3) as u8)
}
#[doc = "Bits 10:11 - PWMnDBCTL Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_dbctlupd(&self) -> PWM_2_CTL_DBCTLUPDR {
PWM_2_CTL_DBCTLUPDR::_from(((self.bits >> 10) & 3) as u8)
}
#[doc = "Bits 12:13 - PWMnDBRISE Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_dbriseupd(&self) -> PWM_2_CTL_DBRISEUPDR {
PWM_2_CTL_DBRISEUPDR::_from(((self.bits >> 12) & 3) as u8)
}
#[doc = "Bits 14:15 - PWMnDBFALL Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_dbfallupd(&self) -> PWM_2_CTL_DBFALLUPDR {
PWM_2_CTL_DBFALLUPDR::_from(((self.bits >> 14) & 3) as u8)
}
#[doc = "Bit 16 - Fault Condition Source"]
#[inline(always)]
pub fn pwm_2_ctl_fltsrc(&self) -> PWM_2_CTL_FLTSRCR {
let bits = ((self.bits >> 16) & 1) != 0;
PWM_2_CTL_FLTSRCR { bits }
}
#[doc = "Bit 17 - Minimum Fault Period"]
#[inline(always)]
pub fn pwm_2_ctl_minfltper(&self) -> PWM_2_CTL_MINFLTPERR {
let bits = ((self.bits >> 17) & 1) != 0;
PWM_2_CTL_MINFLTPERR { bits }
}
#[doc = "Bit 18 - Latch Fault Input"]
#[inline(always)]
pub fn pwm_2_ctl_latch(&self) -> PWM_2_CTL_LATCHR {
let bits = ((self.bits >> 18) & 1) != 0;
PWM_2_CTL_LATCHR { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - PWM Block Enable"]
#[inline(always)]
pub fn pwm_2_ctl_enable(&mut self) -> _PWM_2_CTL_ENABLEW {
_PWM_2_CTL_ENABLEW { w: self }
}
#[doc = "Bit 1 - Counter Mode"]
#[inline(always)]
pub fn pwm_2_ctl_mode(&mut self) -> _PWM_2_CTL_MODEW {
_PWM_2_CTL_MODEW { w: self }
}
#[doc = "Bit 2 - Debug Mode"]
#[inline(always)]
pub fn pwm_2_ctl_debug(&mut self) -> _PWM_2_CTL_DEBUGW {
_PWM_2_CTL_DEBUGW { w: self }
}
#[doc = "Bit 3 - Load Register Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_loadupd(&mut self) -> _PWM_2_CTL_LOADUPDW {
_PWM_2_CTL_LOADUPDW { w: self }
}
#[doc = "Bit 4 - Comparator A Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_cmpaupd(&mut self) -> _PWM_2_CTL_CMPAUPDW {
_PWM_2_CTL_CMPAUPDW { w: self }
}
#[doc = "Bit 5 - Comparator B Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_cmpbupd(&mut self) -> _PWM_2_CTL_CMPBUPDW {
_PWM_2_CTL_CMPBUPDW { w: self }
}
#[doc = "Bits 6:7 - PWMnGENA Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_genaupd(&mut self) -> _PWM_2_CTL_GENAUPDW {
_PWM_2_CTL_GENAUPDW { w: self }
}
#[doc = "Bits 8:9 - PWMnGENB Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_genbupd(&mut self) -> _PWM_2_CTL_GENBUPDW {
_PWM_2_CTL_GENBUPDW { w: self }
}
#[doc = "Bits 10:11 - PWMnDBCTL Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_dbctlupd(&mut self) -> _PWM_2_CTL_DBCTLUPDW {
_PWM_2_CTL_DBCTLUPDW { w: self }
}
#[doc = "Bits 12:13 - PWMnDBRISE Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_dbriseupd(&mut self) -> _PWM_2_CTL_DBRISEUPDW {
_PWM_2_CTL_DBRISEUPDW { w: self }
}
#[doc = "Bits 14:15 - PWMnDBFALL Update Mode"]
#[inline(always)]
pub fn pwm_2_ctl_dbfallupd(&mut self) -> _PWM_2_CTL_DBFALLUPDW {
_PWM_2_CTL_DBFALLUPDW { w: self }
}
#[doc = "Bit 16 - Fault Condition Source"]
#[inline(always)]
pub fn pwm_2_ctl_fltsrc(&mut self) -> _PWM_2_CTL_FLTSRCW {
_PWM_2_CTL_FLTSRCW { w: self }
}
#[doc = "Bit 17 - Minimum Fault Period"]
#[inline(always)]
pub fn pwm_2_ctl_minfltper(&mut self) -> _PWM_2_CTL_MINFLTPERW {
_PWM_2_CTL_MINFLTPERW { w: self }
}
#[doc = "Bit 18 - Latch Fault Input"]
#[inline(always)]
pub fn pwm_2_ctl_latch(&mut self) -> _PWM_2_CTL_LATCHW {
_PWM_2_CTL_LATCHW { w: self }
}
}
|
use bitcoin::Network;
use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
use lightning_block_sync::BlockSource;
use tokio::runtime::Handle;
use self::{
bitcoind_client::BitcoindClient,
remote::{
block_source::RemoteBlockSource, broadcaster::RemoteBroadcaster,
fee_estimator::RemoteFeeEstimator,
},
};
use std::sync::Arc;
pub mod bitcoind_client;
pub mod broadcaster;
pub mod database;
pub mod fee_estimator;
pub mod listener;
pub mod manager;
pub mod remote;
pub enum AnyBlockSource {
Local(Arc<BitcoindClient>),
Remote(remote::block_source::RemoteBlockSource),
}
impl AnyBlockSource {
pub fn new_remote(network: Network, host: String, token: String) -> Self {
AnyBlockSource::Remote(RemoteBlockSource::new(network, host, token))
}
}
impl BlockSource for AnyBlockSource {
fn get_header<'a>(
&'a self,
header_hash: &'a bitcoin::BlockHash,
height_hint: Option<u32>,
) -> lightning_block_sync::AsyncBlockSourceResult<'a, lightning_block_sync::BlockHeaderData>
{
match self {
AnyBlockSource::Local(bitcoind_client) => {
bitcoind_client.get_header(header_hash, height_hint)
}
AnyBlockSource::Remote(remote) => remote.get_header(header_hash, height_hint),
}
}
fn get_block<'a>(
&'a self,
header_hash: &'a bitcoin::BlockHash,
) -> lightning_block_sync::AsyncBlockSourceResult<'a, bitcoin::Block> {
match self {
AnyBlockSource::Local(bitcoind_client) => bitcoind_client.get_block(header_hash),
AnyBlockSource::Remote(remote) => remote.get_block(header_hash),
}
}
fn get_best_block(
&self,
) -> lightning_block_sync::AsyncBlockSourceResult<(bitcoin::BlockHash, Option<u32>)> {
match self {
AnyBlockSource::Local(bitcoind_client) => bitcoind_client.get_best_block(),
AnyBlockSource::Remote(remote) => remote.get_best_block(),
}
}
}
pub enum AnyFeeEstimator {
Local(Arc<BitcoindClient>),
Remote(RemoteFeeEstimator),
}
impl AnyFeeEstimator {
pub fn new_remote(host: String, token: String, handle: Handle) -> Self {
AnyFeeEstimator::Remote(RemoteFeeEstimator::new(host, token, handle))
}
}
impl FeeEstimator for AnyFeeEstimator {
fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
match self {
AnyFeeEstimator::Local(bitcoind_client) => {
bitcoind_client.get_est_sat_per_1000_weight(confirmation_target)
}
AnyFeeEstimator::Remote(remote) => {
remote.get_est_sat_per_1000_weight(confirmation_target)
}
}
}
}
pub enum AnyBroadcaster {
Local(Arc<BitcoindClient>),
Remote(RemoteBroadcaster),
}
impl AnyBroadcaster {
pub fn new_remote(host: String, token: String, handle: Handle) -> Self {
AnyBroadcaster::Remote(RemoteBroadcaster::new(host, token, handle))
}
}
impl BroadcasterInterface for AnyBroadcaster {
fn broadcast_transaction(&self, tx: &bitcoin::Transaction) {
match self {
AnyBroadcaster::Local(bitcoind_client) => bitcoind_client.broadcast_transaction(tx),
AnyBroadcaster::Remote(remote) => remote.broadcast_transaction(tx),
}
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::iter::repeat;
use std::iter::TrustedLen;
use std::sync::atomic::Ordering;
use common_arrow::arrow::bitmap::Bitmap;
use common_arrow::arrow::bitmap::MutableBitmap;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::BlockEntry;
use common_expression::DataBlock;
use common_expression::Scalar;
use common_expression::Value;
use common_hashtable::HashtableEntryRefLike;
use common_hashtable::HashtableLike;
use crate::pipelines::processors::transforms::hash_join::desc::MarkerKind;
use crate::pipelines::processors::transforms::hash_join::desc::JOIN_MAX_BLOCK_SIZE;
use crate::pipelines::processors::transforms::hash_join::row::RowPtr;
use crate::pipelines::processors::transforms::hash_join::ProbeState;
use crate::pipelines::processors::JoinHashTable;
use crate::sql::plans::JoinType;
impl JoinHashTable {
pub(crate) fn probe_left_join<
'a,
const WITH_OTHER_CONJUNCT: bool,
H: HashtableLike<Value = Vec<RowPtr>>,
IT,
>(
&self,
hash_table: &H,
probe_state: &mut ProbeState,
keys_iter: IT,
input: &DataBlock,
) -> Result<Vec<DataBlock>>
where
IT: Iterator<Item = &'a H::Key> + TrustedLen,
H::Key: 'a,
{
let valids = &probe_state.valids;
// The left join will return multiple data blocks of similar size
let mut probed_blocks = vec![];
let mut probe_indexes = Vec::with_capacity(JOIN_MAX_BLOCK_SIZE);
let mut probe_indexes_vec = Vec::new();
// Collect each probe_indexes, used by non-equi conditions filter
let mut local_build_indexes = Vec::with_capacity(JOIN_MAX_BLOCK_SIZE);
let mut validity = MutableBitmap::with_capacity(JOIN_MAX_BLOCK_SIZE);
let mut row_state = match WITH_OTHER_CONJUNCT {
true => vec![0; input.num_rows()],
false => vec![],
};
let dummy_probed_rows = vec![RowPtr {
row_index: 0,
chunk_index: 0,
marker: Some(MarkerKind::False),
}];
// Start to probe hash table
for (i, key) in keys_iter.enumerate() {
let probe_result_ptr = match self.hash_join_desc.from_correlated_subquery {
true => hash_table.entry(key),
false => self.probe_key(hash_table, key, valids, i),
};
let (validity_value, probed_rows) = match probe_result_ptr {
None => (false, &dummy_probed_rows),
Some(v) => (true, v.get()),
};
if self.hash_join_desc.join_type == JoinType::Full {
let mut build_indexes = self.hash_join_desc.join_state.build_indexes.write();
// dummy row ptr
// here assume there is no RowPtr, which chunk_index is usize::MAX and row_index is usize::MAX
match probe_result_ptr {
None => build_indexes.push(RowPtr {
chunk_index: usize::MAX,
row_index: usize::MAX,
marker: Some(MarkerKind::False),
}),
Some(_) => build_indexes.extend(probed_rows),
};
}
if self.hash_join_desc.join_type == JoinType::Single && probed_rows.len() > 1 {
return Err(ErrorCode::Internal(
"Scalar subquery can't return more than one row",
));
}
if WITH_OTHER_CONJUNCT {
row_state[i] += probed_rows.len() as u32;
}
if probe_indexes.len() + probed_rows.len() < probe_indexes.capacity() {
local_build_indexes.extend_from_slice(probed_rows);
validity.extend_constant(probed_rows.len(), validity_value);
probe_indexes.extend(repeat(i as u32).take(probed_rows.len()));
} else {
let mut index = 0_usize;
let mut remain = probed_rows.len();
while index < probed_rows.len() {
if probe_indexes.len() + remain < probe_indexes.capacity() {
validity.extend_constant(remain, validity_value);
probe_indexes.extend(repeat(i as u32).take(remain));
local_build_indexes.extend_from_slice(&probed_rows[index..]);
index += remain;
} else {
if self.interrupt.load(Ordering::Relaxed) {
return Err(ErrorCode::AbortedQuery(
"Aborted query, because the server is shutting down or the query was killed.",
));
}
let addition = probe_indexes.capacity() - probe_indexes.len();
let new_index = index + addition;
validity.extend_constant(addition, validity_value);
probe_indexes.extend(repeat(i as u32).take(addition));
local_build_indexes.extend_from_slice(&probed_rows[index..new_index]);
let validity_bitmap: Bitmap = validity.into();
let build_block = if !self.hash_join_desc.from_correlated_subquery
&& self.hash_join_desc.join_type == JoinType::Single
&& validity_bitmap.unset_bits() == input.num_rows()
{
// Uncorrelated scalar subquery and no row was returned by subquery
// We just construct a block with NULLs
let build_data_schema = self.row_space.data_schema.clone();
let columns = build_data_schema
.fields()
.iter()
.map(|field| BlockEntry {
data_type: field.data_type().wrap_nullable(),
value: Value::Scalar(Scalar::Null),
})
.collect::<Vec<_>>();
DataBlock::new(columns, input.num_rows())
} else {
self.row_space.gather(&local_build_indexes)?
};
// For left join, wrap nullable for build block
let (nullable_columns, num_rows) = if self.row_space.datablocks().is_empty()
&& !local_build_indexes.is_empty()
{
(
build_block
.columns()
.iter()
.map(|c| BlockEntry {
value: Value::Scalar(Scalar::Null),
data_type: c.data_type.wrap_nullable(),
})
.collect::<Vec<_>>(),
local_build_indexes.len(),
)
} else {
(
build_block
.columns()
.iter()
.map(|c| {
Self::set_validity(
c,
build_block.num_rows(),
&validity_bitmap,
)
})
.collect::<Vec<_>>(),
validity_bitmap.len(),
)
};
let nullable_build_block = DataBlock::new(nullable_columns, num_rows);
// For full join, wrap nullable for probe block
let mut probe_block = DataBlock::take(input, &probe_indexes)?;
let num_rows = probe_block.num_rows();
if self.hash_join_desc.join_type == JoinType::Full {
let nullable_probe_columns = probe_block
.columns()
.iter()
.map(|c| {
let mut probe_validity = MutableBitmap::new();
probe_validity.extend_constant(num_rows, true);
let probe_validity: Bitmap = probe_validity.into();
Self::set_validity(c, num_rows, &probe_validity)
})
.collect::<Vec<_>>();
probe_block = DataBlock::new(nullable_probe_columns, num_rows);
}
let merged_block =
self.merge_eq_block(&nullable_build_block, &probe_block)?;
if !merged_block.is_empty() {
probe_indexes_vec.push(probe_indexes.clone());
probed_blocks.push(merged_block);
}
index = new_index;
remain -= addition;
probe_indexes.clear();
local_build_indexes.clear();
validity = MutableBitmap::with_capacity(JOIN_MAX_BLOCK_SIZE);
}
}
}
}
// For full join, wrap nullable for probe block
let mut probe_block = DataBlock::take(input, &probe_indexes)?;
if self.hash_join_desc.join_type == JoinType::Full {
let nullable_probe_columns = probe_block
.columns()
.iter()
.map(|c| {
let mut probe_validity = MutableBitmap::new();
probe_validity.extend_constant(probe_block.num_rows(), true);
let probe_validity: Bitmap = probe_validity.into();
Self::set_validity(c, probe_block.num_rows(), &probe_validity)
})
.collect::<Vec<_>>();
probe_block = DataBlock::new(nullable_probe_columns, probe_block.num_rows());
}
if !WITH_OTHER_CONJUNCT {
let mut rest_pairs = self.hash_join_desc.join_state.rest_pairs.write();
rest_pairs.1.extend(local_build_indexes);
rest_pairs.0.push(probe_block);
let validity: Bitmap = validity.into();
let mut validity_state = self.hash_join_desc.join_state.validity.write();
validity_state.extend_from_bitmap(&validity);
return Ok(probed_blocks);
}
let validity: Bitmap = validity.into();
let build_block = if !self.hash_join_desc.from_correlated_subquery
&& self.hash_join_desc.join_type == JoinType::Single
&& validity.unset_bits() == input.num_rows()
{
// Uncorrelated scalar subquery and no row was returned by subquery
// We just construct a block with NULLs
let build_data_schema = self.row_space.data_schema.clone();
let columns = build_data_schema
.fields()
.iter()
.map(|field| BlockEntry {
data_type: field.data_type().wrap_nullable(),
value: Value::Scalar(Scalar::Null),
})
.collect::<Vec<_>>();
DataBlock::new(columns, input.num_rows())
} else {
self.row_space.gather(&local_build_indexes)?
};
// For left join, wrap nullable for build chunk
let nullable_columns =
if self.row_space.datablocks().is_empty() && !local_build_indexes.is_empty() {
build_block
.columns()
.iter()
.map(|c| BlockEntry {
data_type: c.data_type.clone(),
value: Value::Scalar(Scalar::Null),
})
.collect::<Vec<_>>()
} else {
build_block
.columns()
.iter()
.map(|c| Self::set_validity(c, build_block.num_rows(), &validity))
.collect::<Vec<_>>()
};
let nullable_build_block = DataBlock::new(nullable_columns, validity.len());
// Process no-equi conditions
let merged_block = self.merge_eq_block(&nullable_build_block, &probe_block)?;
if !merged_block.is_empty() || probed_blocks.is_empty() {
probe_indexes_vec.push(probe_indexes.clone());
probed_blocks.push(merged_block);
}
self.non_equi_conditions_for_left_join(&probed_blocks, &probe_indexes_vec, &mut row_state)
}
// keep at least one index of the positive state and the null state
// bitmap: [1, 0, 1] with row_state [2, 1], probe_index: [0, 0, 1]
// bitmap will be [1, 0, 1] -> [1, 0, 1] -> [1, 0, 1] -> [1, 0, 1]
// row_state will be [2, 1] -> [2, 1] -> [1, 1] -> [1, 1]
pub(crate) fn fill_null_for_left_join(
&self,
bm: &mut MutableBitmap,
probe_indexes: &[u32],
row_state: &mut [u32],
) {
for (index, row) in probe_indexes.iter().enumerate() {
let row = *row as usize;
if row_state[row] == 0 {
bm.set(index, true);
continue;
}
if row_state[row] == 1 {
if !bm.get(index) {
bm.set(index, true)
}
continue;
}
if !bm.get(index) {
row_state[row] -= 1;
}
}
}
}
|
extern crate libc;
extern crate std;
use super::os::errno;
pub fn anon_ram_alloc(size: usize) -> *mut libc::c_void {
// todo: handle flags, alignment
let addr = unsafe {
libc::mmap(
std::ptr::null_mut(),
size,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE,
-1,
0)
};
if addr == libc::MAP_FAILED {
panic!("mmapp failed with: {}", errno());
}
addr
}
pub fn anon_ram_free(address: *mut libc::c_void, size: usize) {
let result = unsafe { libc::munmap(address, size) };
if result != 0 {
panic!("munmap failed with: {}", errno());
}
}
pub fn madvise(address: *mut libc::c_void, size: usize, flags: i32) {
let result = unsafe {
libc::madvise(address, size, flags)
};
if result == -1 {
panic!("madvise failed with: {}", errno());
}
}
|
use dynlib::{VoidPtr,LoadWinDynLib,DynLibWin};
use std::alloc::Layout;
use crate::archives::packages::patches::{block::MAX_BLOCK_LENGTH};
type OodleLZDecompress = fn(
input: *mut u8, // buffer
input_size: u64, // buffer_size
output: *mut u8, // result
output_size: u64, // result_buffer_size
u32, // a
u32, // b
u32, // c
u64, // d
u64, // e
u64, // f
u64, // g
u64, // h
u64, // i
u32 // ThreadModule
) -> u64;
struct OodleGuts {
pub lib: DynLibWin,
pub func_ptr: VoidPtr,
pub callable: OodleLZDecompress
}
struct OodleGutsHolder {
pub initialized: bool,
pub guts: Option<OodleGuts>
}
const HOLDER: OodleGutsHolder = OodleGutsHolder {
initialized: false,
guts: None
};
// private static extern long OodleLZ_Decompress(byte[] buffer, long bufferSize, byte[] result, long outputBufferSize, int a, int b, int c, long d, long e, long f, long g, long h, long i, int ThreadModule);
pub struct Oodle {}
impl Oodle {
pub fn init(path: &str) {
if HOLDER.initialized {
return;
}
let lib = LoadWinDynLib::new().load(path).unwrap();
let func_ptr = lib.load_function("OodleLZ_Decompress").unwrap();
let callable: extern "Rust" fn(
*mut u8, // buffer
u64, // buffer_size
*mut u8, // result
u64, // result_buffer_size
u32, // a
u32, // b
u32, // c
u64, // d
u64, // e
u64, // f
u64, // g
u64, // h
u64, // i
u32 // ThreadModule
) -> u64 = unsafe { std::mem::transmute(func_ptr) };
HOLDER.guts = Some(OodleGuts {
lib,
func_ptr,
callable
});
HOLDER.initialized = true;
}
pub fn lz_decompress(mut data: Vec<u8>) -> Vec<u8> {
let target: *mut u8;
let bytes_decompressed: u64;
unsafe {
target = std::alloc::alloc(Layout::array::<u8>(MAX_BLOCK_LENGTH).unwrap());
let data_ptr = data.as_mut_ptr();
bytes_decompressed = (HOLDER.guts.unwrap().callable)(
data_ptr,
data.len() as u64,
target,
MAX_BLOCK_LENGTH as u64,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
);
Vec::<u8>::from_raw_parts(target, bytes_decompressed as usize, MAX_BLOCK_LENGTH)
}
}
} |
pub struct Dane {
pub port: u16,
pub pid: u32,
pub ile_graczy: i32,
pub zajecie_pamieci: u64,
pub obciazenie_serwera: f32,
pub zmienna1: String,
}
impl Dane{
pub fn new() -> Dane{
//let tablica_mem : Vec<u64> = vec![0u64; 10]; //20 wyzerowanych komórek
Dane {
port: 0,
pid: std::process::id(), //nr pid
ile_graczy: 0,
zajecie_pamieci: 0,
obciazenie_serwera: 0_f32,
zmienna1: String::new(),
}
}
pub fn fill(&mut self){
//self.pid = std::process::id();
//self.zmienna1 = String::from("nie pobralo :(");
}
} |
#[derive(Debug, PartialEq)]
pub struct IO {
ports: Vec<u8>,
shift_offset: u8,
shift_value: u16,
}
impl IO {
pub fn new(ports: usize) -> IO {
IO {
ports: vec![0; ports],
shift_offset: 0,
shift_value: 0,
}
}
pub fn read(&self, port: usize) -> u8 {
match port {
3 => (self.shift_value >> (8 - self.shift_offset)) as u8,
_ => self.ports[port],
}
}
pub fn set(&mut self, port: usize, value: u8) -> () {
self.ports[port] = value;
}
pub fn write(&mut self, port: usize, value: u8) -> () {
match port {
2 => self.shift_offset = value & 0x7,
4 => self.shift_value = (self.shift_value >> 8) | u16::from(value) << 8,
6 => (),
_ => self.ports[port] = value,
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn writing_port_4() {
let mut io = IO::new(8);
io.write(4, 0xAB);
assert_eq!(io.shift_value, 0xAB00);
io.write(4, 0xCD);
assert_eq!(io.shift_value, 0xCDAB);
io.write(4, 0xEF);
assert_eq!(io.shift_value, 0xEFCD);
}
#[test]
fn writing_port_2() {
let mut io = IO::new(8);
io.write(2, 1);
assert_eq!(io.shift_offset, 1);
io.write(2, 7);
assert_eq!(io.shift_offset, 7);
io.write(2, 8);
assert_eq!(io.shift_offset, 0);
}
#[test]
fn read_port_3() {
let mut io = IO::new(8);
io.shift_value = 0xDEAD;
io.shift_offset = 0;
assert_eq!(io.read(3), 0xDE);
io.shift_offset = 4;
assert_eq!(io.read(3), 0xEA);
io.shift_offset = 7;
assert_eq!(io.read(3), 0x56);
}
}
|
//! Iron middleware
/// Middleware for requests from the Matrix homeserver
mod matrix;
/// Middleware for requests from the Rocket.Chat server
mod rocketchat;
pub use self::matrix::AccessToken;
pub use self::rocketchat::RocketchatToken;
|
// error-pattern:unknown syntax expander
fn main() { #iamnotanextensionthatexists(""); } |
struct Solution;
impl Solution {
pub fn reverse(x: i32) -> i32 {
let (mut x, mut ret) = (x as i64, 0);
while x != 0 {
// pick the number at a time
ret = ret * 10 + x % 10;
// update the origin number
x = x / 10;
}
if ret > 2_i64.pow(31) - 1 || ret < -2_i64.pow(31) {
return 0;
}
ret as i32
}
}
fn main() {
println!("the answer is {}", Solution::reverse(1534236469));
println!("the answer is {}", Solution::reverse(0));
println!("the answer is {}", Solution::reverse(201));
}
|
use super::*;
impl<A: Array> From<A> for StackVec<A>
{
#[inline(always)]
fn from (
array: A,
) -> StackVec<A>
{
StackVec {
array: mem::ManuallyDrop::new(array),
len: A::LEN,
}
}
}
/// Grants [`Array`]s an [`.into_iter()`][`ArrayIntoIter::into_iter`]
/// method to almost seamlessly use [`array`]s
/// as [by-owned-value iterators][`IntoIterator`].
///
/// # Example
/// ```rust
/// # use ::stackvec::prelude::*;
/// let array: [_; 2] = [
/// vec![1, 2, 3, 4],
/// vec![5, 6],
/// ];
/// let flattened: Vec<u8> = array
/// .into_iter()
/// .flatten()
/// .collect();
/// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
/// ```
///
/// [`array`]: https://doc.rust-lang.org/std/primitive.array.html
pub trait ArrayIntoIter: Array {
/// Consumes the given [`Array`] and its contents and returns a
/// [by-owned-value iterator][`IntoIterator`].
#[inline(always)]
fn into_iter (
self: Self,
) -> crate::IntoIter<Self>
{
StackVec::from(self).into_iter()
}
}
impl<A: Array> ArrayIntoIter for A {}
#[cfg(test)]
mod tests {
use crate::prelude::*;
#[derive(PartialEq, Eq, Hash)]
struct NoClone;
#[test]
fn array_into_iter ()
{
let array = [NoClone, NoClone, NoClone, NoClone];
let set = ::std::collections::HashSet::<NoClone>::from_iter(
array.into_iter()
);
assert!(!set.is_empty());
}
}
|
use sp_core::{Pair, Public, sr25519, H160, Bytes};
use bitg_runtime::{
AccountId, CurrencyId,
BabeConfig, BalancesConfig, GenesisConfig, GrandpaConfig, SudoConfig, SystemConfig,
IndicesConfig, EvmConfig, StakingConfig, SessionConfig, AuthorityDiscoveryConfig,ContractsConfig,
WASM_BINARY,
TokenSymbol, TokensConfig, BITG,
StakerStatus,
ImOnlineId, AuthorityDiscoveryId,
MaxNativeTokenExistentialDeposit,
get_all_module_accounts,
opaque::SessionKeys,
};
use sp_consensus_babe::AuthorityId as BabeId;
use sp_finality_grandpa::AuthorityId as GrandpaId;
use sp_runtime::traits::{IdentifyAccount};
use sc_service::{ChainType, Properties};
use sc_telemetry::TelemetryEndpoints;
use sp_std::{collections::btree_map::BTreeMap, str::FromStr};
use sc_chain_spec::ChainSpecExtension;
use serde::{Deserialize, Serialize};
use hex_literal::hex;
use sp_core::{crypto::UncheckedInto, bytes::from_hex};
use bitg_primitives::{AccountPublic, Balance, Nonce};
// The URL for the telemetry server.
const TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";
/// Node `ChainSpec` extensions.
///
/// Additional parameters for some Substrate core modules,
/// customizable from the chain spec.
#[derive(Default, Clone, Serialize, Deserialize, ChainSpecExtension)]
#[serde(rename_all = "camelCase")]
pub struct Extensions {
/// Block numbers with known hashes.
pub fork_blocks: sc_client_api::ForkBlocks<bitg_primitives::Block>,
/// Known bad block hashes.
pub bad_blocks: sc_client_api::BadBlocks<bitg_primitives::Block>,
}
/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.
pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig, Extensions>;
fn get_session_keys(
grandpa: GrandpaId,
babe: BabeId,
im_online: ImOnlineId,
authority_discovery: AuthorityDiscoveryId,
) -> SessionKeys {
SessionKeys { babe, grandpa, im_online, authority_discovery }
}
/// Helper function to generate a crypto pair from seed
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(&format!("//{}", seed), None)
.expect("static values are valid; qed")
.public()
}
/// Helper function to generate an account ID from seed
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
/// Generate an authority keys.
pub fn get_authority_keys_from_seed(seed: &str)
-> (AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId) {
(
get_account_id_from_seed::<sr25519::Public>(&format!("{}//stash", seed)),
get_account_id_from_seed::<sr25519::Public>(seed),
get_from_seed::<GrandpaId>(seed),
get_from_seed::<BabeId>(seed),
get_from_seed::<ImOnlineId>(seed),
get_from_seed::<AuthorityDiscoveryId>(seed),
)
}
pub fn development_config() -> Result<ChainSpec, String> {
let wasm_binary = WASM_BINARY.ok_or_else(|| "WASM binary not available".to_string())?;
Ok(ChainSpec::from_genesis(
// Name
"Development",
// ID
"dev",
ChainType::Development,
move || testnet_genesis(
wasm_binary,
// Initial PoA authorities
vec![
get_authority_keys_from_seed("Alice"),
],
// Sudo account
get_account_id_from_seed::<sr25519::Public>("Alice"),
// Pre-funded accounts
vec![
get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Bob"),
get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
],
),
// Bootnodes
vec![],
// Telemetry
None,
// Protocol ID
None,
// Properties
Some(bitg_properties()),
// Extensions
Default::default(),
))
}
pub fn local_testnet_config() -> Result<ChainSpec, String> {
let wasm_binary = WASM_BINARY.ok_or_else(|| "WASM binary not available".to_string())?;
Ok(ChainSpec::from_genesis(
// Name
"Local Testnet",
// ID
"local_testnet",
ChainType::Local,
move || testnet_genesis(
wasm_binary,
// Initial PoA authorities
vec![
get_authority_keys_from_seed("Alice"),
get_authority_keys_from_seed("Bob"),
],
// Sudo account
get_account_id_from_seed::<sr25519::Public>("Alice"),
// Pre-funded accounts
vec![
get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Bob"),
get_account_id_from_seed::<sr25519::Public>("Charlie"),
get_account_id_from_seed::<sr25519::Public>("Dave"),
get_account_id_from_seed::<sr25519::Public>("Eve"),
get_account_id_from_seed::<sr25519::Public>("Ferdie"),
get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
],
),
// Bootnodes
vec![],
// Telemetry
// TelemetryEndpoints::new(vec![(TELEMETRY_URL.into(), 0)]).ok(),
None,
// Protocol ID
Some("bitg_local_testnet"),
// Properties
Some(bitg_properties()),
// Extensions
Default::default(),
))
}
pub fn public_testnet_config() -> Result<ChainSpec, String> {
let wasm_binary = WASM_BINARY.ok_or_else(|| "WASM binary not available".to_string())?;
Ok(ChainSpec::from_genesis(
// Name
"Bitgreen Testnet",
// ID
"bitg_testnet",
ChainType::Live,
move || testnet_genesis(
wasm_binary,
// Initial authorities keys:
// stash
// controller
// grandpa
// babe
// im-online
// authority-discovery
vec![
(
// Boot Node/Validator 1: ip address 95.217.2.2
hex!["0a8e3c33501c0001bb08efc7511ca0b81f700eb8010ec91dc2d9324b3e0d2860"].into(),
hex!["fabe0e7010a320055f706192258876f3e97d237f836c8e1b753175df17d97b40"].into(),
hex!["a538f6fbd05fdcd42d91600eca9c7e6b7240fa82fc23b569deea91af6c97a5f1"].unchecked_into(),
hex!["a66bdf2c219a5fc728188edfeed3eb1ef17612d65764a71effcffd7f16a72834"].unchecked_into(),
hex!["50341e1134ad1a2244caaba520c4fff3a44bcca58c68d2fb9fdf924180c6b67f"].unchecked_into(),
hex!["7e4e3fd0a36ae866460c5e857682671a3c9f6a511d589084d400f3fe55672439"].unchecked_into(),
),
(
// Boot Node/Validator 2: ip addres 95.217.4.158
hex!["c866ae8a5b961062016bda70138e00b84a2975c22b6f61d44d2004a4ef9c6116"].into(),
hex!["ca514d67c95446d8ee62020f22c0b70616b4d6112dfc2c6e5dcafd67e9c27d09"].into(),
hex!["7ea36efa84a2e3e9416d94f4979aa9a6423d6a6dd2abb475e496cb571ee99dff"].unchecked_into(),
hex!["44c24fd0fc8cda7ba0c2613be44ef78782ee600eea05d4eb3af0a64f12056e6e"].unchecked_into(),
hex!["768d7df7f1f8dfbef05c34fa11358a52106a71ada232fa2bd35cb15df86f1b58"].unchecked_into(),
hex!["a2c666674fbf9a66df9ad15f1fa3bcea315990f7515c3dd2c26dcccc9d4bc27a"].unchecked_into(),
),
(
// Boot Node/Validator 3: ip addres 95.217.1.25
hex!["42547f143cb05a47a8de112e9b8362dec1d586fa241f29f0e591e17815f1d71a"].into(),
hex!["8e4ddd28c76a5963b7e81f73495afd663d9ed26ec66dfe8b8b7e3a8b4f01b330"].into(),
hex!["b034fb357e174f6c7bf7588dba0e191a24ae4f0b63f4ee41e9fcd9b00fcc5ed0"].unchecked_into(),
hex!["a401838c6a5043cc3353517e7c4396090277b568100806fed7769fadc8baa35b"].unchecked_into(),
hex!["6acdf720031ddf5d4c7cb06ee7876eef77688956575f5c0480df40b059804a38"].unchecked_into(),
hex!["bc2efdfdccb4c371eebd9fc1d9d86a6a2eaf516878a5989b0ddcd4f09101f606"].unchecked_into(),
),
],
// Sudo
hex!["caca29e30cce36df2263139cb15dd0e3ecbeb053d37aeac7ac8d2291ff7afa5c"].into(),
// Endowed accounts
vec![
hex!["caca29e30cce36df2263139cb15dd0e3ecbeb053d37aeac7ac8d2291ff7afa5c"].into(),
hex!["4e5758a750dad72ea2e777a16222765b5b713c9eeda2eb8cd3f3b989203c5008"].into(),
hex!["ccf2f08394dde73dd5bd1946552e2042d1f502cb50eb7c29061873f5831caf42"].into(),
],
),
// Bootnodes
vec![
"/ip4/95.217.2.2/tcp/30333/p2p/12D3KooWQrG8VAfYs8nXv95XJDu9Yo1iKKQ2KZRJkBVtfxpLvoYe".parse().unwrap(),
"/ip4/95.217.4.158/tcp/30333/p2p/12D3KooWCAdsB5VvsQ7eCWPZZ4eCdYbriFVwEJnvE5B9YAmRNTuY".parse().unwrap(),
"/ip4/95.217.1.25/tcp/30333/p2p/12D3KooWCRjP5nofPVvE5d7yj7wktKBPKwWxzc4oNd78z63nNvJC".parse().unwrap()
],
// Telemetry
TelemetryEndpoints::new(vec![(TELEMETRY_URL.into(), 0)]).ok(),
// Protocol ID
Some("bitg_testnet"),
// Properties
Some(bitg_properties()),
// Extensions
Default::default(),
))
}
pub fn mainnet_config() -> Result<ChainSpec, String> {
let wasm_binary = WASM_BINARY.ok_or_else(|| "WASM binary not available".to_string())?;
Ok(ChainSpec::from_genesis(
// Name
"Bitg Mainnet",
// ID
"bitg_mainnet",
ChainType::Live,
move || mainnet_genesis(
wasm_binary,
// Initial authorities keys:
// stash
// controller
// grandpa
// babe
// im-online
// authority-discovery
vec![
(
hex!["6c08c1f8e0cf1e200b24b43fca4c4e407b963b6b1e459d1aeff80c566a1da469"].into(),
hex!["864eff3160ff8609c030316867630850a9d6e35c47d3efe54de44264fef7665e"].into(),
hex!["dc41d9325da71d90806d727b826d125cd523da28eb39ab048ab983d7bb74fb32"].unchecked_into(),
hex!["8a688a748fd39bedaa507c942600c40478c2082dee17b8263613fc3c086b0c53"].unchecked_into(),
hex!["3a4e80c48718f72326b49c4ae80199d35285643751e75a743f30b7561b538676"].unchecked_into(),
hex!["68d39d0d386ed4e9dd7e280d62e7dc9cf61dc508ef25efb74b6d740fa4dde463"].unchecked_into(),
),
(
hex!["5c22097b5c8b5912ce28b72ba4de52c3da8aca9379c748c1356a6642107d4c4a"].into(),
hex!["543fd4fd9a284c0f955bb083ae6e0fe7a584eb6f6e72b386071a250b94f99a59"].into(),
hex!["f15a651be0ea0afcfe691a118ee7acfa114d11a27cf10991ee91ea97942d2135"].unchecked_into(),
hex!["70e74bed02b733e47bc044da80418fd287bb2b7a0c032bd211d7956c68c9561b"].unchecked_into(),
hex!["724cefffeaa10a44935a973511b9427a8c3c4fb08582afc4af8bf110fe4aac4b"].unchecked_into(),
hex!["a068435c438ddc61b1b656e3f61c876e109706383cf4e27309cc1e308f88b86f"].unchecked_into(),
),
(
hex!["a67f388c1b8d68287fb3288b5aa36f069875c15ebcb9b1e4e62678aad6b24b44"].into(),
hex!["ec912201d98911842b1a8e82983f71f2116dd8b898798ece4e1d210590de7d60"].into(),
hex!["347f5342875b9847ec089ca723c1c09cc532e53dca4b940a6138040025d94eb9"].unchecked_into(),
hex!["64841d2d124e1b1dd5485a58908ab244b296b184ae645a0c103adcbcc565f070"].unchecked_into(),
hex!["50a3452ca93800a8b660d624521c240e5cb20a47a33d23174bb7681811950646"].unchecked_into(),
hex!["7a0caeb50fbcd657b8388adfaeca41a2ae3e85b8916a2ce92761ce1a4db89035"].unchecked_into(),
),
],
// Sudo
hex!["9c48c0498bdf1d716f4544fc21f050963409f2db8154ba21e5233001202cbf08"].into(),
// Endowed accounts
vec![
// Investors
(hex!["3c483acc759b79f8b12fa177e4bdfa0448a6ea03c389cf4db2b4325f0fc8f84a"].into(), 4_340_893_656 as u128),
// Liquidity bridge reserves
(hex!["5adebb35eb317412b58672db0434e4b112fcd27abaf28039f07c0db155b26650"].into(), 2_000_000_000 as u128),
// Lockup & core nominators
(hex!["746db342d3981b230804d1a187245e565f8eb3a2897f83d0d841cc52282e324c"].into(), 500_000_000 as u128),
(hex!["da512d1335a62ad6f79baecfe87578c5d829113dc85dbb984d90a83f50680145"].into(), 500_000_000 as u128),
(hex!["b493eacad9ca9d7d8dc21b940966b4db65dfbe01084f73c1eee2793b1b0a1504"].into(), 500_000_000 as u128),
(hex!["849cf6f8a093c28fd0f699b47383767b0618f06aad9df61c4a9aff4af5809841"].into(), 250_000_000 as u128),
(hex!["863bd6a38c7beb526be033068ac625536cd5d8a83cd51c1577a1779fab41655c"].into(), 250_000_000 as u128),
(hex!["c2d2d7784e9272ef1785f92630dbce167a280149b22f2ae3b0262435e478884d"].into(), 250_000_000 as u128),
// Sudo
(hex!["9c48c0498bdf1d716f4544fc21f050963409f2db8154ba21e5233001202cbf08"].into(), 100_000_000 as u128),
// Developer pool & faucet
(hex!["1acc4a5c6361770eac4da9be1c37ac37ea91a55f57121c03240ceabf0b7c1c5e"].into(), 10_000_000 as u128),
],
),
// Bootnodes
vec![
"/dns/bootnode-1.bitg.org/tcp/30333/p2p/12D3KooWFHSc9cUcyNtavUkLg4VBAeBnYNgy713BnovUa9WNY5pp".parse().unwrap(),
"/dns/bootnode-2.bitg.org/tcp/30333/p2p/12D3KooWAQqcXvcvt4eVEgogpDLAdGWgR5bY1drew44We6FfJAYq".parse().unwrap(),
"/dns/bootnode-3.bitg.org/tcp/30333/p2p/12D3KooWCT7rnUmEK7anTp7svwr4GTs6k3XXnSjmgTcNvdzWzgWU".parse().unwrap(),
],
// Telemetry
TelemetryEndpoints::new(vec![(TELEMETRY_URL.into(), 0)]).ok(),
// Protocol ID
Some("bitg_mainnet"),
// Properties
Some(bitg_properties()),
// Extensions
Default::default(),
))
}
fn testnet_genesis(
wasm_binary: &[u8],
initial_authorities: Vec<(AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId)>,
root_key: AccountId,
endowed_accounts: Vec<AccountId>,
) -> GenesisConfig {
let evm_genesis_accounts = evm_genesis();
const INITIAL_BALANCE: u128 = 100_000_000 * BITG;
const INITIAL_STAKING: u128 = 1_000_000 * BITG;
let existential_deposit = MaxNativeTokenExistentialDeposit::get();
let enable_println=true;
let balances = initial_authorities
.iter()
.map(|x| (x.0.clone(), INITIAL_STAKING))
.chain(endowed_accounts.iter().cloned().map(|k| (k, INITIAL_BALANCE)))
.chain(
get_all_module_accounts()
.iter()
.map(|x| (x.clone(), existential_deposit)),
)
.fold(
BTreeMap::<AccountId, Balance>::new(),
|mut acc, (account_id, amount)| {
if let Some(balance) = acc.get_mut(&account_id) {
*balance = balance
.checked_add(amount)
.expect("balance cannot overflow when building genesis");
} else {
acc.insert(account_id.clone(), amount);
}
acc
},
)
.into_iter()
.collect::<Vec<(AccountId, Balance)>>();
GenesisConfig {
frame_system: Some(SystemConfig {
// Add Wasm runtime to storage.
code: wasm_binary.to_vec(),
changes_trie_config: Default::default(),
}),
pallet_indices: Some(IndicesConfig { indices: vec![] }),
pallet_balances: Some(BalancesConfig { balances }),
pallet_session: Some(SessionConfig {
keys: initial_authorities
.iter()
.map(|x| (
x.0.clone(), // stash
x.0.clone(), // stash
get_session_keys(
x.2.clone(), // grandpa
x.3.clone(), // babe
x.4.clone(), // im-online
x.5.clone(), // authority-discovery
)))
.collect::<Vec<_>>(),
}),
pallet_staking: Some(StakingConfig {
validator_count: initial_authorities.len() as u32 * 2,
minimum_validator_count: initial_authorities.len() as u32,
stakers: initial_authorities
.iter()
.map(|x| (x.0.clone(), x.1.clone(), INITIAL_STAKING, StakerStatus::Validator))
.collect(),
invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(),
slash_reward_fraction: sp_runtime::Perbill::from_percent(10),
..Default::default()
}),
pallet_babe: Some(BabeConfig { authorities: vec![] }),
pallet_grandpa: Some(GrandpaConfig { authorities: vec![] }),
pallet_authority_discovery: Some(AuthorityDiscoveryConfig { keys: vec![] }),
pallet_im_online: Default::default(),
orml_tokens: Some(TokensConfig {
endowed_accounts: endowed_accounts
.iter()
.flat_map(|x| {
vec![
(x.clone(), CurrencyId::Token(TokenSymbol::USDG), INITIAL_BALANCE),
]
})
.collect(),
}),
module_evm: Some(EvmConfig {
accounts: evm_genesis_accounts,
}),
pallet_sudo: Some(SudoConfig { key: root_key }),
pallet_collective_Instance1: Some(Default::default()),
// Nft pallet
orml_nft: Default::default(),
// Smart contracts !Ink Language
pallet_contracts: Some(ContractsConfig {
current_schedule: pallet_contracts::Schedule {
enable_println,
..Default::default()
},
}),
}
}
fn mainnet_genesis(
wasm_binary: &[u8],
initial_authorities: Vec<(AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId)>,
root_key: AccountId,
endowed_accounts: Vec<(AccountId, Balance)>,
) -> GenesisConfig {
let evm_genesis_accounts = evm_genesis();
const INITIAL_STAKING: u128 = 1_000_000 * BITG;
let existential_deposit = MaxNativeTokenExistentialDeposit::get();
let enable_println=true;
let balances = initial_authorities
.iter()
.map(|x| (x.0.clone(), INITIAL_STAKING*2))
.chain(endowed_accounts.iter().cloned().map(|x| (x.0.clone(), x.1 * BITG)))
.chain(
get_all_module_accounts()
.iter()
.map(|x| (x.clone(), existential_deposit)),
)
.fold(
BTreeMap::<AccountId, Balance>::new(),
|mut acc, (account_id, amount)| {
if let Some(balance) = acc.get_mut(&account_id) {
*balance = balance
.checked_add(amount)
.expect("balance cannot overflow when building genesis");
} else {
acc.insert(account_id.clone(), amount);
}
acc
},
)
.into_iter()
.collect::<Vec<(AccountId, Balance)>>();
GenesisConfig {
frame_system: Some(SystemConfig {
// Add Wasm runtime to storage.
code: wasm_binary.to_vec(),
changes_trie_config: Default::default(),
}),
pallet_indices: Some(IndicesConfig { indices: vec![] }),
pallet_balances: Some(BalancesConfig { balances }),
pallet_session: Some(SessionConfig {
keys: initial_authorities
.iter()
.map(|x| (
x.0.clone(), // stash
x.0.clone(), // stash
get_session_keys(
x.2.clone(), // grandpa
x.3.clone(), // babe
x.4.clone(), // im-online
x.5.clone(), // authority-discovery
)))
.collect::<Vec<_>>(),
}),
pallet_staking: Some(StakingConfig {
validator_count: initial_authorities.len() as u32 * 2,
minimum_validator_count: initial_authorities.len() as u32,
stakers: initial_authorities
.iter()
.map(|x| (x.0.clone(), x.1.clone(), INITIAL_STAKING, StakerStatus::Validator))
.collect(),
invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(),
slash_reward_fraction: sp_runtime::Perbill::from_percent(10),
..Default::default()
}),
pallet_babe: Some(BabeConfig { authorities: vec![] }),
pallet_grandpa: Some(GrandpaConfig { authorities: vec![] }),
pallet_authority_discovery: Some(AuthorityDiscoveryConfig { keys: vec![] }),
pallet_im_online: Default::default(),
orml_tokens: Some(TokensConfig {
endowed_accounts: vec![]
}),
module_evm: Some(EvmConfig {
accounts: evm_genesis_accounts,
}),
pallet_sudo: Some(SudoConfig { key: root_key }),
pallet_collective_Instance1: Some(Default::default()),
// Nft pallet
orml_nft: Default::default(),
// Smart contracts !Ink Language
pallet_contracts: Some(ContractsConfig {
current_schedule: pallet_contracts::Schedule {
enable_println,
..Default::default()
},
}),
}
}
/// Token
pub fn bitg_properties() -> Properties {
let mut p = Properties::new();
p.insert("ss58format".into(), 42.into());
p.insert("tokenDecimals".into(), 18.into());
p.insert("tokenSymbol".into(), "BITG".into());
p
}
/// Predeployed contract addresses
pub fn evm_genesis() -> BTreeMap<H160, module_evm::GenesisAccount<Balance, Nonce>> {
let existential_deposit = MaxNativeTokenExistentialDeposit::get();
let contracts_json = &include_bytes!("../../assets/bytecodes.json")[..];
let contracts: Vec<(String, String, String)> = serde_json::from_slice(contracts_json).unwrap();
let mut accounts = BTreeMap::new();
for (_, address, code_string) in contracts {
let account = module_evm::GenesisAccount {
nonce: 0,
balance: existential_deposit,
storage: Default::default(),
code: Bytes::from_str(&code_string).unwrap().0,
};
let addr = H160::from_slice(
from_hex(address.as_str())
.expect("predeploy-contracts must specify address")
.as_slice(),
);
accounts.insert(addr, account);
}
accounts
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::qlib::Common::*;
use super::qlib::kernel::waiter::*;
pub fn Notify(_fd: i32, _mask: u32) {}
pub fn AddFD(_fd: i32, _queue: &Queue) {}
pub fn RemoveFD(_fd: i32) {}
pub fn UpdateFD(_fd: i32) -> Result<()> { return Err(Error::None) }
pub fn NonBlockingPoll(_fd: i32, _mask: EventMask) -> EventMask { 0 } |
use std::error::Error;
use std::fmt;
use std::time::SystemTime;
use rusqlite::{ Connection };
use reqwest::header;
//##: Global definitions
static USERAGENT: &str = "Hydra (PodcastIndex)/v0.1";
struct Podcast {
id: u64,
url: String,
title: String
}
#[derive(Debug)]
struct HydraError(String);
//##: Implement
impl fmt::Display for HydraError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Fatal error: {}", self.0)
}
}
impl Error for HydraError {}
//##: -------------------- Main() -----------------------
//##: ---------------------------------------------------
fn main() {
//Globals
//let pi_database_url: &str = "https://cloudflare-ipfs.com/ipns/k51qzi5uqu5dkde1r01kchnaieukg7xy9i6eu78kk3mm3vaa690oaotk1px6wo/podcastindex_feeds.db.tgz";
let sqlite_file: &str = "podcastindex_feeds.db";
//Fetch urls
let podcasts = get_feeds_from_sql(sqlite_file);
match podcasts {
Ok(podcasts) => {
for podcast in podcasts {
println!("{:#?}|{:#?}|{:#?}", podcast.id, podcast.url, podcast.title);
check_feed_is_updated(podcast.url.as_str());
}
},
Err(e) => println!("{}", e),
}
}
//##: ---------------------------------------------------
//##: Get a list of podcasts from the downloaded sqlite db
fn get_feeds_from_sql(sqlite_file: &str) -> Result<Vec<Podcast>, Box<dyn Error>> {
//Locals
let mut podcasts: Vec<Podcast> = Vec::new();
//Restrict to feeds that have updated in a reasonable amount of time
let since_time: u64 = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(n) => n.as_secs() - (86400 * 90),
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
};
//Connect to the PI sqlite database file
let sql = Connection::open(sqlite_file);
match sql {
Ok(sql) => {
println!("Got some podcasts.");
//Run the query and store the result
let sql_text: String = format!("SELECT id, url, title FROM podcasts WHERE newestItemPubdate > {} LIMIT 1", since_time);
let stmt = sql.prepare(sql_text.as_str());
match stmt {
Ok(mut dbresults) => {
let podcast_iter = dbresults.query_map([], |row| {
Ok(Podcast {
id: row.get(0).unwrap(),
url: row.get(1).unwrap(),
title: row.get(2).unwrap()
})
}).unwrap();
//Iterate the list and store
for podcast in podcast_iter {
let pod: Podcast = podcast.unwrap();
podcasts.push(pod);
}
},
Err(e) => return Err(Box::new(HydraError(format!("Error running SQL query: [{}]", e).into())))
}
//sql.close();
Ok(podcasts)
},
Err(e) => return Err(Box::new(HydraError(format!("Error running SQL query: [{}]", e).into())))
}
}
//##: Fetch the content of a url
fn fetch_feed(url: &str) -> Result<bool, Box<dyn Error>> {
let feed_url: &str = url;
//##: Build the query with the required headers
let mut headers = header::HeaderMap::new();
headers.insert("User-Agent", header::HeaderValue::from_static(USERAGENT));
let client = reqwest::blocking::Client::builder().default_headers(headers).build().unwrap();
//##: Send the request and display the results or the error
let res = client.get(feed_url).send();
match res {
Ok(res) => {
println!("Response Status: [{}]", res.status());
println!("Response Body: {}", res.text().unwrap());
return Ok(true);
},
Err(e) => {
eprintln!("Error: [{}]", e);
return Err(Box::new(HydraError(format!("Error running SQL query: [{}]", e).into())));
}
}
}
//##: Do a head check on a url to see if it's been modified
fn check_feed_is_updated(url: &str) -> Result<bool, Box<dyn Error>> {
//##: Build the query with the required headers
let mut headers = header::HeaderMap::new();
headers.insert("User-Agent", header::HeaderValue::from_static(USERAGENT));
//headers.insert("Last-Modified", header::HeaderValue::from_static());
let client = reqwest::blocking::Client::builder().default_headers(headers).build().unwrap();
//##: Send the request and display the results or the error
let res = client.get(url).send();
match res {
Ok(res) => {
println!("Response Status: [{}]", res.status());
for h in res.headers().into_iter() {
println!("Response Headers: {:?}", h);
}
return Ok(true);
},
Err(e) => {
eprintln!("Error: [{}]", e);
return Err(Box::new(HydraError(format!("Error running SQL query: [{}]", e).into())));
}
}
}
//----------Scratchpad-------------
// use std::io::prelude::*;
// use std::fs::File;
// use std::io::BufReader;
// use futures::stream::StreamExt;
// fn read_lines(path: &str) -> std::io::Result<Vec<String>> {
// let file = File::open(path)?;
// let reader = BufReader::new(file);
// Ok(
// reader.lines().filter_map(Result::ok).collect()
// )
// }
// #[tokio::main]
// async fn fetch_feeds(urls_file: &str) -> Result<(), Box<dyn std::error::Error>> {
// let paths: Vec<String> = read_lines(urls_file)?;
// let fetches = futures::stream::iter(
// paths.into_iter().map(|path| {
// async move {
// match reqwest::get(&path).await {
// Ok(resp) => {
// match resp.text().await {
// Ok(text) => {
// println!("RESPONSE: {} bytes from {}", text.len(), path);
// }
// Err(_) => println!("ERROR reading {}", path),
// }
// }
// Err(_) => println!("ERROR downloading {}", path),
// }
// }
// })
// ).buffer_unordered(100).collect::<Vec<()>>();
// fetches.await;
// Ok(())
// } |
// Copyright (C) 2019 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: MIT
use std::process;
use crate::{Choice, Error, Input, Message, Password, Question, Result};
/// The `dialog` backend.
///
/// This backend uses the external `dialog` program (not to be confused with this crate also called
/// `dialog`) to display text-based dialog boxes in the terminal.
#[derive(Debug)]
pub struct Dialog {
backtitle: Option<String>,
width: String,
height: String,
}
impl Dialog {
/// Creates a new `Dialog` instance without configuration.
pub fn new() -> Dialog {
Dialog {
backtitle: None,
height: "0".to_string(),
width: "0".to_string(),
}
}
/// Sets the backtitle for the dialog boxes.
///
/// The backtitle is displayed on the backdrop, at the top of the screen.
pub fn set_backtitle(&mut self, backtitle: impl Into<String>) {
self.backtitle = Some(backtitle.into());
}
/// Sets the height of the dialog boxes.
///
/// The height is given in characters. The actual height of the dialog box might be higher
/// than the given height if the content would not fit otherwise. The default height is zero.
pub fn set_height(&mut self, height: u32) {
self.height = height.to_string();
}
/// Sets the width of the dialog boxes.
///
/// The width is given in characters. The actual width of the dialog box might be higher than
/// the given width if the content would not fit otherwise. The default width is zero.
pub fn set_width(&mut self, width: u32) {
self.width = width.to_string();
}
pub(crate) fn is_available() -> bool {
super::is_available("dialog")
}
fn execute(
&self,
args: Vec<&str>,
post_args: Vec<&str>,
title: &Option<String>,
) -> Result<process::Output> {
let mut command = process::Command::new("dialog");
command.stdin(process::Stdio::inherit());
command.stdout(process::Stdio::inherit());
if let Some(ref backtitle) = self.backtitle {
command.arg("--backtitle");
command.arg(backtitle);
}
if let Some(ref title) = title {
command.arg("--title");
command.arg(title);
}
command.args(args);
command.arg(&self.height);
command.arg(&self.width);
command.args(post_args);
command.output().map_err(Error::IoError)
}
}
impl AsRef<Dialog> for Dialog {
fn as_ref(&self) -> &Self {
self
}
}
fn require_success(status: process::ExitStatus) -> Result<()> {
if status.success() {
Ok(())
} else {
Err(Error::from(("dialog", status)))
}
}
fn get_choice(status: process::ExitStatus) -> Result<Choice> {
if let Some(code) = status.code() {
match code {
0 => Ok(Choice::Yes),
1 => Ok(Choice::No),
255 => Ok(Choice::Cancel),
_ => Err(Error::from(("dialog", status))),
}
} else {
Err(Error::from(("dialog", status)))
}
}
fn get_stderr(output: process::Output) -> Result<Option<String>> {
if output.status.success() {
String::from_utf8(output.stderr)
.map(Some)
.map_err(Error::from)
} else if let Some(code) = output.status.code() {
match code {
0 => Ok(None),
1 => Ok(None),
255 => Ok(None),
_ => Err(Error::from(("dialog", output.status))),
}
} else {
Err(Error::from(("dialog", output.status)))
}
}
impl super::Backend for Dialog {
fn show_input(&self, input: &Input) -> Result<Option<String>> {
let args = vec!["--inputbox", &input.text];
let mut post_args: Vec<&str> = Vec::new();
if let Some(ref default) = input.default {
post_args.push(default);
}
self.execute(args, post_args, &input.title)
.and_then(get_stderr)
}
fn show_message(&self, message: &Message) -> Result<()> {
let args = vec!["--msgbox", &message.text];
self.execute(args, vec![], &message.title)
.and_then(|output| require_success(output.status))
.map(|_| ())
}
fn show_password(&self, password: &Password) -> Result<Option<String>> {
let args = vec!["--passwordbox", &password.text];
self.execute(args, vec![], &password.title)
.and_then(get_stderr)
}
fn show_question(&self, question: &Question) -> Result<Choice> {
let args = vec!["--yesno", &question.text];
self.execute(args, vec![], &question.title)
.and_then(|output| get_choice(output.status))
}
}
|
// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! X.509 parsing.
use crate::cert;
use crate::cert::der;
use crate::cert::der::Tag;
use crate::cert::Algo;
use crate::cert::Cert;
use crate::cert::Error;
use crate::cert::Name;
use crate::cert::PublicKeyParams;
#[cfg(test)]
#[path = "x509_test.rs"]
mod test;
/// OIDs used by the parser.
#[allow(unused)]
mod oid {
use crate::cert::der::Oid;
pub const RSA_ENCRYPTION: Oid = oid!(1, 2, 840, 113549, 1, 1, 1);
pub const RSA_PKCS1_SHA256: Oid = oid!(1, 2, 840, 113549, 1, 1, 11);
pub const KEY_USAGE: Oid = oid!(2, 5, 29, 15);
pub const BASIC_CONSTRAINTS: Oid = oid!(2, 5, 29, 19);
pub const TCG_DICE_FWID: Oid = oid!(2, 23, 133, 5, 4, 1);
}
/// Parses an RFC3279 algorithm identifier.
fn parse_algo(buf: &mut untrusted::Reader) -> Result<Algo, Error> {
match der::oid(buf)? {
oid::RSA_PKCS1_SHA256 => {
der::null(buf)?;
Ok(Algo::RsaPkcs1Sha256)
}
_ => Err(Error::UnknownAlgorithm),
}
}
/// Parses an X.509 certificate.
///
/// This function performs several aggressive checks to reject any and all
/// certificates that do not fit our profile. These include:
/// - Version must be v3.
/// - Extensions must be present.
/// - `keyUsage`, `authorityKeyIdentifier`, `subjectKeyIdentifier` must all
/// be present.
/// - A `keyUsage` with `keyCertSign` and any other usage is rejected.
///
/// All of the above are treated as encoding errors.
pub fn parse<'cert>(
cert: &'cert [u8],
format: cert::CertFormat,
key: Option<&PublicKeyParams<'_>>,
ciphers: &mut impl cert::Ciphers,
) -> Result<Cert<'cert>, Error> {
let buf = untrusted::Input::from(cert);
let (cert, tbs, sig_algo, sig) =
buf.read_all(Error::BadEncoding, |buf| {
der::tagged(Tag::SEQUENCE, buf, |buf| {
let mark = buf.mark();
let tbs = der::parse(Tag::SEQUENCE, buf)?;
let tbs_bytes =
buf.get_input_between_marks(mark, buf.mark())?;
let sig_algo_bytes = der::parse(Tag::SEQUENCE, buf)?;
let sig_algo =
sig_algo_bytes.read_all(Error::BadEncoding, parse_algo)?;
let sig = der::bits_total(buf)?;
let cert = tbs.read_all(Error::BadEncoding, |buf| {
parse_tbs(format, sig_algo_bytes, buf)
})?;
Ok((
cert,
tbs_bytes.as_slice_less_safe(),
sig_algo,
sig.as_slice_less_safe(),
))
})
})?;
let key = key.unwrap_or_else(|| cert.subject_key());
if !key.is_params_for(sig_algo) {
return Err(Error::WrongAlgorithm);
}
let verifier = ciphers
.verifier(sig_algo, key)
.ok_or(Error::UnknownAlgorithm)?;
verifier.verify(sig, tbs).map_err(|_| Error::BadSignature)?;
Ok(cert)
}
fn parse_tbs<'cert>(
format: cert::CertFormat,
sig_algo_bytes: untrusted::Input,
buf: &mut untrusted::Reader<'cert>,
) -> Result<Cert<'cert>, Error> {
// Although the version field is optional, we reject all non-v3
// certificates, which require this field.
//
// We treat this as a syntactic, rather than semantic, error.
der::tagged(Tag::context_specific(0), buf, |mut buf| {
// `v3` certificates are encoded as an `INTEGER { 2 }`.
if der::u32(&mut buf)? != 2 {
return Err(Error::BadEncoding);
}
Ok(())
})?;
// The certificate serial number must be a positive `INTEGER` consisting
// of at most 20 octets.
//
// Like with the version, this is a syntactic error. The value itself
// is discarded.
let serial = der::uint(buf)?.as_slice_less_safe();
if serial[0] == 0 || serial.len() > 20 {
return Err(Error::BadEncoding);
}
// A mismatch between the inner and outer signature algorithm
// identifiers (byte-for-byte) is a syntax error.
let sig_algo2 = der::parse(Tag::SEQUENCE, buf)?;
if sig_algo2 != sig_algo_bytes {
return Err(Error::BadEncoding);
}
// The issuer is an opaque name.
let issuer = Name(der::parse(Tag::SEQUENCE, buf)?.as_slice_less_safe());
// TODO: Provide some mechanism for the user to pass in a clock, if
// available. X.509 time parsing incurs significant complexity, so
// it probably shouldn't be implemented until it's absolutely necessary.
let _validity = der::parse(Tag::SEQUENCE, buf)?;
// The subject is also opaque
let subject = Name(der::parse(Tag::SEQUENCE, buf)?.as_slice_less_safe());
let subject_key = der::tagged(Tag::SEQUENCE, buf, |buf| {
let (algo, aparams) = der::tagged(Tag::SEQUENCE, buf, |buf| {
let algo = der::oid(buf)?;
let aparams = buf.read_bytes_to_end();
Ok((algo, aparams))
})?;
der::bits_total(buf)?.read_all(Error::BadEncoding, |buf| match algo {
oid::RSA_ENCRYPTION => {
aparams.read_all(Error::BadEncoding, der::null)?;
der::tagged(Tag::SEQUENCE, buf, |buf| {
let mut modulus = der::uint(buf)?.as_slice_less_safe();
// DER inserts a leading zero sometimes (to disambiguate
// negative integers) so we need to remove it.
if modulus[0] == 0 {
modulus = &modulus[1..];
}
let mut exponent = der::uint(buf)?.as_slice_less_safe();
if exponent[0] == 0 {
exponent = &exponent[1..];
}
Ok(PublicKeyParams::Rsa { modulus, exponent })
})
}
_ => Err(Error::UnknownAlgorithm),
})
})?;
// We don't care about the UIDs at all.
let _issuer_uid = der::opt(Tag::context_specific(1), buf)?;
let _subject_uid = der::opt(Tag::context_specific(2), buf)?;
// Extensions are mandatory.
let mut extns = Extensions::default();
der::tagged(Tag::context_specific(3), buf, |buf| {
der::tagged(Tag::SEQUENCE, buf, |buf| {
while !buf.at_end() {
parse_extn(buf, &mut extns)?;
}
Ok(())
})
})?;
let is_cert_sign = match extns.is_cert_sign {
Some(b) => b,
_ => return Err(Error::BadEncoding),
};
let is_ca = match &extns.basic_constraints {
Some(bc) => bc.is_ca,
_ => false,
};
// CA certificates must always specify keyCertSign as a valid usage. To
// fail to do so is a syntax error.
if is_ca != is_cert_sign {
return Err(Error::BadEncoding);
}
Ok(Cert {
format,
issuer,
subject,
subject_key,
basic_constraints: extns.basic_constraints,
is_cert_sign,
})
}
#[derive(Default)]
struct Extensions {
basic_constraints: Option<cert::BasicConstraints>,
is_cert_sign: Option<bool>,
}
fn parse_extn(
buf: &mut untrusted::Reader,
extns: &mut Extensions,
) -> Result<(), Error> {
der::tagged(Tag::SEQUENCE, buf, |buf| {
let oid = der::oid(buf)?;
let is_critical = der::opt_bool(buf)?.unwrap_or(false);
der::tagged(Tag::OCTET_STRING, buf, |buf| match oid {
oid::KEY_USAGE => {
if extns.is_cert_sign.is_some() {
return Err(Error::BadEncoding);
}
// Constants from RFC5280 S4.2.1.3. I.e.,
// ```asn1
// KeyUsage ::= BIT STRING {
// digitalSignature (0),
// nonRepudiation (1),
// keyEncipherment (2),
// dataEncipherment (3),
// keyAgreement (4),
// keyCertSign (5),
// cRLSign (6),
// encipherOnly (7),
// decipherOnly (8),
// }
// ```
//
// Note that the bits in a `BIT STRING` are big endian
// within bytes, so we need to "shift from the left"
// instead.
const CERT_SIGN_MASK: u16 = 1 << (15 - 5);
der::bits_partial(buf)?.read_all(Error::BadEncoding, |buf| {
let first_byte = buf.read_byte().unwrap_or(0);
let second_byte = buf.read_byte().unwrap_or(0);
// NOTE: This technically drops any "domain-specific"
// bits on the ground, but we have zero interest in retaining
// those.
let bits = u16::from_be_bytes([first_byte, second_byte]);
extns.is_cert_sign = Some(bits & CERT_SIGN_MASK != 0);
if extns.is_cert_sign == Some(true)
&& bits != CERT_SIGN_MASK
{
// For domain separation reasons, we reject all
// certificates that mix certificate signing with any
// other usage.
return Err(Error::BadEncoding);
}
Ok(())
})
}
oid::BASIC_CONSTRAINTS => {
if extns.basic_constraints.is_some() {
return Err(Error::BadEncoding);
}
der::tagged(Tag::SEQUENCE, buf, |buf| {
let is_ca = der::opt_bool(buf)?.unwrap_or(false);
let path_len_constraint = der::opt_u32(buf)?;
extns.basic_constraints = Some(cert::BasicConstraints {
is_ca,
path_len_constraint,
});
Ok(())
})
}
_ if is_critical => Err(Error::BadEncoding),
_ => Ok(()),
})
})
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use super::*;
/// Handles commands received from the peer, typically when we are acting in target role for A2DP
/// source and absolute volume support for A2DP sink. Maintains state such as continuations and
/// registered notifications by the peer.
/// FIXME: This is a stub that mostly logs incoming commands as we implement out features in TARGET.
#[derive(Debug)]
pub struct ControlChannelHandler {
/// Handle back to the remote peer. Weak to prevent a reference cycle since the remote peer owns this object.
pub remote_peer: Weak<RemotePeer>,
}
impl ControlChannelHandler {
pub fn new(remote_peer: Weak<RemotePeer>) -> Self {
Self { remote_peer }
}
fn handle_passthrough_command(
&self,
remote_peer: &Arc<RemotePeer>,
command: &AvcCommand,
) -> Result<AvcResponseType, Error> {
let body = command.body();
let command = AvcPanelCommand::from_primitive(body[0]);
fx_log_info!("Received passthrough command {:x?} {}", command, &remote_peer.peer_id);
match command {
Some(_) => Ok(AvcResponseType::Accepted),
None => Ok(AvcResponseType::Rejected),
}
}
fn handle_notify_vendor_command(&self, _inner: &Arc<PeerManagerInner>, command: &AvcCommand) {
let packet_body = command.body();
let preamble = match VendorDependentPreamble::decode(packet_body) {
Err(e) => {
fx_log_err!("Unable to parse vendor dependent preamble: {:?}", e);
// TODO: validate error response is correct. Consider dropping the connection?
let _ = command.send_response(AvcResponseType::NotImplemented, packet_body);
return;
}
Ok(x) => x,
};
let body = &packet_body[preamble.encoded_len()..];
let pdu_id = match PduId::try_from(preamble.pdu_id) {
Err(e) => {
fx_log_err!("Unknown pdu {} received {:#?}: {:?}", preamble.pdu_id, body, e);
let _ = command.send_response(AvcResponseType::NotImplemented, packet_body);
return;
}
Ok(x) => x,
};
// The only PDU that you can send a Notify on is RegisterNotification.
if pdu_id != PduId::RegisterNotification {
let reject_response = RejectResponse::new(&pdu_id, &StatusCode::InvalidParameter);
let packet = reject_response.encode_packet().unwrap();
let _ = command.send_response(AvcResponseType::Rejected, &packet[..]);
return;
}
match RegisterNotificationCommand::decode(&body[..]) {
Ok(notification_command) => match *notification_command.event_id() {
_ => {
fx_log_info!(
"Unhandled register notification {:?}",
*notification_command.event_id()
);
let reject_response = RejectResponse::new(
&PduId::RegisterNotification,
&StatusCode::InvalidParameter,
);
let packet =
reject_response.encode_packet().expect("unable to encode rejection packet");
// TODO: validate this correct error code to respond in this case.
let _ = command.send_response(AvcResponseType::Rejected, &packet[..]);
return;
}
},
Err(e) => {
fx_log_err!(
"Unable to decode register notification command {} {:#?}: {:?}",
preamble.pdu_id,
body,
e
);
let reject_response =
RejectResponse::new(&PduId::RegisterNotification, &StatusCode::InvalidCommand);
let packet =
reject_response.encode_packet().expect("unable to encode rejection packet");
// TODO: validate this correct error code to respond in this case.
let _ = command.send_response(AvcResponseType::Rejected, &packet[..]);
return;
}
}
}
fn handle_status_vendor_command(
&self,
pdu_id: PduId,
body: &[u8],
) -> Result<(AvcResponseType, Vec<u8>), Error> {
match pdu_id {
PduId::GetCapabilities => match GetCapabilitiesCommand::decode(body) {
Ok(get_cap_cmd) => {
fx_vlog!(tag: "avrcp", 2, "Received GetCapabilities Command {:#?}", get_cap_cmd);
match get_cap_cmd.capability_id() {
GetCapabilitiesCapabilityId::CompanyId => {
let response = GetCapabilitiesResponse::new_btsig_company();
let buf =
response.encode_packet().map_err(|e| Error::PacketError(e))?;
Ok((AvcResponseType::ImplementedStable, buf))
}
GetCapabilitiesCapabilityId::EventsId => {
let response = GetCapabilitiesResponse::new_events(&[]);
let buf =
response.encode_packet().map_err(|e| Error::PacketError(e))?;
Ok((AvcResponseType::ImplementedStable, buf))
}
}
}
_ => {
fx_vlog!(tag: "avrcp", 2, "Unable to parse GetCapabilitiesCommand, sending rejection.");
let response = RejectResponse::new(&pdu_id, &StatusCode::InvalidParameter);
let buf = response.encode_packet().map_err(|e| Error::PacketError(e))?;
Ok((AvcResponseType::Rejected, buf))
}
},
PduId::GetElementAttributes => {
let get_element_attrib_command =
GetElementAttributesCommand::decode(body).map_err(|e| Error::PacketError(e))?;
fx_vlog!(tag: "avrcp", 2, "Received GetElementAttributes Command {:#?}", get_element_attrib_command);
let response = GetElementAttributesResponse {
title: Some("Hello world".to_string()),
..GetElementAttributesResponse::default()
};
let buf = response.encode_packet().map_err(|e| Error::PacketError(e))?;
Ok((AvcResponseType::ImplementedStable, buf))
}
_ => {
fx_vlog!(tag: "avrcp", 2, "Received unhandled vendor command {:?}", pdu_id);
Err(Error::CommandNotSupported)
}
}
}
fn handle_vendor_command(
&self,
remote_peer: &Arc<RemotePeer>,
command: &AvcCommand,
pmi: &Arc<PeerManagerInner>,
) -> Result<(), Error> {
let packet_body = command.body();
let preamble = match VendorDependentPreamble::decode(packet_body) {
Err(e) => {
fx_log_info!(
"Unable to parse vendor dependent preamble {}: {:?}",
remote_peer.peer_id,
e
);
// TODO: validate this correct error code to respond in this case.
let _ = command.send_response(AvcResponseType::NotImplemented, &packet_body[..]);
fx_vlog!(tag: "avrcp", 2, "Sent NotImplemented response to unparsable command");
return Ok(());
}
Ok(x) => x,
};
let body = &packet_body[preamble.encoded_len()..];
let pdu_id = match PduId::try_from(preamble.pdu_id) {
Err(e) => {
fx_log_err!(
"Unsupported vendor dependent command pdu {} received from peer {} {:#?}: {:?}",
preamble.pdu_id,
remote_peer.peer_id,
body,
e
);
// recoverable error
let preamble = VendorDependentPreamble::new_single(preamble.pdu_id, 0);
let prelen = preamble.encoded_len();
let mut buf = vec![0; prelen];
preamble.encode(&mut buf[..]).expect("unable to encode preamble");
// TODO: validate this correct error code to respond in this case.
let _ = command.send_response(AvcResponseType::NotImplemented, &buf[..]);
fx_vlog!(tag: "avrcp", 2, "Sent NotImplemented response to unsupported command {:?}", preamble.pdu_id);
return Ok(());
}
Ok(x) => x,
};
fx_vlog!(tag: "avrcp", 2, "Received command PDU {:#?}", pdu_id);
match command.avc_header().packet_type() {
AvcPacketType::Command(AvcCommandType::Notify) => {
fx_vlog!(tag: "avrcp", 2, "Received ctype=notify command {:?}", pdu_id);
self.handle_notify_vendor_command(pmi, &command);
Ok(())
}
AvcPacketType::Command(AvcCommandType::Status) => {
fx_vlog!(tag: "avrcp", 2, "Received ctype=status command {:?}", pdu_id);
// FIXME: handle_status_vendor_command should better match
// handle_notify_vendor_command by sending it's own responses instead
// of delegating it back up here to send. Originally it was done this
// way so that it would be easier to test but behavior difference is
// more confusing than the testability convenience
match self.handle_status_vendor_command(pdu_id, &body[..]) {
Ok((response_type, buf)) => {
if let Err(e) = command.send_response(response_type, &buf[..]) {
fx_log_err!(
"Error sending vendor response to peer {}, {:?}",
remote_peer.peer_id,
e
);
// unrecoverable
return Err(Error::from(e));
}
fx_vlog!(tag: "avrcp", 2, "sent response {:?} to command {:?}", response_type, pdu_id);
Ok(())
}
Err(e) => {
fx_log_err!(
"Error parsing command packet from peer {}, {:?}",
remote_peer.peer_id,
e
);
let response_error_code: StatusCode = match e {
Error::CommandNotSupported => {
let preamble =
VendorDependentPreamble::new_single(preamble.pdu_id, 0);
let prelen = preamble.encoded_len();
let mut buf = vec![0; prelen];
preamble.encode(&mut buf[..]).expect("unable to encode preamble");
if let Err(e) =
command.send_response(AvcResponseType::NotImplemented, &buf[..])
{
fx_log_err!(
"Error sending not implemented response to peer {}, {:?}",
remote_peer.peer_id,
e
);
return Err(Error::from(e));
}
fx_vlog!(tag: "avrcp", 2, "sent not implemented response to command {:?}", pdu_id);
return Ok(());
}
Error::PacketError(PacketError::OutOfRange) => {
StatusCode::InvalidParameter
}
Error::PacketError(PacketError::InvalidHeader) => {
StatusCode::ParameterContentError
}
Error::PacketError(PacketError::InvalidMessage) => {
StatusCode::ParameterContentError
}
Error::PacketError(PacketError::UnsupportedMessage) => {
StatusCode::InternalError
}
_ => StatusCode::InternalError,
};
let pdu_id = PduId::try_from(preamble.pdu_id).expect("Handled above.");
let reject_response = RejectResponse::new(&pdu_id, &response_error_code);
if let Ok(packet) = reject_response.encode_packet() {
if let Err(e) =
command.send_response(AvcResponseType::Rejected, &packet[..])
{
fx_log_err!(
"Error sending vendor reject response to peer {}, {:?}",
remote_peer.peer_id,
e
);
return Err(Error::from(e));
}
fx_vlog!(tag: "avrcp", 2, "sent not reject response {:?} to command {:?}", response_error_code, pdu_id);
} else {
// TODO(BT-2220): Audit behavior. Consider different options in this
// error case like dropping the L2CAP socket.
fx_log_err!("Unable to encoded reject response. dropping.");
}
Ok(())
}
}
}
_ => {
let preamble = VendorDependentPreamble::new_single(preamble.pdu_id, 0);
let prelen = preamble.encoded_len();
let mut buf = vec![0; prelen];
preamble.encode(&mut buf[..]).expect("unable to encode preamble");
let _ = command.send_response(AvcResponseType::NotImplemented, &buf[..]);
fx_vlog!(tag: "avrcp", 2, "unexpected ctype: {:?}. responding with not implemented {:?}", command.avc_header().packet_type(), pdu_id);
Ok(())
}
}
}
pub fn handle_command(
&self,
command: AvcCommand,
pmi: Arc<PeerManagerInner>,
) -> Result<(), Error> {
match Weak::upgrade(&self.remote_peer) {
Some(remote_peer) => {
fx_vlog!(tag: "avrcp", 2, "received command {:#?}", command);
match command.avc_header().op_code() {
&AvcOpCode::VendorDependent => {
self.handle_vendor_command(&remote_peer, &command, &pmi)
}
&AvcOpCode::Passthrough => {
match self.handle_passthrough_command(&remote_peer, &command) {
Ok(response_type) => {
if let Err(e) = command.send_response(response_type, &[]) {
fx_log_err!(
"Unable to send passthrough response to peer {}, {:?}",
remote_peer.peer_id,
e
);
return Err(Error::from(e));
}
fx_vlog!(tag: "avrcp", 2, "sent response {:?} to passthrough command", response_type);
Ok(())
}
Err(e) => {
fx_log_err!(
"Error parsing command packet from peer {}, {:?}",
remote_peer.peer_id,
e
);
// Sending the error response. This is best effort since the peer
// has sent us malformed packet, so we are ignoring and purposefully
// not handling and error received to us sending a rejection response.
// TODO(BT-2220): audit this behavior and consider logging.
let _ = command.send_response(AvcResponseType::Rejected, &[]);
fx_vlog!(tag: "avrcp", 2, "sent reject response to passthrough command: {:?}", command);
Ok(())
}
}
}
_ => {
fx_vlog!(tag: "avrcp", 2, "unexpected on command packet: {:?}", command.avc_header().op_code());
Ok(())
}
}
}
None => panic!("Unexpected state. remote peer should not be deallocated"),
}
}
}
|
use std::{
future::Future,
pin::Pin,
task::{self, Poll},
time::Duration,
};
use pin_project_lite::pin_project;
use tokio::sync::oneshot;
use super::{
channel::{AddressSender, Sender},
MailboxError, SendError,
};
use crate::{clock::Sleep, handler::Message};
pub type Request<A, M> = MsgRequest<AddressSender<A>, M>;
pub type RecipientRequest<M> = MsgRequest<Box<dyn Sender<M>>, M>;
pin_project! {
/// A `Future` which represents an asynchronous message sending process.
#[must_use = "You must wait on the request otherwise the Message will not be delivered"]
pub struct MsgRequest<S, M>
where
S: Sender<M>,
M: Message,
M: Send,
M::Result: Send
{
rx: Option<oneshot::Receiver<M::Result>>,
info: Option<(S, M)>,
#[pin]
timeout: Option<Sleep>,
}
}
impl<S, M> MsgRequest<S, M>
where
S: Sender<M>,
M: Message + Send,
M::Result: Send,
{
pub(crate) fn new(rx: Option<oneshot::Receiver<M::Result>>, info: Option<(S, M)>) -> Self {
Self {
rx,
info,
timeout: None,
}
}
#[cfg(test)]
pub(crate) fn rx_is_some(&self) -> bool {
self.rx.is_some()
}
/// Set message delivery timeout
pub fn timeout(mut self, dur: Duration) -> Self {
self.timeout = Some(actix_rt::time::sleep(dur));
self
}
}
impl<S, M> Future for MsgRequest<S, M>
where
S: Sender<M>,
M: Message + Send,
M::Result: Send,
{
type Output = Result<M::Result, MailboxError>;
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
let this = self.project();
if let Some((sender, msg)) = this.info.take() {
match sender.send(msg) {
Ok(rx) => *this.rx = Some(rx),
Err(SendError::Full(msg)) => {
*this.info = Some((sender, msg));
return Poll::Pending;
}
Err(SendError::Closed(_)) => return Poll::Ready(Err(MailboxError::Closed)),
}
}
match this.rx {
Some(rx) => match Pin::new(rx).poll(cx) {
Poll::Ready(res) => Poll::Ready(res.map_err(|_| MailboxError::Closed)),
Poll::Pending => match this.timeout.as_pin_mut() {
Some(timeout) => timeout.poll(cx).map(|_| Err(MailboxError::Timeout)),
None => Poll::Pending,
},
},
None => Poll::Ready(Err(MailboxError::Closed)),
}
}
}
|
#[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::IF1MCTL {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct CAN_IF1MCTL_DLCR {
bits: u8,
}
impl CAN_IF1MCTL_DLCR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _CAN_IF1MCTL_DLCW<'a> {
w: &'a mut W,
}
impl<'a> _CAN_IF1MCTL_DLCW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 0);
self.w.bits |= ((value as u32) & 15) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct CAN_IF1MCTL_EOBR {
bits: bool,
}
impl CAN_IF1MCTL_EOBR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _CAN_IF1MCTL_EOBW<'a> {
w: &'a mut W,
}
impl<'a> _CAN_IF1MCTL_EOBW<'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 &= !(1 << 7);
self.w.bits |= ((value as u32) & 1) << 7;
self.w
}
}
#[doc = r"Value of the field"]
pub struct CAN_IF1MCTL_TXRQSTR {
bits: bool,
}
impl CAN_IF1MCTL_TXRQSTR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _CAN_IF1MCTL_TXRQSTW<'a> {
w: &'a mut W,
}
impl<'a> _CAN_IF1MCTL_TXRQSTW<'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 &= !(1 << 8);
self.w.bits |= ((value as u32) & 1) << 8;
self.w
}
}
#[doc = r"Value of the field"]
pub struct CAN_IF1MCTL_RMTENR {
bits: bool,
}
impl CAN_IF1MCTL_RMTENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _CAN_IF1MCTL_RMTENW<'a> {
w: &'a mut W,
}
impl<'a> _CAN_IF1MCTL_RMTENW<'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 &= !(1 << 9);
self.w.bits |= ((value as u32) & 1) << 9;
self.w
}
}
#[doc = r"Value of the field"]
pub struct CAN_IF1MCTL_RXIER {
bits: bool,
}
impl CAN_IF1MCTL_RXIER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _CAN_IF1MCTL_RXIEW<'a> {
w: &'a mut W,
}
impl<'a> _CAN_IF1MCTL_RXIEW<'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 &= !(1 << 10);
self.w.bits |= ((value as u32) & 1) << 10;
self.w
}
}
#[doc = r"Value of the field"]
pub struct CAN_IF1MCTL_TXIER {
bits: bool,
}
impl CAN_IF1MCTL_TXIER {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _CAN_IF1MCTL_TXIEW<'a> {
w: &'a mut W,
}
impl<'a> _CAN_IF1MCTL_TXIEW<'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 &= !(1 << 11);
self.w.bits |= ((value as u32) & 1) << 11;
self.w
}
}
#[doc = r"Value of the field"]
pub struct CAN_IF1MCTL_UMASKR {
bits: bool,
}
impl CAN_IF1MCTL_UMASKR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _CAN_IF1MCTL_UMASKW<'a> {
w: &'a mut W,
}
impl<'a> _CAN_IF1MCTL_UMASKW<'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 &= !(1 << 12);
self.w.bits |= ((value as u32) & 1) << 12;
self.w
}
}
#[doc = r"Value of the field"]
pub struct CAN_IF1MCTL_INTPNDR {
bits: bool,
}
impl CAN_IF1MCTL_INTPNDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _CAN_IF1MCTL_INTPNDW<'a> {
w: &'a mut W,
}
impl<'a> _CAN_IF1MCTL_INTPNDW<'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 &= !(1 << 13);
self.w.bits |= ((value as u32) & 1) << 13;
self.w
}
}
#[doc = r"Value of the field"]
pub struct CAN_IF1MCTL_MSGLSTR {
bits: bool,
}
impl CAN_IF1MCTL_MSGLSTR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _CAN_IF1MCTL_MSGLSTW<'a> {
w: &'a mut W,
}
impl<'a> _CAN_IF1MCTL_MSGLSTW<'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 &= !(1 << 14);
self.w.bits |= ((value as u32) & 1) << 14;
self.w
}
}
#[doc = r"Value of the field"]
pub struct CAN_IF1MCTL_NEWDATR {
bits: bool,
}
impl CAN_IF1MCTL_NEWDATR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _CAN_IF1MCTL_NEWDATW<'a> {
w: &'a mut W,
}
impl<'a> _CAN_IF1MCTL_NEWDATW<'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 &= !(1 << 15);
self.w.bits |= ((value as u32) & 1) << 15;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:3 - Data Length Code"]
#[inline(always)]
pub fn can_if1mctl_dlc(&self) -> CAN_IF1MCTL_DLCR {
let bits = ((self.bits >> 0) & 15) as u8;
CAN_IF1MCTL_DLCR { bits }
}
#[doc = "Bit 7 - End of Buffer"]
#[inline(always)]
pub fn can_if1mctl_eob(&self) -> CAN_IF1MCTL_EOBR {
let bits = ((self.bits >> 7) & 1) != 0;
CAN_IF1MCTL_EOBR { bits }
}
#[doc = "Bit 8 - Transmit Request"]
#[inline(always)]
pub fn can_if1mctl_txrqst(&self) -> CAN_IF1MCTL_TXRQSTR {
let bits = ((self.bits >> 8) & 1) != 0;
CAN_IF1MCTL_TXRQSTR { bits }
}
#[doc = "Bit 9 - Remote Enable"]
#[inline(always)]
pub fn can_if1mctl_rmten(&self) -> CAN_IF1MCTL_RMTENR {
let bits = ((self.bits >> 9) & 1) != 0;
CAN_IF1MCTL_RMTENR { bits }
}
#[doc = "Bit 10 - Receive Interrupt Enable"]
#[inline(always)]
pub fn can_if1mctl_rxie(&self) -> CAN_IF1MCTL_RXIER {
let bits = ((self.bits >> 10) & 1) != 0;
CAN_IF1MCTL_RXIER { bits }
}
#[doc = "Bit 11 - Transmit Interrupt Enable"]
#[inline(always)]
pub fn can_if1mctl_txie(&self) -> CAN_IF1MCTL_TXIER {
let bits = ((self.bits >> 11) & 1) != 0;
CAN_IF1MCTL_TXIER { bits }
}
#[doc = "Bit 12 - Use Acceptance Mask"]
#[inline(always)]
pub fn can_if1mctl_umask(&self) -> CAN_IF1MCTL_UMASKR {
let bits = ((self.bits >> 12) & 1) != 0;
CAN_IF1MCTL_UMASKR { bits }
}
#[doc = "Bit 13 - Interrupt Pending"]
#[inline(always)]
pub fn can_if1mctl_intpnd(&self) -> CAN_IF1MCTL_INTPNDR {
let bits = ((self.bits >> 13) & 1) != 0;
CAN_IF1MCTL_INTPNDR { bits }
}
#[doc = "Bit 14 - Message Lost"]
#[inline(always)]
pub fn can_if1mctl_msglst(&self) -> CAN_IF1MCTL_MSGLSTR {
let bits = ((self.bits >> 14) & 1) != 0;
CAN_IF1MCTL_MSGLSTR { bits }
}
#[doc = "Bit 15 - New Data"]
#[inline(always)]
pub fn can_if1mctl_newdat(&self) -> CAN_IF1MCTL_NEWDATR {
let bits = ((self.bits >> 15) & 1) != 0;
CAN_IF1MCTL_NEWDATR { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:3 - Data Length Code"]
#[inline(always)]
pub fn can_if1mctl_dlc(&mut self) -> _CAN_IF1MCTL_DLCW {
_CAN_IF1MCTL_DLCW { w: self }
}
#[doc = "Bit 7 - End of Buffer"]
#[inline(always)]
pub fn can_if1mctl_eob(&mut self) -> _CAN_IF1MCTL_EOBW {
_CAN_IF1MCTL_EOBW { w: self }
}
#[doc = "Bit 8 - Transmit Request"]
#[inline(always)]
pub fn can_if1mctl_txrqst(&mut self) -> _CAN_IF1MCTL_TXRQSTW {
_CAN_IF1MCTL_TXRQSTW { w: self }
}
#[doc = "Bit 9 - Remote Enable"]
#[inline(always)]
pub fn can_if1mctl_rmten(&mut self) -> _CAN_IF1MCTL_RMTENW {
_CAN_IF1MCTL_RMTENW { w: self }
}
#[doc = "Bit 10 - Receive Interrupt Enable"]
#[inline(always)]
pub fn can_if1mctl_rxie(&mut self) -> _CAN_IF1MCTL_RXIEW {
_CAN_IF1MCTL_RXIEW { w: self }
}
#[doc = "Bit 11 - Transmit Interrupt Enable"]
#[inline(always)]
pub fn can_if1mctl_txie(&mut self) -> _CAN_IF1MCTL_TXIEW {
_CAN_IF1MCTL_TXIEW { w: self }
}
#[doc = "Bit 12 - Use Acceptance Mask"]
#[inline(always)]
pub fn can_if1mctl_umask(&mut self) -> _CAN_IF1MCTL_UMASKW {
_CAN_IF1MCTL_UMASKW { w: self }
}
#[doc = "Bit 13 - Interrupt Pending"]
#[inline(always)]
pub fn can_if1mctl_intpnd(&mut self) -> _CAN_IF1MCTL_INTPNDW {
_CAN_IF1MCTL_INTPNDW { w: self }
}
#[doc = "Bit 14 - Message Lost"]
#[inline(always)]
pub fn can_if1mctl_msglst(&mut self) -> _CAN_IF1MCTL_MSGLSTW {
_CAN_IF1MCTL_MSGLSTW { w: self }
}
#[doc = "Bit 15 - New Data"]
#[inline(always)]
pub fn can_if1mctl_newdat(&mut self) -> _CAN_IF1MCTL_NEWDATW {
_CAN_IF1MCTL_NEWDATW { w: self }
}
}
|
#![feature(box_patterns)]
#![feature(repeat_generic_slice)]
#![feature(core_intrinsics)]
#[macro_use]
pub mod macros;
#[macro_use]
pub mod exec;
pub mod class;
pub mod gc;
extern crate libc;
extern crate llvm_sys as llvm;
extern crate rand;
extern crate rustc_hash;
|
use proconio::input;
use proconio::marker::Chars;
fn palindrome(s: &[char]) -> bool {
for l in 0..s.len() / 2 {
let r = s.len() - l - 1;
if s[l] != s[r] {
return false;
}
}
true
}
fn main() {
input! {
n: usize,
mut s: Chars,
};
if palindrome(&s) {
println!("Yes");
return;
}
if n == 2 {
// AB, BA
println!("No");
return;
}
if s[0] == 'A' && s[n - 1] == 'B' {
println!("No");
} else {
println!("Yes");
}
}
|
extern crate sdl2;
use crate::cart::{Cart, CartConfig};
use crate::cart_header::{CartHardware, CartHeader};
use crate::cpu::Cpu;
use crate::frontend::{start_frontend, start_frontend_debug};
use crate::wla_symbols::WlaSymbols;
use failure::ResultExt;
use log::info;
use std::fs::File;
use std::io::{BufReader, Write};
use std::path::PathBuf;
use structopt::StructOpt;
mod audio;
mod cart;
mod cart_header;
mod cpu;
mod debug;
mod frontend;
mod gpu;
mod interrupts;
mod joypad;
mod timer;
mod wla_symbols;
#[derive(Debug, StructOpt)]
#[structopt(name = "Rugby", about = "Rust Game Boy? Yes!")]
enum Opts {
#[structopt(name = "run", about = "Runs the given Game Boy ROM file")]
Run(RunOpts),
#[structopt(name = "debug", about = "Runs the given Game Boy ROM file in debug mode")]
Debug(DebugOpts),
#[structopt(name = "info", about = "Prints information about the given Game Boy ROMs")]
Info(InfoOpts),
}
#[derive(Debug, StructOpt)]
struct RunOpts {
/// The game ROM file path
#[structopt(name = "ROM", parse(from_os_str))]
rom_path: PathBuf,
/// Load and save cartridge RAM to this file
#[structopt(short = "s", long = "save-file", name = "SAVE", parse(from_os_str))]
save_path: Option<PathBuf>,
/// Load symbol file for debugging (in the WLA DX assembler's format
#[structopt(short = "S", long = "symbol-file", name = "SYMBOLS", parse(from_os_str))]
symbols_path: Option<PathBuf>,
}
#[derive(Debug, StructOpt)]
struct DebugOpts {
/// The game ROM file path
#[structopt(name = "ROM", parse(from_os_str))]
rom_path: PathBuf,
/// Load symbol file for debugging (in the WLA DX assembler's format
#[structopt(short = "S", long = "symbol-file", name = "SYMBOLS", parse(from_os_str))]
symbols_path: Option<PathBuf>,
}
#[derive(Debug, StructOpt)]
struct InfoOpts {
/// The game ROM file paths
#[structopt(name = "ROM", parse(from_os_str), required = true)]
rom_paths: Vec<PathBuf>,
/// Show results in a table
#[structopt(short = "t", long = "table")]
table: bool,
}
fn main() -> Result<(), failure::Error> {
let env = env_logger::Env::new().filter("RUGBY_LOG").write_style("RUGBY_LOG_STYLE");
env_logger::Builder::from_env(env)
.format_timestamp(None)
.init();
match &Opts::from_args() {
Opts::Run(run_opts) => run(run_opts),
Opts::Debug(debug_opts) => debug(debug_opts),
Opts::Info(info_opts) => info(info_opts),
}
}
fn run(opts: &RunOpts) -> Result<(), failure::Error> {
let rom = std::fs::read(&opts.rom_path)
.context("Failed to read ROM file")?
.into_boxed_slice();
let cart_header = CartHeader::from_rom(&rom).context("Failed to parse cartridge header")?;
let cart_config = CartConfig::from_cart_header(&cart_header)?;
// TODO(solson): Include some kind of game-identifying information in the save file to
// prevent loading a save file with the wrong game.
let ram = opts.save_path
.as_ref()
.and_then(|path| std::fs::read(path).ok())
.map(|r| r.into_boxed_slice());
if ram.is_some() {
info!("Initialized cartridge RAM from file");
}
let cart = Cart::new(rom, ram, &cart_config).context("Failed to initialize cartridge")?;
let mut cpu = Cpu::new(cart);
if let Some(path) = &opts.symbols_path {
let file = File::open(path).context("Failed to open symbol file")?;
cpu.debug_symbols = Some(WlaSymbols::parse(BufReader::new(file))
.context("Failed to parse WLA DX symbol file")?);
}
start_frontend(&mut cpu, opts.save_path.clone());
Ok(())
}
fn debug(opts: &DebugOpts) -> Result<(), failure::Error> {
let rom = std::fs::read(&opts.rom_path)
.context("Failed to read ROM file")?
.into_boxed_slice();
let cart_header = CartHeader::from_rom(&rom).context("Failed to parse cartridge header")?;
let cart_config = CartConfig::from_cart_header(&cart_header)?;
let cart = Cart::new(rom, None, &cart_config).context("Failed to initialize cartridge")?;
let mut cpu = Cpu::new(cart);
if let Some(path) = &opts.symbols_path {
let file = File::open(path).context("Failed to open symbol file")?;
cpu.debug_symbols = Some(WlaSymbols::parse(BufReader::new(file))
.context("Failed to parse WLA DX symbol file")?);
}
start_frontend_debug(&mut cpu);
Ok(())
}
fn info(opts: &InfoOpts) -> Result<(), failure::Error> {
if opts.table {
info_table(opts)
} else {
info_records(opts)
}
}
/// Print the ROM info in a table with one ROM per row
fn info_table(opts: &InfoOpts) -> Result<(), failure::Error> {
let mut out = tabwriter::TabWriter::new(std::io::stdout());
writeln!(out, "File path\tTitle\tVersion\tType\tHardware\tROM size\tRAM size\tGBC\tSGB\tLicensee\tDestination\tManufacturer")?;
for path in &opts.rom_paths {
let rom = std::fs::read(path)
.with_context(|_| format!("Failed to read ROM file: {}", path.display()))?;
let cart = cart_header::CartHeader::from_rom(&rom)
.with_context(|_| format!("Failed to parse cartridge header: {}", path.display()))?;
write!(out, "{}\t", path.display())?;
match std::str::from_utf8(&cart.title) {
Ok(title) => write!(out, "{}\t", title)?,
Err(_) => write!(out, "{:x?}\t", cart.title)?,
}
write!(out, "{}\t", cart.rom_version)?;
write!(out, "{:?}\t", cart.cart_type)?;
write!(out, "{}\t", CartHardware::flags_to_string(cart.hardware))?;
write!(out, "{}\t", cart.rom_size)?;
write!(out, "{}\t", cart.ram_size)?;
write!(out, "{}\t", cart.gbc_flag)?;
write!(out, "{}\t", cart.sgb_flag)?;
write!(out, "{:?}\t", cart.licensee_code)?;
write!(out, "{:?}\t", cart.destination_code)?;
write!(out, "{:?}", cart.manufacturer_code)?;
writeln!(out, "")?;
}
out.flush()?;
Ok(())
}
/// Print the ROM info in the style of a list of separate key-value records.
fn info_records(opts: &InfoOpts) -> Result<(), failure::Error> {
for path in &opts.rom_paths {
let rom = std::fs::read(path)
.with_context(|_| format!("Failed to read ROM file: {}", path.display()))?;
let cart = cart_header::CartHeader::from_rom(&rom)
.with_context(|_| format!("Failed to parse cartridge header: {}", path.display()))?;
let mut out = tabwriter::TabWriter::new(std::io::stdout());
writeln!(out, "File path:\t{}", path.display())?;
match std::str::from_utf8(&cart.title) {
Ok(title) => writeln!(out, "Title:\t{}", title)?,
Err(_) => writeln!(out, "Title:\t{:x?}", cart.title)?,
}
writeln!(out, "Version:\t{}", cart.rom_version)?;
writeln!(out, "MBC type:\t{:?}", cart.cart_type)?;
writeln!(out, "Hardware:\t{}", CartHardware::flags_to_string(cart.hardware))?;
writeln!(out, "ROM size:\t{}", cart.rom_size)?;
writeln!(out, "RAM size:\t{}", cart.ram_size)?;
writeln!(out, "GBC support:\t{}", cart.gbc_flag)?;
writeln!(out, "SGB support:\t{}", cart.sgb_flag)?;
writeln!(out, "Manufacturer code:\t{:?}", cart.manufacturer_code)?;
writeln!(out, "Licensee code:\t{:?}", cart.licensee_code)?;
writeln!(out, "Destination code:\t{:?}", cart.destination_code)?;
writeln!(out, "")?;
out.flush()?;
}
Ok(())
}
|
use rocket_contrib::JSON;
use validation::user::UserSerializer;
use diesel::prelude::*;
use diesel;
use models::user::{UserModel, NewUser};
use schema::users;
use schema::users::dsl::*;
use helpers::db::DB;
#[post("/login", data = "<user_in>", format = "application/json")]
pub fn login(user_in: JSON<UserSerializer>, db: DB) -> String {
let results = users.filter(email.eq(user_in.email.clone()))
.first::<UserModel>(db.conn());
if results.is_err() {
return "404".to_string();
}
let user = results.unwrap();
if !user.verify_password(user_in.password.as_str()) {
return "no login".to_string();
}
user.generate_auth_token("loginsalt")
}
#[post("/register", data = "<user>", format = "application/json")]
pub fn register(user: JSON<UserSerializer>, db: DB) -> String {
let results = users.filter(email.eq(user.email.clone()))
.first::<UserModel>(db.conn());
if results.is_ok() {
return "conflict".to_string();
}
let new_password_hash = UserModel::make_password_hash(user.password.as_str());
let new_user = NewUser {
email: user.email.clone(),
password_hash: new_password_hash,
};
diesel::insert(&new_user)
.into(users::table)
.execute(db.conn())
.expect("Error saving new post");
"lol".to_string()
}
|
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::{event_loop::EventLoop, window::WindowBuilder};
fn main() {
SimpleLogger::new().init().unwrap();
let event_loop = EventLoop::new();
let window = WindowBuilder::new().build(&event_loop).unwrap();
dbg!(window.available_monitors().collect::<Vec<_>>());
dbg!(window.primary_monitor());
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
#[repr(transparent)]
pub struct PhoneNumberFormat(pub i32);
impl PhoneNumberFormat {
pub const E164: Self = Self(0i32);
pub const International: Self = Self(1i32);
pub const National: Self = Self(2i32);
pub const Rfc3966: Self = Self(3i32);
}
impl ::core::marker::Copy for PhoneNumberFormat {}
impl ::core::clone::Clone for PhoneNumberFormat {
fn clone(&self) -> Self {
*self
}
}
pub type PhoneNumberFormatter = *mut ::core::ffi::c_void;
pub type PhoneNumberInfo = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneNumberMatchResult(pub i32);
impl PhoneNumberMatchResult {
pub const NoMatch: Self = Self(0i32);
pub const ShortNationalSignificantNumberMatch: Self = Self(1i32);
pub const NationalSignificantNumberMatch: Self = Self(2i32);
pub const ExactMatch: Self = Self(3i32);
}
impl ::core::marker::Copy for PhoneNumberMatchResult {}
impl ::core::clone::Clone for PhoneNumberMatchResult {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhoneNumberParseResult(pub i32);
impl PhoneNumberParseResult {
pub const Valid: Self = Self(0i32);
pub const NotANumber: Self = Self(1i32);
pub const InvalidCountryCode: Self = Self(2i32);
pub const TooShort: Self = Self(3i32);
pub const TooLong: Self = Self(4i32);
}
impl ::core::marker::Copy for PhoneNumberParseResult {}
impl ::core::clone::Clone for PhoneNumberParseResult {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PredictedPhoneNumberKind(pub i32);
impl PredictedPhoneNumberKind {
pub const FixedLine: Self = Self(0i32);
pub const Mobile: Self = Self(1i32);
pub const FixedLineOrMobile: Self = Self(2i32);
pub const TollFree: Self = Self(3i32);
pub const PremiumRate: Self = Self(4i32);
pub const SharedCost: Self = Self(5i32);
pub const Voip: Self = Self(6i32);
pub const PersonalNumber: Self = Self(7i32);
pub const Pager: Self = Self(8i32);
pub const UniversalAccountNumber: Self = Self(9i32);
pub const Voicemail: Self = Self(10i32);
pub const Unknown: Self = Self(11i32);
}
impl ::core::marker::Copy for PredictedPhoneNumberKind {}
impl ::core::clone::Clone for PredictedPhoneNumberKind {
fn clone(&self) -> Self {
*self
}
}
|
use super::*;
#[test]
fn with_greater_small_integer_right_returns_true() {
is_greater_than(|_, process| process.integer(-1), true)
}
#[test]
fn with_greater_small_integer_right_returns_false() {
is_greater_than(|_, process| process.integer(1), false)
}
#[test]
fn with_greater_big_integer_right_returns_true() {
is_greater_than(
|_, process| process.integer(SmallInteger::MIN_VALUE - 1),
true,
)
}
#[test]
fn with_greater_big_integer_right_returns_false() {
is_greater_than(
|_, process| process.integer(SmallInteger::MAX_VALUE + 1),
false,
)
}
#[test]
fn with_greater_float_right_returns_true() {
is_greater_than(|_, process| process.float(-1.0), true)
}
#[test]
fn with_greater_float_right_returns_false() {
is_greater_than(|_, process| process.float(1.0), false)
}
#[test]
fn without_number_returns_false() {
run!(
|arc_process| {
(
strategy::term::float(arc_process.clone()),
strategy::term::is_not_number(arc_process.clone()),
)
},
|(left, right)| {
prop_assert_eq!(result(left, right), false.into());
Ok(())
},
);
}
fn is_greater_than<R>(right: R, expected: bool)
where
R: FnOnce(Term, &Process) -> Term,
{
super::is_greater_than(|process| process.float(1.0), right, expected);
}
|
//! To run this code, clone the rusty_engine repository and run the command:
//!
//! cargo run --release --example sound
//! This is an example of playing sound by path. For playing music or sound effect presets, please
//! see the `music` or `sfx` examples.
use rusty_engine::prelude::*;
fn main() {
let mut game = Game::new();
let msg = game.add_text(
"msg",
"You can add your own sound files to the assets/audio directory\n(or its subdirectories) and play them by relative path. This\nworks for both sound effects and music. For example:",
);
msg.translation.y = 100.0;
let msg2 = game.add_text(
"msg2",
"engine.audio_manager.play_sfx(\"sfx/congratulations.ogg\", 1.0);",
);
msg2.translation.y = -100.0;
msg2.font = "font/FiraMono-Medium.ttf".to_string();
game.audio_manager.play_sfx("sfx/congratulations.ogg", 1.0);
game.run(());
}
|
use smart_contract::log;
use smart_contract::payload::Parameters;
use smart_contract_macros::smart_contract;
use serde_json::json;
// use uuid::Uuid;
use indradb::{Datastore, MemoryDatastore, Transaction, VertexQueryExt}; //::{MemoryDatastore};
// #[derive(Serialize, Deserialize)]
struct Contract {
store: MemoryDatastore,
}
#[smart_contract]
impl Contract {
pub fn init(params: &mut Parameters) -> Self {
Self {
store: MemoryDatastore::default(),
}
}
pub fn get_schemas(&mut self, _params: &mut Parameters) -> Result<(), String> {
Ok(())
}
pub fn insert_vertex(&mut self, params: &mut Parameters) -> Result<(), String> {
let trans = self.store.transaction().unwrap();
let vertex_type: String = params.read();
let vertex_t = indradb::Type::new(vertex_type.clone()).unwrap();
let outbound_v = indradb::Vertex::with_id(
uuid::Uuid::new_v3(&uuid::Uuid::NAMESPACE_DNS, ¶ms.transaction_id),
vertex_t.clone(),
);
trans.create_vertex(&outbound_v).unwrap();
Ok(())
}
pub fn get_vertices_by_type(&mut self, params: &mut Parameters) -> Result<(), String> {
let trans = self.store.transaction().unwrap();
let vertex_type: String = params.read();
let type_filter = indradb::Type::new(vertex_type.clone()).unwrap();
let range = trans
.get_vertices(indradb::RangeVertexQuery::new(std::u32::MAX).t(type_filter))
.unwrap();
for vertex in range.into_iter() {
log(&vertex.id.to_string())
}
Ok(())
}
pub fn set_value(&mut self, params: &mut Parameters) -> Result<(), String> {
let trans = self.store.transaction().unwrap();
let id_str: String = params.read();
let uuid = uuid::Uuid::parse_str(&id_str).unwrap();
let props_str: String = params.read();
let props: serde_json::Value = serde_json::from_str(&props_str).unwrap();
// let id = uuid::Uuid::new_v3(&uuid::Uuid::NAMESPACE_DNS, ¶ms.transaction_id),
// let range = trans.get_vertices(indradb::SpecificVertexQuery::single(uuid)).unwrap();
// let vertex = range.get(0).unwrap();
trans.set_vertex_properties(indradb::SpecificVertexQuery::single(uuid).property("props"), &props);
Ok(())
}
pub fn get_value(&mut self, params: &mut Parameters) -> Result<(), String> {
let trans = self.store.transaction().unwrap();
let id_str: String = params.read();
let uuid = uuid::Uuid::parse_str(&id_str).unwrap();
// let id = uuid::Uuid::new_v3(&uuid::Uuid::NAMESPACE_DNS, ¶ms.transaction_id),
// let range = trans.get_vertices(indradb::SpecificVertexQuery::single(uuid)).unwrap();
// let vertex = range.get(0).unwrap();
let res = trans.get_vertex_properties(indradb::SpecificVertexQuery::single(uuid).property("props")).unwrap();
log(&serde_json::to_string(&res.get(0).unwrap().value).unwrap());
Ok(())
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
pub const ECMA: u64 = 0xc96c5795d7870f42;
pub const ISO: u64 = 0xd800000000000000;
lazy_static! {
pub static ref ECMA_TABLE: [u64; 256] = make_table(ECMA);
pub static ref ISO_TABLE: [u64; 256] = make_table(ISO);
}
pub struct Digest {
table: [u64; 256],
initial: u64,
value: u64
}
pub trait Hasher64 {
fn reset(&mut self);
fn write(&mut self, bytes: &[u8]);
fn sum64(&self) -> u64;
}
pub fn make_table(poly: u64) -> [u64; 256] {
let mut table = [0u64; 256];
for i in 0..256 {
let mut value = i as u64;
for _ in 0..8 {
value = if (value & 1) == 1 {
(value >> 1) ^ poly
} else {
value >> 1
}
}
table[i] = value;
}
table
}
pub fn update(mut value: u64, table: &[u64; 256], bytes: &[u8]) -> u64 {
value = !value;
for &i in bytes.iter() {
value = table[((value as u8) ^ i) as usize] ^ (value >> 8)
}
!value
}
pub fn checksum_ecma(bytes: &[u8]) -> u64 {
return update(0, &ECMA_TABLE, bytes);
}
pub fn checksum_iso(bytes: &[u8]) -> u64 {
return update(0, &ISO_TABLE, bytes);
}
impl Digest {
pub fn new(poly: u64) -> Digest {
Digest {
table: make_table(poly),
initial: 0,
value: 0
}
}
pub fn new_with_initial(poly: u64, initial: u64) -> Digest {
Digest {
table: make_table(poly),
initial: initial,
value: initial
}
}
}
impl Hasher64 for Digest {
fn reset(&mut self) {
self.value = self.initial;
}
fn write(&mut self, bytes: &[u8]) {
self.value = update(self.value, &self.table, bytes);
}
fn sum64(&self) -> u64 {
self.value
}
}
|
use std::io::Read;
fn read<T: std::str::FromStr>() -> T {
let token: String = std::io::stdin()
.bytes()
.map(|c| c.ok().unwrap() as char)
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect();
token.parse().ok().unwrap()
}
fn main() {
let n = 5 * 1000000 + 1;
let mut is_prime = vec![true; n];
is_prime[1] = false;
for i in 2..n {
if i * i >= n {
break;
}
if is_prime[i] {
let mut j = i * 2;
while j < n {
is_prime[j] = false;
j += i;
}
}
}
let t: usize = read();
for _ in 0..t {
let a: i64 = read();
let p: i64 = read();
let ans = if is_prime[p as usize] {
if a % p == 0 {
0
} else {
1
}
} else {
-1
};
println!("{}", ans);
}
}
|
use num_bigint::BigInt;
use crate::function::PyFuncArgs;
use crate::pyobject::{PyContext, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol};
use crate::vm::VirtualMachine;
use super::objint;
use crate::obj::objtype::PyClassRef;
#[derive(Debug)]
pub struct PySlice {
// TODO: should be private
pub start: Option<BigInt>,
pub stop: Option<BigInt>,
pub step: Option<BigInt>,
}
impl PyValue for PySlice {
fn class(vm: &VirtualMachine) -> PyClassRef {
vm.ctx.slice_type()
}
}
pub type PySliceRef = PyRef<PySlice>;
fn slice_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
no_kwargs!(vm, args);
let (cls, start, stop, step): (
&PyObjectRef,
Option<&PyObjectRef>,
Option<&PyObjectRef>,
Option<&PyObjectRef>,
) = match args.args.len() {
0 | 1 => Err(vm.new_type_error("slice() must have at least one arguments.".to_owned())),
2 => {
arg_check!(
vm,
args,
required = [
(cls, Some(vm.ctx.type_type())),
(stop, Some(vm.ctx.int_type()))
]
);
Ok((cls, None, Some(stop), None))
}
_ => {
arg_check!(
vm,
args,
required = [
(cls, Some(vm.ctx.type_type())),
(start, Some(vm.ctx.int_type())),
(stop, Some(vm.ctx.int_type()))
],
optional = [(step, Some(vm.ctx.int_type()))]
);
Ok((cls, Some(start), Some(stop), step))
}
}?;
PySlice {
start: start.map(|x| objint::get_value(x).clone()),
stop: stop.map(|x| objint::get_value(x).clone()),
step: step.map(|x| objint::get_value(x).clone()),
}
.into_ref_with_type(vm, cls.clone().downcast().unwrap())
.map(PyRef::into_object)
}
fn get_property_value(vm: &VirtualMachine, value: &Option<BigInt>) -> PyObjectRef {
if let Some(value) = value {
vm.ctx.new_int(value.clone())
} else {
vm.get_none()
}
}
impl PySliceRef {
fn start(self, vm: &VirtualMachine) -> PyObjectRef {
get_property_value(vm, &self.start)
}
fn stop(self, vm: &VirtualMachine) -> PyObjectRef {
get_property_value(vm, &self.stop)
}
fn step(self, vm: &VirtualMachine) -> PyObjectRef {
get_property_value(vm, &self.step)
}
}
pub fn init(context: &PyContext) {
let slice_type = &context.slice_type;
extend_class!(context, slice_type, {
"__new__" => context.new_rustfunc(slice_new),
"start" => context.new_property(PySliceRef::start),
"stop" => context.new_property(PySliceRef::stop),
"step" => context.new_property(PySliceRef::step)
});
}
|
pub mod qemu_virt;
|
pub mod client;
pub mod error;
pub mod server;
pub mod util;
#[cfg(test)]
mod tests {
use crate::client;
use crate::error;
use crate::server;
use crate::util;
#[test]
fn it_should_return_string_client() {
assert_eq!("subclient", client::client());
}
#[test]
fn it_should_return_string_server() {
assert_eq!("subserver", server::server());
}
#[test]
fn it_should_return_string_from_util_module() {
assert_eq!("configuration from util", util::configure());
}
#[test]
fn it_should_return_string_from_error_module() {
assert_eq!("error", error::error());
}
}
|
#[doc = "Reader of register OR"]
pub type R = crate::R<u32, super::OR>;
#[doc = "Writer for register OR"]
pub type W = crate::W<u32, super::OR>;
#[doc = "Register OR `reset()`'s with value 0"]
impl crate::ResetValue for super::OR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `OR_0`"]
pub type OR_0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OR_0`"]
pub struct OR_0_W<'a> {
w: &'a mut W,
}
impl<'a> OR_0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `OR_1`"]
pub type OR_1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OR_1`"]
pub struct OR_1_W<'a> {
w: &'a mut W,
}
impl<'a> OR_1_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
}
}
impl R {
#[doc = "Bit 0 - Option register bit 0"]
#[inline(always)]
pub fn or_0(&self) -> OR_0_R {
OR_0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Option register bit 1"]
#[inline(always)]
pub fn or_1(&self) -> OR_1_R {
OR_1_R::new(((self.bits >> 1) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Option register bit 0"]
#[inline(always)]
pub fn or_0(&mut self) -> OR_0_W {
OR_0_W { w: self }
}
#[doc = "Bit 1 - Option register bit 1"]
#[inline(always)]
pub fn or_1(&mut self) -> OR_1_W {
OR_1_W { w: self }
}
}
|
use std::collections::{HashMap, HashSet};
use std::ops::RangeInclusive;
#[derive(Debug, Clone)]
struct Rule(RangeInclusive<i64>, RangeInclusive<i64>);
fn main() {
let mut lines = aoc::file_lines_iter("./day16.txt");
let mut rules : HashMap<String, Rule> = HashMap::new();
let mut line = lines.next().unwrap();
while !line.is_empty() {
let v : Vec<_> = line.split(": ").collect();
let ranges : Vec<_> = v[1].split(" or ").collect();
let range1 : Vec<_> = ranges[0].split("-").map(|v| v.parse::<i64>().unwrap()).collect();
let range2 : Vec<_> = ranges[1].split("-").map(|v| v.parse::<i64>().unwrap()).collect();
rules.insert(v[0].to_string(), Rule(range1[0]..=range1[1], range2[0]..=range2[1]));
line = lines.next().unwrap();
}
line = lines.next().unwrap();
assert!(line == "your ticket:");
line = lines.next().unwrap();
let my_ticket : Vec<i64> = aoc::csv_iter::<i64>(&line).collect();
line = lines.nth(1).unwrap();
assert!(line == "nearby tickets:");
let mut invalid_sum = 0;
let mut valid_tickets : Vec<Vec<i64>> = Vec::new();
for line in lines {
let ticket : Vec<i64> = aoc::csv_iter::<i64>(&line).collect();
let mut valid_ticket = true;
for value in &ticket {
let valid = rules.values().any(|Rule(r1, r2)| {
r1.contains(&value) || r2.contains(&value)
});
if !valid {
invalid_sum += value;
valid_ticket = false;
}
}
if valid_ticket {
valid_tickets.push(ticket);
}
}
println!("Part 1: {}", invalid_sum);
valid_tickets.push(my_ticket.clone());
let ticket_fields_count = valid_tickets[0].len();
let mut rule_to_field_set : HashMap<String, HashSet<usize>> = HashMap::new();
for (name, Rule(r1, r2)) in &rules {
for i in 0..ticket_fields_count {
if valid_tickets.iter().all(|t| r1.contains(&t[i]) || r2.contains(&t[i])) {
rule_to_field_set.entry(name.clone()).or_insert(HashSet::new()).insert(i);
}
}
}
let mut rule_to_field : HashMap<String, usize> = HashMap::new();
loop {
// drain_filter would be nice, but it's in nightly right now
// I think this is the first time I truly "fought" the borrow checker
let mut rule : String = String::new();
let mut pos : usize = 0;
for (r, set) in &mut rule_to_field_set {
if set.len() == 1 {
rule = r.to_string();
pos = set.drain().nth(0).unwrap();
rule_to_field.insert(r.to_string(), pos);
break;
}
}
rule_to_field_set.remove(&rule);
if rule_to_field_set.is_empty() {
break;
}
for (_r, set) in &mut rule_to_field_set {
set.remove(&pos);
}
}
let part2 : i64 = rules.iter()
.filter(|(k, _v)| k.starts_with("departure"))
.map(|(k, _v)| my_ticket[*rule_to_field.get(k).unwrap()])
.product();
println!("Part 2: {}", part2);
}
|
use failure::Error;
#[derive(Debug, Fail)]
pub enum AliEcsCtlError {
#[fail(display = "no monitor data for instance: {}", _0)]
NoMonitorData(String),
}
pub type Result<T> = ::std::result::Result<T, Error>;
|
// global variable
static START: i32 = 10;
// constant
const DECREMENT: i32 = 1;
fn main() {
// variables are mutable, mut keyword is optional
let mut c: i32 = START;
let d: i32 = 2; // unused variable
loop {
printf("%d\n", c);
c = c - DECREMENT;
if c == 0 {
return;
}
}
// unreachable
}
|
use enumflags2::BitFlags;
use failure_derive::Fail;
#[derive(Clone, Debug, PartialEq)]
pub struct CartHeader {
/// The title of the game. At most 16 bytes.
pub title: Vec<u8>,
/// Specifies what kind of physical cartridge this ROM comes with, e.g. a cartridge with a
/// memory bank controller.
pub cart_type: CartType,
/// Specifies what extra hardware is present in the cartridge.
pub hardware: BitFlags<CartHardware>,
/// The size in bytes of the ROM in the cartridge.
pub rom_size: MemSize,
/// The size in bytes of the RAM in the cartridge.
pub ram_size: MemSize,
/// The level of Game Boy Color support the game has or requires.
pub gbc_flag: GbcFlag,
/// The level of Super Game Boy support the game has.
pub sgb_flag: SgbFlag,
/// Only present in newer cartridges.
pub manufacturer_code: Option<String>,
/// Indicates the company or publisher of the game.
pub licensee_code: LicenseeCode,
/// Indicates whether the cartridge is supposed to be sold in Japan or outside Japan.
pub destination_code: DestinationCode,
/// Some games have more than one version, and this byte indicates that. Usually zero.
pub rom_version: u8,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CartType {
NoMbc,
Mbc1,
Mbc2,
Mbc3,
Mbc5,
Mbc6,
Mbc7,
Mmm01,
HuC1,
HuC3,
PocketCamera,
BandaiTama5,
Unknown(u8),
}
#[derive(BitFlags, Copy, Clone, Debug)]
#[repr(u8)]
pub enum CartHardware {
Ram = 1 << 0,
Timer = 1 << 1,
Battery = 1 << 2,
Rumble = 1 << 3,
Accelerometer = 1 << 4,
}
impl CartHardware {
pub fn flags_to_string(flags: BitFlags<CartHardware>) -> String {
let hardware: Vec<String> = flags.iter().map(|h| format!("{:?}", h)).collect();
if hardware.is_empty() { String::from("none") } else { hardware.join("+") }
}
}
/// Represents RAM or ROM size, which are parsed from a single byte in the header according to an
/// arbitrary mapping. We use the `Unknown` variant for values not covered by the mapping.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MemSize {
/// A size in bytes.
Bytes(usize),
/// An unrecognized RAM or ROM size byte from a cartridge header.
Unknown(u8),
}
impl std::fmt::Display for MemSize {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
MemSize::Bytes(b) =>
if b % 1024 == 0 { write!(f, "{} KiB", b / 1024) } else { write!(f, "{} B", b) },
MemSize::Unknown(n) =>
write!(f, "unknown (0x{:02X})", n),
}
}
}
/// Represents the level of Game Boy Color support the game supports or requires.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GbcFlag {
/// A GB game with no GBC support.
Unsupported,
/// The game has GBC-specific features, but they are optional so it can run in GB mode.
Supported,
/// The game requires GBC hardware and does not run in GB mode.
Required,
}
impl std::fmt::Display for GbcFlag {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", match self {
GbcFlag::Unsupported => "no",
GbcFlag::Supported => "yes",
GbcFlag::Required => "required",
})
}
}
/// Represents the level of Super Game Boy support the game supports.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SgbFlag {
/// A GB or GBC game with no SGB support.
Unsupported,
/// The game supports SGB features.
Supported,
}
impl std::fmt::Display for SgbFlag {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", match self {
SgbFlag::Unsupported => "no",
SgbFlag::Supported => "yes",
})
}
}
/// Indicates the company or publisher of the game.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LicenseeCode {
/// A single byte licensee code, used in older cartridges.
///
/// This will never be 0x33 because that value signals that the newer 2-byte code is used
/// instead.
Old(u8),
/// A two character ASCII licensee code, used in newer cartridges.
New([u8; 2]),
}
/// Indicates whether the cartridge is supposed to be sold in Japan or outside Japan.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DestinationCode {
Japan,
International,
Invalid(u8),
}
#[derive(Clone, Debug, Fail, PartialEq)]
pub enum HeaderParseError {
#[fail(display = "manufacturer code was not valid UTF-8: {:?}", _0)]
InvalidManufacturerCodeUtf8(Vec<u8>),
#[fail(display = "cartridge ROM has length {} which is too short to contain a header", _0)]
RomTooShort(usize),
}
impl CartHeader {
/// Parse the cartridge header from the given ROM. The header is in the range 0x100..0x150, so
/// the input slice must be at least large enough to contain that.
pub fn from_rom(rom: &[u8]) -> Result<Self, HeaderParseError> {
let bytes = rom.get(0x100..0x150).ok_or(HeaderParseError::RomTooShort(rom.len()))?;
// The last byte of the title is used to determine if this is a Game Boy Color game. This
// GBC flag uses byts which aren't valid ASCII, so we know this isn't actually part of the
// title if the flag is set.
let gbc_flag = match bytes[0x43] {
0x80 => GbcFlag::Supported,
0xC0 => GbcFlag::Required,
_ => GbcFlag::Unsupported,
};
let (mut title_slice, manufacturer_code) = if gbc_flag == GbcFlag::Unsupported {
// For GB-only games, all 16 bytes in 0x34..0x44 may be used for the game title.
(&bytes[0x34..0x44], None)
} else {
// For GBC games, the first 11 bytes are used for the game title and the next 4 bytes
// are used for the manufacturer code.
let manufacturer_code = String::from_utf8(bytes[0x3F..0x43].to_vec())
.map_err(|e| HeaderParseError::InvalidManufacturerCodeUtf8(e.into_bytes()))?;
(&bytes[0x34..0x3F], Some(manufacturer_code))
};
// Ignore trailing null bytes.
if let Some(end) = title_slice.iter().position(|&x| x == 0) {
title_slice = &title_slice[..end];
};
let title = title_slice.to_vec();
let sgb_flag = match bytes[0x46] {
0x03 => SgbFlag::Supported,
_ => SgbFlag::Unsupported,
};
let licensee_code = if sgb_flag == SgbFlag::Unsupported {
LicenseeCode::Old(bytes[0x4B])
} else {
LicenseeCode::New([bytes[0x44], bytes[0x45]])
};
let cart_type = match bytes[0x47] {
0x00 | 0x08..=0x09 => CartType::NoMbc,
0x01..=0x03 => CartType::Mbc1,
0x05..=0x06 => CartType::Mbc2,
0x0B..=0x0D => CartType::Mmm01,
0x0F..=0x13 => CartType::Mbc3,
0x19..=0x1E => CartType::Mbc5,
0x20 => CartType::Mbc6,
0x22 => CartType::Mbc7,
0xFC => CartType::PocketCamera,
0xFD => CartType::BandaiTama5,
0xFE => CartType::HuC3,
0xFF => CartType::HuC1,
n => CartType::Unknown(n),
};
use self::CartHardware::*;
let mut hardware = BitFlags::empty();
match bytes[0x47] {
0x02 | 0x08 | 0x0C | 0x12 | 0x1A => hardware |= Ram,
0x03 | 0x06 | 0x09 | 0x0D | 0x13 | 0x1B | 0x20 | 0xFF => hardware |= Ram | Battery,
0x0F => hardware |= Timer | Battery,
0x10 => hardware |= Ram | Timer | Battery,
0x1C => hardware |= Rumble,
0x1D => hardware |= Ram | Rumble,
0x1E => hardware |= Ram | Battery | Rumble,
0x22 => hardware |= Ram | Battery | Accelerometer,
_ => {}
};
let rom_size = match bytes[0x48] {
n @ 0x00..=0x08 => MemSize::Bytes((32 * 1024) << n),
n => MemSize::Unknown(n),
};
let ram_size = match bytes[0x49] {
0x00 => MemSize::Bytes(0),
0x01 => MemSize::Bytes(2 * 1024),
0x02 => MemSize::Bytes(8 * 1024),
0x03 => MemSize::Bytes(32 * 1024),
0x04 => MemSize::Bytes(128 * 1024),
0x05 => MemSize::Bytes(64 * 1024),
n => MemSize::Unknown(n),
};
let destination_code = match bytes[0x4A] {
0x00 => DestinationCode::Japan,
0x01 => DestinationCode::International,
n => DestinationCode::Invalid(n),
};
let rom_version = bytes[0x4C];
Ok(CartHeader {
title,
cart_type,
hardware,
rom_size,
ram_size,
gbc_flag,
sgb_flag,
manufacturer_code,
licensee_code,
destination_code,
rom_version,
})
}
}
|
// 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 core::sync::atomic;
use alloc::slice;
use super::linux_def::*;
use super::pagetable::*;
// the lockfree bytestream for single writer and single read
pub struct LFByteStream {
pub buf: &'static mut [u8],
pub head: atomic::AtomicUsize,
pub tail: atomic::AtomicUsize,
pub capacity: usize,
pub ringMask: usize,
pub allocator: AlignedAllocator,
}
impl Drop for LFByteStream {
fn drop(&mut self) {
let (addr, size) = self.GetRawBuf();
let size = size as u64;
assert!(size & MemoryDef::PAGE_MASK == 0);
self.allocator.Free(addr).expect("LFByteStream::drop fail");
}
}
impl LFByteStream {
// allocate 1<<ord bytes buffer
pub fn Init(ord: usize) -> Self {
assert!(ord > 12, "LFByteStream ord must be large than 12, i.e. one 4KB Page");
let size = 1 << ord;
let allocator = AlignedAllocator::New(size as usize, MemoryDef::PAGE_SIZE as usize);
let addr = allocator.Allocate().expect("ByteStream can't allocate memory");
let ptr = addr as *mut u8;
let buf = unsafe { slice::from_raw_parts_mut(ptr, size as usize) };
return Self {
buf: buf,
head: atomic::AtomicUsize::new(0),
tail: atomic::AtomicUsize::new(0),
capacity: size,
ringMask: size - 1,
allocator: allocator
}
}
pub fn GetRawBuf(&self) -> (u64, usize) {
return (&self.buf[0] as *const _ as u64, self.buf.len())
}
pub fn AvailableSpace(&self) -> usize {
return self.buf.len() - self.AvailableDataSize();
}
pub fn AvailableDataSize(&self) -> usize {
let head = self.head.load(atomic::Ordering::Acquire);
let tail = self.tail.load(atomic::Ordering::Acquire);
return tail.wrapping_sub(head);
}
pub fn IsFull(&self) -> bool {
return self.AvailableDataSize() == self.capacity;
}
pub fn Consume(&self, size: usize) {
self.head.fetch_add(size, atomic::Ordering::SeqCst);
}
//return (addr, len, whethere there is more space)
pub fn ConsumeAndGetReadBuf(&self, size: usize) -> Option<(u64, usize, bool)> {
let head = self.head.fetch_add(size, atomic::Ordering::SeqCst) + size;
let tail = self.tail.load(atomic::Ordering::Acquire);
let available = tail.wrapping_sub(head);
if available == 0 {
return None
}
let readpos = head & self.ringMask;
let toEnd = self.capacity - readpos;
if toEnd < available {
return Some((&self.buf[0] as *const _ as u64 + readpos as u64, toEnd, true))
} else {
return Some((&self.buf[0] as *const _ as u64 + readpos as u64, available, false))
}
}
pub fn Produce(&self, size: usize) {
self.tail.fetch_add(size, atomic::Ordering::SeqCst);
}
// product size bytes, and return the new writebuf(addr, size, whether there is left buf)
pub fn ProduceAndGetWriteBuf(&self, size: usize) -> Option<(u64, usize, bool)> {
let head = self.head.load(atomic::Ordering::Acquire);
let tail = self.tail.fetch_add(size, atomic::Ordering::SeqCst) + size;
let available = tail.wrapping_sub(head);
if available == self.capacity {
return None
}
let writePos = tail & self.ringMask;
let writeSize = self.capacity - available;
let toEnd = self.capacity - writePos;
if toEnd < writeSize {
return Some((&self.buf[0] as *const _ as u64 + writePos as u64, toEnd, true))
} else {
return Some((&self.buf[0] as *const _ as u64 + writePos as u64, writeSize, false))
}
}
// return (whether is full, read size)
pub fn Read(&mut self, buf: &mut [u8]) -> (bool, usize) {
let head = self.head.load(atomic::Ordering::Acquire);
let tail = self.tail.load(atomic::Ordering::Acquire);
let available = tail.wrapping_sub(head);
let full = available == self.capacity;
let mut readSize = available;
let readpos = head & self.ringMask;
if readSize > buf.len() {
readSize = buf.len();
}
let (firstLen, hasSecond) = {
let toEnd = self.capacity - readpos;
if toEnd < readSize {
(toEnd, true)
} else {
(readSize, false)
}
};
buf[0..firstLen].clone_from_slice(&self.buf[readpos..readpos + firstLen]);
if hasSecond {
let secondLen = readSize - firstLen;
buf[firstLen..firstLen + secondLen].clone_from_slice(&self.buf[0..secondLen])
}
self.head.store(readpos + readSize, atomic::Ordering::Release);
return (full, readSize)
}
pub fn Write(&mut self, buf: &[u8]) -> (bool, usize) {
let head = self.head.load(atomic::Ordering::Acquire);
let tail = self.tail.load(atomic::Ordering::Acquire);
let available = tail.wrapping_sub(head);
let empty = available == 0;
let writePos = tail & self.ringMask;
let mut writeSize = self.capacity - available;
if writeSize > buf.len() {
writeSize = buf.len();
}
let (firstLen, hasSecond) = {
let toEnd = self.capacity - writePos;
if toEnd < writeSize {
(toEnd, true)
} else {
(writeSize, false)
}
};
self.buf[writePos..writePos + firstLen].clone_from_slice(&buf[0..firstLen]);
if hasSecond {
let secondLen = writeSize - firstLen;
self.buf[0..secondLen].clone_from_slice(&buf[firstLen..firstLen + secondLen]);
}
self.tail.store(tail + writeSize, atomic::Ordering::Release);
return (empty, writeSize)
}
} |
mod stack_with_min;
pub use self::stack_with_min::*;
|
mod error;
mod robot_client;
mod robot_command;
mod robot_config;
pub use error::*;
pub use robot_client::*;
pub use robot_command::*;
pub use robot_config::*;
|
mod models;
use models::*;
fn main() {
let c = Command::Create("s1".to_string());
let s = Stock::None.action(&c);
println!("{:?}", s);
let c2 = Command::Update(10);
let s2 = s.unwrap_or(Stock::None).action(&c2);
println!("{:?}", s2);
let s2_a = s2.clone().unwrap_or(Stock::None).action(&c2);
println!("{:?}", s2_a);
let c3 = Command::Update(0);
let s3 = s2.unwrap_or(Stock::None).action(&c3);
println!("{:?}", s3);
}
|
pub struct AdventYear {
year: u16,
advents: Vec<Box<dyn Advent>>,
}
impl AdventYear {
pub fn new(year: u16, advents: Vec<Box<dyn Advent>>) -> Self {
Self { year, advents }
}
pub fn get_year(&self) -> u16 {
self.year
}
pub fn into_advents(self) -> Vec<Box<dyn Advent>> {
self.advents
}
pub fn iter(&self) -> impl Iterator<Item = &Box<dyn Advent>> {
self.advents.iter()
}
}
pub trait Advent {
fn get_index(&self) -> u8;
fn skip(&self) -> bool {
false
}
fn get_input_names(&self) -> Vec<String> {
vec!["input.txt".to_owned()]
}
/// Process the given data. The data is the content of the files provided by
/// `Advent::get_input_names`
fn process_input(&self, data: Vec<String>);
}
pub struct SkippedAdvent(u8);
impl SkippedAdvent {
pub fn new(advent: u8) -> Self {
Self(advent)
}
}
impl Advent for SkippedAdvent {
fn get_index(&self) -> u8 {
self.0
}
fn skip(&self) -> bool {
true
}
fn get_input_names(&self) -> Vec<String> {
Vec::new()
}
fn process_input(&self, _data: Vec<String>) {
unimplemented!()
}
}
|
// 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::sync::Arc;
use std::time::SystemTime;
use common_catalog::table_context::TableContext;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::DataSchemaRef;
use common_expression::DataSchemaRefExt;
use common_expression::SendableDataBlockStream;
use crate::interpreters::InterpreterMetrics;
use crate::interpreters::InterpreterQueryLog;
use crate::pipelines::executor::ExecutorSettings;
use crate::pipelines::executor::PipelineCompleteExecutor;
use crate::pipelines::executor::PipelinePullingExecutor;
use crate::pipelines::PipelineBuildResult;
use crate::pipelines::SourcePipeBuilder;
use crate::sessions::QueryContext;
use crate::sessions::SessionManager;
use crate::stream::DataBlockStream;
use crate::stream::ProgressStream;
use crate::stream::PullingExecutorStream;
#[async_trait::async_trait]
/// Interpreter is a trait for different PlanNode
/// Each type of planNode has its own corresponding interpreter
pub trait Interpreter: Sync + Send {
/// Return the name of Interpreter, such as "CreateDatabaseInterpreter"
fn name(&self) -> &str;
/// Return the schema of Interpreter
fn schema(&self) -> DataSchemaRef {
DataSchemaRefExt::create(vec![])
}
/// The core of the databend processor which will execute the logical plan and get the DataBlock
async fn execute(&self, ctx: Arc<QueryContext>) -> Result<SendableDataBlockStream> {
InterpreterMetrics::record_query_start(&ctx);
log_query_start(&ctx);
let mut build_res = match self.execute2().await {
Ok(build_res) => build_res,
Err(build_error) => {
InterpreterMetrics::record_query_error(&ctx);
log_query_finished(&ctx, Some(build_error.clone()));
return Err(build_error);
}
};
if build_res.main_pipeline.is_empty() {
InterpreterMetrics::record_query_finished(&ctx, None);
log_query_finished(&ctx, None);
return Ok(Box::pin(DataBlockStream::create(None, vec![])));
}
let query_ctx = ctx.clone();
build_res.main_pipeline.set_on_finished(move |may_error| {
InterpreterMetrics::record_query_finished(&query_ctx, may_error.clone());
log_query_finished(&query_ctx, may_error.clone());
match may_error {
None => Ok(()),
Some(error) => Err(error.clone()),
}
});
let settings = ctx.get_settings();
let query_id = ctx.get_id();
build_res.set_max_threads(settings.get_max_threads()? as usize);
let settings = ExecutorSettings::try_create(&settings, query_id)?;
if build_res.main_pipeline.is_complete_pipeline()? {
let mut pipelines = build_res.sources_pipelines;
pipelines.push(build_res.main_pipeline);
let complete_executor = PipelineCompleteExecutor::from_pipelines(pipelines, settings)?;
ctx.set_executor(Arc::downgrade(&complete_executor.get_inner()));
complete_executor.execute()?;
return Ok(Box::pin(DataBlockStream::create(None, vec![])));
}
let pulling_executor = PipelinePullingExecutor::from_pipelines(build_res, settings)?;
ctx.set_executor(Arc::downgrade(&pulling_executor.get_inner()));
Ok(Box::pin(ProgressStream::try_create(
Box::pin(PullingExecutorStream::create(pulling_executor)?),
ctx.get_result_progress(),
)?))
}
/// The core of the databend processor which will execute the logical plan and build the pipeline
async fn execute2(&self) -> Result<PipelineBuildResult>;
fn set_source_pipe_builder(&self, _builder: Option<SourcePipeBuilder>) -> Result<()> {
Err(ErrorCode::Unimplemented(format!(
"UnImplement set_source_pipe_builder method for {:?}",
self.name()
)))
}
}
pub type InterpreterPtr = Arc<dyn Interpreter>;
fn log_query_start(ctx: &QueryContext) {
let now = SystemTime::now();
let session = ctx.get_current_session();
if session.get_type().is_user_session() {
SessionManager::instance().status.write().query_start(now);
}
if let Err(error) = InterpreterQueryLog::log_start(ctx, now, None) {
tracing::error!("interpreter.start.error: {:?}", error)
}
}
fn log_query_finished(ctx: &QueryContext, error: Option<ErrorCode>) {
let now = SystemTime::now();
let session = ctx.get_current_session();
session.get_status().write().query_finish();
if session.get_type().is_user_session() {
SessionManager::instance().status.write().query_finish(now)
}
if let Err(error) = InterpreterQueryLog::log_finish(ctx, now, error) {
tracing::error!("interpreter.finish.error: {:?}", error)
}
}
|
#[cfg(not(windows))]
fn compile_resource() {
// do nothing
}
#[cfg(windows)]
#[path = "src/view_assets_catalog.rs"]
pub(crate) mod resource_catalog;
#[cfg(windows)]
fn compile_resource() {
use resource_catalog as catalog;
use resw::*;
Build::with_two_languages(lang::LANG_CHS)
.resource(
catalog::IDI_CHARLESMINE,
resource::Icon::from_file("./res/CharlesMine.ico"),
)
.resource(
catalog::IDC_CHARLESMINE,
resource::Accelerators::from_builder()
.event(
catalog::IDM_HELP_ABOUT,
accelerators::Event::ascii_key_event(
accelerators::ASCIIKey::ascii_key(b'/'),
accelerators::ASCIIModifier::Alt,
),
)
.event(
catalog::IDM_HELP_ABOUT,
accelerators::Event::ascii_key_event(
accelerators::ASCIIKey::ascii_key(b'?'),
accelerators::ASCIIModifier::Alt,
),
)
.event(
catalog::IDM_FILE_NEW,
accelerators::Event::virt_key_event(
accelerators::VirtKey::F2,
accelerators::Modifier::None,
),
)
.event(
catalog::IDM_ADVANCED_RESTART,
accelerators::Event::virt_key_event(
accelerators::VirtKey::F8,
accelerators::Modifier::None,
),
)
.event(
catalog::IDM_ADVANCED_RECORD_STOP,
accelerators::Event::virt_key_event(
accelerators::VirtKey::F12,
accelerators::Modifier::None,
),
)
.event(
catalog::IDM_ADVANCED_LOADMAP,
accelerators::Event::virt_key_event(
accelerators::VirtKey::F5,
accelerators::Modifier::None,
),
)
.event(
catalog::IDM_ADVANCED_SAVEMAP,
accelerators::Event::virt_key_event(
accelerators::VirtKey::F6,
accelerators::Modifier::None,
),
)
.build(),
)
.resource(
catalog::IDB_BLOCKS,
resource::Bitmap::from_file("./res/Blocks.bmp"),
)
.resource(
catalog::IDB_BUTTON,
resource::Bitmap::from_file("./res/Button.bmp"),
)
.resource(
catalog::IDB_DIGIT,
resource::Bitmap::from_file("./res/Digit.bmp"),
)
.resource(
catalog::IDC_CHARLESMINE,
resource::Menu::from_builder()
.popup(
MultiLangText::from("&Game").lang(lang::LANG_CHS, "游戏(&G)"),
|popup| {
popup
.item(
catalog::IDM_FILE_NEW,
MultiLangText::from("&New\tF2")
.lang(lang::LANG_CHS, "开局(&N)\tF2"),
)
.separator()
.item(
catalog::IDM_FILE_GAME_EASY,
MultiLangText::from("&Beginner").lang(lang::LANG_CHS, "初级(&B)"),
)
.item(
catalog::IDM_FILE_GAME_MEDIUM,
MultiLangText::from("&Intermediate")
.lang(lang::LANG_CHS, "中级(&I)"),
)
.item(
catalog::IDM_FILE_GAME_HARD,
MultiLangText::from("&Expert").lang(lang::LANG_CHS, "高级(&E)"),
)
.item(
catalog::IDM_FILE_GAME_CUSTOM,
MultiLangText::from("&Custom...")
.lang(lang::LANG_CHS, "自定义(&C)..."),
)
.separator()
.item(
catalog::IDM_FILE_MARK,
MultiLangText::from("&Marks (?)")
.lang(lang::LANG_CHS, "标记(?)(&M)"),
)
.separator()
.item(
catalog::IDM_FILE_HERO_LIST,
MultiLangText::from("Best &Times...")
.lang(lang::LANG_CHS, "扫雷英雄榜(&T)..."),
)
.separator()
.item(
catalog::IDM_FILE_EXIT,
MultiLangText::from("E&xit").lang(lang::LANG_CHS, "退出(&X)"),
)
},
)
.popup(
MultiLangText::from("&Advanced").lang(lang::LANG_CHS, "高级(&A)"),
|popup| {
popup
.item(
catalog::IDM_ADVANCED_LOADMAP,
MultiLangText::from("&Load Game\tF5")
.lang(lang::LANG_CHS, "加载雷局(&L)\tF5"),
)
.item(
catalog::IDM_ADVANCED_SAVEMAP,
MultiLangText::from("&Save Game\tF6")
.lang(lang::LANG_CHS, "保存雷局(&S)\tF6"),
)
.separator()
.item(
catalog::IDM_ADVANCED_RESTART,
MultiLangText::from("&Restart Game\tF8")
.lang(lang::LANG_CHS, "重新开始本局(&R)\tF8"),
)
.separator()
.item(
catalog::IDM_ADVANCED_RECORD_RECORD,
MultiLangText::from("Start R&ecording")
.lang(lang::LANG_CHS, "开始录像(&E)"),
)
.item(
catalog::IDM_ADVANCED_RECORD_PLAY,
MultiLangText::from("Start &Playback")
.lang(lang::LANG_CHS, "开始回放(&P)"),
)
.item(
catalog::IDM_ADVANCED_RECORD_STOP,
MultiLangText::from("S&top Recording/Playback\tF12")
.lang(lang::LANG_CHS, "停止(&T)\tF12"),
)
.separator()
.item(
catalog::IDM_ADVANCED_ZOOM_1x,
MultiLangText::from("Zoom 1x").lang(lang::LANG_CHS, "缩放 1x"),
)
.item(
catalog::IDM_ADVANCED_ZOOM_2x,
MultiLangText::from("Zoom 2x").lang(lang::LANG_CHS, "缩放 2x"),
)
.item(
catalog::IDM_ADVANCED_ZOOM_3x,
MultiLangText::from("Zoom 3x").lang(lang::LANG_CHS, "缩放 3x"),
)
},
)
.popup(
MultiLangText::from("&Help").lang(lang::LANG_CHS, "帮助(&H)"),
|popup| {
popup.item(
catalog::IDM_HELP_ABOUT,
MultiLangText::from("&About CharlesMine...")
.lang(lang::LANG_CHS, "关于 钻石扫雷(&A)..."),
)
},
)
.build(),
)
.resource(
catalog::IDD_ABOUTBOX,
resource::Dialog::from_builder()
.system_menu()
.caption(MultiLangText::from("About").lang(lang::LANG_CHS, "关于"))
.font(
"Tahoma",
FontSize::pt(9),
FontWeight::default(),
FontItalic::default(),
FontCharset::default(),
)
.lang_specific_font(
lang::LANG_CHS,
"SimSun",
FontSize::pt(9),
FontWeight::default(),
FontItalic::default(),
FontCharset::default(),
)
.style(dialog::DialogStyle::MODAL_FRAME)
.rect(Rect::new(22, 17, 186, 60))
.control(
catalog::IDC_MYICON,
dialog::Control::from_template(dialog::ControlTemplate::ICON)
.image_id(catalog::IDI_CHARLESMINE)
.rect(Rect::new(14, 9, 21, 21)),
)
.control(
catalog::IDC_TEXT1,
dialog::Control::from_template(dialog::ControlTemplate::LTEXT)
.text(
MultiLangText::from("CharlesMine 1.0")
.lang(lang::LANG_CHS, "钻石扫雷 1.0"),
)
.rect(Rect::new(49, 10, 119, 8))
.style(dialog::StaticControlStyle::NO_PREFIX),
)
.control(
catalog::IDC_TEXT2,
dialog::Control::from_template(dialog::ControlTemplate::LTEXT)
.text(
MultiLangText::from("CrLF0710 Home-made")
.lang(lang::LANG_CHS, "CrLF0710 制作"),
)
.rect(Rect::new(49, 20, 119, 8)),
)
.control(
predefined_id::OK,
dialog::Control::from_template(dialog::ControlTemplate::DEFPUSHBUTTON)
.text(MultiLangText::from("OK"))
.rect(Rect::new(75, 32, 36, 15))
.style(dialog::WindowStyle::GROUP),
)
.build(),
)
.compile()
.expect("Failed to compile resource");
}
fn main() {
compile_resource();
}
|
#[macro_use]
extern crate nom;
mod compiler;
mod parser;
mod vm;
fn main() {
vm::VM::run(vec![0, 8, 0, 6, 19, 64]);
let source = include_str!("../examples/first.🐛");
let parsed = parser::run(source);
println!("{:?}", parsed);
compiler::test(parsed);
}
|
use core::alloc::{AllocError, Layout};
use core::ptr::{self, NonNull};
/// Fallback for realloc that allocates a new region, copies old data
/// into the new region, and frees the old region.
#[inline]
pub unsafe fn realloc_fallback(
old_ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
use core::cmp::min;
use core::intrinsics::unlikely;
let old_size = old_layout.size();
let new_size = new_layout.size();
if unlikely(old_size == new_size) {
return Ok(NonNull::slice_from_raw_parts(old_ptr, new_size));
}
let align = old_layout.align();
let new_layout = Layout::from_size_align(new_size, align).expect("invalid layout");
// Allocate new region, using mmap for allocations larger than page size
let new_ptr = crate::arch::alloc::allocate(new_layout)?;
// Copy old region to new region
ptr::copy_nonoverlapping(
old_ptr.as_ptr(),
new_ptr.as_mut_ptr(),
min(old_size, new_ptr.len()),
);
// Free old region
crate::arch::alloc::deallocate(old_ptr, old_layout);
Ok(new_ptr)
}
/// Returns `size` rounded up to a multiple of `base`.
#[inline]
pub fn round_up_to_multiple_of(size: usize, base: usize) -> usize {
let rem = size % base;
if rem == 0 {
size
} else {
size + base - rem
}
}
|
//! Helper struct that manages attributes.
//! It creates an `Attribute` instance if it does not exists or uses a cached one.
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::{self, Debug};
use std::fs;
use std::path::Path;
use std::string::String;
use crate::utils::OrErr;
use crate::{Attribute, Ev3Error, Ev3Result, Port};
/// The driver path `/sys/class/`.
#[cfg(not(feature = "override-driver-path"))]
pub const DRIVER_PATH: &str = "/sys/class/";
/// The driver path that was set with the env variable `EV3DEV_DRIVER_PATH` (default value: `/sys/class/`).
#[cfg(feature = "override-driver-path")]
pub const DRIVER_PATH: &str = get_driver_path();
#[cfg(feature = "override-driver-path")]
const fn get_driver_path() -> &'static str {
let path = std::option_env!("EV3DEV_DRIVER_PATH");
if let Some(path) = path {
path
} else {
"/sys/class/"
}
}
/// Helper struct that manages attributes.
/// It creates an `Attribute` instance if it does not exists or uses a cached one.
#[derive(Clone)]
pub struct Driver {
class_name: String,
name: String,
attributes: RefCell<HashMap<String, Attribute>>,
}
impl Driver {
/// Returns a new `Driver`.
/// All attributes created by this driver will use the path `/sys/class/{class_name}/{name}`.
pub fn new(class_name: &str, name: &str) -> Driver {
Driver {
class_name: class_name.to_owned(),
name: name.to_owned(),
attributes: RefCell::new(HashMap::new()),
}
}
/// Returns the name of the device with the given `class_name`, `driver_name` and at the given `port`.
///
/// Returns `Ev3Error::NotFound` if no such device exists.
pub fn find_name_by_port_and_driver(
class_name: &str,
port: &dyn Port,
driver_name_vec: &[&str],
) -> Ev3Result<String> {
let port_address = port.address();
let paths = fs::read_dir(Path::new(DRIVER_PATH).join(class_name))?;
for path in paths {
let file_name = path?.file_name();
let name = file_name.to_str().or_err()?;
let address = Attribute::from_sys_class(class_name, name, "address")?;
if address.get::<String>()?.contains(&port_address) {
let driver = Attribute::from_sys_class(class_name, name, "driver_name")?;
let driver_name = driver.get::<String>()?;
if driver_name_vec.iter().any(|n| &driver_name == n) {
return Ok(name.to_owned());
}
}
}
Err(Ev3Error::NotConnected {
device: format!("{driver_name_vec:?}"),
port: Some(port_address),
})
}
/// Returns the name of the device with the given `class_name`.
///
/// Returns `Ev3Error::NotFound` if no such device exists.
/// Returns `Ev3Error::MultipleMatches` if more then one matching device exists.
pub fn find_name_by_driver(class_name: &str, driver_name_vec: &[&str]) -> Ev3Result<String> {
let mut names = Driver::find_names_by_driver(class_name, driver_name_vec)?;
match names.len() {
0 => Err(Ev3Error::NotConnected {
device: format!("{driver_name_vec:?}"),
port: None,
}),
1 => Ok(names
.pop()
.expect("Name vector should contains exactly one element")),
_ => Err(Ev3Error::MultipleMatches {
device: format!("{driver_name_vec:?}"),
ports: names,
}),
}
}
/// Returns the names of the devices with the given `class_name`.
pub fn find_names_by_driver(
class_name: &str,
driver_name_vec: &[&str],
) -> Ev3Result<Vec<String>> {
let paths = fs::read_dir(Path::new(DRIVER_PATH).join(class_name))?;
let mut found_names = Vec::new();
for path in paths {
let file_name = path?.file_name();
let name = file_name.to_str().or_err()?;
let driver = Attribute::from_sys_class(class_name, name, "driver_name")?;
let driver_name = driver.get::<String>()?;
if driver_name_vec.iter().any(|n| &driver_name == n) {
found_names.push(name.to_owned());
}
}
Ok(found_names)
}
/// Return the `Attribute` wrapper for the given `attribute_name`.
/// Creates a new one if it does not exist.
pub fn get_attribute(&self, attribute_name: &str) -> Attribute {
let mut attributes = self.attributes.borrow_mut();
if !attributes.contains_key(attribute_name) {
if let Ok(v) = Attribute::from_sys_class(
self.class_name.as_ref(),
self.name.as_ref(),
attribute_name,
) {
attributes.insert(attribute_name.to_owned(), v);
};
};
attributes
.get(attribute_name)
.expect("Internal error in the attribute map")
.clone()
}
}
impl Debug for Driver {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Driver {{ class_name: {}, name: {} }}",
self.class_name, self.name
)
}
}
|
use crate::name::Name;
use crate::rr_type::RRType;
use crate::util::{hex::from_hex, StringBuffer};
use anyhow::{anyhow, bail, Result};
use std::net::{Ipv4Addr, Ipv6Addr};
use time::{Date, Time};
pub fn name_from_str(buf: &mut StringBuffer) -> Result<Name> {
buf.read::<Name>()
}
pub fn ipv4_from_str(buf: &mut StringBuffer) -> Result<Ipv4Addr> {
buf.read::<Ipv4Addr>()
}
pub fn ipv6_from_str(buf: &mut StringBuffer) -> Result<Ipv6Addr> {
buf.read::<Ipv6Addr>()
}
pub fn u8_from_str(buf: &mut StringBuffer) -> Result<u8> {
buf.read::<u8>()
}
pub fn u16_from_str(buf: &mut StringBuffer) -> Result<u16> {
buf.read::<u16>()
}
pub fn rrtype_from_str(buf: &mut StringBuffer) -> Result<RRType> {
buf.read::<RRType>()
}
pub fn u32_from_str(buf: &mut StringBuffer) -> Result<u32> {
buf.read::<u32>()
}
pub fn text_from_str(buf: &mut StringBuffer) -> Result<Vec<Vec<u8>>> {
buf.read_text()
}
pub fn string_from_str(buf: &mut StringBuffer) -> Result<Vec<u8>> {
buf.read_char_string()
}
pub fn timestamp_from_str(buf: &mut StringBuffer) -> Result<u32> {
let ts = buf.read_str().ok_or(anyhow!("read timestamp failed"))?;
if ts.len() != 14 {
bail!("timestamp isn't in YYYYMMDDHHmmSS format");
}
Ok(
Date::try_from_ymd(ts[0..4].parse()?, ts[4..6].parse()?, ts[6..8].parse()?)
.map_err(|_| anyhow!("invalid date"))?
.with_time(
Time::try_from_hms(ts[8..10].parse()?, ts[10..12].parse()?, ts[12..14].parse()?)
.map_err(|_| anyhow!("invalid time"))?,
)
.assume_utc()
.unix_timestamp() as u32,
)
}
pub fn binary_from_str(buf: &mut StringBuffer) -> Result<Vec<u8>> {
buf.read_str()
.and_then(|s| from_hex(s))
.ok_or(anyhow!("invalid hex"))
}
pub fn base64_from_str(buf: &mut StringBuffer) -> Result<Vec<u8>> {
buf.read_left()
.and_then(|s| {
//rfc4034 allow whitespace in base64 encoded string
//but rust base64 lib won't allow it so strip the
let bs: String = s.chars().filter(|c| !c.is_whitespace()).collect();
base64::decode(bs).ok()
})
.ok_or(anyhow!("invalid base64"))
}
|
// Copyright 2017 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.
// ignore-tidy-linelength
// compile-flags: -Z verbose -Z mir-emit-validate=1
struct Test {
x: i32
}
fn foo(_x: &i32) {}
fn main() {
// These internal unsafe functions should have no effect on the code generation.
unsafe fn _unused1() {}
fn _unused2(x: *const i32) -> i32 { unsafe { *x }}
let t = Test { x: 0 };
let t = &t;
foo(&t.x);
}
// END RUST SOURCE
// START rustc.main.EraseRegions.after.mir
// fn main() -> (){
// let mut _0: ();
// scope 1 {
// scope 3 {
// }
// scope 4 {
// let _2: &ReErased Test;
// }
// }
// scope 2 {
// let _1: Test;
// }
// let mut _3: ();
// let mut _4: &ReErased i32;
// let mut _5: &ReErased i32;
// bb0: {
// StorageLive(_1);
// _1 = Test { x: const 0i32 };
// StorageLive(_2);
// Validate(Suspend(ReScope(Remainder(BlockRemainder { block: ItemLocalId(20), first_statement_index: 3 }))), [_1: Test]);
// _2 = &ReErased _1;
// Validate(Acquire, [(*_2): Test/ReScope(Remainder(BlockRemainder { block: ItemLocalId(20), first_statement_index: 3 })) (imm)]);
// StorageLive(_4);
// StorageLive(_5);
// Validate(Suspend(ReScope(Node(ItemLocalId(18)))), [((*_2).0: i32): i32/ReScope(Remainder(BlockRemainder { block: ItemLocalId(20), first_statement_index: 3 })) (imm)]);
// _5 = &ReErased ((*_2).0: i32);
// Validate(Acquire, [(*_5): i32/ReScope(Node(ItemLocalId(18))) (imm)]);
// Validate(Suspend(ReScope(Node(ItemLocalId(18)))), [(*_5): i32/ReScope(Node(ItemLocalId(18))) (imm)]);
// _4 = &ReErased (*_5);
// Validate(Acquire, [(*_4): i32/ReScope(Node(ItemLocalId(18))) (imm)]);
// Validate(Release, [_3: (), _4: &ReScope(Node(ItemLocalId(18))) i32]);
// _3 = const foo(move _4) -> bb1;
// }
// bb1: {
// Validate(Acquire, [_3: ()]);
// EndRegion(ReScope(Node(ItemLocalId(18))));
// StorageDead(_4);
// StorageDead(_5);
// _0 = ();
// EndRegion(ReScope(Remainder(BlockRemainder { block: ItemLocalId(20), first_statement_index: 3 })));
// StorageDead(_2);
// StorageDead(_1);
// return;
// }
// }
// END rustc.main.EraseRegions.after.mir
|
use cranelift_entity::entity_impl;
use intrusive_collections::linked_list::{Cursor, LinkedList};
use intrusive_collections::{LinkedListLink, UnsafeRef};
use super::*;
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Block(u32);
entity_impl!(Block, "block");
impl Default for Block {
#[inline]
fn default() -> Self {
use cranelift_entity::packed_option::ReservedValue;
Self::reserved_value()
}
}
pub struct BlockData {
pub link: LinkedListLink,
pub params: ValueList,
pub insts: LinkedList<InstAdapter>,
}
impl Drop for BlockData {
fn drop(&mut self) {
self.insts.fast_clear();
}
}
impl Clone for BlockData {
fn clone(&self) -> Self {
Self {
link: LinkedListLink::default(),
params: self.params.clone(),
insts: LinkedList::new(InstAdapter::new()),
}
}
}
impl BlockData {
pub(crate) fn new() -> Self {
Self {
link: LinkedListLink::default(),
params: ValueList::new(),
insts: LinkedList::new(InstAdapter::new()),
}
}
pub fn insts<'f>(&'f self) -> impl Iterator<Item = Inst> + 'f {
Insts {
cursor: self.insts.front(),
}
}
pub unsafe fn append(&mut self, inst: UnsafeRef<InstNode>) {
self.insts.push_back(inst);
}
pub fn first(&self) -> Option<Inst> {
self.insts.front().get().map(|data| data.key)
}
pub fn last(&self) -> Option<Inst> {
self.insts.back().get().map(|data| data.key)
}
pub fn is_empty(&self) -> bool {
self.insts.is_empty()
}
}
struct Insts<'f> {
cursor: Cursor<'f, InstAdapter>,
}
impl<'f> Iterator for Insts<'f> {
type Item = Inst;
fn next(&mut self) -> Option<Self::Item> {
if self.cursor.is_null() {
return None;
}
let next = self.cursor.get().map(|data| data.key);
self.cursor.move_next();
next
}
}
|
use super::lgamma_r;
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn lgamma(x: f64) -> f64 {
lgamma_r(x).0
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qerrormessage.h
// dst-file: /src/widgets/qerrormessage.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 super::qdialog::*; // 773
use std::ops::Deref;
use super::super::core::qobjectdefs::*; // 771
use super::qwidget::*; // 773
use super::super::core::qstring::*; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QErrorMessage_Class_Size() -> c_int;
// proto: const QMetaObject * QErrorMessage::metaObject();
fn C_ZNK13QErrorMessage10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QErrorMessage::QErrorMessage(QWidget * parent);
fn C_ZN13QErrorMessageC2EP7QWidget(arg0: *mut c_void) -> u64;
// proto: static QErrorMessage * QErrorMessage::qtHandler();
fn C_ZN13QErrorMessage9qtHandlerEv() -> *mut c_void;
// proto: void QErrorMessage::showMessage(const QString & message, const QString & type);
fn C_ZN13QErrorMessage11showMessageERK7QStringS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QErrorMessage::showMessage(const QString & message);
fn C_ZN13QErrorMessage11showMessageERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QErrorMessage::~QErrorMessage();
fn C_ZN13QErrorMessageD2Ev(qthis: u64 /* *mut c_void*/);
} // <= ext block end
// body block begin =>
// class sizeof(QErrorMessage)=1
#[derive(Default)]
pub struct QErrorMessage {
qbase: QDialog,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QErrorMessage {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QErrorMessage {
return QErrorMessage{qbase: QDialog::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QErrorMessage {
type Target = QDialog;
fn deref(&self) -> &QDialog {
return & self.qbase;
}
}
impl AsRef<QDialog> for QErrorMessage {
fn as_ref(& self) -> & QDialog {
return & self.qbase;
}
}
// proto: const QMetaObject * QErrorMessage::metaObject();
impl /*struct*/ QErrorMessage {
pub fn metaObject<RetType, T: QErrorMessage_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QErrorMessage_metaObject<RetType> {
fn metaObject(self , rsthis: & QErrorMessage) -> RetType;
}
// proto: const QMetaObject * QErrorMessage::metaObject();
impl<'a> /*trait*/ QErrorMessage_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QErrorMessage) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QErrorMessage10metaObjectEv()};
let mut ret = unsafe {C_ZNK13QErrorMessage10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QErrorMessage::QErrorMessage(QWidget * parent);
impl /*struct*/ QErrorMessage {
pub fn new<T: QErrorMessage_new>(value: T) -> QErrorMessage {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QErrorMessage_new {
fn new(self) -> QErrorMessage;
}
// proto: void QErrorMessage::QErrorMessage(QWidget * parent);
impl<'a> /*trait*/ QErrorMessage_new for (Option<&'a QWidget>) {
fn new(self) -> QErrorMessage {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QErrorMessageC2EP7QWidget()};
let ctysz: c_int = unsafe{QErrorMessage_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN13QErrorMessageC2EP7QWidget(arg0)};
let rsthis = QErrorMessage{qbase: QDialog::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: static QErrorMessage * QErrorMessage::qtHandler();
impl /*struct*/ QErrorMessage {
pub fn qtHandler_s<RetType, T: QErrorMessage_qtHandler_s<RetType>>( overload_args: T) -> RetType {
return overload_args.qtHandler_s();
// return 1;
}
}
pub trait QErrorMessage_qtHandler_s<RetType> {
fn qtHandler_s(self ) -> RetType;
}
// proto: static QErrorMessage * QErrorMessage::qtHandler();
impl<'a> /*trait*/ QErrorMessage_qtHandler_s<QErrorMessage> for () {
fn qtHandler_s(self ) -> QErrorMessage {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QErrorMessage9qtHandlerEv()};
let mut ret = unsafe {C_ZN13QErrorMessage9qtHandlerEv()};
let mut ret1 = QErrorMessage::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QErrorMessage::showMessage(const QString & message, const QString & type);
impl /*struct*/ QErrorMessage {
pub fn showMessage<RetType, T: QErrorMessage_showMessage<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.showMessage(self);
// return 1;
}
}
pub trait QErrorMessage_showMessage<RetType> {
fn showMessage(self , rsthis: & QErrorMessage) -> RetType;
}
// proto: void QErrorMessage::showMessage(const QString & message, const QString & type);
impl<'a> /*trait*/ QErrorMessage_showMessage<()> for (&'a QString, &'a QString) {
fn showMessage(self , rsthis: & QErrorMessage) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QErrorMessage11showMessageERK7QStringS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN13QErrorMessage11showMessageERK7QStringS2_(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QErrorMessage::showMessage(const QString & message);
impl<'a> /*trait*/ QErrorMessage_showMessage<()> for (&'a QString) {
fn showMessage(self , rsthis: & QErrorMessage) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QErrorMessage11showMessageERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN13QErrorMessage11showMessageERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QErrorMessage::~QErrorMessage();
impl /*struct*/ QErrorMessage {
pub fn free<RetType, T: QErrorMessage_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QErrorMessage_free<RetType> {
fn free(self , rsthis: & QErrorMessage) -> RetType;
}
// proto: void QErrorMessage::~QErrorMessage();
impl<'a> /*trait*/ QErrorMessage_free<()> for () {
fn free(self , rsthis: & QErrorMessage) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QErrorMessageD2Ev()};
unsafe {C_ZN13QErrorMessageD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// <= body block end
|
use std::convert::TryInto;
use std::sync::Arc;
use liblumen_core::locks::Mutex;
use liblumen_alloc::erts::term::prelude::*;
use crate::executor::Executor;
#[native_implemented::label]
pub fn result(apply_returned: Term, executor: Term) -> Term {
let executor_boxed_resource: Boxed<Resource> = executor.try_into().unwrap();
let executor_resource: Resource = executor_boxed_resource.into();
let executor_mutex: &Arc<Mutex<Executor>> = executor_resource.downcast_ref().unwrap();
executor_mutex.lock().resolve(apply_returned);
apply_returned
}
|
#![crate_type="lib"]
#![no_std]
#![feature(box_syntax, drop_types_in_const, compiler_builtins_lib)]
#![feature(lang_items, start, alloc, global_allocator, allocator_api, link_args)]
#![feature(slice_concat_ext)]
#[macro_use]
extern crate alloc;
extern crate libc;
extern crate nostd_io;
extern crate nostd_collections;
extern crate compiler_builtins;
#[macro_use]
extern crate lazy_static;
pub mod stub;
#[macro_use]
pub mod macros;
mod kernel;
mod warden;
use warden::Warden;
use nostd_io::Write;
use nostd_collections::HashMap;
use alloc::String;
use alloc::Vec;
use alloc::boxed::Box;
use alloc::borrow::ToOwned;
use alloc::string::ToString;
use kernel::allocator::Allocator;
use kernel::LockGroup;
use kernel::LockGroupAttribute;
use kernel::RwLock;
use kernel::LockAttribute;
#[global_allocator]
pub static GLOBAL: Allocator = Allocator;
static mut WARDEN_GROUP: Option<LockGroup> = None;
static mut WARDEN: Option<RwLock<Warden>> = None;
#[no_mangle]
pub fn warden_init() {
// let mut h: HashMap<String, String> = HashMap::new();
// for i in 0..999 {
// let key = format!("test{}", i).to_string();
// println!("Inserting {}", key);
// h.insert(key, "Heap allocation working".to_string());
// }
// println!("{:?}", h);
let wrdn_result = Warden::new();
match wrdn_result {
Ok(wrdn) => {
let group_attr = LockGroupAttribute::new();
let group = LockGroup::new("warden_global", group_attr);
let attr = LockAttribute::new();
unsafe {
WARDEN = Some(RwLock::new(&group, attr, wrdn));
WARDEN_GROUP = Some(group);
}
}
Err(err) => {
println!("Failed to initialize Warden - {:?}. Bye :(", err);
return;
}
}
let wrdn_lock = warden();
let mut wrdn = wrdn_lock.writable();
let register_result = wrdn.register_vnode();
match register_result {
Ok(_) => println!("Registered KAuth VNode"),
Err(err) => println!("Unable to register KAuth VNode - {:?}", err),
}
}
#[no_mangle]
pub fn warden_deinit() {
unsafe {
WARDEN = None;
WARDEN_GROUP = None;
}
}
pub fn warden() -> &'static mut RwLock<Warden> {
unsafe {
match WARDEN {
Some(ref mut w) => w,
None => {
println!("Warden not properly initizalized");
panic!("Bye :(");
}
}
}
}
// Exception handeling hooks
// https://stackoverflow.com/questions/16597350/what-is-an-exception-handling-personality-function
// TODO :: flesh eh_personality out
#[lang = "eh_personality"]
#[no_mangle]
pub extern "C" fn rust_eh_personality() {}
#[lang = "panic_fmt"]
#[no_mangle]
pub fn panic_fmt(fmt: core::fmt::Arguments, file_line: &(&'static str, u32)) -> ! {
println!("Panic : {}", fmt);
let &(ref file, ref line) = file_line;
println!("{} {}", file, line);
loop {}
}
|
// Copyright 2019-2021 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Moonbeam is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Moonbeam. If not, see <http://www.gnu.org/licenses/>.
//! Unit testing
use crate::*;
use frame_support::dispatch::{DispatchError, Dispatchable};
use frame_support::{assert_noop, assert_ok};
use mock::*;
use parity_scale_codec::Encode;
use sp_core::Pair;
use sp_runtime::MultiSignature;
// Constant that reflects the desired vesting period for the tests
// Most tests complete initialization passing initRelayBlock + VESTING as the endRelayBlock
const VESTING: u32 = 8;
#[test]
fn geneses() {
empty().execute_with(|| {
assert!(System::events().is_empty());
// Insert contributors
let pairs = get_ed25519_pairs(3);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
([1u8; 32].into(), Some(1), 500u32.into()),
([2u8; 32].into(), Some(2), 500u32.into()),
(pairs[0].public().into(), None, 500u32.into()),
(pairs[1].public().into(), None, 500u32.into()),
(pairs[2].public().into(), None, 500u32.into())
]
));
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
assert_eq!(Crowdloan::total_contributors(), 5);
// accounts_payable
assert!(Crowdloan::accounts_payable(&1).is_some());
assert!(Crowdloan::accounts_payable(&2).is_some());
assert!(Crowdloan::accounts_payable(&3).is_none());
assert!(Crowdloan::accounts_payable(&4).is_none());
assert!(Crowdloan::accounts_payable(&5).is_none());
// claimed address existence
assert!(Crowdloan::claimed_relay_chain_ids(&[1u8; 32]).is_some());
assert!(Crowdloan::claimed_relay_chain_ids(&[2u8; 32]).is_some());
assert!(Crowdloan::claimed_relay_chain_ids(pairs[0].public().as_array_ref()).is_none());
assert!(Crowdloan::claimed_relay_chain_ids(pairs[1].public().as_array_ref()).is_none());
assert!(Crowdloan::claimed_relay_chain_ids(pairs[2].public().as_array_ref()).is_none());
// unassociated_contributions
assert!(Crowdloan::unassociated_contributions(&[1u8; 32]).is_none());
assert!(Crowdloan::unassociated_contributions(&[2u8; 32]).is_none());
assert!(Crowdloan::unassociated_contributions(pairs[0].public().as_array_ref()).is_some());
assert!(Crowdloan::unassociated_contributions(pairs[1].public().as_array_ref()).is_some());
assert!(Crowdloan::unassociated_contributions(pairs[2].public().as_array_ref()).is_some());
});
}
#[test]
fn proving_assignation_works() {
let pairs = get_ed25519_pairs(3);
let signature: MultiSignature = pairs[0].sign(&3u64.encode()).into();
let alread_associated_signature: MultiSignature = pairs[0].sign(&1u64.encode()).into();
empty().execute_with(|| {
// Insert contributors
let pairs = get_ed25519_pairs(3);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
([1u8; 32].into(), Some(1), 500u32.into()),
([2u8; 32].into(), Some(2), 500u32.into()),
(pairs[0].public().into(), None, 500u32.into()),
(pairs[1].public().into(), None, 500u32.into()),
(pairs[2].public().into(), None, 500u32.into())
],
));
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
// 4 is not payable first
assert!(Crowdloan::accounts_payable(&3).is_none());
assert_eq!(
Crowdloan::accounts_payable(&1)
.unwrap()
.contributed_relay_addresses,
vec![[1u8; 32]]
);
roll_to(4);
// Signature is wrong, prove fails
assert_noop!(
Crowdloan::associate_native_identity(
Origin::signed(4),
4,
pairs[0].public().into(),
signature.clone()
),
Error::<Test>::InvalidClaimSignature
);
// Signature is right, but address already claimed
assert_noop!(
Crowdloan::associate_native_identity(
Origin::signed(4),
1,
pairs[0].public().into(),
alread_associated_signature
),
Error::<Test>::AlreadyAssociated
);
// Signature is right, prove passes
assert_ok!(Crowdloan::associate_native_identity(
Origin::signed(4),
3,
pairs[0].public().into(),
signature.clone()
));
// Signature is right, but relay address is no longer on unassociated
assert_noop!(
Crowdloan::associate_native_identity(
Origin::signed(4),
3,
pairs[0].public().into(),
signature
),
Error::<Test>::NoAssociatedClaim
);
// now three is payable
assert!(Crowdloan::accounts_payable(&3).is_some());
assert_eq!(
Crowdloan::accounts_payable(&3)
.unwrap()
.contributed_relay_addresses,
vec![*pairs[0].public().as_array_ref()]
);
assert!(Crowdloan::unassociated_contributions(pairs[0].public().as_array_ref()).is_none());
assert!(Crowdloan::claimed_relay_chain_ids(pairs[0].public().as_array_ref()).is_some());
let expected = vec![
crate::Event::InitialPaymentMade(1, 100),
crate::Event::InitialPaymentMade(2, 100),
crate::Event::InitialPaymentMade(3, 100),
crate::Event::NativeIdentityAssociated(pairs[0].public().into(), 3, 500),
];
assert_eq!(events(), expected);
});
}
#[test]
fn initializing_multi_relay_to_single_native_address_works() {
empty().execute_with(|| {
// Insert contributors
let pairs = get_ed25519_pairs(3);
// The init relay block gets inserted
roll_to(2);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
([1u8; 32].into(), Some(1), 500u32.into()),
([2u8; 32].into(), Some(1), 500u32.into()),
(pairs[0].public().into(), None, 500u32.into()),
(pairs[1].public().into(), None, 500u32.into()),
(pairs[2].public().into(), None, 500u32.into())
]
));
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
// 1 is payable
assert!(Crowdloan::accounts_payable(&1).is_some());
assert_eq!(
Crowdloan::accounts_payable(&1)
.unwrap()
.contributed_relay_addresses,
vec![[1u8; 32], [2u8; 32]]
);
roll_to(4);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_eq!(Crowdloan::accounts_payable(&1).unwrap().claimed_reward, 400);
assert_noop!(
Crowdloan::claim(Origin::signed(3)),
Error::<Test>::NoAssociatedClaim
);
let expected = vec![
crate::Event::InitialPaymentMade(1, 100),
crate::Event::InitialPaymentMade(1, 100),
crate::Event::RewardsPaid(1, 200),
];
assert_eq!(events(), expected);
});
}
#[test]
fn paying_works_step_by_step() {
empty().execute_with(|| {
// Insert contributors
let pairs = get_ed25519_pairs(3);
// The init relay block gets inserted
roll_to(2);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
([1u8; 32].into(), Some(1), 500u32.into()),
([2u8; 32].into(), Some(2), 500u32.into()),
(pairs[0].public().into(), None, 500u32.into()),
(pairs[1].public().into(), None, 500u32.into()),
(pairs[2].public().into(), None, 500u32.into())
]
));
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
// 1 is payable
assert!(Crowdloan::accounts_payable(&1).is_some());
roll_to(4);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_eq!(Crowdloan::accounts_payable(&1).unwrap().claimed_reward, 200);
assert_noop!(
Crowdloan::claim(Origin::signed(3)),
Error::<Test>::NoAssociatedClaim
);
roll_to(5);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_eq!(Crowdloan::accounts_payable(&1).unwrap().claimed_reward, 250);
roll_to(6);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_eq!(Crowdloan::accounts_payable(&1).unwrap().claimed_reward, 300);
roll_to(7);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_eq!(Crowdloan::accounts_payable(&1).unwrap().claimed_reward, 350);
roll_to(8);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_eq!(Crowdloan::accounts_payable(&1).unwrap().claimed_reward, 400);
roll_to(9);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_eq!(Crowdloan::accounts_payable(&1).unwrap().claimed_reward, 450);
roll_to(10);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_eq!(Crowdloan::accounts_payable(&1).unwrap().claimed_reward, 500);
roll_to(11);
assert_noop!(
Crowdloan::claim(Origin::signed(1)),
Error::<Test>::RewardsAlreadyClaimed
);
let expected = vec![
crate::Event::InitialPaymentMade(1, 100),
crate::Event::InitialPaymentMade(2, 100),
crate::Event::RewardsPaid(1, 100),
crate::Event::RewardsPaid(1, 50),
crate::Event::RewardsPaid(1, 50),
crate::Event::RewardsPaid(1, 50),
crate::Event::RewardsPaid(1, 50),
crate::Event::RewardsPaid(1, 50),
crate::Event::RewardsPaid(1, 50),
];
assert_eq!(events(), expected);
});
}
#[test]
fn paying_works_after_unclaimed_period() {
empty().execute_with(|| {
// Insert contributors
let pairs = get_ed25519_pairs(3);
// The init relay block gets inserted
roll_to(2);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
([1u8; 32].into(), Some(1), 500u32.into()),
([2u8; 32].into(), Some(2), 500u32.into()),
(pairs[0].public().into(), None, 500u32.into()),
(pairs[1].public().into(), None, 500u32.into()),
(pairs[2].public().into(), None, 500u32.into())
]
));
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
// 1 is payable
assert!(Crowdloan::accounts_payable(&1).is_some());
roll_to(4);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_eq!(Crowdloan::accounts_payable(&1).unwrap().claimed_reward, 200);
assert_noop!(
Crowdloan::claim(Origin::signed(3)),
Error::<Test>::NoAssociatedClaim
);
roll_to(5);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_eq!(Crowdloan::accounts_payable(&1).unwrap().claimed_reward, 250);
roll_to(6);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_eq!(Crowdloan::accounts_payable(&1).unwrap().claimed_reward, 300);
roll_to(7);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_eq!(Crowdloan::accounts_payable(&1).unwrap().claimed_reward, 350);
roll_to(11);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_eq!(Crowdloan::accounts_payable(&1).unwrap().claimed_reward, 500);
roll_to(330);
assert_noop!(
Crowdloan::claim(Origin::signed(1)),
Error::<Test>::RewardsAlreadyClaimed
);
let expected = vec![
crate::Event::InitialPaymentMade(1, 100),
crate::Event::InitialPaymentMade(2, 100),
crate::Event::RewardsPaid(1, 100),
crate::Event::RewardsPaid(1, 50),
crate::Event::RewardsPaid(1, 50),
crate::Event::RewardsPaid(1, 50),
crate::Event::RewardsPaid(1, 150),
];
assert_eq!(events(), expected);
});
}
#[test]
fn paying_late_joiner_works() {
let pairs = get_ed25519_pairs(3);
let signature: MultiSignature = pairs[0].sign(&3u64.encode()).into();
empty().execute_with(|| {
// Insert contributors
let pairs = get_ed25519_pairs(3);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
([1u8; 32].into(), Some(1), 500u32.into()),
([2u8; 32].into(), Some(2), 500u32.into()),
(pairs[0].public().into(), None, 500u32.into()),
(pairs[1].public().into(), None, 500u32.into()),
(pairs[2].public().into(), None, 500u32.into())
]
));
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
roll_to(12);
assert_ok!(Crowdloan::associate_native_identity(
Origin::signed(4),
3,
pairs[0].public().into(),
signature.clone()
));
assert_ok!(Crowdloan::claim(Origin::signed(3)));
assert_eq!(Crowdloan::accounts_payable(&3).unwrap().claimed_reward, 500);
let expected = vec![
crate::Event::InitialPaymentMade(1, 100),
crate::Event::InitialPaymentMade(2, 100),
crate::Event::InitialPaymentMade(3, 100),
crate::Event::NativeIdentityAssociated(pairs[0].public().into(), 3, 500),
crate::Event::RewardsPaid(3, 400),
];
assert_eq!(events(), expected);
});
}
#[test]
fn update_address_works() {
empty().execute_with(|| {
// Insert contributors
let pairs = get_ed25519_pairs(3);
// The init relay block gets inserted
roll_to(2);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
([1u8; 32].into(), Some(1), 500u32.into()),
([2u8; 32].into(), Some(2), 500u32.into()),
(pairs[0].public().into(), None, 500u32.into()),
(pairs[1].public().into(), None, 500u32.into()),
(pairs[2].public().into(), None, 500u32.into())
]
));
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
roll_to(4);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_noop!(
Crowdloan::claim(Origin::signed(8)),
Error::<Test>::NoAssociatedClaim
);
assert_ok!(Crowdloan::update_reward_address(Origin::signed(1), 8));
assert_eq!(Crowdloan::accounts_payable(&8).unwrap().claimed_reward, 200);
roll_to(6);
assert_ok!(Crowdloan::claim(Origin::signed(8)));
assert_eq!(Crowdloan::accounts_payable(&8).unwrap().claimed_reward, 300);
// The initial payment is not
let expected = vec![
crate::Event::InitialPaymentMade(1, 100),
crate::Event::InitialPaymentMade(2, 100),
crate::Event::RewardsPaid(1, 100),
crate::Event::RewardAddressUpdated(1, 8),
crate::Event::RewardsPaid(8, 100),
];
assert_eq!(events(), expected);
});
}
#[test]
fn update_address_with_existing_address_fails() {
empty().execute_with(|| {
// Insert contributors
let pairs = get_ed25519_pairs(3);
// The init relay block gets inserted
roll_to(2);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
([1u8; 32].into(), Some(1), 500u32.into()),
([2u8; 32].into(), Some(2), 500u32.into()),
(pairs[0].public().into(), None, 500u32.into()),
(pairs[1].public().into(), None, 500u32.into()),
(pairs[2].public().into(), None, 500u32.into())
]
));
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
roll_to(4);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
assert_ok!(Crowdloan::claim(Origin::signed(2)));
assert_noop!(
Crowdloan::update_reward_address(Origin::signed(1), 2),
Error::<Test>::AlreadyAssociated
);
});
}
#[test]
fn update_address_with_existing_with_multi_address_works() {
empty().execute_with(|| {
// Insert contributors
let pairs = get_ed25519_pairs(3);
// The init relay block gets inserted
roll_to(2);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
([1u8; 32].into(), Some(1), 500u32.into()),
([2u8; 32].into(), Some(1), 500u32.into()),
(pairs[0].public().into(), None, 500u32.into()),
(pairs[1].public().into(), None, 500u32.into()),
(pairs[2].public().into(), None, 500u32.into())
]
));
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
roll_to(4);
assert_ok!(Crowdloan::claim(Origin::signed(1)));
// We make sure all rewards go to the new address
assert_ok!(Crowdloan::update_reward_address(Origin::signed(1), 2));
assert_eq!(Crowdloan::accounts_payable(&2).unwrap().claimed_reward, 400);
assert_eq!(Crowdloan::accounts_payable(&2).unwrap().total_reward, 1000);
assert_noop!(
Crowdloan::claim(Origin::signed(1)),
Error::<Test>::NoAssociatedClaim
);
});
}
#[test]
fn initialize_new_addresses() {
empty().execute_with(|| {
// The init relay block gets inserted
roll_to(2);
// Insert contributors
let pairs = get_ed25519_pairs(3);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
([1u8; 32].into(), Some(1), 500u32.into()),
([2u8; 32].into(), Some(2), 500u32.into()),
(pairs[0].public().into(), None, 500u32.into()),
(pairs[1].public().into(), None, 500u32.into()),
(pairs[2].public().into(), None, 500u32.into())
]
));
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
assert_eq!(Crowdloan::initialized(), true);
roll_to(4);
assert_noop!(
Crowdloan::initialize_reward_vec(
Origin::root(),
vec![([1u8; 32].into(), Some(1), 500u32.into())]
),
Error::<Test>::RewardVecAlreadyInitialized,
);
assert_noop!(
Crowdloan::complete_initialization(Origin::root(), init_block + VESTING * 2),
Error::<Test>::RewardVecAlreadyInitialized,
);
});
}
#[test]
fn initialize_new_addresses_handle_dust() {
empty().execute_with(|| {
// The init relay block gets inserted
roll_to(2);
// Insert contributors
let pairs = get_ed25519_pairs(2);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
([1u8; 32].into(), Some(1), 500u32.into()),
([2u8; 32].into(), Some(2), 500u32.into()),
(pairs[0].public().into(), None, 500u32.into()),
(pairs[1].public().into(), None, 999u32.into()),
]
));
let crowdloan_pot = Crowdloan::pot();
let previous_issuance = Balances::total_issuance();
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
// We have burnt 1 unit
assert!(Crowdloan::pot() == crowdloan_pot - 1);
assert!(Balances::total_issuance() == previous_issuance - 1);
assert_eq!(Crowdloan::initialized(), true);
assert_eq!(Balances::free_balance(10), 0);
});
}
#[test]
fn initialize_new_addresses_not_matching_funds() {
empty().execute_with(|| {
// The init relay block gets inserted
roll_to(2);
// Insert contributors
let pairs = get_ed25519_pairs(2);
let init_block = Crowdloan::init_vesting_block();
// Total supply is 2500.Lets ensure inserting 2495 is not working.
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
([1u8; 32].into(), Some(1), 500u32.into()),
([2u8; 32].into(), Some(2), 500u32.into()),
(pairs[0].public().into(), None, 500u32.into()),
(pairs[1].public().into(), None, 995u32.into()),
]
));
assert_noop!(
Crowdloan::complete_initialization(Origin::root(), init_block + VESTING),
Error::<Test>::RewardsDoNotMatchFund
);
});
}
#[test]
fn initialize_new_addresses_with_batch() {
empty().execute_with(|| {
// This time should succeed trully
roll_to(10);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(mock::Call::Utility(UtilityCall::batch_all(vec![
mock::Call::Crowdloan(crate::Call::initialize_reward_vec(vec![(
[4u8; 32].into(),
Some(3),
1250
)],)),
mock::Call::Crowdloan(crate::Call::initialize_reward_vec(vec![(
[5u8; 32].into(),
Some(1),
1250
)],))
]))
.dispatch(Origin::root()));
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
assert_eq!(Crowdloan::total_contributors(), 2);
// Verify that the second ending block provider had no effect
assert_eq!(Crowdloan::end_vesting_block(), init_block + VESTING);
// Batch calls always succeed. We just need to check the inner event
assert_ok!(
mock::Call::Utility(UtilityCall::batch(vec![mock::Call::Crowdloan(
crate::Call::initialize_reward_vec(vec![([4u8; 32].into(), Some(3), 500)])
)]))
.dispatch(Origin::root())
);
let expected = vec![
pallet_utility::Event::ItemCompleted,
pallet_utility::Event::ItemCompleted,
pallet_utility::Event::BatchCompleted,
pallet_utility::Event::BatchInterrupted(
0,
DispatchError::Module {
index: 2,
error: 8,
message: None,
},
),
];
assert_eq!(batch_events(), expected);
});
}
#[test]
fn floating_point_arithmetic_works() {
empty().execute_with(|| {
// The init relay block gets inserted
roll_to(2);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(mock::Call::Utility(UtilityCall::batch_all(vec![
mock::Call::Crowdloan(crate::Call::initialize_reward_vec(vec![(
[4u8; 32].into(),
Some(1),
1190
)])),
mock::Call::Crowdloan(crate::Call::initialize_reward_vec(vec![(
[5u8; 32].into(),
Some(2),
1185
)])),
// We will work with this. This has 100/8=12.5 payable per block
mock::Call::Crowdloan(crate::Call::initialize_reward_vec(vec![(
[3u8; 32].into(),
Some(3),
125
)]))
]))
.dispatch(Origin::root()));
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
assert_eq!(Crowdloan::total_contributors(), 3);
assert_eq!(
Crowdloan::accounts_payable(&3).unwrap().claimed_reward,
25u128
);
// Block relay number is 2 post init initialization
// In this case there is no problem. Here we pay 12.5*2=25
// Total claimed reward: 25+25 = 50
roll_to(4);
assert_ok!(Crowdloan::claim(Origin::signed(3)));
assert_eq!(
Crowdloan::accounts_payable(&3).unwrap().claimed_reward,
50u128
);
roll_to(5);
// If we claim now we have to pay 12.5. 12 will be paid.
assert_ok!(Crowdloan::claim(Origin::signed(3)));
assert_eq!(
Crowdloan::accounts_payable(&3).unwrap().claimed_reward,
62u128
);
roll_to(6);
// Now we should pay 12.5. However the calculus will be:
// Account 3 should have claimed 50 + 25 at this block, but
// he only claimed 62. The payment is 13
assert_ok!(Crowdloan::claim(Origin::signed(3)));
assert_eq!(
Crowdloan::accounts_payable(&3).unwrap().claimed_reward,
75u128
);
let expected = vec![
crate::Event::InitialPaymentMade(1, 238),
crate::Event::InitialPaymentMade(2, 237),
crate::Event::InitialPaymentMade(3, 25),
crate::Event::RewardsPaid(3, 25),
crate::Event::RewardsPaid(3, 12),
crate::Event::RewardsPaid(3, 13),
];
assert_eq!(events(), expected);
});
}
#[test]
fn reward_below_vesting_period_works() {
empty().execute_with(|| {
// The init relay block gets inserted
roll_to(2);
let init_block = Crowdloan::init_vesting_block();
assert_ok!(mock::Call::Utility(UtilityCall::batch_all(vec![
mock::Call::Crowdloan(crate::Call::initialize_reward_vec(vec![(
[4u8; 32].into(),
Some(1),
1247
)])),
mock::Call::Crowdloan(crate::Call::initialize_reward_vec(vec![(
[5u8; 32].into(),
Some(2),
1247
)])),
// We will work with this. This has 5/8=0.625 payable per block
mock::Call::Crowdloan(crate::Call::initialize_reward_vec(vec![(
[3u8; 32].into(),
Some(3),
6
)]))
]))
.dispatch(Origin::root()));
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
assert_eq!(
Crowdloan::accounts_payable(&3).unwrap().claimed_reward,
1u128
);
// Block relay number is 2 post init initialization
// Here we should pay floor(0.625*2)=1
// Total claimed reward: 1+1 = 2
roll_to(4);
assert_ok!(Crowdloan::claim(Origin::signed(3)));
assert_eq!(
Crowdloan::accounts_payable(&3).unwrap().claimed_reward,
2u128
);
roll_to(5);
// If we claim now we have to pay floor(0.625) = 0
assert_ok!(Crowdloan::claim(Origin::signed(3)));
assert_eq!(
Crowdloan::accounts_payable(&3).unwrap().claimed_reward,
2u128
);
roll_to(6);
// Now we should pay 1 again. The claimer should have claimed floor(0.625*4) + 1
// but he only claimed 2
assert_ok!(Crowdloan::claim(Origin::signed(3)));
assert_eq!(
Crowdloan::accounts_payable(&3).unwrap().claimed_reward,
3u128
);
roll_to(10);
// We pay the remaining
assert_ok!(Crowdloan::claim(Origin::signed(3)));
assert_eq!(
Crowdloan::accounts_payable(&3).unwrap().claimed_reward,
6u128
);
roll_to(11);
// Nothing more to claim
assert_noop!(
Crowdloan::claim(Origin::signed(3)),
Error::<Test>::RewardsAlreadyClaimed
);
let expected = vec![
crate::Event::InitialPaymentMade(1, 249),
crate::Event::InitialPaymentMade(2, 249),
crate::Event::InitialPaymentMade(3, 1),
crate::Event::RewardsPaid(3, 1),
crate::Event::RewardsPaid(3, 0),
crate::Event::RewardsPaid(3, 1),
crate::Event::RewardsPaid(3, 3),
];
assert_eq!(events(), expected);
});
}
#[test]
fn test_initialization_errors() {
empty().execute_with(|| {
// The init relay block gets inserted
roll_to(2);
let init_block = Crowdloan::init_vesting_block();
let pot = Crowdloan::pot();
// Too many contributors
assert_noop!(
Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
([1u8; 32].into(), Some(1), 1),
([2u8; 32].into(), Some(2), 1),
([3u8; 32].into(), Some(3), 1),
([4u8; 32].into(), Some(4), 1),
([5u8; 32].into(), Some(5), 1),
([6u8; 32].into(), Some(6), 1),
([7u8; 32].into(), Some(7), 1),
([8u8; 32].into(), Some(8), 1),
([9u8; 32].into(), Some(9), 1)
]
),
Error::<Test>::TooManyContributors
);
// Go beyond fund pot
assert_noop!(
Crowdloan::initialize_reward_vec(
Origin::root(),
vec![([1u8; 32].into(), Some(1), pot + 1)]
),
Error::<Test>::BatchBeyondFundPot
);
// Dont fill rewards
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![([1u8; 32].into(), Some(1), pot - 1)]
));
// Fill rewards
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![([2u8; 32].into(), Some(2), 1)]
));
// Insert a non-valid vesting period
assert_noop!(
Crowdloan::complete_initialization(Origin::root(), init_block),
Error::<Test>::VestingPeriodNonValid
);
// Cannot claim if we dont complete initialization
assert_noop!(
Crowdloan::claim(Origin::signed(1)),
Error::<Test>::RewardVecNotFullyInitializedYet
);
// Complete
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
// Cannot initialize again
assert_noop!(
Crowdloan::complete_initialization(Origin::root(), init_block),
Error::<Test>::RewardVecAlreadyInitialized
);
});
}
#[test]
fn test_relay_signatures_can_change_reward_addresses() {
empty().execute_with(|| {
// 5 relay keys
let pairs = get_ed25519_pairs(5);
// The init relay block gets inserted
roll_to(2);
let init_block = Crowdloan::init_vesting_block();
// We will have all pointint to the same reward account
assert_ok!(Crowdloan::initialize_reward_vec(
Origin::root(),
vec![
(pairs[0].public().into(), Some(1), 500u32.into()),
(pairs[1].public().into(), Some(1), 500u32.into()),
(pairs[2].public().into(), Some(1), 500u32.into()),
(pairs[3].public().into(), Some(1), 500u32.into()),
(pairs[4].public().into(), Some(1), 500u32.into())
],
));
// Complete
assert_ok!(Crowdloan::complete_initialization(
Origin::root(),
init_block + VESTING
));
let reward_info = Crowdloan::accounts_payable(&1).unwrap();
// We should have all of them as contributors
for pair in pairs.clone() {
assert!(reward_info
.contributed_relay_addresses
.contains(&pair.public().into()))
}
// Threshold is set to 50%, so we need at least 3 votes to pass
// Let's make sure that we dont pass with 2
let mut payload = WRAPPED_BYTES_PREFIX.to_vec();
payload.append(&mut 2u64.encode());
payload.append(&mut 1u64.encode());
payload.append(&mut WRAPPED_BYTES_POSTFIX.to_vec());
let mut insufficient_proofs: Vec<([u8; 32], MultiSignature)> = vec![];
for i in 0..2 {
insufficient_proofs.push((pairs[i].public().into(), pairs[i].sign(&payload).into()));
}
// Not sufficient proofs presented
assert_noop!(
Crowdloan::change_association_with_relay_keys(
Origin::signed(1),
2,
1,
insufficient_proofs.clone()
),
Error::<Test>::InsufficientNumberOfValidProofs
);
// With three votes we should passs
let mut sufficient_proofs = insufficient_proofs.clone();
// We push one more
sufficient_proofs.push((pairs[2].public().into(), pairs[2].sign(&payload).into()));
// This time should pass
assert_ok!(Crowdloan::change_association_with_relay_keys(
Origin::signed(1),
2,
1,
sufficient_proofs.clone()
));
// 1 should no longer be payable
assert!(Crowdloan::accounts_payable(&1).is_none());
// 2 should be now payable
let reward_info_2 = Crowdloan::accounts_payable(&2).unwrap();
// The reward info should be identical
assert_eq!(reward_info, reward_info_2);
});
}
|
use {
super::*,
crate::{
app::*,
errors::ConfError,
path::PathAnchor,
},
regex::Regex,
ahash::AHashMap,
std::{
path::PathBuf,
},
};
/// Definition of how the user input should be checked
/// and maybe parsed to provide the arguments used
/// for execution or description.
#[derive(Debug)]
pub struct InvocationParser {
/// pattern of how the command is supposed to be typed in the input
pub invocation_pattern: VerbInvocation,
/// a regex to read the arguments in the user input
/// This regex declares named groups, with the name being the
/// name of the replacement variable (this implies that an
/// invocation name's characters are [_0-9a-zA-Z.\[\]])
args_parser: Option<Regex>,
/// whether the path, when non absolute, should be interpreted
/// as relative to the closest directory (which may be the selection)
/// or to the parent of the selection
pub arg_anchor: PathAnchor,
/// contain the type of selection in case there's only one arg
/// and it's a path (when it's not None, the user can type ctrl-P
/// to select the argument in another panel)
pub arg_selection_type: Option<SelectionType>,
}
impl InvocationParser {
pub fn new(
invocation_str: &str,
) -> Result<Self, ConfError> {
let invocation_pattern = VerbInvocation::from(invocation_str);
let mut args_parser = None;
let mut arg_selection_type = None;
let mut arg_anchor = PathAnchor::Unspecified;
if let Some(args) = &invocation_pattern.args {
let spec = GROUP.replace_all(args, r"(?P<$1>.+)");
let spec = format!("^{}$", spec);
args_parser = match Regex::new(&spec) {
Ok(regex) => Some(regex),
Err(_) => {
return Err(ConfError::InvalidVerbInvocation { invocation: spec });
}
};
if let Some(group) = GROUP.find(args) {
if group.start() == 0 && group.end() == args.len() {
// there's one group, covering the whole args
arg_selection_type = Some(SelectionType::Any);
let group_str = group.as_str();
if group_str.ends_with("path-from-parent}") {
arg_anchor = PathAnchor::Parent;
} else if group_str.ends_with("path-from-directory}") {
arg_anchor = PathAnchor::Directory;
}
}
}
}
Ok(Self {
invocation_pattern,
args_parser,
arg_anchor,
arg_selection_type,
})
}
pub fn name(&self) -> &str {
&self.invocation_pattern.name
}
/// Assuming the verb has been matched, check whether the arguments
/// are OK according to the regex. Return none when there's no problem
/// and return the error to display if arguments don't match
pub fn check_args(
&self,
invocation: &VerbInvocation,
_other_path: &Option<PathBuf>,
) -> Option<String> {
match (&invocation.args, &self.args_parser) {
(None, None) => None,
(None, Some(ref regex)) => {
if regex.is_match("") {
None
} else {
Some(self.invocation_pattern.to_string_for_name(&invocation.name))
}
}
(Some(ref s), Some(ref regex)) => {
if regex.is_match(s) {
None
} else {
Some(self.invocation_pattern.to_string_for_name(&invocation.name))
}
}
(Some(_), None) => Some(format!("{} doesn't take arguments", invocation.name)),
}
}
pub fn parse(&self, args: &str) -> Option<AHashMap<String, String>> {
self.args_parser.as_ref()
.map(|r| {
let mut map = AHashMap::default();
if let Some(input_cap) = r.captures(args) {
for name in r.capture_names().flatten() {
if let Some(c) = input_cap.name(name) {
map.insert(name.to_string(), c.as_str().to_string());
}
}
}
map
})
}
}
|
/**
* author: KBuild<qwer7995@gmail.com>
* desc: file save example
*/
#![feature(io)] // use old_io
#![feature(path)] // use file path
#![feature(core)] // use as_slice
use std::old_io::{File, Append, ReadWrite};
use std::old_io::stdin;
use std::str::FromStr;
struct Book {
name : String,
cost : u32,
}
impl Book {
fn new(_name: String, _cost: u32) -> Book{
Book{ name : _name, cost : _cost}
}
fn get_name(&self) -> &String {
&self.name
}
fn get_cost(&self) -> u32 {
self.cost
}
fn to_string(&self) -> String {
let mut ret = String::new();
ret.push_str(self.name.as_slice());
ret.push_str(",");
ret.push_str(self.cost.to_string().as_slice());
ret
}
}
fn main() {
let p = Path::new("data.txt");
let mut file = match File::open_mode(&p, Append, ReadWrite) {
Ok(f) => f,
Err(e) => panic!("file error: {}", e),
};
print!("Input Book's name : ");
let inputn = stdin().read_line().ok().expect("Fail to read line");
let name: String = FromStr::from_str(inputn.trim()).unwrap();
print!("Input Book's cost : ");
let inputc = stdin().read_line().ok().expect("Fail to read line");
let cost: u32 = FromStr::from_str(inputc.trim()).unwrap();
let book = Book::new(name, cost);
println!("{}, {} saved", book.get_name(), book.get_cost());
file.write_str(book.to_string().as_slice());
file.write_str("\n");
/*
let book1 = Book::new("옥상의 민들레꽃", 10000);
let book2 = Book::new("동의보감", 300000);
file.write_str(book1.to_string().as_slice());
file.write_str("\n");
file.write_str(book2.to_string().as_slice());
file.write_str("\n");
*/
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::seq::*;
use super::super::common::*;
use super::super::linux_def::*;
pub trait IOReader {
fn Read(&mut self, buf: &mut [u8]) -> Result<i64>;
}
pub trait IORead {
fn IORead(&mut self, buf: &mut [IoVec]) -> Result<i64>;
}
pub trait IOWriter {
fn Write(&mut self, buf: &[u8]) -> Result<i64>;
}
pub trait IOWrite {
fn IOWrite(&mut self, buf: &[IoVec]) -> Result<i64>;
}
pub trait IOReaderAt {
fn ReadAt(&mut self, buf: &mut [u8], off: i64) -> Result<i64>;
}
pub trait IOReadAt {
fn IOReadAt(&mut self, buf: &mut [IoVec], off: u64) -> Result<i64>;
}
pub trait IOWriterAt {
fn WriteAt(&mut self, buf: &[u8], off: i64) -> Result<i64>;
}
pub trait IOWriteAt {
fn IOWriteAt(&mut self, buf: &[IoVec], off: u64) -> Result<i64>;
}
pub trait BlockReader {
fn ReadToBlocks(&mut self, dsts: BlockSeq) -> Result<i64>;
}
pub trait BlockWriter {
fn WriteFromBlocks(&mut self, srcs: BlockSeq) -> Result<i64>;
}
pub fn ReadFullToBlocks(r: &mut BlockReader, dsts: BlockSeq) -> Result<i64> {
let mut done = 0;
let mut dsts = dsts;
while !dsts.IsEmpty() {
let n = r.ReadToBlocks(dsts)?;
done += n;
dsts = dsts.DropFirst(n as u64);
}
return Ok(done);
}
pub fn WriteFullFromBlocks(w: &mut BlockWriter, srcs: BlockSeq) -> Result<i64> {
let mut done = 0;
let mut srcs = srcs;
while !srcs.IsEmpty() {
let n = w.WriteFromBlocks(srcs)?;
if n == 0 {
return Ok(done);
}
done += n;
srcs = srcs.DropFirst(n as u64);
}
return Ok(done);
}
pub struct BlockSeqReader(pub BlockSeq);
impl BlockReader for BlockSeqReader {
fn ReadToBlocks(&mut self, dsts: BlockSeq) -> Result<i64> {
let n = BlockSeq::Copy(dsts, self.0);
self.0 = self.0.DropFirst(n as u64);
return Ok(n);
}
}
pub struct BlockSeqWriter(pub BlockSeq);
impl BlockWriter for BlockSeqWriter {
fn WriteFromBlocks(&mut self, srcs: BlockSeq) -> Result<i64> {
let n = BlockSeq::Copy(self.0, srcs);
self.0 = self.0.DropFirst(n as u64);
return Ok(n);
}
}
pub struct ToIOReader<'a> {
pub reader: &'a mut BlockReader,
}
impl<'a> IOReader for ToIOReader<'a> {
fn Read(&mut self, dst: &mut [u8]) -> Result<i64> {
let b = IoVec::NewFromSlice(dst);
let seq = BlockSeq::NewFromBlock(b);
let n = self.reader.ReadToBlocks(seq)?;
return Ok(n)
}
}
pub struct ToIOWriter<'a> {
pub writer: &'a mut BlockWriter,
}
impl<'a> IOWriter for ToIOWriter<'a> {
fn Write(&mut self, src: &[u8]) -> Result<i64> {
let b = IoVec::NewFromSlice(src);
let seq = BlockSeq::NewFromBlock(b);
let n = WriteFullFromBlocks(self.writer, seq)?;
return Ok(n)
}
}
pub struct FromIOReader<'a> {
pub reader: &'a mut IOReader
}
impl<'a> BlockReader for FromIOReader<'a> {
fn ReadToBlocks(&mut self, dsts: BlockSeq) -> Result<i64> {
let mut done = 0;
let mut dsts = dsts;
while !dsts.IsEmpty() {
let mut dst = dsts.Head();
dsts = dsts.Tail();
let slice = dst.ToSliceMut();
if slice.len() == 0 {
continue;
}
let cnt = self.reader.Read(slice)?;
if cnt == 0 {
return Ok(done)
}
done += cnt;
}
Ok(done)
}
}
pub struct FromIOWriter<'a> {
pub writer: &'a mut IOWriter
}
impl<'a> BlockWriter for FromIOWriter<'a> {
fn WriteFromBlocks(&mut self, srcs: BlockSeq) -> Result<i64> {
let mut done = 0;
let mut srcs = srcs;
while !srcs.IsEmpty() {
let src = srcs.Head();
srcs = srcs.Tail();
let slice = src.ToSlice();
if slice.len() == 0 {
continue;
}
let cnt = self.writer.Write(slice)?;
if cnt == 0 {
return Ok(done)
}
done += cnt;
}
Ok(done)
}
}
pub struct FromIOReaderAt<'a> {
pub reader: &'a mut IOReaderAt,
pub offset: i64,
}
impl<'a> BlockReader for FromIOReaderAt<'a> {
fn ReadToBlocks(&mut self, dsts: BlockSeq) -> Result<i64> {
let mut done = 0;
let mut dsts = dsts;
while !dsts.IsEmpty() {
let mut dst = dsts.Head();
dsts = dsts.Tail();
let slice = dst.ToSliceMut();
if slice.len() == 0 {
continue;
}
let cnt = self.reader.ReadAt(slice, self.offset)?;
self.offset += cnt;
if cnt == 0 {
return Ok(done)
}
done += cnt;
}
Ok(done)
}
}
pub struct FromIOWriterAt<'a> {
pub writer: &'a mut IOWriterAt,
pub offset: i64,
}
impl<'a> BlockWriter for FromIOWriterAt<'a> {
fn WriteFromBlocks(&mut self, srcs: BlockSeq) -> Result<i64> {
let mut done = 0;
let mut srcs = srcs;
while !srcs.IsEmpty() {
let src = srcs.Head();
srcs = srcs.Tail();
let slice = src.ToSlice();
if slice.len() == 0 {
continue;
}
let cnt = self.writer.WriteAt(slice, self.offset)?;
self.offset += cnt;
if cnt == 0 {
return Ok(done)
}
done += cnt;
}
Ok(done)
}
} |
use std::env;
fn main() {
let path = env::current_dir().unwrap();
let mut pir_cpp = path.clone();
pir_cpp.push("sealpir/pir.cpp");
let mut pir_server = path.clone();
pir_server.push("sealpir/pir_server.cpp");
let mut pir_client = path.clone();
pir_client.push("sealpir/pir_client.cpp");
let mut pir_bindings_file = path.clone();
pir_bindings_file.push("sealpir-bindings/pir_rust.cpp");
let mut pir_bindings = path.clone();
pir_bindings.push("sealpir-bindings");
let mut sealpir_dir = path.clone();
sealpir_dir.push("sealpir");
let mut seal_dir = path;
seal_dir.push("deps/SEAL_2.3.1/SEAL/");
cc::Build::new()
.file(pir_cpp)
.file(pir_server)
.file(pir_client)
.file(pir_bindings_file)
.include(pir_bindings)
.include(sealpir_dir)
.include(seal_dir.clone())
.flag("-Wno-unknown-pragmas")
.flag("-Wno-sign-compare")
.flag("-Wno-unused-parameter")
.flag("-std=c++17")
.flag("-fopenmp")
.pic(true)
.cpp(true)
.compile("libsealpir.a");
// Compile and link SEAL
let dst = cmake::Config::new(seal_dir)
.define("CMAKE_BUILD_TYPE", "Release")
.define("CMAKE_POSITION_INDEPENDENT_CODE", "ON")
.build();
println!("cargo:rustc-link-search={}/lib/", dst.display());
println!("cargo:rustc-link-lib=static=seal");
}
|
mod event;
mod event_manager;
mod event_writer;
mod oot;
pub use event_manager::EventManager;
pub use event_writer::EventWriter;
|
#[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::REPORTPER {
#[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 `REPORTPER`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum REPORTPERR {
#[doc = "10 samples per report."]
_10SMPL,
#[doc = "40 samples per report."]
_40SMPL,
#[doc = "80 samples per report."]
_80SMPL,
#[doc = "120 samples per report."]
_120SMPL,
#[doc = "160 samples per report."]
_160SMPL,
#[doc = "200 samples per report."]
_200SMPL,
#[doc = "240 samples per report."]
_240SMPL,
#[doc = "280 samples per report."]
_280SMPL,
}
impl REPORTPERR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
REPORTPERR::_10SMPL => 0,
REPORTPERR::_40SMPL => 1,
REPORTPERR::_80SMPL => 2,
REPORTPERR::_120SMPL => 3,
REPORTPERR::_160SMPL => 4,
REPORTPERR::_200SMPL => 5,
REPORTPERR::_240SMPL => 6,
REPORTPERR::_280SMPL => 7,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> REPORTPERR {
match value {
0 => REPORTPERR::_10SMPL,
1 => REPORTPERR::_40SMPL,
2 => REPORTPERR::_80SMPL,
3 => REPORTPERR::_120SMPL,
4 => REPORTPERR::_160SMPL,
5 => REPORTPERR::_200SMPL,
6 => REPORTPERR::_240SMPL,
7 => REPORTPERR::_280SMPL,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `_10SMPL`"]
#[inline]
pub fn is_10smpl(&self) -> bool {
*self == REPORTPERR::_10SMPL
}
#[doc = "Checks if the value of the field is `_40SMPL`"]
#[inline]
pub fn is_40smpl(&self) -> bool {
*self == REPORTPERR::_40SMPL
}
#[doc = "Checks if the value of the field is `_80SMPL`"]
#[inline]
pub fn is_80smpl(&self) -> bool {
*self == REPORTPERR::_80SMPL
}
#[doc = "Checks if the value of the field is `_120SMPL`"]
#[inline]
pub fn is_120smpl(&self) -> bool {
*self == REPORTPERR::_120SMPL
}
#[doc = "Checks if the value of the field is `_160SMPL`"]
#[inline]
pub fn is_160smpl(&self) -> bool {
*self == REPORTPERR::_160SMPL
}
#[doc = "Checks if the value of the field is `_200SMPL`"]
#[inline]
pub fn is_200smpl(&self) -> bool {
*self == REPORTPERR::_200SMPL
}
#[doc = "Checks if the value of the field is `_240SMPL`"]
#[inline]
pub fn is_240smpl(&self) -> bool {
*self == REPORTPERR::_240SMPL
}
#[doc = "Checks if the value of the field is `_280SMPL`"]
#[inline]
pub fn is_280smpl(&self) -> bool {
*self == REPORTPERR::_280SMPL
}
}
#[doc = "Values that can be written to the field `REPORTPER`"]
pub enum REPORTPERW {
#[doc = "10 samples per report."]
_10SMPL,
#[doc = "40 samples per report."]
_40SMPL,
#[doc = "80 samples per report."]
_80SMPL,
#[doc = "120 samples per report."]
_120SMPL,
#[doc = "160 samples per report."]
_160SMPL,
#[doc = "200 samples per report."]
_200SMPL,
#[doc = "240 samples per report."]
_240SMPL,
#[doc = "280 samples per report."]
_280SMPL,
}
impl REPORTPERW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
REPORTPERW::_10SMPL => 0,
REPORTPERW::_40SMPL => 1,
REPORTPERW::_80SMPL => 2,
REPORTPERW::_120SMPL => 3,
REPORTPERW::_160SMPL => 4,
REPORTPERW::_200SMPL => 5,
REPORTPERW::_240SMPL => 6,
REPORTPERW::_280SMPL => 7,
}
}
}
#[doc = r" Proxy"]
pub struct _REPORTPERW<'a> {
w: &'a mut W,
}
impl<'a> _REPORTPERW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: REPORTPERW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "10 samples per report."]
#[inline]
pub fn _10smpl(self) -> &'a mut W {
self.variant(REPORTPERW::_10SMPL)
}
#[doc = "40 samples per report."]
#[inline]
pub fn _40smpl(self) -> &'a mut W {
self.variant(REPORTPERW::_40SMPL)
}
#[doc = "80 samples per report."]
#[inline]
pub fn _80smpl(self) -> &'a mut W {
self.variant(REPORTPERW::_80SMPL)
}
#[doc = "120 samples per report."]
#[inline]
pub fn _120smpl(self) -> &'a mut W {
self.variant(REPORTPERW::_120SMPL)
}
#[doc = "160 samples per report."]
#[inline]
pub fn _160smpl(self) -> &'a mut W {
self.variant(REPORTPERW::_160SMPL)
}
#[doc = "200 samples per report."]
#[inline]
pub fn _200smpl(self) -> &'a mut W {
self.variant(REPORTPERW::_200SMPL)
}
#[doc = "240 samples per report."]
#[inline]
pub fn _240smpl(self) -> &'a mut W {
self.variant(REPORTPERW::_240SMPL)
}
#[doc = "280 samples per report."]
#[inline]
pub fn _280smpl(self) -> &'a mut W {
self.variant(REPORTPERW::_280SMPL)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 7;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:2 - Number of samples to generate an EVENT_REPORTRDY."]
#[inline]
pub fn reportper(&self) -> REPORTPERR {
REPORTPERR::_from({
const MASK: u8 = 7;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:2 - Number of samples to generate an EVENT_REPORTRDY."]
#[inline]
pub fn reportper(&mut self) -> _REPORTPERW {
_REPORTPERW { w: self }
}
}
|
use itertools::Itertools;
use std::{
collections::{HashMap, HashSet, VecDeque},
io::{self, BufRead},
iter,
};
type Maze = HashMap<Point, Tile>;
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
struct Point(isize, isize);
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
enum Tile {
Wall,
Floor,
}
fn parse_input() -> (Maze, Vec<(usize, Point)>) {
let stdin = io::stdin();
let mut maze = Maze::new();
let mut points = Vec::new();
for (y, line) in stdin.lock().lines().enumerate() {
for (x, tile) in line.unwrap().chars().enumerate() {
let point = Point(x as isize, y as isize);
maze.insert(
point,
match tile {
'#' => Tile::Wall,
_ => Tile::Floor,
},
);
if tile.is_digit(10) {
points.push((tile.to_digit(10).unwrap() as usize, point));
}
}
}
(maze, points)
}
fn neighbours(p: Point) -> impl Iterator<Item = Point> {
let (x, y) = (p.0, p.1);
[(1, 0), (0, -1), (-1, 0), (0, 1)]
.iter()
.map(move |(dx, dy)| Point(*dx + x, *dy + y))
}
fn shortest_path(maze: &Maze, from: Point, to: Point) -> usize {
let mut queue = VecDeque::new();
let mut seen = HashSet::new();
queue.push_back((from, 0));
seen.insert(from);
while let Some((next, step)) = queue.pop_front() {
if next == to {
return step;
}
for neighbour in neighbours(next) {
if let Some(Tile::Floor) = maze.get(&neighbour) {
if !seen.contains(&neighbour) {
queue.push_back((neighbour, step + 1));
seen.insert(neighbour);
}
}
}
}
0
}
fn solve_a(maze: &Maze, points: &Vec<(usize, Point)>) -> usize {
let combinations: HashMap<(usize, usize), usize> = points
.iter()
.permutations(2)
.map(|points| {
let (i1, p1) = *points[0];
let (i2, p2) = *points[1];
((i1, i2), shortest_path(maze, p1, p2))
})
.collect();
points
.iter()
.filter(|(id, _)| *id != 0)
.map(|&(id, _)| id)
.permutations(points.len() - 1)
.map(|perm| {
(iter::once(&0usize).chain(perm.iter()))
.zip(perm.iter())
.map(|(&i1, &i2)| combinations.get(&(i1, i2)).unwrap())
.sum()
})
.min()
.unwrap()
}
fn solve_b(maze: &Maze, points: &Vec<(usize, Point)>) -> usize {
let combinations: HashMap<(usize, usize), usize> = points
.iter()
.permutations(2)
.map(|points| {
let (i1, p1) = *points[0];
let (i2, p2) = *points[1];
((i1, i2), shortest_path(maze, p1, p2))
})
.collect();
points
.iter()
.filter(|(id, _)| *id != 0)
.map(|&(id, _)| id)
.permutations(points.len() - 1)
.map(|perm| {
(iter::once(&0usize).chain(perm.iter()))
.zip(perm.iter().chain(iter::once(&0usize)))
.map(|(&i1, &i2)| combinations.get(&(i1, i2)).unwrap())
.sum()
})
.min()
.unwrap()
}
fn main() {
let (maze, points) = parse_input();
println!("{}", solve_a(&maze, &points));
println!("{}", solve_b(&maze, &points));
}
|
use core::ffi::c_void;
use core::fmt::{self, Debug};
use core::mem::transmute;
use crate::erts::process::FrameWithArguments;
use crate::erts::term::closure::Definition;
use crate::erts::term::prelude::*;
use crate::erts::ModuleFunctionArity;
use crate::Arity;
use super::ffi::ErlangResult;
#[derive(Clone)]
pub struct Frame {
definition: Definition,
module_function_arity: ModuleFunctionArity,
native: Native,
}
impl Frame {
pub fn new(module_function_arity: ModuleFunctionArity, native: Native) -> Frame {
Frame {
definition: Definition::Export {
function: module_function_arity.function,
},
module_function_arity,
native,
}
}
pub fn from_definition(
module: Atom,
definition: Definition,
arity: u8,
native: Native,
) -> Frame {
Frame {
module_function_arity: ModuleFunctionArity {
module,
function: definition.function_name(),
arity,
},
definition,
native,
}
}
pub fn module_function_arity(&self) -> ModuleFunctionArity {
self.module_function_arity
}
pub fn definition(&self) -> &Definition {
&self.definition
}
pub fn native(&self) -> Native {
self.native
}
pub fn with_arguments(&self, uses_returned: bool, arguments: &[Term]) -> FrameWithArguments {
FrameWithArguments::new(self.clone(), uses_returned, arguments)
}
}
impl Debug for Frame {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Frame")
.field("module_function_arity", &self.module_function_arity)
.field("native", &self.native)
.finish()
}
}
#[derive(Copy, Clone)]
pub enum Native {
Zero(extern "C-unwind" fn() -> ErlangResult),
One(extern "C-unwind" fn(Term) -> ErlangResult),
Two(extern "C-unwind" fn(Term, Term) -> ErlangResult),
Three(extern "C-unwind" fn(Term, Term, Term) -> ErlangResult),
Four(extern "C-unwind" fn(Term, Term, Term, Term) -> ErlangResult),
Five(extern "C-unwind" fn(Term, Term, Term, Term, Term) -> ErlangResult),
}
impl Native {
pub unsafe fn from_ptr(ptr: *const c_void, arity: Arity) -> Self {
match arity {
0 => Self::Zero(transmute::<_, extern "C-unwind" fn() -> ErlangResult>(ptr)),
1 => Self::One(transmute::<_, extern "C-unwind" fn(Term) -> ErlangResult>(
ptr,
)),
2 => Self::Two(transmute::<
_,
extern "C-unwind" fn(Term, Term) -> ErlangResult,
>(ptr)),
3 => Self::Three(transmute::<
_,
extern "C-unwind" fn(Term, Term, Term) -> ErlangResult,
>(ptr)),
4 => Self::Four(transmute::<
_,
extern "C-unwind" fn(Term, Term, Term, Term) -> ErlangResult,
>(ptr)),
5 => Self::Five(transmute::<
_,
extern "C-unwind" fn(Term, Term, Term, Term, Term) -> ErlangResult,
>(ptr)),
_ => unimplemented!(
"Converting `*const c_void` ptr with arity {} to `fn`",
arity
),
}
}
pub fn apply(&self, arguments: &[Term]) -> ErlangResult {
match self {
Self::Zero(f) => {
assert_eq!(arguments.len(), 0);
f()
}
Self::One(f) => {
assert_eq!(arguments.len(), 1);
f(arguments[0])
}
Self::Two(f) => {
assert_eq!(arguments.len(), 2);
f(arguments[0], arguments[1])
}
Self::Three(f) => {
assert_eq!(arguments.len(), 3);
f(arguments[0], arguments[1], arguments[2])
}
Self::Four(f) => {
assert_eq!(arguments.len(), 4);
f(arguments[0], arguments[1], arguments[2], arguments[3])
}
Self::Five(f) => {
assert_eq!(arguments.len(), 5);
f(
arguments[0],
arguments[1],
arguments[2],
arguments[3],
arguments[4],
)
}
}
}
pub fn arity(&self) -> Arity {
match self {
Self::Zero(_) => 0,
Self::One(_) => 1,
Self::Two(_) => 2,
Self::Three(_) => 3,
Self::Four(_) => 4,
Self::Five(_) => 5,
}
}
pub fn ptr(&self) -> *const c_void {
match *self {
Self::Zero(ptr) => ptr as *const c_void,
Self::One(ptr) => ptr as *const c_void,
Self::Two(ptr) => ptr as *const c_void,
Self::Three(ptr) => ptr as *const c_void,
Self::Four(ptr) => ptr as *const c_void,
Self::Five(ptr) => ptr as *const c_void,
}
}
}
impl Debug for Native {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:x}/{}", self.ptr() as usize, self.arity())
}
}
|
pub const TEXT_START_ADDR: i32 = 0x00400000;
pub const R_TYPES: [&str; 5] = ["add", "and", "or", "nor", "sub"];
pub const I_TYPES: [&str; 4] = ["addi", "andi", "ori", "li"];
/*
pub const REGISTER_IDENTIFIERS: [&str; 32] = ["$zero",
"$at",
"$v0",
"$v1",
"$a0",
"$a1",
"$a2",
"$a3",
"$t0",
"$t1",
"$t2",
"$t3",
"$t4",
"$t5",
"$t6",
"$t7",
"$s0",
"$s1",
"$s2",
"$s3",
"$s4",
"$s5",
"$s6",
"$s7",
"$t8",
"$t9",
"$k1",
"$k2",
"$gp",
"$sp",
"$fp",
"$ra",
];
*/
|
#[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::PRUART {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_PRUART_R0R {
bits: bool,
}
impl SYSCTL_PRUART_R0R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_PRUART_R0W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_PRUART_R0W<'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 &= !(1 << 0);
self.w.bits |= ((value as u32) & 1) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_PRUART_R1R {
bits: bool,
}
impl SYSCTL_PRUART_R1R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_PRUART_R1W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_PRUART_R1W<'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 &= !(1 << 1);
self.w.bits |= ((value as u32) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_PRUART_R2R {
bits: bool,
}
impl SYSCTL_PRUART_R2R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_PRUART_R2W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_PRUART_R2W<'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 &= !(1 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_PRUART_R3R {
bits: bool,
}
impl SYSCTL_PRUART_R3R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_PRUART_R3W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_PRUART_R3W<'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 &= !(1 << 3);
self.w.bits |= ((value as u32) & 1) << 3;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_PRUART_R4R {
bits: bool,
}
impl SYSCTL_PRUART_R4R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_PRUART_R4W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_PRUART_R4W<'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 &= !(1 << 4);
self.w.bits |= ((value as u32) & 1) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_PRUART_R5R {
bits: bool,
}
impl SYSCTL_PRUART_R5R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_PRUART_R5W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_PRUART_R5W<'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 &= !(1 << 5);
self.w.bits |= ((value as u32) & 1) << 5;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_PRUART_R6R {
bits: bool,
}
impl SYSCTL_PRUART_R6R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_PRUART_R6W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_PRUART_R6W<'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 &= !(1 << 6);
self.w.bits |= ((value as u32) & 1) << 6;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_PRUART_R7R {
bits: bool,
}
impl SYSCTL_PRUART_R7R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_PRUART_R7W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_PRUART_R7W<'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 &= !(1 << 7);
self.w.bits |= ((value as u32) & 1) << 7;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - UART Module 0 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r0(&self) -> SYSCTL_PRUART_R0R {
let bits = ((self.bits >> 0) & 1) != 0;
SYSCTL_PRUART_R0R { bits }
}
#[doc = "Bit 1 - UART Module 1 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r1(&self) -> SYSCTL_PRUART_R1R {
let bits = ((self.bits >> 1) & 1) != 0;
SYSCTL_PRUART_R1R { bits }
}
#[doc = "Bit 2 - UART Module 2 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r2(&self) -> SYSCTL_PRUART_R2R {
let bits = ((self.bits >> 2) & 1) != 0;
SYSCTL_PRUART_R2R { bits }
}
#[doc = "Bit 3 - UART Module 3 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r3(&self) -> SYSCTL_PRUART_R3R {
let bits = ((self.bits >> 3) & 1) != 0;
SYSCTL_PRUART_R3R { bits }
}
#[doc = "Bit 4 - UART Module 4 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r4(&self) -> SYSCTL_PRUART_R4R {
let bits = ((self.bits >> 4) & 1) != 0;
SYSCTL_PRUART_R4R { bits }
}
#[doc = "Bit 5 - UART Module 5 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r5(&self) -> SYSCTL_PRUART_R5R {
let bits = ((self.bits >> 5) & 1) != 0;
SYSCTL_PRUART_R5R { bits }
}
#[doc = "Bit 6 - UART Module 6 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r6(&self) -> SYSCTL_PRUART_R6R {
let bits = ((self.bits >> 6) & 1) != 0;
SYSCTL_PRUART_R6R { bits }
}
#[doc = "Bit 7 - UART Module 7 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r7(&self) -> SYSCTL_PRUART_R7R {
let bits = ((self.bits >> 7) & 1) != 0;
SYSCTL_PRUART_R7R { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - UART Module 0 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r0(&mut self) -> _SYSCTL_PRUART_R0W {
_SYSCTL_PRUART_R0W { w: self }
}
#[doc = "Bit 1 - UART Module 1 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r1(&mut self) -> _SYSCTL_PRUART_R1W {
_SYSCTL_PRUART_R1W { w: self }
}
#[doc = "Bit 2 - UART Module 2 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r2(&mut self) -> _SYSCTL_PRUART_R2W {
_SYSCTL_PRUART_R2W { w: self }
}
#[doc = "Bit 3 - UART Module 3 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r3(&mut self) -> _SYSCTL_PRUART_R3W {
_SYSCTL_PRUART_R3W { w: self }
}
#[doc = "Bit 4 - UART Module 4 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r4(&mut self) -> _SYSCTL_PRUART_R4W {
_SYSCTL_PRUART_R4W { w: self }
}
#[doc = "Bit 5 - UART Module 5 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r5(&mut self) -> _SYSCTL_PRUART_R5W {
_SYSCTL_PRUART_R5W { w: self }
}
#[doc = "Bit 6 - UART Module 6 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r6(&mut self) -> _SYSCTL_PRUART_R6W {
_SYSCTL_PRUART_R6W { w: self }
}
#[doc = "Bit 7 - UART Module 7 Peripheral Ready"]
#[inline(always)]
pub fn sysctl_pruart_r7(&mut self) -> _SYSCTL_PRUART_R7W {
_SYSCTL_PRUART_R7W { w: self }
}
}
|
pub fn run(path: &str) {
let freqs = parse_input(path);
let part_1_solution = part_1(&freqs);
println!("Day 1, part 1: {}", part_1_solution);
let part_2_solution = part_2(&freqs);
println!("Day 1, part 2: {}", part_2_solution);
}
pub fn parse_input(path: &str) -> Vec<i32> {
let data = std::fs::read_to_string(path).expect("Couldn't read data file");
data.lines()
.map(|f| f.parse().expect("Bad frequency"))
.collect()
}
pub fn part_1(frequencies: &[i32]) -> i32 {
frequencies.iter().sum()
}
#[test]
fn day_1_test() {
assert_eq!(part_1(&[1, -2, 3, 1]), 3);
assert_eq!(part_1(&[1, 1, 1]), 3);
assert_eq!(part_1(&[1, 1, -2]), 0);
assert_eq!(part_1(&[-1, -2, -3]), -6);
}
use std::collections::HashSet;
pub fn part_2(frequencies: &[i32]) -> i32 {
let mut seen_frequencies = HashSet::new();
let mut current_freq = 0;
loop {
for f in frequencies {
seen_frequencies.insert(current_freq);
current_freq += f;
if seen_frequencies.contains(¤t_freq) {
return current_freq;
}
}
}
}
#[test]
fn day_1_part_2_test() {
assert_eq!(part_2(&[1, -2, 3, 1]), 2);
assert_eq!(part_2(&[1, -1]), 0);
assert_eq!(part_2(&[3, 3, 4, -2, -4]), 10);
assert_eq!(part_2(&[-6, 3, 8, 5, -6]), 5);
assert_eq!(part_2(&[7, 7, -2, -7, -4]), 14);
}
|
use crate::todo;
use crate::ui;
use crate::database;
use crate::key_binding;
use termion::{event::Key, raw::IntoRawMode, input::TermRead};
use tui::widgets::{Block, Borders, List, ListItem, Paragraph};
use tui::style::{Color, Modifier, Style};
use tui::layout::{Layout, Constraint, Direction};
use tui::text::{Span, Spans};
use std::io::{self, Read};
use todo::{TodoData};
use std::error::Error;
use tui::Terminal;
use tui::backend::TermionBackend;
use ui::todolist::TodoList;
pub fn show_list(
mut todo_list: TodoList,
db_filename: &str,
workspace_name: &str
) -> Result<(), Box<dyn Error>> {
let stdout = io::stdout()
.into_raw_mode()
.expect("Unable to listen input on stdout");
let backend = TermionBackend::new(stdout);
let mut terminal = Terminal::new(backend).expect("Unable to select terminal");
let mut asi = termion::async_stdin();
// Clear current terminal before drawing the app to avoid conflicts
terminal
.clear()
.expect("Error clearing terminal");
loop {
terminal.draw(|f| {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(
[
Constraint::Max(99),
Constraint::Max(1),
]
.as_ref(),
)
.split(f.size());
// Iterate through all elements in the `items` app and append some debug text to it.
let items: Vec<ListItem> = todo_list
.items
.items
.iter()
.map(|i| {
let content = Span::from(String::from(i.title.as_str()));
let checkbox = match i.done {
true => Span::from("[\u{2714}] "),
false => Span::from("[ ] ")
};
let spans = Spans::from(vec![checkbox, content]);
ListItem::new(spans).style(Style::default().fg(Color::Black).bg(Color::White))
})
.collect();
// Create a List from all list items and highlight the selected one
let items = List::new(items)
.block(Block::default().borders(Borders::ALL).title("TODO"))
.highlight_style(
Style::default()
.bg(Color::LightGreen)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol(">> ");
f.render_stateful_widget(items, chunks[0], &mut todo_list.items.state);
let workspace_text = Spans::from(
Span::styled(
format!("Workspace: {}{}", workspace_name, get_key_bindings_string()),
Style::default().add_modifier(Modifier::ITALIC).add_modifier(Modifier::BOLD)
),
);
let workspace_bar = Paragraph::new(workspace_text)
.block(
Block::default()
.style(
Style::default()
.bg(Color::White)
.fg(Color::Black)
.add_modifier(Modifier::BOLD)
),
);
f.render_widget(workspace_bar, chunks[1]);
})?;
for k in asi.by_ref().keys() {
match k.unwrap() {
Key::Char('q') => {
terminal.clear()?;
// Save current todo list before exit
database::save(&TodoData {
todos: todo_list.items.items
}, &db_filename);
return Ok(());
},
Key::Up => {
todo_list.items.previous()
},
Key::Down => {
todo_list.items.next()
},
Key::Char('t') => {
&todo_list.items.items[todo_list.items.state.selected().unwrap()].toggle();
},
Key::Char('d') => {
todo_list.items.remove()
},
_ => (),
}
}
}
}
fn get_key_bindings_string() -> String {
let mut key_bindings_string = String::from("");
key_binding::get_key_bindings()
.into_iter()
.for_each(|f| {
let key_binding_string = format!(" [{}] {}", f.key, f.description);
key_bindings_string.push_str(&key_binding_string);
});
key_bindings_string
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.