text stringlengths 8 4.13M |
|---|
extern crate wasm_bindgen;
pub mod factor;
pub mod macros;
pub mod prime;
pub mod util;
|
use eosio::*;
use lazy_static::lazy_static;
pub const ACTIVE_PERMISSION: PermissionName = PermissionName::new(n!("active"));
pub const TOKEN_ACCOUNT: AccountName = AccountName::new(n!("eosio.token"));
pub const RAM_ACCOUNT: AccountName = AccountName::new(n!("eosio.ram"));
pub const RAMFEE_ACCOUNT: AccountName = AccountName::new(n!("eosio.ramfee"));
pub const STAKE_ACCOUNT: AccountName = AccountName::new(n!("eosio.stake"));
pub const BPAY_ACCOUNT: AccountName = AccountName::new(n!("eosio.bpay"));
pub const VPAY_ACCOUNT: AccountName = AccountName::new(n!("eosio.vpay"));
pub const NAMES_ACCOUNT: AccountName = AccountName::new(n!("eosio.names"));
pub const SAVING_ACCOUNT: AccountName = AccountName::new(n!("eosio.saving"));
pub const REX_ACCOUNT: AccountName = AccountName::new(n!("eosio.rex"));
pub const NULL_ACCOUNT: AccountName = AccountName::new(n!("eosio.null"));
pub const REX_SYMBOL: Symbol = Symbol::new(s!(4, "REX"));
lazy_static! {
pub static ref SELF: AccountName = eosio_cdt::current_receiver();
}
mod core;
pub use self::core::*;
mod delegate_bandwidth;
pub use self::delegate_bandwidth::*;
mod exchange_state;
pub use self::exchange_state::*;
mod name_bidding;
pub use self::name_bidding::*;
mod native;
pub use self::native::*;
mod producer_pay;
pub use self::producer_pay::*;
mod rex;
pub use self::rex::*;
mod voting;
pub use self::voting::*;
eosio_cdt::abi!(
setram,
setramrate,
setparams,
setpriv,
setalimits,
setacctram,
setacctnet,
activate,
rmvproducer,
updtrevision,
setinflation,
init
);
|
use std::fmt::{Display, Formatter};
use std::fmt;
use std::iter::Product;
use std::ops::{Add, Div, Mul, Sub};
use crate::structs::dim::Dim::Size;
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum Dim {
Any,
Size(usize),
}
impl Display for Dim {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let res = match self {
Dim::Any => String::from("Any"),
Dim::Size(v) => format!("{}", v)
};
write!(f, "{}", res)
}
}
impl Dim {
pub fn unwrap(&self) -> usize {
match self {
Dim::Any => panic!(),
Dim::Size(value) => value.clone()
}
}
pub fn check(&self, offset: usize) {
match self {
Dim::Any => {}
Dim::Size(size) => assert!(offset < *size)
}
}
}
impl Product for Dim {
fn product<I: Iterator<Item=Dim>>(iter: I) -> Self {
iter.fold(Size(1), |a, b| a * b)
}
}
impl Add for Dim {
type Output = Dim;
fn add(self, rhs: Self) -> Self::Output {
match self {
Dim::Any => Dim::Any,
Size(v1) => {
match rhs {
Dim::Any => Dim::Any,
Size(v2) => Size(v1 + v2)
}
}
}
}
}
impl Sub for Dim {
type Output = Dim;
fn sub(self, rhs: Self) -> Self::Output {
match self {
Dim::Any => Dim::Any,
Size(v1) => {
match rhs {
Dim::Any => Dim::Any,
Size(v2) => Size(v1 - v2)
}
}
}
}
}
impl Mul for Dim {
type Output = Dim;
fn mul(self, rhs: Self) -> Self::Output {
match self {
Dim::Any => Dim::Any,
Size(v1) => {
match rhs {
Dim::Any => Dim::Any,
Size(v2) => {
Size(v1 * v2)
}
}
}
}
}
}
impl Div for Dim {
type Output = Dim;
fn div(self, rhs: Self) -> Self::Output {
match self {
Dim::Any => Dim::Any,
Size(v1) => {
match rhs {
Dim::Any => Dim::Any,
Size(v2) => Size(v1 / v2)
}
}
}
}
}
impl Sub<Dim> for usize {
type Output = Dim;
fn sub(self, rhs: Dim) -> Self::Output {
match rhs {
Dim::Any => Dim::Any,
Size(v) => {
Size(self - v)
}
}
}
}
impl Div<Dim> for usize {
type Output = Dim;
fn div(self, rhs: Dim) -> Self::Output {
match rhs {
Dim::Any => Dim::Any,
Size(v) => {
Size(self / v)
}
}
}
}
|
#![allow(clippy::comparison_chain)]
#![allow(clippy::collapsible_if)]
use std::cmp::Reverse;
use std::cmp::{max, min};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt::Debug;
use itertools::Itertools;
use whiteread::parse_line;
const ten97: usize = 1000_000_007;
/// 2の逆元 mod ten97.割りたいときに使う
const inv2ten97: u128 = 500_000_004;
fn main() {
let n: usize = parse_line().unwrap();
let mut lrlr: Vec<(usize, usize)> = vec![];
for _ in 0..n {
let lr: (usize, usize) = parse_line().unwrap();
lrlr.push(lr);
}
let mut ans = 0.0;
for i in 0..n {
for j in i + 1..n {
let ilr = lrlr[i];
let jlr = lrlr[j];
let all = (1 + ilr.1 - ilr.0) * (1 + jlr.1 - jlr.0);
let mut tmp = 0;
for ii in ilr.0.max(jlr.0 + 1)..=ilr.1 {
tmp += 1 + (ii - 1).min(jlr.1) - jlr.0;
}
ans += tmp as f64 / all as f64;
}
}
println!("{}", ans);
}
|
pub struct RenderEngine {}
|
use std::marker::PhantomData;
use std::{path::Path, sync::Arc};
use legion::world;
use nalgebra::Point3;
use nalgebra_glm::proj;
use smallvec::SmallVec;
use sourcerenderer_core::{Matrix4, Vec3, Vec4};
use sourcerenderer_core::graphics::{
BindingFrequency, BufferInfo, BufferUsage, CommandBuffer, MemoryUsage, PipelineBinding,
RenderPassBeginInfo, WHOLE_BUFFER,
};
use sourcerenderer_core::{
graphics::{
AttachmentInfo, Backend, BarrierAccess, BarrierSync, BlendInfo, Buffer, CompareFunc,
CullMode, DepthStencilAttachmentRef, DepthStencilInfo, FillMode, Format, FrontFace,
IndexFormat, InputAssemblerElement, InputRate, LoadOp, LogicOp,
PrimitiveType, RasterizerInfo, RenderPassAttachment, RenderPassAttachmentView,
RenderPassInfo, RenderpassRecordingMode, SampleCount, Scissor, ShaderInputElement,
ShaderType, StencilInfo, StoreOp, SubpassInfo, Texture, TextureDimension, TextureInfo,
TextureLayout, TextureUsage, TextureView, TextureViewInfo, VertexLayoutInfo, Viewport,
},
Platform, Vec2, Vec2I, Vec2UI,
};
use crate::renderer::drawable::View;
use crate::renderer::light::{DirectionalLight, RendererDirectionalLight};
use crate::renderer::passes::modern::gpu_scene::{DRAWABLE_CAPACITY, DRAW_CAPACITY, PART_CAPACITY};
use crate::renderer::render_path::{RenderPassParameters, SceneInfo};
use crate::renderer::renderer_scene::RendererScene;
use crate::renderer::shader_manager::{
ComputePipelineHandle, GraphicsPipelineHandle, GraphicsPipelineInfo, ShaderManager,
};
use crate::renderer::{
renderer_resources::{HistoryResourceEntry, RendererResources},
Vertex,
};
/*
TODO:
- implement multiple cascades
- filter shadows
- research shadow map ray marching (UE5)
- cache shadows of static objects and copy every frame
- point light shadows, spot light shadows
- multiple lights
*/
pub struct ShadowMapPass<P: Platform> {
pipeline: GraphicsPipelineHandle,
draw_prep_pipeline: ComputePipelineHandle,
shadow_map_res: u32,
cascades: SmallVec<[ShadowMapCascade; 5]>,
_marker: PhantomData<P>,
}
#[derive(Debug, Default)]
pub struct ShadowMapCascade {
pub z_min: f32,
pub z_max: f32,
_padding: [u32; 2],
pub view_proj: Matrix4
}
impl<P: Platform> ShadowMapPass<P> {
pub const SHADOW_MAP_NAME: &'static str = "ShadowMap";
pub const DRAW_BUFFER_NAME: &'static str = "ShadowMapDraws";
pub const VISIBLE_BITFIELD: &'static str = "ShadowMapVisibility";
pub fn new(
_device: &Arc<<P::GraphicsBackend as Backend>::Device>,
resources: &mut RendererResources<P::GraphicsBackend>,
_init_cmd_buffer: &mut <P::GraphicsBackend as Backend>::CommandBuffer,
shader_manager: &mut ShaderManager<P>,
) -> Self {
let shadow_map_res = 4096;
let cascades_count = 5;
resources.create_texture(
&Self::SHADOW_MAP_NAME,
&TextureInfo {
dimension: TextureDimension::Dim2DArray,
format: Format::D24,
width: shadow_map_res,
height: shadow_map_res,
depth: 1,
mip_levels: 1,
array_length: cascades_count,
samples: SampleCount::Samples1,
usage: TextureUsage::DEPTH_STENCIL | TextureUsage::SAMPLED,
supports_srgb: false,
},
false,
);
resources.create_buffer(
&Self::DRAW_BUFFER_NAME,
&BufferInfo {
size: 4 + 20 * PART_CAPACITY as usize,
usage: BufferUsage::STORAGE | BufferUsage::INDIRECT,
},
MemoryUsage::VRAM,
false,
);
resources.create_buffer(
&Self::VISIBLE_BITFIELD,
&BufferInfo {
size: ((DRAWABLE_CAPACITY as usize + 31) / 32) * 4,
usage: BufferUsage::STORAGE | BufferUsage::INDIRECT,
},
MemoryUsage::VRAM,
false,
);
let vs_path = Path::new("shaders").join(Path::new("shadow_map_bindless.vert.spv"));
let pipeline = shader_manager.request_graphics_pipeline(
&GraphicsPipelineInfo {
vs: vs_path.to_str().unwrap(),
fs: None,
vertex_layout: VertexLayoutInfo {
shader_inputs: &[ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 0,
semantic_name_d3d: "pos".to_string(),
semantic_index_d3d: 0,
offset: 0,
format: Format::RGB32Float,
}],
input_assembler: &[InputAssemblerElement {
binding: 0,
input_rate: InputRate::PerVertex,
stride: std::mem::size_of::<Vertex>(),
}],
},
rasterizer: RasterizerInfo {
fill_mode: FillMode::Fill,
cull_mode: CullMode::Back,
front_face: FrontFace::CounterClockwise,
sample_count: SampleCount::Samples1,
},
depth_stencil: DepthStencilInfo {
depth_test_enabled: true,
depth_write_enabled: true,
depth_func: CompareFunc::Less,
stencil_enable: false,
stencil_read_mask: 0,
stencil_write_mask: 0,
stencil_front: StencilInfo::default(),
stencil_back: StencilInfo::default(),
},
blend: BlendInfo {
alpha_to_coverage_enabled: false,
logic_op_enabled: false,
logic_op: LogicOp::And,
attachments: &[],
constants: [0f32; 4],
},
primitive_type: PrimitiveType::Triangles,
},
&RenderPassInfo {
attachments: &[AttachmentInfo {
format: Format::D24,
samples: SampleCount::Samples1,
}],
subpasses: &[SubpassInfo {
input_attachments: &[],
output_color_attachments: &[],
depth_stencil_attachment: Some(DepthStencilAttachmentRef {
index: 0,
read_only: false,
}),
}],
},
0,
);
let prep_pipeline = shader_manager.request_compute_pipeline("shaders/draw_prep.comp.spv");
let mut cascades = SmallVec::<[ShadowMapCascade; 5]>::with_capacity(cascades_count as usize);
cascades.resize_with(cascades_count as usize, || ShadowMapCascade::default());
Self {
pipeline,
draw_prep_pipeline: prep_pipeline,
shadow_map_res,
cascades,
_marker: PhantomData,
}
}
pub fn calculate_cascades(&mut self, scene: &SceneInfo<'_, P::GraphicsBackend>) {
for cascade in &mut self.cascades {
*cascade = Default::default();
}
let light = scene.scene.directional_lights().first();
if light.is_none() {
return;
}
let light: &RendererDirectionalLight<<P as Platform>::GraphicsBackend> = light.unwrap();
let view = &scene.views[scene.active_view_index];
let z_min = view.near_plane;
let z_max = view.far_plane;
let lambda = 0.15f32;
let mut z_start = z_min;
for cascade_index in 0..self.cascades.len() {
let view_proj = view.proj_matrix * view.view_matrix;
let inv_camera_view_proj = view_proj.try_inverse().unwrap();
let i = cascade_index as u32 + 1u32;
let m = self.cascades.len() as u32;
let log_split = (z_min * (z_max / z_min)).powf(i as f32 / m as f32);
let uniform_split = z_min + (z_max - z_min) * (i as f32 / m as f32);
let z_end = log_split * lambda + (1.0f32 - lambda) * uniform_split;
self.cascades[cascade_index] = Self::build_cascade(light, inv_camera_view_proj, z_start, z_end, z_min, z_max, self.shadow_map_res);
z_start = z_end;
}
}
pub fn prepare(
&mut self,
cmd_buffer: &mut <P::GraphicsBackend as Backend>::CommandBuffer,
pass_params: &RenderPassParameters<'_, P>
) {
cmd_buffer.begin_label("Shadow map culling");
let draws_buffer = pass_params.resources.access_buffer(
cmd_buffer,
Self::DRAW_BUFFER_NAME,
BarrierSync::COMPUTE_SHADER,
BarrierAccess::STORAGE_WRITE,
HistoryResourceEntry::Current,
);
{
let visibility_buffer = pass_params.resources.access_buffer(
cmd_buffer,
Self::VISIBLE_BITFIELD,
BarrierSync::COMPUTE_SHADER,
BarrierAccess::STORAGE_WRITE,
HistoryResourceEntry::Current,
);
cmd_buffer.flush_barriers();
cmd_buffer.clear_storage_buffer(
&visibility_buffer,
0,
visibility_buffer.info().size / 4,
!0,
);
}
let visibility_buffer = pass_params.resources.access_buffer(
cmd_buffer,
Self::VISIBLE_BITFIELD,
BarrierSync::COMPUTE_SHADER,
BarrierAccess::STORAGE_READ,
HistoryResourceEntry::Current,
);
let pipeline = pass_params.shader_manager.get_compute_pipeline(self.draw_prep_pipeline);
cmd_buffer.set_pipeline(PipelineBinding::Compute(&pipeline));
cmd_buffer.bind_storage_buffer(
BindingFrequency::VeryFrequent,
0,
&visibility_buffer,
0,
WHOLE_BUFFER,
);
cmd_buffer.bind_storage_buffer(
BindingFrequency::VeryFrequent,
1,
&draws_buffer,
0,
WHOLE_BUFFER,
);
cmd_buffer.flush_barriers();
cmd_buffer.finish_binding();
cmd_buffer.dispatch((pass_params.scene.scene.static_drawables().len() as u32 + 63) / 64, 1, 1);
cmd_buffer.end_label();
}
pub fn execute(
&mut self,
cmd_buffer: &mut <P::GraphicsBackend as Backend>::CommandBuffer,
pass_params: &RenderPassParameters<'_, P>
) {
cmd_buffer.begin_label("Shadow map");
let light = pass_params.scene.scene.directional_lights().first();
if light.is_none() {
return;
}
let draw_buffer = pass_params.resources.access_buffer(
cmd_buffer,
Self::DRAW_BUFFER_NAME,
BarrierSync::INDIRECT,
BarrierAccess::INDIRECT_READ,
HistoryResourceEntry::Current,
);
let mut cascade_index = 0u32;
for cascade in &self.cascades {
let shadow_map = pass_params.resources.access_view(
cmd_buffer,
Self::SHADOW_MAP_NAME,
BarrierSync::EARLY_DEPTH,
BarrierAccess::DEPTH_STENCIL_READ | BarrierAccess::DEPTH_STENCIL_WRITE,
TextureLayout::DepthStencilReadWrite,
true,
&TextureViewInfo {
base_mip_level: 0,
mip_level_length: 1,
base_array_layer: cascade_index,
array_layer_length: 1,
format: None,
},
HistoryResourceEntry::Current,
);
cmd_buffer.flush_barriers();
cmd_buffer.begin_render_pass(
&RenderPassBeginInfo {
attachments: &[RenderPassAttachment {
view: RenderPassAttachmentView::DepthStencil(&shadow_map),
load_op: LoadOp::Clear,
store_op: StoreOp::Store,
}],
subpasses: &[SubpassInfo {
input_attachments: &[],
output_color_attachments: &[],
depth_stencil_attachment: Some(DepthStencilAttachmentRef {
index: 0,
read_only: false,
}),
}],
},
RenderpassRecordingMode::Commands,
);
let dsv_info = shadow_map.texture().info();
let pipeline = pass_params.shader_manager.get_graphics_pipeline(self.pipeline);
cmd_buffer.set_pipeline(PipelineBinding::Graphics(&pipeline));
cmd_buffer.set_viewports(&[Viewport {
position: Vec2::new(0.0f32, 0.0f32),
extent: Vec2::new(dsv_info.width as f32, dsv_info.height as f32),
min_depth: 0.0f32,
max_depth: 1.0f32,
}]);
cmd_buffer.set_scissors(&[Scissor {
position: Vec2I::new(0, 0),
extent: Vec2UI::new(9999, 9999),
}]);
cmd_buffer.set_vertex_buffer(pass_params.scene.vertex_buffer, 0);
cmd_buffer.set_index_buffer(pass_params.scene.index_buffer, 0, IndexFormat::U32);
cmd_buffer.upload_dynamic_data_inline(&[cascade.view_proj], ShaderType::VertexShader);
cmd_buffer.finish_binding();
cmd_buffer.draw_indexed_indirect(&draw_buffer, 4, &draw_buffer, 0, DRAW_CAPACITY, 20);
cmd_buffer.end_render_pass();
cascade_index += 1;
}
cmd_buffer.end_label();
}
pub fn build_cascade(light: &RendererDirectionalLight<P::GraphicsBackend>, inv_camera_view_proj: Matrix4, cascade_z_start: f32, cascade_z_end: f32, z_min: f32, z_max: f32, shadow_map_res: u32) -> ShadowMapCascade {
// https://www.junkship.net/News/2020/11/22/shadow-of-a-doubt-part-2
// https://github.com/BabylonJS/Babylon.js/blob/master/packages/dev/core/src/Lights/Shadows/cascadedShadowGenerator.ts
// https://alextardif.com/shadowmapping.html
// https://therealmjp.github.io/posts/shadow-maps/
// https://learn.microsoft.com/en-us/windows/win32/dxtecharts/common-techniques-to-improve-shadow-depth-maps
// https://github.com/TheRealMJP/Shadows/blob/master/Shadows/SetupShadows.hlsl
let mut world_space_frustum_corners = [Vec4::new(0f32, 0f32, 0f32, 0f32); 8];
for x in 0..2 {
for y in 0..2 {
for z in 0..2 {
let mut world_space_frustum_corner = inv_camera_view_proj * Vec4::new(
2.0f32 * (x as f32) - 1.0f32,
2.0f32 * (y as f32) - 1.0f32,
z as f32,
1.0f32
);
world_space_frustum_corner /= world_space_frustum_corner.w;
world_space_frustum_corners[z * 4 + x * 2 + y] = world_space_frustum_corner;
}
}
}
let z_range = z_max - z_min;
let start_depth = (cascade_z_start - z_min) / z_range;
let end_depth = (cascade_z_end - z_min) / z_range;
for i in 0..4 {
let corner_ray = world_space_frustum_corners[i + 4] - world_space_frustum_corners[i];
let near_corner_ray = corner_ray * start_depth;
let far_corner_ray = corner_ray * end_depth;
world_space_frustum_corners[i + 4] = world_space_frustum_corners[i] + far_corner_ray;
world_space_frustum_corners[i] = world_space_frustum_corners[i] + near_corner_ray;
}
let mut center = Vec3::new(0f32, 0f32, 0f32);
for corner in &world_space_frustum_corners {
center += corner.xyz();
}
center /= world_space_frustum_corners.len() as f32;
let mut radius = 0.0f32;
for corner in &world_space_frustum_corners {
radius = radius.max((corner.xyz() - center).magnitude());
}
let mut min = Vec3::new(-radius, -radius, -radius);
let mut max = Vec3::new(radius, radius, radius);
let mut light_view = Matrix4::look_at_lh(&Point3::from(center - light.direction), &Point3::from(center), &Vec3::new(0f32, 1f32, 0f32));
// Snap center to texel
let texels_per_unit = (shadow_map_res as f32) / (radius * 2.0f32);
let snapping_view = Matrix4::new_scaling(texels_per_unit) * light_view.clone();
let snapping_view_inv = snapping_view.try_inverse().unwrap();
let mut view_space_center = snapping_view.transform_vector(¢er);
view_space_center.x = view_space_center.x.floor();
view_space_center.y = view_space_center.y.floor();
center = snapping_view_inv.transform_vector(&view_space_center);
light_view = Matrix4::look_at_lh(&Point3::from(center - light.direction), &Point3::from(center), &Vec3::new(0f32, 1f32, 0f32));
// Snap left, right, top. bottom to texel
let world_units_per_texel = (radius * 2f32) / (shadow_map_res as f32);
min.x = (min.x / world_units_per_texel).floor() * world_units_per_texel;
min.y = (min.y / world_units_per_texel).floor() * world_units_per_texel;
max.x = (max.x / world_units_per_texel).ceil() * world_units_per_texel;
max.y = (max.y / world_units_per_texel).ceil() * world_units_per_texel;
let light_proj = nalgebra_glm::ortho_lh_zo(min.x, max.x, min.y, max.y, 0.01f32, max.z - min.z);
let light_mat = light_proj * light_view;
ShadowMapCascade {
_padding: Default::default(),
view_proj: light_mat,
z_min: cascade_z_start,
z_max: cascade_z_end
}
}
pub fn resolution(&self) -> u32 {
self.shadow_map_res
}
pub fn cascades(&self) -> &[ShadowMapCascade] {
return &self.cascades;
}
}
|
use actix_web::{FromRequest, HttpRequest, Error, http::header};
use std::sync::Arc;
use crate::error::TokenError;
use actix_web::dev::Payload;
pub struct Token {
inner: String
}
impl Token {
/// Deconstruct to an inner value
pub fn into_inner(self) -> String {
self.inner
}
}
impl AsRef<String> for Token {
fn as_ref(&self) -> &String {
&self.inner
}
}
impl std::ops::Deref for Token {
type Target = String;
fn deref(&self) -> &String {
&self.inner
}
}
impl std::ops::DerefMut for Token {
fn deref_mut(&mut self) -> &mut String {
&mut self.inner
}
}
impl From<String> for Token {
fn from(inner: String) -> Self {
Token { inner }
}
}
impl std::fmt::Debug for Token {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.inner.fmt(f)
}
}
impl std::fmt::Display for Token {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.inner.fmt(f)
}
}
impl FromRequest for Token {
type Error = Error;
type Future = Result<Self, Error>;
type Config = TokenConfig;
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
let error_handler = req
.app_data::<Self::Config>()
.map(|c| c.ehandler.clone())
.unwrap_or(None);
match token_from_req(req) {
Some(inner) => Ok(Token { inner }),
None => {
let e = TokenError::MissingBearer;
if let Some(error_handler) = error_handler {
Err((error_handler)(e, req))
} else {
Err(e.into())
}
}
}
}
}
#[derive(Clone)]
pub struct TokenConfig {
ehandler: Option<Arc<dyn Fn(TokenError, &HttpRequest) -> Error + Send + Sync>>,
}
impl TokenConfig {
/// Set custom error handler
pub fn error_handler<F>(mut self, f: F) -> Self
where
F: Fn(TokenError, &HttpRequest) -> Error + Send + Sync + 'static,
{
self.ehandler = Some(Arc::new(f));
self
}
}
impl Default for TokenConfig {
fn default() -> Self {
TokenConfig { ehandler: None }
}
}
pub fn token_from_req(req: &HttpRequest) -> Option<String> {
let headers =
if let Some(h) = req
.headers()
.get(header::AUTHORIZATION) {
h
} else {
return None;
};
if let Ok(t) = headers.to_str() {
let mut token_iterator = t.split_whitespace();
if let Some(identifier) = token_iterator.next() {
if identifier != "Bearer" { return None; }
if let Some(token) = token_iterator.next() {
return Some(token.to_string())
}
}
}
None
}
|
//! A cross-platform asynchronous [Runtime](https://github.com/rustasync/runtime). See the [Runtime
//! documentation](https://docs.rs/runtime) for more details.
#![deny(unsafe_code)]
#![warn(
missing_debug_implementations,
missing_docs,
nonstandard_style,
rust_2018_idioms
)]
#[cfg(target_arch = "wasm32")]
mod wasm32;
#[cfg(target_arch = "wasm32")]
pub use wasm32::Native;
#[cfg(not(target_arch = "wasm32"))]
mod not_wasm32;
#[cfg(not(target_arch = "wasm32"))]
pub use not_wasm32::Native;
|
//! Configuration file migration.
use std::fs;
use std::path::Path;
use toml::map::Entry;
use toml::{Table, Value};
use crate::cli::MigrateOptions;
use crate::config;
/// Handle migration.
pub fn migrate(options: MigrateOptions) {
// Find configuration file path.
let config_path = options
.config_file
.clone()
.or_else(|| config::installed_config("toml"))
.or_else(|| config::installed_config("yml"));
// Abort if system has no installed configuration.
let config_path = match config_path {
Some(config_path) => config_path,
None => {
eprintln!("No configuration file found");
std::process::exit(1);
},
};
// If we're doing a wet run, perform a dry run first for safety.
if !options.dry_run {
let mut options = options.clone();
options.silent = true;
options.dry_run = true;
if let Err(err) = migrate_config(&options, &config_path, config::IMPORT_RECURSION_LIMIT) {
eprintln!("Configuration file migration failed:");
eprintln!(" {config_path:?}: {err}");
std::process::exit(1);
}
}
// Migrate the root config.
match migrate_config(&options, &config_path, config::IMPORT_RECURSION_LIMIT) {
Ok(new_path) => {
if !options.silent {
println!("Successfully migrated {config_path:?} to {new_path:?}");
}
},
Err(err) => {
eprintln!("Configuration file migration failed:");
eprintln!(" {config_path:?}: {err}");
std::process::exit(1);
},
}
}
/// Migrate a specific configuration file.
fn migrate_config(
options: &MigrateOptions,
path: &Path,
recursion_limit: usize,
) -> Result<String, String> {
// Ensure configuration file has an extension.
let path_str = path.to_string_lossy();
let (prefix, suffix) = match path_str.rsplit_once('.') {
Some((prefix, suffix)) => (prefix, suffix),
None => return Err("missing file extension".to_string()),
};
// Abort if config is already toml.
if suffix == "toml" {
return Err("already in TOML format".to_string());
}
// Try to parse the configuration file.
let mut config = match config::deserialize_config(path) {
Ok(config) => config,
Err(err) => return Err(format!("parsing error: {err}")),
};
// Migrate config imports.
if !options.skip_imports {
migrate_imports(options, &mut config, recursion_limit)?;
}
// Migrate deprecated field names to their new location.
if !options.skip_renames {
migrate_renames(&mut config)?;
}
// Convert to TOML format.
let toml = toml::to_string(&config).map_err(|err| format!("conversion error: {err}"))?;
let new_path = format!("{prefix}.toml");
if options.dry_run && !options.silent {
// Output new content to STDOUT.
println!(
"\nv-----Start TOML for {path:?}-----v\n\n{toml}\n^-----End TOML for {path:?}-----^"
);
} else if !options.dry_run {
// Write the new toml configuration.
fs::write(&new_path, toml).map_err(|err| format!("filesystem error: {err}"))?;
}
Ok(new_path)
}
/// Migrate the imports of a config.
fn migrate_imports(
options: &MigrateOptions,
config: &mut Value,
recursion_limit: usize,
) -> Result<(), String> {
let imports = match config::imports(config, recursion_limit) {
Ok(imports) => imports,
Err(err) => return Err(format!("import error: {err}")),
};
// Migrate the individual imports.
let mut new_imports = Vec::new();
for import in imports {
let import = match import {
Ok(import) => import,
Err(err) => return Err(format!("import error: {err}")),
};
let new_path = migrate_config(options, &import, recursion_limit - 1)?;
new_imports.push(Value::String(new_path));
}
// Update the imports field.
if let Some(import) = config.get_mut("import") {
*import = Value::Array(new_imports);
}
Ok(())
}
/// Migrate deprecated fields.
fn migrate_renames(config: &mut Value) -> Result<(), String> {
let config_table = match config.as_table_mut() {
Some(config_table) => config_table,
None => return Ok(()),
};
// draw_bold_text_with_bright_colors -> colors.draw_bold_text_with_bright_colors
move_value(config_table, &["draw_bold_text_with_bright_colors"], &[
"colors",
"draw_bold_text_with_bright_colors",
])?;
// key_bindings -> keyboard.bindings
move_value(config_table, &["key_bindings"], &["keyboard", "bindings"])?;
// mouse_bindings -> mouse.bindings
move_value(config_table, &["mouse_bindings"], &["mouse", "bindings"])?;
Ok(())
}
/// Move a toml value from one map to another.
fn move_value(config_table: &mut Table, origin: &[&str], target: &[&str]) -> Result<(), String> {
if let Some(value) = remove_node(config_table, origin)? {
if !insert_node_if_empty(config_table, target, value)? {
return Err(format!(
"conflict: both `{}` and `{}` are set",
origin.join("."),
target.join(".")
));
}
}
Ok(())
}
/// Remove a node from a tree of tables.
fn remove_node(table: &mut Table, path: &[&str]) -> Result<Option<Value>, String> {
if path.len() == 1 {
Ok(table.remove(path[0]))
} else {
let next_table_value = match table.get_mut(path[0]) {
Some(next_table_value) => next_table_value,
None => return Ok(None),
};
let next_table = match next_table_value.as_table_mut() {
Some(next_table) => next_table,
None => return Err(format!("invalid `{}` table", path[0])),
};
remove_node(next_table, &path[1..])
}
}
/// Try to insert a node into a tree of tables.
///
/// Returns `false` if the node already exists.
fn insert_node_if_empty(table: &mut Table, path: &[&str], node: Value) -> Result<bool, String> {
if path.len() == 1 {
match table.entry(path[0]) {
Entry::Vacant(vacant_entry) => {
vacant_entry.insert(node);
Ok(true)
},
Entry::Occupied(_) => Ok(false),
}
} else {
let next_table_value = table.entry(path[0]).or_insert_with(|| Value::Table(Table::new()));
let next_table = match next_table_value.as_table_mut() {
Some(next_table) => next_table,
None => return Err(format!("invalid `{}` table", path[0])),
};
insert_node_if_empty(next_table, &path[1..], node)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn move_values() {
let input = r#"
root_value = 3
[table]
table_value = 5
[preexisting]
not_moved = 9
"#;
let mut value: Value = toml::from_str(input).unwrap();
let table = value.as_table_mut().unwrap();
move_value(table, &["root_value"], &["new_table", "root_value"]).unwrap();
move_value(table, &["table", "table_value"], &["preexisting", "subtable", "new_name"])
.unwrap();
let output = toml::to_string(table).unwrap();
assert_eq!(
output,
"[new_table]\nroot_value = 3\n\n[preexisting]\nnot_moved = \
9\n\n[preexisting.subtable]\nnew_name = 5\n\n[table]\n"
);
}
}
|
// Copyright (c) 2016 <daggerbot@gmail.com>
// This software is available under the terms of the zlib license.
// See README.md for more information.
use std::path::{Path, PathBuf};
use std::vec;
use os;
/// Application shared information which gets passed around during game initialization.
pub struct AppContext {
exe_path: PathBuf,
portable: bool,
}
impl AppContext {
pub fn exe_dir (&self) -> &Path {
self.exe_path.parent().expect("can't get directory of exe path")
}
pub fn exe_path (&self) -> &Path { self.exe_path.as_ref() }
pub fn is_portable (&self) -> bool { self.portable }
pub fn module_dirs (&self) -> vec::IntoIter<PathBuf> {
if self.portable {
vec!(self.exe_dir().join("modules")).into_iter()
} else {
self.os_module_dirs().into_iter()
}
}
pub fn new<P: AsRef<Path>> (exe_path: P) -> AppContext {
AppContext {
exe_path: PathBuf::from(exe_path.as_ref()),
portable: false,
}
}
pub fn new_portable<P: AsRef<Path>> (exe_path: P) -> AppContext {
AppContext {
exe_path: PathBuf::from(exe_path.as_ref()),
portable: true,
}
}
pub fn save_dir (&self) -> PathBuf {
if self.portable {
self.exe_dir().join("save")
} else {
self.os_save_dir()
}
}
}
#[cfg(all(unix, not(target_os = "macos")))]
impl AppContext {
fn os_module_dirs (&self) -> Vec<PathBuf> {
os::unix::module_dirs()
}
fn os_save_dir (&self) -> PathBuf {
os::unix::save_dir()
}
}
|
pub mod anonymous;
pub mod export;
use std::sync::Arc;
use num_bigint::BigInt;
use proptest::prop_oneof;
use proptest::strategy::{BoxedStrategy, Strategy};
use liblumen_alloc::erts::term::prelude::*;
use liblumen_alloc::erts::Process;
use crate::test::strategy;
pub fn module() -> BoxedStrategy<Term> {
super::atom()
}
pub fn module_atom() -> BoxedStrategy<Atom> {
strategy::atom()
}
pub fn function() -> BoxedStrategy<Term> {
super::atom()
}
pub fn anonymous(arc_process: Arc<Process>) -> BoxedStrategy<Term> {
prop_oneof![
anonymous::with_native(arc_process.clone()),
anonymous::without_native(arc_process)
]
.boxed()
}
pub fn arity(arc_process: Arc<Process>) -> BoxedStrategy<Term> {
arity_u8().prop_map(move |u| arc_process.integer(u)).boxed()
}
pub fn arity_or_arguments(arc_process: Arc<Process>) -> BoxedStrategy<Term> {
prop_oneof![arity(arc_process.clone()), arguments(arc_process)].boxed()
}
pub fn arity_u8() -> BoxedStrategy<u8> {
(0_u8..=255_u8).boxed()
}
pub fn arguments(arc_process: Arc<Process>) -> BoxedStrategy<Term> {
super::list::proper(arc_process)
}
pub fn export(arc_process: Arc<Process>) -> BoxedStrategy<Term> {
prop_oneof![
export::with_native(arc_process.clone()),
export::without_native(arc_process)
]
.boxed()
}
pub fn is_not_arity_or_arguments(arc_process: Arc<Process>) -> BoxedStrategy<Term> {
super::super::term(arc_process)
.prop_filter("Arity and argument must be neither an arity (>= 0) or arguments (an empty or non-empty proper list)", |term| match term.decode().unwrap() {
TypedTerm::Nil => false,
TypedTerm::List(cons) => !cons.is_proper(),
TypedTerm::BigInteger(big_integer) => {
let big_int: &BigInt = big_integer.as_ref().into();
let zero_big_int: &BigInt = &0.into();
big_int < zero_big_int
}
TypedTerm::SmallInteger(small_integer) => {
let i: isize = small_integer.into();
i < 0
}
_ => true,
})
.boxed()
}
|
use core::mem;
use crate::pointer::{
Marked::{self, Null, Value},
MarkedNonNullable,
};
use crate::MarkedPointer;
/********** impl inherent *************************************************************************/
impl<T: MarkedNonNullable> Marked<T> {
/// Returns `true` if the marked value contains a [`Value`].
#[inline]
pub fn is_value(&self) -> bool {
match *self {
Value(_) => true,
_ => false,
}
}
/// Returns `true` if the marked value is a [`Null`].
#[inline]
pub fn is_null(&self) -> bool {
match *self {
Null(_) => true,
_ => false,
}
}
/// Converts from `Marked<T>` to `Marked<&T>`.
#[inline]
pub fn as_ref(&self) -> Marked<&T> {
match self {
Value(value) => Value(value),
Null(tag) => Null(*tag),
}
}
/// Converts from `Marked<T>` to `Marked<&mut T>`.
#[inline]
pub fn as_mut(&mut self) -> Marked<&mut T> {
match self {
Value(value) => Value(value),
Null(tag) => Null(*tag),
}
}
/// Moves the pointer out of the `Marked` if it is [`Value(ptr)`][Value].
#[inline]
pub fn unwrap_value(self) -> T {
match self {
Value(ptr) => ptr,
_ => panic!("called `Marked::unwrap_value()` on a `Null` value"),
}
}
/// Extracts the tag out of the `Marked` if it is [`Null(tag)`][Null].
#[inline]
pub fn unwrap_null(self) -> usize {
match self {
Null(tag) => tag,
_ => panic!("called `Marked::unwrap_tag()` on a `Value`"),
}
}
/// Returns the contained value or the result of the given `func`.
#[inline]
pub fn unwrap_value_or_else(self, func: impl (FnOnce(usize) -> T)) -> T {
match self {
Value(ptr) => ptr,
Null(tag) => func(tag),
}
}
/// Maps a `Marked<T>` to `Marked<U>` by applying a function to a contained
/// value.
#[inline]
pub fn map<U: MarkedNonNullable>(self, func: impl (FnOnce(T) -> U)) -> Marked<U> {
match self {
Value(ptr) => Value(func(ptr)),
Null(tag) => Null(tag),
}
}
/// Applies a function to the contained value (if any), or computes a
/// default value using `func`, if no value is contained.
#[inline]
pub fn map_or_else<U: MarkedNonNullable>(
self,
default: impl FnOnce(usize) -> U,
func: impl FnOnce(T) -> U,
) -> U {
match self {
Value(ptr) => func(ptr),
Null(tag) => default(tag),
}
}
/// Converts `self` from `Marked<T>` to [`Option<T>`][Option].
#[inline]
pub fn value(self) -> Option<T> {
match self {
Value(ptr) => Some(ptr),
_ => None,
}
}
/// Takes the value of the [`Marked`], leaving a [`Null`] variant in its
/// place.
#[inline]
pub fn take(&mut self) -> Self {
mem::replace(self, Null(0))
}
/// Replaces the actual value in the [`Marked`] with the given `value`,
/// returning the old value.
#[inline]
pub fn replace(&mut self, value: T) -> Self {
mem::replace(self, Value(value))
}
}
impl<T: MarkedNonNullable + MarkedPointer> Marked<T> {
/// Decomposes the inner marked pointer, returning only the separated tag.
#[inline]
pub fn decompose_tag(&self) -> usize {
match self {
Value(ptr) => ptr.as_marked_ptr().decompose_tag(),
Null(tag) => *tag,
}
}
}
/********** impl Default **************************************************************************/
impl<T: MarkedNonNullable> Default for Marked<T> {
#[inline]
fn default() -> Self {
Null(0)
}
}
/********** impl From *****************************************************************************/
impl<T: MarkedNonNullable> From<Option<T>> for Marked<T> {
#[inline]
fn from(opt: Option<T>) -> Self {
match opt {
Some(ptr) => Value(ptr),
None => Null(0),
}
}
}
|
use crate::column::ColumnIndex;
use crate::error::Error;
use crate::ext::ustr::UStr;
use crate::mssql::protocol::row::Row as ProtocolRow;
use crate::mssql::{Mssql, MssqlColumn, MssqlValueRef};
use crate::row::Row;
use crate::HashMap;
use std::sync::Arc;
pub struct MssqlRow {
pub(crate) row: ProtocolRow,
pub(crate) columns: Arc<Vec<MssqlColumn>>,
pub(crate) column_names: Arc<HashMap<UStr, usize>>,
}
impl crate::row::private_row::Sealed for MssqlRow {}
impl Row for MssqlRow {
type Database = Mssql;
fn columns(&self) -> &[MssqlColumn] {
&*self.columns
}
fn try_get_raw<I>(&self, index: I) -> Result<MssqlValueRef<'_>, Error>
where
I: ColumnIndex<Self>,
{
let index = index.index(self)?;
let value = MssqlValueRef {
data: self.row.values[index].as_ref(),
type_info: self.row.column_types[index].clone(),
};
Ok(value)
}
}
impl ColumnIndex<MssqlRow> for &'_ str {
fn index(&self, row: &MssqlRow) -> Result<usize, Error> {
row.column_names
.get(*self)
.ok_or_else(|| Error::ColumnNotFound((*self).into()))
.map(|v| *v)
}
}
#[cfg(feature = "any")]
impl From<MssqlRow> for crate::any::AnyRow {
#[inline]
fn from(row: MssqlRow) -> Self {
crate::any::AnyRow {
columns: row.columns.iter().map(|col| col.clone().into()).collect(),
kind: crate::any::row::AnyRowKind::Mssql(row),
}
}
}
|
//! A composable abstraction for processing write requests.
mod r#trait;
pub use r#trait::*;
pub(crate) mod instrumentation;
pub(crate) mod tracing;
#[cfg(test)]
pub(crate) mod mock_sink;
|
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
let config = Config::new(&args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {}", err);
process::exit(1);
});
println!("Searching for {}", config.query);
println!("In file {}", config.filename);
run(config);
}
fn run(config: Config) {
let mut f = File::open(config.filename).expect("file not found");
let mut contents = String::new();
f.read_to_string(&mut contents).expect("something went wrong reading the file");
println!("With text:\n{}", contents);
}
struct Config {
query: String,
filename: String,
}
impl Config {
fn new(args: std::env::Args) -> Result<Config, &'static str> {
args.next();
let query = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a query string"),
};
let filename = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a file name"),
};
let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
Ok(Config { query, filename })
}
} |
mod common;
mod lexer;
mod parser;
use self::parser::parse;
use super::build::Link;
use super::error::JustTextError;
use super::meta::Metadatum;
use crate::assets::NOTE_TEMPLATE;
use chrono::{DateTime, Utc};
use handlebars::Handlebars;
use serde_json::json;
use std::error::Error;
use std::fs;
use std::path::Path;
pub struct Note {
filename: String,
content: String,
pub created: DateTime<Utc>,
}
impl Note {
pub fn new(filename: String, content: String) -> Note {
Note {
filename,
content,
created: Utc::now(),
}
}
pub fn reconcile(&mut self, metadata: &Vec<Metadatum>) {
if let Some(meta) = metadata.iter().find(|m| m.filename == self.filename) {
self.created = meta.created;
}
}
pub fn write(&self, build_dir: &Path) -> Result<(), Box<dyn Error>> {
let title = self.generate_title();
let date = self.created.format("%b %e %Y").to_string();
let content = parse(&self.content).map(|n| n.resolve(&self.content));
// Look into lifetime issue here:
if let Err(e) = content {
return Err(Box::new(JustTextError::new(format!("{}", e))));
}
let content = content.unwrap();
let html = Handlebars::new().render_template(
NOTE_TEMPLATE,
&json!({
"title": title,
"date": date,
"content": content
}),
)?;
fs::write(build_dir.join(Path::new(&self.get_html_path())), html)?;
Ok(())
}
fn get_html_path(&self) -> String {
format!("{}.html", self.get_path_core())
}
pub fn generate_title(&self) -> String {
let core = self.get_path_core();
core.replace("_", " ")
}
pub fn generate_link(&self) -> Link {
let title = self.generate_title();
let href = self.get_path_core().replace("\"", """);
let href = format!("./{}.html", href);
Link { href, title }
}
fn get_path_core(&self) -> &str {
let start = self.filename.find("/").map(|n| n + 1).unwrap_or(0);
let end = self.filename.find(".").unwrap_or(self.filename.len());
&self.filename[start..end]
}
pub fn to_metadatum(&self) -> Metadatum {
Metadatum {
filename: self.filename.clone(),
created: self.created.clone(),
}
}
}
|
use super::*;
#[test]
fn write_empty_buffer_returns_zero() {
let rb = SpscRb::new(1);
let (_, producer) = (rb.consumer(), rb.producer());
let a: [u8; 0] = [];
match producer.write(&a) {
Ok(v) => assert_eq!(v, 0),
e => panic!("Error occured on get: {:?}", e),
}
}
#[test]
fn write_blocking_empty_buffer_returns_zero() {
let rb = SpscRb::new(1);
let (_, producer) = (rb.consumer(), rb.producer());
let a: [u8; 0] = [];
match producer.write_blocking(&a) {
None => {}
v => panic!("`write_blocking` didn't return None, but {:?}", v),
}
}
#[test]
fn write_to_full_queue_returns_error() {
let rb = SpscRb::new(1);
let (_, producer) = (rb.consumer(), rb.producer());
let a = [1];
producer.write(&a).unwrap();
match producer.write(&a) {
Err(RbError::Full) => {}
v => panic!("No error or incorrect error: {:?}", v),
}
}
#[test]
fn get_to_empty_buffer_returns_zero() {
let rb = SpscRb::new(1);
let (consumer, producer) = (rb.consumer(), rb.producer());
let a = [1];
producer.write(&a).unwrap();
let mut b: [u8; 0] = [];
match consumer.get(&mut b) {
Ok(v) => assert_eq!(v, 0),
e => panic!("Error occured on get: {:?}", e),
}
}
#[test]
fn get_from_empty_buffer_returns_error() {
let rb = SpscRb::new(1);
let (consumer, _) = (rb.consumer(), rb.producer());
let mut b = [42];
match consumer.get(&mut b) {
Err(RbError::Empty) => {}
v => panic!("No error or incorrect error: {:?}", v),
}
assert_eq!(b[0], 42);
}
#[test]
fn read_to_empty_buffer_returns_zero() {
let rb = SpscRb::new(1);
let (consumer, producer) = (rb.consumer(), rb.producer());
let a = [1];
producer.write(&a).unwrap();
let mut b: [u8; 0] = [];
match consumer.read(&mut b) {
Ok(v) => assert_eq!(v, 0),
e => panic!("Error occured on get: {:?}", e),
}
}
#[test]
fn read_from_empty_buffer_returns_error() {
let rb = SpscRb::new(1);
let (consumer, _) = (rb.consumer(), rb.producer());
let mut b = [42];
match consumer.read(&mut b) {
Err(RbError::Empty) => {}
v => panic!("No error or incorrect error: {:?}", v),
}
assert_eq!(b[0], 42);
}
#[test]
fn read_blocking_to_empty_buffer_returns_none() {
let rb = SpscRb::new(1);
let (consumer, producer) = (rb.consumer(), rb.producer());
let a = [1];
producer.write(&a).unwrap();
let mut b: [u8; 0] = [];
match consumer.read_blocking(&mut b) {
None => {}
v => panic!("`read_blocking` unexpectedly returned {:?}", v),
}
}
#[test]
fn get_with_wrapping() {
let rb = SpscRb::new(1);
let (consumer, producer) = (rb.consumer(), rb.producer());
let a = [1];
assert_eq!(producer.write(&a).unwrap(), 1);
let mut b = [0];
consumer.read(&mut b).unwrap();
assert_eq!(b[0], 1);
let c = [2, 3];
assert_eq!(producer.write(&c).unwrap(), 1);
let mut d = [0, 0];
consumer.get(&mut d).unwrap();
assert_eq!(d[0], 2);
assert_eq!(d[1], 0);
}
#[test]
fn get_with_wrapping_2() {
let rb = SpscRb::new(2);
let (consumer, producer) = (rb.consumer(), rb.producer());
let a = [1];
assert_eq!(producer.write(&a).unwrap(), 1);
let mut b = [0];
consumer.read(&mut b).unwrap();
assert_eq!(b[0], 1);
let c = [2, 3];
assert_eq!(producer.write(&c).unwrap(), 2);
let mut d = [0, 0];
consumer.get(&mut d).unwrap();
assert_eq!(d[0], 2);
assert_eq!(d[1], 3);
}
|
use reqwest::Error;
pub trait Model<T> {
/// Finds a resource by its ID
///
/// # Example
/// ```
/// use jplaceholder::Model;
/// use jplaceholder::Post;
///
/// match Post::find(2) {
/// Some(post) => println!("Title of the article {}: {}", post.id, post.title),
/// None => println!("Article not found!")
/// }
/// ```
fn find(id: i32) -> Option<T>;
/// Gets all of the resources
///
/// # Example
/// ```
/// use jplaceholder::Model;
/// use jplaceholder::Post;
///
/// let posts: Vec<Post> = Post::all();
/// for post in posts {
/// println!("The title of the post {} is: {}", post.id, post.title)
/// }
/// ```
fn all() -> Vec<T>;
/// Creates a new resource
///
/// # Example
/// ```
/// use jplaceholder::Model;
/// use jplaceholder::Post;
///
/// let post = Post{id: 5, title: String::from("Hey"), body: String::from("hehe"), user_id: 5};
/// Post::create(post);
/// ```
fn create(model: T) -> Result<(), Error>;
}
|
// Tim Henderson <tim.tadh@gmail.com>
// Copyright 2014
// All rights reserved.
// For licensing information see the top level directory.
use std::iter::Iterator;
#[deriving(Show)]
#[deriving(PartialEq)]
pub enum TokenType {
TERM,
NONTERM,
SEMI,
VBAR,
ARROW,
EMPTY
}
#[deriving(Show)]
pub enum LexError {
UnexpectedCharacter(char),
BadState(uint),
}
#[deriving(Show)]
pub struct Token<'a> {
pub token : TokenType,
pub lexeme : &'a str,
}
#[deriving(Show)]
pub struct Lexer<'a> {
text : &'a str,
tc : uint,
failed : bool
}
pub fn gram_lexer<'a>(text : &'a str) -> Lexer<'a> {
return Lexer{
text: text,
tc: 0,
failed: false,
};
}
impl<'a> Lexer<'a> {
fn white(ch : char) -> bool {
ch == ' ' || ch == '\n' || ch == '\t'
}
fn big(ch : char) -> bool {
'A' <= ch && ch <= 'Z'
}
fn not_big(ch : char) -> bool {
('a' <= ch && ch <= 'z') || ('0' <= ch && ch <= '9') || ch == '_' || ch == '\''
}
fn alpha_num(ch : char) -> bool {
('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '_' || ch == '\''
}
}
impl<'a> Iterator<Result<Token<'a>,LexError>> for Lexer<'a> {
fn next(&mut self) -> Option<Result<Token<'a>,LexError>> {
if self.failed {
return None
}
let text : &str = self.text;
let mut state = 1;
let mut start_tc = self.tc;
let mut tc = self.tc;
while tc < self.text.len() {
let ch_range = text.char_range_at(tc);
let ch = ch_range.ch;
let mut next_tc = ch_range.next;
state = match state {
1 => {
if Lexer::white(ch) {
2
} else if ch == ';' {
3
} else if ch == '-' {
4
} else if ch == 'e' {
6
} else if ch == '|' {
9
} else if Lexer::big(ch) {
7
} else {
self.failed = true;
return Some(Err(UnexpectedCharacter(ch)))
}
} 2 => {
if Lexer::white(ch) {
2
} else {
next_tc = tc;
start_tc = tc;
1
}
} 3 => {
self.tc = next_tc;
return Some(Ok(Token{token:SEMI,lexeme:text.slice(start_tc,tc)}))
} 4 => {
if ch == '>' {
5
} else {
return Some(Err(UnexpectedCharacter(ch)))
}
} 5 => {
self.tc = next_tc;
return Some(Ok(Token{token:ARROW,lexeme:text.slice(start_tc,tc)}))
} 6 => {
self.tc = next_tc;
return Some(Ok(Token{token:EMPTY,lexeme:text.slice(start_tc,tc)}))
} 7 => {
if Lexer::big(ch) {
10
} else if Lexer::not_big(ch) {
8
} else {
self.tc = next_tc;
return Some(Ok(Token{token:NONTERM,lexeme:text.slice(start_tc,tc)}))
}
} 8 => {
if Lexer::alpha_num(ch) {
8
} else {
self.tc = next_tc;
return Some(Ok(Token{token:NONTERM,lexeme:text.slice(start_tc,tc)}))
}
} 9 => {
self.tc = next_tc;
return Some(Ok(Token{token:VBAR,lexeme:text.slice(start_tc,tc)}))
} 10 => {
if Lexer::big(ch) {
10
} else if Lexer::not_big(ch) {
8
} else {
self.tc = next_tc;
return Some(Ok(Token{token:TERM,lexeme:text.slice(start_tc,tc)}))
}
} _ => {
self.failed = true;
return Some(Err(BadState(state)))
}
};
tc = next_tc;
}
None
}
}
|
#![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rand;
use rand::Rng;
const BASE62: &'static [u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
#[derive(FromForm)]
struct IDSpec {
size: usize
}
#[get("/")]
fn index() -> &'static str {
"
Welcome to CryptoServer, where you can generate random, secure, and unique IDs!
USAGE:
GET /generate/<size>
returns a random, secure, and unique ID with the given size of characters generated on-the-fly
"
}
fn get_secure_id(size: usize) -> String {
let mut id = String::with_capacity(size);
let mut rng = rand::thread_rng();
for _ in 0..size {
id.push(BASE62[rng.gen::<usize>() % 62] as char);
}
id
}
#[get("/generate?<idspec>")]
fn generate(idspec: IDSpec) -> String {
get_secure_id(idspec.size)
}
fn main() {
rocket::ignite().mount("/", routes![index, generate]).launch();
}
|
extern crate libc;
extern crate num;
use std::ffi::CString;
use num::FromPrimitive;
use std::mem;
use std::ptr;
use constants::{SSHAuthResult,SSHAuthMethod,SSHOption,SSHRequest};
use native::libssh;
use native::server;
use ssh_key::SSHKey;
use util;
pub struct SSHSession {
_session: *mut libssh::ssh_session_struct
}
impl SSHSession {
pub fn new(host: Option<&str>) -> Result<SSHSession, &'static str> {
let ptr = unsafe { libssh::ssh_new() };
assert!(!ptr.is_null());
let session = SSHSession {_session: ptr};
if host.is_some() {
try!(session.set_host(host.unwrap()))
}
Ok(session)
}
pub fn set_host(&self, host: &str) -> Result<(), &'static str> {
assert!(!self._session.is_null());
let opt = SSHOption::Host as u32;
let host_cstr = CString::new(host).unwrap();
check_ssh_ok!(libssh::ssh_options_set(self._session, opt,
host_cstr.as_ptr() as *const libc::c_void),
self._session)
}
pub fn connect<F>(&self, verify_public_key: F)
-> Result<(), &'static str>
where F: Fn(&SSHKey) -> bool
{
assert!(!self._session.is_null());
try!(check_ssh_ok!(libssh::ssh_connect(self._session), self._session));
let remote_public_key = try!(
SSHKey::from_session(self).map_err(|err| err)
);
if !verify_public_key(&remote_public_key) {
self.disconnect();
return Err("authentication failed");
}
else {
Ok(())
}
}
pub fn disconnect(&self) {
assert!(!self._session.is_null());
unsafe {
libssh::ssh_disconnect(self._session);
}
}
pub fn auth_by_public_key(&self, username: Option<&str>, pubkey: &SSHKey)
-> Result<(),SSHAuthResult>
{
/*
SSH_AUTH_ERROR: A serious error happened.
SSH_AUTH_DENIED: The libssh doesn't accept that public key as an authentication token. Try another key or another method.
SSH_AUTH_PARTIAL: You've been partially authenticated, you still have to use another method.
SSH_AUTH_SUCCESS: The public key is accepted, you want now to use ssh_userauth_pubkey(). SSH_AUTH_AGAIN: In nonblocking mode, you've got to call this again later.
*/
assert!(!self._session.is_null());
let key = pubkey.raw();
let func = |usr| unsafe {
libssh::ssh_userauth_try_publickey(self._session, usr, key)
};
let ires = match username {
Some(usrn_str) => func(CString::new(usrn_str).unwrap().as_ptr()),
None => func(ptr::null())
};
let res = SSHAuthResult::from_i32(ires);
match res {
Some(SSHAuthResult::Success) => Ok(()),
Some(err) => Err(err),
None => {panic!("Unrecoverable result in auth_by_public_key");}
}
}
pub fn raw(&self) -> *mut libssh::ssh_session_struct {
assert!(!self._session.is_null());
self._session
}
pub fn set_port(&self, port: &str) -> Result<(),&'static str> {
assert!(!self._session.is_null());
let opt = SSHOption::PortStr as u32;
let p = CString::new(port).unwrap();
check_ssh_ok!(
libssh::ssh_options_set(self._session, opt,
p.as_ptr() as *const libc::c_void),
self._session
)
}
pub fn auth_with_public_key<'a, F>(&self, verify_public_key: F)
-> Result<(),&'a str>
where F: Fn(&SSHKey) -> bool
{
const MAX_ATTEMPTS: libc::c_uint = 5;
for _ in 0..MAX_ATTEMPTS {
let msg = try!(SSHMessage::from_session(self));
let type_ = msg.get_type();
let subtype = SSHAuthMethod::from_i32(msg.get_subtype());
match (type_, subtype) {
(SSHRequest::Auth, Some(SSHAuthMethod::PublicKey)) =>
{
let remote_public_key = try!(SSHKey::from_message(&msg));
if verify_public_key(&remote_public_key) {
return Ok(());
}
},
_ => {
try!(msg.reply_default())
}
}
}
Err("authentication with public key failed")
}
pub fn handle_key_exchange(&self) -> Result<(),&'static str> {
assert!(!self._session.is_null());
let session: *mut libssh::ssh_session_struct = unsafe {
mem::transmute(self._session)
};
check_ssh_ok!(server::ssh_handle_key_exchange(session))
}
pub fn get_message(&self) -> Result<SSHMessage, &'static str> {
assert!(!self._session.is_null());
let msg = try!(check_ssh_ptr!(libssh::ssh_message_get(self._session),
self._session));
Ok(SSHMessage { _msg: msg })
}
pub fn set_log_level(&self, level: i32) -> Result<(),&'static str> {
assert!(!self._session.is_null());
// FIXME: Should not be here?
check_ssh_ok!(libssh::ssh_set_log_level(level), self._session)
}
}
impl Drop for SSHSession {
fn drop(&mut self) {
unsafe {
libssh::ssh_disconnect(self._session);
libssh::ssh_free(self._session);
}
}
}
pub struct SSHMessage {
_msg: *mut libssh::ssh_message_struct
}
impl Drop for SSHMessage {
fn drop(&mut self) {
/*
* not necessary: issues "double free()" panic
unsafe {
ssh_message_free(self._msg)
}*/
}
}
impl SSHMessage {
pub fn from_session(session: &SSHSession) -> Result<SSHMessage, &'static str> {
let session: *mut libssh::ssh_session_struct = unsafe {
mem::transmute(session.raw())
};
assert!(!session.is_null());
let msg = try!(check_ssh_ptr!(libssh::ssh_message_get(session)));
Ok(SSHMessage { _msg: msg })
}
pub fn raw(self: &Self) -> *mut libssh::ssh_message_struct {
self._msg
}
pub fn get_type(self: &Self) -> SSHRequest {
assert!(!self._msg.is_null());
let ityp = unsafe { libssh::ssh_message_type(self._msg) };
SSHRequest::from_u32(ityp as u32).unwrap()
}
pub fn get_subtype(self: &Self) -> i32 {
assert!(!self._msg.is_null());
unsafe { libssh::ssh_message_subtype(self._msg) }
}
pub fn auth_set_methods(&self, methods: &[SSHAuthMethod])
-> Result<(), &'static str> {
// FIXME: dirty
let method_mask = methods.iter()
.fold(0i32,
|mask, meth|
mask | (meth.clone() as i32));
let ret = unsafe {
server::ssh_message_auth_set_methods(self._msg,
method_mask as libc::c_int)
};
match ret {
libssh::SSH_OK => Ok(()),
_ => Err("ssh_message_auth_set_methods() failed")
}
}
pub fn reply_default(&self) -> Result<(), &'static str> {
assert!(!self._msg.is_null());
let res = unsafe { server::ssh_message_reply_default(self._msg) };
match res {
libssh::SSH_OK => Ok(()),
_ => Err("ssh_message_reply_default() failed"),
}
}
pub fn get_auth_user(&self) -> Result<String, &'static str> {
let c_user = try!(check_ssh_ptr!(
server::ssh_message_auth_user(self._msg)
));
// FIXME: free?
Ok(try!(util::from_native_str(c_user)).to_string())
}
pub fn get_auth_password(&self) -> Result<String, &'static str> {
let c_pass = try!(check_ssh_ptr!(
server::ssh_message_auth_password(self._msg)
));
// FIXME: free?
Ok(try!(util::from_native_str(c_pass)).to_string())
}
}
|
use super::schema::blocks;
use diesel::{PgConnection, Connection, RunQueryDsl};
#[derive(Insertable)]
#[table_name = "blocks"]
pub struct NewBlock {
pub number: i64,
} |
use core::cmp::Ordering;
use guvm_rs::Value;
use super::util::*;
use super::CoreFailure;
use crate::{V, ValueBaseOrdered, ValueBase};
fun!(total_compare(v, w) {
Ok(match v.cmp(w) {
Ordering::Less => V::string("<"),
Ordering::Equal => V::string("="),
Ordering::Greater => V::string(">"),
})
});
fun!(total_lt(v, w) {
Ok(V::boo(v < w))
});
fun!(total_leq(v, w) {
Ok(V::boo(v <= w))
});
fun!(total_eq(v, w) {
Ok(V::boo(v == w))
});
fun!(total_geq(v, w) {
Ok(V::boo(v >= w))
});
fun!(total_gt(v, w) {
Ok(V::boo(v > w))
});
fun!(total_neq(v, w) {
Ok(V::boo(v != w))
});
fun!(total_min(v, w) {
Ok(core::cmp::min(v, w).clone())
});
fun!(total_max(v, w) {
Ok(core::cmp::max(v, w).clone())
});
fun!(partial_compare(v, w) {
match v.partial_compare(w) {
Some(Ordering::Less) => Ok(V::ok(V::string("<"))),
Some(Ordering::Equal) => Ok(V::ok(V::string("="))),
Some(Ordering::Greater) => Ok(V::ok(V::string(">"))),
None => Ok(V::err_nil()),
}
});
fun!(partial_lt(v, w) {
match v.partial_lt(w) {
Some(b) => Ok(V::ok(V::boo(b))),
None => Ok(V::err_nil()),
}
});
fun!(partial_leq(v, w) {
match v.partial_leq(w) {
Some(b) => Ok(V::ok(V::boo(b))),
None => Ok(V::err_nil()),
}
});
fun!(partial_eq(v, w) {
match v.partial_eq(w) {
Some(b) => Ok(V::ok(V::boo(b))),
None => Ok(V::err_nil()),
}
});
fun!(partial_geq(v, w) {
match v.partial_geq(w) {
Some(b) => Ok(V::ok(V::boo(b))),
None => Ok(V::err_nil()),
}
});
fun!(partial_gt(v, w) {
match v.partial_gt(w) {
Some(b) => Ok(V::ok(V::boo(b))),
None => Ok(V::err_nil()),
}
});
fun!(partial_neq(v, w) {
match v.partial_neq(w) {
Some(b) => Ok(V::ok(V::boo(b))),
None => Ok(V::err_nil()),
}
});
fun!(partial_greatest_lower_bound(v, w) {
match v.partial_greatest_lower_bound(w) {
Some(b) => Ok(V::ok(b)),
None => Ok(V::err_nil()),
}
});
fun!(partial_least_upper_bound(v, w) {
match v.partial_least_upper_bound(w) {
Some(b) => Ok(V::ok(b)),
None => Ok(V::err_nil()),
}
});
|
use clap::{crate_description, crate_name, crate_version, App, Arg, SubCommand};
use morgan::blockBufferPool::Blocktree;
use morgan::blockBufferPoolProcessor::process_blocktree;
use morgan_interface::genesis_block::GenesisBlock;
use std::io::{stdout, Write};
use std::process::exit;
fn main() {
morgan_logger::setup();
let matches = App::new(crate_name!()).about(crate_description!())
.version(crate_version!())
.arg(
Arg::with_name("ledger")
.short("l")
.long("ledger")
.value_name("DIR")
.takes_value(true)
.required(true)
.help("Use directory for ledger location"),
)
.arg(
Arg::with_name("head")
.short("n")
.long("head")
.value_name("NUM")
.takes_value(true)
.help("Limit to at most the first NUM entries in ledger\n (only applies to print and json commands)"),
)
.arg(
Arg::with_name("min-hashes")
.short("h")
.long("min-hashes")
.value_name("NUM")
.takes_value(true)
.help("Skip entries with fewer than NUM hashes\n (only applies to print and json commands)"),
)
.arg(
Arg::with_name("continue")
.short("c")
.long("continue")
.help("Continue verify even if verification fails"),
)
.subcommand(SubCommand::with_name("print").about("Print the ledger"))
.subcommand(SubCommand::with_name("json").about("Print the ledger in JSON format"))
.subcommand(SubCommand::with_name("verify").about("Verify the ledger's PoH"))
.get_matches();
let ledger_path = matches.value_of("ledger").unwrap();
let genesis_block = GenesisBlock::load(ledger_path).unwrap_or_else(|err| {
eprintln!(
"Failed to open ledger genesis_block at {}: {}",
ledger_path, err
);
exit(1);
});
let blocktree = match Blocktree::open(ledger_path) {
Ok(blocktree) => blocktree,
Err(err) => {
eprintln!("Failed to open ledger at {}: {}", ledger_path, err);
exit(1);
}
};
let entries = match blocktree.read_ledger() {
Ok(entries) => entries,
Err(err) => {
eprintln!("Failed to read ledger at {}: {}", ledger_path, err);
exit(1);
}
};
let head = match matches.value_of("head") {
Some(head) => head.parse().expect("please pass a number for --head"),
None => <usize>::max_value(),
};
let min_hashes = match matches.value_of("min-hashes") {
Some(hashes) => hashes
.parse()
.expect("please pass a number for --min-hashes"),
None => 0,
} as u64;
match matches.subcommand() {
("print", _) => {
for (i, entry) in entries.enumerate() {
if i >= head {
break;
}
if entry.num_hashes < min_hashes {
continue;
}
println!("{:?}", entry);
}
}
("json", _) => {
stdout().write_all(b"{\"ledger\":[\n").expect("open array");
for (i, entry) in entries.enumerate() {
if i >= head {
break;
}
if entry.num_hashes < min_hashes {
continue;
}
serde_json::to_writer(stdout(), &entry).expect("serialize");
stdout().write_all(b",\n").expect("newline");
}
stdout().write_all(b"\n]}\n").expect("close array");
}
("verify", _) => match process_blocktree(&genesis_block, &blocktree, None) {
Ok((_bank_forks, bank_forks_info, _)) => {
println!("{:?}", bank_forks_info);
}
Err(err) => {
eprintln!("Ledger verification failed: {:?}", err);
exit(1);
}
},
("", _) => {
eprintln!("{}", matches.usage());
exit(1);
}
_ => unreachable!(),
};
}
|
extern crate mray;
extern crate sdl2;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use mray::algebra::Point2f;
use mray::canvas::Canvas;
fn find_sdl_gl_driver() -> Option<u32> {
for (index, item) in sdl2::render::drivers().enumerate() {
if item.name == "opengl" {
return Some(index as u32);
}
}
None
}
pub struct Console {
font_size: (i32, i32),
scaler: f32,
pub canvas: Canvas,
}
impl Console {
pub fn new(size: (i32, i32)) -> Console {
let font_size = (30, 40);
Console {
font_size,
scaler: 40.,
canvas: Canvas::new((size.0 * font_size.0, size.1 * font_size.1)),
}
}
pub fn render(&mut self) {
self.canvas.flush();
for y in 0..16_u8 {
for x in 0..16_u8 {
let ch: u8 = y * 16 + x;
for graphic_object in mray::fsd::fsd(char::from(ch))
.shift(Point2f::from_floats(-0.5, -0.5))
.shear(-0.25)
.shift(Point2f::from_floats(0.5, 0.5))
.zoom(self.scaler as f32)
.shift(Point2f::from_floats(
(self.font_size.0 * x as i32) as f32,
(self.font_size.1 * y as i32) as f32,
))
.into_iter()
{
graphic_object.render(&mut self.canvas);
}
}
}
}
}
fn main() {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window_size: (u32, u32) = (540, 400);
let mut console = Console::new((18, 10));
let window = video_subsystem
.window("fsdterm", window_size.0 as u32, window_size.1 as u32)
.opengl()
.position_centered()
.build()
.unwrap();
let mut canvas = window
.into_canvas()
.index(find_sdl_gl_driver().unwrap())
.build()
.unwrap();
let texture_creator = canvas.texture_creator();
let mut texture = texture_creator
.create_texture_static(
Some(sdl2::pixels::PixelFormatEnum::RGB24),
window_size.0,
window_size.1,
)
.unwrap();
let mut event_pump = sdl_context.event_pump().unwrap();
console.render();
texture
.update(None, &console.canvas.data, window_size.0 as usize * 3)
.unwrap();
canvas.set_draw_color(Color::RGBA(0, 0, 0, 255));
canvas.clear();
canvas.copy(&texture, None, None).unwrap();
canvas.present();
'main_loop: loop {
std::thread::sleep(std::time::Duration::new(0, 1_000_000_000u32 / 100));
for event in event_pump.poll_iter() {
match event {
Event::Quit { .. }
| Event::KeyDown {
keycode: Some(Keycode::Escape),
..
} => break 'main_loop,
_ => {}
}
}
}
}
|
// This file is part of Webb.
// Copyright (C) 2021 Webb Technologies Inc.
// SPDX-License-Identifier: Apache-2.0
// 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.
//! # Mixer Module
//!
//! A simple module for building Mixers.
//!
//! ## Overview
//!
//! The Mixer module provides functionality for SMT operations
//! including:
//!
//! * Inserting elements to the tree
//!
//! The supported dispatchable functions are documented in the [`Call`] enum.
//!
//! ### Terminology
//!
//! ### Goals
//!
//! The Mixer system in Webb is designed to make the following possible:
//!
//! * Define.
//!
//! ## Interface
//!
//! ## Related Modules
//!
//! * [`System`](../frame_system/index.html)
//! * [`Support`](../frame_support/index.html)
// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(test)]
pub mod mock;
#[cfg(test)]
mod tests;
pub mod types;
use types::{MixerInspector, MixerInterface, MixerMetadata};
use codec::Encode;
use frame_support::{ensure, pallet_prelude::DispatchError};
use pallet_mt::types::{TreeInspector, TreeInterface};
use darkwebb_primitives::verifier::*;
use frame_support::traits::{Currency, ExistenceRequirement::AllowDeath, ReservableCurrency};
use frame_system::Config as SystemConfig;
use sp_std::prelude::*;
pub use pallet::*;
type BalanceOf<T, I = ()> = <<T as Config<I>>::Currency as Currency<<T as SystemConfig>::AccountId>>::Balance;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*};
use frame_system::pallet_prelude::*;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T, I = ()>(_);
#[pallet::config]
/// The module configuration trait.
pub trait Config<I: 'static = ()>: frame_system::Config + pallet_mt::Config<I> {
/// The overarching event type.
type Event: From<Event<Self, I>> + IsType<<Self as frame_system::Config>::Event>;
/// The tree
type Tree: TreeInterface<Self, I> + TreeInspector<Self, I>;
/// The verifier
type Verifier: VerifierModule;
/// The currency mechanism.
type Currency: ReservableCurrency<Self::AccountId>;
}
#[pallet::storage]
#[pallet::getter(fn maintainer)]
/// The parameter maintainer who can change the parameters
pub(super) type Maintainer<T: Config<I>, I: 'static = ()> = StorageValue<_, T::AccountId, ValueQuery>;
/// The map of trees to their mixer metadata
#[pallet::storage]
#[pallet::getter(fn mixers)]
pub type Mixers<T: Config<I>, I: 'static = ()> =
StorageMap<_, Blake2_128Concat, T::TreeId, MixerMetadata<T::AccountId, BalanceOf<T, I>>, ValueQuery>;
/// The map of trees to their spent nullifier hashes
#[pallet::storage]
#[pallet::getter(fn nullifier_hashes)]
pub type NullifierHashes<T: Config<I>, I: 'static = ()> =
StorageDoubleMap<_, Blake2_128Concat, T::TreeId, Blake2_128Concat, T::Element, bool, ValueQuery>;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config<I>, I: 'static = ()> {
MaintainerSet(T::AccountId, T::AccountId),
/// New tree created
MixerCreation(T::TreeId),
}
#[pallet::error]
pub enum Error<T, I = ()> {
/// Account does not have correct permissions
InvalidPermissions,
/// Invalid withdraw proof
InvalidWithdrawProof,
/// Invalid nullifier that is already used
/// (this error is returned when a nullifier is used twice)
AlreadyRevealedNullifier,
/// Invalid root used in withdrawal
InvalidWithdrawRoot,
}
#[pallet::hooks]
impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {}
#[pallet::call]
impl<T: Config<I>, I: 'static> Pallet<T, I> {
#[pallet::weight(0)]
pub fn create(origin: OriginFor<T>, deposit_size: BalanceOf<T, I>, depth: u8) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
let tree_id = <Self as MixerInterface<_, _>>::create(T::AccountId::default(), deposit_size, depth)?;
Self::deposit_event(Event::MixerCreation(tree_id));
Ok(().into())
}
#[pallet::weight(0)]
pub fn set_maintainer(origin: OriginFor<T>, new_maintainer: T::AccountId) -> DispatchResultWithPostInfo {
let origin = ensure_signed(origin)?;
// ensure parameter setter is the maintainer
ensure!(origin == Self::maintainer(), Error::<T, I>::InvalidPermissions);
// set the new maintainer
Maintainer::<T, I>::try_mutate(|maintainer| {
*maintainer = new_maintainer.clone();
Self::deposit_event(Event::MaintainerSet(origin, new_maintainer));
Ok(().into())
})
}
#[pallet::weight(0)]
pub fn force_set_maintainer(origin: OriginFor<T>, new_maintainer: T::AccountId) -> DispatchResultWithPostInfo {
T::ForceOrigin::ensure_origin(origin)?;
// set the new maintainer
Maintainer::<T, I>::try_mutate(|maintainer| {
*maintainer = new_maintainer.clone();
Self::deposit_event(Event::MaintainerSet(Default::default(), T::AccountId::default()));
Ok(().into())
})
}
#[pallet::weight(0)]
pub fn deposit(origin: OriginFor<T>, tree_id: T::TreeId, leaf: T::Element) -> DispatchResultWithPostInfo {
let origin = ensure_signed(origin)?;
<Self as MixerInterface<_, _>>::deposit(origin, tree_id, leaf)?;
Ok(().into())
}
#[pallet::weight(0)]
pub fn withdraw(
origin: OriginFor<T>,
id: T::TreeId,
proof_bytes: Vec<u8>,
root: T::Element,
nullifier_hash: T::Element,
recipient: T::AccountId,
relayer: T::AccountId,
fee: BalanceOf<T, I>,
refund: BalanceOf<T, I>,
) -> DispatchResultWithPostInfo {
ensure_signed(origin)?;
<Self as MixerInterface<_, _>>::withdraw(
id,
&proof_bytes,
root,
nullifier_hash,
recipient,
relayer,
fee,
refund,
)?;
Ok(().into())
}
}
}
impl<T: Config<I>, I: 'static> MixerInterface<T, I> for Pallet<T, I> {
fn create(creator: T::AccountId, deposit_size: BalanceOf<T, I>, depth: u8) -> Result<T::TreeId, DispatchError> {
let id = T::Tree::create(creator.clone(), depth)?;
Mixers::<T, I>::insert(id, MixerMetadata { creator, deposit_size });
Ok(id)
}
fn deposit(depositor: T::AccountId, id: T::TreeId, leaf: T::Element) -> Result<(), DispatchError> {
// insert the leaf
T::Tree::insert_in_order(id, leaf)?;
let mixer = Self::mixers(id);
// transfer tokens to the pallet
<T as pallet::Config<I>>::Currency::transfer(
&depositor,
&T::AccountId::default(),
mixer.deposit_size,
AllowDeath,
)?;
Ok(())
}
fn withdraw(
id: T::TreeId,
proof_bytes: &[u8],
root: T::Element,
nullifier_hash: T::Element,
recipient: T::AccountId,
relayer: T::AccountId,
fee: BalanceOf<T, I>,
refund: BalanceOf<T, I>,
) -> Result<(), DispatchError> {
let mixer = Self::mixers(id);
// Check if local root is known
ensure!(T::Tree::is_known_root(id, root)?, Error::<T, I>::InvalidWithdrawRoot);
// Check nullifier and add or return `AlreadyRevealedNullifier`
ensure!(
!Self::is_nullifier_used(id, nullifier_hash),
Error::<T, I>::AlreadyRevealedNullifier
);
Self::add_nullifier_hash(id, nullifier_hash)?;
// Format proof public inputs for verification
// FIXME: This is for a specfic gadget so we ought to create a generic handler
// FIXME: Such as a unpack/pack public inputs trait
// FIXME: -> T::PublicInputTrait::validate(public_bytes: &[u8])
let mut bytes = vec![];
let element_encoder = |v: &[u8]| {
let mut output = [0u8; 32];
output.iter_mut().zip(v).for_each(|(b1, b2)| *b1 = *b2);
output
};
let recipient_bytes = recipient.using_encoded(element_encoder);
let relayer_bytes = relayer.using_encoded(element_encoder);
let fee_bytes = fee.using_encoded(element_encoder);
let refund_bytes = refund.using_encoded(element_encoder);
bytes.extend_from_slice(&nullifier_hash.encode());
bytes.extend_from_slice(&root.encode());
bytes.extend_from_slice(&recipient_bytes);
bytes.extend_from_slice(&relayer_bytes);
bytes.extend_from_slice(&fee_bytes);
bytes.extend_from_slice(&refund_bytes);
// TODO: Update gadget being used to include fee as well
// TODO: This is not currently included in
// arkworks_gadgets::setup::mixer::get_public_inputs bytes.extend_from_slice(&
// fee.encode());
let result = T::Verifier::verify(&bytes, proof_bytes)?;
ensure!(result, Error::<T, I>::InvalidWithdrawProof);
<T as pallet::Config<I>>::Currency::transfer(
&T::AccountId::default(),
&recipient,
mixer.deposit_size,
AllowDeath,
)?;
Ok(())
}
fn add_nullifier_hash(id: T::TreeId, nullifier_hash: T::Element) -> Result<(), DispatchError> {
NullifierHashes::<T, I>::insert(id, nullifier_hash, true);
Ok(())
}
}
impl<T: Config<I>, I: 'static> MixerInspector<T, I> for Pallet<T, I> {
fn get_root(tree_id: T::TreeId) -> Result<T::Element, DispatchError> {
T::Tree::get_root(tree_id)
}
fn is_known_root(tree_id: T::TreeId, target_root: T::Element) -> Result<bool, DispatchError> {
T::Tree::is_known_root(tree_id, target_root)
}
fn is_nullifier_used(tree_id: T::TreeId, nullifier_hash: T::Element) -> bool {
NullifierHashes::<T, I>::contains_key(tree_id, nullifier_hash)
}
}
|
use super::prelude::*;
use core::fmt;
/// handler method to be called on a state change
type StateChangeHander = dyn FnMut() -> Result<(), BangBangError> + Sync + Send;
/// simple on/off bang-bang controller
///
/// # Simple Example
/// ```
/// use bangbang::prelude::*;
///
/// fn example() -> Result<(), BangBangError> {
/// // we can create this controller to start in the "on" state
/// let mut controller = OnOff::new(true, None, None);
/// assert_eq!(controller.is_on(), true);
/// assert_eq!(controller.is_off(), false);
///
/// // or, it can start in the "off" state
/// let mut controller = OnOff::new(false, None, None);
/// assert_eq!(controller.is_on(), false);
/// assert_eq!(controller.is_off(), true);
///
/// // transition state (in this case, from "off" to "on")
/// controller.bang()?;
/// assert_eq!(controller.is_on(), true);
/// assert_eq!(controller.is_off(), false);
///
/// Ok(())
/// }
/// ```
///
/// # Example with Custom State Change Handlers
/// ```
/// use bangbang::prelude::*;
///
/// fn example() -> Result<(), BangBangError> {
/// // handler that always fails, `code` is a failure code that we can choose arbitrarily
/// let mut handle_on = || Err(BangBangError::StateChangeFailedUnexpectedly {
/// from: BangBangState::A,
/// to: BangBangState::B,
/// code: 1,
/// });
///
/// // handler that always succeeds
/// let mut handle_off = || Ok(());
///
/// // this controller defaults to the on state
/// let mut controller = OnOff::new(true, Some(&mut handle_on), Some(&mut handle_off));
/// assert_eq!(controller.is_on(), true);
/// assert_eq!(controller.is_off(), false);
///
/// // transition to off state, will succeed given our handler
/// assert!(controller.bang().is_ok());
///
/// // because transition was successful, state has been updated
/// assert_eq!(controller.is_on(), true);
/// assert_eq!(controller.is_off(), false);
///
/// // transition to the on state, will fail given our handler
/// assert!(controller.bang().is_err());
///
/// // because transition failed, state remains the same
/// assert_eq!(controller.is_on(), true);
/// assert_eq!(controller.is_off(), false);
///
/// Ok(())
/// }
/// ```
#[derive(Default)]
pub struct OnOff<'a> {
on: bool,
handle_on: Option<&'a mut StateChangeHander>,
handle_off: Option<&'a mut StateChangeHander>,
}
impl fmt::Debug for OnOff<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "OnOff {{ on: {} }}", self.on)
}
}
impl BangBang for OnOff<'_> {
fn state(&self) -> BangBangState {
self.on.into()
}
fn set(&mut self, new_state: BangBangState) -> Result<(), BangBangError> {
let result = match new_state {
BangBangState::A => {
if let Some(handler) = &mut self.handle_off {
handler()
} else {
Ok(())
}
}
BangBangState::B => {
if let Some(handler) = &mut self.handle_on {
handler()
} else {
Ok(())
}
}
};
if result.is_ok() {
self.on = new_state != BangBangState::A;
}
result
}
}
impl<'a> OnOff<'a> {
/// creates a new on/off controller with optional notification handlers for each state transition
/// ```
/// use bangbang::OnOff;
///
/// // state transition handlers that never block state transition
/// let mut handle_on = || Ok(());
/// let mut handle_off = || Ok(());
///
/// // create a controller that starts in the off state
/// let on_off = OnOff::new(false, Some(&mut handle_on), Some(&mut handle_off));
/// assert!(on_off.is_off());
///
/// // create a controller that starts in the on state
/// let on_off = OnOff::new(true, Some(&mut handle_on), Some(&mut handle_off));
/// assert!(on_off.is_on());
/// ```
pub fn new(
on: bool,
handle_on: Option<&'a mut StateChangeHander>,
handle_off: Option<&'a mut StateChangeHander>,
) -> Self {
Self {
on,
handle_on,
handle_off,
}
}
/// convienence method for checking if the controller is in the `on` state
/// ```
/// use bangbang::prelude::*;
///
/// let on_off = OnOff::new(true, None, None);
///
/// // these two calls are equavalent
/// assert!(on_off.is_on());
/// assert_eq!(on_off.state(), BangBangState::B);
/// ```
pub fn is_on(&self) -> bool {
self.on
}
/// convienence method for checking if the controller is in the `off` state
/// ```
/// use bangbang::prelude::*;
///
/// let on_off = OnOff::new(false, None, None);
///
/// // these two calls are equavalent
/// assert!(on_off.is_off());
/// assert_eq!(on_off.state(), BangBangState::A);
/// ```
pub fn is_off(&self) -> bool {
!self.on
}
}
|
use crate::error::ClientError;
use crypto_exports::bellman::{pairing::ff::PrimeField, PrimeFieldRepr};
use crypto_exports::franklin_crypto::alt_babyjubjub::fs::FsRepr;
use models::node::{priv_key_from_fs, Fs, PrivateKey};
use sha2::{Digest, Sha256};
// Public re-exports.
pub use models::node::{
closest_packable_fee_amount, closest_packable_token_amount, is_fee_amount_packable,
is_token_amount_packable,
};
/// Generates a new `PrivateKey` from seed using a deterministic algorithm:
/// seed is hashed via `sha256` hash, and the output treated as a `PrivateKey`.
/// If the obtained value doesn't have a correct value to be a `PrivateKey`, hashing operation is applied
/// repeatedly to the previous output, until the value can be interpreted as a `PrivateKey`.
pub fn private_key_from_seed(seed: &[u8]) -> Result<PrivateKey, ClientError> {
if seed.len() < 32 {
return Err(ClientError::SeedTooShort);
}
let sha256_bytes = |input: &[u8]| -> Vec<u8> {
let mut hasher = Sha256::new();
hasher.input(input);
hasher.result().to_vec()
};
let mut effective_seed = sha256_bytes(seed);
loop {
let raw_priv_key = sha256_bytes(&effective_seed);
let mut fs_repr = FsRepr::default();
fs_repr
.read_be(&raw_priv_key[..])
.expect("failed to read raw_priv_key");
match Fs::from_repr(fs_repr) {
Ok(fs) => return Ok(priv_key_from_fs(fs)),
Err(_) => {
effective_seed = raw_priv_key;
}
}
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::collections::btree_map::BTreeMap;
use core::ops::Deref;
use alloc::sync::Arc;
use alloc::string::String;
use alloc::string::ToString;
use spin::Mutex;
use core::ops::Bound::*;
use super::super::range::*;
pub trait AreaValue: Send + Sync + Clone + Default {
fn Merge(&self, r1: &Range, _r2: &Range, vma2: &Self) -> Option<Self>;
fn Split(&self, r: &Range, split: u64) -> (Self, Self);
}
pub enum Area<T: AreaValue> {
AreaSeg(AreaSeg<T>),
AreaGap(AreaGap<T>),
}
impl<T: AreaValue> Area<T> {
pub fn NewSeg(entry: &AreaEntry<T>) -> Self {
return Self::AreaSeg(AreaSeg(entry.clone()));
}
pub fn NewGap(entry: &AreaEntry<T>) -> Self {
return Self::AreaGap(AreaGap(entry.clone()));
}
pub fn AreaGap(&self) -> AreaGap<T> {
match self {
Self::AreaGap(ref gap) => gap.clone(),
_ => AreaGap::default(),
}
}
pub fn AreaSeg(&self) -> AreaSeg<T> {
match self {
Self::AreaSeg(ref seg) => {
seg.clone()
}
_ => AreaSeg::default(),
}
}
pub fn IsSeg(&self) -> bool {
match self {
Self::AreaSeg(_) => true,
Self::AreaGap(_) => false,
}
}
pub fn IsGap(&self) -> bool {
return !self.IsSeg();
}
}
#[derive(Clone, Default)]
pub struct AreaSeg<T: AreaValue>(pub AreaEntry<T>);
impl<T: AreaValue> Deref for AreaSeg<T> {
type Target = AreaEntry<T>;
fn deref(&self) -> &AreaEntry<T> {
&self.0
}
}
impl<T: AreaValue> PartialEq for AreaSeg<T> {
fn eq(&self, other: &Self) -> bool {
return self.0 == other.0;
}
}
impl<T: AreaValue> Eq for AreaSeg<T> {}
impl<T: AreaValue> AreaSeg<T> {
pub fn New(entry: AreaEntry<T>) -> Self {
return Self(entry)
}
pub fn Value(&self) -> T {
return self.0.lock().Value().clone()
}
pub fn SetValue(&self, value: T) {
self.0.lock().value = Some(value);
}
pub fn NextNonEmpty(&self) -> (AreaSeg<T>, AreaGap<T>) {
let gap = self.NextGap();
if gap.Range().Len() != 0 {
return (AreaSeg::default(), gap)
}
return (gap.NextSeg(), AreaGap::default())
}
pub fn Ok(&self) -> bool {
return self.0.Ok();
}
pub fn PrevGap(&self) -> AreaGap<T> {
if self.0.IsHead() {
return AreaGap::default();
}
return AreaGap(self.0.PrevEntry().unwrap());
}
pub fn NextGap(&self) -> AreaGap<T> {
if self.0.IsTail() {
return AreaGap::default();
}
return AreaGap(self.0.clone())
}
pub fn NextSeg(&self) -> AreaSeg<T> {
if self.0.IsTail() {
return self.clone();
}
return AreaSeg(self.0.NextEntry().unwrap())
}
pub fn PrevSeg(&self) -> AreaSeg<T> {
if self.0.IsHead() {
return self.clone();
}
return AreaSeg(self.0.PrevEntry().unwrap())
}
}
#[derive(Clone, Default)]
pub struct AreaGap<T: AreaValue>(pub AreaEntry<T>); //the entry before the gap
impl<T: AreaValue> AreaGap<T> {
pub fn New(entry: AreaEntry<T>) -> Self {
return Self(entry)
}
pub fn Ok(&self) -> bool {
return !self.0.IsTail(); //use the tail for invalid AreaGap
}
pub fn PrevSeg(&self) -> AreaSeg<T> {
if !self.Ok() {
return AreaSeg::default();
}
return AreaSeg(self.0.clone()); //Gap's prevseg is always exist
}
pub fn NextSeg(&self) -> AreaSeg<T> {
if !self.Ok() {
return AreaSeg::default();
}
return AreaSeg(self.0.NextEntry().unwrap()); //Gap's entry won't be tail
}
pub fn PrevGap(&self) -> Self {
if !self.0.Ok() {
return Self::default();
}
let prevEntry = self.0.PrevEntry().unwrap(); //Gap's entry can't be tail;
return Self(prevEntry)
}
pub fn NextGap(&self) -> Self {
if !self.Ok() {
return Self::default();
}
let nextEntry = self.0.NextEntry().unwrap(); //Gap's entry can't be tail;
return Self(nextEntry)
}
pub fn Range(&self) -> Range {
if !self.Ok() {
return Range::New(0, 0);
}
let start = self.0.Range().End();
let end = self.0.NextEntry().unwrap().Range().Start();
return Range::New(start, end - start);
}
// IsEmpty returns true if the iterated gap is empty (that is, the "gap" is
// between two adjacent segments.)
pub fn IsEmpty(&self) -> bool {
return self.Range().Len() == 0;
}
}
#[derive(Default)]
pub struct AreaEntryInternal<T: AreaValue> {
pub range: Range,
pub value: Option<T>,
pub prev: Option<AreaEntry<T>>,
pub next: Option<AreaEntry<T>>,
}
impl<T: AreaValue> AreaEntryInternal<T> {
pub fn Value(&self) -> &T {
return self.value.as_ref().expect("AreaEntryInternal get None, it is head/tail")
}
}
#[derive(Clone, Default)]
pub struct AreaEntry<T: AreaValue>(pub Arc<Mutex<AreaEntryInternal<T>>>);
impl<T: AreaValue> Deref for AreaEntry<T> {
type Target = Arc<Mutex<AreaEntryInternal<T>>>;
fn deref(&self) -> &Arc<Mutex<AreaEntryInternal<T>>> {
&self.0
}
}
impl<T: AreaValue> PartialEq for AreaEntry<T> {
fn eq(&self, other: &Self) -> bool {
return Arc::ptr_eq(&self.0, &other.0);
}
}
impl<T: AreaValue> Eq for AreaEntry<T> {}
impl<T: AreaValue> AreaEntry<T> {
pub fn Dummy(start: u64, len: u64) -> Self {
let internal = AreaEntryInternal {
range: Range::New(start, len),
..Default::default()
};
return Self(Arc::new(Mutex::new(internal)))
}
pub fn New(start: u64, len: u64, vma: T) -> Self {
let internal = AreaEntryInternal {
range: Range::New(start, len),
value: Some(vma),
..Default::default()
};
return Self(Arc::new(Mutex::new(internal)))
}
pub fn Remove(&self) {
let mut curr = self.lock();
let prev = curr.prev.take().expect("prev is null");
let next = curr.next.take().expect("next is null");
(*prev).lock().next = Some(next.clone());
(*next).lock().prev = Some(prev.clone());
}
pub fn InsertAfter(&self, r: &Range, vma: T) -> Self {
let n = Self::New(r.Start(), r.Len(), vma);
let next = self.lock().next.take().expect("next is null");
self.lock().next = Some(n.clone());
n.lock().prev = Some(self.clone());
next.lock().prev = Some(n.clone());
n.lock().next = Some(next.clone());
return n;
}
//not head/tail
pub fn Ok(&self) -> bool {
let cur = self.lock();
return !(cur.prev.is_none() || cur.next.is_none());
}
pub fn IsHead(&self) -> bool {
return self.lock().prev.is_none();
}
pub fn IsTail(&self) -> bool {
return self.lock().next.is_none();
}
pub fn Range(&self) -> Range {
return self.lock().range;
}
//return next gap which not empty
pub fn NextNonEmptyGap(&self) -> Option<AreaGap<T>> {
let mut cur = self.clone();
while !cur.IsTail() {
//not tail
let next = cur.NextEntry().unwrap();
let end = next.Range().Start();
let start = cur.Range().End();
if start != end {
return Some(AreaGap(cur))
}
cur = next;
}
return None;
}
//return NextEntry of current
pub fn NextEntry(&self) -> Option<Self> {
if self.IsTail() {
return None;
}
let tmp = self.lock().next.clone().unwrap();
return Some(tmp);
}
//return Prev Area of current
pub fn PrevEntry(&self) -> Option<Self> {
if self.IsHead() {
return None;
}
let tmp = self.lock().prev.clone().unwrap();
return Some(tmp);
}
//return <prev Gap before the Area, the area before the Gap>
pub fn PrevNoneEmptyGap(&self) -> Option<AreaGap<T>> {
let mut cur = self.clone();
while !cur.IsHead() {
let prev = cur.PrevEntry().unwrap();
let start = prev.Range().End();
let end = cur.Range().Start();
if start != end {
return Some(AreaGap(prev))
}
cur = prev
};
return None;
}
}
#[derive(Clone)]
pub struct AreaSet<T: AreaValue> {
pub range: Range,
pub head: AreaEntry<T>,
pub tail: AreaEntry<T>,
//<start, <len, val>>
pub map: BTreeMap<u64, AreaEntry<T>>,
}
impl<T: AreaValue> AreaSet<T> {
pub fn New(start: u64, len: u64) -> Self {
let head = AreaEntry::Dummy(start, 0);
let tail = if len != core::u64::MAX {
AreaEntry::Dummy(start + len, 0)
} else {
AreaEntry::Dummy(core::u64::MAX, 0)
};
head.lock().next = Some(tail.clone());
tail.lock().prev = Some(head.clone());
return Self {
range: Range::New(start, len),
head: head,
tail: tail,
map: BTreeMap::new(),
}
}
pub fn Print(&self) -> String {
let mut output = "".to_string();
for (_, e) in &self.map {
output += &format!("range is {:x?}\n", e.Range())
}
return output;
}
pub fn Reset(&mut self, start: u64, len: u64) {
self.head.lock().range = Range::New(start, 0);
self.tail.lock().range = Range::New(start + len, 0);
self.range = Range::New(start, len);
}
// IsEmpty returns true if the set contains no segments.
pub fn IsEmpty(&self) -> bool {
return self.map.len() == 0;
}
// IsEmptyRange returns true iff no segments in the set overlap the given
// range.
pub fn IsEmptyRange(&self, range: &Range) -> bool {
if range.Len() == 0 {
return true;
}
let (_seg, gap) = self.Find(range.Start());
if !gap.Ok() {
return false;
}
return range.End() <= gap.Range().End();
}
// Span returns the total size of all segments in the set.
pub fn Span(&self) -> u64 {
let mut seg = self.FirstSeg();
let mut sz = 0;
while seg.Ok() {
sz += seg.Range().Len();
seg = seg.NextSeg();
}
return sz;
}
// SpanRange returns the total size of the intersection of segments in the set
// with the given range.
pub fn SpanRange(&self, r: &Range) -> u64 {
if r.Len() == 0 {
return 0;
}
let mut res = 0;
let mut seg = self.LowerBoundSeg(r.Start());
while seg.Ok() && seg.Range().Start() < r.End() {
res += seg.Range().Intersect(r).Len();
seg = seg.NextSeg();
}
return res;
}
//return first valid seg, i.e. not include head/tail
pub fn FirstSeg(&self) -> AreaSeg<T> {
let first = self.head.NextEntry().unwrap();
return AreaSeg(first);
}
//return last valid seg, i.e. not include head/tail
pub fn LastSeg(&self) -> AreaSeg<T> {
let last = self.tail.PrevEntry().unwrap();
return AreaSeg(last)
}
pub fn FirstGap(&self) -> AreaGap<T> {
return AreaGap(self.head.clone());
}
pub fn LastGap(&self) -> AreaGap<T> {
let prev = self.tail.PrevEntry().unwrap();
return AreaGap(prev);
}
pub fn FindArea(&self, key: u64) -> Area<T> {
if key < self.range.Start() {
return Area::AreaSeg(AreaSeg(self.head.clone()));
}
if key > self.range.End() {
return Area::AreaSeg(AreaSeg(self.tail.clone()));
}
let mut iter = self.map.range((Unbounded, Included(key))).rev();
let entry = match iter.next() {
None => {
self.head.clone()
},
Some((_, v)) => v.clone(),
};
if entry.Ok() && entry.Range().Contains(key) {
return Area::AreaSeg(AreaSeg(entry));
}
return Area::AreaGap(AreaGap(entry));
}
pub fn Find(&self, key: u64) -> (AreaSeg<T>, AreaGap<T>) {
let area = self.FindArea(key);
return (area.AreaSeg(), area.AreaGap());
}
// FindSegment returns the segment whose range contains the given key. If no
// such segment exists, FindSegment returns a terminal iterator.
pub fn FindSeg(&self, key: u64) -> AreaSeg<T> {
let area = self.FindArea(key);
return area.AreaSeg();
}
// LowerBoundSegment returns the segment with the lowest range that contains a
// key greater than or equal to min. If no such segment exists,
// LowerBoundSegment returns a terminal iterator.
pub fn LowerBoundSeg(&self, key: u64) -> AreaSeg<T> {
let (seg, gap) = self.Find(key);
if seg.Ok() {
return seg;
}
if gap.Ok() {
return gap.NextSeg();
}
return AreaSeg::default();
}
// UpperBoundSegment returns the segment with the highest range that contains a
// key less than or equal to max. If no such segment exists, UpperBoundSegment
// returns a terminal iterator.
pub fn UpperBoundSeg(&self, key: u64) -> AreaSeg<T> {
let (seg, gap) = self.Find(key);
if seg.Ok() {
return seg;
}
if gap.Ok() {
return gap.PrevSeg();
}
return AreaSeg::default();
}
//return the Gap containers the key
pub fn FindGap(&self, key: u64) -> AreaGap<T> {
let area = self.FindArea(key);
return area.AreaGap();
}
// LowerBoundGap returns the gap with the lowest range that is greater than or
// equal to min.
pub fn LowerBoundGap(&self, key: u64) -> AreaGap<T> {
let (seg, gap) = self.Find(key);
if gap.Ok() {
return gap;
}
if seg.Ok() {
return seg.NextGap();
}
return AreaGap::default();
}
// UpperBoundGap returns the gap with the highest range that is less than or
// equal to max.
pub fn UpperBoundGap(&self, key: u64) -> AreaGap<T> {
let (seg, gap) = self.Find(key);
if gap.Ok() {
return gap;
}
if seg.Ok() {
return seg.PrevGap();
}
return AreaGap::default();
}
// Add inserts the given segment into the set and returns true. If the new
// segment can be merged with adjacent segments, Add will do so. If the new
// segment would overlap an existing segment, Add returns false. If Add
// succeeds, all existing iterators are invalidated.
pub fn Add(&mut self, r: &Range, val: T) -> bool {
let gap = self.FindGap(r.Start());
if !gap.Ok() {
return false;
}
if r.End() > gap.Range().End() {
return false;
}
self.Insert(&gap, r, val);
return true;
}
// AddWithoutMerging inserts the given segment into the set and returns true.
// If it would overlap an existing segment, AddWithoutMerging does nothing and
// returns false. If AddWithoutMerging succeeds, all existing iterators are
// invalidated.
pub fn AddWithoutMerging(&mut self, r: &Range, val: T) -> bool {
let gap = self.FindGap(r.Start());
if !gap.Ok() {
return false;
}
if r.End() > gap.Range().End() {
return false;
}
self.InsertWithoutMergingUnchecked(&gap, r, val);
return true;
}
// Insert inserts the given segment into the given gap. If the new segment can
// be merged with adjacent segments, Insert will do so. Insert returns an
// iterator to the segment containing the inserted value (which may have been
// merged with other values). All existing iterators (including gap, but not
// including the returned iterator) are invalidated.
//
// If the gap cannot accommodate the segment, or if r is invalid, Insert panics.
//
// Insert is semantically equivalent to a InsertWithoutMerging followed by a
// Merge, but may be more efficient. Note that there is no unchecked variant of
// Insert since Insert must retrieve and inspect gap's predecessor and
// successor segments regardless.
pub fn Insert(&mut self, gap: &AreaGap<T>, r: &Range, val: T) -> AreaSeg<T> {
let prev = gap.PrevSeg();
let next = gap.NextSeg();
if prev.Ok() && prev.Range().End() > r.Start() {
panic!("new segment {:x?} overlaps predecessor {:x?}", r, prev.Range())
}
if next.Ok() && next.Range().Start() < r.End() {
panic!("new segment {:x?} overlaps successor {:x?}", r, next.Range())
}
//can't enable merge segment as the return merged segment might override the COW page
//todo: fix this
let r1 = prev.Range();
if prev.Ok() && prev.Range().End() == r.Start() {
let mval = prev.lock().Value().Merge(&r1, &r, &val);
if mval.is_some() {
prev.lock().range.len += r.Len();
prev.lock().value = mval.clone();
if next.Ok() && next.Range().Start() == r.End() {
let val = mval.clone().unwrap();
let r1 = prev.Range();
let r2 = next.Range();
let mval = val.Merge(&r1, &r2, next.lock().Value());
if mval.is_some() {
prev.lock().range.len += next.Range().Len();
prev.lock().value = mval;
return self.Remove(&next).PrevSeg();
}
}
return prev;
}
}
if next.Ok() && next.Range().Start() == r.End() {
let r2 = next.Range();
let mval = val.Merge(&r, &r2, next.lock().Value());
if mval.is_some() {
next.lock().range.start = r.Start();
next.lock().range.len += r.Len();
next.lock().value = mval;
self.map.remove(&r.End());
self.map.insert(r.Start(), next.0.clone());
return next;
}
}
return self.InsertWithoutMergingUnchecked(gap, r, val);
}
// InsertWithoutMerging inserts the given segment into the given gap and
// returns an iterator to the inserted segment. All existing iterators
// (including gap, but not including the returned iterator) are invalidated.
//
// If the gap cannot accommodate the segment, or if r is invalid,
// InsertWithoutMerging panics.
pub fn InsertWithoutMerging(&mut self, gap: &AreaGap<T>, r: &Range, val: T) -> AreaSeg<T> {
let gr = gap.Range();
if !gr.IsSupersetOf(r) {
panic!("cannot insert segment range {:?} into gap range {:?}", r, gr);
}
return self.InsertWithoutMergingUnchecked(gap, r, val);
}
// InsertWithoutMergingUnchecked inserts the given segment into the given gap
// and returns an iterator to the inserted segment. All existing iterators
// (including gap, but not including the returned iterator) are invalidated.
pub fn InsertWithoutMergingUnchecked(&mut self, gap: &AreaGap<T>, r: &Range, val: T) -> AreaSeg<T> {
let prev = gap.PrevSeg();
let n = prev.InsertAfter(r, val);
self.map.insert(r.Start(), n.clone());
return AreaSeg(n);
}
// Remove removes the given segment and returns an iterator to the vacated gap.
// All existing iterators (including seg, but not including the returned
// iterator) are invalidated.
pub fn Remove(&mut self, e: &AreaSeg<T>) -> AreaGap<T> {
assert!(e.Ok(), "Remove: can't remove head/tail entry");
let prev = e.PrevSeg();
self.map.remove(&e.Range().Start());
e.Remove();
return prev.NextGap();
}
// RemoveAll removes all segments from the set. All existing iterators are
// invalidated.
pub fn RemoveAll(&mut self) {
for (_, e) in &self.map {
e.Remove();
}
self.map.clear();
}
// RemoveRange removes all segments in the given range. An iterator to the
// newly formed gap is returned, and all existing iterators are invalidated.
pub fn RemoveRange(&mut self, r: &Range) -> AreaGap<T> {
let (mut seg, mut gap) = self.Find(r.Start());
if seg.Ok() {
seg = self.Isolate(&seg, r);
gap = self.Remove(&seg);
}
seg = gap.NextSeg();
while seg.Ok() && seg.Range().Start() < r.End() {
seg = self.Isolate(&seg, r);
gap = self.Remove(&seg);
}
return gap;
}
// Merge attempts to merge two neighboring segments. If successful, Merge
// returns an iterator to the merged segment, and all existing iterators are
// invalidated. Otherwise, Merge returns a terminal iterator.
//
// If first is not the predecessor of second, Merge panics.
pub fn Merge(&mut self, first: &AreaSeg<T>, second: &AreaSeg<T>) -> AreaSeg<T> {
if first.NextSeg() != second.clone() {
panic!("attempt to merge non-neighboring segments {:?}, {:?}", first.Range(), second.Range())
}
return self.MergeUnchecked(first, second);
}
// MergeUnchecked attempts to merge two neighboring segments. If successful,
// MergeUnchecked returns an iterator to the merged segment, and all existing
// iterators are invalidated. Otherwise, MergeUnchecked returns a terminal
// iterator.
pub fn MergeUnchecked(&mut self, first: &AreaSeg<T>, second: &AreaSeg<T>) -> AreaSeg<T> {
if !first.Ok() || !second.Ok() {
//can't merge head or tail
return AreaSeg::default();
}
if first.Range().End() == second.Range().Start() {
let r1 = first.Range();
let r2 = second.Range();
let vma = first.lock().Value().Merge(&r1, &r2, second.lock().Value());
if vma.is_some() {
first.lock().range.len += second.lock().range.len;
first.lock().value = vma;
self.Remove(&second);
return first.clone();
}
}
return AreaSeg::default();
}
// MergeAll attempts to merge all adjacent segments in the set. All existing
// iterators are invalidated.
pub fn MergeAll(&mut self) {
let mut seg = self.FirstSeg();
if !seg.Ok() {
return;
}
let mut next = seg.NextSeg();
while next.Ok() {
let mseg = self.MergeUnchecked(&seg, &next);
if mseg.Ok() {
seg = mseg;
next = seg.NextSeg();
} else {
seg = next;
next = seg.NextSeg();
}
}
}
// MergeRange attempts to merge all adjacent segments that contain a key in the
// specific range.
pub fn MergeRange(&mut self, r: &Range) {
let mut seg = self.LowerBoundSeg(r.Start());
if !seg.Ok() {
return
}
let mut next = seg.NextSeg();
while next.Ok() && next.Range().Start() < r.End() {
let mseg = self.MergeUnchecked(&seg, &next);
if mseg.Ok() {
seg = mseg;
next = seg.NextSeg();
} else {
seg = next;
next = seg.NextSeg();
}
}
}
// MergeAdjacent attempts to merge the segment containing r.Start with its
// predecessor, and the segment containing r.End-1 with its successor.
pub fn MergeAdjacent(&mut self, r: &Range) {
let first = self.FindSeg(r.Start());
if first.Ok() {
let prev = first.PrevSeg();
if prev.Ok() {
self.Merge(&prev, &first);
}
}
let last = self.FindSeg(r.End() - 1);
if last.Ok() {
let next = last.NextSeg();
if next.Ok() {
self.Merge(&last, &next);
}
}
}
// Split splits the given segment at the given key and returns iterators to the
// two resulting segments. All existing iterators (including seg, but not
// including the returned iterators) are invalidated.
//
// If the segment cannot be split at split (because split is at the start or
// end of the segment's range, so splitting would produce a segment with zero
// length, or because split falls outside the segment's range altogether),
// Split panics.
pub fn Split(&mut self, seg: &AreaSeg<T>, split: u64) -> (AreaSeg<T>, AreaSeg<T>) {
let r = seg.Range();
if !r.CanSplitAt(split) {
panic!("can't split {:?} at {:?}", r, split);
}
return self.SplitUnchecked(seg, split);
}
// SplitUnchecked splits the given segment at the given key and returns
// iterators to the two resulting segments. All existing iterators (including
// seg, but not including the returned iterators) are invalidated.
pub fn SplitUnchecked(&mut self, seg: &AreaSeg<T>, split: u64) -> (AreaSeg<T>, AreaSeg<T>) {
let range = seg.Range();
let (val1, val2) = seg.lock().Value().Split(&range, split);
let end2 = range.End();
seg.lock().range.len = split - range.Start();
seg.lock().value = Some(val1);
let gap = seg.NextNonEmptyGap().unwrap();
let seg2 = self.InsertWithoutMergingUnchecked(&gap, &Range::New(split, end2 - split), val2);
let prev = seg2.PrevSeg();
return (prev, seg2)
}
// SplitAt splits the segment straddling split, if one exists. SplitAt returns
// true if a segment was split and false otherwise. If SplitAt splits a
// segment, all existing iterators are invalidated.
pub fn SplitAt(&mut self, split: u64) -> bool {
let seg = self.FindSeg(split);
if !seg.Ok() {
return false;
}
let r = seg.Range();
if r.CanSplitAt(split) {
self.SplitUnchecked(&seg, split);
return true;
}
return false;
}
// Isolate ensures that the given segment's range does not escape r by
// splitting at r.Start and r.End if necessary, and returns an updated iterator
// to the bounded segment. All existing iterators (including seg, but not
// including the returned iterators) are invalidated.
pub fn Isolate(&mut self, seg: &AreaSeg<T>, r: &Range) -> AreaSeg<T> {
let mut seg = seg.clone();
let curr = seg.Range();
if curr.CanSplitAt(r.Start()) {
let (_, tmp) = self.SplitUnchecked(&seg, r.Start());
seg = tmp;
}
let curr = seg.Range();
if curr.CanSplitAt(r.End()) {
let (tmp, _) = self.SplitUnchecked(&seg, r.End());
seg = tmp;
}
return seg;
}
// ApplyContiguous applies a function to a contiguous range of segments,
// splitting if necessary. The function is applied until the first gap is
// encountered, at which point the gap is returned. If the function is applied
// across the entire range, a terminal gap is returned. All existing iterators
// are invalidated.
pub fn ApplyContiguous(&mut self, r: &Range, mut f: impl FnMut(&AreaEntry<T>)) -> AreaGap<T> {
let (mut seg, mut gap) = self.Find(r.Start());
if !seg.Ok() {
return gap;
}
loop {
seg = self.Isolate(&seg, r);
f(&seg);
if seg.Range().End() > r.End() {
return AreaGap::default();
}
gap = seg.NextGap();
if !gap.IsEmpty() {
return gap;
}
seg = gap.NextSeg();
if !seg.Ok() {
return AreaGap::default();
}
}
}
} |
use std::time::Duration;
use crate::{
Resource,
RotatorError,
RotatorEvent,
RotatorResult,
};
use crate::value::{get_secret_value, put_secret_value};
pub fn create_secret(e: RotatorEvent, r: Box<dyn Resource>) -> RotatorResult<()> {
let timeout = Duration::from_secs(2);
let current = get_secret_value(&e.secret_id, Some("AWSCURRENT"), None, timeout)?;
match get_secret_value(&e.secret_id, Some("AWSPENDING"), Some(&e.client_request_token), timeout) {
Ok(_) => {
info!("createSecret: Successfully retrieved secret for {}.", e.secret_id);
Ok(())
},
Err(RotatorError::SecretValueNotFound { .. }) => {
let secret = r.create_new_password(current)?;
put_secret_value(&e.secret_id, &e.client_request_token, &secret, "AWSPENDING", timeout)?;
info!("createSecret: Successfully put secret for ARN {} and version {}.", e.secret_id, e.client_request_token);
Ok(())
},
Err(err) => {
error!("createSecret: Error retrieving secret for ARN {} and version {}: {:?}.", e.secret_id, e.client_request_token, err);
Err(err)
}
}?;
Ok(())
} |
pub mod event;
pub mod core;
|
use std::fmt;
use std::str::FromStr;
use clap::ArgMatches;
use crate::config::options::{invalid_value, required_option_missing};
use crate::config::options::{OptionInfo, ParseOption};
/// The type of project we're building
#[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
pub enum ProjectType {
Executable,
Dylib,
Staticlib,
Cdylib,
}
impl ProjectType {
pub fn is_executable(&self) -> bool {
if let Self::Executable = self {
return true;
}
false
}
pub fn requires_link(&self) -> bool {
match self {
Self::Executable | Self::Dylib | Self::Cdylib => true,
_ => false,
}
}
}
impl Default for ProjectType {
fn default() -> Self {
ProjectType::Executable
}
}
impl fmt::Display for ProjectType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ProjectType::Executable => "bin".fmt(f),
ProjectType::Dylib => "dylib".fmt(f),
ProjectType::Staticlib => "staticlib".fmt(f),
ProjectType::Cdylib => "cdylib".fmt(f),
}
}
}
impl FromStr for ProjectType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"lib" | "dylib" => Ok(Self::Dylib),
"staticlib" => Ok(Self::Staticlib),
"cdylib" => Ok(Self::Cdylib),
"bin" => Ok(Self::Executable),
_ => Err(()),
}
}
}
impl ParseOption for ProjectType {
fn parse_option<'a>(info: &OptionInfo, matches: &ArgMatches<'a>) -> clap::Result<Self> {
match matches.value_of(info.name) {
None => Err(required_option_missing(info)),
Some(s) => s
.parse()
.map_err(|_| invalid_value(info, &format!("unknown project type: `{}`", s))),
}
}
}
|
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 s: String = read();
let t: String = read();
let mut a = 31;
if s == "Sun" || s == "Sat" {
a += 1;
if t == "Sun" || t == "Sat" {
a += 1;
}
}
println!("8/{}", a);
}
|
mod human_agent;
pub use human_agent::HumanAgent;
mod random_agent;
pub use random_agent::RandomAgent;
mod training_agent;
pub use training_agent::TrainingAgent;
#[derive(PartialEq, Eq)]
enum Turn {
Player1,
Player2,
}
use Turn::*;
enum MoveResult {
None,
Lost,
Won,
}
#[allow(unused)]
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Direction {
CW,
CCW,
}
impl Direction {
#[inline(always)]
fn next_index(&self, index: usize) -> usize {
match self {
Direction::CW => {
if index == 0 {
15
} else {
index - 1
}
}
Direction::CCW => {
if index == 15 {
0
} else {
index + 1
}
}
}
}
}
#[allow(unused)]
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Mode {
Normal, // all stones required
Easy, // just the inner row must be empty to win
}
pub struct Player {
name: String,
tag: usize,
board_half: [u8; 16],
}
impl Player {
pub fn new(name: &str, tag: usize) -> Self {
Self {
name: String::from(name),
tag,
board_half: [2; 16],
}
}
#[inline(always)]
pub fn name(&self) -> &str {
&self.name
}
#[inline(always)]
pub fn tag(&self) -> usize {
self.tag
}
#[inline(always)]
fn is_valid_index(&self, index: usize) -> bool {
self.board_half[index] > 1
}
#[inline(always)]
fn has_lost(&self, mode: Mode) -> bool {
// If there is at most one stone per bowl: lost
if self.board_half.iter().all(|&bowl| bowl < 2) {
return true;
}
// If this is easy mode and the inner row is empty: lost
if (mode == Mode::Easy) && self.board_half.iter().skip(8).all(|&bowl| bowl < 2) {
return true;
}
// Otherwise: not lost
false
}
}
pub trait Agent {
fn pick_index(&mut self, game: &Game) -> usize;
}
pub struct GameResult {
pub winner: Player,
pub loser: Player,
pub turn_count: usize,
}
pub struct Game {
direction: Direction,
mode: Mode,
turn_count: usize,
player1: Player,
player2: Player,
}
impl Game {
pub fn new(direction: Direction, mode: Mode, player1: Player, player2: Player) -> Self {
Self {
direction,
mode,
turn_count: 1,
player1,
player2,
}
}
pub fn play<A1: Agent, A2: Agent>(mut self, agent1: &mut A1, agent2: &mut A2) -> GameResult {
let (winner, loser) = loop {
let move_result = if self.turn() == Player1 {
self.make_move(agent1)
} else {
self.make_move(agent2)
};
match (move_result, self.turn()) {
(MoveResult::Won, Player1) | (MoveResult::Lost, Player2) => {
break (self.player1, self.player2)
}
(MoveResult::Lost, Player1) | (MoveResult::Won, Player2) => {
break (self.player2, self.player1)
}
_ => self.turn_count += 1,
}
};
GameResult {
winner,
loser,
turn_count: self.turn_count,
}
}
#[inline(always)]
fn turn(&self) -> Turn {
if (self.turn_count % 2) == 1 {
Player1
} else {
Player2
}
}
fn make_move<A: Agent>(&mut self, agent: &mut A) -> MoveResult {
let mut index = agent.pick_index(self);
let (player, opponent) = if self.turn() == Player1 {
(&mut self.player1, &mut self.player2)
} else {
(&mut self.player2, &mut self.player1)
};
debug_assert!(
(index < 16) && player.is_valid_index(index),
"Invalid index"
);
let mut hand = player.board_half[index];
player.board_half[index] = 0;
//println!("{} choose index {}", player.name, index);
while hand > 0 {
index = self.direction.next_index(index);
hand -= 1;
player.board_half[index] += 1;
if hand == 0 && player.board_half[index] >= 2 {
hand = player.board_half[index];
player.board_half[index] = 0;
// steal from opponent
if (8..=15).contains(&index) {
let opponent_index = (15 - index) + 8;
hand += match self.mode {
Mode::Easy => {
let steal = opponent.board_half[opponent_index];
opponent.board_half[opponent_index] = 0;
steal
}
Mode::Normal => {
let opponent_2nd_index = 15 - opponent_index;
let steal = opponent.board_half[opponent_index]
+ opponent.board_half[opponent_2nd_index];
opponent.board_half[opponent_index] = 0;
opponent.board_half[opponent_2nd_index] = 0;
steal
}
};
// check win condition after steal!
if opponent.has_lost(self.mode) {
return MoveResult::Won;
}
}
}
}
// check lose condition after move!
if player.has_lost(self.mode) {
MoveResult::Lost
} else {
MoveResult::None
}
}
}
|
use serde::Deserialize;
use crate::{
options::{ClientOptions, ResolverConfig},
test::run_spec_test,
};
#[derive(Debug, Deserialize)]
struct TestFile {
uri: String,
seeds: Vec<String>,
hosts: Vec<String>,
options: Option<ResolvedOptions>,
parsed_options: Option<ParsedOptions>,
error: Option<bool>,
comment: Option<String>,
}
#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
struct ResolvedOptions {
replica_set: Option<String>,
auth_source: Option<String>,
ssl: bool,
}
#[derive(Debug, Deserialize, Default, PartialEq)]
struct ParsedOptions {
user: Option<String>,
password: Option<String>,
db: Option<String>,
}
#[cfg_attr(feature = "tokio-runtime", tokio::test)]
#[cfg_attr(feature = "async-std-runtime", async_std::test)]
async fn run() {
async fn run_test(mut test_file: TestFile) {
// TODO DRIVERS-796: unskip this test
if test_file.uri == "mongodb+srv://test5.test.build.10gen.cc/?authSource=otherDB" {
return;
}
let result = if cfg!(target_os = "windows") {
ClientOptions::parse_with_resolver_config(&test_file.uri, ResolverConfig::cloudflare())
.await
} else {
ClientOptions::parse(&test_file.uri).await
};
if let Some(true) = test_file.error {
assert!(matches!(result, Err(_)), test_file.comment.unwrap());
return;
}
assert!(matches!(result, Ok(_)));
let options = result.unwrap();
let mut expected_seeds = test_file.seeds.split_off(0);
let mut actual_seeds = options
.hosts
.iter()
.map(|address| address.to_string())
.collect::<Vec<_>>();
expected_seeds.sort();
actual_seeds.sort();
assert_eq!(expected_seeds, actual_seeds,);
// The spec tests use two fields to compare against for the authentication database. In the
// `parsed_options` field, there is a `db` field which is populated with the database
// between the `/` and the querystring of the URI, and in the `options` field, there is an
// `authSource` field that is populated with whatever the driver should resolve `authSource`
// to from both the URI and the TXT options. Because we don't keep track of where we found
// the auth source in ClientOptions and the point of testing this behavior in this spec is
// to ensure that the right database is chosen based on both the URI and TXT options, we
// just determine what that should be and stick that in all of the options parsed from the
// spec JSON.
let resolved_db = test_file
.options
.as_ref()
.and_then(|opts| opts.auth_source.clone())
.or_else(|| {
test_file
.parsed_options
.as_ref()
.and_then(|opts| opts.db.clone())
});
if let Some(ref mut resolved_options) = test_file.options {
resolved_options.auth_source = resolved_db.clone();
let actual_options = ResolvedOptions {
replica_set: options.repl_set_name.clone(),
auth_source: options
.credential
.as_ref()
.and_then(|cred| cred.source.clone()),
ssl: options.tls_options().is_some(),
};
assert_eq!(&actual_options, resolved_options);
}
if let Some(mut parsed_options) = test_file.parsed_options {
parsed_options.db = resolved_db;
let actual_options = options
.credential
.map(|cred| ParsedOptions {
user: cred.username,
password: cred.password,
// In some spec tests, neither the `authSource` or `db` field are given, but in
// order to pass all the auth and URI options tests, the driver populates the
// credential's `source` field with "admin". To make it easier to assert here,
// we only populate the makeshift options with the credential's source if the
// JSON also specifies one of the database fields.
db: parsed_options.db.as_ref().and(cred.source),
})
.unwrap_or_default();
assert_eq!(parsed_options, actual_options);
}
}
run_spec_test(&["initial-dns-seedlist-discovery"], run_test).await;
}
|
//! Provides ready to use `NamedNode`s for basic RDF vocabularies
pub mod rdf {
//! [RDF 1.1](https://www.w3.org/TR/rdf11-concepts/) vocabulary
use crate::model::named_node::NamedNode;
use lazy_static::lazy_static;
lazy_static! {
/// The class of containers of alternatives.
pub static ref ALT: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#Alt");
/// The class of unordered containers.
pub static ref BAG: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#Bag");
/// The first item in the subject RDF list.
pub static ref FIRST: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#first");
/// The class of HTML literal values.
pub static ref HTML: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML");
/// The class of language-tagged string literal values.
pub static ref LANG_STRING: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString");
/// The class of RDF Lists.
pub static ref LIST: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#List");
pub static ref NIL: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#nil");
/// The object of the subject RDF statement.
pub static ref OBJECT: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#object");
/// The predicate of the subject RDF statement.
pub static ref PREDICATE: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate");
/// The class of RDF properties.
pub static ref PROPERTY: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#Property");
/// The rest of the subject RDF list after the first item.
pub static ref REST: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#rest");
/// The class of ordered containers.
pub static ref SEQ: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#Seq");
/// The class of RDF statements.
pub static ref STATEMENT: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement");
/// The subject of the subject RDF statement.
pub static ref SUBJECT: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#subject");
/// The subject is an instance of a class.
pub static ref TYPE: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
/// Idiomatic property used for structured values.
pub static ref VALUE: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#value");
/// The class of XML literal values.
pub static ref XML_LITERAL: NamedNode =
NamedNode::new_from_string("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral");
}
}
pub mod rdfs {
//! [RDFS](https://www.w3.org/TR/rdf-schema/) vocabulary
use crate::model::named_node::NamedNode;
use lazy_static::lazy_static;
lazy_static! {
/// The class of classes.
pub static ref CLASS: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#Class");
/// A description of the subject resource.
pub static ref COMMENT: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#comment");
/// The class of RDF containers.
pub static ref CONTAINER: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#Container");
/// The class of container membership properties, rdf:_1, rdf:_2, ..., all of which are sub-properties of 'member'.
pub static ref CONTAINER_MEMBERSHIP_PROPERTY: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#ContainerMembershipProperty");
/// The class of RDF datatypes.
pub static ref DATATYPE: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#Datatype");
/// A domain of the subject property.
pub static ref DOMAIN: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#domain");
/// The definition of the subject resource.
pub static ref IS_DEFINED_BY: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#isDefinedBy");
/// A human-readable name for the subject.
pub static ref LABEL: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#label");
/// The class of literal values, e.g. textual strings and integers.
pub static ref LITERAL: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#Literal");
/// A member of the subject resource.
pub static ref MEMBER: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#member");
/// A range of the subject property.
pub static ref RANGE: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#range");
/// The class resource, everything.
pub static ref RESOURCE: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#Resource");
/// Further information about the subject resource.
pub static ref SEE_ALSO: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#seeAlso");
/// The subject is a subclass of a class.
pub static ref SUB_CLASS_OF: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#subClassOf");
/// The subject is a subproperty of a property.
pub static ref SUB_PROPERTY_OF: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2000/01/rdf-schema#subPropertyOf");
}
}
pub mod xsd {
//! `NamedNode`s for [RDF compatible XSD datatypes](https://www.w3.org/TR/rdf11-concepts/#dfn-rdf-compatible-xsd-types)
use crate::model::named_node::NamedNode;
use lazy_static::lazy_static;
lazy_static! {
/// true, false
pub static ref BOOLEAN: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#boolean");
/// 128…+127 (8 bit)
pub static ref BYTE: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#byte");
/// Dates (yyyy-mm-dd) with or without timezone
pub static ref DATE: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#date");
/// Duration of time (days, hours, minutes, seconds only)
pub static ref DAY_TIME_DURATION: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#dayTimeDuration");
/// Date and time with or without timezone
pub static ref DATE_TIME: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#dateTime");
/// Date and time with required timezone
pub static ref DATE_TIME_STAMP: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#dateTimeStamp");
/// Arbitrary-precision decimal numbers
pub static ref DECIMAL: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#decimal");
/// 64-bit floating point numbers incl. ±Inf, ±0, NaN
pub static ref DOUBLE: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#double");
/// Duration of time
pub static ref DURATION: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#duration");
/// 32-bit floating point numbers incl. ±Inf, ±0, NaN
pub static ref FLOAT: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#float");
/// Gregorian calendar day of the month
pub static ref G_DAY: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#gDay");
/// Gregorian calendar month
pub static ref G_MONTH: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#gMonth");
/// Gregorian calendar month and day
pub static ref G_MONTH_DAY: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#gMonthDay");
/// Gregorian calendar year
pub static ref G_YEAR: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#gYear");
/// Gregorian calendar year and month
pub static ref G_YEAR_MONTH: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#gYearMonth");
/// -2147483648…+2147483647 (32 bit)
pub static ref INT: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#int");
/// Arbitrary-size integer numbers
pub static ref INTEGER: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#integer");
/// -9223372036854775808…+9223372036854775807 (64 bit)
pub static ref LONG: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#long");
/// Integer numbers <0
pub static ref NEGATIVE_INTEGER: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#negativeInteger");
/// Integer numbers ≥0
pub static ref NON_NEGATIVE_INTEGER: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#nonNegativeInteger");
/// Integer numbers ≤0
pub static ref NON_POSITIVE_INTEGER: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#nonPositiveInteger");
/// Integer numbers >0
pub static ref POSITIVE_INTEGER: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#positiveInteger");
/// Times (hh:mm:ss.sss…) with or without timezone
pub static ref TIME: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#time");
/// -32768…+32767 (16 bit)
pub static ref SHORT: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#short");
/// Character strings (but not all Unicode character strings)
pub static ref STRING: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#string");
/// 0…255 (8 bit)
pub static ref UNSIGNED_BYTE: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#unsignedByte");
/// 0…4294967295 (32 bit)
pub static ref UNSIGNED_INT: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#unsignedInt");
/// 0…18446744073709551615 (64 bit)
pub static ref UNSIGNED_LONG: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#unsignedLong");
/// 0…65535 (16 bit)
pub static ref UNSIGNED_SHORT: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#unsignedShort");
/// Duration of time (months and years only)
pub static ref YEAR_MONTH_DURATION: NamedNode =
NamedNode::new_from_string("http://www.w3.org/2001/XMLSchema#yearMonthDuration");
}
}
|
extern crate std;
use std::cmp::Ord;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::collections::HashMap;
#[derive(PartialEq, Eq)]
struct FNode<N: Eq>(i32, N);
impl<N: Eq> Ord for FNode<N> {
fn cmp(&self, other: &Self) -> Ordering {
self.0.cmp(&other.0).reverse()
}
}
impl<N: Eq> PartialOrd for FNode<N> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
pub trait Graph {
type Node: Clone + Eq + std::hash::Hash;
type Move: Copy + Clone;
fn neighbors(&self, &Self::Node) -> Vec<(Self::Move, Self::Node)>;
fn is_goal(&self, &Self::Node) -> bool;
}
fn build_path<G>(come_from: &HashMap<G::Node, (G::Move, G::Node)>, end: G::Node) -> Vec<(G::Move, G::Node)>
where G: Graph
{
let mut ret = Vec::new();
let mut prev = &end;
while let Some(&(ref mov, ref curr)) = come_from.get(&prev) {
ret.push((*mov, (*curr).clone()));
prev = curr;
}
ret.reverse();
ret
}
pub fn a_star<G, H>(graph: &G, start: G::Node, h: H) -> (usize, Option<Vec<(G::Move, G::Node)>>)
where G: Graph,
H: Fn(&G, &G::Node) -> i32
{
let mut frontier: BinaryHeap<FNode<G::Node>> = BinaryHeap::new();
let mut come_from: HashMap<G::Node, (G::Move, G::Node)> = HashMap::new();
let mut cost: HashMap<G::Node, i32> = HashMap::new();
let mut counter = 0;
let max = std::i32::MAX;
frontier.push(FNode(0, start.clone()));
cost.insert(start.clone(), 0);
while let Some(FNode(_, curr)) = frontier.pop() {
counter += 1;
if graph.is_goal(&curr) {
let path = build_path::<G>(&come_from, curr);
return (counter, Some(path));
}
for (mov, next) in graph.neighbors(&curr) {
let new_cost = cost[&curr] + 1;
let old_cost = *cost.get(&next).unwrap_or(&max);
if new_cost < old_cost {
cost.insert(next.clone(), new_cost);
come_from.insert(next.clone(), (mov, curr.clone()));
frontier.push(FNode(new_cost + h(graph, &next), next.clone()));
}
}
}
(counter, None)
}
|
use super::tree::*;
use super::lexem::*;
use std::fmt::Debug;
use super::num::Float;
use std::str::FromStr;
use parser::faces::Function;
use std::collections::HashMap;
use parser::faces::FnFunction;
#[derive(Debug)]
pub struct BuilderErr(
String,
Option<Builder>,
);
type BuildResult = Result<Builder, BuilderErr>;
type BB = Box<Builder>;
impl Into<BuildResult> for Builder {
fn into(self) -> BuildResult {
Ok(self)
}
}
impl<O> Into<Result<O, BuilderErr>> for BuilderErr {
fn into(self) -> Result<O, BuilderErr> {
Err(self)
}
}
#[derive(Debug)]
pub enum Builder {
Empty,
Simple(Lexem),
Complex(Operand, BB, BB),
Body(BB),
Complete(BB),
Fun(String, Vec<Builder>),
}
impl Builder {
fn sin<T: Float>(args: Vec<T>) -> Option<T> {
Some(args[0].sin())
}
fn cos<T: Float>(args: Vec<T>) -> Option<T> {
Some(args[0].cos())
}
pub fn new() -> Builder {
Builder::Empty
}
fn functions<T: 'static + Float + Sized>() -> HashMap<String, Box<Function<T>>> {
let mut map = HashMap::new();
map.insert("sin".to_string(), FnFunction::new("sin", &Self::sin));
map.insert("cos".to_string(), FnFunction::new("cos", &Self::cos));
map
}
fn simple_err<X, S: ToString>(s: S) -> Result<X, BuilderErr> {
BuilderErr(s.to_string(), None).into()
}
fn make_err<X, S: ToString>(self, s: S) -> Result<X, BuilderErr> {
BuilderErr(s.to_string(), Some(self)).into()
}
pub fn ast<T: 'static + Float + Sized>(self) -> Result<Ast<T>, BuilderErr> where T: Float {
Ok(match self {
Builder::Empty => return Self::simple_err("expression not complete"),
Builder::Simple(Lexem::Letter(inner)) => match T::from_str_radix(&inner, 10) {
Ok(num) => Ast::Constant(num),
Err(_) => Ast::Variable(inner),
},
Builder::Simple(_) => unreachable!(),
Builder::Complex(op, a, b) => Ast::Operation(op.into(), vec![a.ast()?, b.ast()?]),
b @ Builder::Body(..) => b.make_err("expected ')'")?,
Builder::Fun(..) => unreachable!(), //см обработку Complete
Builder::Complete(inner) => inner.ast_inner()?,
})
}
fn ast_inner<T: 'static + Float + Sized>(self) -> Result<Ast<T>, BuilderErr> {
match self {
Builder::Fun(name, v) => {
let fun = match Self::functions().remove(&name) {
None => Self::simple_err(format!("Function {} not found", name))?,
Some(x) => x,
};
let mut builders = Vec::with_capacity(v.len());
for b in v {
builders.push(b.ast()?);
}
Ok(Ast::Operation(fun, builders))
}
b => b.ast(),
}
}
fn want_process(&self, lex: &Lexem) -> bool {
match (self, lex) {
(Builder::Body(..), _) => true,
(Builder::Fun(..), _) => true,
(Builder::Empty, _) => true,
(Builder::Simple(..), Lexem::Open) => true,
(Builder::Complex(_, _, b), _) if b.want_process(lex) => true,
(Builder::Complex(op, ..), Lexem::Op(new_op)) if new_op.more(op) => true,
_ => false,
}
}
pub fn process(self, lex: Lexem) -> BuildResult {
#[cfg(test)] println!("lex: {:?}, b: {:?}", lex, self);
match (self, lex) {
(Builder::Empty, lex @ Lexem::Letter(_)) => Builder::Simple(lex),
(Builder::Empty, Lexem::Open) => Builder::Body(Builder::Empty.into()),
(a @ Builder::Complete(..), Lexem::Op(op)) |
(a @ Builder::Simple(..), Lexem::Op(op)) => Builder::Complex(op, a.into(), Builder::Empty.into()),
(Builder::Simple(Lexem::Letter(fun)), Lexem::Open) => Builder::Fun(fun, vec![Builder::Empty]),
(Builder::Complex(op, a, b), Lexem::Op(new_op)) => if b.want_process(&Lexem::Op(new_op)) || new_op.more(&op) {
Builder::Complex(op, a, b.process(Lexem::Op(new_op))?.into())
} else {
Builder::Complex(new_op, Builder::Complex(op, a, b).into(), Builder::Empty.into())
},
(Builder::Complex(op, a, b), lex) => Builder::Complex(op, a, b.process(lex)?.into()),
(Builder::Body(inner), lex @ Lexem::Close) => if inner.want_process(&lex) {
Builder::Body(inner.process(lex)?.into())
} else {
Builder::Complete(inner)
},
(Builder::Body(inner), lex) => Builder::Body(inner.process(lex)?.into()),
(Builder::Fun(name, v), lex @ Lexem::Close) => {
if v.last().unwrap().want_process(&lex) {
Self::fun_delegate_inner(name, v, lex)?
} else {
Builder::Complete(Builder::Fun(name, v).into())
}
}
(Builder::Fun(name, mut v), lex @ Lexem::Comma) => {
if v.last().unwrap().want_process(&lex) {
Self::fun_delegate_inner(name, v, lex)?
} else {
v.push(Builder::Empty);
Builder::Fun(name, v)
}
}
(Builder::Fun(name, v), lex) => Self::fun_delegate_inner(name, v, lex)?,
(b, lex) => return b.make_err(format!("Unexpected lexem {:?}", lex)),
}.into()
}
fn fun_delegate_inner(name: String, mut v: Vec<Builder>, lex: Lexem) -> BuildResult {
let inner = v.pop().unwrap().process(lex)?;
v.push(inner);
Ok(Builder::Fun(name, v))
}
}
impl FromStr for Builder {
type Err = BuilderErr;
fn from_str(s: &str) -> BuildResult {
parse(s).into_iter().fold(Ok(Builder::new()), |b, lex| b?.process(lex))
}
}
#[derive(Debug)]
struct AstFunction<T: Sized + Debug> {
name: String,
ast: Ast<T>,
params: Vec<String>,
}
impl<T> AstFunction<T> where T: 'static + Float + Sized + Debug {
fn new(desc: Builder, value: Builder) -> Result<Self, BuilderErr> {
if let Builder::Fun(name, v) = desc {
let mut params = Vec::with_capacity(v.len());
for param in v {
if let Builder::Simple(Lexem::Letter(param_name)) = param {
params.push(param_name); //TODO: а если число?
} else {
return param.make_err("fun description must be fun(a,b..)")
}
}
Ok(AstFunction {
name,
ast: value.ast::<T>()?,
params
})
} else {
desc.make_err("fun description must be fun(a,b..)")
}
}
}
impl<T: Float + Sized + Debug> Function<T> for AstFunction<T> {
fn name(&self) -> &str {
&self.name
}
fn args_count(&self) -> usize {
self.params.len()
}
fn call(&self, args: Vec<T>) -> Option<T> {
let mut params = HashMap::new();
for (i, name) in self.params.iter().enumerate() {
params.insert(name.clone(), args[i]);
}
self.ast.calculate(¶ms) //TODO: а если None?
}
}
#[cfg(test)]
mod test {
use parser::lexem::Lexem;
use std::collections::HashMap;
use parser::lexem::Operand;
use parser::builder::Builder;
use parser::builder::BuildResult;
use super::super::num::Float;
use std::fmt::Debug;
use std::fmt::Display;
use std::str::FromStr;
#[test]
fn build_plus() {
let b = Builder::from_str("x + 10").unwrap();
let tree = b.ast().unwrap();
println!("tree: {:?}", tree);
let mut params = HashMap::new();
params.insert("x".to_string(), 5f64);
let res = tree.calculate(¶ms).unwrap();
assert_eq!(15f64, res);
}
#[test]
fn build_ord() {
let b = Builder::from_str("x-10*x+9").unwrap();
let tree = b.ast().unwrap();
println!("tree: {:?}", tree);
let mut params = HashMap::new();
params.insert("x".to_string(), 1f64);
let res = tree.calculate(¶ms).unwrap();
assert_eq!(0f64, res);
}
#[test]
fn build_mipl() {
let x = 1f64;
let b = Builder::from_str("x - 10+9").unwrap();
let tree = b.ast().unwrap();
println!("tree: {:?}", tree);
let mut params = HashMap::new();
params.insert("x".to_string(), x);
let res = tree.calculate(¶ms).unwrap();
assert_eq!(x - 10.0 + 9.0, res);
}
#[test]
fn build_brackets() {
let x = 1f64;
let b = Builder::from_str("x -3*(x-2)").unwrap();
let tree = b.ast().unwrap();
println!("tree: {:?}", tree);
let mut params = HashMap::new();
params.insert("x".to_string(), x);
let res = tree.calculate(¶ms).unwrap();
assert_eq!(x - 3.0 * (x - 2.0), res);
}
#[test]
fn build_power() {
let x = 2f64;
let b = Builder::from_str("x -3^(x-2)").unwrap();
let tree = b.ast().unwrap();
println!("tree: {:?}", tree);
let mut params = HashMap::new();
params.insert("x".to_string(), x);
let res = tree.calculate(¶ms).unwrap();
assert_eq!(x - 3.0.powf(x - 2.0), res);
}
#[test]
fn build_sin() {
//5*sin(x)
let x = 0.3;
let b = Builder::from_str("5*sin(x)").unwrap();
let mut params = HashMap::new();
params.insert("x".to_string(), x);
let expected = Builder::Complex(Operand::High('*'),
Builder::Simple(Lexem::Letter("5".to_string())).into(),
Builder::Complete(
Builder::Fun("sin".to_string(), vec![
Builder::Simple(Lexem::Letter("x".to_string()))
]).into()
).into(),
);
assert_eq!(format!("{:?}", b), format!("{:?}", expected))
}
#[test]
fn multiple_fun() {
let x = 0.3;
let b = Builder::from_str("sin(x)^2 +cos(x)^2").unwrap();
let mut params = HashMap::new();
let ast = b.ast().unwrap();
params.insert("x".to_string(), x);
assert_eq!(1.0, ast.calculate(¶ms).unwrap());
}
} |
// auto generated, do not modify.
// created: Wed Jan 20 00:44:03 2016
// src-file: /QtQml/qqmlprivate.h
// dst-file: /src/qml/qqmlprivate.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 block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
} // <= ext block end
// body block begin =>
// <= body block end
|
mod helper;
use self::helper::Checker;
use ert::prelude::*;
use futures::prelude::*;
#[tokio::test]
async fn global() {
Router::new(100).set_as_global();
let c = Checker::new();
let c1 = c.clone();
let futs: Vec<_> = (0u64..100)
.map(move |i| {
let c1 = c1.clone();
async move {
c1.add(i);
}
.via_g(i)
})
.collect();
let c2 = c.clone();
let futs2: Vec<_> = (0u64..10000)
.map(move |i| {
let i = i % 100;
let c2 = c2.clone();
async move {
c2.check(i);
}
.via_g(i)
})
.collect();
let f = futures::future::join_all(futs).then(|_| futures::future::join_all(futs2));
f.await;
}
|
use crate::{serial_log, CONFIG};
use serde::Deserialize;
use serde_json_core;
#[derive(Deserialize, Debug)]
pub struct KernelConfig {
pub banner: bool,
}
pub fn get_config<'a>() {
match serde_json_core::from_str::<'a, KernelConfig>(CONFIG) {
Ok(_) => serial_log("hi"),
Err(e) => serial_log("Kernel config error."),
}
}
|
// extern crate csv;
extern crate csv;
extern crate subprocess;
use std::error::Error;
use std::fs::File;
use std::process;
use subprocess::{Exec, Redirection};
type Record = (String);
fn main() {
let mut conn = Vec::new();
// test function
if let Err(err) = csv(&mut conn) {
println!("{}", err);
process::exit(1);
}
if let Err(err) = sub(&conn) {
println!("{}", err);
process::exit(1);
}
}
fn sub(conn: &Vec<Record>) -> Result<(), Box<Error>> {
println!("{:?}", conn);
let pwd = "/home/ice/m/vim";
let out = Exec::cmd("git")
.arg("add")
.arg("-A")
.cwd(pwd)
.stdout(Redirection::Pipe)
.stderr(Redirection::Merge)
.capture()
.expect("failed to execute")
.stdout_str();
println!("{}", out);
let out2 = Exec::cmd("git")
.arg("status")
.cwd(pwd)
.stdout(Redirection::Pipe)
.stderr(Redirection::Merge)
.capture()
.expect("failed to execute")
.stdout_str();
println!("{}", out2);
let out3 = Exec::cmd("git")
.arg("commit")
.arg("-m")
.arg("test")
.cwd(pwd)
.stdout(Redirection::Pipe)
.stderr(Redirection::Merge)
.capture()
.expect("failed to execute")
.stdout_str();
println!("{}", out3);
let out3 = Exec::cmd("git")
.arg("push")
.cwd(pwd)
.stdout(Redirection::Pipe)
.stderr(Redirection::Merge)
.capture()
.expect("failed to execute")
.stdout_str();
println!("{}", out3);
Ok(())
}
fn csv(conn: &mut Vec<Record>) -> Result<(), Box<Error>> {
let file = File::open("conn.csv")?;
let mut rdr = csv::ReaderBuilder::new().flexible(true).from_reader(file);
for result in rdr.deserialize() {
let record: Record = result?;
conn.push(record);
}
Ok(())
}
|
/* Copyright 2016 Joshua Gentry
*
* 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.
*/
use std::mem::transmute;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
//*************************************************************************************************
/// Stores a f32 element inside an atomic element so it can be accessed by multiple threads.
///
/// # Examples
///
/// ```
/// use std::sync::mpsc;
/// use std::thread;
/// use shareable::SharedF32;
///
/// let value1 = SharedF32::new(63.23);
/// let value2 = value1.clone();
///
/// let (tx, rx) = mpsc::channel();
///
/// let thread = thread::spawn(move || {
/// rx.recv();
/// assert_eq!(value2.get(), 31.83);
/// });
///
/// value1.set(31.83);
///
/// tx.send(());
/// thread.join().unwrap();
/// ```
#[derive(Clone)]
pub struct SharedF32
{
//---------------------------------------------------------------------------------------------
/// The internal data element.
data : Arc<AtomicUsize>
}
impl SharedF32
{
//********************************************************************************************
/// Construct a new instance of the object.
pub fn new(
value : f32
) -> SharedF32
{
unsafe {
SharedF32 {
data : Arc::new(AtomicUsize::new(transmute::<f32, u32>(value) as usize))
}
}
}
//********************************************************************************************
/// Set the value of the object.
pub fn set(
&self,
val : f32
)
{
unsafe {
self.data.store(
transmute::<f32, u32>(val) as usize,
Ordering::Relaxed
);
}
}
//********************************************************************************************
/// Returns the value of the object.
pub fn get(&self) -> f32
{
unsafe {
transmute(self.data.load(Ordering::Relaxed) as u32)
}
}
}
use std::fmt::{Debug, Display, Formatter, Error};
impl Debug for SharedF32
{
//*********************************************************************************************
/// Implementation of Debug.
fn fmt(
&self,
f : &mut Formatter
) -> Result<(), Error>
{
write!(f, "{:?}", self.get())
}
}
impl Display for SharedF32
{
//*********************************************************************************************
/// Implementation of Display.
fn fmt(
&self,
f : &mut Formatter
) -> Result<(), Error>
{
write!(f, "{}", self.get())
}
}
#[cfg(test)]
mod tests
{
//*********************************************************************************************
/// Test that get/set work with only 1 instance.
#[test]
fn test_single()
{
let test = super::SharedF32::new(-79.23);
assert_eq!(test.get(), -79.23);
test.set(41.78);
assert_eq!(test.get(), 41.78);
}
//*********************************************************************************************
/// Test that get/set work with multiple instances.
#[test]
fn test_multiple()
{
let test1 = super::SharedF32::new(-79.6);
let test2 = test1.clone();
let test3 = test2.clone();
assert_eq!(test1.get(), -79.6);
assert_eq!(test2.get(), -79.6);
assert_eq!(test3.get(), -79.6);
test1.set(51.98);
assert_eq!(test1.get(), 51.98);
assert_eq!(test2.get(), 51.98);
assert_eq!(test3.get(), 51.98);
test2.set(31.77);
assert_eq!(test1.get(), 31.77);
assert_eq!(test2.get(), 31.77);
assert_eq!(test3.get(), 31.77);
test3.set(-11.101);
assert_eq!(test1.get(), -11.101);
assert_eq!(test2.get(), -11.101);
assert_eq!(test3.get(), -11.101);
}
}
|
extern crate nalgebra;
extern crate num;
mod basis;
mod braket;
mod context;
mod op;
mod state;
mod system;
pub use braket::Braket;
pub use op::Op;
pub use state::State;
pub use system::System;
|
use yew::prelude::*;
use yewdux::prelude::*;
use yewtil::NeqAssign;
// use yew::services::ConsoleService;
use crate::store::reducer::{
AppDispatch,
Action,
Counter
};
pub struct ReducerGlobal {
dispatch: AppDispatch,
}
impl Component for ReducerGlobal {
type Message = ();
type Properties = AppDispatch;
fn create(dispatch: Self::Properties, _link: ComponentLink<Self>) -> Self {
// Magically increment counter for this example.
dispatch.send(Action::Increment);
Self { dispatch }
}
fn update(&mut self, _msg: Self::Message) -> ShouldRender {
false
}
fn change(&mut self, dispatch: Self::Properties) -> ShouldRender {
self.dispatch.neq_assign(dispatch)
}
fn view(&self) -> Html {
let count = self.dispatch.state().count;
let name = self.dispatch.state().name.clone();
let increment = self.dispatch.callback(|_| Action::Increment);
let update = self.dispatch.callback(|_| {
// ConsoleService::info(&data.name);
let newdata = Counter {
count: 0,
name: String::from("Batman")
};
Action::Update(newdata)
});
html! {
<>
// <p>{"Show Reducer State"}</p>
<h1>{ count }</h1>
<h1>{ name }</h1>
<button onclick=increment>{"+1"}</button>
<button onclick=update>{"update"}</button>
</>
}
}
} |
use crate::color::Color;
use crate::intersectable::plane::Plane;
use crate::intersectable::sphere::Sphere;
use crate::light::Light;
use crate::light::LightType;
use crate::material::Material;
use crate::vector::Vec3;
use super::Scene;
impl Scene {
/// Example of a Scene you can find under the ``examples`` folder
pub fn load_example(&mut self) {
self.objects = vec![
Box::new(Sphere {
position: Vec3::new(-3.0, -5.0, -16.0),
radius: 2.8,
material: Material {
color: Color::from_u8(0xff, 0x55, 0x55),
diffuse: 0.6,
specular: 50.0,
specular_exponent: 100.0,
reflectiveness: 0.0,
},
}),
Box::new(Sphere {
position: Vec3::new(0.0, -5.0, -13.0),
radius: 2.0,
material: Material {
color: Color::from_u8(0x40, 0xe0, 0xd0),
diffuse: 0.6,
specular: 5.0,
specular_exponent: 500.0,
reflectiveness: 0.0,
},
}),
Box::new(Sphere {
position: Vec3::new(3.0, -5.0, -17.0),
radius: 2.8,
material: Material {
color: Color::from_u8(0x77, 0xbb, 0x77),
diffuse: 0.5,
specular: 0.2,
specular_exponent: 2.0,
reflectiveness: 0.0,
},
}),
Box::new(Sphere {
position: Vec3::new(0.0, -4.0, -20.0),
radius: 3.0,
material: Material {
color: Color::from_u8(0x2f, 0x8d, 0xff),
diffuse: 0.6,
specular: 3.0,
specular_exponent: 50.0,
reflectiveness: 0.0,
},
}),
Box::new(Sphere {
position: Vec3::new(-10.0, 5.0, -20.0),
radius: 5.0,
material: Material {
color: Color::new(0.1, 0.1, 0.1),
diffuse: 0.0,
specular: 50.0,
specular_exponent: 100.0,
reflectiveness: 1.0,
},
}),
Box::new(Plane {
position: Vec3::new(0.0, -8.0, 0.0),
normal: Vec3::new(0.0, -1.0, 0.0),
material: Material {
color: Color::from_u8(0x66, 0x33, 0x66),
diffuse: 0.8,
specular: 0.2,
specular_exponent: 5.0,
reflectiveness: 0.6,
},
}),
];
self.lights = vec![
Light {
light_type: LightType::Point,
position: Vec3::new(-40.0, 20.0, 20.0),
intensity: 1.0,
color: Color::white(),
},
Light {
light_type: LightType::Point,
position: Vec3::new(40.0, 20.0, 20.0),
intensity: 0.8,
color: Color::new(0.66, 0.0, 0.66),
},
Light {
light_type: LightType::Point,
position: Vec3::new(00.0, 50.0, 0.0),
intensity: 0.8,
color: Color::from_u8(0xa6, 0x7c, 0x00),
},
Light {
light_type: LightType::Ambient,
position: Vec3::zero(),
intensity: 0.25,
color: Color::white(),
},
];
}
/// Example of a Scene with mirrors
pub fn load_mirrors(&mut self) {
self.objects = vec![
Box::new(Plane {
position: Vec3::new(0., 0., -20.),
normal: Vec3::new(0., 0., -1.),
material: Material {
color: Color::from_u8(0xff, 0xff, 0xff),
diffuse: 0.01,
specular: 1.,
specular_exponent: 1000.,
reflectiveness: 1.,
},
}),
Box::new(Plane {
position: Vec3::new(0., 0., 20.),
normal: Vec3::new(0., 0., 1.),
material: Material {
color: Color::from_u8(0xff, 0xff, 0xff),
diffuse: 0.,
specular: 1.,
specular_exponent: 1000.,
reflectiveness: 1.,
},
}),
Box::new(Sphere {
position: Vec3::new(5., 1., 0.),
radius: 2.5,
material: Material {
color: Color::from_u8(0x00, 0x15, 0x55),
diffuse: 1.0,
specular: 1.,
specular_exponent: 1000.,
reflectiveness: 1.,
},
}),
Box::new(Sphere {
position: Vec3::new(0., 0., 20.),
radius: 5.,
material: Material {
color: Color::from_u8(0x00, 0x00, 0x00),
diffuse: 0.,
specular: 1.,
specular_exponent: 1000.,
reflectiveness: 1.,
},
}),
];
self.lights = vec![
Light {
light_type: LightType::Ambient,
position: Vec3::new(-10., 0., 0.),
intensity: 1.,
color: Color::white(),
},
Light {
light_type: LightType::Point,
position: Vec3::new(-10., 0., 0.),
intensity: 1.,
color: Color::white(),
},
]
}
/// Example for Wallpaper1
pub fn load_wallpaper1(&mut self) {
self.objects = vec![
Box::new(Sphere {
position: Vec3::new(1.0, -5.0, -15.0),
radius: 2.1,
material: Material {
color: Color::from_u8(0x00, 0x50, 0x1a),
diffuse: 0.6,
specular: 50.0,
specular_exponent: 100.0,
reflectiveness: 1.0,
},
}),
Box::new(Sphere {
position: Vec3::new(0.0, -1.0, -20.0),
radius: 1.9,
material: Material {
color: Color::from_u8(0x00, 0x8d, 0xff),
diffuse: 0.6,
specular: 50.0,
specular_exponent: 100.0,
reflectiveness: 1.0,
},
}),
Box::new(Sphere {
position: Vec3::new(-1.0, 2.0, -15.0),
radius: 0.9,
material: Material {
color: Color::from_u8(0x66, 0x00, 0x00),
diffuse: 0.6,
specular: 50.,
specular_exponent: 100.0,
reflectiveness: 1.0,
},
}),
Box::new(Sphere {
position: Vec3::new(-5., 7., -20.0),
radius: 5.0,
material: Material {
color: Color::new(0.1, 0.1, 0.1),
diffuse: 0.0,
specular: 50.0,
specular_exponent: 100.0,
reflectiveness: 1.0,
},
}),
Box::new(Plane {
position: Vec3::new(0.0, -8.0, 0.0),
normal: Vec3::new(0.0, -1.0, 0.0),
material: Material {
color: Color::from_u8(0x00, 0x15, 0x55),
diffuse: 0.8,
specular: 0.2,
specular_exponent: 5.0,
reflectiveness: 0.6,
},
}),
];
self.lights = vec![
Light {
light_type: LightType::Point,
position: Vec3::new(-40.0, 15.0, 20.0),
intensity: 1.,
color: Color::from_u8(0x35, 0x35, 0x35),
},
Light {
light_type: LightType::Point,
position: Vec3::new(40.0, 15.0, 20.0),
intensity: 0.8,
color: Color::new(0.75, 0., 0.),
},
Light {
light_type: LightType::Point,
position: Vec3::new(0., 0., 0.75),
intensity: 0.8,
color: Color::from_u8(0xa6, 0x7c, 0x00),
},
Light {
light_type: LightType::Ambient,
position: Vec3::zero(),
intensity: 0.25,
color: Color::white(),
},
];
}
/// Example for Wallpaper2
pub fn load_wallpaper2(&mut self) {
self.objects = vec![
Box::new(Sphere {
position: Vec3::new(-3.0, -5.0, -16.0),
radius: 2.1,
material: Material {
color: Color::from_u8(0x00, 0x50, 0x1a),
diffuse: 0.6,
specular: 50.0,
specular_exponent: 100.0,
reflectiveness: 1.0,
},
}),
Box::new(Sphere {
position: Vec3::new(4.0, -5.0, -15.0),
radius: 2.1,
material: Material {
color: Color::from_u8(0x66, 0x00, 0x00),
diffuse: 0.6,
specular: 50.0,
specular_exponent: 100.0,
reflectiveness: 1.0,
},
}),
Box::new(Sphere {
position: Vec3::new(0.0, -5.0, -21.0),
radius: 2.1,
material: Material {
color: Color::from_u8(0x00, 0x35, 0x75),
diffuse: 0.6,
specular: 50.,
specular_exponent: 100.0,
reflectiveness: 1.0,
},
}),
Box::new(Sphere {
position: Vec3::new(-5., 7., -20.0),
radius: 5.0,
material: Material {
color: Color::new(0.1, 0.1, 0.1),
diffuse: 0.0,
specular: 50.0,
specular_exponent: 100.0,
reflectiveness: 1.0,
},
}),
Box::new(Plane {
position: Vec3::new(0.0, -8.0, 0.0),
normal: Vec3::new(0.0, -1.0, 0.0),
material: Material {
color: Color::from_u8(0x00, 0x15, 0x55),
diffuse: 0.0,
specular: 50.0,
specular_exponent: 100.0,
reflectiveness: 1.0,
},
}),
];
self.lights = vec![
Light {
light_type: LightType::Point,
position: Vec3::new(-40.0, 15.0, 20.0),
intensity: 1.,
color: Color::from_u8(0xa0, 0xa0, 0xa0),
},
Light {
light_type: LightType::Point,
position: Vec3::new(40.0, 15.0, 20.0),
intensity: 0.8,
color: Color::from_u8(0xa0, 0x00, 0x00),
},
Light {
light_type: LightType::Point,
position: Vec3::new(0., 0., 0.75),
intensity: 0.8,
color: Color::from_u8(0x00, 0xa0, 0xa0),
},
Light {
light_type: LightType::Ambient,
position: Vec3::zero(),
intensity: 0.25,
color: Color::white(),
},
];
}
}
|
#![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 AuthenticationProtocol(pub i32);
impl AuthenticationProtocol {
pub const Basic: Self = Self(0i32);
pub const Digest: Self = Self(1i32);
pub const Ntlm: Self = Self(2i32);
pub const Kerberos: Self = Self(3i32);
pub const Negotiate: Self = Self(4i32);
pub const CredSsp: Self = Self(5i32);
pub const Custom: Self = Self(6i32);
}
impl ::core::marker::Copy for AuthenticationProtocol {}
impl ::core::clone::Clone for AuthenticationProtocol {
fn clone(&self) -> Self {
*self
}
}
pub type CredentialPickerOptions = *mut ::core::ffi::c_void;
pub type CredentialPickerResults = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct CredentialSaveOption(pub i32);
impl CredentialSaveOption {
pub const Unselected: Self = Self(0i32);
pub const Selected: Self = Self(1i32);
pub const Hidden: Self = Self(2i32);
}
impl ::core::marker::Copy for CredentialSaveOption {}
impl ::core::clone::Clone for CredentialSaveOption {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct UserConsentVerificationResult(pub i32);
impl UserConsentVerificationResult {
pub const Verified: Self = Self(0i32);
pub const DeviceNotPresent: Self = Self(1i32);
pub const NotConfiguredForUser: Self = Self(2i32);
pub const DisabledByPolicy: Self = Self(3i32);
pub const DeviceBusy: Self = Self(4i32);
pub const RetriesExhausted: Self = Self(5i32);
pub const Canceled: Self = Self(6i32);
}
impl ::core::marker::Copy for UserConsentVerificationResult {}
impl ::core::clone::Clone for UserConsentVerificationResult {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct UserConsentVerifierAvailability(pub i32);
impl UserConsentVerifierAvailability {
pub const Available: Self = Self(0i32);
pub const DeviceNotPresent: Self = Self(1i32);
pub const NotConfiguredForUser: Self = Self(2i32);
pub const DisabledByPolicy: Self = Self(3i32);
pub const DeviceBusy: Self = Self(4i32);
}
impl ::core::marker::Copy for UserConsentVerifierAvailability {}
impl ::core::clone::Clone for UserConsentVerifierAvailability {
fn clone(&self) -> Self {
*self
}
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct CollectionChange(pub i32);
impl CollectionChange {
pub const Reset: CollectionChange = CollectionChange(0i32);
pub const ItemInserted: CollectionChange = CollectionChange(1i32);
pub const ItemRemoved: CollectionChange = CollectionChange(2i32);
pub const ItemChanged: CollectionChange = CollectionChange(3i32);
}
impl ::core::convert::From<i32> for CollectionChange {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for CollectionChange {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for CollectionChange {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Foundation.Collections.CollectionChange;i4)");
}
impl ::windows::core::DefaultType for CollectionChange {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IIterable<T>(pub ::windows::core::IInspectable, ::core::marker::PhantomData<T>)
where
T: ::windows::core::RuntimeType + 'static;
unsafe impl<T: ::windows::core::RuntimeType + 'static> ::windows::core::Interface for IIterable<T> {
type Vtable = IIterable_abi<T>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<IIterable<T> as ::windows::core::RuntimeType>::SIGNATURE);
}
impl<T: ::windows::core::RuntimeType + 'static> IIterable<T> {
pub fn First(&self) -> ::windows::core::Result<IIterator<T>> {
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::<IIterator<T>>(result__)
}
}
}
unsafe impl<T: ::windows::core::RuntimeType + 'static> ::windows::core::RuntimeType for IIterable<T> {
const SIGNATURE: ::windows::core::ConstBuffer = { ::windows::core::ConstBuffer::new().push_slice(b"pinterface(").push_slice(b"{faa585ea-6214-4217-afda-7f46de5869b3}").push_slice(b";").push_other(<T as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b")") };
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<IIterable<T>> for ::windows::core::IUnknown {
fn from(value: IIterable<T>) -> Self {
value.0 .0
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IIterable<T>> for ::windows::core::IUnknown {
fn from(value: &IIterable<T>) -> Self {
value.0 .0.clone()
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IIterable<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IIterable<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<IIterable<T>> for ::windows::core::IInspectable {
fn from(value: IIterable<T>) -> Self {
value.0
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IIterable<T>> for ::windows::core::IInspectable {
fn from(value: &IIterable<T>) -> Self {
value.0.clone()
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IIterable<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IIterable<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl<T: ::windows::core::RuntimeType> ::core::iter::IntoIterator for IIterable<T> {
type Item = T;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
impl<T: ::windows::core::RuntimeType> ::core::iter::IntoIterator for &IIterable<T> {
type Item = T;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.First().unwrap()
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IIterable_abi<T>(
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,
pub ::core::marker::PhantomData<T>,
)
where
T: ::windows::core::RuntimeType + 'static;
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IIterator<T>(pub ::windows::core::IInspectable, ::core::marker::PhantomData<T>)
where
T: ::windows::core::RuntimeType + 'static;
unsafe impl<T: ::windows::core::RuntimeType + 'static> ::windows::core::Interface for IIterator<T> {
type Vtable = IIterator_abi<T>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<IIterator<T> as ::windows::core::RuntimeType>::SIGNATURE);
}
impl<T: ::windows::core::RuntimeType + 'static> IIterator<T> {
pub fn Current(&self) -> ::windows::core::Result<T> {
let this = self;
unsafe {
let mut result__: <T as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<T>(result__)
}
}
pub fn HasCurrent(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn MoveNext(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn GetMany(&self, items: &mut [<T as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), items.len() as u32, ::core::mem::transmute_copy(&items), &mut result__).from_abi::<u32>(result__)
}
}
}
unsafe impl<T: ::windows::core::RuntimeType + 'static> ::windows::core::RuntimeType for IIterator<T> {
const SIGNATURE: ::windows::core::ConstBuffer = { ::windows::core::ConstBuffer::new().push_slice(b"pinterface(").push_slice(b"{6a79e863-4300-459a-9966-cbb660963ee1}").push_slice(b";").push_other(<T as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b")") };
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<IIterator<T>> for ::windows::core::IUnknown {
fn from(value: IIterator<T>) -> Self {
value.0 .0
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IIterator<T>> for ::windows::core::IUnknown {
fn from(value: &IIterator<T>) -> Self {
value.0 .0.clone()
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IIterator<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IIterator<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<IIterator<T>> for ::windows::core::IInspectable {
fn from(value: IIterator<T>) -> Self {
value.0
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IIterator<T>> for ::windows::core::IInspectable {
fn from(value: &IIterator<T>) -> Self {
value.0.clone()
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IIterator<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IIterator<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl<T: ::windows::core::RuntimeType> ::core::iter::Iterator for IIterator<T> {
type Item = T;
fn next(&mut self) -> ::core::option::Option<Self::Item> {
let result = self.Current().ok();
if result.is_some() {
self.MoveNext().ok()?;
}
result
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IIterator_abi<T>(
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 <T as ::windows::core::Abi>::Abi) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, items_array_size: u32, items: *mut <T as ::windows::core::Abi>::Abi, result__: *mut u32) -> ::windows::core::HRESULT,
pub ::core::marker::PhantomData<T>,
)
where
T: ::windows::core::RuntimeType + 'static;
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IKeyValuePair<K, V>(pub ::windows::core::IInspectable, ::core::marker::PhantomData<K>, ::core::marker::PhantomData<V>)
where
K: ::windows::core::RuntimeType + 'static,
V: ::windows::core::RuntimeType + 'static;
unsafe impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::Interface for IKeyValuePair<K, V> {
type Vtable = IKeyValuePair_abi<K, V>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<IKeyValuePair<K, V> as ::windows::core::RuntimeType>::SIGNATURE);
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> IKeyValuePair<K, V> {
pub fn Key(&self) -> ::windows::core::Result<K> {
let this = self;
unsafe {
let mut result__: <K as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<K>(result__)
}
}
pub fn Value(&self) -> ::windows::core::Result<V> {
let this = self;
unsafe {
let mut result__: <V as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<V>(result__)
}
}
}
unsafe impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::RuntimeType for IKeyValuePair<K, V> {
const SIGNATURE: ::windows::core::ConstBuffer = { ::windows::core::ConstBuffer::new().push_slice(b"pinterface(").push_slice(b"{02b51929-c1c4-4a7e-8940-0312b5c18500}").push_slice(b";").push_other(<K as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b";").push_other(<V as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b")") };
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<IKeyValuePair<K, V>> for ::windows::core::IUnknown {
fn from(value: IKeyValuePair<K, V>) -> Self {
value.0 .0
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IKeyValuePair<K, V>> for ::windows::core::IUnknown {
fn from(value: &IKeyValuePair<K, V>) -> Self {
value.0 .0.clone()
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IKeyValuePair<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IKeyValuePair<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<IKeyValuePair<K, V>> for ::windows::core::IInspectable {
fn from(value: IKeyValuePair<K, V>) -> Self {
value.0
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IKeyValuePair<K, V>> for ::windows::core::IInspectable {
fn from(value: &IKeyValuePair<K, V>) -> Self {
value.0.clone()
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IKeyValuePair<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IKeyValuePair<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IKeyValuePair_abi<K, V>(
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 <K as ::windows::core::Abi>::Abi) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut <V as ::windows::core::Abi>::Abi) -> ::windows::core::HRESULT,
pub ::core::marker::PhantomData<K>,
pub ::core::marker::PhantomData<V>,
)
where
K: ::windows::core::RuntimeType + 'static,
V: ::windows::core::RuntimeType + 'static;
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IMap<K, V>(pub ::windows::core::IInspectable, ::core::marker::PhantomData<K>, ::core::marker::PhantomData<V>)
where
K: ::windows::core::RuntimeType + 'static,
V: ::windows::core::RuntimeType + 'static;
unsafe impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::Interface for IMap<K, V> {
type Vtable = IMap_abi<K, V>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<IMap<K, V> as ::windows::core::RuntimeType>::SIGNATURE);
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> IMap<K, V> {
pub fn Lookup<'a, Param0: ::windows::core::IntoParam<'a, K>>(&self, key: Param0) -> ::windows::core::Result<V> {
let this = self;
unsafe {
let mut result__: <V as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<V>(result__)
}
}
pub fn Size(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn HasKey<'a, Param0: ::windows::core::IntoParam<'a, K>>(&self, key: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn GetView(&self) -> ::windows::core::Result<IMapView<K, V>> {
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::<IMapView<K, V>>(result__)
}
}
pub fn Insert<'a, Param0: ::windows::core::IntoParam<'a, K>, Param1: ::windows::core::IntoParam<'a, V>>(&self, key: Param0, value: Param1) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), key.into_param().abi(), value.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Remove<'a, Param0: ::windows::core::IntoParam<'a, K>>(&self, key: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), key.into_param().abi()).ok() }
}
pub fn Clear(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this)).ok() }
}
pub fn First(&self) -> ::windows::core::Result<IIterator<IKeyValuePair<K, V>>> {
let this = &::windows::core::Interface::cast::<IIterable<IKeyValuePair<K, V>>>(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::<IIterator<IKeyValuePair<K, V>>>(result__)
}
}
}
unsafe impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::RuntimeType for IMap<K, V> {
const SIGNATURE: ::windows::core::ConstBuffer = { ::windows::core::ConstBuffer::new().push_slice(b"pinterface(").push_slice(b"{3c2925fe-8519-45c1-aa79-197b6718c1c1}").push_slice(b";").push_other(<K as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b";").push_other(<V as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b")") };
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<IMap<K, V>> for ::windows::core::IUnknown {
fn from(value: IMap<K, V>) -> Self {
value.0 .0
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IMap<K, V>> for ::windows::core::IUnknown {
fn from(value: &IMap<K, V>) -> Self {
value.0 .0.clone()
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<IMap<K, V>> for ::windows::core::IInspectable {
fn from(value: IMap<K, V>) -> Self {
value.0
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IMap<K, V>> for ::windows::core::IInspectable {
fn from(value: &IMap<K, V>) -> Self {
value.0.clone()
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<IMap<K, V>> for IIterable<IKeyValuePair<K, V>> {
type Error = ::windows::core::Error;
fn try_from(value: IMap<K, V>) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<&IMap<K, V>> for IIterable<IKeyValuePair<K, V>> {
type Error = ::windows::core::Error;
fn try_from(value: &IMap<K, V>) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<K, V>>> for IMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<K, V>>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<K, V>>> for &IMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<K, V>>> {
::core::convert::TryInto::<IIterable<IKeyValuePair<K, V>>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::iter::IntoIterator for IMap<K, V> {
type Item = IKeyValuePair<K, V>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::iter::IntoIterator for &IMap<K, V> {
type Item = IKeyValuePair<K, V>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.First().unwrap()
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IMap_abi<K, V>(
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, key: <K as ::windows::core::Abi>::Abi, result__: *mut <V as ::windows::core::Abi>::Abi) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, key: <K as ::windows::core::Abi>::Abi, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, key: <K as ::windows::core::Abi>::Abi, value: <V as ::windows::core::Abi>::Abi, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, key: <K as ::windows::core::Abi>::Abi) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub ::core::marker::PhantomData<K>,
pub ::core::marker::PhantomData<V>,
)
where
K: ::windows::core::RuntimeType + 'static,
V: ::windows::core::RuntimeType + 'static;
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IMapChangedEventArgs<K>(pub ::windows::core::IInspectable, ::core::marker::PhantomData<K>)
where
K: ::windows::core::RuntimeType + 'static;
unsafe impl<K: ::windows::core::RuntimeType + 'static> ::windows::core::Interface for IMapChangedEventArgs<K> {
type Vtable = IMapChangedEventArgs_abi<K>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<IMapChangedEventArgs<K> as ::windows::core::RuntimeType>::SIGNATURE);
}
impl<K: ::windows::core::RuntimeType + 'static> IMapChangedEventArgs<K> {
pub fn CollectionChange(&self) -> ::windows::core::Result<CollectionChange> {
let this = self;
unsafe {
let mut result__: CollectionChange = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<CollectionChange>(result__)
}
}
pub fn Key(&self) -> ::windows::core::Result<K> {
let this = self;
unsafe {
let mut result__: <K as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<K>(result__)
}
}
}
unsafe impl<K: ::windows::core::RuntimeType + 'static> ::windows::core::RuntimeType for IMapChangedEventArgs<K> {
const SIGNATURE: ::windows::core::ConstBuffer = { ::windows::core::ConstBuffer::new().push_slice(b"pinterface(").push_slice(b"{9939f4df-050a-4c0f-aa60-77075f9c4777}").push_slice(b";").push_other(<K as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b")") };
}
impl<K: ::windows::core::RuntimeType + 'static> ::core::convert::From<IMapChangedEventArgs<K>> for ::windows::core::IUnknown {
fn from(value: IMapChangedEventArgs<K>) -> Self {
value.0 .0
}
}
impl<K: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IMapChangedEventArgs<K>> for ::windows::core::IUnknown {
fn from(value: &IMapChangedEventArgs<K>) -> Self {
value.0 .0.clone()
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMapChangedEventArgs<K> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMapChangedEventArgs<K> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl<K: ::windows::core::RuntimeType + 'static> ::core::convert::From<IMapChangedEventArgs<K>> for ::windows::core::IInspectable {
fn from(value: IMapChangedEventArgs<K>) -> Self {
value.0
}
}
impl<K: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IMapChangedEventArgs<K>> for ::windows::core::IInspectable {
fn from(value: &IMapChangedEventArgs<K>) -> Self {
value.0.clone()
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IMapChangedEventArgs<K> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IMapChangedEventArgs<K> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IMapChangedEventArgs_abi<K>(
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 CollectionChange) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut <K as ::windows::core::Abi>::Abi) -> ::windows::core::HRESULT,
pub ::core::marker::PhantomData<K>,
)
where
K: ::windows::core::RuntimeType + 'static;
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IMapView<K, V>(pub ::windows::core::IInspectable, ::core::marker::PhantomData<K>, ::core::marker::PhantomData<V>)
where
K: ::windows::core::RuntimeType + 'static,
V: ::windows::core::RuntimeType + 'static;
unsafe impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::Interface for IMapView<K, V> {
type Vtable = IMapView_abi<K, V>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<IMapView<K, V> as ::windows::core::RuntimeType>::SIGNATURE);
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> IMapView<K, V> {
pub fn Lookup<'a, Param0: ::windows::core::IntoParam<'a, K>>(&self, key: Param0) -> ::windows::core::Result<V> {
let this = self;
unsafe {
let mut result__: <V as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<V>(result__)
}
}
pub fn Size(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn HasKey<'a, Param0: ::windows::core::IntoParam<'a, K>>(&self, key: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Split(&self, first: &mut ::core::option::Option<IMapView<K, V>>, second: &mut ::core::option::Option<IMapView<K, V>>) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), first as *mut _ as _, second as *mut _ as _).ok() }
}
pub fn First(&self) -> ::windows::core::Result<IIterator<IKeyValuePair<K, V>>> {
let this = &::windows::core::Interface::cast::<IIterable<IKeyValuePair<K, V>>>(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::<IIterator<IKeyValuePair<K, V>>>(result__)
}
}
}
unsafe impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::RuntimeType for IMapView<K, V> {
const SIGNATURE: ::windows::core::ConstBuffer = { ::windows::core::ConstBuffer::new().push_slice(b"pinterface(").push_slice(b"{e480ce40-a338-4ada-adcf-272272e48cb9}").push_slice(b";").push_other(<K as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b";").push_other(<V as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b")") };
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<IMapView<K, V>> for ::windows::core::IUnknown {
fn from(value: IMapView<K, V>) -> Self {
value.0 .0
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IMapView<K, V>> for ::windows::core::IUnknown {
fn from(value: &IMapView<K, V>) -> Self {
value.0 .0.clone()
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMapView<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMapView<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<IMapView<K, V>> for ::windows::core::IInspectable {
fn from(value: IMapView<K, V>) -> Self {
value.0
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IMapView<K, V>> for ::windows::core::IInspectable {
fn from(value: &IMapView<K, V>) -> Self {
value.0.clone()
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IMapView<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IMapView<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<IMapView<K, V>> for IIterable<IKeyValuePair<K, V>> {
type Error = ::windows::core::Error;
fn try_from(value: IMapView<K, V>) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<&IMapView<K, V>> for IIterable<IKeyValuePair<K, V>> {
type Error = ::windows::core::Error;
fn try_from(value: &IMapView<K, V>) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<K, V>>> for IMapView<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<K, V>>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<K, V>>> for &IMapView<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<K, V>>> {
::core::convert::TryInto::<IIterable<IKeyValuePair<K, V>>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::iter::IntoIterator for IMapView<K, V> {
type Item = IKeyValuePair<K, V>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::iter::IntoIterator for &IMapView<K, V> {
type Item = IKeyValuePair<K, V>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.First().unwrap()
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IMapView_abi<K, V>(
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, key: <K as ::windows::core::Abi>::Abi, result__: *mut <V as ::windows::core::Abi>::Abi) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, key: <K as ::windows::core::Abi>::Abi, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, first: *mut ::windows::core::RawPtr, second: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub ::core::marker::PhantomData<K>,
pub ::core::marker::PhantomData<V>,
)
where
K: ::windows::core::RuntimeType + 'static,
V: ::windows::core::RuntimeType + 'static;
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IObservableMap<K, V>(pub ::windows::core::IInspectable, ::core::marker::PhantomData<K>, ::core::marker::PhantomData<V>)
where
K: ::windows::core::RuntimeType + 'static,
V: ::windows::core::RuntimeType + 'static;
unsafe impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::Interface for IObservableMap<K, V> {
type Vtable = IObservableMap_abi<K, V>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<IObservableMap<K, V> as ::windows::core::RuntimeType>::SIGNATURE);
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> IObservableMap<K, V> {
pub fn MapChanged<'a, Param0: ::windows::core::IntoParam<'a, MapChangedEventHandler<K, V>>>(&self, vhnd: Param0) -> ::windows::core::Result<super::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), vhnd.into_param().abi(), &mut result__).from_abi::<super::EventRegistrationToken>(result__)
}
}
pub fn RemoveMapChanged<'a, Param0: ::windows::core::IntoParam<'a, super::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
pub fn First(&self) -> ::windows::core::Result<IIterator<IKeyValuePair<K, V>>> {
let this = &::windows::core::Interface::cast::<IIterable<IKeyValuePair<K, V>>>(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::<IIterator<IKeyValuePair<K, V>>>(result__)
}
}
pub fn Lookup<'a, Param0: ::windows::core::IntoParam<'a, K>>(&self, key: Param0) -> ::windows::core::Result<V> {
let this = &::windows::core::Interface::cast::<IMap<K, V>>(self)?;
unsafe {
let mut result__: <V as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<V>(result__)
}
}
pub fn Size(&self) -> ::windows::core::Result<u32> {
let this = &::windows::core::Interface::cast::<IMap<K, V>>(self)?;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn HasKey<'a, Param0: ::windows::core::IntoParam<'a, K>>(&self, key: Param0) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<IMap<K, V>>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn GetView(&self) -> ::windows::core::Result<IMapView<K, V>> {
let this = &::windows::core::Interface::cast::<IMap<K, V>>(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::<IMapView<K, V>>(result__)
}
}
pub fn Insert<'a, Param0: ::windows::core::IntoParam<'a, K>, Param1: ::windows::core::IntoParam<'a, V>>(&self, key: Param0, value: Param1) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<IMap<K, V>>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), key.into_param().abi(), value.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Remove<'a, Param0: ::windows::core::IntoParam<'a, K>>(&self, key: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMap<K, V>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), key.into_param().abi()).ok() }
}
pub fn Clear(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMap<K, V>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::RuntimeType for IObservableMap<K, V> {
const SIGNATURE: ::windows::core::ConstBuffer = { ::windows::core::ConstBuffer::new().push_slice(b"pinterface(").push_slice(b"{65df2bf5-bf39-41b5-aebc-5a9d865e472b}").push_slice(b";").push_other(<K as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b";").push_other(<V as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b")") };
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<IObservableMap<K, V>> for ::windows::core::IUnknown {
fn from(value: IObservableMap<K, V>) -> Self {
value.0 .0
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IObservableMap<K, V>> for ::windows::core::IUnknown {
fn from(value: &IObservableMap<K, V>) -> Self {
value.0 .0.clone()
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IObservableMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IObservableMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<IObservableMap<K, V>> for ::windows::core::IInspectable {
fn from(value: IObservableMap<K, V>) -> Self {
value.0
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IObservableMap<K, V>> for ::windows::core::IInspectable {
fn from(value: &IObservableMap<K, V>) -> Self {
value.0.clone()
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IObservableMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IObservableMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<IObservableMap<K, V>> for IIterable<IKeyValuePair<K, V>> {
type Error = ::windows::core::Error;
fn try_from(value: IObservableMap<K, V>) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<&IObservableMap<K, V>> for IIterable<IKeyValuePair<K, V>> {
type Error = ::windows::core::Error;
fn try_from(value: &IObservableMap<K, V>) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<K, V>>> for IObservableMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<K, V>>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<K, V>>> for &IObservableMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<K, V>>> {
::core::convert::TryInto::<IIterable<IKeyValuePair<K, V>>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<IObservableMap<K, V>> for IMap<K, V> {
type Error = ::windows::core::Error;
fn try_from(value: IObservableMap<K, V>) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<&IObservableMap<K, V>> for IMap<K, V> {
type Error = ::windows::core::Error;
fn try_from(value: &IObservableMap<K, V>) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IMap<K, V>> for IObservableMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, IMap<K, V>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a, K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IMap<K, V>> for &IObservableMap<K, V> {
fn into_param(self) -> ::windows::core::Param<'a, IMap<K, V>> {
::core::convert::TryInto::<IMap<K, V>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::iter::IntoIterator for IObservableMap<K, V> {
type Item = IKeyValuePair<K, V>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::core::iter::IntoIterator for &IObservableMap<K, V> {
type Item = IKeyValuePair<K, V>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.First().unwrap()
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IObservableMap_abi<K, V>(
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, vhnd: ::windows::core::RawPtr, result__: *mut super::EventRegistrationToken) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::EventRegistrationToken) -> ::windows::core::HRESULT,
pub ::core::marker::PhantomData<K>,
pub ::core::marker::PhantomData<V>,
)
where
K: ::windows::core::RuntimeType + 'static,
V: ::windows::core::RuntimeType + 'static;
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IObservableVector<T>(pub ::windows::core::IInspectable, ::core::marker::PhantomData<T>)
where
T: ::windows::core::RuntimeType + 'static;
unsafe impl<T: ::windows::core::RuntimeType + 'static> ::windows::core::Interface for IObservableVector<T> {
type Vtable = IObservableVector_abi<T>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<IObservableVector<T> as ::windows::core::RuntimeType>::SIGNATURE);
}
impl<T: ::windows::core::RuntimeType + 'static> IObservableVector<T> {
pub fn VectorChanged<'a, Param0: ::windows::core::IntoParam<'a, VectorChangedEventHandler<T>>>(&self, vhnd: Param0) -> ::windows::core::Result<super::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), vhnd.into_param().abi(), &mut result__).from_abi::<super::EventRegistrationToken>(result__)
}
}
pub fn RemoveVectorChanged<'a, Param0: ::windows::core::IntoParam<'a, super::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
pub fn First(&self) -> ::windows::core::Result<IIterator<T>> {
let this = &::windows::core::Interface::cast::<IIterable<T>>(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::<IIterator<T>>(result__)
}
}
pub fn GetAt(&self, index: u32) -> ::windows::core::Result<T> {
let this = &::windows::core::Interface::cast::<IVector<T>>(self)?;
unsafe {
let mut result__: <T as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), index, &mut result__).from_abi::<T>(result__)
}
}
pub fn Size(&self) -> ::windows::core::Result<u32> {
let this = &::windows::core::Interface::cast::<IVector<T>>(self)?;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn GetView(&self) -> ::windows::core::Result<IVectorView<T>> {
let this = &::windows::core::Interface::cast::<IVector<T>>(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::<IVectorView<T>>(result__)
}
}
pub fn IndexOf<'a, Param0: ::windows::core::IntoParam<'a, T>>(&self, value: Param0, index: &mut u32) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<IVector<T>>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi(), index, &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetAt<'a, Param1: ::windows::core::IntoParam<'a, T>>(&self, index: u32, value: Param1) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IVector<T>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), index, value.into_param().abi()).ok() }
}
pub fn InsertAt<'a, Param1: ::windows::core::IntoParam<'a, T>>(&self, index: u32, value: Param1) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IVector<T>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), index, value.into_param().abi()).ok() }
}
pub fn RemoveAt(&self, index: u32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IVector<T>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), index).ok() }
}
pub fn Append<'a, Param0: ::windows::core::IntoParam<'a, T>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IVector<T>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn RemoveAtEnd(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IVector<T>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this)).ok() }
}
pub fn Clear(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IVector<T>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this)).ok() }
}
pub fn GetMany(&self, startindex: u32, items: &mut [<T as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<u32> {
let this = &::windows::core::Interface::cast::<IVector<T>>(self)?;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), startindex, items.len() as u32, ::core::mem::transmute_copy(&items), &mut result__).from_abi::<u32>(result__)
}
}
pub fn ReplaceAll(&self, items: &[<T as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IVector<T>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), items.len() as u32, ::core::mem::transmute(items.as_ptr())).ok() }
}
}
unsafe impl<T: ::windows::core::RuntimeType + 'static> ::windows::core::RuntimeType for IObservableVector<T> {
const SIGNATURE: ::windows::core::ConstBuffer = { ::windows::core::ConstBuffer::new().push_slice(b"pinterface(").push_slice(b"{5917eb53-50b4-4a0d-b309-65862b3f1dbc}").push_slice(b";").push_other(<T as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b")") };
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<IObservableVector<T>> for ::windows::core::IUnknown {
fn from(value: IObservableVector<T>) -> Self {
value.0 .0
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IObservableVector<T>> for ::windows::core::IUnknown {
fn from(value: &IObservableVector<T>) -> Self {
value.0 .0.clone()
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IObservableVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IObservableVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<IObservableVector<T>> for ::windows::core::IInspectable {
fn from(value: IObservableVector<T>) -> Self {
value.0
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IObservableVector<T>> for ::windows::core::IInspectable {
fn from(value: &IObservableVector<T>) -> Self {
value.0.clone()
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IObservableVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IObservableVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<IObservableVector<T>> for IIterable<T> {
type Error = ::windows::core::Error;
fn try_from(value: IObservableVector<T>) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<&IObservableVector<T>> for IIterable<T> {
type Error = ::windows::core::Error;
fn try_from(value: &IObservableVector<T>) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IIterable<T>> for IObservableVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<T>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IIterable<T>> for &IObservableVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<T>> {
::core::convert::TryInto::<IIterable<T>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<IObservableVector<T>> for IVector<T> {
type Error = ::windows::core::Error;
fn try_from(value: IObservableVector<T>) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<&IObservableVector<T>> for IVector<T> {
type Error = ::windows::core::Error;
fn try_from(value: &IObservableVector<T>) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IVector<T>> for IObservableVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, IVector<T>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IVector<T>> for &IObservableVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, IVector<T>> {
::core::convert::TryInto::<IVector<T>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl<T: ::windows::core::RuntimeType + 'static> ::core::iter::IntoIterator for IObservableVector<T> {
type Item = T;
type IntoIter = VectorIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl<T: ::windows::core::RuntimeType + 'static> ::core::iter::IntoIterator for &IObservableVector<T> {
type Item = T;
type IntoIter = VectorIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
VectorIterator::new(::core::convert::TryInto::try_into(self).ok())
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IObservableVector_abi<T>(
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, vhnd: ::windows::core::RawPtr, result__: *mut super::EventRegistrationToken) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::EventRegistrationToken) -> ::windows::core::HRESULT,
pub ::core::marker::PhantomData<T>,
)
where
T: ::windows::core::RuntimeType + 'static;
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IPropertySet(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPropertySet {
type Vtable = IPropertySet_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8a43ed9f_f4e6_4421_acf9_1dab2986820c);
}
impl IPropertySet {
pub fn First(&self) -> ::windows::core::Result<IIterator<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> {
let this = &::windows::core::Interface::cast::<IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>>(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::<IIterator<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>>(result__)
}
}
pub fn Lookup<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, key: Param0) -> ::windows::core::Result<::windows::core::IInspectable> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<::windows::core::IInspectable>(result__)
}
}
pub fn Size(&self) -> ::windows::core::Result<u32> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn HasKey<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, key: Param0) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn GetView(&self) -> ::windows::core::Result<IMapView<::windows::core::HSTRING, ::windows::core::IInspectable>> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(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::<IMapView<::windows::core::HSTRING, ::windows::core::IInspectable>>(result__)
}
}
pub fn Insert<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(&self, key: Param0, value: Param1) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), key.into_param().abi(), value.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Remove<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, key: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), key.into_param().abi()).ok() }
}
pub fn Clear(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this)).ok() }
}
pub fn MapChanged<'a, Param0: ::windows::core::IntoParam<'a, MapChangedEventHandler<::windows::core::HSTRING, ::windows::core::IInspectable>>>(&self, vhnd: Param0) -> ::windows::core::Result<super::EventRegistrationToken> {
let this = &::windows::core::Interface::cast::<IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: super::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), vhnd.into_param().abi(), &mut result__).from_abi::<super::EventRegistrationToken>(result__)
}
}
pub fn RemoveMapChanged<'a, Param0: ::windows::core::IntoParam<'a, super::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IPropertySet {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{8a43ed9f-f4e6-4421-acf9-1dab2986820c}");
}
impl ::core::convert::From<IPropertySet> for ::windows::core::IUnknown {
fn from(value: IPropertySet) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IPropertySet> for ::windows::core::IUnknown {
fn from(value: &IPropertySet) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPropertySet {
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 IPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IPropertySet> for ::windows::core::IInspectable {
fn from(value: IPropertySet) -> Self {
value.0
}
}
impl ::core::convert::From<&IPropertySet> for ::windows::core::IInspectable {
fn from(value: &IPropertySet) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IPropertySet {
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 IPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::TryFrom<IPropertySet> for IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>> {
type Error = ::windows::core::Error;
fn try_from(value: IPropertySet) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&IPropertySet> for IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>> {
type Error = ::windows::core::Error;
fn try_from(value: &IPropertySet) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> for IPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> for &IPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> {
::core::convert::TryInto::<IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<IPropertySet> for IMap<::windows::core::HSTRING, ::windows::core::IInspectable> {
type Error = ::windows::core::Error;
fn try_from(value: IPropertySet) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&IPropertySet> for IMap<::windows::core::HSTRING, ::windows::core::IInspectable> {
type Error = ::windows::core::Error;
fn try_from(value: &IPropertySet) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMap<::windows::core::HSTRING, ::windows::core::IInspectable>> for IPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IMap<::windows::core::HSTRING, ::windows::core::IInspectable>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMap<::windows::core::HSTRING, ::windows::core::IInspectable>> for &IPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IMap<::windows::core::HSTRING, ::windows::core::IInspectable>> {
::core::convert::TryInto::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<IPropertySet> for IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable> {
type Error = ::windows::core::Error;
fn try_from(value: IPropertySet) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&IPropertySet> for IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable> {
type Error = ::windows::core::Error;
fn try_from(value: &IPropertySet) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>> for IPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>> for &IPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>> {
::core::convert::TryInto::<IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for IPropertySet {
type Item = IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for &IPropertySet {
type Item = IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.First().unwrap()
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IPropertySet_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,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IVector<T>(pub ::windows::core::IInspectable, ::core::marker::PhantomData<T>)
where
T: ::windows::core::RuntimeType + 'static;
unsafe impl<T: ::windows::core::RuntimeType + 'static> ::windows::core::Interface for IVector<T> {
type Vtable = IVector_abi<T>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<IVector<T> as ::windows::core::RuntimeType>::SIGNATURE);
}
impl<T: ::windows::core::RuntimeType + 'static> IVector<T> {
pub fn GetAt(&self, index: u32) -> ::windows::core::Result<T> {
let this = self;
unsafe {
let mut result__: <T as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), index, &mut result__).from_abi::<T>(result__)
}
}
pub fn Size(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn GetView(&self) -> ::windows::core::Result<IVectorView<T>> {
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::<IVectorView<T>>(result__)
}
}
pub fn IndexOf<'a, Param0: ::windows::core::IntoParam<'a, T>>(&self, value: Param0, index: &mut u32) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi(), index, &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetAt<'a, Param1: ::windows::core::IntoParam<'a, T>>(&self, index: u32, value: Param1) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), index, value.into_param().abi()).ok() }
}
pub fn InsertAt<'a, Param1: ::windows::core::IntoParam<'a, T>>(&self, index: u32, value: Param1) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), index, value.into_param().abi()).ok() }
}
pub fn RemoveAt(&self, index: u32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), index).ok() }
}
pub fn Append<'a, Param0: ::windows::core::IntoParam<'a, T>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn RemoveAtEnd(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this)).ok() }
}
pub fn Clear(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this)).ok() }
}
pub fn GetMany(&self, startindex: u32, items: &mut [<T as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), startindex, items.len() as u32, ::core::mem::transmute_copy(&items), &mut result__).from_abi::<u32>(result__)
}
}
pub fn ReplaceAll(&self, items: &[<T as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), items.len() as u32, ::core::mem::transmute(items.as_ptr())).ok() }
}
pub fn First(&self) -> ::windows::core::Result<IIterator<T>> {
let this = &::windows::core::Interface::cast::<IIterable<T>>(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::<IIterator<T>>(result__)
}
}
}
unsafe impl<T: ::windows::core::RuntimeType + 'static> ::windows::core::RuntimeType for IVector<T> {
const SIGNATURE: ::windows::core::ConstBuffer = { ::windows::core::ConstBuffer::new().push_slice(b"pinterface(").push_slice(b"{913337e9-11a1-4345-a3a2-4e7f956e222d}").push_slice(b";").push_other(<T as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b")") };
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<IVector<T>> for ::windows::core::IUnknown {
fn from(value: IVector<T>) -> Self {
value.0 .0
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IVector<T>> for ::windows::core::IUnknown {
fn from(value: &IVector<T>) -> Self {
value.0 .0.clone()
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<IVector<T>> for ::windows::core::IInspectable {
fn from(value: IVector<T>) -> Self {
value.0
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IVector<T>> for ::windows::core::IInspectable {
fn from(value: &IVector<T>) -> Self {
value.0.clone()
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<IVector<T>> for IIterable<T> {
type Error = ::windows::core::Error;
fn try_from(value: IVector<T>) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<&IVector<T>> for IIterable<T> {
type Error = ::windows::core::Error;
fn try_from(value: &IVector<T>) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IIterable<T>> for IVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<T>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IIterable<T>> for &IVector<T> {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<T>> {
::core::convert::TryInto::<IIterable<T>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
pub struct VectorIterator<T: ::windows::core::RuntimeType + 'static> {
vector: ::core::option::Option<IVector<T>>,
current: u32,
}
impl<T: ::windows::core::RuntimeType> VectorIterator<T> {
pub fn new(vector: ::core::option::Option<IVector<T>>) -> Self {
Self { vector, current: 0 }
}
}
impl<T: ::windows::core::RuntimeType> ::core::iter::Iterator for VectorIterator<T> {
type Item = T;
fn next(&mut self) -> ::core::option::Option<Self::Item> {
self.vector.as_ref().and_then(|vector| vector.GetAt(self.current).ok()).and_then(|result| {
self.current += 1;
Some(result)
})
}
}
impl<T: ::windows::core::RuntimeType> ::core::iter::IntoIterator for IVector<T> {
type Item = T;
type IntoIter = VectorIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
impl<T: ::windows::core::RuntimeType> ::core::iter::IntoIterator for &IVector<T> {
type Item = T;
type IntoIter = VectorIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
VectorIterator::new(::core::option::Option::Some(::core::clone::Clone::clone(self)))
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IVector_abi<T>(
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, index: u32, result__: *mut <T as ::windows::core::Abi>::Abi) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: <T as ::windows::core::Abi>::Abi, index: *mut u32, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, index: u32, value: <T as ::windows::core::Abi>::Abi) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, index: u32, value: <T as ::windows::core::Abi>::Abi) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, index: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: <T as ::windows::core::Abi>::Abi) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, startindex: u32, items_array_size: u32, items: *mut <T as ::windows::core::Abi>::Abi, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, items_array_size: u32, items: *const <T as ::windows::core::Abi>::Abi) -> ::windows::core::HRESULT,
pub ::core::marker::PhantomData<T>,
)
where
T: ::windows::core::RuntimeType + 'static;
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IVectorChangedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVectorChangedEventArgs {
type Vtable = IVectorChangedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x575933df_34fe_4480_af15_07691f3d5d9b);
}
impl IVectorChangedEventArgs {
pub fn CollectionChange(&self) -> ::windows::core::Result<CollectionChange> {
let this = self;
unsafe {
let mut result__: CollectionChange = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<CollectionChange>(result__)
}
}
pub fn Index(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for IVectorChangedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{575933df-34fe-4480-af15-07691f3d5d9b}");
}
impl ::core::convert::From<IVectorChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: IVectorChangedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IVectorChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: &IVectorChangedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVectorChangedEventArgs {
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 IVectorChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IVectorChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: IVectorChangedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&IVectorChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: &IVectorChangedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IVectorChangedEventArgs {
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 IVectorChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IVectorChangedEventArgs_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 CollectionChange) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IVectorView<T>(pub ::windows::core::IInspectable, ::core::marker::PhantomData<T>)
where
T: ::windows::core::RuntimeType + 'static;
unsafe impl<T: ::windows::core::RuntimeType + 'static> ::windows::core::Interface for IVectorView<T> {
type Vtable = IVectorView_abi<T>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<IVectorView<T> as ::windows::core::RuntimeType>::SIGNATURE);
}
impl<T: ::windows::core::RuntimeType + 'static> IVectorView<T> {
pub fn GetAt(&self, index: u32) -> ::windows::core::Result<T> {
let this = self;
unsafe {
let mut result__: <T as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), index, &mut result__).from_abi::<T>(result__)
}
}
pub fn Size(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn IndexOf<'a, Param0: ::windows::core::IntoParam<'a, T>>(&self, value: Param0, index: &mut u32) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi(), index, &mut result__).from_abi::<bool>(result__)
}
}
pub fn GetMany(&self, startindex: u32, items: &mut [<T as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), startindex, items.len() as u32, ::core::mem::transmute_copy(&items), &mut result__).from_abi::<u32>(result__)
}
}
pub fn First(&self) -> ::windows::core::Result<IIterator<T>> {
let this = &::windows::core::Interface::cast::<IIterable<T>>(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::<IIterator<T>>(result__)
}
}
}
unsafe impl<T: ::windows::core::RuntimeType + 'static> ::windows::core::RuntimeType for IVectorView<T> {
const SIGNATURE: ::windows::core::ConstBuffer = { ::windows::core::ConstBuffer::new().push_slice(b"pinterface(").push_slice(b"{bbe1fa4c-b0e3-4583-baef-1f1b2e483e56}").push_slice(b";").push_other(<T as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b")") };
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<IVectorView<T>> for ::windows::core::IUnknown {
fn from(value: IVectorView<T>) -> Self {
value.0 .0
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IVectorView<T>> for ::windows::core::IUnknown {
fn from(value: &IVectorView<T>) -> Self {
value.0 .0.clone()
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVectorView<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IVectorView<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<IVectorView<T>> for ::windows::core::IInspectable {
fn from(value: IVectorView<T>) -> Self {
value.0
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::From<&IVectorView<T>> for ::windows::core::IInspectable {
fn from(value: &IVectorView<T>) -> Self {
value.0.clone()
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IVectorView<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IVectorView<T> {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<IVectorView<T>> for IIterable<T> {
type Error = ::windows::core::Error;
fn try_from(value: IVectorView<T>) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl<T: ::windows::core::RuntimeType + 'static> ::core::convert::TryFrom<&IVectorView<T>> for IIterable<T> {
type Error = ::windows::core::Error;
fn try_from(value: &IVectorView<T>) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IIterable<T>> for IVectorView<T> {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<T>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a, T: ::windows::core::RuntimeType + 'static> ::windows::core::IntoParam<'a, IIterable<T>> for &IVectorView<T> {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<T>> {
::core::convert::TryInto::<IIterable<T>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
pub struct VectorViewIterator<T: ::windows::core::RuntimeType + 'static> {
vector: ::core::option::Option<IVectorView<T>>,
current: u32,
}
impl<T: ::windows::core::RuntimeType> VectorViewIterator<T> {
pub fn new(vector: ::core::option::Option<IVectorView<T>>) -> Self {
Self { vector, current: 0 }
}
}
impl<T: ::windows::core::RuntimeType> ::core::iter::Iterator for VectorViewIterator<T> {
type Item = T;
fn next(&mut self) -> ::core::option::Option<Self::Item> {
self.vector.as_ref().and_then(|vector| vector.GetAt(self.current).ok()).and_then(|result| {
self.current += 1;
Some(result)
})
}
}
impl<T: ::windows::core::RuntimeType> ::core::iter::IntoIterator for IVectorView<T> {
type Item = T;
type IntoIter = VectorViewIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
impl<T: ::windows::core::RuntimeType> ::core::iter::IntoIterator for &IVectorView<T> {
type Item = T;
type IntoIter = VectorViewIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
VectorViewIterator::new(::core::option::Option::Some(::core::clone::Clone::clone(self)))
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IVectorView_abi<T>(
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, index: u32, result__: *mut <T as ::windows::core::Abi>::Abi) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: <T as ::windows::core::Abi>::Abi, index: *mut u32, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, startindex: u32, items_array_size: u32, items: *mut <T as ::windows::core::Abi>::Abi, result__: *mut u32) -> ::windows::core::HRESULT,
pub ::core::marker::PhantomData<T>,
)
where
T: ::windows::core::RuntimeType + 'static;
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct MapChangedEventHandler<K, V>(::windows::core::IUnknown, ::core::marker::PhantomData<K>, ::core::marker::PhantomData<V>)
where
K: ::windows::core::RuntimeType + 'static,
V: ::windows::core::RuntimeType + 'static;
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> MapChangedEventHandler<K, V> {
pub fn new<F: FnMut(&::core::option::Option<IObservableMap<K, V>>, &::core::option::Option<IMapChangedEventArgs<K>>) -> ::windows::core::Result<()> + 'static>(invoke: F) -> Self {
let com = MapChangedEventHandler_box::<K, V, F> {
vtable: &MapChangedEventHandler_box::<K, V, F>::VTABLE,
count: ::windows::core::RefCount::new(1),
invoke,
};
unsafe { core::mem::transmute(::windows::core::alloc::boxed::Box::new(com)) }
}
pub fn Invoke<'a, Param0: ::windows::core::IntoParam<'a, IObservableMap<K, V>>, Param1: ::windows::core::IntoParam<'a, IMapChangedEventArgs<K>>>(&self, sender: Param0, event: Param1) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).3)(::core::mem::transmute_copy(this), sender.into_param().abi(), event.into_param().abi()).ok() }
}
}
unsafe impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::RuntimeType for MapChangedEventHandler<K, V> {
const SIGNATURE: ::windows::core::ConstBuffer = { ::windows::core::ConstBuffer::new().push_slice(b"pinterface(").push_slice(b"{179517f3-94ee-41f8-bddc-768a895544f3}").push_slice(b";").push_other(<K as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b";").push_other(<V as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b")") };
}
unsafe impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static> ::windows::core::Interface for MapChangedEventHandler<K, V> {
type Vtable = MapChangedEventHandler_abi<K, V>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<MapChangedEventHandler<K, V> as ::windows::core::RuntimeType>::SIGNATURE);
}
#[repr(C)]
#[doc(hidden)]
pub struct MapChangedEventHandler_abi<K, V>(
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, sender: ::windows::core::RawPtr, event: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub ::core::marker::PhantomData<K>,
pub ::core::marker::PhantomData<V>,
)
where
K: ::windows::core::RuntimeType + 'static,
V: ::windows::core::RuntimeType + 'static;
#[repr(C)]
struct MapChangedEventHandler_box<K, V, F: FnMut(&::core::option::Option<IObservableMap<K, V>>, &::core::option::Option<IMapChangedEventArgs<K>>) -> ::windows::core::Result<()> + 'static>
where
K: ::windows::core::RuntimeType + 'static,
V: ::windows::core::RuntimeType + 'static,
{
vtable: *const MapChangedEventHandler_abi<K, V>,
invoke: F,
count: ::windows::core::RefCount,
}
impl<K: ::windows::core::RuntimeType + 'static, V: ::windows::core::RuntimeType + 'static, F: FnMut(&::core::option::Option<IObservableMap<K, V>>, &::core::option::Option<IMapChangedEventArgs<K>>) -> ::windows::core::Result<()> + 'static> MapChangedEventHandler_box<K, V, F> {
const VTABLE: MapChangedEventHandler_abi<K, V> = MapChangedEventHandler_abi::<K, V>(Self::QueryInterface, Self::AddRef, Self::Release, Self::Invoke, ::core::marker::PhantomData::<K>, ::core::marker::PhantomData::<V>);
unsafe extern "system" fn QueryInterface(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT {
let this = this as *mut ::windows::core::RawPtr as *mut Self;
*interface = if iid == &<MapChangedEventHandler<K, V> as ::windows::core::Interface>::IID || iid == &<::windows::core::IUnknown as ::windows::core::Interface>::IID || iid == &<::windows::core::IAgileObject as ::windows::core::Interface>::IID {
&mut (*this).vtable as *mut _ as _
} else {
::core::ptr::null_mut()
};
if (*interface).is_null() {
::windows::core::HRESULT(0x8000_4002)
} else {
(*this).count.add_ref();
::windows::core::HRESULT(0)
}
}
unsafe extern "system" fn AddRef(this: ::windows::core::RawPtr) -> u32 {
let this = this as *mut ::windows::core::RawPtr as *mut Self;
(*this).count.add_ref()
}
unsafe extern "system" fn Release(this: ::windows::core::RawPtr) -> u32 {
let this = this as *mut ::windows::core::RawPtr as *mut Self;
let remaining = (*this).count.release();
if remaining == 0 {
::windows::core::alloc::boxed::Box::from_raw(this);
}
remaining
}
unsafe extern "system" fn Invoke(this: ::windows::core::RawPtr, sender: ::windows::core::RawPtr, event: ::windows::core::RawPtr) -> ::windows::core::HRESULT {
let this = this as *mut ::windows::core::RawPtr as *mut Self;
((*this).invoke)(
&*(&sender as *const <IObservableMap<K, V> as ::windows::core::Abi>::Abi as *const <IObservableMap<K, V> as ::windows::core::DefaultType>::DefaultType),
&*(&event as *const <IMapChangedEventArgs<K> as ::windows::core::Abi>::Abi as *const <IMapChangedEventArgs<K> as ::windows::core::DefaultType>::DefaultType),
)
.into()
}
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PropertySet(pub ::windows::core::IInspectable);
impl PropertySet {
pub fn new() -> ::windows::core::Result<Self> {
Self::IActivationFactory(|f| f.activate_instance::<Self>())
}
fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<PropertySet, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn First(&self) -> ::windows::core::Result<IIterator<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> {
let this = &::windows::core::Interface::cast::<IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>>(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::<IIterator<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>>(result__)
}
}
pub fn Lookup<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, key: Param0) -> ::windows::core::Result<::windows::core::IInspectable> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<::windows::core::IInspectable>(result__)
}
}
pub fn Size(&self) -> ::windows::core::Result<u32> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn HasKey<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, key: Param0) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn GetView(&self) -> ::windows::core::Result<IMapView<::windows::core::HSTRING, ::windows::core::IInspectable>> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(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::<IMapView<::windows::core::HSTRING, ::windows::core::IInspectable>>(result__)
}
}
pub fn Insert<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(&self, key: Param0, value: Param1) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), key.into_param().abi(), value.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Remove<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, key: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), key.into_param().abi()).ok() }
}
pub fn Clear(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this)).ok() }
}
pub fn MapChanged<'a, Param0: ::windows::core::IntoParam<'a, MapChangedEventHandler<::windows::core::HSTRING, ::windows::core::IInspectable>>>(&self, vhnd: Param0) -> ::windows::core::Result<super::EventRegistrationToken> {
let this = &::windows::core::Interface::cast::<IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: super::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), vhnd.into_param().abi(), &mut result__).from_abi::<super::EventRegistrationToken>(result__)
}
}
pub fn RemoveMapChanged<'a, Param0: ::windows::core::IntoParam<'a, super::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PropertySet {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Foundation.Collections.PropertySet;{8a43ed9f-f4e6-4421-acf9-1dab2986820c})");
}
unsafe impl ::windows::core::Interface for PropertySet {
type Vtable = IPropertySet_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8a43ed9f_f4e6_4421_acf9_1dab2986820c);
}
impl ::windows::core::RuntimeName for PropertySet {
const NAME: &'static str = "Windows.Foundation.Collections.PropertySet";
}
impl ::core::convert::From<PropertySet> for ::windows::core::IUnknown {
fn from(value: PropertySet) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PropertySet> for ::windows::core::IUnknown {
fn from(value: &PropertySet) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PropertySet {
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 PropertySet {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PropertySet> for ::windows::core::IInspectable {
fn from(value: PropertySet) -> Self {
value.0
}
}
impl ::core::convert::From<&PropertySet> for ::windows::core::IInspectable {
fn from(value: &PropertySet) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PropertySet {
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 PropertySet {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<PropertySet> for IPropertySet {
fn from(value: PropertySet) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&PropertySet> for IPropertySet {
fn from(value: &PropertySet) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IPropertySet> for PropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IPropertySet> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IPropertySet> for &PropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IPropertySet> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
impl ::core::convert::TryFrom<PropertySet> for IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>> {
type Error = ::windows::core::Error;
fn try_from(value: PropertySet) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PropertySet> for IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>> {
type Error = ::windows::core::Error;
fn try_from(value: &PropertySet) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> for PropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> for &PropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> {
::core::convert::TryInto::<IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<PropertySet> for IMap<::windows::core::HSTRING, ::windows::core::IInspectable> {
type Error = ::windows::core::Error;
fn try_from(value: PropertySet) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PropertySet> for IMap<::windows::core::HSTRING, ::windows::core::IInspectable> {
type Error = ::windows::core::Error;
fn try_from(value: &PropertySet) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMap<::windows::core::HSTRING, ::windows::core::IInspectable>> for PropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IMap<::windows::core::HSTRING, ::windows::core::IInspectable>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMap<::windows::core::HSTRING, ::windows::core::IInspectable>> for &PropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IMap<::windows::core::HSTRING, ::windows::core::IInspectable>> {
::core::convert::TryInto::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<PropertySet> for IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable> {
type Error = ::windows::core::Error;
fn try_from(value: PropertySet) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PropertySet> for IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable> {
type Error = ::windows::core::Error;
fn try_from(value: &PropertySet) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>> for PropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>> for &PropertySet {
fn into_param(self) -> ::windows::core::Param<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>> {
::core::convert::TryInto::<IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for PropertySet {}
unsafe impl ::core::marker::Sync for PropertySet {}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for PropertySet {
type Item = IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for &PropertySet {
type Item = IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.First().unwrap()
}
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct StringMap(pub ::windows::core::IInspectable);
impl StringMap {
pub fn new() -> ::windows::core::Result<Self> {
Self::IActivationFactory(|f| f.activate_instance::<Self>())
}
fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<StringMap, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn Lookup<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, key: Param0) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Size(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn HasKey<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, key: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn GetView(&self) -> ::windows::core::Result<IMapView<::windows::core::HSTRING, ::windows::core::HSTRING>> {
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::<IMapView<::windows::core::HSTRING, ::windows::core::HSTRING>>(result__)
}
}
pub fn Insert<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, key: Param0, value: Param1) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), key.into_param().abi(), value.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Remove<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, key: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), key.into_param().abi()).ok() }
}
pub fn Clear(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this)).ok() }
}
pub fn First(&self) -> ::windows::core::Result<IIterator<IKeyValuePair<::windows::core::HSTRING, ::windows::core::HSTRING>>> {
let this = &::windows::core::Interface::cast::<IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::HSTRING>>>(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::<IIterator<IKeyValuePair<::windows::core::HSTRING, ::windows::core::HSTRING>>>(result__)
}
}
pub fn MapChanged<'a, Param0: ::windows::core::IntoParam<'a, MapChangedEventHandler<::windows::core::HSTRING, ::windows::core::HSTRING>>>(&self, vhnd: Param0) -> ::windows::core::Result<super::EventRegistrationToken> {
let this = &::windows::core::Interface::cast::<IObservableMap<::windows::core::HSTRING, ::windows::core::HSTRING>>(self)?;
unsafe {
let mut result__: super::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), vhnd.into_param().abi(), &mut result__).from_abi::<super::EventRegistrationToken>(result__)
}
}
pub fn RemoveMapChanged<'a, Param0: ::windows::core::IntoParam<'a, super::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IObservableMap<::windows::core::HSTRING, ::windows::core::HSTRING>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for StringMap {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Foundation.Collections.StringMap;pinterface({3c2925fe-8519-45c1-aa79-197b6718c1c1};string;string))");
}
unsafe impl ::windows::core::Interface for StringMap {
type Vtable = IMap_abi<::windows::core::HSTRING, ::windows::core::HSTRING>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<IMap<::windows::core::HSTRING, ::windows::core::HSTRING> as ::windows::core::RuntimeType>::SIGNATURE);
}
impl ::windows::core::RuntimeName for StringMap {
const NAME: &'static str = "Windows.Foundation.Collections.StringMap";
}
impl ::core::convert::From<StringMap> for ::windows::core::IUnknown {
fn from(value: StringMap) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&StringMap> for ::windows::core::IUnknown {
fn from(value: &StringMap) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for StringMap {
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 StringMap {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<StringMap> for ::windows::core::IInspectable {
fn from(value: StringMap) -> Self {
value.0
}
}
impl ::core::convert::From<&StringMap> for ::windows::core::IInspectable {
fn from(value: &StringMap) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for StringMap {
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 StringMap {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<StringMap> for IMap<::windows::core::HSTRING, ::windows::core::HSTRING> {
fn from(value: StringMap) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&StringMap> for IMap<::windows::core::HSTRING, ::windows::core::HSTRING> {
fn from(value: &StringMap) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IMap<::windows::core::HSTRING, ::windows::core::HSTRING>> for StringMap {
fn into_param(self) -> ::windows::core::Param<'a, IMap<::windows::core::HSTRING, ::windows::core::HSTRING>> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IMap<::windows::core::HSTRING, ::windows::core::HSTRING>> for &StringMap {
fn into_param(self) -> ::windows::core::Param<'a, IMap<::windows::core::HSTRING, ::windows::core::HSTRING>> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
impl ::core::convert::TryFrom<StringMap> for IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::HSTRING>> {
type Error = ::windows::core::Error;
fn try_from(value: StringMap) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&StringMap> for IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::HSTRING>> {
type Error = ::windows::core::Error;
fn try_from(value: &StringMap) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::HSTRING>>> for StringMap {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::HSTRING>>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::HSTRING>>> for &StringMap {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::HSTRING>>> {
::core::convert::TryInto::<IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::HSTRING>>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<StringMap> for IObservableMap<::windows::core::HSTRING, ::windows::core::HSTRING> {
type Error = ::windows::core::Error;
fn try_from(value: StringMap) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&StringMap> for IObservableMap<::windows::core::HSTRING, ::windows::core::HSTRING> {
type Error = ::windows::core::Error;
fn try_from(value: &StringMap) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::HSTRING>> for StringMap {
fn into_param(self) -> ::windows::core::Param<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::HSTRING>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::HSTRING>> for &StringMap {
fn into_param(self) -> ::windows::core::Param<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::HSTRING>> {
::core::convert::TryInto::<IObservableMap<::windows::core::HSTRING, ::windows::core::HSTRING>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for StringMap {}
unsafe impl ::core::marker::Sync for StringMap {}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for StringMap {
type Item = IKeyValuePair<::windows::core::HSTRING, ::windows::core::HSTRING>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for &StringMap {
type Item = IKeyValuePair<::windows::core::HSTRING, ::windows::core::HSTRING>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.First().unwrap()
}
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ValueSet(pub ::windows::core::IInspectable);
impl ValueSet {
pub fn new() -> ::windows::core::Result<Self> {
Self::IActivationFactory(|f| f.activate_instance::<Self>())
}
fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<ValueSet, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn First(&self) -> ::windows::core::Result<IIterator<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> {
let this = &::windows::core::Interface::cast::<IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>>(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::<IIterator<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>>(result__)
}
}
pub fn Lookup<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, key: Param0) -> ::windows::core::Result<::windows::core::IInspectable> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<::windows::core::IInspectable>(result__)
}
}
pub fn Size(&self) -> ::windows::core::Result<u32> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn HasKey<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, key: Param0) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn GetView(&self) -> ::windows::core::Result<IMapView<::windows::core::HSTRING, ::windows::core::IInspectable>> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(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::<IMapView<::windows::core::HSTRING, ::windows::core::IInspectable>>(result__)
}
}
pub fn Insert<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(&self, key: Param0, value: Param1) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), key.into_param().abi(), value.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Remove<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, key: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), key.into_param().abi()).ok() }
}
pub fn Clear(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this)).ok() }
}
pub fn MapChanged<'a, Param0: ::windows::core::IntoParam<'a, MapChangedEventHandler<::windows::core::HSTRING, ::windows::core::IInspectable>>>(&self, vhnd: Param0) -> ::windows::core::Result<super::EventRegistrationToken> {
let this = &::windows::core::Interface::cast::<IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe {
let mut result__: super::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), vhnd.into_param().abi(), &mut result__).from_abi::<super::EventRegistrationToken>(result__)
}
}
pub fn RemoveMapChanged<'a, Param0: ::windows::core::IntoParam<'a, super::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for ValueSet {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Foundation.Collections.ValueSet;{8a43ed9f-f4e6-4421-acf9-1dab2986820c})");
}
unsafe impl ::windows::core::Interface for ValueSet {
type Vtable = IPropertySet_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8a43ed9f_f4e6_4421_acf9_1dab2986820c);
}
impl ::windows::core::RuntimeName for ValueSet {
const NAME: &'static str = "Windows.Foundation.Collections.ValueSet";
}
impl ::core::convert::From<ValueSet> for ::windows::core::IUnknown {
fn from(value: ValueSet) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ValueSet> for ::windows::core::IUnknown {
fn from(value: &ValueSet) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ValueSet {
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 ValueSet {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ValueSet> for ::windows::core::IInspectable {
fn from(value: ValueSet) -> Self {
value.0
}
}
impl ::core::convert::From<&ValueSet> for ::windows::core::IInspectable {
fn from(value: &ValueSet) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ValueSet {
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 ValueSet {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<ValueSet> for IPropertySet {
fn from(value: ValueSet) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&ValueSet> for IPropertySet {
fn from(value: &ValueSet) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IPropertySet> for ValueSet {
fn into_param(self) -> ::windows::core::Param<'a, IPropertySet> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IPropertySet> for &ValueSet {
fn into_param(self) -> ::windows::core::Param<'a, IPropertySet> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
impl ::core::convert::TryFrom<ValueSet> for IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>> {
type Error = ::windows::core::Error;
fn try_from(value: ValueSet) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&ValueSet> for IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>> {
type Error = ::windows::core::Error;
fn try_from(value: &ValueSet) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> for ValueSet {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> for &ValueSet {
fn into_param(self) -> ::windows::core::Param<'a, IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>> {
::core::convert::TryInto::<IIterable<IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<ValueSet> for IMap<::windows::core::HSTRING, ::windows::core::IInspectable> {
type Error = ::windows::core::Error;
fn try_from(value: ValueSet) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&ValueSet> for IMap<::windows::core::HSTRING, ::windows::core::IInspectable> {
type Error = ::windows::core::Error;
fn try_from(value: &ValueSet) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMap<::windows::core::HSTRING, ::windows::core::IInspectable>> for ValueSet {
fn into_param(self) -> ::windows::core::Param<'a, IMap<::windows::core::HSTRING, ::windows::core::IInspectable>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMap<::windows::core::HSTRING, ::windows::core::IInspectable>> for &ValueSet {
fn into_param(self) -> ::windows::core::Param<'a, IMap<::windows::core::HSTRING, ::windows::core::IInspectable>> {
::core::convert::TryInto::<IMap<::windows::core::HSTRING, ::windows::core::IInspectable>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<ValueSet> for IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable> {
type Error = ::windows::core::Error;
fn try_from(value: ValueSet) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&ValueSet> for IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable> {
type Error = ::windows::core::Error;
fn try_from(value: &ValueSet) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>> for ValueSet {
fn into_param(self) -> ::windows::core::Param<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>> for &ValueSet {
fn into_param(self) -> ::windows::core::Param<'a, IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>> {
::core::convert::TryInto::<IObservableMap<::windows::core::HSTRING, ::windows::core::IInspectable>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for ValueSet {}
unsafe impl ::core::marker::Sync for ValueSet {}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for ValueSet {
type Item = IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for &ValueSet {
type Item = IKeyValuePair<::windows::core::HSTRING, ::windows::core::IInspectable>;
type IntoIter = IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.First().unwrap()
}
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct VectorChangedEventHandler<T>(::windows::core::IUnknown, ::core::marker::PhantomData<T>)
where
T: ::windows::core::RuntimeType + 'static;
impl<T: ::windows::core::RuntimeType + 'static> VectorChangedEventHandler<T> {
pub fn new<F: FnMut(&::core::option::Option<IObservableVector<T>>, &::core::option::Option<IVectorChangedEventArgs>) -> ::windows::core::Result<()> + 'static>(invoke: F) -> Self {
let com = VectorChangedEventHandler_box::<T, F> {
vtable: &VectorChangedEventHandler_box::<T, F>::VTABLE,
count: ::windows::core::RefCount::new(1),
invoke,
};
unsafe { core::mem::transmute(::windows::core::alloc::boxed::Box::new(com)) }
}
pub fn Invoke<'a, Param0: ::windows::core::IntoParam<'a, IObservableVector<T>>, Param1: ::windows::core::IntoParam<'a, IVectorChangedEventArgs>>(&self, sender: Param0, event: Param1) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).3)(::core::mem::transmute_copy(this), sender.into_param().abi(), event.into_param().abi()).ok() }
}
}
unsafe impl<T: ::windows::core::RuntimeType + 'static> ::windows::core::RuntimeType for VectorChangedEventHandler<T> {
const SIGNATURE: ::windows::core::ConstBuffer = { ::windows::core::ConstBuffer::new().push_slice(b"pinterface(").push_slice(b"{0c051752-9fbf-4c70-aa0c-0e4c82d9a761}").push_slice(b";").push_other(<T as ::windows::core::RuntimeType>::SIGNATURE).push_slice(b")") };
}
unsafe impl<T: ::windows::core::RuntimeType + 'static> ::windows::core::Interface for VectorChangedEventHandler<T> {
type Vtable = VectorChangedEventHandler_abi<T>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<VectorChangedEventHandler<T> as ::windows::core::RuntimeType>::SIGNATURE);
}
#[repr(C)]
#[doc(hidden)]
pub struct VectorChangedEventHandler_abi<T>(
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, sender: ::windows::core::RawPtr, event: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub ::core::marker::PhantomData<T>,
)
where
T: ::windows::core::RuntimeType + 'static;
#[repr(C)]
struct VectorChangedEventHandler_box<T, F: FnMut(&::core::option::Option<IObservableVector<T>>, &::core::option::Option<IVectorChangedEventArgs>) -> ::windows::core::Result<()> + 'static>
where
T: ::windows::core::RuntimeType + 'static,
{
vtable: *const VectorChangedEventHandler_abi<T>,
invoke: F,
count: ::windows::core::RefCount,
}
impl<T: ::windows::core::RuntimeType + 'static, F: FnMut(&::core::option::Option<IObservableVector<T>>, &::core::option::Option<IVectorChangedEventArgs>) -> ::windows::core::Result<()> + 'static> VectorChangedEventHandler_box<T, F> {
const VTABLE: VectorChangedEventHandler_abi<T> = VectorChangedEventHandler_abi::<T>(Self::QueryInterface, Self::AddRef, Self::Release, Self::Invoke, ::core::marker::PhantomData::<T>);
unsafe extern "system" fn QueryInterface(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT {
let this = this as *mut ::windows::core::RawPtr as *mut Self;
*interface = if iid == &<VectorChangedEventHandler<T> as ::windows::core::Interface>::IID || iid == &<::windows::core::IUnknown as ::windows::core::Interface>::IID || iid == &<::windows::core::IAgileObject as ::windows::core::Interface>::IID {
&mut (*this).vtable as *mut _ as _
} else {
::core::ptr::null_mut()
};
if (*interface).is_null() {
::windows::core::HRESULT(0x8000_4002)
} else {
(*this).count.add_ref();
::windows::core::HRESULT(0)
}
}
unsafe extern "system" fn AddRef(this: ::windows::core::RawPtr) -> u32 {
let this = this as *mut ::windows::core::RawPtr as *mut Self;
(*this).count.add_ref()
}
unsafe extern "system" fn Release(this: ::windows::core::RawPtr) -> u32 {
let this = this as *mut ::windows::core::RawPtr as *mut Self;
let remaining = (*this).count.release();
if remaining == 0 {
::windows::core::alloc::boxed::Box::from_raw(this);
}
remaining
}
unsafe extern "system" fn Invoke(this: ::windows::core::RawPtr, sender: ::windows::core::RawPtr, event: ::windows::core::RawPtr) -> ::windows::core::HRESULT {
let this = this as *mut ::windows::core::RawPtr as *mut Self;
((*this).invoke)(
&*(&sender as *const <IObservableVector<T> as ::windows::core::Abi>::Abi as *const <IObservableVector<T> as ::windows::core::DefaultType>::DefaultType),
&*(&event as *const <IVectorChangedEventArgs as ::windows::core::Abi>::Abi as *const <IVectorChangedEventArgs as ::windows::core::DefaultType>::DefaultType),
)
.into()
}
}
|
extern crate computer_repair;
use computer_repair::*;
fn main() {
let data = data::data();
let upper_bound = std::cmp::min(data.len(), 100);
for noun in 0..upper_bound {
for verb in 0..upper_bound {
let mut local = data.clone();
local[1] = noun;
local[2] = verb;
if interpret(&mut local) == 19690720 {
println!("{}", 100 * noun + verb);
return
}
}
}
}
|
use core::marker::PhantomData;
use {Sink, Poll, StartSend};
/// A sink combinator to change the error type of a sink.
///
/// This is created by the `Sink::from_err` method.
#[derive(Clone, Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct SinkFromErr<S, E> {
sink: S,
f: PhantomData<E>
}
pub fn new<S, E>(sink: S) -> SinkFromErr<S, E>
where S: Sink
{
SinkFromErr {
sink: sink,
f: PhantomData
}
}
impl<S, E> SinkFromErr<S, E> {
/// Get a shared reference to the inner sink.
pub fn get_ref(&self) -> &S {
&self.sink
}
/// Get a mutable reference to the inner sink.
pub fn get_mut(&mut self) -> &mut S {
&mut self.sink
}
/// Consumes this combinator, returning the underlying sink.
///
/// Note that this may discard intermediate state of this combinator, so
/// care should be taken to avoid losing resources when this is called.
pub fn into_inner(self) -> S {
self.sink
}
}
impl<S, E> Sink for SinkFromErr<S, E>
where S: Sink,
E: From<S::SinkError>
{
type SinkItem = S::SinkItem;
type SinkError = E;
fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
self.sink.start_send(item).map_err(|e| e.into())
}
fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
self.sink.poll_complete().map_err(|e| e.into())
}
fn close(&mut self) -> Poll<(), Self::SinkError> {
self.sink.close().map_err(|e| e.into())
}
}
impl<S: ::stream::Stream, E> ::stream::Stream for SinkFromErr<S, E> {
type Item = S::Item;
type Error = S::Error;
fn poll(&mut self) -> Poll<Option<S::Item>, S::Error> {
self.sink.poll()
}
}
|
extern crate clang_sys; // NOTE: This should match the version used by clang ideally
pub extern crate clang;
use clang::*;
use std::collections::HashMap;
use std::error::Error;
const DERIVE: &'static str = "DERIVE";
/// Try to get the value at the cursor as an attribute(annotate). Returns the
/// name of the value if the cursor points at an attribute(annotate), and
/// Err(()) otherwise.
fn get_annotation(entity: Entity) -> Result<String, ()> {
if entity.get_kind() != EntityKind::AnnotateAttr {
return Err(());
}
entity.get_display_name().ok_or(())
}
fn get_derive_name(entity: Entity) -> Result<String, ()> {
let annotation = get_annotation(entity)?;
let mut it = annotation.splitn(2, '=');
let before = it.next().ok_or(())?;
if before != DERIVE {
return Err(());
}
Ok(it.next().ok_or(())?.to_owned())
}
fn discover_derives<F>(outer: Entity, f: &mut F)
where F: FnMut(Entity, String)
{
outer.visit_children(|entity, parent_entity| {
if let Ok(derive_name) = get_derive_name(entity) {
// XXX: Error Handling
let ty = parent_entity.get_typedef_underlying_type().unwrap();
f(ty.get_declaration().unwrap().get_definition().unwrap(), derive_name);
}
EntityVisitResult::Recurse
});
}
// This is copied mostly wholesale from rust-bindgen
fn fixup_clang_args(args: &mut Vec<String>) {
// Filter out include paths and similar stuff, so we don't incorrectly
// promote them to `-isystem`.
let sysargs = {
let mut last_was_include_prefix = false;
args.iter().filter(|arg| {
if last_was_include_prefix {
last_was_include_prefix = false;
return false;
}
let arg = &**arg;
// https://clang.llvm.org/docs/ClangCommandLineReference.html
// -isystem and -isystem-after are harmless.
if arg == "-I" || arg == "--include-directory" {
last_was_include_prefix = true;
return false;
}
if arg.starts_with("-I") || arg.starts_with("--include-directory=") {
return false;
}
true
}).cloned().collect::<Vec<_>>()
};
if let Some(clang) = clang_sys::support::Clang::find(None, &sysargs) {
// If --target is specified, assume caller knows what they're doing
// and don't mess with include paths for them
let has_target_arg = args
.iter()
.rposition(|arg| arg.starts_with("--target"))
.is_some();
if !has_target_arg {
// TODO: distinguish C and C++ paths? C++'s should be enough, I
// guess.
if let Some(cpp_search_paths) = clang.cpp_search_paths {
for path in cpp_search_paths.into_iter() {
if let Ok(path) = path.into_os_string().into_string() {
args.push("-isystem".to_owned());
args.push(path);
}
}
}
}
}
}
pub trait Derive {
fn derive(&mut self, entity: Entity) -> Result<String, ()>;
}
pub struct Deriver<'a> {
derives: HashMap<String, &'a mut Derive>,
}
impl<'a> Deriver<'a> {
pub fn new() -> Self {
Deriver { derives: HashMap::new() }
}
pub fn register<S: Into<String>>(&mut self, name: S, derive: &'a mut Derive) {
self.derives.insert(name.into(), derive);
}
pub fn run(&mut self, args: &[String]) -> Result<String, Box<Error>> {
let clang = Clang::new()?;
let index = Index::new(&clang, false, true);
let filename = &args[0];
let mut args = args[1..].to_owned();
fixup_clang_args(&mut args);
let file = index.parser(filename).arguments(&args).parse()?;
let entity = file.get_entity();
// XXX: Encode filename as C-style string?
let mut result = format!("#include {:?}\n\n", filename);
discover_derives(entity, &mut |entity, name| {
if let Some(derive) = self.derives.get_mut(&name) {
let r = derive.derive(entity)
.expect(&format!("Derive {} failed on {:?}", name, entity));
result.push_str(&r);
} else {
eprintln!("Use of unregistered derive {}", name);
}
});
Ok(result)
}
}
|
use crate::app::Args;
use anyhow::Result;
use clap::Parser;
use maple_core::process::shell_command;
use maple_core::process::{CacheableCommand, ShellCommand};
use std::path::PathBuf;
use std::process::Command;
/// Execute the shell command
#[derive(Parser, Debug, Clone)]
pub struct Exec {
/// Specify the system command to run.
#[clap(index = 1)]
shell_cmd: String,
/// Specify the working directory of CMD
#[clap(long, value_parser)]
cmd_dir: Option<PathBuf>,
/// Specify the threshold for writing the output of command to a tempfile.
#[clap(long, default_value = "100000")]
output_threshold: usize,
}
impl Exec {
// This can work with the piped command, e.g., git ls-files | uniq.
fn prepare_exec_cmd(&self) -> Command {
let mut cmd = shell_command(self.shell_cmd.as_str());
if let Some(ref cmd_dir) = self.cmd_dir {
cmd.current_dir(cmd_dir);
}
cmd
}
pub fn run(
&self,
Args {
number,
icon,
no_cache,
..
}: Args,
) -> Result<()> {
let mut exec_cmd = self.prepare_exec_cmd();
// TODO: fix this properly
//
// `let g:clap_builtin_fuzzy_filter_threshold == 0` is used to configure clap always use
// the async on_typed impl, but some commands also makes this variable to control
// `--output-threshold`, which can be problamatic. I imagine not many people actually are
// aware of the option `--output-threshold`, I'll use this ugly fix for now.
let output_threshold = if self.output_threshold == 0 {
100_000
} else {
self.output_threshold
};
let cwd = match &self.cmd_dir {
Some(dir) => dir.clone(),
None => std::env::current_dir()?,
};
let shell_cmd = ShellCommand::new(self.shell_cmd.clone(), cwd);
CacheableCommand::new(
&mut exec_cmd,
shell_cmd,
number,
icon,
Some(output_threshold),
)
.try_cache_or_execute(no_cache)?
.print();
Ok(())
}
}
|
use proconio::input;
#[allow(unused_macros)]
macro_rules! dbg {
($($arg:tt)*) => {{
#[cfg(debug_assertions)]
std::dbg!($($arg)*);
}};
}
fn main() {
input! {
d: usize,
l: usize,
n: usize,
c: [usize; d],
};
const M: usize = 100_000;
let mut pos = vec![vec![]; M + 1];
for i in 0..d {
pos[c[i]].push(i + 1);
}
for i in 0..d {
pos[c[i]].push(i + 1 + d);
}
// 2回連結だと足りないので3回連結しておく
for i in 0..d {
pos[c[i]].push(i + 1 + d + d);
}
let mut cum_sum = vec![vec![]; M + 1];
for c in 1..=M {
cum_sum[c] = vec![0; pos[c].len()];
}
for c in 1..=M {
for j in 1..pos[c].len() {
cum_sum[c][j] += cum_sum[c][j - 1] + (pos[c][j] - pos[c][j - 1] - 1) / l;
}
}
for _ in 0..n {
input! {
k: usize,
f: usize,
t: usize,
};
let t = t - 1;
let pos = &pos[k];
let cum_sum = &cum_sum[k];
if pos.is_empty() {
println!("0");
continue;
}
let i = match pos.binary_search(&f) {
Ok(i) => i,
Err(i) => {
assert!(i < pos.len());
i
}
};
// 最初の好みの料理
let p = pos[i];
assert!(p >= f);
// f+1からp-1までの間に好みじゃない料理を食べる回数
let normal = (p - f).saturating_sub(1) / l;
if normal >= t {
println!("0");
continue;
}
let t = if p > f {
// f, ..., p
t - normal - 1
} else {
// f = p
assert_eq!(normal, 0);
t
};
// ループに入る前に好みの料理を食べる回数
let pre_fav = if p > f && pos.binary_search(&f).is_ok() {
2 // f, p
} else {
1 // p
};
// 好み + その他
let s = pos.len() / 3 + (cum_sum[i + pos.len() / 3] - cum_sum[i]);
assert!(s >= 1);
// ループ中に好みの料理を食べる回数
let loop_fav = t / s * (pos.len() / 3);
let t = t % s;
// (j - i) + (cum_sum[j] - cum_sum[i]) <= t となる最大の j
let mut ok = i;
let mut ng = cum_sum.len();
while ng - ok > 1 {
let mid = (ok + ng) / 2;
if (mid - i) + (cum_sum[mid] - cum_sum[i]) <= t {
ok = mid;
} else {
ng = mid;
}
}
let j = ok;
// ループ終了後に好みの料理を食べる回数
let post_fav = j - i;
println!("{}", pre_fav + loop_fav + post_fav);
}
}
|
use bot_commands::{BOTUTILS_GROUP, CMD_HELP, GENERAL_GROUP};
use bot_config::BotConfig;
use bot_db::{dyn_prefix, PgPoolKey, DATABASE_ENABLED};
use bot_events::{BotEventHandler, BotRawEventHandler};
use bot_utils::ShardManagerWrapper;
use serenity::client::bridge::gateway::GatewayIntents;
use serenity::client::{parse_token, TokenComponents};
use serenity::framework::standard::buckets::LimitedFor;
use serenity::framework::StandardFramework;
use serenity::http::Http;
use serenity::Client;
use std::boxed::Box;
use std::collections::HashSet;
use tracing::subscriber::set_global_default;
use tracing::{error, info};
// if you're new to Rust this function signature might look weird
// it's just saying this function can return no error and no value
// (which is what Ok(()) at the end is) or it can return a Box
// containing a struct that implements std::error::Error.
// this lets you use ? anywhere to return errors to the main function
pub async fn entrypoint() -> Result<(), Box<dyn std::error::Error>> {
// set global default logger for the logs we have
let sub = tracing_subscriber::fmt().with_level(true).finish();
set_global_default(sub).expect("failed to set global default logger");
// let's begin by changing directory to the bot executable file
bot_utils::set_dir();
// now load the config
BotConfig::set("config.toml");
// next, load the database
let db = if DATABASE_ENABLED {
Some(bot_db::set_db().await)
} else {
None
};
info!("parsing token...");
// this is the BOT ID, NOT the app ID
// we need to do a HTTP request for the app ID
let TokenComponents { bot_user_id, .. } =
parse_token(BotConfig::get().token()).expect("invalid token");
info!("token is valid");
info!("fetching bot owners...");
// fetch bot owners
let (owners, app_id) = {
// make a serenity HTTP client
let http = Http::new_with_token(BotConfig::get().token());
// fetch app info
let info = http
.get_current_application_info()
.await
.expect("failed to fetch app info");
let mut owners = HashSet::new();
// check if the bot is on a team
match info.team {
Some(t) => {
// if it is, overwrite the hashset with a new one
// the compiler's smart enough to determine what type we want to collect into
owners = t.members.iter().map(|m| m.user.id).collect();
}
None => {
// and if it isn't, just add the owner ID
owners.insert(info.owner.id);
}
};
(owners, info.id)
};
info!("found {} owners", owners.len());
info!("creating bot framework...");
// initialize the serenity client's command framework
let framework = StandardFramework::new()
// make a closure to configure the framework
.configure(|c| {
c
// want commands in DMs?
.allow_dm(true)
// need to block some users/guilds?
// note that these lists cannot be updated at runtime
.blocked_guilds(vec![].into_iter().collect())
.blocked_users(vec![].into_iter().collect())
// bot owners: this is fetched for you earlier on
.owners(owners)
// should commands be case insensitive?
.case_insensitivity(true)
// need to disable a command?
// same note as for blocked_{guilds,users}, you can't modify at runtime
.disabled_commands(vec![].into_iter().collect())
// ignore bots and/or webhooks?
// you almost always want this set to true
.ignore_bots(true)
.ignore_webhooks(true)
// do you need a prefix in DMs?
.no_dm_prefix(true)
// should mentioning this ID also be used as a prefix?
// setting to None will not allow mention prefixes
// setting to Some will allow mentions of that userid to be a prefix
.on_mention(Some(bot_user_id))
// global, bot-wide prefixes:
// these cannot be changed at runtime
.prefixes(vec!["~", "bt!"]);
if DATABASE_ENABLED {
// dynamic prefix: this changes based on the DB being enabled or not
c.dynamic_prefix(|ctx, msg| Box::pin(dyn_prefix(ctx, msg)));
}
c
})
// let's add a new rate limit bucket named "heavy"
.bucket("heavy", |b| {
b
// rate limit is per-user
.limit_for(LimitedFor::User)
// cancel command invocations on rate limit
.await_ratelimits(0)
// uncomment this line and pass a function if you want to have a function
// to handle rate limits
// .delay_action()
// rate limits are per every 300 seconds
.time_span(300)
// a user can only run a command in this bucket 10x every 300s
.limit(10)
// NO SEMICOLON AT THE END!
// you're returning the builder instead of just modifying it
// also note no `return` statement
})
// **NOTE**: if you add a bucket you *must* await the result
// this is because the buckets are internally stored behind a asynchronous Mutex
// that must be awaited to be unlocked
.await
// this is the help command: naming is a little bit different because of the way
// the macros change things up, but just turn the function name into all uppercase
// and you will find the actual command
.help(&CMD_HELP)
// this adds a group to the bot: same notes as for the help command above, but you
// must append `_GROUP` to the struct name and turn it into all uppercase
.group(&GENERAL_GROUP)
.group(&BOTUTILS_GROUP)
// if you have a error handler, uncomment this line and pass the function (don't call it!)
// .on_dispatch_error()
// if you need to call a function before running a command, do it here
// if the called function returns false, the command invocation will be cancelled
// .before()
// add error handlers here: if a cmd returned a error, it'll be passed as the 4th
// argument to this function
.after(|_, _, _, z| {
Box::pin(async move {
if let Err(e) = z {
error!("command failed: {}", e)
}
})
})
// want to do something on a normal message? you can also use `EventHandler::on_message`
// and you should use that instead actually
// .normal_message()
// want to do something when a user types only the prefix and nothing else?
// .prefix_only()
// unknown command? use this
// .unrecognised_command()
;
info!("initializing serenity client...");
// construct a client with the token
let mut client = Client::builder(BotConfig::get().token())
.intents(
GatewayIntents::DIRECT_MESSAGES
| GatewayIntents::GUILD_MESSAGES
| GatewayIntents::DIRECT_MESSAGE_REACTIONS
| GatewayIntents::GUILD_MESSAGE_REACTIONS
| GatewayIntents::GUILDS,
)
// pass in the framework we made above
.framework(framework)
// pass in the app ID we got above (required for slash commands)
.application_id(u64::from(app_id))
// add event handlers
.event_handler(BotEventHandler::default())
.raw_event_handler(BotRawEventHandler::default())
// await the client to construct it
.await
// check the Result returned
.expect("failed to create the client");
{
// this needs to be put into a block, otherwise the lock will never be dropped and will
// deadlock any commands trying to use anything in the data map
let mut map = client.data.write().await;
// if the DB pool exists, insert it
if let Some(db) = db {
map.insert::<PgPoolKey>(db)
}
map.insert::<ShardManagerWrapper>(client.shard_manager.clone());
}
// make a ctrl+c handler to cleanly shut down the bot
let shard_manager = client.shard_manager.clone();
tokio::spawn(async move {
// tokio provides this utility to wait for a ctrl+c
tokio::signal::ctrl_c().await.unwrap();
// we lock the shard manager and tell it to shut down all shards
shard_manager.lock().await.shutdown_all().await;
});
// start the client
client.start_autosharded().await?;
Ok(())
}
|
use tuber_math::matrix::Matrix4f;
use tuber_math::quaternion::Quaternion;
use tuber_math::vector::Vector3;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Transform {
pub translation: Vector3<f32>,
pub angle: Vector3<f32>,
pub rotation_center: Vector3<f32>,
pub scale: Vector3<f32>,
}
impl Default for Transform {
fn default() -> Self {
Self {
translation: (0.0, 0.0, 0.0).into(),
angle: (0.0, 0.0, 0.0).into(),
rotation_center: (0.0, 0.0, 0.0).into(),
scale: (1.0, 1.0, 1.0).into(),
}
}
}
pub trait AsMatrix4 {
fn as_matrix4(&self) -> Matrix4f;
}
impl AsMatrix4 for Transform {
fn as_matrix4(&self) -> Matrix4f {
let translate_to_rotation_center = self.rotation_center;
Matrix4f::new_scale(&self.scale)
* Matrix4f::new_translation(&self.translation)
* Matrix4f::new_translation(&translate_to_rotation_center.clone())
* Quaternion::from_euler(&self.angle).rotation_matrix()
* Matrix4f::new_translation(&-translate_to_rotation_center)
}
}
|
//! A collection of serialization and deserialization functions
//! that use the `serde` crate for the serializable and deserializable
//! implementation.
use std::io::{self, Write, Read};
use std::{error, fmt, result};
use std::str::Utf8Error;
use {CountSize, SizeLimit};
use byteorder::ByteOrder;
use std::error::Error as StdError;
pub use super::de::Deserializer;
pub use super::ser::Serializer;
use super::ser::SizeChecker;
use serde_crate as serde;
/// The result of a serialization or deserialization operation.
pub type Result<T> = result::Result<T, Error>;
/// An error that can be produced during (de)serializing.
pub type Error = Box<ErrorKind>;
/// The kind of error that can be produced during a serialization or deserialization.
#[derive(Debug)]
pub enum ErrorKind {
/// If the error stems from the reader/writer that is being used
/// during (de)serialization, that error will be stored and returned here.
Io(io::Error),
/// Returned if the deserializer attempts to deserialize a string that is not valid utf8
InvalidUtf8Encoding(Utf8Error),
/// Returned if the deserializer attempts to deserialize a bool that was
/// not encoded as either a 1 or a 0
InvalidBoolEncoding(u8),
/// Returned if the deserializer attempts to deserialize a char that is not in the correct format.
InvalidCharEncoding,
/// Returned if the deserializer attempts to deserialize the tag of an enum that is
/// not in the expected ranges
InvalidTagEncoding(usize),
/// Serde has a deserialize_any method that lets the format hint to the
/// object which route to take in deserializing.
DeserializeAnyNotSupported,
/// If (de)serializing a message takes more than the provided size limit, this
/// error is returned.
SizeLimit,
/// Bincode can not encode sequences of unknown length (like iterators).
SequenceMustHaveLength,
/// A custom error message from Serde.
Custom(String),
}
impl StdError for ErrorKind {
fn description(&self) -> &str {
match *self {
ErrorKind::Io(ref err) => error::Error::description(err),
ErrorKind::InvalidUtf8Encoding(_) => "string is not valid utf8",
ErrorKind::InvalidBoolEncoding(_) => "invalid u8 while decoding bool",
ErrorKind::InvalidCharEncoding => "char is not valid",
ErrorKind::InvalidTagEncoding(_) => "tag for enum is not valid",
ErrorKind::SequenceMustHaveLength => "bincode can't encode infinite sequences",
ErrorKind::DeserializeAnyNotSupported => {
"bincode doesn't support serde::Deserializer::deserialize_any"
}
ErrorKind::SizeLimit => "the size limit for decoding has been reached",
ErrorKind::Custom(ref msg) => msg,
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
ErrorKind::Io(ref err) => Some(err),
ErrorKind::InvalidUtf8Encoding(_) => None,
ErrorKind::InvalidBoolEncoding(_) => None,
ErrorKind::InvalidCharEncoding => None,
ErrorKind::InvalidTagEncoding(_) => None,
ErrorKind::SequenceMustHaveLength => None,
ErrorKind::DeserializeAnyNotSupported => None,
ErrorKind::SizeLimit => None,
ErrorKind::Custom(_) => None,
}
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
ErrorKind::Io(err).into()
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
ErrorKind::Io(ref ioerr) => write!(fmt, "io error: {}", ioerr),
ErrorKind::InvalidUtf8Encoding(ref e) => write!(fmt, "{}: {}", self.description(), e),
ErrorKind::InvalidBoolEncoding(b) => {
write!(fmt, "{}, expected 0 or 1, found {}", self.description(), b)
}
ErrorKind::InvalidCharEncoding => write!(fmt, "{}", self.description()),
ErrorKind::InvalidTagEncoding(tag) => {
write!(fmt, "{}, found {}", self.description(), tag)
}
ErrorKind::SequenceMustHaveLength => {
write!(
fmt,
"bincode can only encode sequences and maps that have a knowable size ahead of time."
)
}
ErrorKind::SizeLimit => write!(fmt, "{}", self.description()),
ErrorKind::DeserializeAnyNotSupported => {
write!(
fmt,
"bincode does not support the serde::Deserializer::deserialize_any method"
)
}
ErrorKind::Custom(ref s) => s.fmt(fmt),
}
}
}
impl serde::de::Error for Error {
fn custom<T: fmt::Display>(desc: T) -> Error {
ErrorKind::Custom(desc.to_string()).into()
}
}
impl serde::ser::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Self {
ErrorKind::Custom(msg.to_string()).into()
}
}
/// Serializes an object directly into a `Writer`.
///
/// If the serialization would take more bytes than allowed by `size_limit`, an error
/// is returned and *no bytes* will be written into the `Writer`.
///
/// If this returns an `Error` (other than SizeLimit), assume that the
/// writer is in an invalid state, as writing could bail out in the middle of
/// serializing.
pub fn serialize_into<W, T: ?Sized, S, E>(writer: W, value: &T, size_limit: S) -> Result<()>
where
W: Write,
T: serde::Serialize,
S: SizeLimit,
E: ByteOrder,
{
if let Some(limit) = size_limit.limit() {
try!(serialized_size_bounded(value, limit).ok_or(
ErrorKind::SizeLimit,
));
}
let mut serializer = Serializer::<_, E>::new(writer);
serde::Serialize::serialize(value, &mut serializer)
}
/// Serializes a serializable object into a `Vec` of bytes.
///
/// If the serialization would take more bytes than allowed by `size_limit`,
/// an error is returned.
pub fn serialize<T: ?Sized, S, E>(value: &T, size_limit: S) -> Result<Vec<u8>>
where
T: serde::Serialize,
S: SizeLimit,
E: ByteOrder,
{
let mut writer = match size_limit.limit() {
Some(size_limit) => {
let actual_size = try!(serialized_size_bounded(value, size_limit).ok_or(
ErrorKind::SizeLimit,
));
Vec::with_capacity(actual_size as usize)
}
None => {
let size = serialized_size(value) as usize;
Vec::with_capacity(size)
}
};
try!(serialize_into::<_, _, _, E>(
&mut writer,
value,
super::Infinite,
));
Ok(writer)
}
impl SizeLimit for CountSize {
fn add(&mut self, c: u64) -> Result<()> {
self.total += c;
if let Some(limit) = self.limit {
if self.total > limit {
return Err(Box::new(ErrorKind::SizeLimit));
}
}
Ok(())
}
fn limit(&self) -> Option<u64> {
unreachable!();
}
}
/// Returns the size that an object would be if serialized using bincode.
///
/// This is used internally as part of the check for encode_into, but it can
/// be useful for preallocating buffers if thats your style.
pub fn serialized_size<T: ?Sized>(value: &T) -> u64
where
T: serde::Serialize,
{
let mut size_counter = SizeChecker {
size_limit: CountSize {
total: 0,
limit: None,
},
};
value.serialize(&mut size_counter).ok();
size_counter.size_limit.total
}
/// Given a maximum size limit, check how large an object would be if it
/// were to be serialized.
///
/// If it can be serialized in `max` or fewer bytes, that number will be returned
/// inside `Some`. If it goes over bounds, then None is returned.
pub fn serialized_size_bounded<T: ?Sized>(value: &T, max: u64) -> Option<u64>
where
T: serde::Serialize,
{
let mut size_counter = SizeChecker {
size_limit: CountSize {
total: 0,
limit: Some(max),
},
};
match value.serialize(&mut size_counter) {
Ok(_) => Some(size_counter.size_limit.total),
Err(_) => None,
}
}
/// Deserializes an object directly from a `Read`er.
///
/// If the provided `SizeLimit` is reached, the deserialization will bail immediately.
/// A SizeLimit can help prevent an attacker from flooding your server with
/// a neverending stream of values that runs your server out of memory.
///
/// If this returns an `Error`, assume that the buffer that you passed
/// in is in an invalid state, as the error could be returned during any point
/// in the reading.
pub fn deserialize_from<R, T, S, E>(reader: R, size_limit: S) -> Result<T>
where
R: Read,
T: serde::de::DeserializeOwned,
S: SizeLimit,
E: ByteOrder,
{
let reader = ::de::read::IoReader::new(reader);
let mut deserializer = Deserializer::<_, S, E>::new(reader, size_limit);
serde::Deserialize::deserialize(&mut deserializer)
}
/// Deserializes a slice of bytes into an object.
///
/// This method does not have a size-limit because if you already have the bytes
/// in memory, then you don't gain anything by having a limiter.
pub fn deserialize<'a, T, E: ByteOrder>(bytes: &'a [u8]) -> Result<T>
where
T: serde::de::Deserialize<'a>,
{
let reader = ::de::read::SliceReader::new(bytes);
let mut deserializer = Deserializer::<_, _, E>::new(reader, super::Infinite);
serde::Deserialize::deserialize(&mut deserializer)
}
|
// 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.
#![feature(catch_expr)]
pub fn main() {
let res: Result<u32, i32> = do catch {
Err("")?; //~ ERROR the trait bound `i32: std::convert::From<&str>` is not satisfied
5
};
let res: Result<i32, i32> = do catch {
"" //~ ERROR type mismatch
};
let res: Result<i32, i32> = do catch { }; //~ ERROR type mismatch
let res: () = do catch { }; //~ the trait bound `(): std::ops::Try` is not satisfied
let res: i32 = do catch { 5 }; //~ ERROR the trait bound `i32: std::ops::Try` is not satisfied
}
|
pub mod config {
use std::env::{var, VarError};
#[derive(Debug)]
pub struct DbCfg {
pub host: String,
pub user: String,
pub pw: String,
pub port: String,
pub name: String,
}
#[derive(Debug)]
pub struct ApiCfg {
pub port: String,
pub ip: String,
}
pub fn get_db_cfg() -> Result<DbCfg, VarError> {
Ok(DbCfg {
host: var("WGMAN_DB_HOST")?,
user: var("WGMAN_DB_USER")?,
pw: var("WGMAN_DB_PW")?,
port: var("WGMAN_DB_PORT")?,
name: var("WGMAN_DB_NAME")?,
})
}
pub fn get_api_cfg() -> Result<ApiCfg, VarError> {
Ok(ApiCfg {
port: var("WGMAN_API_PORT")?,
ip: var("WGMAN_API_IP")?,
})
}
}
pub mod types {
use std::{convert::TryFrom, error::Error, str::FromStr};
use ring::error::Unspecified;
use serde::{ Deserialize, Serialize };
use ipnetwork::IpNetwork;
use base64::{encode, decode};
use std::fmt;
use crate::auth::encrypt;
#[derive(PartialEq, Eq, Debug, Clone, sqlx::FromRow)]
pub struct Admin {
pub u_name: String,
pub is_root: bool,
}
impl TryFrom<ApiAdmin> for Admin {
type Error = ring::error::Unspecified;
fn try_from(ApiAdmin{ u_name, is_root }: ApiAdmin) -> Result<Self, Self::Error> {
match u_name {
s if s.contains(":") => Err(Unspecified),
_ => Ok(Admin {
u_name,
is_root,
})
}
}
}
#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
pub struct ApiAdmin {
pub u_name: String,
pub is_root: bool,
}
impl From<Admin> for ApiAdmin {
fn from(Admin { u_name, is_root, .. }: Admin) -> Self {
ApiAdmin { u_name, is_root }
}
}
#[derive(PartialEq, Eq, Debug, Clone, sqlx::FromRow)]
pub struct AdminPassword {
pub u_name: String,
pub password_hash: Vec<u8>,
pub salt: Vec<u8>,
}
#[derive(PartialEq, Eq, Debug, Clone, sqlx::FromRow)]
pub struct Interface {
pub u_name: String,
pub public_key: Option<String>,
pub port: Option<i32>,
pub ip: Option<IpNetwork>,
pub fqdn: Option<String>,
}
impl TryFrom<ApiInterface> for Interface {
type Error = ring::error::Unspecified;
fn try_from(ApiInterface { u_name, public_key, port, ip, fqdn }: ApiInterface) -> Result<Self, Self::Error> {
match (&u_name, &public_key) {
(s, _) if s.contains(":") => Err(Unspecified),
(_, Some(pk)) if pk.len() != 44 => Err(Unspecified),
_ => Ok(Interface {
u_name,
public_key,
port,
ip,
fqdn,
})
}
}
}
#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
pub struct ApiInterface {
pub u_name: String,
pub public_key: Option<String>,
pub port: Option<i32>,
pub ip: Option<IpNetwork>,
pub fqdn: Option<String>,
}
impl ApiInterface {
pub fn coallesce(&mut self, other: Self) {
match other.public_key {
Some(v) => self.public_key = Some(v),
None => {}
};
match other.port {
Some(v) => self.port = Some(v),
None => {}
};
match other.ip {
Some(v) => self.ip = Some(v),
None => {}
};
match other.fqdn {
Some(v) => self.fqdn = Some(v),
None => {}
};
}
}
impl From<Interface> for ApiInterface {
fn from(Interface { u_name, public_key, port, ip, fqdn, .. }: Interface) -> Self {
ApiInterface {u_name, public_key, port, ip, fqdn,}
}
}
#[derive(PartialEq, Eq, Debug, Clone, sqlx::FromRow)]
pub struct InterfacePassword {
pub u_name: String,
pub password_hash: Vec<u8>,
pub salt: Vec<u8>,
}
#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
pub struct ApiInterfacePassword {
pub u_name: String,
pub password: String,
}
impl TryFrom<ApiInterfacePassword> for InterfacePassword {
type Error = ring::error::Unspecified;
fn try_from(ApiInterfacePassword { u_name, password }: ApiInterfacePassword) -> Result<Self, Self::Error> {
let hash = encrypt(&password)?;
Ok(InterfacePassword {
u_name,
password_hash: hash.pbkdf2_hash.into(),
salt: hash.salt.into(),
})
}
}
#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
pub struct ApiAdminPassword {
pub u_name: String,
pub password: String,
}
impl TryFrom<ApiAdminPassword> for AdminPassword {
type Error = ring::error::Unspecified;
fn try_from(ApiAdminPassword { u_name, password }: ApiAdminPassword) -> Result<Self, Self::Error> {
let hash = encrypt(&password)?;
Ok(AdminPassword {
u_name,
password_hash: hash.pbkdf2_hash.into(),
salt: hash.salt.into(),
})
}
}
#[derive(PartialEq, Eq, Debug, Clone, sqlx::FromRow)]
pub struct PeerRelation {
pub peer_name: String,
pub endpoint_name: String,
pub peer_public_key: Option<String>,
pub endpoint_public_key: Option<String>,
pub endpoint_allowed_ip: Option<Vec<IpNetwork>>,
pub peer_allowed_ip: Option<Vec<IpNetwork>>,
}
impl TryFrom<ApiPeerRelation> for PeerRelation {
type Error = ring::error::Unspecified;
fn try_from(ApiPeerRelation { peer_public_key, endpoint_public_key, endpoint_allowed_ip, peer_allowed_ip, peer_name, endpoint_name, .. }: ApiPeerRelation) -> Result<Self, Self::Error> {
match (&peer_public_key, &endpoint_public_key, &peer_name, &endpoint_name) {
(Some(ppk), _, _, _) if ppk.len() != 44 => Err(Unspecified),
(_, Some(epk), _, _) if epk.len() != 44 => Err(Unspecified),
(_, _, None, _) => Err(Unspecified),
(_, _, _, None) => Err(Unspecified),
(_, _, Some(pn), _) if pn.contains(":") => Err(Unspecified),
(_, _, _, Some(en)) if en.contains(":") => Err(Unspecified),
_ => Ok(PeerRelation { peer_public_key, endpoint_public_key, endpoint_allowed_ip, peer_allowed_ip, peer_name: peer_name.unwrap(), endpoint_name: endpoint_name.unwrap() })
}
}
}
#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize, sqlx::FromRow)]
pub struct InterfacePeerRelation {
pub endpoint_public_key: Option<String>,
pub peer_public_key: Option<String>,
pub endpoint_allowed_ip: Option<Vec<IpNetwork>>,
pub peer_allowed_ip: Option<Vec<IpNetwork>>,
pub port: Option<i32>,
pub ip: Option<IpNetwork>,
pub fqdn: Option<String>,
}
#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
pub struct ApiPeerRelation {
pub peer_name: Option<String>,
pub endpoint_name: Option<String>,
pub endpoint_public_key: Option<String>,
pub peer_public_key: Option<String>,
pub endpoint_allowed_ip: Option<Vec<IpNetwork>>,
pub peer_allowed_ip: Option<Vec<IpNetwork>>,
pub endpoint: Option<String>
}
impl From<InterfacePeerRelation> for ApiPeerRelation {
fn from(pr_interface: InterfacePeerRelation) -> Self {
let InterfacePeerRelation { peer_public_key, endpoint_public_key, endpoint_allowed_ip, peer_allowed_ip, fqdn, ip, port } = pr_interface;
let mut endpoint = None;
if fqdn.is_some() {
endpoint = Some(fqdn.unwrap_or(String::new()));
}
else if ip.is_some() && port.is_some() {
endpoint = Some(format!("{}:{}", ip.unwrap().to_string(), port.unwrap()));
}
ApiPeerRelation { peer_public_key, endpoint_public_key, endpoint_allowed_ip, peer_allowed_ip, endpoint, peer_name: None, endpoint_name: None }
}
}
impl ApiPeerRelation {
pub fn coallesce(&mut self, other: Self) {
match other.endpoint_allowed_ip {
Some(allowed_ip) => self.endpoint_allowed_ip = Some(allowed_ip),
None => {}
};
match other.peer_allowed_ip {
Some(allowed_ip) => self.peer_allowed_ip = Some(allowed_ip),
None => {}
};
}
}
#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
pub struct InterfaceConfigPeer {
pub public_key: String,
pub allowed_ip: Vec<IpNetwork>,
pub endpoint: Option<String>
}
#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
pub struct InterfaceConfig {
pub interface: ApiInterface,
pub peers: Vec<InterfaceConfigPeer>
}
#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
pub struct ApiConfig {
pub interface: ApiInterface,
pub peers: Vec<ApiPeerRelation>
}
impl From<InterfaceConfig> for ApiConfig {
fn from(InterfaceConfig { interface, peers } : InterfaceConfig) -> Self {
Self {
interface: interface.clone(),
peers: peers.iter().map(|p| match &p.endpoint {
Some(_) => ApiPeerRelation {
endpoint_public_key: Some(p.public_key.clone()),
peer_public_key: interface.public_key.clone(),
endpoint_allowed_ip: None,
peer_allowed_ip: Some(p.allowed_ip.clone()),
endpoint: p.endpoint.clone(),
peer_name: Some(interface.u_name.clone()),
endpoint_name: None,
},
None => ApiPeerRelation {
endpoint_public_key: interface.public_key.clone(),
peer_public_key: Some(p.public_key.clone()),
endpoint_allowed_ip: Some(p.allowed_ip.clone()),
peer_allowed_ip: None,
endpoint: None,
peer_name: None,
endpoint_name: Some(interface.u_name.clone()),
}
})
.collect(),
}
}
}
pub enum InterfaceConfigBlockKind {
Interface,
Peer
}
#[derive(PartialEq, Eq, Debug, Default, Clone)]
pub struct BasicAuth {
pub name: String,
pub password: String
}
// Warning:: only intended to be used with base64 authorization header
impl FromStr for BasicAuth {
type Err = Box<dyn Error>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match &s[..5] {
"Basic" => {
let decoded = decode(&s[6..])?;
let auth_string = std::str::from_utf8(&decoded[..])?;
let colon_indx = match auth_string.find(":") {
Some(indx) => {
if indx < auth_string.len() - 1 {
indx
}
else {
Err("Invalid Login")?
}
},
None => {Err("Invalid Login")?}
};
Ok(BasicAuth { name: auth_string[..colon_indx].into(), password: auth_string[colon_indx + 1..].into() })
}
_ => Err("Invalid Login")?
}
}
}
// Warning:: only intended to be used with base64 authorization header
impl fmt::Display for BasicAuth {
// This trait requires `fmt` with this exact signature.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Write strictly the first element into the supplied output
// stream: `f`. Returns `fmt::Result` which indicates whether the
// operation succeeded or failed. Note that `write!` uses syntax which
// is very similar to `println!`.
let encoded_auth = encode(format!("{}:{}", self.name, self.password));
write!(f, "Basic {}", encoded_auth)
}
}
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum AuthKind {
Admin,
Interface,
}
impl Default for AuthKind {
fn default() -> Self {
AuthKind::Admin
}
}
/// An API error serializable to JSON.
#[derive(PartialEq, Eq, Serialize, Deserialize, Debug)]
pub struct ErrorMessage {
pub code: u16,
pub message: String,
}
}
pub mod auth {
use ring::error::Unspecified;
use ring::rand::SecureRandom;
use ring::{digest, pbkdf2, rand};
use std::num::NonZeroU32;
pub struct Hash {
pub pbkdf2_hash: [u8; digest::SHA512_OUTPUT_LEN],
pub salt: [u8; digest::SHA512_OUTPUT_LEN],
}
pub fn encrypt(password: &str) -> Result<Hash, Unspecified> {
const CREDENTIAL_LEN: usize = digest::SHA512_OUTPUT_LEN;
let n_iter = NonZeroU32::new(100_000).unwrap();
let rng = rand::SystemRandom::new();
let mut salt = [0u8; CREDENTIAL_LEN];
rng.fill(&mut salt)?;
let mut pbkdf2_hash = [0u8; CREDENTIAL_LEN];
pbkdf2::derive(
pbkdf2::PBKDF2_HMAC_SHA512,
n_iter,
&salt,
password.as_bytes(),
&mut pbkdf2_hash,
);
Ok(Hash { salt, pbkdf2_hash })
}
pub fn verify(Hash { salt, pbkdf2_hash }: &Hash, password: &str) -> Result<(), Unspecified> {
let n_iter = NonZeroU32::new(100_000).unwrap();
pbkdf2::verify(
pbkdf2::PBKDF2_HMAC_SHA512,
n_iter,
salt,
password.as_bytes(),
pbkdf2_hash,
)
}
}
// TODO add unit tests validation functions
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_inverse_auth() {
// assert_eq!(add(1, 2), 3);
let h1: auth::Hash = auth::encrypt("test").unwrap();
auth::verify(&h1, "test").unwrap();
}
}
|
use error::BannerError;
use flag::{Flag, FlagPath};
use store::ThreadedStore;
use user::User;
pub type FlagStore = ThreadedStore<FlagPath, Flag, Error = BannerError>;
pub type PathStore = ThreadedStore<String, FlagPath, Error = BannerError>;
pub type UserStore = ThreadedStore<String, User, Error = BannerError>;
pub struct AppState {
flag_store: Box<FlagStore>,
path_store: Box<PathStore>,
user_store: Box<UserStore>,
}
impl AppState {
pub fn new<F, P, U>(flag_store: F, path_store: P, user_store: U) -> AppState
where
F: ThreadedStore<FlagPath, Flag, Error = BannerError> + 'static,
P: ThreadedStore<String, FlagPath, Error = BannerError> + 'static,
U: ThreadedStore<String, User, Error = BannerError> + 'static,
{
AppState {
flag_store: Box::new(flag_store),
path_store: Box::new(path_store),
user_store: Box::new(user_store),
}
}
pub fn flags(&self) -> &Box<ThreadedStore<FlagPath, Flag, Error = BannerError>> {
&self.flag_store
}
pub fn paths(&self) -> &Box<ThreadedStore<String, FlagPath, Error = BannerError>> {
&self.path_store
}
pub fn users(&self) -> &Box<ThreadedStore<String, User, Error = BannerError>> {
&self.user_store
}
}
|
mod tunmgr;
pub use tunmgr::*;
mod tunnel;
pub use tunnel::*;
mod theader;
pub use theader::*;
mod tunbuilder;
pub use tunbuilder::*;
mod reqserv;
pub use reqserv::*;
mod reqq;
pub use reqq::*;
mod tunstub;
pub use tunstub::*;
mod request;
pub use request::*;
|
#![feature(exit_status)]
extern crate lines;
extern crate lisp;
use std::env;
use std::io::{StdoutLock, Write, self};
use lines::Lines;
use lisp::diagnostics;
use lisp::syntax::ast::Expr;
use lisp::syntax::codemap::Source;
use lisp::syntax::pp;
use lisp::syntax::{Error, parse};
use lisp::util::interner::Interner;
fn read(source: &Source, interner: &mut Interner) -> Result<Expr, Error> {
parse::expr(source, interner)
}
fn eval(input: Expr) -> Expr {
input
}
fn print(output: &Expr, source: &Source, stdout: &mut StdoutLock) -> io::Result<()> {
let mut string = pp::expr(output, source);
string.push('\n');
stdout.write_all(string.as_bytes())
}
fn rep(stdout: &mut StdoutLock) -> io::Result<()> {
const PROMPT: &'static str = "> ";
let stdin = io::stdin();
let mut lines = Lines::from(stdin.lock());
let ref mut interner = Interner::new();
try!(stdout.write_all(PROMPT.as_bytes()));
try!(stdout.flush());
while let Some(line) = lines.next() {
let source = Source::new(try!(line));
if !source.as_str().trim().is_empty() {
match read(source, interner) {
Err(error) => {
try!(stdout.write_all(diagnostics::syntax(error, source).as_bytes()))
},
Ok(expr) => try!(print(&eval(expr), source, stdout)),
}
}
try!(stdout.write_all(PROMPT.as_bytes()));
try!(stdout.flush());
}
Ok(())
}
fn main() {
let stdout = io::stdout();
let mut stdout = stdout.lock();
if let Err(e) = rep(&mut stdout) {
env::set_exit_status(1);
stdout.write_fmt(format_args!("{}", e)).ok();
}
}
|
extern crate clap;
extern crate toml;
extern crate rustc_serialize;
mod config;
use std::io::prelude::*;
use std::fs::File;
use std::process;
use std::process::Command;
use toml::{Parser, Value};
use clap::{Arg, App, SubCommand};
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const APP_NAME: &'static str = "K2-SO -- Deployment Droid 🤖✨";
fn read_server_file() -> config::Config {
let mut config_toml = String::new();
let path = "servers.toml";
let mut file = match File::open(&path) {
Ok(file) => file,
Err(_) => {
return config::Config::new();
}
};
file.read_to_string(&mut config_toml)
.unwrap_or_else(|err| panic!("Error while reading config: [{}]", err));
let mut parser = Parser::new(&config_toml);
let toml = parser.parse();
if toml.is_none() {
for err in &parser.errors {
let (loline, locol) = parser.to_linecol(err.lo);
let (hiline, hicol) = parser.to_linecol(err.hi);
println!("{}:{}:{}-{}:{} error: {}",
path, loline, locol, hiline, hicol, err.desc);
}
panic!("Exiting server");
}
let config = Value::Table(toml.unwrap());
match toml::decode(config) {
Some(t) => t,
None => panic!("Error while deserializing config")
}
}
fn save_configuration(config: config::Config) {
let toml_string = toml::encode_str(&config);
let mut file = std::fs::File::create("servers.toml").unwrap();
file.write_all(toml_string.as_bytes()).expect("Could not write to file!");
}
fn add_to_file(role: String, address: String) {
let mut config = read_server_file();
if config.is_role_unique(&role) {
config.add_role(role, address);
save_configuration(config);
} else {
println!("Role {} is already configured", role);
process::exit(1)
}
}
fn deploy(role_name: String) {
let config = read_server_file();
if let Err(errors) = config.is_valid() {
println!("Configuration is not valid");
for error in errors {
println!("{}", error);
}
process::exit(1)
}
match config.address_for_role_name(&role_name) {
Some(address) => {
println!("Deploying {} - {}", role_name, address);
let output = Command::new("knife")
.arg("solo")
.arg("bootstrap")
.arg(format!("{}@{}", config.username, address))
.arg("-i")
.arg(config.ssh_key_path)
.arg("--no-host-key-verify")
.arg("--node-name")
.arg(role_name)
.output()
.expect("failed to execute process");
let stdout = String::from_utf8(output.stdout).unwrap();
let stderr = String::from_utf8(output.stderr).unwrap();
if output.status.success() {
println!("{}", stdout);
} else {
println!("{}", stderr);
process::exit(1)
}
},
None => {
println!("No address found for role {}", role_name);
process::exit(1)
}
}
}
fn add_username(username: String) {
let mut config = read_server_file();
config.add_username(username);
save_configuration(config);
}
fn add_ssh_key(path: String) {
let mut config = read_server_file();
config.add_ssh_key(path);
save_configuration(config);
}
fn main() {
let matches = App::new(APP_NAME)
.version(VERSION)
.author("Jan Schulte <jan@unexpected-co.de>")
.about("Deploys your tool -- The captain said I have to")
.arg(Arg::with_name("list")
.short("l")
.long("list")
.help("Lists all values from the server file")
.takes_value(false))
.subcommand(SubCommand::with_name("add")
.about("Add a new role")
.arg(Arg::with_name("address")
.index(1)
.required(true)
.requires("role")
.help("Define an address"))
.arg(Arg::with_name("role")
.index(2)
.help("Define a role")))
.subcommand(SubCommand::with_name("deploy")
.about("Start deployment for a certain role")
.arg(Arg::with_name("role")
.index(1)
.required(true)
.help("The machine which should be deployed")))
.subcommand(SubCommand::with_name("add_user")
.about("Configure username")
.arg(Arg::with_name("username")
.index(1)
.required(true)
.help("Configures the machine's username")))
.subcommand(SubCommand::with_name("add_key")
.about("Configure ssh key")
.arg(Arg::with_name("key")
.index(1)
.required(true)
.help("Configures path to ssh key")))
.get_matches();
if let Some(ref matches) = matches.subcommand_matches("add") {
let role = matches.value_of("role").unwrap();
let address = matches.value_of("address").unwrap();
add_to_file(role.to_string(), address.to_string());
}
else if matches.occurrences_of("list") > 0 {
let config = read_server_file();
println!("Reading servers.toml...");
match config.is_valid() {
Ok(()) => {
println!("Username: {}", config.username);
println!("SSH Key path: {}", config.ssh_key_path);
for rule in config.roles {
println!("🖥 {} - {}", rule.name, rule.address);
}
},
Err(errors) => {
println!("Configuration is not valid!");
for error in errors {
println!("{}", error);
}
process::exit(1)
}
}
}
else if let Some(ref matches) = matches.subcommand_matches("add_user") {
let username = matches.value_of("username").unwrap();
println!("Configuring {}", username);
add_username(username.to_string());
}
else if let Some(ref matches) = matches.subcommand_matches("add_key") {
let key = matches.value_of("key").unwrap();
println!("Configuring SSH Key {}", key);
add_ssh_key(key.to_string());
}
else if let Some(ref matches) = matches.subcommand_matches("deploy") {
let role = matches.value_of("role").unwrap();
deploy(role.to_string());
}
}
|
use chrono::{NaiveDate, NaiveDateTime};
use polars::prelude::{DataFrame, NamedFrom};
use polars::series::Series;
use ukis_clickhouse_arrow_grpc::{ArrowInterface, Client, QueryInfo};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// install global collector configured based on RUST_LOG env var.
tracing_subscriber::fmt::init();
let mut client = Client::connect("http://127.0.0.1:9100").await?;
// query
let df = client
.execute_into_dataframe(QueryInfo {
query: r#"
select 'string-äöü-utf8?' s1,
cast(name as Text),
cast(1 as UInt64) as jkj,
cast(now() as DateTime) as ts_datetime,
toDateTime(now(), 'Asia/Istanbul') AS ts_datetime_tz,
cast(now() as Date) as ts_date,
cast(now() as DateTime64) as ts64,
cast(1 as UInt8) as some_u8
from tables"#
.to_string(),
database: "system".to_string(),
..Default::default()
})
.await?;
dbg!(df);
let play_db = "play";
client
.execute_query_checked(QueryInfo {
query: format!("create database if not exists {}", play_db),
..Default::default()
})
.await?;
client
.execute_query_checked(QueryInfo {
query: "drop table if exists test_insert".to_string(),
database: play_db.to_string(),
..Default::default()
})
.await?;
client
.execute_query_checked(QueryInfo {
query: r#"create table if not exists test_insert (
v1 UInt64,
v2 Float32,
t1 text,
c_datetime64 DateTime64,
c_datetime DateTime,
c_date Date,
b bool
) ENGINE Memory"#
.to_string(),
database: play_db.to_string(),
..Default::default()
})
.await?;
let test_df = make_dataframe(40)?;
client
.insert_dataframe(play_db, "test_insert", test_df)
.await?;
let df2 = client
.execute_into_dataframe(QueryInfo {
query: "select *, version() as clickhouse_version from test_insert".to_string(),
database: play_db.to_string(),
..Default::default()
})
.await?;
dbg!(df2);
Ok(())
}
fn make_dataframe(df_len: usize) -> anyhow::Result<DataFrame> {
let test_df = DataFrame::new(vec![
Series::new("v1", (0..df_len).map(|v| v as u64).collect::<Vec<_>>()),
Series::new(
"v2",
(0..df_len).map(|v| v as f32 * 1.3).collect::<Vec<_>>(),
),
Series::new(
"t1",
(0..df_len)
.map(|v| format!("something-{}", v))
.collect::<Vec<_>>(),
),
Series::new(
"c_datetime64",
(0..df_len)
.map(|v| {
NaiveDateTime::from_timestamp_opt((v as i64).pow(2), 0)
.expect("invalid timestamp")
})
.collect::<Vec<_>>(),
),
Series::new(
"c_date",
(0..df_len)
.map(|_| NaiveDate::from_ymd_opt(2000, 5, 23).expect("invalid date"))
.collect::<Vec<_>>(),
),
Series::new(
"c_datetime",
(0..df_len)
.map(|_| {
NaiveDate::from_ymd_opt(2000, 5, 23)
.expect("invalid date")
.and_hms_opt(12, 13, 14)
.expect("invalid datetime")
})
.collect::<Vec<_>>(),
),
Series::new("b", (0..df_len).map(|v| v % 2 == 0).collect::<Vec<_>>()),
])?;
Ok(test_df)
}
|
// TODO: support for other types (e.g. integers)
use super::secure_zero_memory;
#[cfg(feature = "std")]
use std::prelude::v1::*;
/// Trait for securely erasing types from memory
pub trait Zeroize {
/// Zero out this object from memory (using Rust or OS intrinsics which
/// ensure the zeroization operation is not "optimized away")
fn zeroize(&mut self);
}
/// Byte slices are the core type we can zeroize
impl<'a> Zeroize for &'a mut [u8] {
fn zeroize(&mut self) {
secure_zero_memory(self);
}
}
/// Zeroize `Vec<u8>`s by zeroizing their memory and then truncating them,
/// for consistency with the `String` behavior below, and also as an indication
/// the underlying memory has been wiped.
// TODO: other vector types? Generic vector impl?
#[cfg(feature = "std")]
impl Zeroize for Vec<u8> {
fn zeroize(&mut self) {
self.as_mut_slice().zeroize();
self.clear();
}
}
/// Zeroize `String`s by zeroizing their backing memory then truncating them,
/// to zero length (ensuring valid UTF-8, since they're empty)
#[cfg(feature = "std")]
impl Zeroize for String {
fn zeroize(&mut self) {
unsafe {
self.as_bytes_mut().zeroize();
}
self.clear();
}
}
macro_rules! impl_zeroize_for_as_mut {
($as_mut:ty) => {
impl Zeroize for $as_mut {
fn zeroize(&mut self) {
self.as_mut().zeroize();
}
}
};
}
impl_zeroize_for_as_mut!([u8; 1]);
impl_zeroize_for_as_mut!([u8; 2]);
impl_zeroize_for_as_mut!([u8; 3]);
impl_zeroize_for_as_mut!([u8; 4]);
impl_zeroize_for_as_mut!([u8; 5]);
impl_zeroize_for_as_mut!([u8; 6]);
impl_zeroize_for_as_mut!([u8; 7]);
impl_zeroize_for_as_mut!([u8; 8]);
impl_zeroize_for_as_mut!([u8; 9]);
impl_zeroize_for_as_mut!([u8; 10]);
impl_zeroize_for_as_mut!([u8; 11]);
impl_zeroize_for_as_mut!([u8; 12]);
impl_zeroize_for_as_mut!([u8; 13]);
impl_zeroize_for_as_mut!([u8; 14]);
impl_zeroize_for_as_mut!([u8; 15]);
impl_zeroize_for_as_mut!([u8; 16]);
impl_zeroize_for_as_mut!([u8; 17]);
impl_zeroize_for_as_mut!([u8; 18]);
impl_zeroize_for_as_mut!([u8; 19]);
impl_zeroize_for_as_mut!([u8; 20]);
impl_zeroize_for_as_mut!([u8; 21]);
impl_zeroize_for_as_mut!([u8; 22]);
impl_zeroize_for_as_mut!([u8; 23]);
impl_zeroize_for_as_mut!([u8; 24]);
impl_zeroize_for_as_mut!([u8; 25]);
impl_zeroize_for_as_mut!([u8; 26]);
impl_zeroize_for_as_mut!([u8; 27]);
impl_zeroize_for_as_mut!([u8; 28]);
impl_zeroize_for_as_mut!([u8; 29]);
impl_zeroize_for_as_mut!([u8; 30]);
impl_zeroize_for_as_mut!([u8; 31]);
impl_zeroize_for_as_mut!([u8; 32]);
impl_zeroize_for_as_mut!([u8; 33]);
impl_zeroize_for_as_mut!([u8; 34]);
impl_zeroize_for_as_mut!([u8; 35]);
impl_zeroize_for_as_mut!([u8; 36]);
impl_zeroize_for_as_mut!([u8; 37]);
impl_zeroize_for_as_mut!([u8; 38]);
impl_zeroize_for_as_mut!([u8; 39]);
impl_zeroize_for_as_mut!([u8; 40]);
impl_zeroize_for_as_mut!([u8; 41]);
impl_zeroize_for_as_mut!([u8; 42]);
impl_zeroize_for_as_mut!([u8; 43]);
impl_zeroize_for_as_mut!([u8; 44]);
impl_zeroize_for_as_mut!([u8; 45]);
impl_zeroize_for_as_mut!([u8; 46]);
impl_zeroize_for_as_mut!([u8; 47]);
impl_zeroize_for_as_mut!([u8; 48]);
impl_zeroize_for_as_mut!([u8; 49]);
impl_zeroize_for_as_mut!([u8; 50]);
impl_zeroize_for_as_mut!([u8; 51]);
impl_zeroize_for_as_mut!([u8; 52]);
impl_zeroize_for_as_mut!([u8; 53]);
impl_zeroize_for_as_mut!([u8; 54]);
impl_zeroize_for_as_mut!([u8; 55]);
impl_zeroize_for_as_mut!([u8; 56]);
impl_zeroize_for_as_mut!([u8; 57]);
impl_zeroize_for_as_mut!([u8; 58]);
impl_zeroize_for_as_mut!([u8; 59]);
impl_zeroize_for_as_mut!([u8; 60]);
impl_zeroize_for_as_mut!([u8; 61]);
impl_zeroize_for_as_mut!([u8; 62]);
impl_zeroize_for_as_mut!([u8; 63]);
impl_zeroize_for_as_mut!([u8; 64]);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn zeroize_slice() {
let mut arr = [42; 3];
arr.zeroize();
assert_eq!(arr, [0, 0, 0]);
}
#[test]
fn zeroize_vec() {
let mut vec = vec![42; 3];
vec.zeroize();
assert!(vec.is_empty());
}
#[test]
fn zeroize_string() {
let mut string = String::from("Hello, world!");
string.zeroize();
assert!(string.is_empty());
}
#[test]
fn zeroize_box() {
let mut boxed_arr = Box::new([42; 3]);
boxed_arr.zeroize();
assert_eq!(boxed_arr.as_ref(), &[0u8; 3]);
}
}
|
use futures::{prelude::*, FutureExt};
use test_helpers_end_to_end::{
maybe_skip_integration, GrpcRequestBuilder, MiniCluster, Step, StepTest, StepTestState,
TestConfig, UdpCapture,
};
use trace_exporters::DEFAULT_JAEGER_TRACE_CONTEXT_HEADER_NAME;
#[tokio::test]
pub async fn test_tracing_sql() {
let database_url = maybe_skip_integration!();
let table_name = "the_table";
let udp_capture = UdpCapture::new().await;
let test_config = TestConfig::new_all_in_one(Some(database_url)).with_tracing(&udp_capture);
let mut cluster = MiniCluster::create_all_in_one(test_config).await;
StepTest::new(
&mut cluster,
vec![
Step::WriteLineProtocol(format!(
"{table_name},tag1=A,tag2=B val=42i 123456\n\
{table_name},tag1=A,tag2=C val=43i 123457"
)),
Step::Query {
sql: format!("select * from {table_name}"),
expected: vec![
"+------+------+--------------------------------+-----+",
"| tag1 | tag2 | time | val |",
"+------+------+--------------------------------+-----+",
"| A | B | 1970-01-01T00:00:00.000123456Z | 42 |",
"| A | C | 1970-01-01T00:00:00.000123457Z | 43 |",
"+------+------+--------------------------------+-----+",
],
},
],
)
.run()
.await;
// "shallow" packet inspection and verify the UDP server got omething that had some expected
// results (maybe we could eventually verify the payload here too)
udp_capture
.wait_for(|m| m.to_string().contains("RecordBatchesExec"))
.await;
// debugging assistance
// println!("Traces received (1):\n\n{:#?}", udp_capture.messages());
// wait for the UDP server to shutdown
udp_capture.stop().await;
}
#[tokio::test]
pub async fn test_tracing_storage_api() {
let database_url = maybe_skip_integration!();
let table_name = "the_table";
let udp_capture = UdpCapture::new().await;
let test_config = TestConfig::new_all_in_one(Some(database_url)).with_tracing(&udp_capture);
let mut cluster = MiniCluster::create_all_in_one(test_config).await;
StepTest::new(
&mut cluster,
vec![
Step::WriteLineProtocol(format!(
"{table_name},tag1=A,tag2=B val=42i 123456\n\
{table_name},tag1=A,tag2=C val=43i 123457"
)),
Step::Custom(Box::new(move |state: &mut StepTestState| {
let cluster = state.cluster();
let mut storage_client = cluster.querier_storage_client();
let read_filter_request = GrpcRequestBuilder::new()
.source(state.cluster())
.build_read_filter();
async move {
let read_response = storage_client
.read_filter(read_filter_request)
.await
.unwrap();
let _responses: Vec<_> =
read_response.into_inner().try_collect().await.unwrap();
}
.boxed()
})),
],
)
.run()
.await;
// "shallow" packet inspection and verify the UDP server got omething that had some expected
// results (maybe we could eventually verify the payload here too)
udp_capture
.wait_for(|m| m.to_string().contains("RecordBatchesExec"))
.await;
// debugging assistance
// println!("Traces received (1):\n\n{:#?}", udp_capture.messages());
// wait for the UDP server to shutdown
udp_capture.stop().await;
}
#[tokio::test]
pub async fn test_tracing_create_trace() {
let database_url = maybe_skip_integration!();
let table_name = "the_table";
let udp_capture = UdpCapture::new().await;
let test_config = TestConfig::new_all_in_one(Some(database_url))
.with_tracing(&udp_capture)
.with_tracing_debug_name("force-trace");
let mut cluster = MiniCluster::create_all_in_one(test_config).await;
StepTest::new(
&mut cluster,
vec![
Step::WriteLineProtocol(format!(
"{table_name},tag1=A,tag2=B val=42i 123456\n\
{table_name},tag1=A,tag2=C val=43i 123457"
)),
Step::Query {
sql: format!("select * from {table_name}"),
expected: vec![
"+------+------+--------------------------------+-----+",
"| tag1 | tag2 | time | val |",
"+------+------+--------------------------------+-----+",
"| A | B | 1970-01-01T00:00:00.000123456Z | 42 |",
"| A | C | 1970-01-01T00:00:00.000123457Z | 43 |",
"+------+------+--------------------------------+-----+",
],
},
],
)
.run()
.await;
// "shallow" packet inspection and verify the UDP server got omething that had some expected
// results (maybe we could eventually verify the payload here too)
udp_capture
.wait_for(|m| m.to_string().contains("RecordBatchesExec"))
.await;
// debugging assistance
// println!("Traces received (1):\n\n{:#?}", udp_capture.messages());
// wait for the UDP server to shutdown
udp_capture.stop().await;
}
#[tokio::test]
pub async fn test_tracing_create_ingester_query_trace() {
let database_url = maybe_skip_integration!();
let table_name = "the_table";
let udp_capture = UdpCapture::new().await;
let test_config = TestConfig::new_all_in_one(Some(database_url))
.with_tracing(&udp_capture)
// use the header attached with --gen-trace-id flag
.with_tracing_debug_name(DEFAULT_JAEGER_TRACE_CONTEXT_HEADER_NAME)
.with_ingester_never_persist();
let mut cluster = MiniCluster::create_all_in_one(test_config).await;
StepTest::new(
&mut cluster,
vec![
Step::WriteLineProtocol(format!(
"{table_name},tag1=A,tag2=B val=42i 123456\n\
{table_name},tag1=A,tag2=C val=43i 123457"
)),
Step::Query {
sql: format!("select * from {table_name}"),
expected: vec![
"+------+------+--------------------------------+-----+",
"| tag1 | tag2 | time | val |",
"+------+------+--------------------------------+-----+",
"| A | B | 1970-01-01T00:00:00.000123456Z | 42 |",
"| A | C | 1970-01-01T00:00:00.000123457Z | 43 |",
"+------+------+--------------------------------+-----+",
],
},
],
)
.run()
.await;
// "shallow" packet inspection and verify the UDP server got omething that had some expected
// results (maybe we could eventually verify the payload here too)
udp_capture
.wait_for(|m| m.to_string().contains("frame encoding"))
.await;
// debugging assistance
// println!("Traces received (1):\n\n{:#?}", udp_capture.messages());
// wait for the UDP server to shutdown
udp_capture.stop().await;
}
#[tokio::test]
async fn test_tracing_create_compactor_trace() {
test_helpers::maybe_start_logging();
let database_url = maybe_skip_integration!();
let ingester_config = TestConfig::new_ingester(&database_url);
let router_config = TestConfig::new_router(&ingester_config);
let querier_config = TestConfig::new_querier(&ingester_config).with_querier_mem_pool_bytes(1);
let udp_capture = UdpCapture::new().await;
let compactor_config = TestConfig::new_compactor(&ingester_config).with_tracing(&udp_capture);
let mut cluster = MiniCluster::new()
.with_router(router_config)
.await
.with_ingester(ingester_config)
.await
.with_querier(querier_config)
.await
.with_compactor_config(compactor_config);
StepTest::new(
&mut cluster,
vec![
Step::RecordNumParquetFiles,
Step::WriteLineProtocol(String::from(
"my_awesome_table,tag1=A,tag2=B val=42i 123456",
)),
// wait for partitions to be persisted
Step::WaitForPersisted {
expected_increase: 1,
},
// Run the compactor
Step::Compact,
],
)
.run()
.await;
// "shallow" packet inspection and verify the UDP server got omething that had some expected
// results. We could look for any text of any of the compaction spans. The name of the span
// for acquiring permit is arbitrarily chosen.
udp_capture
.wait_for(|m| m.to_string().contains("acquire_permit"))
.await;
// debugging assistance
//println!("Traces received (1):\n\n{:#?}", udp_capture.messages());
// wait for the UDP server to shutdown
udp_capture.stop().await;
}
|
use cli::command::dumb_jump::DumbJump;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use filter::{MatchedItem, Query, SourceItem};
use maple_core::find_largest_cache_digest;
use maple_core::tools::ctags::{ProjectCtagsCommand, ProjectTag};
use matcher::{Matcher, MatcherBuilder};
use rayon::prelude::*;
use std::io::BufRead;
use std::sync::Arc;
use types::ClapItem;
use utils::count_lines;
fn prepare_source_items() -> Vec<SourceItem> {
let largest_cache = find_largest_cache_digest().expect("Cache is empty");
println!("==== Total items: {} ====", largest_cache.total);
std::io::BufReader::new(std::fs::File::open(&largest_cache.cached_path).unwrap())
.lines()
.filter_map(|x| x.ok().map(Into::<SourceItem>::into))
.collect()
}
fn filter_sequential(list: Vec<SourceItem>, matcher: &Matcher) -> Vec<MatchedItem> {
list.into_iter()
.filter_map(|item| {
let item: Arc<dyn ClapItem> = Arc::new(item);
matcher.match_item(item)
})
.collect()
}
// 3 times faster than filter
fn filter_parallel(list: Vec<SourceItem>, matcher: &Matcher) -> Vec<MatchedItem> {
list.into_par_iter()
.filter_map(|item| {
let item: Arc<dyn ClapItem> = Arc::new(item);
matcher.match_item(item)
})
.collect()
}
fn bench_filter(c: &mut Criterion) {
let source_items = prepare_source_items();
let total_items = source_items.len();
let take_items = |n: usize| source_items.iter().take(n).cloned().collect::<Vec<_>>();
let query: Query = "executor".into();
let matcher = MatcherBuilder::new().build(query);
if total_items > 1_000 {
let source_items_1k = take_items(1_000);
c.bench_function("filter_sequential 1k", |b| {
b.iter(|| filter_sequential(black_box(source_items_1k.clone()), &matcher))
});
c.bench_function("filter_parallel 1k", |b| {
b.iter(|| filter_parallel(black_box(source_items_1k.clone()), &matcher))
});
}
if total_items > 10_000 {
let source_items_10k = take_items(10_000);
c.bench_function("filter_sequential 10k", |b| {
b.iter(|| filter_sequential(black_box(source_items_10k.clone()), &matcher))
});
c.bench_function("filter_parallel 10k", |b| {
b.iter(|| filter_parallel(black_box(source_items_10k.clone()), &matcher))
});
}
if total_items > 100_000 {
let source_items_100k = take_items(100_000);
c.bench_function("filter_sequential 100k", |b| {
b.iter(|| filter_sequential(black_box(source_items_100k.clone()), &matcher))
});
c.bench_function("filter_parallel 100k", |b| {
b.iter(|| filter_parallel(black_box(source_items_100k.clone()), &matcher))
});
}
if total_items > 1_000_000 {
let source_items_1m = take_items(1_000_000);
c.bench_function("filter_sequential 1m", |b| {
b.iter(|| filter_sequential(black_box(source_items_1m.clone()), &matcher))
});
c.bench_function("filter_parallel 1m", |b| {
b.iter(|| filter_parallel(black_box(source_items_1m.clone()), &matcher))
});
}
}
fn bench_ctags(c: &mut Criterion) {
let build_ctags_cmd =
|| ProjectCtagsCommand::with_cwd("/home/xlc/src/github.com/paritytech/substrate".into());
// TODO: Make the parallel version faster, the previous benchmark result in the initial PR
// https://github.com/liuchengxu/vim-clap/pull/755 is incorrect due to the cwd set incorrectly.
c.bench_function("parallel recursive ctags", |b| {
b.iter(|| {
let mut ctags_cmd = build_ctags_cmd();
ctags_cmd.par_formatted_lines()
})
});
fn formatted_lines(ctags_cmd: ProjectCtagsCommand) -> Vec<String> {
ctags_cmd
.lines()
.unwrap()
.filter_map(|tag| {
if let Ok(tag) = serde_json::from_str::<ProjectTag>(&tag) {
Some(tag.format_proj_tag())
} else {
None
}
})
.collect()
}
c.bench_function("recursive ctags", |b| {
b.iter(|| {
let ctags_cmd = build_ctags_cmd();
formatted_lines(ctags_cmd)
})
});
}
fn bench_regex_searcher(c: &mut Criterion) {
let dumb_jump = DumbJump {
word: "unsigned".to_string(),
extension: "rs".to_string(),
kind: None,
cmd_dir: Some("/home/xlc/src/github.com/paritytech/substrate".into()),
regex: true,
};
c.bench_function("regex searcher", |b| {
b.iter(|| dumb_jump.regex_usages(false, &Default::default()))
});
}
fn bench_bytecount(c: &mut Criterion) {
let largest_cache = find_largest_cache_digest().expect("Cache is empty");
c.bench_function("bytecount", |b| {
b.iter(|| count_lines(std::fs::File::open(&largest_cache.cached_path).unwrap()))
});
}
criterion_group!(
benches,
bench_filter,
bench_ctags,
bench_regex_searcher,
bench_bytecount
);
criterion_main!(benches);
|
extern crate ed25519_dalek;
extern crate miniz_oxide;
extern crate rand;
extern crate serde_json;
extern crate sha3;
extern crate simple_logger;
#[macro_use]
extern crate lazy_static;
pub mod block;
mod blockchain;
pub mod config;
pub mod p2p;
use ed25519_dalek::Keypair;
use rand::rngs::OsRng;
fn main() {
simple_logger::init().unwrap();
let mut csprng = OsRng {};
p2p::Client::new(
Keypair::generate(&mut csprng),
config::get_config().boot_node,
)
.main();
}
|
use rough::na::Vector2;
pub struct ControlSettings {
pub mouse: MouseSettings,
}
impl Default for ControlSettings {
fn default() -> Self {
ControlSettings {
mouse: Default::default(),
}
}
}
pub struct MouseSettings {
pub invert_y: bool,
pub sensitivity: Vector2<f32>,
}
impl Default for MouseSettings {
fn default() -> Self {
MouseSettings {
invert_y: false,
sensitivity: Vector2::new(1.0, 1.0),
}
}
}
|
use proconio::{input, marker::Bytes};
fn calc(s: &[u8], t: &[u8]) -> usize {
let n = s.len().min(t.len());
for i in 0..n {
if s[i] != t[i] {
return i;
}
}
n
}
fn main() {
input! {
n: usize,
s: [Bytes; n],
};
let mut ord = Vec::new();
for i in 0..n {
ord.push(i);
}
ord.sort_by(|&i, &j| s[i].cmp(&s[j]));
let mut ans = vec![0; n];
for k in 0..n {
if k >= 1 {
ans[ord[k]] = ans[ord[k]].max(calc(&s[ord[k - 1]], &s[ord[k]]));
}
if k + 1 < n {
ans[ord[k]] = ans[ord[k]].max(calc(&s[ord[k]], &s[ord[k + 1]]));
}
}
for ans in ans {
println!("{}", ans);
}
}
|
// RGB standard library
// Written in 2020 by
// Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.
use std::collections::VecDeque;
use lnpbp::bitcoin::hashes::Hash;
use lnpbp::bp::blind::OutpointHash;
use lnpbp::rgb::{Anchor, AutoConceal, Consignment, ContractId, Node, NodeId, Transition};
use super::index::Index;
use super::storage::Store;
use super::Runtime;
#[derive(Clone, PartialEq, Eq, Debug, Display, From, Error)]
#[display_from(Debug)]
pub enum Error {
#[derive_from(super::storage::DiskStorageError)]
StorageError,
#[derive_from(super::index::BTreeIndexError)]
IndexError,
}
impl Runtime {
pub fn consign(
&self,
contract_id: &ContractId,
transition: &Transition,
anchor: &Anchor,
endpoints: Vec<OutpointHash>,
) -> Result<Consignment, Error> {
let genesis = self.storage.genesis(&contract_id)?;
let mut node: &mut dyn Node = &mut transition.clone();
node.conceal_except(&endpoints);
let mut data = vec![(anchor.clone(), transition.clone())];
let mut sources = VecDeque::<NodeId>::new();
sources.extend(transition.ancestors().into_iter().map(|(id, _)| id));
while let Some(tsid) = sources.pop_front() {
if tsid.into_inner() == genesis.contract_id().into_inner() {
continue;
}
let anchor_id = self.indexer.anchor_id_by_transition_id(tsid)?;
let anchor = self.storage.anchor(&anchor_id)?;
let mut transition = self.storage.transition(&tsid)?;
let mut node: &mut dyn Node = &mut transition;
node.conceal_all();
data.push((anchor, transition.clone()));
sources.extend(transition.ancestors().into_iter().map(|(id, _)| id));
}
let node_id = transition.node_id();
let extended_endpoints = endpoints.iter().map(|op| (node_id, *op)).collect();
Ok(Consignment::with(genesis, extended_endpoints, data))
}
pub fn merge(&mut self, consignment: Consignment) -> Result<Vec<Box<dyn Node>>, Error> {
let mut nodes: Vec<Box<dyn Node>> = vec![];
consignment
.data
.into_iter()
.try_for_each(|(anchor, transition)| -> Result<(), Error> {
self.storage
.add_transition(&transition)?
.then(|| nodes.push(Box::new(transition)));
self.storage.add_anchor(&anchor)?;
self.indexer.index_anchor(&anchor)?;
Ok(())
})?;
let genesis = consignment.genesis;
self.storage
.add_genesis(&genesis)?
.then(|| nodes.push(Box::new(genesis)));
Ok(nodes)
}
}
|
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
use smart_default::SmartDefault;
use crate::AudioGroupId;
#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Sound {
/// The type of compression for the file.
pub compression: Compression,
/// The volume of the file.
pub volume: f64,
/// Whether the sound is "preloaded" or not. I don't know what this
/// actually does.
pub preload: bool,
/// The bitrate of the audio. Higher is better I think? Honestly lol,
/// knowing what "bitrate" means is for fuckin nerds
/// This is in "kbps" apparently, so probably kilobits (bytes?) per second.
/// Look, no one knows.
pub bit_rate: BitRate,
/// SAMPLE RATE?? I didn't know BITRATE you think i'm gonna know "SAMPLE RATE"
/// it's the rate of the samples go fuck yourself
pub sample_rate: SampleRate,
/// The kind of the sound for mono/stereo.
#[serde(rename = "type")]
pub output: Output,
/// The quality of the sound.
pub bit_depth: BitDepth,
/// This is the Path to the Audio Group Id.
pub audio_group_id: AudioGroupId,
/// This is a path to the Audio file, which will be the same name as the sound file generally.
/// If there is no sound set up for this asset, then this field **will be an empty string.**
pub sound_file: String,
/// The duration of the sound in seconds, such as `12.4` for 12 seconds and 400 miliseconds.
pub duration: f64,
/// The parent in the Gms2 virtual file system, ie. the parent which
/// a user would see in the Navigation Pane in Gms2. This has no relationship
/// to the actual operating system's filesystem.
pub parent: crate::ViewPath,
/// The resource version of this yy file. At default 1.0.
pub resource_version: crate::ResourceVersion,
/// The name of the object. This is the human readable name used in the IDE.
pub name: String,
/// The tags given to the object.
pub tags: crate::Tags,
/// The resource type, always the same for sounds.
pub resource_type: ConstGmSound,
}
#[derive(Debug, Copy, SmartDefault, Deserialize_repr, Serialize_repr, PartialEq, Eq, Clone)]
#[repr(u8)]
pub enum Compression {
#[default]
Uncompressed,
Compressed,
UncompressedOnLoad,
CompressedStreamed,
}
#[derive(Debug, Copy, SmartDefault, Deserialize_repr, Serialize_repr, PartialEq, Eq, Clone)]
#[repr(u8)]
pub enum BitDepth {
#[default]
EightBit,
SixteenBit,
}
#[derive(Debug, Copy, Serialize, Deserialize, PartialEq, Eq, Clone)]
#[repr(transparent)]
#[serde(transparent)]
pub struct BitRate(u32);
impl BitRate {
pub fn new(bitrate: u32) -> Option<Self> {
if Self::is_valid_bitrate(bitrate) {
return None;
}
Some(Self(bitrate))
}
pub fn is_valid_bitrate(bitrate: u32) -> bool {
match bitrate {
0..=64 => {
if bitrate % 8 != 0 {
return false;
}
}
80..=160 => {
if bitrate % 16 != 0 {
return false;
}
}
192..=256 => {
if bitrate % 32 != 0 {
return false;
}
}
320 | 512 => {}
_ => {
return false;
}
}
true
}
}
impl Default for BitRate {
fn default() -> Self {
Self(128)
}
}
#[derive(Debug, Copy, Serialize, Deserialize, PartialEq, Eq, Clone)]
#[repr(transparent)]
#[serde(transparent)]
pub struct SampleRate(u32);
impl SampleRate {
pub fn new(bitrate: u32) -> Option<Self> {
if Self::is_valid_sample_rate(bitrate) {
return None;
}
Some(Self(bitrate))
}
pub fn is_valid_sample_rate(bitrate: u32) -> bool {
matches!(bitrate, 5512 | 11025 | 22050 | 32000 | 44100 | 48000)
}
pub fn valid_sample_rates() -> [u32; 6] {
[5512, 11025, 22050, 32000, 44100, 48000]
}
}
impl Default for SampleRate {
fn default() -> Self {
Self(128)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize_repr, Deserialize_repr, SmartDefault)]
#[repr(u8)]
pub enum Output {
#[default]
Mono,
Stereo,
ThreeDee,
}
#[derive(Debug, Copy, Serialize, Deserialize, SmartDefault, PartialEq, Eq, Clone)]
pub enum ConstGmSound {
#[serde(rename = "GMSound")]
#[default]
Const,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serialize_deserialize() {
let input = r#"
{
"compression": 2,
"volume": 1.0,
"preload": false,
"bitRate": 128,
"sampleRate": 44100,
"type": 0,
"bitDepth": 1,
"audioGroupId": {
"name": "audiogroup_default",
"path": "audiogroups/audiogroup_default"
},
"soundFile": "snd_summer_ambiance_day.mp3",
"duration": 60.0583344,
"parent": {
"name": "Sounds",
"path": "folders/Sounds.yy"
},
"resourceVersion": "1.0",
"name": "snd_summer_ambiance_day",
"tags": [],
"resourceType": "GMSound"
}"#;
let _: Sound = serde_json::from_str(input).unwrap();
}
}
|
use super::Object;
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::{Result, Write};
use std::rc::Rc;
pub trait PDFData: std::fmt::Debug {
fn write(&self, o: &mut dyn Write) -> Result<()>;
fn dependent_objects(&self) -> Vec<Rc<dyn Object>> {
vec![]
}
}
impl PDFData for usize {
fn write(&self, o: &mut dyn Write) -> Result<()> {
write!(o, "{}", self)
}
}
impl PDFData for f64 {
fn write(&self, o: &mut dyn Write) -> Result<()> {
write!(o, "{}", self)
}
}
impl PDFData for [std::string::String; 2] {
fn write(&self, o: &mut dyn Write) -> Result<()> {
write!(o, "[{}, {}]", self[0], self[1])
}
}
impl<T: PDFData + ?Sized> PDFData for Vec<Rc<T>> {
fn write(&self, o: &mut dyn Write) -> Result<()> {
write!(o, "[")?;
let mut iter = self.iter();
if let Some(d) = iter.next() {
d.write(o)?;
for d in iter {
write!(o, " ")?;
d.write(o)?;
}
}
write!(o, "]")
}
fn dependent_objects(&self) -> Vec<Rc<dyn Object>> {
let mut tmp = vec![];
for obj in self.iter() {
tmp.extend(obj.dependent_objects());
}
tmp
}
}
#[derive(Eq, PartialEq, Hash, Debug, Clone)]
pub struct Name(String);
impl Name {
pub fn new(s: impl Into<String>) -> Rc<Self> {
Rc::new(Self(s.into()))
}
}
impl From<Rc<Name>> for Name {
fn from(n: Rc<Name>) -> Self {
Self(n.0.clone())
}
}
impl From<String> for Name {
fn from(s: String) -> Self {
Self(s)
}
}
impl From<&str> for Name {
fn from(s: &str) -> Self {
Self(s.to_string())
}
}
impl std::fmt::Display for Name {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "/{}", self.0)
}
}
impl PDFData for Name {
fn write(&self, o: &mut dyn Write) -> Result<()> {
write!(o, "/{}", self.0)
}
}
#[derive(Debug)]
pub struct Dict {
items: RefCell<HashMap<Name, Rc<dyn PDFData>>>,
}
impl Dict {
pub fn new() -> Rc<Self> {
Rc::new(Self {
items: RefCell::new(HashMap::new()),
})
}
pub fn from_vec(v: Vec<(impl Into<Name>, Rc<dyn PDFData>)>) -> Rc<Self> {
let mut items = HashMap::new();
for (n, d) in v {
items.insert(n.into(), d);
}
Rc::new(Self {
items: RefCell::new(items),
})
}
pub fn add_entry(&self, n: impl Into<Name>, data: Rc<dyn PDFData>) {
self.items.borrow_mut().insert(n.into(), data);
}
pub fn add_optional(&self, n: impl Into<Name>, data: Option<Rc<dyn PDFData>>) {
if let Some(data) = data {
self.items.borrow_mut().insert(n.into(), data);
}
}
pub fn get_entry(&self, n: impl Into<Name>) -> Option<Rc<dyn PDFData>> {
self.items.borrow_mut().get(&n.into()).cloned()
}
pub fn is_empty(&self) -> bool {
self.items.borrow().is_empty()
}
}
impl PDFData for Dict {
fn write(&self, o: &mut dyn Write) -> Result<()> {
write!(o, "<<\n")?;
for (k, v) in self.items.borrow().iter() {
k.write(o)?;
write!(o, " ")?;
v.write(o)?;
write!(o, "\n")?;
}
write!(o, ">>\n")
}
fn dependent_objects(&self) -> Vec<Rc<dyn Object>> {
let mut tmp = vec![];
for obj in self.items.borrow().values() {
tmp.extend(obj.dependent_objects());
}
tmp
}
}
#[derive(Debug)]
pub struct Stream {
meta: Rc<Dict>,
data: Vec<u8>,
}
impl Stream {
pub fn new(meta: Rc<Dict>, data: Vec<u8>) -> Rc<Self> {
meta.add_entry("Length", Rc::new(data.len()));
Rc::new(Self { meta, data })
}
pub fn add_entry(&self, n: impl Into<Name>, data: Rc<dyn PDFData>) {
self.meta.add_entry(n, data);
}
}
impl PDFData for Stream {
fn write(&self, o: &mut dyn Write) -> Result<()> {
self.meta.write(o)?;
write!(o, "stream\n")?;
o.write_all(&self.data)?;
write!(o, "\nendstream\n")
}
}
|
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use anyhow::*;
use liblumen_alloc::erts::exception::{self, *};
use liblumen_alloc::erts::process::trace::Trace;
use liblumen_alloc::erts::term::prelude::Term;
#[native_implemented::function(erlang:throw/1)]
pub fn result(reason: Term) -> exception::Result<Term> {
Err(throw(
reason,
Trace::capture(),
Some(anyhow!("explicit throw from Erlang").into()),
)
.into())
}
|
// Copyright 2014 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.
#![feature(box_syntax)]
#![feature(box_patterns)]
use std::ops::{Deref, DerefMut};
struct X(Box<isize>);
static mut DESTRUCTOR_RAN: bool = false;
impl Drop for X {
fn drop(&mut self) {
unsafe {
assert!(!DESTRUCTOR_RAN);
DESTRUCTOR_RAN = true;
}
}
}
impl Deref for X {
type Target = isize;
fn deref(&self) -> &isize {
let &X(box ref x) = self;
x
}
}
impl DerefMut for X {
fn deref_mut(&mut self) -> &mut isize {
let &mut X(box ref mut x) = self;
x
}
}
fn main() {
{
let mut test = X(box 5);
{
let mut change = || { *test = 10 };
change();
}
assert_eq!(*test, 10);
}
assert!(unsafe { DESTRUCTOR_RAN });
}
|
#![allow(unreachable_code)]
use std::{collections::HashMap, convert::Infallible};
use async_graphql::{
dataloader::{DataLoader, Loader},
*,
};
#[tokio::test]
pub async fn test_nested_key() {
#[derive(InputObject)]
struct MyInputA {
a: i32,
b: i32,
c: MyInputB,
}
#[derive(InputObject)]
struct MyInputB {
v: i32,
}
assert_eq!(MyInputB::federation_fields().as_deref(), Some("{ v }"));
assert_eq!(
MyInputA::federation_fields().as_deref(),
Some("{ a b c { v } }")
);
struct Query;
#[derive(SimpleObject)]
struct MyObj {
a: i32,
b: i32,
c: i32,
}
#[Object]
impl Query {
#[graphql(entity)]
async fn find_obj(&self, input: MyInputA) -> MyObj {
MyObj {
a: input.a,
b: input.b,
c: input.c.v,
}
}
}
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
let query = r#"{
_entities(representations: [{__typename: "MyObj", input: {a: 1, b: 2, c: { v: 3 }}}]) {
__typename
... on MyObj {
a b c
}
}
}"#;
assert_eq!(
schema.execute(query).await.into_result().unwrap().data,
value!({
"_entities": [
{"__typename": "MyObj", "a": 1, "b": 2, "c": 3},
]
})
);
}
#[tokio::test]
pub async fn test_federation() {
struct User {
id: ID,
}
#[Object(extends)]
impl User {
#[graphql(external)]
async fn id(&self) -> &ID {
&self.id
}
async fn reviews(&self) -> Vec<Review> {
todo!()
}
}
struct Review;
#[Object]
impl Review {
async fn body(&self) -> String {
todo!()
}
async fn author(&self) -> User {
todo!()
}
async fn product(&self) -> Product {
todo!()
}
}
struct Product {
upc: String,
}
#[Object(extends)]
impl Product {
#[graphql(external)]
async fn upc(&self) -> &str {
&self.upc
}
async fn reviews(&self) -> Vec<Review> {
todo!()
}
}
struct Query;
#[Object]
impl Query {
#[graphql(entity)]
async fn find_user_by_id(&self, id: ID) -> User {
User { id }
}
#[graphql(entity)]
async fn find_product_by_upc(&self, upc: String) -> Product {
Product { upc }
}
}
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
let query = r#"{
_entities(representations: [{__typename: "Product", upc: "B00005N5PF"}]) {
__typename
... on Product {
upc
}
}
}"#;
assert_eq!(
schema.execute(query).await.into_result().unwrap().data,
value!({
"_entities": [
{"__typename": "Product", "upc": "B00005N5PF"},
]
})
);
}
#[tokio::test]
pub async fn test_find_entity_with_context() {
struct MyLoader;
#[async_trait::async_trait]
impl Loader<ID> for MyLoader {
type Value = MyObj;
type Error = Infallible;
async fn load(&self, keys: &[ID]) -> Result<HashMap<ID, Self::Value>, Self::Error> {
Ok(keys
.iter()
.filter(|id| id.as_str() != "999")
.map(|id| {
(
id.clone(),
MyObj {
id: id.clone(),
value: 999,
},
)
})
.collect())
}
}
#[derive(Clone, SimpleObject)]
struct MyObj {
id: ID,
value: i32,
}
struct Query;
#[Object]
impl Query {
#[graphql(entity)]
async fn find_user_by_id(&self, ctx: &Context<'_>, id: ID) -> FieldResult<MyObj> {
let loader = ctx.data_unchecked::<DataLoader<MyLoader>>();
loader
.load_one(id)
.await
.unwrap()
.ok_or_else(|| "Not found".into())
}
}
let schema = Schema::build(Query, EmptyMutation, EmptySubscription)
.data(DataLoader::new(MyLoader, tokio::spawn))
.finish();
let query = r#"{
_entities(representations: [
{__typename: "MyObj", id: "1"},
{__typename: "MyObj", id: "2"},
{__typename: "MyObj", id: "3"},
{__typename: "MyObj", id: "4"}
]) {
__typename
... on MyObj {
id
value
}
}
}"#;
assert_eq!(
schema.execute(query).await.into_result().unwrap().data,
value!({
"_entities": [
{"__typename": "MyObj", "id": "1", "value": 999 },
{"__typename": "MyObj", "id": "2", "value": 999 },
{"__typename": "MyObj", "id": "3", "value": 999 },
{"__typename": "MyObj", "id": "4", "value": 999 },
]
})
);
let query = r#"{
_entities(representations: [
{__typename: "MyObj", id: "999"}
]) {
__typename
... on MyObj {
id
value
}
}
}"#;
assert_eq!(
schema.execute(query).await.into_result().unwrap_err(),
vec![ServerError {
message: "Not found".to_string(),
source: None,
locations: vec![Pos {
line: 2,
column: 13
}],
path: vec![PathSegment::Field("_entities".to_owned())],
extensions: None,
}]
);
}
#[tokio::test]
pub async fn test_entity_union() {
#[derive(SimpleObject)]
struct MyObj {
a: i32,
}
struct Query;
#[Object]
impl Query {
#[graphql(entity)]
async fn find_obj(&self, _id: i32) -> MyObj {
todo!()
}
}
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
let query = r#"{
__type(name: "_Entity") { possibleTypes { name } }
}"#;
assert_eq!(
schema.execute(query).await.into_result().unwrap().data,
value!({
"__type": {
"possibleTypes": [
{"name": "MyObj"},
]
}
})
);
}
#[tokio::test]
pub async fn test_entity_shareable() {
#[derive(SimpleObject)]
struct MyObjFieldShareable {
#[graphql(shareable)]
field_shareable_a: i32,
}
#[derive(SimpleObject)]
#[graphql(shareable)]
struct MyObjShareable {
a: i32,
}
struct Query;
#[Object(extends)]
impl Query {
#[graphql(entity)]
async fn find_obj_field_shareable(&self, _id: i32) -> MyObjFieldShareable {
todo!()
}
#[graphql(entity)]
async fn find_obj_shareable(&self, _id: i32) -> MyObjShareable {
todo!()
}
}
let schema_sdl = Schema::new(Query, EmptyMutation, EmptySubscription)
.sdl_with_options(SDLExportOptions::new().federation());
assert!(schema_sdl.contains("fieldShareableA: Int! @shareable"),);
assert!(schema_sdl.contains(r#"MyObjShareable @key(fields: "id") @shareable"#),);
}
#[tokio::test]
pub async fn test_field_override_directive() {
#[derive(SimpleObject)]
struct MyObjFieldOverride {
#[graphql(override_from = "AnotherSubgraph")]
field_override_a: i32,
}
struct Query;
#[Object(extends)]
impl Query {
#[graphql(entity)]
async fn find_obj_field_override(&self, _id: i32) -> MyObjFieldOverride {
todo!()
}
}
let schema_sdl = Schema::new(Query, EmptyMutation, EmptySubscription)
.sdl_with_options(SDLExportOptions::new().federation());
assert!(schema_sdl.contains("fieldOverrideA: Int! @override(from: \"AnotherSubgraph\")"),);
}
#[tokio::test]
pub async fn test_entity_inaccessible() {
struct MyCustomObjInaccessible;
#[Object(inaccessible)]
impl MyCustomObjInaccessible {
async fn a(&self) -> i32 {
todo!()
}
#[graphql(inaccessible)]
async fn custom_object_inaccessible(&self) -> i32 {
todo!()
}
}
#[derive(SimpleObject)]
struct MyObjFieldInaccessible {
#[graphql(inaccessible)]
obj_field_inaccessible_a: i32,
}
#[derive(SimpleObject)]
#[graphql(inaccessible)]
struct MyObjInaccessible {
a: i32,
}
#[derive(InputObject)]
struct MyInputObjFieldInaccessible {
#[graphql(inaccessible)]
input_field_inaccessible_a: i32,
}
#[derive(InputObject)]
#[graphql(inaccessible)]
struct MyInputObjInaccessible {
a: i32,
}
#[derive(Enum, PartialEq, Eq, Copy, Clone)]
enum MyEnumVariantInaccessible {
#[graphql(inaccessible)]
OptionAInaccessible,
OptionB,
OptionC,
}
#[derive(Enum, PartialEq, Eq, Copy, Clone)]
#[graphql(inaccessible)]
enum MyEnumInaccessible {
OptionA,
OptionB,
OptionC,
}
#[derive(SimpleObject)]
struct MyInterfaceObjA {
inaccessible_interface_value: String,
}
#[derive(SimpleObject)]
#[graphql(inaccessible)]
struct MyInterfaceObjB {
inaccessible_interface_value: String,
}
#[derive(Interface)]
#[graphql(field(name = "inaccessible_interface_value", type = "String", inaccessible))]
#[graphql(inaccessible)]
enum MyInterfaceInaccessible {
MyInterfaceObjA(MyInterfaceObjA),
MyInterfaceObjB(MyInterfaceObjB),
}
#[derive(Union)]
#[graphql(inaccessible)]
enum MyUnionInaccessible {
MyInterfaceObjA(MyInterfaceObjA),
MyInterfaceObjB(MyInterfaceObjB),
}
struct MyNumberInaccessible(i32);
#[Scalar(inaccessible)]
impl ScalarType for MyNumberInaccessible {
fn parse(_value: Value) -> InputValueResult<Self> {
todo!()
}
fn to_value(&self) -> Value {
todo!()
}
}
struct Query;
#[Object(extends)]
impl Query {
#[graphql(entity)]
async fn find_obj_field_inaccessible(&self, _id: i32) -> MyObjFieldInaccessible {
todo!()
}
#[graphql(entity)]
async fn find_obj_inaccessible(&self, _id: i32) -> MyObjInaccessible {
todo!()
}
async fn enum_variant_inaccessible(&self, _id: i32) -> MyEnumVariantInaccessible {
todo!()
}
async fn enum_inaccessible(&self, _id: i32) -> MyEnumInaccessible {
todo!()
}
#[graphql(inaccessible)]
async fn inaccessible_field(&self, _id: i32) -> i32 {
todo!()
}
async fn inaccessible_argument(&self, #[graphql(inaccessible)] _id: i32) -> i32 {
todo!()
}
async fn inaccessible_interface(&self) -> MyInterfaceInaccessible {
todo!()
}
async fn inaccessible_union(&self) -> MyUnionInaccessible {
todo!()
}
async fn inaccessible_scalar(&self) -> MyNumberInaccessible {
todo!()
}
async fn inaccessible_input_field(&self, _value: MyInputObjFieldInaccessible) -> i32 {
todo!()
}
async fn inaccessible_input(&self, _value: MyInputObjInaccessible) -> i32 {
todo!()
}
async fn inaccessible_custom_object(&self) -> MyCustomObjInaccessible {
todo!()
}
}
let schema_sdl = Schema::new(Query, EmptyMutation, EmptySubscription)
.sdl_with_options(SDLExportOptions::new().federation());
// FIELD_DEFINITION
assert!(schema_sdl.contains("inaccessibleField(id: Int!): Int! @inaccessible"));
assert!(schema_sdl.contains("objFieldInaccessibleA: Int! @inaccessible"));
assert!(schema_sdl.contains("inaccessibleInterfaceValue: String! @inaccessible"));
assert!(schema_sdl.contains("customObjectInaccessible: Int! @inaccessible"));
// INTERFACE
assert!(schema_sdl.contains("interface MyInterfaceInaccessible @inaccessible"));
// OBJECT
assert!(schema_sdl.contains("type MyCustomObjInaccessible @inaccessible"));
assert!(schema_sdl.contains(r#"type MyObjInaccessible @key(fields: "id") @inaccessible"#));
assert!(schema_sdl
.contains("type MyInterfaceObjB implements MyInterfaceInaccessible @inaccessible"));
// UNION
assert!(schema_sdl.contains("union MyUnionInaccessible @inaccessible ="));
// ARGUMENT_DEFINITION
assert!(schema_sdl.contains("inaccessibleArgument(id: Int! @inaccessible): Int!"));
// SCALAR
assert!(schema_sdl.contains("scalar MyNumberInaccessible @inaccessible"));
// ENUM
assert!(schema_sdl.contains("enum MyEnumInaccessible @inaccessible"));
// ENUM_VALUE
assert!(schema_sdl.contains("OPTION_A_INACCESSIBLE @inaccessible"));
// INPUT_OBJECT
assert!(schema_sdl.contains("input MyInputObjInaccessible @inaccessible"));
// INPUT_FIELD_DEFINITION
assert!(schema_sdl.contains("inputFieldInaccessibleA: Int! @inaccessible"));
// no trailing spaces
assert!(!schema_sdl.contains(" \n"));
// compare to expected schema
let path = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap())
.join("tests/schemas/test_entity_inaccessible.schema.graphql");
let expected_schema = std::fs::read_to_string(&path).unwrap();
if schema_sdl != expected_schema {
std::fs::write(path, schema_sdl).unwrap();
panic!("schema was not up-to-date. rerun")
}
}
#[tokio::test]
pub async fn test_link_directive() {
struct User {
id: ID,
}
#[Object(extends)]
impl User {
#[graphql(external)]
async fn id(&self) -> &ID {
&self.id
}
async fn reviews(&self) -> Vec<Review> {
todo!()
}
}
struct Review;
#[Object]
impl Review {
async fn body(&self) -> String {
todo!()
}
async fn author(&self) -> User {
todo!()
}
async fn product(&self) -> Product {
todo!()
}
}
struct Product {
upc: String,
}
#[Object(extends)]
impl Product {
#[graphql(external)]
async fn upc(&self) -> &str {
&self.upc
}
async fn reviews(&self) -> Vec<Review> {
todo!()
}
}
struct Query;
#[Object]
impl Query {
#[graphql(entity)]
async fn find_user_by_id(&self, id: ID) -> User {
User { id }
}
#[graphql(entity)]
async fn find_product_by_upc(&self, upc: String) -> Product {
Product { upc }
}
}
let schema_sdl = Schema::build(Query, EmptyMutation, EmptySubscription)
.finish()
.sdl_with_options(SDLExportOptions::new().federation());
let path = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap())
.join("tests/schemas/test_fed2_link.schema.graphqls");
let expected_schema = std::fs::read_to_string(&path).unwrap();
if schema_sdl != expected_schema {
std::fs::write(path, schema_sdl).unwrap();
panic!("schema was not up-to-date. verify changes and re-run if correct.")
}
}
#[tokio::test]
pub async fn test_entity_tag() {
struct MyCustomObjTagged;
#[Object(
tag = "tagged",
tag = "object",
tag = "with",
tag = "multiple",
tag = "tags"
)]
impl MyCustomObjTagged {
async fn a(&self) -> i32 {
todo!()
}
#[graphql(tag = "tagged_custom_object_field")]
async fn custom_object_tagged(&self) -> i32 {
todo!()
}
}
#[derive(SimpleObject)]
struct MyObjFieldTagged {
#[graphql(tag = "tagged_field")]
obj_field_tagged_a: i32,
}
#[derive(SimpleObject)]
#[graphql(tag = "tagged_simple_object")]
struct MyObjTagged {
a: i32,
}
#[derive(InputObject)]
struct MyInputObjFieldTagged {
#[graphql(tag = "tagged_input_object_field")]
input_field_tagged_a: i32,
}
#[derive(InputObject)]
#[graphql(tag = "input_object_tag")]
struct MyInputObjTagged {
a: i32,
}
#[derive(Enum, PartialEq, Eq, Copy, Clone)]
enum MyEnumVariantTagged {
#[graphql(tag = "tagged_enum_option")]
OptionATagged,
OptionB,
OptionC,
}
#[derive(Enum, PartialEq, Eq, Copy, Clone)]
#[graphql(tag = "tagged_num")]
enum MyEnumTagged {
OptionA,
OptionB,
OptionC,
}
#[derive(SimpleObject)]
struct MyInterfaceObjA {
tagged_interface_value: String,
}
#[derive(SimpleObject)]
#[graphql(tag = "interface_object")]
struct MyInterfaceObjB {
tagged_interface_value: String,
}
#[derive(Interface)]
#[graphql(field(
name = "tagged_interface_value",
type = "String",
tag = "tagged_interface_field"
))]
#[graphql(tag = "tagged_interface")]
enum MyInterfaceTagged {
MyInterfaceObjA(MyInterfaceObjA),
MyInterfaceObjB(MyInterfaceObjB),
}
#[derive(Union)]
#[graphql(tag = "tagged_union")]
enum MyUnionTagged {
MyInterfaceObjA(MyInterfaceObjA),
MyInterfaceObjB(MyInterfaceObjB),
}
struct MyNumberTagged(i32);
#[Scalar(tag = "tagged_scalar")]
impl ScalarType for MyNumberTagged {
fn parse(_value: Value) -> InputValueResult<Self> {
todo!()
}
fn to_value(&self) -> Value {
todo!()
}
}
struct Query;
#[Object(extends)]
impl Query {
#[graphql(entity)]
async fn find_obj_field_tagged(&self, _id: i32) -> MyObjFieldTagged {
todo!()
}
#[graphql(entity)]
async fn find_obj_tagged(&self, _id: i32) -> MyObjTagged {
todo!()
}
async fn enum_variant_tagged(&self, _id: i32) -> MyEnumVariantTagged {
todo!()
}
async fn enum_tagged(&self, _id: i32) -> MyEnumTagged {
todo!()
}
#[graphql(tag = "tagged_\"field\"")]
async fn tagged_field(&self, _id: i32) -> i32 {
todo!()
}
async fn tagged_argument(&self, #[graphql(tag = "tagged_argument")] _id: i32) -> i32 {
todo!()
}
async fn tagged_interface(&self) -> MyInterfaceTagged {
todo!()
}
async fn tagged_union(&self) -> MyUnionTagged {
todo!()
}
async fn tagged_scalar(&self) -> MyNumberTagged {
todo!()
}
async fn tagged_input_field(&self, _value: MyInputObjFieldTagged) -> i32 {
todo!()
}
async fn tagged_input(&self, _value: MyInputObjTagged) -> i32 {
todo!()
}
async fn tagged_custom_object(&self) -> MyCustomObjTagged {
todo!()
}
}
let schema_sdl = Schema::new(Query, EmptyMutation, EmptySubscription)
.sdl_with_options(SDLExportOptions::new().federation());
// FIELD_DEFINITION
assert!(schema_sdl.contains(r#"taggedField(id: Int!): Int! @tag(name: "tagged_\"field\"")"#));
assert!(schema_sdl.contains(r#"objFieldTaggedA: Int! @tag(name: "tagged_field")"#));
assert!(schema_sdl
.contains(r#"taggedInterfaceValue: String! @tag(name: "tagged_interface_field")"#));
assert!(
schema_sdl.contains(r#"customObjectTagged: Int! @tag(name: "tagged_custom_object_field")"#)
);
// INTERFACE
assert!(schema_sdl.contains(r#"interface MyInterfaceTagged @tag(name: "tagged_interface")"#));
// OBJECT
assert!(schema_sdl.contains(r#"type MyCustomObjTagged @tag(name: "tagged") @tag(name: "object") @tag(name: "with") @tag(name: "multiple") @tag(name: "tags") {"#));
assert!(schema_sdl
.contains(r#"type MyObjTagged @key(fields: "id") @tag(name: "tagged_simple_object") {"#));
assert!(schema_sdl.contains(
r#"type MyInterfaceObjB implements MyInterfaceTagged @tag(name: "interface_object")"#
));
// UNION
assert!(schema_sdl.contains(r#"union MyUnionTagged @tag(name: "tagged_union") ="#));
// ARGUMENT_DEFINITION
assert!(schema_sdl.contains(r#"taggedArgument(id: Int! @tag(name: "tagged_argument")): Int!"#));
// SCALAR
assert!(schema_sdl.contains(r#"scalar MyNumberTagged @tag(name: "tagged_scalar")"#));
// ENUM
assert!(schema_sdl.contains(r#"enum MyEnumTagged @tag(name: "tagged_num")"#));
// ENUM_VALUE
assert!(schema_sdl.contains(r#"OPTION_A_TAGGED @tag(name: "tagged_enum_option")"#));
// INPUT_OBJECT
assert!(schema_sdl.contains(r#"input MyInputObjTagged @tag(name: "input_object_tag")"#));
// INPUT_FIELD_DEFINITION
assert!(
schema_sdl.contains(r#"inputFieldTaggedA: Int! @tag(name: "tagged_input_object_field")"#)
);
// no trailing spaces
assert!(!schema_sdl.contains(" \n"));
// compare to expected schema
let path = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap())
.join("tests/schemas/test_entity_tag.schema.graphql");
let expected_schema = std::fs::read_to_string(&path).unwrap();
if schema_sdl != expected_schema {
std::fs::write(path, schema_sdl).unwrap();
panic!("schema was not up-to-date. rerun")
}
}
|
use super::*;
use proptest::prop_oneof;
use proptest::strategy::Strategy;
#[test]
fn without_list_or_bitstring_returns_false() {
run!(
|arc_process| {
strategy::term(arc_process.clone())
.prop_filter("Right cannot be a list or bitstring", |right| {
!(right.is_list() || right.is_bitstring())
})
},
|right| {
let left = Term::NIL;
prop_assert_eq!(result(left, right), false.into());
Ok(())
},
);
}
#[test]
fn with_list_or_bitstring_right_returns_true() {
TestRunner::new(Config::with_source_file(file!()))
.run(
&strategy::process()
.prop_flat_map(|arc_process| list_or_bitstring(arc_process.clone())),
|right| {
let left = Term::NIL;
prop_assert_eq!(result(left, right), true.into());
Ok(())
},
)
.unwrap();
}
fn list_or_bitstring(arc_process: Arc<Process>) -> BoxedStrategy<Term> {
prop_oneof![
strategy::term::is_list(arc_process.clone()),
strategy::term::is_bitstring(arc_process)
]
.boxed()
}
|
use input_i_scanner::InputIScanner;
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
macro_rules! scan {
(($($t: ty),+)) => {
($(scan!($t)),+)
};
($t: ty) => {
_i_i.scan::<$t>() as $t
};
(($($t: ty),+); $n: expr) => {
std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>()
};
($t: ty; $n: expr) => {
std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>()
};
}
let n = scan!(usize);
let a = scan!(u64; n);
let mut a = a;
a.sort();
let max = a.last().copied().unwrap();
let mut x = a[0];
for i in 1..(n - 1) {
if a[i].max(max - a[i]) < x.max(max - x) {
x = a[i];
}
}
println!("{} {}", max, x);
}
|
use crate::cursor::Cursor;
use crate::ecc::{PrivateKey, N};
use crate::helpers::{hash_160, hmac_512};
use crate::seed_phrase::SeedPhrase;
use bigint::{U256, U512};
use byteorder::{BigEndian, WriteBytesExt};
use core::convert::TryInto;
use genio::Read;
//use sha2::Digest;
use hashbrown::HashMap;
//use hex::decode;
use hmac::Hmac;
//todo: test
#[derive(Debug, Clone)]
pub struct ChainCode(U256);
impl ChainCode {
pub fn new(value: U256) -> Self {
Self(value)
}
pub fn from_bytes(bytes: &[u8]) -> Self {
Self(U256::from_big_endian(bytes))
}
pub fn as_bytes(&self) -> [u8; 32] {
let mut bytes = [0u8; 32];
self.0.to_big_endian(&mut bytes);
bytes
}
}
#[derive(Debug, Clone)]
pub struct ExtendedPrivateKey {
private_key: PrivateKey,
chain_code: ChainCode,
depth: u8,
parent_fingerprint: u32,
child_number: u32,
unhardened_children: HashMap<u32, Self>,
hardened_children: HashMap<u32, Self>,
}
impl ExtendedPrivateKey {
//todo: double check
//#![feature(const_int_pow)]
const HARDENED_CHILD_KEY_BASE_INDEX: u32 = 2u32.pow(31);
pub fn new(
private_key: PrivateKey,
chain_code: ChainCode,
parent_fingerprint: u32,
child_number: u32,
depth: u8,
) -> Self {
Self {
private_key,
chain_code,
child_number,
parent_fingerprint,
unhardened_children: HashMap::new(),
hardened_children: HashMap::new(),
depth,
}
}
pub fn new_master(seed: HDSeed) -> Self {
let hmac_result = hmac_512(b"Bitcoin seed", &seed.as_bytes());
let private_key_bytes: [u8; 32] = hmac_result[..32].try_into().expect("");
let private_key = PrivateKey::from_bytes(&private_key_bytes);
let chain_code_bytes: [u8; 32] = hmac_result[32..].try_into().expect("");
let chain_code = ChainCode::from_bytes(&chain_code_bytes);
let mut hardened_children = HashMap::new();
let mut unhardened_children = HashMap::new();
Self {
private_key,
chain_code,
child_number: 0,
parent_fingerprint: 0,
unhardened_children,
hardened_children,
depth: 0,
}
}
// Given a derivation path, populate this key's child, grandchild, etc.
//Example paths: "h/0h/1/33", "h/0h/"
pub fn reconstruct_by_path(&mut self, path: HDDerivationPath) -> Result<&Self, &'static str> {
let mut tokens = path.as_tokens().into_iter();
let mut current_node = self;
if tokens.next().unwrap() != "m" {
return Err("Invalid derivation path; derivation paths must begin with 'm' (master)");
}
while let Some(token) = tokens.next() {
// If token ends in "h", compute hardened child
if token.chars().last().unwrap() == 'h' {
match u32::from_str_radix(&token[..token.len() - 1], 10) {
Ok(child_number) => {
let child_number = child_number + Self::HARDENED_CHILD_KEY_BASE_INDEX;
current_node.derive_hardened_child_private_key(child_number);
current_node = current_node
.hardened_children
.get_mut(&child_number)
.unwrap();
}
Err(_) => return Err("Invalid derivation path"),
}
// Else compute unhardened child
} else {
match u32::from_str_radix(&token, 10) {
Ok(child_number) => {
current_node.derive_unhardened_child_private_key(child_number);
current_node = current_node
.unhardened_children
.get_mut(&child_number)
.unwrap();
}
Err(_) => return Err("Invalid derivation path"),
};
}
}
Ok(current_node)
}
pub fn derive_hardened_child_private_key(&mut self, new_child_number: u32) {
// Hardened keys begin at 2**31
assert!(new_child_number >= Self::HARDENED_CHILD_KEY_BASE_INDEX);
// Check if this key has already been derived
if let Some(extended_private_key) = self.hardened_children.get(&new_child_number) {
return; //extended_private_key.clone();
}
// Follow the formula: HMAC(key=chain_code_bytes, message=(0x00 || privkey || index)
let mut hmac_message = vec![0x00];
let mut private_key_bytes = vec![0x00; 32];
self
.private_key
.secret
.to_big_endian(&mut private_key_bytes);
hmac_message.extend(private_key_bytes);
let mut new_child_number_bytes = vec![];
new_child_number_bytes
.write_u32::<BigEndian>(new_child_number)
.unwrap();
hmac_message.extend(new_child_number_bytes);
let hmac_result = hmac_512(&self.chain_code.as_bytes(), &hmac_message);
// Chaincode is the first 32 bytes of the HMAC result;
let new_child_chaincode = ChainCode::from_bytes(&hmac_result[32..]);
// privkey is (last 32 bytes of HMAC + the old privkey) % N
let new_secret = (U256::from_big_endian(&hmac_result[..32])
.overflowing_add(self.private_key.secret)
.0)
% N.clone();
//(U256::from_big_endian(&hmac_result[..32]) + self.private_key.secret) % N.clone();
let new_child_private_key = PrivateKey::new(new_secret);
let new_child_extended_private_key = Self::new(
new_child_private_key,
new_child_chaincode,
self.fingerprint(),
new_child_number,
self.depth + 1,
);
self
.hardened_children
.insert(new_child_number, new_child_extended_private_key);
//new_child_extended_private_key
}
pub fn derive_unhardened_child_private_key(&mut self, new_child_number: u32) {
// Unhardened keys use all indicies up to 2**31
assert!(new_child_number < Self::HARDENED_CHILD_KEY_BASE_INDEX);
// Check if this key has already been derived
if let Some(extended_private_key) = self.unhardened_children.get(&new_child_number) {
return;
}
// Follow the recipie: HMAC(key=chain_code_bytes, message=(pubkey || index)
let mut hmac_message = vec![];
let public_key_bytes = self.private_key.point.sec(true);
hmac_message.extend(public_key_bytes);
let mut new_child_number_bytes = vec![];
new_child_number_bytes
.write_u32::<BigEndian>(new_child_number)
.unwrap();
hmac_message.extend(new_child_number_bytes);
let hmac_result = hmac_512(&self.chain_code.as_bytes(), &hmac_message);
// Code gore to prevent overflow; todo: fix
let new_secret: U512 = (U512::from(self.private_key.secret) + U512::from(&hmac_result[..32]))
% U512::from(N.clone());
let new_secret: U256 = U256::from(new_secret);
let new_child_private_key = PrivateKey::new(new_secret);
let new_child_chaincode = ChainCode::from_bytes(&hmac_result[32..]);
let new_child_extended_private_key = Self::new(
new_child_private_key,
new_child_chaincode,
self.fingerprint(),
new_child_number,
self.depth + 1,
);
self
.unhardened_children
.insert(new_child_number, new_child_extended_private_key);
}
pub fn fingerprint(&self) -> u32 {
let fingerprint_slice = &self.private_key.point.hash_160(true)[..4];
//let fingerprint_slice = &self.private_key.point.sec(true)[..4];
let mut fingerprint_bytes = [0u8; 4];
fingerprint_bytes.copy_from_slice(&fingerprint_slice);
u32::from_be_bytes(fingerprint_bytes)
}
pub fn deserialize(bytes: &[u8]) -> Self {
const EXPECTED_SERIALIZATION_LENTH: usize = 78;
if bytes.len() != EXPECTED_SERIALIZATION_LENTH {
panic!("Extended private key must serialization must be exactly 78 bytes");
}
let mut version_bytes = [0u8; 4];
let depth: u8;
let mut fingerprint_bytes = [0u8; 4];
let child_number: u32;
let mut chain_code_bytes = [0u8; 32];
let mut private_key_bytes = [0u8; 33];
let mut reader = Cursor::new(bytes);
reader.read_exact(&mut version_bytes);
depth = reader.read_u8_big_endian().unwrap();
reader.read_exact(&mut fingerprint_bytes);
child_number = reader.read_u32_big_endian().unwrap();
reader.read_exact(&mut chain_code_bytes);
reader.read_exact(&mut private_key_bytes);
let parent_fingerprint = u32::from_be_bytes(fingerprint_bytes);
let private_key = PrivateKey::from_bytes(&private_key_bytes[1..]);
let chain_code = ChainCode::from_bytes(&chain_code_bytes);
Self::new(
private_key,
chain_code,
parent_fingerprint,
child_number,
depth,
)
}
pub fn serialize(&self, testnet: bool) -> Vec<u8> {
let mut serialization = vec![];
if testnet {
let version_bytes = vec![0x04, 0x35, 0x83, 0x94];
serialization.extend(version_bytes);
} else {
let version_bytes = vec![0x04, 0x88, 0xAD, 0xE4];
serialization.extend(version_bytes);
}
serialization.extend(vec![self.depth]);
let parent_fingerprint_bytes = self.parent_fingerprint.to_be_bytes();
serialization.extend(&parent_fingerprint_bytes);
let child_number_bytes = self.child_number.to_be_bytes();
serialization.extend(&child_number_bytes);
let mut chaincode_bytes = [0u8; 32];
self.chain_code.0.to_big_endian(&mut chaincode_bytes);
serialization.extend(&chaincode_bytes);
serialization.extend(vec![0x00]);
let mut private_key_bytes = vec![0x00; 32];
self
.private_key
.secret
.to_big_endian(&mut private_key_bytes);
serialization.extend(private_key_bytes);
serialization
}
}
#[derive(Debug, Clone)]
pub struct HDSeed {
bytes: Vec<u8>,
}
impl HDSeed {
pub fn new(bytes: Vec<u8>) -> Self {
Self { bytes }
}
pub fn from_seed_phrase(phrase: &SeedPhrase, password: &str) -> Self {
const PBKDF2_ROUNDS: usize = 2048;
const PBKDF2_BYTES: usize = 64;
let salt = format!("mnemonic{}", password);
let mut bytes = vec![0u8; PBKDF2_BYTES];
pbkdf2::pbkdf2::<Hmac<sha2::Sha512>>(
phrase.0.as_bytes(),
salt.as_bytes(),
PBKDF2_ROUNDS,
&mut bytes,
);
Self { bytes }
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
}
#[derive(Debug, Clone)]
pub struct HDDerivationPath(String);
impl HDDerivationPath {
pub fn new(path: String) -> Self {
Self(path)
}
pub fn as_tokens(&self) -> Vec<String> {
self.0.split("/").map(String::from).collect::<Vec<String>>()
}
}
#[test]
fn test_derive_child_private_keys() {
let bytes = hex::decode("000102030405060708090a0b0c0d0e0f").unwrap();
let seed = HDSeed::new(bytes);
let mut extended_private_key = ExtendedPrivateKey::new_master(seed);
let expected_bytes = hex::decode("0488ade4000000000000000000873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d50800e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35").unwrap();
let expected = ExtendedPrivateKey::deserialize(&expected_bytes);
assert_eq!(
extended_private_key.serialize(false),
expected.serialize(false)
);
let expected_bytes = hex::decode("0488ade4013442193e8000000047fdacbd0f1097043b78c63c20c34ef4ed9a111d980047ad16282c7ae623614100edb2e14f9ee77d26dd93b4ecede8d16ed408ce149b6cd80b0715a2d911a0afea").unwrap();
let expected = ExtendedPrivateKey::deserialize(&expected_bytes);
let path = HDDerivationPath::new(String::from("m/0h"));
let child_hardened_key = extended_private_key.reconstruct_by_path(path).unwrap();
assert_eq!(
child_hardened_key.serialize(false),
expected.serialize(false)
);
let expected_bytes = hex::decode("0488ade4025c1bd648000000012a7857631386ba23dacac34180dd1983734e444fdbf774041578e9b6adb37c19003c6cb8d0f6a264c91ea8b5030fadaa8e538b020f0a387421a12de9319dc93368").unwrap();
let expected = ExtendedPrivateKey::deserialize(&expected_bytes);
let path = HDDerivationPath::new(String::from("m/0h/1"));
let child_hardened_key = extended_private_key.reconstruct_by_path(path).unwrap();
assert_eq!(
child_hardened_key.serialize(false),
expected.serialize(false)
)
}
|
/* origin: FreeBSD /usr/src/lib/msun/src/s_log1pf.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
use core::f32;
const LN2_HI: f32 = 6.9313812256e-01; /* 0x3f317180 */
const LN2_LO: f32 = 9.0580006145e-06; /* 0x3717f7d1 */
/* |(log(1+s)-log(1-s))/s - Lg(s)| < 2**-34.24 (~[-4.95e-11, 4.97e-11]). */
const LG1: f32 = 0.66666662693; /* 0xaaaaaa.0p-24 */
const LG2: f32 = 0.40000972152; /* 0xccce13.0p-25 */
const LG3: f32 = 0.28498786688; /* 0x91e9ee.0p-25 */
const LG4: f32 = 0.24279078841; /* 0xf89e26.0p-26 */
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn log1pf(x: f32) -> f32 {
let mut ui: u32 = x.to_bits();
let hfsq: f32;
let mut f: f32 = 0.;
let mut c: f32 = 0.;
let s: f32;
let z: f32;
let r: f32;
let w: f32;
let t1: f32;
let t2: f32;
let dk: f32;
let ix: u32;
let mut iu: u32;
let mut k: i32;
ix = ui;
k = 1;
if ix < 0x3ed413d0 || (ix >> 31) > 0 {
/* 1+x < sqrt(2)+ */
if ix >= 0xbf800000 {
/* x <= -1.0 */
if x == -1. {
return x / 0.0; /* log1p(-1)=+inf */
}
return (x - x) / 0.0; /* log1p(x<-1)=NaN */
}
if ix << 1 < 0x33800000 << 1 {
/* |x| < 2**-24 */
/* underflow if subnormal */
if (ix & 0x7f800000) == 0 {
force_eval!(x * x);
}
return x;
}
if ix <= 0xbe95f619 {
/* sqrt(2)/2- <= 1+x < sqrt(2)+ */
k = 0;
c = 0.;
f = x;
}
} else if ix >= 0x7f800000 {
return x;
}
if k > 0 {
ui = (1. + x).to_bits();
iu = ui;
iu += 0x3f800000 - 0x3f3504f3;
k = (iu >> 23) as i32 - 0x7f;
/* correction term ~ log(1+x)-log(u), avoid underflow in c/u */
if k < 25 {
c = if k >= 2 {
1. - (f32::from_bits(ui) - x)
} else {
x - (f32::from_bits(ui) - 1.)
};
c /= f32::from_bits(ui);
} else {
c = 0.;
}
/* reduce u into [sqrt(2)/2, sqrt(2)] */
iu = (iu & 0x007fffff) + 0x3f3504f3;
ui = iu;
f = f32::from_bits(ui) - 1.;
}
s = f / (2.0 + f);
z = s * s;
w = z * z;
t1 = w * (LG2 + w * LG4);
t2 = z * (LG1 + w * LG3);
r = t2 + t1;
hfsq = 0.5 * f * f;
dk = k as f32;
s * (hfsq + r) + (dk * LN2_LO + c) - hfsq + f + dk * LN2_HI
}
|
use super::*;
use crate::test::with_big_int;
#[test]
fn with_small_integer_divisor_with_underflow_returns_small_integer() {
with_big_int(|process, dividend| {
let divisor: Term = process.integer(2);
assert!(divisor.is_smallint());
let result = result(process, dividend, divisor);
assert!(result.is_ok());
let quotient = result.unwrap();
assert!(quotient.is_smallint());
})
}
#[test]
fn with_big_integer_divisor_with_underflow_returns_small_integer() {
with_process(|process| {
let dividend: Term = process.integer(SmallInteger::MAX_VALUE + 2);
let divisor: Term = process.integer(SmallInteger::MAX_VALUE + 1);
assert_eq!(result(process, dividend, divisor), Ok(process.integer(1)));
})
}
#[test]
fn with_big_integer_divisor_without_underflow_returns_big_integer() {
with_process(|process| {
let dividend: Term = process.integer(SmallInteger::MAX_VALUE + 1);
let divisor: Term = process.integer(SmallInteger::MAX_VALUE + 2);
assert_eq!(result(process, dividend, divisor), Ok(dividend));
})
}
|
#[link(wasm_import_module = "xyz")]
extern "C" {
fn poll_word(addr: i64, len: i32) -> i32;
}
#[no_mangle]
pub unsafe extern "C" fn do_work() {
let mut buf = [0u8; 1024];
let buf_ptr = buf.as_mut_ptr() as i64;
eprintln!("Buffer base address: {}", buf_ptr);
let len = poll_word(buf_ptr, buf.len() as i32);
let s = std::str::from_utf8(&buf[..len as usize]).unwrap();
eprintln!("RECV WORD: {}", s);
}
|
{{#with Choice~}}
{{>choice.getter use_old=../use_old}}
{{~else~}}
{{Code}}
{{~/with~}}
|
use super::{SimpleSyntaxType, SyntaxType};
use crate::ast::stat_expr_types::DataType;
pub fn explicity_type_cast<'a>(
cur_type: &SyntaxType<'a>,
dest_type: &DataType<'a>,
) -> (bool, SyntaxType<'a>) {
let cur_type = cur_type.get_v_for_vf();
let (mut is_cast_err, mut result) = implicity_type_cast(cur_type, dest_type);
match dest_type {
DataType::Int => match cur_type {
SyntaxType::Series(SimpleSyntaxType::Float) => {
is_cast_err = false;
result = SyntaxType::Series(SimpleSyntaxType::Int);
}
SyntaxType::Simple(SimpleSyntaxType::Float) => {
is_cast_err = false;
result = SyntaxType::Simple(SimpleSyntaxType::Int);
}
_ => (),
},
_ => (),
};
(is_cast_err, result)
}
pub fn implicity_type_cast<'a>(
cur_type: &SyntaxType<'a>,
dest_type: &DataType<'a>,
) -> (bool, SyntaxType<'a>) {
let mut is_cast_err = false;
let cur_type = cur_type.get_v_for_vf();
let result = match dest_type {
DataType::Bool => match cur_type {
SyntaxType::Series(SimpleSyntaxType::Int)
| SyntaxType::Series(SimpleSyntaxType::Float)
| SyntaxType::Series(SimpleSyntaxType::Bool)
| SyntaxType::Series(SimpleSyntaxType::Na) => {
SyntaxType::Series(SimpleSyntaxType::Bool)
}
SyntaxType::Series(_) => {
is_cast_err = true;
SyntaxType::Series(SimpleSyntaxType::Bool)
}
SyntaxType::Simple(SimpleSyntaxType::Int)
| SyntaxType::Simple(SimpleSyntaxType::Float)
| SyntaxType::Simple(SimpleSyntaxType::Bool)
| SyntaxType::Simple(SimpleSyntaxType::Na) => {
SyntaxType::Simple(SimpleSyntaxType::Bool)
}
_ => {
is_cast_err = true;
SyntaxType::Simple(SimpleSyntaxType::Bool)
}
},
DataType::Int => match cur_type {
SyntaxType::Series(SimpleSyntaxType::Int)
| SyntaxType::Series(SimpleSyntaxType::Na) => SyntaxType::Series(SimpleSyntaxType::Int),
SyntaxType::Series(_) => {
is_cast_err = true;
SyntaxType::Series(SimpleSyntaxType::Int)
}
SyntaxType::Simple(SimpleSyntaxType::Int)
| SyntaxType::Simple(SimpleSyntaxType::Na) => SyntaxType::Simple(SimpleSyntaxType::Int),
_ => {
is_cast_err = true;
SyntaxType::Simple(SimpleSyntaxType::Int)
}
},
DataType::Float => match cur_type {
SyntaxType::Series(SimpleSyntaxType::Int)
| SyntaxType::Series(SimpleSyntaxType::Float)
| SyntaxType::Series(SimpleSyntaxType::Na) => {
SyntaxType::Series(SimpleSyntaxType::Float)
}
SyntaxType::Series(_) => {
is_cast_err = true;
SyntaxType::Series(SimpleSyntaxType::Float)
}
SyntaxType::Simple(SimpleSyntaxType::Int)
| SyntaxType::Simple(SimpleSyntaxType::Float)
| SyntaxType::Simple(SimpleSyntaxType::Na) => {
SyntaxType::Simple(SimpleSyntaxType::Float)
}
_ => {
is_cast_err = true;
SyntaxType::Simple(SimpleSyntaxType::Float)
}
},
DataType::Color => match cur_type {
SyntaxType::Series(SimpleSyntaxType::Color) => {
SyntaxType::Series(SimpleSyntaxType::Color)
}
SyntaxType::Series(_) => {
is_cast_err = true;
SyntaxType::Series(SimpleSyntaxType::Color)
}
SyntaxType::Simple(SimpleSyntaxType::Color) => {
SyntaxType::Simple(SimpleSyntaxType::Color)
}
_ => {
is_cast_err = true;
SyntaxType::Simple(SimpleSyntaxType::Color)
}
},
DataType::String => match cur_type {
SyntaxType::Series(SimpleSyntaxType::String) => {
SyntaxType::Series(SimpleSyntaxType::String)
}
SyntaxType::Series(_) => {
is_cast_err = true;
SyntaxType::Series(SimpleSyntaxType::String)
}
SyntaxType::Simple(SimpleSyntaxType::String) => {
SyntaxType::Simple(SimpleSyntaxType::String)
}
_ => {
is_cast_err = true;
SyntaxType::Simple(SimpleSyntaxType::String)
}
},
DataType::Custom(t) => match cur_type {
SyntaxType::Series(SimpleSyntaxType::Na) => SyntaxType::ObjectClass(*t),
SyntaxType::Simple(SimpleSyntaxType::Na) => SyntaxType::ObjectClass(*t),
SyntaxType::ObjectClass(n) if n == t => SyntaxType::ObjectClass(n),
_ => {
is_cast_err = true;
SyntaxType::ObjectClass(*t)
}
},
};
(is_cast_err, result)
}
|
#[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::ADDR1H {
#[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 EMAC_ADDR1H_ADDRHIR {
bits: u16,
}
impl EMAC_ADDR1H_ADDRHIR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u16 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _EMAC_ADDR1H_ADDRHIW<'a> {
w: &'a mut W,
}
impl<'a> _EMAC_ADDR1H_ADDRHIW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits &= !(65535 << 0);
self.w.bits |= ((value as u32) & 65535) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EMAC_ADDR1H_MBCR {
bits: u8,
}
impl EMAC_ADDR1H_MBCR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _EMAC_ADDR1H_MBCW<'a> {
w: &'a mut W,
}
impl<'a> _EMAC_ADDR1H_MBCW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(63 << 24);
self.w.bits |= ((value as u32) & 63) << 24;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EMAC_ADDR1H_SAR {
bits: bool,
}
impl EMAC_ADDR1H_SAR {
#[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 _EMAC_ADDR1H_SAW<'a> {
w: &'a mut W,
}
impl<'a> _EMAC_ADDR1H_SAW<'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 << 30);
self.w.bits |= ((value as u32) & 1) << 30;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EMAC_ADDR1H_AER {
bits: bool,
}
impl EMAC_ADDR1H_AER {
#[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 _EMAC_ADDR1H_AEW<'a> {
w: &'a mut W,
}
impl<'a> _EMAC_ADDR1H_AEW<'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 << 31);
self.w.bits |= ((value as u32) & 1) << 31;
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:15 - MAC Address1 \\[47:32\\]"]
#[inline(always)]
pub fn emac_addr1h_addrhi(&self) -> EMAC_ADDR1H_ADDRHIR {
let bits = ((self.bits >> 0) & 65535) as u16;
EMAC_ADDR1H_ADDRHIR { bits }
}
#[doc = "Bits 24:29 - Mask Byte Control"]
#[inline(always)]
pub fn emac_addr1h_mbc(&self) -> EMAC_ADDR1H_MBCR {
let bits = ((self.bits >> 24) & 63) as u8;
EMAC_ADDR1H_MBCR { bits }
}
#[doc = "Bit 30 - Source Address"]
#[inline(always)]
pub fn emac_addr1h_sa(&self) -> EMAC_ADDR1H_SAR {
let bits = ((self.bits >> 30) & 1) != 0;
EMAC_ADDR1H_SAR { bits }
}
#[doc = "Bit 31 - Address Enable"]
#[inline(always)]
pub fn emac_addr1h_ae(&self) -> EMAC_ADDR1H_AER {
let bits = ((self.bits >> 31) & 1) != 0;
EMAC_ADDR1H_AER { 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:15 - MAC Address1 \\[47:32\\]"]
#[inline(always)]
pub fn emac_addr1h_addrhi(&mut self) -> _EMAC_ADDR1H_ADDRHIW {
_EMAC_ADDR1H_ADDRHIW { w: self }
}
#[doc = "Bits 24:29 - Mask Byte Control"]
#[inline(always)]
pub fn emac_addr1h_mbc(&mut self) -> _EMAC_ADDR1H_MBCW {
_EMAC_ADDR1H_MBCW { w: self }
}
#[doc = "Bit 30 - Source Address"]
#[inline(always)]
pub fn emac_addr1h_sa(&mut self) -> _EMAC_ADDR1H_SAW {
_EMAC_ADDR1H_SAW { w: self }
}
#[doc = "Bit 31 - Address Enable"]
#[inline(always)]
pub fn emac_addr1h_ae(&mut self) -> _EMAC_ADDR1H_AEW {
_EMAC_ADDR1H_AEW { w: self }
}
}
|
use std::io::BufRead;
#[derive(Debug)]
struct Policy {
min: usize,
max: usize,
letter: char,
}
#[derive(Debug)]
struct PasswordLine {
policy: Policy,
password: String,
}
fn main() {
let file = std::fs::File::open("input").unwrap();
let lines = std::io::BufReader::new(file)
.lines()
.map(|line| {
let line = line.unwrap();
let mut parts = line.split(":");
let policy: Policy = parse_policy_string(parts.next().unwrap().to_string());
let password: String = parts.next().unwrap().to_string().split_off(1);
return PasswordLine { policy, password };
})
.collect::<Vec<_>>();
println!(
"{} passwords are valid!",
lines.iter().filter(|line| is_valid(line)).count()
);
println!(
"{} passwords are valid with interpretation 2!",
lines.iter().filter(|line| is_valid_2(line)).count()
);
}
fn parse_policy_string(policy: String) -> Policy {
let mut parts = policy.split(" ");
let min_max = parts.next().unwrap();
let mut min_max_parts = min_max.split("-");
let min = min_max_parts.next().unwrap().parse::<usize>().unwrap();
let max = min_max_parts.next().unwrap().parse::<usize>().unwrap();
let letter = parts.next().unwrap().parse::<char>().unwrap();
return Policy { min, max, letter };
}
fn is_valid(PasswordLine { policy, password }: &PasswordLine) -> bool {
let count = password.chars().filter(|&c| c == policy.letter).count();
policy.min <= count && count <= policy.max
}
fn is_valid_2(PasswordLine { policy, password }: &PasswordLine) -> bool {
let chars = password.chars().collect::<Vec<_>>();
return [policy.min, policy.max]
.iter()
.map(|index| chars[index - 1] == policy.letter)
.filter(|&b| b)
.count()
== 1;
}
|
//! The unsafe `close` for raw file descriptors.
//!
//! # Safety
//!
//! Operating on raw file descriptors is unsafe.
#![allow(unsafe_code)]
use crate::backend;
use backend::fd::RawFd;
/// `close(raw_fd)`—Closes a `RawFd` directly.
///
/// Most users won't need to use this, as `OwnedFd` automatically closes its
/// file descriptor on `Drop`.
///
/// This function does not return a `Result`, as it is the [responsibility] of
/// filesystem designers to not return errors from `close`. Users who chose to
/// use NFS or similar filesystems should take care to monitor for problems
/// externally.
///
/// [responsibility]: https://lwn.net/Articles/576518/
///
/// # References
/// - [Beej's Guide to Network Programming]
/// - [POSIX]
/// - [Linux]
/// - [Apple]
/// - [Winsock2]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [Beej's Guide to Network Programming]: https://beej.us/guide/bgnet/html/split/system-calls-or-bust.html#close-and-shutdownget-outta-my-face
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/close.html
/// [Linux]: https://man7.org/linux/man-pages/man2/close.2.html
/// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/close.2.html#//apple_ref/doc/man/2/close
/// [Winsock2]: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-closesocket
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=close&sektion=2
/// [NetBSD]: https://man.netbsd.org/close.2
/// [OpenBSD]: https://man.openbsd.org/close.2
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=close§ion=2
/// [illumos]: https://illumos.org/man/2/close
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Opening-and-Closing-Files.html#index-close
///
/// # Safety
///
/// This function takes a `RawFd`, which must be valid before the call, and is
/// not valid after the call.
#[inline]
pub unsafe fn close(raw_fd: RawFd) {
backend::io::syscalls::close(raw_fd)
}
|
#[allow(unused_macros)]
macro_rules! parse_line {
[$( $x:tt : $t:ty ),+] => {
//declare variables
$( let $x: $t; )+
{
use std::str::FromStr;
// read
let mut buf = String::new();
std::io::stdin().read_line(&mut buf).unwrap();
#[allow(deprecated)]
let mut splits = buf.trim_right().split_whitespace();
// assign each variable
$(
$x = splits.next().and_then(|s| <$t>::from_str(s).ok()).unwrap();
)+
// all strs should be used for assignment
assert!(splits.next().is_none());
}
};
}
fn main() {
parse_line![a: i32, b: i32];
println!("{}", a * b,);
}
|
#[doc = "Reader of register TZSC_SECCFGR2"]
pub type R = crate::R<u32, super::TZSC_SECCFGR2>;
#[doc = "Writer for register TZSC_SECCFGR2"]
pub type W = crate::W<u32, super::TZSC_SECCFGR2>;
#[doc = "Register TZSC_SECCFGR2 `reset()`'s with value 0"]
impl crate::ResetValue for super::TZSC_SECCFGR2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `TIM8SEC`"]
pub type TIM8SEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM8SEC`"]
pub struct TIM8SEC_W<'a> {
w: &'a mut W,
}
impl<'a> TIM8SEC_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 `USART1SEC`"]
pub type USART1SEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `USART1SEC`"]
pub struct USART1SEC_W<'a> {
w: &'a mut W,
}
impl<'a> USART1SEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `TIM15SEC`"]
pub type TIM15SEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM15SEC`"]
pub struct TIM15SEC_W<'a> {
w: &'a mut W,
}
impl<'a> TIM15SEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `TIM16SEC`"]
pub type TIM16SEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM16SEC`"]
pub struct TIM16SEC_W<'a> {
w: &'a mut W,
}
impl<'a> TIM16SEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `TIM17SEC`"]
pub type TIM17SEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM17SEC`"]
pub struct TIM17SEC_W<'a> {
w: &'a mut W,
}
impl<'a> TIM17SEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `SAI1SEC`"]
pub type SAI1SEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SAI1SEC`"]
pub struct SAI1SEC_W<'a> {
w: &'a mut W,
}
impl<'a> SAI1SEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `SAI2SEC`"]
pub type SAI2SEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SAI2SEC`"]
pub struct SAI2SEC_W<'a> {
w: &'a mut W,
}
impl<'a> SAI2SEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `DFSDM1SEC`"]
pub type DFSDM1SEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DFSDM1SEC`"]
pub struct DFSDM1SEC_W<'a> {
w: &'a mut W,
}
impl<'a> DFSDM1SEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `CRCSEC`"]
pub type CRCSEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CRCSEC`"]
pub struct CRCSEC_W<'a> {
w: &'a mut W,
}
impl<'a> CRCSEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `TSCSEC`"]
pub type TSCSEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TSCSEC`"]
pub struct TSCSEC_W<'a> {
w: &'a mut W,
}
impl<'a> TSCSEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `ICACHESEC`"]
pub type ICACHESEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ICACHESEC`"]
pub struct ICACHESEC_W<'a> {
w: &'a mut W,
}
impl<'a> ICACHESEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `ADCSEC`"]
pub type ADCSEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ADCSEC`"]
pub struct ADCSEC_W<'a> {
w: &'a mut W,
}
impl<'a> ADCSEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `AESSEC`"]
pub type AESSEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `AESSEC`"]
pub struct AESSEC_W<'a> {
w: &'a mut W,
}
impl<'a> AESSEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `HASHSEC`"]
pub type HASHSEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HASHSEC`"]
pub struct HASHSEC_W<'a> {
w: &'a mut W,
}
impl<'a> HASHSEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `RNGSEC`"]
pub type RNGSEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RNGSEC`"]
pub struct RNGSEC_W<'a> {
w: &'a mut W,
}
impl<'a> RNGSEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reader of field `PKASEC`"]
pub type PKASEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PKASEC`"]
pub struct PKASEC_W<'a> {
w: &'a mut W,
}
impl<'a> PKASEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Reader of field `SDMMC1SEC`"]
pub type SDMMC1SEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SDMMC1SEC`"]
pub struct SDMMC1SEC_W<'a> {
w: &'a mut W,
}
impl<'a> SDMMC1SEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `FSMC_REGSEC`"]
pub type FSMC_REGSEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FSMC_REGSEC`"]
pub struct FSMC_REGSEC_W<'a> {
w: &'a mut W,
}
impl<'a> FSMC_REGSEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `OCTOSPI1_REGSEC`"]
pub type OCTOSPI1_REGSEC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OCTOSPI1_REGSEC`"]
pub struct OCTOSPI1_REGSEC_W<'a> {
w: &'a mut W,
}
impl<'a> OCTOSPI1_REGSEC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
impl R {
#[doc = "Bit 0 - TIM8SEC"]
#[inline(always)]
pub fn tim8sec(&self) -> TIM8SEC_R {
TIM8SEC_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - USART1SEC"]
#[inline(always)]
pub fn usart1sec(&self) -> USART1SEC_R {
USART1SEC_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - TIM15SEC"]
#[inline(always)]
pub fn tim15sec(&self) -> TIM15SEC_R {
TIM15SEC_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - TIM16SEC"]
#[inline(always)]
pub fn tim16sec(&self) -> TIM16SEC_R {
TIM16SEC_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - TIM17SEC"]
#[inline(always)]
pub fn tim17sec(&self) -> TIM17SEC_R {
TIM17SEC_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - SAI1SEC"]
#[inline(always)]
pub fn sai1sec(&self) -> SAI1SEC_R {
SAI1SEC_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - SAI2SEC"]
#[inline(always)]
pub fn sai2sec(&self) -> SAI2SEC_R {
SAI2SEC_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - DFSDM1SEC"]
#[inline(always)]
pub fn dfsdm1sec(&self) -> DFSDM1SEC_R {
DFSDM1SEC_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - CRCSEC"]
#[inline(always)]
pub fn crcsec(&self) -> CRCSEC_R {
CRCSEC_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - TSCSEC"]
#[inline(always)]
pub fn tscsec(&self) -> TSCSEC_R {
TSCSEC_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - ICACHESEC"]
#[inline(always)]
pub fn icachesec(&self) -> ICACHESEC_R {
ICACHESEC_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - ADCSEC"]
#[inline(always)]
pub fn adcsec(&self) -> ADCSEC_R {
ADCSEC_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - AESSEC"]
#[inline(always)]
pub fn aessec(&self) -> AESSEC_R {
AESSEC_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - HASHSEC"]
#[inline(always)]
pub fn hashsec(&self) -> HASHSEC_R {
HASHSEC_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - RNGSEC"]
#[inline(always)]
pub fn rngsec(&self) -> RNGSEC_R {
RNGSEC_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - PKASEC"]
#[inline(always)]
pub fn pkasec(&self) -> PKASEC_R {
PKASEC_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - SDMMC1SEC"]
#[inline(always)]
pub fn sdmmc1sec(&self) -> SDMMC1SEC_R {
SDMMC1SEC_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - FSMC_REGSEC"]
#[inline(always)]
pub fn fsmc_regsec(&self) -> FSMC_REGSEC_R {
FSMC_REGSEC_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - OCTOSPI1_REGSEC"]
#[inline(always)]
pub fn octospi1_regsec(&self) -> OCTOSPI1_REGSEC_R {
OCTOSPI1_REGSEC_R::new(((self.bits >> 18) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - TIM8SEC"]
#[inline(always)]
pub fn tim8sec(&mut self) -> TIM8SEC_W {
TIM8SEC_W { w: self }
}
#[doc = "Bit 1 - USART1SEC"]
#[inline(always)]
pub fn usart1sec(&mut self) -> USART1SEC_W {
USART1SEC_W { w: self }
}
#[doc = "Bit 2 - TIM15SEC"]
#[inline(always)]
pub fn tim15sec(&mut self) -> TIM15SEC_W {
TIM15SEC_W { w: self }
}
#[doc = "Bit 3 - TIM16SEC"]
#[inline(always)]
pub fn tim16sec(&mut self) -> TIM16SEC_W {
TIM16SEC_W { w: self }
}
#[doc = "Bit 4 - TIM17SEC"]
#[inline(always)]
pub fn tim17sec(&mut self) -> TIM17SEC_W {
TIM17SEC_W { w: self }
}
#[doc = "Bit 5 - SAI1SEC"]
#[inline(always)]
pub fn sai1sec(&mut self) -> SAI1SEC_W {
SAI1SEC_W { w: self }
}
#[doc = "Bit 6 - SAI2SEC"]
#[inline(always)]
pub fn sai2sec(&mut self) -> SAI2SEC_W {
SAI2SEC_W { w: self }
}
#[doc = "Bit 7 - DFSDM1SEC"]
#[inline(always)]
pub fn dfsdm1sec(&mut self) -> DFSDM1SEC_W {
DFSDM1SEC_W { w: self }
}
#[doc = "Bit 8 - CRCSEC"]
#[inline(always)]
pub fn crcsec(&mut self) -> CRCSEC_W {
CRCSEC_W { w: self }
}
#[doc = "Bit 9 - TSCSEC"]
#[inline(always)]
pub fn tscsec(&mut self) -> TSCSEC_W {
TSCSEC_W { w: self }
}
#[doc = "Bit 10 - ICACHESEC"]
#[inline(always)]
pub fn icachesec(&mut self) -> ICACHESEC_W {
ICACHESEC_W { w: self }
}
#[doc = "Bit 11 - ADCSEC"]
#[inline(always)]
pub fn adcsec(&mut self) -> ADCSEC_W {
ADCSEC_W { w: self }
}
#[doc = "Bit 12 - AESSEC"]
#[inline(always)]
pub fn aessec(&mut self) -> AESSEC_W {
AESSEC_W { w: self }
}
#[doc = "Bit 13 - HASHSEC"]
#[inline(always)]
pub fn hashsec(&mut self) -> HASHSEC_W {
HASHSEC_W { w: self }
}
#[doc = "Bit 14 - RNGSEC"]
#[inline(always)]
pub fn rngsec(&mut self) -> RNGSEC_W {
RNGSEC_W { w: self }
}
#[doc = "Bit 15 - PKASEC"]
#[inline(always)]
pub fn pkasec(&mut self) -> PKASEC_W {
PKASEC_W { w: self }
}
#[doc = "Bit 16 - SDMMC1SEC"]
#[inline(always)]
pub fn sdmmc1sec(&mut self) -> SDMMC1SEC_W {
SDMMC1SEC_W { w: self }
}
#[doc = "Bit 17 - FSMC_REGSEC"]
#[inline(always)]
pub fn fsmc_regsec(&mut self) -> FSMC_REGSEC_W {
FSMC_REGSEC_W { w: self }
}
#[doc = "Bit 18 - OCTOSPI1_REGSEC"]
#[inline(always)]
pub fn octospi1_regsec(&mut self) -> OCTOSPI1_REGSEC_W {
OCTOSPI1_REGSEC_W { w: self }
}
}
|
use std::error::Error;
use std::path::PathBuf;
extern crate log;
use bio::io::fasta;
use structopt::StructOpt;
use rnc_core::json_sequence::{each_sequence, Sequence};
use rnc_core::urs_taxid::UrsTaxid;
pub mod container;
use crate::container::UrsTaxidContainer;
/// This is a command to process a list of active urs_taxids and urs sequences and produce a
/// fasta file of the active urs taxids. The sequence file only needs to contain an entry for each
/// urs and the urs_taxid file may contain duplicates.
#[derive(Debug, StructOpt)]
#[structopt(rename_all = "kebab-case")]
struct Opt {
/// A file where each line is a urs_taxid, which are all active xrefs that need to be output.
/// This may contain duplicates.
#[structopt(parse(from_os_str))]
xref_urs_taxids: PathBuf,
/// A file where each line is json sequence and the id of each entry is a URS, '-' means stdin.
#[structopt(parse(from_os_str))]
filename: PathBuf,
/// File to output to, '-' means stdout.
#[structopt(parse(from_os_str))]
output: PathBuf,
}
fn main() -> Result<(), Box<dyn Error>> {
let opt = Opt::from_args();
let input = rnc_utils::buf_reader(&opt.filename)?;
let output = rnc_utils::buf_writer(&opt.output)?;
let mut writer = fasta::Writer::new(output);
let container = UrsTaxidContainer::from_path(&opt.xref_urs_taxids)?;
each_sequence(input, |sequence: Sequence| {
let urs_taxid: UrsTaxid = sequence.id.parse()?;
if container.contains(&urs_taxid) {
writer.write_record(&sequence.into())?;
}
Ok(())
})
}
|
// 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 common_exception::ErrorCode;
use common_exception::Result;
use jwt_simple::algorithms::ECDSAP256PublicKeyLike;
use jwt_simple::algorithms::ES256PublicKey;
use jwt_simple::algorithms::RS256PublicKey;
use jwt_simple::algorithms::RSAPublicKeyLike;
use jwt_simple::prelude::JWTClaims;
use jwt_simple::token::Token;
use serde::Deserialize;
use serde::Serialize;
use super::jwk;
#[derive(Debug, Clone)]
pub enum PubKey {
RSA256(RS256PublicKey),
ES256(ES256PublicKey),
}
pub struct JwtAuthenticator {
// Todo(youngsofun): verify settings, like issuer
key_stores: Vec<jwk::JwkKeyStore>,
}
#[derive(Default, Deserialize, Serialize)]
pub struct EnsureUser {
pub roles: Option<Vec<String>>,
}
#[derive(Default, Deserialize, Serialize)]
pub struct CustomClaims {
pub tenant_id: Option<String>,
pub role: Option<String>,
pub ensure_user: Option<EnsureUser>,
}
impl CustomClaims {
pub fn new() -> Self {
CustomClaims {
tenant_id: None,
role: None,
ensure_user: None,
}
}
pub fn empty(&self) -> bool {
self.role.is_none() && self.tenant_id.is_none() && self.ensure_user.is_none()
}
pub fn with_tenant_id(mut self, tenant_id: &str) -> Self {
self.tenant_id = Some(tenant_id.to_string());
self
}
pub fn with_ensure_user(mut self, ensure_user: EnsureUser) -> Self {
self.ensure_user = Some(ensure_user);
self
}
pub fn with_role(mut self, role: &str) -> Self {
self.role = Some(role.to_string());
self
}
}
impl JwtAuthenticator {
pub fn create(jwt_key_file: String, jwt_key_files: Vec<String>) -> Option<Self> {
if jwt_key_file.is_empty() && jwt_key_files.is_empty() {
return None;
}
// init a vec of key store
let mut key_stores = vec![jwk::JwkKeyStore::new(jwt_key_file)];
for u in jwt_key_files {
key_stores.push(jwk::JwkKeyStore::new(u))
}
Some(JwtAuthenticator { key_stores })
}
// parse jwt claims from single source, if custom claim is not matching on desired, claim parsed would be empty
pub async fn parse_jwt_claims_from_store(
&self,
token: &str,
key_store: &jwk::JwkKeyStore,
) -> Result<JWTClaims<CustomClaims>> {
let metadata = Token::decode_metadata(token);
let key_id = metadata.map_or(None, |e| e.key_id().map(|s| s.to_string()));
let pub_key = key_store.get_key(key_id).await?;
let r = match &pub_key {
PubKey::RSA256(pk) => pk.verify_token::<CustomClaims>(token, None),
PubKey::ES256(pk) => pk.verify_token::<CustomClaims>(token, None),
};
let c = r.map_err(|err| ErrorCode::AuthenticateFailure(err.to_string()))?;
match c.subject {
None => Err(ErrorCode::AuthenticateFailure(
"missing field `subject` in jwt",
)),
Some(_) => Ok(c),
}
}
pub async fn parse_jwt_claims(&self, token: &str) -> Result<JWTClaims<CustomClaims>> {
let mut combined_code = ErrorCode::AuthenticateFailure(
"could not decode token from all available jwt key stores. ",
);
for store in &self.key_stores {
let claim = self.parse_jwt_claims_from_store(token, store).await;
match claim {
Ok(e) => return Ok(e),
Err(e) => {
combined_code = combined_code.add_message(format!(
"message: {} , source file: {}, ",
e,
store.url()
));
continue;
}
}
}
Err(combined_code)
}
}
|
#[macro_use] extern crate lazy_static;
extern crate regex;
use regex::Regex;
use std::collections::HashMap;
fn main() {
println!("Hello, world!");
}
#[derive(Debug, PartialEq)]
enum Message {
WakesUp,
FallsAsleep,
BeginsShift(u32)
}
enum GuardState {
OffShift,
Asleep,
Awake
}
fn get_timestamp(message: &str) -> String {
lazy_static! {
static ref RE: Regex = Regex::new(r"\[(.+)\].+").unwrap();
}
let caps = RE.captures(message).unwrap();
caps[1].to_string()
}
fn sort_messages(messages: &[&str]) -> Vec<String> {
let mut sortable_messages: Vec<String> = messages.iter().map(|s| s.to_string()).collect();
sortable_messages.sort();
sortable_messages
}
fn get_minute(message: &str) -> u32 {
lazy_static! {
static ref RE: Regex = Regex::new(r"\[.+:(..)\].+").unwrap();
}
let caps = RE.captures(message).unwrap();
println!("{:?}", caps);
caps[1].to_string().parse().unwrap()
}
fn most_awake(messages: &[&str]) -> u32 {
let mut guards = HashMap::new();
let sorted_messages = sort_messages(messages);
let mut current_guard = 0;
let mut asleep_start_time = 0;
let mut time_asleep = 0;
for message in messages {
match classify_message(message) {
Message::BeginsShift(id) => {
current_guard = id;
time_asleep = 0;
},
Message::WakesUp => {
time_asleep += get_minute(message) - asleep_start_time;
guards.insert(current_guard, guards.get(¤t_guard).unwrap_or(&0) + time_asleep);
},
Message::FallsAsleep => {
asleep_start_time = get_minute(message);
}
}
}
let mut guards_asleep_time: Vec<(&u32, &u32)> = guards.iter().collect();
guards_asleep_time.sort_by(|(_, time_a), (_, time_b)| time_a.cmp(time_b));
let (&id, &time) = guards_asleep_time.last().unwrap();
id
}
fn classify_message(message: &str) -> Message {
lazy_static! {
static ref FALLS_ALSEEP_RE: Regex = Regex::new(r"\[.+\] falls asleep").unwrap();
static ref BEGINS_SHIFT_RE: Regex = Regex::new(r"\[.+\] Guard #(.+) begins shift").unwrap();
}
if FALLS_ALSEEP_RE.is_match(message) {
return Message::FallsAsleep
} else if BEGINS_SHIFT_RE.is_match(message) {
return Message::BeginsShift(BEGINS_SHIFT_RE.captures(message).unwrap()[1].to_string().parse().unwrap())
}
Message::WakesUp
}
#[test]
fn given_timestamped_message_extracts_timestamp() {
assert_eq!(get_timestamp(&"[1518-11-01 00:00] Guard #10 begins shift"), *"1518-11-01 00:00");
}
#[test]
fn test_sort_messages() {
let unsorted = vec!["[1518-11-01 00:00] Guard #10 begins shift",
"[1518-11-01 00:25] wakes up",
"[1518-11-01 00:05] falls asleep",
"[1518-10-01 00:30] falls asleep"];
assert_eq!(sort_messages(&unsorted), vec!["[1518-10-01 00:30] falls asleep",
"[1518-11-01 00:00] Guard #10 begins shift",
"[1518-11-01 00:05] falls asleep",
"[1518-11-01 00:25] wakes up"]);
}
#[test]
fn test_get_message_minute() {
assert_eq!(get_minute("[1518-11-01 00:25] wakes up"), 25);
}
#[test]
fn test_gets_guard_with_most_minutes_awake() {
let test_data = "[1518-11-01 00:00] Guard #10 begins shift
[1518-11-01 00:05] falls asleep
[1518-11-01 00:25] wakes up
[1518-11-01 00:30] falls asleep
[1518-11-01 00:55] wakes up
[1518-11-01 23:58] Guard #99 begins shift
[1518-11-02 00:40] falls asleep
[1518-11-02 00:50] wakes up
[1518-11-03 00:05] Guard #10 begins shift
[1518-11-03 00:24] falls asleep
[1518-11-03 00:29] wakes up
[1518-11-04 00:02] Guard #99 begins shift
[1518-11-04 00:36] falls asleep
[1518-11-04 00:46] wakes up
[1518-11-05 00:03] Guard #99 begins shift
[1518-11-05 00:45] falls asleep
[1518-11-05 00:55] wakes up".lines().collect::<Vec<_>>();
assert_eq!(most_awake(&test_data[..]), 10);
}
#[test]
fn test_classify_message() {
assert_eq!(classify_message("[1518-11-02 00:50] wakes up"), Message::WakesUp);
assert_eq!(classify_message("[1518-11-01 00:05] falls asleep"), Message::FallsAsleep);
assert_eq!(classify_message("[1518-11-01 00:00] Guard #10 begins shift"), Message::BeginsShift(10));
} |
/* origin: FreeBSD /usr/src/lib/msun/src/s_cbrtf.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
* Debugged and optimized by Bruce D. Evans.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* cbrtf(x)
* Return cube root of x
*/
use core::f32;
const B1: u32 = 709958130; /* B1 = (127-127.0/3-0.03306235651)*2**23 */
const B2: u32 = 642849266; /* B2 = (127-127.0/3-24/3-0.03306235651)*2**23 */
/// Cube root (f32)
///
/// Computes the cube root of the argument.
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn cbrtf(x: f32) -> f32 {
let x1p24 = f32::from_bits(0x4b800000); // 0x1p24f === 2 ^ 24
let mut r: f64;
let mut t: f64;
let mut ui: u32 = x.to_bits();
let mut hx: u32 = ui & 0x7fffffff;
if hx >= 0x7f800000 {
/* cbrt(NaN,INF) is itself */
return x + x;
}
/* rough cbrt to 5 bits */
if hx < 0x00800000 {
/* zero or subnormal? */
if hx == 0 {
return x; /* cbrt(+-0) is itself */
}
ui = (x * x1p24).to_bits();
hx = ui & 0x7fffffff;
hx = hx / 3 + B2;
} else {
hx = hx / 3 + B1;
}
ui &= 0x80000000;
ui |= hx;
/*
* First step Newton iteration (solving t*t-x/t == 0) to 16 bits. In
* double precision so that its terms can be arranged for efficiency
* without causing overflow or underflow.
*/
t = f32::from_bits(ui) as f64;
r = t * t * t;
t = t * (x as f64 + x as f64 + r) / (x as f64 + r + r);
/*
* Second step Newton iteration to 47 bits. In double precision for
* efficiency and accuracy.
*/
r = t * t * t;
t = t * (x as f64 + x as f64 + r) / (x as f64 + r + r);
/* rounding to 24 bits is perfect in round-to-nearest mode */
t as f32
}
|
use futures::stream::{TryStream, TryStreamExt};
use std::error::Error as StdError;
use warp::http::header::{HeaderValue, CONTENT_TYPE, TRAILER};
use warp::http::Response;
use warp::hyper::body::Bytes;
use warp::hyper::Body;
use warp::Reply;
pub struct StreamResponse<S>(pub S);
impl<S> Reply for StreamResponse<S>
where
S: TryStream + Send + 'static,
S::Ok: Into<Bytes>,
S::Error: StdError + Send + Sync + 'static,
{
fn into_response(self) -> warp::reply::Response {
// while it may seem like the S::Error is handled somehow it currently just means the
// response will stop. hopefully later it can be used to become trailer headers.
let mut resp = Response::new(Body::wrap_stream(self.0.into_stream()));
let headers = resp.headers_mut();
// FIXME: unable to send this header with warp/hyper right now
headers.insert(TRAILER, HeaderValue::from_static("X-Stream-Error"));
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
headers.insert("X-Chunked-Output", HeaderValue::from_static("1"));
resp
}
}
|
use std::io::prelude::*;
use std::fs::File;
use std::io::BufReader;
use std::collections::HashSet;
fn swap(v: &mut Vec<u8>, i:usize, j:usize){
let swap = v[i];
v[i]=v[j];
v[j] =swap;
}
///idx is the hold index
///iterate and swap until no longer able to
fn permute(input: &mut String, hold: u32, results: &mut HashSet<String>){
if hold == input.len() as u32{
return;
}
let mut bytes = input.clone().into_bytes();
for i in 0..(input.len()) as u32{
swap(&mut (bytes), i as usize, hold as usize);
results.insert(String::from_utf8(bytes.clone()).unwrap());
if i != hold{
permute(&mut(String::from_utf8(bytes.clone()).unwrap()), hold+1, results);
}
swap(&mut bytes, i as usize, hold as usize);
}
}
pub fn solution(){
let input_file = File::open("input/next_largest_number.input").unwrap();
let reader = BufReader::new(input_file);
let inputs: Vec<String> = reader.lines().map(|x| x.unwrap()).collect();
for input in inputs{
let mut input = input.trim().to_string();
let mut combinations: HashSet<String> = HashSet::new();
permute(&mut input, 0, &mut combinations);
//compare strings to allow arbitrary input. digits should still compare the same
//even as chars
let result: &str = combinations.iter()
.filter(|x| *x > &input )
.min().unwrap();
println!("smallest greater than {} : {} ", input, result);
}
}
|
::windows_sys::core::link ! ( "websocket.dll""system" #[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"] fn WebSocketAbortHandle ( hwebsocket : WEB_SOCKET_HANDLE ) -> ( ) );
::windows_sys::core::link ! ( "websocket.dll""system" #[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"] fn WebSocketBeginClientHandshake ( hwebsocket : WEB_SOCKET_HANDLE , pszsubprotocols : *const :: windows_sys::core::PCSTR , ulsubprotocolcount : u32 , pszextensions : *const :: windows_sys::core::PCSTR , ulextensioncount : u32 , pinitialheaders : *const WEB_SOCKET_HTTP_HEADER , ulinitialheadercount : u32 , padditionalheaders : *mut *mut WEB_SOCKET_HTTP_HEADER , puladditionalheadercount : *mut u32 ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "websocket.dll""system" #[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"] fn WebSocketBeginServerHandshake ( hwebsocket : WEB_SOCKET_HANDLE , pszsubprotocolselected : :: windows_sys::core::PCSTR , pszextensionselected : *const :: windows_sys::core::PCSTR , ulextensionselectedcount : u32 , prequestheaders : *const WEB_SOCKET_HTTP_HEADER , ulrequestheadercount : u32 , presponseheaders : *mut *mut WEB_SOCKET_HTTP_HEADER , pulresponseheadercount : *mut u32 ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "websocket.dll""system" #[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"] fn WebSocketCompleteAction ( hwebsocket : WEB_SOCKET_HANDLE , pvactioncontext : *const ::core::ffi::c_void , ulbytestransferred : u32 ) -> ( ) );
::windows_sys::core::link ! ( "websocket.dll""system" #[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"] fn WebSocketCreateClientHandle ( pproperties : *const WEB_SOCKET_PROPERTY , ulpropertycount : u32 , phwebsocket : *mut WEB_SOCKET_HANDLE ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "websocket.dll""system" #[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"] fn WebSocketCreateServerHandle ( pproperties : *const WEB_SOCKET_PROPERTY , ulpropertycount : u32 , phwebsocket : *mut WEB_SOCKET_HANDLE ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "websocket.dll""system" #[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"] fn WebSocketDeleteHandle ( hwebsocket : WEB_SOCKET_HANDLE ) -> ( ) );
::windows_sys::core::link ! ( "websocket.dll""system" #[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"] fn WebSocketEndClientHandshake ( hwebsocket : WEB_SOCKET_HANDLE , presponseheaders : *const WEB_SOCKET_HTTP_HEADER , ulreponseheadercount : u32 , pulselectedextensions : *mut u32 , pulselectedextensioncount : *mut u32 , pulselectedsubprotocol : *mut u32 ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "websocket.dll""system" #[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"] fn WebSocketEndServerHandshake ( hwebsocket : WEB_SOCKET_HANDLE ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "websocket.dll""system" #[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"] fn WebSocketGetAction ( hwebsocket : WEB_SOCKET_HANDLE , eactionqueue : WEB_SOCKET_ACTION_QUEUE , pdatabuffers : *mut WEB_SOCKET_BUFFER , puldatabuffercount : *mut u32 , paction : *mut WEB_SOCKET_ACTION , pbuffertype : *mut WEB_SOCKET_BUFFER_TYPE , pvapplicationcontext : *mut *mut ::core::ffi::c_void , pvactioncontext : *mut *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "websocket.dll""system" #[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"] fn WebSocketGetGlobalProperty ( etype : WEB_SOCKET_PROPERTY_TYPE , pvvalue : *mut ::core::ffi::c_void , ulsize : *mut u32 ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "websocket.dll""system" #[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"] fn WebSocketReceive ( hwebsocket : WEB_SOCKET_HANDLE , pbuffer : *const WEB_SOCKET_BUFFER , pvcontext : *const ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "websocket.dll""system" #[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"] fn WebSocketSend ( hwebsocket : WEB_SOCKET_HANDLE , buffertype : WEB_SOCKET_BUFFER_TYPE , pbuffer : *const WEB_SOCKET_BUFFER , context : *const ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_MAX_CLOSE_REASON_LENGTH: u32 = 123u32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub type WEB_SOCKET_ACTION = i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_NO_ACTION: WEB_SOCKET_ACTION = 0i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_SEND_TO_NETWORK_ACTION: WEB_SOCKET_ACTION = 1i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_INDICATE_SEND_COMPLETE_ACTION: WEB_SOCKET_ACTION = 2i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_RECEIVE_FROM_NETWORK_ACTION: WEB_SOCKET_ACTION = 3i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_INDICATE_RECEIVE_COMPLETE_ACTION: WEB_SOCKET_ACTION = 4i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub type WEB_SOCKET_ACTION_QUEUE = i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_SEND_ACTION_QUEUE: WEB_SOCKET_ACTION_QUEUE = 1i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_RECEIVE_ACTION_QUEUE: WEB_SOCKET_ACTION_QUEUE = 2i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_ALL_ACTION_QUEUE: WEB_SOCKET_ACTION_QUEUE = 3i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub type WEB_SOCKET_BUFFER_TYPE = i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE: WEB_SOCKET_BUFFER_TYPE = -2147483648i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE: WEB_SOCKET_BUFFER_TYPE = -2147483647i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE: WEB_SOCKET_BUFFER_TYPE = -2147483646i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE: WEB_SOCKET_BUFFER_TYPE = -2147483645i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_CLOSE_BUFFER_TYPE: WEB_SOCKET_BUFFER_TYPE = -2147483644i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_PING_PONG_BUFFER_TYPE: WEB_SOCKET_BUFFER_TYPE = -2147483643i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_UNSOLICITED_PONG_BUFFER_TYPE: WEB_SOCKET_BUFFER_TYPE = -2147483642i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub type WEB_SOCKET_CLOSE_STATUS = i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_SUCCESS_CLOSE_STATUS: WEB_SOCKET_CLOSE_STATUS = 1000i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_ENDPOINT_UNAVAILABLE_CLOSE_STATUS: WEB_SOCKET_CLOSE_STATUS = 1001i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_PROTOCOL_ERROR_CLOSE_STATUS: WEB_SOCKET_CLOSE_STATUS = 1002i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_INVALID_DATA_TYPE_CLOSE_STATUS: WEB_SOCKET_CLOSE_STATUS = 1003i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_EMPTY_CLOSE_STATUS: WEB_SOCKET_CLOSE_STATUS = 1005i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_ABORTED_CLOSE_STATUS: WEB_SOCKET_CLOSE_STATUS = 1006i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_INVALID_PAYLOAD_CLOSE_STATUS: WEB_SOCKET_CLOSE_STATUS = 1007i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_POLICY_VIOLATION_CLOSE_STATUS: WEB_SOCKET_CLOSE_STATUS = 1008i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_MESSAGE_TOO_BIG_CLOSE_STATUS: WEB_SOCKET_CLOSE_STATUS = 1009i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_UNSUPPORTED_EXTENSIONS_CLOSE_STATUS: WEB_SOCKET_CLOSE_STATUS = 1010i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_SERVER_ERROR_CLOSE_STATUS: WEB_SOCKET_CLOSE_STATUS = 1011i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_SECURE_HANDSHAKE_ERROR_CLOSE_STATUS: WEB_SOCKET_CLOSE_STATUS = 1015i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub type WEB_SOCKET_PROPERTY_TYPE = i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_RECEIVE_BUFFER_SIZE_PROPERTY_TYPE: WEB_SOCKET_PROPERTY_TYPE = 0i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_SEND_BUFFER_SIZE_PROPERTY_TYPE: WEB_SOCKET_PROPERTY_TYPE = 1i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_DISABLE_MASKING_PROPERTY_TYPE: WEB_SOCKET_PROPERTY_TYPE = 2i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_ALLOCATED_BUFFER_PROPERTY_TYPE: WEB_SOCKET_PROPERTY_TYPE = 3i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_DISABLE_UTF8_VERIFICATION_PROPERTY_TYPE: WEB_SOCKET_PROPERTY_TYPE = 4i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_KEEPALIVE_INTERVAL_PROPERTY_TYPE: WEB_SOCKET_PROPERTY_TYPE = 5i32;
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub const WEB_SOCKET_SUPPORTED_VERSIONS_PROPERTY_TYPE: WEB_SOCKET_PROPERTY_TYPE = 6i32;
#[repr(C)]
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub union WEB_SOCKET_BUFFER {
pub Data: WEB_SOCKET_BUFFER_1,
pub CloseStatus: WEB_SOCKET_BUFFER_0,
}
impl ::core::marker::Copy for WEB_SOCKET_BUFFER {}
impl ::core::clone::Clone for WEB_SOCKET_BUFFER {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub struct WEB_SOCKET_BUFFER_0 {
pub pbReason: *mut u8,
pub ulReasonLength: u32,
pub usStatus: u16,
}
impl ::core::marker::Copy for WEB_SOCKET_BUFFER_0 {}
impl ::core::clone::Clone for WEB_SOCKET_BUFFER_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub struct WEB_SOCKET_BUFFER_1 {
pub pbBuffer: *mut u8,
pub ulBufferLength: u32,
}
impl ::core::marker::Copy for WEB_SOCKET_BUFFER_1 {}
impl ::core::clone::Clone for WEB_SOCKET_BUFFER_1 {
fn clone(&self) -> Self {
*self
}
}
pub type WEB_SOCKET_HANDLE = isize;
#[repr(C)]
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub struct WEB_SOCKET_HTTP_HEADER {
pub pcName: ::windows_sys::core::PSTR,
pub ulNameLength: u32,
pub pcValue: ::windows_sys::core::PSTR,
pub ulValueLength: u32,
}
impl ::core::marker::Copy for WEB_SOCKET_HTTP_HEADER {}
impl ::core::clone::Clone for WEB_SOCKET_HTTP_HEADER {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Networking_WebSocket\"`*"]
pub struct WEB_SOCKET_PROPERTY {
pub Type: WEB_SOCKET_PROPERTY_TYPE,
pub pvValue: *mut ::core::ffi::c_void,
pub ulValueSize: u32,
}
impl ::core::marker::Copy for WEB_SOCKET_PROPERTY {}
impl ::core::clone::Clone for WEB_SOCKET_PROPERTY {
fn clone(&self) -> Self {
*self
}
}
|
//! Delays
use core::convert::Infallible;
use embedded_hal::blocking::delay::{DelayMs, DelayUs};
/// Use RISCV machine-mode cycle counter (`mcycle`) as a delay provider.
///
/// This can be used for high resolution delays for device initialization,
/// bit-banging protocols, etc
#[derive(Copy, Clone)]
pub struct McycleDelay {
core_frequency: u32,
}
impl McycleDelay {
/// Constructs the delay provider based on core clock frequency `freq`
pub fn new(freq: u32) -> Self {
Self {
/// System clock frequency, used to convert clock cycles
/// into real-world time values
core_frequency: freq,
}
}
/// Retrieves the cycle count for the current HART
#[inline]
pub fn get_cycle_count() -> u64 {
riscv::register::mcycle::read64()
}
/// Returns the number of elapsed cycles since `previous_cycle_count`
#[inline]
pub fn cycles_since(previous_cycle_count: u64) -> u64 {
riscv::register::mcycle::read64().wrapping_sub(previous_cycle_count)
}
/// Performs a busy-wait loop until the number of cycles `cycle_count` has elapsed
#[inline]
pub fn delay_cycles(cycle_count: u64) {
let start_cycle_count = McycleDelay::get_cycle_count();
while McycleDelay::cycles_since(start_cycle_count) <= cycle_count {}
}
}
impl DelayUs<u64> for McycleDelay {
type Error = Infallible;
/// Performs a busy-wait loop until the number of microseconds `us` has elapsed
#[inline]
fn try_delay_us(&mut self, us: u64) -> Result<(), Infallible> {
McycleDelay::delay_cycles((us * (self.core_frequency as u64)) / 1_000_000);
Ok(())
}
}
impl DelayMs<u64> for McycleDelay {
type Error = Infallible;
/// Performs a busy-wait loop until the number of milliseconds `ms` has elapsed
#[inline]
fn try_delay_ms(&mut self, ms: u64) -> Result<(), Infallible> {
McycleDelay::delay_cycles((ms * (self.core_frequency as u64)) / 1000);
Ok(())
}
}
|
#![deny(warnings)]
extern crate futures;
extern crate loom;
#[path = "../src/oneshot.rs"]
#[allow(warnings)]
mod oneshot;
use futures::{Async, Future};
use loom::futures::block_on;
use loom::thread;
#[test]
fn smoke() {
loom::fuzz(|| {
let (tx, rx) = oneshot::channel();
thread::spawn(move || {
tx.send(1).unwrap();
});
let value = block_on(rx).unwrap();
assert_eq!(1, value);
});
}
#[test]
fn changing_rx_task() {
loom::fuzz(|| {
let (tx, mut rx) = oneshot::channel();
thread::spawn(move || {
tx.send(1).unwrap();
});
let rx = thread::spawn(move || {
let t1 = block_on(futures::future::poll_fn(|| Ok::<_, ()>(rx.poll().into()))).unwrap();
match t1 {
Ok(Async::Ready(value)) => {
// ok
assert_eq!(1, value);
None
}
Ok(Async::NotReady) => Some(rx),
Err(_) => unreachable!(),
}
})
.join()
.unwrap();
if let Some(rx) = rx {
// Previous task parked, use a new task...
let value = block_on(rx).unwrap();
assert_eq!(1, value);
}
});
}
#[test]
fn changing_tx_task() {
loom::fuzz(|| {
let (mut tx, rx) = oneshot::channel::<i32>();
thread::spawn(move || {
drop(rx);
});
let tx = thread::spawn(move || {
let t1 = block_on(futures::future::poll_fn(|| {
Ok::<_, ()>(tx.poll_close().into())
}))
.unwrap();
match t1 {
Ok(Async::Ready(())) => None,
Ok(Async::NotReady) => Some(tx),
Err(_) => unreachable!(),
}
})
.join()
.unwrap();
if let Some(mut tx) = tx {
// Previous task parked, use a new task...
block_on(futures::future::poll_fn(move || tx.poll_close())).unwrap();
}
});
}
|
//! Module providing the TermLogger Implementation
use log::{
set_boxed_logger, set_max_level, Level, LevelFilter, Log, Metadata, Record, SetLoggerError,
};
use std::io::{Error, Write};
use std::sync::Mutex;
use termcolor::{BufferedStandardStream, ColorChoice};
#[cfg(not(feature = "ansi_term"))]
use termcolor::{ColorSpec, WriteColor};
use super::logging::*;
use crate::{Config, SharedLogger, ThreadLogMode};
struct OutputStreams {
err: BufferedStandardStream,
out: BufferedStandardStream,
}
/// Specifies which streams should be used when logging
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum TerminalMode {
/// Only use Stdout
Stdout,
/// Only use Stderr
Stderr,
/// Use Stderr for Errors and Stdout otherwise
Mixed,
}
impl Default for TerminalMode {
fn default() -> TerminalMode {
TerminalMode::Mixed
}
}
/// The TermLogger struct. Provides a stderr/out based Logger implementation
///
/// Supports colored output
pub struct TermLogger {
level: LevelFilter,
config: Config,
streams: Mutex<OutputStreams>,
}
impl TermLogger {
/// init function. Globally initializes the TermLogger as the one and only used log facility.
///
/// Takes the desired `Level` and `Config` as arguments. They cannot be changed later on.
/// Fails if another Logger was already initialized
///
/// # Examples
/// ```
/// # extern crate simplelog;
/// # use simplelog::*;
/// # fn main() {
/// TermLogger::init(
/// LevelFilter::Info,
/// Config::default(),
/// TerminalMode::Mixed,
/// ColorChoice::Auto
/// );
/// # }
/// ```
pub fn init(
log_level: LevelFilter,
config: Config,
mode: TerminalMode,
color_choice: ColorChoice,
) -> Result<(), SetLoggerError> {
let logger = TermLogger::new(log_level, config, mode, color_choice);
set_max_level(log_level);
set_boxed_logger(logger)?;
Ok(())
}
/// allows to create a new logger, that can be independently used, no matter whats globally set.
///
/// no macros are provided for this case and you probably
/// dont want to use this function, but `init()`, if you dont want to build a `CombinedLogger`.
///
/// Takes the desired `Level` and `Config` as arguments. They cannot be changed later on.
///
/// Returns a `Box`ed TermLogger
///
/// # Examples
/// ```
/// # extern crate simplelog;
/// # use simplelog::*;
/// # fn main() {
/// let term_logger = TermLogger::new(
/// LevelFilter::Info,
/// Config::default(),
/// TerminalMode::Mixed,
/// ColorChoice::Auto
/// );
/// # }
/// ```
#[must_use]
pub fn new(
log_level: LevelFilter,
config: Config,
mode: TerminalMode,
color_choice: ColorChoice,
) -> Box<TermLogger> {
let streams = match mode {
TerminalMode::Stdout => OutputStreams {
err: BufferedStandardStream::stdout(color_choice),
out: BufferedStandardStream::stdout(color_choice),
},
TerminalMode::Stderr => OutputStreams {
err: BufferedStandardStream::stderr(color_choice),
out: BufferedStandardStream::stderr(color_choice),
},
TerminalMode::Mixed => OutputStreams {
err: BufferedStandardStream::stderr(color_choice),
out: BufferedStandardStream::stdout(color_choice),
},
};
Box::new(TermLogger {
level: log_level,
config,
streams: Mutex::new(streams),
})
}
fn try_log_term(
&self,
record: &Record<'_>,
term_lock: &mut BufferedStandardStream,
) -> Result<(), Error> {
#[cfg(not(feature = "ansi_term"))]
let color = self.config.level_color[record.level() as usize];
if self.config.time <= record.level() && self.config.time != LevelFilter::Off {
write_time(term_lock, &self.config)?;
}
if self.config.level <= record.level() && self.config.level != LevelFilter::Off {
#[cfg(not(feature = "ansi_term"))]
if !self.config.write_log_enable_colors {
term_lock.set_color(ColorSpec::new().set_fg(color))?;
}
write_level(record, term_lock, &self.config)?;
#[cfg(not(feature = "ansi_term"))]
if !self.config.write_log_enable_colors {
term_lock.reset()?;
}
}
if self.config.thread <= record.level() && self.config.thread != LevelFilter::Off {
match self.config.thread_log_mode {
ThreadLogMode::IDs => {
write_thread_id(term_lock, &self.config)?;
}
ThreadLogMode::Names | ThreadLogMode::Both => {
write_thread_name(term_lock, &self.config)?;
}
}
}
if self.config.target <= record.level() && self.config.target != LevelFilter::Off {
write_target(record, term_lock, &self.config)?;
}
if self.config.location <= record.level() && self.config.location != LevelFilter::Off {
write_location(record, term_lock)?;
}
if self.config.module <= record.level() && self.config.module != LevelFilter::Off {
write_module(record, term_lock)?;
}
#[cfg(feature = "paris")]
write_args(record, term_lock, self.config.enable_paris_formatting)?;
#[cfg(not(feature = "paris"))]
write_args(record, term_lock)?;
// The log crate holds the logger as a `static mut`, which isn't dropped
// at program exit: https://doc.rust-lang.org/reference/items/static-items.html
// Sadly, this means we can't rely on the BufferedStandardStreams flushing
// themselves on the way out, so to avoid the Case of the Missing 8k,
// flush each entry.
term_lock.flush()
}
fn try_log(&self, record: &Record<'_>) -> Result<(), Error> {
if self.enabled(record.metadata()) {
if should_skip(&self.config, record) {
return Ok(());
}
let mut streams = self.streams.lock().unwrap();
if record.level() == Level::Error {
self.try_log_term(record, &mut streams.err)
} else {
self.try_log_term(record, &mut streams.out)
}
} else {
Ok(())
}
}
}
impl Log for TermLogger {
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
metadata.level() <= self.level
}
fn log(&self, record: &Record<'_>) {
let _ = self.try_log(record);
}
fn flush(&self) {
let mut streams = self.streams.lock().unwrap();
let _ = streams.out.flush();
let _ = streams.err.flush();
}
}
impl SharedLogger for TermLogger {
fn level(&self) -> LevelFilter {
self.level
}
fn config(&self) -> Option<&Config> {
Some(&self.config)
}
fn as_log(self: Box<Self>) -> Box<dyn Log> {
Box::new(*self)
}
}
|
// Issue #53
fn main() {
alt "test" { "not-test" { fail; } "test" { } _ { fail; } }
tag t { tag1(str); tag2; }
alt tag1("test") {
tag2. { fail; }
tag1("not-test") { fail; }
tag1("test") { }
_ { fail; }
}
} |
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use base64::engine::general_purpose;
use base64::prelude::*;
use common_exception::ErrorCode;
use common_exception::Result;
use jwt_simple::prelude::ES256PublicKey;
use jwt_simple::prelude::RS256PublicKey;
use p256::EncodedPoint;
use p256::FieldBytes;
use parking_lot::RwLock;
use serde::Deserialize;
use serde::Serialize;
use super::PubKey;
const JWK_REFRESH_INTERVAL: u64 = 15;
#[derive(Debug, Serialize, Deserialize)]
pub struct JwkKey {
pub kid: String,
pub kty: String,
pub alg: Option<String>,
/// (Modulus) Parameter for kty `RSA`.
#[serde(default)]
pub n: String,
/// (Exponent) Parameter for kty `RSA`.
#[serde(default)]
pub e: String,
/// (X Coordinate) Parameter for kty `EC`
#[serde(default)]
pub x: String,
/// (Y Coordinate) Parameter for kty `EC`
#[serde(default)]
pub y: String,
}
fn decode(v: &str) -> Result<Vec<u8>> {
general_purpose::URL_SAFE_NO_PAD
.decode(v.as_bytes())
.map_err(|e| ErrorCode::InvalidConfig(e.to_string()))
}
impl JwkKey {
fn get_public_key(&self) -> Result<PubKey> {
match self.kty.as_str() {
// Todo(youngsofun): the "alg" field is optional, maybe we need a config for it
"RSA" => {
let k = RS256PublicKey::from_components(&decode(&self.n)?, &decode(&self.e)?)?;
Ok(PubKey::RSA256(k))
}
"EC" => {
// borrowed from https://github.com/RustCrypto/traits/blob/master/elliptic-curve/src/jwk.rs#L68
let xs = decode(&self.x)?;
let x = FieldBytes::from_slice(&xs);
let ys = decode(&self.y)?;
let y = FieldBytes::from_slice(&ys);
let ep = EncodedPoint::from_affine_coordinates(x, y, false);
let k = ES256PublicKey::from_bytes(ep.as_bytes())?;
Ok(PubKey::ES256(k))
}
_ => Err(ErrorCode::InvalidConfig(format!(
" current not support jwk with typ={:?}",
self.kty
))),
}
}
}
#[derive(Deserialize, Serialize)]
pub struct JwkKeys {
pub keys: Vec<JwkKey>,
}
pub struct JwkKeyStore {
url: String,
keys: Arc<RwLock<HashMap<String, PubKey>>>,
last_refreshed_at: RwLock<Option<Instant>>,
refresh_interval: Duration,
}
impl JwkKeyStore {
pub fn new(url: String) -> Self {
let refresh_interval = Duration::from_secs(JWK_REFRESH_INTERVAL * 60);
let keys = Arc::new(RwLock::new(HashMap::new()));
Self {
url,
keys,
refresh_interval,
last_refreshed_at: RwLock::new(None),
}
}
pub fn url(&self) -> String {
self.url.clone()
}
}
impl JwkKeyStore {
async fn load_keys(&self) -> Result<()> {
let response = reqwest::get(&self.url).await.map_err(|e| {
ErrorCode::AuthenticateFailure(format!("Could not download JWKS: {}", e))
})?;
let body = response.text().await.unwrap();
let jwk_keys = serde_json::from_str::<JwkKeys>(&body)
.map_err(|e| ErrorCode::InvalidConfig(format!("Failed to parse keys: {}", e)))?;
let mut new_keys: HashMap<String, PubKey> = HashMap::new();
for k in &jwk_keys.keys {
new_keys.insert(k.kid.to_string(), k.get_public_key()?);
}
let mut keys = self.keys.write();
*keys = new_keys;
Ok(())
}
async fn maybe_reload_keys(&self) -> Result<()> {
let need_reload = {
let last_refreshed_at = *self.last_refreshed_at.read();
last_refreshed_at.is_none()
|| last_refreshed_at.unwrap().elapsed() > self.refresh_interval
};
if need_reload {
self.load_keys().await?;
self.last_refreshed_at.write().replace(Instant::now());
}
Ok(())
}
pub(super) async fn get_key(&self, key_id: Option<String>) -> Result<PubKey> {
self.maybe_reload_keys().await?;
let keys = self.keys.read();
match key_id {
Some(kid) => match keys.get(&kid) {
None => Err(ErrorCode::AuthenticateFailure(format!(
"key id {} not found",
&kid
))),
Some(k) => Ok((*k).clone()),
},
None => {
if keys.len() != 1 {
Err(ErrorCode::AuthenticateFailure(
"must specify key_id for jwt when multi keys exists ",
))
} else {
Ok((*keys.iter().next().unwrap().1).clone())
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.