text stringlengths 8 4.13M |
|---|
pub mod game;
pub mod inning;
pub mod inning_half;
|
use std::sync::Arc;
use gltf::texture::{
MagFilter,
MinFilter,
};
use smallvec::SmallVec;
use sourcerenderer_core::graphics::{
AddressMode,
AttachmentBlendInfo,
AttachmentInfo,
Backend,
Barrier,
BarrierAccess,
BarrierSync,
BarrierTextureRange,
BindingFrequency,
BlendInfo,
CommandBuffer,
CompareFunc,
CullMode,
DepthStencilAttachmentRef,
DepthStencilInfo,
Device,
FillMode,
Filter,
Format,
FrontFace,
IndexFormat,
InputAssemblerElement,
InputRate,
LoadOp,
LogicOp,
OutputAttachmentRef,
PipelineBinding,
PrimitiveType,
RasterizerInfo,
RenderPassAttachment,
RenderPassAttachmentView,
RenderPassBeginInfo,
RenderPassInfo,
RenderpassRecordingMode,
SampleCount,
SamplerInfo,
Scissor,
ShaderInputElement,
ShaderType,
StencilInfo,
StoreOp,
SubpassInfo,
Swapchain,
Texture,
TextureDimension,
TextureInfo,
TextureLayout,
TextureUsage,
TextureView,
TextureViewInfo,
VertexLayoutInfo,
Viewport,
WHOLE_BUFFER,
};
use sourcerenderer_core::{
Platform,
Vec2,
Vec2I,
Vec2UI,
};
use crate::renderer::drawable::View;
use crate::renderer::renderer_assets::{
RendererAssets,
RendererMaterial,
RendererMaterialValue,
};
use crate::renderer::renderer_resources::{
HistoryResourceEntry,
RendererResources,
};
use crate::renderer::renderer_scene::RendererScene;
use crate::renderer::shader_manager::{
GraphicsPipelineHandle,
GraphicsPipelineInfo,
ShaderManager,
};
pub struct GeometryPass<P: Platform> {
pipeline: GraphicsPipelineHandle,
sampler: Arc<<P::GraphicsBackend as Backend>::Sampler>,
}
impl<P: Platform> GeometryPass<P> {
pub const DEPTH_TEXTURE_NAME: &'static str = "Depth";
pub(super) fn new(
device: &Arc<<P::GraphicsBackend as Backend>::Device>,
swapchain: &Arc<<P::GraphicsBackend as Backend>::Swapchain>,
_init_cmd_buffer: &mut <P::GraphicsBackend as Backend>::CommandBuffer,
resources: &mut RendererResources<P::GraphicsBackend>,
shader_manager: &mut ShaderManager<P>,
) -> Self {
let sampler = device.create_sampler(&SamplerInfo {
mag_filter: Filter::Linear,
min_filter: Filter::Linear,
mip_filter: Filter::Linear,
address_mode_u: AddressMode::Repeat,
address_mode_v: AddressMode::Repeat,
address_mode_w: AddressMode::ClampToEdge,
mip_bias: 0.0f32,
max_anisotropy: 0.0f32,
compare_op: None,
min_lod: 0.0f32,
max_lod: None,
});
resources.create_texture(
Self::DEPTH_TEXTURE_NAME,
&TextureInfo {
dimension: TextureDimension::Dim2D,
format: Format::D32,
width: swapchain.width(),
height: swapchain.height(),
depth: 1,
mip_levels: 1,
array_length: 1,
samples: SampleCount::Samples1,
usage: TextureUsage::DEPTH_STENCIL,
supports_srgb: false,
},
false,
);
let shader_file_extension = if cfg!(target_family = "wasm") {
"glsl"
} else {
"spv"
};
let fs_name = format!("shaders/web_geometry.web.frag.{}", shader_file_extension);
let pipeline_info: GraphicsPipelineInfo = GraphicsPipelineInfo {
vs: &format!("shaders/web_geometry.web.vert.{}", shader_file_extension),
fs: Some(&fs_name),
primitive_type: PrimitiveType::Triangles,
vertex_layout: VertexLayoutInfo {
input_assembler: &[InputAssemblerElement {
binding: 0,
stride: 64,
input_rate: InputRate::PerVertex,
}],
shader_inputs: &[
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 0,
semantic_name_d3d: String::from(""),
semantic_index_d3d: 0,
offset: 0,
format: Format::RGB32Float,
},
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 1,
semantic_name_d3d: String::from(""),
semantic_index_d3d: 0,
offset: 16,
format: Format::RGB32Float,
},
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 2,
semantic_name_d3d: String::from(""),
semantic_index_d3d: 0,
offset: 32,
format: Format::RG32Float,
},
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 3,
semantic_name_d3d: String::from(""),
semantic_index_d3d: 0,
offset: 40,
format: Format::RG32Float,
},
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 4,
semantic_name_d3d: String::from(""),
semantic_index_d3d: 0,
offset: 48,
format: Format::R32Float,
},
],
},
rasterizer: RasterizerInfo {
fill_mode: FillMode::Fill,
cull_mode: CullMode::Back,
front_face: FrontFace::Clockwise,
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: 0u8,
stencil_write_mask: 0u8,
stencil_front: StencilInfo::default(),
stencil_back: StencilInfo::default(),
},
blend: BlendInfo {
alpha_to_coverage_enabled: false,
logic_op_enabled: false,
logic_op: LogicOp::And,
constants: [0f32, 0f32, 0f32, 0f32],
attachments: &[AttachmentBlendInfo::default()],
},
};
let pipeline = shader_manager.request_graphics_pipeline(
&pipeline_info,
&RenderPassInfo {
attachments: &[
AttachmentInfo {
format: swapchain.format(),
samples: swapchain.sample_count(),
},
AttachmentInfo {
format: Format::D32,
samples: SampleCount::Samples1,
},
],
subpasses: &[SubpassInfo {
input_attachments: &[],
output_color_attachments: &[OutputAttachmentRef {
index: 0,
resolve_attachment_index: None,
}],
depth_stencil_attachment: Some(DepthStencilAttachmentRef {
index: 1,
read_only: false,
}),
}],
},
0,
);
Self { pipeline, sampler }
}
pub(super) fn execute(
&mut self,
cmd_buffer: &mut <P::GraphicsBackend as Backend>::CommandBuffer,
scene: &RendererScene<P::GraphicsBackend>,
view: &View,
camera_buffer: &Arc<<P::GraphicsBackend as Backend>::Buffer>,
resources: &RendererResources<P::GraphicsBackend>,
backbuffer: &Arc<<P::GraphicsBackend as Backend>::TextureView>,
shader_manager: &ShaderManager<P>,
assets: &RendererAssets<P>,
) {
cmd_buffer.barrier(&[Barrier::TextureBarrier {
old_sync: BarrierSync::empty(),
new_sync: BarrierSync::RENDER_TARGET,
old_access: BarrierAccess::empty(),
new_access: BarrierAccess::RENDER_TARGET_WRITE | BarrierAccess::RENDER_TARGET_READ,
old_layout: TextureLayout::Undefined,
new_layout: TextureLayout::RenderTarget,
texture: backbuffer.texture(),
range: BarrierTextureRange::default(),
}]);
let dsv = resources.access_view(
cmd_buffer,
Self::DEPTH_TEXTURE_NAME,
BarrierSync::EARLY_DEPTH | BarrierSync::LATE_DEPTH,
BarrierAccess::DEPTH_STENCIL_READ | BarrierAccess::DEPTH_STENCIL_WRITE,
TextureLayout::DepthStencilReadWrite,
true,
&TextureViewInfo::default(),
HistoryResourceEntry::Current,
);
cmd_buffer.flush_barriers();
cmd_buffer.begin_render_pass(
&RenderPassBeginInfo {
attachments: &[
RenderPassAttachment {
view: RenderPassAttachmentView::RenderTarget(&backbuffer),
load_op: LoadOp::Clear,
store_op: StoreOp::Store,
},
RenderPassAttachment {
view: RenderPassAttachmentView::DepthStencil(&dsv),
load_op: LoadOp::Clear,
store_op: StoreOp::Store,
},
],
subpasses: &[SubpassInfo {
input_attachments: &[],
output_color_attachments: &[OutputAttachmentRef {
index: 0,
resolve_attachment_index: None,
}],
depth_stencil_attachment: Some(DepthStencilAttachmentRef {
index: 1,
read_only: false,
}),
}],
},
RenderpassRecordingMode::Commands,
);
let rtv_info = backbuffer.texture().info();
let pipeline = 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(rtv_info.width as f32, rtv_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),
}]);
//let camera_buffer = cmd_buffer.upload_dynamic_data(&[view.proj_matrix * view.view_matrix], BufferUsage::CONSTANT);
cmd_buffer.bind_uniform_buffer(BindingFrequency::Frame, 0, camera_buffer, 0, WHOLE_BUFFER);
let drawables = scene.static_drawables();
let parts = &view.drawable_parts;
for part in parts {
let drawable = &drawables[part.drawable_index];
cmd_buffer.upload_dynamic_data_inline(&[drawable.transform], ShaderType::VertexShader);
let model = assets.get_model(drawable.model);
if model.is_none() {
log::info!("Skipping draw because of missing model");
continue;
}
let model = model.unwrap();
let mesh = assets.get_mesh(model.mesh_handle());
if mesh.is_none() {
log::info!("Skipping draw because of missing mesh");
continue;
}
let mesh = mesh.unwrap();
let materials: SmallVec<[&RendererMaterial; 4]> = model
.material_handles()
.iter()
.map(|handle| assets.get_material(*handle))
.collect();
let range = &mesh.parts[part.part_index];
let material = &materials[part.part_index];
let albedo_value = material.get("albedo").unwrap();
match albedo_value {
RendererMaterialValue::Texture(handle) => {
let texture = assets.get_texture(*handle);
let albedo_view = &texture.view;
cmd_buffer.bind_sampling_view_and_sampler(
BindingFrequency::Frequent,
0,
albedo_view,
&self.sampler,
);
}
_ => unimplemented!(),
}
cmd_buffer.finish_binding();
cmd_buffer.set_vertex_buffer(mesh.vertices.buffer(), mesh.vertices.offset() as usize);
if let Some(indices) = mesh.indices.as_ref() {
cmd_buffer.set_index_buffer(
indices.buffer(),
indices.offset() as usize,
IndexFormat::U32,
);
cmd_buffer.draw_indexed(1, 0, range.count, range.start, 0);
} else {
cmd_buffer.draw(range.count, range.start);
}
}
cmd_buffer.end_render_pass();
cmd_buffer.barrier(&[Barrier::TextureBarrier {
old_sync: BarrierSync::RENDER_TARGET,
new_sync: BarrierSync::empty(),
old_access: BarrierAccess::RENDER_TARGET_WRITE,
new_access: BarrierAccess::empty(),
old_layout: TextureLayout::RenderTarget,
new_layout: TextureLayout::Present,
texture: backbuffer.texture(),
range: BarrierTextureRange::default(),
}]);
}
}
|
#[doc = "Reader of register APB2LPENR"]
pub type R = crate::R<u32, super::APB2LPENR>;
#[doc = "Writer for register APB2LPENR"]
pub type W = crate::W<u32, super::APB2LPENR>;
#[doc = "Register APB2LPENR `reset()`'s with value 0"]
impl crate::ResetValue for super::APB2LPENR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "USART1 clock enable during Sleep mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum USART1LPEN_A {
#[doc = "0: Clock disabled"]
DISABLED = 0,
#[doc = "1: Clock enabled"]
ENABLED = 1,
}
impl From<USART1LPEN_A> for bool {
#[inline(always)]
fn from(variant: USART1LPEN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `USART1LPEN`"]
pub type USART1LPEN_R = crate::R<bool, USART1LPEN_A>;
impl USART1LPEN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> USART1LPEN_A {
match self.bits {
false => USART1LPEN_A::DISABLED,
true => USART1LPEN_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == USART1LPEN_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == USART1LPEN_A::ENABLED
}
}
#[doc = "Write proxy for field `USART1LPEN`"]
pub struct USART1LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> USART1LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: USART1LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clock disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::DISABLED)
}
#[doc = "Clock enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::ENABLED)
}
#[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 = "SPI 1 clock enable during Sleep mode"]
pub type SPI1LPEN_A = USART1LPEN_A;
#[doc = "Reader of field `SPI1LPEN`"]
pub type SPI1LPEN_R = crate::R<bool, USART1LPEN_A>;
#[doc = "Write proxy for field `SPI1LPEN`"]
pub struct SPI1LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SPI1LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SPI1LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clock disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::DISABLED)
}
#[doc = "Clock enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::ENABLED)
}
#[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 = "SDIO clock enable during Sleep mode"]
pub type SDIOLPEN_A = USART1LPEN_A;
#[doc = "Reader of field `SDIOLPEN`"]
pub type SDIOLPEN_R = crate::R<bool, USART1LPEN_A>;
#[doc = "Write proxy for field `SDIOLPEN`"]
pub struct SDIOLPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SDIOLPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SDIOLPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clock disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::DISABLED)
}
#[doc = "Clock enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::ENABLED)
}
#[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 = "ADC1 interface clock enable during Sleep mode"]
pub type ADC1LPEN_A = USART1LPEN_A;
#[doc = "Reader of field `ADC1LPEN`"]
pub type ADC1LPEN_R = crate::R<bool, USART1LPEN_A>;
#[doc = "Write proxy for field `ADC1LPEN`"]
pub struct ADC1LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> ADC1LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ADC1LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clock disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::DISABLED)
}
#[doc = "Clock enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::ENABLED)
}
#[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 = "TIM11 timer clock enable during Sleep mode"]
pub type TIM11LPEN_A = USART1LPEN_A;
#[doc = "Reader of field `TIM11LPEN`"]
pub type TIM11LPEN_R = crate::R<bool, USART1LPEN_A>;
#[doc = "Write proxy for field `TIM11LPEN`"]
pub struct TIM11LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> TIM11LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIM11LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clock disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::DISABLED)
}
#[doc = "Clock enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::ENABLED)
}
#[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 = "TIM10 timer clock enable during Sleep mode"]
pub type TIM10LPEN_A = USART1LPEN_A;
#[doc = "Reader of field `TIM10LPEN`"]
pub type TIM10LPEN_R = crate::R<bool, USART1LPEN_A>;
#[doc = "Write proxy for field `TIM10LPEN`"]
pub struct TIM10LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> TIM10LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIM10LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clock disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::DISABLED)
}
#[doc = "Clock enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::ENABLED)
}
#[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 = "TIM9 timer clock enable during Sleep mode"]
pub type TIM9LPEN_A = USART1LPEN_A;
#[doc = "Reader of field `TIM9LPEN`"]
pub type TIM9LPEN_R = crate::R<bool, USART1LPEN_A>;
#[doc = "Write proxy for field `TIM9LPEN`"]
pub struct TIM9LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> TIM9LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIM9LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clock disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::DISABLED)
}
#[doc = "Clock enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::ENABLED)
}
#[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 = "System configuration controller clock enable during Sleep mode"]
pub type SYSCFGLPEN_A = USART1LPEN_A;
#[doc = "Reader of field `SYSCFGLPEN`"]
pub type SYSCFGLPEN_R = crate::R<bool, USART1LPEN_A>;
#[doc = "Write proxy for field `SYSCFGLPEN`"]
pub struct SYSCFGLPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SYSCFGLPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SYSCFGLPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clock disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::DISABLED)
}
#[doc = "Clock enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(USART1LPEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 14 - USART1 clock enable during Sleep mode"]
#[inline(always)]
pub fn usart1lpen(&self) -> USART1LPEN_R {
USART1LPEN_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 12 - SPI 1 clock enable during Sleep mode"]
#[inline(always)]
pub fn spi1lpen(&self) -> SPI1LPEN_R {
SPI1LPEN_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 11 - SDIO clock enable during Sleep mode"]
#[inline(always)]
pub fn sdiolpen(&self) -> SDIOLPEN_R {
SDIOLPEN_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 9 - ADC1 interface clock enable during Sleep mode"]
#[inline(always)]
pub fn adc1lpen(&self) -> ADC1LPEN_R {
ADC1LPEN_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 4 - TIM11 timer clock enable during Sleep mode"]
#[inline(always)]
pub fn tim11lpen(&self) -> TIM11LPEN_R {
TIM11LPEN_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 3 - TIM10 timer clock enable during Sleep mode"]
#[inline(always)]
pub fn tim10lpen(&self) -> TIM10LPEN_R {
TIM10LPEN_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 2 - TIM9 timer clock enable during Sleep mode"]
#[inline(always)]
pub fn tim9lpen(&self) -> TIM9LPEN_R {
TIM9LPEN_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 0 - System configuration controller clock enable during Sleep mode"]
#[inline(always)]
pub fn syscfglpen(&self) -> SYSCFGLPEN_R {
SYSCFGLPEN_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 14 - USART1 clock enable during Sleep mode"]
#[inline(always)]
pub fn usart1lpen(&mut self) -> USART1LPEN_W {
USART1LPEN_W { w: self }
}
#[doc = "Bit 12 - SPI 1 clock enable during Sleep mode"]
#[inline(always)]
pub fn spi1lpen(&mut self) -> SPI1LPEN_W {
SPI1LPEN_W { w: self }
}
#[doc = "Bit 11 - SDIO clock enable during Sleep mode"]
#[inline(always)]
pub fn sdiolpen(&mut self) -> SDIOLPEN_W {
SDIOLPEN_W { w: self }
}
#[doc = "Bit 9 - ADC1 interface clock enable during Sleep mode"]
#[inline(always)]
pub fn adc1lpen(&mut self) -> ADC1LPEN_W {
ADC1LPEN_W { w: self }
}
#[doc = "Bit 4 - TIM11 timer clock enable during Sleep mode"]
#[inline(always)]
pub fn tim11lpen(&mut self) -> TIM11LPEN_W {
TIM11LPEN_W { w: self }
}
#[doc = "Bit 3 - TIM10 timer clock enable during Sleep mode"]
#[inline(always)]
pub fn tim10lpen(&mut self) -> TIM10LPEN_W {
TIM10LPEN_W { w: self }
}
#[doc = "Bit 2 - TIM9 timer clock enable during Sleep mode"]
#[inline(always)]
pub fn tim9lpen(&mut self) -> TIM9LPEN_W {
TIM9LPEN_W { w: self }
}
#[doc = "Bit 0 - System configuration controller clock enable during Sleep mode"]
#[inline(always)]
pub fn syscfglpen(&mut self) -> SYSCFGLPEN_W {
SYSCFGLPEN_W { w: self }
}
}
|
use crate::game_rules::Action;
use text_io::read;
pub fn select_action(available_actions: Vec<&Action>) -> Option<&Action> {
if available_actions.len() > 1 {
println!(
"Select action by number:\n{}",
available_actions
.iter()
.enumerate()
.map(|(i, a)| format!("{}. {}", i, a))
.collect::<Vec<String>>()
.join("\n"),
);
let selected_action_index: usize = read!();
if let Some(chosen_action) = available_actions.get(selected_action_index) {
return Some(chosen_action);
} else {
println!("Invalid action selection");
return select_action(available_actions);
}
} else if available_actions.len() == 1 {
println!("{}", available_actions[0]);
return Some(available_actions[0]);
} else {
println!("No actions available to you right now");
return None;
}
}
|
// `with_safe` in unit tests
test_stdout!(
with_used_with_binary_returns_how_many_bytes_were_consumed_along_with_term,
"{hello, 9}\n{hello, 9}\ntrue\nhello\n"
);
|
use super::*;
use std::fmt;
#[allow(unused_imports)]
use core_extensions::SelfOps;
use crate::{
abi_stability::PrefixStableAbi,
erased_types::{c_functions::adapt_std_fmt, InterfaceType, MakeRequiredTraits},
pointer_trait::{
AsMutPtr, AsPtr, CanTransmuteElement, GetPointerKind, PK_Reference, PK_SmartPointer,
PointerKind, TransmuteElement,
},
sabi_trait::vtable::{BaseVtable_Prefix, BaseVtable_Ref},
sabi_types::{MaybeCmp, RMut, RRef},
std_types::UTypeId,
type_level::{
impl_enum::{Implemented, Unimplemented},
trait_marker,
},
StableAbi,
};
/// `RObject` implements ffi-safe trait objects, for a minimal selection of traits.
///
/// The main use of `RObject<_>` is as the default backend for `#[sabi_trait]`
/// generated trait objects.
///
/// # Construction
///
/// `RObject<_>` is how `#[sabi_trait]`-based ffi-safe trait objects are implemented,
/// and there's no way to construct it separate from those.
///
/// # Trait object
///
/// `RObject<'borrow, Pointer<()>, Interface, VTable>`
/// can be used as a trait object for any combination of
/// the traits listed below:
///
/// - [`Send`]
///
/// - [`Sync`]
///
/// - [`Unpin`](std::marker::Unpin)
///
/// - [`Debug`]
///
/// - [`Display`]
///
/// - [`Error`](std::error::Error)
///
/// - [`Clone`]
///
/// # Deconstruction
///
/// `RObject<_>` can be unwrapped into a concrete type,
/// within the same dynamic library/executable that constructed it,
/// using these (fallible) conversion methods:
///
/// - [`downcast_into`](#method.downcast_into):
/// Unwraps into a pointer to `T`.Requires `T: 'static`.
///
/// - [`downcast_as`](#method.downcast_as):
/// Unwraps into a `&T`.Requires `T: 'static`.
///
/// - [`downcast_as_mut`](#method.downcast_as_mut):
/// Unwraps into a `&mut T`.Requires `T: 'static`.
///
/// `RObject` can only be converted back if the trait object was constructed to allow it.
///
///
///
///
///
#[repr(C)]
#[derive(StableAbi)]
#[sabi(
not_stableabi(V),
bound(V: PrefixStableAbi),
bound(I: InterfaceType),
extra_checks = <I as MakeRequiredTraits>::MAKE,
)]
pub struct RObject<'lt, P, I, V>
where
P: GetPointerKind,
{
vtable: PrefixRef<V>,
ptr: ManuallyDrop<P>,
_marker: PhantomData<(&'lt (), extern "C" fn() -> I)>,
}
mod clone_impl {
pub trait CloneImpl<PtrKind> {
fn clone_impl(&self) -> Self;
}
}
use self::clone_impl::CloneImpl;
/// This impl is for smart pointers.
impl<'lt, P, I, V> CloneImpl<PK_SmartPointer> for RObject<'lt, P, I, V>
where
P: AsPtr,
I: InterfaceType<Clone = Implemented<trait_marker::Clone>>,
{
fn clone_impl(&self) -> Self {
let ptr =
unsafe { self.sabi_robject_vtable()._sabi_clone().unwrap()(RRef::new(&self.ptr)) };
Self {
vtable: self.vtable,
ptr: ManuallyDrop::new(ptr),
_marker: PhantomData,
}
}
}
/// This impl is for references.
impl<'lt, P, I, V> CloneImpl<PK_Reference> for RObject<'lt, P, I, V>
where
P: AsPtr + Copy,
I: InterfaceType,
{
fn clone_impl(&self) -> Self {
Self {
vtable: self.vtable,
ptr: ManuallyDrop::new(*self.ptr),
_marker: PhantomData,
}
}
}
/// Clone is implemented for references and smart pointers,
/// using `GetPointerKind` to decide whether `P` is a smart pointer or a reference.
///
/// RObject does not implement Clone if `P` == `&mut ()` :
///
///
/// ```compile_fail
/// use abi_stable::{
/// sabi_trait::{doc_examples::ConstExample_TO, TD_Opaque},
/// std_types::*,
/// };
///
/// let mut object = ConstExample_TO::from_value(10usize, TD_Opaque);
/// let borrow = object.sabi_reborrow_mut();
/// let _ = borrow.clone();
/// ```
///
/// Here is the same example with `sabi_reborrow`
///
/// ```
/// use abi_stable::{
/// sabi_trait::{doc_examples::ConstExample_TO, TD_Opaque},
/// std_types::*,
/// };
///
/// let mut object = ConstExample_TO::from_value(10usize, TD_Opaque);
/// let borrow = object.sabi_reborrow();
/// let _ = borrow.clone();
/// ```
///
///
impl<'lt, P, I, V> Clone for RObject<'lt, P, I, V>
where
P: AsPtr,
I: InterfaceType,
Self: CloneImpl<<P as GetPointerKind>::Kind>,
{
fn clone(&self) -> Self {
self.clone_impl()
}
}
impl<'lt, P, I, V> Debug for RObject<'lt, P, I, V>
where
P: AsPtr<PtrTarget = ()> + AsPtr,
I: InterfaceType<Debug = Implemented<trait_marker::Debug>>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
unsafe {
adapt_std_fmt::<ErasedObject>(
self.sabi_erased_ref(),
self.sabi_robject_vtable()._sabi_debug().unwrap(),
f,
)
}
}
}
impl<'lt, P, I, V> Display for RObject<'lt, P, I, V>
where
P: AsPtr<PtrTarget = ()>,
I: InterfaceType<Display = Implemented<trait_marker::Display>>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
unsafe {
adapt_std_fmt::<ErasedObject>(
self.sabi_erased_ref(),
self.sabi_robject_vtable()._sabi_display().unwrap(),
f,
)
}
}
}
impl<'lt, P, I, V> std::error::Error for RObject<'lt, P, I, V>
where
P: AsPtr<PtrTarget = ()>,
I: InterfaceType<
Display = Implemented<trait_marker::Display>,
Debug = Implemented<trait_marker::Debug>,
Error = Implemented<trait_marker::Error>,
>,
{
}
unsafe impl<'lt, P, I, V> Send for RObject<'lt, P, I, V>
where
P: GetPointerKind,
I: InterfaceType<Send = Implemented<trait_marker::Send>>,
{
}
unsafe impl<'lt, P, I, V> Sync for RObject<'lt, P, I, V>
where
P: GetPointerKind,
I: InterfaceType<Sync = Implemented<trait_marker::Sync>>,
{
}
impl<'lt, P, I, V> Unpin for RObject<'lt, P, I, V>
where
// `Unpin` is a property of the referent
P: GetPointerKind,
I: InterfaceType<Unpin = Implemented<trait_marker::Unpin>>,
{
}
impl<'lt, P, I, V> RObject<'lt, P, I, V>
where
P: AsPtr<PtrTarget = ()>,
{
/// Constructs an RObject from a pointer and an extra vtable.
///
/// This is mostly intended to be called by `#[sabi_trait]` generated trait objects.
///
/// # Safety
///
/// These are the requirements for the caller:
///
/// - `P` must be a pointer to the type that the vtable functions
/// take as the first parameter.
///
/// - The vtable must not come from a reborrowed `RObject`
/// (created using `RObject::reborrow` or `RObject::reborrow_mut`).
///
/// - The vtable must be the `SomeVTableName` of a struct declared with
/// `#[derive(StableAbi)] #[sabi(kind(Prefix(prefix_ref= SomeVTableName)))]`.
///
/// - The vtable must have `RObjectVtable_Ref` as its first declared field
///
pub unsafe fn with_vtable<OrigPtr>(ptr: OrigPtr, vtable: PrefixRef<V>) -> RObject<'lt, P, I, V>
where
OrigPtr: CanTransmuteElement<(), TransmutedPtr = P>,
OrigPtr::PtrTarget: Sized + 'lt,
P: AsPtr<PtrTarget = ()>,
{
RObject {
vtable,
ptr: ManuallyDrop::new(unsafe { ptr.transmute_element::<()>() }),
_marker: PhantomData,
}
}
}
impl<'borr, 'a, I, V> RObject<'borr, RRef<'a, ()>, I, V> {
/// This function allows constructing an RObject in a constant/static.
///
/// This is mostly intended for `#[sabi_trait]`-generated trait objects
///
/// # Safety
///
/// This has the same safety requirements as `RObject::with_vtable`
///
/// # Example
///
/// Because this is intended for `#[sabi_trait]` generated trait objects,
/// this demonstrates how to construct one in a constant.
///
/// ```
/// use abi_stable::sabi_trait::{
/// doc_examples::ConstExample_CTO,
/// prelude::TD_Opaque,
/// };
///
/// const EXAMPLE0: ConstExample_CTO<'static, 'static> =
/// ConstExample_CTO::from_const(&0usize, TD_Opaque);
///
/// ```
pub const unsafe fn with_vtable_const<T, Downcasting>(ptr: &'a T, vtable: PrefixRef<V>) -> Self
where
T: 'borr,
{
RObject {
vtable,
ptr: {
let x = unsafe { RRef::new(ptr).transmute::<()>() };
ManuallyDrop::new(x)
},
_marker: PhantomData,
}
}
}
impl<'lt, P, I, V> RObject<'lt, P, I, V>
where
P: GetPointerKind,
{
/// The uid in the vtable has to be the same as the one for T,
/// otherwise it was not created from that T in the library that
/// declared the trait object.
fn sabi_check_same_utypeid<T>(&self) -> Result<(), UneraseError<()>>
where
T: 'static,
{
let expected_typeid = self.sabi_robject_vtable()._sabi_type_id()();
let actual_typeid = UTypeId::new::<T>();
if expected_typeid == MaybeCmp::Just(actual_typeid) {
Ok(())
} else {
Err(UneraseError {
robject: (),
expected_typeid,
actual_typeid,
})
}
}
/// Attempts to unerase this trait object into the pointer it was constructed with.
///
/// # Errors
///
/// This will return an error in any of these conditions:
///
/// - It is called in a dynamic library/binary outside
/// the one from which this RObject was constructed.
///
/// - The trait object wrapping this `RObject` was constructed with a
/// `TD_CanDowncast` argument.
///
/// - `T` is not the concrete type this `RObject<_>` was constructed with.
///
/// # Example
///
/// ```rust
/// use abi_stable::{
/// sabi_trait::doc_examples::Doer_TO, std_types::RBox,
/// type_level::downcasting::TD_CanDowncast,
/// };
///
/// let to = || Doer_TO::from_value(5usize, TD_CanDowncast);
///
/// // `to.obj` is an RObject
/// assert_eq!(
/// to().obj.downcast_into::<usize>().ok(),
/// Some(RBox::new(5usize))
/// );
/// assert_eq!(to().obj.downcast_into::<u8>().ok(), None);
///
/// ```
pub fn downcast_into<T>(self) -> Result<P::TransmutedPtr, UneraseError<Self>>
where
T: 'static,
P: AsPtr<PtrTarget = ()> + CanTransmuteElement<T>,
{
check_unerased!(self, self.sabi_check_same_utypeid::<T>());
unsafe {
let this = ManuallyDrop::new(self);
Ok(ptr::read(&*this.ptr).transmute_element::<T>())
}
}
/// Attempts to unerase this trait object into a reference of
/// the value was constructed with.
///
/// # Errors
///
/// This will return an error in any of these conditions:
///
/// - It is called in a dynamic library/binary outside
/// the one from which this RObject was constructed.
///
/// - The trait object wrapping this `RObject` was constructed with a
/// `TD_CanDowncast` argument.
///
/// - `T` is not the concrete type this `RObject<_>` was constructed with.
///
/// # Example
///
/// ```rust
/// use abi_stable::{
/// sabi_trait::doc_examples::Doer_TO, std_types::RArc,
/// type_level::downcasting::TD_CanDowncast, RMut, RRef,
/// };
///
/// {
/// let to: Doer_TO<'_, RArc<()>> =
/// Doer_TO::from_ptr(RArc::new(8usize), TD_CanDowncast);
///
/// // `to.obj` is an RObject
/// assert_eq!(to.obj.downcast_as::<usize>().ok(), Some(&8usize));
/// assert_eq!(to.obj.downcast_as::<u8>().ok(), None);
/// }
/// {
/// // `#[sabi_trait]` trait objects constructed from `&`
/// // use `RRef<'_, ()>` instead of `&'_ ()`
/// // since `&T` can't soundly be transmuted back and forth into `&()`
/// let to: Doer_TO<'_, RRef<'_, ()>> = Doer_TO::from_ptr(&13usize, TD_CanDowncast);
///
/// assert_eq!(to.obj.downcast_as::<usize>().ok(), Some(&13usize));
/// assert_eq!(to.obj.downcast_as::<u8>().ok(), None);
/// }
/// {
/// let mmut = &mut 21usize;
/// // `#[sabi_trait]` trait objects constructed from `&mut`
/// // use `RMut<'_, ()>` instead of `&'_ mut ()`
/// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()`
/// let to: Doer_TO<'_, RMut<'_, ()>> = Doer_TO::from_ptr(mmut, TD_CanDowncast);
///
/// assert_eq!(to.obj.downcast_as::<usize>().ok(), Some(&21usize));
/// assert_eq!(to.obj.downcast_as::<u8>().ok(), None);
/// }
///
/// ```
pub fn downcast_as<T>(&self) -> Result<&T, UneraseError<&Self>>
where
T: 'static,
P: AsPtr<PtrTarget = ()> + CanTransmuteElement<T>,
{
check_unerased!(self, self.sabi_check_same_utypeid::<T>());
unsafe { Ok(&*(self.ptr.as_ptr() as *const T)) }
}
/// Attempts to unerase this trait object into a mutable reference of
/// the value was constructed with.
///
/// # Errors
///
/// This will return an error in any of these conditions:
///
/// - It is called in a dynamic library/binary outside
/// the one from which this RObject was constructed.
///
/// - The trait object wrapping this `RObject` was constructed with a
/// `TD_CanDowncast` argument.
///
/// - `T` is not the concrete type this `RObject<_>` was constructed with.
///
///
/// # Example
///
/// ```rust
/// use abi_stable::{
/// sabi_trait::doc_examples::Doer_TO, std_types::RBox,
/// type_level::downcasting::TD_CanDowncast, RMut, RRef,
/// };
///
/// {
/// let mut to: Doer_TO<'_, RBox<()>> =
/// Doer_TO::from_value(34usize, TD_CanDowncast);
///
/// // `to.obj` is an RObject
/// assert_eq!(to.obj.downcast_as_mut::<usize>().ok(), Some(&mut 34usize));
/// assert_eq!(to.obj.downcast_as_mut::<u8>().ok(), None);
/// }
/// {
/// let mmut = &mut 55usize;
/// // `#[sabi_trait]` trait objects constructed from `&mut`
/// // use `RMut<'_, ()>` instead of `&'_ mut ()`
/// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()`
/// let mut to: Doer_TO<'_, RMut<'_, ()>> = Doer_TO::from_ptr(mmut, TD_CanDowncast);
///
/// assert_eq!(to.obj.downcast_as_mut::<usize>().ok(), Some(&mut 55usize));
/// assert_eq!(to.obj.downcast_as_mut::<u8>().ok(), None);
/// }
///
/// ```
pub fn downcast_as_mut<T>(&mut self) -> Result<&mut T, UneraseError<&mut Self>>
where
T: 'static,
P: AsMutPtr<PtrTarget = ()> + CanTransmuteElement<T>,
{
check_unerased!(self, self.sabi_check_same_utypeid::<T>());
unsafe { Ok(&mut *(self.ptr.as_mut_ptr() as *mut T)) }
}
/// Unwraps the `RObject<_>` into a pointer to T,
/// without checking whether `T` is the type that the RObject was constructed with.
///
/// # Safety
///
/// You must check that `T` is the type that RObject was constructed
/// with through other means.
///
/// # Example
///
/// ```rust
/// use abi_stable::{
/// sabi_trait::doc_examples::Doer_TO, std_types::RBox,
/// type_level::downcasting::TD_Opaque,
/// };
///
/// let to = || Doer_TO::from_value(5usize, TD_Opaque);
///
/// unsafe {
/// // `to.obj` is an RObject
/// assert_eq!(
/// to().obj.unchecked_downcast_into::<usize>(),
/// RBox::new(5usize)
/// );
/// }
/// ```
#[inline]
pub unsafe fn unchecked_downcast_into<T>(self) -> P::TransmutedPtr
where
P: AsPtr<PtrTarget = ()> + CanTransmuteElement<T>,
{
let this = ManuallyDrop::new(self);
unsafe { ptr::read(&*this.ptr).transmute_element::<T>() }
}
/// Unwraps the `RObject<_>` into a reference to T,
/// without checking whether `T` is the type that the RObject was constructed with.
///
/// # Safety
///
/// You must check that `T` is the type that RObject was constructed
/// with through other means.
///
/// # Example
///
/// ```rust
/// use abi_stable::{
/// sabi_trait::doc_examples::Doer_TO, std_types::RArc,
/// type_level::downcasting::TD_Opaque, RMut, RRef,
/// };
///
/// {
/// let to: Doer_TO<'_, RArc<()>> = Doer_TO::from_ptr(RArc::new(8usize), TD_Opaque);
///
/// unsafe {
/// // `to.obj` is an RObject
/// assert_eq!(to.obj.unchecked_downcast_as::<usize>(), &8usize);
/// }
/// }
/// {
/// // `#[sabi_trait]` trait objects constructed from `&`
/// // use `RRef<'_, ()>` instead of `&'_ ()`
/// // since `&T` can't soundly be transmuted back and forth into `&()`
/// let to: Doer_TO<'_, RRef<'_, ()>> = Doer_TO::from_ptr(&13usize, TD_Opaque);
///
/// unsafe {
/// assert_eq!(to.obj.unchecked_downcast_as::<usize>(), &13usize);
/// }
/// }
/// {
/// let mmut = &mut 21usize;
/// // `#[sabi_trait]` trait objects constructed from `&mut`
/// // use `RMut<'_, ()>` instead of `&'_ mut ()`
/// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()`
/// let to: Doer_TO<'_, RMut<'_, ()>> = Doer_TO::from_ptr(mmut, TD_Opaque);
///
/// unsafe {
/// assert_eq!(to.obj.unchecked_downcast_as::<usize>(), &21usize);
/// }
/// }
///
/// ```
#[inline]
pub unsafe fn unchecked_downcast_as<T>(&self) -> &T
where
P: AsPtr<PtrTarget = ()>,
{
unsafe { &*(self.ptr.as_ptr() as *const T) }
}
/// Unwraps the `RObject<_>` into a mutable reference to T,
/// without checking whether `T` is the type that the RObject was constructed with.
///
/// # Safety
///
/// You must check that `T` is the type that RObject was constructed
/// with through other means.
///
/// # Example
///
/// ```rust
/// use abi_stable::{
/// sabi_trait::doc_examples::Doer_TO, std_types::RBox,
/// type_level::downcasting::TD_Opaque, RMut, RRef,
/// };
///
/// {
/// let mut to: Doer_TO<'_, RBox<()>> = Doer_TO::from_value(34usize, TD_Opaque);
///
/// unsafe {
/// // `to.obj` is an RObject
/// assert_eq!(to.obj.unchecked_downcast_as_mut::<usize>(), &mut 34usize);
/// }
/// }
/// {
/// let mmut = &mut 55usize;
/// // `#[sabi_trait]` trait objects constructed from `&mut`
/// // use `RMut<'_, ()>` instead of `&'_ mut ()`
/// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()`
/// let mut to: Doer_TO<'_, RMut<'_, ()>> = Doer_TO::from_ptr(mmut, TD_Opaque);
///
/// unsafe {
/// assert_eq!(to.obj.unchecked_downcast_as_mut::<usize>(), &mut 55usize);
/// }
/// }
///
/// ```
#[inline]
pub unsafe fn unchecked_downcast_as_mut<T>(&mut self) -> &mut T
where
P: AsMutPtr<PtrTarget = ()>,
{
unsafe { &mut *(self.ptr.as_mut_ptr() as *mut T) }
}
}
mod private_struct {
pub struct PrivStruct;
}
use self::private_struct::PrivStruct;
/// This is used to make sure that reborrowing does not change
/// the Send-ness or Sync-ness of the pointer.
pub trait ReborrowBounds<SendNess, SyncNess> {}
// If it's reborrowing, it must have either both Sync+Send or neither.
impl ReborrowBounds<Unimplemented<trait_marker::Send>, Unimplemented<trait_marker::Sync>>
for PrivStruct
{
}
impl ReborrowBounds<Implemented<trait_marker::Send>, Implemented<trait_marker::Sync>>
for PrivStruct
{
}
impl<'lt, P, I, V> RObject<'lt, P, I, V>
where
P: GetPointerKind,
I: InterfaceType,
{
/// Creates a shared reborrow of this RObject.
///
/// This is only callable if `RObject` is either `Send + Sync` or `!Send + !Sync`.
///
/// # Example
///
/// ```rust
/// use abi_stable::{
/// sabi_trait::doc_examples::Doer_TO, std_types::RBox,
/// type_level::downcasting::TD_Opaque, RMut, RRef,
/// };
///
/// let mut to: Doer_TO<'_, RBox<()>> = Doer_TO::from_value(13usize, TD_Opaque);
///
/// // `to.obj` is an RObject
/// assert_eq!(debug_string(to.obj.reborrow()), "13");
/// assert_eq!(debug_string(to.obj.reborrow()), "13");
///
/// // `#[sabi_trait]` trait objects have an equivalent `sabi_reborrow` method.
/// assert_eq!(debug_string(to.sabi_reborrow()), "13");
/// assert_eq!(debug_string(to.sabi_reborrow()), "13");
///
/// fn debug_string<T>(to: T) -> String
/// where
/// T: std::fmt::Debug,
/// {
/// format!("{:?}", to)
/// }
///
/// ```
pub fn reborrow<'re>(&'re self) -> RObject<'lt, RRef<'re, ()>, I, V>
where
P: AsPtr<PtrTarget = ()>,
PrivStruct: ReborrowBounds<I::Send, I::Sync>,
{
// Reborrowing will break if I add extra functions that operate on `P`.
RObject {
vtable: self.vtable,
ptr: ManuallyDrop::new(self.ptr.as_rref()),
_marker: PhantomData,
}
}
/// Creates a mutable reborrow of this RObject.
///
/// The reborrowed RObject cannot use these methods:
///
/// - RObject::clone
///
/// This is only callable if `RObject` is either `Send + Sync` or `!Send + !Sync`.
///
/// # Example
///
/// ```rust
/// use abi_stable::{
/// sabi_trait::doc_examples::{Doer, Doer_TO},
/// std_types::RBox,
/// type_level::downcasting::TD_Opaque,
/// RMut, RRef,
/// };
///
/// let mut to: Doer_TO<'_, RBox<()>> = Doer_TO::from_value(2usize, TD_Opaque);
///
/// // `#[sabi_trait]` trait objects have an equivalent `sabi_reborrow_mut` method,
/// // which delegate to this method.
/// assert_eq!(increment(to.sabi_reborrow_mut()).value(), 3);
/// assert_eq!(increment(to.sabi_reborrow_mut()).value(), 4);
///
/// fn increment<T>(mut to: T) -> T
/// where
/// T: Doer,
/// {
/// to.add_into(1);
/// to
/// }
///
/// ```
pub fn reborrow_mut<'re>(&'re mut self) -> RObject<'lt, RMut<'re, ()>, I, V>
where
P: AsMutPtr<PtrTarget = ()>,
PrivStruct: ReborrowBounds<I::Send, I::Sync>,
{
// Reborrowing will break if I add extra functions that operate on `P`.
RObject {
vtable: self.vtable,
ptr: ManuallyDrop::new(self.ptr.as_rmut()),
_marker: PhantomData,
}
}
}
impl<'lt, P, I, V> RObject<'lt, P, I, V>
where
P: GetPointerKind,
{
/// Gets the vtable.
#[inline]
pub const fn sabi_et_vtable(&self) -> PrefixRef<V> {
self.vtable
}
/// The vtable common to all `#[sabi_trait]` generated trait objects.
#[inline]
pub fn sabi_robject_vtable(&self) -> RObjectVtable_Ref<(), P, I> {
unsafe { BaseVtable_Ref(self.vtable.cast::<BaseVtable_Prefix<(), P, I>>())._sabi_vtable() }
}
#[inline]
fn sabi_into_erased_ptr(self) -> ManuallyDrop<P> {
let __this = ManuallyDrop::new(self);
unsafe { ptr::read(&__this.ptr) }
}
/// Gets an `RRef` pointing to the erased object.
pub fn sabi_erased_ref(&self) -> RRef<'_, ErasedObject<()>>
where
P: AsPtr<PtrTarget = ()>,
{
unsafe { RRef::from_raw(self.ptr.as_ptr() as *const _) }
}
/// Gets an `RMut` pointing to the erased object.
pub fn sabi_erased_mut(&mut self) -> RMut<'_, ErasedObject<()>>
where
P: AsMutPtr<PtrTarget = ()>,
{
unsafe { RMut::from_raw(self.ptr.as_mut_ptr() as *mut _) }
}
/// Gets an `RRef` pointing to the erased object.
pub fn sabi_as_rref(&self) -> RRef<'_, ()>
where
P: AsPtr<PtrTarget = ()>,
{
self.ptr.as_rref()
}
/// Gets an `RMut` pointing to the erased object.
pub fn sabi_as_rmut(&mut self) -> RMut<'_, ()>
where
P: AsMutPtr<PtrTarget = ()>,
{
self.ptr.as_rmut()
}
/// Calls the `f` callback with an `MovePtr` pointing to the erased object.
#[inline]
pub fn sabi_with_value<F, R>(self, f: F) -> R
where
P: OwnedPointer<PtrTarget = ()>,
F: FnOnce(MovePtr<'_, ()>) -> R,
{
OwnedPointer::with_move_ptr(self.sabi_into_erased_ptr(), f)
}
}
impl<'lt, I, V> RObject<'lt, crate::std_types::RArc<()>, I, V> {
/// Does a shallow clone of the object, just incrementing the reference counter
pub fn shallow_clone(&self) -> Self {
Self {
vtable: self.vtable,
ptr: self.ptr.clone(),
_marker: PhantomData,
}
}
}
impl<P, I, V> Drop for RObject<'_, P, I, V>
where
P: GetPointerKind,
{
fn drop(&mut self) {
// This condition is necessary because if the RObject was reborrowed,
// the destructor function would take a different pointer type.
if <P as GetPointerKind>::KIND == PointerKind::SmartPointer {
let destructor = self.sabi_robject_vtable()._sabi_drop();
unsafe {
destructor(RMut::<P>::new(&mut self.ptr));
}
}
}
}
//////////////////////////////////////////////////////////////////
/// Error for `RObject<_>` being downcasted into the wrong type
/// with one of the `*downcast*` methods.
#[derive(Copy, Clone)]
pub struct UneraseError<T> {
robject: T,
expected_typeid: MaybeCmp<UTypeId>,
actual_typeid: UTypeId,
}
#[allow(clippy::missing_const_for_fn)]
impl<T> UneraseError<T> {
fn map<F, U>(self, f: F) -> UneraseError<U>
where
F: FnOnce(T) -> U,
{
UneraseError {
robject: f(self.robject),
expected_typeid: self.expected_typeid,
actual_typeid: self.actual_typeid,
}
}
/// Extracts the RObject, to handle the failure to unerase it.
#[must_use]
pub fn into_inner(self) -> T {
self.robject
}
}
impl<D> fmt::Debug for UneraseError<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UneraseError")
.field("dyn_trait", &"<not shown>")
.field("expected_typeid", &self.expected_typeid)
.field("actual_typeid", &self.actual_typeid)
.finish()
}
}
impl<D> fmt::Display for UneraseError<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl<D> ::std::error::Error for UneraseError<D> {}
//////////////////////////////////////////////////////////////////
|
extern crate test;
use stringify::Stringify;
use std::ffi::{CStr, CString};
use std::borrow::Cow;
use self::test::Bencher;
#[bench]
fn convert_to_cow_str_bench(b: &mut Bencher) {
let libc_char = CString::new("something".to_string()).unwrap().as_ptr();
b.iter(|| libc_char.convert_to_cow_str());
}
#[bench]
fn convert_to_cstr_bench(b: &mut Bencher) {
let libc_char = CString::new("something".to_string()).unwrap().as_ptr();
b.iter(|| libc_char.convert_to_cstr());
}
#[bench]
fn convert_to_str_bench(b: &mut Bencher) {
let libc_char = CString::new("something".to_string()).unwrap().as_ptr();
b.iter(|| libc_char.convert_to_str());
}
#[bench]
fn convert_to_string_bench(b: &mut Bencher) {
let libc_char = CString::new("something".to_string()).unwrap().as_ptr();
b.iter(|| libc_char.convert_to_string());
}
#[bench]
fn convert_to_libc_char_bench(b: &mut Bencher) {
let libc_char = CString::new("something".to_string()).unwrap().as_ptr();
b.iter(|| libc_char.convert_to_libc_char());
}
|
use crate::schema::*;
use serde_derive::Serialize;
#[derive(Queryable, Clone, Debug, Serialize, Deserialize, AsChangeset, Identifiable)]
#[table_name = "repositories"]
pub struct Repository {
pub id: i32,
pub name: String,
pub url: String,
pub ver: String,
}
#[derive(Insertable, AsChangeset, Debug)]
#[table_name = "repositories"]
pub struct NewRepository<'a> {
pub name: &'a str,
pub url: &'a str,
pub ver: &'a str,
}
#[derive(Queryable, Clone, Debug, Serialize, Deserialize)]
pub struct Function {
pub id: i64,
pub repo_id: i32,
pub name: String,
pub type_signature: String,
}
impl PartialEq for Function {
fn eq(&self, other: &Function) -> bool {
self.id == other.id
}
}
#[derive(Insertable, Debug)]
#[table_name = "functions"]
pub struct NewFunction<'a> {
pub repo_id: i32,
pub type_signature: String,
pub name: &'a str,
}
#[derive(Serialize, Queryable, QueryableByName)]
#[table_name = "repository_function_mat_view"]
pub struct FunctionWithRepo {
pub repo_id: i32,
pub repo_name: String,
pub repo_url: String,
pub repo_version: String,
pub func_id: i64,
pub func_name: String,
pub func_type_sig: String,
}
|
// 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::sync::Arc;
use common_base::runtime::GlobalIORuntime;
use common_catalog::table::AppendMode;
use common_catalog::table::Table;
use common_catalog::table_context::TableContext;
use common_exception::Result;
use common_expression::DataSchemaRef;
use common_pipeline_core::Pipeline;
use crate::pipelines::processors::TransformResortAddOn;
use crate::pipelines::PipelineBuildResult;
use crate::sessions::QueryContext;
fn fill_missing_columns(
ctx: Arc<QueryContext>,
source_schema: &DataSchemaRef,
table: Arc<dyn Table>,
pipeline: &mut Pipeline,
) -> Result<()> {
pipeline.add_transform(|transform_input_port, transform_output_port| {
TransformResortAddOn::try_create(
ctx.clone(),
transform_input_port,
transform_output_port,
source_schema.clone(),
table.clone(),
)
})?;
Ok(())
}
pub fn append2table(
ctx: Arc<QueryContext>,
table: Arc<dyn Table>,
source_schema: DataSchemaRef,
build_res: &mut PipelineBuildResult,
overwrite: bool,
need_commit: bool,
append_mode: AppendMode,
) -> Result<()> {
fill_missing_columns(
ctx.clone(),
&source_schema,
table.clone(),
&mut build_res.main_pipeline,
)?;
table.append_data(
ctx.clone(),
&mut build_res.main_pipeline,
append_mode,
false,
)?;
if need_commit {
build_res.main_pipeline.set_on_finished(move |may_error| {
// capture out variable
let overwrite = overwrite;
let ctx = ctx.clone();
let table = table.clone();
if may_error.is_none() {
let append_entries = ctx.consume_precommit_blocks();
// We must put the commit operation to global runtime, which will avoid the "dispatch dropped without returning error" in tower
return GlobalIORuntime::instance().block_on(async move {
table
.commit_insertion(ctx, append_entries, None, overwrite)
.await
});
}
Err(may_error.as_ref().unwrap().clone())
});
}
Ok(())
}
|
use tuple::T2;
pub type Length = f32;
pub type Scale = f32;
pub type Point = T2<f32, f32>;
pub type Size = T2<f32, f32>;
/*
pub struct Rect {
x: f32,
y: f32,
width: f32,
height: f32,
}
pub struct Trafo {
x: (Length, Scale),
y: (Length, Scale)
}
*/
|
#![no_std]
pub const USB_DEVICE_VID: u16 = 0xdead;
pub const USB_DEVICE_PID: u16 = 0xbeef;
pub const REQ_SELECT: u8 = 0xff;
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ResetStatus {
/// RESET=0
Asserted,
/// RESET=1
Deasserted,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Boot0Status {
/// BOOT0=1, run from system memory (bootloader)
Asserted,
/// BOOT0=0, run from flash
Deasserted,
}
const MASK_RESET: u16 = 0x0100;
const MASK_BOOT0: u16 = 0x0200;
const MASK_USB: u16 = 0x0400;
const MASK_POWER: u16 = 0x0800;
#[derive(Debug, Default, Eq, PartialEq, Copy, Clone)]
pub struct Selection(pub u16);
impl Selection {
pub fn channel(&self) -> u8 {
(self.0 & 0xff) as u8
}
pub fn set_channel(&mut self, channel: u8) -> &mut Self {
self.0 = (self.0 & 0xff00) | (channel as u16);
self
}
pub fn reset(&self) -> ResetStatus {
match self.0 & MASK_RESET != 0 {
true => ResetStatus::Asserted,
false => ResetStatus::Deasserted,
}
}
pub fn set_reset(&mut self, reset: ResetStatus) -> &mut Self {
match reset {
ResetStatus::Asserted => self.0 |= MASK_RESET,
ResetStatus::Deasserted => self.0 &= !MASK_RESET,
}
self
}
pub fn boot0(&self) -> Boot0Status {
match self.0 & MASK_BOOT0 != 0 {
true => Boot0Status::Asserted,
false => Boot0Status::Deasserted,
}
}
pub fn set_boot0(&mut self, boot0: Boot0Status) -> &mut Self {
match boot0 {
Boot0Status::Asserted => self.0 |= MASK_BOOT0,
Boot0Status::Deasserted => self.0 &= !MASK_BOOT0,
}
self
}
pub fn usb_enabled(&self) -> bool {
self.0 & MASK_USB != 0
}
pub fn set_usb_enabled(&mut self, enabled: bool) -> &mut Self {
match enabled {
true => self.0 |= MASK_USB,
false => self.0 &= !MASK_USB,
}
self
}
pub fn power_enabled(&self) -> bool {
self.0 & MASK_POWER != 0
}
pub fn set_power_enabled(&mut self, enabled: bool) -> &mut Self {
match enabled {
true => self.0 |= MASK_POWER,
false => self.0 &= !MASK_POWER,
}
self
}
}
|
use std::i32;
pub fn sort(a: &mut Vec<i32>, size: usize) {
return merge_sort(a, 0, size - 1);
}
fn merge_sort(a: &mut Vec<i32>, p: usize, r: usize) {
if p < r {
let q = (p + r) / 2;
merge_sort(a, p, q);
merge_sort(a, q + 1, r);
return merge(a, p, q, r);
}
}
fn merge(a: &mut Vec<i32>, p: usize, q: usize, r: usize) {
let n1 = q - p + 1;
let n2 = r - q;
let mut left = vec![0; n1 + 1];
for i in 0..n1 {
left[i] = a[p + i as usize]
}
left[n1] = i32::MAX;
let mut right = vec![0; n2 + 1];
for j in 0..n2 {
right[j] = a[q + j + 1 as usize]
}
right[n2] = i32::MAX;
let mut i = 0;
let mut j = 0;
for k in p..=r {
if left[i] <= right[j] {
a[k] = left[i];
i += 1
} else {
a[k] = right[j];
j += 1
}
}
}
|
#![allow(clippy::all)]
pub const SCENARIO: &str = "
SchemaData(
activity: {
\"A1\": Activity(id: \"A1\", lat: 52.895461, lon: -1.702781),
\"A10\": Activity(id: \"A10\", lat: 53.157758, lon: -1.76056),
\"A100\": Activity(id: \"A100\", lat: 53.302244, lon: -1.540919),
\"A101\": Activity(id: \"A101\", lat: 53.003741, lon: -1.60364),
\"A102\": Activity(id: \"A102\", lat: 53.111961, lon: -1.713595),
\"A103\": Activity(id: \"A103\", lat: 53.362528, lon: -1.962575),
\"A104\": Activity(id: \"A104\", lat: 53.060147, lon: -1.656907),
\"A105\": Activity(id: \"A105\", lat: 52.977311, lon: -1.635001),
\"A106\": Activity(id: \"A106\", lat: 53.093224, lon: -1.608594),
\"A107\": Activity(id: \"A107\", lat: 53.491053, lon: -1.956725),
\"A108\": Activity(id: \"A108\", lat: 53.328724, lon: -1.765085),
\"A109\": Activity(id: \"A109\", lat: 53.436296, lon: -1.815088),
\"A11\": Activity(id: \"A11\", lat: 52.954781, lon: -1.807161),
\"A110\": Activity(id: \"A110\", lat: 53.090331, lon: -1.779308),
\"A111\": Activity(id: \"A111\", lat: 53.256376, lon: -1.642303),
\"A112\": Activity(id: \"A112\", lat: 53.226335, lon: -1.426915),
\"A113\": Activity(id: \"A113\", lat: 53.235168, lon: -1.501145),
\"A114\": Activity(id: \"A114\", lat: 53.342574, lon: -1.825946),
\"A115\": Activity(id: \"A115\", lat: 52.946245, lon: -1.647704),
\"A116\": Activity(id: \"A116\", lat: 53.30077, lon: -1.952303),
\"A117\": Activity(id: \"A117\", lat: 52.969088, lon: -1.334645),
\"A118\": Activity(id: \"A118\", lat: 53.335003, lon: -1.423296),
\"A119\": Activity(id: \"A119\", lat: 53.258822, lon: -1.871336),
\"A12\": Activity(id: \"A12\", lat: 53.406814, lon: -1.741654),
\"A120\": Activity(id: \"A120\", lat: 53.131492, lon: -1.46502),
\"A121\": Activity(id: \"A121\", lat: 53.170703, lon: -1.409659),
\"A122\": Activity(id: \"A122\", lat: 53.369993, lon: -1.67112),
\"A123\": Activity(id: \"A123\", lat: 53.289086, lon: -1.776838),
\"A124\": Activity(id: \"A124\", lat: 53.109431, lon: -1.770752),
\"A125\": Activity(id: \"A125\", lat: 52.933132, lon: -1.785185),
\"A126\": Activity(id: \"A126\", lat: 53.006136, lon: -1.689555),
\"A127\": Activity(id: \"A127\", lat: 53.188072, lon: -1.589908),
\"A128\": Activity(id: \"A128\", lat: 53.236173, lon: -1.286784),
\"A129\": Activity(id: \"A129\", lat: 52.928848, lon: -1.686538),
\"A13\": Activity(id: \"A13\", lat: 52.824353, lon: -1.459144),
\"A130\": Activity(id: \"A130\", lat: 53.343623, lon: -1.660273),
\"A131\": Activity(id: \"A131\", lat: 53.292066, lon: -1.629404),
\"A132\": Activity(id: \"A132\", lat: 53.460162, lon: -1.92956),
\"A133\": Activity(id: \"A133\", lat: 53.201532, lon: -1.846235),
\"A134\": Activity(id: \"A134\", lat: 53.32616, lon: -1.312491),
\"A135\": Activity(id: \"A135\", lat: 53.384027, lon: -1.826467),
\"A136\": Activity(id: \"A136\", lat: 52.792122, lon: -1.475579),
\"A137\": Activity(id: \"A137\", lat: 53.21477, lon: -1.783971),
\"A138\": Activity(id: \"A138\", lat: 53.047506, lon: -1.599418),
\"A139\": Activity(id: \"A139\", lat: 52.724984, lon: -1.560515),
\"A14\": Activity(id: \"A14\", lat: 52.822398, lon: -1.58857),
\"A140\": Activity(id: \"A140\", lat: 53.331498, lon: -1.919278),
\"A141\": Activity(id: \"A141\", lat: 53.128405, lon: -1.690844),
\"A142\": Activity(id: \"A142\", lat: 53.047964, lon: -1.385388),
\"A143\": Activity(id: \"A143\", lat: 52.830612, lon: -1.396891),
\"A144\": Activity(id: \"A144\", lat: 53.32442, lon: -1.673996),
\"A145\": Activity(id: \"A145\", lat: 52.765984, lon: -1.513818),
\"A146\": Activity(id: \"A146\", lat: 53.131835, lon: -1.640547),
\"A147\": Activity(id: \"A147\", lat: 53.124498, lon: -1.777206),
\"A148\": Activity(id: \"A148\", lat: 53.330363, lon: -1.992963),
\"A149\": Activity(id: \"A149\", lat: 53.203068, lon: -1.238474),
\"A15\": Activity(id: \"A15\", lat: 53.196949, lon: -1.497222),
\"A150\": Activity(id: \"A150\", lat: 53.174016, lon: -1.417788),
\"A151\": Activity(id: \"A151\", lat: 53.280986, lon: -1.99321),
\"A152\": Activity(id: \"A152\", lat: 53.368666, lon: -2.017387),
\"A153\": Activity(id: \"A153\", lat: 53.26186, lon: -1.889077),
\"A154\": Activity(id: \"A154\", lat: 53.204186, lon: -1.690539),
\"A155\": Activity(id: \"A155\", lat: 53.367123, lon: -1.696538),
\"A156\": Activity(id: \"A156\", lat: 53.344521, lon: -2.001349),
\"A157\": Activity(id: \"A157\", lat: 53.420076, lon: -1.992052),
\"A158\": Activity(id: \"A158\", lat: 53.281417, lon: -1.947929),
\"A159\": Activity(id: \"A159\", lat: 53.056457, lon: -1.567071),
\"A16\": Activity(id: \"A16\", lat: 53.378869, lon: -1.987709),
\"A160\": Activity(id: \"A160\", lat: 53.149712, lon: -1.369614),
\"A161\": Activity(id: \"A161\", lat: 53.477366, lon: -1.932357),
\"A162\": Activity(id: \"A162\", lat: 52.818869, lon: -1.413796),
\"A163\": Activity(id: \"A163\", lat: 53.222625, lon: -1.494977),
\"A164\": Activity(id: \"A164\", lat: 53.168128, lon: -1.555829),
\"A165\": Activity(id: \"A165\", lat: 53.239681, lon: -1.205787),
\"A166\": Activity(id: \"A166\", lat: 53.053485, lon: -1.403755),
\"A167\": Activity(id: \"A167\", lat: 53.28622, lon: -1.798781),
\"A168\": Activity(id: \"A168\", lat: 53.353646, lon: -1.717227),
\"A169\": Activity(id: \"A169\", lat: 52.901794, lon: -1.784895),
\"A17\": Activity(id: \"A17\", lat: 53.091206, lon: -1.601057),
\"A170\": Activity(id: \"A170\", lat: 52.927151, lon: -1.331099),
\"A171\": Activity(id: \"A171\", lat: 52.968995, lon: -1.641415),
\"A172\": Activity(id: \"A172\", lat: 53.232371, lon: -1.609568),
\"A173\": Activity(id: \"A173\", lat: 53.147449, lon: -1.686576),
\"A174\": Activity(id: \"A174\", lat: 53.4107, lon: -1.713109),
\"A175\": Activity(id: \"A175\", lat: 53.057276, lon: -1.456752),
\"A176\": Activity(id: \"A176\", lat: 52.952174, lon: -1.35175),
\"A177\": Activity(id: \"A177\", lat: 53.148252, lon: -1.531846),
\"A178\": Activity(id: \"A178\", lat: 53.140294, lon: -1.673649),
\"A179\": Activity(id: \"A179\", lat: 53.001331, lon: -1.560815),
\"A18\": Activity(id: \"A18\", lat: 53.269399, lon: -1.687727),
\"A180\": Activity(id: \"A180\", lat: 53.420637, lon: -1.801242),
\"A181\": Activity(id: \"A181\", lat: 52.74258, lon: -1.657078),
\"A182\": Activity(id: \"A182\", lat: 53.290278, lon: -1.76266),
\"A183\": Activity(id: \"A183\", lat: 53.119458, lon: -1.481837),
\"A184\": Activity(id: \"A184\", lat: 53.238248, lon: -1.28768),
\"A185\": Activity(id: \"A185\", lat: 53.262886, lon: -1.397974),
\"A186\": Activity(id: \"A186\", lat: 53.216243, lon: -1.218082),
\"A187\": Activity(id: \"A187\", lat: 53.193009, lon: -1.372517),
\"A188\": Activity(id: \"A188\", lat: 53.400516, lon: -1.719402),
\"A189\": Activity(id: \"A189\", lat: 53.2324, lon: -1.433419),
\"A19\": Activity(id: \"A19\", lat: 53.265344, lon: -1.814759),
\"A190\": Activity(id: \"A190\", lat: 53.299376, lon: -1.226383),
\"A191\": Activity(id: \"A191\", lat: 52.956144, lon: -1.450832),
\"A192\": Activity(id: \"A192\", lat: 53.260321, lon: -1.233531),
\"A193\": Activity(id: \"A193\", lat: 53.354296, lon: -1.926996),
\"A194\": Activity(id: \"A194\", lat: 53.295993, lon: -1.722853),
\"A195\": Activity(id: \"A195\", lat: 53.492103, lon: -1.828135),
\"A196\": Activity(id: \"A196\", lat: 52.849991, lon: -1.411366),
\"A197\": Activity(id: \"A197\", lat: 53.064366, lon: -1.780321),
\"A198\": Activity(id: \"A198\", lat: 53.236873, lon: -1.56818),
\"A199\": Activity(id: \"A199\", lat: 53.380292, lon: -1.925854),
\"A2\": Activity(id: \"A2\", lat: 53.017264, lon: -1.661276),
\"A20\": Activity(id: \"A20\", lat: 52.883217, lon: -1.746418),
\"A200\": Activity(id: \"A200\", lat: 52.889563, lon: -1.271449),
\"A201\": Activity(id: \"A201\", lat: 53.303507, lon: -1.903997),
\"A202\": Activity(id: \"A202\", lat: 53.435866, lon: -1.9772),
\"A203\": Activity(id: \"A203\", lat: 52.885656, lon: -1.420787),
\"A204\": Activity(id: \"A204\", lat: 53.474378, lon: -1.910913),
\"A205\": Activity(id: \"A205\", lat: 52.988367, lon: -1.595523),
\"A206\": Activity(id: \"A206\", lat: 53.143872, lon: -1.601927),
\"A207\": Activity(id: \"A207\", lat: 53.268901, lon: -1.819037),
\"A208\": Activity(id: \"A208\", lat: 53.299187, lon: -1.444857),
\"A209\": Activity(id: \"A209\", lat: 53.41614, lon: -1.99759),
\"A21\": Activity(id: \"A21\", lat: 53.021597, lon: -1.445402),
\"A210\": Activity(id: \"A210\", lat: 53.232915, lon: -1.857649),
\"A211\": Activity(id: \"A211\", lat: 53.250224, lon: -1.346552),
\"A212\": Activity(id: \"A212\", lat: 53.340342, lon: -1.97752),
\"A213\": Activity(id: \"A213\", lat: 52.861015, lon: -1.392436),
\"A214\": Activity(id: \"A214\", lat: 52.915007, lon: -1.844042),
\"A215\": Activity(id: \"A215\", lat: 53.008206, lon: -1.348586),
\"A216\": Activity(id: \"A216\", lat: 53.286645, lon: -1.798027),
\"A217\": Activity(id: \"A217\", lat: 52.964313, lon: -1.823585),
\"A218\": Activity(id: \"A218\", lat: 52.860917, lon: -1.576771),
\"A219\": Activity(id: \"A219\", lat: 53.468706, lon: -1.823086),
\"A22\": Activity(id: \"A22\", lat: 53.170751, lon: -1.722464),
\"A220\": Activity(id: \"A220\", lat: 53.123541, lon: -1.412519),
\"A221\": Activity(id: \"A221\", lat: 53.454633, lon: -1.805966),
\"A222\": Activity(id: \"A222\", lat: 52.950795, lon: -1.782421),
\"A223\": Activity(id: \"A223\", lat: 52.868583, lon: -1.515564),
\"A224\": Activity(id: \"A224\", lat: 52.721439, lon: -1.570583),
\"A225\": Activity(id: \"A225\", lat: 53.11083, lon: -1.409434),
\"A226\": Activity(id: \"A226\", lat: 53.078846, lon: -1.521526),
\"A227\": Activity(id: \"A227\", lat: 52.98787, lon: -1.50494),
\"A228\": Activity(id: \"A228\", lat: 53.270855, lon: -1.992862),
\"A229\": Activity(id: \"A229\", lat: 53.089788, lon: -1.351129),
\"A23\": Activity(id: \"A23\", lat: 53.096364, lon: -1.696789),
\"A230\": Activity(id: \"A230\", lat: 52.808678, lon: -1.420621),
\"A231\": Activity(id: \"A231\", lat: 53.273298, lon: -1.791583),
\"A232\": Activity(id: \"A232\", lat: 52.84775, lon: -1.441183),
\"A233\": Activity(id: \"A233\", lat: 53.342244, lon: -1.717264),
\"A234\": Activity(id: \"A234\", lat: 53.51084, lon: -1.872637),
\"A235\": Activity(id: \"A235\", lat: 53.167896, lon: -1.748658),
\"A236\": Activity(id: \"A236\", lat: 53.042137, lon: -1.47593),
\"A237\": Activity(id: \"A237\", lat: 53.471398, lon: -1.979178),
\"A238\": Activity(id: \"A238\", lat: 52.828708, lon: -1.468058),
\"A239\": Activity(id: \"A239\", lat: 53.237055, lon: -1.266349),
\"A24\": Activity(id: \"A24\", lat: 53.300303, lon: -1.259392),
\"A240\": Activity(id: \"A240\", lat: 52.897553, lon: -1.611039),
\"A241\": Activity(id: \"A241\", lat: 53.288665, lon: -1.740187),
\"A242\": Activity(id: \"A242\", lat: 53.304599, lon: -1.91251),
\"A243\": Activity(id: \"A243\", lat: 52.809838, lon: -1.569947),
\"A244\": Activity(id: \"A244\", lat: 53.05, lon: -1.494993),
\"A245\": Activity(id: \"A245\", lat: 53.341321, lon: -1.897862),
\"A246\": Activity(id: \"A246\", lat: 53.26279, lon: -1.849513),
\"A247\": Activity(id: \"A247\", lat: 52.851646, lon: -1.5092),
\"A248\": Activity(id: \"A248\", lat: 53.182662, lon: -1.35157),
\"A249\": Activity(id: \"A249\", lat: 53.359811, lon: -1.933053),
\"A25\": Activity(id: \"A25\", lat: 53.194612, lon: -1.538533),
\"A250\": Activity(id: \"A250\", lat: 52.736827, lon: -1.677467),
\"A251\": Activity(id: \"A251\", lat: 53.043909, lon: -1.461499),
\"A252\": Activity(id: \"A252\", lat: 53.243075, lon: -1.818523),
\"A253\": Activity(id: \"A253\", lat: 53.480589, lon: -1.884952),
\"A254\": Activity(id: \"A254\", lat: 52.986479, lon: -1.40144),
\"A255\": Activity(id: \"A255\", lat: 53.278519, lon: -1.976291),
\"A256\": Activity(id: \"A256\", lat: 53.245881, lon: -1.472619),
\"A257\": Activity(id: \"A257\", lat: 53.447163, lon: -1.872359),
\"A258\": Activity(id: \"A258\", lat: 53.101018, lon: -1.318505),
\"A259\": Activity(id: \"A259\", lat: 53.294113, lon: -1.237886),
\"A26\": Activity(id: \"A26\", lat: 52.949058, lon: -1.588481),
\"A260\": Activity(id: \"A260\", lat: 53.20105, lon: -1.436085),
\"A261\": Activity(id: \"A261\", lat: 53.186277, lon: -1.597598),
\"A262\": Activity(id: \"A262\", lat: 52.880919, lon: -1.520913),
\"A263\": Activity(id: \"A263\", lat: 53.475374, lon: -1.844016),
\"A264\": Activity(id: \"A264\", lat: 53.293792, lon: -1.284614),
\"A265\": Activity(id: \"A265\", lat: 52.986783, lon: -1.632825),
\"A266\": Activity(id: \"A266\", lat: 53.249626, lon: -1.87524),
\"A267\": Activity(id: \"A267\", lat: 53.157233, lon: -1.548882),
\"A268\": Activity(id: \"A268\", lat: 52.873592, lon: -1.339804),
\"A269\": Activity(id: \"A269\", lat: 52.760505, lon: -1.613011),
\"A27\": Activity(id: \"A27\", lat: 52.928912, lon: -1.713495),
\"A270\": Activity(id: \"A270\", lat: 52.887979, lon: -1.301632),
\"A271\": Activity(id: \"A271\", lat: 53.333099, lon: -1.837163),
\"A272\": Activity(id: \"A272\", lat: 53.085708, lon: -1.542234),
\"A273\": Activity(id: \"A273\", lat: 53.228546, lon: -1.690212),
\"A274\": Activity(id: \"A274\", lat: 52.959489, lon: -1.311193),
\"A275\": Activity(id: \"A275\", lat: 53.337783, lon: -1.716267),
\"A276\": Activity(id: \"A276\", lat: 52.902604, lon: -1.542454),
\"A277\": Activity(id: \"A277\", lat: 53.222418, lon: -1.867287),
\"A278\": Activity(id: \"A278\", lat: 53.294497, lon: -1.980553),
\"A279\": Activity(id: \"A279\", lat: 53.285831, lon: -1.778673),
\"A28\": Activity(id: \"A28\", lat: 53.09807, lon: -1.421342),
\"A280\": Activity(id: \"A280\", lat: 52.860392, lon: -1.374045),
\"A281\": Activity(id: \"A281\", lat: 52.961136, lon: -1.362867),
\"A282\": Activity(id: \"A282\", lat: 52.832524, lon: -1.48973),
\"A283\": Activity(id: \"A283\", lat: 53.307381, lon: -1.849985),
\"A284\": Activity(id: \"A284\", lat: 52.977953, lon: -1.331897),
\"A285\": Activity(id: \"A285\", lat: 52.844231, lon: -1.553895),
\"A286\": Activity(id: \"A286\", lat: 52.896011, lon: -1.647761),
\"A287\": Activity(id: \"A287\", lat: 53.060305, lon: -1.685304),
\"A288\": Activity(id: \"A288\", lat: 53.454527, lon: -1.798711),
\"A289\": Activity(id: \"A289\", lat: 53.263796, lon: -1.389613),
\"A29\": Activity(id: \"A29\", lat: 53.308228, lon: -1.581307),
\"A290\": Activity(id: \"A290\", lat: 53.273302, lon: -1.818144),
\"A291\": Activity(id: \"A291\", lat: 53.352408, lon: -1.683063),
\"A292\": Activity(id: \"A292\", lat: 53.027303, lon: -1.495461),
\"A293\": Activity(id: \"A293\", lat: 53.152314, lon: -1.803471),
\"A294\": Activity(id: \"A294\", lat: 52.872447, lon: -1.484113),
\"A295\": Activity(id: \"A295\", lat: 53.013974, lon: -1.337265),
\"A296\": Activity(id: \"A296\", lat: 53.294662, lon: -1.77954),
\"A297\": Activity(id: \"A297\", lat: 52.930391, lon: -1.602513),
\"A298\": Activity(id: \"A298\", lat: 53.333415, lon: -1.672731),
\"A299\": Activity(id: \"A299\", lat: 53.066765, lon: -1.683283),
\"A3\": Activity(id: \"A3\", lat: 52.853447, lon: -1.421925),
\"A30\": Activity(id: \"A30\", lat: 53.345618, lon: -1.716767),
\"A300\": Activity(id: \"A300\", lat: 53.377213, lon: -1.914478),
\"A301\": Activity(id: \"A301\", lat: 53.152098, lon: -1.531613),
\"A302\": Activity(id: \"A302\", lat: 52.835175, lon: -1.608345),
\"A303\": Activity(id: \"A303\", lat: 53.253982, lon: -1.298671),
\"A304\": Activity(id: \"A304\", lat: 52.951183, lon: -1.617319),
\"A305\": Activity(id: \"A305\", lat: 53.159561, lon: -1.511656),
\"A306\": Activity(id: \"A306\", lat: 52.874192, lon: -1.594772),
\"A307\": Activity(id: \"A307\", lat: 53.194373, lon: -1.826719),
\"A308\": Activity(id: \"A308\", lat: 53.335955, lon: -1.646242),
\"A309\": Activity(id: \"A309\", lat: 53.251988, lon: -1.462683),
\"A31\": Activity(id: \"A31\", lat: 52.997224, lon: -1.750269),
\"A310\": Activity(id: \"A310\", lat: 53.263076, lon: -1.946183),
\"A311\": Activity(id: \"A311\", lat: 53.194798, lon: -1.531571),
\"A312\": Activity(id: \"A312\", lat: 52.9639, lon: -1.479179),
\"A313\": Activity(id: \"A313\", lat: 52.797571, lon: -1.455035),
\"A314\": Activity(id: \"A314\", lat: 53.27326, lon: -1.91086),
\"A315\": Activity(id: \"A315\", lat: 53.209721, lon: -1.683791),
\"A316\": Activity(id: \"A316\", lat: 53.388276, lon: -1.702803),
\"A317\": Activity(id: \"A317\", lat: 53.363278, lon: -1.969355),
\"A318\": Activity(id: \"A318\", lat: 52.745878, lon: -1.643253),
\"A319\": Activity(id: \"A319\", lat: 53.366992, lon: -1.993477),
\"A32\": Activity(id: \"A32\", lat: 53.248787, lon: -1.21252),
\"A320\": Activity(id: \"A320\", lat: 53.373365, lon: -1.890693),
\"A321\": Activity(id: \"A321\", lat: 53.210913, lon: -1.607096),
\"A322\": Activity(id: \"A322\", lat: 52.88559, lon: -1.820358),
\"A323\": Activity(id: \"A323\", lat: 52.92046, lon: -1.471585),
\"A324\": Activity(id: \"A324\", lat: 53.082714, lon: -1.62502),
\"A325\": Activity(id: \"A325\", lat: 53.380904, lon: -1.975926),
\"A326\": Activity(id: \"A326\", lat: 53.298654, lon: -1.436648),
\"A327\": Activity(id: \"A327\", lat: 53.220142, lon: -1.563642),
\"A328\": Activity(id: \"A328\", lat: 53.390658, lon: -1.684257),
\"A329\": Activity(id: \"A329\", lat: 53.075047, lon: -1.635613),
\"A33\": Activity(id: \"A33\", lat: 53.392995, lon: -1.784665),
\"A330\": Activity(id: \"A330\", lat: 53.2175, lon: -1.340501),
\"A331\": Activity(id: \"A331\", lat: 53.274318, lon: -1.679263),
\"A332\": Activity(id: \"A332\", lat: 53.348353, lon: -1.842712),
\"A333\": Activity(id: \"A333\", lat: 53.176491, lon: -1.254203),
\"A334\": Activity(id: \"A334\", lat: 53.501256, lon: -1.863441),
\"A335\": Activity(id: \"A335\", lat: 53.435886, lon: -1.98357),
\"A336\": Activity(id: \"A336\", lat: 53.033146, lon: -1.582961),
\"A337\": Activity(id: \"A337\", lat: 53.376749, lon: -1.700681),
\"A338\": Activity(id: \"A338\", lat: 53.394419, lon: -1.892288),
\"A339\": Activity(id: \"A339\", lat: 53.358037, lon: -1.931724),
\"A34\": Activity(id: \"A34\", lat: 53.06775, lon: -1.443167),
\"A340\": Activity(id: \"A340\", lat: 53.290725, lon: -1.508049),
\"A341\": Activity(id: \"A341\", lat: 53.161724, lon: -1.813916),
\"A342\": Activity(id: \"A342\", lat: 53.062894, lon: -1.650108),
\"A343\": Activity(id: \"A343\", lat: 53.481683, lon: -1.976595),
\"A344\": Activity(id: \"A344\", lat: 53.24118, lon: -1.939691),
\"A345\": Activity(id: \"A345\", lat: 52.958963, lon: -1.344107),
\"A346\": Activity(id: \"A346\", lat: 53.284835, lon: -1.664746),
\"A347\": Activity(id: \"A347\", lat: 52.88491, lon: -1.316082),
\"A348\": Activity(id: \"A348\", lat: 53.318902, lon: -1.682998),
\"A349\": Activity(id: \"A349\", lat: 53.468879, lon: -1.968936),
\"A35\": Activity(id: \"A35\", lat: 53.189373, lon: -1.218481),
\"A350\": Activity(id: \"A350\", lat: 53.334408, lon: -1.865757),
\"A351\": Activity(id: \"A351\", lat: 53.09876, lon: -1.514937),
\"A352\": Activity(id: \"A352\", lat: 53.026837, lon: -1.541276),
\"A353\": Activity(id: \"A353\", lat: 52.854873, lon: -1.546077),
\"A354\": Activity(id: \"A354\", lat: 53.244597, lon: -1.815372),
\"A355\": Activity(id: \"A355\", lat: 52.915106, lon: -1.775061),
\"A356\": Activity(id: \"A356\", lat: 52.955428, lon: -1.628927),
\"A357\": Activity(id: \"A357\", lat: 53.294105, lon: -1.221945),
\"A358\": Activity(id: \"A358\", lat: 53.251348, lon: -1.680541),
\"A359\": Activity(id: \"A359\", lat: 53.320682, lon: -1.699642),
\"A36\": Activity(id: \"A36\", lat: 53.276409, lon: -1.382221),
\"A360\": Activity(id: \"A360\", lat: 53.298263, lon: -1.899204),
\"A361\": Activity(id: \"A361\", lat: 52.912373, lon: -1.748691),
\"A362\": Activity(id: \"A362\", lat: 53.252445, lon: -1.621241),
\"A363\": Activity(id: \"A363\", lat: 52.934, lon: -1.681377),
\"A364\": Activity(id: \"A364\", lat: 53.219499, lon: -1.626522),
\"A365\": Activity(id: \"A365\", lat: 53.272999, lon: -1.970053),
\"A366\": Activity(id: \"A366\", lat: 53.3707, lon: -1.86995),
\"A367\": Activity(id: \"A367\", lat: 53.214615, lon: -1.476523),
\"A368\": Activity(id: \"A368\", lat: 52.893235, lon: -1.704581),
\"A369\": Activity(id: \"A369\", lat: 53.292336, lon: -1.949444),
\"A37\": Activity(id: \"A37\", lat: 53.239115, lon: -1.954457),
\"A370\": Activity(id: \"A370\", lat: 52.720544, lon: -1.568702),
\"A371\": Activity(id: \"A371\", lat: 53.145712, lon: -1.765019),
\"A372\": Activity(id: \"A372\", lat: 52.95817, lon: -1.633874),
\"A373\": Activity(id: \"A373\", lat: 52.908175, lon: -1.288014),
\"A374\": Activity(id: \"A374\", lat: 53.494554, lon: -1.860928),
\"A375\": Activity(id: \"A375\", lat: 53.281127, lon: -1.648983),
\"A376\": Activity(id: \"A376\", lat: 52.915235, lon: -1.702199),
\"A377\": Activity(id: \"A377\", lat: 53.089769, lon: -1.347454),
\"A378\": Activity(id: \"A378\", lat: 52.951426, lon: -1.699051),
\"A379\": Activity(id: \"A379\", lat: 52.95235, lon: -1.43183),
\"A38\": Activity(id: \"A38\", lat: 52.853051, lon: -1.500005),
\"A380\": Activity(id: \"A380\", lat: 52.93266, lon: -1.480134),
\"A381\": Activity(id: \"A381\", lat: 53.365809, lon: -1.967201),
\"A382\": Activity(id: \"A382\", lat: 53.081526, lon: -1.544023),
\"A383\": Activity(id: \"A383\", lat: 52.981228, lon: -1.342728),
\"A384\": Activity(id: \"A384\", lat: 52.826656, lon: -1.60056),
\"A385\": Activity(id: \"A385\", lat: 52.741292, lon: -1.577162),
\"A386\": Activity(id: \"A386\", lat: 52.95563, lon: -1.82363),
\"A387\": Activity(id: \"A387\", lat: 52.946932, lon: -1.520254),
\"A388\": Activity(id: \"A388\", lat: 52.991118, lon: -1.499832),
\"A389\": Activity(id: \"A389\", lat: 53.320769, lon: -1.851326),
\"A39\": Activity(id: \"A39\", lat: 52.964071, lon: -1.757419),
\"A390\": Activity(id: \"A390\", lat: 52.887326, lon: -1.732402),
\"A391\": Activity(id: \"A391\", lat: 52.948133, lon: -1.328279),
\"A392\": Activity(id: \"A392\", lat: 53.278316, lon: -1.441839),
\"A393\": Activity(id: \"A393\", lat: 53.488166, lon: -1.831044),
\"A394\": Activity(id: \"A394\", lat: 53.330352, lon: -1.634426),
\"A395\": Activity(id: \"A395\", lat: 53.284403, lon: -1.398876),
\"A396\": Activity(id: \"A396\", lat: 53.054644, lon: -1.495943),
\"A397\": Activity(id: \"A397\", lat: 53.02094, lon: -1.400515),
\"A398\": Activity(id: \"A398\", lat: 53.17824, lon: -1.383992),
\"A399\": Activity(id: \"A399\", lat: 53.056656, lon: -1.674705),
\"A4\": Activity(id: \"A4\", lat: 53.456315, lon: -1.938831),
\"A40\": Activity(id: \"A40\", lat: 52.962609, lon: -1.298392),
\"A400\": Activity(id: \"A400\", lat: 53.242542, lon: -1.522038),
\"A401\": Activity(id: \"A401\", lat: 53.093855, lon: -1.51691),
\"A402\": Activity(id: \"A402\", lat: 53.292557, lon: -1.193528),
\"A403\": Activity(id: \"A403\", lat: 52.945326, lon: -1.674717),
\"A404\": Activity(id: \"A404\", lat: 52.944174, lon: -1.698331),
\"A405\": Activity(id: \"A405\", lat: 52.874737, lon: -1.410662),
\"A406\": Activity(id: \"A406\", lat: 53.363599, lon: -1.851945),
\"A407\": Activity(id: \"A407\", lat: 53.363548, lon: -1.955202),
\"A408\": Activity(id: \"A408\", lat: 52.961086, lon: -1.711434),
\"A409\": Activity(id: \"A409\", lat: 53.117539, lon: -1.401815),
\"A41\": Activity(id: \"A41\", lat: 52.849239, lon: -1.567405),
\"A410\": Activity(id: \"A410\", lat: 53.082292, lon: -1.377611),
\"A411\": Activity(id: \"A411\", lat: 53.333941, lon: -1.882775),
\"A412\": Activity(id: \"A412\", lat: 52.970549, lon: -1.396183),
\"A413\": Activity(id: \"A413\", lat: 53.060047, lon: -1.69394),
\"A414\": Activity(id: \"A414\", lat: 52.975226, lon: -1.580557),
\"A415\": Activity(id: \"A415\", lat: 53.125995, lon: -1.338938),
\"A416\": Activity(id: \"A416\", lat: 53.084924, lon: -1.346203),
\"A417\": Activity(id: \"A417\", lat: 52.814947, lon: -1.572609),
\"A418\": Activity(id: \"A418\", lat: 53.078543, lon: -1.414319),
\"A419\": Activity(id: \"A419\", lat: 52.914469, lon: -1.45553),
\"A42\": Activity(id: \"A42\", lat: 53.224717, lon: -1.548871),
\"A420\": Activity(id: \"A420\", lat: 53.116948, lon: -1.755561),
\"A421\": Activity(id: \"A421\", lat: 53.086729, lon: -1.319432),
\"A422\": Activity(id: \"A422\", lat: 53.166087, lon: -1.409332),
\"A423\": Activity(id: \"A423\", lat: 53.063094, lon: -1.658877),
\"A424\": Activity(id: \"A424\", lat: 52.894409, lon: -1.471499),
\"A425\": Activity(id: \"A425\", lat: 53.407812, lon: -1.795975),
\"A426\": Activity(id: \"A426\", lat: 53.246651, lon: -1.787108),
\"A427\": Activity(id: \"A427\", lat: 52.847759, lon: -1.408824),
\"A428\": Activity(id: \"A428\", lat: 53.479052, lon: -1.841059),
\"A429\": Activity(id: \"A429\", lat: 52.765804, lon: -1.528912),
\"A43\": Activity(id: \"A43\", lat: 53.219331, lon: -1.610057),
\"A430\": Activity(id: \"A430\", lat: 53.366188, lon: -1.937097),
\"A431\": Activity(id: \"A431\", lat: 53.070116, lon: -1.360459),
\"A432\": Activity(id: \"A432\", lat: 53.400829, lon: -1.734086),
\"A433\": Activity(id: \"A433\", lat: 53.025994, lon: -1.661312),
\"A434\": Activity(id: \"A434\", lat: 53.111149, lon: -1.572826),
\"A435\": Activity(id: \"A435\", lat: 52.956482, lon: -1.507907),
\"A436\": Activity(id: \"A436\", lat: 52.877214, lon: -1.528643),
\"A437\": Activity(id: \"A437\", lat: 52.984477, lon: -1.752706),
\"A438\": Activity(id: \"A438\", lat: 52.914053, lon: -1.721192),
\"A439\": Activity(id: \"A439\", lat: 53.332707, lon: -1.830553),
\"A44\": Activity(id: \"A44\", lat: 53.273162, lon: -1.47),
\"A440\": Activity(id: \"A440\", lat: 53.43098, lon: -1.770276),
\"A441\": Activity(id: \"A441\", lat: 53.129048, lon: -1.395214),
\"A442\": Activity(id: \"A442\", lat: 53.228466, lon: -1.884525),
\"A443\": Activity(id: \"A443\", lat: 53.295666, lon: -1.6698),
\"A444\": Activity(id: \"A444\", lat: 53.18657, lon: -1.797845),
\"A445\": Activity(id: \"A445\", lat: 53.20495, lon: -1.293644),
\"A446\": Activity(id: \"A446\", lat: 53.26562, lon: -1.398309),
\"A447\": Activity(id: \"A447\", lat: 53.232097, lon: -1.800436),
\"A448\": Activity(id: \"A448\", lat: 52.821922, lon: -1.463052),
\"A449\": Activity(id: \"A449\", lat: 53.249979, lon: -1.535328),
\"A45\": Activity(id: \"A45\", lat: 52.884377, lon: -1.600451),
\"A450\": Activity(id: \"A450\", lat: 53.27744, lon: -2.000087),
\"A451\": Activity(id: \"A451\", lat: 53.0181, lon: -1.505363),
\"A452\": Activity(id: \"A452\", lat: 53.282658, lon: -1.286859),
\"A453\": Activity(id: \"A453\", lat: 53.076445, lon: -1.631166),
\"A454\": Activity(id: \"A454\", lat: 53.328098, lon: -1.983478),
\"A455\": Activity(id: \"A455\", lat: 53.315843, lon: -1.889687),
\"A456\": Activity(id: \"A456\", lat: 53.319146, lon: -1.910055),
\"A457\": Activity(id: \"A457\", lat: 53.467618, lon: -1.80971),
\"A458\": Activity(id: \"A458\", lat: 52.954112, lon: -1.730794),
\"A459\": Activity(id: \"A459\", lat: 52.90781, lon: -1.410795),
\"A46\": Activity(id: \"A46\", lat: 53.318464, lon: -1.434432),
\"A460\": Activity(id: \"A460\", lat: 52.873254, lon: -1.334265),
\"A461\": Activity(id: \"A461\", lat: 53.208337, lon: -1.270018),
\"A462\": Activity(id: \"A462\", lat: 53.191659, lon: -1.442761),
\"A463\": Activity(id: \"A463\", lat: 53.080587, lon: -1.465793),
\"A464\": Activity(id: \"A464\", lat: 53.282889, lon: -1.921572),
\"A465\": Activity(id: \"A465\", lat: 53.490712, lon: -1.830792),
\"A466\": Activity(id: \"A466\", lat: 52.982847, lon: -1.727329),
\"A467\": Activity(id: \"A467\", lat: 53.148933, lon: -1.433652),
\"A468\": Activity(id: \"A468\", lat: 52.769495, lon: -1.600818),
\"A469\": Activity(id: \"A469\", lat: 53.112414, lon: -1.515076),
\"A47\": Activity(id: \"A47\", lat: 53.374198, lon: -1.754786),
\"A470\": Activity(id: \"A470\", lat: 53.290689, lon: -1.295722),
\"A471\": Activity(id: \"A471\", lat: 52.764137, lon: -1.548128),
\"A472\": Activity(id: \"A472\", lat: 53.250858, lon: -1.867588),
\"A473\": Activity(id: \"A473\", lat: 53.460591, lon: -1.780312),
\"A474\": Activity(id: \"A474\", lat: 52.972763, lon: -1.459385),
\"A475\": Activity(id: \"A475\", lat: 53.123278, lon: -1.575332),
\"A476\": Activity(id: \"A476\", lat: 53.412625, lon: -1.727333),
\"A477\": Activity(id: \"A477\", lat: 53.358398, lon: -1.986541),
\"A478\": Activity(id: \"A478\", lat: 53.242286, lon: -1.309946),
\"A479\": Activity(id: \"A479\", lat: 53.065831, lon: -1.381648),
\"A48\": Activity(id: \"A48\", lat: 53.394356, lon: -1.97847),
\"A480\": Activity(id: \"A480\", lat: 53.000672, lon: -1.378069),
\"A481\": Activity(id: \"A481\", lat: 53.00669, lon: -1.524029),
\"A482\": Activity(id: \"A482\", lat: 53.039846, lon: -1.696042),
\"A483\": Activity(id: \"A483\", lat: 53.281574, lon: -1.504146),
\"A484\": Activity(id: \"A484\", lat: 52.96476, lon: -1.781217),
\"A485\": Activity(id: \"A485\", lat: 52.862261, lon: -1.52767),
\"A486\": Activity(id: \"A486\", lat: 53.133531, lon: -1.634838),
\"A487\": Activity(id: \"A487\", lat: 53.394783, lon: -1.80511),
\"A488\": Activity(id: \"A488\", lat: 53.389977, lon: -1.849766),
\"A489\": Activity(id: \"A489\", lat: 53.284252, lon: -1.504242),
\"A49\": Activity(id: \"A49\", lat: 52.894157, lon: -1.593967),
\"A490\": Activity(id: \"A490\", lat: 53.131108, lon: -1.539769),
\"A491\": Activity(id: \"A491\", lat: 53.391711, lon: -1.77286),
\"A492\": Activity(id: \"A492\", lat: 52.78365, lon: -1.5172),
\"A493\": Activity(id: \"A493\", lat: 53.205933, lon: -1.290005),
\"A494\": Activity(id: \"A494\", lat: 53.125268, lon: -1.633345),
\"A495\": Activity(id: \"A495\", lat: 53.267446, lon: -1.636776),
\"A496\": Activity(id: \"A496\", lat: 53.344936, lon: -1.622277),
\"A497\": Activity(id: \"A497\", lat: 53.297222, lon: -1.394429),
\"A498\": Activity(id: \"A498\", lat: 53.070688, lon: -1.394259),
\"A499\": Activity(id: \"A499\", lat: 53.1071, lon: -1.380987),
\"A5\": Activity(id: \"A5\", lat: 53.04544, lon: -1.653596),
\"A50\": Activity(id: \"A50\", lat: 52.980995, lon: -1.687655),
\"A500\": Activity(id: \"A500\", lat: 53.075312, lon: -1.514646),
\"A51\": Activity(id: \"A51\", lat: 53.081827, lon: -1.338886),
\"A52\": Activity(id: \"A52\", lat: 53.305782, lon: -1.399702),
\"A53\": Activity(id: \"A53\", lat: 52.898776, lon: -1.385245),
\"A54\": Activity(id: \"A54\", lat: 53.270796, lon: -1.383411),
\"A55\": Activity(id: \"A55\", lat: 53.346368, lon: -1.929756),
\"A56\": Activity(id: \"A56\", lat: 53.255629, lon: -1.377794),
\"A57\": Activity(id: \"A57\", lat: 52.928268, lon: -1.710506),
\"A58\": Activity(id: \"A58\", lat: 53.039406, lon: -1.448758),
\"A59\": Activity(id: \"A59\", lat: 53.027457, lon: -1.508424),
\"A6\": Activity(id: \"A6\", lat: 52.881123, lon: -1.699716),
\"A60\": Activity(id: \"A60\", lat: 53.120566, lon: -1.595411),
\"A61\": Activity(id: \"A61\", lat: 53.065032, lon: -1.366517),
\"A62\": Activity(id: \"A62\", lat: 53.460849, lon: -1.946062),
\"A63\": Activity(id: \"A63\", lat: 53.011494, lon: -1.665914),
\"A64\": Activity(id: \"A64\", lat: 52.762773, lon: -1.566517),
\"A65\": Activity(id: \"A65\", lat: 53.106076, lon: -1.393463),
\"A66\": Activity(id: \"A66\", lat: 53.141061, lon: -1.777693),
\"A67\": Activity(id: \"A67\", lat: 52.900893, lon: -1.430698),
\"A68\": Activity(id: \"A68\", lat: 53.265366, lon: -1.839951),
\"A69\": Activity(id: \"A69\", lat: 53.026581, lon: -1.446926),
\"A7\": Activity(id: \"A7\", lat: 53.356282, lon: -1.98683),
\"A70\": Activity(id: \"A70\", lat: 53.140561, lon: -1.355278),
\"A71\": Activity(id: \"A71\", lat: 52.963467, lon: -1.644309),
\"A72\": Activity(id: \"A72\", lat: 52.930169, lon: -1.302114),
\"A73\": Activity(id: \"A73\", lat: 53.046974, lon: -1.736582),
\"A74\": Activity(id: \"A74\", lat: 53.199876, lon: -1.777463),
\"A75\": Activity(id: \"A75\", lat: 52.75809, lon: -1.588261),
\"A76\": Activity(id: \"A76\", lat: 53.08767, lon: -1.431045),
\"A77\": Activity(id: \"A77\", lat: 52.907125, lon: -1.423618),
\"A78\": Activity(id: \"A78\", lat: 52.996284, lon: -1.74657),
\"A79\": Activity(id: \"A79\", lat: 52.921935, lon: -1.36243),
\"A8\": Activity(id: \"A8\", lat: 52.878424, lon: -1.412139),
\"A80\": Activity(id: \"A80\", lat: 52.94032, lon: -1.753777),
\"A81\": Activity(id: \"A81\", lat: 53.215379, lon: -1.595284),
\"A82\": Activity(id: \"A82\", lat: 53.263962, lon: -1.567333),
\"A83\": Activity(id: \"A83\", lat: 53.155083, lon: -1.529034),
\"A84\": Activity(id: \"A84\", lat: 53.222542, lon: -1.33159),
\"A85\": Activity(id: \"A85\", lat: 53.102216, lon: -1.407565),
\"A86\": Activity(id: \"A86\", lat: 53.023731, lon: -1.750332),
\"A87\": Activity(id: \"A87\", lat: 53.217449, lon: -1.912982),
\"A88\": Activity(id: \"A88\", lat: 53.476779, lon: -1.92496),
\"A89\": Activity(id: \"A89\", lat: 53.503041, lon: -1.965831),
\"A9\": Activity(id: \"A9\", lat: 52.976237, lon: -1.401738),
\"A90\": Activity(id: \"A90\", lat: 53.061543, lon: -1.568773),
\"A91\": Activity(id: \"A91\", lat: 53.252783, lon: -1.719633),
\"A92\": Activity(id: \"A92\", lat: 53.30846, lon: -1.393857),
\"A93\": Activity(id: \"A93\", lat: 53.086748, lon: -1.388024),
\"A94\": Activity(id: \"A94\", lat: 53.210029, lon: -1.252932),
\"A95\": Activity(id: \"A95\", lat: 52.827881, lon: -1.408901),
\"A96\": Activity(id: \"A96\", lat: 52.751808, lon: -1.674164),
\"A97\": Activity(id: \"A97\", lat: 52.80051, lon: -1.577267),
\"A98\": Activity(id: \"A98\", lat: 52.980786, lon: -1.439274),
\"A99\": Activity(id: \"A99\", lat: 53.128494, lon: -1.407428)
},
resource: {
\"R1\": Resource(id: \"R1\", lat: 52.98186, lon: -1.48284),
\"R10\": Resource(id: \"R10\", lat: 52.915582, lon: -1.822536),
\"R2\": Resource(id: \"R2\", lat: 53.244035, lon: -1.712563),
\"R3\": Resource(id: \"R3\", lat: 52.865613, lon: -1.508073),
\"R4\": Resource(id: \"R4\", lat: 52.875805, lon: -1.698446),
\"R5\": Resource(id: \"R5\", lat: 53.393973, lon: -1.789481),
\"R6\": Resource(id: \"R6\", lat: 52.924522, lon: -1.684105),
\"R7\": Resource(id: \"R7\", lat: 53.030762, lon: -1.43239),
\"R8\": Resource(id: \"R8\", lat: 53.232308, lon: -1.798809),
\"R9\": Resource(id: \"R9\", lat: 52.942768, lon: -1.610388)
},
route: [
],
allocation: {
},
status: Some(Status(
start_time: 0.0,
new_data: true,
changed: false,
quality: 0.0,
distance: 0.0,
value: 0.0,
travel_time: 0.0)),
)";
|
extern crate rltk;
use specs::prelude::*;
use crate::{Context, get_screen_bounds, Map, State, Viewshed};
use self::rltk::{Algorithm2D, ColorPair, Point, RGB};
#[derive(PartialEq, Copy, Clone)]
pub enum RangedTargetResult { Cancel, NoResponse, Selected(Point) }
pub fn ranged_target(state: &mut State, context: &mut Context, settings: RangedTargetDrawerSettings) -> RangedTargetResult {
RangedTargetDrawer {
state,
context,
settings,
}.draw_ranged_target()
}
struct RangedTargetDrawer<'a, 'b> {
state: &'a mut State,
context: &'a mut Context<'b>,
settings: RangedTargetDrawerSettings,
}
pub struct RangedTargetDrawerSettings {
pub range: i32,
pub radius: Option<i32>,
}
impl<'a, 'b> RangedTargetDrawer<'a, 'b> {
pub fn draw_ranged_target(&mut self) -> RangedTargetResult {
let (result_or_none, in_range_tiles) = self.draw_range();
if result_or_none.is_some() {
return result_or_none.unwrap();
}
let (screen_x, screen_y) = self.context.rltk.mouse_pos();
let (min_x, _, min_y, _) = get_screen_bounds(&self.state.ecs, self.context);
let (map_x, map_y) = (screen_x + min_x, screen_y + min_y);
let is_in_range = in_range_tiles
.iter()
.any(|visible| visible.x == map_x && visible.y == map_y);
if is_in_range {
self.draw_radius(Point::new(screen_x, screen_y));
self.context.set_bg(Point::new(screen_x, screen_y), RGB::named(rltk::CYAN));
if self.context.rltk.left_click {
return RangedTargetResult::Selected(Point::new(map_x, map_y));
}
} else {
self.context.set_bg(Point::new(screen_x, screen_y), RGB::named(rltk::RED));
if self.context.rltk.left_click {
return RangedTargetResult::Cancel;
}
}
RangedTargetResult::NoResponse
}
fn draw_range(&mut self) -> (Option<RangedTargetResult>, Vec<Point>) {
let (min_x, _, min_y, _) = get_screen_bounds(&self.state.ecs, self.context);
let player_entity = self.state.ecs.fetch::<Entity>();
let player_position = self.state.ecs.fetch::<Point>();
let viewsheds = self.state.ecs.read_storage::<Viewshed>();
self.context.print_color(Point::new(5, 0), "Select Target:", ColorPair::new(RGB::named(rltk::YELLOW), RGB::named(rltk::BLACK)));
let player_viewshed = viewsheds.get(*player_entity);
let mut in_range_tiles = Vec::new();
match player_viewshed {
None => return (Some(RangedTargetResult::Cancel), in_range_tiles),
Some(player_viewshed) => {
for visible_tile in player_viewshed.visible_tiles.iter() {
let distance = rltk::DistanceAlg::Pythagoras.distance2d(*player_position, *visible_tile);
if distance <= self.settings.range as f32 {
self.context.set_bg(Point::new(visible_tile.x - min_x, visible_tile.y - min_y), RGB::named(rltk::BLUE));
in_range_tiles.push(*visible_tile);
}
}
}
}
(None, in_range_tiles)
}
fn draw_radius(&mut self, screen_target: Point) {
if self.settings.radius.is_none() {
return;
}
let (min_x, _, min_y, _) = get_screen_bounds(&self.state.ecs, self.context);
let map_target = Point::new(screen_target.x + min_x, screen_target.y + min_y);
let map = self.state.ecs.fetch::<Map>();
let blast_tiles = rltk::field_of_view(
map_target,
self.settings.radius.unwrap(),
&*map);
let valid_blast_tiles = blast_tiles
.iter()
.filter(|p| map.in_bounds(**p) && map.is_revealed(p.x, p.y));
for tile in valid_blast_tiles {
let screen_tile = Point::new(tile.x - min_x, tile.y - min_y);
self.context.set_bg(screen_tile, RGB::named(rltk::ORANGE));
}
}
} |
use std::collections::HashMap;
fn main() {
let bootstrap = std::fs::read_to_string("input")
.unwrap()
.split(",")
.map(|s| s.parse::<usize>().unwrap())
.collect::<Vec<_>>();
dbg!(part_1(&*bootstrap, 2020));
dbg!(part_1(&*bootstrap, 30000000));
}
fn part_1(bootstrap: &[usize], nth: usize) -> usize {
let mut last = HashMap::<usize, Vec<usize>>::new();
let mut current = 0usize;
for i in 0..nth {
current = if i < bootstrap.len() {
bootstrap[i]
} else if last[¤t].len() > 1 {
let h = &last[¤t];
h[h.len() - 1] - h[h.len() - 2]
} else {
0
};
last.entry(current).or_default().push(i);
}
current
}
#[test]
fn t0() {
assert_eq!(part_1(&[0, 3, 6], 1), 0);
assert_eq!(part_1(&[0, 3, 6], 2), 3);
assert_eq!(part_1(&[0, 3, 6], 3), 6);
assert_eq!(part_1(&[0, 3, 6], 4), 0);
assert_eq!(part_1(&[0, 3, 6], 5), 3);
}
|
//! Type wrappers and convenience functions for 2D collision detection
pub use collision::algorithm::minkowski::GJK2;
pub use collision::primitive::{Circle, ConvexPolygon, Particle2, Rectangle, Square};
use cgmath::{Basis2, Point2};
use collision::algorithm::broad_phase::BruteForce;
use collision::primitive::Primitive2;
use collision::Aabb2;
use collide::*;
use BodyPose;
/// Collision shape for 2D, see [`CollisionShape`](../collide/struct.CollisionShape.html) for more
/// information
///
/// ### Type parameters:
///
/// - `S`: Scalar type (f32 or f64)
/// - `T`: Transform
/// - `Y`: Collider type, see `Collider` for more information
pub type CollisionShape2<S, T, Y = ()> = CollisionShape<Primitive2<S>, T, Aabb2<S>, Y>;
/// Broad phase brute force algorithm for 2D, see
/// [`BruteForce`](../collide/broad/struct.BruteForce.html) for more information.
pub type BroadBruteForce2 = BruteForce;
/// Broad phase sweep and prune algorithm
///
/// ### Type parameters:
///
/// - `S`: Scalar type (f32 or f64)
pub type SweepAndPrune2<S> = ::collision::algorithm::broad_phase::SweepAndPrune2<S, Aabb2<S>>;
/// Body pose transform for 2D, see [`BodyPos`e](../struct.BodyPose.html) for more information.
///
/// ### Type parameters:
///
/// - `S`: Scalar type (f32 or f64)
pub type BodyPose2<S> = BodyPose<Point2<S>, Basis2<S>>;
|
#![allow(non_upper_case_globals)]
use std::any::Any;
use std::ffi::{CStr, CString};
use std::mem::ManuallyDrop;
use std::os::raw::c_char;
use std::ptr::null_mut;
pub type CU64 = u64;
pub type CBool = u32;
pub const CFalse: CBool = 0u32;
pub const CTrue: CBool = 1u32;
/// call free_c_char to free memory
pub fn to_c_char(s: &str) -> *mut c_char {
match CString::new(s) {
Err(_e) => {
null_mut()
}
Ok(cs) => cs.into_raw()
}
}
/// free the memory that make by to_c_char or CString::into_raw
pub fn free_c_char(cs: &mut *mut c_char) {
unsafe {
if !cs.is_null() {
CString::from_raw(*cs);
*cs = null_mut(); //sure null
}
};
}
// do not free the cs's memory
pub fn to_str(cs: *const c_char) -> &'static str {
let s = unsafe {
if cs.is_null() {
""
} else {
CStr::from_ptr(cs).to_str().expect("Failed to create str")
}
};
return s;
}
/// 释放c struct的内存, 这些内存需要手工管理
pub trait CStruct {
fn free(&mut self);
///返回当前是否为struct,用于解决多层raw指针时的内存释放问题
fn is_struct(&self) -> bool {
true
}
}
/// 为类型 “*mut T”实现 trait CStruct, T要实现 trait CStruct, T 与 *mut T是两种不同的类型,所以要再实现一次
/// 注1:如果T为“*mut”类型,实际类型为“*mut *mut”,这时调用free方法时,要递归调用
/// 注2:如果rust支持泛型特化后,就可以不使用TypeId了,而使用下面注释的实现方式,高效且结构明确
impl<T: CStruct + Any> CStruct for *mut T {
fn free(&mut self) {
if !self.is_null() {
unsafe {
if !((**self).is_struct()) {
(**self).free();
}
if std::any::TypeId::of::<c_char>() == std::any::TypeId::of::<T>() {
free_c_char(&mut (*self as *mut c_char));
} else {
Box::from_raw(*self);
}
}
*self = null_mut();
}
}
fn is_struct(&self) -> bool {
false
}
}
// impl fmt::Debug for *mut c_char{
// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// unimplemented!()
// }
// }
// /// 为类型 “*mut c_char”实现 trait CStruct,因为现在rust还不支持泛型特化,所不支持
// impl CStruct for *mut c_char {
// fn free(&mut self) {
// free_c_char(self);
// }
// fn is_struct(&self) -> bool {
// false
// }
// }
//为所有需要 c <==> rust的原始类型实现 CStruct
macro_rules! promise_c_struct {
($t:ident) => {
impl CStruct for $t {
fn free(&mut self) {}
}
};
($t:ident,$($t2:ident),+) => {
impl CStruct for $t {
fn free(&mut self) {}
}
promise_c_struct!($($t2), +);
};
}
promise_c_struct!(c_char, i16,i32, i64, u16,u32, u64, f32, f64);
/// 实现drop, 要求实现 trait CStruct
#[macro_export]
macro_rules! drop_ctype {
($t:ident) => {
impl Drop for $t {
fn drop(&mut self) {
self.free();
}
}
};
($t:ident<$tt:tt>) => {
impl<$tt: crate::kits::CStruct> Drop for $t<$tt> {
fn drop(&mut self) {
self.free();
}
}
};
}
pub trait CR<C: CStruct, R> {
fn to_c(r: &R) -> C;
fn to_c_ptr(r: &R) -> *mut C;
fn to_rust(c: &C) -> R;
fn ptr_rust(c: *mut C) -> R;
}
/// c的数组需要定义两个字段,所定义一个结构体进行统一管理
/// 注:c不支持范型,所以cbindgen工具会使用具体的类型来代替
#[repr(C)]
#[derive(Debug)] //,DlStruct,DlDefault
pub struct CArray<T: CStruct> {
ptr: *mut T,
//数组指针,变量命名参考 rust Vec
len: CU64,
//数组长度,由于usize是不确定大小类型,在跨语言时不方便使用,所以使用u64类型
cap: CU64, //数组的最大容量,由于usize是不确定大小类型,在跨语言时不方便使用,所以使用u64类型
}
impl<T: CStruct> CArray<T> {
pub fn new(ar: Vec<T>) -> Self {
//Vec::into_raw_parts 这个方法不是稳定方法,所以参考它手动实现
let mut t = ManuallyDrop::new(ar);
Self {
len: t.len() as CU64,
ptr: t.as_mut_ptr(),
cap: t.capacity() as CU64,
}
}
pub fn set(&mut self, ar: Vec<T>) {
self.free(); //释放之前的内存
//Vec::into_raw_parts 这个方法不是稳定方法,所以参考它手动实现
let mut t = ManuallyDrop::new(ar);
self.len = t.len() as CU64;
self.ptr = t.as_mut_ptr();
self.cap = t.capacity() as CU64;
}
pub fn get_mut(&mut self) -> &mut [T] {
//from_raw_parts_mut 这个函数并不会获取所有权,所以它不会释放内存
let p = unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len as usize) };
return p;
}
pub fn get(&self) -> &[T] {
//from_raw_parts_mut 这个函数并不会获取所有权,所以它不会释放内存
let p = unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len as usize) };
return p;
}
}
impl<T: CStruct> Default for CArray<T> {
fn default() -> Self {
CArray {
ptr: null_mut(),
len: 0,
cap: 0,
}
}
}
impl<T: CStruct> CStruct for CArray<T> {
fn free(&mut self) {
unsafe {
if (self.len > 0 || self.cap > 0) && !self.ptr.is_null() {
let mut v = Vec::from_raw_parts(self.ptr, self.len as usize, self.cap as usize);
for it in v.iter_mut() {
if !((*it).is_struct()) {
(*it).free();
} else {
break;
}
}
}
}
self.len = 0;
self.cap = 0;
self.ptr = null_mut();
}
}
impl<T: CStruct + CR<T, R>, R: Default> CR<CArray<T>, Vec<R>> for CArray<T> {
fn to_c(r: &Vec<R>) -> CArray<T> {
let mut c = Self::default();
let temp = r.iter().map(|it| T::to_c(it)).collect();
c.set(temp);
c
}
fn to_c_ptr(r: &Vec<R>) -> *mut CArray<T> {
Box::into_raw(Box::new(Self::to_c(r)))
}
fn to_rust(c: &CArray<T>) -> Vec<R> {
let temp = c.get().iter().map(|it| T::to_rust(it)).collect();
temp
}
fn ptr_rust(c: *mut CArray<T>) -> Vec<R> {
Self::to_rust(unsafe { &*c })
}
}
drop_ctype!(CArray<T>);
impl CR<*mut c_char, String> for *mut c_char {
fn to_c(r: &String) -> *mut c_char {
to_c_char(r)
}
fn to_c_ptr(r: &String) -> *mut *mut c_char {
let t = d_ptr_alloc();
unsafe { *t = to_c_char(r); }
t
}
fn to_rust(c: &*mut c_char) -> String {
to_str(*c).to_owned()
}
fn ptr_rust(c: *mut *mut c_char) -> String {
to_str(unsafe { *c }).to_owned()
}
}
impl CStruct for Vec<&str>{
fn free(&mut self) {
}
}
impl CStruct for Vec<String>{
fn free(&mut self) {
}
}
pub fn d_ptr_alloc<T>() -> *mut *mut T {
Box::into_raw(Box::new(null_mut()))
}
pub fn ptr_alloc<T: Default>() -> *mut T {
Box::into_raw(Box::new(T::default()))
}
|
// Copyright 2012 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.
// run-pass
// Test that when we match a trait reference like `Foo<A>: Foo<_#0t>`,
// we unify with `_#0t` with `A`. In this code, if we failed to do
// that, then you get an unconstrained type-variable in `call`.
//
// Also serves as a regression test for issue #26952, though the test
// was derived from another reported regression with the same cause.
use std::marker::PhantomData;
trait Trait<A> { fn foo(&self); }
struct Type<A> { a: PhantomData<A> }
fn as_trait<A>(t: &Type<A>) -> &Trait<A> { loop { } }
fn want<A,T:Trait<A>+?Sized>(t: &T) { }
fn call<A>(p: Type<A>) {
let q = as_trait(&p);
want(q); // parameter A to `want` *would* be unconstrained
}
fn main() { }
|
use std::sync::Arc;
use base64::encode;
use model::*;
use utils::*;
type Players = Vec<Player>;
#[derive(Debug)]
pub struct State {
pub players : Vec<Arc<Player>>,
pub requests : Vec<Request>
}
impl State {
pub fn new() -> State {
State {
players : Vec::new(),
requests : Vec::new()
}
}
pub fn add_request(&mut self, request : Request) {
self.requests.push(request);
}
pub fn has_request(&self, id : Id) -> bool {
self.requests.iter().any( |r| {
r.src_id == id
})
}
pub fn purge_request(&mut self, id : Id) {
self.requests.retain( |req| {
req.src_id != id && req.dest_id != id
});
}
pub fn player_list_string(&self) -> BasicResult<String> {
let player_strings : Vec<String> = self.players.iter()
.filter_map(|player| {
match player_string(&player) { // FIXME
Ok(name) => name,
Err(err) => {
warn!("Failed getting name {}", err);
None
}
}
})
.collect();
Ok(player_strings.join(";"))
}
}
pub fn find_player_on_hold(id : Id, state : &State) -> Option<Arc<Player>> {
state.players.iter()
.find(|&p| { p.id == id && p.is_on_hold_unsafe() })
.map(|p| p.clone())
}
fn player_string(player : &Player) -> BasicResult<Option<String>> {
let state = try!(box_err(player.state.read()));
if state.name.is_empty() {
Ok(None)
} else {
let status = match state.status { // crap
PlayerStatus::OnHold => 0,
_ => 1
};
Ok(Some(format!("{}:{}:{}", encode(state.name.as_bytes()) , status, player.id)))
}
}
|
//! ```elixir
//! case Lumen.Web.Document.body(document) do
//! {:ok, body} -> ...
//! :error -> ...
//! end
//! ```
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use crate::{document, option_to_ok_tuple_or_error};
#[native_implemented::function(Elixir.Lumen.Web.Document:body/1)]
pub fn result(process: &Process, document: Term) -> exception::Result<Term> {
let document_document = document::from_term(document)?;
Ok(option_to_ok_tuple_or_error(
process,
document_document.body(),
))
}
|
use std::cmp;
use std::cmp::Ordering;
mod utils;
fn main() {
let data = utils::load_input("./data/day_9.txt").unwrap();
let nbs: Vec<u64> = data.lines().map(|nb| nb.parse().unwrap()).collect();
let invalid_nb: u64 = find_invalid_nb(&nbs).unwrap();
let weakness: u64 = find_weakness(&nbs, invalid_nb).unwrap();
println!("Answer 1/2: {}", invalid_nb);
println!("Answer 2/2: {}", weakness);
}
fn find_weakness(nbs: &[u64], invalid_nb: u64) -> Option<u64> {
let nbs_len = nbs.len();
let mut w_start: usize = 0;
let mut w_end: usize = 2;
while w_end < nbs_len {
let w: &[u64] = &nbs[w_start..w_end];
let w_sum: u64 = w.iter().sum();
match w_sum.cmp(&invalid_nb) {
Ordering::Greater => {
w_start += 1;
w_end = w_start + 2;
}
Ordering::Less => {
w_end += 1;
}
Ordering::Equal => return Some(w.iter().min().unwrap() + w.iter().max().unwrap()),
}
}
None
}
fn find_invalid_nb(nbs: &[u64]) -> Option<u64> {
let pre_len = 25;
let nbs_len = nbs.len();
for (i, nb) in nbs.iter().skip(pre_len).enumerate() {
let pre_end = cmp::min(nbs_len, i + pre_len);
let pre = &nbs[i..pre_end];
if is_valid(&nb, &pre) {
continue;
}
return Some(*nb);
}
None
}
fn is_valid(nb: &u64, pre: &[u64]) -> bool {
for n in pre {
for b in pre {
if (n + b) == *nb {
return true;
}
}
}
return false;
}
|
use std::path::PathBuf;
use anyhow::{bail, Context, Result};
use async_std::io::{Read, Write};
use async_std::net::{TcpListener, TcpStream};
use async_std::os::unix::net::{UnixListener, UnixStream};
use async_trait::async_trait;
/// A new trait, which can be used to represent Unix- and TcpListeners.
/// This is necessary to easily write generic functions where both types can be used.
#[async_trait]
pub trait GenericListener: Sync + Send {
async fn accept<'a>(&'a self) -> Result<Socket>;
}
#[async_trait]
impl GenericListener for TcpListener {
async fn accept<'a>(&'a self) -> Result<Socket> {
let (socket, _) = self.accept().await?;
Ok(Box::new(socket))
}
}
#[async_trait]
impl GenericListener for UnixListener {
async fn accept<'a>(&'a self) -> Result<Socket> {
let (socket, _) = self.accept().await?;
Ok(Box::new(socket))
}
}
/// A new trait, which can be used to represent Unix- and TcpStream.
/// This is necessary to easily write generic functions where both types can be used.
pub trait GenericSocket: Read + Write + Unpin + Send + Sync {}
impl GenericSocket for TcpStream {}
impl GenericSocket for UnixStream {}
/// Two convenient types, so we don't have type write Box<dyn ...> all the time.
pub type Listener = Box<dyn GenericListener>;
pub type Socket = Box<dyn GenericSocket>;
/// Get a new stream for the client.
/// This can either be a UnixStream or a TCPStream,
/// which depends on the parameters.
pub async fn get_client(unix_socket_path: Option<String>, port: Option<String>) -> Result<Socket> {
if let Some(socket_path) = unix_socket_path {
if !PathBuf::from(&socket_path).exists() {
bail!(
"Couldn't find unix socket at path {:?}. Is the daemon running yet?",
socket_path
);
}
let stream = UnixStream::connect(socket_path).await?;
return Ok(Box::new(stream));
}
let port = port.unwrap();
// Don't allow anything else than loopback until we have proper crypto
// let address = format!("{}:{}", address, port);
let address = format!("127.0.0.1:{}", &port);
// Connect to socket
let socket = TcpStream::connect(&address).await.context(format!(
"Failed to connect to the daemon on port {}. Did you start it?",
&port
))?;
Ok(Box::new(socket))
}
/// Get a new listener for the daemon.
/// This can either be a UnixListener or a TCPlistener,
/// which depends on the parameters.
pub async fn get_listener(
unix_socket_path: Option<String>,
port: Option<String>,
) -> Result<Listener> {
if let Some(socket_path) = unix_socket_path {
// Check, if the socket already exists
// In case it does, we have to check, if it's an active socket.
// If it is, we have to throw an error, because another daemon is already running.
// Otherwise, we can simply remove it.
if PathBuf::from(&socket_path).exists() {
if get_client(Some(socket_path.clone()), None).await.is_ok() {
bail!(
"There seems to be an active pueue daemon.\n\
If you're sure there isn't, please remove the socket by hand \
inside the pueue_directory."
);
}
std::fs::remove_file(&socket_path)?;
}
return Ok(Box::new(UnixListener::bind(socket_path).await?));
}
let port = port.unwrap();
let address = format!("127.0.0.1:{}", port);
Ok(Box::new(TcpListener::bind(address).await?))
}
|
#![cfg(target_arch="wasm32")]
extern crate mandelbrot;
extern crate image;
use mandelbrot::point::{Point, PlotSpace, point_resolver};
use mandelbrot::mandelbrot_paint::paint_mandelbrot;
use image::RgbImage;
#[no_mangle]
pub extern fn plot_mandelbrot(width: u32, height: u32, ss_scale: u32, subimage_height: u32, subimage_top: u32, origin_x: f64, origin_y: f64, plot_width: f64, plot_height: f64) -> *mut RgbImage {
let mut img = RgbImage::new(width * ss_scale, subimage_height * ss_scale);
let plot_space = PlotSpace::new(Point::new(origin_x, origin_y), plot_width, plot_height);
let resolve_point = point_resolver(width * ss_scale, height * ss_scale, plot_space);
for (x, y, px) in img.enumerate_pixels_mut() {
let point = resolve_point(x, y + subimage_top);
*px = paint_mandelbrot(point);
}
let final_img = if ss_scale > 1 {
let resized_img = image::imageops::resize(&img, width, subimage_height, image::FilterType::Triangle);
resized_img
} else {
img
};
Box::into_raw(Box::new(final_img))
}
#[no_mangle]
pub extern fn image_bytes_ptr(img_ptr: *mut RgbImage) -> *mut u8 {
let img = unsafe { &mut *img_ptr };
// ImageBuffer gives you the slice by implementing Deref, when it really shouldn't
// You can get bytes_ptr by just doing img.as_mut_ptr() but it's best to illustrate this weird API design decision
let img_bytes_slice = &mut (**img);
let bytes_ptr = img_bytes_slice.as_mut_ptr();
bytes_ptr
}
#[no_mangle]
pub extern fn destroy_image(img_ptr: *mut RgbImage) {
unsafe {
Box::from_raw(img_ptr);
}
}
|
use crate::{DocBase, VarType};
const DESCRIPTION: &'static str = r#"
Momentum of x price and x price y bars ago. This is simply a difference `x - x[y]`.
"#;
const ARGUMENTS: &'static str = r#"
source (series(float)) Series of values to process.
length (int) Offset from the current bar to the previous bar.
"#;
pub fn gen_doc() -> Vec<DocBase> {
let fn_doc = DocBase {
var_type: VarType::Function,
name: "mom",
signatures: vec![],
description: DESCRIPTION,
example: "",
returns: "Momentum of x price and x price y bars ago.",
arguments: ARGUMENTS,
remarks: "",
links: "",
};
vec![fn_doc]
}
|
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Energy {
pub energy: f32,
pub max: f32,
pub regen_rate: f32,
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Helper library for integration testing netdump.
use {
failure::{format_err, Error},
fdio::{self, WatchEvent},
fidl_fuchsia_netemul_environment::ManagedEnvironmentMarker,
fidl_fuchsia_netemul_network::{
EndpointManagerMarker, EndpointManagerProxy, EndpointProxy, FakeEndpointMarker,
FakeEndpointProxy, NetworkContextMarker, NetworkManagerMarker, NetworkProxy,
},
fidl_fuchsia_sys::{LauncherMarker, LauncherProxy},
fuchsia_async::{Executor, Interval},
fuchsia_component::client,
fuchsia_zircon as zx,
futures::{
future::{self, Either},
Future, StreamExt,
},
net_types::ip::IpVersion,
std::boxed::Box,
std::fs::File,
std::net::{IpAddr, SocketAddr, UdpSocket},
std::path::Path,
};
mod tests;
/// Directory for dumpfile to reside.
pub const DUMPFILE_DIR: &str = "/vdata";
/// Default dumpfile name to use.
pub const DEFAULT_DUMPFILE: &str = "netdump.pcapng";
/// Minimum valid dumpfile size in bytes.
/// Size of PCAPNG section header + interface description blocks.
pub const MIN_DUMPFILE_SIZE: usize = 28 + 20;
const DUMPFILE_SIZE_CHECK_INTERVAL_MILLIS: i64 = 30;
const NETDUMP_URL: &str = fuchsia_component::fuchsia_single_component_package_url!("netdump");
/// Helper for constructing valid command-line arguments to netdump.
pub struct Args {
// Always non-empty with the device path being the last element.
args: Vec<String>,
}
impl From<Args> for Vec<String> {
fn from(input: Args) -> Self {
input.args
}
}
impl Args {
/// New set of arguments given an endpoint path of the device to sniff.
pub fn new(path: &str) -> Self {
Args { args: vec![path.to_string()] }
}
/// Insert an argument in the correct place in the argument list before the capture device path.
pub fn insert_arg(mut self, arg: String) -> Self {
let last = self.args.len() - 1;
self.args.insert(last, arg);
self
}
/// Helper method for inserting a packet count argument.
pub fn insert_packet_count(self, count: usize) -> Self {
self.insert_arg("-c".into()).insert_arg(count.to_string())
}
/// Helper method for inserting a display link-level information argument.
pub fn insert_link_level(self) -> Self {
self.insert_arg("-e".into())
}
/// Helper method for inserting a filter argument.
pub fn insert_filter(self, filter: &str) -> Self {
self.insert_arg("-f".into()).insert_arg(filter.into())
}
/// Helper method for inserting a timeout argument.
pub fn insert_timeout(self, timeout_secs: u64) -> Self {
self.insert_arg("-t".into()).insert_arg(timeout_secs.to_string())
}
/// Helper method for inserting a write to pcapng dumpfile argument.
/// `path`: The file path to use, relative to `DUMPFILE_DIR`.
pub fn insert_write_to_dumpfile(self, path: &str) -> Self {
self.insert_arg("-w".into()).insert_arg(format!("{}/{}", DUMPFILE_DIR, path))
}
/// Helper method for inserting a pcapng dump to stdout argument.
pub fn insert_pcapng_dump_to_stdout(self) -> Self {
self.insert_arg("--pcapdump".into())
}
}
#[derive(Copy, Clone)]
pub enum EndpointType {
TX,
RX,
}
/// Provide default values for creating a socket attached to the endpoint.
impl EndpointType {
pub fn default_port(self) -> u16 {
match self {
Self::TX => 1111,
Self::RX => 2222,
}
}
pub fn default_ip_addr_str(self, ver: IpVersion) -> &'static str {
match (ver, self) {
(IpVersion::V4, EndpointType::TX) => "192.168.0.1",
(IpVersion::V6, EndpointType::TX) => "fd00::1",
(IpVersion::V4, EndpointType::RX) => "192.168.0.2",
(IpVersion::V6, EndpointType::RX) => "fd00::2",
}
}
pub fn default_ip_addr(self, ver: IpVersion) -> IpAddr {
self.default_ip_addr_str(ver).parse().unwrap()
}
pub fn default_socket_addr(self, ver: IpVersion) -> SocketAddr {
SocketAddr::new(self.default_ip_addr(ver), self.default_port())
}
}
/// The environment infrastructure for a test consisting of multiple test cases, for helping with
/// launching packet capture. Only one should be created per test. It is expected that the running
/// test `test_name` has the following configured as part of the netemul runner setup:
/// - Endpoints `test_name_tx` and `test_name_rx`.
/// - A network `test_name_net` with the above endpoints present.
/// - The endpoints are attached to the ambient `ManagedEnvironment` under `/vdev/class/ethernet/`.
/// Packets are isolated to each network, and do not travel across networks.
/// The "tx" and "rx" in the endpoint names are to suggest the source and sink endpoints for packets
/// in tests. However there is no actual restriction on use.
///
/// There are multiple ways to write packets to the network:
/// - The backing Ethernet device for the endpoints can be obtained for writing.
/// - The endpoints can be bound to netstack, which is in turn exercised to produce packets.
/// - A netemul `FakeEndpoint` can be used to write to the network directly.
/// To ensure that packet capturing and writing to the network happen concurrently, tests should
/// set up a Fuchsia async `Executor` and give its ownership to `TestEnvironment`. This allows
/// execution of async test case code uniformly through the provided `run_test_case` method.
/// TODO(CONN-170): Allow parallel test cases.
pub struct TestEnvironment {
test_name: String,
epm: EndpointManagerProxy,
net: NetworkProxy,
launcher: LauncherProxy,
executor: Executor,
}
impl TestEnvironment {
pub fn new(mut executor: Executor, test_name: &str) -> Result<Self, Error> {
let env = client::connect_to_service::<ManagedEnvironmentMarker>()?;
let netctx = client::connect_to_service::<NetworkContextMarker>()?;
let (epm, epm_server_end) = fidl::endpoints::create_proxy::<EndpointManagerMarker>()?;
netctx.get_endpoint_manager(epm_server_end)?;
let (netm, netm_server_end) = fidl::endpoints::create_proxy::<NetworkManagerMarker>()?;
netctx.get_network_manager(netm_server_end)?;
let net_name = format!("{}_net", test_name);
let net = executor
.run_singlethreaded(netm.get_network(&net_name))?
.ok_or(format_err!("Cannot find network {}", &net_name))?
.into_proxy()?;
let (launcher, launcher_req) = fidl::endpoints::create_proxy::<LauncherMarker>()?;
env.get_launcher(launcher_req)?;
Ok(Self { test_name: test_name.to_string(), epm, net, launcher, executor })
}
/// Create a new `Args` instance with the specified endpoint as the capture device.
pub fn new_args(&self, ep_type: EndpointType) -> Args {
Args::new(&format!("/vdev/class/ethernet/{}", &self.ep_name_by_type(ep_type)))
}
/// Run a test case in the current environment. Can be reused for multiple test cases provided
/// that all previous test cases passed and did not return `Result::Err`.
///
/// Packet capture during the test case will be launched with the given arguments.
/// Packet transmission is performed concurrently after a watched dumpfile comes into existence.
/// This method blocks until both packet transmission and capture are complete. No timeout is
/// implemented, but the test will be killed by the global timeout enforced by netemul.
/// The result is the output produced by the capture.
/// `args`: Arguments to launch packet capture.
/// `send_packets_fut`: The future to execute in order to send packets on the network.
/// `dumpfile`: The file path relative to `DUMPFILE_DIR` to watch for a dumpfile. If the file
/// exists, it is removed. Packet transmission begins after the file is added by packet capture
/// and become non-zero in size due to the output of PCAPNG header blocks.
pub fn run_test_case(
&mut self,
args: Vec<String>,
send_packets_fut: impl Future<Output = Result<(), Error>> + Send + 'static,
dumpfile: &str,
) -> Result<client::Output, Error> {
Self::remove_dumpfile(dumpfile)?;
let app_fut =
client::AppBuilder::new(NETDUMP_URL.to_string()).args(args).output(&self.launcher)?;
let watcher_fut = Box::pin(Self::watch_for_dumpfile(dumpfile.into()));
let setup_fut = future::select(app_fut, watcher_fut);
// Run capture setup and dumpfile watcher on 2 threads.
// This should not deadlock as netdump always writes PCAPNG header bocks in its
// write_shb() and write_idb() calls in handle_rx() to file even if no packets
// are transmitted.
let capture_fut = match self.executor.run(setup_fut, 2) {
Either::Left(_) => Err(format_err!(
"Capture exited early. Please refer to FLK-487 if this appears flaky."
)),
Either::Right((_, fut)) => Ok(fut),
}?;
// Complete the test by running capture and packet transmission on 2 threads.
match self.executor.run(future::try_join(capture_fut, send_packets_fut), 2)? {
(output, _) => Ok(output),
}
}
/// Run a test case in the current environment that does not require packets on the network.
/// Can be reused for multiple test cases provided that all previous test cases passed and did not
/// return `Result::Err`. Useful for testing invalid packet capture setup.
pub fn run_test_case_no_packets(&mut self, args: Vec<String>) -> Result<client::Output, Error> {
let app_fut =
client::AppBuilder::new(NETDUMP_URL.to_string()).args(args).output(&self.launcher)?;
self.executor.run_singlethreaded(app_fut)
}
/// Get one of the real endpoints in the environment.
pub fn endpoint(&mut self, ep_type: EndpointType) -> Result<EndpointProxy, Error> {
let ep_name = self.ep_name_by_type(ep_type);
let ep = self
.executor
.run_singlethreaded(self.epm.get_endpoint(&ep_name))?
.ok_or(format_err!("Cannot obtain endpoint {}", &ep_name))?
.into_proxy()?;
Ok(ep)
}
/// Create a new fake endpoint.
pub fn create_fake_endpoint(&self) -> Result<FakeEndpointProxy, Error> {
let (ep_fake, ep_fake_server_end) = fidl::endpoints::create_proxy::<FakeEndpointMarker>()?;
self.net.create_fake_endpoint(ep_fake_server_end)?;
Ok(ep_fake)
}
fn ep_name_by_type(&self, ep_type: EndpointType) -> String {
match ep_type {
EndpointType::TX => format!("{}_tx", &self.test_name),
EndpointType::RX => format!("{}_rx", &self.test_name),
}
}
// Remove the dumpfile if it exists.
fn remove_dumpfile(dumpfile: &str) -> Result<(), Error> {
let dumpfile_path_string = format!("{}/{}", DUMPFILE_DIR, dumpfile);
let dumpfile_path = Path::new(&dumpfile_path_string);
if dumpfile_path.exists() {
std::fs::remove_file(dumpfile_path)?;
}
Ok(())
}
// Watch for the dumpfile to be added, then periodically check its size.
async fn watch_for_dumpfile(dumpfile: String) -> Result<(), Error> {
let dir = File::open(DUMPFILE_DIR)?;
let dumpfile_path = Path::new(&dumpfile);
// Blocks until the relevant `AddFile` event is received.
let status = fdio::watch_directory(&dir, zx::sys::ZX_TIME_INFINITE, |event, got_path| {
if event == WatchEvent::AddFile && got_path == dumpfile_path {
Err(zx::Status::STOP)
} else {
Ok(()) // Continue watching.
}
});
match status {
zx::Status::STOP => Ok(()), // Dumpfile now exists.
status => Err(format_err!("Dumpfile watcher returned with status {:?}", status)),
}?;
let fut = Self::watch_dumpfile_size(format!("{}/{}", DUMPFILE_DIR, &dumpfile));
fut.await
}
// Periodically check for dumpfile size until it is at least minimum size.
async fn watch_dumpfile_size(dumpfile_path_str: String) -> Result<(), Error> {
let interval_dur = zx::Duration::from_millis(DUMPFILE_SIZE_CHECK_INTERVAL_MILLIS);
let mut interval = Interval::new(interval_dur);
let dumpfile_path = Path::new(&dumpfile_path_str);
while std::fs::metadata(&dumpfile_path)?.len() < MIN_DUMPFILE_SIZE as u64 {
interval.next().await;
}
Ok(())
}
}
/// Tear down `TestEnvironment` and return the owned executor.
impl From<TestEnvironment> for Executor {
fn from(env: TestEnvironment) -> Self {
env.executor
}
}
#[macro_export]
macro_rules! test_case {
($name:ident, $($args:expr),*) => {
println!("Running test case {}.", stringify!($name));
$name($($args),*)?;
println!("Test case {} passed.", stringify!($name));
};
}
/// Converting the `client::Output` data of components into a String.
pub fn output_string(data: &Vec<u8>) -> String {
String::from_utf8_lossy(data).into_owned()
}
/// Return Ok if everything in `substrs` is a substring of `st`, otherwise Err with the substring
/// that is not present.
pub fn check_all_substrs<'a>(st: &str, substrs: &[&'a str]) -> Result<(), &'a str> {
substrs.iter().try_for_each(|&substr| if st.contains(substr) { Ok(()) } else { Err(substr) })
}
/// Example packet transmission task that can be used with `TestEnvironment::run_test_case`.
/// Send UDP packets from the given socket to the receiving socket address `addr_rx`.
pub async fn send_udp_packets(
socket: UdpSocket,
addr_rx: SocketAddr,
payload_size_octets: usize,
count: usize,
) -> Result<(), Error> {
let buf: Vec<u8> = std::iter::repeat(0).take(payload_size_octets).collect();
for _ in 0..count {
socket.send_to(&buf, addr_rx)?;
}
Ok(())
}
|
mod args;
#[cfg(feature = "tui")]
mod tui;
use args::Args;
use rlifesrc_lib::{Search, Status};
use std::process::exit;
/// Runs the search without TUI.
///
/// If `all` is true, it will print all possible results
/// instead of only the first one.
fn run_search(mut search: Box<dyn Search>, all: bool) {
if all {
let mut found = false;
loop {
match search.search(None) {
Status::Found => {
found = true;
println!("{}", search.rle_gen(0))
}
Status::None => break,
_ => (),
}
}
if !found {
eprintln!("Not found.");
exit(1);
}
} else if let Status::Found = search.search(None) {
println!("{}", search.rle_gen(0));
} else {
eprintln!("Not found.");
exit(1);
}
}
#[cfg(feature = "tui")]
fn main() {
let args = Args::parse().unwrap_or_else(|e| e.exit());
let search = args.search;
if args.no_tui {
run_search(search, args.all);
} else {
tui::tui(search, args.reset).unwrap();
}
}
#[cfg(not(feature = "tui"))]
fn main() {
let args = Args::parse().unwrap_or_else(|e| e.exit());
run_search(args.search, args.all);
}
|
// Count Sorted Vowel Strings
// https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3607/
pub struct Solution;
impl Solution {
pub fn count_vowel_strings(n: i32) -> i32 {
const NUM_VOWELS: usize = 5;
let mut by_1st_char = [1; NUM_VOWELS];
for _ in 2..=n {
let mut sum = 1;
for vowel in 1..NUM_VOWELS {
let num = unsafe { by_1st_char.get_unchecked_mut(vowel) };
sum += *num;
*num = sum;
}
}
by_1st_char.iter().sum()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn example1() {
assert_eq!(Solution::count_vowel_strings(1), 5);
}
#[test]
fn example2() {
assert_eq!(Solution::count_vowel_strings(2), 15);
}
#[test]
fn example3() {
assert_eq!(Solution::count_vowel_strings(33), 66045);
}
}
|
mod small_vec;
pub use small_vec::{SmallVectorImpl, Span, StableId}; |
pub struct Solution;
impl Solution {
pub fn sort_colors(nums: &mut Vec<i32>) {
let n = nums.len();
let mut two_pos = n;
let mut one_pos = n;
let mut i = 0;
while i < one_pos {
match nums[i] {
0 => i += 1,
1 => {
one_pos -= 1;
nums.swap(i, one_pos);
}
2 => {
two_pos -= 1;
nums.swap(i, two_pos);
if two_pos < one_pos {
one_pos = two_pos;
}
}
_ => unreachable!(),
}
}
}
}
#[test]
fn test0075() {
let mut nums = vec![2, 0, 2, 1, 1, 0];
Solution::sort_colors(&mut nums);
assert_eq!(nums, vec![0, 0, 1, 1, 2, 2]);
let mut nums = vec![2];
Solution::sort_colors(&mut nums);
assert_eq!(nums, vec![2]);
}
|
pub trait Same<Lhs, Rhs, Out = ()> {
type Output;
}
impl<T, Out> Same<T, T, Out> for () {
type Output = Out;
}
pub type SameOp<Lhs, Rhs> = <() as Same<Lhs, Rhs>>::Output;
pub type SameExOp<Lhs, Rhs, Out> = <() as Same<Lhs, Rhs, Out>>::Output;
|
/// Macro that allows you to quickly define a handlebars helper by passing a
/// name and a closure.
///
/// # Examples
///
/// ```rust
/// #[macro_use] extern crate handlebars;
/// #[macro_use] extern crate serde_json;
///
/// handlebars_helper!(is_above_10: |x: u64| x > 10);
///
/// # fn main() {
/// #
/// let mut handlebars = handlebars::Handlebars::new();
/// handlebars.register_helper("is-above-10", Box::new(is_above_10));
///
/// let result = handlebars
/// .render_template("{{#if (is-above-10 12)}}great!{{else}}okay{{/if}}", &json!({}))
/// .unwrap();
/// assert_eq!(&result, "great!");
/// # }
/// ```
#[macro_export]
macro_rules! handlebars_helper {
($struct_name:ident: |$($name:ident: $tpe:tt),*| $body:expr ) => {
#[allow(non_camel_case_types)]
pub struct $struct_name;
impl $crate::HelperDef for $struct_name {
#[allow(unused_assignments)]
fn call_inner<'reg: 'rc, 'rc>(
&self,
h: &$crate::Helper<'reg, 'rc>,
_: &'reg $crate::Handlebars,
_: &'rc $crate::Context,
_: &mut $crate::RenderContext<'reg>,
) -> Result<Option<$crate::ScopedJson<'reg, 'rc>>, $crate::RenderError> {
let mut param_idx = 0;
$(
let $name = h.param(param_idx)
.map(|x| x.value())
.ok_or_else(|| $crate::RenderError::new(&format!(
"`{}` helper: Couldn't read parameter {}",
stringify!($fn_name), stringify!($name),
)))
.and_then(|x|
handlebars_helper!(@as_json_value x, $tpe)
.ok_or_else(|| $crate::RenderError::new(&format!(
"`{}` helper: Couldn't convert parameter {} to type `{}`. \
It's {:?} as JSON. Got these params: {:?}",
stringify!($fn_name), stringify!($name), stringify!($tpe),
x, h.params(),
)))
)?;
param_idx += 1;
)*
let result = $body;
Ok(Some($crate::ScopedJson::Derived($crate::JsonValue::from(result))))
}
}
};
(@as_json_value $x:ident, object) => { $x.as_object() };
(@as_json_value $x:ident, array) => { $x.as_array() };
(@as_json_value $x:ident, str) => { $x.as_str() };
(@as_json_value $x:ident, i64) => { $x.as_i64() };
(@as_json_value $x:ident, u64) => { $x.as_u64() };
(@as_json_value $x:ident, f64) => { $x.as_f64() };
(@as_json_value $x:ident, bool) => { $x.as_bool() };
(@as_json_value $x:ident, null) => { $x.as_null() };
}
/// This macro is defined if the `logging` feature is set.
///
/// It ignores all logging calls inside the library.
#[cfg(feature = "no_logging")]
#[macro_export]
macro_rules! debug {
(target: $target:expr, $($arg:tt)*) => {};
($($arg:tt)*) => {};
}
/// This macro is defined if the `logging` feature is not set.
///
/// It ignores all logging calls inside the library.
#[cfg(feature = "no_logging")]
#[macro_export]
macro_rules! error {
(target: $target:expr, $($arg:tt)*) => {};
($($arg:tt)*) => {};
}
/// This macro is defined if the `logging` feature is not set.
///
/// It ignores all logging calls inside the library.
#[cfg(not(feature = "logging"))]
#[macro_export]
macro_rules! info {
(target: $target:expr, $($arg:tt)*) => {};
($($arg:tt)*) => {};
}
/// This macro is defined if the `logging` feature is not set.
///
/// It ignores all logging calls inside the library.
#[cfg(feature = "no_logging")]
#[macro_export]
macro_rules! log {
(target: $target:expr, $($arg:tt)*) => {};
($($arg:tt)*) => {};
}
/// This macro is defined if the `logging` feature is not set.
///
/// It ignores all logging calls inside the library.
#[cfg(feature = "no_logging")]
#[macro_export]
macro_rules! trace {
(target: $target:expr, $($arg:tt)*) => {};
($($arg:tt)*) => {};
}
/// This macro is defined if the `logging` feature is not set.
///
/// It ignores all logging calls inside the library.
#[cfg(feature = "no_logging")]
#[macro_export]
macro_rules! warn {
(target: $target:expr, $($arg:tt)*) => {};
($($arg:tt)*) => {};
}
|
//! 1D linear regression.
use std::fmt;
/// A linear regression predictor.
#[derive(Clone, Debug)]
pub struct LinearRegression {
pub slope: f64,
pub offset: f64,
pub error_r2: f64,
}
impl LinearRegression {
/// Train a linear regression using the least square error.
pub fn train(x: &[f64], y: &[f64]) -> LinearRegression {
assert_eq!(x.len(), y.len());
let x_mean = mean(x);
let y_mean = mean(y);
let mut a = 0f64;
let mut b = 0f64;
for (x, y) in x.iter().zip(y) {
a += (x - x_mean) * (y - y_mean);
b += (x - x_mean).powi(2);
}
let slope = a / b;
let offset = y_mean - slope * x_mean;
let mut ss_reg = 0f64;
let mut ss_tot = 0f64;
for (x, y) in x.iter().zip(y) {
ss_reg += (x * slope + offset - y).powi(2);
ss_tot += (y_mean - y).powi(2);
}
LinearRegression {
slope,
offset,
error_r2: 1.0 - ss_reg / ss_tot,
}
}
}
impl fmt::Display for LinearRegression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"y = {:.4e} * x + {:.2}, r2 = {:.8}",
self.slope, self.offset, self.error_r2
)
}
}
/// Computes the mean value of a slice.
pub fn mean(x: &[f64]) -> f64 {
x.iter().sum::<f64>() / (x.len() as f64)
}
|
#![link(name="git2")]
extern crate git2;
use git2::git2;
use std::io::TempDir;
#[test]
fn test_init_01() {
let dir = TempDir::new("git2_test1").unwrap();
println!("new test repo in {}", dir.path().display());
let bare = false;
let repo = match git2::Repository::init(dir.path(), bare) {
Ok(r) => r,
Err(e) => fail!("Failed to init repo:\n{}", e.message)
};
assert!(repo.is_bare() == bare);
assert!(repo.is_empty() == true);
}
#[test]
fn test_init_02() {
let dir = TempDir::new("git2_test1").unwrap();
println!("new test repo in {}", dir.path().display());
let bare = true;
let repo = match git2::Repository::init(dir.path(), bare) {
Ok(r) => r,
Err(e) => fail!("Failed to init repo:\n{}", e.message)
};
assert!(repo.is_bare() == bare);
assert!(repo.is_empty() == true);
assert!(repo.is_shallow() == false);
let path = repo.path();
println!("{}", path.display());
assert!(&path == dir.path());
}
#[test]
fn test_clone_https() {
let dir = TempDir::new("git2_test1").unwrap();
println!("Cloning into {}", dir.path().display());
let result = git2::clone("https://github.com/eminence/libgit2-rs.git", dir.path(), None);
let repo = match result {
Err(e) => fail!("Failed to clone! {}", e),
Ok(r) => r
};
assert!(repo.is_bare() == false);
}
#[test]
fn test_clone_http() {
let dir = TempDir::new("git2_test1").unwrap();
println!("Cloning into {}", dir.path().display());
let result = git2::clone("http://github.com/eminence/libgit2-rs.git", dir.path(), None);
let repo = match result {
Err(e) => fail!("Failed to clone! {}", e),
Ok(r) => r
};
assert!(repo.is_bare() == false);
}
#[test]
fn test_clone_git() {
use git2::git2::ToOID;
let dir = TempDir::new("git2_test1").unwrap();
println!("Cloning into {}", dir.path().display());
let result = git2::clone("git://github.com/eminence/libgit2-rs.git", dir.path(), None);
let repo = match result {
Err(e) => fail!("Failed to clone! {}", e),
Ok(r) => r
};
assert!(repo.is_bare() == false);
let commit = repo.lookup_commit("444ff52ddb1f2f4b6a5627d57a5dd6d5a9fc86fd").unwrap();
println!("commit.message() -->{}<--", commit.message());
assert!(commit.message().as_slice() == "Added capability and version check\n");
assert!(commit.author().name.as_slice() == "Andrew Chin");
assert!(commit.author().email.as_slice() == "achin@eminence32.net");
assert!(commit.parentcount() == 1);
let parent = match commit.parent(0) {
Err(r) => fail!("Failed to get parent! {}", r),
Ok(p) => p
};
assert!(parent.id().to_string().as_slice() == "e7abafb574c707ba9906e90c1dc03126bab98973");
assert!(parent.id() == "e7abafb574c707ba9906e90c1dc03126bab98973".to_oid().unwrap());
}
#[test]
fn test_libgit2_caps() {
let caps = git2::capabilities();
println!("caps: {}", caps.bits());
println!("Has Threads: {}", caps.contains(git2::GIT_CAP_THREADS));
println!("Has SSH: {}", caps.contains(git2::GIT_CAP_SSH));
println!("Has HTTPS: {}", caps.contains(git2::GIT_CAP_HTTPS));
}
#[test]
fn test_libgit2_version() {
let version = git2::version();
println!("Version: {}", version);
assert!(git2::version_check(false) == true);
}
|
use std::error::Error;
/// HTTP Client used to call the OANDA web services.
#[derive(Debug)]
pub struct Client {
/// The reqwest object to use. Note that this is a synchronous client
/// that cannot be used in async code.
pub reqwest: reqwest::blocking::Client,
/// OANDA host to use (do not include https://)
pub host: String,
/// OANDA API key
pub authentication: String,
}
macro_rules! client_requests {
( $( $func:ident ( $request:ident ) -> $response:ident ),* ) => {
$(
use $request;
use $response;
impl Client {
pub fn $func( &self, x: $request ) -> Result<$response, Box<dyn Error>> {
x.remote(&self)
}
}
)*
};
}
client_requests!( candles(GetInstrumentCandlesRequest) -> GetInstrumentCandlesResponse,
orderbook(GetOrderBookRequest) -> GetOrderBookResponse,
positionbook(GetPositionBookRequest) -> GetPositionBookResponse,
pricing(GetPricesRequest) -> GetPricesResponse,
accounts(ListAccountsRequest) -> ListAccountsResponse,
account_summary(GetAccountSummaryRequest) -> GetAccountSummaryResponse);
|
use mode::{Mode, normal, Transition};
use mode_map::ModeMap;
use op::{InsertOp, PendingOp, NormalOp};
use state::State;
use typeahead::{Parse, RemapType};
use client;
pub struct StateMachine<K>
where
K: Ord,
K: Copy,
K: Parse,
{
state: State<K>,
mode: Mode<K>,
}
impl<K> StateMachine<K>
where
K: Ord,
K: Copy,
K: Parse,
{
pub fn new(
client: Box<client::Client>,
normal_map: ModeMap<K, NormalOp>,
pending_map: ModeMap<K, PendingOp>,
insert_map: ModeMap<K, InsertOp>,
) -> Self {
StateMachine {
state: State::new(client, normal_map, pending_map, insert_map),
mode: normal(),
}
}
pub fn process(&mut self, key: K) {
self.state.put(key, RemapType::Remap);
self.mode = self.mode.transition(&mut self.state);
}
pub fn mode(&self) -> &'static str {
self.mode.name()
}
}
|
#[cfg(test)]
mod tests {
#[test]
fn should_not_panic() {
#[cfg(feature = "foo")]
panic!("should not foo");
println!("aaa");
}
}
|
use std::fs::File;
use std::io::prelude::*;
use std::{thread, time};
use std::collections::HashSet;
use std::collections::HashMap;
use serde_json::json;
extern crate nalgebra as na;
use crate::structs;
use na::Point2;
use na::Vector2;
use std::collections::BTreeSet;
use structs::Deck;
use structs::DeckPosition;
pub fn smacofmajorization(decks: &Vec<Deck>, lands: &Vec<String>, colormapping: &HashMap<String, (u32,u32,u32,u32,u32)>) {
let x = Deck::get_dissimilarity_matrix( decks.clone(), lands );
//the tensormajorization needs
let towrite = json!( x ).to_string();
let mut file = File::create("dissimilaritiesmatrix.json").unwrap();
file.write_all( towrite.as_bytes() ).unwrap();
//the colors of the decks
let mut deckcolours: Vec<(f32,f32,f32)> = Vec::new();
for deck in decks{
deckcolours.push ( deck.get_color( colormapping ) );
}
let towrite = json!( deckcolours ).to_string();
let mut file = File::create("deckcolours.json").unwrap();
file.write_all( towrite.as_bytes() ).unwrap();
//the cards in the decks
let mut deckcards: Vec<Vec<String>> = Vec::new();
for deck in decks{
deckcards.push( deck.cards.clone() );
}
let towrite = json!( deckcards ).to_string();
let mut file = File::create("deckcards.json").unwrap();
file.write_all( towrite.as_bytes() ).unwrap();
}
pub fn manual_majorization(decks: Vec<Deck>, colormapping: &HashMap<String, (u32,u32,u32,u32,u32)>) {
let mut posdecks = Vec::new();
for deck in decks{
posdecks.push( DeckPosition::from_deck_with_random_initialization(&deck) );
}
//used to normalize how much the objects should move
//the objects should move on average 0.05 units per tick
let mut normalizationamount = 1.;
for x in 0..1500{
let mut curtotalmovement = 0.;
for deckid in 0..posdecks.len(){
curtotalmovement += improve_deck_position(&mut posdecks, deckid, normalizationamount);
}
curtotalmovement = curtotalmovement/(posdecks.len() as f32);
//should
normalizationamount = 1.0;// ((1.0/(curtotalmovement + 0.1)) * 0.2 ).min(10.0) *0.2 + normalizationamount*0.8;
use crate::actions::draw;
println!("sts{:?}", DeckPosition::get_stress_score(&posdecks));
draw::draw_decks(&posdecks, "manmaj", &colormapping);
}
}
fn improve_deck_position(decks: &mut Vec<DeckPosition>, target: usize, multiplier: f32) -> f32{
let targetdeckcopy = decks[target].clone();
let deltapos = targetdeckcopy.get_repulsion_vector_batch(&decks) * multiplier;
decks[target].move_pos(deltapos);
return deltapos.magnitude();
}
|
use std::sync::Arc;
use failure::Fallible;
use headless_chrome::{Browser, LaunchOptions, Tab, browser::tab::SyncSendEvent, protocol::Event};
fn start() -> Fallible<()> {
let browser = Browser::new(LaunchOptions {
headless: false,
..Default::default()
})?;
let tab = browser.wait_for_initial_tab().unwrap();
tab.navigate_to("https://www.google.com")
.expect("failed to navigate");
tab.wait_until_navigated().unwrap();
let sync_event = SyncSendEvent(
tab.clone(),
Box::new(move |event: &Event, tab: &Tab| {
match event {
Event::Lifecycle(lifecycle) => {
if lifecycle.params.name == "DOMContentLoaded" {
println!("{}",tab.get_url());
}
}
_ => {}
}
}),
);
tab.add_event_listener(Arc::new(sync_event)).unwrap();
Ok(())
}
fn main() -> Fallible<()> {
start()
}
|
pub mod org_bluez_adapter1;
pub mod org_bluez_device1;
pub mod org_bluez_gatt_service1;
pub mod org_bluez_gatt_characteristic1;
pub mod org_bluez_gatt_descriptor1;
pub mod utils;
pub mod dbus_processor;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
//! Websocket server implementation
//!
//! The websocket uses Tokio under the hood and manages a state for each connection. It also shares
//! the latest token to all clients and logs every events concerning connecting and disconnecting.
use std::fmt::Debug;
use std::rc::Rc;
use std::cell::RefCell;
use std::path::PathBuf;
use websocket::WebSocketError;
use websocket::message::OwnedMessage;
use websocket::server::InvalidConnection;
use websocket::r#async::Server;
use tokio_core::reactor::{Handle, Core};
use futures::{Future, Sink, Stream, sync::mpsc::{Sender, channel}};
use crate::state::State;
use hex_conf::Conf;
use hex_server_protocol::{Answer, AnswerAction};
use hex_database::{Instance, GossipConf, TransitionAction};
/// Start the websocket server, supplied with a configuration
pub fn start(conf: Conf, path: PathBuf) {
let mut core = Core::new().unwrap();
let handle = core.handle();
// bind to the server
let addr = ("0.0.0.0", conf.server.port);
let incoming = Server::bind(addr, &handle).unwrap().incoming();
let mut gossip = GossipConf::new();
if let Some(ref peer) = conf.peer {
gossip = gossip.addr((conf.host, peer.port));
gossip = gossip.id(peer.id());
gossip = gossip.network_key(peer.network_key());
gossip = gossip.contacts(peer.contacts.clone());
gossip = gossip.discover(peer.discover);
}
let mut instance = Instance::from_file(&path.join("music.db"), gossip);
let (read, write) = (instance.reader(), instance.writer());
let broadcasts: Rc<RefCell<Vec<Sender<TransitionAction>>>> = Rc::new(RefCell::new(Vec::new()));
// a stream of incoming connections
let f = incoming
.map(|x| Some(x))
// we don't wanna save the stream if it drops
.or_else(|InvalidConnection { error, .. }| {
eprintln!("Error = {:?}", error);
Ok(None)
}).filter_map(|x| x)
.for_each(|(upgrade, addr)| {
info!("Got a connection from {} (to {})", addr, upgrade.uri());
// check if it has the protocol we want
if !upgrade.protocols().iter().any(|s| s == "rust-websocket") {
// reject it if it doesn't
spawn_future(upgrade.reject(), &handle);
return Ok(());
}
let handle2 = handle.clone();
let path_cpy = path.clone();
let (read, write) = (read.clone(), write.clone());
let (s, r) = channel(1024);
broadcasts.borrow_mut().push(s);
// accept the request to be a ws connection if it does
let f = upgrade
.use_protocol("rust-websocket")
.accept()
.and_then(move |(s,_)| {
let mut state = State::new(handle2, &path_cpy, read, write);
let (sink, stream) = s.split();
let stream = stream.filter_map(move |m| {
match m {
OwnedMessage::Ping(p) => Some(OwnedMessage::Pong(p)),
OwnedMessage::Pong(_) => None,
OwnedMessage::Text(_) => Some(OwnedMessage::Text("Text not supported".into())),
OwnedMessage::Binary(data) => state.process(data).map(|x| OwnedMessage::Binary(x)),
OwnedMessage::Close(_) => {
info!("Client disconnected from {}", addr);
Some(OwnedMessage::Close(None))
}
}
})
.or_else(|e| {
eprintln!("Got websocket error = {:?}", e);
Ok(OwnedMessage::Close(None))
});
// forward transitions
let push = r.and_then(|x| {
Answer::new([0u32; 4], Ok(AnswerAction::Transition(x))).to_buf()
.map(|x| OwnedMessage::Binary(x))
.map_err(|_| ())
}).map_err(|_| WebSocketError::NoDataAvailable);
Stream::select(stream, push)
.forward(sink)
.and_then(move |(_, sink)| {
sink.send(OwnedMessage::Close(None))
})
});
spawn_future(f, &handle);
Ok(())
});
let tmp = broadcasts.clone();
let c = instance.for_each(|x| {
let mut senders = tmp.borrow_mut();
senders.retain(|x| !x.is_closed());
for i in &mut *senders {
if let Err(err) = i.try_send(x.clone()) {
eprintln!("Got error: {}", err);
}
}
Ok(())
});
core.run(Future::join(f, c)).unwrap();
}
fn spawn_future<F, I, E>(f: F, handle: &Handle)
where F: Future<Item = I, Error = E> + 'static,
E: Debug
{
handle.spawn(f.map_err(move |_| ())
.map(move |_| ()));
}
|
#[doc = "Reader of register TDCR"]
pub type R = crate::R<u32, super::TDCR>;
#[doc = "Reader of field `TDCF`"]
pub type TDCF_R = crate::R<u8, u8>;
#[doc = "Reader of field `TDCO`"]
pub type TDCO_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:6 - Transmitter Delay Compensation Filter Window Length"]
#[inline(always)]
pub fn tdcf(&self) -> TDCF_R {
TDCF_R::new((self.bits & 0x7f) as u8)
}
#[doc = "Bits 8:14 - Transmitter Delay Compensation Offset"]
#[inline(always)]
pub fn tdco(&self) -> TDCO_R {
TDCO_R::new(((self.bits >> 8) & 0x7f) as u8)
}
}
|
use anyhow::Result;
use clap::{Parser, Subcommand};
use mdbook::preprocess::{CmdPreprocessor, Preprocessor};
use mdbook_plantuml::plantuml_config;
use std::io;
use std::process;
#[derive(Parser)]
#[clap(version, author, about)]
pub struct Args {
/// Log to './output.log'
///
/// (may help troubleshooting rendering issues).
#[clap(short, long)]
log: bool,
#[clap(subcommand)]
command: Option<Command>,
}
#[derive(Subcommand)]
pub enum Command {
/// Check whether a renderer is supported by this preprocessor
Supports { renderer: String },
}
fn main() {
let args = Args::parse();
let preprocessor = mdbook_plantuml::Preprocessor;
if let Some(Command::Supports { renderer }) = args.command {
handle_supports(&preprocessor, &renderer);
} else if let Err(e) = handle_preprocessing(&preprocessor, args.log) {
panic!("{}", e);
}
}
fn handle_preprocessing(pre: &dyn Preprocessor, log_to_file: bool) -> Result<()> {
let (ctx, book) = CmdPreprocessor::parse_input(io::stdin())?;
let config = plantuml_config(&ctx);
setup_logging(log_to_file, config.verbose)?;
log::debug!(
"============================== Starting preprocessor ============================"
);
if ctx.mdbook_version != mdbook::MDBOOK_VERSION {
// We should probably use the `semver` crate to check compatibility
// here...
eprintln!(
"Warning: The {} plugin was built against version {} of mdbook, but we're being \
called from version {}",
pre.name(),
mdbook::MDBOOK_VERSION,
ctx.mdbook_version
);
}
// Preprocess the book
let processed_book = pre.run(&ctx, book)?;
// And let mdbook know the result
serde_json::to_writer(io::stdout(), &processed_book)?;
// Save the output to file too (uncomment when debugging)
// use std::fs::File;
// match File::create("mdbook-plantuml_back-to-mdbook.json") {
// Err(why) => eprintln!("couldn't open mdbook-plantuml_back-to-mdbook.json: {}", why),
// Ok(file) => serde_json::to_writer_pretty(file, &processed_book)?,
// };
Ok(())
}
fn handle_supports(pre: &dyn Preprocessor, renderer: &str) -> ! {
// Signal whether the renderer is supported by exiting with 1 or 0.
if pre.supports_renderer(renderer) {
process::exit(0);
} else {
process::exit(1);
}
}
fn setup_logging(log_to_file: bool, verbose: bool) -> Result<()> {
use log::LevelFilter;
use log4rs::append::console::{ConsoleAppender, Target};
use log4rs::append::file::FileAppender;
use log4rs::filter::threshold::ThresholdFilter;
use log4rs::config::{Appender, Config, Root};
use log4rs::encode::pattern::PatternEncoder;
// Whatever you do, DO NOT, log to stdout. Stdout is only for communication with mdbook
let log_std_err = ConsoleAppender::builder().target(Target::Stderr).build();
let mut config_builder = Config::builder().appender({
let log_level = if verbose {
LevelFilter::Debug
} else {
LevelFilter::Info
};
Appender::builder()
.filter(Box::new(ThresholdFilter::new(log_level)))
.build("logstderr", Box::new(log_std_err))
});
if log_to_file {
let logfile = FileAppender::builder()
.encoder(Box::new(PatternEncoder::new("{l} - {m}\n")))
.build("output.log")?;
config_builder =
config_builder.appender(Appender::builder().build("logfile", Box::new(logfile)));
}
let mut root_builder = Root::builder();
root_builder = root_builder.appender("logstderr");
if log_to_file {
root_builder = root_builder.appender("logfile");
}
let config = config_builder.build(root_builder.build(LevelFilter::Debug))?;
log4rs::init_config(config)?;
Ok(())
}
|
use common::*;
mod depgraph;
mod occ;
use futures::{future, stream, FutureExt, StreamExt};
use rocksdb::DB;
use rustop::opts;
use web3::types::U256;
// define a "trait alias" (see https://www.worthe-it.co.za/blog/2017-01-15-aliasing-traits-in-rust.html)
trait BlockDataStream: stream::Stream<Item = (u64, (Vec<U256>, Vec<rpc::TxInfo>))> {}
impl<T> BlockDataStream for T where T: stream::Stream<Item = (u64, (Vec<U256>, Vec<rpc::TxInfo>))> {}
async fn occ_detailed_stats(
trace_db: &DB,
batch_size: usize,
stream: impl BlockDataStream + Unpin,
) {
println!("block,num_txs,num_conflicts,serial_gas_cost,pool_t_2,pool_t_4,pool_t_8,pool_t_16,pool_t_all,optimal_t_2,optimal_t_4,optimal_t_8,optimal_t_16,optimal_t_all");
let mut stream = stream.chunks(batch_size);
while let Some(batch) = stream.next().await {
let mut blocks = vec![];
let mut txs = vec![];
let mut gas = vec![];
let mut info = vec![];
for (block, (batch_gas, batch_info)) in batch {
blocks.push(block);
txs.extend(db::tx_infos(&trace_db, block, &batch_info).into_iter());
gas.extend(batch_gas.into_iter());
info.extend(batch_info.into_iter());
}
assert_eq!(txs.len(), gas.len());
assert_eq!(txs.len(), info.len());
let num_txs = txs.len();
let num_conflicts = occ::num_conflicts(&txs);
let serial = gas.iter().fold(U256::from(0), |acc, item| acc + item);
let occ = |num_threads| {
occ::thread_pool(
&txs,
&gas,
&info,
num_threads,
false, // allow_ignore_slots
false, // allow_avoid_conflicts_during_scheduling
false, // allow_read_from_uncommitted
)
};
let pool_t_2_q_0 = occ(2);
let pool_t_4_q_0 = occ(4);
let pool_t_8_q_0 = occ(8);
let pool_t_16_q_0 = occ(16);
let pool_t_all_q_0 = occ(txs.len());
let graph = depgraph::DependencyGraph::simple(&txs, &info);
let optimal_t_2 = graph.cost(&gas, 2);
let optimal_t_4 = graph.cost(&gas, 4);
let optimal_t_8 = graph.cost(&gas, 8);
let optimal_t_16 = graph.cost(&gas, 16);
let optimal_t_all = graph.cost(&gas, txs.len());
let block = blocks
.into_iter()
.map(|b| b.to_string())
.collect::<Vec<String>>()
.join("-");
println!(
"{},{},{},{},{},{},{},{},{},{},{},{},{},{}",
block,
num_txs,
num_conflicts,
serial,
pool_t_2_q_0,
pool_t_4_q_0,
pool_t_8_q_0,
pool_t_16_q_0,
pool_t_all_q_0,
optimal_t_2,
optimal_t_4,
optimal_t_8,
optimal_t_16,
optimal_t_all,
);
}
}
#[allow(dead_code)]
fn stream_from_rpc(provider: &str, from: u64, to: u64) -> web3::Result<impl BlockDataStream> {
// connect to node
let transport = web3::transports::Http::new(provider)?;
let web3 = web3::Web3::new(transport);
// stream RPC results
let gas_and_infos = stream::iter(from..=to)
.map(move |b| {
let web3_clone = web3.clone();
let gas = tokio::spawn(async move {
rpc::gas_parity(&web3_clone, b)
.await
.expect("parity_getBlockReceipts RPC should succeed")
});
let web3_clone = web3.clone();
let infos = tokio::spawn(async move {
rpc::tx_infos(&web3_clone, b)
.await
.expect("eth_getBlock RPC should succeed")
.expect("block should exist")
});
future::join(gas, infos)
.map(|(gas, infos)| (gas.expect("future OK"), infos.expect("future OK")))
})
.buffered(10);
let blocks = stream::iter(from..=to);
let stream = blocks.zip(gas_and_infos);
Ok(stream)
}
#[allow(dead_code)]
fn stream_from_db(db_path: &str, from: u64, to: u64) -> impl BlockDataStream {
let rpc_db = db::RpcDb::open_for_read_only(db_path).expect("db open succeeds");
let gas_and_infos = stream::iter(from..=to).map(move |block| {
let gas = rpc_db
.gas_used(block)
.expect(&format!("get gas #{} failed", block)[..])
.expect(&format!("#{} not found in db", block)[..]);
let info = rpc_db
.tx_infos(block)
.expect(&format!("get infos #{} failed", block)[..])
.expect(&format!("#{} not found in db", block)[..]);
(gas, info)
});
let blocks = stream::iter(from..=to);
let stream = blocks.zip(gas_and_infos);
stream
}
#[tokio::main]
async fn main() -> web3::Result<()> {
// parse args
let (args, _) = opts! {
opt from:u64, desc:"Process from this block number.";
opt to:u64, desc:"Process up to (and including) this block number.";
opt traces:String, desc:"Path to trace DB.";
opt rpc_db:Option<String>, desc:"Path to RPC DB (optional).";
opt rpc_provider:Option<String>, desc:"RPC provider URL (optional).";
opt batch_size:usize=1, desc:"Size of block batch (optional).";
}
.parse_or_exit();
if args.rpc_db.is_none() && args.rpc_provider.is_none() {
println!("Error: you need to specify one of '--rpc-db' and '--rpc-provider'.");
println!("Try --help for help.");
return Ok(());
}
// open db and validate args
let trace_db = db::open_traces(&args.traces);
let latest_raw = trace_db
.get(b"latest")
.expect("get latest should succeed")
.expect("latest should exist");
let latest = std::str::from_utf8(&latest_raw[..])
.expect("parse to string succeed")
.parse::<u64>()
.expect("parse to int should succees");
if args.to > latest {
println!("Latest header in trace db: #{}", latest);
return Ok(());
}
// initialize logger
env_logger::builder()
.format_timestamp(None)
.format_level(false)
.format_module_path(false)
.init();
// process all blocks in range
match (args.rpc_db, args.rpc_provider) {
(Some(rpc_db), _) => {
let stream = stream_from_db(&rpc_db, args.from, args.to);
occ_detailed_stats(&trace_db, args.batch_size, stream).await;
}
(_, Some(rpc_provider)) => {
let stream = stream_from_rpc(&rpc_provider, args.from, args.to)?;
occ_detailed_stats(&trace_db, args.batch_size, stream).await;
}
_ => unreachable!(),
};
Ok(())
}
|
use std::fmt;
pub mod roll;
use serde::Serialize;
#[derive(Serialize, Debug, PartialEq, Eq, Clone)]
pub enum DiceExpression {
Many(Vec<DiceExpression>),
Sum(Box<DiceExpression>),
Max(Box<DiceExpression>),
Min(Box<DiceExpression>),
Add(Box<DiceExpression>, Box<DiceExpression>),
Multiply(Box<DiceExpression>, Box<DiceExpression>),
Equal(Box<DiceExpression>, Box<DiceExpression>),
LessThan(Box<DiceExpression>, Box<DiceExpression>),
Negative(Box<DiceExpression>),
Constant(i64),
Die(i64),
DieOutcome(i64, i64),
}
use DiceExpression::*;
impl From<i64> for DiceExpression {
fn from(val: i64) -> Self {
Constant(val)
}
}
impl fmt::Display for DiceExpression {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Constant(i) => write!(f, "{}", i),
Die(sides) => write!(f, "d{}", sides),
Sum(e) => {
match &**e {
//?????
Many(v) => write!(
f,
"{}",
v.iter()
.map(|x| format!("{}", x))
.collect::<Vec<String>>()
.join(" + ")
),
_ => write!(f, "sum({})", e),
}
}
Negative(e) => {
if e.size() > 1 {
write!(f, "-({})", e)
} else {
write!(f, "-{}", e)
}
}
Max(e) => write!(f, "max({})", e),
Min(e) => write!(f, "min({})", e),
Add(left, right) => write!(f, "{} + {}", left, right),
Multiply(left, right) => {
if right.size() > 1 {
write!(f, "{} * ({})", left, right)
} else {
write!(f, "{} * {}", left, right)
}
}
Equal(left, right) => {
let mut form = String::from("");
if left.size() > 1 {
form = form + &format!("({})", left);
} else {
form = form + &format!("{}", left);
}
form = form + " = ";
if right.size() > 1 {
form = form + &format!("({})", right);
} else {
form = form + &format!("{}", right);
}
write!(f, "{}", form)
}
LessThan(left, right) => {
let mut form = String::from("");
if left.size() > 1 {
form = form + &format!("({})", left);
} else {
form = form + &format!("{}", left);
}
form = form + " < ";
if right.size() > 1 {
form = form + &format!("({})", right);
} else {
form = form + &format!("{}", right);
}
write!(f, "{}", form)
}
Many(v) => write!(
f,
"{}",
v.iter()
.fold(String::new(), |acc, val| acc
+ format!("{}", val).as_str()
+ ",")
.trim_end_matches(',')
),
DieOutcome(sides, result) => write!(f, "(d{}):{}", sides, result),
}
}
}
impl DiceExpression {
// Return true if only a single constant
pub fn trivial(&self) -> bool {
match self {
Constant(_) => true,
_ => false,
}
}
// Return the number of elements
pub fn size(&self) -> usize {
match self {
Sum(e) | Negative(e) | Min(e) | Max(e) => 1 + e.size(),
Many(v) => v.iter().fold(0, |acc, x| acc + x.size()),
Add(l, r) | Multiply(l, r) | Equal(l, r) | LessThan(l, r) => 1 + l.size() + r.size(),
Constant(_) => 1,
Die(_) | DieOutcome(_, _) => 1,
}
}
// Return the number of elements
pub fn number_of_rolls(&self) -> usize {
match self {
Sum(e) | Negative(e) | Min(e) | Max(e) => e.number_of_rolls(),
Many(v) => v.iter().fold(0, |acc, x| acc + x.number_of_rolls()),
Add(l, r) | Multiply(l, r) | Equal(l, r) | LessThan(l, r) => {
l.number_of_rolls() + r.number_of_rolls()
}
Constant(_) => 0,
Die(_) | DieOutcome(_, _) => 1,
}
}
pub fn sum(self) -> DiceExpression {
Sum(Box::new(self))
}
pub fn add(self, other: DiceExpression) -> DiceExpression {
Add(Box::new(self), Box::new(other))
}
pub fn negate(self) -> DiceExpression {
Negative(Box::new(self))
}
pub fn subtract(self, other: DiceExpression) -> DiceExpression {
self.add(other.negate())
}
pub fn multiply(self, other: DiceExpression) -> DiceExpression {
Multiply(Box::new(self), Box::new(other))
}
pub fn also(self, other: DiceExpression) -> DiceExpression {
Many(vec![self, other])
}
pub fn eq(self, other: DiceExpression) -> DiceExpression {
Equal(Box::new(self), Box::new(other))
}
pub fn lt(self, other: DiceExpression) -> DiceExpression {
LessThan(Box::new(self), Box::new(other))
}
pub fn gt(self, other: DiceExpression) -> DiceExpression {
LessThan(Box::new(other), Box::new(self))
}
pub fn repeat(self, times: i64) -> DiceExpression {
if times > 1 {
Many((0..times).map(|_| self.clone()).collect())
} else {
self
}
}
pub fn max(self) -> DiceExpression {
Max(Box::new(self))
}
pub fn min(self) -> DiceExpression {
Min(Box::new(self))
}
}
|
use super::*;
use std::{
collections::hash_map::{Entry, OccupiedEntry, VacantEntry},
mem::ManuallyDrop,
ptr,
};
use crate::{
marker_type::UnsafeIgnoredType,
prefix_type::WithMetadata,
sabi_types::{RMut, RRef},
};
/// The enum stored alongside the unerased HashMap.
pub(super) enum BoxedREntry<'a, K, V> {
Occupied(UnerasedOccupiedEntry<'a, K, V>),
Vacant(UnerasedVacantEntry<'a, K, V>),
}
/// A handle into an entry in a map, which is either vacant or occupied.
#[derive(StableAbi)]
#[repr(C)]
#[sabi(bound(K: 'a), bound(V: 'a))]
pub enum REntry<'a, K, V> {
/// An occupied entry
Occupied(ROccupiedEntry<'a, K, V>),
/// A vacnt entry
Vacant(RVacantEntry<'a, K, V>),
}
/////////////////////////////////////////////////////////////////////////////////////////////
#[derive(StableAbi)]
#[repr(C)]
struct ErasedOccupiedEntry<K, V>(PhantomData<(K, V)>);
#[derive(StableAbi)]
#[repr(C)]
struct ErasedVacantEntry<K, V>(PhantomData<(K, V)>);
type UnerasedOccupiedEntry<'a, K, V> = ManuallyDrop<OccupiedEntry<'a, MapKey<K>, V>>;
type UnerasedVacantEntry<'a, K, V> = ManuallyDrop<VacantEntry<'a, MapKey<K>, V>>;
impl<'a, K: 'a, V: 'a> ErasedType<'a> for ErasedOccupiedEntry<K, V> {
type Unerased = UnerasedOccupiedEntry<'a, K, V>;
}
impl<'a, K: 'a, V: 'a> ErasedType<'a> for ErasedVacantEntry<K, V> {
type Unerased = UnerasedVacantEntry<'a, K, V>;
}
/////////////////////////////////////////////////////////////////////////////////////////////
impl<'a, K, V> From<Entry<'a, MapKey<K>, V>> for BoxedREntry<'a, K, V>
where
K: Eq + Hash,
{
fn from(entry: Entry<'a, MapKey<K>, V>) -> Self {
match entry {
Entry::Occupied(entry) => entry.piped(ManuallyDrop::new).piped(BoxedREntry::Occupied),
Entry::Vacant(entry) => entry.piped(ManuallyDrop::new).piped(BoxedREntry::Vacant),
}
}
}
impl<'a, K, V> REntry<'a, K, V>
where
K: Eq + Hash,
{
pub(super) unsafe fn new(entry: &'a mut BoxedREntry<'a, K, V>) -> Self {
match entry {
BoxedREntry::Occupied(entry) => {
entry.piped(ROccupiedEntry::new).piped(REntry::Occupied)
}
BoxedREntry::Vacant(entry) => entry.piped(RVacantEntry::new).piped(REntry::Vacant),
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
impl<'a, K, V> REntry<'a, K, V> {
/// Returns a reference to the value in the entry.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::RHashMap;
///
/// let mut map: RHashMap<u32, u32> = vec![(1, 100)].into_iter().collect();
///
/// assert_eq!(map.entry(0).get(), None);
/// assert_eq!(map.entry(1).get(), Some(&100));
///
/// ```
pub fn get(&self) -> Option<&V> {
match self {
REntry::Occupied(entry) => Some(entry.get()),
REntry::Vacant(_) => None,
}
}
/// Returns a mutable reference to the value in the entry.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::RHashMap;
///
/// let mut map: RHashMap<u32, u32> = vec![(1, 100)].into_iter().collect();
///
/// assert_eq!(map.entry(0).get_mut(), None);
/// assert_eq!(map.entry(1).get_mut(), Some(&mut 100));
///
/// ```
pub fn get_mut(&mut self) -> Option<&mut V> {
match self {
REntry::Occupied(entry) => Some(entry.get_mut()),
REntry::Vacant(_) => None,
}
}
/// Inserts `default` as the value in the entry if it wasn't occupied,
/// returning a mutable reference to the value in the entry.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::RHashMap;
///
/// let mut map = RHashMap::<u32, u32>::new();
///
/// assert_eq!(map.entry(0).or_insert(100), &mut 100);
///
/// assert_eq!(map.entry(0).or_insert(400), &mut 100);
///
/// ```
pub fn or_insert(self, default: V) -> &'a mut V {
match self {
REntry::Occupied(entry) => entry.into_mut(),
REntry::Vacant(entry) => entry.insert(default),
}
}
/// Inserts `default()` as the value in the entry if it wasn't occupied,
/// returning a mutable reference to the value in the entry.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::{RHashMap, RString};
///
/// let mut map = RHashMap::<u32, RString>::new();
///
/// assert_eq!(
/// map.entry(0).or_insert_with(|| "foo".into()),
/// &mut RString::from("foo")
/// );
///
/// assert_eq!(
/// map.entry(0).or_insert_with(|| "bar".into()),
/// &mut RString::from("foo")
/// );
///
/// ```
pub fn or_insert_with<F>(self, default: F) -> &'a mut V
where
F: FnOnce() -> V,
{
match self {
REntry::Occupied(entry) => entry.into_mut(),
REntry::Vacant(entry) => entry.insert(default()),
}
}
/// Gets the key of the entry.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::{RHashMap, RString};
///
/// let mut map = RHashMap::<RString, RString>::new();
/// map.insert("foo".into(), "bar".into());
///
/// assert_eq!(map.entry("foo".into()).key(), &RString::from("foo"));
/// ```
pub fn key(&self) -> &K {
match self {
REntry::Occupied(entry) => entry.key(),
REntry::Vacant(entry) => entry.key(),
}
}
/// Allows mutating an occupied entry before doing other operations.
///
/// This is a no-op on a vacant entry.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::{RHashMap, RString};
///
/// let mut map = RHashMap::<RString, RString>::new();
/// map.insert("foo".into(), "bar".into());
///
/// assert_eq!(
/// map.entry("foo".into())
/// .and_modify(|x| x.push_str("hoo"))
/// .get(),
/// Some(&RString::from("barhoo"))
/// );
/// ```
pub fn and_modify<F>(self, f: F) -> Self
where
F: FnOnce(&mut V),
{
match self {
REntry::Occupied(mut entry) => {
f(entry.get_mut());
REntry::Occupied(entry)
}
REntry::Vacant(entry) => REntry::Vacant(entry),
}
}
/// Inserts the `V::default()` value in the entry if it wasn't occupied,
/// returning a mutable reference to the value in the entry.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::RHashMap;
///
/// let mut map = RHashMap::<u32, u32>::new();
///
/// assert_eq!(map.entry(0).or_insert(100), &mut 100);
/// assert_eq!(map.entry(0).or_default(), &mut 100);
///
/// assert_eq!(map.entry(1).or_default(), &mut 0);
///
/// ```
pub fn or_default(self) -> &'a mut V
where
V: Default,
{
match self {
REntry::Occupied(entry) => entry.into_mut(),
REntry::Vacant(entry) => entry.insert(Default::default()),
}
}
}
impl<K, V> Debug for REntry<'_, K, V>
where
K: Debug,
V: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
REntry::Occupied(entry) => Debug::fmt(entry, f),
REntry::Vacant(entry) => Debug::fmt(entry, f),
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
/// A handle into an occupied entry in a map.
#[derive(StableAbi)]
#[repr(C)]
#[sabi(bound(K: 'a), bound(V: 'a))]
pub struct ROccupiedEntry<'a, K, V> {
entry: RMut<'a, ErasedOccupiedEntry<K, V>>,
vtable: OccupiedVTable_Ref<K, V>,
_marker: UnsafeIgnoredType<OccupiedEntry<'a, K, V>>,
}
/// A handle into a vacant entry in a map.
#[derive(StableAbi)]
#[repr(C)]
#[sabi(bound(K: 'a), bound(V: 'a))]
pub struct RVacantEntry<'a, K, V> {
entry: RMut<'a, ErasedVacantEntry<K, V>>,
vtable: VacantVTable_Ref<K, V>,
_marker: UnsafeIgnoredType<VacantEntry<'a, K, V>>,
}
/////////////////////////////////////////////////////////////////////////////////////////////
impl<'a, K, V> ROccupiedEntry<'a, K, V> {
const fn vtable(&self) -> OccupiedVTable_Ref<K, V> {
self.vtable
}
}
impl<'a, K, V> ROccupiedEntry<'a, K, V> {
fn into_inner(self) -> RMut<'a, ErasedOccupiedEntry<K, V>> {
let mut this = ManuallyDrop::new(self);
unsafe { ((&mut this.entry) as *mut RMut<'a, ErasedOccupiedEntry<K, V>>).read() }
}
pub(super) fn new(entry: &'a mut UnerasedOccupiedEntry<'a, K, V>) -> Self {
unsafe {
Self {
entry: ErasedOccupiedEntry::from_unerased(entry),
vtable: OccupiedVTable::VTABLE_REF,
_marker: UnsafeIgnoredType::DEFAULT,
}
}
}
/// Gets a reference to the key of the entry.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::map::{REntry, RHashMap};
///
/// let mut map = RHashMap::<u32, u32>::new();
///
/// map.insert(0, 100);
///
/// match map.entry(0) {
/// REntry::Occupied(entry) => {
/// assert_eq!(entry.key(), &0);
/// }
/// REntry::Vacant(_) => unreachable!(),
/// };
///
/// ```
pub fn key(&self) -> &K {
let vtable = self.vtable();
vtable.key()(self.entry.as_rref())
}
/// Gets a reference to the value in the entry.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::map::{REntry, RHashMap};
///
/// let mut map = RHashMap::<u32, u32>::new();
///
/// map.insert(6, 15);
///
/// match map.entry(6) {
/// REntry::Occupied(entry) => {
/// assert_eq!(entry.get(), &15);
/// }
/// REntry::Vacant(_) => unreachable!(),
/// };
///
///
/// ```
pub fn get(&self) -> &V {
let vtable = self.vtable();
vtable.get_elem()(self.entry.as_rref())
}
/// Gets a mutable reference to the value in the entry.
/// To borrow with the lifetime of the map, use `ROccupiedEntry::into_mut`.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::map::{REntry, RHashMap};
///
/// let mut map = RHashMap::<u32, u32>::new();
///
/// map.insert(6, 15);
///
/// match map.entry(6) {
/// REntry::Occupied(mut entry) => {
/// assert_eq!(entry.get_mut(), &mut 15);
/// }
/// REntry::Vacant(_) => unreachable!(),
/// };
///
///
/// ```
pub fn get_mut(&mut self) -> &mut V {
let vtable = self.vtable();
vtable.get_mut_elem()(self.entry.reborrow())
}
/// Gets a mutable reference to the value in the entry,
/// that borrows with the lifetime of the map instead of
/// borrowing from this `ROccupiedEntry`.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::map::{REntry, RHashMap};
///
/// let mut map = RHashMap::<String, u32>::new();
///
/// map.insert("baz".into(), 0xDEAD);
///
/// match map.entry("baz".into()) {
/// REntry::Occupied(entry) => {
/// assert_eq!(entry.into_mut(), &mut 0xDEAD);
/// }
/// REntry::Vacant(_) => unreachable!(),
/// };
///
///
/// ```
pub fn into_mut(self) -> &'a mut V {
let vtable = self.vtable();
vtable.fn_into_mut_elem()(self)
}
/// Replaces the current value of the entry with `value`, returning the previous value.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::map::{REntry, RHashMap};
///
/// let mut map = RHashMap::<String, u32>::new();
///
/// map.insert("baz".into(), 0xD00D);
///
/// match map.entry("baz".into()) {
/// REntry::Occupied(mut entry) => {
/// assert_eq!(entry.insert(0xDEAD), 0xD00D);
/// }
/// REntry::Vacant(_) => {
/// unreachable!();
/// }
/// }
///
/// assert_eq!(map.get("baz"), Some(&0xDEAD));
///
/// ```
pub fn insert(&mut self, value: V) -> V {
let vtable = self.vtable();
vtable.insert_elem()(self.entry.reborrow(), value)
}
/// Removes the entry from the map, returns the value.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::map::{REntry, RHashMap};
///
/// let mut map = RHashMap::<String, u32>::new();
///
/// map.insert("baz".into(), 0xDEAD);
///
/// match map.entry("baz".into()) {
/// REntry::Occupied(entry) => {
/// assert_eq!(entry.remove(), 0xDEAD);
/// }
/// REntry::Vacant(_) => {
/// unreachable!();
/// }
/// }
///
/// assert!(!map.contains_key("baz"));
///
/// ```
pub fn remove(self) -> V {
let vtable = self.vtable();
vtable.remove()(self)
}
}
impl<K, V> Debug for ROccupiedEntry<'_, K, V>
where
K: Debug,
V: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ROccupiedEntry")
.field("key", self.key())
.field("value", self.get())
.finish()
}
}
impl<'a, K, V> Drop for ROccupiedEntry<'a, K, V> {
fn drop(&mut self) {
let vtable = self.vtable();
unsafe {
vtable.drop_entry()(self.entry.reborrow());
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
impl<'a, K, V> RVacantEntry<'a, K, V> {
const fn vtable(&self) -> VacantVTable_Ref<K, V> {
self.vtable
}
}
impl<'a, K, V> RVacantEntry<'a, K, V> {
fn into_inner(self) -> RMut<'a, ErasedVacantEntry<K, V>> {
let mut this = ManuallyDrop::new(self);
unsafe { ((&mut this.entry) as *mut RMut<'a, ErasedVacantEntry<K, V>>).read() }
}
pub(super) fn new(entry: &'a mut UnerasedVacantEntry<'a, K, V>) -> Self
where
K: Eq + Hash,
{
unsafe {
Self {
entry: ErasedVacantEntry::from_unerased(entry),
vtable: VacantVTable::VTABLE_REF,
_marker: UnsafeIgnoredType::DEFAULT,
}
}
}
/// Gets a reference to the key of the entry.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::map::{REntry, RHashMap};
///
/// let mut map = RHashMap::<u32, u32>::new();
///
/// match map.entry(1337) {
/// REntry::Occupied(_) => {
/// unreachable!();
/// }
/// REntry::Vacant(entry) => {
/// assert_eq!(entry.key(), &1337);
/// }
/// }
///
/// assert_eq!(map.get(&1337), None);
///
/// ```
pub fn key(&self) -> &K {
let vtable = self.vtable();
vtable.key()(self.entry.as_rref())
}
/// Gets back the key that was passed to `RHashMap::entry`.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::map::{REntry, RHashMap};
///
/// let mut map = RHashMap::<String, u32>::new();
///
/// match map.entry("lol".into()) {
/// REntry::Occupied(_) => {
/// unreachable!();
/// }
/// REntry::Vacant(entry) => {
/// assert_eq!(entry.into_key(), "lol".to_string());
/// }
/// }
///
/// assert_eq!(map.get("lol"), None);
///
/// ```
pub fn into_key(self) -> K {
let vtable = self.vtable();
vtable.fn_into_key()(self)
}
/// Sets the value of the entry, returning a mutable reference to it.
///
/// # Example
///
/// ```
/// use abi_stable::std_types::map::{REntry, RHashMap};
///
/// let mut map = RHashMap::<String, u32>::new();
///
/// match map.entry("lol".into()) {
/// REntry::Occupied(_) => {
/// unreachable!();
/// }
/// REntry::Vacant(entry) => {
/// assert_eq!(entry.insert(67), &mut 67);
/// }
/// }
///
/// assert_eq!(map.get("lol"), Some(&67));
///
/// ```
pub fn insert(self, value: V) -> &'a mut V {
let vtable = self.vtable();
vtable.insert_elem()(self, value)
}
}
impl<K, V> Debug for RVacantEntry<'_, K, V>
where
K: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RVacantEntry")
.field("key", self.key())
.finish()
}
}
impl<'a, K, V> Drop for RVacantEntry<'a, K, V> {
fn drop(&mut self) {
let vtable = self.vtable();
unsafe { vtable.drop_entry()(self.entry.reborrow()) }
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
#[derive(StableAbi)]
#[repr(C)]
#[sabi(kind(Prefix), missing_field(panic))]
pub struct OccupiedVTable<K, V> {
drop_entry: unsafe extern "C" fn(RMut<'_, ErasedOccupiedEntry<K, V>>),
key: extern "C" fn(RRef<'_, ErasedOccupiedEntry<K, V>>) -> &K,
get_elem: extern "C" fn(RRef<'_, ErasedOccupiedEntry<K, V>>) -> &V,
get_mut_elem: extern "C" fn(RMut<'_, ErasedOccupiedEntry<K, V>>) -> &mut V,
fn_into_mut_elem: extern "C" fn(ROccupiedEntry<'_, K, V>) -> &'_ mut V,
insert_elem: extern "C" fn(RMut<'_, ErasedOccupiedEntry<K, V>>, V) -> V,
remove: extern "C" fn(ROccupiedEntry<'_, K, V>) -> V,
}
impl<K, V> OccupiedVTable<K, V> {
const VTABLE_REF: OccupiedVTable_Ref<K, V> = OccupiedVTable_Ref(Self::WM_VTABLE.as_prefix());
staticref! {
const WM_VTABLE: WithMetadata<OccupiedVTable<K, V>> = WithMetadata::new(Self::VTABLE)
}
const VTABLE: OccupiedVTable<K, V> = OccupiedVTable {
drop_entry: ErasedOccupiedEntry::drop_entry,
key: ErasedOccupiedEntry::key,
get_elem: ErasedOccupiedEntry::get_elem,
get_mut_elem: ErasedOccupiedEntry::get_mut_elem,
fn_into_mut_elem: ErasedOccupiedEntry::fn_into_mut_elem,
insert_elem: ErasedOccupiedEntry::insert_elem,
remove: ErasedOccupiedEntry::remove,
};
}
impl<K, V> ErasedOccupiedEntry<K, V> {
unsafe extern "C" fn drop_entry(this: RMut<'_, Self>) {
unsafe {
extern_fn_panic_handling! {no_early_return;
Self::run_downcast_as_mut(this, |this| {
ManuallyDrop::drop(this);
})
}
}
}
extern "C" fn key(this: RRef<'_, Self>) -> &K {
unsafe {
extern_fn_panic_handling! {no_early_return;
Self::run_downcast_as(
this,
|this| this.key().as_ref()
)
}
}
}
extern "C" fn get_elem(this: RRef<'_, Self>) -> &V {
unsafe {
extern_fn_panic_handling! {no_early_return;
Self::run_downcast_as(
this,
|this| this.get()
)
}
}
}
extern "C" fn get_mut_elem(this: RMut<'_, Self>) -> &mut V {
unsafe {
extern_fn_panic_handling! {no_early_return;
Self::run_downcast_as_mut(
this,
|this| this.get_mut()
)
}
}
}
extern "C" fn fn_into_mut_elem(this: ROccupiedEntry<'_, K, V>) -> &'_ mut V {
unsafe {
extern_fn_panic_handling! {no_early_return;
Self::run_downcast_as_mut(
this.into_inner(),
|this| take_manuallydrop(this).into_mut()
)
}
}
}
extern "C" fn insert_elem(this: RMut<'_, Self>, elem: V) -> V {
unsafe {
extern_fn_panic_handling! {no_early_return;
Self::run_downcast_as_mut(
this,
|this| this.insert(elem)
)
}
}
}
extern "C" fn remove(this: ROccupiedEntry<'_, K, V>) -> V {
unsafe {
extern_fn_panic_handling! {no_early_return;
Self::run_downcast_as_mut(
this.into_inner(),
|this| take_manuallydrop(this).remove()
)
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
#[derive(StableAbi)]
#[repr(C)]
#[sabi(kind(Prefix), missing_field(panic))]
pub struct VacantVTable<K, V> {
drop_entry: unsafe extern "C" fn(RMut<'_, ErasedVacantEntry<K, V>>),
key: extern "C" fn(RRef<'_, ErasedVacantEntry<K, V>>) -> &K,
fn_into_key: extern "C" fn(RVacantEntry<'_, K, V>) -> K,
insert_elem: extern "C" fn(RVacantEntry<'_, K, V>, V) -> &'_ mut V,
}
impl<K, V> VacantVTable<K, V> {
const VTABLE_REF: VacantVTable_Ref<K, V> = VacantVTable_Ref(Self::WM_VTABLE.as_prefix());
staticref! {
const WM_VTABLE: WithMetadata<VacantVTable<K, V>> = WithMetadata::new(Self::VTABLE)
}
const VTABLE: VacantVTable<K, V> = VacantVTable {
drop_entry: ErasedVacantEntry::drop_entry,
key: ErasedVacantEntry::key,
fn_into_key: ErasedVacantEntry::fn_into_key,
insert_elem: ErasedVacantEntry::insert_elem,
};
}
impl<K, V> ErasedVacantEntry<K, V> {
unsafe extern "C" fn drop_entry(this: RMut<'_, Self>) {
unsafe {
extern_fn_panic_handling! {no_early_return;
Self::run_downcast_as_mut(this, |this|{
ManuallyDrop::drop(this);
})
}
}
}
extern "C" fn key(this: RRef<'_, Self>) -> &K {
unsafe {
extern_fn_panic_handling! {no_early_return;
Self::run_downcast_as(
this,
|this| this.key().as_ref()
)
}
}
}
extern "C" fn fn_into_key(this: RVacantEntry<'_, K, V>) -> K {
unsafe {
extern_fn_panic_handling! {no_early_return;
Self::run_downcast_as_mut(
this.into_inner(),
|this| take_manuallydrop(this).into_key().into_inner()
)
}
}
}
extern "C" fn insert_elem(this: RVacantEntry<'_, K, V>, elem: V) -> &'_ mut V {
unsafe {
extern_fn_panic_handling! {no_early_return;
Self::run_downcast_as_mut(
this.into_inner(),
|this| take_manuallydrop(this).insert(elem)
)
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
/// Copy paste of the unstable `ManuallyDrop::take`
unsafe fn take_manuallydrop<T>(slot: &mut ManuallyDrop<T>) -> T {
unsafe { ManuallyDrop::into_inner(ptr::read(slot)) }
}
|
use rustc_serialize::base64;
use std::{num, str, string};
#[derive(Debug)]
pub enum MacaroonError {
InitializationError,
HashFailed,
NotUTF8(str::Utf8Error),
UnknownSerialization,
DeserializationError(String),
BadMacaroon(&'static str),
KeyError(&'static str),
DecryptionError(&'static str),
}
impl From<serde_json::Error> for MacaroonError {
fn from(error: serde_json::Error) -> MacaroonError {
MacaroonError::DeserializationError(format!("{}", error))
}
}
impl From<string::FromUtf8Error> for MacaroonError {
fn from(error: string::FromUtf8Error) -> MacaroonError {
MacaroonError::DeserializationError(format!("{}", error))
}
}
impl From<base64::FromBase64Error> for MacaroonError {
fn from(error: base64::FromBase64Error) -> MacaroonError {
MacaroonError::DeserializationError(format!("{}", error))
}
}
impl From<num::ParseIntError> for MacaroonError {
fn from(error: num::ParseIntError) -> MacaroonError {
MacaroonError::DeserializationError(format!("{}", error))
}
}
impl From<str::Utf8Error> for MacaroonError {
fn from(error: str::Utf8Error) -> MacaroonError {
MacaroonError::DeserializationError(format!("{}", error))
}
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Devices_Perception_Provider")]
pub mod Provider;
#[repr(transparent)]
#[doc(hidden)]
pub struct IKnownCameraIntrinsicsPropertiesStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IKnownCameraIntrinsicsPropertiesStatics {
type Vtable = IKnownCameraIntrinsicsPropertiesStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x08c03978_437a_4d97_a663_fd3195600249);
}
#[repr(C)]
#[doc(hidden)]
pub struct IKnownCameraIntrinsicsPropertiesStatics_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IKnownPerceptionColorFrameSourcePropertiesStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IKnownPerceptionColorFrameSourcePropertiesStatics {
type Vtable = IKnownPerceptionColorFrameSourcePropertiesStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5df1cca2_01f8_4a87_b859_d5e5b7e1de4b);
}
#[repr(C)]
#[doc(hidden)]
pub struct IKnownPerceptionColorFrameSourcePropertiesStatics_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IKnownPerceptionDepthFrameSourcePropertiesStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IKnownPerceptionDepthFrameSourcePropertiesStatics {
type Vtable = IKnownPerceptionDepthFrameSourcePropertiesStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5df1cca2_01f8_4a87_b859_d5e5b7e1de4a);
}
#[repr(C)]
#[doc(hidden)]
pub struct IKnownPerceptionDepthFrameSourcePropertiesStatics_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IKnownPerceptionFrameSourcePropertiesStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IKnownPerceptionFrameSourcePropertiesStatics {
type Vtable = IKnownPerceptionFrameSourcePropertiesStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5df1cca2_01f8_4a87_b859_d5e5b7e1de47);
}
#[repr(C)]
#[doc(hidden)]
pub struct IKnownPerceptionFrameSourcePropertiesStatics_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IKnownPerceptionFrameSourcePropertiesStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IKnownPerceptionFrameSourcePropertiesStatics2 {
type Vtable = IKnownPerceptionFrameSourcePropertiesStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa9c86871_05dc_4a4d_8a5c_a4ecf26bbc46);
}
#[repr(C)]
#[doc(hidden)]
pub struct IKnownPerceptionFrameSourcePropertiesStatics2_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IKnownPerceptionInfraredFrameSourcePropertiesStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IKnownPerceptionInfraredFrameSourcePropertiesStatics {
type Vtable = IKnownPerceptionInfraredFrameSourcePropertiesStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5df1cca2_01f8_4a87_b859_d5e5b7e1de49);
}
#[repr(C)]
#[doc(hidden)]
pub struct IKnownPerceptionInfraredFrameSourcePropertiesStatics_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IKnownPerceptionVideoFrameSourcePropertiesStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IKnownPerceptionVideoFrameSourcePropertiesStatics {
type Vtable = IKnownPerceptionVideoFrameSourcePropertiesStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5df1cca2_01f8_4a87_b859_d5e5b7e1de48);
}
#[repr(C)]
#[doc(hidden)]
pub struct IKnownPerceptionVideoFrameSourcePropertiesStatics_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IKnownPerceptionVideoProfilePropertiesStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IKnownPerceptionVideoProfilePropertiesStatics {
type Vtable = IKnownPerceptionVideoProfilePropertiesStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8f08e2e7_5a76_43e3_a13a_da3d91a9ef98);
}
#[repr(C)]
#[doc(hidden)]
pub struct IKnownPerceptionVideoProfilePropertiesStatics_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionColorFrame(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionColorFrame {
type Vtable = IPerceptionColorFrame_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfe621549_2cbf_4f94_9861_f817ea317747);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionColorFrame_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Media")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Media"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionColorFrameArrivedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionColorFrameArrivedEventArgs {
type Vtable = IPerceptionColorFrameArrivedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8fad02d5_86f7_4d8d_b966_5a3761ba9f59);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionColorFrameArrivedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionColorFrameReader(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionColorFrameReader {
type Vtable = IPerceptionColorFrameReader_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7650f56e_b9f5_461b_83ad_f222af2aaadc);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionColorFrameReader_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionColorFrameSource(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionColorFrameSource {
type Vtable = IPerceptionColorFrameSource_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdc6dba7c_0b58_468d_9ca1_6db04cc0477c);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionColorFrameSource_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::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, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Media_Devices_Core")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Media_Devices_Core"))] usize,
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, targetid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, targetid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, targetid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result: *mut super::super::Foundation::Numerics::Matrix4x4, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, correlateddepthframesource: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, targetsourceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, correlateddepthframesource: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, controlsession: ::windows::core::RawPtr, profile: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionColorFrameSource2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionColorFrameSource2 {
type Vtable = IPerceptionColorFrameSource2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf88008e5_5631_45ed_ad98_8c6aa04cfb91);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionColorFrameSource2_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionColorFrameSourceAddedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionColorFrameSourceAddedEventArgs {
type Vtable = IPerceptionColorFrameSourceAddedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd16bf4e6_da24_442c_bbd5_55549b5b94f3);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionColorFrameSourceAddedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionColorFrameSourceRemovedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionColorFrameSourceRemovedEventArgs {
type Vtable = IPerceptionColorFrameSourceRemovedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd277fa69_eb4c_42ef_ba4f_288f615c93c1);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionColorFrameSourceRemovedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionColorFrameSourceStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionColorFrameSourceStatics {
type Vtable = IPerceptionColorFrameSourceStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5df3cca2_01f8_4a87_b859_d5e5b7e1de49);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionColorFrameSourceStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionColorFrameSourceWatcher(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionColorFrameSourceWatcher {
type Vtable = IPerceptionColorFrameSourceWatcher_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96bd1392_e667_40c4_89f9_1462dea6a9cc);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionColorFrameSourceWatcher_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Devices_Enumeration")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::Enumeration::DeviceWatcherStatus) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Devices_Enumeration"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionControlSession(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionControlSession {
type Vtable = IPerceptionControlSession_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x99998653_5a3d_417f_9239_f1889e548b48);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionControlSession_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, value: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionDepthCorrelatedCameraIntrinsics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionDepthCorrelatedCameraIntrinsics {
type Vtable = IPerceptionDepthCorrelatedCameraIntrinsics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6548ca01_86de_5be1_6582_807fcf4c95cf);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionDepthCorrelatedCameraIntrinsics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pixelcoordinate: super::super::Foundation::Point, depthframe: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Numerics::Vector3) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Numerics")))] usize,
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sourceCoordinates_array_size: u32, sourcecoordinates: *const super::super::Foundation::Point, depthframe: ::windows::core::RawPtr, results_array_size: u32, results: *mut super::super::Foundation::Numerics::Vector3) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Numerics")))] usize,
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, region: super::super::Foundation::Rect, depthframe: ::windows::core::RawPtr, results_array_size: u32, results: *mut super::super::Foundation::Numerics::Vector3, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Numerics")))] usize,
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, depthframe: ::windows::core::RawPtr, results_array_size: u32, results: *mut super::super::Foundation::Numerics::Vector3, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Numerics")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionDepthCorrelatedCoordinateMapper(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionDepthCorrelatedCoordinateMapper {
type Vtable = IPerceptionDepthCorrelatedCoordinateMapper_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5b4d9d1d_b5f6_469c_b8c2_b97a45e6863b);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionDepthCorrelatedCoordinateMapper_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sourcepixelcoordinate: super::super::Foundation::Point, depthframe: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Point) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sourceCoordinates_array_size: u32, sourcecoordinates: *const super::super::Foundation::Point, depthframe: ::windows::core::RawPtr, results_array_size: u32, results: *mut super::super::Foundation::Point) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, region: super::super::Foundation::Rect, depthframe: ::windows::core::RawPtr, targetCoordinates_array_size: u32, targetcoordinates: *mut super::super::Foundation::Point, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, depthframe: ::windows::core::RawPtr, targetCoordinates_array_size: u32, targetcoordinates: *mut super::super::Foundation::Point, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionDepthFrame(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionDepthFrame {
type Vtable = IPerceptionDepthFrame_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa37b81fc_9906_4ffd_9161_0024b360b657);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionDepthFrame_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Media")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Media"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameArrivedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionDepthFrameArrivedEventArgs {
type Vtable = IPerceptionDepthFrameArrivedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x443d25b2_b282_4637_9173_ac978435c985);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameArrivedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameReader(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionDepthFrameReader {
type Vtable = IPerceptionDepthFrameReader_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb1a3c09f_299b_4612_a4f7_270f25a096ec);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameReader_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameSource(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionDepthFrameSource {
type Vtable = IPerceptionDepthFrameSource_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79d433d6_47fb_4df1_bfc9_f01d40bd9942);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameSource_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::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, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Media_Devices_Core")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Media_Devices_Core"))] usize,
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, targetid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, targetid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, targetid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result: *mut super::super::Foundation::Numerics::Matrix4x4, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, target: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, targetid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, depthframesourcetomapwith: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, controlsession: ::windows::core::RawPtr, profile: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameSource2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionDepthFrameSource2 {
type Vtable = IPerceptionDepthFrameSource2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe3d23d2e_6e2c_4e6d_91d9_704cd8dff79d);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameSource2_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameSourceAddedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionDepthFrameSourceAddedEventArgs {
type Vtable = IPerceptionDepthFrameSourceAddedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x93a48168_8bf8_45d2_a2f8_4ac0931cc7a6);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameSourceAddedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameSourceRemovedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionDepthFrameSourceRemovedEventArgs {
type Vtable = IPerceptionDepthFrameSourceRemovedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa0c0cc4d_e96c_4d81_86dd_38b95e49c6df);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameSourceRemovedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameSourceStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionDepthFrameSourceStatics {
type Vtable = IPerceptionDepthFrameSourceStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5df3cca2_01f8_4a87_b859_d5e5b7e1de48);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameSourceStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameSourceWatcher(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionDepthFrameSourceWatcher {
type Vtable = IPerceptionDepthFrameSourceWatcher_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x780e96d1_8d02_4d2b_ada4_5ba624a0eb10);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionDepthFrameSourceWatcher_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Devices_Enumeration")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::Enumeration::DeviceWatcherStatus) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Devices_Enumeration"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionFrameSourcePropertiesChangedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionFrameSourcePropertiesChangedEventArgs {
type Vtable = IPerceptionFrameSourcePropertiesChangedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6c68e068_bcf1_4ecc_b891_7625d1244b6b);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionFrameSourcePropertiesChangedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Collections::CollectionChange) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionFrameSourcePropertyChangeResult(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionFrameSourcePropertyChangeResult {
type Vtable = IPerceptionFrameSourcePropertyChangeResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1e33390a_3c90_4d22_b898_f42bba6418ff);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionFrameSourcePropertyChangeResult_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 PerceptionFrameSourcePropertyChangeStatus) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrame(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionInfraredFrame {
type Vtable = IPerceptionInfraredFrame_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0886276_849e_4c7a_8ae6_b56064532153);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrame_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Media")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Media"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameArrivedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionInfraredFrameArrivedEventArgs {
type Vtable = IPerceptionInfraredFrameArrivedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9f77fac7_b4bd_4857_9d50_be8ef075daef);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameArrivedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameReader(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionInfraredFrameReader {
type Vtable = IPerceptionInfraredFrameReader_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7960ce18_d39b_4fc8_a04a_929734c6756c);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameReader_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameSource(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionInfraredFrameSource {
type Vtable = IPerceptionInfraredFrameSource_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x55b08742_1808_494e_9e30_9d2a7be8f700);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameSource_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::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, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Media_Devices_Core")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Media_Devices_Core"))] usize,
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, targetid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, targetid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, targetid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result: *mut super::super::Foundation::Numerics::Matrix4x4, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, target: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, targetid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, depthframesourcetomapwith: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, controlsession: ::windows::core::RawPtr, profile: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameSource2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionInfraredFrameSource2 {
type Vtable = IPerceptionInfraredFrameSource2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdcd4d798_4b0b_4300_8d85_410817faa032);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameSource2_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameSourceAddedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionInfraredFrameSourceAddedEventArgs {
type Vtable = IPerceptionInfraredFrameSourceAddedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6d334120_95ce_4660_907a_d98035aa2b7c);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameSourceAddedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameSourceRemovedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionInfraredFrameSourceRemovedEventArgs {
type Vtable = IPerceptionInfraredFrameSourceRemovedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xea1a8071_7a70_4a61_af94_07303853f695);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameSourceRemovedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameSourceStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionInfraredFrameSourceStatics {
type Vtable = IPerceptionInfraredFrameSourceStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5df3cca2_01f8_4a87_b859_d5e5b7e1de47);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameSourceStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameSourceWatcher(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionInfraredFrameSourceWatcher {
type Vtable = IPerceptionInfraredFrameSourceWatcher_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x383cff99_d70c_444d_a8b0_720c2e66fe3b);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionInfraredFrameSourceWatcher_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Devices_Enumeration")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::Enumeration::DeviceWatcherStatus) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Devices_Enumeration"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPerceptionVideoProfile(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPerceptionVideoProfile {
type Vtable = IPerceptionVideoProfile_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x75763ea3_011a_470e_8225_6f05ade25648);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPerceptionVideoProfile_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Graphics::Imaging::BitmapPixelFormat) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
#[cfg(feature = "Graphics_Imaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Graphics::Imaging::BitmapAlphaMode) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Graphics_Imaging"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, other: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
pub struct KnownCameraIntrinsicsProperties {}
impl KnownCameraIntrinsicsProperties {
#[cfg(feature = "deprecated")]
pub fn FocalLength() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownCameraIntrinsicsPropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn PrincipalPoint() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownCameraIntrinsicsPropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn RadialDistortion() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownCameraIntrinsicsPropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn TangentialDistortion() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownCameraIntrinsicsPropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IKnownCameraIntrinsicsPropertiesStatics<R, F: FnOnce(&IKnownCameraIntrinsicsPropertiesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<KnownCameraIntrinsicsProperties, IKnownCameraIntrinsicsPropertiesStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for KnownCameraIntrinsicsProperties {
const NAME: &'static str = "Windows.Devices.Perception.KnownCameraIntrinsicsProperties";
}
pub struct KnownPerceptionColorFrameSourceProperties {}
impl KnownPerceptionColorFrameSourceProperties {
#[cfg(feature = "deprecated")]
pub fn Exposure() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionColorFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn AutoExposureEnabled() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionColorFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn ExposureCompensation() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionColorFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IKnownPerceptionColorFrameSourcePropertiesStatics<R, F: FnOnce(&IKnownPerceptionColorFrameSourcePropertiesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<KnownPerceptionColorFrameSourceProperties, IKnownPerceptionColorFrameSourcePropertiesStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for KnownPerceptionColorFrameSourceProperties {
const NAME: &'static str = "Windows.Devices.Perception.KnownPerceptionColorFrameSourceProperties";
}
pub struct KnownPerceptionDepthFrameSourceProperties {}
impl KnownPerceptionDepthFrameSourceProperties {
#[cfg(feature = "deprecated")]
pub fn MinDepth() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionDepthFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn MaxDepth() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionDepthFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IKnownPerceptionDepthFrameSourcePropertiesStatics<R, F: FnOnce(&IKnownPerceptionDepthFrameSourcePropertiesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<KnownPerceptionDepthFrameSourceProperties, IKnownPerceptionDepthFrameSourcePropertiesStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for KnownPerceptionDepthFrameSourceProperties {
const NAME: &'static str = "Windows.Devices.Perception.KnownPerceptionDepthFrameSourceProperties";
}
pub struct KnownPerceptionFrameSourceProperties {}
impl KnownPerceptionFrameSourceProperties {
#[cfg(feature = "deprecated")]
pub fn Id() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn PhysicalDeviceIds() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn FrameKind() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn DeviceModelVersion() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn EnclosureLocation() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn DeviceId() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionFrameSourcePropertiesStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IKnownPerceptionFrameSourcePropertiesStatics<R, F: FnOnce(&IKnownPerceptionFrameSourcePropertiesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<KnownPerceptionFrameSourceProperties, IKnownPerceptionFrameSourcePropertiesStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IKnownPerceptionFrameSourcePropertiesStatics2<R, F: FnOnce(&IKnownPerceptionFrameSourcePropertiesStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<KnownPerceptionFrameSourceProperties, IKnownPerceptionFrameSourcePropertiesStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for KnownPerceptionFrameSourceProperties {
const NAME: &'static str = "Windows.Devices.Perception.KnownPerceptionFrameSourceProperties";
}
pub struct KnownPerceptionInfraredFrameSourceProperties {}
impl KnownPerceptionInfraredFrameSourceProperties {
#[cfg(feature = "deprecated")]
pub fn Exposure() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionInfraredFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn AutoExposureEnabled() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionInfraredFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn ExposureCompensation() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionInfraredFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn ActiveIlluminationEnabled() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionInfraredFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn AmbientSubtractionEnabled() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionInfraredFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn StructureLightPatternEnabled() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionInfraredFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn InterleavedIlluminationEnabled() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionInfraredFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IKnownPerceptionInfraredFrameSourcePropertiesStatics<R, F: FnOnce(&IKnownPerceptionInfraredFrameSourcePropertiesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<KnownPerceptionInfraredFrameSourceProperties, IKnownPerceptionInfraredFrameSourcePropertiesStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for KnownPerceptionInfraredFrameSourceProperties {
const NAME: &'static str = "Windows.Devices.Perception.KnownPerceptionInfraredFrameSourceProperties";
}
pub struct KnownPerceptionVideoFrameSourceProperties {}
impl KnownPerceptionVideoFrameSourceProperties {
#[cfg(feature = "deprecated")]
pub fn VideoProfile() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionVideoFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn SupportedVideoProfiles() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionVideoFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn AvailableVideoProfiles() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionVideoFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn IsMirrored() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionVideoFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn CameraIntrinsics() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionVideoFrameSourcePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IKnownPerceptionVideoFrameSourcePropertiesStatics<R, F: FnOnce(&IKnownPerceptionVideoFrameSourcePropertiesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<KnownPerceptionVideoFrameSourceProperties, IKnownPerceptionVideoFrameSourcePropertiesStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for KnownPerceptionVideoFrameSourceProperties {
const NAME: &'static str = "Windows.Devices.Perception.KnownPerceptionVideoFrameSourceProperties";
}
pub struct KnownPerceptionVideoProfileProperties {}
impl KnownPerceptionVideoProfileProperties {
#[cfg(feature = "deprecated")]
pub fn BitmapPixelFormat() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionVideoProfilePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn BitmapAlphaMode() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionVideoProfilePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn Width() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionVideoProfilePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn Height() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionVideoProfilePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn FrameDuration() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IKnownPerceptionVideoProfilePropertiesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IKnownPerceptionVideoProfilePropertiesStatics<R, F: FnOnce(&IKnownPerceptionVideoProfilePropertiesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<KnownPerceptionVideoProfileProperties, IKnownPerceptionVideoProfilePropertiesStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for KnownPerceptionVideoProfileProperties {
const NAME: &'static str = "Windows.Devices.Perception.KnownPerceptionVideoProfileProperties";
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionColorFrame(pub ::windows::core::IInspectable);
impl PerceptionColorFrame {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Media")]
pub fn VideoFrame(&self) -> ::windows::core::Result<super::super::Media::VideoFrame> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Media::VideoFrame>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionColorFrame {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionColorFrame;{fe621549-2cbf-4f94-9861-f817ea317747})");
}
unsafe impl ::windows::core::Interface for PerceptionColorFrame {
type Vtable = IPerceptionColorFrame_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfe621549_2cbf_4f94_9861_f817ea317747);
}
impl ::windows::core::RuntimeName for PerceptionColorFrame {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionColorFrame";
}
impl ::core::convert::From<PerceptionColorFrame> for ::windows::core::IUnknown {
fn from(value: PerceptionColorFrame) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionColorFrame> for ::windows::core::IUnknown {
fn from(value: &PerceptionColorFrame) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionColorFrame {
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 PerceptionColorFrame {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionColorFrame> for ::windows::core::IInspectable {
fn from(value: PerceptionColorFrame) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionColorFrame> for ::windows::core::IInspectable {
fn from(value: &PerceptionColorFrame) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionColorFrame {
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 PerceptionColorFrame {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<PerceptionColorFrame> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: PerceptionColorFrame) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&PerceptionColorFrame> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &PerceptionColorFrame) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for PerceptionColorFrame {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &PerceptionColorFrame {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for PerceptionColorFrame {}
unsafe impl ::core::marker::Sync for PerceptionColorFrame {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionColorFrameArrivedEventArgs(pub ::windows::core::IInspectable);
impl PerceptionColorFrameArrivedEventArgs {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RelativeTime(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn TryOpenFrame(&self) -> ::windows::core::Result<PerceptionColorFrame> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionColorFrame>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionColorFrameArrivedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionColorFrameArrivedEventArgs;{8fad02d5-86f7-4d8d-b966-5a3761ba9f59})");
}
unsafe impl ::windows::core::Interface for PerceptionColorFrameArrivedEventArgs {
type Vtable = IPerceptionColorFrameArrivedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8fad02d5_86f7_4d8d_b966_5a3761ba9f59);
}
impl ::windows::core::RuntimeName for PerceptionColorFrameArrivedEventArgs {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionColorFrameArrivedEventArgs";
}
impl ::core::convert::From<PerceptionColorFrameArrivedEventArgs> for ::windows::core::IUnknown {
fn from(value: PerceptionColorFrameArrivedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionColorFrameArrivedEventArgs> for ::windows::core::IUnknown {
fn from(value: &PerceptionColorFrameArrivedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionColorFrameArrivedEventArgs {
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 PerceptionColorFrameArrivedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionColorFrameArrivedEventArgs> for ::windows::core::IInspectable {
fn from(value: PerceptionColorFrameArrivedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionColorFrameArrivedEventArgs> for ::windows::core::IInspectable {
fn from(value: &PerceptionColorFrameArrivedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionColorFrameArrivedEventArgs {
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 PerceptionColorFrameArrivedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionColorFrameArrivedEventArgs {}
unsafe impl ::core::marker::Sync for PerceptionColorFrameArrivedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionColorFrameReader(pub ::windows::core::IInspectable);
impl PerceptionColorFrameReader {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn FrameArrived<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionColorFrameReader, PerceptionColorFrameArrivedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveFrameArrived<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::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() }
}
#[cfg(feature = "deprecated")]
pub fn Source(&self) -> ::windows::core::Result<PerceptionColorFrameSource> {
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::<PerceptionColorFrameSource>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn IsPaused(&self) -> ::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), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetIsPaused(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "deprecated")]
pub fn TryReadLatestFrame(&self) -> ::windows::core::Result<PerceptionColorFrame> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionColorFrame>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionColorFrameReader {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionColorFrameReader;{7650f56e-b9f5-461b-83ad-f222af2aaadc})");
}
unsafe impl ::windows::core::Interface for PerceptionColorFrameReader {
type Vtable = IPerceptionColorFrameReader_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7650f56e_b9f5_461b_83ad_f222af2aaadc);
}
impl ::windows::core::RuntimeName for PerceptionColorFrameReader {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionColorFrameReader";
}
impl ::core::convert::From<PerceptionColorFrameReader> for ::windows::core::IUnknown {
fn from(value: PerceptionColorFrameReader) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionColorFrameReader> for ::windows::core::IUnknown {
fn from(value: &PerceptionColorFrameReader) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionColorFrameReader {
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 PerceptionColorFrameReader {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionColorFrameReader> for ::windows::core::IInspectable {
fn from(value: PerceptionColorFrameReader) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionColorFrameReader> for ::windows::core::IInspectable {
fn from(value: &PerceptionColorFrameReader) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionColorFrameReader {
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 PerceptionColorFrameReader {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<PerceptionColorFrameReader> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: PerceptionColorFrameReader) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&PerceptionColorFrameReader> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &PerceptionColorFrameReader) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for PerceptionColorFrameReader {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &PerceptionColorFrameReader {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for PerceptionColorFrameReader {}
unsafe impl ::core::marker::Sync for PerceptionColorFrameReader {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionColorFrameSource(pub ::windows::core::IInspectable);
impl PerceptionColorFrameSource {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn AvailableChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionColorFrameSource, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveAvailableChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::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() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn ActiveChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionColorFrameSource, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveActiveChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn PropertiesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionColorFrameSource, PerceptionFrameSourcePropertiesChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemovePropertiesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn VideoProfileChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionColorFrameSource, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveVideoProfileChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn CameraIntrinsicsChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionColorFrameSource, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveCameraIntrinsicsChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn Id(&self) -> ::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).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn DisplayName(&self) -> ::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).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn DeviceKind(&self) -> ::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).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Available(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Active(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn IsControlled(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn Properties(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, ::windows::core::IInspectable>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, ::windows::core::IInspectable>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn SupportedVideoProfiles(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PerceptionVideoProfile>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PerceptionVideoProfile>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn AvailableVideoProfiles(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PerceptionVideoProfile>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PerceptionVideoProfile>>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn VideoProfile(&self) -> ::windows::core::Result<PerceptionVideoProfile> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionVideoProfile>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Media_Devices_Core")]
pub fn CameraIntrinsics(&self) -> ::windows::core::Result<super::super::Media::Devices::Core::CameraIntrinsics> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Media::Devices::Core::CameraIntrinsics>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn AcquireControlSession(&self) -> ::windows::core::Result<PerceptionControlSession> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionControlSession>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn CanControlIndependentlyFrom<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, targetid: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), targetid.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn IsCorrelatedWith<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, targetid: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), targetid.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Numerics")]
pub fn TryGetTransformTo<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, targetid: Param0, result: &mut super::super::Foundation::Numerics::Matrix4x4) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), targetid.into_param().abi(), result, &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn TryGetDepthCorrelatedCameraIntrinsicsAsync<'a, Param0: ::windows::core::IntoParam<'a, PerceptionDepthFrameSource>>(&self, correlateddepthframesource: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionDepthCorrelatedCameraIntrinsics>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), correlateddepthframesource.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionDepthCorrelatedCameraIntrinsics>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn TryGetDepthCorrelatedCoordinateMapperAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, PerceptionDepthFrameSource>>(&self, targetsourceid: Param0, correlateddepthframesource: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionDepthCorrelatedCoordinateMapper>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), targetsourceid.into_param().abi(), correlateddepthframesource.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionDepthCorrelatedCoordinateMapper>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn TrySetVideoProfileAsync<'a, Param0: ::windows::core::IntoParam<'a, PerceptionControlSession>, Param1: ::windows::core::IntoParam<'a, PerceptionVideoProfile>>(&self, controlsession: Param0, profile: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionFrameSourcePropertyChangeResult>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).33)(::core::mem::transmute_copy(this), controlsession.into_param().abi(), profile.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionFrameSourcePropertyChangeResult>>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn OpenReader(&self) -> ::windows::core::Result<PerceptionColorFrameReader> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).34)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionColorFrameReader>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn CreateWatcher() -> ::windows::core::Result<PerceptionColorFrameSourceWatcher> {
Self::IPerceptionColorFrameSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionColorFrameSourceWatcher>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))]
pub fn FindAllAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<PerceptionColorFrameSource>>> {
Self::IPerceptionColorFrameSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<PerceptionColorFrameSource>>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(id: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionColorFrameSource>> {
Self::IPerceptionColorFrameSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), id.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionColorFrameSource>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RequestAccessAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionFrameSourceAccessStatus>> {
Self::IPerceptionColorFrameSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionFrameSourceAccessStatus>>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn DeviceId(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<IPerceptionColorFrameSource2>(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), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn IPerceptionColorFrameSourceStatics<R, F: FnOnce(&IPerceptionColorFrameSourceStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<PerceptionColorFrameSource, IPerceptionColorFrameSourceStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionColorFrameSource {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionColorFrameSource;{dc6dba7c-0b58-468d-9ca1-6db04cc0477c})");
}
unsafe impl ::windows::core::Interface for PerceptionColorFrameSource {
type Vtable = IPerceptionColorFrameSource_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdc6dba7c_0b58_468d_9ca1_6db04cc0477c);
}
impl ::windows::core::RuntimeName for PerceptionColorFrameSource {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionColorFrameSource";
}
impl ::core::convert::From<PerceptionColorFrameSource> for ::windows::core::IUnknown {
fn from(value: PerceptionColorFrameSource) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionColorFrameSource> for ::windows::core::IUnknown {
fn from(value: &PerceptionColorFrameSource) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionColorFrameSource {
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 PerceptionColorFrameSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionColorFrameSource> for ::windows::core::IInspectable {
fn from(value: PerceptionColorFrameSource) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionColorFrameSource> for ::windows::core::IInspectable {
fn from(value: &PerceptionColorFrameSource) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionColorFrameSource {
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 PerceptionColorFrameSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionColorFrameSource {}
unsafe impl ::core::marker::Sync for PerceptionColorFrameSource {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionColorFrameSourceAddedEventArgs(pub ::windows::core::IInspectable);
impl PerceptionColorFrameSourceAddedEventArgs {
#[cfg(feature = "deprecated")]
pub fn FrameSource(&self) -> ::windows::core::Result<PerceptionColorFrameSource> {
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::<PerceptionColorFrameSource>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionColorFrameSourceAddedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionColorFrameSourceAddedEventArgs;{d16bf4e6-da24-442c-bbd5-55549b5b94f3})");
}
unsafe impl ::windows::core::Interface for PerceptionColorFrameSourceAddedEventArgs {
type Vtable = IPerceptionColorFrameSourceAddedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd16bf4e6_da24_442c_bbd5_55549b5b94f3);
}
impl ::windows::core::RuntimeName for PerceptionColorFrameSourceAddedEventArgs {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionColorFrameSourceAddedEventArgs";
}
impl ::core::convert::From<PerceptionColorFrameSourceAddedEventArgs> for ::windows::core::IUnknown {
fn from(value: PerceptionColorFrameSourceAddedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionColorFrameSourceAddedEventArgs> for ::windows::core::IUnknown {
fn from(value: &PerceptionColorFrameSourceAddedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionColorFrameSourceAddedEventArgs {
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 PerceptionColorFrameSourceAddedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionColorFrameSourceAddedEventArgs> for ::windows::core::IInspectable {
fn from(value: PerceptionColorFrameSourceAddedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionColorFrameSourceAddedEventArgs> for ::windows::core::IInspectable {
fn from(value: &PerceptionColorFrameSourceAddedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionColorFrameSourceAddedEventArgs {
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 PerceptionColorFrameSourceAddedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionColorFrameSourceAddedEventArgs {}
unsafe impl ::core::marker::Sync for PerceptionColorFrameSourceAddedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionColorFrameSourceRemovedEventArgs(pub ::windows::core::IInspectable);
impl PerceptionColorFrameSourceRemovedEventArgs {
#[cfg(feature = "deprecated")]
pub fn FrameSource(&self) -> ::windows::core::Result<PerceptionColorFrameSource> {
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::<PerceptionColorFrameSource>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionColorFrameSourceRemovedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionColorFrameSourceRemovedEventArgs;{d277fa69-eb4c-42ef-ba4f-288f615c93c1})");
}
unsafe impl ::windows::core::Interface for PerceptionColorFrameSourceRemovedEventArgs {
type Vtable = IPerceptionColorFrameSourceRemovedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd277fa69_eb4c_42ef_ba4f_288f615c93c1);
}
impl ::windows::core::RuntimeName for PerceptionColorFrameSourceRemovedEventArgs {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionColorFrameSourceRemovedEventArgs";
}
impl ::core::convert::From<PerceptionColorFrameSourceRemovedEventArgs> for ::windows::core::IUnknown {
fn from(value: PerceptionColorFrameSourceRemovedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionColorFrameSourceRemovedEventArgs> for ::windows::core::IUnknown {
fn from(value: &PerceptionColorFrameSourceRemovedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionColorFrameSourceRemovedEventArgs {
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 PerceptionColorFrameSourceRemovedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionColorFrameSourceRemovedEventArgs> for ::windows::core::IInspectable {
fn from(value: PerceptionColorFrameSourceRemovedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionColorFrameSourceRemovedEventArgs> for ::windows::core::IInspectable {
fn from(value: &PerceptionColorFrameSourceRemovedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionColorFrameSourceRemovedEventArgs {
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 PerceptionColorFrameSourceRemovedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionColorFrameSourceRemovedEventArgs {}
unsafe impl ::core::marker::Sync for PerceptionColorFrameSourceRemovedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionColorFrameSourceWatcher(pub ::windows::core::IInspectable);
impl PerceptionColorFrameSourceWatcher {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SourceAdded<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionColorFrameSourceWatcher, PerceptionColorFrameSourceAddedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveSourceAdded<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::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() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SourceRemoved<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionColorFrameSourceWatcher, PerceptionColorFrameSourceRemovedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveSourceRemoved<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn Stopped<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionColorFrameSourceWatcher, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveStopped<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn EnumerationCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionColorFrameSourceWatcher, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveEnumerationCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Devices_Enumeration")]
pub fn Status(&self) -> ::windows::core::Result<super::Enumeration::DeviceWatcherStatus> {
let this = self;
unsafe {
let mut result__: super::Enumeration::DeviceWatcherStatus = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::Enumeration::DeviceWatcherStatus>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Start(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "deprecated")]
pub fn Stop(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionColorFrameSourceWatcher {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionColorFrameSourceWatcher;{96bd1392-e667-40c4-89f9-1462dea6a9cc})");
}
unsafe impl ::windows::core::Interface for PerceptionColorFrameSourceWatcher {
type Vtable = IPerceptionColorFrameSourceWatcher_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96bd1392_e667_40c4_89f9_1462dea6a9cc);
}
impl ::windows::core::RuntimeName for PerceptionColorFrameSourceWatcher {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionColorFrameSourceWatcher";
}
impl ::core::convert::From<PerceptionColorFrameSourceWatcher> for ::windows::core::IUnknown {
fn from(value: PerceptionColorFrameSourceWatcher) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionColorFrameSourceWatcher> for ::windows::core::IUnknown {
fn from(value: &PerceptionColorFrameSourceWatcher) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionColorFrameSourceWatcher {
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 PerceptionColorFrameSourceWatcher {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionColorFrameSourceWatcher> for ::windows::core::IInspectable {
fn from(value: PerceptionColorFrameSourceWatcher) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionColorFrameSourceWatcher> for ::windows::core::IInspectable {
fn from(value: &PerceptionColorFrameSourceWatcher) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionColorFrameSourceWatcher {
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 PerceptionColorFrameSourceWatcher {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionColorFrameSourceWatcher {}
unsafe impl ::core::marker::Sync for PerceptionColorFrameSourceWatcher {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionControlSession(pub ::windows::core::IInspectable);
impl PerceptionControlSession {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn ControlLost<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionControlSession, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveControlLost<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::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() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn TrySetPropertyAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(&self, name: Param0, value: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionFrameSourcePropertyChangeResult>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), name.into_param().abi(), value.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionFrameSourcePropertyChangeResult>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionControlSession {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionControlSession;{99998653-5a3d-417f-9239-f1889e548b48})");
}
unsafe impl ::windows::core::Interface for PerceptionControlSession {
type Vtable = IPerceptionControlSession_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x99998653_5a3d_417f_9239_f1889e548b48);
}
impl ::windows::core::RuntimeName for PerceptionControlSession {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionControlSession";
}
impl ::core::convert::From<PerceptionControlSession> for ::windows::core::IUnknown {
fn from(value: PerceptionControlSession) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionControlSession> for ::windows::core::IUnknown {
fn from(value: &PerceptionControlSession) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionControlSession {
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 PerceptionControlSession {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionControlSession> for ::windows::core::IInspectable {
fn from(value: PerceptionControlSession) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionControlSession> for ::windows::core::IInspectable {
fn from(value: &PerceptionControlSession) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionControlSession {
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 PerceptionControlSession {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<PerceptionControlSession> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: PerceptionControlSession) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&PerceptionControlSession> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &PerceptionControlSession) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for PerceptionControlSession {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &PerceptionControlSession {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for PerceptionControlSession {}
unsafe impl ::core::marker::Sync for PerceptionControlSession {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionDepthCorrelatedCameraIntrinsics(pub ::windows::core::IInspectable);
impl PerceptionDepthCorrelatedCameraIntrinsics {
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics"))]
pub fn UnprojectPixelAtCorrelatedDepth<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Point>, Param1: ::windows::core::IntoParam<'a, PerceptionDepthFrame>>(&self, pixelcoordinate: Param0, depthframe: Param1) -> ::windows::core::Result<super::super::Foundation::Numerics::Vector3> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::Numerics::Vector3 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), pixelcoordinate.into_param().abi(), depthframe.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::Numerics::Vector3>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics"))]
pub fn UnprojectPixelsAtCorrelatedDepth<'a, Param1: ::windows::core::IntoParam<'a, PerceptionDepthFrame>>(&self, sourcecoordinates: &[<super::super::Foundation::Point as ::windows::core::DefaultType>::DefaultType], depthframe: Param1, results: &mut [<super::super::Foundation::Numerics::Vector3 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), sourcecoordinates.len() as u32, ::core::mem::transmute(sourcecoordinates.as_ptr()), depthframe.into_param().abi(), results.len() as u32, ::core::mem::transmute_copy(&results)).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics"))]
pub fn UnprojectRegionPixelsAtCorrelatedDepthAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>, Param1: ::windows::core::IntoParam<'a, PerceptionDepthFrame>>(&self, region: Param0, depthframe: Param1, results: &mut [<super::super::Foundation::Numerics::Vector3 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), region.into_param().abi(), depthframe.into_param().abi(), results.len() as u32, ::core::mem::transmute_copy(&results), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics"))]
pub fn UnprojectAllPixelsAtCorrelatedDepthAsync<'a, Param0: ::windows::core::IntoParam<'a, PerceptionDepthFrame>>(&self, depthframe: Param0, results: &mut [<super::super::Foundation::Numerics::Vector3 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), depthframe.into_param().abi(), results.len() as u32, ::core::mem::transmute_copy(&results), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionDepthCorrelatedCameraIntrinsics {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionDepthCorrelatedCameraIntrinsics;{6548ca01-86de-5be1-6582-807fcf4c95cf})");
}
unsafe impl ::windows::core::Interface for PerceptionDepthCorrelatedCameraIntrinsics {
type Vtable = IPerceptionDepthCorrelatedCameraIntrinsics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6548ca01_86de_5be1_6582_807fcf4c95cf);
}
impl ::windows::core::RuntimeName for PerceptionDepthCorrelatedCameraIntrinsics {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionDepthCorrelatedCameraIntrinsics";
}
impl ::core::convert::From<PerceptionDepthCorrelatedCameraIntrinsics> for ::windows::core::IUnknown {
fn from(value: PerceptionDepthCorrelatedCameraIntrinsics) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionDepthCorrelatedCameraIntrinsics> for ::windows::core::IUnknown {
fn from(value: &PerceptionDepthCorrelatedCameraIntrinsics) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionDepthCorrelatedCameraIntrinsics {
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 PerceptionDepthCorrelatedCameraIntrinsics {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionDepthCorrelatedCameraIntrinsics> for ::windows::core::IInspectable {
fn from(value: PerceptionDepthCorrelatedCameraIntrinsics) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionDepthCorrelatedCameraIntrinsics> for ::windows::core::IInspectable {
fn from(value: &PerceptionDepthCorrelatedCameraIntrinsics) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionDepthCorrelatedCameraIntrinsics {
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 PerceptionDepthCorrelatedCameraIntrinsics {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionDepthCorrelatedCameraIntrinsics {}
unsafe impl ::core::marker::Sync for PerceptionDepthCorrelatedCameraIntrinsics {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionDepthCorrelatedCoordinateMapper(pub ::windows::core::IInspectable);
impl PerceptionDepthCorrelatedCoordinateMapper {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn MapPixelToTarget<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Point>, Param1: ::windows::core::IntoParam<'a, PerceptionDepthFrame>>(&self, sourcepixelcoordinate: Param0, depthframe: Param1) -> ::windows::core::Result<super::super::Foundation::Point> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::Point = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), sourcepixelcoordinate.into_param().abi(), depthframe.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::Point>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn MapPixelsToTarget<'a, Param1: ::windows::core::IntoParam<'a, PerceptionDepthFrame>>(&self, sourcecoordinates: &[<super::super::Foundation::Point as ::windows::core::DefaultType>::DefaultType], depthframe: Param1, results: &mut [<super::super::Foundation::Point as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), sourcecoordinates.len() as u32, ::core::mem::transmute(sourcecoordinates.as_ptr()), depthframe.into_param().abi(), results.len() as u32, ::core::mem::transmute_copy(&results)).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn MapRegionOfPixelsToTargetAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>, Param1: ::windows::core::IntoParam<'a, PerceptionDepthFrame>>(&self, region: Param0, depthframe: Param1, targetcoordinates: &mut [<super::super::Foundation::Point as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), region.into_param().abi(), depthframe.into_param().abi(), targetcoordinates.len() as u32, ::core::mem::transmute_copy(&targetcoordinates), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn MapAllPixelsToTargetAsync<'a, Param0: ::windows::core::IntoParam<'a, PerceptionDepthFrame>>(&self, depthframe: Param0, targetcoordinates: &mut [<super::super::Foundation::Point as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), depthframe.into_param().abi(), targetcoordinates.len() as u32, ::core::mem::transmute_copy(&targetcoordinates), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionDepthCorrelatedCoordinateMapper {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionDepthCorrelatedCoordinateMapper;{5b4d9d1d-b5f6-469c-b8c2-b97a45e6863b})");
}
unsafe impl ::windows::core::Interface for PerceptionDepthCorrelatedCoordinateMapper {
type Vtable = IPerceptionDepthCorrelatedCoordinateMapper_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5b4d9d1d_b5f6_469c_b8c2_b97a45e6863b);
}
impl ::windows::core::RuntimeName for PerceptionDepthCorrelatedCoordinateMapper {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionDepthCorrelatedCoordinateMapper";
}
impl ::core::convert::From<PerceptionDepthCorrelatedCoordinateMapper> for ::windows::core::IUnknown {
fn from(value: PerceptionDepthCorrelatedCoordinateMapper) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionDepthCorrelatedCoordinateMapper> for ::windows::core::IUnknown {
fn from(value: &PerceptionDepthCorrelatedCoordinateMapper) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionDepthCorrelatedCoordinateMapper {
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 PerceptionDepthCorrelatedCoordinateMapper {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionDepthCorrelatedCoordinateMapper> for ::windows::core::IInspectable {
fn from(value: PerceptionDepthCorrelatedCoordinateMapper) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionDepthCorrelatedCoordinateMapper> for ::windows::core::IInspectable {
fn from(value: &PerceptionDepthCorrelatedCoordinateMapper) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionDepthCorrelatedCoordinateMapper {
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 PerceptionDepthCorrelatedCoordinateMapper {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionDepthCorrelatedCoordinateMapper {}
unsafe impl ::core::marker::Sync for PerceptionDepthCorrelatedCoordinateMapper {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionDepthFrame(pub ::windows::core::IInspectable);
impl PerceptionDepthFrame {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Media")]
pub fn VideoFrame(&self) -> ::windows::core::Result<super::super::Media::VideoFrame> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Media::VideoFrame>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionDepthFrame {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionDepthFrame;{a37b81fc-9906-4ffd-9161-0024b360b657})");
}
unsafe impl ::windows::core::Interface for PerceptionDepthFrame {
type Vtable = IPerceptionDepthFrame_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa37b81fc_9906_4ffd_9161_0024b360b657);
}
impl ::windows::core::RuntimeName for PerceptionDepthFrame {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionDepthFrame";
}
impl ::core::convert::From<PerceptionDepthFrame> for ::windows::core::IUnknown {
fn from(value: PerceptionDepthFrame) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionDepthFrame> for ::windows::core::IUnknown {
fn from(value: &PerceptionDepthFrame) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionDepthFrame {
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 PerceptionDepthFrame {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionDepthFrame> for ::windows::core::IInspectable {
fn from(value: PerceptionDepthFrame) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionDepthFrame> for ::windows::core::IInspectable {
fn from(value: &PerceptionDepthFrame) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionDepthFrame {
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 PerceptionDepthFrame {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<PerceptionDepthFrame> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: PerceptionDepthFrame) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&PerceptionDepthFrame> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &PerceptionDepthFrame) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for PerceptionDepthFrame {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &PerceptionDepthFrame {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for PerceptionDepthFrame {}
unsafe impl ::core::marker::Sync for PerceptionDepthFrame {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionDepthFrameArrivedEventArgs(pub ::windows::core::IInspectable);
impl PerceptionDepthFrameArrivedEventArgs {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RelativeTime(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn TryOpenFrame(&self) -> ::windows::core::Result<PerceptionDepthFrame> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionDepthFrame>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionDepthFrameArrivedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionDepthFrameArrivedEventArgs;{443d25b2-b282-4637-9173-ac978435c985})");
}
unsafe impl ::windows::core::Interface for PerceptionDepthFrameArrivedEventArgs {
type Vtable = IPerceptionDepthFrameArrivedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x443d25b2_b282_4637_9173_ac978435c985);
}
impl ::windows::core::RuntimeName for PerceptionDepthFrameArrivedEventArgs {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionDepthFrameArrivedEventArgs";
}
impl ::core::convert::From<PerceptionDepthFrameArrivedEventArgs> for ::windows::core::IUnknown {
fn from(value: PerceptionDepthFrameArrivedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionDepthFrameArrivedEventArgs> for ::windows::core::IUnknown {
fn from(value: &PerceptionDepthFrameArrivedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionDepthFrameArrivedEventArgs {
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 PerceptionDepthFrameArrivedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionDepthFrameArrivedEventArgs> for ::windows::core::IInspectable {
fn from(value: PerceptionDepthFrameArrivedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionDepthFrameArrivedEventArgs> for ::windows::core::IInspectable {
fn from(value: &PerceptionDepthFrameArrivedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionDepthFrameArrivedEventArgs {
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 PerceptionDepthFrameArrivedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionDepthFrameArrivedEventArgs {}
unsafe impl ::core::marker::Sync for PerceptionDepthFrameArrivedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionDepthFrameReader(pub ::windows::core::IInspectable);
impl PerceptionDepthFrameReader {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn FrameArrived<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionDepthFrameReader, PerceptionDepthFrameArrivedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveFrameArrived<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::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() }
}
#[cfg(feature = "deprecated")]
pub fn Source(&self) -> ::windows::core::Result<PerceptionDepthFrameSource> {
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::<PerceptionDepthFrameSource>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn IsPaused(&self) -> ::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), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetIsPaused(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "deprecated")]
pub fn TryReadLatestFrame(&self) -> ::windows::core::Result<PerceptionDepthFrame> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionDepthFrame>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionDepthFrameReader {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionDepthFrameReader;{b1a3c09f-299b-4612-a4f7-270f25a096ec})");
}
unsafe impl ::windows::core::Interface for PerceptionDepthFrameReader {
type Vtable = IPerceptionDepthFrameReader_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb1a3c09f_299b_4612_a4f7_270f25a096ec);
}
impl ::windows::core::RuntimeName for PerceptionDepthFrameReader {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionDepthFrameReader";
}
impl ::core::convert::From<PerceptionDepthFrameReader> for ::windows::core::IUnknown {
fn from(value: PerceptionDepthFrameReader) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionDepthFrameReader> for ::windows::core::IUnknown {
fn from(value: &PerceptionDepthFrameReader) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionDepthFrameReader {
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 PerceptionDepthFrameReader {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionDepthFrameReader> for ::windows::core::IInspectable {
fn from(value: PerceptionDepthFrameReader) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionDepthFrameReader> for ::windows::core::IInspectable {
fn from(value: &PerceptionDepthFrameReader) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionDepthFrameReader {
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 PerceptionDepthFrameReader {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<PerceptionDepthFrameReader> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: PerceptionDepthFrameReader) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&PerceptionDepthFrameReader> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &PerceptionDepthFrameReader) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for PerceptionDepthFrameReader {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &PerceptionDepthFrameReader {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for PerceptionDepthFrameReader {}
unsafe impl ::core::marker::Sync for PerceptionDepthFrameReader {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionDepthFrameSource(pub ::windows::core::IInspectable);
impl PerceptionDepthFrameSource {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn AvailableChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionDepthFrameSource, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveAvailableChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::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() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn ActiveChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionDepthFrameSource, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveActiveChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn PropertiesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionDepthFrameSource, PerceptionFrameSourcePropertiesChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemovePropertiesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn VideoProfileChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionDepthFrameSource, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveVideoProfileChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn CameraIntrinsicsChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionDepthFrameSource, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveCameraIntrinsicsChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn Id(&self) -> ::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).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn DisplayName(&self) -> ::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).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn DeviceKind(&self) -> ::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).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Available(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Active(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn IsControlled(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn Properties(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, ::windows::core::IInspectable>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, ::windows::core::IInspectable>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn SupportedVideoProfiles(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PerceptionVideoProfile>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PerceptionVideoProfile>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn AvailableVideoProfiles(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PerceptionVideoProfile>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PerceptionVideoProfile>>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn VideoProfile(&self) -> ::windows::core::Result<PerceptionVideoProfile> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionVideoProfile>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Media_Devices_Core")]
pub fn CameraIntrinsics(&self) -> ::windows::core::Result<super::super::Media::Devices::Core::CameraIntrinsics> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Media::Devices::Core::CameraIntrinsics>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn AcquireControlSession(&self) -> ::windows::core::Result<PerceptionControlSession> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionControlSession>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn CanControlIndependentlyFrom<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, targetid: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), targetid.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn IsCorrelatedWith<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, targetid: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), targetid.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Numerics")]
pub fn TryGetTransformTo<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, targetid: Param0, result: &mut super::super::Foundation::Numerics::Matrix4x4) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), targetid.into_param().abi(), result, &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn TryGetDepthCorrelatedCameraIntrinsicsAsync<'a, Param0: ::windows::core::IntoParam<'a, PerceptionDepthFrameSource>>(&self, target: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionDepthCorrelatedCameraIntrinsics>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), target.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionDepthCorrelatedCameraIntrinsics>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn TryGetDepthCorrelatedCoordinateMapperAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, PerceptionDepthFrameSource>>(&self, targetid: Param0, depthframesourcetomapwith: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionDepthCorrelatedCoordinateMapper>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), targetid.into_param().abi(), depthframesourcetomapwith.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionDepthCorrelatedCoordinateMapper>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn TrySetVideoProfileAsync<'a, Param0: ::windows::core::IntoParam<'a, PerceptionControlSession>, Param1: ::windows::core::IntoParam<'a, PerceptionVideoProfile>>(&self, controlsession: Param0, profile: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionFrameSourcePropertyChangeResult>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).33)(::core::mem::transmute_copy(this), controlsession.into_param().abi(), profile.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionFrameSourcePropertyChangeResult>>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn OpenReader(&self) -> ::windows::core::Result<PerceptionDepthFrameReader> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).34)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionDepthFrameReader>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn CreateWatcher() -> ::windows::core::Result<PerceptionDepthFrameSourceWatcher> {
Self::IPerceptionDepthFrameSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionDepthFrameSourceWatcher>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))]
pub fn FindAllAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<PerceptionDepthFrameSource>>> {
Self::IPerceptionDepthFrameSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<PerceptionDepthFrameSource>>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(id: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionDepthFrameSource>> {
Self::IPerceptionDepthFrameSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), id.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionDepthFrameSource>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RequestAccessAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionFrameSourceAccessStatus>> {
Self::IPerceptionDepthFrameSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionFrameSourceAccessStatus>>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn DeviceId(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<IPerceptionDepthFrameSource2>(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), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn IPerceptionDepthFrameSourceStatics<R, F: FnOnce(&IPerceptionDepthFrameSourceStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<PerceptionDepthFrameSource, IPerceptionDepthFrameSourceStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionDepthFrameSource {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionDepthFrameSource;{79d433d6-47fb-4df1-bfc9-f01d40bd9942})");
}
unsafe impl ::windows::core::Interface for PerceptionDepthFrameSource {
type Vtable = IPerceptionDepthFrameSource_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79d433d6_47fb_4df1_bfc9_f01d40bd9942);
}
impl ::windows::core::RuntimeName for PerceptionDepthFrameSource {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionDepthFrameSource";
}
impl ::core::convert::From<PerceptionDepthFrameSource> for ::windows::core::IUnknown {
fn from(value: PerceptionDepthFrameSource) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionDepthFrameSource> for ::windows::core::IUnknown {
fn from(value: &PerceptionDepthFrameSource) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionDepthFrameSource {
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 PerceptionDepthFrameSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionDepthFrameSource> for ::windows::core::IInspectable {
fn from(value: PerceptionDepthFrameSource) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionDepthFrameSource> for ::windows::core::IInspectable {
fn from(value: &PerceptionDepthFrameSource) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionDepthFrameSource {
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 PerceptionDepthFrameSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionDepthFrameSource {}
unsafe impl ::core::marker::Sync for PerceptionDepthFrameSource {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionDepthFrameSourceAddedEventArgs(pub ::windows::core::IInspectable);
impl PerceptionDepthFrameSourceAddedEventArgs {
#[cfg(feature = "deprecated")]
pub fn FrameSource(&self) -> ::windows::core::Result<PerceptionDepthFrameSource> {
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::<PerceptionDepthFrameSource>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionDepthFrameSourceAddedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionDepthFrameSourceAddedEventArgs;{93a48168-8bf8-45d2-a2f8-4ac0931cc7a6})");
}
unsafe impl ::windows::core::Interface for PerceptionDepthFrameSourceAddedEventArgs {
type Vtable = IPerceptionDepthFrameSourceAddedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x93a48168_8bf8_45d2_a2f8_4ac0931cc7a6);
}
impl ::windows::core::RuntimeName for PerceptionDepthFrameSourceAddedEventArgs {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionDepthFrameSourceAddedEventArgs";
}
impl ::core::convert::From<PerceptionDepthFrameSourceAddedEventArgs> for ::windows::core::IUnknown {
fn from(value: PerceptionDepthFrameSourceAddedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionDepthFrameSourceAddedEventArgs> for ::windows::core::IUnknown {
fn from(value: &PerceptionDepthFrameSourceAddedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionDepthFrameSourceAddedEventArgs {
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 PerceptionDepthFrameSourceAddedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionDepthFrameSourceAddedEventArgs> for ::windows::core::IInspectable {
fn from(value: PerceptionDepthFrameSourceAddedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionDepthFrameSourceAddedEventArgs> for ::windows::core::IInspectable {
fn from(value: &PerceptionDepthFrameSourceAddedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionDepthFrameSourceAddedEventArgs {
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 PerceptionDepthFrameSourceAddedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionDepthFrameSourceAddedEventArgs {}
unsafe impl ::core::marker::Sync for PerceptionDepthFrameSourceAddedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionDepthFrameSourceRemovedEventArgs(pub ::windows::core::IInspectable);
impl PerceptionDepthFrameSourceRemovedEventArgs {
#[cfg(feature = "deprecated")]
pub fn FrameSource(&self) -> ::windows::core::Result<PerceptionDepthFrameSource> {
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::<PerceptionDepthFrameSource>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionDepthFrameSourceRemovedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionDepthFrameSourceRemovedEventArgs;{a0c0cc4d-e96c-4d81-86dd-38b95e49c6df})");
}
unsafe impl ::windows::core::Interface for PerceptionDepthFrameSourceRemovedEventArgs {
type Vtable = IPerceptionDepthFrameSourceRemovedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa0c0cc4d_e96c_4d81_86dd_38b95e49c6df);
}
impl ::windows::core::RuntimeName for PerceptionDepthFrameSourceRemovedEventArgs {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionDepthFrameSourceRemovedEventArgs";
}
impl ::core::convert::From<PerceptionDepthFrameSourceRemovedEventArgs> for ::windows::core::IUnknown {
fn from(value: PerceptionDepthFrameSourceRemovedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionDepthFrameSourceRemovedEventArgs> for ::windows::core::IUnknown {
fn from(value: &PerceptionDepthFrameSourceRemovedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionDepthFrameSourceRemovedEventArgs {
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 PerceptionDepthFrameSourceRemovedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionDepthFrameSourceRemovedEventArgs> for ::windows::core::IInspectable {
fn from(value: PerceptionDepthFrameSourceRemovedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionDepthFrameSourceRemovedEventArgs> for ::windows::core::IInspectable {
fn from(value: &PerceptionDepthFrameSourceRemovedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionDepthFrameSourceRemovedEventArgs {
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 PerceptionDepthFrameSourceRemovedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionDepthFrameSourceRemovedEventArgs {}
unsafe impl ::core::marker::Sync for PerceptionDepthFrameSourceRemovedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionDepthFrameSourceWatcher(pub ::windows::core::IInspectable);
impl PerceptionDepthFrameSourceWatcher {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SourceAdded<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionDepthFrameSourceWatcher, PerceptionDepthFrameSourceAddedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveSourceAdded<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::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() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SourceRemoved<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionDepthFrameSourceWatcher, PerceptionDepthFrameSourceRemovedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveSourceRemoved<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn Stopped<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionDepthFrameSourceWatcher, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveStopped<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn EnumerationCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionDepthFrameSourceWatcher, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveEnumerationCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Devices_Enumeration")]
pub fn Status(&self) -> ::windows::core::Result<super::Enumeration::DeviceWatcherStatus> {
let this = self;
unsafe {
let mut result__: super::Enumeration::DeviceWatcherStatus = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::Enumeration::DeviceWatcherStatus>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Start(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "deprecated")]
pub fn Stop(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionDepthFrameSourceWatcher {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionDepthFrameSourceWatcher;{780e96d1-8d02-4d2b-ada4-5ba624a0eb10})");
}
unsafe impl ::windows::core::Interface for PerceptionDepthFrameSourceWatcher {
type Vtable = IPerceptionDepthFrameSourceWatcher_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x780e96d1_8d02_4d2b_ada4_5ba624a0eb10);
}
impl ::windows::core::RuntimeName for PerceptionDepthFrameSourceWatcher {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionDepthFrameSourceWatcher";
}
impl ::core::convert::From<PerceptionDepthFrameSourceWatcher> for ::windows::core::IUnknown {
fn from(value: PerceptionDepthFrameSourceWatcher) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionDepthFrameSourceWatcher> for ::windows::core::IUnknown {
fn from(value: &PerceptionDepthFrameSourceWatcher) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionDepthFrameSourceWatcher {
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 PerceptionDepthFrameSourceWatcher {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionDepthFrameSourceWatcher> for ::windows::core::IInspectable {
fn from(value: PerceptionDepthFrameSourceWatcher) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionDepthFrameSourceWatcher> for ::windows::core::IInspectable {
fn from(value: &PerceptionDepthFrameSourceWatcher) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionDepthFrameSourceWatcher {
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 PerceptionDepthFrameSourceWatcher {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionDepthFrameSourceWatcher {}
unsafe impl ::core::marker::Sync for PerceptionDepthFrameSourceWatcher {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PerceptionFrameSourceAccessStatus(pub i32);
impl PerceptionFrameSourceAccessStatus {
pub const Unspecified: PerceptionFrameSourceAccessStatus = PerceptionFrameSourceAccessStatus(0i32);
pub const Allowed: PerceptionFrameSourceAccessStatus = PerceptionFrameSourceAccessStatus(1i32);
pub const DeniedByUser: PerceptionFrameSourceAccessStatus = PerceptionFrameSourceAccessStatus(2i32);
pub const DeniedBySystem: PerceptionFrameSourceAccessStatus = PerceptionFrameSourceAccessStatus(3i32);
}
impl ::core::convert::From<i32> for PerceptionFrameSourceAccessStatus {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PerceptionFrameSourceAccessStatus {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PerceptionFrameSourceAccessStatus {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Perception.PerceptionFrameSourceAccessStatus;i4)");
}
impl ::windows::core::DefaultType for PerceptionFrameSourceAccessStatus {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionFrameSourcePropertiesChangedEventArgs(pub ::windows::core::IInspectable);
impl PerceptionFrameSourcePropertiesChangedEventArgs {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn CollectionChange(&self) -> ::windows::core::Result<super::super::Foundation::Collections::CollectionChange> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::Collections::CollectionChange = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::CollectionChange>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Key(&self) -> ::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).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionFrameSourcePropertiesChangedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionFrameSourcePropertiesChangedEventArgs;{6c68e068-bcf1-4ecc-b891-7625d1244b6b})");
}
unsafe impl ::windows::core::Interface for PerceptionFrameSourcePropertiesChangedEventArgs {
type Vtable = IPerceptionFrameSourcePropertiesChangedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6c68e068_bcf1_4ecc_b891_7625d1244b6b);
}
impl ::windows::core::RuntimeName for PerceptionFrameSourcePropertiesChangedEventArgs {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionFrameSourcePropertiesChangedEventArgs";
}
impl ::core::convert::From<PerceptionFrameSourcePropertiesChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: PerceptionFrameSourcePropertiesChangedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionFrameSourcePropertiesChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: &PerceptionFrameSourcePropertiesChangedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionFrameSourcePropertiesChangedEventArgs {
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 PerceptionFrameSourcePropertiesChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionFrameSourcePropertiesChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: PerceptionFrameSourcePropertiesChangedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionFrameSourcePropertiesChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: &PerceptionFrameSourcePropertiesChangedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionFrameSourcePropertiesChangedEventArgs {
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 PerceptionFrameSourcePropertiesChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionFrameSourcePropertiesChangedEventArgs {}
unsafe impl ::core::marker::Sync for PerceptionFrameSourcePropertiesChangedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionFrameSourcePropertyChangeResult(pub ::windows::core::IInspectable);
impl PerceptionFrameSourcePropertyChangeResult {
#[cfg(feature = "deprecated")]
pub fn Status(&self) -> ::windows::core::Result<PerceptionFrameSourcePropertyChangeStatus> {
let this = self;
unsafe {
let mut result__: PerceptionFrameSourcePropertyChangeStatus = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionFrameSourcePropertyChangeStatus>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn NewValue(&self) -> ::windows::core::Result<::windows::core::IInspectable> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::IInspectable>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionFrameSourcePropertyChangeResult {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionFrameSourcePropertyChangeResult;{1e33390a-3c90-4d22-b898-f42bba6418ff})");
}
unsafe impl ::windows::core::Interface for PerceptionFrameSourcePropertyChangeResult {
type Vtable = IPerceptionFrameSourcePropertyChangeResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1e33390a_3c90_4d22_b898_f42bba6418ff);
}
impl ::windows::core::RuntimeName for PerceptionFrameSourcePropertyChangeResult {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionFrameSourcePropertyChangeResult";
}
impl ::core::convert::From<PerceptionFrameSourcePropertyChangeResult> for ::windows::core::IUnknown {
fn from(value: PerceptionFrameSourcePropertyChangeResult) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionFrameSourcePropertyChangeResult> for ::windows::core::IUnknown {
fn from(value: &PerceptionFrameSourcePropertyChangeResult) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionFrameSourcePropertyChangeResult {
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 PerceptionFrameSourcePropertyChangeResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionFrameSourcePropertyChangeResult> for ::windows::core::IInspectable {
fn from(value: PerceptionFrameSourcePropertyChangeResult) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionFrameSourcePropertyChangeResult> for ::windows::core::IInspectable {
fn from(value: &PerceptionFrameSourcePropertyChangeResult) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionFrameSourcePropertyChangeResult {
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 PerceptionFrameSourcePropertyChangeResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionFrameSourcePropertyChangeResult {}
unsafe impl ::core::marker::Sync for PerceptionFrameSourcePropertyChangeResult {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PerceptionFrameSourcePropertyChangeStatus(pub i32);
impl PerceptionFrameSourcePropertyChangeStatus {
pub const Unknown: PerceptionFrameSourcePropertyChangeStatus = PerceptionFrameSourcePropertyChangeStatus(0i32);
pub const Accepted: PerceptionFrameSourcePropertyChangeStatus = PerceptionFrameSourcePropertyChangeStatus(1i32);
pub const LostControl: PerceptionFrameSourcePropertyChangeStatus = PerceptionFrameSourcePropertyChangeStatus(2i32);
pub const PropertyNotSupported: PerceptionFrameSourcePropertyChangeStatus = PerceptionFrameSourcePropertyChangeStatus(3i32);
pub const PropertyReadOnly: PerceptionFrameSourcePropertyChangeStatus = PerceptionFrameSourcePropertyChangeStatus(4i32);
pub const ValueOutOfRange: PerceptionFrameSourcePropertyChangeStatus = PerceptionFrameSourcePropertyChangeStatus(5i32);
}
impl ::core::convert::From<i32> for PerceptionFrameSourcePropertyChangeStatus {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PerceptionFrameSourcePropertyChangeStatus {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PerceptionFrameSourcePropertyChangeStatus {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Perception.PerceptionFrameSourcePropertyChangeStatus;i4)");
}
impl ::windows::core::DefaultType for PerceptionFrameSourcePropertyChangeStatus {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionInfraredFrame(pub ::windows::core::IInspectable);
impl PerceptionInfraredFrame {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Media")]
pub fn VideoFrame(&self) -> ::windows::core::Result<super::super::Media::VideoFrame> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Media::VideoFrame>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionInfraredFrame {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionInfraredFrame;{b0886276-849e-4c7a-8ae6-b56064532153})");
}
unsafe impl ::windows::core::Interface for PerceptionInfraredFrame {
type Vtable = IPerceptionInfraredFrame_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0886276_849e_4c7a_8ae6_b56064532153);
}
impl ::windows::core::RuntimeName for PerceptionInfraredFrame {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionInfraredFrame";
}
impl ::core::convert::From<PerceptionInfraredFrame> for ::windows::core::IUnknown {
fn from(value: PerceptionInfraredFrame) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionInfraredFrame> for ::windows::core::IUnknown {
fn from(value: &PerceptionInfraredFrame) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionInfraredFrame {
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 PerceptionInfraredFrame {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionInfraredFrame> for ::windows::core::IInspectable {
fn from(value: PerceptionInfraredFrame) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionInfraredFrame> for ::windows::core::IInspectable {
fn from(value: &PerceptionInfraredFrame) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionInfraredFrame {
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 PerceptionInfraredFrame {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<PerceptionInfraredFrame> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: PerceptionInfraredFrame) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&PerceptionInfraredFrame> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &PerceptionInfraredFrame) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for PerceptionInfraredFrame {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &PerceptionInfraredFrame {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for PerceptionInfraredFrame {}
unsafe impl ::core::marker::Sync for PerceptionInfraredFrame {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionInfraredFrameArrivedEventArgs(pub ::windows::core::IInspectable);
impl PerceptionInfraredFrameArrivedEventArgs {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RelativeTime(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn TryOpenFrame(&self) -> ::windows::core::Result<PerceptionInfraredFrame> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionInfraredFrame>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionInfraredFrameArrivedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionInfraredFrameArrivedEventArgs;{9f77fac7-b4bd-4857-9d50-be8ef075daef})");
}
unsafe impl ::windows::core::Interface for PerceptionInfraredFrameArrivedEventArgs {
type Vtable = IPerceptionInfraredFrameArrivedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9f77fac7_b4bd_4857_9d50_be8ef075daef);
}
impl ::windows::core::RuntimeName for PerceptionInfraredFrameArrivedEventArgs {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionInfraredFrameArrivedEventArgs";
}
impl ::core::convert::From<PerceptionInfraredFrameArrivedEventArgs> for ::windows::core::IUnknown {
fn from(value: PerceptionInfraredFrameArrivedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionInfraredFrameArrivedEventArgs> for ::windows::core::IUnknown {
fn from(value: &PerceptionInfraredFrameArrivedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionInfraredFrameArrivedEventArgs {
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 PerceptionInfraredFrameArrivedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionInfraredFrameArrivedEventArgs> for ::windows::core::IInspectable {
fn from(value: PerceptionInfraredFrameArrivedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionInfraredFrameArrivedEventArgs> for ::windows::core::IInspectable {
fn from(value: &PerceptionInfraredFrameArrivedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionInfraredFrameArrivedEventArgs {
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 PerceptionInfraredFrameArrivedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionInfraredFrameArrivedEventArgs {}
unsafe impl ::core::marker::Sync for PerceptionInfraredFrameArrivedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionInfraredFrameReader(pub ::windows::core::IInspectable);
impl PerceptionInfraredFrameReader {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn FrameArrived<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionInfraredFrameReader, PerceptionInfraredFrameArrivedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveFrameArrived<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::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() }
}
#[cfg(feature = "deprecated")]
pub fn Source(&self) -> ::windows::core::Result<PerceptionInfraredFrameSource> {
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::<PerceptionInfraredFrameSource>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn IsPaused(&self) -> ::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), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetIsPaused(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "deprecated")]
pub fn TryReadLatestFrame(&self) -> ::windows::core::Result<PerceptionInfraredFrame> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionInfraredFrame>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionInfraredFrameReader {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionInfraredFrameReader;{7960ce18-d39b-4fc8-a04a-929734c6756c})");
}
unsafe impl ::windows::core::Interface for PerceptionInfraredFrameReader {
type Vtable = IPerceptionInfraredFrameReader_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7960ce18_d39b_4fc8_a04a_929734c6756c);
}
impl ::windows::core::RuntimeName for PerceptionInfraredFrameReader {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionInfraredFrameReader";
}
impl ::core::convert::From<PerceptionInfraredFrameReader> for ::windows::core::IUnknown {
fn from(value: PerceptionInfraredFrameReader) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionInfraredFrameReader> for ::windows::core::IUnknown {
fn from(value: &PerceptionInfraredFrameReader) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionInfraredFrameReader {
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 PerceptionInfraredFrameReader {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionInfraredFrameReader> for ::windows::core::IInspectable {
fn from(value: PerceptionInfraredFrameReader) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionInfraredFrameReader> for ::windows::core::IInspectable {
fn from(value: &PerceptionInfraredFrameReader) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionInfraredFrameReader {
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 PerceptionInfraredFrameReader {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<PerceptionInfraredFrameReader> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: PerceptionInfraredFrameReader) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&PerceptionInfraredFrameReader> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &PerceptionInfraredFrameReader) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for PerceptionInfraredFrameReader {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &PerceptionInfraredFrameReader {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for PerceptionInfraredFrameReader {}
unsafe impl ::core::marker::Sync for PerceptionInfraredFrameReader {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionInfraredFrameSource(pub ::windows::core::IInspectable);
impl PerceptionInfraredFrameSource {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn AvailableChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionInfraredFrameSource, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveAvailableChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::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() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn ActiveChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionInfraredFrameSource, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveActiveChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn PropertiesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionInfraredFrameSource, PerceptionFrameSourcePropertiesChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemovePropertiesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn VideoProfileChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionInfraredFrameSource, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveVideoProfileChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn CameraIntrinsicsChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionInfraredFrameSource, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveCameraIntrinsicsChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn Id(&self) -> ::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).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn DisplayName(&self) -> ::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).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn DeviceKind(&self) -> ::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).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Available(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Active(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn IsControlled(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn Properties(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, ::windows::core::IInspectable>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, ::windows::core::IInspectable>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn SupportedVideoProfiles(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PerceptionVideoProfile>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PerceptionVideoProfile>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn AvailableVideoProfiles(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<PerceptionVideoProfile>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<PerceptionVideoProfile>>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn VideoProfile(&self) -> ::windows::core::Result<PerceptionVideoProfile> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionVideoProfile>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Media_Devices_Core")]
pub fn CameraIntrinsics(&self) -> ::windows::core::Result<super::super::Media::Devices::Core::CameraIntrinsics> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Media::Devices::Core::CameraIntrinsics>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn AcquireControlSession(&self) -> ::windows::core::Result<PerceptionControlSession> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionControlSession>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn CanControlIndependentlyFrom<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, targetid: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), targetid.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn IsCorrelatedWith<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, targetid: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), targetid.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Numerics")]
pub fn TryGetTransformTo<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, targetid: Param0, result: &mut super::super::Foundation::Numerics::Matrix4x4) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), targetid.into_param().abi(), result, &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn TryGetDepthCorrelatedCameraIntrinsicsAsync<'a, Param0: ::windows::core::IntoParam<'a, PerceptionDepthFrameSource>>(&self, target: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionDepthCorrelatedCameraIntrinsics>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), target.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionDepthCorrelatedCameraIntrinsics>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn TryGetDepthCorrelatedCoordinateMapperAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, PerceptionDepthFrameSource>>(&self, targetid: Param0, depthframesourcetomapwith: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionDepthCorrelatedCoordinateMapper>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), targetid.into_param().abi(), depthframesourcetomapwith.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionDepthCorrelatedCoordinateMapper>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn TrySetVideoProfileAsync<'a, Param0: ::windows::core::IntoParam<'a, PerceptionControlSession>, Param1: ::windows::core::IntoParam<'a, PerceptionVideoProfile>>(&self, controlsession: Param0, profile: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionFrameSourcePropertyChangeResult>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).33)(::core::mem::transmute_copy(this), controlsession.into_param().abi(), profile.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionFrameSourcePropertyChangeResult>>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn OpenReader(&self) -> ::windows::core::Result<PerceptionInfraredFrameReader> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).34)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionInfraredFrameReader>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn CreateWatcher() -> ::windows::core::Result<PerceptionInfraredFrameSourceWatcher> {
Self::IPerceptionInfraredFrameSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionInfraredFrameSourceWatcher>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))]
pub fn FindAllAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<PerceptionInfraredFrameSource>>> {
Self::IPerceptionInfraredFrameSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<PerceptionInfraredFrameSource>>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(id: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionInfraredFrameSource>> {
Self::IPerceptionInfraredFrameSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), id.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionInfraredFrameSource>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RequestAccessAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PerceptionFrameSourceAccessStatus>> {
Self::IPerceptionInfraredFrameSourceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PerceptionFrameSourceAccessStatus>>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn DeviceId(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<IPerceptionInfraredFrameSource2>(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), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn IPerceptionInfraredFrameSourceStatics<R, F: FnOnce(&IPerceptionInfraredFrameSourceStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<PerceptionInfraredFrameSource, IPerceptionInfraredFrameSourceStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionInfraredFrameSource {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionInfraredFrameSource;{55b08742-1808-494e-9e30-9d2a7be8f700})");
}
unsafe impl ::windows::core::Interface for PerceptionInfraredFrameSource {
type Vtable = IPerceptionInfraredFrameSource_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x55b08742_1808_494e_9e30_9d2a7be8f700);
}
impl ::windows::core::RuntimeName for PerceptionInfraredFrameSource {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionInfraredFrameSource";
}
impl ::core::convert::From<PerceptionInfraredFrameSource> for ::windows::core::IUnknown {
fn from(value: PerceptionInfraredFrameSource) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionInfraredFrameSource> for ::windows::core::IUnknown {
fn from(value: &PerceptionInfraredFrameSource) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionInfraredFrameSource {
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 PerceptionInfraredFrameSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionInfraredFrameSource> for ::windows::core::IInspectable {
fn from(value: PerceptionInfraredFrameSource) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionInfraredFrameSource> for ::windows::core::IInspectable {
fn from(value: &PerceptionInfraredFrameSource) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionInfraredFrameSource {
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 PerceptionInfraredFrameSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionInfraredFrameSource {}
unsafe impl ::core::marker::Sync for PerceptionInfraredFrameSource {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionInfraredFrameSourceAddedEventArgs(pub ::windows::core::IInspectable);
impl PerceptionInfraredFrameSourceAddedEventArgs {
#[cfg(feature = "deprecated")]
pub fn FrameSource(&self) -> ::windows::core::Result<PerceptionInfraredFrameSource> {
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::<PerceptionInfraredFrameSource>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionInfraredFrameSourceAddedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionInfraredFrameSourceAddedEventArgs;{6d334120-95ce-4660-907a-d98035aa2b7c})");
}
unsafe impl ::windows::core::Interface for PerceptionInfraredFrameSourceAddedEventArgs {
type Vtable = IPerceptionInfraredFrameSourceAddedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6d334120_95ce_4660_907a_d98035aa2b7c);
}
impl ::windows::core::RuntimeName for PerceptionInfraredFrameSourceAddedEventArgs {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionInfraredFrameSourceAddedEventArgs";
}
impl ::core::convert::From<PerceptionInfraredFrameSourceAddedEventArgs> for ::windows::core::IUnknown {
fn from(value: PerceptionInfraredFrameSourceAddedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionInfraredFrameSourceAddedEventArgs> for ::windows::core::IUnknown {
fn from(value: &PerceptionInfraredFrameSourceAddedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionInfraredFrameSourceAddedEventArgs {
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 PerceptionInfraredFrameSourceAddedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionInfraredFrameSourceAddedEventArgs> for ::windows::core::IInspectable {
fn from(value: PerceptionInfraredFrameSourceAddedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionInfraredFrameSourceAddedEventArgs> for ::windows::core::IInspectable {
fn from(value: &PerceptionInfraredFrameSourceAddedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionInfraredFrameSourceAddedEventArgs {
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 PerceptionInfraredFrameSourceAddedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionInfraredFrameSourceAddedEventArgs {}
unsafe impl ::core::marker::Sync for PerceptionInfraredFrameSourceAddedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionInfraredFrameSourceRemovedEventArgs(pub ::windows::core::IInspectable);
impl PerceptionInfraredFrameSourceRemovedEventArgs {
#[cfg(feature = "deprecated")]
pub fn FrameSource(&self) -> ::windows::core::Result<PerceptionInfraredFrameSource> {
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::<PerceptionInfraredFrameSource>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionInfraredFrameSourceRemovedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionInfraredFrameSourceRemovedEventArgs;{ea1a8071-7a70-4a61-af94-07303853f695})");
}
unsafe impl ::windows::core::Interface for PerceptionInfraredFrameSourceRemovedEventArgs {
type Vtable = IPerceptionInfraredFrameSourceRemovedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xea1a8071_7a70_4a61_af94_07303853f695);
}
impl ::windows::core::RuntimeName for PerceptionInfraredFrameSourceRemovedEventArgs {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionInfraredFrameSourceRemovedEventArgs";
}
impl ::core::convert::From<PerceptionInfraredFrameSourceRemovedEventArgs> for ::windows::core::IUnknown {
fn from(value: PerceptionInfraredFrameSourceRemovedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionInfraredFrameSourceRemovedEventArgs> for ::windows::core::IUnknown {
fn from(value: &PerceptionInfraredFrameSourceRemovedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionInfraredFrameSourceRemovedEventArgs {
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 PerceptionInfraredFrameSourceRemovedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionInfraredFrameSourceRemovedEventArgs> for ::windows::core::IInspectable {
fn from(value: PerceptionInfraredFrameSourceRemovedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionInfraredFrameSourceRemovedEventArgs> for ::windows::core::IInspectable {
fn from(value: &PerceptionInfraredFrameSourceRemovedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionInfraredFrameSourceRemovedEventArgs {
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 PerceptionInfraredFrameSourceRemovedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionInfraredFrameSourceRemovedEventArgs {}
unsafe impl ::core::marker::Sync for PerceptionInfraredFrameSourceRemovedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionInfraredFrameSourceWatcher(pub ::windows::core::IInspectable);
impl PerceptionInfraredFrameSourceWatcher {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SourceAdded<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionInfraredFrameSourceWatcher, PerceptionInfraredFrameSourceAddedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveSourceAdded<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::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() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SourceRemoved<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionInfraredFrameSourceWatcher, PerceptionInfraredFrameSourceRemovedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveSourceRemoved<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn Stopped<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionInfraredFrameSourceWatcher, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveStopped<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn EnumerationCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<PerceptionInfraredFrameSourceWatcher, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveEnumerationCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Devices_Enumeration")]
pub fn Status(&self) -> ::windows::core::Result<super::Enumeration::DeviceWatcherStatus> {
let this = self;
unsafe {
let mut result__: super::Enumeration::DeviceWatcherStatus = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::Enumeration::DeviceWatcherStatus>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Start(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "deprecated")]
pub fn Stop(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionInfraredFrameSourceWatcher {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionInfraredFrameSourceWatcher;{383cff99-d70c-444d-a8b0-720c2e66fe3b})");
}
unsafe impl ::windows::core::Interface for PerceptionInfraredFrameSourceWatcher {
type Vtable = IPerceptionInfraredFrameSourceWatcher_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x383cff99_d70c_444d_a8b0_720c2e66fe3b);
}
impl ::windows::core::RuntimeName for PerceptionInfraredFrameSourceWatcher {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionInfraredFrameSourceWatcher";
}
impl ::core::convert::From<PerceptionInfraredFrameSourceWatcher> for ::windows::core::IUnknown {
fn from(value: PerceptionInfraredFrameSourceWatcher) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionInfraredFrameSourceWatcher> for ::windows::core::IUnknown {
fn from(value: &PerceptionInfraredFrameSourceWatcher) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionInfraredFrameSourceWatcher {
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 PerceptionInfraredFrameSourceWatcher {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionInfraredFrameSourceWatcher> for ::windows::core::IInspectable {
fn from(value: PerceptionInfraredFrameSourceWatcher) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionInfraredFrameSourceWatcher> for ::windows::core::IInspectable {
fn from(value: &PerceptionInfraredFrameSourceWatcher) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionInfraredFrameSourceWatcher {
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 PerceptionInfraredFrameSourceWatcher {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionInfraredFrameSourceWatcher {}
unsafe impl ::core::marker::Sync for PerceptionInfraredFrameSourceWatcher {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PerceptionVideoProfile(pub ::windows::core::IInspectable);
impl PerceptionVideoProfile {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Graphics_Imaging")]
pub fn BitmapPixelFormat(&self) -> ::windows::core::Result<super::super::Graphics::Imaging::BitmapPixelFormat> {
let this = self;
unsafe {
let mut result__: super::super::Graphics::Imaging::BitmapPixelFormat = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Graphics::Imaging::BitmapPixelFormat>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Graphics_Imaging")]
pub fn BitmapAlphaMode(&self) -> ::windows::core::Result<super::super::Graphics::Imaging::BitmapAlphaMode> {
let this = self;
unsafe {
let mut result__: super::super::Graphics::Imaging::BitmapAlphaMode = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Graphics::Imaging::BitmapAlphaMode>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Width(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Height(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn FrameDuration(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn IsEqual<'a, Param0: ::windows::core::IntoParam<'a, PerceptionVideoProfile>>(&self, other: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), other.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for PerceptionVideoProfile {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.PerceptionVideoProfile;{75763ea3-011a-470e-8225-6f05ade25648})");
}
unsafe impl ::windows::core::Interface for PerceptionVideoProfile {
type Vtable = IPerceptionVideoProfile_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x75763ea3_011a_470e_8225_6f05ade25648);
}
impl ::windows::core::RuntimeName for PerceptionVideoProfile {
const NAME: &'static str = "Windows.Devices.Perception.PerceptionVideoProfile";
}
impl ::core::convert::From<PerceptionVideoProfile> for ::windows::core::IUnknown {
fn from(value: PerceptionVideoProfile) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PerceptionVideoProfile> for ::windows::core::IUnknown {
fn from(value: &PerceptionVideoProfile) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionVideoProfile {
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 PerceptionVideoProfile {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PerceptionVideoProfile> for ::windows::core::IInspectable {
fn from(value: PerceptionVideoProfile) -> Self {
value.0
}
}
impl ::core::convert::From<&PerceptionVideoProfile> for ::windows::core::IInspectable {
fn from(value: &PerceptionVideoProfile) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionVideoProfile {
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 PerceptionVideoProfile {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PerceptionVideoProfile {}
unsafe impl ::core::marker::Sync for PerceptionVideoProfile {}
|
// Copyright 2016 Mozilla Foundation
//
// 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.
pub use anyhow::{anyhow, bail, Context, Error};
use futures::future;
use futures::Future;
use std::boxed::Box;
use std::fmt::Display;
use std::process;
// We use `anyhow` for error handling.
// - Use `context()`/`with_context()` to annotate errors.
// - Use `anyhow!` with a string to create a new `anyhow::Error`.
// - The error types below (`BadHttpStatusError`, etc.) are internal ones that
// need to be checked at points other than the outermost error-checking
// layer.
// - There are some combinators below for working with futures.
#[cfg(feature = "hyper")]
#[derive(Debug)]
pub struct BadHttpStatusError(pub hyper::StatusCode);
#[derive(Debug)]
pub struct HttpClientError(pub String);
#[derive(Debug)]
pub struct ProcessError(pub process::Output);
#[cfg(feature = "hyper")]
impl std::error::Error for BadHttpStatusError {}
impl std::error::Error for HttpClientError {}
impl std::error::Error for ProcessError {}
#[cfg(feature = "hyper")]
impl std::fmt::Display for BadHttpStatusError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "didn't get a successful HTTP status, got `{}`", self.0)
}
}
impl std::fmt::Display for HttpClientError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "didn't get a successful HTTP status, got `{}`", self.0)
}
}
impl std::fmt::Display for ProcessError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", String::from_utf8_lossy(&self.0.stderr))
}
}
pub type Result<T> = anyhow::Result<T>;
pub type SFuture<T> = Box<dyn Future<Item = T, Error = Error>>;
pub type SFutureSend<T> = Box<dyn Future<Item = T, Error = Error> + Send>;
pub type SFutureStd<T> = Box<dyn std::future::Future<Output = Result<T>>>;
pub trait FutureContext<T> {
fn fcontext<C>(self, context: C) -> SFuture<T>
where
C: Display + Send + Sync + 'static;
fn fwith_context<C, CB>(self, callback: CB) -> SFuture<T>
where
CB: FnOnce() -> C + 'static,
C: Display + Send + Sync + 'static;
}
impl<F> FutureContext<F::Item> for F
where
F: Future + 'static,
F::Error: Into<Error> + Send + Sync,
{
fn fcontext<C>(self, context: C) -> SFuture<F::Item>
where
C: Display + Send + Sync + 'static,
{
Box::new(self.then(|r| r.map_err(F::Error::into).context(context)))
}
fn fwith_context<C, CB>(self, callback: CB) -> SFuture<F::Item>
where
CB: FnOnce() -> C + 'static,
C: Display + Send + Sync + 'static,
{
Box::new(self.then(|r| r.map_err(F::Error::into).context(callback())))
}
}
/// Like `try`, but returns an SFuture instead of a Result.
macro_rules! ftry {
($e:expr) => {
match $e {
Ok(v) => v,
Err(e) => return Box::new(futures::future::err(e.into())) as SFuture<_>,
}
};
}
#[cfg(feature = "dist-client")]
macro_rules! ftry_send {
($e:expr) => {
match $e {
Ok(v) => v,
Err(e) => return Box::new(futures::future::err(e)) as SFutureSend<_>,
}
};
}
pub fn f_ok<T>(t: T) -> SFuture<T>
where
T: 'static,
{
Box::new(future::ok(t))
}
pub fn f_err<T, E>(e: E) -> SFuture<T>
where
T: 'static,
E: Into<Error>,
{
Box::new(future::err(e.into()))
}
|
//! OAuth 1
//!
//!# Example
//!
//! TODO
extern crate time;
use std::default::Default;
use std::fmt;
use self::time::now_utc;
use std::rand::{thread_rng, Rng};
#[derive(Copy, Show, PartialEq, Eq, Clone)]
#[unstable]
/// Signature Type
pub enum SignatureMethod {
/// HMAC_SHA1
HMAC_SHA1,
/// RSA_SHA1
RSA_SHA1,
/// Plaintext
PLAINTEXT
}
impl Default for SignatureMethod {
fn default() -> SignatureMethod {
SignatureMethod::HMAC_SHA1}
}
impl fmt::String for SignatureMethod {
fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result{
let out = match *self {
SignatureMethod::HMAC_SHA1 => {"HMAC-SHA1"},
SignatureMethod::RSA_SHA1 => {"RSA-SHA1"},
SignatureMethod::PLAINTEXT => {"PLAINTEXT"}
};
write!(f, "{}", out)
}
}
pub trait AuthorizationHeader {
fn get_header(&self) -> String;
}
#[unstable]
pub struct Session<'a> {
oauth_consumer_key : &'a str,
oauth_token : &'a str,
oauth_token_secret : &'a str,
oauth_signature_method : SignatureMethod,
oauth_signature : &'a str,
}
// TODO: add to crypto library?
// TODO: Should we have a longer nonce than 10?
fn generate_nonce() -> String {
thread_rng().gen_ascii_chars()
.take(10)
.collect()
}
impl<'a> Session<'a> {
pub fn new (consumer_key: &'a str, token: &'a str, secret: &'a str,
signature_method: SignatureMethod) -> Session<'a> {
Session {
oauth_consumer_key: consumer_key,
oauth_token: token,
oauth_token_secret : secret,
oauth_signature_method: signature_method,
oauth_signature: "TODO",
}
}
// pub fn set_realm(&mut self, realm : Option<&'a str>)->&Session<'a>{
// self.realm = realm;
// self
// }
pub fn get_temporary_credentials(&self) {
// TODO
unimplemented!();
}
}
impl<'a> AuthorizationHeader for Session<'a>{
fn get_header(&self) -> String {
let header = format!("Authorization: OAuth oauth_consumer_key=\"{}\" \
oauth_signature=\"{}\", oauth_signature_method=\"{}\", \
oauth_token=\"{}\", oauth_version=\"1.0\"",
self.oauth_consumer_key, self.oauth_signature,
self.oauth_signature_method, self.oauth_token);
match self.oauth_signature_method {
SignatureMethod::PLAINTEXT => header,
_ => format!("{}, oauth_timestamp=\"{}\", oauth_nonce=\"{}\"",
header, now_utc().to_timespec().sec, generate_nonce())
}
}
}
#[cfg(test)]
mod tests {
use super::{Session, SignatureMethod, AuthorizationHeader};
// Session initialization and setup test
#[test]
fn hw() {
let s = Session::new("k0azC44q2c0DgF7ua9YZ6Q",
"119544186-6YZKqkECA9Z0bxq9bA1vzzG7tfPotCml4oTySkzj",
"zvNmU9daj9V00118H9KQBozQQsZt4pyLQcZdc",
SignatureMethod::HMAC_SHA1);
println!("{}", s.get_header());
}
}
#[derive(Clone)]
pub struct Builder {
request_url : String,
consumer_key : String,
callback_url : String,
signature_method : SignatureMethod,
require_nonce : bool,
require_timestamp : bool,
version : Option<String>,
realm : Option<String>
}
#[derive(Clone)]
pub struct TemporaryCredentials {
request_url : String,
consumer_key : String,
callback_url : String,
signature_method : SignatureMethod,
version : Option<String>,
realm : Option<String>,
nonce : Option<String>,
timestamp : Option<String>,
}
impl Builder {
pub fn new(request_url : String, consumer_key : String, callback_url : String, signature_method : SignatureMethod) -> Builder {
let require = match signature_method {SignatureMethod::PLAINTEXT => false, _ => true};
Builder {
request_url : request_url,
consumer_key : consumer_key,
callback_url : callback_url,
signature_method : signature_method,
require_nonce : require,
require_timestamp : require,
version : None,
realm : None
}
}
pub fn set_version(mut self)-> Builder {
self.version = Some("1.0".to_string());
self
}
pub fn set_realm(mut self, realm : String) -> Builder {
self.realm = Some(realm);
self
}
pub fn require_nonce(mut self) -> Builder {
self.require_nonce = true;
self
}
pub fn require_timestamp(mut self) -> Builder {
self.require_timestamp = true;
self
}
pub fn create(self) -> TemporaryCredentials {
TemporaryCredentials {
request_url : self.request_url,
consumer_key : self.consumer_key,
callback_url : self.callback_url,
signature_method : self.signature_method,
version : self.version,
realm : self.realm,
nonce : if self.require_nonce {Some(generate_nonce())}
else {None},
timestamp : if self.require_timestamp {Some(now_utc().to_timespec().sec.to_string())}
else {None}
}
}
}
impl TemporaryCredentials {
pub fn send_post_request(self)->Result<(),()>{
Ok(())
}
}
impl AuthorizationHeader for TemporaryCredentials {
fn get_header(&self) -> String {
"".to_string()
}
}
impl fmt::Show for TemporaryCredentials {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let builder : String;
write!(f, "output")
}
}
|
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkPipelineDepthStencilStateCreateInfo {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub flags: VkPipelineDepthStencilStateCreateFlagBits,
pub depthTestEnable: VkBool32,
pub depthWriteEnable: VkBool32,
pub depthCompareOp: VkCompareOp,
pub depthBoundsTestEnable: VkBool32,
pub stencilTestEnable: VkBool32,
pub front: VkStencilOpState,
pub back: VkStencilOpState,
pub minDepthBounds: f32,
pub maxDepthBounds: f32,
}
impl VkPipelineDepthStencilStateCreateInfo {
pub fn new<T>(
flags: T,
depth_test_enable: bool,
depth_write_enable: bool,
depth_compare_op: VkCompareOp,
depth_bounds_test_enable: bool,
stencil_test_enable: bool,
front: VkStencilOpState,
back: VkStencilOpState,
min_depth_bounds: f32,
max_depth_bounds: f32,
) -> VkPipelineDepthStencilStateCreateInfo
where
T: Into<VkPipelineDepthStencilStateCreateFlagBits>,
{
VkPipelineDepthStencilStateCreateInfo {
sType: VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
pNext: ptr::null(),
flags: flags.into(),
depthTestEnable: depth_test_enable.into(),
depthWriteEnable: depth_write_enable.into(),
depthCompareOp: depth_compare_op,
depthBoundsTestEnable: depth_bounds_test_enable.into(),
stencilTestEnable: stencil_test_enable.into(),
front,
back,
minDepthBounds: min_depth_bounds,
maxDepthBounds: max_depth_bounds,
}
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use fidl_fuchsia_intl::Profile;
/// Manual implementations of `Clone` for intl FIDL data types.
pub trait CloneExt {
fn clone(&self) -> Self;
}
// This manual impl is necessary because `Profile` is a table without
// [MaxHandles], so it could potentially have non-cloneable handles
// added to it in the future.
impl CloneExt for Profile {
fn clone(&self) -> Self {
Profile {
locales: self.locales.clone(),
calendars: self.calendars.clone(),
time_zones: self.time_zones.clone(),
temperature_unit: self.temperature_unit.clone(),
}
}
}
|
extern crate rand;
extern crate ansi_term;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
use ansi_term::Colour::{Red, Blue, Yellow, Green};
fn main() {
println!("{}", Blue.bold().underline().paint("\n\n-- Guess the number --\n\n"));
println!("Please input your guess, between 1-100.");
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => {
if num > 100 {
println!("{}", Red.paint("Please type a BETWEEN 1-100 you idiot..."));
100
} else {
num
}
},
Err(_) => {
println!("{}", Red.paint("Please type a number you idiot..."));
continue;
},
};
println!("You guessed: {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("{}", Yellow.paint("Too small.. Guess again:")),
Ordering::Greater => println!("{}", Yellow.paint("Too big.. Guess again:")),
Ordering::Equal => {
println!("{}", Green.bold().paint("\n\nTA-DA-RA-DUM!\nYou win!!\n\n\n"));
break;
}
}
}
}
|
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
mod lib;
fn main() {
let s = get_file_string();
let steps = lib::solve_first(&*s);
println!("shortest amount of steps: \n{}", steps);
let steps = lib::solve_second(&*s);
println!("Max amount of steps: \n{}", steps);
}
fn get_file_string() -> String {
// Create a path to the desired file
let path = Path::new("directions.txt");
let display = path.display();
// Open the path in read-only mode, returns `io::Result<File>`
let mut file = match File::open(&path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}", display,
why.description()),
Ok(file) => file,
};
// Read the file contents into a string, returns `io::Result<usize>`
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) => panic!("couldn't read {}: {}", display,
why.description()),
Ok(_) => print!("{} read\n", display),
}
return s;
} |
extern crate femapi;
fn main() {
femapi::init_server();
}
|
use std::{
fmt::Display,
sync::atomic::{AtomicI64, Ordering},
};
use async_trait::async_trait;
use data_types::{CompactionLevel, ParquetFile, ParquetFileId, ParquetFileParams, PartitionId};
use parking_lot::Mutex;
use super::{Commit, Error};
#[derive(Debug, PartialEq, Eq, Clone)]
pub(crate) struct CommitHistoryEntry {
pub(crate) partition_id: PartitionId,
pub(crate) delete: Vec<ParquetFile>,
pub(crate) upgrade: Vec<ParquetFile>,
pub(crate) created: Vec<ParquetFile>,
pub(crate) target_level: CompactionLevel,
}
#[derive(Debug, Default)]
pub(crate) struct MockCommit {
history: Mutex<Vec<CommitHistoryEntry>>,
id_counter: AtomicI64,
}
impl MockCommit {
pub(crate) fn new() -> Self {
Self {
history: Default::default(),
id_counter: AtomicI64::new(1000),
}
}
#[cfg(test)]
pub(crate) fn history(&self) -> Vec<CommitHistoryEntry> {
self.history.lock().clone()
}
}
impl Display for MockCommit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "mock")
}
}
#[async_trait]
impl Commit for MockCommit {
async fn commit(
&self,
partition_id: PartitionId,
delete: &[ParquetFile],
upgrade: &[ParquetFile],
create: &[ParquetFileParams],
target_level: CompactionLevel,
) -> Result<Vec<ParquetFileId>, Error> {
let (created, ids): (Vec<_>, Vec<_>) = create
.iter()
.map(|params| {
let id = ParquetFileId::new(self.id_counter.fetch_add(1, Ordering::SeqCst));
let created = ParquetFile::from_params(params.clone(), id);
(created, id)
})
.unzip();
self.history.lock().push(CommitHistoryEntry {
partition_id,
delete: delete.to_vec(),
upgrade: upgrade.to_vec(),
created,
target_level,
});
Ok(ids)
}
}
#[cfg(test)]
mod tests {
use super::*;
use assert_matches::assert_matches;
use iox_tests::{partition_identifier, ParquetFileBuilder};
#[test]
fn test_display() {
assert_eq!(MockCommit::new().to_string(), "mock");
}
#[tokio::test]
async fn test_commit() {
let commit = MockCommit::new();
let partition_id_1 = PartitionId::new(1);
let transition_partition_id_1 = partition_identifier(1);
let partition_id_2 = PartitionId::new(2);
let transition_partition_id_2 = partition_identifier(2);
let existing_1 = ParquetFileBuilder::new(1).build();
let existing_2 = ParquetFileBuilder::new(2).build();
let existing_3 = ParquetFileBuilder::new(3).build();
let existing_4 = ParquetFileBuilder::new(4).build();
let existing_5 = ParquetFileBuilder::new(5).build();
let existing_6 = ParquetFileBuilder::new(6).build();
let existing_7 = ParquetFileBuilder::new(7).build();
let existing_8 = ParquetFileBuilder::new(8).build();
let created_1_1 = ParquetFileBuilder::new(1000)
.with_partition(transition_partition_id_1.clone())
.build();
let created_1_2 = ParquetFileBuilder::new(1001)
.with_partition(transition_partition_id_1.clone())
.build();
let created_1_3 = ParquetFileBuilder::new(1003)
.with_partition(transition_partition_id_1)
.build();
let created_2_1 = ParquetFileBuilder::new(1002)
.with_partition(transition_partition_id_2)
.build();
let ids = commit
.commit(
partition_id_1,
&[existing_1.clone(), existing_2.clone()],
&[existing_3.clone(), existing_4.clone()],
&[created_1_1.clone().into(), created_1_2.clone().into()],
CompactionLevel::FileNonOverlapped,
)
.await;
assert_matches!(
ids,
Ok(res) if res == vec![ParquetFileId::new(1000), ParquetFileId::new(1001)]
);
let ids = commit
.commit(
partition_id_2,
&[existing_3.clone()],
&[],
&[created_2_1.clone().into()],
CompactionLevel::Final,
)
.await;
assert_matches!(
ids,
Ok(res) if res == vec![ParquetFileId::new(1002)]
);
let ids = commit
.commit(
partition_id_1,
&[existing_5.clone(), existing_6.clone(), existing_7.clone()],
&[],
&[created_1_3.clone().into()],
CompactionLevel::FileNonOverlapped,
)
.await;
assert_matches!(
ids,
Ok(res) if res == vec![ParquetFileId::new(1003)]
);
// simulate fill implosion of the file (this may happen w/ delete predicates)
let ids = commit
.commit(
partition_id_1,
&[existing_8.clone()],
&[],
&[],
CompactionLevel::FileNonOverlapped,
)
.await;
assert_matches!(
ids,
Ok(res) if res == vec![]
);
assert_eq!(
commit.history(),
vec![
CommitHistoryEntry {
partition_id: partition_id_1,
delete: vec![existing_1, existing_2],
upgrade: vec![existing_3.clone(), existing_4.clone()],
created: vec![created_1_1, created_1_2],
target_level: CompactionLevel::FileNonOverlapped,
},
CommitHistoryEntry {
partition_id: partition_id_2,
delete: vec![existing_3],
upgrade: vec![],
created: vec![created_2_1],
target_level: CompactionLevel::Final,
},
CommitHistoryEntry {
partition_id: partition_id_1,
delete: vec![existing_5, existing_6, existing_7,],
upgrade: vec![],
created: vec![created_1_3],
target_level: CompactionLevel::FileNonOverlapped,
},
CommitHistoryEntry {
partition_id: partition_id_1,
delete: vec![existing_8],
upgrade: vec![],
created: vec![],
target_level: CompactionLevel::FileNonOverlapped,
},
]
)
}
}
|
#![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 AMSI_ATTRIBUTE(pub i32);
pub const AMSI_ATTRIBUTE_APP_NAME: AMSI_ATTRIBUTE = AMSI_ATTRIBUTE(0i32);
pub const AMSI_ATTRIBUTE_CONTENT_NAME: AMSI_ATTRIBUTE = AMSI_ATTRIBUTE(1i32);
pub const AMSI_ATTRIBUTE_CONTENT_SIZE: AMSI_ATTRIBUTE = AMSI_ATTRIBUTE(2i32);
pub const AMSI_ATTRIBUTE_CONTENT_ADDRESS: AMSI_ATTRIBUTE = AMSI_ATTRIBUTE(3i32);
pub const AMSI_ATTRIBUTE_SESSION: AMSI_ATTRIBUTE = AMSI_ATTRIBUTE(4i32);
pub const AMSI_ATTRIBUTE_REDIRECT_CHAIN_SIZE: AMSI_ATTRIBUTE = AMSI_ATTRIBUTE(5i32);
pub const AMSI_ATTRIBUTE_REDIRECT_CHAIN_ADDRESS: AMSI_ATTRIBUTE = AMSI_ATTRIBUTE(6i32);
pub const AMSI_ATTRIBUTE_ALL_SIZE: AMSI_ATTRIBUTE = AMSI_ATTRIBUTE(7i32);
pub const AMSI_ATTRIBUTE_ALL_ADDRESS: AMSI_ATTRIBUTE = AMSI_ATTRIBUTE(8i32);
pub const AMSI_ATTRIBUTE_QUIET: AMSI_ATTRIBUTE = AMSI_ATTRIBUTE(9i32);
impl ::core::convert::From<i32> for AMSI_ATTRIBUTE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for AMSI_ATTRIBUTE {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct AMSI_RESULT(pub i32);
pub const AMSI_RESULT_CLEAN: AMSI_RESULT = AMSI_RESULT(0i32);
pub const AMSI_RESULT_NOT_DETECTED: AMSI_RESULT = AMSI_RESULT(1i32);
pub const AMSI_RESULT_BLOCKED_BY_ADMIN_START: AMSI_RESULT = AMSI_RESULT(16384i32);
pub const AMSI_RESULT_BLOCKED_BY_ADMIN_END: AMSI_RESULT = AMSI_RESULT(20479i32);
pub const AMSI_RESULT_DETECTED: AMSI_RESULT = AMSI_RESULT(32768i32);
impl ::core::convert::From<i32> for AMSI_RESULT {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for AMSI_RESULT {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct AMSI_UAC_MSI_ACTION(pub i32);
pub const AMSI_UAC_MSI_ACTION_INSTALL: AMSI_UAC_MSI_ACTION = AMSI_UAC_MSI_ACTION(0i32);
pub const AMSI_UAC_MSI_ACTION_UNINSTALL: AMSI_UAC_MSI_ACTION = AMSI_UAC_MSI_ACTION(1i32);
pub const AMSI_UAC_MSI_ACTION_UPDATE: AMSI_UAC_MSI_ACTION = AMSI_UAC_MSI_ACTION(2i32);
pub const AMSI_UAC_MSI_ACTION_MAINTENANCE: AMSI_UAC_MSI_ACTION = AMSI_UAC_MSI_ACTION(3i32);
pub const AMSI_UAC_MSI_ACTION_MAX: AMSI_UAC_MSI_ACTION = AMSI_UAC_MSI_ACTION(4i32);
impl ::core::convert::From<i32> for AMSI_UAC_MSI_ACTION {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for AMSI_UAC_MSI_ACTION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct AMSI_UAC_REQUEST_AX_INFO {
pub ulLength: u32,
pub lpwszLocalInstallPath: super::super::Foundation::PWSTR,
pub lpwszSourceURL: super::super::Foundation::PWSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl AMSI_UAC_REQUEST_AX_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for AMSI_UAC_REQUEST_AX_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for AMSI_UAC_REQUEST_AX_INFO {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("AMSI_UAC_REQUEST_AX_INFO").field("ulLength", &self.ulLength).field("lpwszLocalInstallPath", &self.lpwszLocalInstallPath).field("lpwszSourceURL", &self.lpwszSourceURL).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for AMSI_UAC_REQUEST_AX_INFO {
fn eq(&self, other: &Self) -> bool {
self.ulLength == other.ulLength && self.lpwszLocalInstallPath == other.lpwszLocalInstallPath && self.lpwszSourceURL == other.lpwszSourceURL
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for AMSI_UAC_REQUEST_AX_INFO {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for AMSI_UAC_REQUEST_AX_INFO {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct AMSI_UAC_REQUEST_COM_INFO {
pub ulLength: u32,
pub lpwszServerBinary: super::super::Foundation::PWSTR,
pub lpwszRequestor: super::super::Foundation::PWSTR,
pub Clsid: ::windows::core::GUID,
}
#[cfg(feature = "Win32_Foundation")]
impl AMSI_UAC_REQUEST_COM_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for AMSI_UAC_REQUEST_COM_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for AMSI_UAC_REQUEST_COM_INFO {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("AMSI_UAC_REQUEST_COM_INFO").field("ulLength", &self.ulLength).field("lpwszServerBinary", &self.lpwszServerBinary).field("lpwszRequestor", &self.lpwszRequestor).field("Clsid", &self.Clsid).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for AMSI_UAC_REQUEST_COM_INFO {
fn eq(&self, other: &Self) -> bool {
self.ulLength == other.ulLength && self.lpwszServerBinary == other.lpwszServerBinary && self.lpwszRequestor == other.lpwszRequestor && self.Clsid == other.Clsid
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for AMSI_UAC_REQUEST_COM_INFO {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for AMSI_UAC_REQUEST_COM_INFO {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct AMSI_UAC_REQUEST_CONTEXT {
pub ulLength: u32,
pub ulRequestorProcessId: u32,
pub UACTrustState: AMSI_UAC_TRUST_STATE,
pub Type: AMSI_UAC_REQUEST_TYPE,
pub RequestType: AMSI_UAC_REQUEST_CONTEXT_0,
pub bAutoElevateRequest: super::super::Foundation::BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl AMSI_UAC_REQUEST_CONTEXT {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for AMSI_UAC_REQUEST_CONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for AMSI_UAC_REQUEST_CONTEXT {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for AMSI_UAC_REQUEST_CONTEXT {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for AMSI_UAC_REQUEST_CONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union AMSI_UAC_REQUEST_CONTEXT_0 {
pub ExeInfo: AMSI_UAC_REQUEST_EXE_INFO,
pub ComInfo: AMSI_UAC_REQUEST_COM_INFO,
pub MsiInfo: AMSI_UAC_REQUEST_MSI_INFO,
pub ActiveXInfo: AMSI_UAC_REQUEST_AX_INFO,
pub PackagedAppInfo: AMSI_UAC_REQUEST_PACKAGED_APP_INFO,
}
#[cfg(feature = "Win32_Foundation")]
impl AMSI_UAC_REQUEST_CONTEXT_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for AMSI_UAC_REQUEST_CONTEXT_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for AMSI_UAC_REQUEST_CONTEXT_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for AMSI_UAC_REQUEST_CONTEXT_0 {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for AMSI_UAC_REQUEST_CONTEXT_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct AMSI_UAC_REQUEST_EXE_INFO {
pub ulLength: u32,
pub lpwszApplicationName: super::super::Foundation::PWSTR,
pub lpwszCommandLine: super::super::Foundation::PWSTR,
pub lpwszDLLParameter: super::super::Foundation::PWSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl AMSI_UAC_REQUEST_EXE_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for AMSI_UAC_REQUEST_EXE_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for AMSI_UAC_REQUEST_EXE_INFO {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("AMSI_UAC_REQUEST_EXE_INFO").field("ulLength", &self.ulLength).field("lpwszApplicationName", &self.lpwszApplicationName).field("lpwszCommandLine", &self.lpwszCommandLine).field("lpwszDLLParameter", &self.lpwszDLLParameter).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for AMSI_UAC_REQUEST_EXE_INFO {
fn eq(&self, other: &Self) -> bool {
self.ulLength == other.ulLength && self.lpwszApplicationName == other.lpwszApplicationName && self.lpwszCommandLine == other.lpwszCommandLine && self.lpwszDLLParameter == other.lpwszDLLParameter
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for AMSI_UAC_REQUEST_EXE_INFO {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for AMSI_UAC_REQUEST_EXE_INFO {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct AMSI_UAC_REQUEST_MSI_INFO {
pub ulLength: u32,
pub MsiAction: AMSI_UAC_MSI_ACTION,
pub lpwszProductName: super::super::Foundation::PWSTR,
pub lpwszVersion: super::super::Foundation::PWSTR,
pub lpwszLanguage: super::super::Foundation::PWSTR,
pub lpwszManufacturer: super::super::Foundation::PWSTR,
pub lpwszPackagePath: super::super::Foundation::PWSTR,
pub lpwszPackageSource: super::super::Foundation::PWSTR,
pub ulUpdates: u32,
pub ppwszUpdates: *mut super::super::Foundation::PWSTR,
pub ppwszUpdateSources: *mut super::super::Foundation::PWSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl AMSI_UAC_REQUEST_MSI_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for AMSI_UAC_REQUEST_MSI_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for AMSI_UAC_REQUEST_MSI_INFO {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("AMSI_UAC_REQUEST_MSI_INFO")
.field("ulLength", &self.ulLength)
.field("MsiAction", &self.MsiAction)
.field("lpwszProductName", &self.lpwszProductName)
.field("lpwszVersion", &self.lpwszVersion)
.field("lpwszLanguage", &self.lpwszLanguage)
.field("lpwszManufacturer", &self.lpwszManufacturer)
.field("lpwszPackagePath", &self.lpwszPackagePath)
.field("lpwszPackageSource", &self.lpwszPackageSource)
.field("ulUpdates", &self.ulUpdates)
.field("ppwszUpdates", &self.ppwszUpdates)
.field("ppwszUpdateSources", &self.ppwszUpdateSources)
.finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for AMSI_UAC_REQUEST_MSI_INFO {
fn eq(&self, other: &Self) -> bool {
self.ulLength == other.ulLength
&& self.MsiAction == other.MsiAction
&& self.lpwszProductName == other.lpwszProductName
&& self.lpwszVersion == other.lpwszVersion
&& self.lpwszLanguage == other.lpwszLanguage
&& self.lpwszManufacturer == other.lpwszManufacturer
&& self.lpwszPackagePath == other.lpwszPackagePath
&& self.lpwszPackageSource == other.lpwszPackageSource
&& self.ulUpdates == other.ulUpdates
&& self.ppwszUpdates == other.ppwszUpdates
&& self.ppwszUpdateSources == other.ppwszUpdateSources
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for AMSI_UAC_REQUEST_MSI_INFO {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for AMSI_UAC_REQUEST_MSI_INFO {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct AMSI_UAC_REQUEST_PACKAGED_APP_INFO {
pub ulLength: u32,
pub lpwszApplicationName: super::super::Foundation::PWSTR,
pub lpwszCommandLine: super::super::Foundation::PWSTR,
pub lpPackageFamilyName: super::super::Foundation::PWSTR,
pub lpApplicationId: super::super::Foundation::PWSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl AMSI_UAC_REQUEST_PACKAGED_APP_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for AMSI_UAC_REQUEST_PACKAGED_APP_INFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for AMSI_UAC_REQUEST_PACKAGED_APP_INFO {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("AMSI_UAC_REQUEST_PACKAGED_APP_INFO")
.field("ulLength", &self.ulLength)
.field("lpwszApplicationName", &self.lpwszApplicationName)
.field("lpwszCommandLine", &self.lpwszCommandLine)
.field("lpPackageFamilyName", &self.lpPackageFamilyName)
.field("lpApplicationId", &self.lpApplicationId)
.finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for AMSI_UAC_REQUEST_PACKAGED_APP_INFO {
fn eq(&self, other: &Self) -> bool {
self.ulLength == other.ulLength && self.lpwszApplicationName == other.lpwszApplicationName && self.lpwszCommandLine == other.lpwszCommandLine && self.lpPackageFamilyName == other.lpPackageFamilyName && self.lpApplicationId == other.lpApplicationId
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for AMSI_UAC_REQUEST_PACKAGED_APP_INFO {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for AMSI_UAC_REQUEST_PACKAGED_APP_INFO {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct AMSI_UAC_REQUEST_TYPE(pub i32);
pub const AMSI_UAC_REQUEST_TYPE_EXE: AMSI_UAC_REQUEST_TYPE = AMSI_UAC_REQUEST_TYPE(0i32);
pub const AMSI_UAC_REQUEST_TYPE_COM: AMSI_UAC_REQUEST_TYPE = AMSI_UAC_REQUEST_TYPE(1i32);
pub const AMSI_UAC_REQUEST_TYPE_MSI: AMSI_UAC_REQUEST_TYPE = AMSI_UAC_REQUEST_TYPE(2i32);
pub const AMSI_UAC_REQUEST_TYPE_AX: AMSI_UAC_REQUEST_TYPE = AMSI_UAC_REQUEST_TYPE(3i32);
pub const AMSI_UAC_REQUEST_TYPE_PACKAGED_APP: AMSI_UAC_REQUEST_TYPE = AMSI_UAC_REQUEST_TYPE(4i32);
pub const AMSI_UAC_REQUEST_TYPE_MAX: AMSI_UAC_REQUEST_TYPE = AMSI_UAC_REQUEST_TYPE(5i32);
impl ::core::convert::From<i32> for AMSI_UAC_REQUEST_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for AMSI_UAC_REQUEST_TYPE {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct AMSI_UAC_TRUST_STATE(pub i32);
pub const AMSI_UAC_TRUST_STATE_TRUSTED: AMSI_UAC_TRUST_STATE = AMSI_UAC_TRUST_STATE(0i32);
pub const AMSI_UAC_TRUST_STATE_UNTRUSTED: AMSI_UAC_TRUST_STATE = AMSI_UAC_TRUST_STATE(1i32);
pub const AMSI_UAC_TRUST_STATE_BLOCKED: AMSI_UAC_TRUST_STATE = AMSI_UAC_TRUST_STATE(2i32);
pub const AMSI_UAC_TRUST_STATE_MAX: AMSI_UAC_TRUST_STATE = AMSI_UAC_TRUST_STATE(3i32);
impl ::core::convert::From<i32> for AMSI_UAC_TRUST_STATE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for AMSI_UAC_TRUST_STATE {
type Abi = Self;
}
#[inline]
pub unsafe fn AmsiCloseSession<'a, Param0: ::windows::core::IntoParam<'a, HAMSICONTEXT>, Param1: ::windows::core::IntoParam<'a, HAMSISESSION>>(amsicontext: Param0, amsisession: Param1) {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn AmsiCloseSession(amsicontext: HAMSICONTEXT, amsisession: HAMSISESSION);
}
::core::mem::transmute(AmsiCloseSession(amsicontext.into_param().abi(), amsisession.into_param().abi()))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn AmsiInitialize<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(appname: Param0) -> ::windows::core::Result<HAMSICONTEXT> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn AmsiInitialize(appname: super::super::Foundation::PWSTR, amsicontext: *mut HAMSICONTEXT) -> ::windows::core::HRESULT;
}
let mut result__: <HAMSICONTEXT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
AmsiInitialize(appname.into_param().abi(), &mut result__).from_abi::<HAMSICONTEXT>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn AmsiNotifyOperation<'a, Param0: ::windows::core::IntoParam<'a, HAMSICONTEXT>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(amsicontext: Param0, buffer: *const ::core::ffi::c_void, length: u32, contentname: Param3) -> ::windows::core::Result<AMSI_RESULT> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn AmsiNotifyOperation(amsicontext: HAMSICONTEXT, buffer: *const ::core::ffi::c_void, length: u32, contentname: super::super::Foundation::PWSTR, result: *mut AMSI_RESULT) -> ::windows::core::HRESULT;
}
let mut result__: <AMSI_RESULT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
AmsiNotifyOperation(amsicontext.into_param().abi(), ::core::mem::transmute(buffer), ::core::mem::transmute(length), contentname.into_param().abi(), &mut result__).from_abi::<AMSI_RESULT>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn AmsiOpenSession<'a, Param0: ::windows::core::IntoParam<'a, HAMSICONTEXT>>(amsicontext: Param0) -> ::windows::core::Result<HAMSISESSION> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn AmsiOpenSession(amsicontext: HAMSICONTEXT, amsisession: *mut HAMSISESSION) -> ::windows::core::HRESULT;
}
let mut result__: <HAMSISESSION as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
AmsiOpenSession(amsicontext.into_param().abi(), &mut result__).from_abi::<HAMSISESSION>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn AmsiScanBuffer<'a, Param0: ::windows::core::IntoParam<'a, HAMSICONTEXT>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param4: ::windows::core::IntoParam<'a, HAMSISESSION>>(amsicontext: Param0, buffer: *const ::core::ffi::c_void, length: u32, contentname: Param3, amsisession: Param4) -> ::windows::core::Result<AMSI_RESULT> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn AmsiScanBuffer(amsicontext: HAMSICONTEXT, buffer: *const ::core::ffi::c_void, length: u32, contentname: super::super::Foundation::PWSTR, amsisession: HAMSISESSION, result: *mut AMSI_RESULT) -> ::windows::core::HRESULT;
}
let mut result__: <AMSI_RESULT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
AmsiScanBuffer(amsicontext.into_param().abi(), ::core::mem::transmute(buffer), ::core::mem::transmute(length), contentname.into_param().abi(), amsisession.into_param().abi(), &mut result__).from_abi::<AMSI_RESULT>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn AmsiScanString<'a, Param0: ::windows::core::IntoParam<'a, HAMSICONTEXT>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, HAMSISESSION>>(amsicontext: Param0, string: Param1, contentname: Param2, amsisession: Param3) -> ::windows::core::Result<AMSI_RESULT> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn AmsiScanString(amsicontext: HAMSICONTEXT, string: super::super::Foundation::PWSTR, contentname: super::super::Foundation::PWSTR, amsisession: HAMSISESSION, result: *mut AMSI_RESULT) -> ::windows::core::HRESULT;
}
let mut result__: <AMSI_RESULT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
AmsiScanString(amsicontext.into_param().abi(), string.into_param().abi(), contentname.into_param().abi(), amsisession.into_param().abi(), &mut result__).from_abi::<AMSI_RESULT>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
#[inline]
pub unsafe fn AmsiUninitialize<'a, Param0: ::windows::core::IntoParam<'a, HAMSICONTEXT>>(amsicontext: Param0) {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn AmsiUninitialize(amsicontext: HAMSICONTEXT);
}
::core::mem::transmute(AmsiUninitialize(amsicontext.into_param().abi()))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
pub const CAntimalware: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfdb00e52_a214_4aa1_8fba_4357bb0072ec);
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq)]
#[repr(transparent)]
pub struct HAMSICONTEXT(pub isize);
impl ::core::default::Default for HAMSICONTEXT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
unsafe impl ::windows::core::Handle for HAMSICONTEXT {}
unsafe impl ::windows::core::Abi for HAMSICONTEXT {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq)]
#[repr(transparent)]
pub struct HAMSISESSION(pub isize);
impl ::core::default::Default for HAMSISESSION {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
unsafe impl ::windows::core::Handle for HAMSISESSION {}
unsafe impl ::windows::core::Abi for HAMSISESSION {
type Abi = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAmsiStream(pub ::windows::core::IUnknown);
impl IAmsiStream {
pub unsafe fn GetAttribute(&self, attribute: AMSI_ATTRIBUTE, datasize: u32, data: *mut u8, retdata: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(attribute), ::core::mem::transmute(datasize), ::core::mem::transmute(data), ::core::mem::transmute(retdata)).ok()
}
pub unsafe fn Read(&self, position: u64, size: u32, buffer: *mut u8, readsize: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(position), ::core::mem::transmute(size), ::core::mem::transmute(buffer), ::core::mem::transmute(readsize)).ok()
}
}
unsafe impl ::windows::core::Interface for IAmsiStream {
type Vtable = IAmsiStream_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3e47f2e5_81d4_4d3b_897f_545096770373);
}
impl ::core::convert::From<IAmsiStream> for ::windows::core::IUnknown {
fn from(value: IAmsiStream) -> Self {
value.0
}
}
impl ::core::convert::From<&IAmsiStream> for ::windows::core::IUnknown {
fn from(value: &IAmsiStream) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAmsiStream {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAmsiStream {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAmsiStream_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, attribute: AMSI_ATTRIBUTE, datasize: u32, data: *mut u8, retdata: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, position: u64, size: u32, buffer: *mut u8, readsize: *mut u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAntimalware(pub ::windows::core::IUnknown);
impl IAntimalware {
pub unsafe fn Scan<'a, Param0: ::windows::core::IntoParam<'a, IAmsiStream>>(&self, stream: Param0, result: *mut AMSI_RESULT, provider: *mut ::core::option::Option<IAntimalwareProvider>) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), stream.into_param().abi(), ::core::mem::transmute(result), ::core::mem::transmute(provider)).ok()
}
pub unsafe fn CloseSession(&self, session: u64) {
::core::mem::transmute((::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(session)))
}
}
unsafe impl ::windows::core::Interface for IAntimalware {
type Vtable = IAntimalware_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x82d29c2e_f062_44e6_b5c9_3d9a2f24a2df);
}
impl ::core::convert::From<IAntimalware> for ::windows::core::IUnknown {
fn from(value: IAntimalware) -> Self {
value.0
}
}
impl ::core::convert::From<&IAntimalware> for ::windows::core::IUnknown {
fn from(value: &IAntimalware) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAntimalware {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAntimalware {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAntimalware_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, stream: ::windows::core::RawPtr, result: *mut AMSI_RESULT, provider: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, session: u64),
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAntimalware2(pub ::windows::core::IUnknown);
impl IAntimalware2 {
pub unsafe fn Scan<'a, Param0: ::windows::core::IntoParam<'a, IAmsiStream>>(&self, stream: Param0, result: *mut AMSI_RESULT, provider: *mut ::core::option::Option<IAntimalwareProvider>) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), stream.into_param().abi(), ::core::mem::transmute(result), ::core::mem::transmute(provider)).ok()
}
pub unsafe fn CloseSession(&self, session: u64) {
::core::mem::transmute((::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(session)))
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Notify<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, buffer: *const ::core::ffi::c_void, length: u32, contentname: Param2, appname: Param3) -> ::windows::core::Result<AMSI_RESULT> {
let mut result__: <AMSI_RESULT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(buffer), ::core::mem::transmute(length), contentname.into_param().abi(), appname.into_param().abi(), &mut result__).from_abi::<AMSI_RESULT>(result__)
}
}
unsafe impl ::windows::core::Interface for IAntimalware2 {
type Vtable = IAntimalware2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x301035b5_2d42_4f56_8c65_2dcaa7fb3cdc);
}
impl ::core::convert::From<IAntimalware2> for ::windows::core::IUnknown {
fn from(value: IAntimalware2) -> Self {
value.0
}
}
impl ::core::convert::From<&IAntimalware2> for ::windows::core::IUnknown {
fn from(value: &IAntimalware2) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAntimalware2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAntimalware2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IAntimalware2> for IAntimalware {
fn from(value: IAntimalware2) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IAntimalware2> for IAntimalware {
fn from(value: &IAntimalware2) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IAntimalware> for IAntimalware2 {
fn into_param(self) -> ::windows::core::Param<'a, IAntimalware> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IAntimalware> for &IAntimalware2 {
fn into_param(self) -> ::windows::core::Param<'a, IAntimalware> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAntimalware2_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, stream: ::windows::core::RawPtr, result: *mut AMSI_RESULT, provider: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, session: u64),
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, buffer: *const ::core::ffi::c_void, length: u32, contentname: super::super::Foundation::PWSTR, appname: super::super::Foundation::PWSTR, presult: *mut AMSI_RESULT) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAntimalwareProvider(pub ::windows::core::IUnknown);
impl IAntimalwareProvider {
pub unsafe fn Scan<'a, Param0: ::windows::core::IntoParam<'a, IAmsiStream>>(&self, stream: Param0) -> ::windows::core::Result<AMSI_RESULT> {
let mut result__: <AMSI_RESULT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), stream.into_param().abi(), &mut result__).from_abi::<AMSI_RESULT>(result__)
}
pub unsafe fn CloseSession(&self, session: u64) {
::core::mem::transmute((::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(session)))
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn DisplayName(&self) -> ::windows::core::Result<super::super::Foundation::PWSTR> {
let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__)
}
}
unsafe impl ::windows::core::Interface for IAntimalwareProvider {
type Vtable = IAntimalwareProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb2cabfe3_fe04_42b1_a5df_08d483d4d125);
}
impl ::core::convert::From<IAntimalwareProvider> for ::windows::core::IUnknown {
fn from(value: IAntimalwareProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IAntimalwareProvider> for ::windows::core::IUnknown {
fn from(value: &IAntimalwareProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAntimalwareProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAntimalwareProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAntimalwareProvider_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, stream: ::windows::core::RawPtr, result: *mut AMSI_RESULT) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, session: u64),
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, displayname: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAntimalwareProvider2(pub ::windows::core::IUnknown);
impl IAntimalwareProvider2 {
pub unsafe fn Scan<'a, Param0: ::windows::core::IntoParam<'a, IAmsiStream>>(&self, stream: Param0) -> ::windows::core::Result<AMSI_RESULT> {
let mut result__: <AMSI_RESULT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), stream.into_param().abi(), &mut result__).from_abi::<AMSI_RESULT>(result__)
}
pub unsafe fn CloseSession(&self, session: u64) {
::core::mem::transmute((::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(session)))
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn DisplayName(&self) -> ::windows::core::Result<super::super::Foundation::PWSTR> {
let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Notify<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, buffer: *const ::core::ffi::c_void, length: u32, contentname: Param2, appname: Param3) -> ::windows::core::Result<AMSI_RESULT> {
let mut result__: <AMSI_RESULT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(buffer), ::core::mem::transmute(length), contentname.into_param().abi(), appname.into_param().abi(), &mut result__).from_abi::<AMSI_RESULT>(result__)
}
}
unsafe impl ::windows::core::Interface for IAntimalwareProvider2 {
type Vtable = IAntimalwareProvider2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7c1e6570_3f73_4e0f_8ad4_98b94cd3290f);
}
impl ::core::convert::From<IAntimalwareProvider2> for ::windows::core::IUnknown {
fn from(value: IAntimalwareProvider2) -> Self {
value.0
}
}
impl ::core::convert::From<&IAntimalwareProvider2> for ::windows::core::IUnknown {
fn from(value: &IAntimalwareProvider2) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAntimalwareProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAntimalwareProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IAntimalwareProvider2> for IAntimalwareProvider {
fn from(value: IAntimalwareProvider2) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IAntimalwareProvider2> for IAntimalwareProvider {
fn from(value: &IAntimalwareProvider2) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IAntimalwareProvider> for IAntimalwareProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, IAntimalwareProvider> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IAntimalwareProvider> for &IAntimalwareProvider2 {
fn into_param(self) -> ::windows::core::Param<'a, IAntimalwareProvider> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAntimalwareProvider2_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, stream: ::windows::core::RawPtr, result: *mut AMSI_RESULT) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, session: u64),
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, displayname: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, buffer: *const ::core::ffi::c_void, length: u32, contentname: super::super::Foundation::PWSTR, appname: super::super::Foundation::PWSTR, presult: *mut AMSI_RESULT) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAntimalwareUacProvider(pub ::windows::core::IUnknown);
impl IAntimalwareUacProvider {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn UacScan(&self, context: *const AMSI_UAC_REQUEST_CONTEXT) -> ::windows::core::Result<AMSI_RESULT> {
let mut result__: <AMSI_RESULT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(context), &mut result__).from_abi::<AMSI_RESULT>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn DisplayName(&self) -> ::windows::core::Result<super::super::Foundation::PWSTR> {
let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__)
}
}
unsafe impl ::windows::core::Interface for IAntimalwareUacProvider {
type Vtable = IAntimalwareUacProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb2cabfe4_fe04_42b1_a5df_08d483d4d125);
}
impl ::core::convert::From<IAntimalwareUacProvider> for ::windows::core::IUnknown {
fn from(value: IAntimalwareUacProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&IAntimalwareUacProvider> for ::windows::core::IUnknown {
fn from(value: &IAntimalwareUacProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAntimalwareUacProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IAntimalwareUacProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAntimalwareUacProvider_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,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, context: *const AMSI_UAC_REQUEST_CONTEXT, result: *mut AMSI_RESULT) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, displayname: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[cfg(feature = "Win32_Foundation")]
#[inline]
pub unsafe fn InstallELAMCertificateInfo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(elamfile: Param0) -> super::super::Foundation::BOOL {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn InstallELAMCertificateInfo(elamfile: super::super::Foundation::HANDLE) -> super::super::Foundation::BOOL;
}
::core::mem::transmute(InstallELAMCertificateInfo(elamfile.into_param().abi()))
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
|
use std::{
borrow::Cow,
iter::{FusedIterator, Peekable},
str::CharIndices,
};
#[derive(Debug, Clone, Copy)]
enum State {
Start,
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
S11,
Trap,
}
impl Default for State {
fn default() -> Self {
Self::Start
}
}
impl State {
fn is_final(&self) -> bool {
#[allow(clippy::match_like_matches_macro)]
match self {
Self::S3 | Self::S5 | Self::S6 | Self::S7 | Self::S8 | Self::S9 | Self::S11 => true,
_ => false,
}
}
fn is_trapped(&self) -> bool {
#[allow(clippy::match_like_matches_macro)]
match self {
Self::Trap => true,
_ => false,
}
}
fn transition(&mut self, c: char) {
*self = match c {
'\u{1b}' | '\u{9b}' => match self {
Self::Start => Self::S1,
_ => Self::Trap,
},
'(' | ')' => match self {
Self::S1 => Self::S2,
Self::S2 | Self::S4 => Self::S4,
_ => Self::Trap,
},
';' => match self {
Self::S1 | Self::S2 | Self::S4 => Self::S4,
Self::S5 | Self::S6 | Self::S7 | Self::S8 | Self::S10 => Self::S10,
_ => Self::Trap,
},
'[' | '#' | '?' => match self {
Self::S1 | Self::S2 | Self::S4 => Self::S4,
_ => Self::Trap,
},
'0'..='2' => match self {
Self::S1 | Self::S4 => Self::S5,
Self::S2 => Self::S3,
Self::S5 => Self::S6,
Self::S6 => Self::S7,
Self::S7 => Self::S8,
Self::S8 => Self::S9,
Self::S10 => Self::S5,
_ => Self::Trap,
},
'3'..='9' => match self {
Self::S1 | Self::S4 => Self::S5,
Self::S2 => Self::S5,
Self::S5 => Self::S6,
Self::S6 => Self::S7,
Self::S7 => Self::S8,
Self::S8 => Self::S9,
Self::S10 => Self::S5,
_ => Self::Trap,
},
'A'..='P' | 'R' | 'Z' | 'c' | 'f'..='n' | 'q' | 'r' | 'y' | '=' | '>' | '<' => {
match self {
Self::S1
| Self::S2
| Self::S4
| Self::S5
| Self::S6
| Self::S7
| Self::S8
| Self::S10 => Self::S11,
_ => Self::Trap,
}
}
_ => Self::Trap,
};
}
}
#[derive(Debug)]
struct Matches<'a> {
s: &'a str,
it: Peekable<CharIndices<'a>>,
}
impl<'a> Matches<'a> {
fn new(s: &'a str) -> Self {
let it = s.char_indices().peekable();
Self { s, it }
}
}
#[derive(Debug)]
struct Match<'a> {
text: &'a str,
start: usize,
end: usize,
}
impl<'a> Match<'a> {
#[inline]
pub fn as_str(&self) -> &'a str {
&self.text[self.start..self.end]
}
}
impl<'a> Iterator for Matches<'a> {
type Item = Match<'a>;
fn next(&mut self) -> Option<Self::Item> {
find_ansi_code_exclusive(&mut self.it).map(|(start, end)| Match {
text: self.s,
start,
end,
})
}
}
impl<'a> FusedIterator for Matches<'a> {}
fn find_ansi_code_exclusive(it: &mut Peekable<CharIndices>) -> Option<(usize, usize)> {
'outer: loop {
if let (start, '\u{1b}') | (start, '\u{9b}') = it.peek()? {
let start = *start;
let mut state = State::default();
let mut maybe_end = None;
loop {
let item = it.peek();
if let Some((idx, c)) = item {
state.transition(*c);
if state.is_final() {
maybe_end = Some(*idx);
}
}
// The match is greedy so run till we hit the trap state no matter what. A valid
// match is just one that was final at some point
if state.is_trapped() || item.is_none() {
match maybe_end {
Some(end) => {
// All possible final characters are a single byte so it's safe to make
// the end exclusive by just adding one
return Some((start, end + 1));
}
// The character we are peeking right now might be the start of a match so
// we want to continue the loop without popping off that char
None => continue 'outer,
}
}
it.next();
}
}
it.next();
}
}
/// Helper function to strip ansi codes.
pub fn strip_ansi_codes(s: &str) -> Cow<str> {
let mut char_it = s.char_indices().peekable();
match find_ansi_code_exclusive(&mut char_it) {
Some(_) => {
let stripped: String = AnsiCodeIterator::new(s)
.filter_map(|(text, is_ansi)| if is_ansi { None } else { Some(text) })
.collect();
Cow::Owned(stripped)
}
None => Cow::Borrowed(s),
}
}
/// An iterator over ansi codes in a string.
///
/// This type can be used to scan over ansi codes in a string.
/// It yields tuples in the form `(s, is_ansi)` where `s` is a slice of
/// the original string and `is_ansi` indicates if the slice contains
/// ansi codes or string values.
pub struct AnsiCodeIterator<'a> {
s: &'a str,
pending_item: Option<(&'a str, bool)>,
last_idx: usize,
cur_idx: usize,
iter: Matches<'a>,
}
impl<'a> AnsiCodeIterator<'a> {
/// Creates a new ansi code iterator.
pub fn new(s: &'a str) -> AnsiCodeIterator<'a> {
AnsiCodeIterator {
s,
pending_item: None,
last_idx: 0,
cur_idx: 0,
iter: Matches::new(s),
}
}
/// Returns the string slice up to the current match.
pub fn current_slice(&self) -> &str {
&self.s[..self.cur_idx]
}
/// Returns the string slice from the current match to the end.
pub fn rest_slice(&self) -> &str {
&self.s[self.cur_idx..]
}
}
impl<'a> Iterator for AnsiCodeIterator<'a> {
type Item = (&'a str, bool);
fn next(&mut self) -> Option<(&'a str, bool)> {
if let Some(pending_item) = self.pending_item.take() {
self.cur_idx += pending_item.0.len();
Some(pending_item)
} else if let Some(m) = self.iter.next() {
let s = &self.s[self.last_idx..m.start];
self.last_idx = m.end;
if s.is_empty() {
self.cur_idx = m.end;
Some((m.as_str(), true))
} else {
self.cur_idx = m.start;
self.pending_item = Some((m.as_str(), true));
Some((s, false))
}
} else if self.last_idx < self.s.len() {
let rv = &self.s[self.last_idx..];
self.cur_idx = self.s.len();
self.last_idx = self.s.len();
Some((rv, false))
} else {
None
}
}
}
impl<'a> FusedIterator for AnsiCodeIterator<'a> {}
#[cfg(test)]
mod tests {
use super::*;
use lazy_static::lazy_static;
use proptest::prelude::*;
use regex::Regex;
// The manual dfa `State` is a handwritten translation from the previously used regex. That
// regex is kept here and used to ensure that the new matches are the same as the old
lazy_static! {
static ref STRIP_ANSI_RE: Regex = Regex::new(
r"[\x1b\x9b]([()][012AB]|[\[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><])",
)
.unwrap();
}
impl<'a, 'b> PartialEq<Match<'a>> for regex::Match<'b> {
fn eq(&self, other: &Match<'a>) -> bool {
self.start() == other.start && self.end() == other.end
}
}
proptest! {
#[test]
fn dfa_matches_old_regex(s in r"([\x1b\x9b]?.*){0,5}") {
let old_matches: Vec<_> = STRIP_ANSI_RE.find_iter(&s).collect();
let new_matches: Vec<_> = Matches::new(&s).collect();
assert_eq!(old_matches, new_matches);
}
}
#[test]
fn dfa_matches_regex_on_small_strings() {
// To make sure the test runs in a reasonable time this is a slimmed down list of
// characters to reduce the groups that are only used with each other along with one
// arbitrarily chosen character not used in the regex (' ')
const POSSIBLE_BYTES: &[u8] = &[b' ', 0x1b, 0x9b, b'(', b'0', b'[', b';', b'3', b'C'];
fn check_all_strings_of_len(len: usize) {
_check_all_strings_of_len(len, &mut Vec::with_capacity(len));
}
fn _check_all_strings_of_len(len: usize, chunk: &mut Vec<u8>) {
if len == 0 {
if let Ok(s) = std::str::from_utf8(chunk) {
let old_matches: Vec<_> = STRIP_ANSI_RE.find_iter(s).collect();
let new_matches: Vec<_> = Matches::new(s).collect();
assert_eq!(old_matches, new_matches);
}
return;
}
for b in POSSIBLE_BYTES {
chunk.push(*b);
_check_all_strings_of_len(len - 1, chunk);
chunk.pop();
}
}
for str_len in 0..=6 {
check_all_strings_of_len(str_len);
}
}
#[test]
fn complex_data() {
let s = std::fs::read_to_string(
std::path::Path::new("tests")
.join("data")
.join("sample_zellij_session.log"),
)
.unwrap();
let old_matches: Vec<_> = STRIP_ANSI_RE.find_iter(&s).collect();
let new_matches: Vec<_> = Matches::new(&s).collect();
assert_eq!(old_matches, new_matches);
}
#[test]
fn state_machine() {
let ansi_code = "\x1b)B";
let mut state = State::default();
assert!(!state.is_final());
for c in ansi_code.chars() {
state.transition(c);
}
assert!(state.is_final());
state.transition('A');
assert!(state.is_trapped());
}
#[test]
fn back_to_back_entry_char() {
let s = "\x1b\x1bf";
let matches: Vec<_> = Matches::new(s).map(|m| m.as_str()).collect();
assert_eq!(&["\x1bf"], matches.as_slice());
}
#[test]
fn early_paren_can_use_many_chars() {
let s = "\x1b(C";
let matches: Vec<_> = Matches::new(s).map(|m| m.as_str()).collect();
assert_eq!(&[s], matches.as_slice());
}
#[test]
fn long_run_of_digits() {
let s = "\u{1b}00000";
let matches: Vec<_> = Matches::new(s).map(|m| m.as_str()).collect();
assert_eq!(&[s], matches.as_slice());
}
#[test]
fn test_ansi_iter_re_vt100() {
let s = "\x1b(0lpq\x1b)Benglish";
let mut iter = AnsiCodeIterator::new(s);
assert_eq!(iter.next(), Some(("\x1b(0", true)));
assert_eq!(iter.next(), Some(("lpq", false)));
assert_eq!(iter.next(), Some(("\x1b)B", true)));
assert_eq!(iter.next(), Some(("english", false)));
}
#[test]
fn test_ansi_iter_re() {
use crate::style;
let s = format!("Hello {}!", style("World").red().force_styling(true));
let mut iter = AnsiCodeIterator::new(&s);
assert_eq!(iter.next(), Some(("Hello ", false)));
assert_eq!(iter.current_slice(), "Hello ");
assert_eq!(iter.rest_slice(), "\x1b[31mWorld\x1b[0m!");
assert_eq!(iter.next(), Some(("\x1b[31m", true)));
assert_eq!(iter.current_slice(), "Hello \x1b[31m");
assert_eq!(iter.rest_slice(), "World\x1b[0m!");
assert_eq!(iter.next(), Some(("World", false)));
assert_eq!(iter.current_slice(), "Hello \x1b[31mWorld");
assert_eq!(iter.rest_slice(), "\x1b[0m!");
assert_eq!(iter.next(), Some(("\x1b[0m", true)));
assert_eq!(iter.current_slice(), "Hello \x1b[31mWorld\x1b[0m");
assert_eq!(iter.rest_slice(), "!");
assert_eq!(iter.next(), Some(("!", false)));
assert_eq!(iter.current_slice(), "Hello \x1b[31mWorld\x1b[0m!");
assert_eq!(iter.rest_slice(), "");
assert_eq!(iter.next(), None);
}
#[test]
fn test_ansi_iter_re_on_multi() {
use crate::style;
let s = format!("{}", style("a").red().bold().force_styling(true));
let mut iter = AnsiCodeIterator::new(&s);
assert_eq!(iter.next(), Some(("\x1b[31m", true)));
assert_eq!(iter.current_slice(), "\x1b[31m");
assert_eq!(iter.rest_slice(), "\x1b[1ma\x1b[0m");
assert_eq!(iter.next(), Some(("\x1b[1m", true)));
assert_eq!(iter.current_slice(), "\x1b[31m\x1b[1m");
assert_eq!(iter.rest_slice(), "a\x1b[0m");
assert_eq!(iter.next(), Some(("a", false)));
assert_eq!(iter.current_slice(), "\x1b[31m\x1b[1ma");
assert_eq!(iter.rest_slice(), "\x1b[0m");
assert_eq!(iter.next(), Some(("\x1b[0m", true)));
assert_eq!(iter.current_slice(), "\x1b[31m\x1b[1ma\x1b[0m");
assert_eq!(iter.rest_slice(), "");
assert_eq!(iter.next(), None);
}
}
|
//! HTTP helpers.
use std::io::Read;
use std::result;
use hyper::Client;
use hyper::header::ContentType;
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
pub use hyper::status::StatusCode;
pub use hyper::Error as HttpError;
header! { (SoapAction, "SOAPAction") => [String] }
/// Simplified HTTP response representation.
#[derive(Debug)]
pub struct Response {
pub status: StatusCode,
pub body: String,
}
/// Perform a GET request to specified URL.
pub fn get(url: &str) -> Result<Response> {
let client = Client::new();
let mut response = client.get(url).send()?;
let mut body = String::new();
response.read_to_string(&mut body)?;
Ok(Response {
status: response.status,
body: body,
})
}
/// Perform a SOAP action to specified URL.
pub fn soap_action(url: &str, action: &str, xml: &str) -> Result<Response> {
let client = Client::new();
let mut response = try!(
client.post(url)
.header(ContentType(Mime(TopLevel::Text, SubLevel::Xml,
vec![(Attr::Charset, Value::Utf8)])))
.header(SoapAction(action.into()))
.body(xml)
.send()
);
let mut body = String::new();
response.read_to_string(&mut body)?;
Ok(Response {
status: response.status,
body: body,
})
}
pub type Result<T> = result::Result<T, HttpError>;
|
use errors::*;
use net::endpoint::Endpoint;
use net::event::{ClientEvent, Event, ServerEvent};
use net::session_client::SessionClient;
use net::session_server::SessionServer;
use std;
use std::collections::{hash_map, HashMap};
struct StdNetListenCon {
socket: std::net::TcpListener,
}
impl StdNetListenCon {
fn new(socket: std::net::TcpListener) -> Self {
StdNetListenCon { socket }
}
}
fn wrap_listen(endpoint: &Endpoint) -> Result<std::net::TcpListener> {
let addr = endpoint.to_socket_addr()?;
let socket = std::net::TcpListener::bind(addr)?;
socket.set_nonblocking(true)?;
Ok(socket)
}
pub struct StdNetNode {
node_id: Vec<u8>,
local_discover_endpoints: Vec<Endpoint>,
listen_cons: Vec<StdNetListenCon>,
server_new_cons: Vec<SessionServer>,
server_cons: HashMap<String, SessionServer>,
client_cons: Vec<SessionClient>,
events: Vec<Event>,
}
impl StdNetNode {
pub fn new(node_id: &[u8]) -> Self {
StdNetNode {
node_id: node_id.to_vec(),
local_discover_endpoints: Vec::new(),
listen_cons: Vec::new(),
server_new_cons: Vec::new(),
server_cons: HashMap::new(),
client_cons: Vec::new(),
events: Vec::new(),
}
}
pub fn add_local_discover_endpoint(&mut self, endpoint: &Endpoint) {
self.local_discover_endpoints.push(endpoint.clone());
}
pub fn get_node_id(&self) -> Vec<u8> {
self.node_id.clone()
}
pub fn list_connected_nodes(&self) -> Vec<Vec<u8>> {
let mut out: Vec<Vec<u8>> = Vec::new();
for con in &self.client_cons {
out.push(con.remote_node_id.clone());
}
for con in self.server_cons.values() {
out.push(con.remote_node_id.clone());
}
out
}
pub fn list_discoverable(&self) -> HashMap<Vec<u8>, Vec<Endpoint>> {
let mut out: HashMap<Vec<u8>, Vec<Endpoint>> = HashMap::new();
for con in &self.client_cons {
if con.remote_node_id.is_empty() || con.remote_discover.is_empty() {
continue;
}
out.insert(con.remote_node_id.clone(), con.remote_discover.clone());
}
for con in self.server_cons.values() {
if con.remote_node_id.is_empty() || con.remote_discover.is_empty() {
continue;
}
out.insert(con.remote_node_id.clone(), con.remote_discover.clone());
}
out
}
pub fn send(&mut self, dest_node_id: &[u8], data: Vec<u8>) {
for con in &mut self.client_cons {
if con.remote_node_id == dest_node_id {
con.user_message(data).unwrap();
return;
}
}
for con in self.server_cons.values_mut() {
if con.remote_node_id == dest_node_id {
con.user_message(data).unwrap();
return;
}
}
self.events
.push(Event::OnError("no connection to node id".into()));
}
pub fn process_once(&mut self) -> Vec<Event> {
self.process_listen_cons();
self.process_server_cons();
self.process_client_cons();
self.events.drain(..).collect()
}
pub fn listen(&mut self, endpoint: &Endpoint) {
let socket = match wrap_listen(endpoint) {
Err(e) => {
self.events
.push(Event::OnServerEvent(ServerEvent::OnError(e)));
return;
}
Ok(s) => s,
};
self.listen_cons.push(StdNetListenCon::new(socket));
self.events
.push(Event::OnServerEvent(ServerEvent::OnListening(
endpoint.clone(),
)));
}
pub fn connect(&mut self, endpoint: &Endpoint) {
let session = match SessionClient::new_initial_connect(
endpoint,
&self.node_id,
self.local_discover_endpoints.clone(),
) {
Err(e) => {
self.events
.push(Event::OnClientEvent(ClientEvent::OnError(e)));
return;
}
Ok(s) => s,
};
self.client_cons.push(session);
}
// -- private -- //
fn process_listen_cons(&mut self) {
let mut new_listen_cons: Vec<StdNetListenCon> = Vec::new();
'top: for con in self.listen_cons.drain(..) {
loop {
match con.socket.accept() {
Ok((s, addr)) => {
let addr = Endpoint::from(addr);
if let Err(e) = s.set_nonblocking(true) {
self.events
.push(Event::OnServerEvent(ServerEvent::OnError(e.into())));
continue;
}
let mut session = match SessionServer::new(
&self.node_id,
&addr,
self.local_discover_endpoints.clone(),
) {
Err(e) => {
self.events
.push(Event::OnServerEvent(ServerEvent::OnError(e)));
continue;
}
Ok(s) => s,
};
session.cur_socket = Some(s);
self.server_new_cons.push(session);
continue;
}
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
break;
}
Err(e) => {
self.events
.push(Event::OnServerEvent(ServerEvent::OnError(e.into())));
break 'top;
}
}
}
new_listen_cons.push(con);
}
self.listen_cons = new_listen_cons;
}
fn process_server_cons(&mut self) {
let mut new_cons_list: Vec<SessionServer> = Vec::new();
let mut new_cons_hash: HashMap<String, SessionServer> = HashMap::new();
for (mut _k, mut con) in self.server_cons.drain() {
let (con, mut events) = con.process_once();
if let Some(con) = con {
new_cons_hash.insert(con.session_id.clone(), con);
}
self.events.append(&mut events);
}
for mut con in self.server_new_cons.drain(..) {
let (con, mut events) = con.process_once();
if let Some(con) = con {
if !con.session_id.is_empty() {
let key = con.session_id.clone();
match new_cons_hash.entry(key) {
hash_map::Entry::Occupied(mut e) => {
let session = e.get_mut();
session.cur_socket = con.cur_socket;
session.cur_request = con.cur_request;
}
hash_map::Entry::Vacant(e) => {
e.insert(con);
}
}
} else {
new_cons_list.push(con);
}
}
self.events.append(&mut events);
}
self.server_new_cons = new_cons_list;
self.server_cons = new_cons_hash;
}
fn process_client_cons(&mut self) {
let mut new_client_cons: Vec<SessionClient> = Vec::new();
for mut con in self.client_cons.drain(..) {
let (con, mut events) = con.process_once();
if let Some(con) = con {
new_client_cons.push(con);
}
self.events.append(&mut events);
}
self.client_cons = new_client_cons;
}
}
|
#[doc = "Reader of register FMC"]
pub type R = crate::R<u32, super::FMC>;
#[doc = "Writer for register FMC"]
pub type W = crate::W<u32, super::FMC>;
#[doc = "Register FMC `reset()`'s with value 0"]
impl crate::ResetValue for super::FMC {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `WRITE`"]
pub type WRITE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `WRITE`"]
pub struct WRITE_W<'a> {
w: &'a mut W,
}
impl<'a> WRITE_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 `ERASE`"]
pub type ERASE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ERASE`"]
pub struct ERASE_W<'a> {
w: &'a mut W,
}
impl<'a> ERASE_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 `MERASE`"]
pub type MERASE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MERASE`"]
pub struct MERASE_W<'a> {
w: &'a mut W,
}
impl<'a> MERASE_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 `COMT`"]
pub type COMT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `COMT`"]
pub struct COMT_W<'a> {
w: &'a mut W,
}
impl<'a> COMT_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 `WRKEY`"]
pub type WRKEY_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `WRKEY`"]
pub struct WRKEY_W<'a> {
w: &'a mut W,
}
impl<'a> WRKEY_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x7fff << 17)) | (((value as u32) & 0x7fff) << 17);
self.w
}
}
impl R {
#[doc = "Bit 0 - Write a Word into Flash Memory"]
#[inline(always)]
pub fn write(&self) -> WRITE_R {
WRITE_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Erase a Page of Flash Memory"]
#[inline(always)]
pub fn erase(&self) -> ERASE_R {
ERASE_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Mass Erase Flash Memory"]
#[inline(always)]
pub fn merase(&self) -> MERASE_R {
MERASE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Commit Register Value"]
#[inline(always)]
pub fn comt(&self) -> COMT_R {
COMT_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bits 17:31 - FLASH write key"]
#[inline(always)]
pub fn wrkey(&self) -> WRKEY_R {
WRKEY_R::new(((self.bits >> 17) & 0x7fff) as u16)
}
}
impl W {
#[doc = "Bit 0 - Write a Word into Flash Memory"]
#[inline(always)]
pub fn write(&mut self) -> WRITE_W {
WRITE_W { w: self }
}
#[doc = "Bit 1 - Erase a Page of Flash Memory"]
#[inline(always)]
pub fn erase(&mut self) -> ERASE_W {
ERASE_W { w: self }
}
#[doc = "Bit 2 - Mass Erase Flash Memory"]
#[inline(always)]
pub fn merase(&mut self) -> MERASE_W {
MERASE_W { w: self }
}
#[doc = "Bit 3 - Commit Register Value"]
#[inline(always)]
pub fn comt(&mut self) -> COMT_W {
COMT_W { w: self }
}
#[doc = "Bits 17:31 - FLASH write key"]
#[inline(always)]
pub fn wrkey(&mut self) -> WRKEY_W {
WRKEY_W { w: self }
}
}
|
use crate::{err_fmt, Err};
use bytes::Bytes;
use futures::{
future::BoxFuture,
prelude::*,
task::{Context, Poll},
};
use http::{Method, Request, Response, Uri};
use hyper::Body;
use std::pin::Pin;
#[derive(Debug)]
pub(crate) struct Client {
base: Uri,
client: hyper::Client<hyper::client::HttpConnector>,
}
impl Client {
pub(crate) fn new(uri: Uri) -> Self {
Self {
base: uri,
client: hyper::Client::new(),
}
}
fn set_origin<B>(&self, req: Request<B>) -> Result<Request<B>, Err> {
let (mut parts, body) = req.into_parts();
let (scheme, authority) = {
let scheme = self
.base
.scheme_part()
.ok_or(err_fmt!("PathAndQuery not found"))?;
let authority = self
.base
.authority_part()
.ok_or(err_fmt!("PathAndQuery not found"))?;
(scheme, authority)
};
let path = parts
.uri
.path_and_query()
.ok_or(err_fmt!("PathAndQuery not found"))?;
let uri = Uri::builder()
.scheme(scheme.clone())
.authority(authority.clone())
.path_and_query(path.clone())
.build()?;
parts.uri = uri;
Ok(Request::from_parts(parts, body))
}
}
/// A trait modeling interactions with the [Lambda Runtime API](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html).
pub(crate) trait EventClient<'a>: Send + Sync {
/// A future containing the next event from the Lambda Runtime API.
type Fut: Future<Output = Result<Response<Bytes>, Err>> + Send + 'a;
fn call(&self, req: Request<Bytes>) -> Self::Fut;
}
impl<'a> EventClient<'a> for Client {
type Fut = BoxFuture<'a, Result<Response<Bytes>, Err>>;
fn call(&self, req: Request<Bytes>) -> Self::Fut {
use futures::compat::{Future01CompatExt, Stream01CompatExt};
use pin_utils::pin_mut;
let req = {
let (parts, body) = req.into_parts();
let body = Body::from(body);
Request::from_parts(parts, body)
};
let req = self.set_origin(req).unwrap();
let res = self.client.request(req).compat();
let fut = async {
let res = res.await?;
let (parts, body) = res.into_parts();
let body = body.compat();
pin_mut!(body);
let mut buf: Vec<u8> = vec![];
while let Some(Ok(chunk)) = body.next().await {
let mut chunk: Vec<u8> = chunk.into_bytes().to_vec();
buf.append(&mut chunk)
}
let buf = Bytes::from(buf);
let res = Response::from_parts(parts, buf);
Ok(res)
};
fut.boxed()
}
}
/// The `Stream` implementation for `EventStream` converts a `Future`
/// containing the next event from the Lambda Runtime into a continuous
/// stream of events. While _this_ stream will continue to produce
/// events indefinitely, AWS Lambda will only run the Lambda function attached
/// to this runtime *if and only if* there is an event available for it to process.
/// For Lambda functions that receive a “warm wakeup”—i.e., the function is
/// readily available in the Lambda service's cache—this runtime is able
/// to immediately fetch the next event.
pub(crate) struct EventStream<'a, T>
where
T: EventClient<'a>,
{
current: Option<BoxFuture<'a, Result<Response<Bytes>, Err>>>,
client: &'a T,
}
impl<'a, T> EventStream<'a, T>
where
T: EventClient<'a>,
{
pub(crate) fn new(inner: &'a T) -> Self {
Self {
current: None,
client: inner,
}
}
pub(crate) fn next_event(&self) -> BoxFuture<'a, Result<Response<Bytes>, Err>> {
let req = Request::builder()
.method(Method::GET)
.uri(Uri::from_static("/runtime/invocation/next"))
.body(Bytes::new())
.unwrap();
Box::pin(self.client.call(req))
}
}
#[must_use = "streams do nothing unless you `.await` or poll them"]
impl<'a, T> Stream for EventStream<'a, T>
where
T: EventClient<'a>,
{
type Item = Result<Response<Bytes>, Err>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
// The `loop` is used to drive the inner future (`current`) to completion, advancing
// the state of this stream to yield a new `Item`. Loops like the one below are
// common in many hand-implemented `Futures` and `Streams`.
loop {
// The stream first checks an inner future is set. If the future is present,
// a runtime polls the inner future to completion.
if let Some(current) = &mut self.current {
match current.as_mut().poll(cx) {
// If the inner future signals readiness, we:
// 1. Create a new Future that represents the _next_ event which will be polled
// by subsequent iterations of this loop.
// 2. Return the current future, yielding the resolved future.
Poll::Ready(res) => {
let next = self.next_event();
self.current = Some(Box::pin(next));
return Poll::Ready(Some(res));
}
// Otherwise, the future signals that it's not ready, so we propagate the
// Poll::Pending signal to the caller.
Poll::Pending => return Poll::Pending,
}
} else {
self.current = Some(self.next_event());
}
}
}
}
|
use std::os::raw::c_char;
/// The boolean value type.
///
/// See [documentation](https://developer.apple.com/documentation/objectivec/bool).
pub type BOOL = c_char;
/// The [`BOOL`](type.BOOL.html) equivalent to
/// [`false`](https://doc.rust-lang.org/std/keyword.false.html).
///
/// See [documentation](https://developer.apple.com/documentation/objectivec/no).
pub const NO: BOOL = 0;
/// The [`BOOL`](type.BOOL.html) equivalent to
/// [`true`](https://doc.rust-lang.org/std/keyword.true.html).
///
/// See [documentation](https://developer.apple.com/documentation/objectivec/yes).
pub const YES: BOOL = 1;
|
// error-pattern: cyclic import
import zed::bar;
import bar::zed;
fn main(args: vec[str]) { log "loop"; } |
use std::collections::HashMap;
use chrono::prelude::*;
use serde_derive::{Deserialize, Serialize};
use strum_macros::Display;
/// This enum represents the status of the internal task handling of Pueue.
/// They basically represent the internal task life-cycle.
#[derive(Clone, Debug, Display, PartialEq, Serialize, Deserialize)]
pub enum TaskStatus {
/// The task is queued and waiting for a free slot
Queued,
/// The task has been manually stashed. It won't be executed until it's manually enqueued
Stashed,
/// The task is started and running
Running,
/// A previously running task has been paused
Paused,
/// Task finished successfully
Done,
/// Used while the command of a task is edited (to prevent starting the task)
Locked,
}
/// This enum represents the exit status of an actually spawned program.
/// It's only of relevance, once a task actually spawned and somehow finished.
#[derive(Clone, Debug, Display, PartialEq, Serialize, Deserialize)]
pub enum TaskResult {
/// Task exited with 0
Success,
/// The task failed in some other kind of way (error code != 0)
Failed(i32),
/// The task couldn't be spawned. Probably a typo in the command
FailedToSpawn(String),
/// Task has been actively killed by either the user or the daemon on shutdown
Killed,
/// A dependency of the task failed.
DependencyFailed,
}
/// Representation of a task.
/// start will be set the second the task starts processing.
/// exit_code, output and end won't be initialized, until the task has finished.
/// The output of the task is written into seperate files.
/// Upon task completion, the output is read from the files and put into the struct.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Task {
pub id: usize,
pub command: String,
pub path: String,
pub envs: HashMap<String, String>,
pub group: Option<String>,
pub enqueue_at: Option<DateTime<Local>>,
pub dependencies: Vec<usize>,
pub status: TaskStatus,
pub prev_status: TaskStatus,
pub result: Option<TaskResult>,
pub start: Option<DateTime<Local>>,
pub end: Option<DateTime<Local>>,
}
impl Task {
pub fn new(
command: String,
path: String,
envs: HashMap<String, String>,
group: Option<String>,
starting_status: TaskStatus,
enqueue_at: Option<DateTime<Local>>,
dependencies: Vec<usize>,
) -> Task {
Task {
id: 0,
command,
path,
envs,
group,
enqueue_at,
dependencies,
status: starting_status.clone(),
prev_status: starting_status,
result: None,
start: None,
end: None,
}
}
/// A convenience function, which is used to create a duplicate task.
pub fn from_task(task: &Task) -> Task {
Task {
id: 0,
command: task.command.clone(),
path: task.path.clone(),
envs: task.envs.clone(),
group: None,
enqueue_at: None,
dependencies: Vec::new(),
status: TaskStatus::Queued,
prev_status: TaskStatus::Queued,
result: None,
start: None,
end: None,
}
}
pub fn is_running(&self) -> bool {
self.status == TaskStatus::Running || self.status == TaskStatus::Paused
}
pub fn is_done(&self) -> bool {
self.status == TaskStatus::Done
}
/// Check if the task errored.
/// The only case when it didn't error is if it didn't run yet or if the task exited successfully.
pub fn failed(&self) -> bool {
match self.result {
None => false,
Some(TaskResult::Success) => false,
_ => true,
}
}
pub fn is_queued(&self) -> bool {
self.status == TaskStatus::Queued || self.status == TaskStatus::Stashed
}
}
|
// Copyright 2019 The n-sql Project Developers.
//
// 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::fmt::{Debug, Error, Formatter};
mod arithmetic_expression;
mod case_when_expression;
mod constant;
mod function;
mod unary_expression;
mod variable;
use ast::Column;
pub use self::arithmetic_expression::*;
pub use self::case_when_expression::*;
pub use self::constant::*;
pub use self::function::*;
pub use self::unary_expression::*;
pub use self::variable::*;
#[derive(Clone, Debug)]
pub enum Expression {
Constant(ConstantValue),
Column(Column),
Arithmetic(ArithmeticExpression),
Function(Function),
CaseWhen(CaseWhenExpression),
Unary(UnaryExpression),
Variable(Variable)
}
impl From<ConstantValue> for Expression {
fn from(v: ConstantValue) -> Self {
Expression::Constant(v)
}
}
impl From<CastFn> for Expression {
fn from(v: CastFn) -> Self {
Expression::Function(Function::Cast(v.into()).into())
}
}
impl From<i32> for Expression {
fn from(value: i32) -> Self {
ConstantValue::from(value).into()
}
}
impl Expression {
pub fn constant_numeric(&self) -> Option<NumericValue> {
match self {
Expression::Constant(t) => match t {
ConstantValue::Numeric(n) => Some(n.clone()),
_ => None
},
_ => None
}
}
}
|
extern crate clap;
use clap::{App, Arg, SubCommand};
mod extractor;
mod creator;
fn main() {
let matches = App::new("wtar")
.version("1.0")
.author("Wyatt E. <wyatt.k.emery@gmail.com>")
.about("A small version of tar that is compatible with tar -H ustar. Only supports files, directories and links")
.subcommand(SubCommand::with_name("create")
.about("Creates a tar file from a set of input files")
.arg(Arg::with_name("file")
.help("The file name of the output tar directory")
.takes_value(true)
.short("f")
.long("file")
.required(true))
.arg(Arg::with_name("input")
.help("The input files to be put into the tar directory")
.takes_value(true)
.index(1)
.multiple(true)
))
.subcommand(SubCommand::with_name("extract")
.about("Extracts a given tar file")
.arg(Arg::with_name("file")
.help("the file name of the unput tar directory")
.takes_value(true)
.short("f")
.long("file")
.required(true)))
.get_matches();
match matches.subcommand_name() {
Some("extract") => extract(&matches.subcommand_matches("extract").unwrap()),
Some("create") => create(&matches.subcommand_matches("create").unwrap()),
None => println!("No subcommands were used"),
_ => println!("An unrecognized subcmomand was used")
}
}
fn extract( matches : &clap::ArgMatches)
{
let input_file = matches.value_of("file").unwrap();
/*Begin to extract the tar*/
}
fn create(matches: &clap::ArgMatches)
{
let output_file = matches.value_of("file").unwrap();
let mut input_files = Vec::new();
let values = matches.values_of("input");
if values.is_some() {
let files = values.unwrap();
for file in files{
input_files.push(file);
}
}
creator::create(output_file, input_files);
}
|
extern crate rand_chacha;
extern crate rand_core;
pub use self::rand_chacha::ChaChaRng;
pub use self::rand_core::{RngCore, SeedableRng};
pub fn make_seeded_rng(fuzzer_input: &[u8]) -> ChaChaRng {
// We need 8 bytes worth of data to convet into u64, so start with zero and replace
// as much of those as there is data available.
let mut seed_slice = [0u8; 8];
if fuzzer_input.len() >= 8 {
seed_slice.copy_from_slice(&fuzzer_input[..8]);
} else {
seed_slice[..fuzzer_input.len()].copy_from_slice(&fuzzer_input);
}
let seed: u64 = u64::from_le_bytes(seed_slice);
ChaChaRng::seed_from_u64(seed)
}
|
use structs::other::Error;
#[derive(Debug, Fail)]
pub enum CBError {
#[fail(display = "http: {}", _0)]
Http(#[cause] super::hyper::Error),
#[fail(display = "serde: {}\n {}", error, data)]
Serde {
#[cause]
error: super::serde_json::Error,
data: String,
},
#[fail(display = "coinbase: {}", _0)]
Coinbase(Error),
#[fail(display = "null")]
Null,
}
#[derive(Debug, Fail)]
pub enum WSError {
#[fail(display = "connect")]
Connect(#[cause] super::tokio_tungstenite::tungstenite::Error),
#[fail(display = "send")]
Send(#[cause] super::tokio_tungstenite::tungstenite::Error),
#[fail(display = "read")]
Read(#[cause] super::tokio_tungstenite::tungstenite::Error),
#[fail(display = "serde")]
Serde {
#[cause]
error: super::serde_json::Error,
data: String,
},
}
use super::serde::{Deserialize, Deserializer};
impl<'de> Deserialize<'de> for WSError {
fn deserialize<D>(_deserializer: D) -> Result<WSError, D::Error>
where
D: Deserializer<'de>,
{
unimplemented!()
}
}
|
#[macro_use]
extern crate lazy_static;
use std::env;
use std::path::Path;
#[cfg(windows)]
lazy_static! {
static ref LIBS: Vec<&'static str> =
vec!["improbable_worker", "RakNetLibStatic", "ssl", "zlibstatic",];
}
#[cfg(unix)]
lazy_static! {
static ref LIBS: Vec<&'static str> = vec!["improbable_worker", "RakNetLibStatic", "ssl", "z",];
}
#[cfg(target_os = "linux")]
static PACKAGE_DIR: &str = "linux";
#[cfg(target_os = "macos")]
static PACKAGE_DIR: &str = "macos";
#[cfg(target_os = "windows")]
static PACKAGE_DIR: &str = "win";
fn main() {
let lib_dir = match env::var("SPATIAL_LIB_DIR") {
Ok(s) => s,
Err(_) => panic!("SPATIAL_LIB_DIR environment variable not set."),
};
let package_dir = Path::new(&lib_dir).join(PACKAGE_DIR);
println!("cargo:rustc-link-search={}", package_dir.to_str().unwrap());
for lib in LIBS.iter() {
println!("cargo:rustc-link-lib=static={}", lib)
}
#[cfg(target_os = "macos")]
println!("cargo:rustc-link-lib=dylib=c++");
#[cfg(target_os = "linux")]
println!("cargo:rustc-link-lib=dylib=stdc++");
#[cfg(target_os = "windows")]
{
println!("cargo:rustc-link-lib=dylib=gdi32");
println!("cargo:rustc-link-lib=dylib=user32");
}
}
|
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 mut x: i32 = read();
let mut y: i32 = read();
let z: i32 = read();
if x < y {
std::mem::swap(&mut x, &mut y);
}
let mut ans = 0;
ans += y;
x -= y;
if x > z {
ans += z;
} else {
ans += x + (z - x) / 2;
}
println!("{}", ans);
}
|
pub mod client;
use crate::client::{ClientActor,ClientCommand};
use actix::*;
use actix_rt::Arbiter;
use actix::io::SinkWrite;
use awc::Client;
use std::{io,thread};
use futures::StreamExt;
/*
* Connects to the websocket; and if valid, can send a text inputted from the terminal.
*/
fn main() {
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
env_logger::init();
let sys = System::new("client");
Arbiter::spawn(async {
let args: Vec<String> = std::env::args().collect();
Client::new()
.ws(format!("ws://0.0.0.0:8080/connect/{}",args[1]))
.connect()
.await
.map_err(|e| {
println!("{}", e);
})
.map(|(response,framed)|{
println!("{:?}",response);
let (sink, stream) = framed.split();
let addr = ClientActor::create(|ctx| {
ClientActor::add_stream(stream, ctx);
ClientActor(SinkWrite::new(sink, ctx))
});
// start console loop
thread::spawn(move || loop {
let mut cmd = String::new();
if io::stdin().read_line(&mut cmd).is_err() {
println!("error");
return;
}
addr.do_send(ClientCommand(cmd.trim().to_string()));
});
}).unwrap();
});
match sys.run() {
Ok(_) => println!("Ran successfully"),
Err(e) => {
println!("Error:{:?}",e);
std::process::exit(0);
}
}
}
|
use nodes::prelude::*;
pub struct Leaf {
content: NodeList<NodeP>
}
impl Leaf {
pub fn from(io: &Io, env: &GraphChain, items: Vec<source::Item>) -> Leaf {
Leaf {
content: NodeList::from(io,
items.into_iter().map(|n| item_node(io, env, n))
)
}
}
pub fn get(&self, n: usize) -> Option<NodeP> {
self.content.iter().nth(n).cloned()
}
pub fn iter<'a>(&'a self) -> impl Iterator<Item=&'a NodeP> {
self.content.iter()
}
}
impl Node for Leaf {
fn childs(&self, out: &mut Vec<NodeP>) {
self.content.childs(out)
}
fn layout(&self, env: LayoutChain, w: &mut Writer) {
if self.content.size() > 0 {
self.content.layout(env, w);
w.promote(Glue::Newline { fill: true });
}
}
}
|
use bitflags::bitflags;
use either::Either;
use crate::io::Encode;
use crate::mssql::io::MssqlBufMutExt;
use crate::mssql::protocol::header::{AllHeaders, Header};
use crate::mssql::MssqlArguments;
pub(crate) struct RpcRequest<'a> {
pub(crate) transaction_descriptor: u64,
// the procedure can be encoded as a u16 of a built-in or the name for a custom one
pub(crate) procedure: Either<&'a str, Procedure>,
pub(crate) options: OptionFlags,
pub(crate) arguments: &'a MssqlArguments,
}
#[derive(Debug, Copy, Clone)]
#[repr(u16)]
#[allow(dead_code)]
pub(crate) enum Procedure {
Cursor = 1,
CursorOpen = 2,
CursorPrepare = 3,
CursorExecute = 4,
CursorPrepareExecute = 5,
CursorUnprepare = 6,
CursorFetch = 7,
CursorOption = 8,
CursorClose = 9,
ExecuteSql = 10,
Prepare = 11,
Execute = 12,
PrepareExecute = 13,
PrepareExecuteRpc = 14,
Unprepare = 15,
}
bitflags! {
pub(crate) struct OptionFlags: u16 {
const WITH_RECOMPILE = 1;
// The server sends NoMetaData only if fNoMetadata is set to 1 in the request
const NO_META_DATA = 2;
// 1 if the metadata has not changed from the previous call and the server SHOULD reuse
// its cached metadata (the metadata MUST still be sent).
const REUSE_META_DATA = 4;
}
}
bitflags! {
pub(crate) struct StatusFlags: u8 {
// if the parameter is passed by reference (OUTPUT parameter) or
// 0 if parameter is passed by value
const BY_REF_VALUE = 1;
// 1 if the parameter being passed is to be the default value
const DEFAULT_VALUE = 2;
// 1 if the parameter that is being passed is encrypted. This flag is valid
// only when the column encryption feature is negotiated by client and server
// and is turned on
const ENCRYPTED = 8;
}
}
impl Encode<'_> for RpcRequest<'_> {
fn encode_with(&self, buf: &mut Vec<u8>, _: ()) {
AllHeaders(&[Header::TransactionDescriptor {
outstanding_request_count: 1,
transaction_descriptor: self.transaction_descriptor,
}])
.encode(buf);
match &self.procedure {
Either::Left(name) => {
buf.extend(&(name.len() as u16).to_le_bytes());
buf.put_utf16_str(name);
}
Either::Right(id) => {
buf.extend(&(0xffff_u16).to_le_bytes());
buf.extend(&(*id as u16).to_le_bytes());
}
}
buf.extend(&self.options.bits.to_le_bytes());
buf.extend(&self.arguments.data);
}
}
// TODO: Test serialization of this?
|
#[cfg(not(feature = "threading"))]
use std::rc::Rc;
#[cfg(feature = "threading")]
use std::sync::Arc;
// type aliases instead of newtypes because you can't do `fn method(self: PyRc<Self>)` with a
// newtype; requires the arbitrary_self_types unstable feature
#[cfg(feature = "threading")]
pub type PyRc<T> = Arc<T>;
#[cfg(not(feature = "threading"))]
pub type PyRc<T> = Rc<T>;
|
use num::cast::FromPrimitive;
use num::{One, Zero};
use std::iter::Sum;
use std::ops::{Add, Div, Mul, Sub};
#[derive(Debug, Clone)]
pub struct Position<I> {
x: I,
y: I,
z: I,
}
impl<I> Position<I> {
pub fn new(x: I, y: I, z: I) -> Self {
Position { x, y, z }
}
}
impl<I: Add<Output = I> + Sub<Output = I> + Mul<Output = I> + Copy> Position<I> {
pub fn distance_squared(&self, other: &Self) -> I {
let x_dist = self.x - other.x;
let y_dist = self.y - other.y;
let z_dist = self.z - other.z;
x_dist * x_dist + y_dist * y_dist + z_dist * z_dist
}
}
#[derive(Debug, Clone)]
pub struct Vector<I> {
x: I,
y: I,
z: I,
}
impl<I> Vector<I> {
pub fn new(x: I, y: I, z: I) -> Self {
Vector { x, y, z }
}
}
impl<I: Mul<Output = I> + Copy> Vector<I> {
pub fn scale(self, c: I) -> Self {
Vector::new(self.x * c, self.y * c, self.z * c)
}
}
impl<I: Add<Output = I> + Zero + One + Div<Output = I> + Mul + Copy + FromPrimitive> Vector<I> {
pub fn average(c: Vec<Self>) -> Option<Self> {
if !c.is_empty() {
let len = I::from_usize(c.len()).unwrap();
Some(c.into_iter().sum::<Vector<I>>().scale(I::one() / len))
} else {
None
}
}
}
impl<I: Add<Output = I>> Add for Vector<I> {
type Output = Self;
fn add(self, other: Self) -> Self {
Vector::new(self.x + other.x, self.y + other.y, self.z + other.z)
}
}
impl<I: Sub<Output = I>> Sub for Vector<I> {
type Output = Self;
fn sub(self, other: Self) -> Self {
Vector::new(self.x - other.x, self.y - other.y, self.z - other.z)
}
}
impl<I: Add<Output = I> + Zero> Sum for Vector<I> {
fn sum<A: Iterator<Item = Self>>(iter: A) -> Self {
iter.fold(Vector::new(I::zero(), I::zero(), I::zero()), Add::add)
}
}
|
use crate::smb2::{
helper_functions::negotiate_context::{
CompressionCapabilities, ContextType, EncryptionCapabilities, NegotiateContext,
NetnameNegotiateContextId, PreauthIntegrityCapabilities, RdmaTransformCapabilities,
TransportCapabilities,
},
requests::negotiate::Negotiate,
};
/// Serializes a negotiate request from the corresponding struct.
pub fn serialize_negotiate_request_body(request: &Negotiate) -> Vec<u8> {
let mut serialized_request: Vec<u8> = Vec::new();
serialized_request.append(&mut request.structure_size.clone());
serialized_request.append(&mut request.dialect_count.clone());
serialized_request.append(&mut request.security_mode.clone());
serialized_request.append(&mut request.reserved.clone());
serialized_request.append(&mut request.capabilities.clone());
serialized_request.append(&mut request.client_guid.clone());
serialized_request.append(&mut request.negotiate_context_offset.clone());
serialized_request.append(&mut request.negotiate_context_count.clone());
serialized_request.append(&mut request.reserved2.clone());
serialized_request.append(&mut request.dialects.iter().cloned().flatten().collect());
serialized_request.append(&mut request.padding.clone());
let mut serialized_contexts = serialize_negotiate_contexts(
request.negotiate_context_list.clone(),
serialized_request.len() as u32,
);
serialized_request.append(&mut serialized_contexts);
serialized_request
}
/// Serializes the list of negotiate contexts.
pub fn serialize_negotiate_contexts(
context_list: Vec<NegotiateContext>,
packet_size: u32,
) -> Vec<u8> {
let mut serialized_negotiate_contexts: Vec<u8> = Vec::new();
let context_list_length = context_list.len() as usize;
for (index, context) in context_list.into_iter().enumerate() {
serialized_negotiate_contexts.append(&mut context.context_type.clone());
serialized_negotiate_contexts.append(&mut context.data_length.clone());
serialized_negotiate_contexts.append(&mut context.reserved.clone());
serialized_negotiate_contexts.append(&mut navigate_to_corresponding_serializer(
&context.data.unwrap(),
));
if index < context_list_length - 1 {
serialized_negotiate_contexts.append(&mut add_alignment_padding_if_necessary(
packet_size + serialized_negotiate_contexts.len() as u32,
));
}
}
serialized_negotiate_contexts
}
/// Adds an alignment padding between negotiate contexts if the data length is not 8 byte aligned.
pub fn add_alignment_padding_if_necessary(packet_size: u32) -> Vec<u8> {
let remainer = packet_size % 8;
match remainer {
0 => vec![],
_ => vec![0; 8 - remainer as usize],
}
}
/// Navigates to a different serializer depending on the given context type.
pub fn navigate_to_corresponding_serializer(context_type: &ContextType) -> Vec<u8> {
match context_type {
ContextType::PreauthIntegrityCapabilities(preauth) => {
serialize_preauth_capabilities(preauth)
}
ContextType::EncryptionCapabilities(encryption) => {
serialize_encryption_capabilities(encryption)
}
ContextType::CompressionCapabilities(compression) => {
serialize_compression_capabilities(compression)
}
ContextType::NetnameNegotiateContextId(netname) => serialize_netname_context_id(netname),
ContextType::TransportCapabilities(transport) => {
serialize_transport_capabilities(transport)
}
ContextType::RdmaTransformCapabilities(rdma) => serialize_rdma_transform_capabilities(rdma),
}
}
/// Serializes pre authentication capabilities.
pub fn serialize_preauth_capabilities(preauth: &PreauthIntegrityCapabilities) -> Vec<u8> {
let mut serialized_preauth: Vec<u8> = Vec::new();
serialized_preauth.append(&mut preauth.hash_algorithm_count.clone());
serialized_preauth.append(&mut preauth.salt_length.clone());
serialized_preauth.append(&mut preauth.hash_algorithms.iter().cloned().flatten().collect());
serialized_preauth.append(&mut preauth.salt.clone());
serialized_preauth
}
/// Serializes encryption capabilities.
pub fn serialize_encryption_capabilities(encryption: &EncryptionCapabilities) -> Vec<u8> {
let mut serialized_encryption: Vec<u8> = Vec::new();
serialized_encryption.append(&mut encryption.cipher_count.clone());
serialized_encryption.append(&mut encryption.ciphers.iter().cloned().flatten().collect());
serialized_encryption
}
/// Serializes compression capabilities.
pub fn serialize_compression_capabilities(compression: &CompressionCapabilities) -> Vec<u8> {
let mut serialized_compression: Vec<u8> = Vec::new();
serialized_compression.append(&mut compression.compression_algorithm_count.clone());
serialized_compression.append(&mut compression.padding.clone());
serialized_compression.append(&mut compression.flags.clone());
serialized_compression.append(
&mut compression
.compression_algorithms
.iter()
.cloned()
.flatten()
.collect(),
);
serialized_compression
}
/// Serializes the netname context id.
pub fn serialize_netname_context_id(netname: &NetnameNegotiateContextId) -> Vec<u8> {
netname.net_name.clone()
}
/// Serializes transport capabilities.
pub fn serialize_transport_capabilities(transport: &TransportCapabilities) -> Vec<u8> {
transport.reserved.clone()
}
/// Serializes rdma transform capabilities.
pub fn serialize_rdma_transform_capabilities(rdma: &RdmaTransformCapabilities) -> Vec<u8> {
let mut serialized_rdma_transform: Vec<u8> = Vec::new();
serialized_rdma_transform.append(&mut rdma.transform_count.clone());
serialized_rdma_transform.append(&mut rdma.reserved1.clone());
serialized_rdma_transform.append(&mut rdma.reserved2.clone());
serialized_rdma_transform
.append(&mut rdma.rdma_transform_ids.iter().cloned().flatten().collect());
serialized_rdma_transform
}
#[cfg(test)]
mod tests {
use crate::smb2::{
helper_functions::fields::Capabilities,
helper_functions::{fields, negotiate_context},
requests,
};
use super::*;
struct Setup {
preauth: PreauthIntegrityCapabilities,
encrypt: EncryptionCapabilities,
compress: CompressionCapabilities,
netname: NetnameNegotiateContextId,
transport: TransportCapabilities,
rdma: RdmaTransformCapabilities,
negotiate_context_encrypt: NegotiateContext,
negotiate_context_compress: NegotiateContext,
}
impl Setup {
pub fn new() -> Self {
let mut preauth = PreauthIntegrityCapabilities::default();
preauth.hash_algorithm_count = b"\x01\x00".to_vec();
preauth.salt_length = b"\x20\x00".to_vec();
preauth.hash_algorithms = vec![b"\x01\x00".to_vec()];
preauth.salt =
b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f".to_vec();
preauth.salt.append(
&mut b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f".to_vec(),
);
let mut encrypt = EncryptionCapabilities::default();
encrypt.cipher_count = b"\x01\x00".to_vec();
encrypt.ciphers = vec![b"\x04\x00".to_vec()];
let mut compress = CompressionCapabilities::default();
compress.compression_algorithm_count = b"\x03\x00".to_vec();
compress.padding = vec![0; 2];
compress.flags =
negotiate_context::Flags::CompressionCapabilitiesFlagNone.unpack_byte_code();
compress.compression_algorithms = vec![
negotiate_context::CompressionAlgorithms::Lznt1.unpack_byte_code(),
negotiate_context::CompressionAlgorithms::Lz77.unpack_byte_code(),
negotiate_context::CompressionAlgorithms::Lz77Huffman.unpack_byte_code(),
];
let mut netname = NetnameNegotiateContextId::default();
netname.net_name = b"\x31\x00\x39\x00\x32\x00\x2e\x00\x31\x00\x36\x00\x38\x00\x2e\x00\x31\x00\x37\x00\x31\x00".to_vec();
let mut rdma = RdmaTransformCapabilities::default();
rdma.transform_count = b"\x01\x00".to_vec();
rdma.rdma_transform_ids =
vec![negotiate_context::RdmaTransformIds::RdmaTransformNone.unpack_byte_code()];
let mut negotiate_context_encrypt = NegotiateContext::default();
let encrypt_context = ContextType::EncryptionCapabilities(encrypt.clone());
negotiate_context_encrypt.context_type = encrypt_context.unpack_byte_code();
negotiate_context_encrypt.data_length = b"\x04\x00".to_vec();
negotiate_context_encrypt.data = Some(encrypt_context);
let mut negotiate_context_compress = NegotiateContext::default();
let compress_context = ContextType::CompressionCapabilities(compress.clone());
negotiate_context_compress.context_type = compress_context.unpack_byte_code();
negotiate_context_compress.data_length = b"\x0e\x00".to_vec();
negotiate_context_compress.data = Some(compress_context);
Setup {
preauth,
encrypt,
compress,
netname,
transport: TransportCapabilities::default(),
rdma,
negotiate_context_encrypt,
negotiate_context_compress,
}
}
}
#[test]
fn test_serialize_negotiate_request_body() {
let setup = Setup::new();
let mut negotiate_request = requests::negotiate::Negotiate::default();
negotiate_request.dialect_count = vec![1, 0];
negotiate_request.security_mode =
fields::SecurityMode::NegotiateSigningEnabled.unpack_byte_code(2);
negotiate_request.capabilities = Capabilities::return_all_capabilities();
negotiate_request.client_guid = vec![0; 16];
negotiate_request.negotiate_context_offset = b"\x62\x00\x00\x00".to_vec();
negotiate_request.negotiate_context_count = vec![2, 0];
negotiate_request
.dialects
.push(requests::negotiate::Dialects::Smb311.unpack_byte_code());
negotiate_request.padding = vec![0; 2];
negotiate_request.negotiate_context_list = vec![
setup.negotiate_context_encrypt,
setup.negotiate_context_compress,
];
let mut expected_byte_array = b"\x24\x00\x01\x00\x01\x00\x00\x00\x7f\x00\x00\x00".to_vec();
expected_byte_array.append(&mut vec![0; 16]);
expected_byte_array
.append(&mut b"\x62\x00\x00\x00\x02\x00\x00\x00\x11\x03\x00\x00".to_vec());
expected_byte_array.append(
&mut b"\x02\x00\x04\x00\x00\x00\x00\x00\x01\x00\x04\x00\x00\x00\x00\x00".to_vec(),
);
expected_byte_array.append(&mut b"\x03\x00\x0e\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x02\x00\x03\x00".to_vec());
assert_eq!(
expected_byte_array,
serialize_negotiate_request_body(&negotiate_request)
);
}
#[test]
fn test_serialize_negotiate_contexts() {
let setup = Setup::new();
let expected_byte_array = b"\x02\x00\x04\x00\x00\x00\x00\x00\x01\x00\x04\x00".to_vec();
assert_eq!(
expected_byte_array,
serialize_negotiate_contexts(vec![setup.negotiate_context_encrypt.clone()], 0)
);
let expected_byte_array = b"\x03\x00\x0e\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x02\x00\x03\x00".to_vec();
assert_eq!(
expected_byte_array,
serialize_negotiate_contexts(vec![setup.negotiate_context_compress.clone()], 0)
);
let mut expected_byte_array =
b"\x02\x00\x04\x00\x00\x00\x00\x00\x01\x00\x04\x00\x00\x00\x00\x00".to_vec();
expected_byte_array.append(&mut b"\x03\x00\x0e\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x02\x00\x03\x00".to_vec());
assert_eq!(
expected_byte_array,
serialize_negotiate_contexts(
vec![
setup.negotiate_context_encrypt,
setup.negotiate_context_compress
],
0
)
);
}
#[test]
fn test_navigate_to_corresponding_serializer() {
let setup = Setup::new();
let mut expected_byte_array = b"\x01\x00\x04\x00".to_vec();
assert_eq!(
expected_byte_array,
navigate_to_corresponding_serializer(&ContextType::EncryptionCapabilities(
setup.encrypt
))
);
expected_byte_array = b"\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x02\x00\x03\x00".to_vec();
assert_eq!(
expected_byte_array,
navigate_to_corresponding_serializer(&ContextType::CompressionCapabilities(
setup.compress
))
);
}
#[test]
fn test_serialize_preauth_capabilities() {
let setup = Setup::new();
let mut expected_byte_array = b"\x01\x00\x20\x00\x01\x00".to_vec();
expected_byte_array.append(
&mut b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f".to_vec(),
);
expected_byte_array.append(
&mut b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f".to_vec(),
);
assert_eq!(
expected_byte_array,
serialize_preauth_capabilities(&setup.preauth)
);
}
#[test]
fn test_serialize_encryption_capabilities() {
let setup = Setup::new();
let expected_byte_array = b"\x01\x00\x04\x00".to_vec();
assert_eq!(
expected_byte_array,
serialize_encryption_capabilities(&setup.encrypt)
);
}
#[test]
fn test_serialize_compression_capabilities() {
let setup = Setup::new();
let expected_byte_array =
b"\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x02\x00\x03\x00".to_vec();
assert_eq!(
expected_byte_array,
serialize_compression_capabilities(&setup.compress)
);
}
#[test]
fn test_serialize_netname_context_id() {
let setup = Setup::new();
let expected_byte_array = b"\x31\x00\x39\x00\x32\x00\x2e\x00\x31\x00\x36\x00\x38\x00\x2e\x00\x31\x00\x37\x00\x31\x00".to_vec();
assert_eq!(
expected_byte_array,
serialize_netname_context_id(&setup.netname)
);
}
#[test]
fn test_serialize_transport_capabilities() {
let setup = Setup::new();
let expected_byte_array = vec![0; 4];
assert_eq!(
expected_byte_array,
serialize_transport_capabilities(&setup.transport)
);
}
#[test]
fn test_serialize_rdma_transform_capabilities() {
let setup = Setup::new();
let expected_byte_array = b"\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00".to_vec();
assert_eq!(
expected_byte_array,
serialize_rdma_transform_capabilities(&setup.rdma)
);
}
}
|
extern crate cpal;
extern crate rand;
#[cfg(test)]
extern crate float_cmp;
mod synthesizer;
use synthesizer::{Synthesizer, Voice, VoiceKind};
use cpal::{EventLoop, StreamData, UnknownTypeOutputBuffer};
// series of events, each event is just the beginning of a bar
// generates new events,
// add attributes (which audio sample to play)
// bass?
fn main() {
let mut synth = Synthesizer::new();
synth.voice(Voice::new().amplitude(0.5).frequency(220.0).kind(VoiceKind::Saw));
let event_loop = EventLoop::new();
let device = cpal::default_output_device()
.expect("no output device available");
let format = device.default_output_format()
.unwrap();
let stream_id = event_loop.build_output_stream(&device, &format)
.unwrap();
event_loop.play_stream(stream_id);
let mut samples_written: u64 = 0;
event_loop.run(move |_stream_id, stream_data| {
let mut buffer = if let StreamData::Output{buffer} = stream_data {
if let UnknownTypeOutputBuffer::F32(buffer) = buffer {
buffer
} else {
panic!("got non f32 buffer");
}
} else {
panic!("got StreamData::Input, which we didn't request.");
};
for elem in buffer.iter_mut() {
let time = (samples_written / format.channels as u64) as f64 / format.sample_rate.0 as f64;
*elem = synth.sample(time) as f32;
samples_written += 1;
}
});
}
|
use gtk::prelude::*;
pub struct MainWindow {
window: gtk::Window,
results_store: gtk::ListStore,
query_entry: gtk::Entry,
}
macro_rules! clone {
(@param _) => ( _ );
(@param $x:ident) => ( $x );
($($n:ident),+ => move || $body:expr) => (
{
$( let $n = $n.clone(); )+
move || $body
}
);
($($n:ident),+ => move |$($p:tt),+| $body:expr) => (
{
$( let $n = $n.clone(); )+
move |$(clone!(@param $p),)+| $body
}
);
}
impl MainWindow {
pub fn new() -> MainWindow {
let glade_src = include_str!("mainwindow.glade");
let builder = gtk::Builder::new_from_string(glade_src);
let window: gtk::Window = builder.get_object("mainWindow").unwrap();
let query_entry: gtk::Entry = builder.get_object("queryEntry").unwrap();
let results_view: gtk::TreeView = builder.get_object("resultsList").unwrap();;
results_view.append_column(&MainWindow::build_results_column());
let results_store = gtk::ListStore::new(&[gtk::Type::String]);
results_view.set_model(Some(&results_store));
results_view.connect_row_activated(clone!(results_view => move |_, _, _| {
let selection = results_view.get_selection();
selection.get_selected().map(|(model, iter)| {
let hmm: Option<String> = model.get_value(&iter, 0).get();
println!("{:?}", hmm.unwrap());
});
}));
MainWindow {
window,
results_store,
query_entry,
}
}
pub fn build_results_column() -> gtk::TreeViewColumn {
let column = gtk::TreeViewColumn::new();
let cell = gtk::CellRendererText::new();
column.set_sort_column_id(0);
column.set_title("results");
column.set_visible(true);
column.pack_start(&cell, true);
column.add_attribute(&cell, "text", 0);
return column
}
pub fn start(&self) {
glib::set_application_name("launcher");
self.window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
self.window.show_all();
}
pub fn update_from(&self, query_results: Vec<String>) {
// For some reason only the first line of the initial insert shows, and
// then later inserts show all values. This line works around this quirk
self.results_store.insert_with_values(None, &[0], &[&""]);
self.results_store.clear();
for query_result in query_results.iter() {
self.results_store.insert_with_values(None, &[0], &[&query_result]);
}
}
pub fn query_entry(&self) -> >k::Entry {
&self.query_entry
}
}
|
use std::{sync::mpsc, thread, time::Duration}; // multiple producer, single consumer
#[test]
#[ignore = "safe concurrency"]
fn ownership_transference() {
println!("\n--- 16.2 fearless concurrency : channels and ownership transference ---\n");
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
println!("val is {}", val);
});
let received = rx.recv().unwrap();
println!("Got: {},", received);
}
fn multiple_values_and_waiting_receiver() {
println!("\n--- 16.2 fearless concurrency : sending multiple values and seeing the receiver wait ---\n");
// spwanwed thread will now send multiple messages and pause for a second between each message
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for val in vals {
tx.send(val).unwrap();
// this causes the receive to wait
thread::sleep(Duration::from_millis(500));
}
});
for received in rx {
println!("Got: {}", received);
}
}
pub fn main() {
println!("\n--- 16. fearless concurrency : message passing ---\n");
// transmitter (sender), receiver
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
// channels and ownership transference
//ownership_transference();
// sending multiple values and seeing the receiver wait
multiple_values_and_waiting_receiver();
}
|
extern crate rand;
mod bitcrush {
use rand::prelude::*;
static bits: u32 = 8;
#[no_mangle]
pub extern "C" fn awgn_generator()->f64 {
let mut tmp1: f64 = 0.0;
let mut tmp2: f64 = 0.0;
let mut result: f64 = 0.0;
|
//! This module contains implementations of [`iox_query`] interfaces for [QuerierNamespace].
use crate::{
namespace::QuerierNamespace,
query_log::QueryLog,
system_tables::{SystemSchemaProvider, SYSTEM_SCHEMA},
table::QuerierTable,
};
use async_trait::async_trait;
use data_types::NamespaceId;
use datafusion::{
catalog::{schema::SchemaProvider, CatalogProvider},
datasource::TableProvider,
error::DataFusionError,
prelude::Expr,
};
use datafusion_util::config::DEFAULT_SCHEMA;
use iox_query::{
exec::{ExecutorType, IOxSessionContext},
QueryChunk, QueryCompletedToken, QueryNamespace, QueryText,
};
use observability_deps::tracing::{debug, trace};
use std::{any::Any, collections::HashMap, sync::Arc};
use trace::ctx::SpanContext;
#[async_trait]
impl QueryNamespace for QuerierNamespace {
async fn chunks(
&self,
table_name: &str,
filters: &[Expr],
projection: Option<&Vec<usize>>,
ctx: IOxSessionContext,
) -> Result<Vec<Arc<dyn QueryChunk>>, DataFusionError> {
debug!(%table_name, ?filters, "Finding chunks for table");
// get table metadata
let table = match self.tables.get(table_name).map(Arc::clone) {
Some(table) => table,
None => {
// table gone
trace!(%table_name, "No entry for table");
return Ok(vec![]);
}
};
let chunks = table
.chunks(
filters,
ctx.child_span("QuerierNamespace chunks"),
projection,
)
.await?;
Ok(chunks)
}
fn retention_time_ns(&self) -> Option<i64> {
self.retention_period.map(|d| {
self.catalog_cache.time_provider().now().timestamp_nanos() - d.as_nanos() as i64
})
}
fn record_query(
&self,
ctx: &IOxSessionContext,
query_type: &str,
query_text: QueryText,
) -> QueryCompletedToken {
// When the query token is dropped the query entry's completion time
// will be set.
let query_log = Arc::clone(&self.query_log);
let trace_id = ctx.span().map(|s| s.ctx.trace_id);
let entry = query_log.push(self.id, query_type, query_text, trace_id);
QueryCompletedToken::new(move |success| query_log.set_completed(entry, success))
}
fn new_query_context(&self, span_ctx: Option<SpanContext>) -> IOxSessionContext {
let mut cfg = self
.exec
.new_execution_config(ExecutorType::Query)
.with_default_catalog(Arc::new(QuerierCatalogProvider::from_namespace(self)) as _)
.with_span_context(span_ctx);
for (k, v) in self.datafusion_config.as_ref() {
cfg = cfg.with_config_option(k, v);
}
cfg.build()
}
}
pub struct QuerierCatalogProvider {
/// Namespace ID.
namespace_id: NamespaceId,
/// A snapshot of all tables.
tables: Arc<HashMap<Arc<str>, Arc<QuerierTable>>>,
/// Query log.
query_log: Arc<QueryLog>,
/// Include debug info tables.
include_debug_info_tables: bool,
}
impl QuerierCatalogProvider {
fn from_namespace(namespace: &QuerierNamespace) -> Self {
Self {
namespace_id: namespace.id,
tables: Arc::clone(&namespace.tables),
query_log: Arc::clone(&namespace.query_log),
include_debug_info_tables: namespace.include_debug_info_tables,
}
}
}
impl CatalogProvider for QuerierCatalogProvider {
fn as_any(&self) -> &dyn Any {
self as &dyn Any
}
fn schema_names(&self) -> Vec<String> {
vec![DEFAULT_SCHEMA.to_string(), SYSTEM_SCHEMA.to_string()]
}
fn schema(&self, name: &str) -> Option<Arc<dyn SchemaProvider>> {
match name {
DEFAULT_SCHEMA => Some(Arc::new(UserSchemaProvider {
tables: Arc::clone(&self.tables),
})),
SYSTEM_SCHEMA => Some(Arc::new(SystemSchemaProvider::new(
Arc::clone(&self.query_log),
self.namespace_id,
self.include_debug_info_tables,
))),
_ => None,
}
}
}
/// Provider for user-provided tables in [`DEFAULT_SCHEMA`].
struct UserSchemaProvider {
/// A snapshot of all tables.
tables: Arc<HashMap<Arc<str>, Arc<QuerierTable>>>,
}
#[async_trait]
impl SchemaProvider for UserSchemaProvider {
fn as_any(&self) -> &dyn Any {
self as &dyn Any
}
fn table_names(&self) -> Vec<String> {
let mut names: Vec<_> = self.tables.keys().map(|s| s.to_string()).collect();
names.sort();
names
}
async fn table(&self, name: &str) -> Option<Arc<dyn TableProvider>> {
self.tables.get(name).map(|t| Arc::clone(t) as _)
}
fn table_exist(&self, name: &str) -> bool {
self.tables.contains_key(name)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::namespace::test_util::{clear_parquet_cache, querier_namespace};
use arrow::record_batch::RecordBatch;
use arrow_util::test_util::{batches_to_sorted_lines, Normalizer};
use data_types::ColumnType;
use datafusion::common::DataFusionError;
use iox_query::frontend::sql::SqlQueryPlanner;
use iox_tests::{TestCatalog, TestParquetFileBuilder};
use iox_time::Time;
use metric::{Observation, RawReporter};
use snafu::{ResultExt, Snafu};
use trace::{span::SpanStatus, RingBufferTraceCollector};
#[tokio::test]
async fn test_query() {
test_helpers::maybe_start_logging();
let catalog = TestCatalog::new();
// namespace with infinite retention policy
let ns = catalog.create_namespace_with_retention("ns", None).await;
let table_cpu = ns.create_table("cpu").await;
let table_mem = ns.create_table("mem").await;
table_cpu.create_column("host", ColumnType::Tag).await;
table_cpu.create_column("time", ColumnType::Time).await;
table_cpu.create_column("load", ColumnType::F64).await;
table_cpu.create_column("foo", ColumnType::I64).await;
table_mem.create_column("host", ColumnType::Tag).await;
table_mem.create_column("time", ColumnType::Time).await;
table_mem.create_column("perc", ColumnType::F64).await;
let partition_cpu_a_1 = table_cpu.create_partition("a").await;
let partition_cpu_a_2 = table_cpu.create_partition("a").await;
let partition_cpu_b_1 = table_cpu.create_partition("b").await;
let partition_mem_c_1 = table_mem.create_partition("c").await;
let partition_mem_c_2 = table_mem.create_partition("c").await;
let builder = TestParquetFileBuilder::default()
.with_max_l0_created_at(Time::from_timestamp_nanos(1))
.with_line_protocol("cpu,host=a load=1 11")
.with_min_time(11)
.with_max_time(11);
partition_cpu_a_1.create_parquet_file(builder).await;
let builder = TestParquetFileBuilder::default()
.with_max_l0_created_at(Time::from_timestamp_nanos(2))
.with_line_protocol("cpu,host=a load=2 22")
.with_min_time(22)
.with_max_time(22);
partition_cpu_a_1
.create_parquet_file(builder)
.await
.flag_for_delete() // will be pruned because of soft delete
.await;
let builder = TestParquetFileBuilder::default()
.with_max_l0_created_at(Time::from_timestamp_nanos(3))
.with_line_protocol("cpu,host=z load=0 0")
.with_min_time(22)
.with_max_time(22);
partition_cpu_a_1.create_parquet_file(builder).await;
let builder = TestParquetFileBuilder::default()
.with_max_l0_created_at(Time::from_timestamp_nanos(4))
.with_line_protocol("cpu,host=a load=3 33")
.with_min_time(33)
.with_max_time(33);
partition_cpu_a_1.create_parquet_file(builder).await;
let builder = TestParquetFileBuilder::default()
.with_max_l0_created_at(Time::from_timestamp_nanos(5))
.with_line_protocol("cpu,host=a load=4 10001")
.with_min_time(10_001)
.with_max_time(10_001);
partition_cpu_a_2.create_parquet_file(builder).await;
let builder = TestParquetFileBuilder::default()
.with_creation_time(Time::from_timestamp_nanos(6))
.with_line_protocol("cpu,host=b load=5 11")
.with_min_time(11)
.with_max_time(11);
partition_cpu_b_1.create_parquet_file(builder).await;
let lp = [
"mem,host=c perc=50 11",
"mem,host=c perc=51 12",
"mem,host=d perc=53 14",
]
.join("\n");
let builder = TestParquetFileBuilder::default()
.with_max_l0_created_at(Time::from_timestamp_nanos(7))
.with_line_protocol(&lp)
.with_min_time(11)
.with_max_time(14);
partition_mem_c_1.create_parquet_file(builder).await;
let builder = TestParquetFileBuilder::default()
.with_max_l0_created_at(Time::from_timestamp_nanos(8))
.with_line_protocol("mem,host=c perc=50 1001")
.with_min_time(1001)
.with_max_time(1001);
partition_mem_c_2
.create_parquet_file(builder)
.await
.flag_for_delete()
.await;
let querier_namespace = Arc::new(querier_namespace(&ns).await);
let traces = Arc::new(RingBufferTraceCollector::new(100));
let span_ctx = SpanContext::new(Arc::clone(&traces) as _);
insta::assert_yaml_snapshot!(
format_query_with_span_ctx(
&querier_namespace,
"SELECT * FROM cpu WHERE host != 'z' ORDER BY host,time",
Some(span_ctx),
).await,
@r###"
---
- +-----+------+------+--------------------------------+
- "| foo | host | load | time |"
- +-----+------+------+--------------------------------+
- "| | a | 1.0 | 1970-01-01T00:00:00.000000011Z |"
- "| | a | 3.0 | 1970-01-01T00:00:00.000000033Z |"
- "| | a | 4.0 | 1970-01-01T00:00:00.000010001Z |"
- "| | b | 5.0 | 1970-01-01T00:00:00.000000011Z |"
- +-----+------+------+--------------------------------+
"###
);
// check span
let span = traces
.spans()
.into_iter()
.find(|s| s.name == "QuerierTable chunks")
.expect("tracing span not found");
assert_eq!(span.status, SpanStatus::Ok);
// check metrics
let mut reporter = RawReporter::default();
catalog.metric_registry().report(&mut reporter);
assert_eq!(
reporter
.metric("query_pruner_chunks")
.unwrap()
.observation(&[("result", "pruned_early")])
.unwrap(),
&Observation::U64Counter(0),
);
assert_eq!(
reporter
.metric("query_pruner_rows")
.unwrap()
.observation(&[("result", "pruned_early")])
.unwrap(),
&Observation::U64Counter(0),
);
assert_eq!(
reporter
.metric("query_pruner_bytes")
.unwrap()
.observation(&[("result", "pruned_early")])
.unwrap(),
&Observation::U64Counter(0),
);
assert_eq!(
reporter
.metric("query_pruner_chunks")
.unwrap()
.observation(&[("result", "pruned_late")])
.unwrap(),
&Observation::U64Counter(0),
);
assert_eq!(
reporter
.metric("query_pruner_rows")
.unwrap()
.observation(&[("result", "pruned_late")])
.unwrap(),
&Observation::U64Counter(0),
);
assert_eq!(
reporter
.metric("query_pruner_bytes")
.unwrap()
.observation(&[("result", "pruned_late")])
.unwrap(),
&Observation::U64Counter(0),
);
assert_eq!(
reporter
.metric("query_pruner_chunks")
.unwrap()
.observation(&[("result", "not_pruned")])
.unwrap(),
&Observation::U64Counter(5),
);
assert_eq!(
reporter
.metric("query_pruner_rows")
.unwrap()
.observation(&[("result", "not_pruned")])
.unwrap(),
&Observation::U64Counter(5),
);
if let Observation::U64Counter(bytes) = reporter
.metric("query_pruner_bytes")
.unwrap()
.observation(&[("result", "not_pruned")])
.unwrap()
{
assert!(*bytes > 6000, "bytes ({bytes}) must be > 6000");
} else {
panic!("Wrong metrics type");
}
assert_eq!(
reporter
.metric("query_pruner_chunks")
.unwrap()
.observation(&[
("result", "could_not_prune"),
("reason", "No expression on predicate")
])
.unwrap(),
&Observation::U64Counter(0),
);
assert_eq!(
reporter
.metric("query_pruner_rows")
.unwrap()
.observation(&[
("result", "could_not_prune"),
("reason", "No expression on predicate")
])
.unwrap(),
&Observation::U64Counter(0),
);
assert_eq!(
reporter
.metric("query_pruner_bytes")
.unwrap()
.observation(&[
("result", "could_not_prune"),
("reason", "No expression on predicate")
])
.unwrap(),
&Observation::U64Counter(0),
);
insta::assert_yaml_snapshot!(
format_query(
&querier_namespace,
"SELECT * FROM mem ORDER BY host,time"
).await,
@r###"
---
- +------+------+--------------------------------+
- "| host | perc | time |"
- +------+------+--------------------------------+
- "| c | 50.0 | 1970-01-01T00:00:00.000000011Z |"
- "| c | 51.0 | 1970-01-01T00:00:00.000000012Z |"
- "| d | 53.0 | 1970-01-01T00:00:00.000000014Z |"
- +------+------+--------------------------------+
"###
);
// ---------------------------------------------------------
// EXPLAIN
// 5 chunks but one was flaged for deleted -> 4 chunks left
// all chunks are persisted and do not overlap -> they will be scanned in one IOxReadFilterNode node
insta::assert_yaml_snapshot!(
format_explain(&querier_namespace, "EXPLAIN SELECT * FROM cpu").await,
@r###"
---
- "----------"
- "| plan_type | plan |"
- "----------"
- "| logical_plan | TableScan: cpu projection=[foo, host, load, time] |"
- "| physical_plan | ParquetExec: file_groups={1 group: [[1/1/1/00000000-0000-0000-0000-000000000000.parquet, 1/1/1/00000000-0000-0000-0000-000000000001.parquet, 1/1/1/00000000-0000-0000-0000-000000000002.parquet, 1/1/1/00000000-0000-0000-0000-000000000003.parquet, 1/1/1/00000000-0000-0000-0000-000000000004.parquet]]}, projection=[foo, host, load, time] |"
- "| | |"
- "----------"
"###
);
// The 2 participated chunks in the plan do not overlap -> no deduplication, no sort. Final
// sort is for order by.
insta::assert_yaml_snapshot!(
format_explain(&querier_namespace, "EXPLAIN SELECT * FROM mem ORDER BY host,time").await,
@r###"
---
- "----------"
- "| plan_type | plan |"
- "----------"
- "| logical_plan | Sort: mem.host ASC NULLS LAST, mem.time ASC NULLS LAST |"
- "| | TableScan: mem projection=[host, perc, time] |"
- "| physical_plan | SortExec: expr=[host@0 ASC NULLS LAST,time@2 ASC NULLS LAST] |"
- "| | ParquetExec: file_groups={1 group: [[1/1/1/00000000-0000-0000-0000-000000000000.parquet]]}, projection=[host, perc, time], output_ordering=[host@0 ASC, time@2 ASC] |"
- "| | |"
- "----------"
"###
);
// -----------
// Add an overlapped chunk
// (overlaps `partition_cpu_a_2`)
let builder = TestParquetFileBuilder::default()
.with_max_l0_created_at(Time::from_timestamp_nanos(10))
// duplicate row with different field value (load=14)
.with_line_protocol("cpu,host=a load=14 10001")
.with_min_time(10_001)
.with_max_time(10_001);
partition_cpu_a_2.create_parquet_file(builder).await;
// Since we made a new parquet file, we need to tell querier about it
clear_parquet_cache(&querier_namespace, table_cpu.table.id);
insta::assert_yaml_snapshot!(
format_query(&querier_namespace,
"SELECT * FROM cpu", // no need `order by` because data is sorted before comparing in assert_query
).await,
@r###"
---
- +-----+------+------+--------------------------------+
- "| foo | host | load | time |"
- +-----+------+------+--------------------------------+
- "| | a | 1.0 | 1970-01-01T00:00:00.000000011Z |"
- "| | a | 14.0 | 1970-01-01T00:00:00.000010001Z |"
- "| | a | 3.0 | 1970-01-01T00:00:00.000000033Z |"
- "| | b | 5.0 | 1970-01-01T00:00:00.000000011Z |"
- "| | z | 0.0 | 1970-01-01T00:00:00Z |"
- +-----+------+------+--------------------------------+
"###
);
// 5 chunks:
// . 2 chunks overlap with each other and must be deduplicated but no sort needed because they are sorted on the same sort key
// . 3 chunks do not overlap and have no duplicated --> will be scanned in one IOxReadFilterNode node
insta::assert_yaml_snapshot!(
format_explain(&querier_namespace, "EXPLAIN SELECT * FROM cpu").await,
@r###"
---
- "----------"
- "| plan_type | plan |"
- "----------"
- "| logical_plan | TableScan: cpu projection=[foo, host, load, time] |"
- "| physical_plan | UnionExec |"
- "| | ParquetExec: file_groups={1 group: [[1/1/1/00000000-0000-0000-0000-000000000000.parquet]]}, projection=[foo, host, load, time], output_ordering=[host@1 ASC, time@3 ASC] |"
- "| | ParquetExec: file_groups={1 group: [[1/1/1/00000000-0000-0000-0000-000000000001.parquet, 1/1/1/00000000-0000-0000-0000-000000000002.parquet, 1/1/1/00000000-0000-0000-0000-000000000003.parquet]]}, projection=[foo, host, load, time] |"
- "| | ProjectionExec: expr=[foo@1 as foo, host@2 as host, load@3 as load, time@4 as time] |"
- "| | DeduplicateExec: [host@2 ASC,time@4 ASC] |"
- "| | SortPreservingMergeExec: [host@2 ASC,time@4 ASC,__chunk_order@0 ASC] |"
- "| | ParquetExec: file_groups={2 groups: [[1/1/1/00000000-0000-0000-0000-000000000004.parquet], [1/1/1/00000000-0000-0000-0000-000000000005.parquet]]}, projection=[__chunk_order, foo, host, load, time], output_ordering=[host@2 ASC, time@4 ASC, __chunk_order@0 ASC] |"
- "| | |"
- "----------"
"###
);
}
async fn format_query(querier_namespace: &Arc<QuerierNamespace>, sql: &str) -> Vec<String> {
format_query_with_span_ctx(querier_namespace, sql, None).await
}
async fn format_query_with_span_ctx(
querier_namespace: &Arc<QuerierNamespace>,
sql: &str,
span_ctx: Option<SpanContext>,
) -> Vec<String> {
let results = run(querier_namespace, sql, span_ctx).await;
batches_to_sorted_lines(&results)
}
async fn format_explain(querier_namespace: &Arc<QuerierNamespace>, sql: &str) -> Vec<String> {
let results = run(querier_namespace, sql, None).await;
let normalizer = Normalizer {
normalized_uuids: true,
..Default::default()
};
normalizer.normalize_results(results)
}
async fn run(
querier_namespace: &Arc<QuerierNamespace>,
sql: &str,
span_ctx: Option<SpanContext>,
) -> Vec<RecordBatch> {
run_res(querier_namespace, sql, span_ctx)
.await
.expect("Build+run plan")
}
#[derive(Debug, Snafu)]
enum RunError {
#[snafu(display("Cannot build plan: {}", source))]
Build { source: DataFusionError },
#[snafu(display("Cannot run plan: {}", source))]
Run { source: DataFusionError },
}
async fn run_res(
querier_namespace: &Arc<QuerierNamespace>,
sql: &str,
span_ctx: Option<SpanContext>,
) -> Result<Vec<RecordBatch>, RunError> {
let planner = SqlQueryPlanner::default();
let ctx = querier_namespace.new_query_context(span_ctx);
let physical_plan = planner.query(sql, &ctx).await.context(BuildSnafu)?;
ctx.collect(physical_plan).await.context(RunSnafu)
}
}
|
/// 虚拟块设备前端驱动
/// ref: https://github.com/rcore-os/virtio-drivers/blob/master/src/blk.rs
/// thanks!
use bitflags::bitflags;
use volatile::Volatile;
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use core::ptr::NonNull;
use super::mmio::VirtIOHeader;
use super::queue::VirtQueue;
use super::util::AsBuf;
use super::config::*;
use super::*;
pub struct BlockFuture<'blk> {
/// 请求类型
/// 0 表示读,1 表示写
_req_type: u8,
/// 该块设备的虚拟队列,用于 poll 操作的时候判断请求是否完成
queue: &'blk mut VirtQueue,
/// 块设备的回应,用于 poll 操作的时候从这里读取请求被处理的状态
/// unused
response: NonNull<()>,
}
impl Future for BlockFuture<'_> {
type Output = Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
unsafe { riscv::register::sie::clear_sext(); }
// 这里对 status 的判断有很奇怪的 bug,先不对其进行判断
let resp: NonNull<BlockResp> = self.response.cast();
let status = unsafe { *&resp.as_ref().status };
match self.queue.can_pop() {
true => {
self.queue.pop_used()?;
unsafe { riscv::register::sie::set_sext(); }
Poll::Ready(Ok(()))
}
false => {
// 这里不进行唤醒,直接返回 pending
// 外部中断到来的时候在内核里面唤醒
unsafe { riscv::register::sie::set_sext(); }
Poll::Pending
}
}
}
}
unsafe impl Send for BlockFuture<'_> {}
unsafe impl Sync for BlockFuture<'_> {}
/// 虚拟块设备
/// 读写请求放在虚拟队列里面并会被设备处理
pub struct VirtIOBlock {
header: &'static mut VirtIOHeader,
/// 虚拟队列
queue: VirtQueue,
/// 容量
capacity: usize
}
impl VirtIOBlock {
/// 以异步方式创建虚拟块设备驱动
pub async fn async_new(header: &'static mut VirtIOHeader) -> Result<VirtIOBlock> {
if !header.verify() {
return Err(VirtIOError::HeaderVerifyError);
}
header.begin_init(|f| {
let features = BlockFeature::from_bits_truncate(f);
println!("[virtio] block device features: {:?}", features);
// 对这些 features 进行谈判
let supported_featuers = BlockFeature::empty();
(features & supported_featuers).bits()
});
// 读取配置空间
let config = unsafe {
&mut *(header.config_space() as *mut BlockConfig)
};
println!("[virtio] config: {:?}", config);
println!(
"[virtio] found a block device of size {} KB",
config.capacity.read() / 2
);
let queue = VirtQueue::async_new(
header, 0, VIRT_QUEUE_SIZE as u16
).await?;
header.finish_init();
Ok(VirtIOBlock {
header,
queue,
capacity: config.capacity.read() as usize
})
}
pub fn new(header: &'static mut VirtIOHeader) -> Result<Self> {
if !header.verify() {
return Err(VirtIOError::HeaderVerifyError);
}
header.begin_init(|f| {
let features = BlockFeature::from_bits_truncate(f);
println!("[virtio] block device features: {:?}", features);
// 对这些 features 进行谈判
let supported_featuers = BlockFeature::empty();
(features & supported_featuers).bits()
});
// 读取配置空间
let config = unsafe {
&mut *(header.config_space() as *mut BlockConfig)
};
println!("[virtio] config: {:?}", config);
println!(
"[virtio] found a block device of size {} KB",
config.capacity.read() / 2
);
let queue = VirtQueue::new(
header, 0, VIRT_QUEUE_SIZE as u16
)?;
header.finish_init();
Ok(VirtIOBlock {
header,
queue,
capacity: config.capacity.read() as usize
})
}
/// 通知设备 virtio 外部中断已经处理完成
pub fn ack_interrupt(&mut self) -> bool {
self.header.ack_interrupt()
}
/// 以异步方式读取一个块
pub fn async_read(&mut self, block_id: usize, buf: &mut [u8]) -> BlockFuture {
if buf.len() != BLOCK_SIZE {
panic!("[virtio] buffer size must equal to block size - 512!");
}
let req = BlockReq {
type_: BlockReqType::In,
reserved: 0,
sector: block_id as u64
};
let mut resp = BlockResp::default();
self.queue.add_buf(&[req.as_buf()], &[buf, resp.as_buf_mut()])
.expect("[virtio] virtual queue add buf error");
self.header.notify(0);
BlockFuture {
_req_type: 0,
queue: &mut self.queue,
response: NonNull::new(&resp as *const _ as *mut ()).unwrap()
}
}
/// 以异步方式写入一个块
pub fn async_write(&mut self, block_id: usize, buf: &[u8]) -> BlockFuture {
if buf.len() != BLOCK_SIZE {
panic!("[virtio] buffer size must equal to block size - 512!");
}
let req = BlockReq {
type_: BlockReqType::Out,
reserved: 0,
sector: block_id as u64,
};
let mut resp = BlockResp::default();
self.queue.add_buf(&[req.as_buf(), buf], &[resp.as_buf_mut()])
.expect("[virtio] virtual queue add buf error");
self.header.notify(0);
BlockFuture {
_req_type: 1,
queue: &mut self.queue,
response: NonNull::new(&resp as *const _ as *mut ()).unwrap()
}
}
pub fn read_block(&mut self, block_id: usize, buf: &mut [u8]) -> Result<()> {
if buf.len() != BLOCK_SIZE {
panic!("[virtio] buffer size must equal to block size - 512!");
}
let req = BlockReq {
type_: BlockReqType::In,
reserved: 0,
sector: block_id as u64,
};
let mut resp = BlockResp::default();
self.queue.add_buf(&[req.as_buf()], &[buf, resp.as_buf_mut()])
.expect("[virtio] virtual queue add buf error");
self.header.notify(0);
while !self.queue.can_pop() {}
self.queue.pop_used()?;
match resp.status {
BlockRespStatus::Ok => Ok(()),
_ => Err(VirtIOError::IOError)
}
}
pub fn write_block(&mut self, block_id: usize, buf: &[u8]) -> Result<()> {
if buf.len() != BLOCK_SIZE {
panic!("[virtio] buffer size must equal to block size - 512!");
}
let req = BlockReq {
type_: BlockReqType::Out,
reserved: 0,
sector: block_id as u64,
};
let mut resp = BlockResp::default();
self.queue.add_buf(&[req.as_buf(), buf], &[resp.as_buf_mut()])
.expect("[virtio] virtual queue add buf error");
self.header.notify(0);
while !self.queue.can_pop() {}
self.queue.pop_used()?;
match resp.status {
BlockRespStatus::Ok => Ok(()),
_ => Err(VirtIOError::IOError)
}
}
/// 处理 virtio 外部中断
pub unsafe fn handle_interrupt(&mut self) -> Result<InterruptRet> {
if !self.queue.can_pop() {
return Err(VirtIOError::IOError);
}
self.ack_interrupt();
let (index, _len) = self.queue.next_used()?;
let desc = self.queue.descriptor(index as usize);
let desc_va = virtio_phys_to_virt(desc.paddr.read() as usize);
let req = &*(desc_va as *const BlockReq);
let ret = match req.type_ {
BlockReqType::In => InterruptRet::Read(req.sector as usize),
BlockReqType::Out => InterruptRet::Write(req.sector as usize),
_ => InterruptRet::Other
};
Ok(ret)
}
}
bitflags! {
struct BlockFeature: u64 {
/// Device supports request barriers. (legacy)
const BARRIER = 1 << 0;
/// Maximum size of any single segment is in `size_max`.
const SIZE_MAX = 1 << 1;
/// Maximum number of segments in a request is in `seg_max`.
const SEG_MAX = 1 << 2;
/// Disk-style geometry specified in geometry.
const GEOMETRY = 1 << 4;
/// Device is read-only.
const RO = 1 << 5;
/// Block size of disk is in `blk_size`.
const BLK_SIZE = 1 << 6;
/// Device supports scsi packet commands. (legacy)
const SCSI = 1 << 7;
/// Cache flush command support.
const FLUSH = 1 << 9;
/// Device exports information on optimal I/O alignment.
const TOPOLOGY = 1 << 10;
/// Device can toggle its cache between writeback and writethrough modes.
const CONFIG_WCE = 1 << 11;
/// Device can support discard command, maximum discard sectors size in
/// `max_discard_sectors` and maximum discard segment number in
/// `max_discard_seg`.
const DISCARD = 1 << 13;
/// Device can support write zeroes command, maximum write zeroes sectors
/// size in `max_write_zeroes_sectors` and maximum write zeroes segment
/// number in `max_write_zeroes_seg`.
const WRITE_ZEROES = 1 << 14;
// device independent
const NOTIFY_ON_EMPTY = 1 << 24; // legacy
const ANY_LAYOUT = 1 << 27; // legacy
const RING_INDIRECT_DESC = 1 << 28;
const RING_EVENT_IDX = 1 << 29;
const UNUSED = 1 << 30; // legacy
const VERSION_1 = 1 << 32; // detect legacy
// the following since virtio v1.1
const ACCESS_PLATFORM = 1 << 33;
const RING_PACKED = 1 << 34;
const IN_ORDER = 1 << 35;
const ORDER_PLATFORM = 1 << 36;
const SR_IOV = 1 << 37;
const NOTIFICATION_DATA = 1 << 38;
}
}
/// 块设备配置
#[repr(C)]
#[derive(Debug)]
struct BlockConfig {
/// 扇区数目
capacity: Volatile<u64>,
size_max: Volatile<u32>,
seg_max: Volatile<u32>,
cylinders: Volatile<u16>,
heads: Volatile<u8>,
sectors: Volatile<u8>,
/// 扇区大小
sector_size: Volatile<u32>,
physical_block_exp: Volatile<u8>,
alignment_offset: Volatile<u8>,
min_io_size: Volatile<u16>,
opt_io_size: Volatile<u32>,
// ... ignored
}
/// 块设备请求
#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct BlockReq {
type_: BlockReqType,
reserved: u32,
sector: u64
}
/// 块设备回应
#[repr(C)]
#[derive(Debug)]
struct BlockResp {
status: BlockRespStatus,
}
/// 块设备请求类型
#[repr(C)]
#[derive(Debug, Clone, Copy)]
enum BlockReqType {
In = 0,
Out = 1,
Flush = 4,
Discard = 11,
WriteZeroes = 13,
}
/// 块设备回应状态
#[repr(u8)]
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
enum BlockRespStatus {
Ok = 0,
IoErr = 1,
Unsupported = 2,
NotReady = 3,
}
impl Default for BlockResp {
fn default() -> Self {
BlockResp {
status: BlockRespStatus::NotReady,
}
}
}
unsafe impl AsBuf for BlockReq {}
unsafe impl AsBuf for BlockResp {}
/// 中断响应返回值
pub enum InterruptRet {
/// 读请求完成的块
Read(usize),
/// 写请求完成的块
Write(usize),
/// 其他
Other
}
extern "C" {
/// 内核提供的物理地址到虚拟地址的转换函数
fn virtio_phys_to_virt(paddr: usize) -> usize;
} |
extern crate rustplot;
use rustplot::chart_builder;
use rustplot::chart_builder::Chart;
use rustplot::data_parser;
#[test]
fn xy_scatter_tests() {
let data_1 = data_parser::get_str_col(0, 0, 1, "./resources/box_plot_tests.csv");
let data_2 = data_parser::get_num_col(3, 0, 15, "./resources/box_plot_tests.csv");
let box_whisker = chart_builder::BoxWhiskerPlot::new(
String::from("Test Box Whisker Plot 1"),
data_1.clone(),
vec![data_2.clone()],
);
box_whisker.draw();
let data_3 = data_parser::get_str_col(0, 0, 2, "./resources/box_plot_tests.csv");
let data_4 = data_parser::get_num_col(2, 0, 10, "./resources/box_plot_tests.csv");
let box_whisker = chart_builder::BoxWhiskerPlot::new(
String::from("Test Box Whisker Plot 2"),
data_3.clone(),
vec![data_2.clone(), data_4.clone()],
);
box_whisker.draw();
let data_5 = data_parser::get_str_col(0, 0, 3, "./resources/box_plot_tests.csv");
let data_6 = data_parser::get_num_col(1, 0, 10, "./resources/box_plot_tests.csv");
let box_whisker = chart_builder::BoxWhiskerPlot::new(
String::from("Test Box Whisker Plot 3"),
data_5.clone(),
vec![data_2.clone(), data_6.clone(), data_4.clone()],
);
box_whisker.draw();
}
|
use crate::runtime::data::launches::structures::Launch;
use tui::widgets::{Paragraph, Borders, Block};
use tui::text::{Spans, Span};
use crate::utilities::countdown;
use chrono::Utc;
use webbrowser::BrowserOptions;
use tui::style::{Style, Color};
use crate::runtime::state::State;
pub fn render_list(state: &mut State, launch: Launch) -> Paragraph<'static> {
let mut updates: Vec<Spans> = vec![];
let mut update_index = 0;
// let mut updates_used_space = 0;
for update in launch.updates.unwrap_or(vec![]) {
if update_index <= 2 {
let timespan = countdown(update.created_on.unwrap_or(Utc::now().to_string()));
let untitle = update.comment.unwrap_or("Comment not found".to_string());
let timestr = if timespan.days > 0 {
if timespan.days > 1 || timespan.days == 0 {
format!("Updated {} days ago", timespan.days)
} else {
format!("Updated {} day ago", timespan.days)
}
} else if timespan.hours > 0 {
if (timespan.hours > 1 || timespan.hours == 0) && (timespan.minutes > 1 || timespan.minutes == 0) {
format!("Updated {} hours {} minutes ago", timespan.hours, timespan.minutes)
} else if timespan.hours > 1 && timespan.minutes == 0 {
format!("Updated {} hours {} minute ago", timespan.hours, timespan.minutes)
} else if timespan.hours == 1 && timespan.minutes > 1 {
format!("Updated {} hour {} minutes ago", timespan.hours, timespan.minutes)
} else {
format!("Updated {} hour {} minute ago", timespan.hours, timespan.minutes)
}
} else if timespan.minutes > 0 {
if (timespan.minutes > 1 || timespan.minutes == 0) && (timespan.seconds > 1 || timespan.seconds == 0) {
format!("Updated {} minutes {} seconds ago", timespan.minutes, timespan.seconds)
} else if timespan.minutes > 1 && timespan.seconds == 1 {
format!("Updated {} minutes {} second ago", timespan.minutes, timespan.seconds)
} else if timespan.minutes == 1 && timespan.seconds > 1 {
format!("Updated {} minute {} seconds ago", timespan.minutes, timespan.seconds)
} else {
format!("Updated {} minute {} second ago", timespan.minutes, timespan.seconds)
}
} else {
if timespan.seconds > 1 || timespan.seconds == 0 {
format!("Updated {} seconds ago", timespan.seconds)
} else {
format!("Updated {} second ago", timespan.seconds)
}
};
if state.selected_side == 0 && update_index == state.selected_update {
if state.open_selected && update.info_url.is_some() {
let _ = webbrowser::open_browser_with_options(
BrowserOptions {
url: update.info_url.unwrap(),
suppress_output: Some(true),
browser: Some(webbrowser::Browser::Default),
});
}
updates.push(Spans::from(vec![
Span::styled(format!(" {}", update.created_by.unwrap_or("Unknown author".to_string())), Style::default().fg(Color::Magenta)),
Span::raw(" - "),
Span::styled(untitle, Style::default().fg(Color::Cyan))
]));
// } else if side == 1 && update_index == selected_update {
// updates.push(Spans::from(vec![
// Span::styled(format!(" {}", update.created_by.unwrap_or("Unknown author".to_string())), Style::default().fg(Color::Magenta)),
// Span::raw(" - "),
// Span::styled(untitle, Style::default().fg(Color::Magenta))
// ]));
} else {
updates.push(Spans::from(vec![
Span::styled(format!(" {}", update.created_by.unwrap_or("Unknown author".to_string())), Style::default().fg(Color::Magenta)),
Span::raw(" - "),
Span::raw(untitle)
]));
}
update_index += 1;
updates.push(Spans::from(vec![
Span::styled(format!(" {}", timestr), Style::default().fg(Color::DarkGray))
]));
updates.push(Spans::from(vec![
Span::raw("")
]));
}
}
if updates.is_empty() {
Paragraph::new(" This launch does not have any updates yet.")
.block(Block::default().title(" Updates ")
.borders(Borders::ALL))
} else {
Paragraph::new(updates)
.block(Block::default().title(" Updates ")
.borders(Borders::ALL))
}
} |
//! The Oasis ABIs.
use std::collections::BTreeSet;
use oasis_contract_sdk_types as contract_sdk;
use oasis_runtime_sdk::{
context::Context,
modules::core::{self},
types::token,
};
use super::{gas, ExecutionContext, ExecutionResult, ABI};
use crate::{wasm::ContractError, Config, Error};
mod env;
mod memory;
mod storage;
#[cfg(test)]
mod test;
const EXPORT_INSTANTIATE: &str = "instantiate";
const EXPORT_CALL: &str = "call";
const EXPORT_HANDLE_REPLY: &str = "handle_reply";
const EXPORT_PRE_UPGRADE: &str = "pre_upgrade";
const EXPORT_POST_UPGRADE: &str = "post_upgrade";
const EXPORT_QUERY: &str = "query";
const GAS_SCALING_FACTOR: u64 = 1;
/// The Oasis V1 ABI.
pub struct OasisV1<Cfg: Config> {
_cfg: std::marker::PhantomData<Cfg>,
}
impl<Cfg: Config> OasisV1<Cfg> {
/// The set of required exports.
const REQUIRED_EXPORTS: &'static [&'static str] = &[
memory::EXPORT_ALLOCATE,
memory::EXPORT_DEALLOCATE,
EXPORT_INSTANTIATE,
EXPORT_CALL,
];
/// The set of reserved exports.
const RESERVED_EXPORTS: &'static [&'static str] =
&[gas::EXPORT_GAS_LIMIT, gas::EXPORT_GAS_LIMIT_EXHAUSTED];
/// Create a new instance of the ABI.
pub fn new() -> Self {
Self {
_cfg: std::marker::PhantomData,
}
}
fn raw_call_with_request_context<'ctx, C: Context>(
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
request: &[u8],
deposited_tokens: &[token::BaseUnits],
function_name: &str,
) -> Result<contract_sdk::ExecutionOk, Error> {
// Allocate memory for context and request, copy serialized data into the region.
let context_dst = Self::serialize_and_allocate(
instance,
contract_sdk::ExecutionContext {
instance_id: ctx.instance_info.id,
instance_address: ctx.instance_info.address().into(),
caller_address: ctx.caller_address.into(),
deposited_tokens: deposited_tokens.iter().map(|b| b.into()).collect(),
},
)
.map_err(|err| Error::ExecutionFailed(err.into()))?;
let request_dst = Self::allocate_and_copy(instance, request)
.map_err(|err| Error::ExecutionFailed(err.into()))?;
// Call the corresponding function in the smart contract.
let result = {
// The high-level function signature of the WASM export is as follows:
//
// fn(ctx: &contract_sdk::ExecutionContext, request: &[u8]) -> contract_sdk::ExecutionResult
//
let func = instance
.find_function::<((u32, u32), (u32, u32)), (u32, u32)>(function_name)
.map_err(|err| Error::ExecutionFailed(err.into()))?;
let result = func
.call_with_context(ctx, (context_dst.to_arg(), request_dst.to_arg()))
.map_err(|err| Error::ExecutionFailed(err.into()))?;
memory::Region::from_arg(result)
};
// Enforce maximum result size limit before attempting to deserialize it.
if result.length as u32 > ctx.params.max_result_size_bytes {
return Err(Error::ResultTooLarge(
result.length as u32,
ctx.params.max_result_size_bytes,
));
}
// Deserialize region into result structure.
let result: contract_sdk::ExecutionResult = instance
.runtime()
.try_with_memory(|memory| -> Result<_, Error> {
let data = result
.as_slice(&memory)
.map_err(|err| Error::ExecutionFailed(err.into()))?;
cbor::from_slice(data).map_err(|err| Error::ExecutionFailed(err.into()))
})
.unwrap()?;
match result {
contract_sdk::ExecutionResult::Ok(ok) => Ok(ok),
contract_sdk::ExecutionResult::Failed {
module,
code,
message,
} => Err(ContractError::new(ctx.instance_info.code_id, &module, code, &message).into()),
}
}
fn call_with_request_context<'ctx, C: Context>(
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
request: &[u8],
deposited_tokens: &[token::BaseUnits],
function_name: &str,
) -> ExecutionResult {
// Fetch initial gas counter value so we can determine how much gas was used.
let initial_gas = gas::get_remaining_gas(instance);
let inner = Self::raw_call_with_request_context(
ctx,
instance,
request,
deposited_tokens,
function_name,
)
.map_err(|err| {
// Check if call failed due to gas being exhausted and return a proper error.
let exhausted_gas = gas::get_exhausted_amount(instance);
if exhausted_gas != 0 {
// Compute how much gas was wanted.
let final_gas = gas::get_remaining_gas(instance);
let wanted_gas = initial_gas + exhausted_gas.saturating_sub(final_gas);
core::Error::OutOfGas(initial_gas, wanted_gas).into()
} else {
err
}
});
// Compute how much gas (in SDK units) was actually used.
let final_gas = gas::get_remaining_gas(instance);
let gas_used = initial_gas.saturating_sub(final_gas) / GAS_SCALING_FACTOR;
ExecutionResult { inner, gas_used }
}
}
impl<Cfg: Config, C: Context> ABI<C> for OasisV1<Cfg> {
fn validate(&self, module: &mut walrus::Module) -> Result<(), Error> {
// Verify that all required exports are there.
let exports: BTreeSet<&str> = module
.exports
.iter()
.map(|export| export.name.as_str())
.collect();
for required in Self::REQUIRED_EXPORTS {
if !exports.contains(required) {
return Err(Error::CodeMissingRequiredExport(required.to_string()));
}
}
for reserved in Self::RESERVED_EXPORTS {
if exports.contains(reserved) {
return Err(Error::CodeDeclaresReservedExport(reserved.to_string()));
}
}
// Verify that there is no start function defined.
if module.start.is_some() {
return Err(Error::CodeDeclaresStartFunction);
}
// Verify that there is at most one memory defined.
if module.memories.iter().count() > 1 {
return Err(Error::CodeDeclaresTooManyMemories);
}
// Add gas metering instrumentation.
gas::transform(module);
Ok(())
}
fn link(
&self,
instance: &mut wasm3::Instance<'_, '_, ExecutionContext<'_, C>>,
) -> Result<(), Error> {
// Storage imports.
Self::link_storage(instance)?;
// Environment imports.
Self::link_env(instance)?;
// Crypto imports.
Self::link_crypto(instance)?;
Ok(())
}
fn set_gas_limit(
&self,
instance: &mut wasm3::Instance<'_, '_, ExecutionContext<'_, C>>,
gas_limit: u64,
) -> Result<(), Error> {
// Derive gas limit from remaining transaction gas based on a scaling factor.
let gas_limit = gas_limit.saturating_mul(GAS_SCALING_FACTOR);
gas::set_gas_limit(instance, gas_limit)?;
Ok(())
}
fn instantiate<'ctx>(
&self,
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
request: &[u8],
deposited_tokens: &[token::BaseUnits],
) -> ExecutionResult {
Self::call_with_request_context(
ctx,
instance,
request,
deposited_tokens,
EXPORT_INSTANTIATE,
)
}
fn call<'ctx>(
&self,
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
request: &[u8],
deposited_tokens: &[token::BaseUnits],
) -> ExecutionResult {
Self::call_with_request_context(ctx, instance, request, deposited_tokens, EXPORT_CALL)
}
fn handle_reply<'ctx>(
&self,
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
reply: contract_sdk::message::Reply,
) -> ExecutionResult {
Self::call_with_request_context(
ctx,
instance,
&cbor::to_vec(reply),
&[],
EXPORT_HANDLE_REPLY,
)
}
fn pre_upgrade<'ctx>(
&self,
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
request: &[u8],
deposited_tokens: &[token::BaseUnits],
) -> ExecutionResult {
Self::call_with_request_context(
ctx,
instance,
request,
deposited_tokens,
EXPORT_PRE_UPGRADE,
)
}
fn post_upgrade<'ctx>(
&self,
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
request: &[u8],
deposited_tokens: &[token::BaseUnits],
) -> ExecutionResult {
Self::call_with_request_context(
ctx,
instance,
request,
deposited_tokens,
EXPORT_POST_UPGRADE,
)
}
fn query<'ctx>(
&self,
ctx: &mut ExecutionContext<'ctx, C>,
instance: &wasm3::Instance<'_, '_, ExecutionContext<'ctx, C>>,
request: &[u8],
) -> ExecutionResult {
Self::call_with_request_context(ctx, instance, request, &[], EXPORT_QUERY)
}
}
|
use std::iter::FromIterator;
pub struct SimpleLinkedList<T> {
head: Option<Box<Node<T>>>,
}
struct Node<T> {
data: T,
next: Option<Box<Node<T>>>,
}
impl<T> SimpleLinkedList<T> {
pub fn new() -> Self {
SimpleLinkedList{head: None}
}
pub fn len(&self) -> usize {
// TODO: store length as instance variable?
let mut head = &self.head;
let mut length = 0;
while let Some(current) = head {
length += 1;
head = ¤t.next;
}
length
}
pub fn push(&mut self, element: T) {
self.head = Some(Box::new(Node{
data: element,
next: self.head.take()
}));
}
pub fn append(&mut self, element: T) {
let mut head = &mut self.head;
while let Some(current) = head {
head = &mut current.next;
}
*head = Some(Box::new(Node{
data: element,
next: None
}));
}
pub fn pop(&mut self) -> Option<T> {
match self.head.take() {
Some(mut node) => {
self.head = node.next.take();
Some(node.data)
}
None => None,
}
}
pub fn peek(&self) -> Option<&T> {
match self.head {
Some(ref node) => {
Some(&node.data)
}
None => None,
}
}
}
impl<T: Clone> SimpleLinkedList<T> {
pub fn rev(self) -> SimpleLinkedList<T> {
let mut new_list: SimpleLinkedList<T> = SimpleLinkedList::new();
let mut head = &self.head;
while let Some(current) = head {
new_list.push(current.data.clone());
head = ¤t.next;
}
return new_list;
}
}
impl<T> FromIterator<T> for SimpleLinkedList<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut list: SimpleLinkedList<T> = SimpleLinkedList::new();
for item in iter {
list.push(item);
}
list
}
}
// In general, it would be preferable to implement IntoIterator for SimpleLinkedList<T>
// instead of implementing an explicit conversion to a vector. This is because, together,
// FromIterator and IntoIterator enable conversion between arbitrary collections.
// Given that implementation, converting to a vector is trivial:
//
// let vec: Vec<_> = simple_linked_list.into_iter().collect();
//
// The reason this exercise's API includes an explicit conversion to Vec<T> instead
// of IntoIterator is that implementing that interface is fairly complicated, and
// demands more of the student than we expect at this point in the track.
impl<T: Clone> Into<Vec<T>> for SimpleLinkedList<T> {
fn into(self) -> Vec<T> {
let mut result = vec![];
let mut head = &self.head;
while let Some(current) = head {
head = ¤t.next;
result.push(current.data.clone());
}
result.reverse();
result
}
}
|
// Copyright 2020-2021, The Tremor Team
//
// 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.
#![cfg(not(tarpaulin_include))]
use crate::source::prelude::*;
//NOTE: This is required for StreamHandlers
use std::time::Duration;
use tremor_common::time::nanotime;
#[derive(Deserialize, Debug, Clone)]
pub struct Config {
/// Interval in milliseconds
pub interval: u64,
}
impl ConfigImpl for Config {}
#[derive(Clone, Debug)]
pub struct Metronome {
pub config: Config,
origin_uri: EventOriginUri,
duration: Duration,
onramp_id: TremorUrl,
}
impl onramp::Impl for Metronome {
fn from_config(id: &TremorUrl, config: &Option<YamlValue>) -> Result<Box<dyn Onramp>> {
if let Some(config) = config {
let config: Config = Config::new(config)?;
let origin_uri = EventOriginUri {
uid: 0,
scheme: "tremor-metronome".to_string(),
host: hostname(),
port: None,
path: vec![config.interval.to_string()],
};
let duration = Duration::from_millis(config.interval);
Ok(Box::new(Self {
config,
origin_uri,
duration,
onramp_id: id.clone(),
}))
} else {
Err("Missing config for metronome onramp".into())
}
}
}
#[async_trait::async_trait()]
impl Source for Metronome {
fn id(&self) -> &TremorUrl {
&self.onramp_id
}
async fn pull_event(&mut self, id: u64) -> Result<SourceReply> {
task::sleep(self.duration).await;
let data = literal!({
"onramp": "metronome",
"ingest_ns": nanotime(),
"id": id
});
Ok(SourceReply::Structured {
origin_uri: self.origin_uri.clone(),
data: data.into(),
})
}
async fn init(&mut self) -> Result<SourceState> {
Ok(SourceState::Connected)
}
}
#[async_trait::async_trait]
impl Onramp for Metronome {
async fn start(&mut self, config: OnrampConfig<'_>) -> Result<onramp::Addr> {
SourceManager::start(self.clone(), config).await
}
fn default_codec(&self) -> &str {
"json"
}
}
|
#![cfg_attr(feature = "clippy", feature(plugin))] // Use clippy if it's available
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![cfg_attr(feature = "clippy", deny(clippy))] // And make every warning fatal.
#[macro_use]
extern crate lazy_static;
mod ascii;
mod unicode;
pub mod display;
pub mod human_names;
|
use crate::{
markdown::Markdown,
model::{Article, ArticleSearchIndex, DisambiguationSearchIndex, SearchIndex, Section},
};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, convert::TryFrom, fs, fs::File, io::Read};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Disambiguation {
pub name: String,
pub articles: Vec<Article>,
}
impl TryFrom<Vec<Article>> for Disambiguation {
type Error = ();
fn try_from(articles: Vec<Article>) -> Result<Self, Self::Error> {
if articles.len() <= 1 {
Err(())
} else {
let name = articles[0].name.clone();
for article in &articles {
if article.name != name {
return Err(());
}
}
Ok(Self { name, articles })
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct LanguageSite {
pub language: String,
pub sections: HashMap<String, Section>,
pub disambiguation: Vec<Disambiguation>,
pub top_level_articles: Vec<Markdown>,
pub translation: toml::Value,
}
impl LanguageSite {
fn new(
language: String,
sections_vec: Vec<Section>,
disambiguation: Vec<Vec<Article>>,
top_level_articles: Vec<Markdown>,
translation: toml::Value,
) -> Self {
let mut sections = HashMap::new();
for section in sections_vec {
sections.insert(section.name.clone(), section);
}
Self {
language,
sections,
disambiguation: disambiguation
.into_iter()
.map(|x| Disambiguation::try_from(x).unwrap())
.collect(),
top_level_articles,
translation,
}
}
fn collect_name_articles_map(
sections: impl Iterator<Item = Section>,
) -> HashMap<String, Vec<Article>> {
let articles: Vec<_> = sections
.map(|section| section.articles.into_iter())
.flatten()
.collect();
let mut result = HashMap::new();
for article in articles {
result
.entry(article.name.clone())
.or_insert_with(Vec::new)
.push(article.clone())
}
result
}
fn collect_disambiguation(sections: &[Section]) -> Vec<Vec<Article>> {
Self::collect_name_articles_map(sections.iter().cloned())
.iter()
.filter(|(_, articles)| articles.len() > 1)
.map(|(_name, article)| article.clone())
.collect()
}
pub fn collect_search_indexes(&self) -> Vec<SearchIndex> {
let (disambiguation_pages, simple_pages): (Vec<_>, Vec<_>) =
Self::collect_name_articles_map(self.sections.values().cloned())
.values()
.cloned()
.partition(|articles| articles.len() > 1);
let simple_pages = simple_pages
.into_iter()
.filter_map(|it| it.first().cloned());
disambiguation_pages
.into_iter()
.map(|it| it.into())
.map(|it: DisambiguationSearchIndex| it.into())
.chain(
simple_pages
.map(|it| it.into())
.map(|it: ArticleSearchIndex| it.into()),
)
.collect()
}
pub(crate) fn load(dir: fs::DirEntry) -> Self {
let sections_vec: Vec<_> = fs::read_dir(dir.path())
.unwrap()
.filter_map(Result::ok)
.filter(|it| it.metadata().unwrap().is_dir())
.map(Section::load)
.collect();
let raw_files: Vec<_> = fs::read_dir(dir.path())
.unwrap()
.filter_map(Result::ok)
.filter_map(|d| {
d.path().to_str().and_then(|f| {
if f.ends_with(".md") {
Some(d.path())
} else {
None
}
})
})
.map(Markdown::load_from_path)
.filter_map(Result::ok)
.collect();
let disambiguation = Self::collect_disambiguation(§ions_vec);
let mut translation_file = File::open(dir.path().join("translation.toml")).unwrap();
let mut translation_content = String::new();
translation_file
.read_to_string(&mut translation_content)
.unwrap();
let translation: toml::Value = toml::from_str(&translation_content).unwrap();
Self::new(
dir.file_name().into_string().unwrap(),
sections_vec,
disambiguation,
raw_files,
translation,
)
}
pub fn article_count(&self) -> usize {
self.sections.iter().map(|(_, it)| it.articles.len()).sum()
}
}
|
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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 euclid::rect::TypedRect;
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use euclid::point::TypedPoint2D;
use geometry::{DevicePixel, LayerPixel};
use layers::{BufferRequest, Layer, LayerBuffer};
use std::rc::Rc;
pub struct Scene<T> {
pub root: Option<Rc<Layer<T>>>,
pub viewport: TypedRect<f32, DevicePixel>,
/// The scene scale, to allow for zooming and high-resolution painting.
pub scale: ScaleFactor<f32, LayerPixel, DevicePixel>,
}
impl<T> Scene<T> {
pub fn new(viewport: TypedRect<f32, DevicePixel>) -> Scene<T> {
Scene {
root: None,
viewport: viewport,
scale: ScaleFactor::new(1.0),
}
}
pub fn get_buffer_requests_for_layer(&mut self,
layer: Rc<Layer<T>>,
dirty_rect: TypedRect<f32, LayerPixel>,
viewport_rect: TypedRect<f32, LayerPixel>,
layers_and_requests: &mut Vec<(Rc<Layer<T>>,
Vec<BufferRequest>)>,
unused_buffers: &mut Vec<Box<LayerBuffer>>) {
// Get buffers for this layer, in global (screen) coordinates.
let requests = layer.get_buffer_requests(dirty_rect, viewport_rect, self.scale);
if !requests.is_empty() {
layers_and_requests.push((layer.clone(), requests));
}
unused_buffers.extend(layer.collect_unused_buffers().into_iter());
// If this layer masks its children, we don't need to ask for tiles outside the
// boundaries of this layer.
let child_dirty_rect = if !*layer.masks_to_bounds.borrow() {
dirty_rect
} else {
match layer.transform_state.borrow().screen_rect {
Some(ref screen_rect) => {
match dirty_rect.to_untyped().intersection(&screen_rect.rect) {
Some(ref child_dirty_rect) => TypedRect::from_untyped(child_dirty_rect),
None => return, // The layer is entirely outside the dirty rect.
}
},
None => return, // The layer is entirely clipped.
}
};
for kid in layer.children().iter() {
self.get_buffer_requests_for_layer(kid.clone(),
child_dirty_rect,
viewport_rect,
layers_and_requests,
unused_buffers);
}
}
pub fn get_buffer_requests(&mut self,
requests: &mut Vec<(Rc<Layer<T>>, Vec<BufferRequest>)>,
unused_buffers: &mut Vec<Box<LayerBuffer>>) {
let root_layer = match self.root {
Some(ref root_layer) => root_layer.clone(),
None => return,
};
self.get_buffer_requests_for_layer(root_layer.clone(),
*root_layer.bounds.borrow(),
*root_layer.bounds.borrow(),
requests,
unused_buffers);
}
pub fn mark_layer_contents_as_changed_recursively_for_layer(&self, layer: Rc<Layer<T>>) {
layer.contents_changed();
for kid in layer.children().iter() {
self.mark_layer_contents_as_changed_recursively_for_layer(kid.clone());
}
}
pub fn mark_layer_contents_as_changed_recursively(&self) {
let root_layer = match self.root {
Some(ref root_layer) => root_layer.clone(),
None => return,
};
self.mark_layer_contents_as_changed_recursively_for_layer(root_layer);
}
pub fn set_root_layer_size(&self, new_size: TypedSize2D<f32, DevicePixel>) {
if let Some(ref root_layer) = self.root {
*root_layer.bounds.borrow_mut() = TypedRect::new(TypedPoint2D::zero(),
new_size / self.scale);
}
}
/// Calculate the amount of memory used by all the layers in the
/// scene graph. The memory may be allocated on the heap or in GPU memory.
pub fn get_memory_usage(&self) -> usize {
match self.root {
Some(ref root_layer) => root_layer.get_memory_usage(),
None => 0,
}
}
}
|
use std::fs::File;
use std::io::Read;
fn main() {
let mut in_dat_fh = File::open("./data/input.txt").unwrap();
let mut in_dat = String::new();
in_dat_fh.read_to_string(&mut in_dat).unwrap();
}
#[cfg(test)]
mod tests {}
|
use proconio::input;
fn main() {
input! {
p: char,
q: char,
};
let (p, q) = if p < q {
(p, q)
} else {
(q, p)
};
let index = |ch: char| {
ch as usize - 'A' as usize
};
let mut x = [0, 3, 1, 4, 1, 5, 9];
for i in 1..x.len() {
x[i] += x[i - 1];
}
let ans = x[index(q)] - x[index(p)];
println!("{}", ans);
}
|
use std::sync::Arc;
use std::thread::ThreadId;
use firefly_codegen::meta::CompiledModule;
use firefly_syntax_base::ApplicationMetadata;
use crate::compiler::queries;
use crate::diagnostics::ErrorReported;
use crate::interner::*;
use crate::parser::Parser;
#[salsa::query_group(CompilerStorage)]
pub trait Compiler: Parser {
#[salsa::invoke(queries::compile)]
fn compile(
&self,
thread_id: ThreadId,
input: InternedInput,
app: Arc<ApplicationMetadata>,
) -> Result<Option<CompiledModule>, ErrorReported>;
}
|
// Copyright 2018 Mattias Cibien
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 clap::{Arg, App};
fn main() {
let matches = App::new("Dice Roller")
.version("1.0")
.author("Mattias Cibien <mattias@mattiascibien.net>")
.about("Rolls dice using Standard Dice Notation")
.arg(Arg::with_name("notation")
.required(true)
.index(1)
.takes_value(true))
.get_matches();
let notation = matches.value_of("notation").unwrap();
let result = dicenotation::roll_dice::<i32>(notation).unwrap();
println!("Rolling: {}", notation);
println!("\t-> {}", result);
} |
use crate::{
camera::{ProjectionExt, ScaledOrthographicProjection},
controller::Player,
input::CursorState,
physics::PhysicsBundle,
plugins::{config::DebugConfig, timed::Timed},
};
use game_camera::CameraPlugin;
use game_controller::ControllerSystem;
use game_core::{modes::ModeExt, GameStage, GlobalMode, ModeEvent};
use game_input::InputBindings;
use game_lib::{
bevy::{
diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin},
ecs as bevy_ecs,
prelude::*,
render::camera::Camera,
},
tracing::{self, instrument},
};
use game_physics::{PhysicsPlugin, Velocity};
use game_tiles::{EntityWorldPosition, EntityWorldRect, RegionWorldPosition};
use std::{fmt::Write, time::Duration, writeln};
struct DebugText;
#[derive(Clone, Debug)]
struct Styles {
normal: TextStyle,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, SystemLabel)]
pub struct DebugPlugin;
impl DebugPlugin {
#[instrument(skip(commands, asset_server))]
fn setup_debug_text(mut commands: Commands, asset_server: Res<AssetServer>) {
let fonts = Styles {
normal: TextStyle {
font: asset_server.load("fonts/selawik/selawk.ttf"),
font_size: 18.0,
color: Color::WHITE,
},
};
commands
.spawn_bundle(TextBundle {
style: Style {
align_self: AlignSelf::FlexEnd,
position: Rect {
top: Val::Px(0.0),
left: Val::Px(0.0),
..Default::default()
},
..Default::default()
},
text: Text::default(),
..Default::default()
})
.insert(DebugText);
commands.insert_resource(fonts);
}
#[instrument(skip(
diagnostics,
cursor_state,
windows,
input_config,
styles,
camera_query,
player_query,
text_query,
visible_regions
))]
fn update_debug_text(
diagnostics: Res<Diagnostics>,
cursor_state: Res<CursorState>,
windows: Res<Windows>,
input_config: Res<InputBindings>,
styles: Res<Styles>,
camera_query: Query<(&ScaledOrthographicProjection, &Camera, &Transform)>,
player_query: Query<&Velocity, With<Player>>,
mut text_query: Query<&mut Text, With<DebugText>>,
visible_regions: Query<&RegionWorldPosition>,
) {
let mut new_text = String::with_capacity(1000);
// FPS
if let Some(fps) = diagnostics.get(FrameTimeDiagnosticsPlugin::FPS) {
if let (Some(average), Some(duration)) = (fps.average(), fps.duration()) {
writeln!(new_text, "FPS: {:.0} ({}ms)", average, duration.as_millis()).unwrap();
} else {
writeln!(new_text, "FPS: ???").unwrap();
}
}
// Cursor info
writeln!(
new_text,
"Cursor screen position: {}",
cursor_state.screen_position
)
.unwrap();
writeln!(
new_text,
"Cursor world position: {}",
cursor_state.world_position
)
.unwrap();
// Camera info
for (projection, camera, transform) in camera_query.iter() {
if let Some(window) = windows.get(camera.window) {
let screen_size = Vec2::new(window.width(), window.height());
let screen_top_left = Vec2::new(0.0, screen_size.y);
let screen_bottom_right = Vec2::new(screen_size.x, 0.0);
let world_top_left: Vec2 = projection
.screen_to_world(transform, screen_top_left, screen_size)
.0
.into();
let world_bottom_right: Vec2 = projection
.screen_to_world(transform, screen_bottom_right, screen_size)
.0
.into();
writeln!(
new_text,
"Camera {:?} world position: left: {}, right: {}, top: {}, bottom: {}",
camera.name.as_ref().unwrap_or(&"unnamed".into()),
world_top_left.x,
world_bottom_right.x,
world_top_left.y,
world_bottom_right.y
)
.unwrap();
}
}
writeln!(
new_text,
"Rendered regions: {}",
visible_regions.iter().count()
)
.unwrap();
// Player info
for velocity in player_query.iter() {
writeln!(new_text, "Player velocity: {}", velocity.0).unwrap();
}
// Controls
writeln!(new_text, "Controls:").unwrap();
for (input, action) in input_config.keyboard.iter() {
writeln!(new_text, "[{:?}]: {:?}", input, action).unwrap();
}
for (input, action) in input_config.mouse.iter() {
writeln!(new_text, "[{:?}]: {:?}", input, action).unwrap();
}
// Update text
let new_text = vec![TextSection {
value: new_text,
style: styles.normal.clone(),
}];
for mut text in text_query.iter_mut() {
text.sections.clone_from(&new_text);
}
}
#[instrument(skip(config, input))]
fn debug_input(mut config: ResMut<DebugConfig>, input: Res<Input<KeyCode>>) {
if input.just_released(KeyCode::F1) {
config.enable_teleporting = !config.enable_teleporting;
}
}
#[instrument(skip(config, input, cursor_state, player_query))]
fn teleport_on_click(
config: Res<DebugConfig>,
input: Res<Input<MouseButton>>,
cursor_state: Res<CursorState>,
mut player_query: Query<(&mut EntityWorldRect, &mut Velocity), With<Player>>,
) {
if config.enable_teleporting && input.pressed(MouseButton::Left) {
for (mut bounds, mut velocity) in player_query.iter_mut() {
*bounds = EntityWorldRect::from_center(
cursor_state.world_position.into(),
bounds.size() / 2.0,
);
velocity.0 = EntityWorldPosition::ZERO;
}
}
}
#[instrument(skip(commands, materials, input, cursor_state))]
fn spawn_on_click(
mut commands: Commands,
mut materials: ResMut<Assets<ColorMaterial>>,
input: Res<Input<MouseButton>>,
cursor_state: Res<CursorState>,
) {
if input.pressed(MouseButton::Right) {
let size = Vec2::new(0.1, 0.1);
commands
.spawn_bundle(SpriteBundle {
sprite: Sprite {
size,
..Default::default()
},
transform: Transform::from_translation(cursor_state.world_position.extend(0.0)),
material: materials.add(ColorMaterial::color(Color::WHITE)),
..Default::default()
})
.insert_bundle(PhysicsBundle {
bounds: EntityWorldRect::from_center(
cursor_state.world_position.into(),
(size / 2.0).into(),
),
..Default::default()
})
.insert(Timed::new(Duration::from_secs_f32(3.0)));
}
}
}
impl Plugin for DebugPlugin {
fn build(&self, app: &mut AppBuilder) {
app.add_system_set_to_stage(
GameStage::GameUpdate,
SystemSet::new()
.label(DebugPlugin)
.label(DebugSystem::SetupText)
.with_run_criteria(GlobalMode::InGame.on(ModeEvent::Enter))
.with_system(Self::setup_debug_text.system()),
)
.add_system_set_to_stage(
GameStage::GameUpdate,
SystemSet::new()
.label(DebugPlugin)
.label(DebugSystem::ProcessInput)
.with_run_criteria(GlobalMode::InGame.on(ModeEvent::Active))
.with_system(Self::debug_input.system()),
)
.add_system_set_to_stage(
GameStage::GameUpdate,
SystemSet::new()
.label(DebugPlugin)
.label(DebugSystem::HandleInput)
.before(PhysicsPlugin)
.after(ControllerSystem::HandleControls)
.after(DebugSystem::ProcessInput)
.with_run_criteria(GlobalMode::InGame.on(ModeEvent::Active))
.with_system(Self::teleport_on_click.system())
.with_system(Self::spawn_on_click.system()),
)
.add_system_set_to_stage(
GameStage::GameUpdate,
SystemSet::new()
.label(DebugPlugin)
.label(DebugSystem::ShowDebugInfo)
.after(PhysicsPlugin)
.after(DebugSystem::HandleInput)
.after(DebugSystem::SetupText)
.after(ControllerSystem::UpdateCamera)
.after(CameraPlugin)
.with_run_criteria(GlobalMode::InGame.on(ModeEvent::Active))
// TODO: this is slow af
// .with_system(Self::update_debug_text.system()),
);
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, SystemLabel)]
pub enum DebugSystem {
SetupText,
ProcessInput,
HandleInput,
ShowDebugInfo,
}
|
use super::*;
// Any mathematical expression
#[derive(Clone)]
pub enum Expression {
Constant(Constant),
Variable(Variable),
TermSum(TermSum),
Term(Term),
BasicTerm(BasicTerm),
}
impl Expression {
/// Converts to smallest type possible
/// Where TermSum > Term > BasicTerm > [Variable, Constant, Function]
pub fn simplify_type (&self) -> Expression {
// TODO implement
match *self {
Expression::TermSum(ref t) => {
// A TermSum with 0 terms is simply 0
if t.terms.len() == 0 {
return Expression::Constant(Constant::Int(0));
}
// A TermSum with 1 term is simply that term
else if t.terms.len() == 1 {
let term = t.terms.first();
if let Some(term) = term {
// TODO: Avoid clone here
return Expression::Term(term.clone()).simplify_type();
}
}
}
_ => {}
}
self.clone()
}
}
impl From<Constant> for Expression {
fn from(c: Constant) -> Expression {
Expression::Constant(c)
}
}
impl From<Variable> for Expression {
fn from(v: Variable) -> Expression {
Expression::Variable(v)
}
}
impl From<TermSum> for Expression {
fn from(t: TermSum) -> Expression {
Expression::TermSum(t)
}
}
impl From<Term> for Expression {
fn from(t: Term) -> Expression {
Expression::Term(t)
}
}
impl From<BasicTerm> for Expression {
fn from(b: BasicTerm) -> Expression {
Expression::BasicTerm(b)
}
}
impl Evaluate for Expression {
fn evaluate_f64(&self, a:&Vec<Assignment>) -> Result<f64,String> {
match self.clone() {
Expression::Variable(v) => {return v.evaluate_f64(a);},
Expression::Constant(c) => {return c.evaluate_f64(a);},
Expression::BasicTerm(b) => {return b.evaluate_f64(a);},
Expression::TermSum(t) => {return t.evaluate_f64(a);},
Expression::Term(t) => {return t.evaluate_f64(a);},
}
}
}
impl fmt::Display for Expression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Expression::Constant(ref c) => c.fmt(f),
Expression::Variable(ref v) => v.fmt(f),
Expression::BasicTerm(ref b) => b.fmt(f),
Expression::TermSum(ref t) => t.fmt(f),
Expression::Term(ref t) => t.fmt(f),
}
}
} |
mod entity;
mod space;
use crate::entity::Entity;
use crate::space::Vector;
fn main() {
let mut rng = rand::thread_rng();
let e1 = Entity::random(&mut rng);
println!("e1 direction: {:?}", e1.direction);
let e2 = Entity::random(&mut rng);
println!("e2 direction: {:?}", e2.direction);
let avg = Vector::average(vec![e1.direction.clone(), e2.direction.clone()]);
println!("Average: {:?}", avg);
let mut e3 = Entity::random(&mut rng);
println!("Before flock: {:?}", e3);
let flock = vec![e1, e2, e3];
// e3.flock(&flock);
println!("After flock: {:?}", e3);
let a: u8 = 0;
let b = (a as i8 - 1) as u8;
println!("{}", b);
}
|
pub const WHITE: Side = 0u8;
pub const BLACK: Side = 1u8;
pub type Side = u8;
|
// 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.
/// Returns the intended databend semver for Sentry as an `Option<Cow<'static, str>>`.
///
/// This can be used with `sentry::ClientOptions` to set the databend semver.
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate common_tracing;
/// # fn main() {
/// let _sentry = sentry::init(sentry::ClientOptions {
/// release: common_tracing::databend_semver!(),
/// ..Default::default()
/// });
/// # }
/// ```
#[macro_export]
macro_rules! databend_semver {
() => {{
use std::sync::Once;
static mut INIT: Once = Once::new();
static mut RELEASE: Option<String> = None;
unsafe {
INIT.call_once(|| {
RELEASE = option_env!("CARGO_PKG_NAME").and_then(|name| {
option_env!("DATABEND_GIT_SEMVER")
.map(|version| format!("{}@{}", name, version))
});
});
RELEASE.as_ref().map(|x| {
let release: &'static str = ::std::mem::transmute(x.as_str());
::std::borrow::Cow::Borrowed(release)
})
}
}};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.