text stringlengths 8 4.13M |
|---|
fn main() {
let s1 = String::from("Hello");
let s2 = s1.clone();
//takes_ownership(s1);
//let x = 5;
//makes_copy(x);
//println!("{}", x);
//let len = calculate_length(&s1);
//println!("{}", len)
let mut s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{}, {}", r1, r2);
let r3 = &mut s;
println!("{}", r3);
}
fn takes_ownership(some_string: String) {
println!("{}", some_string);
}
fn makes_copy(some_integer: i32) {
println!("{}", some_integer);
}
fn gives_ownership() -> String {
let some_string = String::from("hello");
some_string
}
fn take_and_gives_back(a_string: String) -> String {
a_string
}
fn calculate_length(s: &String) -> usize {
let length = s.len();
length
}
|
#![feature(test)]
extern crate test;
extern crate raytracer;
use test::Bencher;
use raytracer::*;
#[bench]
fn bench_perlin(b: &mut Bencher) {
let v = Vec3::new(0.5, 0.6, 0.7);
b.iter(|| perlin_noise(&v))
}
|
use crate::Literal;
use std::mem::swap;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct CRef {
idx: u32,
len: u16,
}
impl CRef {
pub fn iter<'a>(&'a self, db: &'a Database) -> impl Iterator<Item = &Literal> + 'a {
self.as_slice(db).iter()
}
#[inline]
pub fn as_slice<'a>(&'a self, db: &'a Database) -> &'a [Literal] {
unsafe {
&db
.literals
.get_unchecked(self.idx as usize..(self.idx + self.len as u32) as usize)
}
}
pub const fn len(&self) -> usize { self.len as usize }
pub const fn is_empty(&self) -> bool { self.len == 0 }
}
#[derive(Debug, PartialEq)]
pub struct Database {
/// All clauses in this database
pub literals: Vec<Literal>,
swap_space: Vec<Literal>,
pub max_var: u32,
pub num_clauses: u32,
}
impl Database {
pub const fn new() -> Self {
Database {
literals: vec![],
swap_space: vec![],
max_var: 0,
num_clauses: 0,
}
}
pub fn clear(&mut self) {
self.literals.clear();
self.swap_space.clear();
self.max_var = 0;
self.num_clauses = 0;
}
/*
#[must_use]
pub fn add_clause(&mut self, ls: impl Iterator<Item = Literal>) -> CRef {
self.num_clauses += 1;
let idx = self.literals.len() as u32;
self.literals.extend(ls);
CRef {
idx,
len: (self.literals.len() as u32 - idx) as u16,
}
}
*/
#[must_use]
pub fn add_clause_from_slice(&mut self, ls: &[Literal]) -> CRef {
self.num_clauses += 1;
let idx = self.literals.len() as u32;
self.literals.extend_from_slice(ls);
CRef {
idx,
len: ls.len() as u16,
}
}
/// Removes satisfied clauses at level 0.
pub fn compact<'a>(
&'a mut self,
assns: &'a [Option<bool>],
clauses: impl Iterator<Item = CRef> + 'a,
) -> impl Iterator<Item = (CRef, Literal, Literal)> + 'a {
swap(&mut self.literals, &mut self.swap_space);
self.num_clauses = 1;
self.literals.clear();
clauses.filter_map(move |c| {
if !self.swap_space[c.idx as usize].is_valid() {
return None;
}
let lits = unsafe {
&self
.swap_space
.get_unchecked(c.idx as usize..c.idx as usize + c.len as usize)
};
if lits.iter().any(|l| l.assn(assns) == Some(true)) {
return None;
}
let lits = lits.iter().filter(|l| l.assn(assns) == None);
let idx = self.literals.len() as u32;
self.literals.extend(lits);
let len = (self.literals.len() as u32 - idx) as u16;
self.swap_space[c.idx as usize] = Literal::INVALID;
if len == 0 {
None
} else if len == 1 {
self.num_clauses += 1;
let cref = CRef { idx, len };
let mut lits = cref.iter(&self).copied();
let l_0 = lits.next().unwrap();
debug_assert!(l_0.is_valid());
Some((cref, l_0, Literal::INVALID))
} else {
self.num_clauses += 1;
let cref = CRef { idx, len };
let mut lits = cref.iter(&self).copied();
let l_0 = lits.next().unwrap();
let l_1 = lits.next().unwrap();
debug_assert!(l_0.is_valid());
debug_assert!(l_1.is_valid());
Some((cref, l_0, l_1))
}
})
}
}
|
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
use std::iter::Iterator;
use std::ops::{Add, AddAssign, Mul};
use std::str::FromStr;
use std::fmt::Debug;
/// The output is wrapped in a Result to allow matching on errors
/// Returns an Iterator to the Reader of the lines of the file.
pub fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
pub fn read_lines_as_vec<P>(filename: P) -> Vec<String>
where P: AsRef<Path>, {
let file = File::open(filename).expect("no such file");
let buf = io::BufReader::new(file);
buf.lines()
.map(|l| l.expect("Could not parse line"))
.collect()
}
/// Returns an Iterator to the lines of the file.
pub fn file_lines_iter<F>(file: F) -> impl Iterator<Item = String>
where F: AsRef<Path> {
let f = File::open(file).expect("No such file");
io::BufReader::new(f)
.lines()
.map(Result::unwrap)
}
/// Parse a line of csv separated Ts into a Iter<T>
pub fn csv_iter<T: FromStr>(line: &str) -> impl Iterator<Item = T> + '_
where <T as FromStr>::Err: Debug {
line.split(",").map(move |v| v.parse::<T>().expect(&line))
}
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Vec2 {
pub x: i32,
pub y: i32,
}
impl Add for Vec2 {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl AddAssign for Vec2 {
fn add_assign(&mut self, other: Self) {
*self = Self {
x: self.x + other.x,
y: self.y + other.y,
};
}
}
impl Mul<i32> for Vec2 {
type Output = Self;
fn mul(self, rhs: i32) -> Self::Output {
Self {
x: self.x * rhs,
y: self.y * rhs,
}
}
}
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Vec3 {
pub x: i32,
pub y: i32,
pub z: i32,
}
impl Add for Vec3 {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
}
}
}
impl AddAssign for Vec3 {
fn add_assign(&mut self, other: Self) {
*self = Self {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
};
}
}
impl Mul<i32> for Vec3 {
type Output = Self;
fn mul(self, rhs: i32) -> Self::Output {
Self {
x: self.x * rhs,
y: self.y * rhs,
z: self.z * rhs,
}
}
}
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Vec4 {
pub x: i32,
pub y: i32,
pub z: i32,
pub w: i32,
}
impl Add for Vec4 {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
w: self.w + other.w,
}
}
}
impl AddAssign for Vec4 {
fn add_assign(&mut self, other: Self) {
*self = Self {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
w: self.w + other.w,
};
}
}
impl Mul<i32> for Vec4 {
type Output = Self;
fn mul(self, rhs: i32) -> Self::Output {
Self {
x: self.x * rhs,
y: self.y * rhs,
z: self.z * rhs,
w: self.w * rhs,
}
}
}
#[macro_export]
macro_rules! multi_for {
([$x:ident in $x_range:expr, $y:ident in $y_range:expr] $($body:tt)*) => {
for $y in $y_range {
for $x in $x_range {
$($body)*
}
}
};
([$x:ident in $x_range:expr, $y:ident in $y_range:expr, $z:ident in $z_range:expr] $($body:tt)*) => {
for $z in $z_range {
for $y in $y_range {
for $x in $x_range {
$($body)*
}
}
}
};
([$x:ident in $x_range:expr, $y:ident in $y_range:expr, $z:ident in $z_range:expr, $w:ident=$w_range:expr] $($body:tt)*) => {
for $w in $w_range {
for $z in $z_range {
for $y in $y_range {
for $x in $x_range {
$($body)*
}
}
}
}
};
}
|
use crate::error::Error;
pub enum CloseReason {
Normal,
Abnormal(Error),
}
|
use libc;
/*
* raidautorun implementation for busybox
*
* Copyright (C) 2006 Bernhard Reutner-Fischer
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config RAIDAUTORUN
//config: bool "raidautorun (1.3 kb)"
//config: default y
//config: select PLATFORM_LINUX
//config: help
//config: raidautorun tells the kernel md driver to
//config: search and start RAID arrays.
//applet:IF_RAIDAUTORUN(APPLET_NOEXEC(raidautorun, raidautorun, BB_DIR_SBIN, SUID_DROP, raidautorun))
//kbuild:lib-$(CONFIG_RAIDAUTORUN) += raidautorun.o
//usage:#define raidautorun_trivial_usage
//usage: "DEVICE"
//usage:#define raidautorun_full_usage "\n\n"
//usage: "Tell the kernel to automatically search and start RAID arrays"
//usage:
//usage:#define raidautorun_example_usage
//usage: "$ raidautorun /dev/md0"
pub unsafe fn raidautorun_main(
mut _argc: libc::c_int,
mut argv: *mut *mut libc::c_char,
) -> libc::c_int {
crate::libbb::xfuncs_printf::bb_xioctl(
crate::libbb::xfuncs_printf::xopen(crate::libbb::single_argv::single_argv(argv), 0),
0u32 << 0 + 8 + 8 + 14
| (9 << 0 + 8) as libc::c_uint
| (0x14 << 0) as libc::c_uint
| (0 << 0 + 8 + 8) as libc::c_uint,
0 as *mut libc::c_void,
b"RAID_AUTORUN\x00" as *const u8 as *const libc::c_char,
);
return 0;
}
|
//! Handles all the FASTA/FASTQ parsing
use std::fs::File;
use std::io::{stdin, Cursor, Read};
use std::path::Path;
#[cfg(feature = "compression")]
use bzip2::read::BzDecoder;
#[cfg(feature = "compression")]
use flate2::read::MultiGzDecoder;
#[cfg(feature = "compression")]
use xz2::read::XzDecoder;
use crate::errors::ParseError;
pub use crate::parser::fasta::Reader as FastaReader;
pub use crate::parser::fastq::Reader as FastqReader;
mod record;
mod utils;
mod fasta;
mod fastq;
pub use crate::parser::utils::FastxReader;
// Magic bytes for each compression format
#[cfg(feature = "compression")]
const GZ_MAGIC: [u8; 2] = [0x1F, 0x8B];
#[cfg(feature = "compression")]
const BZ_MAGIC: [u8; 2] = [0x42, 0x5A];
#[cfg(feature = "compression")]
const XZ_MAGIC: [u8; 2] = [0xFD, 0x37];
fn get_fastx_reader<'a, R: 'a + io::Read + Send>(
reader: R,
first_byte: u8,
) -> Result<Box<dyn FastxReader + 'a>, ParseError> {
match first_byte {
b'>' => Ok(Box::new(FastaReader::new(reader))),
b'@' => Ok(Box::new(FastqReader::new(reader))),
_ => Err(ParseError::new_unknown_format(first_byte)),
}
}
/// The main entry point of needletail if you're reading from something that implements [`std::io::Read`].
/// This automatically detects whether the file is:
/// 1. compressed: [`gzip`][gzip], [`bz`][bz] and [`xz`][xz] are supported and will use the appropriate decoder
/// 2. FASTA or FASTQ: the right parser will be automatically instantiated
///
/// Option 1 is only available if the `compression` feature is enabled.
///
/// # Errors
///
/// If the object you're reading from has less than 2 bytes then a [`ParserError`](needletail::errors::ParserError) of the kind
/// [`ParseErrorKind::EmptyFile`](needletail::errors::ParseErrorKind::EmptyFile) is returned.
///
/// If the first byte in the object is unknown, then a `ParserError` of the kind
/// [`ParseErrorKind::UnknownFormat`](needletail::errors::ParseErrorKind::UnknownFormat) is returned.
///
/// # Examples
///
/// ```
/// use needletail::parse_fastx_reader;
///
/// let reader = ">read1\nACGT\nread2\nGGGG".as_bytes();
/// let mut fastx_reader = parse_fastx_reader(reader).expect("invalid reader");
/// let mut idx = 0;
/// let read_ids = [b"read1", b"read2"];
///
/// while let Some(r) = fastx_reader.next() {
/// let record = r.expect("invalid record");
/// assert_eq!(record.id(), read_ids[idx]);
/// idx += 1;
/// }
/// ```
///
/// [gzip]: https://www.gnu.org/software/gzip/
/// [bz]: https://sourceware.org/bzip2/
/// [xz]: https://tukaani.org/xz/format.html
///
pub fn parse_fastx_reader<'a, R: 'a + io::Read + Send>(
mut reader: R,
) -> Result<Box<dyn FastxReader + 'a>, ParseError> {
let mut first_two_bytes = [0; 2];
reader
.read_exact(&mut first_two_bytes)
.map_err(|_| ParseError::new_empty_file())?;
let first_two_cursor = Cursor::new(first_two_bytes);
let new_reader = first_two_cursor.chain(reader);
match first_two_bytes {
#[cfg(feature = "compression")]
GZ_MAGIC => {
let mut gz_reader = MultiGzDecoder::new(new_reader);
let mut first = [0; 1];
gz_reader.read_exact(&mut first)?;
let r = Cursor::new(first).chain(gz_reader);
get_fastx_reader(r, first[0])
}
#[cfg(feature = "compression")]
BZ_MAGIC => {
let mut bz_reader = BzDecoder::new(new_reader);
let mut first = [0; 1];
bz_reader.read_exact(&mut first)?;
let r = Cursor::new(first).chain(bz_reader);
get_fastx_reader(r, first[0])
}
#[cfg(feature = "compression")]
XZ_MAGIC => {
let mut xz_reader = XzDecoder::new(new_reader);
let mut first = [0; 1];
xz_reader.read_exact(&mut first)?;
let r = Cursor::new(first).chain(xz_reader);
get_fastx_reader(r, first[0])
}
_ => get_fastx_reader(new_reader, first_two_bytes[0]),
}
}
/// The main entry point of needletail if you're reading from stdin.
/// Shortcut to calling `parse_fastx_reader` with `stdin()`
pub fn parse_fastx_stdin() -> Result<Box<dyn FastxReader>, ParseError> {
let stdin = stdin();
parse_fastx_reader(stdin)
}
/// The main entry point of needletail if you're reading from a file.
/// Shortcut to calling `parse_fastx_reader` with a file
pub fn parse_fastx_file<P: AsRef<Path>>(path: P) -> Result<Box<dyn FastxReader>, ParseError> {
parse_fastx_reader(File::open(&path)?)
}
pub use record::{mask_header_tabs, mask_header_utf8, write_fasta, write_fastq, SequenceRecord};
use std::io;
pub use utils::{Format, LineEnding};
#[cfg(test)]
mod test {
use crate::errors::ParseErrorKind;
use crate::parse_fastx_reader;
#[test]
fn test_empty_file_raises_parser_error_of_same_kind() {
let reader = "".as_bytes();
let actual = parse_fastx_reader(reader);
assert!(actual.is_err());
let actual_err = actual.err().unwrap().kind;
let expected_err = ParseErrorKind::EmptyFile;
assert_eq!(actual_err, expected_err);
}
#[test]
fn test_only_one_byte_in_file_raises_empty_file_error() {
let reader = "@".as_bytes();
let actual = parse_fastx_reader(reader);
assert!(actual.is_err());
let actual_err = actual.err().unwrap().kind;
let expected_err = ParseErrorKind::EmptyFile;
assert_eq!(actual_err, expected_err);
}
}
|
/**
* Copyright © 2019
* Sami Shalayel <sami.shalayel@tutamail.com>,
* Carl Schwan <carl@carlschwan.eu>,
* Daniel Freiermuth <d_freiermu14@cs.uni-kl.de>
*
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See the LICENSE file for more details.
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See the LICENSE
* file for more details. **/
use crate::ray::Ray;
use crate::shader::Shader;
use crate::world::World;
use nalgebra::{Unit, Vector2, Vector3};
pub struct MirrorShader {
pub initial_step: f64,
}
impl Shader for MirrorShader {
fn get_appearance_for(
&self,
intersection_pos: Vector3<f64>,
ray_dir: Vector3<f64>,
surface_normal: Vector3<f64>,
world: &World,
_surface_pos: Vector2<f64>,
recursion_depth: f64,
) -> Vector3<f64> {
if recursion_depth < 1.0 {
return Vector3::new(0.0, 0.0, 0.0);
}
let unit_normal = surface_normal.normalize();
let othogonal_part = unit_normal.dot(&-ray_dir) * unit_normal;
let mirror_ray_dir = (2.0 * othogonal_part + ray_dir).normalize();
let mirror_ray = Ray {
start: intersection_pos + mirror_ray_dir * self.initial_step,
dir: Unit::new_normalize(mirror_ray_dir),
};
world.appearance(mirror_ray, recursion_depth - 1.0)
}
}
|
#![feature(test)]
extern crate test;
use test::Bencher;
extern crate graph_layout;
use graph_layout::layout::*;
use graph_layout::compression::*;
#[bench]
fn encode_decode_h(bencher: &mut Bencher) {
let tangler = Hilbert::new();
let mut index = 0;
bencher.iter(|| { index += 1; assert!(index == tangler.entangle(tangler.detangle(index))) });
}
#[bench]
fn encode_h(bencher: &mut Bencher) {
let tangler = Hilbert::new();
let mut index = 0;
bencher.iter(|| { index += 1; tangler.entangle((index, 7u32)) });
}
#[bench]
fn decode_h(bencher: &mut Bencher) {
let tangler = Hilbert::new();
let mut index = 0;
bencher.iter(|| { index += 1; tangler.detangle(index) });
}
#[bench]
fn encode_decode_z(bencher: &mut Bencher) {
let tangler = ZOrder::new();
let mut index = 0;
bencher.iter(|| { index += 1; assert!(index == tangler.entangle(tangler.detangle(index))) });
}
#[bench]
fn encode_z(bencher: &mut Bencher) {
let tangler = ZOrder::new();
let mut index = 0;
bencher.iter(|| { index += 1; tangler.entangle((index, 7u32)) });
}
#[bench]
fn decode_z(bencher: &mut Bencher) {
let tangler = ZOrder::new();
let mut index = 0;
bencher.iter(|| { index += 1; tangler.detangle(index) });
}
#[bench]
fn compress_e(bencher: &mut Bencher) {
let mut compressor = Compressor::with_capacity(1_000_000);
let mut index = 0u64;
bencher.iter(|| {
index += 1;
compressor.push(index)
})
}
#[bench]
fn compress_d(bencher: &mut Bencher) {
let compressed = Compressed::from(0..1_000_000);
let mut decompressor = compressed.decompress();
bencher.iter(|| {
decompressor.next()
});
}
|
use std::sync::Arc;
use sourcerenderer_core::graphics::{
Backend,
CommandBuffer,
Device,
Queue,
Swapchain,
SwapchainError, FenceRef,
};
use sourcerenderer_core::Platform;
use crate::input::Input;
use crate::renderer::render_path::{
FrameInfo,
RenderPath,
SceneInfo,
ZeroTextures,
};
use crate::renderer::renderer_assets::RendererAssets;
use crate::renderer::renderer_resources::RendererResources;
use crate::renderer::shader_manager::ShaderManager;
use crate::renderer::LateLatching;
mod geometry;
use self::geometry::GeometryPass;
pub struct WebRenderer<P: Platform> {
device: Arc<<P::GraphicsBackend as Backend>::Device>,
swapchain: Arc<<P::GraphicsBackend as Backend>::Swapchain>,
geometry: GeometryPass<P>,
resources: RendererResources<P::GraphicsBackend>,
}
impl<P: Platform> WebRenderer<P> {
pub fn new(
device: &Arc<<P::GraphicsBackend as Backend>::Device>,
swapchain: &Arc<<P::GraphicsBackend as Backend>::Swapchain>,
shader_manager: &mut ShaderManager<P>,
) -> Self {
let mut resources = RendererResources::<P::GraphicsBackend>::new(device);
let mut init_cmd_buffer = device.graphics_queue().create_command_buffer();
let geometry_pass = GeometryPass::<P>::new(
device,
swapchain,
&mut init_cmd_buffer,
&mut resources,
shader_manager,
);
let init_submission = init_cmd_buffer.finish();
device
.graphics_queue()
.submit(init_submission, &[], &[], false);
Self {
device: device.clone(),
swapchain: swapchain.clone(),
geometry: geometry_pass,
resources,
}
}
}
impl<P: Platform> RenderPath<P> for WebRenderer<P> {
fn is_gpu_driven(&self) -> bool {
false
}
fn write_occlusion_culling_results(&self, _frame: u64, bitset: &mut Vec<u32>) {
bitset.fill(!0u32);
}
fn on_swapchain_changed(
&mut self,
_swapchain: &Arc<<P::GraphicsBackend as Backend>::Swapchain>,
) {
}
fn render(
&mut self,
scene: &SceneInfo<P::GraphicsBackend>,
_zero_textures: &ZeroTextures<P::GraphicsBackend>,
late_latching: Option<&dyn LateLatching<P::GraphicsBackend>>,
input: &Input,
_frame_info: &FrameInfo,
shader_manager: &ShaderManager<P>,
assets: &RendererAssets<P>,
) -> Result<(), sourcerenderer_core::graphics::SwapchainError> {
let back_buffer_res = self.swapchain.prepare_back_buffer();
if back_buffer_res.is_none() {
return Err(SwapchainError::Other);
}
let back_buffer = back_buffer_res.unwrap();
let queue = self.device.graphics_queue();
let mut cmd_buffer = queue.create_command_buffer();
let view_ref = &scene.views[scene.active_view_index];
let late_latching_buffer = late_latching.unwrap().buffer();
self.geometry.execute(
&mut cmd_buffer,
scene.scene,
&view_ref,
&late_latching_buffer,
&self.resources,
back_buffer.texture_view,
shader_manager,
assets,
);
if let Some(late_latching) = late_latching {
let input_state = input.poll();
late_latching.before_submit(&input_state, &view_ref);
}
queue.submit(
cmd_buffer.finish(),
&[FenceRef::WSIFence(back_buffer.prepare_fence)],
&[FenceRef::WSIFence(back_buffer.present_fence)],
false,
);
queue.present(&self.swapchain, back_buffer.present_fence, false);
if let Some(late_latching) = late_latching {
late_latching.after_submit(&self.device);
}
Ok(())
}
fn set_ui_data(&mut self, data: crate::ui::UIDrawData<<P as Platform>::GraphicsBackend>) {
todo!()
}
}
|
use proconio::input;
use std::collections::HashSet;
fn main() {
input! {
n: usize,
x: i32,
y: i32,
a: [i32; n],
};
let mut dp_x = HashSet::new();
dp_x.insert(a[0]);
let mut dp_y = HashSet::new();
dp_y.insert(0);
for i in 1..n {
if i % 2 == 1 {
let mut new_dp_y = HashSet::new();
for y in dp_y {
new_dp_y.insert(y + a[i]);
new_dp_y.insert(y - a[i]);
}
dp_y = new_dp_y;
} else {
let mut new_dp_x = HashSet::new();
for x in dp_x {
new_dp_x.insert(x + a[i]);
new_dp_x.insert(x - a[i]);
}
dp_x = new_dp_x;
}
}
let ok = dp_x.contains(&x) && dp_y.contains(&y);
if ok {
println!("Yes");
} else {
println!("No");
}
}
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
/// Registrar for arenas.
pub trait ArenasRegistrar
{
/// Register an arena.
///
/// It is not permissible to register multiple arenas for the same type of `R`.
fn register_arena<A: Arena<R> + 'static, R: Reactor + 'static, T: Terminate>(&mut self, arena: A) -> CompressedTypeIdentifier;
}
|
mod models;
use models::{Stock, CreateStock, ShipStock, ArriveStock, StockEvent};
fn print_restore(events: Vec<&StockEvent>) {
println!(
"*** restore {}: {:?}",
events.len(),
Stock::restore(Stock::Nothing, events)
);
}
fn main() {
let id1 = "s1";
let r1 = Stock::handle(Stock::Nothing, &CreateStock(id1.to_string()));
println!("{:?}", r1);
if let Some((s1, e1)) = r1 {
print_restore(vec![&e1]);
let r2 = Stock::handle(s1.clone(), &ShipStock(id1.to_string(), 2));
println!("{:?}", r2);
let r2b = Stock::handle(s1.clone(), &ArriveStock(id1.to_string(), 5));
println!("{:?}", r2b);
if let Some((s2, e2)) = r2b {
print_restore(vec![&e1, &e2]);
let r3 = Stock::handle(s2.clone(), &ShipStock(id1.to_string(), 2));
println!("{:?}", r3);
if let Some((s3, e3)) = r3 {
print_restore(vec![&e1, &e2, &e3]);
let r4 = Stock::handle(s3.clone(), &ShipStock(id1.to_string(), 3));
println!("{:?}", r4);
if let Some((_, e4)) = r4 {
print_restore(vec![&e1, &e2, &e3, &e4]);
}
}
}
}
}
|
use crate::auth::AuthParam;
use crate::list_form::ListForm;
use serde::{Deserialize, Serialize};
use structopt::StructOpt;
#[derive(Debug, Serialize, Deserialize, StructOpt)]
#[structopt(about = "Occurrence related operations")]
#[serde(untagged)]
pub enum OccurrenceCmd {
#[serde(rename_all = "camelCase")]
#[structopt(about = "Get Occurrence by :id")]
Get {
#[structopt(long)]
id: String,
#[structopt(flatten)]
auth_param: AuthParam
},
#[serde(rename_all = "camelCase")]
#[structopt(about = "List all Occurrences")]
List {
#[structopt(flatten)]
form: ListForm,
#[structopt(flatten)]
auth_param: AuthParam
}
}
|
use std::io::{self, prelude::*};
use std::net::TcpStream;
use tui::Terminal;
use tui::backend::CrosstermBackend;
use tui::widgets::{Widget, Block, Borders, Paragraph, Wrap};
use tui::layout::{Layout, Constraint, Direction};
use tui::text::{Spans, Span};
fn main() -> std::io::Result<()> {
let stdout = io::stdout();
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
terminal.clear()?;
terminal.draw(|f| {
let chunks = Layout::default()
.direction(Direction::Vertical)
.margin(1)
.constraints(
[
Constraint::Percentage(10),
Constraint::Percentage(80),
Constraint::Percentage(10)
].as_ref()
)
.split(f.size());
let block = Block::default()
.title("Block")
.borders(Borders::ALL);
f.render_widget(block,chunks[0]);
let block = Block::default()
.title("Block 2")
.borders(Borders::ALL);
f.render_widget(block,chunks[1]);
let block = Block::default()
.title("Block 3")
.borders(Borders::ALL);
let text = vec![
Spans::from("This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text This is some test text "),
];
let paragraph = Paragraph::new(text).block(block).wrap(Wrap {trim: true});
f.render_widget(paragraph, chunks[2]);
//f.render_widget(block,chunks[2]);
})?;
let mut stream = TcpStream::connect("localhost:8080")?;
stream.write_all(b"Hello, World!")?;
let mut buf = [0; 10];
let _n = stream.read(&mut buf[..]);
let rx_val = String::from_utf8_lossy(&buf);
println!("Received the bytes: {:?}", rx_val);
Ok(())
}
|
pub mod use_case_diagram;
|
// Copyright (c) 2021 ESRLabs
//
// 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 anyhow::{Context, Result};
use colored::Colorize;
use itertools::Itertools;
use northstar::api::model::{
Container, ContainerData, MountResult, Notification, Repository, RepositoryId, Response,
};
use prettytable::{format, Attr, Cell, Row, Table};
use std::{collections::HashMap, io};
use tokio::time;
pub(crate) fn notification<W: io::Write>(mut w: W, notification: &Notification) {
// TODO
let msg = format!("📣 {:?}", notification);
writeln!(w, "{}", msg).ok();
}
pub(crate) fn containers<W: io::Write>(mut w: W, containers: &[ContainerData]) -> Result<()> {
let mut table = Table::new();
table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
table.set_titles(Row::new(vec![
Cell::new("Name").with_style(Attr::Bold),
Cell::new("Version").with_style(Attr::Bold),
Cell::new("Repository").with_style(Attr::Bold),
Cell::new("Type").with_style(Attr::Bold),
Cell::new("Mounted").with_style(Attr::Bold),
Cell::new("PID").with_style(Attr::Bold),
Cell::new("Uptime").with_style(Attr::Bold),
]));
for container in containers
.iter()
.sorted_by_key(|c| &c.manifest.name) // Sort by name
.sorted_by_key(|c| c.manifest.init.is_none())
{
table.add_row(Row::new(vec![
Cell::new(&container.container.name()).with_style(Attr::Bold),
Cell::new(&container.container.version().to_string()),
Cell::new(&container.repository),
Cell::new(
container
.manifest
.init
.as_ref()
.map(|_| "App")
.unwrap_or("Resource"),
),
Cell::new(if container.mounted { "yes" } else { "no" }),
Cell::new(
&container
.process
.as_ref()
.map(|p| p.pid.to_string())
.unwrap_or_default(),
)
.with_style(Attr::ForegroundColor(prettytable::color::GREEN)),
Cell::new(
&container
.process
.as_ref()
.map(|p| format!("{:?}", time::Duration::from_nanos(p.uptime)))
.unwrap_or_default(),
),
]));
}
print_table(&mut w, &table)
}
pub(crate) fn repositories<W: io::Write>(
mut w: W,
repositories: &HashMap<RepositoryId, Repository>,
) -> Result<()> {
let mut table = Table::new();
table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
table.set_titles(Row::new(vec![
Cell::new("Name").with_style(Attr::Bold),
Cell::new("Path").with_style(Attr::Bold),
]));
for (id, repo) in repositories.iter().sorted_by_key(|(i, _)| (*i).clone())
// Sort by name
{
table.add_row(Row::new(vec![
Cell::new(&id).with_style(Attr::Bold),
Cell::new(&repo.dir.display().to_string()),
]));
}
print_table(&mut w, &table)
}
pub(crate) fn mounts<W: io::Write>(mut w: W, mounts: &[(Container, MountResult)]) -> Result<()> {
let mut table = Table::new();
table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
table.set_titles(Row::new(vec![
Cell::new("Name").with_style(Attr::Bold),
Cell::new("Path").with_style(Attr::Bold),
]));
for (container, result) in mounts
.iter()
.sorted_by_key(|(container, _)| (*container).to_string())
{
table.add_row(Row::new(vec![
Cell::new(&container.to_string()).with_style(Attr::Bold),
Cell::new(match result {
MountResult::Ok => "ok",
MountResult::Err(_) => "failed",
}),
]));
}
print_table(&mut w, &table)
}
pub(crate) async fn print_response<W: std::io::Write>(
mut output: &mut W,
response: Response,
) -> Result<()> {
match response {
Response::Containers(cs) => containers(&mut output, &cs),
Response::Repositories(rs) => repositories(&mut output, &rs),
Response::Ok(()) => {
writeln!(output, "{}", "✔ success".green()).context("Failed to write to stdout")
}
Response::Err(e) => {
writeln!(output, "{}: {:?}", "✗ failed".red(), e).context("Failed to write to stdout")
}
Response::Mount(results) => mounts(&mut output, &results),
}
}
fn print_table<W: std::io::Write>(mut w: W, table: &Table) -> Result<()> {
for line in table.to_string().lines() {
writeln!(w, " {}", line)?;
}
w.flush()?;
Ok(())
}
|
// Copyright 2018 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.
// aux-build:edition-lint-paths.rs
// run-rustfix
// compile-flags:--edition 2018
// The "normal case". Ideally we would remove the `extern crate` here,
// but we don't.
#![feature(rust_2018_preview)]
#![deny(rust_2018_idioms)]
#![allow(dead_code)]
extern crate edition_lint_paths;
//~^ ERROR unused extern crate
extern crate edition_lint_paths as bar;
//~^ ERROR `extern crate` is not idiomatic in the new edition
fn main() {
// This is not considered to *use* the `extern crate` in Rust 2018:
use edition_lint_paths::foo;
foo();
// But this should be a use of the (renamed) crate:
crate::bar::foo();
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Clock control register"]
pub cr: CR,
#[doc = "0x04 - Internal clock sources calibration register"]
pub icscr: ICSCR,
#[doc = "0x08 - Clock configuration register"]
pub cfgr: CFGR,
#[doc = "0x0c - Clock interrupt register"]
pub cir: CIR,
#[doc = "0x10 - AHB peripheral reset register"]
pub ahbrstr: AHBRSTR,
#[doc = "0x14 - APB2 peripheral reset register"]
pub apb2rstr: APB2RSTR,
#[doc = "0x18 - APB1 peripheral reset register"]
pub apb1rstr: APB1RSTR,
#[doc = "0x1c - AHB peripheral clock enable register"]
pub ahbenr: AHBENR,
#[doc = "0x20 - APB2 peripheral clock enable register"]
pub apb2enr: APB2ENR,
#[doc = "0x24 - APB1 peripheral clock enable register"]
pub apb1enr: APB1ENR,
#[doc = "0x28 - AHB peripheral clock enable in low power mode register"]
pub ahblpenr: AHBLPENR,
#[doc = "0x2c - APB2 peripheral clock enable in low power mode register"]
pub apb2lpenr: APB2LPENR,
#[doc = "0x30 - APB1 peripheral clock enable in low power mode register"]
pub apb1lpenr: APB1LPENR,
#[doc = "0x34 - Control/status register"]
pub csr: CSR,
}
#[doc = "Clock control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr](cr) module"]
pub type CR = crate::Reg<u32, _CR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CR;
#[doc = "`read()` method returns [cr::R](cr::R) reader structure"]
impl crate::Readable for CR {}
#[doc = "`write(|w| ..)` method takes [cr::W](cr::W) writer structure"]
impl crate::Writable for CR {}
#[doc = "Clock control register"]
pub mod cr;
#[doc = "Internal clock sources calibration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [icscr](icscr) module"]
pub type ICSCR = crate::Reg<u32, _ICSCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ICSCR;
#[doc = "`read()` method returns [icscr::R](icscr::R) reader structure"]
impl crate::Readable for ICSCR {}
#[doc = "`write(|w| ..)` method takes [icscr::W](icscr::W) writer structure"]
impl crate::Writable for ICSCR {}
#[doc = "Internal clock sources calibration register"]
pub mod icscr;
#[doc = "Clock configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cfgr](cfgr) module"]
pub type CFGR = crate::Reg<u32, _CFGR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CFGR;
#[doc = "`read()` method returns [cfgr::R](cfgr::R) reader structure"]
impl crate::Readable for CFGR {}
#[doc = "`write(|w| ..)` method takes [cfgr::W](cfgr::W) writer structure"]
impl crate::Writable for CFGR {}
#[doc = "Clock configuration register"]
pub mod cfgr;
#[doc = "Clock interrupt register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cir](cir) module"]
pub type CIR = crate::Reg<u32, _CIR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CIR;
#[doc = "`read()` method returns [cir::R](cir::R) reader structure"]
impl crate::Readable for CIR {}
#[doc = "`write(|w| ..)` method takes [cir::W](cir::W) writer structure"]
impl crate::Writable for CIR {}
#[doc = "Clock interrupt register"]
pub mod cir;
#[doc = "AHB peripheral reset register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ahbrstr](ahbrstr) module"]
pub type AHBRSTR = crate::Reg<u32, _AHBRSTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _AHBRSTR;
#[doc = "`read()` method returns [ahbrstr::R](ahbrstr::R) reader structure"]
impl crate::Readable for AHBRSTR {}
#[doc = "`write(|w| ..)` method takes [ahbrstr::W](ahbrstr::W) writer structure"]
impl crate::Writable for AHBRSTR {}
#[doc = "AHB peripheral reset register"]
pub mod ahbrstr;
#[doc = "APB2 peripheral reset register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb2rstr](apb2rstr) module"]
pub type APB2RSTR = crate::Reg<u32, _APB2RSTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _APB2RSTR;
#[doc = "`read()` method returns [apb2rstr::R](apb2rstr::R) reader structure"]
impl crate::Readable for APB2RSTR {}
#[doc = "`write(|w| ..)` method takes [apb2rstr::W](apb2rstr::W) writer structure"]
impl crate::Writable for APB2RSTR {}
#[doc = "APB2 peripheral reset register"]
pub mod apb2rstr;
#[doc = "APB1 peripheral reset register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb1rstr](apb1rstr) module"]
pub type APB1RSTR = crate::Reg<u32, _APB1RSTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _APB1RSTR;
#[doc = "`read()` method returns [apb1rstr::R](apb1rstr::R) reader structure"]
impl crate::Readable for APB1RSTR {}
#[doc = "`write(|w| ..)` method takes [apb1rstr::W](apb1rstr::W) writer structure"]
impl crate::Writable for APB1RSTR {}
#[doc = "APB1 peripheral reset register"]
pub mod apb1rstr;
#[doc = "AHB peripheral clock enable register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ahbenr](ahbenr) module"]
pub type AHBENR = crate::Reg<u32, _AHBENR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _AHBENR;
#[doc = "`read()` method returns [ahbenr::R](ahbenr::R) reader structure"]
impl crate::Readable for AHBENR {}
#[doc = "`write(|w| ..)` method takes [ahbenr::W](ahbenr::W) writer structure"]
impl crate::Writable for AHBENR {}
#[doc = "AHB peripheral clock enable register"]
pub mod ahbenr;
#[doc = "APB2 peripheral clock enable register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb2enr](apb2enr) module"]
pub type APB2ENR = crate::Reg<u32, _APB2ENR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _APB2ENR;
#[doc = "`read()` method returns [apb2enr::R](apb2enr::R) reader structure"]
impl crate::Readable for APB2ENR {}
#[doc = "`write(|w| ..)` method takes [apb2enr::W](apb2enr::W) writer structure"]
impl crate::Writable for APB2ENR {}
#[doc = "APB2 peripheral clock enable register"]
pub mod apb2enr;
#[doc = "APB1 peripheral clock enable register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb1enr](apb1enr) module"]
pub type APB1ENR = crate::Reg<u32, _APB1ENR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _APB1ENR;
#[doc = "`read()` method returns [apb1enr::R](apb1enr::R) reader structure"]
impl crate::Readable for APB1ENR {}
#[doc = "`write(|w| ..)` method takes [apb1enr::W](apb1enr::W) writer structure"]
impl crate::Writable for APB1ENR {}
#[doc = "APB1 peripheral clock enable register"]
pub mod apb1enr;
#[doc = "AHB peripheral clock enable in low power mode register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ahblpenr](ahblpenr) module"]
pub type AHBLPENR = crate::Reg<u32, _AHBLPENR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _AHBLPENR;
#[doc = "`read()` method returns [ahblpenr::R](ahblpenr::R) reader structure"]
impl crate::Readable for AHBLPENR {}
#[doc = "`write(|w| ..)` method takes [ahblpenr::W](ahblpenr::W) writer structure"]
impl crate::Writable for AHBLPENR {}
#[doc = "AHB peripheral clock enable in low power mode register"]
pub mod ahblpenr;
#[doc = "APB2 peripheral clock enable in low power mode register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb2lpenr](apb2lpenr) module"]
pub type APB2LPENR = crate::Reg<u32, _APB2LPENR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _APB2LPENR;
#[doc = "`read()` method returns [apb2lpenr::R](apb2lpenr::R) reader structure"]
impl crate::Readable for APB2LPENR {}
#[doc = "`write(|w| ..)` method takes [apb2lpenr::W](apb2lpenr::W) writer structure"]
impl crate::Writable for APB2LPENR {}
#[doc = "APB2 peripheral clock enable in low power mode register"]
pub mod apb2lpenr;
#[doc = "APB1 peripheral clock enable in low power mode register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb1lpenr](apb1lpenr) module"]
pub type APB1LPENR = crate::Reg<u32, _APB1LPENR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _APB1LPENR;
#[doc = "`read()` method returns [apb1lpenr::R](apb1lpenr::R) reader structure"]
impl crate::Readable for APB1LPENR {}
#[doc = "`write(|w| ..)` method takes [apb1lpenr::W](apb1lpenr::W) writer structure"]
impl crate::Writable for APB1LPENR {}
#[doc = "APB1 peripheral clock enable in low power mode register"]
pub mod apb1lpenr;
#[doc = "Control/status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [csr](csr) module"]
pub type CSR = crate::Reg<u32, _CSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CSR;
#[doc = "`read()` method returns [csr::R](csr::R) reader structure"]
impl crate::Readable for CSR {}
#[doc = "`write(|w| ..)` method takes [csr::W](csr::W) writer structure"]
impl crate::Writable for CSR {}
#[doc = "Control/status register"]
pub mod csr;
|
use openexr_sys as sys;
use std::ffi::CString;
use std::path::Path;
use crate::core::{error::Error, header::HeaderRef, version::Version};
type Result<T, E = Error> = std::result::Result<T, E>;
/// Manages writing multi-part images.
///
/// Multi-part images are essentially just containers around multiple
/// [`InputFile`](crate::core::input_file::InputFile)s.
///
/// Certain attributes are shared between all parts:
/// * `displayWindow`
/// * `pixelAspectRatio`
/// * `timeCode`
/// * `chromaticities`
///
#[repr(transparent)]
pub struct MultiPartInputFile(pub(crate) *mut sys::Imf_MultiPartInputFile_t);
impl MultiPartInputFile {
/// Create a new `MultiPartInputFile` to read the file at `filename`.
///
/// # Errors
/// * [`Error::Base`] - if any error occurs.
///
pub fn new<P: AsRef<Path>>(
filename: P,
num_threads: i32,
reconstruct_chunk_offset_table: bool,
) -> Result<MultiPartInputFile> {
let c_filename = CString::new(
filename
.as_ref()
.to_str()
.expect("Invalid bytes in filename"),
)
.expect("Internal null bytes in filename");
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_MultiPartInputFile_ctor(
&mut ptr,
c_filename.as_ptr(),
num_threads,
reconstruct_chunk_offset_table,
)
.into_result()?;
}
Ok(MultiPartInputFile(ptr))
}
/// The number of parts in the file
///
pub fn parts(&self) -> i32 {
let mut v = 0;
unsafe {
sys::Imf_MultiPartInputFile_parts(self.0, &mut v)
.into_result()
.expect("MultiPartInputFile::parts");
}
v
}
/// Get a reference to the [`Header`](crate::core::header::Header) for part `n`.
///
/// # Errors
/// * [`Error::OutOfRange`] - if `n` does not index a part in the file.
///
pub fn header(&self, n: i32) -> Result<HeaderRef> {
// OpenEXR itself doesn't handle this
// https://github.com/AcademySoftwareFoundation/openexr/issues/1031
if n < 0 || n >= self.parts() {
Err(Error::OutOfRange)
} else {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_MultiPartInputFile_header(self.0, &mut ptr, n)
.into_result()
.expect("MultiPartInputFile::header");
}
Ok(HeaderRef::new(ptr))
}
}
/// Get the file format version
///
pub fn version(&self) -> Version {
let mut v = 0;
unsafe {
sys::Imf_MultiPartInputFile_version(self.0, &mut v)
.into_result()
.expect("MultiPartInputFile::version");
}
Version::from_c_int(v)
}
/// Check whether the entire chunk offset table for the part is written
/// correctly.
///
pub fn part_complete(&self, part: i32) -> bool {
let mut v = false;
unsafe {
sys::Imf_MultiPartInputFile_partComplete(self.0, &mut v, part)
.into_result()
.expect("MultiPartInputFile::partComplete");
}
v
}
/// Flushes the internal part cache.
///
/// Intended for debugging purposes, but can be used to temporarily reduce
/// memory overhead, or to switch between types (e.g. TiledInputPart, to
/// DeepScanlineInputPart to InputPart).
///
pub fn flush_part_cache(&mut self) {
unsafe {
sys::Imf_MultiPartInputFile_flushPartCache(self.0)
.into_result()
.expect("MultiPartInputFile::flushPartCache");
}
}
}
impl Drop for MultiPartInputFile {
fn drop(&mut self) {
unsafe { sys::Imf_MultiPartInputFile_dtor(self.0) };
}
}
#[cfg(test)]
#[test]
fn read_multipartinputfile1() -> Result<()> {
use crate::multi_part::multi_part_input_file::MultiPartInputFile;
use std::path::PathBuf;
let path = PathBuf::from(
std::env::var("CARGO_MANIFEST_DIR")
.expect("CARGO_MANIFEST_DIR not set"),
)
.join("images")
.join("ferris-multipart.exr");
let file = MultiPartInputFile::new(path, 4, true)?;
assert_eq!(file.parts(), 2);
assert_eq!(file.header(0).unwrap().name().unwrap(), "left");
assert_eq!(file.header(1).unwrap().name().unwrap(), "right");
assert_eq!(file.version().is_multi_part(), true);
assert_eq!(file.version().is_tiled(), false);
Ok(())
}
|
use std::path::Path;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
use std::env;
use echain::{ErrorKind, Result};
use gtk;
use gtk::prelude::*;
use gtk::{Builder, Window, WidgetExt, TreeView, TreeViewExt, TreeViewColumn, CellRendererText, TreeStore, TreeModel, TextTag};
use sourceview::{Buffer, BufferExt, LanguageManager, LanguageManagerExt, View};
use syntex_syntax::codemap::FilePathMapping;
use syntex_syntax::parse::{self, ParseSess};
use syntex_syntax::visit::walk_crate;
use visitor::TreeVisitor;
use tree_column_set_data_func_ext::TreeViewColumnSetCellDataFuncExt;
use ast_model_extensions::{AstModelExt, AstModelColumns, AstPropertiesColumns};
macro_rules! column {
($tree:expr, $col:ident, $cell:ident, $type:ident, $title:expr, $expand:expr) => {
let $col = TreeViewColumn::new();
$col.set_title($title);
let $cell = $type::new();
$col.pack_end(&$cell, $expand);
$tree.append_column(&$col);
};
}
fn add_ast_columns(tree: &TreeView) {
column!(tree, type_col, type_cell, CellRendererText, "Type", true);
type_col.add_attribute(&type_cell, "text", AstModelColumns::Type as i32);
column!(tree, kind_col, kind_cell, CellRendererText, "Kind", true);
kind_col.add_attribute(&kind_cell, "text", AstModelColumns::Kind as i32);
column!(tree, span_col, span_cell, CellRendererText, "Span", false);
span_col.set_cell_data_func(&span_cell, move |_column, cell, model, iter| {
let text_cell = cell.clone().downcast::<CellRendererText>()
.expect("Couldn't downcast to CellRendererText");
if let Some((lo, hi)) = model.get_span(iter) {
text_cell.set_property_text(Some(&format!("[{}..{})", lo, hi)));
}
else {
text_cell.set_property_text(Some(""));
}
});
}
fn add_properties_columns(list: &TreeView) {
column!(list, name_col, name_cell, CellRendererText, "Property", true);
name_col.add_attribute(&name_cell, "text", AstPropertiesColumns::Name as i32);
column!(list, value_col, value_cell, CellRendererText, "Value", true);
value_col.add_attribute(&value_cell, "text", AstPropertiesColumns::Value as i32);
}
fn open_file<T: AsRef<Path>>(path: T, buffer: &Buffer) {
let file = File::open(&path).expect("Couldn't open file");
let mut reader = BufReader::new(file);
let mut contents = String::new();
reader.read_to_string(&mut contents).expect("Couldn't read the file");
buffer.set_text(&contents);
let lang_manager = LanguageManager::new();
if let Some(lang) = lang_manager.guess_language(path.as_ref().to_str(), None) {
buffer.set_language(Some(&lang));
}
}
fn parse_file<T: AsRef<Path>>(path: T) -> TreeStore {
let path_mapping = FilePathMapping::empty();
let parse_session = ParseSess::new(path_mapping);
let krate = match parse::parse_crate_from_file(path.as_ref(), &parse_session) {
// There may be parse errors that the parser recovered from, which we
// want to treat as an error.
Ok(_) if parse_session.span_diagnostic.has_errors() => Err(None),
Ok(krate) => Ok(krate),
Err(e) => Err(Some(e)),
};
let mut vis = TreeVisitor::new();
walk_crate(&mut vis, &krate.expect("Could not walk crate"));
vis.tree
}
macro_rules! get_widget {
($builder:expr, $name:ident, $type:ty) => {
let $name: $type = $builder.get_object(stringify!($name))
.ok_or(ErrorKind::WidgetNotFound(stringify!($name)))?;
}
}
pub(crate) fn gui_main() -> Result<()> {
gtk::init()?;
let glade_src = include_str!("syntax_visualizer.glade");
let builder = Builder::new_from_string(glade_src);
get_widget!(builder, main_window, Window);
get_widget!(builder, source_view, View);
get_widget!(builder, syntax_tree_view, TreeView);
get_widget!(builder, node_properties_view, TreeView);
let buffer: Buffer = source_view.get_buffer()
.ok_or(ErrorKind::WidgetNotFound("Buffer"))?
.downcast::<Buffer>()
.map_err(|_| ErrorKind::DowncastFailed("TextBuffer", "Buffer"))?;
// syntax_tree_view.set_headers_visible(false);
add_ast_columns(&syntax_tree_view);
add_properties_columns(&node_properties_view);
if let Some(path) = env::args().nth(1) {
let syntax_tree_store = parse_file(&path);
open_file(&path, &buffer);
syntax_tree_view.set_model(Some(&syntax_tree_store));
}
let tag_table = buffer.get_tag_table().ok_or(ErrorKind::WidgetNotFound("TagTable"))?;
let tag_highlighted = TextTag::new("highlighted");
tag_highlighted.set_property_background(Some("#dcebff"));
tag_table.add(&tag_highlighted);
let syntax_tree_selection = syntax_tree_view.get_selection();
let buffer_clone = buffer.clone();
syntax_tree_selection.connect_changed(move |tree_selection| {
let (start_iter, end_iter) = buffer_clone.get_bounds();
buffer_clone.remove_tag_by_name("highlighted", &start_iter, &end_iter);
if let Some((model, iter)) = tree_selection.get_selected() {
let props = model.get_properties_list(&iter);
node_properties_view.set_model(Some(&props));
if let Some((lo, hi)) = model.get_span(&iter) {
let mut lo_iter = buffer_clone.get_iter_at_offset(lo as i32);
let hi_iter = buffer_clone.get_iter_at_offset(hi as i32);
buffer_clone.apply_tag_by_name("highlighted", &lo_iter, &hi_iter);
source_view.scroll_to_iter(&mut lo_iter, 0.1, false, 0.0, 0.0);
}
}
else {
node_properties_view.set_model(None::<&TreeModel>);
}
});
buffer.connect_property_cursor_position_notify(move |buffer| {
let pos = buffer.get_property_cursor_position();
println!("new cursor position: {}", pos);
let model = syntax_tree_view.get_model().expect("Couldnt get tree model");
if let Some(iter) = model.find_node_by_pos(pos) {
let path = model.get_path(&iter).expect("Could not get tree path");
syntax_tree_view.expand_to_path(&path);
syntax_tree_selection.select_iter(&iter);
syntax_tree_view.scroll_to_cell(&path, None, false, 0.0, 0.0);
}
});
main_window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
main_window.show_all();
gtk::main();
Ok(())
}
|
/// Defines a bloc in LaTex
/// for example \begin{center}...\end{center}
///
use core::*;
use latex_file::LatexFile;
use std::io::BufWriter;
use std::io::Write;
use writable::*;
#[derive(Clone)]
pub struct Bloc {
/// The type of the Bloc
bloc_type: String,
/// The content in the Bloc
content: Vec<Core>,
}
impl Bloc {
/// Returns a new Bloc
pub fn new<T: AsRef<str>>(bloc_type: T, content: Vec<Core>) -> Self {
Bloc {
bloc_type: bloc_type.as_ref().to_string(),
content,
}
}
/// Returns a new Bloc with an empty body
pub fn new_empty<T: AsRef<str>>(bloc_type: T) -> Self {
Bloc {
bloc_type: bloc_type.as_ref().to_string(),
content: Vec::new(),
}
}
/// Adds an element to the content of the bloc
pub fn add(&mut self, element: Core) {
self.content.push(element);
}
}
impl Writable for Bloc {
fn write_latex(&self, file: &mut LatexFile) {
let mut writer = BufWriter::new(file);
self.write_to_buffer(&mut writer);
}
fn write_to_buffer(&self, mut buf: &mut BufWriter<&mut LatexFile>) {
writeln!(&mut buf, "\\begin{{{}}}", self.bloc_type).unwrap();
for item in self.content.iter() {
item.write_to_buffer(&mut buf);
}
writeln!(&mut buf, "\n\\end{{{}}}", self.bloc_type).unwrap();
}
}
#[cfg(test)]
mod tests_bloc {
use super::*;
use latex_file::*;
#[test]
fn creation_bloc_new_empty() {
let _ = Bloc::new_empty("center");
}
#[test]
fn creation_bloc_new() {
let _ = Bloc::new("center", vec![Core::bloc("verbatim")]);
}
#[test]
fn test_add() {
let mut b = Bloc::new_empty("center");
assert_eq!(b.content.len(), 0);
b.add(Core::bloc("verbatim"));
assert_eq!(b.content.len(), 1);
}
#[test]
fn test_add_core() {
let mut b = Core::bloc("center");
b.add(Core::bloc("verbatim"));
}
#[test]
fn test_write_simple_bloc_empty() {
let mut f = new_latex_file("./tests_results/bloc/bloc_simple_test_empty.tex");
f.begin_document();
let b = Bloc::new_empty("center");
b.write_latex(&mut f);
f.write_footer();
}
#[test]
fn test_write_simple_bloc_non_empty() {
let mut f = new_latex_file("./tests_results/bloc/bloc_simple_test_non_empty.tex");
f.begin_document();
let mut b = Bloc::new_empty("center");
b.add(Core::text("This is supposed to be centered"));
b.write_latex(&mut f);
f.write_footer();
}
#[test]
fn test_write_nested_bloc_non_empty() {
let mut f = new_latex_file("./tests_results/bloc/bloc_nested_test_non_empty.tex");
f.begin_document();
let mut b = Bloc::new_empty("center");
let mut b2 = Bloc::new_empty("verbatim");
b2.add(Core::text("To be or not to be"));
b.add(Core::Bloc(b2));
b.write_latex(&mut f);
f.write_footer();
}
}
|
fn main() {
println!("Don't forget --release before you benchmark!");
}
|
//! Traits for generic code over low and high bit depth video.
//!
//! Borrowed from rav1e.
use num_traits::{AsPrimitive, PrimInt};
use std::fmt::{Debug, Display};
/// Defines a type which supports being cast to from a generic integer type.
///
/// Intended for casting to and from a [`Pixel`](trait.Pixel.html).
pub trait CastFromPrimitive<T>: Copy + 'static {
/// Cast from a generic integer type to the given type.
fn cast_from(v: T) -> Self;
}
macro_rules! impl_cast_from_primitive {
( $T:ty => $U:ty ) => {
impl CastFromPrimitive<$U> for $T {
#[inline(always)]
fn cast_from(v: $U) -> Self { v as Self }
}
};
( $T:ty => { $( $U:ty ),* } ) => {
$( impl_cast_from_primitive!($T => $U); )*
};
}
// casts to { u8, u16 } are implemented separately using Pixel, so that the
// compiler understands that CastFromPrimitive<T: Pixel> is always implemented
impl_cast_from_primitive!(u8 => { u32, u64, usize });
impl_cast_from_primitive!(u8 => { i8, i16, i32, i64, isize });
impl_cast_from_primitive!(u16 => { u32, u64, usize });
impl_cast_from_primitive!(u16 => { i8, i16, i32, i64, isize });
impl_cast_from_primitive!(i16 => { u32, u64, usize });
impl_cast_from_primitive!(i16 => { i8, i16, i32, i64, isize });
impl_cast_from_primitive!(i32 => { u32, u64, usize });
impl_cast_from_primitive!(i32 => { i8, i16, i32, i64, isize });
#[doc(hidden)]
pub enum PixelType {
U8,
U16,
}
/// A trait for types which may represent a pixel in a video.
/// Currently implemented for `u8` and `u16`.
/// `u8` should be used for low-bit-depth video, and `u16`
/// for high-bit-depth video.
pub trait Pixel:
PrimInt
+ Into<u32>
+ Into<i32>
+ AsPrimitive<u8>
+ AsPrimitive<i16>
+ AsPrimitive<u16>
+ AsPrimitive<i32>
+ AsPrimitive<u32>
+ AsPrimitive<usize>
+ CastFromPrimitive<u8>
+ CastFromPrimitive<i16>
+ CastFromPrimitive<u16>
+ CastFromPrimitive<i32>
+ CastFromPrimitive<u32>
+ CastFromPrimitive<usize>
+ Debug
+ Display
+ Send
+ Sync
+ 'static
{
#[doc(hidden)]
fn type_enum() -> PixelType;
}
impl Pixel for u8 {
fn type_enum() -> PixelType {
PixelType::U8
}
}
impl Pixel for u16 {
fn type_enum() -> PixelType {
PixelType::U16
}
}
macro_rules! impl_cast_from_pixel_to_primitive {
( $T:ty ) => {
impl<T: Pixel> CastFromPrimitive<T> for $T {
#[inline(always)]
fn cast_from(v: T) -> Self {
v.as_()
}
}
};
}
impl_cast_from_pixel_to_primitive!(u8);
impl_cast_from_pixel_to_primitive!(i16);
impl_cast_from_pixel_to_primitive!(u16);
impl_cast_from_pixel_to_primitive!(i32);
impl_cast_from_pixel_to_primitive!(u32);
|
use anyhow::Result;
use app::{
models::{cache, entry, entry_tag, tag},
templates::get_env,
};
use camino::Utf8Path;
use glob::glob;
use lol_html::{element, html_content::ContentType, text, HtmlRewriter, Settings};
use minijinja::context;
use pathdiff::diff_utf8_paths;
use sea_orm::{
prelude::*, sea_query::Index, ActiveModelTrait, ActiveValue::Set, ConnectionTrait, Database,
EntityTrait, Schema,
};
use serde_json as json;
use std::{cell::RefCell, collections::HashSet, fs, rc::Rc};
use syntect::{
html::{ClassStyle, ClassedHTMLGenerator},
parsing::SyntaxSet,
util::LinesWithEndings,
};
use tokio::try_join;
fn rewrite_and_scrape(
contents: String,
) -> Result<(
Option<entry::frontmatter::Frontmatter>,
Vec<u8>,
entry::Elements,
)> {
let data: Rc<RefCell<Option<entry::frontmatter::Frontmatter>>> = Rc::new(RefCell::new(None));
let mut elements = HashSet::<String>::new();
let template_env = get_env();
let ss = SyntaxSet::load_defaults_newlines();
let mut output = Vec::new();
let language_buffer = Rc::new(RefCell::new(String::new()));
let mut rewriter = HtmlRewriter::new(
Settings {
element_content_handlers: vec![
element!("front-matter", |el| {
el.remove();
Ok(())
}),
text!("front-matter", |el| {
if let Ok(d) = json::from_str::<entry::frontmatter::Frontmatter>(el.as_str()) {
data.borrow_mut().replace(d);
}
Ok(())
}),
element!("code-block[language]", |el| {
if let Some(language) = el.get_attribute("language") {
language_buffer.borrow_mut().push_str(&language);
}
el.remove_and_keep_content();
Ok(())
}),
text!("code-block[language]", |el| {
let mut language = language_buffer.borrow_mut();
if let Some(syntax) = ss.find_syntax_by_extension(&language) {
let inner_html = String::from(el.as_str());
let mut highlighted_lines = Vec::<String>::new();
for line in LinesWithEndings::from(inner_html.trim()) {
let mut html_generator = ClassedHTMLGenerator::new_with_class_style(
syntax,
&ss,
ClassStyle::Spaced,
);
html_generator.parse_html_for_line_which_includes_newline(line)?;
highlighted_lines.push(html_generator.finalize());
}
let ctx = context! {
language => language.clone(),
highlighted_lines => highlighted_lines,
inner_html => inner_html
};
let template = template_env.get_template("elements/code-block.jinja")?;
let replacement_html = template.render(ctx)?;
el.replace(replacement_html.as_str(), ContentType::Html);
elements.insert("code-block".to_string());
}
language.clear();
Ok(())
}),
],
..Default::default()
},
|c: &[u8]| output.extend_from_slice(c),
);
rewriter.write(contents.as_bytes())?;
rewriter.end()?;
let elements = entry::Elements(elements.into_iter().collect::<Vec<String>>());
let data = data.take();
Ok((data, output, elements))
}
#[tokio::main]
async fn main() -> Result<()> {
fs::remove_dir_all("storage").ok();
fs::create_dir_all("storage")?;
let connection = Database::connect("sqlite://./storage/content.db?mode=rwc")
.await
.expect("database should connect");
let backend = connection.get_database_backend();
let schema = Schema::new(backend);
try_join!(
connection.execute(
backend
.build(&schema.create_table_from_entity(entry::Entity))
.to_owned(),
),
connection.execute(
backend
.build(&schema.create_table_from_entity(tag::Entity))
.to_owned(),
),
connection.execute(
backend
.build(&schema.create_table_from_entity(entry_tag::Entity))
.to_owned(),
),
connection.execute(
backend
.build(
Index::create()
.name("entry-slug-category-unique")
.table(entry::Entity)
.col(entry::Column::Slug)
.col(entry::Column::Category)
.unique()
)
.to_owned(),
),
connection.execute(
backend
.build(&schema.create_table_from_entity(cache::Entity))
.to_owned(),
),
)?;
let paths = glob("content/*/*.html".to_string().as_str())?;
for path in paths.flatten() {
if let Some(path) = Utf8Path::from_path(&path) {
let diff = diff_utf8_paths(path, Utf8Path::new("content/"))
.expect("path should be diffable with content");
let mut entry = entry::ActiveModel {
..Default::default()
};
let slug = diff.file_stem().expect("file stem should exist");
let category = diff.parent().expect("parent should exist");
let contents = fs::read_to_string(path)?;
let (data, content, elements) = rewrite_and_scrape(contents)?;
if let Some(data) = data.clone() {
entry.title = Set(data.title);
entry.description = Set(data.description);
entry.permalink = Set(data.permalink);
entry.template = Set(data.template);
entry.date = Set(data.date);
entry.feed = Set(data.feed);
}
entry.content = Set(String::from_utf8(content)?);
entry.elements = Set(elements);
entry.slug = Set(slug.to_string());
entry.category = Set(category.to_string());
let entry = entry.insert(&connection).await?;
if let Some(data) = data {
if let Some(tags) = data.tags {
for slug in tags {
let tag = if let Some(tag) = tag::Entity::find()
.filter(tag::Column::Slug.eq(slug.clone()))
.one(&connection)
.await?
{
tag
} else {
let mut tag = tag::ActiveModel {
..Default::default()
};
tag.slug = Set(slug);
tag.insert(&connection).await?
};
let mut entry_tag = entry_tag::ActiveModel {
..Default::default()
};
entry_tag.entry_id = Set(entry.id);
entry_tag.tag_id = Set(tag.id);
entry_tag.insert(&connection).await?;
}
}
}
}
}
Ok(())
}
|
use crate::{config::ServerConfig, connect};
use futures_util::ready;
use futures_util::stream::{Stream, StreamExt};
use hyper::server::{accept::from_stream, conn::Http, Builder};
use hyper::service::{make_service_fn, service_fn};
use std::convert::Infallible;
use std::net::IpAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf, Result};
use tokio::net::{TcpListener, TcpStream};
use tokio_rustls::server::TlsStream;
pub async fn run(tcp: TcpListener, config: ServerConfig) {
let config = Arc::new(config);
let stream = AcceptTcpStream::new(tcp).filter_map(|rst| {
let config = config.clone();
async move {
let (stream, ip) = match rst {
Ok(val) => val,
// Failed to receive request
Err(_) => return None,
};
// HTTPS
if let Some(tls) = &config.tls {
let stream = match tls.clone().accept(stream).await {
Ok(s) => s,
// TLS connection failed
Err(_) => return None,
};
let (_, session) = stream.get_ref();
// TODO
// Matching certificate
let hostname = match session.get_sni_hostname() {
Some(name) => name,
None => return None,
};
let i = config
.sites
.iter()
.position(|site| site.host.is_match(hostname))
.unwrap();
return Some(Ok::<_, hyper::Error>(HttpConnect::TlsStream(stream, ip, i)));
}
// HTTP
Some(Ok::<_, hyper::Error>(HttpConnect::Stream(stream, ip)))
}
});
let service = make_service_fn(|req: &HttpConnect| {
let config = config.clone();
let (remote, site_position) = match req {
HttpConnect::Stream(_, ip) => (*ip, None),
HttpConnect::TlsStream(_, ip, i) => (*ip, Some(*i)),
};
async move {
let service = service_fn(move |req| {
let sites = match site_position {
Some(i) => vec![config.sites[i].clone()],
None => config.sites.clone(),
};
connect(req, remote, sites)
});
Ok::<_, Infallible>(service)
}
});
let http = Http::new();
let _ = Builder::new(from_stream(stream), http).serve(service).await;
}
// Accept stream and remote ip from TcpListener
struct AcceptTcpStream {
listener: TcpListener,
}
impl AcceptTcpStream {
fn new(tcp: TcpListener) -> Self {
Self { listener: tcp }
}
}
impl Stream for AcceptTcpStream {
type Item = Result<(TcpStream, IpAddr)>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let poll = self.listener.poll_accept(cx);
let rst = ready!(poll);
let item = rst.map(|(stream, addr)| (stream, addr.ip()));
Poll::Ready(Some(item))
}
}
// Distinguish between http and https
pub enum HttpConnect {
Stream(TcpStream, IpAddr),
TlsStream(TlsStream<TcpStream>, IpAddr, usize),
}
impl AsyncRead for HttpConnect {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<Result<()>> {
match self.get_mut() {
Self::Stream(stream, _) => Pin::new(stream).poll_read(cx, buf),
Self::TlsStream(stream, _, _) => Pin::new(stream).poll_read(cx, buf),
}
}
}
impl AsyncWrite for HttpConnect {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>> {
match self.get_mut() {
Self::Stream(stream, _) => Pin::new(stream).poll_write(cx, buf),
Self::TlsStream(stream, _, _) => Pin::new(stream).poll_write(cx, buf),
}
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
match self.get_mut() {
Self::Stream(stream, _) => Pin::new(stream).poll_flush(cx),
Self::TlsStream(stream, _, _) => Pin::new(stream).poll_flush(cx),
}
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
match self.get_mut() {
Self::Stream(stream, _) => Pin::new(stream).poll_shutdown(cx),
Self::TlsStream(stream, _, _) => Pin::new(stream).poll_shutdown(cx),
}
}
}
|
//! Contains constructs for describing the nodes in a Binary Merkle Patricia Tree
//! used by Starknet.
//!
//! For more information about how these Starknet trees are structured, see
//! [`MerkleTree`](crate::tree::MerkleTree).
use std::{cell::RefCell, rc::Rc};
use bitvec::{order::Msb0, prelude::BitVec, slice::BitSlice};
use stark_hash::Felt;
use pathfinder_common::hash::FeltHash;
/// A node in a Binary Merkle-Patricia Tree graph.
#[derive(Clone, Debug, PartialEq)]
pub enum InternalNode {
/// A node that has not been fetched from storage yet.
///
/// As such, all we know is its hash.
Unresolved(Felt),
/// A branch node with exactly two children.
Binary(BinaryNode),
/// Describes a path connecting two other nodes.
Edge(EdgeNode),
/// A leaf node that contains a value.
Leaf(Felt),
}
/// Describes the [InternalNode::Binary] variant.
#[derive(Clone, Debug, PartialEq)]
pub struct BinaryNode {
/// The hash of this node. Is [None] if the node
/// has not yet been committed.
pub hash: Option<Felt>,
/// The height of this node in the tree.
pub height: usize,
/// [Left](Direction::Left) child.
pub left: Rc<RefCell<InternalNode>>,
/// [Right](Direction::Right) child.
pub right: Rc<RefCell<InternalNode>>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct EdgeNode {
/// The hash of this node. Is [None] if the node
/// has not yet been committed.
pub hash: Option<Felt>,
/// The starting height of this node in the tree.
pub height: usize,
/// The path this edge takes.
pub path: BitVec<Msb0, u8>,
/// The child of this node.
pub child: Rc<RefCell<InternalNode>>,
}
/// Describes the direction a child of a [BinaryNode] may have.
///
/// Binary nodes have two children, one left and one right.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
Left,
Right,
}
impl Direction {
/// Inverts the [Direction].
///
/// [Left] becomes [Right], and [Right] becomes [Left].
///
/// [Left]: Direction::Left
/// [Right]: Direction::Right
pub fn invert(self) -> Direction {
match self {
Direction::Left => Direction::Right,
Direction::Right => Direction::Left,
}
}
}
impl From<bool> for Direction {
fn from(tf: bool) -> Self {
match tf {
true => Direction::Right,
false => Direction::Left,
}
}
}
impl From<Direction> for bool {
fn from(direction: Direction) -> Self {
match direction {
Direction::Left => false,
Direction::Right => true,
}
}
}
impl BinaryNode {
/// Maps the key's bit at the binary node's height to a [Direction].
///
/// This can be used to check which direction the key descibes in the context
/// of this binary node i.e. which direction the child along the key's path would
/// take.
pub fn direction(&self, key: &BitSlice<Msb0, u8>) -> Direction {
key[self.height].into()
}
/// Returns the [Left] or [Right] child.
///
/// [Left]: Direction::Left
/// [Right]: Direction::Right
pub fn get_child(&self, direction: Direction) -> Rc<RefCell<InternalNode>> {
match direction {
Direction::Left => self.left.clone(),
Direction::Right => self.right.clone(),
}
}
/// If possible, calculates and sets its own hash value.
///
/// Does nothing if the hash is already [Some].
///
/// If either childs hash is [None], then the hash cannot
/// be calculated and it will remain [None].
pub(crate) fn calculate_hash<H: FeltHash>(&mut self) {
if self.hash.is_some() {
return;
}
let left = match self.left.borrow().hash() {
Some(hash) => hash,
None => unreachable!("subtrees have to be commited first"),
};
let right = match self.right.borrow().hash() {
Some(hash) => hash,
None => unreachable!("subtrees have to be commited first"),
};
self.hash = Some(H::hash(left, right));
}
}
impl InternalNode {
/// Convenience function which sets the inner node's hash to [None], if
/// applicable.
///
/// Used to indicate that this node has been mutated.
pub fn mark_dirty(&mut self) {
match self {
InternalNode::Binary(inner) => inner.hash = None,
InternalNode::Edge(inner) => inner.hash = None,
_ => {}
}
}
/// Returns true if the node represents an empty node -- this is defined as a node
/// with the [Felt::ZERO].
///
/// This can occur for the root node in an empty graph.
pub fn is_empty(&self) -> bool {
match self {
InternalNode::Unresolved(hash) => hash == &Felt::ZERO,
_ => false,
}
}
pub fn is_binary(&self) -> bool {
matches!(self, InternalNode::Binary(..))
}
pub fn as_binary(&self) -> Option<&BinaryNode> {
match self {
InternalNode::Binary(binary) => Some(binary),
_ => None,
}
}
pub fn as_edge(&self) -> Option<&EdgeNode> {
match self {
InternalNode::Edge(edge) => Some(edge),
_ => None,
}
}
pub fn hash(&self) -> Option<Felt> {
match self {
InternalNode::Unresolved(hash) => Some(*hash),
InternalNode::Binary(binary) => binary.hash,
InternalNode::Edge(edge) => edge.hash,
InternalNode::Leaf(value) => Some(*value),
}
}
}
impl EdgeNode {
/// Returns true if the edge node's path matches the same path given by the key.
pub fn path_matches(&self, key: &BitSlice<Msb0, u8>) -> bool {
self.path == key[self.height..self.height + self.path.len()]
}
/// Returns the common bit prefix between the edge node's path and the given key.
///
/// This is calculated with the edge's height taken into account.
pub fn common_path(&self, key: &BitSlice<Msb0, u8>) -> &BitSlice<Msb0, u8> {
let key_path = key.iter().skip(self.height);
let common_length = key_path
.zip(self.path.iter())
.take_while(|(a, b)| a == b)
.count();
&self.path[..common_length]
}
/// If possible, calculates and sets its own hash value.
///
/// Does nothing if the hash is already [Some].
///
/// If the child's hash is [None], then the hash cannot
/// be calculated and it will remain [None].
pub(crate) fn calculate_hash<H: FeltHash>(&mut self) {
if self.hash.is_some() {
return;
}
let child = match self.child.borrow().hash() {
Some(hash) => hash,
None => unreachable!("subtree has to be commited before"),
};
let path = Felt::from_bits(&self.path).unwrap();
let mut length = [0; 32];
// Safe as len() is guaranteed to be <= 251
length[31] = self.path.len() as u8;
let length = Felt::from_be_bytes(length).unwrap();
let hash = H::hash(child, path) + length;
self.hash = Some(hash);
}
}
#[cfg(test)]
mod tests {
use super::*;
use pathfinder_common::hash::PedersenHash;
mod direction {
use super::*;
use Direction::*;
#[test]
fn invert() {
assert_eq!(Left.invert(), Right);
assert_eq!(Right.invert(), Left);
}
#[test]
fn bool_round_trip() {
assert_eq!(Direction::from(bool::from(Left)), Left);
assert_eq!(Direction::from(bool::from(Right)), Right);
}
#[test]
fn right_is_true() {
assert!(bool::from(Right));
}
#[test]
fn left_is_false() {
assert!(!bool::from(Left));
}
}
mod binary {
use super::*;
use bitvec::bitvec;
use pathfinder_common::felt;
#[test]
fn direction() {
let uut = BinaryNode {
hash: None,
height: 1,
left: Rc::new(RefCell::new(InternalNode::Leaf(felt!("0xabc")))),
right: Rc::new(RefCell::new(InternalNode::Leaf(felt!("0xdef")))),
};
let mut zero_key = bitvec![Msb0, u8; 1; 251];
zero_key.set(1, false);
let mut one_key = bitvec![Msb0, u8; 0; 251];
one_key.set(1, true);
let zero_direction = uut.direction(&zero_key);
let one_direction = uut.direction(&one_key);
assert_eq!(zero_direction, Direction::from(false));
assert_eq!(one_direction, Direction::from(true));
}
#[test]
fn get_child() {
let left = Rc::new(RefCell::new(InternalNode::Leaf(felt!("0xabc"))));
let right = Rc::new(RefCell::new(InternalNode::Leaf(felt!("0xdef"))));
let uut = BinaryNode {
hash: None,
height: 1,
left: left.clone(),
right: right.clone(),
};
use Direction::*;
assert_eq!(uut.get_child(Left), left);
assert_eq!(uut.get_child(Right), right);
}
#[test]
fn hash() {
// Test data taken from starkware cairo-lang repo:
// https://github.com/starkware-libs/cairo-lang/blob/fc97bdd8322a7df043c87c371634b26c15ed6cee/src/starkware/starkware_utils/commitment_tree/patricia_tree/nodes_test.py#L14
//
// Note that the hash function must be exchanged for `async_stark_hash_func`, otherwise it just uses some other test hash function.
let expected = Felt::from_hex_str(
"0615bb8d47888d2987ad0c63fc06e9e771930986a4dd8adc55617febfcf3639e",
)
.unwrap();
let left = felt!("0x1234");
let right = felt!("0xabcd");
let left = Rc::new(RefCell::new(InternalNode::Unresolved(left)));
let right = Rc::new(RefCell::new(InternalNode::Unresolved(right)));
let mut uut = BinaryNode {
hash: None,
height: 0,
left,
right,
};
uut.calculate_hash::<PedersenHash>();
assert_eq!(uut.hash, Some(expected));
}
}
mod edge {
use super::*;
use bitvec::bitvec;
use pathfinder_common::felt;
#[test]
fn hash() {
// Test data taken from starkware cairo-lang repo:
// https://github.com/starkware-libs/cairo-lang/blob/fc97bdd8322a7df043c87c371634b26c15ed6cee/src/starkware/starkware_utils/commitment_tree/patricia_tree/nodes_test.py#L38
//
// Note that the hash function must be exchanged for `async_stark_hash_func`, otherwise it just uses some other test hash function.
let expected = Felt::from_hex_str(
"1d937094c09b5f8e26a662d21911871e3cbc6858d55cc49af9848ea6fed4e9",
)
.unwrap();
let child = felt!("0x1234ABCD");
let child = Rc::new(RefCell::new(InternalNode::Unresolved(child)));
// Path = 42 in binary.
let path = bitvec![Msb0, u8; 1, 0, 1, 0, 1, 0];
let mut uut = EdgeNode {
hash: None,
height: 0,
path,
child,
};
uut.calculate_hash::<PedersenHash>();
assert_eq!(uut.hash, Some(expected));
}
mod path_matches {
use super::*;
use pathfinder_common::felt;
#[test]
fn full() {
let key = felt!("0x123456789abcdef");
let child = Rc::new(RefCell::new(InternalNode::Leaf(felt!("0xabc"))));
let uut = EdgeNode {
hash: None,
height: 0,
path: key.view_bits().to_bitvec(),
child,
};
assert!(uut.path_matches(key.view_bits()));
}
#[test]
fn prefix() {
let key = felt!("0x123456789abcdef");
let child = Rc::new(RefCell::new(InternalNode::Leaf(felt!("0xabc"))));
let path = key.view_bits()[..45].to_bitvec();
let uut = EdgeNode {
hash: None,
height: 0,
path,
child,
};
assert!(uut.path_matches(key.view_bits()));
}
#[test]
fn suffix() {
let key = felt!("0x123456789abcdef");
let child = Rc::new(RefCell::new(InternalNode::Leaf(felt!("0xabc"))));
let path = key.view_bits()[50..].to_bitvec();
let uut = EdgeNode {
hash: None,
height: 50,
path,
child,
};
assert!(uut.path_matches(key.view_bits()));
}
#[test]
fn middle_slice() {
let key = felt!("0x123456789abcdef");
let child = Rc::new(RefCell::new(InternalNode::Leaf(felt!("0xabc"))));
let path = key.view_bits()[230..235].to_bitvec();
let uut = EdgeNode {
hash: None,
height: 230,
path,
child,
};
assert!(uut.path_matches(key.view_bits()));
}
}
}
}
|
use procon_reader::ProconReader;
use std::collections::HashMap;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let a: Vec<u32> = rd.get_vec(n);
let mut freq = HashMap::new();
let mut ans = n * (n - 1) / 2;
for x in a {
let e = freq.entry(x).or_insert(0);
ans -= *e;
*e += 1;
}
println!("{}", ans);
}
|
// 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.
use http_types::{headers, StatusCode};
use serde::Serialize;
use std::sync::{MutexGuard, PoisonError};
use tide::Response;
use tremor_runtime::errors::{Error as TremorError, ErrorKind};
/// Tremor API error
#[derive(Debug, Serialize)]
pub struct Error {
pub code: StatusCode,
pub error: String,
}
impl Error {
/// Create new error from the given status code and error string
#[must_use]
pub fn new(code: StatusCode, error: String) -> Self {
Self { code, error }
}
/// Convenience function for creating aretefact not found errors
pub fn not_found() -> Self {
Self::new(StatusCode::NotFound, "Artefact not found".into())
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.error)
}
}
impl std::error::Error for Error {}
impl From<Error> for Response {
fn from(err: Error) -> Response {
Response::builder(err.code)
.header(
headers::CONTENT_TYPE,
crate::api::ResourceType::Json.as_str(),
)
.body(format!(
r#"{{"code":{},"error":"{}"}}"#,
err.code, err.error
))
.build()
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Self::new(StatusCode::InternalServerError, format!("IO error: {}", e))
}
}
impl From<simd_json::Error> for Error {
fn from(e: simd_json::Error) -> Self {
Self::new(StatusCode::BadRequest, format!("JSON error: {}", e))
}
}
impl From<serde_yaml::Error> for Error {
fn from(e: serde_yaml::Error) -> Self {
Self::new(StatusCode::BadRequest, format!("YAML error: {}", e))
}
}
impl From<http_types::Error> for Error {
fn from(e: http_types::Error) -> Self {
Self::new(
StatusCode::InternalServerError,
format!("HTTP type error: {}", e),
)
}
}
impl From<tremor_pipeline::errors::Error> for Error {
fn from(e: tremor_pipeline::errors::Error) -> Self {
Self::new(StatusCode::BadRequest, format!("Pipeline error: {}", e))
}
}
impl From<tremor_script::prelude::CompilerError> for Error {
fn from(e: tremor_script::prelude::CompilerError) -> Self {
Self::new(
StatusCode::InternalServerError,
format!("Compiler error: {:?}", e),
)
}
}
impl From<PoisonError<MutexGuard<'_, tremor_script::Registry>>> for Error {
fn from(e: PoisonError<MutexGuard<tremor_script::Registry>>) -> Self {
Self::new(
StatusCode::InternalServerError,
format!("Locking error: {}", e),
)
}
}
impl From<TremorError> for Error {
fn from(e: TremorError) -> Self {
match e.0 {
ErrorKind::UnpublishFailedNonZeroInstances(_) => Error::new(
StatusCode::Conflict,
"Resource still has active instances".into(),
),
ErrorKind::ArtefactNotFound(_) => {
Error::new(StatusCode::NotFound, "Artefact not found".into())
}
ErrorKind::PublishFailedAlreadyExists(_) => Error::new(
StatusCode::Conflict,
"A resource with the requested ID already exists".into(),
),
ErrorKind::UnpublishFailedSystemArtefact(_) => Error::new(
StatusCode::Forbidden,
"System artefacts cannot be unpublished".into(),
),
_e => Error::new(
StatusCode::InternalServerError,
"Internal server error".into(),
),
}
}
}
|
use super::*;
use crate::{TableIndex, TypeReader};
#[derive(Copy, Clone)]
pub struct InterfaceImpl {
pub reader: &'static TypeReader,
pub row: Row,
}
impl InterfaceImpl {
pub fn interface(&self) -> TypeDefOrRef {
self.reader.decode(self.row, 1)
}
pub fn attributes(&self) -> impl Iterator<Item = Attribute> + '_ {
self.reader
.equal_range(
self.row.file_index,
TableIndex::CustomAttribute,
0,
HasAttribute::InterfaceImpl(*self).encode(),
)
.map(move |row| Attribute {
reader: self.reader,
row,
})
}
pub fn has_attribute(&self, name: (&str, &str)) -> bool {
self.attributes().any(|attribute| attribute.name() == name)
}
pub fn is_default(&self) -> bool {
self.has_attribute(("Windows.Foundation.Metadata", "DefaultAttribute"))
}
}
impl std::fmt::Debug for InterfaceImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("InterfaceImpl")
.field("row", &self.row)
.finish()
}
}
impl PartialEq for InterfaceImpl {
fn eq(&self, other: &Self) -> bool {
self.row == other.row
}
}
impl Eq for InterfaceImpl {}
impl Ord for InterfaceImpl {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.row.cmp(&other.row)
}
}
impl PartialOrd for InterfaceImpl {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynAboutData(pub ::windows::core::IInspectable);
impl AllJoynAboutData {
#[cfg(feature = "deprecated")]
pub fn IsEnabled(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetIsEnabled(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "deprecated")]
pub fn DefaultAppName(&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).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetDefaultAppName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn AppNames(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IMap<::windows::core::HSTRING, ::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IMap<::windows::core::HSTRING, ::windows::core::HSTRING>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn DateOfManufacture(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::super::Foundation::DateTime>> {
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::<super::super::Foundation::IReference<super::super::Foundation::DateTime>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SetDateOfManufacture<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::IReference<super::super::Foundation::DateTime>>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn DefaultDescription(&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).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetDefaultDescription<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn Descriptions(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IMap<::windows::core::HSTRING, ::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IMap<::windows::core::HSTRING, ::windows::core::HSTRING>>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn DefaultManufacturer(&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 SetDefaultManufacturer<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn Manufacturers(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IMap<::windows::core::HSTRING, ::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IMap<::windows::core::HSTRING, ::windows::core::HSTRING>>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn ModelNumber(&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).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetModelNumber<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn SoftwareVersion(&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).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetSoftwareVersion<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SupportUrl(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
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::Uri>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SetSupportUrl<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn AppId(&self) -> ::windows::core::Result<::windows::core::GUID> {
let this = self;
unsafe {
let mut result__: ::windows::core::GUID = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetAppId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynAboutData {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynAboutData;{e5a9bf00-1fa2-4839-93ef-f9df404890f7})");
}
unsafe impl ::windows::core::Interface for AllJoynAboutData {
type Vtable = IAllJoynAboutData_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe5a9bf00_1fa2_4839_93ef_f9df404890f7);
}
impl ::windows::core::RuntimeName for AllJoynAboutData {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynAboutData";
}
impl ::core::convert::From<AllJoynAboutData> for ::windows::core::IUnknown {
fn from(value: AllJoynAboutData) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynAboutData> for ::windows::core::IUnknown {
fn from(value: &AllJoynAboutData) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynAboutData {
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 AllJoynAboutData {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynAboutData> for ::windows::core::IInspectable {
fn from(value: AllJoynAboutData) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynAboutData> for ::windows::core::IInspectable {
fn from(value: &AllJoynAboutData) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynAboutData {
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 AllJoynAboutData {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynAboutData {}
unsafe impl ::core::marker::Sync for AllJoynAboutData {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynAboutDataView(pub ::windows::core::IInspectable);
impl AllJoynAboutDataView {
#[cfg(feature = "deprecated")]
pub fn Status(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(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).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, ::windows::core::IInspectable>>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn AJSoftwareVersion(&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).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn AppId(&self) -> ::windows::core::Result<::windows::core::GUID> {
let this = self;
unsafe {
let mut result__: ::windows::core::GUID = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn DateOfManufacture(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::super::Foundation::DateTime>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::super::Foundation::DateTime>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Globalization")]
pub fn DefaultLanguage(&self) -> ::windows::core::Result<super::super::Globalization::Language> {
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::<super::super::Globalization::Language>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn DeviceId(&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).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn HardwareVersion(&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).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn ModelNumber(&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).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SoftwareVersion(&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).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation_Collections", feature = "Globalization"))]
pub fn SupportedLanguages(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<super::super::Globalization::Language>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<super::super::Globalization::Language>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SupportUrl(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn AppName(&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 Description(&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).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn DeviceName(&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).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Manufacturer(&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).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn GetDataBySessionPortAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, AllJoynBusAttachment>>(uniquename: Param0, busattachment: Param1, sessionport: u16) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AllJoynAboutDataView>> {
Self::IAllJoynAboutDataViewStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), uniquename.into_param().abi(), busattachment.into_param().abi(), sessionport, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AllJoynAboutDataView>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Globalization"))]
pub fn GetDataBySessionPortWithLanguageAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, AllJoynBusAttachment>, Param3: ::windows::core::IntoParam<'a, super::super::Globalization::Language>>(uniquename: Param0, busattachment: Param1, sessionport: u16, language: Param3) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AllJoynAboutDataView>> {
Self::IAllJoynAboutDataViewStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), uniquename.into_param().abi(), busattachment.into_param().abi(), sessionport, language.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AllJoynAboutDataView>>(result__)
})
}
pub fn IAllJoynAboutDataViewStatics<R, F: FnOnce(&IAllJoynAboutDataViewStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynAboutDataView, IAllJoynAboutDataViewStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynAboutDataView {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynAboutDataView;{6823111f-6212-4934-9c48-e19ca4984288})");
}
unsafe impl ::windows::core::Interface for AllJoynAboutDataView {
type Vtable = IAllJoynAboutDataView_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6823111f_6212_4934_9c48_e19ca4984288);
}
impl ::windows::core::RuntimeName for AllJoynAboutDataView {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynAboutDataView";
}
impl ::core::convert::From<AllJoynAboutDataView> for ::windows::core::IUnknown {
fn from(value: AllJoynAboutDataView) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynAboutDataView> for ::windows::core::IUnknown {
fn from(value: &AllJoynAboutDataView) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynAboutDataView {
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 AllJoynAboutDataView {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynAboutDataView> for ::windows::core::IInspectable {
fn from(value: AllJoynAboutDataView) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynAboutDataView> for ::windows::core::IInspectable {
fn from(value: &AllJoynAboutDataView) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynAboutDataView {
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 AllJoynAboutDataView {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynAboutDataView {}
unsafe impl ::core::marker::Sync for AllJoynAboutDataView {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynAcceptSessionJoinerEventArgs(pub ::windows::core::IInspectable);
impl AllJoynAcceptSessionJoinerEventArgs {
#[cfg(feature = "deprecated")]
pub fn UniqueName(&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).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SessionPort(&self) -> ::windows::core::Result<u16> {
let this = self;
unsafe {
let mut result__: u16 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u16>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn TrafficType(&self) -> ::windows::core::Result<AllJoynTrafficType> {
let this = self;
unsafe {
let mut result__: AllJoynTrafficType = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AllJoynTrafficType>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SamePhysicalNode(&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 SameNetwork(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Accept(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "deprecated")]
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param4: ::windows::core::IntoParam<'a, IAllJoynAcceptSessionJoiner>>(uniquename: Param0, sessionport: u16, traffictype: AllJoynTrafficType, proximity: u8, acceptsessionjoiner: Param4) -> ::windows::core::Result<AllJoynAcceptSessionJoinerEventArgs> {
Self::IAllJoynAcceptSessionJoinerEventArgsFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), uniquename.into_param().abi(), sessionport, traffictype, proximity, acceptsessionjoiner.into_param().abi(), &mut result__).from_abi::<AllJoynAcceptSessionJoinerEventArgs>(result__)
})
}
pub fn IAllJoynAcceptSessionJoinerEventArgsFactory<R, F: FnOnce(&IAllJoynAcceptSessionJoinerEventArgsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynAcceptSessionJoinerEventArgs, IAllJoynAcceptSessionJoinerEventArgsFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynAcceptSessionJoinerEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynAcceptSessionJoinerEventArgs;{4efb5365-3e8a-4257-8f10-539ce0d56c0f})");
}
unsafe impl ::windows::core::Interface for AllJoynAcceptSessionJoinerEventArgs {
type Vtable = IAllJoynAcceptSessionJoinerEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4efb5365_3e8a_4257_8f10_539ce0d56c0f);
}
impl ::windows::core::RuntimeName for AllJoynAcceptSessionJoinerEventArgs {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynAcceptSessionJoinerEventArgs";
}
impl ::core::convert::From<AllJoynAcceptSessionJoinerEventArgs> for ::windows::core::IUnknown {
fn from(value: AllJoynAcceptSessionJoinerEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynAcceptSessionJoinerEventArgs> for ::windows::core::IUnknown {
fn from(value: &AllJoynAcceptSessionJoinerEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynAcceptSessionJoinerEventArgs {
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 AllJoynAcceptSessionJoinerEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynAcceptSessionJoinerEventArgs> for ::windows::core::IInspectable {
fn from(value: AllJoynAcceptSessionJoinerEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynAcceptSessionJoinerEventArgs> for ::windows::core::IInspectable {
fn from(value: &AllJoynAcceptSessionJoinerEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynAcceptSessionJoinerEventArgs {
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 AllJoynAcceptSessionJoinerEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynAcceptSessionJoinerEventArgs {}
unsafe impl ::core::marker::Sync for AllJoynAcceptSessionJoinerEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynAuthenticationCompleteEventArgs(pub ::windows::core::IInspectable);
impl AllJoynAuthenticationCompleteEventArgs {
#[cfg(feature = "deprecated")]
pub fn AuthenticationMechanism(&self) -> ::windows::core::Result<AllJoynAuthenticationMechanism> {
let this = self;
unsafe {
let mut result__: AllJoynAuthenticationMechanism = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AllJoynAuthenticationMechanism>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn PeerUniqueName(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn Succeeded(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynAuthenticationCompleteEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynAuthenticationCompleteEventArgs;{97b4701c-15dc-4b53-b6a4-7d134300d7bf})");
}
unsafe impl ::windows::core::Interface for AllJoynAuthenticationCompleteEventArgs {
type Vtable = IAllJoynAuthenticationCompleteEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x97b4701c_15dc_4b53_b6a4_7d134300d7bf);
}
impl ::windows::core::RuntimeName for AllJoynAuthenticationCompleteEventArgs {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynAuthenticationCompleteEventArgs";
}
impl ::core::convert::From<AllJoynAuthenticationCompleteEventArgs> for ::windows::core::IUnknown {
fn from(value: AllJoynAuthenticationCompleteEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynAuthenticationCompleteEventArgs> for ::windows::core::IUnknown {
fn from(value: &AllJoynAuthenticationCompleteEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynAuthenticationCompleteEventArgs {
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 AllJoynAuthenticationCompleteEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynAuthenticationCompleteEventArgs> for ::windows::core::IInspectable {
fn from(value: AllJoynAuthenticationCompleteEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynAuthenticationCompleteEventArgs> for ::windows::core::IInspectable {
fn from(value: &AllJoynAuthenticationCompleteEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynAuthenticationCompleteEventArgs {
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 AllJoynAuthenticationCompleteEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynAuthenticationCompleteEventArgs {}
unsafe impl ::core::marker::Sync for AllJoynAuthenticationCompleteEventArgs {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct AllJoynAuthenticationMechanism(pub i32);
impl AllJoynAuthenticationMechanism {
pub const None: AllJoynAuthenticationMechanism = AllJoynAuthenticationMechanism(0i32);
pub const SrpAnonymous: AllJoynAuthenticationMechanism = AllJoynAuthenticationMechanism(1i32);
pub const SrpLogon: AllJoynAuthenticationMechanism = AllJoynAuthenticationMechanism(2i32);
pub const EcdheNull: AllJoynAuthenticationMechanism = AllJoynAuthenticationMechanism(3i32);
pub const EcdhePsk: AllJoynAuthenticationMechanism = AllJoynAuthenticationMechanism(4i32);
pub const EcdheEcdsa: AllJoynAuthenticationMechanism = AllJoynAuthenticationMechanism(5i32);
pub const EcdheSpeke: AllJoynAuthenticationMechanism = AllJoynAuthenticationMechanism(6i32);
}
impl ::core::convert::From<i32> for AllJoynAuthenticationMechanism {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for AllJoynAuthenticationMechanism {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for AllJoynAuthenticationMechanism {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.AllJoyn.AllJoynAuthenticationMechanism;i4)");
}
impl ::windows::core::DefaultType for AllJoynAuthenticationMechanism {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynBusAttachment(pub ::windows::core::IInspectable);
impl AllJoynBusAttachment {
pub fn new() -> ::windows::core::Result<Self> {
Self::IActivationFactory(|f| f.activate_instance::<Self>())
}
fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynBusAttachment, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
#[cfg(feature = "deprecated")]
pub fn AboutData(&self) -> ::windows::core::Result<AllJoynAboutData> {
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::<AllJoynAboutData>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn ConnectionSpecification(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn State(&self) -> ::windows::core::Result<AllJoynBusAttachmentState> {
let this = self;
unsafe {
let mut result__: AllJoynBusAttachmentState = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AllJoynBusAttachmentState>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn UniqueName(&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).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn PingAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, uniquename: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<i32>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), uniquename.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<i32>>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Connect(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "deprecated")]
pub fn Disconnect(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn StateChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<AllJoynBusAttachment, AllJoynBusAttachmentStateChangedEventArgs>>>(&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).13)(::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 RemoveStateChanged<'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).14)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Collections")]
pub fn AuthenticationMechanisms(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<AllJoynAuthenticationMechanism>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<AllJoynAuthenticationMechanism>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn CredentialsRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<AllJoynBusAttachment, AllJoynCredentialsRequestedEventArgs>>>(&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).16)(::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 RemoveCredentialsRequested<'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).17)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn CredentialsVerificationRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<AllJoynBusAttachment, AllJoynCredentialsVerificationRequestedEventArgs>>>(&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).18)(::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 RemoveCredentialsVerificationRequested<'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).19)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn AuthenticationComplete<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<AllJoynBusAttachment, AllJoynAuthenticationCompleteEventArgs>>>(&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).20)(::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 RemoveAuthenticationComplete<'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).21)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(connectionspecification: Param0) -> ::windows::core::Result<AllJoynBusAttachment> {
Self::IAllJoynBusAttachmentFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), connectionspecification.into_param().abi(), &mut result__).from_abi::<AllJoynBusAttachment>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn GetAboutDataAsync<'a, Param0: ::windows::core::IntoParam<'a, AllJoynServiceInfo>>(&self, serviceinfo: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AllJoynAboutDataView>> {
let this = &::windows::core::Interface::cast::<IAllJoynBusAttachment2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), serviceinfo.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AllJoynAboutDataView>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Globalization"))]
pub fn GetAboutDataWithLanguageAsync<'a, Param0: ::windows::core::IntoParam<'a, AllJoynServiceInfo>, Param1: ::windows::core::IntoParam<'a, super::super::Globalization::Language>>(&self, serviceinfo: Param0, language: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AllJoynAboutDataView>> {
let this = &::windows::core::Interface::cast::<IAllJoynBusAttachment2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), serviceinfo.into_param().abi(), language.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AllJoynAboutDataView>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn AcceptSessionJoinerRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<AllJoynBusAttachment, AllJoynAcceptSessionJoinerEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = &::windows::core::Interface::cast::<IAllJoynBusAttachment2>(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 RemoveAcceptSessionJoinerRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IAllJoynBusAttachment2>(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 SessionJoined<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<AllJoynBusAttachment, AllJoynSessionJoinedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = &::windows::core::Interface::cast::<IAllJoynBusAttachment2>(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 RemoveSessionJoined<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IAllJoynBusAttachment2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn GetDefault() -> ::windows::core::Result<AllJoynBusAttachment> {
Self::IAllJoynBusAttachmentStatics(|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::<AllJoynBusAttachment>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Devices_Enumeration", feature = "Foundation_Collections"))]
pub fn GetWatcher<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(requiredinterfaces: Param0) -> ::windows::core::Result<super::Enumeration::DeviceWatcher> {
Self::IAllJoynBusAttachmentStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), requiredinterfaces.into_param().abi(), &mut result__).from_abi::<super::Enumeration::DeviceWatcher>(result__)
})
}
pub fn IAllJoynBusAttachmentFactory<R, F: FnOnce(&IAllJoynBusAttachmentFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynBusAttachment, IAllJoynBusAttachmentFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IAllJoynBusAttachmentStatics<R, F: FnOnce(&IAllJoynBusAttachmentStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynBusAttachment, IAllJoynBusAttachmentStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynBusAttachment {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynBusAttachment;{f309f153-1eed-42c3-a20e-436d41fe62f6})");
}
unsafe impl ::windows::core::Interface for AllJoynBusAttachment {
type Vtable = IAllJoynBusAttachment_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf309f153_1eed_42c3_a20e_436d41fe62f6);
}
impl ::windows::core::RuntimeName for AllJoynBusAttachment {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynBusAttachment";
}
impl ::core::convert::From<AllJoynBusAttachment> for ::windows::core::IUnknown {
fn from(value: AllJoynBusAttachment) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynBusAttachment> for ::windows::core::IUnknown {
fn from(value: &AllJoynBusAttachment) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynBusAttachment {
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 AllJoynBusAttachment {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynBusAttachment> for ::windows::core::IInspectable {
fn from(value: AllJoynBusAttachment) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynBusAttachment> for ::windows::core::IInspectable {
fn from(value: &AllJoynBusAttachment) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynBusAttachment {
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 AllJoynBusAttachment {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynBusAttachment {}
unsafe impl ::core::marker::Sync for AllJoynBusAttachment {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct AllJoynBusAttachmentState(pub i32);
impl AllJoynBusAttachmentState {
pub const Disconnected: AllJoynBusAttachmentState = AllJoynBusAttachmentState(0i32);
pub const Connecting: AllJoynBusAttachmentState = AllJoynBusAttachmentState(1i32);
pub const Connected: AllJoynBusAttachmentState = AllJoynBusAttachmentState(2i32);
pub const Disconnecting: AllJoynBusAttachmentState = AllJoynBusAttachmentState(3i32);
}
impl ::core::convert::From<i32> for AllJoynBusAttachmentState {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for AllJoynBusAttachmentState {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for AllJoynBusAttachmentState {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.AllJoyn.AllJoynBusAttachmentState;i4)");
}
impl ::windows::core::DefaultType for AllJoynBusAttachmentState {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynBusAttachmentStateChangedEventArgs(pub ::windows::core::IInspectable);
impl AllJoynBusAttachmentStateChangedEventArgs {
#[cfg(feature = "deprecated")]
pub fn State(&self) -> ::windows::core::Result<AllJoynBusAttachmentState> {
let this = self;
unsafe {
let mut result__: AllJoynBusAttachmentState = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AllJoynBusAttachmentState>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Status(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynBusAttachmentStateChangedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynBusAttachmentStateChangedEventArgs;{d82e75f4-c02a-41ec-a8d5-eab1558953aa})");
}
unsafe impl ::windows::core::Interface for AllJoynBusAttachmentStateChangedEventArgs {
type Vtable = IAllJoynBusAttachmentStateChangedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd82e75f4_c02a_41ec_a8d5_eab1558953aa);
}
impl ::windows::core::RuntimeName for AllJoynBusAttachmentStateChangedEventArgs {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynBusAttachmentStateChangedEventArgs";
}
impl ::core::convert::From<AllJoynBusAttachmentStateChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: AllJoynBusAttachmentStateChangedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynBusAttachmentStateChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: &AllJoynBusAttachmentStateChangedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynBusAttachmentStateChangedEventArgs {
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 AllJoynBusAttachmentStateChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynBusAttachmentStateChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: AllJoynBusAttachmentStateChangedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynBusAttachmentStateChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: &AllJoynBusAttachmentStateChangedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynBusAttachmentStateChangedEventArgs {
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 AllJoynBusAttachmentStateChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynBusAttachmentStateChangedEventArgs {}
unsafe impl ::core::marker::Sync for AllJoynBusAttachmentStateChangedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynBusObject(pub ::windows::core::IInspectable);
impl AllJoynBusObject {
pub fn new() -> ::windows::core::Result<Self> {
Self::IActivationFactory(|f| f.activate_instance::<Self>())
}
fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynBusObject, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
#[cfg(feature = "deprecated")]
pub fn Start(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::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).7)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "deprecated")]
pub fn AddProducer<'a, Param0: ::windows::core::IntoParam<'a, IAllJoynProducer>>(&self, producer: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), producer.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn BusAttachment(&self) -> ::windows::core::Result<AllJoynBusAttachment> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AllJoynBusAttachment>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Session(&self) -> ::windows::core::Result<AllJoynSession> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AllJoynSession>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn Stopped<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<AllJoynBusObject, AllJoynBusObjectStoppedEventArgs>>>(&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).11)(::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).12)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(objectpath: Param0) -> ::windows::core::Result<AllJoynBusObject> {
Self::IAllJoynBusObjectFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), objectpath.into_param().abi(), &mut result__).from_abi::<AllJoynBusObject>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn CreateWithBusAttachment<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, AllJoynBusAttachment>>(objectpath: Param0, busattachment: Param1) -> ::windows::core::Result<AllJoynBusObject> {
Self::IAllJoynBusObjectFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), objectpath.into_param().abi(), busattachment.into_param().abi(), &mut result__).from_abi::<AllJoynBusObject>(result__)
})
}
pub fn IAllJoynBusObjectFactory<R, F: FnOnce(&IAllJoynBusObjectFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynBusObject, IAllJoynBusObjectFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynBusObject {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynBusObject;{e8fd825e-f73a-490c-8804-04e026643047})");
}
unsafe impl ::windows::core::Interface for AllJoynBusObject {
type Vtable = IAllJoynBusObject_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe8fd825e_f73a_490c_8804_04e026643047);
}
impl ::windows::core::RuntimeName for AllJoynBusObject {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynBusObject";
}
impl ::core::convert::From<AllJoynBusObject> for ::windows::core::IUnknown {
fn from(value: AllJoynBusObject) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynBusObject> for ::windows::core::IUnknown {
fn from(value: &AllJoynBusObject) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynBusObject {
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 AllJoynBusObject {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynBusObject> for ::windows::core::IInspectable {
fn from(value: AllJoynBusObject) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynBusObject> for ::windows::core::IInspectable {
fn from(value: &AllJoynBusObject) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynBusObject {
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 AllJoynBusObject {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynBusObject {}
unsafe impl ::core::marker::Sync for AllJoynBusObject {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynBusObjectStoppedEventArgs(pub ::windows::core::IInspectable);
impl AllJoynBusObjectStoppedEventArgs {
#[cfg(feature = "deprecated")]
pub fn Status(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Create(status: i32) -> ::windows::core::Result<AllJoynBusObjectStoppedEventArgs> {
Self::IAllJoynBusObjectStoppedEventArgsFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), status, &mut result__).from_abi::<AllJoynBusObjectStoppedEventArgs>(result__)
})
}
pub fn IAllJoynBusObjectStoppedEventArgsFactory<R, F: FnOnce(&IAllJoynBusObjectStoppedEventArgsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynBusObjectStoppedEventArgs, IAllJoynBusObjectStoppedEventArgsFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynBusObjectStoppedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynBusObjectStoppedEventArgs;{de102115-ef8e-4d42-b93b-a2ae74519766})");
}
unsafe impl ::windows::core::Interface for AllJoynBusObjectStoppedEventArgs {
type Vtable = IAllJoynBusObjectStoppedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xde102115_ef8e_4d42_b93b_a2ae74519766);
}
impl ::windows::core::RuntimeName for AllJoynBusObjectStoppedEventArgs {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynBusObjectStoppedEventArgs";
}
impl ::core::convert::From<AllJoynBusObjectStoppedEventArgs> for ::windows::core::IUnknown {
fn from(value: AllJoynBusObjectStoppedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynBusObjectStoppedEventArgs> for ::windows::core::IUnknown {
fn from(value: &AllJoynBusObjectStoppedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynBusObjectStoppedEventArgs {
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 AllJoynBusObjectStoppedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynBusObjectStoppedEventArgs> for ::windows::core::IInspectable {
fn from(value: AllJoynBusObjectStoppedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynBusObjectStoppedEventArgs> for ::windows::core::IInspectable {
fn from(value: &AllJoynBusObjectStoppedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynBusObjectStoppedEventArgs {
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 AllJoynBusObjectStoppedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynBusObjectStoppedEventArgs {}
unsafe impl ::core::marker::Sync for AllJoynBusObjectStoppedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynCredentials(pub ::windows::core::IInspectable);
impl AllJoynCredentials {
#[cfg(feature = "deprecated")]
pub fn AuthenticationMechanism(&self) -> ::windows::core::Result<AllJoynAuthenticationMechanism> {
let this = self;
unsafe {
let mut result__: AllJoynAuthenticationMechanism = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AllJoynAuthenticationMechanism>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Security_Cryptography_Certificates")]
pub fn Certificate(&self) -> ::windows::core::Result<super::super::Security::Cryptography::Certificates::Certificate> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Security::Cryptography::Certificates::Certificate>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Security_Cryptography_Certificates")]
pub fn SetCertificate<'a, Param0: ::windows::core::IntoParam<'a, super::super::Security::Cryptography::Certificates::Certificate>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Security_Credentials")]
pub fn PasswordCredential(&self) -> ::windows::core::Result<super::super::Security::Credentials::PasswordCredential> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Security::Credentials::PasswordCredential>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Security_Credentials")]
pub fn SetPasswordCredential<'a, Param0: ::windows::core::IntoParam<'a, super::super::Security::Credentials::PasswordCredential>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn Timeout(&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).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SetTimeout<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynCredentials {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynCredentials;{824650f2-a190-40b1-abab-349ec244dfaa})");
}
unsafe impl ::windows::core::Interface for AllJoynCredentials {
type Vtable = IAllJoynCredentials_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x824650f2_a190_40b1_abab_349ec244dfaa);
}
impl ::windows::core::RuntimeName for AllJoynCredentials {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynCredentials";
}
impl ::core::convert::From<AllJoynCredentials> for ::windows::core::IUnknown {
fn from(value: AllJoynCredentials) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynCredentials> for ::windows::core::IUnknown {
fn from(value: &AllJoynCredentials) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynCredentials {
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 AllJoynCredentials {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynCredentials> for ::windows::core::IInspectable {
fn from(value: AllJoynCredentials) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynCredentials> for ::windows::core::IInspectable {
fn from(value: &AllJoynCredentials) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynCredentials {
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 AllJoynCredentials {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynCredentials {}
unsafe impl ::core::marker::Sync for AllJoynCredentials {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynCredentialsRequestedEventArgs(pub ::windows::core::IInspectable);
impl AllJoynCredentialsRequestedEventArgs {
#[cfg(feature = "deprecated")]
pub fn AttemptCount(&self) -> ::windows::core::Result<u16> {
let this = self;
unsafe {
let mut result__: u16 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u16>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Credentials(&self) -> ::windows::core::Result<AllJoynCredentials> {
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::<AllJoynCredentials>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn PeerUniqueName(&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).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn RequestedUserName(&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).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::Foundation::Deferral> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Deferral>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynCredentialsRequestedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynCredentialsRequestedEventArgs;{6a87e34e-b069-4b80-9e1a-41bc837c65d2})");
}
unsafe impl ::windows::core::Interface for AllJoynCredentialsRequestedEventArgs {
type Vtable = IAllJoynCredentialsRequestedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6a87e34e_b069_4b80_9e1a_41bc837c65d2);
}
impl ::windows::core::RuntimeName for AllJoynCredentialsRequestedEventArgs {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynCredentialsRequestedEventArgs";
}
impl ::core::convert::From<AllJoynCredentialsRequestedEventArgs> for ::windows::core::IUnknown {
fn from(value: AllJoynCredentialsRequestedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynCredentialsRequestedEventArgs> for ::windows::core::IUnknown {
fn from(value: &AllJoynCredentialsRequestedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynCredentialsRequestedEventArgs {
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 AllJoynCredentialsRequestedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynCredentialsRequestedEventArgs> for ::windows::core::IInspectable {
fn from(value: AllJoynCredentialsRequestedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynCredentialsRequestedEventArgs> for ::windows::core::IInspectable {
fn from(value: &AllJoynCredentialsRequestedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynCredentialsRequestedEventArgs {
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 AllJoynCredentialsRequestedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynCredentialsRequestedEventArgs {}
unsafe impl ::core::marker::Sync for AllJoynCredentialsRequestedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynCredentialsVerificationRequestedEventArgs(pub ::windows::core::IInspectable);
impl AllJoynCredentialsVerificationRequestedEventArgs {
#[cfg(feature = "deprecated")]
pub fn AuthenticationMechanism(&self) -> ::windows::core::Result<AllJoynAuthenticationMechanism> {
let this = self;
unsafe {
let mut result__: AllJoynAuthenticationMechanism = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AllJoynAuthenticationMechanism>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn PeerUniqueName(&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__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Security_Cryptography_Certificates")]
pub fn PeerCertificate(&self) -> ::windows::core::Result<super::super::Security::Cryptography::Certificates::Certificate> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Security::Cryptography::Certificates::Certificate>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Networking_Sockets")]
pub fn PeerCertificateErrorSeverity(&self) -> ::windows::core::Result<super::super::Networking::Sockets::SocketSslErrorSeverity> {
let this = self;
unsafe {
let mut result__: super::super::Networking::Sockets::SocketSslErrorSeverity = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Networking::Sockets::SocketSslErrorSeverity>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation_Collections", feature = "Security_Cryptography_Certificates"))]
pub fn PeerCertificateErrors(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<super::super::Security::Cryptography::Certificates::ChainValidationResult>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<super::super::Security::Cryptography::Certificates::ChainValidationResult>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation_Collections", feature = "Security_Cryptography_Certificates"))]
pub fn PeerIntermediateCertificates(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<super::super::Security::Cryptography::Certificates::Certificate>> {
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::<super::super::Foundation::Collections::IVectorView<super::super::Security::Cryptography::Certificates::Certificate>>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Accept(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::Foundation::Deferral> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Deferral>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynCredentialsVerificationRequestedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynCredentialsVerificationRequestedEventArgs;{800a7612-b805-44af-a2e1-792ab655a2d0})");
}
unsafe impl ::windows::core::Interface for AllJoynCredentialsVerificationRequestedEventArgs {
type Vtable = IAllJoynCredentialsVerificationRequestedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x800a7612_b805_44af_a2e1_792ab655a2d0);
}
impl ::windows::core::RuntimeName for AllJoynCredentialsVerificationRequestedEventArgs {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynCredentialsVerificationRequestedEventArgs";
}
impl ::core::convert::From<AllJoynCredentialsVerificationRequestedEventArgs> for ::windows::core::IUnknown {
fn from(value: AllJoynCredentialsVerificationRequestedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynCredentialsVerificationRequestedEventArgs> for ::windows::core::IUnknown {
fn from(value: &AllJoynCredentialsVerificationRequestedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynCredentialsVerificationRequestedEventArgs {
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 AllJoynCredentialsVerificationRequestedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynCredentialsVerificationRequestedEventArgs> for ::windows::core::IInspectable {
fn from(value: AllJoynCredentialsVerificationRequestedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynCredentialsVerificationRequestedEventArgs> for ::windows::core::IInspectable {
fn from(value: &AllJoynCredentialsVerificationRequestedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynCredentialsVerificationRequestedEventArgs {
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 AllJoynCredentialsVerificationRequestedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynCredentialsVerificationRequestedEventArgs {}
unsafe impl ::core::marker::Sync for AllJoynCredentialsVerificationRequestedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynMessageInfo(pub ::windows::core::IInspectable);
impl AllJoynMessageInfo {
#[cfg(feature = "deprecated")]
pub fn SenderUniqueName(&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).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(senderuniquename: Param0) -> ::windows::core::Result<AllJoynMessageInfo> {
Self::IAllJoynMessageInfoFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), senderuniquename.into_param().abi(), &mut result__).from_abi::<AllJoynMessageInfo>(result__)
})
}
pub fn IAllJoynMessageInfoFactory<R, F: FnOnce(&IAllJoynMessageInfoFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynMessageInfo, IAllJoynMessageInfoFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynMessageInfo {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynMessageInfo;{ff2b0127-2c12-4859-aa3a-c74461ee814c})");
}
unsafe impl ::windows::core::Interface for AllJoynMessageInfo {
type Vtable = IAllJoynMessageInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xff2b0127_2c12_4859_aa3a_c74461ee814c);
}
impl ::windows::core::RuntimeName for AllJoynMessageInfo {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynMessageInfo";
}
impl ::core::convert::From<AllJoynMessageInfo> for ::windows::core::IUnknown {
fn from(value: AllJoynMessageInfo) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynMessageInfo> for ::windows::core::IUnknown {
fn from(value: &AllJoynMessageInfo) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynMessageInfo {
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 AllJoynMessageInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynMessageInfo> for ::windows::core::IInspectable {
fn from(value: AllJoynMessageInfo) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynMessageInfo> for ::windows::core::IInspectable {
fn from(value: &AllJoynMessageInfo) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynMessageInfo {
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 AllJoynMessageInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynMessageInfo {}
unsafe impl ::core::marker::Sync for AllJoynMessageInfo {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynProducerStoppedEventArgs(pub ::windows::core::IInspectable);
impl AllJoynProducerStoppedEventArgs {
#[cfg(feature = "deprecated")]
pub fn Status(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Create(status: i32) -> ::windows::core::Result<AllJoynProducerStoppedEventArgs> {
Self::IAllJoynProducerStoppedEventArgsFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), status, &mut result__).from_abi::<AllJoynProducerStoppedEventArgs>(result__)
})
}
pub fn IAllJoynProducerStoppedEventArgsFactory<R, F: FnOnce(&IAllJoynProducerStoppedEventArgsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynProducerStoppedEventArgs, IAllJoynProducerStoppedEventArgsFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynProducerStoppedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynProducerStoppedEventArgs;{51309770-4937-492d-8080-236439987ceb})");
}
unsafe impl ::windows::core::Interface for AllJoynProducerStoppedEventArgs {
type Vtable = IAllJoynProducerStoppedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x51309770_4937_492d_8080_236439987ceb);
}
impl ::windows::core::RuntimeName for AllJoynProducerStoppedEventArgs {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynProducerStoppedEventArgs";
}
impl ::core::convert::From<AllJoynProducerStoppedEventArgs> for ::windows::core::IUnknown {
fn from(value: AllJoynProducerStoppedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynProducerStoppedEventArgs> for ::windows::core::IUnknown {
fn from(value: &AllJoynProducerStoppedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynProducerStoppedEventArgs {
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 AllJoynProducerStoppedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynProducerStoppedEventArgs> for ::windows::core::IInspectable {
fn from(value: AllJoynProducerStoppedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynProducerStoppedEventArgs> for ::windows::core::IInspectable {
fn from(value: &AllJoynProducerStoppedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynProducerStoppedEventArgs {
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 AllJoynProducerStoppedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynProducerStoppedEventArgs {}
unsafe impl ::core::marker::Sync for AllJoynProducerStoppedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynServiceInfo(pub ::windows::core::IInspectable);
impl AllJoynServiceInfo {
#[cfg(feature = "deprecated")]
pub fn UniqueName(&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).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn ObjectPath(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn SessionPort(&self) -> ::windows::core::Result<u16> {
let this = self;
unsafe {
let mut result__: u16 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u16>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(uniquename: Param0, objectpath: Param1, sessionport: u16) -> ::windows::core::Result<AllJoynServiceInfo> {
Self::IAllJoynServiceInfoFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), uniquename.into_param().abi(), objectpath.into_param().abi(), sessionport, &mut result__).from_abi::<AllJoynServiceInfo>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(deviceid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AllJoynServiceInfo>> {
Self::IAllJoynServiceInfoStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AllJoynServiceInfo>>(result__)
})
}
pub fn IAllJoynServiceInfoFactory<R, F: FnOnce(&IAllJoynServiceInfoFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynServiceInfo, IAllJoynServiceInfoFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IAllJoynServiceInfoStatics<R, F: FnOnce(&IAllJoynServiceInfoStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynServiceInfo, IAllJoynServiceInfoStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynServiceInfo {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynServiceInfo;{4cbe8209-b93e-4182-999b-ddd000f9c575})");
}
unsafe impl ::windows::core::Interface for AllJoynServiceInfo {
type Vtable = IAllJoynServiceInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4cbe8209_b93e_4182_999b_ddd000f9c575);
}
impl ::windows::core::RuntimeName for AllJoynServiceInfo {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynServiceInfo";
}
impl ::core::convert::From<AllJoynServiceInfo> for ::windows::core::IUnknown {
fn from(value: AllJoynServiceInfo) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynServiceInfo> for ::windows::core::IUnknown {
fn from(value: &AllJoynServiceInfo) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynServiceInfo {
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 AllJoynServiceInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynServiceInfo> for ::windows::core::IInspectable {
fn from(value: AllJoynServiceInfo) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynServiceInfo> for ::windows::core::IInspectable {
fn from(value: &AllJoynServiceInfo) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynServiceInfo {
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 AllJoynServiceInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynServiceInfo {}
unsafe impl ::core::marker::Sync for AllJoynServiceInfo {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynServiceInfoRemovedEventArgs(pub ::windows::core::IInspectable);
impl AllJoynServiceInfoRemovedEventArgs {
#[cfg(feature = "deprecated")]
pub fn UniqueName(&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).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(uniquename: Param0) -> ::windows::core::Result<AllJoynServiceInfoRemovedEventArgs> {
Self::IAllJoynServiceInfoRemovedEventArgsFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), uniquename.into_param().abi(), &mut result__).from_abi::<AllJoynServiceInfoRemovedEventArgs>(result__)
})
}
pub fn IAllJoynServiceInfoRemovedEventArgsFactory<R, F: FnOnce(&IAllJoynServiceInfoRemovedEventArgsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynServiceInfoRemovedEventArgs, IAllJoynServiceInfoRemovedEventArgsFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynServiceInfoRemovedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynServiceInfoRemovedEventArgs;{3057a95f-1d3f-41f3-8969-e32792627396})");
}
unsafe impl ::windows::core::Interface for AllJoynServiceInfoRemovedEventArgs {
type Vtable = IAllJoynServiceInfoRemovedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3057a95f_1d3f_41f3_8969_e32792627396);
}
impl ::windows::core::RuntimeName for AllJoynServiceInfoRemovedEventArgs {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynServiceInfoRemovedEventArgs";
}
impl ::core::convert::From<AllJoynServiceInfoRemovedEventArgs> for ::windows::core::IUnknown {
fn from(value: AllJoynServiceInfoRemovedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynServiceInfoRemovedEventArgs> for ::windows::core::IUnknown {
fn from(value: &AllJoynServiceInfoRemovedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynServiceInfoRemovedEventArgs {
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 AllJoynServiceInfoRemovedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynServiceInfoRemovedEventArgs> for ::windows::core::IInspectable {
fn from(value: AllJoynServiceInfoRemovedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynServiceInfoRemovedEventArgs> for ::windows::core::IInspectable {
fn from(value: &AllJoynServiceInfoRemovedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynServiceInfoRemovedEventArgs {
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 AllJoynServiceInfoRemovedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynServiceInfoRemovedEventArgs {}
unsafe impl ::core::marker::Sync for AllJoynServiceInfoRemovedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynSession(pub ::windows::core::IInspectable);
impl AllJoynSession {
#[cfg(feature = "deprecated")]
pub fn Id(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Status(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveMemberAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, uniquename: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<i32>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), uniquename.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<i32>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn MemberAdded<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<AllJoynSession, AllJoynSessionMemberAddedEventArgs>>>(&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).9)(::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 RemoveMemberAdded<'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).10)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn MemberRemoved<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<AllJoynSession, AllJoynSessionMemberRemovedEventArgs>>>(&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).11)(::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 RemoveMemberRemoved<'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).12)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn Lost<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<AllJoynSession, AllJoynSessionLostEventArgs>>>(&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).13)(::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 RemoveLost<'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).14)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn GetFromServiceInfoAsync<'a, Param0: ::windows::core::IntoParam<'a, AllJoynServiceInfo>>(serviceinfo: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AllJoynSession>> {
Self::IAllJoynSessionStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), serviceinfo.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AllJoynSession>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn GetFromServiceInfoAndBusAttachmentAsync<'a, Param0: ::windows::core::IntoParam<'a, AllJoynServiceInfo>, Param1: ::windows::core::IntoParam<'a, AllJoynBusAttachment>>(serviceinfo: Param0, busattachment: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AllJoynSession>> {
Self::IAllJoynSessionStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), serviceinfo.into_param().abi(), busattachment.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AllJoynSession>>(result__)
})
}
pub fn IAllJoynSessionStatics<R, F: FnOnce(&IAllJoynSessionStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynSession, IAllJoynSessionStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynSession {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynSession;{e8d11b0c-c0d4-406c-88a9-a93efa85d4b1})");
}
unsafe impl ::windows::core::Interface for AllJoynSession {
type Vtable = IAllJoynSession_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe8d11b0c_c0d4_406c_88a9_a93efa85d4b1);
}
impl ::windows::core::RuntimeName for AllJoynSession {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynSession";
}
impl ::core::convert::From<AllJoynSession> for ::windows::core::IUnknown {
fn from(value: AllJoynSession) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynSession> for ::windows::core::IUnknown {
fn from(value: &AllJoynSession) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynSession {
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 AllJoynSession {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynSession> for ::windows::core::IInspectable {
fn from(value: AllJoynSession) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynSession> for ::windows::core::IInspectable {
fn from(value: &AllJoynSession) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynSession {
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 AllJoynSession {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynSession {}
unsafe impl ::core::marker::Sync for AllJoynSession {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynSessionJoinedEventArgs(pub ::windows::core::IInspectable);
impl AllJoynSessionJoinedEventArgs {
#[cfg(feature = "deprecated")]
pub fn Session(&self) -> ::windows::core::Result<AllJoynSession> {
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::<AllJoynSession>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, AllJoynSession>>(session: Param0) -> ::windows::core::Result<AllJoynSessionJoinedEventArgs> {
Self::IAllJoynSessionJoinedEventArgsFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), session.into_param().abi(), &mut result__).from_abi::<AllJoynSessionJoinedEventArgs>(result__)
})
}
pub fn IAllJoynSessionJoinedEventArgsFactory<R, F: FnOnce(&IAllJoynSessionJoinedEventArgsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynSessionJoinedEventArgs, IAllJoynSessionJoinedEventArgsFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynSessionJoinedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynSessionJoinedEventArgs;{9e9f5bd0-b5d7-47c5-8dab-b040cc192871})");
}
unsafe impl ::windows::core::Interface for AllJoynSessionJoinedEventArgs {
type Vtable = IAllJoynSessionJoinedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9e9f5bd0_b5d7_47c5_8dab_b040cc192871);
}
impl ::windows::core::RuntimeName for AllJoynSessionJoinedEventArgs {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynSessionJoinedEventArgs";
}
impl ::core::convert::From<AllJoynSessionJoinedEventArgs> for ::windows::core::IUnknown {
fn from(value: AllJoynSessionJoinedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynSessionJoinedEventArgs> for ::windows::core::IUnknown {
fn from(value: &AllJoynSessionJoinedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynSessionJoinedEventArgs {
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 AllJoynSessionJoinedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynSessionJoinedEventArgs> for ::windows::core::IInspectable {
fn from(value: AllJoynSessionJoinedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynSessionJoinedEventArgs> for ::windows::core::IInspectable {
fn from(value: &AllJoynSessionJoinedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynSessionJoinedEventArgs {
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 AllJoynSessionJoinedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynSessionJoinedEventArgs {}
unsafe impl ::core::marker::Sync for AllJoynSessionJoinedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynSessionLostEventArgs(pub ::windows::core::IInspectable);
impl AllJoynSessionLostEventArgs {
#[cfg(feature = "deprecated")]
pub fn Reason(&self) -> ::windows::core::Result<AllJoynSessionLostReason> {
let this = self;
unsafe {
let mut result__: AllJoynSessionLostReason = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AllJoynSessionLostReason>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Create(reason: AllJoynSessionLostReason) -> ::windows::core::Result<AllJoynSessionLostEventArgs> {
Self::IAllJoynSessionLostEventArgsFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), reason, &mut result__).from_abi::<AllJoynSessionLostEventArgs>(result__)
})
}
pub fn IAllJoynSessionLostEventArgsFactory<R, F: FnOnce(&IAllJoynSessionLostEventArgsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynSessionLostEventArgs, IAllJoynSessionLostEventArgsFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynSessionLostEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynSessionLostEventArgs;{e766a48a-8bb8-4954-ae67-d2fa43d1f96b})");
}
unsafe impl ::windows::core::Interface for AllJoynSessionLostEventArgs {
type Vtable = IAllJoynSessionLostEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe766a48a_8bb8_4954_ae67_d2fa43d1f96b);
}
impl ::windows::core::RuntimeName for AllJoynSessionLostEventArgs {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynSessionLostEventArgs";
}
impl ::core::convert::From<AllJoynSessionLostEventArgs> for ::windows::core::IUnknown {
fn from(value: AllJoynSessionLostEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynSessionLostEventArgs> for ::windows::core::IUnknown {
fn from(value: &AllJoynSessionLostEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynSessionLostEventArgs {
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 AllJoynSessionLostEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynSessionLostEventArgs> for ::windows::core::IInspectable {
fn from(value: AllJoynSessionLostEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynSessionLostEventArgs> for ::windows::core::IInspectable {
fn from(value: &AllJoynSessionLostEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynSessionLostEventArgs {
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 AllJoynSessionLostEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynSessionLostEventArgs {}
unsafe impl ::core::marker::Sync for AllJoynSessionLostEventArgs {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct AllJoynSessionLostReason(pub i32);
impl AllJoynSessionLostReason {
pub const None: AllJoynSessionLostReason = AllJoynSessionLostReason(0i32);
pub const ProducerLeftSession: AllJoynSessionLostReason = AllJoynSessionLostReason(1i32);
pub const ProducerClosedAbruptly: AllJoynSessionLostReason = AllJoynSessionLostReason(2i32);
pub const RemovedByProducer: AllJoynSessionLostReason = AllJoynSessionLostReason(3i32);
pub const LinkTimeout: AllJoynSessionLostReason = AllJoynSessionLostReason(4i32);
pub const Other: AllJoynSessionLostReason = AllJoynSessionLostReason(5i32);
}
impl ::core::convert::From<i32> for AllJoynSessionLostReason {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for AllJoynSessionLostReason {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for AllJoynSessionLostReason {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.AllJoyn.AllJoynSessionLostReason;i4)");
}
impl ::windows::core::DefaultType for AllJoynSessionLostReason {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynSessionMemberAddedEventArgs(pub ::windows::core::IInspectable);
impl AllJoynSessionMemberAddedEventArgs {
#[cfg(feature = "deprecated")]
pub fn UniqueName(&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).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(uniquename: Param0) -> ::windows::core::Result<AllJoynSessionMemberAddedEventArgs> {
Self::IAllJoynSessionMemberAddedEventArgsFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), uniquename.into_param().abi(), &mut result__).from_abi::<AllJoynSessionMemberAddedEventArgs>(result__)
})
}
pub fn IAllJoynSessionMemberAddedEventArgsFactory<R, F: FnOnce(&IAllJoynSessionMemberAddedEventArgsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynSessionMemberAddedEventArgs, IAllJoynSessionMemberAddedEventArgsFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynSessionMemberAddedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynSessionMemberAddedEventArgs;{49a2798a-0dd1-46c1-9cd6-27190e503a5e})");
}
unsafe impl ::windows::core::Interface for AllJoynSessionMemberAddedEventArgs {
type Vtable = IAllJoynSessionMemberAddedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x49a2798a_0dd1_46c1_9cd6_27190e503a5e);
}
impl ::windows::core::RuntimeName for AllJoynSessionMemberAddedEventArgs {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynSessionMemberAddedEventArgs";
}
impl ::core::convert::From<AllJoynSessionMemberAddedEventArgs> for ::windows::core::IUnknown {
fn from(value: AllJoynSessionMemberAddedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynSessionMemberAddedEventArgs> for ::windows::core::IUnknown {
fn from(value: &AllJoynSessionMemberAddedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynSessionMemberAddedEventArgs {
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 AllJoynSessionMemberAddedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynSessionMemberAddedEventArgs> for ::windows::core::IInspectable {
fn from(value: AllJoynSessionMemberAddedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynSessionMemberAddedEventArgs> for ::windows::core::IInspectable {
fn from(value: &AllJoynSessionMemberAddedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynSessionMemberAddedEventArgs {
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 AllJoynSessionMemberAddedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynSessionMemberAddedEventArgs {}
unsafe impl ::core::marker::Sync for AllJoynSessionMemberAddedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynSessionMemberRemovedEventArgs(pub ::windows::core::IInspectable);
impl AllJoynSessionMemberRemovedEventArgs {
#[cfg(feature = "deprecated")]
pub fn UniqueName(&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).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(uniquename: Param0) -> ::windows::core::Result<AllJoynSessionMemberRemovedEventArgs> {
Self::IAllJoynSessionMemberRemovedEventArgsFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), uniquename.into_param().abi(), &mut result__).from_abi::<AllJoynSessionMemberRemovedEventArgs>(result__)
})
}
pub fn IAllJoynSessionMemberRemovedEventArgsFactory<R, F: FnOnce(&IAllJoynSessionMemberRemovedEventArgsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynSessionMemberRemovedEventArgs, IAllJoynSessionMemberRemovedEventArgsFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynSessionMemberRemovedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynSessionMemberRemovedEventArgs;{409a219f-aa4a-4893-b430-baa1b63c6219})");
}
unsafe impl ::windows::core::Interface for AllJoynSessionMemberRemovedEventArgs {
type Vtable = IAllJoynSessionMemberRemovedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x409a219f_aa4a_4893_b430_baa1b63c6219);
}
impl ::windows::core::RuntimeName for AllJoynSessionMemberRemovedEventArgs {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynSessionMemberRemovedEventArgs";
}
impl ::core::convert::From<AllJoynSessionMemberRemovedEventArgs> for ::windows::core::IUnknown {
fn from(value: AllJoynSessionMemberRemovedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynSessionMemberRemovedEventArgs> for ::windows::core::IUnknown {
fn from(value: &AllJoynSessionMemberRemovedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynSessionMemberRemovedEventArgs {
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 AllJoynSessionMemberRemovedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynSessionMemberRemovedEventArgs> for ::windows::core::IInspectable {
fn from(value: AllJoynSessionMemberRemovedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynSessionMemberRemovedEventArgs> for ::windows::core::IInspectable {
fn from(value: &AllJoynSessionMemberRemovedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynSessionMemberRemovedEventArgs {
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 AllJoynSessionMemberRemovedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynSessionMemberRemovedEventArgs {}
unsafe impl ::core::marker::Sync for AllJoynSessionMemberRemovedEventArgs {}
pub struct AllJoynStatus {}
impl AllJoynStatus {
#[cfg(feature = "deprecated")]
pub fn Ok() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn Fail() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn OperationTimedOut() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| 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 OtherEndClosed() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| 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")]
pub fn ConnectionRefused() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn AuthenticationFailed() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn AuthenticationRejectedByUser() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn SslConnectFailed() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn SslIdentityVerificationFailed() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn InsufficientSecurity() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn InvalidArgument1() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn InvalidArgument2() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn InvalidArgument3() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn InvalidArgument4() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn InvalidArgument5() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn InvalidArgument6() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn InvalidArgument7() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn InvalidArgument8() -> ::windows::core::Result<i32> {
Self::IAllJoynStatusStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
pub fn IAllJoynStatusStatics<R, F: FnOnce(&IAllJoynStatusStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynStatus, IAllJoynStatusStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for AllJoynStatus {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynStatus";
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct AllJoynTrafficType(pub i32);
impl AllJoynTrafficType {
pub const Unknown: AllJoynTrafficType = AllJoynTrafficType(0i32);
pub const Messages: AllJoynTrafficType = AllJoynTrafficType(1i32);
pub const RawUnreliable: AllJoynTrafficType = AllJoynTrafficType(2i32);
pub const RawReliable: AllJoynTrafficType = AllJoynTrafficType(4i32);
}
impl ::core::convert::From<i32> for AllJoynTrafficType {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for AllJoynTrafficType {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for AllJoynTrafficType {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.AllJoyn.AllJoynTrafficType;i4)");
}
impl ::windows::core::DefaultType for AllJoynTrafficType {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AllJoynWatcherStoppedEventArgs(pub ::windows::core::IInspectable);
impl AllJoynWatcherStoppedEventArgs {
#[cfg(feature = "deprecated")]
pub fn Status(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Create(status: i32) -> ::windows::core::Result<AllJoynWatcherStoppedEventArgs> {
Self::IAllJoynWatcherStoppedEventArgsFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), status, &mut result__).from_abi::<AllJoynWatcherStoppedEventArgs>(result__)
})
}
pub fn IAllJoynWatcherStoppedEventArgsFactory<R, F: FnOnce(&IAllJoynWatcherStoppedEventArgsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AllJoynWatcherStoppedEventArgs, IAllJoynWatcherStoppedEventArgsFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AllJoynWatcherStoppedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.AllJoyn.AllJoynWatcherStoppedEventArgs;{c9fca03b-701d-4aa8-97dd-a2bb0a8f5fa3})");
}
unsafe impl ::windows::core::Interface for AllJoynWatcherStoppedEventArgs {
type Vtable = IAllJoynWatcherStoppedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc9fca03b_701d_4aa8_97dd_a2bb0a8f5fa3);
}
impl ::windows::core::RuntimeName for AllJoynWatcherStoppedEventArgs {
const NAME: &'static str = "Windows.Devices.AllJoyn.AllJoynWatcherStoppedEventArgs";
}
impl ::core::convert::From<AllJoynWatcherStoppedEventArgs> for ::windows::core::IUnknown {
fn from(value: AllJoynWatcherStoppedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AllJoynWatcherStoppedEventArgs> for ::windows::core::IUnknown {
fn from(value: &AllJoynWatcherStoppedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AllJoynWatcherStoppedEventArgs {
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 AllJoynWatcherStoppedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AllJoynWatcherStoppedEventArgs> for ::windows::core::IInspectable {
fn from(value: AllJoynWatcherStoppedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AllJoynWatcherStoppedEventArgs> for ::windows::core::IInspectable {
fn from(value: &AllJoynWatcherStoppedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AllJoynWatcherStoppedEventArgs {
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 AllJoynWatcherStoppedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AllJoynWatcherStoppedEventArgs {}
unsafe impl ::core::marker::Sync for AllJoynWatcherStoppedEventArgs {}
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynAboutData(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynAboutData {
type Vtable = IAllJoynAboutData_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe5a9bf00_1fa2_4839_93ef_f9df404890f7);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynAboutData_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 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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::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")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::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, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::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,
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, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::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,
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, value: ::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, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::GUID) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynAboutDataView(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynAboutDataView {
type Vtable = IAllJoynAboutDataView_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6823111f_6212_4934_9c48_e19ca4984288);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynAboutDataView_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 i32) -> ::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,
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 ::windows::core::GUID) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Globalization")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Globalization"))] 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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation_Collections", feature = "Globalization"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Globalization")))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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 IAllJoynAboutDataViewStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynAboutDataViewStatics {
type Vtable = IAllJoynAboutDataViewStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x57edb688_0c5e_416e_88b5_39b32d25c47d);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynAboutDataViewStatics_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, uniquename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, busattachment: ::windows::core::RawPtr, sessionport: u16, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation", feature = "Globalization"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uniquename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, busattachment: ::windows::core::RawPtr, sessionport: u16, language: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Globalization")))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAllJoynAcceptSessionJoiner(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynAcceptSessionJoiner {
type Vtable = IAllJoynAcceptSessionJoiner_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4da817d2_cd1d_4023_a7c4_16def89c28df);
}
impl IAllJoynAcceptSessionJoiner {
#[cfg(feature = "deprecated")]
pub fn Accept(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IAllJoynAcceptSessionJoiner {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{4da817d2-cd1d-4023-a7c4-16def89c28df}");
}
impl ::core::convert::From<IAllJoynAcceptSessionJoiner> for ::windows::core::IUnknown {
fn from(value: IAllJoynAcceptSessionJoiner) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IAllJoynAcceptSessionJoiner> for ::windows::core::IUnknown {
fn from(value: &IAllJoynAcceptSessionJoiner) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAllJoynAcceptSessionJoiner {
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 IAllJoynAcceptSessionJoiner {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IAllJoynAcceptSessionJoiner> for ::windows::core::IInspectable {
fn from(value: IAllJoynAcceptSessionJoiner) -> Self {
value.0
}
}
impl ::core::convert::From<&IAllJoynAcceptSessionJoiner> for ::windows::core::IInspectable {
fn from(value: &IAllJoynAcceptSessionJoiner) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IAllJoynAcceptSessionJoiner {
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 IAllJoynAcceptSessionJoiner {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynAcceptSessionJoiner_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) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynAcceptSessionJoinerEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynAcceptSessionJoinerEventArgs {
type Vtable = IAllJoynAcceptSessionJoinerEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4efb5365_3e8a_4257_8f10_539ce0d56c0f);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynAcceptSessionJoinerEventArgs_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 u16) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut AllJoynTrafficType) -> ::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) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynAcceptSessionJoinerEventArgsFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynAcceptSessionJoinerEventArgsFactory {
type Vtable = IAllJoynAcceptSessionJoinerEventArgsFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb4435bc0_6145_429e_84db_d5bfe772b14f);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynAcceptSessionJoinerEventArgsFactory_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, uniquename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessionport: u16, traffictype: AllJoynTrafficType, proximity: u8, acceptsessionjoiner: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynAuthenticationCompleteEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynAuthenticationCompleteEventArgs {
type Vtable = IAllJoynAuthenticationCompleteEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x97b4701c_15dc_4b53_b6a4_7d134300d7bf);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynAuthenticationCompleteEventArgs_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 AllJoynAuthenticationMechanism) -> ::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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynBusAttachment(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynBusAttachment {
type Vtable = IAllJoynBusAttachment_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf309f153_1eed_42c3_a20e_436d41fe62f6);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynBusAttachment_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,
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 AllJoynBusAttachmentState) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uniquename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] 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,
#[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_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")] 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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynBusAttachment2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynBusAttachment2 {
type Vtable = IAllJoynBusAttachment2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3474cb1e_2368_43b2_b43e_6a3ac1278d98);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynBusAttachment2_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, serviceinfo: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation", feature = "Globalization"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, serviceinfo: ::windows::core::RawPtr, language: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Globalization")))] 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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynBusAttachmentFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynBusAttachmentFactory {
type Vtable = IAllJoynBusAttachmentFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x642ef1a4_ad85_4ddf_90ae_604452b22288);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynBusAttachmentFactory_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, connectionspecification: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynBusAttachmentStateChangedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynBusAttachmentStateChangedEventArgs {
type Vtable = IAllJoynBusAttachmentStateChangedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd82e75f4_c02a_41ec_a8d5_eab1558953aa);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynBusAttachmentStateChangedEventArgs_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 AllJoynBusAttachmentState) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynBusAttachmentStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynBusAttachmentStatics {
type Vtable = IAllJoynBusAttachmentStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x839d4d3d_1051_40d7_872a_8d0141115b1f);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynBusAttachmentStatics_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 = "Devices_Enumeration", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, requiredinterfaces: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Devices_Enumeration", feature = "Foundation_Collections")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynBusObject(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynBusObject {
type Vtable = IAllJoynBusObject_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe8fd825e_f73a_490c_8804_04e026643047);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynBusObject_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) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, producer: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynBusObjectFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynBusObjectFactory {
type Vtable = IAllJoynBusObjectFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2c2f9f0b_8e02_4f9c_ac27_ea6dad5d3b50);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynBusObjectFactory_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, objectpath: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, objectpath: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, busattachment: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynBusObjectStoppedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynBusObjectStoppedEventArgs {
type Vtable = IAllJoynBusObjectStoppedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xde102115_ef8e_4d42_b93b_a2ae74519766);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynBusObjectStoppedEventArgs_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 i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynBusObjectStoppedEventArgsFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynBusObjectStoppedEventArgsFactory {
type Vtable = IAllJoynBusObjectStoppedEventArgsFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6b22fd48_d0a3_4255_953a_4772b4028073);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynBusObjectStoppedEventArgsFactory_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, status: i32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynCredentials(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynCredentials {
type Vtable = IAllJoynCredentials_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x824650f2_a190_40b1_abab_349ec244dfaa);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynCredentials_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 AllJoynAuthenticationMechanism) -> ::windows::core::HRESULT,
#[cfg(feature = "Security_Cryptography_Certificates")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Security_Cryptography_Certificates"))] usize,
#[cfg(feature = "Security_Cryptography_Certificates")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Security_Cryptography_Certificates"))] usize,
#[cfg(feature = "Security_Credentials")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Security_Credentials"))] usize,
#[cfg(feature = "Security_Credentials")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Security_Credentials"))] usize,
#[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,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynCredentialsRequestedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynCredentialsRequestedEventArgs {
type Vtable = IAllJoynCredentialsRequestedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6a87e34e_b069_4b80_9e1a_41bc837c65d2);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynCredentialsRequestedEventArgs_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 u16) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, 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,
#[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 IAllJoynCredentialsVerificationRequestedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynCredentialsVerificationRequestedEventArgs {
type Vtable = IAllJoynCredentialsVerificationRequestedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x800a7612_b805_44af_a2e1_792ab655a2d0);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynCredentialsVerificationRequestedEventArgs_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 AllJoynAuthenticationMechanism) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Security_Cryptography_Certificates")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Security_Cryptography_Certificates"))] usize,
#[cfg(feature = "Networking_Sockets")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Networking::Sockets::SocketSslErrorSeverity) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Networking_Sockets"))] usize,
#[cfg(all(feature = "Foundation_Collections", feature = "Security_Cryptography_Certificates"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Security_Cryptography_Certificates")))] usize,
#[cfg(all(feature = "Foundation_Collections", feature = "Security_Cryptography_Certificates"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Security_Cryptography_Certificates")))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynMessageInfo(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynMessageInfo {
type Vtable = IAllJoynMessageInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xff2b0127_2c12_4859_aa3a_c74461ee814c);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynMessageInfo_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 IAllJoynMessageInfoFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynMessageInfoFactory {
type Vtable = IAllJoynMessageInfoFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x34664c2a_8289_43d4_b4a8_3f4de359f043);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynMessageInfoFactory_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, senderuniquename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IAllJoynProducer(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynProducer {
type Vtable = IAllJoynProducer_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9d084679_469b_495a_a710_ac50f123069f);
}
impl IAllJoynProducer {
#[cfg(feature = "deprecated")]
pub fn SetBusObject<'a, Param0: ::windows::core::IntoParam<'a, AllJoynBusObject>>(&self, busobject: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), busobject.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IAllJoynProducer {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{9d084679-469b-495a-a710-ac50f123069f}");
}
impl ::core::convert::From<IAllJoynProducer> for ::windows::core::IUnknown {
fn from(value: IAllJoynProducer) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IAllJoynProducer> for ::windows::core::IUnknown {
fn from(value: &IAllJoynProducer) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IAllJoynProducer {
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 IAllJoynProducer {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IAllJoynProducer> for ::windows::core::IInspectable {
fn from(value: IAllJoynProducer) -> Self {
value.0
}
}
impl ::core::convert::From<&IAllJoynProducer> for ::windows::core::IInspectable {
fn from(value: &IAllJoynProducer) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IAllJoynProducer {
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 IAllJoynProducer {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynProducer_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, busobject: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynProducerStoppedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynProducerStoppedEventArgs {
type Vtable = IAllJoynProducerStoppedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x51309770_4937_492d_8080_236439987ceb);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynProducerStoppedEventArgs_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 i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynProducerStoppedEventArgsFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynProducerStoppedEventArgsFactory {
type Vtable = IAllJoynProducerStoppedEventArgsFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x56529961_b219_4d6e_9f78_fa3f99fa8fe5);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynProducerStoppedEventArgsFactory_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, status: i32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynServiceInfo(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynServiceInfo {
type Vtable = IAllJoynServiceInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4cbe8209_b93e_4182_999b_ddd000f9c575);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynServiceInfo_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 u16) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynServiceInfoFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynServiceInfoFactory {
type Vtable = IAllJoynServiceInfoFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7581dabd_fe03_4f4b_94a4_f02fdcbd11b8);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynServiceInfoFactory_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, uniquename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, objectpath: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessionport: u16, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynServiceInfoRemovedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynServiceInfoRemovedEventArgs {
type Vtable = IAllJoynServiceInfoRemovedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3057a95f_1d3f_41f3_8969_e32792627396);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynServiceInfoRemovedEventArgs_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 IAllJoynServiceInfoRemovedEventArgsFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynServiceInfoRemovedEventArgsFactory {
type Vtable = IAllJoynServiceInfoRemovedEventArgsFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0dbf8627_9aff_4955_9227_6953baf41569);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynServiceInfoRemovedEventArgsFactory_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, uniquename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynServiceInfoStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynServiceInfoStatics {
type Vtable = IAllJoynServiceInfoStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5678570a_603a_49fc_b750_0ef13609213c);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynServiceInfoStatics_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, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynSession(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynSession {
type Vtable = IAllJoynSession_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe8d11b0c_c0d4_406c_88a9_a93efa85d4b1);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynSession_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 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, uniquename: ::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, 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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynSessionJoinedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynSessionJoinedEventArgs {
type Vtable = IAllJoynSessionJoinedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9e9f5bd0_b5d7_47c5_8dab_b040cc192871);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynSessionJoinedEventArgs_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 IAllJoynSessionJoinedEventArgsFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynSessionJoinedEventArgsFactory {
type Vtable = IAllJoynSessionJoinedEventArgsFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6824d689_d6cb_4d9e_a09e_35806870b17f);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynSessionJoinedEventArgsFactory_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, session: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynSessionLostEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynSessionLostEventArgs {
type Vtable = IAllJoynSessionLostEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe766a48a_8bb8_4954_ae67_d2fa43d1f96b);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynSessionLostEventArgs_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 AllJoynSessionLostReason) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynSessionLostEventArgsFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynSessionLostEventArgsFactory {
type Vtable = IAllJoynSessionLostEventArgsFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x13bbfd32_d2f4_49c9_980e_2805e13586b1);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynSessionLostEventArgsFactory_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, reason: AllJoynSessionLostReason, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynSessionMemberAddedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynSessionMemberAddedEventArgs {
type Vtable = IAllJoynSessionMemberAddedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x49a2798a_0dd1_46c1_9cd6_27190e503a5e);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynSessionMemberAddedEventArgs_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 IAllJoynSessionMemberAddedEventArgsFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynSessionMemberAddedEventArgsFactory {
type Vtable = IAllJoynSessionMemberAddedEventArgsFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x341de352_1d33_40a1_a1d3_e5777020e1f1);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynSessionMemberAddedEventArgsFactory_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, uniquename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynSessionMemberRemovedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynSessionMemberRemovedEventArgs {
type Vtable = IAllJoynSessionMemberRemovedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x409a219f_aa4a_4893_b430_baa1b63c6219);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynSessionMemberRemovedEventArgs_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 IAllJoynSessionMemberRemovedEventArgsFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynSessionMemberRemovedEventArgsFactory {
type Vtable = IAllJoynSessionMemberRemovedEventArgsFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc4d355e8_42b8_4b67_b757_d0cfcad59280);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynSessionMemberRemovedEventArgsFactory_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, uniquename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynSessionStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynSessionStatics {
type Vtable = IAllJoynSessionStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9e05d604_a06c_46d4_b46c_0b0b54105b44);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynSessionStatics_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, serviceinfo: ::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, serviceinfo: ::windows::core::RawPtr, busattachment: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynStatusStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynStatusStatics {
type Vtable = IAllJoynStatusStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd0b7a17e_0d29_4da9_8ac6_54c554bedbc5);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynStatusStatics_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 i32) -> ::windows::core::HRESULT,
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,
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,
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,
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,
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,
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,
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,
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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynWatcherStoppedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynWatcherStoppedEventArgs {
type Vtable = IAllJoynWatcherStoppedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc9fca03b_701d_4aa8_97dd_a2bb0a8f5fa3);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynWatcherStoppedEventArgs_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 i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAllJoynWatcherStoppedEventArgsFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAllJoynWatcherStoppedEventArgsFactory {
type Vtable = IAllJoynWatcherStoppedEventArgsFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x878fa5a8_2d50_47e1_904a_20bf0d48c782);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAllJoynWatcherStoppedEventArgsFactory_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, status: i32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
|
#![allow(non_snake_case)]
use core::convert::TryInto;
use test_winrt_signatures::*;
use windows::core::*;
use Component::Signatures::*;
#[implement(Component::Signatures::ITestInt16)]
struct RustTest();
impl RustTest {
fn SignatureInt16(&self, a: i16, b: &mut i16) -> Result<i16> {
*b = a;
Ok(a)
}
fn ArraySignatureInt16(&self, a: &[i16], b: &mut [i16], c: &mut Array<i16>) -> Result<Array<i16>> {
assert!(a.len() == b.len());
assert!(c.is_empty());
b.copy_from_slice(a);
*c = Array::from_slice(a);
Ok(Array::from_slice(a))
}
fn CallSignatureInt16(&self, handler: &Option<SignatureInt16>) -> Result<()> {
let a = 123;
let mut b = 0;
// TODO: this seems rather verbose...
let c = handler.as_ref().unwrap().Invoke(a, &mut b)?;
assert!(a == b);
assert!(a == c);
Ok(())
}
fn CallArraySignatureInt16(&self, handler: &Option<ArraySignatureInt16>) -> Result<()> {
let a = [1, 2, 3];
let mut b = [0; 3];
let mut c = Array::new();
let d = handler.as_ref().unwrap().Invoke(&a, &mut b, &mut c)?;
assert!(a == b);
// TODO: should `a == c` be sufficient? Does that work for Vec?
assert!(a == c[..]);
assert!(a == d[..]);
Ok(())
}
}
fn test_interface(test: &ITestInt16) -> Result<()> {
let a = 123;
let mut b = 0;
let c = test.SignatureInt16(a, &mut b)?;
assert!(a == b);
assert!(a == c);
test.CallSignatureInt16(SignatureInt16::new(|a, b| {
*b = a;
Ok(a)
}))?;
let a = [4, 5, 6];
let mut b = [0; 3];
let mut c = Array::new();
let d = test.ArraySignatureInt16(&a, &mut b, &mut c)?;
assert!(a == b);
assert!(a == c[..]);
assert!(a == d[..]);
test.CallArraySignatureInt16(ArraySignatureInt16::new(|a, b, c| {
assert!(a.len() == b.len());
assert!(c.is_empty());
b.copy_from_slice(a);
*c = Array::from_slice(a);
Ok(Array::from_slice(a))
}))?;
Ok(())
}
#[test]
fn test() -> Result<()> {
test_interface(&Test::new()?.try_into()?)?;
test_interface(&RustTest().into())?;
Ok(())
}
|
use super::super::client::SendClientRPC;
use super::super::common_rpc_types::{GraphCommonArgs, NodeName, ShellStartCodeChainRequest, UpdateCodeChainRequest};
use super::super::router::Router;
use super::super::rpc::{response, RPCError, RPCResponse};
use super::types::{
Context, DashboardGetNetworkResponse, DashboardNode, GraphNetworkOutAllAVGResponse, GraphNetworkOutAllResponse,
GraphNetworkOutNodeExtensionResponse, GraphNetworkOutNodePeerResponse, LogGetRequest, LogGetResponse,
LogGetTargetsResponse, NodeConnection, NodeGetInfoResponse,
};
pub fn add_routing(router: &mut Router<Context>) {
router.add_route("ping", Box::new(ping as fn(Context) -> RPCResponse<String>));
router.add_route(
"node_getInfo",
Box::new(node_get_info as fn(Context, (String,)) -> RPCResponse<NodeGetInfoResponse>),
);
router.add_route(
"dashboard_getNetwork",
Box::new(dashboard_get_network as fn(Context) -> RPCResponse<DashboardGetNetworkResponse>),
);
router.add_route(
"node_start",
Box::new(node_start as fn(Context, (String, ShellStartCodeChainRequest)) -> RPCResponse<()>),
);
router.add_route("node_stop", Box::new(node_stop as fn(Context, (String,)) -> RPCResponse<()>));
router.add_route(
"node_update",
Box::new(node_update as fn(Context, (NodeName, UpdateCodeChainRequest)) -> RPCResponse<()>),
);
router.add_route("log_getTargets", Box::new(log_get_targets as fn(Context) -> RPCResponse<LogGetTargetsResponse>));
router.add_route("log_get", Box::new(log_get as fn(Context, (LogGetRequest,)) -> RPCResponse<LogGetResponse>));
router.add_route(
"graph_network_out_all_node",
Box::new(
graph_network_out_all_node as fn(Context, (GraphCommonArgs,)) -> RPCResponse<GraphNetworkOutAllResponse>,
),
);
router.add_route(
"graph_network_out_all_node_avg",
Box::new(
graph_network_out_all_node_avg
as fn(Context, (GraphCommonArgs,)) -> RPCResponse<GraphNetworkOutAllAVGResponse>,
),
);
router.add_route(
"graph_network_out_node_extension",
Box::new(
graph_network_out_node_extension
as fn(Context, (NodeName, GraphCommonArgs)) -> RPCResponse<GraphNetworkOutNodeExtensionResponse>,
),
);
router.add_route(
"graph_network_out_node_peer",
Box::new(
graph_network_out_node_peer
as fn(Context, (NodeName, GraphCommonArgs)) -> RPCResponse<GraphNetworkOutNodePeerResponse>,
),
);
}
fn ping(_: Context) -> RPCResponse<String> {
response("pong".to_string())
}
fn dashboard_get_network(context: Context) -> RPCResponse<DashboardGetNetworkResponse> {
let clients_state = context.db_service.get_clients_state()?;
let connections = context.db_service.get_connections()?;
let dashboard_nodes = clients_state.iter().map(|client| DashboardNode::from_db_state(client)).collect();
response(DashboardGetNetworkResponse {
nodes: dashboard_nodes,
connections: connections.iter().map(|connection| NodeConnection::from_connection(connection)).collect(),
})
}
fn node_get_info(context: Context, args: (String,)) -> RPCResponse<NodeGetInfoResponse> {
let (name,) = args;
let client_query_result = context.db_service.get_client_query_result(&name)?.ok_or(RPCError::ClientNotFound)?;
let extra = context.db_service.get_client_extra(name)?;
response(NodeGetInfoResponse::from_db_state(&client_query_result, &extra))
}
fn node_start(context: Context, args: (NodeName, ShellStartCodeChainRequest)) -> RPCResponse<()> {
let (name, req) = args;
let client = context.client_service.get_client(&name);
if client.is_none() {
return Err(RPCError::ClientNotFound)
}
let client = client.expect("Already checked");
client.shell_start_codechain(req.clone())?;
context.db_service.save_start_option(name, &req.env, &req.args);
response(())
}
fn node_stop(context: Context, args: (String,)) -> RPCResponse<()> {
let (name,) = args;
let client = context.client_service.get_client(&name);
if client.is_none() {
return Err(RPCError::ClientNotFound)
}
let client = client.expect("Already checked");
client.shell_stop_codechain()?;
response(())
}
fn node_update(context: Context, args: (NodeName, UpdateCodeChainRequest)) -> RPCResponse<()> {
let (name, req) = args;
let client = context.client_service.get_client(&name).ok_or(RPCError::ClientNotFound)?;
let extra = context.db_service.get_client_extra(name)?;
let (env, args) = extra.map(|extra| (extra.prev_env, extra.prev_args)).unwrap_or_default();
client.shell_update_codechain((
ShellStartCodeChainRequest {
env,
args,
},
req,
))?;
response(())
}
fn log_get_targets(context: Context) -> RPCResponse<LogGetTargetsResponse> {
let targets = context.db_service.get_log_targets()?;
response(LogGetTargetsResponse {
targets,
})
}
fn log_get(context: Context, args: (LogGetRequest,)) -> RPCResponse<LogGetResponse> {
let (req,) = args;
let logs = context.db_service.get_logs(req)?;
response(LogGetResponse {
logs,
})
}
fn graph_network_out_all_node(context: Context, args: (GraphCommonArgs,)) -> RPCResponse<GraphNetworkOutAllResponse> {
let (graph_args,) = args;
let rows = context.db_service.get_network_out_all_graph(graph_args)?;
response(GraphNetworkOutAllResponse {
rows,
})
}
fn graph_network_out_all_node_avg(
context: Context,
args: (GraphCommonArgs,),
) -> RPCResponse<GraphNetworkOutAllAVGResponse> {
let (graph_args,) = args;
let rows = context.db_service.get_network_out_all_avg_graph(graph_args)?;
response(GraphNetworkOutAllAVGResponse {
rows,
})
}
fn graph_network_out_node_extension(
context: Context,
args: (NodeName, GraphCommonArgs),
) -> RPCResponse<GraphNetworkOutNodeExtensionResponse> {
let (node_name, graph_args) = args;
let rows = context.db_service.get_network_out_node_extension_graph(node_name, graph_args)?;
response(GraphNetworkOutNodeExtensionResponse {
rows,
})
}
fn graph_network_out_node_peer(
context: Context,
args: (NodeName, GraphCommonArgs),
) -> RPCResponse<GraphNetworkOutNodePeerResponse> {
let (node_name, graph_args) = args;
let rows = context.db_service.get_network_out_node_peer_graph(node_name, graph_args)?;
response(GraphNetworkOutNodePeerResponse {
rows,
})
}
|
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Configuration for shared functions."]
pub cfg: CFG,
#[doc = "0x04 - Status register for Master, Slave, and Monitor functions."]
pub stat: STAT,
#[doc = "0x08 - Interrupt Enable Set and read register."]
pub intenset: INTENSET,
#[doc = "0x0c - Interrupt Enable Clear register."]
pub intenclr: INTENCLR,
#[doc = "0x10 - Time-out value register."]
pub timeout: TIMEOUT,
#[doc = "0x14 - Clock pre-divider for the entire I2C block. This determines what time increments are used for the MSTTIME and SLVTIME registers."]
pub div: DIV,
#[doc = "0x18 - Interrupt Status register for Master, Slave, and Monitor functions."]
pub intstat: INTSTAT,
_reserved0: [u8; 4usize],
#[doc = "0x20 - Master control register."]
pub mstctl: MSTCTL,
#[doc = "0x24 - Master timing configuration."]
pub msttime: MSTTIME,
#[doc = "0x28 - Combined Master receiver and transmitter data register."]
pub mstdat: MSTDAT,
_reserved1: [u8; 20usize],
#[doc = "0x40 - Slave control register."]
pub slvctl: SLVCTL,
#[doc = "0x44 - Combined Slave receiver and transmitter data register."]
pub slvdat: SLVDAT,
#[doc = "0x48 - Slave address 0."]
pub slvadr: [SLVADR; 4],
#[doc = "0x58 - Slave Qualification for address 0."]
pub slvqual0: SLVQUAL0,
_reserved2: [u8; 36usize],
#[doc = "0x80 - Monitor receiver data register."]
pub monrxdat: MONRXDAT,
}
#[doc = "Configuration for shared functions."]
pub struct CFG {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Configuration for shared functions."]
pub mod cfg;
#[doc = "Status register for Master, Slave, and Monitor functions."]
pub struct STAT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Status register for Master, Slave, and Monitor functions."]
pub mod stat;
#[doc = "Interrupt Enable Set and read register."]
pub struct INTENSET {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Interrupt Enable Set and read register."]
pub mod intenset;
#[doc = "Interrupt Enable Clear register."]
pub struct INTENCLR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Interrupt Enable Clear register."]
pub mod intenclr;
#[doc = "Time-out value register."]
pub struct TIMEOUT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Time-out value register."]
pub mod timeout;
#[doc = "Clock pre-divider for the entire I2C block. This determines what time increments are used for the MSTTIME and SLVTIME registers."]
pub struct DIV {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Clock pre-divider for the entire I2C block. This determines what time increments are used for the MSTTIME and SLVTIME registers."]
pub mod div;
#[doc = "Interrupt Status register for Master, Slave, and Monitor functions."]
pub struct INTSTAT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Interrupt Status register for Master, Slave, and Monitor functions."]
pub mod intstat;
#[doc = "Master control register."]
pub struct MSTCTL {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Master control register."]
pub mod mstctl;
#[doc = "Master timing configuration."]
pub struct MSTTIME {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Master timing configuration."]
pub mod msttime;
#[doc = "Combined Master receiver and transmitter data register."]
pub struct MSTDAT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Combined Master receiver and transmitter data register."]
pub mod mstdat;
#[doc = "Slave control register."]
pub struct SLVCTL {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Slave control register."]
pub mod slvctl;
#[doc = "Combined Slave receiver and transmitter data register."]
pub struct SLVDAT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Combined Slave receiver and transmitter data register."]
pub mod slvdat;
#[doc = "Slave address 0."]
pub struct SLVADR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Slave address 0."]
pub mod slvadr;
#[doc = "Slave Qualification for address 0."]
pub struct SLVQUAL0 {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Slave Qualification for address 0."]
pub mod slvqual0;
#[doc = "Monitor receiver data register."]
pub struct MONRXDAT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Monitor receiver data register."]
pub mod monrxdat;
|
//! Grammar-based mutators and related utilties.
//!
//! This module provides a grammar-based `impl Mutator<AST>` which generates an abstract syntax
//! tree satisfying a grammar, created through [`grammar_based_ast_mutator`]. The resulting mutator can be
//! transformed into a `Mutator<(AST, String)>`, where the second element of the tuple is the string corresponding
//! to the abstract syntax tree, by calling [`.with_string()`](ASTMutator::with_string).
//!
//! To specify a grammar, you should use the following functions:
# to create a grammar from a regular expression **(only supported on crate feature `regex_grammar`)**"
)]
//! * [`literal`] for a grammar that matches a single character
//! * [`literal_ranges`] for a grammar matching a single character within a specified ranges
//! * [`literal_ranges`] for a grammar matching a single character within any of multiple ranges
//! * [`alternation`] for a grammar matching any of a list of grammar rules
//! * [`concatenation`] matching multiple grammar rules one after the other
//! * [`repetition`] matching a grammar rule multiple times
//! * [`recursive`] and [`recurse`] to create recursive grammar rules
#![cfg_attr(
feature = "regex_grammar",
doc = r###"
Examples:
```
use fuzzcheck::mutators::grammar::{alternation, concatenation, literal, literal_range, recurse, recursive, regex, repetition};
let rule = repetition(
concatenation([
alternation([
regex("hello[0-9]"),
regex("world[0-9]?")
]),
literal(' '),
]),
1..5
);
/* “rule” matches/generates:
hello1
hello2 hello6 world
world8 hello5 world7 world world
...
*/
let rule = recursive(|rule| {
alternation([
concatenation([
regex(r"\(|\["),
recurse(rule),
regex(r"\)|\]"),
]),
literal_range('a' ..= 'z')
])
});
/* rule matches/generates:
(([a)))
(([[d))])
z
...
*/
```
"###
)]
#![allow(clippy::type_complexity)]
#![allow(clippy::module_inception)]
#![allow(clippy::nonstandard_macro_braces)]
mod ast;
mod grammar;
mod mutators;
#[cfg(feature = "regex_grammar")]
mod regex;
#[doc(inline)]
pub use ast::AST;
#[cfg(feature = "regex_grammar")]
#[doc(inline)]
#[doc(cfg(feature = "regex_grammar"))]
pub use grammar::regex;
#[doc(inline)]
pub use grammar::Grammar;
#[doc(inline)]
pub use grammar::{alternation, concatenation, literal, literal_range, literal_ranges, recurse, recursive, repetition};
#[doc(inline)]
pub use mutators::grammar_based_ast_mutator;
#[doc(inline)]
pub use mutators::ASTMutator;
|
use hex::encode;
use rand::Rng;
pub mod iso {
//! ISO compatible UUID generators
use super::encode;
use super::Rng;
/// Generate UUID following ISO standards
pub fn uuid_v4() -> String {
let bytes = (
encode(rand::thread_rng().gen::<[u8; 4]>()),
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 6]>()),
);
format!(
"{}-{}-4{}-{}-{}",
bytes.0,
bytes.1,
&bytes.2[1..],
bytes.3,
bytes.4
)
}
}
/// Null or Nil UUID special case
pub const NULL_UUID: &str = "00000000-0000-0000-0000-000000000000";
/// Generates 8-byte UUID as a String
pub fn uuid8() -> String {
let bytes = (
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 1]>()),
encode(rand::thread_rng().gen::<[u8; 1]>()),
encode(rand::thread_rng().gen::<[u8; 1]>()),
encode(rand::thread_rng().gen::<[u8; 3]>()),
);
format!(
"{}-{}-{}-{}-{}",
bytes.0, bytes.1, bytes.2, bytes.3, bytes.4
)
}
/// Generates 16-byte UUID as a String
pub fn uuid16() -> String {
let bytes = (
encode(rand::thread_rng().gen::<[u8; 4]>()),
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 2]>()),
encode(rand::thread_rng().gen::<[u8; 6]>()),
);
format!(
"{}-{}-{}-{}-{}",
bytes.0, bytes.1, bytes.2, bytes.3, bytes.4
)
}
/// Generates 32-byte UUID as a String
pub fn uuid32() -> String {
let bytes = (
encode(rand::thread_rng().gen::<[u8; 8]>()),
encode(rand::thread_rng().gen::<[u8; 4]>()),
encode(rand::thread_rng().gen::<[u8; 4]>()),
encode(rand::thread_rng().gen::<[u8; 4]>()),
encode(rand::thread_rng().gen::<[u8; 12]>()),
);
format!(
"{}-{}-{}-{}-{}",
bytes.0, bytes.1, bytes.2, bytes.3, bytes.4
)
}
#[cfg(test)]
#[test]
fn test_uuid8() {
let id: String = uuid8();
// 8 * 2 bytes + 4 dashes
assert_eq!(id.len(), 20);
}
#[test]
fn test_uuid16() {
let id: String = uuid16();
// 16 * 2 bytes + 4 dashes
assert_eq!(id.len(), 36);
}
#[test]
fn test_uuid32() {
let id: String = uuid32();
// 32 * 2 bytes + 4 dashes
assert_eq!(id.len(), 68);
}
#[test]
fn test_iso_uuid_v4() {
use self::iso::uuid_v4;
let iso_v4_uuid = uuid_v4();
assert_eq!(iso_v4_uuid.len(), 36);
assert_eq!(iso_v4_uuid.as_bytes()[14] as char, '4');
}
|
use hyper::{Response, Body, StatusCode};
/// # Forbidden
/// Returns a response payload that indicates a 403 forbidden.
pub(crate) fn forbidden() -> Response<Body> {
match Response::builder()
.status(StatusCode::FORBIDDEN)
.body(Body::from("403 Forbidden"))
{
Ok(response) => response,
Err(_) => internal_server_error(),
}
}
/// # Not Found
/// Returns a response payload that indicates a 404 not found.
pub(crate) fn not_found() -> Response<Body> {
match Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::from("404 Not found"))
{
Ok(response) => response,
Err(_) => internal_server_error(),
}
}
/// # Internal Server Serror
/// Returns a response payload that indicates a 500 internal server error.
pub(crate) fn internal_server_error() -> Response<Body> {
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::from("500 Internal Server Error"))
.unwrap()
}
|
#[path = "../repository/employee_repo.rs"] mod employee_repo;
use employee_repo::*;
use models::*;
use warp::{Filter, Rejection, Reply};
pub fn create_employee_endpoints() -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
let employees = warp::path("employees");
let get_all = employees
.and(warp::get())
.and(warp::path::end())
.map(|| warp::reply::json(&get_all_employees()));
let get_single = employees
.and(warp::get())
.and(warp::path::param::<i32>())
.and(warp::path::end())
.map(|e_id: i32| warp::reply::json(&get_employee(e_id)));
let insert = employees
.and(warp::post())
.and(warp::path::end())
.and(warp::body::json())
.map(|employee: NewEmployee| warp::reply::json(&insert_employee(employee)));
let put = employees
.and(warp::put())
.and(warp::path::end())
.and(warp::body::json())
.map(| employee: Employee | warp::reply::json(&update_employee(employee)));
let delete = employees
.and(warp::delete())
.and(warp::path::param::<i32>())
.and(warp::path::end())
.map(|e_id: i32| warp::reply::json(&delete_employee(e_id)));
return get_all.or(get_single).or(insert).or(put).or(delete)
}
|
//! statusplaybefore1stcard.rs - code flow from this status
//region: use
use crate::gamedata::CardStatusCardFace;
use crate::rootrenderingcomponent::RootRenderingComponent;
use crate::websocketcommunication;
use crate::logmod;
use mem4_common::{GameStatus, WsMessage};
use dodrio::builder::text;
use dodrio::bumpalo::{self, Bump};
use dodrio::Node;
use typed_html::dodrio;
//endregion
///render Play or Wait
pub fn div_click_1st_card<'a, 'bump>(
root_rendering_component: &'a RootRenderingComponent,
bump: &'bump Bump,
) -> Node<'bump>
where
'a: 'bump,
{
if root_rendering_component.game_data.my_player_number
== root_rendering_component.game_data.player_turn
{
dodrio!(bump,
<div >
<h2 id= "ws_elem" style= "color:orange;">
{vec![text(bumpalo::format!(in bump, "Play player{} !", root_rendering_component.game_data.player_turn).into_bump_str())]}
</h2>
</div>
)
} else {
//return wait for the other player
dodrio!(bump,
<h2 id="ws_elem" style= "color:red;">
{vec![text(bumpalo::format!(in bump, "Wait for player{} !", root_rendering_component.game_data.player_turn).into_bump_str())]}
</h2>
)
}
}
//div_grid_container() is in divgridcontainer.rs
/// on click
pub fn on_click_1st_card(rrc: &mut RootRenderingComponent, this_click_card_index: usize) {
logmod::log1_str("on_click_1st_card");
rrc.game_data.card_index_of_first_click = this_click_card_index;
//change card status and game status
card_click_1st_card(rrc);
rrc.check_invalidate_for_all_components();
//region: send WsMessage over WebSocket
websocketcommunication::ws_send_msg(
&rrc.game_data.ws,
&WsMessage::PlayerClick1stCard {
my_ws_uid: rrc.game_data.my_ws_uid,
players: unwrap!(serde_json::to_string(&rrc.game_data.players)),
card_grid_data: unwrap!(serde_json::to_string(&rrc.game_data.card_grid_data)),
game_status: rrc.game_data.game_status.clone(),
card_index_of_first_click: rrc.game_data.card_index_of_first_click,
card_index_of_second_click: rrc.game_data.card_index_of_second_click,
},
);
//endregion
}
///on click
pub fn card_click_1st_card(rrc: &mut RootRenderingComponent) {
logmod::log1_str("card_click_1st_card");
//flip the card up
unwrap!(
rrc.game_data
.card_grid_data
.get_mut(rrc.game_data.card_index_of_first_click),
"error this_click_card_index"
)
.status = CardStatusCardFace::UpTemporary;
rrc.game_data.game_status = GameStatus::PlayBefore2ndCard;
}
///msg player click
pub fn on_msg_player_click_1st_card(
rrc: &mut RootRenderingComponent,
game_status: GameStatus,
card_grid_data: &str,
card_index_of_first_click: usize,
card_index_of_second_click: usize,
) {
logmod::log1_str("on_msg_player_click_1st_card");
rrc.game_data.game_status = game_status;
rrc.game_data.card_grid_data = unwrap!(serde_json::from_str(card_grid_data));
rrc.game_data.card_index_of_first_click = card_index_of_first_click;
rrc.game_data.card_index_of_second_click = card_index_of_second_click;
rrc.check_invalidate_for_all_components();
}
|
/*
Primitive Types--
Integers: u8, i8, u16, i16, u32, i32, u64, i64, u128, i128 (number of bits they take in memory)
Floats: f32, f64
Boolean (bool)
Characters (char)
Tuples
Arrays
*/
// Rust is a statically typed language, which means that it
// must know the types of all variables at compile time.
pub fn run() {
// default = i32;
let x =1;
// default f64;
let y = 2.5;
// add expl type
let z: i64 = 454545;
// find max size
println!("Max i32: {}", std::i32::MAX);
println!("Max i64: {}", std::i64::MAX);
// boolian
let foo:bool = true;
println!("{:?}", (x, y, z, foo));
// expression bool
let is_lower = 10 < 12;
println!("is lower: {}", is_lower);
// unicode char
let a1 = 'a';
let smiley1 = '\u{1F600}';
let smiley2 = '\u{1F916}';
println!("{:?}", (a1, smiley1,smiley2,smiley2,smiley1));
} |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppRecordingManager(pub ::windows::core::IInspectable);
impl AppRecordingManager {
pub fn GetStatus(&self) -> ::windows::core::Result<AppRecordingStatus> {
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::<AppRecordingStatus>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage"))]
pub fn StartRecordingToFileAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::StorageFile>>(&self, file: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AppRecordingResult>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), file.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AppRecordingResult>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage"))]
pub fn RecordTimeSpanToFileAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::DateTime>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>, Param2: ::windows::core::IntoParam<'a, super::super::Storage::StorageFile>>(&self, starttime: Param0, duration: Param1, file: Param2) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AppRecordingResult>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), starttime.into_param().abi(), duration.into_param().abi(), file.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AppRecordingResult>>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn SupportedScreenshotMediaEncodingSubtypes(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage"))]
pub fn SaveScreenshotToFilesAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::StorageFolder>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(
&self,
folder: Param0,
filenameprefix: Param1,
option: AppRecordingSaveScreenshotOption,
requestedformats: Param3,
) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<AppRecordingSaveScreenshotResult>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), folder.into_param().abi(), filenameprefix.into_param().abi(), option, requestedformats.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<AppRecordingSaveScreenshotResult>>(result__)
}
}
pub fn GetDefault() -> ::windows::core::Result<AppRecordingManager> {
Self::IAppRecordingManagerStatics(|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::<AppRecordingManager>(result__)
})
}
pub fn IAppRecordingManagerStatics<R, F: FnOnce(&IAppRecordingManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AppRecordingManager, IAppRecordingManagerStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AppRecordingManager {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.AppRecording.AppRecordingManager;{e7e26076-a044-48e2-a512-3094d574c7cc})");
}
unsafe impl ::windows::core::Interface for AppRecordingManager {
type Vtable = IAppRecordingManager_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe7e26076_a044_48e2_a512_3094d574c7cc);
}
impl ::windows::core::RuntimeName for AppRecordingManager {
const NAME: &'static str = "Windows.Media.AppRecording.AppRecordingManager";
}
impl ::core::convert::From<AppRecordingManager> for ::windows::core::IUnknown {
fn from(value: AppRecordingManager) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppRecordingManager> for ::windows::core::IUnknown {
fn from(value: &AppRecordingManager) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppRecordingManager {
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 AppRecordingManager {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppRecordingManager> for ::windows::core::IInspectable {
fn from(value: AppRecordingManager) -> Self {
value.0
}
}
impl ::core::convert::From<&AppRecordingManager> for ::windows::core::IInspectable {
fn from(value: &AppRecordingManager) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppRecordingManager {
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 AppRecordingManager {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppRecordingManager {}
unsafe impl ::core::marker::Sync for AppRecordingManager {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppRecordingResult(pub ::windows::core::IInspectable);
impl AppRecordingResult {
pub fn Succeeded(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn ExtendedError(&self) -> ::windows::core::Result<::windows::core::HRESULT> {
let this = self;
unsafe {
let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HRESULT>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Duration(&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).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__)
}
}
pub fn IsFileTruncated(&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__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppRecordingResult {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.AppRecording.AppRecordingResult;{3a900864-c66d-46f9-b2d9-5bc2dad070d7})");
}
unsafe impl ::windows::core::Interface for AppRecordingResult {
type Vtable = IAppRecordingResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3a900864_c66d_46f9_b2d9_5bc2dad070d7);
}
impl ::windows::core::RuntimeName for AppRecordingResult {
const NAME: &'static str = "Windows.Media.AppRecording.AppRecordingResult";
}
impl ::core::convert::From<AppRecordingResult> for ::windows::core::IUnknown {
fn from(value: AppRecordingResult) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppRecordingResult> for ::windows::core::IUnknown {
fn from(value: &AppRecordingResult) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppRecordingResult {
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 AppRecordingResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppRecordingResult> for ::windows::core::IInspectable {
fn from(value: AppRecordingResult) -> Self {
value.0
}
}
impl ::core::convert::From<&AppRecordingResult> for ::windows::core::IInspectable {
fn from(value: &AppRecordingResult) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppRecordingResult {
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 AppRecordingResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppRecordingResult {}
unsafe impl ::core::marker::Sync for AppRecordingResult {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct AppRecordingSaveScreenshotOption(pub i32);
impl AppRecordingSaveScreenshotOption {
pub const None: AppRecordingSaveScreenshotOption = AppRecordingSaveScreenshotOption(0i32);
pub const HdrContentVisible: AppRecordingSaveScreenshotOption = AppRecordingSaveScreenshotOption(1i32);
}
impl ::core::convert::From<i32> for AppRecordingSaveScreenshotOption {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for AppRecordingSaveScreenshotOption {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for AppRecordingSaveScreenshotOption {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.AppRecording.AppRecordingSaveScreenshotOption;i4)");
}
impl ::windows::core::DefaultType for AppRecordingSaveScreenshotOption {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppRecordingSaveScreenshotResult(pub ::windows::core::IInspectable);
impl AppRecordingSaveScreenshotResult {
pub fn Succeeded(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn ExtendedError(&self) -> ::windows::core::Result<::windows::core::HRESULT> {
let this = self;
unsafe {
let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HRESULT>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn SavedScreenshotInfos(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<AppRecordingSavedScreenshotInfo>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<AppRecordingSavedScreenshotInfo>>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppRecordingSaveScreenshotResult {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.AppRecording.AppRecordingSaveScreenshotResult;{9c5b8d0a-0abb-4457-aaee-24f9c12ec778})");
}
unsafe impl ::windows::core::Interface for AppRecordingSaveScreenshotResult {
type Vtable = IAppRecordingSaveScreenshotResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9c5b8d0a_0abb_4457_aaee_24f9c12ec778);
}
impl ::windows::core::RuntimeName for AppRecordingSaveScreenshotResult {
const NAME: &'static str = "Windows.Media.AppRecording.AppRecordingSaveScreenshotResult";
}
impl ::core::convert::From<AppRecordingSaveScreenshotResult> for ::windows::core::IUnknown {
fn from(value: AppRecordingSaveScreenshotResult) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppRecordingSaveScreenshotResult> for ::windows::core::IUnknown {
fn from(value: &AppRecordingSaveScreenshotResult) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppRecordingSaveScreenshotResult {
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 AppRecordingSaveScreenshotResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppRecordingSaveScreenshotResult> for ::windows::core::IInspectable {
fn from(value: AppRecordingSaveScreenshotResult) -> Self {
value.0
}
}
impl ::core::convert::From<&AppRecordingSaveScreenshotResult> for ::windows::core::IInspectable {
fn from(value: &AppRecordingSaveScreenshotResult) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppRecordingSaveScreenshotResult {
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 AppRecordingSaveScreenshotResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppRecordingSaveScreenshotResult {}
unsafe impl ::core::marker::Sync for AppRecordingSaveScreenshotResult {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppRecordingSavedScreenshotInfo(pub ::windows::core::IInspectable);
impl AppRecordingSavedScreenshotInfo {
#[cfg(feature = "Storage")]
pub fn File(&self) -> ::windows::core::Result<super::super::Storage::StorageFile> {
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::Storage::StorageFile>(result__)
}
}
pub fn MediaEncodingSubtype(&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 AppRecordingSavedScreenshotInfo {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.AppRecording.AppRecordingSavedScreenshotInfo;{9b642d0a-189a-4d00-bf25-e1bb1249d594})");
}
unsafe impl ::windows::core::Interface for AppRecordingSavedScreenshotInfo {
type Vtable = IAppRecordingSavedScreenshotInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9b642d0a_189a_4d00_bf25_e1bb1249d594);
}
impl ::windows::core::RuntimeName for AppRecordingSavedScreenshotInfo {
const NAME: &'static str = "Windows.Media.AppRecording.AppRecordingSavedScreenshotInfo";
}
impl ::core::convert::From<AppRecordingSavedScreenshotInfo> for ::windows::core::IUnknown {
fn from(value: AppRecordingSavedScreenshotInfo) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppRecordingSavedScreenshotInfo> for ::windows::core::IUnknown {
fn from(value: &AppRecordingSavedScreenshotInfo) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppRecordingSavedScreenshotInfo {
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 AppRecordingSavedScreenshotInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppRecordingSavedScreenshotInfo> for ::windows::core::IInspectable {
fn from(value: AppRecordingSavedScreenshotInfo) -> Self {
value.0
}
}
impl ::core::convert::From<&AppRecordingSavedScreenshotInfo> for ::windows::core::IInspectable {
fn from(value: &AppRecordingSavedScreenshotInfo) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppRecordingSavedScreenshotInfo {
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 AppRecordingSavedScreenshotInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppRecordingSavedScreenshotInfo {}
unsafe impl ::core::marker::Sync for AppRecordingSavedScreenshotInfo {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppRecordingStatus(pub ::windows::core::IInspectable);
impl AppRecordingStatus {
pub fn CanRecord(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn CanRecordTimeSpan(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn HistoricalBufferDuration(&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).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__)
}
}
pub fn Details(&self) -> ::windows::core::Result<AppRecordingStatusDetails> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppRecordingStatusDetails>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppRecordingStatus {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.AppRecording.AppRecordingStatus;{1d0cc82c-bc18-4b8a-a6ef-127efab3b5d9})");
}
unsafe impl ::windows::core::Interface for AppRecordingStatus {
type Vtable = IAppRecordingStatus_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1d0cc82c_bc18_4b8a_a6ef_127efab3b5d9);
}
impl ::windows::core::RuntimeName for AppRecordingStatus {
const NAME: &'static str = "Windows.Media.AppRecording.AppRecordingStatus";
}
impl ::core::convert::From<AppRecordingStatus> for ::windows::core::IUnknown {
fn from(value: AppRecordingStatus) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppRecordingStatus> for ::windows::core::IUnknown {
fn from(value: &AppRecordingStatus) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppRecordingStatus {
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 AppRecordingStatus {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppRecordingStatus> for ::windows::core::IInspectable {
fn from(value: AppRecordingStatus) -> Self {
value.0
}
}
impl ::core::convert::From<&AppRecordingStatus> for ::windows::core::IInspectable {
fn from(value: &AppRecordingStatus) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppRecordingStatus {
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 AppRecordingStatus {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppRecordingStatus {}
unsafe impl ::core::marker::Sync for AppRecordingStatus {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppRecordingStatusDetails(pub ::windows::core::IInspectable);
impl AppRecordingStatusDetails {
pub fn IsAnyAppBroadcasting(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsCaptureResourceUnavailable(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsGameStreamInProgress(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsTimeSpanRecordingDisabled(&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__)
}
}
pub fn IsGpuConstrained(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsAppInactive(&self) -> ::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), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsBlockedForApp(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsDisabledByUser(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn IsDisabledBySystem(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppRecordingStatusDetails {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.AppRecording.AppRecordingStatusDetails;{b538a9b0-14ed-4412-ac45-6d672c9c9949})");
}
unsafe impl ::windows::core::Interface for AppRecordingStatusDetails {
type Vtable = IAppRecordingStatusDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb538a9b0_14ed_4412_ac45_6d672c9c9949);
}
impl ::windows::core::RuntimeName for AppRecordingStatusDetails {
const NAME: &'static str = "Windows.Media.AppRecording.AppRecordingStatusDetails";
}
impl ::core::convert::From<AppRecordingStatusDetails> for ::windows::core::IUnknown {
fn from(value: AppRecordingStatusDetails) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppRecordingStatusDetails> for ::windows::core::IUnknown {
fn from(value: &AppRecordingStatusDetails) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppRecordingStatusDetails {
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 AppRecordingStatusDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppRecordingStatusDetails> for ::windows::core::IInspectable {
fn from(value: AppRecordingStatusDetails) -> Self {
value.0
}
}
impl ::core::convert::From<&AppRecordingStatusDetails> for ::windows::core::IInspectable {
fn from(value: &AppRecordingStatusDetails) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppRecordingStatusDetails {
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 AppRecordingStatusDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppRecordingStatusDetails {}
unsafe impl ::core::marker::Sync for AppRecordingStatusDetails {}
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppRecordingManager(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppRecordingManager {
type Vtable = IAppRecordingManager_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe7e26076_a044_48e2_a512_3094d574c7cc);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppRecordingManager_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 = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, file: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage")))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, starttime: super::super::Foundation::DateTime, duration: super::super::Foundation::TimeSpan, file: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage")))] 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(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, folder: ::windows::core::RawPtr, filenameprefix: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, option: AppRecordingSaveScreenshotOption, requestedformats: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppRecordingManagerStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppRecordingManagerStatics {
type Vtable = IAppRecordingManagerStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x50e709f7_38ce_4bd3_9db2_e72bbe9de11d);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppRecordingManagerStatics_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 IAppRecordingResult(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppRecordingResult {
type Vtable = IAppRecordingResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3a900864_c66d_46f9_b2d9_5bc2dad070d7);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppRecordingResult_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 bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::HRESULT) -> ::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 bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppRecordingSaveScreenshotResult(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppRecordingSaveScreenshotResult {
type Vtable = IAppRecordingSaveScreenshotResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9c5b8d0a_0abb_4457_aaee_24f9c12ec778);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppRecordingSaveScreenshotResult_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 bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::HRESULT) -> ::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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppRecordingSavedScreenshotInfo(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppRecordingSavedScreenshotInfo {
type Vtable = IAppRecordingSavedScreenshotInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9b642d0a_189a_4d00_bf25_e1bb1249d594);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppRecordingSavedScreenshotInfo_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 = "Storage")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage"))] 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 IAppRecordingStatus(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppRecordingStatus {
type Vtable = IAppRecordingStatus_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1d0cc82c_bc18_4b8a_a6ef_127efab3b5d9);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppRecordingStatus_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 bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::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 IAppRecordingStatusDetails(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppRecordingStatusDetails {
type Vtable = IAppRecordingStatusDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb538a9b0_14ed_4412_ac45_6d672c9c9949);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppRecordingStatusDetails_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 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,
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,
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,
);
|
// 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 {
crate::{capability::*, model::*},
cm_rust::{
self, CapabilityPath, ExposeDecl, ExposeSource, ExposeTarget, OfferDecl,
OfferDirectorySource, OfferRunnerSource, OfferServiceSource, OfferStorageSource,
StorageDecl, StorageDirectorySource, UseDecl, UseStorageDecl,
},
failure::format_err,
fidl::endpoints::ServerEnd,
fidl_fuchsia_io as fio, fuchsia_zircon as zx,
futures::lock::Mutex,
std::sync::Arc,
};
const SERVICE_OPEN_FLAGS: u32 = fio::OPEN_RIGHT_READABLE | fio::OPEN_RIGHT_WRITABLE;
/// Describes the source of a capability, for any type of capability.
enum OfferSource<'a> {
// TODO(CF-908): Enable this once unified services are implemented.
#[allow(dead_code)]
Service(&'a OfferServiceSource),
LegacyService(&'a OfferServiceSource),
Directory(&'a OfferDirectorySource),
Storage(&'a OfferStorageSource),
Runner(&'a OfferRunnerSource),
}
/// Describes the source of a capability, as determined by `find_capability_source`
enum CapabilitySource {
/// This capability originates from the component instance for the given Realm.
/// point.
Component(RoutedCapability, Arc<Realm>),
/// This capability originates from the root component's realm.
Builtin(ComponentManagerCapability),
/// This capability originates from component manager itself scoped to the requesting
/// component's realm.
Framework(ComponentManagerCapability, Arc<Realm>),
/// This capability originates from a storage declaration in a component's decl. `StorageDecl`
/// describes the backing directory capability offered to this realm, into which storage
/// requests should be fed.
StorageDecl(StorageDecl, Arc<Realm>),
}
/// Finds the source of the `capability` used by `absolute_moniker`, and pass along the
/// `server_chan` to the hosting component's out directory (or componentmgr's namespace, if
/// applicable) using an open request with `open_mode`.
pub async fn route_use_capability<'a>(
model: &'a Model,
flags: u32,
open_mode: u32,
relative_path: String,
use_decl: &'a UseDecl,
abs_moniker: AbsoluteMoniker,
server_chan: zx::Channel,
) -> Result<(), ModelError> {
if let UseDecl::Storage(use_storage) = use_decl {
return route_and_open_storage_capability(
model,
&use_storage,
open_mode,
abs_moniker,
server_chan,
)
.await;
}
let source = find_used_capability_source(model, use_decl, &abs_moniker).await?;
open_capability_at_source(model, flags, open_mode, relative_path, source, server_chan).await
}
/// Finds the source of the expose capability used at `source_path` by
/// `absolute_moniker`, and pass along the `server_chan` to the hosting component's out
/// directory (or componentmgr's namespace, if applicable)
pub async fn route_expose_capability<'a>(
model: &'a Model,
flags: u32,
open_mode: u32,
expose_decl: &'a ExposeDecl,
abs_moniker: AbsoluteMoniker,
server_chan: zx::Channel,
) -> Result<(), ModelError> {
let capability = RoutedCapability::Expose(expose_decl.clone());
let mut pos =
WalkPosition { capability, last_child_moniker: None, moniker: Some(abs_moniker.clone()) };
let source = walk_expose_chain(model, &mut pos).await?;
open_capability_at_source(model, flags, open_mode, String::new(), source, server_chan).await
}
/// Open the capability at the given source, binding to its component instance if necessary.
async fn open_capability_at_source<'a>(
model: &'a Model,
flags: u32,
open_mode: u32,
relative_path: String,
source: CapabilitySource,
server_chan: zx::Channel,
) -> Result<(), ModelError> {
match source {
CapabilitySource::Builtin(capability) => {
open_builtin_capability(
model,
flags,
open_mode,
relative_path,
&capability,
server_chan,
)
.await?;
}
CapabilitySource::Component(source_capability, realm) => {
if let Some(path) = source_capability.source_path() {
Model::bind_instance_open_outgoing(
&model,
realm,
flags,
open_mode,
path,
server_chan,
)
.await?;
} else {
return Err(ModelError::capability_discovery_error(format_err!(
"invalid capability type to come from a component"
)));
}
}
CapabilitySource::Framework(capability, realm) => {
open_framework_capability(
SERVICE_OPEN_FLAGS,
open_mode,
relative_path,
realm,
&capability,
server_chan,
)
.await?;
}
CapabilitySource::StorageDecl(..) => {
panic!("storage capabilities must be separately routed and opened");
}
}
Ok(())
}
async fn open_builtin_capability<'a>(
model: &Model,
flags: u32,
open_mode: u32,
relative_path: String,
capability: &'a ComponentManagerCapability,
server_chan: zx::Channel,
) -> Result<(), ModelError> {
let capability_provider = Arc::new(Mutex::new(None));
let event = Event::RouteBuiltinCapability {
realm: model.root_realm.clone(),
capability: capability.clone(),
capability_provider: capability_provider.clone(),
};
model.root_realm.hooks.dispatch(&event).await?;
let capability_provider = capability_provider.lock().await.take();
if let Some(capability_provider) = capability_provider {
capability_provider.open(flags, open_mode, relative_path, server_chan).await?;
} else {
let path = capability.path();
io_util::connect_in_namespace(&path.to_string(), server_chan, flags)
.map_err(|e| ModelError::capability_discovery_error(e))?;
}
Ok(())
}
async fn open_framework_capability<'a>(
flags: u32,
open_mode: u32,
relative_path: String,
realm: Arc<Realm>,
capability: &'a ComponentManagerCapability,
server_chan: zx::Channel,
) -> Result<(), ModelError> {
let capability_provider = Arc::new(Mutex::new(None));
let event = Event::RouteFrameworkCapability {
realm: realm.clone(),
capability: capability.clone(),
capability_provider: capability_provider.clone(),
};
realm.hooks.dispatch(&event).await?;
let capability_provider = capability_provider.lock().await.take();
// TODO(fsamuel): We should report an error message if we're trying to open a framework
// capability that does not exist.
if let Some(capability_provider) = capability_provider {
capability_provider.open(flags, open_mode, relative_path, server_chan).await?;
}
Ok(())
}
/// Routes a `UseDecl::Storage` to the component instance providing the backing directory and
/// opens its isolated storage with `server_chan`.
pub async fn route_and_open_storage_capability<'a>(
model: &'a Model,
use_decl: &'a UseStorageDecl,
open_mode: u32,
use_abs_moniker: AbsoluteMoniker,
server_chan: zx::Channel,
) -> Result<(), ModelError> {
let (dir_source_realm, dir_source_path, relative_moniker) =
route_storage_capability(model, use_decl, use_abs_moniker).await?;
let storage_dir_proxy = open_isolated_storage(
&model,
dir_source_realm,
&dir_source_path,
use_decl.type_(),
&relative_moniker,
open_mode,
)
.await
.map_err(|e| ModelError::from(e))?;
// clone the final connection to connect the channel we're routing to its destination
storage_dir_proxy
.clone(fio::CLONE_FLAG_SAME_RIGHTS, ServerEnd::new(server_chan))
.map_err(|e| ModelError::capability_discovery_error(format_err!("failed clone {}", e)))?;
Ok(())
}
/// Routes a `UseDecl::Storage` to the component instance providing the backing directory and
/// deletes its isolated storage.
pub async fn route_and_delete_storage<'a>(
model: &'a Model,
use_decl: &'a UseStorageDecl,
use_abs_moniker: AbsoluteMoniker,
) -> Result<(), ModelError> {
let (dir_source_realm, dir_source_path, relative_moniker) =
route_storage_capability(model, use_decl, use_abs_moniker).await?;
delete_isolated_storage(&model, dir_source_realm, &dir_source_path, &relative_moniker)
.await
.map_err(|e| ModelError::from(e))?;
Ok(())
}
/// Assuming `use_decl` is a UseStorage declaration, returns information about the source of the
/// storage capability, including:
/// - Realm hosting the backing directory capability
/// - Path to the backing directory capability
/// - Relative moniker between the backing directory component and the consumer, which identifies
/// the isolated storage directory.
async fn route_storage_capability<'a>(
model: &'a Model,
use_decl: &'a UseStorageDecl,
use_abs_moniker: AbsoluteMoniker,
) -> Result<(Arc<Realm>, CapabilityPath, RelativeMoniker), ModelError> {
// Walk the offer chain to find the storage decl
let parent_moniker = match use_abs_moniker.parent() {
Some(m) => m,
None => {
return Err(ModelError::capability_discovery_error(format_err!(
"storage capabilities cannot come from component manager's namespace"
)))
}
};
let mut pos = WalkPosition {
capability: RoutedCapability::Use(UseDecl::Storage(use_decl.clone())),
last_child_moniker: use_abs_moniker.path().last().map(|c| c.clone()),
moniker: Some(parent_moniker),
};
let source = walk_offer_chain(model, &mut pos).await?;
let (storage_decl, storage_decl_realm) = match source {
Some(CapabilitySource::StorageDecl(s, r)) => (s, r),
_ => {
return Err(ModelError::capability_discovery_error(format_err!(
"storage capabilities must come from a storage declaration"
)))
}
};
// Find the path and source of the directory consumed by the storage capability.
let (dir_source_path, dir_source_realm) = match storage_decl.source {
StorageDirectorySource::Self_ => (storage_decl.source_path, storage_decl_realm.clone()),
StorageDirectorySource::Realm => {
let capability = RoutedCapability::Storage(storage_decl);
let source =
find_offered_capability_source(model, capability, &storage_decl_realm.abs_moniker)
.await?;
match source {
CapabilitySource::Component(source_capability, realm) => {
(source_capability.source_path().unwrap().clone(), realm)
}
_ => {
return Err(ModelError::capability_discovery_error(format_err!(
"storage capability backing directories must be provided by a component"
)))
}
}
}
StorageDirectorySource::Child(ref name) => {
let mut pos = {
let partial = PartialMoniker::new(name.to_string(), None);
let realm_state = storage_decl_realm.lock_state().await;
let realm_state =
realm_state.as_ref().expect("route_storage_capability: not resolved");
let moniker = Some(
realm_state
.extend_moniker_with(&storage_decl_realm.abs_moniker, &partial)
.ok_or(ModelError::capability_discovery_error(format_err!(
"no child {} found from component {} for storage directory source",
partial,
pos.moniker().clone(),
)))?,
);
let capability = RoutedCapability::Storage(storage_decl);
WalkPosition { capability, last_child_moniker: None, moniker }
};
match walk_expose_chain(model, &mut pos).await? {
CapabilitySource::Component(source_capability, realm) => {
(source_capability.source_path().unwrap().clone(), realm)
}
_ => {
return Err(ModelError::capability_discovery_error(format_err!(
"storage capability backing directories must be provided by a component"
)))
}
}
}
};
let relative_moniker =
RelativeMoniker::from_absolute(&storage_decl_realm.abs_moniker, &use_abs_moniker);
Ok((dir_source_realm, dir_source_path, relative_moniker))
}
/// Check if a used capability is a framework service, and if so return a framework `CapabilitySource`.
async fn find_framework_capability<'a>(
model: &'a Model,
use_decl: &'a UseDecl,
abs_moniker: &'a AbsoluteMoniker,
) -> Result<Option<CapabilitySource>, ModelError> {
if let Ok(capability) = ComponentManagerCapability::framework_from_use_decl(use_decl) {
let realm = model.look_up_realm(abs_moniker).await?;
return Ok(Some(CapabilitySource::Framework(capability, realm)));
}
return Ok(None);
}
/// Holds state about the current position when walking the tree.
struct WalkPosition {
/// The capability declaration as it's represented in the current component.
capability: RoutedCapability,
/// The moniker of the child we came from.
last_child_moniker: Option<ChildMoniker>,
/// The moniker of the component we are currently looking at. `None` for component manager's
/// realm.
moniker: Option<AbsoluteMoniker>,
}
impl WalkPosition {
fn moniker(&self) -> &AbsoluteMoniker {
self.moniker.as_ref().unwrap()
}
fn at_componentmgr_realm(&self) -> bool {
self.moniker.is_none()
}
}
async fn find_used_capability_source<'a>(
model: &'a Model,
use_decl: &'a UseDecl,
abs_moniker: &'a AbsoluteMoniker,
) -> Result<CapabilitySource, ModelError> {
if let Some(framework_capability) =
find_framework_capability(model, use_decl, abs_moniker).await?
{
return Ok(framework_capability);
}
let capability = RoutedCapability::Use(use_decl.clone());
find_offered_capability_source(model, capability, abs_moniker).await
}
/// Walks the component tree to find the originating source of a capability, starting on the given
/// abs_moniker. It returns the absolute moniker of the originating component, a reference to its
/// realm, and the capability exposed or offered at the originating source. If the absolute moniker
/// and realm are None, then the capability originates at the returned path in componentmgr's
/// namespace.
async fn find_offered_capability_source<'a>(
model: &'a Model,
capability: RoutedCapability,
abs_moniker: &'a AbsoluteMoniker,
) -> Result<CapabilitySource, ModelError> {
let mut pos = WalkPosition {
capability,
last_child_moniker: abs_moniker.path().last().map(|c| c.clone()),
moniker: abs_moniker.parent(),
};
if let Some(source) = walk_offer_chain(model, &mut pos).await? {
return Ok(source);
}
walk_expose_chain(model, &mut pos).await
}
/// Follows `offer` declarations up the component tree, starting at `pos`. The algorithm looks
/// for a matching `offer` in the parent, as long as the `offer` is from `realm`.
///
/// Returns the source of the capability if found, or `None` if `expose` declarations must be
/// walked.
async fn walk_offer_chain<'a>(
model: &'a Model,
pos: &'a mut WalkPosition,
) -> Result<Option<CapabilitySource>, ModelError> {
'offerloop: loop {
if pos.at_componentmgr_realm() {
// This is a built-in capability because the routing path was traced to the component
// manager's realm.
// TODO(fsamuel): We really ought to test the failure cases here.
let capability = match &pos.capability {
RoutedCapability::Use(use_decl) => {
ComponentManagerCapability::builtin_from_use_decl(use_decl).map_err(|_| {
ModelError::capability_discovery_error(format_err!(
"no matching use found for capability {:?} from component {}",
pos.capability,
pos.moniker(),
))
})
}
RoutedCapability::Offer(offer_decl) => {
ComponentManagerCapability::builtin_from_offer_decl(offer_decl).map_err(|_| {
ModelError::capability_discovery_error(format_err!(
"no matching offers found for capability {:?} from component {}",
pos.capability,
pos.moniker(),
))
})
}
_ => Err(ModelError::capability_discovery_error(format_err!(
"Unsupported capability {:?} from component {}",
pos.capability,
pos.moniker(),
))),
}?;
return Ok(Some(CapabilitySource::Builtin(capability)));
}
let current_realm = model.look_up_realm(&pos.moniker()).await?;
let realm_state = current_realm.lock_state().await;
let realm_state = realm_state.as_ref().expect("walk_offer_chain: not resolved");
// This `get()` is safe because `look_up_realm` populates this field
let decl = realm_state.decl();
let last_child_moniker = pos.last_child_moniker.as_ref().unwrap();
let offer = pos.capability.find_offer_source(decl, last_child_moniker).ok_or(
ModelError::capability_discovery_error(format_err!(
"no matching offers found for capability {:?} from component {}",
pos.capability,
pos.moniker(),
)),
)?;
let source = match offer {
OfferDecl::Service(_) => return Err(ModelError::unsupported("Service capability")),
OfferDecl::LegacyService(s) => OfferSource::LegacyService(&s.source),
OfferDecl::Directory(d) => OfferSource::Directory(&d.source),
OfferDecl::Storage(s) => OfferSource::Storage(s.source()),
OfferDecl::Runner(r) => OfferSource::Runner(&r.source),
};
match source {
OfferSource::Service(_) => {
return Err(ModelError::unsupported("Service capability"));
}
OfferSource::Directory(OfferDirectorySource::Framework) => {
let capability = ComponentManagerCapability::framework_from_offer_decl(offer)
.map_err(|_| {
ModelError::capability_discovery_error(format_err!(
"no matching offers found for capability {:?} from component {}",
pos.capability,
pos.moniker(),
))
})?;
return Ok(Some(CapabilitySource::Framework(capability, current_realm.clone())));
}
OfferSource::LegacyService(OfferServiceSource::Realm)
| OfferSource::Directory(OfferDirectorySource::Realm)
| OfferSource::Storage(OfferStorageSource::Realm) => {
// The offered capability comes from the realm, so follow the
// parent
pos.capability = RoutedCapability::Offer(offer.clone());
pos.last_child_moniker = pos.moniker().path().last().map(|c| c.clone());
pos.moniker = pos.moniker().parent();
continue 'offerloop;
}
OfferSource::LegacyService(OfferServiceSource::Self_)
| OfferSource::Directory(OfferDirectorySource::Self_) => {
// The offered capability comes from the current component,
// return our current location in the tree.
return Ok(Some(CapabilitySource::Component(
RoutedCapability::Offer(offer.clone()),
current_realm.clone(),
)));
}
OfferSource::LegacyService(OfferServiceSource::Child(child_name))
| OfferSource::Directory(OfferDirectorySource::Child(child_name)) => {
// The offered capability comes from a child, break the loop
// and begin walking the expose chain.
pos.capability = RoutedCapability::Offer(offer.clone());
let partial = PartialMoniker::new(child_name.to_string(), None);
pos.moniker =
Some(realm_state.extend_moniker_with(&pos.moniker(), &partial).ok_or(
ModelError::capability_discovery_error(format_err!(
"no child {} found from component {} for offer source",
partial,
pos.moniker().clone(),
)),
)?);
return Ok(None);
}
OfferSource::Storage(OfferStorageSource::Storage(storage_name)) => {
let storage = decl
.find_storage_source(&storage_name)
.expect("storage offer references nonexistent section");
return Ok(Some(CapabilitySource::StorageDecl(
storage.clone(),
current_realm.clone(),
)));
}
OfferSource::Runner(_) => {
// TODO(fxb/4761) implement runner support
return Err(ModelError::unsupported("runner capability"));
}
}
}
}
/// Follows `expose` declarations down the component tree, starting at `pos`. The algorithm looks
/// for a matching `expose` in the child, as long as the `expose` is not from `self`.
///
/// Returns the source of the capability.
async fn walk_expose_chain<'a>(
model: &'a Model,
pos: &'a mut WalkPosition,
) -> Result<CapabilitySource, ModelError> {
// If the first capability is an Expose, assume it corresponds to an Expose declared by the
// first component.
let mut first_expose = {
match &pos.capability {
RoutedCapability::Expose(e) => Some(e.clone()),
_ => None,
}
};
loop {
let current_realm = model.look_up_realm(&pos.moniker()).await?;
let realm_state = current_realm.lock_state().await;
let realm_state = realm_state.as_ref().expect("walk_expose_chain: not resolved");
// This `get()` is safe because look_up_realm populates this field.
let first_expose = first_expose.take();
let expose = first_expose
.as_ref()
.or_else(|| pos.capability.find_expose_source(realm_state.decl()))
.ok_or(ModelError::capability_discovery_error(format_err!(
"no matching offers found for capability {:?} from component {}",
pos.capability,
pos.moniker(),
)))?;
let (source, target) = match expose {
ExposeDecl::Service(_) => return Err(ModelError::unsupported("Service capability")),
ExposeDecl::LegacyService(ls) => (&ls.source, &ls.target),
ExposeDecl::Directory(d) => (&d.source, &d.target),
// TODO(fxb/4761): Implement runner routing.
ExposeDecl::Runner(_) => return Err(ModelError::unsupported("runner capability")),
};
if target != &ExposeTarget::Realm {
return Err(ModelError::capability_discovery_error(format_err!(
"matching exposed capability {:?} from component {} has non-realm target",
pos.capability,
pos.moniker()
)));
}
match source {
ExposeSource::Self_ => {
// The offered capability comes from the current component, return our
// current location in the tree.
return Ok(CapabilitySource::Component(
RoutedCapability::Expose(expose.clone()),
current_realm.clone(),
));
}
ExposeSource::Child(child_name) => {
// The offered capability comes from a child, so follow the child.
pos.capability = RoutedCapability::Expose(expose.clone());
let partial = PartialMoniker::new(child_name.to_string(), None);
pos.moniker =
Some(realm_state.extend_moniker_with(&pos.moniker(), &partial).ok_or(
ModelError::capability_discovery_error(format_err!(
"no child {} found from component {} for expose source",
partial,
pos.moniker().clone(),
)),
)?);
continue;
}
ExposeSource::Framework => {
let capability = ComponentManagerCapability::framework_from_expose_decl(expose)
.map_err(|_| {
ModelError::capability_discovery_error(format_err!(
"no matching offers found for capability {:?} from component {}",
pos.capability,
pos.moniker(),
))
})?;
return Ok(CapabilitySource::Framework(capability, current_realm.clone()));
}
}
}
}
|
//! Contains an ffi-safe wrapper for `parking_lot::Once`.
use std::{
any::Any,
fmt::{self, Debug},
mem,
panic::{self, AssertUnwindSafe},
};
use parking_lot::{Once as PLOnce, OnceState};
use super::{UnsafeOveralignedField, RAW_LOCK_SIZE};
use crate::{
prefix_type::WithMetadata,
sabi_types::RMut,
std_types::{RErr, ROk, RResult},
};
///////////////////////////////////////////////////////////////////////////////
type OpaqueOnce = UnsafeOveralignedField<PLOnce, [u8; OM_PADDING]>;
const OM_PADDING: usize = RAW_LOCK_SIZE - mem::size_of::<PLOnce>();
#[allow(clippy::declare_interior_mutable_const)]
const OPAQUE_ONCE: OpaqueOnce = OpaqueOnce::new(parking_lot::Once::new(), [0u8; OM_PADDING]);
const _: () = assert!(RAW_LOCK_SIZE == mem::size_of::<OpaqueOnce>());
///////////////////////////////////////////////////////////////////////////////
/// A synchronization primitive for running global initialization once.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::{RMutex, ROnce};
///
/// static MUTEX: RMutex<usize> = RMutex::new(0);
///
/// static ONCE: ROnce = ROnce::new();
///
/// let guards = std::iter::repeat_with(|| {
/// std::thread::spawn(|| {
/// ONCE.call_once(|| {
/// *MUTEX.lock() += 1;
/// })
/// })
/// })
/// .take(20)
/// .collect::<Vec<_>>();
///
/// for guard in guards {
/// guard.join().unwrap();
/// }
///
/// assert_eq!(*MUTEX.lock(), 1);
///
/// ```
///
///
#[repr(C)]
#[derive(StableAbi)]
pub struct ROnce {
opaque_once: OpaqueOnce,
vtable: VTable_Ref,
}
impl ROnce {
/// Constructs an ROnce.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::ROnce;
///
/// static ONCE: ROnce = ROnce::new();
///
/// ```
pub const fn new() -> ROnce {
ROnce {
opaque_once: OPAQUE_ONCE,
vtable: VTable::VTABLE,
}
}
}
#[allow(clippy::missing_const_for_fn)]
impl ROnce {
/// Constructs an ROnce.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::ROnce;
///
/// static ONCE: ROnce = ROnce::NEW;
///
/// ```
#[allow(clippy::declare_interior_mutable_const)]
pub const NEW: Self = ROnce {
opaque_once: OPAQUE_ONCE,
vtable: VTable::VTABLE,
};
fn vtable(&self) -> VTable_Ref {
self.vtable
}
/// Gets the running state of this ROnce.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::parking_lot::once::{ROnce, ROnceState};
///
/// use std::panic::AssertUnwindSafe;
///
/// let once = ROnce::new();
///
/// assert_eq!(once.state(), ROnceState::New);
///
/// let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
/// once.call_once(|| panic!());
/// }));
///
/// assert!(once.state().poisoned());
///
/// once.call_once_force(|_| ());
///
/// assert!(once.state().done());
///
/// ```
pub fn state(&self) -> ROnceState {
unsafe { self.vtable().state()(&self.opaque_once) }
}
/// Runs an initialization function.
///
/// `f` will be run only if this is the first time this method has been called
/// on this ROnce.
///
/// Once this function returns it is guaranteed that some closure passed
/// to this method has run to completion.
///
/// # Panics
///
/// Panics in the closure will cause this ROnce to become poisoned,
/// and any future calls to this method will panic.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::ROnce;
///
/// let once = ROnce::new();
/// let mut counter = 0usize;
///
/// once.call_once(|| counter += 1);
/// once.call_once(|| counter += 1);
/// once.call_once(|| counter += 1);
/// once.call_once(|| counter += 1);
///
/// assert_eq!(counter, 1);
///
/// ```
pub fn call_once<F>(&self, f: F)
where
F: FnOnce(),
{
let mut closure = Closure::without_state(f);
let func = closure.func;
let res = unsafe {
self.vtable().call_once()(
&self.opaque_once,
RMut::new(&mut closure).transmute::<ErasedClosure>(),
func,
)
};
if let Err(e) = closure.panic {
panic::resume_unwind(e);
}
if let RErr(()) = res {
panic!("This ROnce instantce is poisoned.");
}
}
/// Runs an initialization function,even if the ROnce is poisoned.
///
/// This will keep trying to run different closures until one of them doesn't panic.
///
/// The ROnceState parameter describes whether the ROnce is New or Poisoned.
///
///
/// # Example
///
/// ```
/// use abi_stable::external_types::ROnce;
///
/// use std::panic::{self, AssertUnwindSafe};
///
/// let once = ROnce::new();
/// let mut counter = 0usize;
///
/// for i in 0..100 {
/// let _ = panic::catch_unwind(AssertUnwindSafe(|| {
/// once.call_once_force(|_| {
/// if i < 6 {
/// panic!();
/// }
/// counter = i;
/// })
/// }));
/// }
///
/// assert_eq!(counter, 6);
///
/// ```
pub fn call_once_force<F>(&self, f: F)
where
F: FnOnce(ROnceState),
{
let mut closure = Closure::with_state(f);
let func = closure.func;
let res = unsafe {
self.vtable().call_once_force()(
&self.opaque_once,
RMut::new(&mut closure).transmute::<ErasedClosure>(),
func,
)
};
if let Err(e) = closure.panic {
panic::resume_unwind(e);
}
if let RErr(()) = res {
panic!("This ROnce instantce is poisoned.");
}
}
}
impl Debug for ROnce {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Once")
.field("state", &self.state())
.finish()
}
}
impl Default for ROnce {
#[inline]
fn default() -> Self {
Self::new()
}
}
unsafe impl Send for ROnce {}
unsafe impl Sync for ROnce {}
///////////////////////////////////////////////////////////////////////////////
/// Describes the running state of an ROnce.
#[repr(u8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug, StableAbi)]
pub enum ROnceState {
/// An ROnce that hasn't started running
New,
/// An ROnce that panicked inside `call_once*`
Poisoned,
/// An ROnce that is the middle of calling `call_once*`
InProgress,
/// An ROnce that has already run.
Done,
}
#[allow(clippy::missing_const_for_fn)]
impl ROnceState {
/// Whether the ROnce is poisoned,requiring call_once_force to run.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::ROnce;
///
/// use std::panic::AssertUnwindSafe;
///
/// let once = ROnce::new();
///
/// let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
/// once.call_once(|| panic!());
/// }));
///
/// assert!(once.state().poisoned());
///
/// ```
///
pub fn poisoned(&self) -> bool {
matches!(self, ROnceState::Poisoned)
}
/// Whether the ROnce has already finished running.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::ROnce;
///
/// let once = ROnce::new();
///
/// once.call_once(|| ());
///
/// assert!(once.state().done());
///
/// ```
pub fn done(&self) -> bool {
matches!(self, ROnceState::Done)
}
}
impl_from_rust_repr! {
impl From<OnceState> for ROnceState {
fn(this){
match this {
OnceState::New=>ROnceState::New,
OnceState::Poisoned=>ROnceState::Poisoned,
OnceState::InProgress=>ROnceState::InProgress,
OnceState::Done=>ROnceState::Done,
}
}
}
}
impl_into_rust_repr! {
impl Into<OnceState> for ROnceState {
fn(this){
match this {
ROnceState::New=>OnceState::New,
ROnceState::Poisoned=>OnceState::Poisoned,
ROnceState::InProgress=>OnceState::InProgress,
ROnceState::Done=>OnceState::Done,
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
#[repr(C)]
#[derive(StableAbi)]
struct ErasedClosure;
struct Closure<F> {
closure: Option<F>,
panic: Result<(), Box<dyn Any + Send + 'static>>,
func: RunClosure,
}
#[derive(StableAbi, Copy, Clone)]
#[repr(transparent)]
struct RunClosure {
func: unsafe extern "C" fn(RMut<'_, ErasedClosure>, ROnceState) -> RResult<(), ()>,
}
impl<F> Closure<F> {
#[inline]
pub fn without_state(function: F) -> Self
where
F: FnOnce(),
{
Self {
closure: Some(function),
panic: Ok(()),
func: RunClosure {
func: Self::run_call_once,
},
}
}
#[inline]
pub fn with_state(function: F) -> Self
where
F: FnOnce(ROnceState),
{
Self {
closure: Some(function),
panic: Ok(()),
func: RunClosure {
func: Self::run_call_once_forced,
},
}
}
unsafe extern "C" fn run_call_once(
this: RMut<'_, ErasedClosure>,
state: ROnceState,
) -> RResult<(), ()>
where
F: FnOnce(),
{
unsafe { Self::run_call(this, state, |f, _| f()) }
}
unsafe extern "C" fn run_call_once_forced(
this: RMut<'_, ErasedClosure>,
state: ROnceState,
) -> RResult<(), ()>
where
F: FnOnce(ROnceState),
{
unsafe { Self::run_call(this, state, |f, state| f(state)) }
}
#[inline]
unsafe fn run_call<M>(
this: RMut<'_, ErasedClosure>,
state: ROnceState,
method: M,
) -> RResult<(), ()>
where
M: FnOnce(F, ROnceState),
{
let mut this = unsafe { this.transmute_into_mut::<Self>() };
let res = panic::catch_unwind(AssertUnwindSafe(|| {
let closure = this.closure.take().unwrap();
method(closure, state);
}));
let ret = match res {
Ok { .. } => ROk(()),
Err { .. } => RErr(()),
};
this.panic = res;
ret
}
}
///////////////////////////////////////////////////////////////////////////////
#[repr(C)]
#[derive(StableAbi)]
#[sabi(kind(Prefix))]
#[sabi(missing_field(panic))]
struct VTable {
state: unsafe extern "C" fn(&OpaqueOnce) -> ROnceState,
call_once:
unsafe extern "C" fn(&OpaqueOnce, RMut<'_, ErasedClosure>, RunClosure) -> RResult<(), ()>,
call_once_force:
unsafe extern "C" fn(&OpaqueOnce, RMut<'_, ErasedClosure>, RunClosure) -> RResult<(), ()>,
}
impl VTable {
// The VTABLE for this type in this executable/library
const VTABLE: VTable_Ref = {
const S: &WithMetadata<VTable> = &WithMetadata::new(VTable {
state,
call_once,
call_once_force,
});
VTable_Ref(S.static_as_prefix())
};
}
///////////////////////////////////////////////////////////////////////////////
unsafe extern "C" fn state(this: &OpaqueOnce) -> ROnceState {
extern_fn_panic_handling! {
this.value.state().into()
}
}
unsafe extern "C" fn call_once(
this: &OpaqueOnce,
erased_closure: RMut<'_, ErasedClosure>,
runner: RunClosure,
) -> RResult<(), ()> {
call_with_closure(|| {
this.value.call_once(|| unsafe {
(runner.func)(erased_closure, ROnceState::New).unwrap();
});
})
}
unsafe extern "C" fn call_once_force(
this: &OpaqueOnce,
erased_closure: RMut<'_, ErasedClosure>,
runner: RunClosure,
) -> RResult<(), ()> {
call_with_closure(|| {
this.value.call_once_force(|state| unsafe {
(runner.func)(erased_closure, state.into()).unwrap();
});
})
}
#[inline]
fn call_with_closure<F>(f: F) -> RResult<(), ()>
where
F: FnOnce(),
{
let res = panic::catch_unwind(AssertUnwindSafe(f));
match res {
Ok { .. } => ROk(()),
Err { .. } => RErr(()),
}
}
///////////////////////////////////////////////////////////////////////////////
#[cfg(all(test, not(feature = "test_miri_track_raw")))]
//#[cfg(test)]
mod tests {
use super::*;
use crossbeam_utils::thread::scope as scoped_thread;
use abi_stable_shared::test_utils::must_panic;
#[test]
#[cfg(not(all(miri, target_os = "windows")))]
fn state() {
{
let once = ROnce::new();
assert_eq!(once.state(), ROnceState::New);
once.call_once(|| {});
assert_eq!(once.state(), ROnceState::Done);
}
{
let once = ROnce::new();
assert_eq!(once.state(), ROnceState::New);
must_panic(|| {
once.call_once(|| panic!());
})
.unwrap();
assert_eq!(once.state(), ROnceState::Poisoned);
}
{
static ONCE: ROnce = ROnce::new();
scoped_thread(|scope| {
let (tx_start, rx_start) = std::sync::mpsc::channel();
let (tx_end, rx_end) = std::sync::mpsc::channel();
scope.spawn(move |_| {
ONCE.call_once(|| {
tx_start.send(()).unwrap();
rx_end.recv().unwrap();
})
});
scope.spawn(move |_| {
rx_start.recv().unwrap();
assert_eq!(ONCE.state(), ROnceState::InProgress);
tx_end.send(()).unwrap();
});
})
.unwrap();
assert_eq!(ONCE.state(), ROnceState::Done);
}
}
#[test]
fn call_once() {
{
let once = ROnce::new();
let mut a = 0;
once.call_once(|| a += 1);
once.call_once(|| a += 2);
once.call_once(|| panic!());
assert_eq!(a, 1);
}
{
let once = ROnce::new();
let mut a = 0;
must_panic(|| {
once.call_once(|| panic!());
})
.unwrap();
must_panic(|| {
once.call_once(|| a += 2);
})
.unwrap();
assert_eq!(a, 0);
}
}
#[test]
fn call_once_force() {
{
let once = ROnce::new();
let mut a = 0;
once.call_once_force(|_| a += 1);
once.call_once_force(|_| a += 2);
assert_eq!(a, 1);
}
{
let once = ROnce::new();
let a = &mut 0;
must_panic(|| {
once.call_once_force(|state| {
assert_eq!(state, ROnceState::New);
panic!()
});
})
.unwrap();
once.call_once_force(|state| {
assert_eq!(state, ROnceState::Poisoned);
*a += 2;
});
once.call_once_force(|_| *a += 4);
once.call_once_force(|_| panic!());
assert_eq!(*a, 2);
}
}
}
|
use crypto::ripemd160::Ripemd160 ;
use crypto::digest::Digest;
pub struct JRipemd160 {
pub jripemd160x: Ripemd160,
}
impl JRipemd160 {
pub fn new() -> Self {
JRipemd160 {
jripemd160x: Ripemd160::new(),
}
}
pub fn input(&mut self, input: &[u8]) {
self.jripemd160x.input(&input);
}
pub fn result(&mut self, ret: &mut [u8]) {
self.jripemd160x.result(ret);
}
pub fn result_str(&mut self) -> String {
self.jripemd160x.result_str()
}
}
|
#[cfg(feature = "mongo-backend")]
use bson;
#[cfg(feature = "redis-backend")]
use redis::{ErrorKind, FromRedisValue, RedisResult, ToRedisArgs, Value as RedisValue};
#[cfg(feature = "dynamo-backend")]
use rusoto_dynamodb::AttributeValue;
#[cfg(feature = "redis-backend")]
use serde_json;
#[cfg(feature = "dynamo-backend")]
use std::collections::HashMap;
use std::str::FromStr;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use error::BannerError;
#[cfg(feature = "dynamo-backend")]
use storage::dynamo::{DynamoError, FromAttrMap};
const PATH_SEP: &'static str = ":";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlagPath {
pub owner: String,
pub app: String,
pub env: String,
pub path: String,
}
impl FlagPath {
pub fn new<T, S, U>(owner: T, app: S, env: U) -> FlagPath
where
T: Into<String>,
S: Into<String>,
U: Into<String>,
{
let o = owner.into();
let a = app.into();
let e = env.into();
let path = FlagPath::make_path(&o, &a, &e);
FlagPath {
owner: o,
app: a,
env: e,
path: path,
}
}
pub fn make_path<T, S, U>(owner: T, app: S, env: U) -> String
where
T: AsRef<str>,
S: AsRef<str>,
U: AsRef<str>,
{
[
owner.as_ref(),
PATH_SEP,
app.as_ref(),
PATH_SEP,
env.as_ref(),
].concat()
}
}
impl AsRef<str> for FlagPath {
fn as_ref(&self) -> &str {
self.path.as_str()
}
}
impl FromStr for FlagPath {
type Err = BannerError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = s.split(PATH_SEP).collect();
if parts.len() == 3 {
Ok(FlagPath::new(parts[0], parts[1], parts[2]))
} else {
Err(BannerError::FailedToParsePath)
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Flag {
key: String,
value: FlagValue,
#[cfg_attr(feature = "mongo-backend", serde(with = "bson::compat::u2f"))] version: u64,
enabled: bool,
#[serde(default = "current_time")]
#[cfg_attr(feature = "mongo-backend", serde(with = "bson::compat::u2f"))]
created: u64,
#[serde(default = "current_time")]
#[cfg_attr(feature = "mongo-backend", serde(with = "bson::compat::u2f"))]
updated: u64,
}
fn current_time() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or(Duration::from_secs(0))
.as_secs()
}
impl Flag {
pub fn new<S>(key: S, value: FlagValue, version: u64, enabled: bool) -> Flag
where
S: Into<String>,
{
let created = current_time();
Flag {
key: key.into(),
value: value,
version: version,
enabled: enabled,
created: created,
updated: created,
}
}
pub fn eval(&self) -> Option<&FlagValue> {
if self.enabled {
Some(&self.value)
} else {
None
}
}
pub fn value(&self) -> &FlagValue {
&self.value
}
pub fn is_enabled(&self) -> bool {
self.enabled
}
pub fn is_ver(&self, ver: u64) -> bool {
self.version == ver
}
pub fn key(&self) -> &str {
self.key.as_str()
}
pub fn set_value(&mut self, val: &FlagValue) {
let new_val = val.clone();
if self.value != new_val {
self.version = self.version + 1;
self.value = new_val;
self.updated = current_time();
}
}
pub fn toggle(&mut self, state: bool) {
if self.enabled != state {
self.enabled = !self.enabled;
self.updated = current_time();
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FlagValue {
Bool(bool),
}
// Backend Impls
#[cfg(feature = "redis-backend")]
impl FromRedisValue for Flag {
fn from_redis_value(v: &RedisValue) -> RedisResult<Flag> {
match *v {
RedisValue::Data(ref data) => {
let data = String::from_utf8(data.clone());
data.or_else(|_| Err((ErrorKind::TypeError, "Expected utf8 string").into()))
.and_then(|ser| {
serde_json::from_str(ser.as_str()).or_else(|_| {
let err = (ErrorKind::TypeError, "Unable to deserialize json to Flag");
Err(err.into())
})
})
}
_ => {
let err = (
ErrorKind::TypeError,
"Recieved non-data type for deserializing",
);
Err(err.into())
}
}
}
}
#[cfg(feature = "redis-backend")]
impl<'a> ToRedisArgs for Flag {
fn write_redis_args(&self, out: &mut Vec<Vec<u8>>) {
let ser = serde_json::to_string(&self);
out.push(
match ser {
Ok(json) => json.as_bytes().into(),
// Because this trait can not normally fail, but json serialization
// can fail, the failure cause is encoded as a special value that
// is checked by the store
Err(_) => "fail".to_string().as_bytes().into(),
},
)
}
}
#[cfg(feature = "redis-backend")]
impl FromRedisValue for FlagPath {
fn from_redis_value(v: &RedisValue) -> RedisResult<FlagPath> {
match *v {
RedisValue::Data(ref data) => {
let data = String::from_utf8(data.clone());
data.or_else(|_| Err((ErrorKind::TypeError, "Expected utf8 string").into()))
.and_then(|ser| {
serde_json::from_str(ser.as_str()).or_else(|_| {
let err = (ErrorKind::TypeError, "Unable to deserialize json to Path");
Err(err.into())
})
})
}
_ => {
let err = (
ErrorKind::TypeError,
"Recieved non-data type for deserializing",
);
Err(err.into())
}
}
}
}
#[cfg(feature = "redis-backend")]
impl<'a> ToRedisArgs for FlagPath {
fn write_redis_args(&self, out: &mut Vec<Vec<u8>>) {
let ser = serde_json::to_string(&self);
out.push(
match ser {
Ok(json) => json.as_bytes().into(),
// Because this trait can not normally fail, but json serialization
// can fail, the failure cause is encoded as a special value that
// is checked by the store
Err(_) => "fail".to_string().as_bytes().into(),
},
)
}
}
#[cfg(feature = "dynamo-backend")]
impl Into<HashMap<String, AttributeValue>> for Flag {
fn into(self) -> HashMap<String, AttributeValue> {
let mut key_attr = AttributeValue::default();
key_attr.s = Some(self.key);
let mut value_attr = AttributeValue::default();
match self.value {
FlagValue::Bool(true) => {
value_attr.bool = Some(true);
}
_ => {
value_attr.bool = Some(false);
}
}
let mut version_attr = AttributeValue::default();
version_attr.n = Some(self.version.to_string());
let mut enabled_attr = AttributeValue::default();
enabled_attr.bool = Some(self.enabled);
let mut created_attr = AttributeValue::default();
created_attr.n = Some(self.created.to_string());
let mut updated_attr = AttributeValue::default();
updated_attr.n = Some(self.updated.to_string());
let mut map = HashMap::new();
map.insert("key".into(), key_attr);
map.insert("value".into(), value_attr);
map.insert("version".into(), version_attr);
map.insert("enabled".into(), enabled_attr);
map.insert("created".into(), created_attr);
map.insert("updated".into(), updated_attr);
map
}
}
#[cfg(feature = "dynamo-backend")]
impl FromAttrMap<Flag> for Flag {
type Error = BannerError;
fn from_attr_map(mut map: HashMap<String, AttributeValue>) -> Result<Flag, BannerError> {
let key = map.remove("key").and_then(|key_data| match key_data.s {
Some(key) => Some(key),
None => None,
});
let value = map.get("value").and_then(|value_data| value_data.bool);
let version = map.get("version")
.and_then(|version_data| match version_data.n {
Some(ref version) => version.parse::<u64>().ok(),
None => None,
});
let enabled = map.get("enabled")
.and_then(|enabled_data| enabled_data.bool);
let created = map.get("created")
.and_then(|created_data| match created_data.n {
Some(ref created) => created.parse::<u64>().ok(),
None => None,
});
let updated = map.get("updated")
.and_then(|updated_data| match updated_data.n {
Some(ref updated) => updated.parse::<u64>().ok(),
None => None,
});
if let (Some(k), Some(vl), Some(vr), Some(e), Some(c), Some(u)) =
(key, value, version, enabled, created, updated)
{
Ok(Flag {
key: k,
value: FlagValue::Bool(vl),
version: vr,
enabled: e,
created: c,
updated: u,
})
} else {
Err(DynamoError::FailedToParseResponse.into())
}
}
}
#[cfg(feature = "dynamo-backend")]
impl Into<HashMap<String, AttributeValue>> for FlagPath {
fn into(self) -> HashMap<String, AttributeValue> {
let mut app_attr = AttributeValue::default();
app_attr.s = Some(self.app);
let mut env_attr = AttributeValue::default();
env_attr.s = Some(self.env);
let mut path_attr = AttributeValue::default();
path_attr.s = Some(self.path);
let mut map = HashMap::new();
map.insert("app".into(), app_attr);
map.insert("env".into(), env_attr);
map.insert("path".into(), path_attr);
map
}
}
#[cfg(feature = "dynamo-backend")]
impl FromAttrMap<FlagPath> for FlagPath {
type Error = BannerError;
fn from_attr_map(mut map: HashMap<String, AttributeValue>) -> Result<FlagPath, BannerError> {
let app = map.remove("app").and_then(|app_data| match app_data.s {
Some(app) => Some(app),
None => None,
});
let env = map.remove("env").and_then(|env_data| match env_data.s {
Some(env) => Some(env),
None => None,
});
if let (Some(a), Some(e)) = (app, env) {
Ok(FlagPath::new(a, e))
} else {
Err(DynamoError::FailedToParseResponse.into())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_returns_some_if_enabled() {
let f = Flag::new("key-string", FlagValue::Bool(true), 1, true);
assert_eq!(f.eval(), Some(&FlagValue::Bool(true)));
}
#[test]
fn test_returns_none_if_disabled() {
let f = Flag::new("key-string", FlagValue::Bool(true), 1, false);
assert_eq!(f.eval(), None);
}
#[test]
fn test_returns_enabled_status() {
let f1 = Flag::new("key-string", FlagValue::Bool(true), 1, true);
let f2 = Flag::new("key-string", FlagValue::Bool(true), 1, false);
assert_eq!(f1.is_enabled(), true);
assert_eq!(f2.is_enabled(), false);
}
#[test]
fn test_checks_version() {
let f = Flag::new("key-string", FlagValue::Bool(true), 1, true);
assert_eq!(f.is_ver(1), true);
assert_eq!(f.is_ver(2), false);
}
}
|
#[doc = "Reader of register ACR"]
pub type R = crate::R<u32, super::ACR>;
#[doc = "Writer for register ACR"]
pub type W = crate::W<u32, super::ACR>;
#[doc = "Register ACR `reset()`'s with value 0x30"]
impl crate::ResetValue for super::ACR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x30
}
}
#[doc = "Latency\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum LATENCY_A {
#[doc = "0: Zero wait state, if 0 < SYSCLK≤ 24 MHz"]
WS0 = 0,
#[doc = "1: One wait state, if 24 MHz < SYSCLK ≤ 48 MHz"]
WS1 = 1,
#[doc = "2: Two wait states, if 48 MHz < SYSCLK ≤ 72 MHz"]
WS2 = 2,
}
impl From<LATENCY_A> for u8 {
#[inline(always)]
fn from(variant: LATENCY_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `LATENCY`"]
pub type LATENCY_R = crate::R<u8, LATENCY_A>;
impl LATENCY_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, LATENCY_A> {
use crate::Variant::*;
match self.bits {
0 => Val(LATENCY_A::WS0),
1 => Val(LATENCY_A::WS1),
2 => Val(LATENCY_A::WS2),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `WS0`"]
#[inline(always)]
pub fn is_ws0(&self) -> bool {
*self == LATENCY_A::WS0
}
#[doc = "Checks if the value of the field is `WS1`"]
#[inline(always)]
pub fn is_ws1(&self) -> bool {
*self == LATENCY_A::WS1
}
#[doc = "Checks if the value of the field is `WS2`"]
#[inline(always)]
pub fn is_ws2(&self) -> bool {
*self == LATENCY_A::WS2
}
}
#[doc = "Write proxy for field `LATENCY`"]
pub struct LATENCY_W<'a> {
w: &'a mut W,
}
impl<'a> LATENCY_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LATENCY_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Zero wait state, if 0 < SYSCLK≤ 24 MHz"]
#[inline(always)]
pub fn ws0(self) -> &'a mut W {
self.variant(LATENCY_A::WS0)
}
#[doc = "One wait state, if 24 MHz < SYSCLK ≤ 48 MHz"]
#[inline(always)]
pub fn ws1(self) -> &'a mut W {
self.variant(LATENCY_A::WS1)
}
#[doc = "Two wait states, if 48 MHz < SYSCLK ≤ 72 MHz"]
#[inline(always)]
pub fn ws2(self) -> &'a mut W {
self.variant(LATENCY_A::WS2)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07);
self.w
}
}
#[doc = "Reader of field `HLFCYA`"]
pub type HLFCYA_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HLFCYA`"]
pub struct HLFCYA_W<'a> {
w: &'a mut W,
}
impl<'a> HLFCYA_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 `PRFTBE`"]
pub type PRFTBE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PRFTBE`"]
pub struct PRFTBE_W<'a> {
w: &'a mut W,
}
impl<'a> PRFTBE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `PRFTBS`"]
pub type PRFTBS_R = crate::R<bool, bool>;
impl R {
#[doc = "Bits 0:2 - Latency"]
#[inline(always)]
pub fn latency(&self) -> LATENCY_R {
LATENCY_R::new((self.bits & 0x07) as u8)
}
#[doc = "Bit 3 - Flash half cycle access enable"]
#[inline(always)]
pub fn hlfcya(&self) -> HLFCYA_R {
HLFCYA_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Prefetch buffer enable"]
#[inline(always)]
pub fn prftbe(&self) -> PRFTBE_R {
PRFTBE_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Prefetch buffer status"]
#[inline(always)]
pub fn prftbs(&self) -> PRFTBS_R {
PRFTBS_R::new(((self.bits >> 5) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:2 - Latency"]
#[inline(always)]
pub fn latency(&mut self) -> LATENCY_W {
LATENCY_W { w: self }
}
#[doc = "Bit 3 - Flash half cycle access enable"]
#[inline(always)]
pub fn hlfcya(&mut self) -> HLFCYA_W {
HLFCYA_W { w: self }
}
#[doc = "Bit 4 - Prefetch buffer enable"]
#[inline(always)]
pub fn prftbe(&mut self) -> PRFTBE_W {
PRFTBE_W { w: self }
}
}
|
mod command;
mod device;
mod instance;
pub use crate::raw::command::RawVkCommandPool;
pub use crate::raw::device::{
RawVkDevice,
VkFeatures,
};
pub use crate::raw::instance::{
RawVkDebugUtils,
RawVkInstance,
};
|
pub trait IntoBoxed {
type Boxed: ?Sized;
fn into_boxed(self) -> Box<Self::Boxed>;
}
/*
impl<T: ?Sized> IntoBoxed for Box<T> {
type Boxed = T;
fn into_boxed(self) -> Box<Self::Boxed> {
self
}
}
impl<T: ?Sized> IntoBoxed for T {
type Boxed = T;
fn into_boxed(self) -> Box<Self::Boxed> {
Box::new(self)
}
}
*/
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use std::collections::HashMap;
use std::sync::Arc;
use common_arrow::arrow::buffer::Buffer;
use common_exception::Result;
use common_expression::type_check::check_function;
use common_expression::types::array::ArrayColumn;
use common_expression::types::map::KvColumn;
use common_expression::types::map::KvPair;
use common_expression::types::number::NumberScalar;
use common_expression::types::number::UInt8Type;
use common_expression::types::AnyType;
use common_expression::types::DataType;
use common_expression::types::NumberDataType;
use common_expression::types::StringType;
use common_expression::BlockEntry;
use common_expression::Column;
use common_expression::DataBlock;
use common_expression::Expr;
use common_expression::FromData;
use common_expression::FunctionContext;
use common_expression::Scalar;
use common_expression::TableDataType;
use common_expression::TableField;
use common_expression::TableSchema;
use common_expression::Value;
use common_functions::BUILTIN_FUNCTIONS;
use storages_common_index::filters::BlockFilter as LatestBloom;
use storages_common_index::BloomIndex;
use storages_common_index::FilterEvalResult;
use storages_common_table_meta::meta::Versioned;
#[test]
fn test_bloom_filter() -> Result<()> {
let schema = Arc::new(TableSchema::new(vec![
TableField::new("0", TableDataType::Number(NumberDataType::UInt8)),
TableField::new("1", TableDataType::String),
TableField::new(
"2",
TableDataType::Map(Box::new(TableDataType::Tuple {
fields_name: vec!["key".to_string(), "value".to_string()],
fields_type: vec![
TableDataType::Number(NumberDataType::UInt8),
TableDataType::String,
],
})),
),
]));
let kv_ty = DataType::Tuple(vec![
DataType::Number(NumberDataType::UInt8),
DataType::String,
]);
let map_ty = DataType::Map(Box::new(kv_ty));
let blocks = vec![
DataBlock::new(
vec![
BlockEntry {
data_type: DataType::Number(NumberDataType::UInt8),
value: Value::Scalar(Scalar::Number(NumberScalar::UInt8(1))),
},
BlockEntry {
data_type: DataType::String,
value: Value::Scalar(Scalar::String(b"a".to_vec())),
},
BlockEntry {
data_type: map_ty.clone(),
value: Value::Scalar(Scalar::Map(Column::Tuple(vec![
UInt8Type::from_data(vec![1, 2]),
StringType::from_data(vec!["a", "b"]),
]))),
},
],
2,
),
DataBlock::new_from_columns(vec![
UInt8Type::from_data(vec![2, 3]),
StringType::from_data(vec!["b", "c"]),
Column::Map(Box::new(
ArrayColumn::<KvPair<AnyType, AnyType>> {
values: KvColumn {
keys: UInt8Type::from_data(vec![1, 2, 3]),
values: StringType::from_data(vec!["b", "c", "d"]),
},
offsets: Buffer::<u64>::from(vec![0, 2, 3]),
}
.upcast(),
)),
]),
];
let blocks_ref = blocks.iter().collect::<Vec<_>>();
let index = BloomIndex::try_create(
FunctionContext::default(),
schema,
LatestBloom::VERSION,
&blocks_ref,
)?
.unwrap();
assert_eq!(
FilterEvalResult::MustFalse,
eval_index(
&index,
"0",
Scalar::Number(NumberScalar::UInt8(0)),
DataType::Number(NumberDataType::UInt8)
)
);
assert_eq!(
FilterEvalResult::Uncertain,
eval_index(
&index,
"0",
Scalar::Number(NumberScalar::UInt8(1)),
DataType::Number(NumberDataType::UInt8)
)
);
assert_eq!(
FilterEvalResult::Uncertain,
eval_index(
&index,
"0",
Scalar::Number(NumberScalar::UInt8(2)),
DataType::Number(NumberDataType::UInt8)
)
);
assert_eq!(
FilterEvalResult::Uncertain,
eval_index(&index, "1", Scalar::String(b"a".to_vec()), DataType::String)
);
assert_eq!(
FilterEvalResult::Uncertain,
eval_index(&index, "1", Scalar::String(b"b".to_vec()), DataType::String)
);
assert_eq!(
FilterEvalResult::MustFalse,
eval_index(&index, "1", Scalar::String(b"d".to_vec()), DataType::String)
);
assert_eq!(
FilterEvalResult::Uncertain,
eval_map_index(
&index,
"2",
map_ty.clone(),
Scalar::Number(NumberScalar::UInt8(1)),
DataType::Number(NumberDataType::UInt8),
Scalar::String(b"a".to_vec()),
DataType::String
)
);
assert_eq!(
FilterEvalResult::Uncertain,
eval_map_index(
&index,
"2",
map_ty.clone(),
Scalar::Number(NumberScalar::UInt8(2)),
DataType::Number(NumberDataType::UInt8),
Scalar::String(b"b".to_vec()),
DataType::String
)
);
assert_eq!(
FilterEvalResult::MustFalse,
eval_map_index(
&index,
"2",
map_ty,
Scalar::Number(NumberScalar::UInt8(3)),
DataType::Number(NumberDataType::UInt8),
Scalar::String(b"x".to_vec()),
DataType::String
)
);
Ok(())
}
fn eval_index(index: &BloomIndex, col_name: &str, val: Scalar, ty: DataType) -> FilterEvalResult {
let expr = check_function(
None,
"eq",
&[],
&[
Expr::ColumnRef {
span: None,
id: col_name.to_string(),
data_type: ty.clone(),
display_name: col_name.to_string(),
},
Expr::Constant {
span: None,
scalar: val,
data_type: ty,
},
],
&BUILTIN_FUNCTIONS,
)
.unwrap();
let point_query_cols = BloomIndex::find_eq_columns(&expr).unwrap();
let mut scalar_map = HashMap::<Scalar, u64>::new();
let func_ctx = FunctionContext::default();
for (_, scalar, ty) in point_query_cols.iter() {
if !scalar_map.contains_key(scalar) {
let digest = BloomIndex::calculate_scalar_digest(func_ctx, scalar, ty).unwrap();
scalar_map.insert(scalar.clone(), digest);
}
}
index.apply(expr, &scalar_map).unwrap()
}
fn eval_map_index(
index: &BloomIndex,
col_name: &str,
map_ty: DataType,
key: Scalar,
key_ty: DataType,
val: Scalar,
ty: DataType,
) -> FilterEvalResult {
let get_expr = check_function(
None,
"get",
&[],
&[
Expr::ColumnRef {
span: None,
id: col_name.to_string(),
data_type: map_ty,
display_name: col_name.to_string(),
},
Expr::Constant {
span: None,
scalar: key,
data_type: key_ty,
},
],
&BUILTIN_FUNCTIONS,
)
.unwrap();
let expr = check_function(
None,
"eq",
&[],
&[get_expr, Expr::Constant {
span: None,
scalar: val,
data_type: ty,
}],
&BUILTIN_FUNCTIONS,
)
.unwrap();
let point_query_cols = BloomIndex::find_eq_columns(&expr).unwrap();
let mut scalar_map = HashMap::<Scalar, u64>::new();
let func_ctx = FunctionContext::default();
for (_, scalar, ty) in point_query_cols.iter() {
if !scalar_map.contains_key(scalar) {
let digest = BloomIndex::calculate_scalar_digest(func_ctx, scalar, ty).unwrap();
scalar_map.insert(scalar.clone(), digest);
}
}
index.apply(expr, &scalar_map).unwrap()
}
|
extern crate cmake;
use std::env;
fn find_and_link_tgl(cmake_cfg: &mut cmake::Config) {
let dst = cmake_cfg.build();
let path = dst.join("build")
.join("tgl");
if cfg!(windows) {
println!("cargo:rustc-link-search=native={}", path.join("Release").display());
} else {
println!("cargo:rustc-link-search=native={}", path.display());
}
println!("cargo:rustc-link-lib=static=tplgy_tgl-static");
}
fn main() {
let mut cmake_cfg = cmake::Config::new("./src/3rdparty");
if let Ok(gen) = env::var("CMAKE_GENERATOR") {
cmake_cfg.generator(gen);
}
println!("cargo:rustc-link-search=native={}", cmake_cfg.build().join("lib").display());
find_and_link_tgl(&mut cmake_cfg);
}
|
//! This module deals with setting up file associations.
//! Since this only makes sense on Windows, this entire module is Windows-only.
use std::io;
use itertools::Itertools;
use winreg::{enums as wre, RegKey};
use crate::error::{Blame, Result};
#[derive(Debug)]
pub enum Args {
Install { amend_pathext: bool },
Uninstall,
}
impl Args {
pub fn subcommand() -> clap::App<'static, 'static> {
use clap::{AppSettings, Arg, SubCommand};
SubCommand::with_name("file-association")
.about("Manage file assocations.")
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(SubCommand::with_name("install")
.about("Install file associations.")
.arg(Arg::with_name("amend_pathext")
.help("Add script extension to PATHEXT. This allows scripts to be executed without typing the file extension.")
.long("amend-pathext")
)
)
.subcommand(SubCommand::with_name("uninstall")
.about("Uninstall file associations.")
)
}
pub fn parse(m: &clap::ArgMatches) -> Self {
match m.subcommand() {
("install", Some(m)) => Args::Install {
amend_pathext: m.is_present("amend_pathext"),
},
("uninstall", _) => Args::Uninstall,
(name, _) => panic!("bad subcommand: {:?}", name),
}
}
}
pub fn try_main(args: Args) -> Result<i32> {
match args {
Args::Install { amend_pathext } => install(amend_pathext)?,
Args::Uninstall => uninstall()?,
}
Ok(0)
}
fn install(amend_pathext: bool) -> Result<()> {
use std::env;
// Set up file association.
let cargo_eval_path = env::current_exe()?;
let cargo_eval_path = cargo_eval_path.canonicalize()?;
// We have to remove the `\\?\` prefix because, if we don't, the shell freaks out.
let cargo_eval_path = cargo_eval_path.to_string_lossy();
let cargo_eval_path = if cargo_eval_path.starts_with(r#"\\?\"#) {
&cargo_eval_path[4..]
} else {
&cargo_eval_path[..]
};
let res = (|| -> io::Result<()> {
let hlcr = RegKey::predef(wre::HKEY_CLASSES_ROOT);
let (dot_crs, _) = hlcr.create_subkey(".crs")?;
dot_crs.set_value("", &"CargoScript.Crs")?;
let (cargo_eval_crs, _) = hlcr.create_subkey("CargoScript.Crs")?;
cargo_eval_crs.set_value("", &"Cargo Script")?;
let (sh_o_c, _) = cargo_eval_crs.create_subkey(r#"shell\open\command"#)?;
sh_o_c.set_value("", &format!(r#""{}" "--" "%1" %*"#, cargo_eval_path))?;
Ok(())
})();
match res {
Ok(()) => (),
Err(e) => {
if e.kind() == io::ErrorKind::PermissionDenied {
println!(
"Access denied. Make sure you run this command from an administrator prompt."
);
return Err((Blame::Human, e).into());
} else {
return Err(e.into());
}
}
}
println!("Created cargo-eval registry entry.");
println!("- Handler set to: {}", cargo_eval_path);
// Amend PATHEXT.
if amend_pathext {
let hklm = RegKey::predef(wre::HKEY_LOCAL_MACHINE);
let env =
hklm.open_subkey(r#"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"#)?;
let pathext: String = env.get_value("PATHEXT")?;
if !pathext.split(';').any(|e| e.eq_ignore_ascii_case(".crs")) {
let pathext = pathext.split(';').chain(Some(".CRS")).join(";");
env.set_value("PATHEXT", &pathext)?;
}
println!(
"Added `.crs` to PATHEXT. You may need to log out for the change to take effect."
);
}
Ok(())
}
fn uninstall() -> Result<()> {
let hlcr = RegKey::predef(wre::HKEY_CLASSES_ROOT);
hlcr.delete_subkey(r#"CargoScript.Crs\shell\open\command"#)
.ignore_missing()?;
hlcr.delete_subkey(r#"CargoScript.Crs\shell\open"#)
.ignore_missing()?;
hlcr.delete_subkey(r#"CargoScript.Crs\shell"#)
.ignore_missing()?;
hlcr.delete_subkey(r#"CargoScript.Crs"#).ignore_missing()?;
println!("Deleted cargo-eval registry entry.");
{
let hklm = RegKey::predef(wre::HKEY_LOCAL_MACHINE);
let env =
hklm.open_subkey(r#"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"#)?;
let pathext: String = env.get_value("PATHEXT")?;
if pathext.split(';').any(|e| e.eq_ignore_ascii_case(".crs")) {
let pathext = pathext
.split(';')
.filter(|e| !e.eq_ignore_ascii_case(".crs"))
.join(";");
env.set_value("PATHEXT", &pathext)?;
println!("Removed `.crs` from PATHEXT. You may need to log out for the change to take effect.");
}
}
Ok(())
}
trait IgnoreMissing {
fn ignore_missing(self) -> Self;
}
impl IgnoreMissing for io::Result<()> {
fn ignore_missing(self) -> Self {
if let Err(ref e) = self {
if e.kind() == io::ErrorKind::NotFound {
return Ok(());
}
}
self
}
}
|
#[macro_use]
mod internal;
#[macro_use]
mod nul_str_macros;
/// Can be used to construct [`CompGenericParams`],
/// when manually implementing [`StableAbi`].
///
/// This stores indices and ranges for the type and/or const parameters taken
/// from the [`SharedVars`] stored in the same [`TypeLayout`] where this is stored.
///
/// # Syntax
///
/// `tl_genparams!( (<lifetime>),* ; <convertible_to_startlen>; <convertible_to_startlen> )`
///
/// `<convertible_to_startlen>` is a range of indices into a slice:
///
/// -` `: No elements.
///
/// -`i`: Uses the `i`th element.
///
/// -`i..j`: Uses the elements from i up to j (exclusive).
///
/// -`i..=j`: Uses the elements from i up to j (inclusive).
///
/// -`x: StartLen`: Uses the elements from `x.start()` up to `x.end()` (exclusive).
///
/// For type parameters, this conceptually references the elements from
/// the slice returned by [`SharedVars::type_layouts`].
///
/// For const parameters, this conceptually references the elements from
/// the slice returned by [`SharedVars::constants`].
///
///
/// # Example
///
/// ```rust
/// use abi_stable::{
/// type_layout::CompGenericParams,
/// tl_genparams,
/// };
///
/// const NO_ARGUMENTS: CompGenericParams = tl_genparams!(;;);
///
/// const THREE_TYPE_ARGUMENTS: CompGenericParams = tl_genparams!(; 0..=2;);
///
/// const ALL_ARGUMENTS: CompGenericParams = tl_genparams!('a,'b,'c,'d; 0; 0..3);
///
/// ```
///
///
///
/// [`MonoTypeLayout`]: ./type_layout/struct.MonoTypeLayout.html
/// [`TypeLayout`]: ./type_layout/struct.TypeLayout.html
/// [`SharedVars`]: ./type_layout/struct.SharedVars.html
/// [`SharedVars::type_layouts`]: ./type_layout/struct.SharedVars.html#method.type_layouts
/// [`SharedVars::constants`]: ./type_layout/struct.SharedVars.html#method.constants
/// [`StableAbi`]: ./trait.StableAbi.html
/// [`CompGenericParams`]: ./type_layout/struct.CompGenericParams.html
///
#[macro_export]
macro_rules! tl_genparams {
( $($lt:lifetime),* $(,)? ; $($ty:expr)? ; $($const_p:expr)? ) => ({
#[allow(unused_parens)]
let ty_param_range =
$crate::type_layout::StartLenConverter( ($($ty)?) ).to_start_len();
#[allow(unused_parens)]
let const_param_range=
$crate::type_layout::StartLenConverter( ($($const_p)?) ).to_start_len();
$crate::type_layout::CompGenericParams::new(
$crate::nulstr_trunc!($crate::pmr::concat!($(stringify!($lt),",",)*)),
$crate::pmr::count_tts!(($($lt)*)) as u8,
ty_param_range,
const_param_range,
)
})
}
///////////////////////////////////////////////////////////////////////
/// Equivalent to `?` for [`RResult`].
///
/// Accepts both `Result` and `RResult` arguments.
///
/// # Example
///
/// Defining an extern function that returns a result.
///
/// ```
/// use abi_stable::{
/// std_types::{RResult, ROk, RBoxError, RStr, Tuple3},
/// rtry,
/// sabi_extern_fn,
/// };
///
///
/// #[sabi_extern_fn]
/// fn parse_tuple(s: RStr<'_>) -> RResult<Tuple3<u32, u32, u32>, RBoxError> {
/// let mut iter = s.split(',').map(|x| x.trim());
/// ROk(Tuple3(
/// rtry!(iter.next().unwrap_or("").parse().map_err(RBoxError::new)),
/// rtry!(iter.next().unwrap_or("").parse().map_err(RBoxError::new)),
/// rtry!(iter.next().unwrap_or("").parse().map_err(RBoxError::new)),
/// ))
/// }
///
/// assert_eq!(parse_tuple("3, 5, 8".into()).unwrap(), Tuple3(3, 5, 8));
/// parse_tuple("".into()).unwrap_err();
///
///
/// ```
///
/// [`RResult`]: ./std_types/enum.RResult.html
#[macro_export]
macro_rules! rtry {
($expr:expr) => {{
match $crate::pmr::RResult::from($expr) {
$crate::pmr::ROk(x) => x,
$crate::pmr::RErr(x) => return $crate::pmr::RErr($crate::pmr::From::from(x)),
}
}};
}
/// Equivalent to `?` for [`ROption`].
///
/// Accepts both `Option` and `ROption` arguments.
///
/// # Example
///
/// ```rust
/// use abi_stable::{
/// std_types::{ROption, RSome, RNone},
/// rtry_opt,
/// sabi_extern_fn,
/// };
///
///
/// #[sabi_extern_fn]
/// fn funct(arg: ROption<u32>) -> ROption<u32> {
/// let value = rtry_opt!(Some(3));
/// RSome(value + rtry_opt!(arg))
/// }
///
/// assert_eq!(funct(RSome(5)), RSome(8));
/// assert_eq!(funct(RNone), RNone::<u32>);
///
/// ```
///
/// [`ROption`]: ./std_types/enum.ROption.html
#[macro_export]
macro_rules! rtry_opt {
($expr:expr) => {{
match $crate::pmr::ROption::from($expr) {
$crate::pmr::RSome(x) => x,
$crate::pmr::RNone => return $crate::pmr::RNone,
}
}};
}
///////////////////////////////////////////////////////////////////////
macro_rules! check_unerased {
(
$this:ident,$res:expr
) => {
if let Err(e) = $res {
return Err(e.map(move |_| $this));
}
};
}
///////////////////////////////////////////////////////////////////////
/// Use this to make sure that you handle panics inside `extern fn` correctly.
///
/// This macro causes an abort if a panic reaches this point.
///
/// It does not prevent functions inside from using `::std::panic::catch_unwind`
/// to catch the panic.
///
/// # Early returns
///
/// This macro by default wraps the passed code in a closure so that any
/// early returns that happen inside don't interfere with the macro generated code.
///
/// If you don't have an early return (a `return`/`continue`/`break`/`?`/etc.)
/// in the code passed to this macro you can use
/// `extern_fn_panic_handling!{no_early_return; <code here> }`,
/// which *might* be cheaper(this has not been tested yet).
///
/// # Example
///
/// ```
/// use std::fmt;
///
/// use abi_stable::{
/// extern_fn_panic_handling,
/// std_types::RString,
/// };
///
///
/// pub extern "C" fn print_debug<T>(this: &T, buf: &mut RString)
/// where
/// T: fmt::Debug,
/// {
/// extern_fn_panic_handling! {
/// use std::fmt::Write;
///
/// println!("{:?}", this);
/// }
/// }
/// ```
///
/// # Example, no_early_return
///
///
/// ```
/// use std::fmt;
///
/// use abi_stable::{
/// extern_fn_panic_handling,
/// std_types::RString,
/// };
///
///
/// pub extern "C" fn print_debug<T>(this: &T, buf: &mut RString)
/// where
/// T: fmt::Debug,
/// {
/// extern_fn_panic_handling!{no_early_return;
/// use std::fmt::Write;
///
/// println!("{:?}", this);
/// }
/// }
///
/// ```
///
/// # Returing in `no_early_return`
///
/// Attempting to do any kind of returning from inside of
/// `extern_fn_panic_handling!{no_early_return}`
/// will cause an abort:
///
/// ```should_panic
/// use abi_stable::extern_fn_panic_handling;
///
/// pub extern "C" fn function() {
/// extern_fn_panic_handling!{no_early_return;
/// return;
/// }
/// }
///
/// function();
///
/// ```
///
///
#[macro_export]
macro_rules! extern_fn_panic_handling {
(no_early_return; $($fn_contents:tt)* ) => ({
let aborter_guard = {
use $crate::utils::{AbortBomb,PanicInfo};
#[allow(dead_code)]
const BOMB:AbortBomb = AbortBomb{
fuse: &PanicInfo{file:file!(),line:line!()}
};
BOMB
};
let res = {
$($fn_contents)*
};
::std::mem::forget(aborter_guard);
res
});
( $($fn_contents:tt)* ) => (
#[allow(clippy::redundant_closure_call)]
{
$crate::extern_fn_panic_handling!{
no_early_return;
let a = $crate::marker_type::NotCopyNotClone;
(move||{
{a};
{
$($fn_contents)*
}
})()
}
}
)
}
///////////////////////////////////////////////////////////////////////////////////////////
/// Constructs a [`Tag`](./type_layout/tagging/struct.Tag.html),
/// a dynamically typed value for users to check extra properties about their types
/// when doing runtime type checking.
///
/// Note that this macro is not recursive,
/// you need to invoke it every time you construct an array/map/set inside of the macro.
///
/// For more examples look in the [tagging module](./type_layout/tagging/index.html)
///
/// # Example
///
/// Using tags to store the traits the type requires,
/// so that if this changes it can be reported as an error.
///
/// This will cause an error if the binary and dynamic library disagree about the values inside
/// the "required traits" map entry .
///
/// In real code this should be written in a
/// way that keeps the tags and the type bounds in sync.
///
/// ```rust
/// use abi_stable::{
/// tag,
/// type_layout::Tag,
/// StableAbi,
/// };
///
/// const TAGS: Tag = tag!{{
/// "required traits" => tag![["Copy"]],
/// }};
///
///
/// #[repr(C)]
/// #[derive(StableAbi)]
/// #[sabi(bound(T: Copy))]
/// #[sabi(tag = TAGS)]
/// struct Value<T>{
/// value: T,
/// }
///
///
/// ```
///
/// [`Tag`]: ./type_layout/tagging/struct.Tag.html
///
#[macro_export]
macro_rules! tag {
([ $( $elem:expr ),* $(,)? ])=>{{
use $crate::type_layout::tagging::{Tag,FromLiteral};
Tag::arr($crate::rslice![
$( FromLiteral($elem).to_tag(), )*
])
}};
({ $( $key:expr=>$value:expr ),* $(,)? })=>{{
use $crate::type_layout::tagging::{FromLiteral,Tag};
Tag::map($crate::rslice![
$(
Tag::kv(
FromLiteral($key).to_tag(),
FromLiteral($value).to_tag(),
),
)*
])
}};
({ $( $key:expr ),* $(,)? })=>{{
use $crate::type_layout::tagging::{Tag,FromLiteral};
Tag::set($crate::rslice![
$(
FromLiteral($key).to_tag(),
)*
])
}};
($expr:expr) => {{
$crate::type_layout::tagging::FromLiteral($expr).to_tag()
}};
}
///////////////////////////////////////////////////////////////////////////////
#[allow(unused_macros)]
macro_rules! assert_matches {
( $(|)? $($pat:pat_param)|* =$expr:expr)=>{{
let ref value=$expr;
assert!(
matches!(*value, $($pat)|* ),
"pattern did not match the value:\n\t\
{:?}
",
*value
);
}};
}
///////////////////////////////////////////////////////////////////////////////
/// Constructs an [`ItemInfo`], with information about the place where it's called.
///
/// [`ItemInfo`]: ./type_layout/struct.ItemInfo.html
#[macro_export]
macro_rules! make_item_info {
() => {
$crate::type_layout::ItemInfo::new(
concat!(env!("CARGO_PKG_NAME"), ";", env!("CARGO_PKG_VERSION")),
line!(),
$crate::type_layout::ModPath::inside($crate::nulstr_trunc!(module_path!())),
)
};
}
///////////////////////////////////////////////////////////////////////////////
/// Constructs an [`RVec`] using the same syntax that the [`std::vec`] macro uses.
///
/// # Example
///
/// ```
///
/// use abi_stable::{
/// rvec,
/// std_types::RVec,
/// };
///
/// assert_eq!(RVec::<u32>::new(), rvec![]);
/// assert_eq!(RVec::from(vec![0]), rvec![0]);
/// assert_eq!(RVec::from(vec![0, 3]), rvec![0, 3]);
/// assert_eq!(RVec::from(vec![0, 3, 6]), rvec![0, 3, 6]);
/// assert_eq!(RVec::from(vec![1; 10]), rvec![1; 10]);
///
/// ```
///
/// [`RVec`]: ./std_types/struct.RVec.html
///
/// [`std::vec`]: https://doc.rust-lang.org/std/macro.vec.html
#[macro_export]
macro_rules! rvec {
( $( $anything:tt )* ) => (
$crate::std_types::RVec::from($crate::pmr::vec![ $($anything)* ])
)
}
///////////////////////////////////////////////////////////////////////////////
/// Use this macro to construct a `abi_stable::std_types::Tuple*`
/// with the values passed to the macro.
///
/// # Example
///
/// ```
/// use abi_stable::{
/// rtuple,
/// std_types::{Tuple1, Tuple2, Tuple3, Tuple4},
/// };
///
/// assert_eq!(rtuple!(), ());
///
/// assert_eq!(rtuple!(3), Tuple1(3));
///
/// assert_eq!(rtuple!(3, 5), Tuple2(3, 5));
///
/// assert_eq!(rtuple!(3, 5, 8), Tuple3(3, 5, 8));
///
/// assert_eq!(rtuple!(3, 5, 8, 9), Tuple4(3, 5, 8, 9));
///
/// ```
///
#[macro_export]
macro_rules! rtuple {
() => {
()
};
($v0:expr $(,)* ) => {
$crate::std_types::Tuple1($v0)
};
($v0:expr,$v1:expr $(,)* ) => {
$crate::std_types::Tuple2($v0, $v1)
};
($v0:expr,$v1:expr,$v2:expr $(,)* ) => {
$crate::std_types::Tuple3($v0, $v1, $v2)
};
($v0:expr,$v1:expr,$v2:expr,$v3:expr $(,)* ) => {
$crate::std_types::Tuple4($v0, $v1, $v2, $v3)
};
}
/// Use this macro to get the type of a `Tuple*` with the types passed to the macro.
///
/// # Example
///
/// ```
/// use abi_stable::{
/// std_types::{Tuple1, Tuple2, Tuple3, Tuple4},
/// RTuple,
/// };
///
/// let tuple0: RTuple!() = ();
///
/// let tuple1: RTuple!(i32) = Tuple1(3);
///
/// let tuple2: RTuple!(i32, i32) = Tuple2(3, 5);
///
/// let tuple3: RTuple!(i32, i32, u32) = Tuple3(3, 5, 8);
///
/// let tuple4: RTuple!(i32, i32, u32, u32) = Tuple4(3, 5, 8, 9);
/// ```
///
#[macro_export]
macro_rules! RTuple {
() => (
()
);
($v0:ty $(,)* ) => (
$crate::std_types::Tuple1<$v0>
);
($v0:ty,$v1:ty $(,)* ) => (
$crate::std_types::Tuple2<$v0,$v1>
);
($v0:ty,$v1:ty,$v2:ty $(,)* ) => (
$crate::std_types::Tuple3<$v0,$v1,$v2>
);
($v0:ty,$v1:ty,$v2:ty,$v3:ty $(,)* ) => (
$crate::std_types::Tuple4<$v0,$v1,$v2,$v3>
);
}
///////////////////////////////////////////////////////////////////////////////
/// A macro to construct [`RSlice`]s.
///
/// When this macro doesn't work(due to lifetime issues),
/// you'll have to separately create a slice,
/// then pass it to the [`RSlice::from_slice`] const function.
///
/// # Examples
///
/// ```
/// use abi_stable::{
/// std_types::RSlice,
/// rslice,
/// };
///
///
/// const EMPTY: RSlice<'_, u8> = rslice![];
/// // `RSlice<'_, T>`s can be compared with `&[T]`s
/// assert_eq!(EMPTY, <&[u8]>::default());
///
/// const FOO: RSlice<'_,u8> = rslice![1, 2, 3, 5, 8, 13];
/// assert_eq!(FOO[..], [1, 2, 3, 5, 8, 13]);
///
/// ```
///
/// [`RSlice`]: ./std_types/struct.RSlice.html
///
/// [`RSlice::from_slice`]: ./std_types/struct.RSlice.html#method.from_slice
///
#[macro_export]
macro_rules! rslice {
( $( $elem:expr ),* $(,)* ) => {
$crate::std_types::RSlice::from_slice(&[ $($elem),* ])
};
}
///////////////////////////////////////////////////////////////////////////////
/// Constructs [`RStr`] constants from `&'static str` constants.
///
/// # Examples
///
/// ```
/// use abi_stable::{
/// std_types::RStr,
/// rstr,
/// };
///
///
/// const FOO: RStr<'_> = rstr!("");
/// // `RStr<'_>`s can be compared with `&str`s
/// assert_eq!(FOO, "");
///
/// const BAR_STR: &str = "1235813";
/// // constructing `RStr<'_>` from a `&str` non-literal constant
/// const BAR: RStr<'_> = rstr!(BAR_STR);
/// assert_eq!(BAR, "1235813");
/// ```
///
/// [`RStr`]: ./std_types/struct.RStr.html
///
#[macro_export]
macro_rules! rstr {
( $str:expr ) => {{
const __SABI_RSTR: $crate::std_types::RStr<'static> =
$crate::std_types::RStr::from_str($str);
__SABI_RSTR
}};
}
/// Constructs a RStr with the concatenation of the passed in strings,
/// and variables with the range for the individual strings.
macro_rules! multi_str {
(
$( #[$mod_attr:meta] )*
mod $module:ident {
$( const $variable:ident=$string:literal; )*
}
) => (
$( #[$mod_attr] )*
mod $module{
$crate::abi_stable_derive::concatenated_and_ranges!{
CONCATENATED( $($variable=$string),* )
}
}
)
}
/// Constructs a `&'static SharedVars`
macro_rules! make_shared_vars{
(
impl[$($impl_gen:tt)*] $type:ty
$(where[$($where_clause:tt)*])?;
let ($mono_shared_vars:ident,$shared_vars:ident) ={
$(
strings={
$( $variable:ident : $string:literal ),* $(,)*
},
)?
$( lifetime_indices=[ $($lifetime_indices:expr),* $(,)* ], )?
$( type_layouts=[ $($ty_layout:ty),* $(,)* ], )?
$( prefix_type_layouts=[ $($prefix_ty_layout:ty),* $(,)* ], )?
$( constant=[ $const_ty:ty => $constants:expr ], )?
};
)=>{
multi_str!{
#[allow(non_upper_case_globals)]
mod _inner_multi_str_mod{
$( $( const $variable = $string; )* )?
}
}
$( use _inner_multi_str_mod::{$($variable,)*}; )?
#[allow(non_upper_case_globals)]
const $mono_shared_vars:&'static $crate::type_layout::MonoSharedVars=
&$crate::type_layout::MonoSharedVars::new(
_inner_multi_str_mod::CONCATENATED,
rslice![ $( $($lifetime_indices),* )? ],
);
struct __ACPromoted<T>(T);
impl<$($impl_gen)*> __ACPromoted<$type>
where $($($where_clause)*)?
{
const CONST_PARAM: &'static [$crate::abi_stability::ConstGeneric] = {
&[
$($crate::abi_stability::ConstGeneric::new(&$constants),)?
]
};
const SHARED_VARS: &'static $crate::type_layout::SharedVars = {
&$crate::type_layout::SharedVars::new(
$mono_shared_vars,
rslice![
$( $( $crate::pmr::get_type_layout::<$ty_layout>,)* )?
$( $( $crate::pmr::get_prefix_field_type_layout::<$prefix_ty_layout>,)* )?
],
$crate::std_types::RSlice::from_slice(Self::CONST_PARAM),
)
};
}
let $shared_vars=__ACPromoted::<Self>::SHARED_VARS;
}
}
///////////////////////////////////////////////////////////////////////////////
/// Allows declaring a [`StaticRef`] inherent associated `const`ant
/// from possibly non-`'static` references.
///
/// This only works in inherent implementations.
///
/// This does not work in:
///
/// - trait definitions
/// - trait implementations.
/// - modules: to define a non-associated constant.
///
/// # Example
///
/// ### Basic
///
/// ```rust
/// use abi_stable::staticref;
///
/// struct NONE_REF<T>(T);
///
/// impl<T> NONE_REF<T> {
/// // Declares a `StaticRef<Option<T>>` that points to a `None`, for any `T`.
/// staticref!(const V: Option<T> = None);
/// }
///
/// let none_string: &'static Option<String> = NONE_REF::<String>::V.get();
/// assert_eq!(none_string, &None::<String>);
///
/// ```
///
/// ### More realistic
///
/// This example demonstrates how you can construct a pointer to a vtable,
/// constructed at compile-time.
///
/// ```rust
/// use abi_stable::{
/// StableAbi,
/// extern_fn_panic_handling,
/// staticref,
/// pointer_trait::CallReferentDrop,
/// prefix_type::{PrefixTypeTrait, WithMetadata},
/// };
///
/// use std::{
/// mem::ManuallyDrop,
/// ops::Deref,
/// };
///
/// fn main(){
/// let boxed = BoxLike::new(100);
///
/// assert_eq!(*boxed, 100);
/// assert_eq!(boxed.into_inner(), 100);
/// }
///
/// /// An ffi-safe `Box<T>`
/// #[repr(C)]
/// #[derive(StableAbi)]
/// pub struct BoxLike<T> {
/// data: *mut T,
///
/// vtable: VTable_Ref<T>,
///
/// _marker: std::marker::PhantomData<T>,
/// }
///
/// impl<T> BoxLike<T>{
/// pub fn new(value: T) -> Self {
/// let box_ = Box::new(value);
///
/// Self{
/// data: Box::into_raw(box_),
/// vtable: VTable::VTABLE,
/// _marker: std::marker::PhantomData,
/// }
/// }
///
/// /// Extracts the value this owns.
/// pub fn into_inner(self) -> T{
/// let this = ManuallyDrop::new(self);
/// unsafe{
/// // Must copy this before calling `self.vtable.destructor()`
/// // because otherwise it would be reading from a dangling pointer.
/// let ret = this.data.read();
/// this.vtable.destructor()(this.data,CallReferentDrop::No);
/// ret
/// }
/// }
/// }
///
///
/// impl<T> Drop for BoxLike<T>{
/// fn drop(&mut self){
/// unsafe{
/// self.vtable.destructor()(self.data, CallReferentDrop::Yes)
/// }
/// }
/// }
///
/// // `#[sabi(kind(Prefix))]` Declares this type as being a prefix-type,
/// // generating both of these types:
/// //
/// // - VTable_Prefix`: A struct with the fields up to (and including) the field with the
/// // `#[sabi(last_prefix_field)]` attribute.
/// //
/// // - VTable_Ref`: An ffi-safe pointer to `VTable`,with methods to get `VTable`'s fields.
/// //
/// #[repr(C)]
/// #[derive(StableAbi)]
/// #[sabi(kind(Prefix))]
/// struct VTable<T>{
/// #[sabi(last_prefix_field)]
/// destructor: unsafe extern "C" fn(*mut T, CallReferentDrop),
/// }
///
/// impl<T> VTable<T>{
/// staticref!(const VTABLE_VAL: WithMetadata<Self> = WithMetadata::new(
/// Self{
/// destructor: destroy_box::<T>,
/// },
/// ));
///
/// const VTABLE: VTable_Ref<T> = {
/// VTable_Ref( Self::VTABLE_VAL.as_prefix() )
/// };
/// }
///
/// unsafe extern "C" fn destroy_box<T>(v: *mut T, call_drop: CallReferentDrop) {
/// extern_fn_panic_handling! {
/// let mut box_ = Box::from_raw(v as *mut ManuallyDrop<T>);
/// if call_drop == CallReferentDrop::Yes {
/// ManuallyDrop::drop(&mut *box_);
/// }
/// drop(box_);
/// }
/// }
///
///
/// impl<T> Deref for BoxLike<T> {
/// type Target=T;
///
/// fn deref(&self)->&T{
/// unsafe{
/// &(*self.data)
/// }
/// }
/// }
/// ```
///
/// [`StaticRef`]: ./sabi_types/struct.StaticRef.html
#[macro_export]
macro_rules! staticref{
(
$(
$(#[$attr:meta])* $vis:vis const $name:ident : $ty:ty = $expr:expr
);*
$(;)?
)=>{
$crate::pmr::paste!{
$(
#[allow(unused_parens)]
#[doc(hidden)]
const [<$name _NHPMWYD3NJA>] : *const ($ty) = &($expr);
#[allow(unused_parens)]
$(#[$attr])*
$vis const $name : $crate::sabi_types::StaticRef<($ty)> = unsafe{
$crate::sabi_types::StaticRef::from_raw(
Self::[<$name _NHPMWYD3NJA>]
)
};
)*
}
};
}
///////////////////////////////////////////////////////////////////////////////
#[allow(unused_macros)]
macro_rules! delegate_interface_serde {
(
impl[$($impl_header:tt)* ] Traits<$this:ty> for $interf:ty ;
lifetime=$lt:lifetime;
delegate_to=$delegates_to:ty;
) => (
impl<$($impl_header)*> $crate::nonexhaustive_enum::SerializeEnum<$this> for $interf
where
$this:$crate::nonexhaustive_enum::GetEnumInfo,
$delegates_to:
$crate::nonexhaustive_enum::SerializeEnum<$this>
{
type Proxy=<
$delegates_to as
$crate::nonexhaustive_enum::SerializeEnum<$this>
>::Proxy;
fn serialize_enum<'a>(
this:&'a $this
) -> Result<Self::Proxy, $crate::std_types::RBoxError>{
<$delegates_to>::serialize_enum(this)
}
}
impl<$lt,$($impl_header)* S,I>
$crate::nonexhaustive_enum::DeserializeEnum<
$lt,
$crate::nonexhaustive_enum::NonExhaustive<$this,S,I>
>
for $interf
where
$this:$crate::nonexhaustive_enum::GetEnumInfo+$lt,
$delegates_to:
$crate::nonexhaustive_enum::DeserializeEnum<
$lt,
$crate::nonexhaustive_enum::NonExhaustive<$this,S,I>
>
{
type Proxy=<
$delegates_to as
$crate::nonexhaustive_enum::DeserializeEnum<
$lt,
$crate::nonexhaustive_enum::NonExhaustive<$this,S,I>
>
>::Proxy;
fn deserialize_enum(
s: Self::Proxy
) -> Result<
$crate::nonexhaustive_enum::NonExhaustive<$this,S,I>,
$crate::std_types::RBoxError
>
{
<$delegates_to as
$crate::nonexhaustive_enum::DeserializeEnum<
$crate::nonexhaustive_enum::NonExhaustive<$this,S,I>
>
>::deserialize_enum(s)
}
}
)
}
|
use std::{
fmt::{Debug, Display},
sync::Arc,
};
use async_trait::async_trait;
use data_types::{CompactionLevel, ParquetFileParams};
use datafusion::{error::DataFusionError, physical_plan::SendableRecordBatchStream};
use iox_time::Time;
use crate::partition_info::PartitionInfo;
pub mod dedicated;
pub mod logging;
pub mod mock;
pub mod object_store;
/// Writes streams if data to the object store as one or more parquet files
#[async_trait]
pub trait ParquetFileSink: Debug + Display + Send + Sync {
async fn store(
&self,
stream: SendableRecordBatchStream,
partition: Arc<PartitionInfo>,
level: CompactionLevel,
max_l0_created_at: Time,
) -> Result<Option<ParquetFileParams>, DataFusionError>;
}
#[async_trait]
impl<T> ParquetFileSink for Arc<T>
where
T: ParquetFileSink + ?Sized,
{
async fn store(
&self,
stream: SendableRecordBatchStream,
partition: Arc<PartitionInfo>,
level: CompactionLevel,
max_l0_created_at: Time,
) -> Result<Option<ParquetFileParams>, DataFusionError> {
self.as_ref()
.store(stream, partition, level, max_l0_created_at)
.await
}
}
|
#![cfg(test)]
mod process;
mod utils;
|
fn main() {
}
#[test]
fn test_shadowing() {
let mut x: i32 = 1;
x = 7;
let x = x;
let y = 4;
let y = "I can also be bound to text!";
print_number(5);
print_number(add_one(6));
let f: fn(i32) -> i32;
}
fn print_number(x: i32) {
println!("x is: {}", x);
}
fn add_one(x: i32) -> i32 {
x + 1
}
#[test]
fn test_if() {
let x = 5;
if x == 5 {
println!("x is five!");
} else if x == 6 {
println!("x is six!");
} else {
println!("x is not five or six :(");
}
}
#[test]
fn test_while() {
let mut x = 5;
let mut done = false;
while !done {
x += x - 3;
println!("{}", x);
if x % 5 == 0 {
done = true;
}
}
}
#[test]
fn test_for() {
for x in 0..10 {
println!( "{}", x );
}
}
#[test]
fn test_enumerate() {
for (i,j) in (5..10).enumerate() {
println!("i = {} and j = {}", i, j);
}
}
#[test]
fn test_iteration() {
let lines = "hello\nworld".lines();
for (linenumber, line) in lines.enumerate() {
println!("{}: {}", linenumber, line);
}
}
#[test]
fn test_iteration_end_early() {
let mut x = 5;
let mut done = false;
while !done {
x += x - 3;
println!("{}", x);
if x % 5 == 0 {
done = true;
}
}
}
#[test]
fn test_iteration_end_early_2() {
let mut x = 5;
loop {
x += x - 3;
println!("{}", x);
if x % 5 == 0 { break; }
}
}
#[test]
fn test_for_continue() {
for x in 0..10 {
if x % 2 == 0 { continue; }
}
}
#[test]
fn test_loop_labels() {
'outer: for x in 0..10 {
'inner: for y in 0..10 {
if x % 2 == 0 { continue 'outer; }
if y % 2 == 0 {continue 'inner; }
println!("x: {}, y:{}", x, y);
}
}
}
|
struct Detector { }
trait Detect<T> {
fn detect(input: T);
}
impl Detect<i32> for Detector {
fn detect(input: i32) {
println!("{} is i32", input);
}
}
impl Detect<&'static str> for Detector {
fn detect(input: &'static str) {
println!("{} is &str", input);
}
}
fn main() {
Detector::detect(12); // => 12 is i32
Detector::detect("XYZ"); // => XYZ is &str
}
|
pub mod communication;
pub mod foreman;
pub mod map;
pub mod miner;
pub mod system;
|
//! Channel flavors.
//!
//! There are six flavors:
//!
//! 1. `after` - Channel that delivers a message after a certain amount of time.
//! 2. `array` - Bounded channel based on a preallocated array.
//! 3. `list` - Unbounded channel implemented as a linked list.
//! 4. `never` - Channel that never delivers messages.
//! 5. `tick` - Channel that delivers messages periodically.
//! 6. `zero` - Zero-capacity channel.
pub mod after;
pub mod array;
pub mod list;
pub mod never;
pub mod tick;
pub mod zero;
|
// 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.
use crate::errors::Error;
use crate::metrics::RampReporter;
use crate::onramp;
use crate::pipeline;
use crate::preprocessor::{make_preprocessors, preprocess, Preprocessors};
use crate::url::ports::{ERR, METRICS, OUT};
use crate::url::TremorUrl;
use crate::{
codec::{self, Codec},
pipeline::ConnectTarget,
};
use crate::Result;
use async_channel::{self, unbounded, Receiver, Sender};
use async_std::task;
use beef::Cow;
use halfbrown::HashMap;
use std::collections::BTreeMap;
use std::time::Duration;
use tremor_common::time::nanotime;
use tremor_pipeline::{CbAction, Event, EventId, EventOriginUri, DEFAULT_STREAM_ID};
use tremor_script::prelude::*;
use self::prelude::OnrampConfig;
pub(crate) mod amqp;
pub(crate) mod blaster;
pub(crate) mod cb;
pub(crate) mod crononome;
pub(crate) mod discord;
pub(crate) mod env;
pub(crate) mod file;
pub(crate) mod gsub;
pub(crate) mod kafka;
pub(crate) mod metronome;
pub(crate) mod nats;
pub(crate) mod otel;
pub(crate) mod postgres;
pub(crate) mod prelude;
pub(crate) mod rest;
pub(crate) mod sse;
pub(crate) mod stdin;
pub(crate) mod tcp;
pub(crate) mod udp;
pub(crate) mod ws;
struct StaticValue(Value<'static>);
#[derive(Default)]
/// Set of pre and postprocessors
pub struct Processors<'processor> {
/// preprocessors
pub pre: &'processor [String],
/// postprocessors
pub post: &'processor [String],
}
#[derive(Debug)]
pub(crate) enum SourceState {
Connected,
Disconnected,
}
#[derive(Debug)]
pub(crate) enum SourceReply {
/// A normal batch_data event with a `Vec<Vec<u8>>` for data
BatchData {
origin_uri: EventOriginUri,
batch_data: Vec<(Vec<u8>, Option<Value<'static>>)>,
/// allow source to override codec when pulling event
/// the given string must be configured in the `config-map` as part of the source config
codec_override: Option<String>,
stream: usize,
},
/// A normal data event with a `Vec<u8>` for data
Data {
origin_uri: EventOriginUri,
data: Vec<u8>,
meta: Option<Value<'static>>,
/// allow source to override codec when pulling event
/// the given string must be configured in the `config-map` as part of the source config
codec_override: Option<String>,
stream: usize,
},
/// Allow for passthrough of already structured events
Structured {
origin_uri: EventOriginUri,
data: EventPayload,
},
/// A stream is opened
StartStream(usize),
/// A stream is closed
EndStream(usize),
/// We change the connection state of the source
StateChange(SourceState),
/// There is no event currently ready and we're asked to wait an amount of ms
Empty(u64),
}
#[async_trait::async_trait]
pub(crate) trait Source {
/// Pulls an event from the source if one exists
/// determine the codec to be used
async fn pull_event(&mut self, id: u64) -> Result<SourceReply>;
/// This callback is called when the data provided from
/// pull_event did not create any events, this is needed for
/// linked sources that require a 1:1 mapping between requests
/// and responses, we're looking at you REST
async fn on_empty_event(&mut self, _id: u64, _stream: usize) -> Result<()> {
Ok(())
}
/// Send event back from source (for linked onramps)
async fn reply_event(
&mut self,
_event: Event,
_codec: &dyn Codec,
_codec_map: &HashMap<String, Box<dyn Codec>>,
) -> Result<()> {
Ok(())
}
/// Pulls metrics from the source
fn metrics(&mut self, _t: u64) -> Vec<Event> {
vec![]
}
/// Initializes the onramp (ideally this should be idempotent)
async fn init(&mut self) -> Result<SourceState>;
/// Graceful shutdown
async fn terminate(&mut self) {}
/// Trigger the circuit breaker on the source
fn trigger_breaker(&mut self) {}
/// Restore the circuit breaker on the source
fn restore_breaker(&mut self) {}
/// Acknowledge an event
fn ack(&mut self, _id: u64) {}
/// Fail an event
fn fail(&mut self, _id: u64) {}
/// Gives a human readable ID for the source
fn id(&self) -> &TremorUrl;
/// Is this source transactional or can acks/fails be ignored
fn is_transactional(&self) -> bool {
false
}
}
fn make_error(source_id: String, e: &Error, original_id: u64) -> tremor_script::EventPayload {
error!("[Source::{}] Error decoding event data: {}", source_id, e);
let mut meta = Object::with_capacity(1);
meta.insert_nocheck("error".into(), e.to_string().into());
let mut data = Object::with_capacity(3);
data.insert_nocheck("error".into(), e.to_string().into());
data.insert_nocheck("event_id".into(), original_id.into());
data.insert_nocheck("source_id".into(), source_id.into());
(Value::from(data), Value::from(meta)).into()
}
pub(crate) struct SourceManager<T>
where
T: Source,
{
source_id: TremorUrl,
source: T,
rx: Receiver<onramp::Msg>,
tx: Sender<onramp::Msg>,
pp_template: Vec<String>,
preprocessors: BTreeMap<usize, Preprocessors>,
codec: Box<dyn Codec>,
codec_map: HashMap<String, Box<dyn Codec>>,
metrics_reporter: RampReporter,
triggered: bool,
pipelines_out: Vec<(TremorUrl, pipeline::Addr)>,
pipelines_err: Vec<(TremorUrl, pipeline::Addr)>,
err_required: bool,
id: u64,
is_transactional: bool,
/// Unique Id for the source
uid: u64,
}
impl<T> SourceManager<T>
where
T: Source + Send + 'static + std::fmt::Debug,
{
fn handle_pp(
&mut self,
stream: usize,
ingest_ns: &mut u64,
data: Vec<u8>,
) -> Result<Vec<Vec<u8>>> {
if let Some(preprocessors) = self.preprocessors.get_mut(&stream) {
preprocess(
preprocessors.as_mut_slice(),
ingest_ns,
data,
&self.source_id,
)
} else {
Err(format!(
"[Source:{}] Failed to fetch preprocessors for stream {}",
self.source_id, stream,
)
.into())
}
}
async fn make_event_data(
&mut self,
stream: usize,
ingest_ns: &mut u64,
codec_override: Option<String>,
data: Vec<u8>,
meta: Option<StaticValue>, // See: https://github.com/rust-lang/rust/issues/63033
) -> Vec<Result<EventPayload>> {
let mut results = vec![];
match self.handle_pp(stream, ingest_ns, data) {
Ok(data) => {
let meta_value = meta.map_or_else(Value::object, |m| m.0);
for d in data {
let line_value = EventPayload::try_new::<Option<Error>, _>(d, |mut_data| {
let codec_map = &mut self.codec_map;
let codec = codec_override
.as_ref()
.and_then(|codec_name| codec_map.get_mut(codec_name))
.unwrap_or(&mut self.codec);
let decoded = codec.decode(mut_data, *ingest_ns);
match decoded {
Ok(None) => Err(None),
Err(e) => Err(Some(e)),
Ok(Some(decoded)) => {
Ok(ValueAndMeta::from_parts(decoded, meta_value.clone()))
}
}
});
match line_value {
Ok(decoded) => results.push(Ok(decoded)),
Err(None) => (),
Err(Some(e)) => {
// TODO: add error context (with error handling update)
results.push(Err(e));
}
}
}
}
Err(e) => {
// record preprocessor failures too
// TODO: add error context (with error handling update)
results.push(Err(e));
}
}
results
}
fn needs_pipeline_msg(&self) -> bool {
self.pipelines_out.is_empty()
|| self.triggered
|| !self.rx.is_empty()
|| (self.err_required && self.pipelines_err.is_empty())
}
async fn handle_pipelines(&mut self) -> Result<bool> {
loop {
let msg = if self.needs_pipeline_msg() {
self.rx.recv().await?
} else {
return Ok(false);
};
match msg {
onramp::Msg::Connect(port, ps) => {
if port.eq_ignore_ascii_case(METRICS.as_ref()) {
if ps.len() > 1 {
warn!("[Source::{}] Connecting more than 1 metrics pipelines will only connect the latest.", self.source_id);
}
for p in ps {
info!(
"[Source::{}] Connecting {} as metrics pipeline.",
self.source_id, p.0
);
self.metrics_reporter.set_metrics_pipeline(p);
}
} else {
for p in ps {
let pipelines = if port == OUT {
&mut self.pipelines_out
} else if port == ERR {
&mut self.pipelines_err
} else {
return Err(format!(
"Invalid Onramp Port: {}. Cannot connect.",
port
)
.into());
};
let msg = pipeline::MgmtMsg::ConnectInput {
input_url: self.source_id.clone(),
target: ConnectTarget::Onramp(self.tx.clone()),
transactional: self.is_transactional,
};
p.1.send_mgmt(msg).await?;
pipelines.push(p);
}
}
}
onramp::Msg::Disconnect { id, tx } => {
for (_, p) in self
.pipelines_out
.iter()
.chain(self.pipelines_err.iter())
.filter(|(pid, _)| pid == &id)
{
p.send_mgmt(pipeline::MgmtMsg::DisconnectInput(id.clone()))
.await?;
}
let mut empty_pipelines = true;
self.pipelines_out.retain(|(pipeline, _)| pipeline != &id);
empty_pipelines &= self.pipelines_out.is_empty();
self.pipelines_err.retain(|(pipeline, _)| pipeline != &id);
empty_pipelines &= self.pipelines_err.is_empty();
tx.send(empty_pipelines).await?;
if empty_pipelines {
self.source.terminate().await;
return Ok(true);
}
}
onramp::Msg::Cb(CbAction::Fail, ids) => {
// TODO: stream handling
// when failing, we use the earliest/min event within the tracked set
if let Some((_stream_id, id)) = ids.get_min_by_source(self.uid) {
self.source.fail(id);
}
}
// Circuit breaker explicit acknowledgement of an event
onramp::Msg::Cb(CbAction::Ack, ids) => {
// TODO: stream handling
// when acknowledging, we use the latest/max event within the tracked set
if let Some((_stream_id, id)) = ids.get_max_by_source(self.uid) {
self.source.ack(id);
}
}
// Circuit breaker source failure - triggers close
onramp::Msg::Cb(CbAction::Close, _ids) => {
self.source.trigger_breaker();
self.triggered = true;
}
//Circuit breaker source recovers - triggers open
onramp::Msg::Cb(CbAction::Open, _ids) => {
self.source.restore_breaker();
self.triggered = false;
}
onramp::Msg::Cb(CbAction::None, _ids) => {}
onramp::Msg::Response(event) => {
if let Err(e) = self
.source
.reply_event(event, self.codec.as_ref(), &self.codec_map)
.await
{
error!(
"[Source::{}] [Onramp] failed to reply event from source: {}",
self.source_id, e
);
}
}
}
}
}
pub(crate) async fn transmit_event(
&mut self,
data: EventPayload,
ingest_ns: u64,
origin_uri: EventOriginUri,
port: Cow<'static, str>,
) -> bool {
let event = Event {
// TODO: use EventIdGen and stream handling
id: EventId::new(self.uid, DEFAULT_STREAM_ID, self.id),
data,
ingest_ns,
// TODO make origin_uri non-optional here too?
origin_uri: Some(origin_uri),
transactional: self.is_transactional,
..Event::default()
};
let mut error = false;
self.id += 1;
let pipelines = if OUT == port {
&mut self.pipelines_out
} else if ERR == port {
&mut self.pipelines_err
} else {
return false;
};
if let Some((last, pipelines)) = pipelines.split_last_mut() {
if let Some(t) = self.metrics_reporter.periodic_flush(ingest_ns) {
self.metrics_reporter.send(self.source.metrics(t));
}
// TODO refactor metrics_reporter to do this by port now
if ERR == port {
self.metrics_reporter.increment_err();
} else {
self.metrics_reporter.increment_out();
}
for (input, addr) in pipelines {
if let Some(input) = input.instance_port() {
if let Err(e) = addr
.send(pipeline::Msg::Event {
input: input.to_string().into(),
event: event.clone(),
})
.await
{
error!(
"[Source::{}] [Onramp] failed to send to pipeline: {}",
self.source_id, e
);
error = true;
}
}
}
if let Some(input) = last.0.instance_port() {
if let Err(e) = last
.1
.send(pipeline::Msg::Event {
input: input.to_string().into(),
event,
})
.await
{
error!(
"[Source::{}] [Onramp] failed to send to pipeline: {}",
self.source_id, e
);
error = true;
}
}
}
error
}
async fn new(mut source: T, config: OnrampConfig<'_>) -> Result<(Self, Sender<onramp::Msg>)> {
// We use a unbounded channel for counterflow, while an unbounded channel seems dangerous
// there is soundness to this.
// The unbounded channel ensures that on counterflow we never have to block, or in other
// words that sinks or pipelines sending data backwards always can progress past
// the sending.
// This prevents a livelock where the pipeline is waiting for a full channel to send data to
// the source and the source is waiting for a full channel to send data to the pipeline.
// We prevent unbounded growth by two mechanisms:
// 1) counterflow is ALWAYS and ONLY created in response to a message
// 2) we always process counterflow prior to forward flow
//
// As long as we have counterflow messages to process, and channel size is growing we do
// not process any forward flow. Without forward flow we stave the counterflow ensuring that
// the counterflow channel is always bounded by the forward flow in a 1:N relationship where
// N is the maximum number of counterflow events a single event can trigger.
// N is normally < 1.
let (tx, rx) = unbounded();
let codec = codec::lookup(config.codec)?;
let mut resolved_codec_map = codec::builtin_codec_map();
// override the builtin map
for (k, v) in config.codec_map {
resolved_codec_map.insert(k, codec::lookup(&v)?);
}
let pp_template = config.processors.pre.to_vec();
let mut preprocessors = BTreeMap::new();
preprocessors.insert(0, make_preprocessors(&pp_template)?);
source.init().await?;
let is_transactional = source.is_transactional();
Ok((
Self {
source_id: source.id().clone(),
pp_template,
source,
rx,
tx: tx.clone(),
preprocessors,
//postprocessors,
codec,
codec_map: resolved_codec_map,
metrics_reporter: config.metrics_reporter,
triggered: false,
id: 0,
pipelines_out: Vec::new(),
pipelines_err: Vec::new(),
uid: config.onramp_uid,
is_transactional,
err_required: config.err_required,
},
tx,
))
}
async fn start(source: T, config: OnrampConfig<'_>) -> Result<onramp::Addr> {
let name = source.id().short_id("src");
let (manager, tx) = SourceManager::new(source, config).await?;
task::Builder::new().name(name).spawn(manager.run())?;
Ok(tx)
}
async fn route_result(
&mut self,
results: Vec<Result<tremor_script::EventPayload>>,
original_id: u64,
ingest_ns: u64,
origin_uri: EventOriginUri,
) -> bool {
let mut error = false;
for result in results {
let (port, data) = result.map_or_else(
|e| (ERR, make_error(self.source_id.to_string(), &e, original_id)),
|data| (OUT, data),
);
error |= self
.transmit_event(data, ingest_ns, origin_uri.clone(), port)
.await;
}
error
}
async fn run(mut self) -> Result<()> {
loop {
if self.handle_pipelines().await? {
return Ok(());
}
let pipelines_out_empty = self.pipelines_out.is_empty();
if !self.triggered && !pipelines_out_empty {
match self.source.pull_event(self.id).await {
Ok(SourceReply::StartStream(id)) => {
self.preprocessors
.insert(id, make_preprocessors(&self.pp_template)?);
}
Ok(SourceReply::EndStream(id)) => {
self.preprocessors.remove(&id);
}
Ok(SourceReply::Structured { origin_uri, data }) => {
let ingest_ns = nanotime();
self.transmit_event(data, ingest_ns, origin_uri, OUT).await;
}
Ok(SourceReply::BatchData {
mut origin_uri,
batch_data,
codec_override,
stream,
}) => {
for (data, meta_data) in batch_data {
origin_uri.maybe_set_uid(self.uid);
let mut ingest_ns = nanotime();
let original_id = self.id;
let results = self
.make_event_data(
stream,
&mut ingest_ns,
codec_override.clone(),
data,
meta_data.map(StaticValue),
)
.await;
if results.is_empty() {
self.source.on_empty_event(original_id, stream).await?;
}
let error = self
.route_result(results, original_id, ingest_ns, origin_uri.clone())
.await;
// We ONLY fail on transmit errors as preprocessor errors might be
// problematic
if error {
self.source.fail(original_id);
}
}
}
Ok(SourceReply::Data {
mut origin_uri,
data,
meta,
codec_override,
stream,
}) => {
origin_uri.maybe_set_uid(self.uid);
let mut ingest_ns = nanotime();
let original_id = self.id;
let results = self
.make_event_data(
stream,
&mut ingest_ns,
codec_override,
data,
meta.map(StaticValue),
)
.await;
if results.is_empty() {
self.source.on_empty_event(original_id, stream).await?;
}
let error = self
.route_result(results, original_id, ingest_ns, origin_uri)
.await;
// We ONLY fail on transmit errors as preprocessor errors might be
// problematic
if error {
self.source.fail(original_id);
}
}
Ok(SourceReply::StateChange(SourceState::Disconnected)) => return Ok(()),
Ok(SourceReply::StateChange(SourceState::Connected)) => (),
Ok(SourceReply::Empty(sleep_ms)) => {
task::sleep(Duration::from_millis(sleep_ms)).await;
}
Err(e) => {
warn!("[Source::{}] Error: {}", self.source_id, e);
self.metrics_reporter.increment_err();
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug)]
struct FakeSource {
url: TremorUrl,
}
#[async_trait::async_trait]
impl Source for FakeSource {
async fn pull_event(&mut self, _id: u64) -> Result<SourceReply> {
Ok(SourceReply::Data {
origin_uri: EventOriginUri::default(),
codec_override: None,
stream: 0,
data: "data".as_bytes().to_vec(),
meta: None,
})
}
async fn init(&mut self) -> Result<SourceState> {
Ok(SourceState::Connected)
}
fn id(&self) -> &TremorUrl {
&self.url
}
}
#[async_std::test]
async fn fake_source_manager_connect_cb() -> Result<()> {
let onramp_url = TremorUrl::from_onramp_id("fake")?;
let s = FakeSource {
url: onramp_url.clone(),
};
let o_config = OnrampConfig {
onramp_uid: 1,
codec: "string",
codec_map: HashMap::new(),
processors: Processors::default(),
metrics_reporter: RampReporter::new(onramp_url.clone(), None),
is_linked: false,
err_required: false,
};
let (sm, sender) = SourceManager::new(s, o_config).await?;
let handle = task::spawn(sm.run());
let pipeline_url = TremorUrl::parse("/pipeline/bla/01/in")?;
let (tx1, rx1) = async_channel::unbounded();
let (tx2, _rx2) = async_channel::unbounded();
let (tx3, rx3) = async_channel::unbounded();
let addr = pipeline::Addr::new(tx1, tx2, tx3, pipeline_url.clone());
// trigger the source to ensure it is not being pulled from
sender
.send(onramp::Msg::Cb(CbAction::Close, EventId::default()))
.await?;
// connect our fake pipeline
sender
.send(onramp::Msg::Connect(
OUT,
vec![(pipeline_url.clone(), addr)],
))
.await?;
let answer = rx3.recv().await?;
match answer {
pipeline::MgmtMsg::ConnectInput {
input_url,
transactional,
..
} => {
assert_eq!(input_url, onramp_url);
assert_eq!(transactional, false);
}
_ => return Err("Invalid Pipeline connect answer.".into()),
}
// ensure no events are pulled as long as we are not opened yet
task::sleep(Duration::from_millis(200)).await;
assert!(rx1.try_recv().is_err()); // nothing put into connected pipeline yet
// send the initial open event
sender
.send(onramp::Msg::Cb(CbAction::Open, EventId::default()))
.await?;
// yield so we can let other tasks progress
task::yield_now().await;
let mut n = 0;
while rx1.len() == 0 && n < 10 {
task::sleep(Duration::from_millis(100)).await;
n += 1;
}
assert!(rx1.len() > 0);
let (tx4, rx4) = async_channel::unbounded();
// disconnect to break the busy loop
sender
.send(onramp::Msg::Disconnect {
id: pipeline_url,
tx: tx4,
})
.await?;
assert_eq!(rx4.recv().await?, true);
handle.cancel().await;
Ok(())
}
#[test]
fn make_error() {
let source_id = "snot".to_string();
let e = Error::from("oh no!");
let original_id = 5;
let error_result = super::make_error(source_id.clone(), &e, original_id);
let mut expec_meta = Object::with_capacity(1);
expec_meta.insert_nocheck("error".into(), e.to_string().into());
let mut expec_data = Object::with_capacity(3);
expec_data.insert_nocheck("error".into(), e.to_string().into());
expec_data.insert_nocheck("event_id".into(), original_id.into());
expec_data.insert_nocheck("source_id".into(), source_id.into());
assert_eq!(error_result.suffix().value(), &Value::from(expec_data));
assert_eq!(error_result.suffix().meta(), &Value::from(expec_meta));
// testing with a second set of inputs
let source_id = "tremor-source-testing".to_string();
let e = Error::from("error oh no!!!");
let original_id = 7;
let error_result = super::make_error(source_id.clone(), &e, original_id);
let mut expec_meta = Object::with_capacity(1);
expec_meta.insert_nocheck("error".into(), e.to_string().into());
let mut expec_data = Object::with_capacity(3);
expec_data.insert_nocheck("error".into(), e.to_string().into());
expec_data.insert_nocheck("event_id".into(), original_id.into());
expec_data.insert_nocheck("source_id".into(), source_id.into());
assert_eq!(error_result.suffix().value(), &Value::from(expec_data));
assert_eq!(error_result.suffix().meta(), &Value::from(expec_meta));
}
}
|
use std::fmt::Display;
use async_trait::async_trait;
use data_types::{Partition, PartitionId};
use super::PartitionSource;
#[derive(Debug)]
pub struct MockPartitionSource {
partitions: Vec<Partition>,
}
impl MockPartitionSource {
#[allow(dead_code)] // not used anywhere
pub fn new(partitions: Vec<Partition>) -> Self {
Self { partitions }
}
}
impl Display for MockPartitionSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "mock")
}
}
#[async_trait]
impl PartitionSource for MockPartitionSource {
async fn fetch_by_id(&self, partition_id: PartitionId) -> Option<Partition> {
self.partitions
.iter()
.find(|p| p.id == partition_id)
.cloned()
}
}
#[cfg(test)]
mod tests {
use iox_tests::PartitionBuilder;
use super::*;
#[test]
fn test_display() {
assert_eq!(MockPartitionSource::new(vec![]).to_string(), "mock",);
}
#[tokio::test]
async fn test_fetch_by_id() {
let cj_1 = PartitionBuilder::new(5).build();
let cj_2 = PartitionBuilder::new(1).build();
let cj_3 = PartitionBuilder::new(12).build();
let compaction_jobs = vec![cj_1.clone(), cj_2.clone(), cj_3.clone()];
let source = MockPartitionSource::new(compaction_jobs);
assert_eq!(
source.fetch_by_id(PartitionId::new(5)).await,
Some(cj_1.clone())
);
assert_eq!(
source.fetch_by_id(PartitionId::new(1)).await,
Some(cj_2.clone())
);
// fetching does not drain
assert_eq!(
source.fetch_by_id(PartitionId::new(5)).await,
Some(cj_1.clone())
);
// unknown table => None result
assert_eq!(source.fetch_by_id(PartitionId::new(3)).await, None,);
}
}
|
use anyhow::{Context, Error, Result};
use pathfinder_common::event::Event;
use pathfinder_common::{
BlockHash, BlockNumber, BlockTimestamp, Chain, ChainId, EventCommitment, SequencerAddress,
StarknetVersion, StateCommitment, TransactionCommitment, TransactionSignatureElem,
};
use pathfinder_merkle_tree::TransactionOrEventTree;
use stark_hash::{stark_hash, Felt, HashChain};
use starknet_gateway_types::reply::{
transaction::{Receipt, Transaction},
Block,
};
#[derive(Debug, PartialEq, Eq)]
pub enum VerifyResult {
Match((TransactionCommitment, EventCommitment)),
Mismatch,
NotVerifiable,
}
/// Verify the block hash value.
///
/// The method to compute the block hash is documented
/// [here](https://docs.starknet.io/docs/Blocks/header/#block-hash).
///
/// Unfortunately that'a not-fully-correct description, since the transaction
/// commitment Merkle tree is not constructed directly with the transaction
/// hashes, but with a hash computed from the transaction hash and the signature
/// values (for invoke transactions).
///
/// See the `compute_block_hash.py` helper script that uses the cairo-lang
/// Python implementation to compute the block hash for details.
pub fn verify_block_hash(
block: &Block,
chain: Chain,
chain_id: ChainId,
expected_block_hash: BlockHash,
) -> Result<VerifyResult> {
let meta_info = meta::for_chain(chain);
if !meta_info.can_verify(block.block_number) {
return Ok(VerifyResult::NotVerifiable);
}
let num_transactions: u64 = block
.transactions
.len()
.try_into()
.expect("too many transactions in block");
let transaction_final_hash_type =
TransactionCommitmentFinalHashType::for_version(&block.starknet_version)?;
let transaction_commitment =
calculate_transaction_commitment(&block.transactions, transaction_final_hash_type)?;
let event_commitment = calculate_event_commitment(&block.transaction_receipts)?;
let verified = if meta_info.uses_pre_0_7_hash_algorithm(block.block_number) {
anyhow::ensure!(
chain != Chain::Custom,
"Chain::Custom should not have any pre 0.7 block hashes"
);
let block_hash = compute_final_hash_pre_0_7(
block.block_number,
block.state_commitment,
num_transactions,
transaction_commitment.0,
block.parent_block_hash,
chain_id,
);
block_hash == expected_block_hash
} else {
let num_events = number_of_events_in_block(block);
let num_events: u64 = num_events.try_into().expect("too many events in block");
let block_sequencer_address = block
.sequencer_address
.unwrap_or(SequencerAddress(Felt::ZERO));
std::iter::once(&block_sequencer_address)
.chain(meta_info.fallback_sequencer_address.iter())
.any(|address| {
let block_hash = compute_final_hash(
block.block_number,
block.state_commitment,
address,
block.timestamp,
num_transactions,
transaction_commitment.0,
num_events,
event_commitment.0,
block.parent_block_hash,
);
block_hash == expected_block_hash
})
};
Ok(match verified {
false => VerifyResult::Mismatch,
true => VerifyResult::Match((transaction_commitment, event_commitment)),
})
}
mod meta {
use pathfinder_common::{sequencer_address, BlockNumber, Chain, SequencerAddress};
use std::ops::Range;
/// Metadata about Starknet chains we use for block hash calculation
///
/// Since the method for calculating block hashes has changed during the
/// operation of the Starknet alpha network, we need this information
/// to be able to decide which method to use for block hash calculation.
///
/// * Before the Starknet 0.7 release block hashes were calculated with
/// a slightly different algorithm (the Starknet chain ID was hashed
/// into the final value). Zero was used both instead of the block
/// timestamp and the sequencer value.
/// * After Starknet 0.7 and before Starknet 0.8 the block hash does
/// not include the chain id anymore. The proper block timestamp is used
/// but zero is used as the sequencer address.
/// * After Starknet 0.8 and before Starknet 0.8.2 the sequencer address
/// is non-zero and is used for the block hash calculation. However, the
/// blocks don't include the sequencer address that was used for the
/// calculation and for the majority of the blocks the block hash
/// value is irrecoverable.
/// * After Starknet 0.8.2 all blocks include the correct sequencer address
/// value.
#[derive(Clone)]
pub struct BlockHashMetaInfo {
/// The number of the first block that was hashed with the Starknet 0.7 hash algorithm.
pub first_0_7_block: BlockNumber,
/// The range of block numbers that can't be verified because of an unknown sequencer address.
pub not_verifiable_range: Option<Range<BlockNumber>>,
/// Fallback sequencer address to use for blocks that don't include the address.
pub fallback_sequencer_address: Option<SequencerAddress>,
}
impl BlockHashMetaInfo {
pub fn can_verify(&self, block_number: BlockNumber) -> bool {
match &self.not_verifiable_range {
Some(range) => !range.contains(&block_number),
None => true,
}
}
pub fn uses_pre_0_7_hash_algorithm(&self, block_number: BlockNumber) -> bool {
block_number < self.first_0_7_block
}
}
const TESTNET_METAINFO: BlockHashMetaInfo = BlockHashMetaInfo {
first_0_7_block: BlockNumber::new_or_panic(47028),
not_verifiable_range: Some(
BlockNumber::new_or_panic(119802)..BlockNumber::new_or_panic(148428),
),
fallback_sequencer_address: Some(sequencer_address!(
"046a89ae102987331d369645031b49c27738ed096f2789c24449966da4c6de6b"
)),
};
const TESTNET2_METAINFO: BlockHashMetaInfo = BlockHashMetaInfo {
first_0_7_block: BlockNumber::new_or_panic(0),
not_verifiable_range: None,
fallback_sequencer_address: Some(sequencer_address!(
"046a89ae102987331d369645031b49c27738ed096f2789c24449966da4c6de6b"
)),
};
const MAINNET_METAINFO: BlockHashMetaInfo = BlockHashMetaInfo {
first_0_7_block: BlockNumber::new_or_panic(833),
not_verifiable_range: None,
fallback_sequencer_address: Some(sequencer_address!(
"021f4b90b0377c82bf330b7b5295820769e72d79d8acd0effa0ebde6e9988bc5"
)),
};
const INTEGRATION_METAINFO: BlockHashMetaInfo = BlockHashMetaInfo {
first_0_7_block: BlockNumber::new_or_panic(110511),
not_verifiable_range: Some(BlockNumber::new_or_panic(0)..BlockNumber::new_or_panic(110511)),
fallback_sequencer_address: Some(sequencer_address!(
"046a89ae102987331d369645031b49c27738ed096f2789c24449966da4c6de6b"
)),
};
const CUSTOM_METAINFO: BlockHashMetaInfo = BlockHashMetaInfo {
first_0_7_block: BlockNumber::new_or_panic(0),
not_verifiable_range: None,
fallback_sequencer_address: None,
};
pub fn for_chain(chain: Chain) -> &'static BlockHashMetaInfo {
match chain {
Chain::Mainnet => &MAINNET_METAINFO,
Chain::Testnet => &TESTNET_METAINFO,
Chain::Testnet2 => &TESTNET2_METAINFO,
Chain::Integration => &INTEGRATION_METAINFO,
Chain::Custom => &CUSTOM_METAINFO,
}
}
}
/// Computes the final block hash for pre-0.7 blocks.
///
/// This deviates from later algorithms by hashing a chain-specific
/// ID into the final hash.
///
/// Note that for these blocks we're using zero for:
/// * timestamps
/// * sequencer addresses
/// * event number and event commitment
fn compute_final_hash_pre_0_7(
block_number: BlockNumber,
state_root: StateCommitment,
num_transactions: u64,
transaction_commitment: Felt,
parent_block_hash: BlockHash,
chain_id: pathfinder_common::ChainId,
) -> BlockHash {
let mut chain = HashChain::default();
// block number
chain.update(Felt::from(block_number.get()));
// global state root
chain.update(state_root.0);
// sequencer address: these versions used 0 as the sequencer address
chain.update(Felt::ZERO);
// block timestamp: these versions used 0 as a timestamp for block hash computation
chain.update(Felt::ZERO);
// number of transactions
chain.update(Felt::from(num_transactions));
// transaction commitment
chain.update(transaction_commitment);
// number of events
chain.update(Felt::ZERO);
// event commitment
chain.update(Felt::ZERO);
// reserved: protocol version
chain.update(Felt::ZERO);
// reserved: extra data
chain.update(Felt::ZERO);
// EXTRA FIELD: chain id
chain.update(chain_id.0);
// parent block hash
chain.update(parent_block_hash.0);
BlockHash(chain.finalize())
}
/// This implements the final hashing step for post-0.7 blocks.
#[allow(clippy::too_many_arguments)]
fn compute_final_hash(
block_number: BlockNumber,
state_root: StateCommitment,
sequencer_address: &SequencerAddress,
timestamp: BlockTimestamp,
num_transactions: u64,
transaction_commitment: Felt,
num_events: u64,
event_commitment: Felt,
parent_block_hash: BlockHash,
) -> BlockHash {
let mut chain = HashChain::default();
// block number
chain.update(Felt::from(block_number.get()));
// global state root
chain.update(state_root.0);
// sequencer address
chain.update(sequencer_address.0);
// block timestamp
chain.update(Felt::from(timestamp.get()));
// number of transactions
chain.update(Felt::from(num_transactions));
// transaction commitment
chain.update(transaction_commitment);
// number of events
chain.update(Felt::from(num_events));
// event commitment
chain.update(event_commitment);
// reserved: protocol version
chain.update(Felt::ZERO);
// reserved: extra data
chain.update(Felt::ZERO);
// parent block hash
chain.update(parent_block_hash.0);
BlockHash(chain.finalize())
}
pub enum TransactionCommitmentFinalHashType {
SignatureIncludedForInvokeOnly,
Normal,
}
impl TransactionCommitmentFinalHashType {
pub fn for_version(version: &StarknetVersion) -> anyhow::Result<Self> {
const V_0_11_1: semver::Version = semver::Version::new(0, 11, 1);
Ok(match version.parse_as_semver()? {
None => Self::SignatureIncludedForInvokeOnly,
Some(v) if v < V_0_11_1 => Self::SignatureIncludedForInvokeOnly,
Some(_) => Self::Normal,
})
}
}
/// Calculate transaction commitment hash value.
///
/// The transaction commitment is the root of the Patricia Merkle tree with height 64
/// constructed by adding the (transaction_index, transaction_hash_with_signature)
/// key-value pairs to the tree and computing the root hash.
pub fn calculate_transaction_commitment(
transactions: &[Transaction],
final_hash_type: TransactionCommitmentFinalHashType,
) -> Result<TransactionCommitment> {
let mut tree = TransactionOrEventTree::default();
transactions
.iter()
.enumerate()
.try_for_each(|(idx, tx)| {
let idx: u64 = idx
.try_into()
.expect("too many transactions while calculating commitment");
let final_hash = match final_hash_type {
TransactionCommitmentFinalHashType::Normal => {
calculate_transaction_hash_with_signature(tx)
}
TransactionCommitmentFinalHashType::SignatureIncludedForInvokeOnly => {
calculate_transaction_hash_with_signature_pre_0_11_1(tx)
}
};
tree.set(idx, final_hash)?;
Result::<_, Error>::Ok(())
})
.context("Failed to create transaction commitment tree")?;
Ok(TransactionCommitment(tree.commit()?))
}
/// Compute the combined hash of the transaction hash and the signature.
///
/// Since the transaction hash doesn't take the signature values as its input
/// computing the transaction commitent uses a hash value that combines
/// the transaction hash with the array of signature values.
///
/// Note that for non-invoke transactions we don't actually have signatures. The
/// cairo-lang uses an empty list (whose hash is not the ZERO value!) in that
/// case.
fn calculate_transaction_hash_with_signature_pre_0_11_1(tx: &Transaction) -> Felt {
lazy_static::lazy_static!(
static ref HASH_OF_EMPTY_LIST: Felt = HashChain::default().finalize();
);
let signature_hash = match tx {
Transaction::Invoke(tx) => calculate_signature_hash(tx.signature()),
Transaction::Deploy(_)
| Transaction::DeployAccount(_)
| Transaction::Declare(_)
| Transaction::L1Handler(_) => *HASH_OF_EMPTY_LIST,
};
stark_hash(tx.hash().0, signature_hash)
}
/// Compute the combined hash of the transaction hash and the signature.
///
/// Since the transaction hash doesn't take the signature values as its input
/// computing the transaction commitent uses a hash value that combines
/// the transaction hash with the array of signature values.
///
/// Note that for non-invoke transactions we don't actually have signatures. The
/// cairo-lang uses an empty list (whose hash is not the ZERO value!) in that
/// case.
fn calculate_transaction_hash_with_signature(tx: &Transaction) -> Felt {
lazy_static::lazy_static!(
static ref HASH_OF_EMPTY_LIST: Felt = HashChain::default().finalize();
);
let signature_hash = match tx {
Transaction::Invoke(tx) => calculate_signature_hash(tx.signature()),
Transaction::Declare(tx) => calculate_signature_hash(tx.signature()),
Transaction::DeployAccount(tx) => calculate_signature_hash(&tx.signature),
Transaction::Deploy(_) | Transaction::L1Handler(_) => *HASH_OF_EMPTY_LIST,
};
stark_hash(tx.hash().0, signature_hash)
}
fn calculate_signature_hash(signature: &[TransactionSignatureElem]) -> Felt {
let mut hash = HashChain::default();
for s in signature {
hash.update(s.0);
}
hash.finalize()
}
/// Calculate event commitment hash value.
///
/// The event commitment is the root of the Patricia Merkle tree with height 64
/// constructed by adding the (event_index, event_hash) key-value pairs to the
/// tree and computing the root hash.
pub fn calculate_event_commitment(transaction_receipts: &[Receipt]) -> Result<EventCommitment> {
let mut tree = TransactionOrEventTree::default();
transaction_receipts
.iter()
.flat_map(|receipt| receipt.events.iter())
.enumerate()
.try_for_each(|(idx, e)| {
let idx: u64 = idx
.try_into()
.expect("too many events in transaction receipt");
let event_hash = calculate_event_hash(e);
tree.set(idx, event_hash)?;
Result::<_, Error>::Ok(())
})
.context("Failed to create event commitment tree")?;
Ok(EventCommitment(tree.commit()?))
}
/// Calculate the hash of an event.
///
/// See the [documentation](https://docs.starknet.io/docs/Events/starknet-events#event-hash)
/// for details.
fn calculate_event_hash(event: &Event) -> Felt {
let mut keys_hash = HashChain::default();
for key in event.keys.iter() {
keys_hash.update(key.0);
}
let keys_hash = keys_hash.finalize();
let mut data_hash = HashChain::default();
for data in event.data.iter() {
data_hash.update(data.0);
}
let data_hash = data_hash.finalize();
let mut event_hash = HashChain::default();
event_hash.update(*event.from_address.get());
event_hash.update(keys_hash);
event_hash.update(data_hash);
event_hash.finalize()
}
/// Return the number of events in the block.
fn number_of_events_in_block(block: &Block) -> usize {
block
.transaction_receipts
.iter()
.flat_map(|r| r.events.iter())
.count()
}
#[cfg(test)]
mod tests {
use super::*;
use assert_matches::assert_matches;
use pathfinder_common::macro_prelude::*;
use pathfinder_common::{felt, Fee};
use starknet_gateway_types::reply::{
transaction::{EntryPointType, InvokeTransaction, InvokeTransactionV0},
Block,
};
#[test]
fn test_event_hash() {
let event = Event {
from_address: contract_address!("0xdeadbeef"),
data: vec![
event_data!("0x5"),
event_data!("0x6"),
event_data!("0x7"),
event_data!("0x8"),
event_data!("0x9"),
],
keys: vec![
event_key!("0x1"),
event_key!("0x2"),
event_key!("0x3"),
event_key!("0x4"),
],
};
// produced by the cairo-lang Python implementation:
// `hex(calculate_event_hash(0xdeadbeef, [1, 2, 3, 4], [5, 6, 7, 8, 9]))`
let expected_event_hash =
felt!("0xdb96455b3a61f9139f7921667188d31d1e1d49fb60a1aa3dbf3756dbe3a9b4");
let calculated_event_hash = calculate_event_hash(&event);
assert_eq!(expected_event_hash, calculated_event_hash);
}
#[test]
fn test_final_transaction_hash() {
let transaction = Transaction::Invoke(InvokeTransaction::V0(InvokeTransactionV0 {
calldata: vec![],
sender_address: contract_address!("0xdeadbeef"),
entry_point_type: Some(EntryPointType::External),
entry_point_selector: entry_point!("0xe"),
max_fee: Fee::ZERO,
signature: vec![
transaction_signature_elem!("0x2"),
transaction_signature_elem!("0x3"),
],
transaction_hash: transaction_hash!("0x1"),
}));
// produced by the cairo-lang Python implementation:
// `hex(calculate_single_tx_hash_with_signature(1, [2, 3], hash_function=pedersen_hash))`
let expected_final_hash =
Felt::from_hex_str("0x259c3bd5a1951eafb2f41e0b783eab92cfe4e108b2b1f071e3736f06b909431")
.unwrap();
let calculated_final_hash = calculate_transaction_hash_with_signature(&transaction);
assert_eq!(expected_final_hash, calculated_final_hash);
}
#[test]
fn test_number_of_events_in_block() {
let json = starknet_gateway_test_fixtures::v0_9_0::block::NUMBER_156000;
let block: Block = serde_json::from_str(json).unwrap();
// this expected value comes from processing the raw JSON and counting the number of events
const EXPECTED_NUMBER_OF_EVENTS: usize = 55;
assert_eq!(number_of_events_in_block(&block), EXPECTED_NUMBER_OF_EVENTS);
}
#[test]
fn test_block_hash_without_sequencer_address() {
// This tests with a post-0.7, pre-0.8.0 block where zero is used as the sequencer address.
let json = starknet_gateway_test_fixtures::v0_9_0::block::NUMBER_90000;
let block: Block = serde_json::from_str(json).unwrap();
assert_matches!(
verify_block_hash(&block, Chain::Testnet, ChainId::TESTNET, block.block_hash).unwrap(),
VerifyResult::Match(_)
);
}
#[test]
fn test_block_hash_with_sequencer_address() {
// This tests with a post-0.8.2 block where we have correct sequencer address
// information in the block itself.
let json = starknet_gateway_test_fixtures::v0_9_0::block::NUMBER_231579;
let block: Block = serde_json::from_str(json).unwrap();
assert_matches!(
verify_block_hash(&block, Chain::Testnet, ChainId::TESTNET, block.block_hash).unwrap(),
VerifyResult::Match(_)
);
}
#[test]
fn test_block_hash_with_sequencer_address_unavailable_but_not_zero() {
// This tests with a post-0.8.0 pre-0.8.2 block where we don't have the sequencer
// address in the JSON but the block hash was calculated with the magic value below
// instead of zero.
let json = starknet_gateway_test_fixtures::v0_9_0::block::NUMBER_156000;
let block: Block = serde_json::from_str(json).unwrap();
assert_matches!(
verify_block_hash(&block, Chain::Testnet, ChainId::TESTNET, block.block_hash,).unwrap(),
VerifyResult::Match(_)
);
}
#[test]
fn test_block_hash_0_11_1() {
let json = starknet_gateway_test_fixtures::integration::block::NUMBER_285915;
let block: Block = serde_json::from_str(json).unwrap();
assert_matches!(
verify_block_hash(
&block,
Chain::Integration,
ChainId::INTEGRATION,
block.block_hash,
)
.unwrap(),
VerifyResult::Match(_)
);
}
#[test]
fn test_block_hash_0() {
// This tests with a pre-0.7 block where the chain ID was hashed into
// the block hash.
let json = starknet_gateway_test_fixtures::v0_9_0::block::GENESIS;
let block: Block = serde_json::from_str(json).unwrap();
assert_matches!(
verify_block_hash(&block, Chain::Testnet, ChainId::TESTNET, block.block_hash).unwrap(),
VerifyResult::Match(_)
);
}
}
|
fn main() {
let name = "agus";
}
|
fn main() {
proconio::input! {k:u64,n:usize,a:[u64;n]};
let mut c = a[0] + k - a[n - 1];
for i in 0..n - 1 {
c = c.max(a[i + 1] - a[i]);
}
println!("{}", k-c)
} |
use abi_stable::{
declare_root_module_statics,
external_types::{RawValueBox, RawValueRef},
library::RootModule,
nonexhaustive_enum::{DeserializeEnum, NonExhaustiveFor, SerializeEnum},
package_version_strings, rvec, sabi_trait,
sabi_types::VersionStrings,
std_types::{RBox, RBoxError, RResult, RStr, RString, RVec},
StableAbi,
};
use serde::{Deserialize, Serialize};
/// Represents United States cents.
#[repr(transparent)]
#[derive(StableAbi, Debug, Clone, Copy, PartialEq, Deserialize, Serialize)]
pub struct Cents {
pub cents: u64,
}
/// The unique identifier of an item that is/was in the catalogue,
/// which are never reused for a different item.
#[repr(transparent)]
#[derive(StableAbi, Debug, Clone, Copy, PartialEq, Deserialize, Serialize)]
pub struct ItemId {
#[doc(hidden)]
pub id: usize,
}
///////////////////////////////////////////////////////////////////////////////
/// The parameters of `Shop::run_command`.
///
/// Every variant of this enum corresponds to a variant of `ReturnVal`.
#[non_exhaustive]
#[repr(u8)]
#[derive(StableAbi, Debug, Clone, PartialEq, Deserialize, Serialize)]
#[sabi(kind(WithNonExhaustive(
size = [usize;8],
traits(Send, Sync, Debug, Clone, PartialEq, Serialize, Deserialize),
assert_nonexhaustive = Command,
)))]
pub enum Command {
/// `#[sabi(with_boxed_constructor)]` tells the `StableAbi` derive macro to
/// generate the `fn CreateItem_NE(ParamCreateItem)->ReturnVal_NE` associated function.
#[sabi(with_boxed_constructor)]
CreateItem(RBox<ParamCreateItem>),
DeleteItem {
id: ItemId,
},
AddItem {
id: ItemId,
count: u32,
},
RemoveItem {
id: ItemId,
count: u32,
},
/// This variant was added in the 1.1 version of the library.
#[cfg(feature = "v1_1")]
RenameItem {
id: ItemId,
new_name: RString,
},
/// This variant was added in the 1.1 version of the library.
///
/// `#[sabi(with_constructor)]` tells the `StableAbi` derive macro to
/// generate the `fn Many_NE(RVec<Command_NE>)->Command_NE` associated function.
#[cfg(feature = "v1_1")]
#[sabi(with_constructor)]
Many {
list: RVec<Command_NE>,
},
}
/*
//This was generated by the StableAbi derive macro on Command.
pub type Command_NE=
NonExhaustive<
Command,
Command_Storage,
Command_Interface,
>;
*/
#[repr(C)]
#[derive(StableAbi, Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct ParamCreateItem {
pub name: RString,
pub initial_count: u32,
pub price: Cents,
}
/// This specifies how `Command_NE` is serialized.
///
/// `Command_Interface` was generated by `#[derive(StableAbi)]`,
/// because `trait()` was passed as a parameter to
/// `#[sabi(kind(WithNonExhaustive( ... )))]`.
impl SerializeEnum<Command> for Command_Interface {
/// The intermediate type the enum is converted into with `SerializeEnum::serialize_enum`,
/// and then serialized.
type Proxy = RawValueBox;
fn serialize_enum(this: &Command) -> Result<RawValueBox, RBoxError> {
serialize_json(this)
}
}
/// This specifies how `Command_NE` is deserialized.
impl<'a> DeserializeEnum<'a, Command_NE> for Command_Interface {
/// The intermediate type that is deserialized,
/// and then converted to the enum with `DeserializeEnum::deserialize_enum`.
type Proxy = RawValueRef<'a>;
fn deserialize_enum(s: RawValueRef<'a>) -> Result<Command_NE, RBoxError> {
ShopMod_Ref::get_module().unwrap().deserialize_command()(s.get_rstr()).into_result()
}
}
#[test]
#[cfg(feature = "v1_1")]
fn examples_of_constructing_a_command() {
use abi_stable::nonexhaustive_enum::NonExhaustive;
let id = ItemId { id: 0 };
// Constructing a Command::CreateItem wrapped in NonExhaustive
// using the constructor generated by using #[sabi(with_boxed_constructor)] on the variant.
assert_eq!(
Command::CreateItem_NE(ParamCreateItem {
name: "foo".into(),
initial_count: 1,
price: Cents { cents: 1 },
}),
{
let x = ParamCreateItem {
name: "foo".into(),
initial_count: 1,
price: Cents { cents: 1 },
};
let x = RBox::new(x);
let x = Command::CreateItem(x);
NonExhaustive::new(x)
}
);
// Constructing a Command::RemoveItem wrapped in NonExhaustive
// without using the constructors generated using
// either #[sabi(with_constructor)] or #[sabi(with_boxed_constructor)],
// since neither attribute was applied to the enum or the variant.
{
let x = Command::RemoveItem { id, count: 1 };
let _ = NonExhaustive::new(x);
}
// Constructing a Command::Many wrapped in NonExhaustive
// using the constructor genereated by using #[sabi(with_constructor)] on the variant
assert_eq!(Command::Many_NE(RVec::new()), {
let x = Command::Many { list: RVec::new() };
NonExhaustive::new(x)
});
}
///////////////////////////////////////////////////////////////////////////////
/// The return value of `Shop::run_command`.
///
/// Every variant of this enum corresponds to a variant of `Command`.
#[non_exhaustive]
#[repr(u8)]
#[derive(StableAbi, Debug, Clone, PartialEq, Deserialize, Serialize)]
#[sabi(kind(WithNonExhaustive(
size = [usize;6],
interface = Command_Interface,
assert_nonexhaustive = ReturnVal,
)))]
pub enum ReturnVal {
CreateItem {
count: u32,
id: ItemId,
},
DeleteItem {
id: ItemId,
},
AddItem {
remaining: u32,
id: ItemId,
},
RemoveItem {
removed: u32,
remaining: u32,
id: ItemId,
},
/// This variant was added in the 1.1 version of the library.
///
/// `#[sabi(with_boxed_constructor)]` tells the `StableAbi` derive macro to
/// generate the `fn RenameItem_NE(RetRenameItem)->ReturnVal_NE` associated function.
#[cfg(feature = "v1_1")]
#[sabi(with_boxed_constructor)]
RenameItem(RBox<RetRenameItem>),
/// This variant was added in the 1.1 version of the library.
///
/// `#[sabi(with_constructor)]` tells the `StableAbi` derive macro to
/// generate the `fn Many_NE(RVec<ReturnVal_NE>)->ReturnVal_NE` associated function.
#[cfg(feature = "v1_1")]
#[sabi(with_constructor)]
Many {
list: RVec<ReturnVal_NE>,
},
}
/*
//This was generated by the StableAbi derive macro on ReturnVal.
pub type ReturnVal_NE=
NonExhaustive<
ReturnVal,
ReturnVal_Storage,
Command_Interface,
>;
*/
/// A command to rename an item in the shop,
/// which must be wrapped in `ReturnVal::RenameItem_NE` to pass to `Shop::run_command`.
#[cfg(feature = "v1_1")]
#[repr(C)]
#[derive(StableAbi, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RetRenameItem {
pub id: ItemId,
pub new_name: RString,
pub old_name: RString,
}
/// This specifies how `ReturnVal_NE` is serialized.
///
/// This is implemented on Command_Interface,
/// because `interface = Command_Interface` was passed as a parameter to
/// `#[sabi(kind(WithNonExhaustive( ... )))]`.
impl SerializeEnum<ReturnVal> for Command_Interface {
/// The intermediate type the enum is converted into with `SerializeEnum::serialize_enum`,
/// and then serialized.
type Proxy = RawValueBox;
fn serialize_enum(this: &ReturnVal) -> Result<RawValueBox, RBoxError> {
serialize_json(this)
}
}
/// This specifies how `ReturnVal_NE` is deserialized.
impl<'a> DeserializeEnum<'a, ReturnVal_NE> for Command_Interface {
/// The intermediate type that is deserialized,
/// and then converted to the enum with `DeserializeEnum::deserialize_enum`.
type Proxy = RawValueRef<'a>;
fn deserialize_enum(s: RawValueRef<'a>) -> Result<ReturnVal_NE, RBoxError> {
ShopMod_Ref::get_module().unwrap().deserialize_ret_val()(s.get_rstr()).into_result()
}
}
#[test]
#[cfg(feature = "v1_1")]
fn examples_of_constructing_a_returnval() {
use abi_stable::nonexhaustive_enum::NonExhaustive;
let id = ItemId { id: 0 };
// Constructing a ReturnVal::RemoveItem wrapped in NonExhaustive
// without using the constructors generated using
// either #[sabi(with_constructor)] or #[sabi(with_boxed_constructor)],
// since neither attribute was applied to the enum or the variant.
{
let x = ReturnVal::RemoveItem {
removed: 0,
remaining: 0,
id,
};
let _ = NonExhaustive::new(x);
}
// Constructing a ReturnVal::RenameItem wrapped in NonExhaustive
// using the constructor generated by using #[sabi(with_boxed_constructor)] on the variant
assert_eq!(
ReturnVal::RenameItem_NE(RetRenameItem {
id,
new_name: "foo".into(),
old_name: "bar".into(),
}),
{
let x = RetRenameItem {
id,
new_name: "foo".into(),
old_name: "bar".into(),
};
let x = RBox::new(x);
let x = ReturnVal::RenameItem(x);
NonExhaustive::new(x)
}
);
// Constructing a ReturnVal::Many wrapped in NonExhaustive
// using the constructor genereated by using #[sabi(with_constructor)] on the variant
assert_eq!(ReturnVal::Many_NE(RVec::new()), {
let x = ReturnVal::Many { list: RVec::new() };
NonExhaustive::new(x)
});
}
///////////////////////////////////////////////////////////////////////////////
#[non_exhaustive]
#[repr(u8)]
#[derive(StableAbi, Debug, Clone, PartialEq)]
#[sabi(kind(WithNonExhaustive(size = [usize;6], traits(Send, Sync, Debug, Clone, PartialEq),)))]
#[sabi(with_constructor)]
pub enum Error {
ItemAlreadyExists {
id: ItemId,
name: RString,
},
ItemIdNotFound {
id: ItemId,
},
#[sabi(with_boxed_constructor)]
InvalidCommand {
cmd: RBox<Command_NE>,
},
}
// Because Error has the `#[sabi(with_constructor)]` attribute applied to it,
// StableAbi generates constructor functions for each variant.
// InvalidCommand overrides it with `#[sabi(with_boxed_constructor)]`,
// which generates constructor functions for variants which wrap a pointer.
#[test]
#[cfg(feature = "v1_1")]
fn examples_of_constructing_an_error() {
use abi_stable::nonexhaustive_enum::NonExhaustive;
let id = ItemId { id: 0 };
assert_eq!(Error::ItemAlreadyExists_NE(id, "hello".into()), {
let x = Error::ItemAlreadyExists {
id,
name: "hello".into(),
};
NonExhaustive::new(x)
});
assert_eq!(Error::ItemIdNotFound_NE(id), {
let x = Error::ItemIdNotFound { id };
NonExhaustive::new(x)
});
assert_eq!(Error::InvalidCommand_NE(Command::Many_NE(rvec![])), {
let x = Command::Many { list: rvec![] };
let x = NonExhaustive::new(x);
let x = RBox::new(x);
let x = Error::InvalidCommand { cmd: x };
NonExhaustive::new(x)
});
}
/// The root module of the `shop` dynamic library.
///
/// To load this module,
/// call <ShopMod_Ref as RootModule>::load_from_directory(some_directory_path)
#[repr(C)]
#[derive(StableAbi)]
#[sabi(kind(Prefix(prefix_ref = ShopMod_Ref)))]
#[sabi(missing_field(panic))]
pub struct ShopMod {
/// Constructs the `Shop_TO` trait object.
pub new: extern "C" fn() -> Shop_TO<'static, RBox<()>>,
/// Deserializes a `Command_NE`.
pub deserialize_command: extern "C" fn(s: RStr<'_>) -> RResult<Command_NE, RBoxError>,
/// Deserializes a `ReturnVal_NE`.
///
/// The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct
/// that was defined in the first compatible version of the library
/// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc),
/// requiring new fields to always be added below preexisting ones.
///
/// The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library
/// bumps its "major" version,
/// at which point it would be moved to the last field at the time.
///
#[sabi(last_prefix_field)]
pub deserialize_ret_val: extern "C" fn(s: RStr<'_>) -> RResult<ReturnVal_NE, RBoxError>,
}
impl RootModule for ShopMod_Ref {
declare_root_module_statics! {ShopMod_Ref}
const BASE_NAME: &'static str = "shop";
const NAME: &'static str = "shop";
const VERSION_STRINGS: VersionStrings = package_version_strings!();
}
#[sabi_trait]
/// This represents a shop manager,
/// which can be sent a growing list of commands with each version.
pub trait Shop {
/// Runs the `cmd` command.
///
///
/// The `#[sabi(last_prefix_field)]` attribute here means that this is the last method
/// that was defined in the first compatible version of the library
/// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc),
/// requiring new methods to always be added below preexisting ones.
///
/// The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library
/// bumps its "major" version,
/// at which point it would be moved to the last method at the time.
///
#[sabi(last_prefix_field)]
fn run_command(&mut self, cmd: Command_NE) -> RResult<ReturnVal_NE, NonExhaustiveFor<Error>>;
}
fn serialize_json<T>(value: &T) -> Result<RawValueBox, RBoxError>
where
T: serde::Serialize,
{
match serde_json::to_string::<T>(&value) {
Ok(v) => unsafe { Ok(RawValueBox::from_string_unchecked(v)) },
Err(e) => Err(RBoxError::new(e)),
}
}
|
use common::aoc::{load_input, run_many, print_result, print_time};
fn main() {
let input = load_input("day02");
let (program, dur_parse) = run_many(10000, || parse_input(&input));
let (res_part1, dur_part1) = run_many(10000, || part1(&program));
let (res_part2, dur_part2) = run_many(10000, || part2(&program));
let (res_part2_bs, dur_part2_bs) = run_many(10000, || part2_bs(&program));
let (res_part2_reduce, dur_part2_reduce) = run_many(10000, || part2_reduce(&program));
print_result("P1", res_part1);
print_result("P2: Pattern Exploit", res_part2);
print_result("P2: Binary Search", res_part2_bs);
print_result("P2: Reduce [not my idea]", res_part2_reduce);
print_time("Parse", dur_parse);
print_time("P1", dur_part1);
print_time("P2: Pattern Exploit", dur_part2);
print_time("P2: Binary Search", dur_part2_bs);
print_time("P2: Reduce [not my idea]", dur_part2_reduce);
}
fn parse_input(input: &str) -> Vec<u32> {
let mut result: Vec<u32> = Vec::with_capacity(input.len() / 2);
let mut next: u32 = 0;
let zero_char = '0' as u32;
for ch in input.chars() {
if ch == '\r' || ch == '\n' {
continue;
} else if ch == ',' {
result.push(next);
next = 0;
continue;
}
next *= 10;
next += (ch as u32) - zero_char;
}
result.push(next);
result
}
fn part1(initial_program: &[u32]) -> u32 {
let mut program = initial_program.to_vec();
program[1] = 12;
program[2] = 2;
run_intcode(&mut program);
program[0]
}
const PART2_TARGET: u32 = 19690720;
const PART2_TARGET_DIV100: u32 = 196907;
fn part2(initial_program: &[u32]) -> u32 {
let mut program = initial_program.to_vec();
for noun in 0..100 {
program[1] = noun;
program[2] = 0;
run_intcode(&mut program);
let hundred = program[0] / 100;
if hundred == PART2_TARGET_DIV100 || hundred == PART2_TARGET_DIV100 - 1 {
let verb = PART2_TARGET - program[0];
return (noun * 100) + verb;
}
program.copy_from_slice(initial_program);
}
panic!("Answer not found for noun-verb pairs in range 0..100")
}
fn part2_bs(initial_program: &[u32]) -> u32 {
let mut program = initial_program.to_vec();
let mut current = 5000;
let mut next_jump_weight = 2500;
loop {
program[1] = current / 100;
program[2] = current % 100;
run_intcode(&mut program);
let result = program[0];
if result == PART2_TARGET {
return current;
} else if result < PART2_TARGET {
current += next_jump_weight;
} else {
current -= next_jump_weight;
}
if next_jump_weight > 1 {
next_jump_weight /= 2;
}
program.copy_from_slice(initial_program);
}
}
fn part2_reduce(initial_program: &[u32]) -> u32 {
let mut program1 = initial_program.to_vec();
let mut program2 = initial_program.to_vec();
let mut program3 = initial_program.to_vec();
program1[1] = 25;
program1[2] = 11;
program2[1] = 26;
program2[2] = 11;
program3[1] = 25;
program3[2] = 12;
run_intcode(&mut program1);
run_intcode(&mut program2);
run_intcode(&mut program3);
let res1 = program1[0];
let res2 = program2[0];
let res3 = program3[0];
let x = res2 - res1;
let y = res3 - res1;
let n = res1 - ((25 * x) + (11 * y));
let nx = (PART2_TARGET - n) / x;
let ny = (PART2_TARGET - n - (nx * x)) / y;
(nx * 100) + ny
}
fn run_intcode(program: &mut Vec<u32>) {
let mut position: usize = 0;
loop {
let opcode = program[position];
match opcode {
1 => {
let target = program[position + 3] as usize;
let left = program[position + 1] as usize;
let right = program[position + 2] as usize;
program[target] = program[left] + program[right];
}
2 => {
let target = program[position + 3] as usize;
let left = program[position + 1] as usize;
let right = program[position + 2] as usize;
program[target] = program[left] * program[right];
}
99 => {
break
}
_ => {
panic!("Unknown opcode: {}", opcode)
}
}
position += 4;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_run_intcode() {
let mut program = vec![1,0,0,0,99];
let expected = vec![2,0,0,0,99];
run_intcode(&mut program);
assert_eq!(program, expected);
let mut program = vec![2,3,0,3,99];
let expected = vec![2,3,0,6,99];
run_intcode(&mut program);
assert_eq!(program, expected);
let mut program = vec![2,4,4,5,99,0];
let expected = vec![2,4,4,5,99,9801];
run_intcode(&mut program);
assert_eq!(program, expected);
let mut program = vec![1,1,1,4,99,5,6,0,99];
let expected = vec![30,1,1,4,2,5,6,0,99];
run_intcode(&mut program);
assert_eq!(program, expected);
}
} |
/*
* Firecracker API
*
* RESTful public-facing API. The API is accessible through HTTP calls on specific URLs carrying JSON modeled data. The transport medium is a Unix Domain Socket.
*
* The version of the OpenAPI document: 0.25.0
* Contact: compute-capsule@amazon.com
* Generated by: https://openapi-generator.tech
*/
/// Logger : Describes the configuration option for the logging capability.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Logger {
/// Set the level. The possible values are case-insensitive.
#[serde(rename = "level", skip_serializing_if = "Option::is_none")]
pub level: Option<Level>,
/// Path to the named pipe or file for the human readable log output.
#[serde(rename = "log_path")]
pub log_path: String,
/// Whether or not to output the level in the logs.
#[serde(rename = "show_level", skip_serializing_if = "Option::is_none")]
pub show_level: Option<bool>,
/// Whether or not to include the file path and line number of the log's origin.
#[serde(rename = "show_log_origin", skip_serializing_if = "Option::is_none")]
pub show_log_origin: Option<bool>,
}
impl Logger {
/// Describes the configuration option for the logging capability.
pub fn new(log_path: String) -> Logger {
Logger {
level: None,
log_path,
show_level: None,
show_log_origin: None,
}
}
}
/// Set the level. The possible values are case-insensitive.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub enum Level {
#[serde(rename = "Error")]
Error,
#[serde(rename = "Warning")]
Warning,
#[serde(rename = "Info")]
Info,
#[serde(rename = "Debug")]
Debug,
}
|
/*
struct PortBBits
{
_BIT_ flippers_motor_backward:1;
_BIT_ spin_motor_forward:1;
_BIT_ spin_motor_backward:1;
_BIT_ mouth_open_switch:1;
_BIT_ mouth_closed_switch:1;
_BIT_ head_push_switch:1;
_BIT_ charger_inhibit_signal:1;
_BIT_ external_io:1;
}
union
{
Byte: u8;
_PORTB_BITS_ bits;
} _PORTB_BYTE_;
struct PortCBits
{
_BIT_ photo_transistor_pull_up:1;
_BIT_ flippers_position_switch:1;
_BIT_ right_blue_led:1;
_BIT_ left_blue_led:1;
_BIT_ i2c_sda_line:1;
_BIT_ i2c_scl_line:1;
_BIT_ reset:1;
_BIT_ ndef:1;
} _PORTC_BITS_;
union
{
Byte: u8;
_PORTC_BITS_ bits;
} _PORTC_BYTE_;
struct PortDBits
{
_BIT_ head_motor_for_mouth:1;
_BIT_ head_motor_for_eyes:1;
_BIT_ ir_receiver_signal:1;
_BIT_ spin_position_switch:1;
_BIT_ flippers_motor_forward:1;
_BIT_ ir_led:1;
_BIT_ eyes_open_switch:1;
_BIT_ eyes_closed_switch:1;
} _PORTD_BITS_;
union
{
Byte: u8;
_PORTD_BITS_ bits;
} _PORTD_BYTE_;
struct SensorStates
{
_BIT_ left_wing_push_button:1;
_BIT_ right_wing_push_button:1;
_BIT_ power_plug_insertion_switch:1;
_BIT_ head_push_button:1;
_BIT_ charger_led_status:1;
_BIT_ rf_connection_status:1;
_BIT_ internal_power_switch:1;
_BIT_ mute_status:1;
} _SENSORS_BITS_;
union
{
Byte: u8;
_SENSORS_BITS_ bits;
} _SENSORS_BYTE_;
struct InfraredState
{
_BIT_ command:6;
_BIT_ toggle:1;
_BIT_ received_flag:1;
} _RC5_BITS_;
union
{
Byte: u8;
_RC5_BITS_ bits;
} _RC5_BYTE_;
struct Version
{
_BIT_ cpu_number:3;
_BIT_ major:5;
} _VERSION_FIRST_BITS_;
union
{
Byte: u8;
_VERSION_FIRST_BITS_ bits;
} _VERSION_FIRST_BYTE_;
struct
{
_BIT_ local_modification:1;
_BIT_ mixed_update:1;
_BIT_ original_release:1;
_BIT_ ndef:5;
} _REVISION_THIRD_BITS_;
union
{
Byte: u8;
_REVISION_THIRD_BITS_ bits;
} _REVISION_THIRD_BYTE_;
struct AudioState
{
_BIT_ no_programming:1;
_BIT_ flash_erased:1;
_BIT_ toc:1;
_BIT_ sounds_track:5;
} _AUDIO_BITS_;
union
{
Byte: u8;
_AUDIO_BITS_ bits;
} _AUDIO_BYTE_;
struct LedEffectState
{
_BIT_ left_led_fading:1;
_BIT_ left_led_pulsing:1;
_BIT_ right_led_fading:1;
_BIT_ right_led_pulsing:1;
_BIT_ led_mask:1;
_BIT_ ndef:3;
} _LED_EFFECT_STATUS_BITS_;
union
{
Byte: u8;
_LED_EFFECT_STATUS_BITS_ bits;
} _LED_EFFECT_STATUS_BYTE_;
struct MotorsState
{
_BIT_ spin_right_on:1;
_BIT_ spin_left_on:1;
_BIT_ eyes_on:1;
_BIT_ mouth_on:1;
_BIT_ flippers_on:1;
_BIT_ ndef:3;
};
*/
/*
union
{
Byte: u8;
_MOTORS_STATUS_BITS_ bits;
} _MOTORS_STATUS_BYTE_;
struct FrameBodyPorts
{
_PORTB_BYTE_ portb;
_PORTC_BYTE_ portc;
_PORTD_BYTE_ portd;
};
struct FrameBodySensors1
{
sensors: SensorStates;
play_internal_sound: u8;
play_general_sound: u8;
};
*/
struct FrameBodyLight
{
high_level: u8;
low_level: u8;
mode: u8;
};
struct FrameBodyPosition1
{
eyes_remaining_mvm: u8;
mouth_remaining_mvm: u8;
flippers_remaining_mvm: u8;
};
struct FrameBodyPosition2
{
spin_remaining_mvm: u8;
flippers_down: u8;
motors: MotorsState;
};
struct FrameBodyIR
{
_RC5_BYTE_ rc5_code;
/*unsigned char ??; NDEF */
/*unsigned char ??; NDEF */
};
struct FrameBodyId
{
msb_number: u8;
lsb_number: u8;
/*unsigned char ??; NDEF */
};
struct FrameBodyBattery
{
high_level: u8;
low_level: u8;
motors_state: u8;
};
struct FrameBodyVersion
{
_VERSION_FIRST_BYTE_ cm;
minor: u8;
update: u8;
};
struct FrameBodyRevision
{
lsb_number: u8;
msb_number: u8;
_REVISION_THIRD_BYTE_ release_type;
};
struct FrameBodyAuthor
{
lsb_id: u8;
msb_id: u8;
variation_number: u8;
};
struct FrameBodyAudio
{
sound_track_played: u8;
_AUDIO_BYTE_ programming_steps;
programmed_sound_track: u8;
};
struct FrameBodySoundVar
{
number_of_sounds: u8;
flash_usage: u8;
/*unsigned char ??; NDEF */
};
struct FrameBodyFlashProg
{
current_state: u8;
last_sound_size: u8;
/*unsigned char ??; NDEF */
};
struct FrameBodyLed
{
left_led_intensity: u8;
right_led_intensity: u8;
_LED_EFFECT_STATUS_BYTE_ effect_status;
};
struct FrameBodyPong
{
pongs_pending_number: u8;
pongs_lost_by_i2c_number: u8;
pongs_lost_by_rf_number: u8;
};
struct HardwareState
{
ports: FrameBodyPorts;
sensors1: FrameBodySensors1;
light: FrameBodyLight;
position1: FrameBodyPosition1;
position2: FrameBodyPosition2;
ir: frame_body_ir_t;
id: frame_body_id_t;
battery: frame_body_battery_t;
version: frame_body_version_t;
revision: frame_body_revision_t;
author: frame_body_author_t;
audio: frame_body_audio_t;
sound_var: frame_body_sound_var_t;
flash_prog: frame_body_flash_prog_t;
led: frame_body_led_t;
pong: frame_body_pong_t;
};
|
mod js_object_utils;
mod options;
mod resources;
mod settings;
use crate::{
js_object_utils::is_null_or_undefined, options::js_options_object_to_rust_options_struct,
resources::ResourceReader, settings::js_settings_object_to_rust_settings_struct,
};
use eyeliner::{inline, servo_config::opts, servo_embedder_traits};
use neon::{
context::FunctionContext,
prelude::*,
register_module,
types::{JsBoolean, JsObject, JsString},
};
use std::path::PathBuf;
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
fn default(mut cx: FunctionContext) -> JsResult<JsString> {
let config = cx
.argument::<JsObject>(0)?
.downcast_or_throw::<JsObject, FunctionContext>(&mut cx)?;
let html = config
.get(&mut cx, "html")?
.downcast_or_throw::<JsString, FunctionContext>(&mut cx)?
.value();
let css = {
let css_property = config.get(&mut cx, "css")?;
if is_null_or_undefined(css_property) {
None
} else {
Some(
css_property
.downcast_or_throw::<JsString, FunctionContext>(&mut cx)?
.value(),
)
}
};
let options = {
let options_property = config.get(&mut cx, "options")?;
if is_null_or_undefined(options_property) {
None
} else {
let js_object =
options_property.downcast_or_throw::<JsObject, FunctionContext>(&mut cx)?;
Some(js_options_object_to_rust_options_struct(
&mut cx, js_object,
)?)
}
};
let settings = {
let settings_property = config.get(&mut cx, "settings")?;
if is_null_or_undefined(settings_property) {
None
} else {
let js_object =
settings_property.downcast_or_throw::<JsObject, FunctionContext>(&mut cx)?;
Some(js_settings_object_to_rust_settings_struct(
&mut cx, js_object,
)?)
}
};
let result = inline(&html, css, options, settings);
Ok(cx.string(&result))
}
fn set_prefs(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let path = cx
.argument::<JsString>(0)?
.downcast_or_throw::<JsString, FunctionContext>(&mut cx)?;
let prefs = PathBuf::from(path.value());
let resource_reader = ResourceReader { prefs };
servo_embedder_traits::resources::set(Box::new(resource_reader));
opts::set_options(opts::default_opts());
Ok(cx.undefined())
}
register_module!(mut module, {
// Register as an ES Module
let es_module = JsObject::new(&mut module);
let js_boolean = JsBoolean::new(&mut module, true);
es_module
.set(&mut module, "value", js_boolean)
.expect("Can't create `__esModule` object.");
module
.exports_object()
.expect("Can't get exports object.")
.set(&mut module, "__esModule", es_module)
.expect("Can't add `__esModule` object to exports.");
// Export default function
module
.export_function("default", default)
.expect("Can't export `default` function.");
module
.export_function("setPrefs", set_prefs)
.expect("Can't export `setPrefs` function.");
Ok(())
});
|
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use anyhow::*;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
#[native_implemented::function(erlang:list_to_tuple/1)]
pub fn result(process: &Process, list: Term) -> exception::Result<Term> {
match list.decode().unwrap() {
TypedTerm::Nil => Ok(process.tuple_from_slice(&[])),
TypedTerm::List(cons) => {
let vec: Vec<Term> = cons
.into_iter()
.collect::<std::result::Result<_, _>>()
.map_err(|_| ImproperListError)
.with_context(|| format!("list ({}) is improper", list))?;
Ok(process.tuple_from_slice(&vec))
}
_ => Err(TypeError)
.context(format!("list ({}) is not a list", list))
.map_err(From::from),
}
}
|
use klt;
use std::{ptr, slice};
use std::os::raw;
pub unsafe fn unsafe_main() {
let ft = klt::KLTReadFeatureTable(ptr::null_mut(), s!("features.txt"));
let ftr = &mut *ft;
let fl = klt::KLTCreateFeatureList(ftr.n_features);
klt::KLTExtractFeatureList(fl, ft, 1);
klt::KLTWriteFeatureList(fl, s!("feat1.txt"), s!("%3d"));
klt::KLTReadFeatureList(fl, s!("feat1.txt"));
klt::KLTStoreFeatureList(fl, ft, 2);
klt::KLTWriteFeatureTable(ft, s!("ft2.txt"), s!("%3d"));
let fh = klt::KLTCreateFeatureHistory(ftr.n_frames);
let fhr = &mut *fh;
klt::KLTExtractFeatureHistory(fh, ft, 5);
println!("The feature history of feature number 5:\n");
for i in 0..fhr.n_frames {
println!("{}: ({:#5.1},{:#5.1}) = {}",
i, idx!(fhr.feature[i, n_frames].x), idx!(fhr.feature[i, n_frames].y),
idx!(fhr.feature[i, n_frames].val));
}
klt::KLTStoreFeatureHistory(fh, ft, 8);
klt::KLTWriteFeatureTable(ft, s!("ft3.txt"), s!("%6.1f"));
}
|
use super::*;
use crate::fn_pointer_extractor::FnParamRet;
abi_stable_shared::declare_type_layout_index! {
attrs=[]
}
impl TypeLayoutIndex {
/// Used to recover from syn errors,
/// this value shouldn't be used in the layout constant since it's reserved
/// for errors.
pub const DUMMY: Self = Self::from_u10(!0);
}
abi_stable_shared::declare_multi_tl_types! {
attrs=[]
}
impl TypeLayoutRange {
pub(crate) fn compress_params<'a>(
params: &[FnParamRet<'a>],
shared_vars: &mut SharedVars<'a>,
) -> Self {
let param_len = params.len();
if param_len <= TypeLayoutRange::STORED_INLINE {
let mut arr = [0u16; TypeLayoutRange::STORED_INLINE];
for (p_i, param) in params.iter().enumerate() {
let ty: &'a syn::Type = param.ty;
arr[p_i] = shared_vars
.push_type(LayoutConstructor::Regular, ty)
.to_u10();
}
Self::with_up_to_5(param_len, arr)
} else {
const I_BEFORE: usize = TypeLayoutRange::STORED_INLINE - 1;
let mut arr = [0u16; TypeLayoutRange::STORED_INLINE];
let mut iter = params.iter().map(|p| -> &'a syn::Type { p.ty });
for (p_i, ty) in iter.by_ref().take(I_BEFORE).enumerate() {
arr[p_i] = shared_vars
.push_type(LayoutConstructor::Regular, ty)
.to_u10();
}
arr[I_BEFORE] = shared_vars
.extend_type(LayoutConstructor::Regular, iter)
.start;
Self::with_more_than_5(param_len, arr)
}
}
}
|
// 1. CLI
// 2. File associations
// 3. Context menu option
mod sys;
pub(super) fn stdin() -> bool {
use tauri::api::clap::{App, Arg};
let app = App::new("gmpublisher");
let matches = app
.version(env!("CARGO_PKG_VERSION"))
.author("William Venner <william@venner.io>")
.about("Publish, extract and work with GMA files")
.args(&[
Arg::new("extract")
.short('e')
.long("extract")
.value_name("FILE")
.takes_value(true)
.about("Extracts a .GMA file")
.conflicts_with_all(&["update", "in", "changes", "icon"]),
Arg::new("out")
.short('o')
.long("out")
.value_name("PATH")
.takes_value(true)
.about("Sets the output path for extracting GMAs. Defaults to the temp directory.")
.requires("extract")
.default_missing_value_os(std::env::temp_dir().join("gmpublisher").as_os_str())
.conflicts_with_all(&["update", "in", "changes", "icon"])
])
.args(&[
Arg::new("update")
.short('u')
.long("update")
.value_name("PublishedFileId")
.takes_value(true)
.about("Publishes an update.")
.requires("in")
.conflicts_with_all(&["out", "extract"]),
Arg::new("in")
.long("in")
.value_name("PATH")
.takes_value(true)
.about("Sets the directory the GMA for updating will be built from.")
.requires("update")
.conflicts_with_all(&["out", "extract"]),
Arg::new("changes")
.long("changes")
.value_name("CHANGES")
.takes_value(true)
.about("Sets the changelog for an update.")
.requires("update")
.conflicts_with_all(&["out", "extract"]),
Arg::new("icon")
.long("icon")
.value_name("PATH")
.takes_value(true)
.about("Path to a (max 1 MB) JPG/PNG/GIF file for Workshop preview image updating.")
.requires("update")
.conflicts_with_all(&["out", "extract"])
])
.get_matches();
println!("{:#?}", matches);
false
}
|
use fall_tree::{AstNode, File};
mod syntax;
mod ast_ext;
pub use self::syntax::*;
pub use self::ast_ext::{SelectorKind, RefKind};
pub fn parse(text: String) -> File {
LANG.parse(text)
}
pub fn ast(file: &File) -> FallFile {
FallFile::new(file.root())
}
|
//!
//! The Tileset struct contains all of the information necessary for tile
//! definitions.
//!
//! Tilesets contain references to the image, have all of the
//! relevant information to turn these images into graphical tiles, and include
//! animation and collision data on a tile-by-tile basis (if any was defined in the
//! editor, that is).
//!
//! The most useful methods of the tileset are the following:
//!
//! pub fn coord_by_gid(&self, gid: u32) -> (u16, u16);
//! pub fn anim_by_gid(&self, gid: u32, milliseconds: u32) -> (u16, u16);
//! pub fn collision_by_gid(&self, gid: u32) -> Option<&Layer>;
//! pub fn tile_by_gid(&self, gid: u32) -> Option<&Tile>;
//! pub fn type_by_gid(&self, gid: u32) -> Option<&String>;
//! pub fn properties_by_gid(&self, gid: u32) -> Option<&Vec<Property>>;
//!
//! This struct implements the trait HasProperty, which enables easy access of
//! Tiled properties for Tilesets. The relevant functions are:
//!
//! tiled_json::Tileset::get_property(&self, name: &str) -> Option<&tiled_json::Property>;
//! tiled_json::Tileset::get_property_vector(&self) -> &Vec<tiled_json::Property>;
//! tiled_json::Tileset::get_property_value(&self, name: &str) -> Option<&tiled_json::PropertyValue>;
//! // See the tiled_json::Property struct to see functionality offered.
//!
//! See Tiled JSON documentation at:
//! <https://doc.mapeditor.org/en/stable/reference/json-map-format/#tileset>
//!
use crate::color::Color;
use crate::layer::Layer;
use crate::property::HasProperty;
use crate::property::Property;
use serde::Deserialize;
const ORIENT_ORTHO: &str = "orthogonal";
const ORIENT_ISO: &str = "isometric";
#[derive(Deserialize)]
#[cfg_attr(debug_assertions, derive(Debug))]
/// The primary means of capturing image data.
pub struct Tileset {
#[serde(default)]
pub tiledversion: String,
pub image: String,
pub firstgid: u32,
pub imageheight: u16,
pub imagewidth: u16,
pub tileheight: u16,
pub tilewidth: u16,
pub tilecount: u32,
pub columns: u16,
#[serde(default)]
pub margin: u16,
#[serde(default)]
pub spacing: u16,
#[serde(default)]
pub name: String,
#[serde(default)]
pub backgroundcolor: Option<Color>,
#[serde(default)]
pub transparentcolor: Option<Color>,
#[serde(default)]
pub grid: Option<Grid>,
#[serde(default)]
pub tiles: Vec<Tile>,
#[serde(default)]
pub tileoffset: Option<TileOffset>,
#[serde(default)]
pub properties: Vec<Property>,
}
impl Tileset {
/// This will give you the coordinates in the image of the tile referenced by the gid provided.
/// You should be sure gid belongs to this tileset.
///
/// This does not take into account any possible animations that may be on the map. If you need
/// animation data, then use anim_by_gid().
pub fn coord_by_gid(&self, gid: u32) -> (u16, u16) {
let lid = self.as_local_id(gid);
let x: u16 = (self.tilewidth + self.spacing) * (lid % self.columns) + self.margin;
let y: u16 = (self.tileheight + self.spacing) * (lid / self.columns) + self.margin;
(x, y)
}
/// This will give you the coordinates of the tile referenced by the gid provided.
/// You should be sure gid belongs to this tileset.
///
/// You must provided the amount of milliseconds that have passed since creation in order to
/// get the correct animation frame.
pub fn anim_by_gid(&self, gid: u32, milliseconds: u32) -> (u16, u16) {
let mut lid = self.as_local_id(gid);
for tile in self.tiles.iter() {
if tile.id == lid {
let anim = tile.get_anim(milliseconds);
if anim.0 {
lid = anim.1
}
break;
}
}
let x: u16 = (self.tilewidth + self.spacing) * (lid % self.columns) + self.margin;
let y: u16 = (self.tileheight + self.spacing) * (lid / self.columns) + self.margin;
(x, y)
}
/// Tiles may have collision data. It is named objectgroup in Tiled;
/// an objectgroup layer defining a collection of objects.
pub fn collision_by_gid(&self, gid: u32) -> Option<&Layer> {
let lid = self.as_local_id(gid);
for tile in self.tiles.iter() {
if tile.id == lid {
return tile.objectgroup.as_ref();
}
}
Option::None
}
/// Tiles may have user-defined 'types' in Tiled. Retreive one if it
/// exists for this gid.
pub fn type_by_gid(&self, gid: u32) -> Option<&String> {
let lid = self.as_local_id(gid);
for tile in self.tiles.iter() {
if tile.id == lid {
return tile.ttype.as_ref();
}
}
Option::None
}
/// Get a reference to a Tile object if one exists in this tileset by
/// the gid of one specified.
pub fn tile_by_gid(&self, gid: u32) -> Option<&Tile> {
let lid = self.as_local_id(gid);
for tile in self.tiles.iter() {
if tile.id == lid {
return Option::Some(tile);
}
}
Option::None
}
/// Tiles will have their own property lists if defined so in Tiled.
/// This function will provide a reference to the property vector if it exists.
/// If it does not, you may want to refer to the properties of the entire tileset.
///
/// It may be more convenient to access the property of the tile through
/// the tile property access methods. Use them in combination with
/// ```Tileset::tile_by_gid(&self, gid: u32)```
pub fn properties_by_gid(&self, gid: u32) -> Option<&Vec<Property>> {
let lid = self.as_local_id(gid);
for tile in self.tiles.iter() {
if tile.id == lid {
return Option::Some(tile.get_property_vector());
}
}
Option::None
}
/// Get the firstgid of the tileset.
pub fn first_gid(&self) -> u32 {
self.firstgid
}
/// Get the image of the tileset as a string.
pub fn image(&self) -> &String {
&self.image
}
/// Image height of the tileset in pixels.
pub fn image_height(&self) -> u16 {
self.imageheight
}
/// Image width of the tileset is in pixels.
pub fn image_width(&self) -> u16 {
self.imagewidth
}
/// Get the height of each tile in pixels.
pub fn tile_height(&self) -> u16 {
self.tileheight
}
/// Get the width of each tile in pixels.
pub fn tile_width(&self) -> u16 {
self.tilewidth
}
/// Give you the number of tiles in this tileset.
/// This will include any blank spots in the image.
pub fn tile_count(&self) -> u32 {
self.tilecount
}
/// Columns refers to the width of the tileset in tile units.
pub fn columns(&self) -> u16 {
self.columns
}
/// Rows is the height of the tileset in tile units.
pub fn rows(&self) -> u16 {
if self.columns == 0 { return 0; }
(self.tilecount / self.columns as u32) as u16
}
/// The distance in pixels from the edge of the image to the start of the tiles.
/// This border remains constant over all 4 edges of the image.
pub fn margin(&self) -> u16 {
self.margin
}
/// The distance in pixels from one tile to the next in both axes in the tileset image.
pub fn spacing(&self) -> u16 {
self.spacing
}
/// The user-defined name of the tileset in Tiled.
pub fn name(&self) -> &String {
&self.name
}
/// The optional background color of the tileset.
pub fn bg_color(&self) -> Option<Color> {
self.backgroundcolor
}
/// The optional transparent color of the tileset.
pub fn tp_color(&self) -> Option<Color> {
self.transparentcolor
}
/// An optional grid, that I'm not quite sure what it does.
pub fn grid(&self) -> Option<Grid> {
self.grid
}
/// This is a vector of any special tiles you have defined in the map editor.
/// This will include tiles with animations, special properties, objectgroups, etc...
pub fn tiles(&self) -> &Vec<Tile> {
&self.tiles
}
/// Get the tileoffset. It is an object with an x and a y.
pub fn tile_offset(&self) -> Option<TileOffset> {
self.tileoffset
}
/// Retrieve the version of Tiled the tileset was compiled with.
pub fn tiled_version(&self) -> &String {
&self.tiledversion
}
#[inline]
fn as_local_id(&self, gid: u32) -> u16 {
(crate::gid_without_flags(gid) - self.firstgid) as u16
}
}
impl HasProperty for Tileset {
/// Get access to properties of Tileset.
fn get_property_vector(&self) -> &Vec<Property> {
&self.properties
}
}
#[derive(Deserialize)]
#[cfg_attr(debug_assertions, derive(Debug))]
/// Tile contains data relevant to overrides of the tileset.
/// This is for containing data specific to certain tiles within the tileset, such
/// animations, collisions, different images, and properties.
///
/// This struct implements the trait HasProperty, which enables easy access of
/// Tiled properties for Tiles. The relevant functions are:
///
/// tiled_json::Tile::get_property(&self, name: &str) -> Option<&tiled_json::Property>;
/// tiled_json::Tile::get_property_vector(&self) -> &Vec<tiled_json::Property>;
/// tiled_json::Tile::get_property_value(&self, name: &str) -> Option<&tiled_json::PropertyValue>;
/// // See the tiled_json::Property struct to see functionality offered.
///
pub struct Tile {
pub id: u16,
#[serde(default)]
pub image: Option<String>,
#[serde(default)]
pub imageheight: u16,
#[serde(default)]
pub imagewidth: u16,
#[serde(default, rename = "type")]
pub ttype: Option<String>,
#[serde(default)]
pub objectgroup: Option<Layer>,
#[serde(default)]
pub animation: Vec<Frame>,
#[serde(default)]
pub properties: Vec<Property>,
}
impl HasProperty for Tile {
/// Get access to the properties of the Tile object.
fn get_property_vector(&self) -> &Vec<Property> {
&self.properties
}
}
impl Tile {
/// This will get you the tileid of the animation frame at msecs (milliseconds) from creation.
///
/// The tuple is a boolean (whether we get an animation or not) and a u16, which will be the local
/// id of the tile in the parent tileset.
pub fn get_anim(&self, msecs: u32) -> (bool, u16) {
if !self.animation.is_empty() {
let total = self.get_anim_total() as u32;
let mut msecs = (msecs % total) as u16;
for f in self.animation.iter() {
if msecs < f.duration {
return (true, f.tileid);
}
msecs -= f.duration;
}
}
(false, 0)
}
/// id refers to the local id of the tile in the tileset.
/// This is dissimilar to the gid (global id) used for storing
/// data in tile layers.
pub fn id(&self) -> u16 {
self.id
}
/// Take the image height in pixels.
/// If this was unspecified in Tiled, this data will be 0.
pub fn image_height(&self) -> u16 {
self.imageheight
}
/// Take the image width in pixels.
/// If this was unspecified in Tiled, this data will be 0.
pub fn image_width(&self) -> u16 {
self.imagewidth
}
/// Access the animation data. This vector can be empty.
pub fn animation(&self) -> &Vec<Frame> {
&self.animation
}
/// Get the filename of the image this refers to.
pub fn image(&self) -> Option<&String> {
self.image.as_ref()
}
/// User specified type of tile.
pub fn get_type(&self) -> Option<&String> {
self.ttype.as_ref()
}
/// This will give you the objectgroup layer. This is for determining collisions
/// as defined in the tileset.
pub fn object_group(&self) -> Option<&Layer> {
self.objectgroup.as_ref()
}
fn get_anim_total(&self) -> u16 {
let mut total: u16 = 0;
for f in self.animation.iter() {
total += f.duration;
}
total
}
}
#[derive(Deserialize, Copy, Clone)]
#[cfg_attr(debug_assertions, derive(Debug))]
/// Frame structure describes each moment in an animation. It has a tileid
/// (the local identifier of the frame in a tileset; NOT a gid) and a duration.
pub struct Frame {
pub duration: u16,
pub tileid: u16,
}
impl Frame {
/// Get the duration of this frame.
pub fn duration(&self) -> u16 {
self.duration
}
/// Get the local tile id of this frame. This is not the same as the gid.
/// The local id describes precisely the location of the tile within a tileset.
pub fn tileid(&self) -> u16 {
self.tileid
}
}
#[derive(Deserialize, Copy, Clone)]
#[cfg_attr(debug_assertions, derive(Debug))]
/// TileOffset structure describes the offset of position for a Tileset.
/// I'm not quite sure how it is used. It has an x and a y component.
pub struct TileOffset {
pub x: i32, // in pixels
pub y: i32, // positive is down
}
#[derive(Deserialize, Copy, Clone)]
#[cfg_attr(debug_assertions, derive(Debug))]
/// This will define a custom grid within a tileset. I'm also not sure how this is
/// used, but it is here in case it is needed. It has a height, width, and
/// orientation as GridOrientation.
pub struct Grid {
pub height: u16,
pub width: u16,
#[serde(default = "default_to_orthogonal")]
pub orientation: GridOrientation,
}
impl Grid {
/// Get grid width
pub fn width(self) -> u16 {
self.width
}
/// Get grid height
pub fn height(self) -> u16 {
self.height
}
/// Get grid orientation as an enum tiled_json::GridOrientation
/// that you can call to_string() on.
pub fn orientation(self) -> GridOrientation {
self.orientation
}
}
#[derive(Deserialize, Copy, Clone)]
#[serde(from = "String")]
#[cfg_attr(debug_assertions, derive(Debug))]
/// GridOrientation is an enum that describes the orientation of a grid.
/// It can be either Orthogonal or Isometric.
///
/// You can call to_string() on this method if need be.
pub enum GridOrientation {
Orthogonal,
Isometric,
}
impl std::fmt::Display for GridOrientation {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
GridOrientation::Orthogonal => ORIENT_ORTHO,
GridOrientation::Isometric => ORIENT_ISO,
};
std::fmt::Display::fmt(s, f)
}
}
impl From<String> for GridOrientation {
fn from(orientation: String) -> Self {
match orientation.as_str() {
ORIENT_ORTHO => GridOrientation::Orthogonal,
ORIENT_ISO => GridOrientation::Isometric,
_ => GridOrientation::Orthogonal,
}
}
}
fn default_to_orthogonal() -> GridOrientation {
GridOrientation::Orthogonal
}
|
use core::{convert::TryFrom, fmt, mem, ops::Range};
use alloc::{boxed::Box, format, string::String, sync::Arc, vec, vec::Vec};
use crate::util::{
alphabet::{self, ByteClassSet},
decode_last_utf8, decode_utf8,
id::{IteratorIDExt, PatternID, PatternIDIter, StateID},
is_word_byte, is_word_char_fwd, is_word_char_rev,
};
pub use self::{
compiler::{Builder, Config},
error::Error,
};
mod compiler;
mod error;
mod map;
pub mod pikevm;
mod range_trie;
/// A map from capture group name to its corresponding capture index.
///
/// Since there are always two slots for each capture index, the pair of slots
/// corresponding to the capture index for a pattern ID of 0 are indexed at
/// `map["<name>"] * 2` and `map["<name>"] * 2 + 1`.
///
/// This type is actually wrapped inside a Vec indexed by pattern ID on the
/// NFA, since multiple patterns may have the same capture group name.
///
/// Note that this is somewhat of a sub-optimal representation, since it
/// requires a hashmap for each pattern. A better representation would be
/// HashMap<(PatternID, Arc<str>), usize>, but this makes it difficult to look
/// up a capture index by name without producing a `Arc<str>`, which requires
/// an allocation. To fix this, I think we'd need to define our own unsized
/// type or something?
#[cfg(feature = "std")]
type CaptureNameMap = std::collections::HashMap<Arc<str>, usize>;
#[cfg(not(feature = "std"))]
type CaptureNameMap = alloc::collections::BTreeMap<Arc<str>, usize>;
// The NFA API below is not something I'm terribly proud of at the moment. In
// particular, it supports both mutating the NFA and actually using the NFA to
// perform a search. I think combining these two things muddies the waters a
// bit too much.
//
// I think the issue is that I saw the compiler as the 'builder,' and where
// the compiler had the ability to manipulate the internal state of the NFA.
// However, one of my goals was to make it possible for others to build their
// own NFAs in a way that is *not* couple to the regex-syntax crate.
//
// So I think really, there should be an NFA, a NFABuilder and then the
// internal compiler which uses the NFABuilder API to build an NFA. Alas, at
// the time of writing, I kind of ran out of steam.
/// A fully compiled Thompson NFA.
///
/// The states of the NFA are indexed by state IDs, which are how transitions
/// are expressed.
#[derive(Clone)]
pub struct NFA {
/// The state list. This list is guaranteed to be indexable by all starting
/// state IDs, and it is also guaranteed to contain at most one `Match`
/// state for each pattern compiled into this NFA. (A pattern may not have
/// a corresponding `Match` state if a `Match` state is impossible to
/// reach.)
states: Vec<State>,
/// The anchored starting state of this NFA.
start_anchored: StateID,
/// The unanchored starting state of this NFA.
start_unanchored: StateID,
/// The starting states for each individual pattern. Starting at any
/// of these states will result in only an anchored search for the
/// corresponding pattern. The vec is indexed by pattern ID. When the NFA
/// contains a single regex, then `start_pattern[0]` and `start_anchored`
/// are always equivalent.
start_pattern: Vec<StateID>,
/// A map from PatternID to its corresponding range of capture slots. Each
/// range is guaranteed to be contiguous with the previous range. The
/// end of the last range corresponds to the total number of slots needed
/// for this NFA.
patterns_to_slots: Vec<Range<usize>>,
/// A map from capture name to its corresponding index. So e.g., given
/// a single regex like '(\w+) (\w+) (?P<word>\w+)', the capture name
/// 'word' for pattern ID=0 would corresponding to the index '3'. Its
/// corresponding slots would then be '3 * 2 = 6' and '3 * 2 + 1 = 7'.
capture_name_to_index: Vec<CaptureNameMap>,
/// A map from pattern ID to capture group index to name, if one exists.
/// This is effectively the inverse of 'capture_name_to_index'. The outer
/// vec is indexed by pattern ID, while the inner vec is index by capture
/// index offset for the corresponding pattern.
///
/// The first capture group for each pattern is always unnamed and is thus
/// always None.
capture_index_to_name: Vec<Vec<Option<Arc<str>>>>,
/// A representation of equivalence classes over the transitions in this
/// NFA. Two bytes in the same equivalence class must not discriminate
/// between a match or a non-match. This map can be used to shrink the
/// total size of a DFA's transition table with a small match-time cost.
///
/// Note that the NFA's transitions are *not* defined in terms of these
/// equivalence classes. The NFA's transitions are defined on the original
/// byte values. For the most part, this is because they wouldn't really
/// help the NFA much since the NFA already uses a sparse representation
/// to represent transitions. Byte classes are most effective in a dense
/// representation.
byte_class_set: ByteClassSet,
/// Various facts about this NFA, which can be used to improve failure
/// modes (e.g., rejecting DFA construction if an NFA has Unicode word
/// boundaries) or for performing optimizations (avoiding an increase in
/// states if there are no look-around states).
facts: Facts,
/// Heap memory used indirectly by NFA states. Since each state might use a
/// different amount of heap, we need to keep track of this incrementally.
memory_states: usize,
}
impl NFA {
pub fn config() -> Config {
Config::new()
}
pub fn builder() -> Builder {
Builder::new()
}
/// Returns an NFA with no states. Its match semantics are unspecified.
///
/// An empty NFA is useful as a starting point for building one. It is
/// itself not intended to be used for matching. For example, its starting
/// state identifiers are configured to be `0`, but since it has no states,
/// the identifiers are invalid.
///
/// If you need an NFA that never matches is anything and can be correctly
/// used for matching, use [`NFA::never_match`].
#[inline]
pub fn empty() -> NFA {
NFA {
states: vec![],
start_anchored: StateID::ZERO,
start_unanchored: StateID::ZERO,
start_pattern: vec![],
patterns_to_slots: vec![],
capture_name_to_index: vec![],
capture_index_to_name: vec![],
byte_class_set: ByteClassSet::empty(),
facts: Facts::default(),
memory_states: 0,
}
}
/// Returns an NFA with a single regex that always matches at every
/// position.
#[inline]
pub fn always_match() -> NFA {
let mut nfa = NFA::empty();
// Since we're only adding one pattern, these are guaranteed to work.
let start = nfa.add_match().unwrap();
assert_eq!(start.as_usize(), 0);
let pid = nfa.finish_pattern(start).unwrap();
assert_eq!(pid.as_usize(), 0);
nfa
}
/// Returns an NFA that never matches at any position. It contains no
/// regexes.
#[inline]
pub fn never_match() -> NFA {
let mut nfa = NFA::empty();
// Since we're only adding one state, this can never fail.
nfa.add_fail().unwrap();
nfa
}
/// Return the number of states in this NFA.
///
/// This is guaranteed to be no bigger than [`StateID::LIMIT`].
#[inline]
pub fn len(&self) -> usize {
self.states.len()
}
/// Returns the total number of distinct match states in this NFA.
/// Stated differently, this returns the total number of regex patterns
/// used to build this NFA.
///
/// This may return zero if the NFA was constructed with no patterns. In
/// this case, and only this case, the NFA can never produce a match for
/// any input.
///
/// This is guaranteed to be no bigger than [`PatternID::LIMIT`].
#[inline]
pub fn pattern_len(&self) -> usize {
self.start_pattern.len()
}
/// Returns the pattern ID of the pattern currently being compiled by this
/// NFA.
fn current_pattern_id(&self) -> PatternID {
// This always works because we never permit more patterns in
// 'start_pattern' than can be addressed by PatternID. Also, we only
// add a new entry to 'start_pattern' once we finish compiling a
// pattern. Thus, the length refers to the ID of the current pattern
// being compiled.
PatternID::new(self.start_pattern.len()).unwrap()
}
/// Returns the total number of capturing groups in this NFA.
///
/// This includes the special 0th capture group that is always present and
/// captures the start and end offset of the entire match.
///
/// This is a convenience routine for `nfa.capture_slot_len() / 2`.
#[inline]
pub fn capture_len(&self) -> usize {
let slots = self.capture_slot_len();
// This assert is guaranteed to pass since the NFA construction process
// guarantees that it is always true.
assert_eq!(slots % 2, 0, "capture slots must be divisible by 2");
slots / 2
}
/// Returns the total number of capturing slots in this NFA.
///
/// This value is guaranteed to be a multiple of 2. (Where each capturing
/// group has precisely two capturing slots in the NFA.)
#[inline]
pub fn capture_slot_len(&self) -> usize {
self.patterns_to_slots.last().map_or(0, |r| r.end)
}
/// Return a range of capture slots for the given pattern.
///
/// The range returned is guaranteed to be contiguous with ranges for
/// adjacent patterns.
///
/// This panics if the given pattern ID is greater than or equal to the
/// number of patterns in this NFA.
#[inline]
pub fn pattern_slots(&self, pid: PatternID) -> Range<usize> {
self.patterns_to_slots[pid].clone()
}
/// Return the capture group index corresponding to the given name in the
/// given pattern. If no such capture group name exists in the given
/// pattern, then this returns `None`.
///
/// If the given pattern ID is invalid, then this panics.
#[inline]
pub fn capture_name_to_index(
&self,
pid: PatternID,
name: &str,
) -> Option<usize> {
assert!(pid.as_usize() < self.pattern_len(), "invalid pattern ID");
self.capture_name_to_index[pid].get(name).cloned()
}
// TODO: add iterators over capture group names.
// Do we also permit indexing?
/// Returns an iterator over all pattern IDs in this NFA.
#[inline]
pub fn patterns(&self) -> PatternIter {
PatternIter {
it: PatternID::iter(self.pattern_len()),
_marker: core::marker::PhantomData,
}
}
/// Return the ID of the initial anchored state of this NFA.
#[inline]
pub fn start_anchored(&self) -> StateID {
self.start_anchored
}
/// Set the anchored starting state ID for this NFA.
#[inline]
pub fn set_start_anchored(&mut self, id: StateID) {
self.start_anchored = id;
}
/// Return the ID of the initial unanchored state of this NFA.
#[inline]
pub fn start_unanchored(&self) -> StateID {
self.start_unanchored
}
/// Set the unanchored starting state ID for this NFA.
#[inline]
pub fn set_start_unanchored(&mut self, id: StateID) {
self.start_unanchored = id;
}
/// Return the ID of the initial anchored state for the given pattern.
///
/// If the pattern doesn't exist in this NFA, then this panics.
#[inline]
pub fn start_pattern(&self, pid: PatternID) -> StateID {
self.start_pattern[pid]
}
/// Get the byte class set for this NFA.
#[inline]
pub fn byte_class_set(&self) -> &ByteClassSet {
&self.byte_class_set
}
/// Return a reference to the NFA state corresponding to the given ID.
#[inline]
pub fn state(&self, id: StateID) -> &State {
&self.states[id]
}
/// Returns a slice of all states in this NFA.
///
/// The slice returned may be indexed by a `StateID` generated by `add`.
#[inline]
pub fn states(&self) -> &[State] {
&self.states
}
#[inline]
pub fn is_always_start_anchored(&self) -> bool {
self.start_anchored() == self.start_unanchored()
}
#[inline]
pub fn has_any_look(&self) -> bool {
self.facts.has_any_look()
}
#[inline]
pub fn has_any_anchor(&self) -> bool {
self.facts.has_any_anchor()
}
#[inline]
pub fn has_word_boundary(&self) -> bool {
self.has_word_boundary_unicode() || self.has_word_boundary_ascii()
}
#[inline]
pub fn has_word_boundary_unicode(&self) -> bool {
self.facts.has_word_boundary_unicode()
}
#[inline]
pub fn has_word_boundary_ascii(&self) -> bool {
self.facts.has_word_boundary_ascii()
}
/// Returns the memory usage, in bytes, of this NFA.
///
/// This does **not** include the stack size used up by this NFA. To
/// compute that, use `std::mem::size_of::<NFA>()`.
#[inline]
pub fn memory_usage(&self) -> usize {
self.states.len() * mem::size_of::<State>()
+ self.memory_states
+ self.start_pattern.len() * mem::size_of::<StateID>()
}
// Why do we define a bunch of 'add_*' routines below instead of just
// defining a single 'add' routine that accepts a 'State'? Indeed, for most
// of the 'add_*' routines below, such a simple API would be more than
// appropriate. Unfortunately, adding capture states and, to a lesser
// extent, match states, is a bit more complex. Namely, when we add a
// capture state, we *really* want to know the corresponding capture
// group's name and index and what not, so that we can update other state
// inside this NFA. But, e.g., the capture group name is not and should
// not be included in 'State::Capture'. So what are our choices?
//
// 1) Define one 'add' and require some additional optional parameters.
// This feels quite ugly, and adds unnecessary complexity to more common
// and simpler cases.
//
// 2) Do what we do below. The sad thing is that our API is bigger with
// more methods. But each method is very specific and hopefully simple.
//
// 3) Define a new enum, say, 'StateWithInfo', or something that permits
// providing both a State and some extra ancillary info in some cases. This
// doesn't seem too bad to me, but seems slightly worse than (2) because of
// the additional type required.
//
// 4) Abandon the idea that we have to specify things like the capture
// group name when we add the Capture state to the NFA. We would then need
// to add other methods that permit the caller to add this additional state
// "out of band." Other than it introducing some additional complexity, I
// decided against this because I wanted the NFA builder API to make it
// as hard as possible to build a bad or invalid NFA. Using the approach
// below, as you'll see, permits us to do a lot of strict checking of our
// inputs and return an error if we see something we don't expect.
pub fn add_range(&mut self, range: Transition) -> Result<StateID, Error> {
self.byte_class_set.set_range(range.start, range.end);
self.add_state(State::Range { range })
}
pub fn add_sparse(
&mut self,
sparse: SparseTransitions,
) -> Result<StateID, Error> {
for range in sparse.ranges.iter() {
self.byte_class_set.set_range(range.start, range.end);
}
self.add_state(State::Sparse(sparse))
}
pub fn add_look(
&mut self,
next: StateID,
look: Look,
) -> Result<StateID, Error> {
self.facts.set_has_any_look(true);
look.add_to_byteset(&mut self.byte_class_set);
match look {
Look::StartLine
| Look::EndLine
| Look::StartText
| Look::EndText => {
self.facts.set_has_any_anchor(true);
}
Look::WordBoundaryUnicode | Look::WordBoundaryUnicodeNegate => {
self.facts.set_has_word_boundary_unicode(true);
}
Look::WordBoundaryAscii | Look::WordBoundaryAsciiNegate => {
self.facts.set_has_word_boundary_ascii(true);
}
}
self.add_state(State::Look { look, next })
}
pub fn add_union(
&mut self,
alternates: Box<[StateID]>,
) -> Result<StateID, Error> {
self.add_state(State::Union { alternates })
}
pub fn add_capture_start(
&mut self,
next_id: StateID,
capture_index: u32,
name: Option<Arc<str>>,
) -> Result<StateID, Error> {
let pid = self.current_pattern_id();
let capture_index = match usize::try_from(capture_index) {
Err(_) => {
return Err(Error::invalid_capture_index(core::usize::MAX))
}
Ok(capture_index) => capture_index,
};
// Do arithmetic to find our absolute slot index first, to make sure
// the index is at least possibly valid (doesn't overflow).
let relative_slot = match capture_index.checked_mul(2) {
Some(relative_slot) => relative_slot,
None => return Err(Error::invalid_capture_index(capture_index)),
};
let slot = match relative_slot.checked_add(self.capture_slot_len()) {
Some(slot) => slot,
None => return Err(Error::invalid_capture_index(capture_index)),
};
// Make sure we have space to insert our (pid,index)|-->name mapping.
if pid.as_usize() >= self.capture_index_to_name.len() {
// Note that we require that if you're adding capturing groups,
// then there must be at least one capturing group per pattern.
// Moreover, whenever we expand our space here, it should always
// first be for the first capture group (at index==0).
if pid.as_usize() > self.capture_index_to_name.len()
|| capture_index > 0
{
return Err(Error::invalid_capture_index(capture_index));
}
self.capture_name_to_index.push(CaptureNameMap::new());
self.capture_index_to_name.push(vec![]);
}
if capture_index >= self.capture_index_to_name[pid].len() {
// We require that capturing groups are added in correspondence
// to their index. So no discontinuous indices. This is likely
// overly strict, but also makes it simpler to provide guarantees
// about our capturing group data.
if capture_index > self.capture_index_to_name[pid].len() {
return Err(Error::invalid_capture_index(capture_index));
}
self.capture_index_to_name[pid].push(None);
}
if let Some(ref name) = name {
self.capture_name_to_index[pid]
.insert(Arc::clone(name), capture_index);
}
self.capture_index_to_name[pid][capture_index] = name;
self.add_state(State::Capture { next: next_id, slot })
}
pub fn add_capture_end(
&mut self,
next_id: StateID,
capture_index: u32,
) -> Result<StateID, Error> {
let pid = self.current_pattern_id();
let capture_index = match usize::try_from(capture_index) {
Err(_) => {
return Err(Error::invalid_capture_index(core::usize::MAX))
}
Ok(capture_index) => capture_index,
};
// If we haven't already added this capture group via a corresponding
// 'add_capture_start' call, then we consider the index given to be
// invalid.
if pid.as_usize() >= self.capture_index_to_name.len()
|| capture_index >= self.capture_index_to_name[pid].len()
{
return Err(Error::invalid_capture_index(capture_index));
}
// Since we've already confirmed that this capture index is invalid
// and has a corresponding starting slot, we know the multiplcation
// has already been done and succeeded.
let relative_slot_start = capture_index.checked_mul(2).unwrap();
let relative_slot = match relative_slot_start.checked_add(1) {
Some(relative_slot) => relative_slot,
None => return Err(Error::invalid_capture_index(capture_index)),
};
let slot = match relative_slot.checked_add(self.capture_slot_len()) {
Some(slot) => slot,
None => return Err(Error::invalid_capture_index(capture_index)),
};
self.add_state(State::Capture { next: next_id, slot })
}
pub fn add_fail(&mut self) -> Result<StateID, Error> {
self.add_state(State::Fail)
}
/// Add a new match state to this NFA and return its state ID.
pub fn add_match(&mut self) -> Result<StateID, Error> {
let pattern_id = self.current_pattern_id();
let sid = self.add_state(State::Match { id: pattern_id })?;
Ok(sid)
}
/// Finish compiling the current pattern and return its identifier. The
/// given ID should be the state ID corresponding to the anchored starting
/// state for matching this pattern.
pub fn finish_pattern(
&mut self,
start_id: StateID,
) -> Result<PatternID, Error> {
// We've gotta make sure that we never permit the user to add more
// patterns than we can identify. So if we're already at the limit,
// then return an error. This is somewhat non-ideal since this won't
// result in an error until trying to complete the compilation of a
// pattern instead of starting it.
if self.start_pattern.len() >= PatternID::LIMIT {
return Err(Error::too_many_patterns(
self.start_pattern.len().saturating_add(1),
));
}
let pid = self.current_pattern_id();
self.start_pattern.push(start_id);
// Add the number of new slots created by this pattern. This is always
// equivalent to '2 * caps.len()', where 'caps.len()' is the number of
// new capturing groups introduced by the pattern we're finishing.
let new_cap_groups = self
.capture_index_to_name
.get(pid.as_usize())
.map_or(0, |caps| caps.len());
let new_slots = match new_cap_groups.checked_mul(2) {
Some(new_slots) => new_slots,
None => {
// Just return the biggest index that we know exists.
let index = new_cap_groups.saturating_sub(1);
return Err(Error::invalid_capture_index(index));
}
};
let slot_start = self.capture_slot_len();
self.patterns_to_slots.push(slot_start..(slot_start + new_slots));
Ok(pid)
}
fn add_state(&mut self, state: State) -> Result<StateID, Error> {
let id = StateID::new(self.states.len())
.map_err(|_| Error::too_many_states(self.states.len()))?;
self.memory_states += state.memory_usage();
self.states.push(state);
Ok(id)
}
/// Remap the transitions in every state of this NFA using the given map.
/// The given map should be indexed according to state ID namespace used by
/// the transitions of the states currently in this NFA.
///
/// This may be used during the final phases of an NFA compiler, which
/// turns its intermediate NFA into the final NFA. Remapping may be
/// required to bring the state pointers from the intermediate NFA to the
/// final NFA.
pub fn remap(&mut self, old_to_new: &[StateID]) {
for state in &mut self.states {
state.remap(old_to_new);
}
self.start_anchored = old_to_new[self.start_anchored];
self.start_unanchored = old_to_new[self.start_unanchored];
for (pid, id) in self.start_pattern.iter_mut().with_pattern_ids() {
*id = old_to_new[*id];
}
}
/// Clear this NFA such that it has zero states and is otherwise "empty."
///
/// An empty NFA is useful as a starting point for building one. It is
/// itself not intended to be used for matching. For example, its starting
/// state identifiers are configured to be `0`, but since it has no states,
/// the identifiers are invalid.
pub fn clear(&mut self) {
self.states.clear();
self.start_anchored = StateID::ZERO;
self.start_unanchored = StateID::ZERO;
self.start_pattern.clear();
self.patterns_to_slots.clear();
self.capture_name_to_index.clear();
self.capture_index_to_name.clear();
self.byte_class_set = ByteClassSet::empty();
self.facts = Facts::default();
self.memory_states = 0;
}
}
impl fmt::Debug for NFA {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "thompson::NFA(")?;
for (sid, state) in self.states.iter().with_state_ids() {
let status = if sid == self.start_anchored {
'^'
} else if sid == self.start_unanchored {
'>'
} else {
' '
};
writeln!(f, "{}{:06?}: {:?}", status, sid.as_usize(), state)?;
}
if self.pattern_len() > 1 {
writeln!(f, "")?;
for pid in self.patterns() {
let sid = self.start_pattern(pid);
writeln!(
f,
"START({:06?}): {:?}",
pid.as_usize(),
sid.as_usize()
)?;
}
}
writeln!(f, "")?;
writeln!(
f,
"transition equivalence classes: {:?}",
self.byte_class_set().byte_classes()
)?;
writeln!(f, ")")?;
Ok(())
}
}
/// A state in a final compiled NFA.
#[derive(Clone, Eq, PartialEq)]
pub enum State {
/// A state that transitions to `next` if and only if the current input
/// byte is in the range `[start, end]` (inclusive).
///
/// This is a special case of Sparse in that it encodes only one transition
/// (and therefore avoids the allocation).
Range { range: Transition },
/// A state with possibly many transitions, represented in a sparse
/// fashion. Transitions are ordered lexicographically by input range. As
/// such, this may only be used when every transition has equal priority.
/// (In practice, this is only used for encoding UTF-8 automata.)
Sparse(SparseTransitions),
/// A conditional epsilon transition satisfied via some sort of
/// look-around.
Look { look: Look, next: StateID },
/// An alternation such that there exists an epsilon transition to all
/// states in `alternates`, where matches found via earlier transitions
/// are preferred over later transitions.
Union { alternates: Box<[StateID]> },
/// An empty state that records a capture location.
///
/// From the perspective of finite automata, this is precisely equivalent
/// to an epsilon transition, but serves the purpose of instructing NFA
/// simulations to record additional state when the finite state machine
/// passes through this epsilon transition.
///
/// These transitions are treated as epsilon transitions with no additional
/// effects in DFAs.
///
/// 'slot' in this context refers to the specific capture group offset that
/// is being recorded. Each capturing group has two slots corresponding to
/// the start and end of the matching portion of that group.
/// A fail state. When encountered, the automaton is guaranteed to never
/// reach a match state.
Capture { next: StateID, slot: usize },
/// A state that cannot be transitioned out of. If a search reaches this
/// state, then no match is possible and the search should terminate.
Fail,
/// A match state. There is exactly one such occurrence of this state for
/// each regex compiled into the NFA.
Match { id: PatternID },
}
impl State {
/// Returns true if and only if this state contains one or more epsilon
/// transitions.
#[inline]
pub fn is_epsilon(&self) -> bool {
match *self {
State::Range { .. }
| State::Sparse { .. }
| State::Fail
| State::Match { .. } => false,
State::Look { .. }
| State::Union { .. }
| State::Capture { .. } => true,
}
}
/// Returns the heap memory usage of this NFA state in bytes.
fn memory_usage(&self) -> usize {
match *self {
State::Range { .. }
| State::Look { .. }
| State::Capture { .. }
| State::Match { .. }
| State::Fail => 0,
State::Sparse(SparseTransitions { ref ranges }) => {
ranges.len() * mem::size_of::<Transition>()
}
State::Union { ref alternates } => {
alternates.len() * mem::size_of::<StateID>()
}
}
}
/// Remap the transitions in this state using the given map. Namely, the
/// given map should be indexed according to the transitions currently
/// in this state.
///
/// This is used during the final phase of the NFA compiler, which turns
/// its intermediate NFA into the final NFA.
fn remap(&mut self, remap: &[StateID]) {
match *self {
State::Range { ref mut range } => range.next = remap[range.next],
State::Sparse(SparseTransitions { ref mut ranges }) => {
for r in ranges.iter_mut() {
r.next = remap[r.next];
}
}
State::Look { ref mut next, .. } => *next = remap[*next],
State::Union { ref mut alternates } => {
for alt in alternates.iter_mut() {
*alt = remap[*alt];
}
}
State::Capture { ref mut next, .. } => *next = remap[*next],
State::Fail => {}
State::Match { .. } => {}
}
}
}
impl fmt::Debug for State {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
State::Range { ref range } => range.fmt(f),
State::Sparse(SparseTransitions { ref ranges }) => {
let rs = ranges
.iter()
.map(|t| format!("{:?}", t))
.collect::<Vec<String>>()
.join(", ");
write!(f, "sparse({})", rs)
}
State::Look { ref look, next } => {
write!(f, "{:?} => {:?}", look, next.as_usize())
}
State::Union { ref alternates } => {
let alts = alternates
.iter()
.map(|id| format!("{:?}", id.as_usize()))
.collect::<Vec<String>>()
.join(", ");
write!(f, "alt({})", alts)
}
State::Capture { next, slot } => {
write!(f, "capture({:?}) => {:?}", slot, next.as_usize())
}
State::Fail => write!(f, "FAIL"),
State::Match { id } => write!(f, "MATCH({:?})", id.as_usize()),
}
}
}
/// A collection of facts about an NFA.
///
/// There are no real cohesive principles behind what gets put in here. For
/// the most part, it is implementation driven.
#[derive(Clone, Copy, Debug, Default)]
struct Facts {
/// Various yes/no facts about this NFA.
bools: u16,
}
impl Facts {
define_bool!(0, has_any_look, set_has_any_look);
define_bool!(1, has_any_anchor, set_has_any_anchor);
define_bool!(2, has_word_boundary_unicode, set_has_word_boundary_unicode);
define_bool!(3, has_word_boundary_ascii, set_has_word_boundary_ascii);
}
/// A sequence of transitions used to represent a sparse state.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SparseTransitions {
pub ranges: Box<[Transition]>,
}
impl SparseTransitions {
pub fn matches(&self, haystack: &[u8], at: usize) -> Option<StateID> {
haystack.get(at).and_then(|&b| self.matches_byte(b))
}
pub fn matches_unit(&self, unit: alphabet::Unit) -> Option<StateID> {
unit.as_u8().map_or(None, |byte| self.matches_byte(byte))
}
pub fn matches_byte(&self, byte: u8) -> Option<StateID> {
for t in self.ranges.iter() {
if t.start > byte {
break;
} else if t.matches_byte(byte) {
return Some(t.next);
}
}
None
/*
// This is an alternative implementation that uses binary search. In
// some ad hoc experiments, like
//
// smallishru=OpenSubtitles2018.raw.sample.smallish.ru
// regex-cli find nfa thompson pikevm -b "@$smallishru" '\b\w+\b'
//
// I could not observe any improvement, and in fact, things seemed to
// be a bit slower.
self.ranges
.binary_search_by(|t| {
if t.end < byte {
core::cmp::Ordering::Less
} else if t.start > byte {
core::cmp::Ordering::Greater
} else {
core::cmp::Ordering::Equal
}
})
.ok()
.map(|i| self.ranges[i].next)
*/
}
}
/// A transition to another state, only if the given byte falls in the
/// inclusive range specified.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct Transition {
pub start: u8,
pub end: u8,
pub next: StateID,
}
impl Transition {
pub fn matches(&self, haystack: &[u8], at: usize) -> bool {
haystack.get(at).map_or(false, |&b| self.matches_byte(b))
}
pub fn matches_unit(&self, unit: alphabet::Unit) -> bool {
unit.as_u8().map_or(false, |byte| self.matches_byte(byte))
}
pub fn matches_byte(&self, byte: u8) -> bool {
self.start <= byte && byte <= self.end
}
}
impl fmt::Debug for Transition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::util::DebugByte;
let Transition { start, end, next } = *self;
if self.start == self.end {
write!(f, "{:?} => {:?}", DebugByte(start), next.as_usize())
} else {
write!(
f,
"{:?}-{:?} => {:?}",
DebugByte(start),
DebugByte(end),
next.as_usize(),
)
}
}
}
/// A conditional NFA epsilon transition.
///
/// A simulation of the NFA can only move through this epsilon transition if
/// the current position satisfies some look-around property. Some assertions
/// are look-behind (StartLine, StartText), some assertions are look-ahead
/// (EndLine, EndText) while other assertions are both look-behind and
/// look-ahead (WordBoundary*).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Look {
/// The previous position is either `\n` or the current position is the
/// beginning of the haystack (i.e., at position `0`).
StartLine = 1 << 0,
/// The next position is either `\n` or the current position is the end of
/// the haystack (i.e., at position `haystack.len()`).
EndLine = 1 << 1,
/// The current position is the beginning of the haystack (i.e., at
/// position `0`).
StartText = 1 << 2,
/// The current position is the end of the haystack (i.e., at position
/// `haystack.len()`).
EndText = 1 << 3,
/// When tested at position `i`, where `p=decode_utf8_rev(&haystack[..i])`
/// and `n=decode_utf8(&haystack[i..])`, this assertion passes if and only
/// if `is_word(p) != is_word(n)`. If `i=0`, then `is_word(p)=false` and if
/// `i=haystack.len()`, then `is_word(n)=false`.
WordBoundaryUnicode = 1 << 4,
/// Same as for `WordBoundaryUnicode`, but requires that
/// `is_word(p) == is_word(n)`.
WordBoundaryUnicodeNegate = 1 << 5,
/// When tested at position `i`, where `p=haystack[i-1]` and
/// `n=haystack[i]`, this assertion passes if and only if `is_word(p)
/// != is_word(n)`. If `i=0`, then `is_word(p)=false` and if
/// `i=haystack.len()`, then `is_word(n)=false`.
WordBoundaryAscii = 1 << 6,
/// Same as for `WordBoundaryAscii`, but requires that
/// `is_word(p) == is_word(n)`.
///
/// Note that it is possible for this assertion to match at positions that
/// split the UTF-8 encoding of a codepoint. For this reason, this may only
/// be used when UTF-8 mode is disable in the regex syntax.
WordBoundaryAsciiNegate = 1 << 7,
}
impl Look {
#[inline(always)]
pub fn matches(&self, bytes: &[u8], at: usize) -> bool {
match *self {
Look::StartLine => at == 0 || bytes[at - 1] == b'\n',
Look::EndLine => at == bytes.len() || bytes[at] == b'\n',
Look::StartText => at == 0,
Look::EndText => at == bytes.len(),
Look::WordBoundaryUnicode => {
let word_before = is_word_char_rev(bytes, at);
let word_after = is_word_char_fwd(bytes, at);
word_before != word_after
}
Look::WordBoundaryUnicodeNegate => {
// This is pretty subtle. Why do we need to do UTF-8 decoding
// here? Well... at time of writing, the is_word_char_{fwd,rev}
// routines will only return true if there is a valid UTF-8
// encoding of a "word" codepoint, and false in every other
// case (including invalid UTF-8). This means that in regions
// of invalid UTF-8 (which might be a subset of valid UTF-8!),
// it would result in \B matching. While this would be
// questionable in the context of truly invalid UTF-8, it is
// *certainly* wrong to report match boundaries that split the
// encoding of a codepoint. So to work around this, we ensure
// that we can decode a codepoint on either side of `at`. If
// either direction fails, then we don't permit \B to match at
// all.
//
// Now, this isn't exactly optimal from a perf perspective. We
// could try and detect this in is_word_char_{fwd,rev}, but
// it's not clear if it's worth it. \B is, after all, rarely
// used.
//
// And in particular, we do *not* have to do this with \b,
// because \b *requires* that at least one side of `at` be a
// "word" codepoint, which in turn implies one side of `at`
// must be valid UTF-8. This in turn implies that \b can never
// split a valid UTF-8 encoding of a codepoint. In the case
// where one side of `at` is truly invalid UTF-8 and the other
// side IS a word codepoint, then we want \b to match since it
// represents a valid UTF-8 boundary. It also makes sense. For
// example, you'd want \b\w+\b to match 'abc' in '\xFFabc\xFF'.
let word_before = at > 0
&& match decode_last_utf8(&bytes[..at]) {
None | Some(Err(_)) => return false,
Some(Ok(_)) => is_word_char_rev(bytes, at),
};
let word_after = at < bytes.len()
&& match decode_utf8(&bytes[at..]) {
None | Some(Err(_)) => return false,
Some(Ok(_)) => is_word_char_fwd(bytes, at),
};
word_before == word_after
}
Look::WordBoundaryAscii => {
let word_before = at > 0 && is_word_byte(bytes[at - 1]);
let word_after = at < bytes.len() && is_word_byte(bytes[at]);
word_before != word_after
}
Look::WordBoundaryAsciiNegate => {
let word_before = at > 0 && is_word_byte(bytes[at - 1]);
let word_after = at < bytes.len() && is_word_byte(bytes[at]);
word_before == word_after
}
}
}
/// Create a look-around assertion from its corresponding integer (as
/// defined in `Look`). If the given integer does not correspond to any
/// assertion, then None is returned.
fn from_int(n: u8) -> Option<Look> {
match n {
0b0000_0001 => Some(Look::StartLine),
0b0000_0010 => Some(Look::EndLine),
0b0000_0100 => Some(Look::StartText),
0b0000_1000 => Some(Look::EndText),
0b0001_0000 => Some(Look::WordBoundaryUnicode),
0b0010_0000 => Some(Look::WordBoundaryUnicodeNegate),
0b0100_0000 => Some(Look::WordBoundaryAscii),
0b1000_0000 => Some(Look::WordBoundaryAsciiNegate),
_ => None,
}
}
/// Flip the look-around assertion to its equivalent for reverse searches.
fn reversed(&self) -> Look {
match *self {
Look::StartLine => Look::EndLine,
Look::EndLine => Look::StartLine,
Look::StartText => Look::EndText,
Look::EndText => Look::StartText,
Look::WordBoundaryUnicode => Look::WordBoundaryUnicode,
Look::WordBoundaryUnicodeNegate => Look::WordBoundaryUnicodeNegate,
Look::WordBoundaryAscii => Look::WordBoundaryAscii,
Look::WordBoundaryAsciiNegate => Look::WordBoundaryAsciiNegate,
}
}
/// Split up the given byte classes into equivalence classes in a way that
/// is consistent with this look-around assertion.
fn add_to_byteset(&self, set: &mut ByteClassSet) {
match *self {
Look::StartText | Look::EndText => {}
Look::StartLine | Look::EndLine => {
set.set_range(b'\n', b'\n');
}
Look::WordBoundaryUnicode
| Look::WordBoundaryUnicodeNegate
| Look::WordBoundaryAscii
| Look::WordBoundaryAsciiNegate => {
// We need to mark all ranges of bytes whose pairs result in
// evaluating \b differently. This isn't technically correct
// for Unicode word boundaries, but DFAs can't handle those
// anyway, and thus, the byte classes don't need to either
// since they are themselves only used in DFAs.
let iswb = regex_syntax::is_word_byte;
let mut b1: u16 = 0;
let mut b2: u16;
while b1 <= 255 {
b2 = b1 + 1;
while b2 <= 255 && iswb(b1 as u8) == iswb(b2 as u8) {
b2 += 1;
}
set.set_range(b1 as u8, (b2 - 1) as u8);
b1 = b2;
}
}
}
}
}
/// LookSet is a memory-efficient set of look-around assertions. Callers may
/// idempotently insert or remove any look-around assertion from a set.
#[repr(transparent)]
#[derive(Clone, Copy, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub(crate) struct LookSet {
set: u8,
}
impl LookSet {
/// Return a LookSet from its representation.
pub(crate) fn from_repr(repr: u8) -> LookSet {
LookSet { set: repr }
}
/// Return a mutable LookSet from a mutable pointer to its representation.
pub(crate) fn from_repr_mut(repr: &mut u8) -> &mut LookSet {
// SAFETY: This is safe since a LookSet is repr(transparent) where its
// repr is a u8.
unsafe { core::mem::transmute::<&mut u8, &mut LookSet>(repr) }
}
/// Return true if and only if this set is empty.
pub(crate) fn is_empty(&self) -> bool {
self.set == 0
}
/// Clears this set such that it has no assertions in it.
pub(crate) fn clear(&mut self) {
self.set = 0;
}
/// Insert the given look-around assertion into this set. If the assertion
/// already exists, then this is a no-op.
pub(crate) fn insert(&mut self, look: Look) {
self.set |= look as u8;
}
/// Remove the given look-around assertion from this set. If the assertion
/// is not in this set, then this is a no-op.
#[cfg(test)]
pub(crate) fn remove(&mut self, look: Look) {
self.set &= !(look as u8);
}
/// Return true if and only if the given assertion is in this set.
pub(crate) fn contains(&self, look: Look) -> bool {
(look as u8) & self.set != 0
}
/// Subtract the given `other` set from the `self` set and return a new
/// set.
pub(crate) fn subtract(&self, other: LookSet) -> LookSet {
LookSet { set: self.set & !other.set }
}
/// Return the intersection of the given `other` set with the `self` set
/// and return the resulting set.
pub(crate) fn intersect(&self, other: LookSet) -> LookSet {
LookSet { set: self.set & other.set }
}
}
impl core::fmt::Debug for LookSet {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
let mut members = vec![];
for i in 0..8 {
let look = match Look::from_int(1 << i) {
None => continue,
Some(look) => look,
};
if self.contains(look) {
members.push(look);
}
}
f.debug_tuple("LookSet").field(&members).finish()
}
}
/// An iterator over all pattern IDs in an NFA.
pub struct PatternIter<'a> {
it: PatternIDIter,
/// We explicitly associate a lifetime with this iterator even though we
/// don't actually borrow anything from the NFA. We do this for backward
/// compatibility purposes. If we ever do need to borrow something from
/// the NFA, then we can and just get rid of this marker without breaking
/// the public API.
_marker: core::marker::PhantomData<&'a ()>,
}
impl<'a> Iterator for PatternIter<'a> {
type Item = PatternID;
fn next(&mut self) -> Option<PatternID> {
self.it.next()
}
}
#[cfg(test)]
mod tests {
use super::*;
// TODO: Replace tests using DFA with NFA matching engine once implemented.
use crate::dfa::{dense, Automaton};
#[test]
fn always_match() {
let nfa = NFA::always_match();
let dfa = dense::Builder::new().build_from_nfa(&nfa).unwrap();
let find = |input, start, end| {
dfa.find_leftmost_fwd_at(None, None, input, start, end)
.unwrap()
.map(|m| m.offset())
};
assert_eq!(Some(0), find(b"", 0, 0));
assert_eq!(Some(0), find(b"a", 0, 1));
assert_eq!(Some(1), find(b"a", 1, 1));
assert_eq!(Some(0), find(b"ab", 0, 2));
assert_eq!(Some(1), find(b"ab", 1, 2));
assert_eq!(Some(2), find(b"ab", 2, 2));
}
#[test]
fn never_match() {
let nfa = NFA::never_match();
let dfa = dense::Builder::new().build_from_nfa(&nfa).unwrap();
let find = |input, start, end| {
dfa.find_leftmost_fwd_at(None, None, input, start, end)
.unwrap()
.map(|m| m.offset())
};
assert_eq!(None, find(b"", 0, 0));
assert_eq!(None, find(b"a", 0, 1));
assert_eq!(None, find(b"a", 1, 1));
assert_eq!(None, find(b"ab", 0, 2));
assert_eq!(None, find(b"ab", 1, 2));
assert_eq!(None, find(b"ab", 2, 2));
}
#[test]
fn look_set() {
let mut f = LookSet::default();
assert!(!f.contains(Look::StartText));
assert!(!f.contains(Look::EndText));
assert!(!f.contains(Look::StartLine));
assert!(!f.contains(Look::EndLine));
assert!(!f.contains(Look::WordBoundaryUnicode));
assert!(!f.contains(Look::WordBoundaryUnicodeNegate));
assert!(!f.contains(Look::WordBoundaryAscii));
assert!(!f.contains(Look::WordBoundaryAsciiNegate));
f.insert(Look::StartText);
assert!(f.contains(Look::StartText));
f.remove(Look::StartText);
assert!(!f.contains(Look::StartText));
f.insert(Look::EndText);
assert!(f.contains(Look::EndText));
f.remove(Look::EndText);
assert!(!f.contains(Look::EndText));
f.insert(Look::StartLine);
assert!(f.contains(Look::StartLine));
f.remove(Look::StartLine);
assert!(!f.contains(Look::StartLine));
f.insert(Look::EndLine);
assert!(f.contains(Look::EndLine));
f.remove(Look::EndLine);
assert!(!f.contains(Look::EndLine));
f.insert(Look::WordBoundaryUnicode);
assert!(f.contains(Look::WordBoundaryUnicode));
f.remove(Look::WordBoundaryUnicode);
assert!(!f.contains(Look::WordBoundaryUnicode));
f.insert(Look::WordBoundaryUnicodeNegate);
assert!(f.contains(Look::WordBoundaryUnicodeNegate));
f.remove(Look::WordBoundaryUnicodeNegate);
assert!(!f.contains(Look::WordBoundaryUnicodeNegate));
f.insert(Look::WordBoundaryAscii);
assert!(f.contains(Look::WordBoundaryAscii));
f.remove(Look::WordBoundaryAscii);
assert!(!f.contains(Look::WordBoundaryAscii));
f.insert(Look::WordBoundaryAsciiNegate);
assert!(f.contains(Look::WordBoundaryAsciiNegate));
f.remove(Look::WordBoundaryAsciiNegate);
assert!(!f.contains(Look::WordBoundaryAsciiNegate));
}
#[test]
fn look_matches_start_line() {
let look = Look::StartLine;
assert!(look.matches(B(""), 0));
assert!(look.matches(B("\n"), 0));
assert!(look.matches(B("\n"), 1));
assert!(look.matches(B("a"), 0));
assert!(look.matches(B("\na"), 1));
assert!(!look.matches(B("a"), 1));
assert!(!look.matches(B("a\na"), 1));
}
#[test]
fn look_matches_end_line() {
let look = Look::EndLine;
assert!(look.matches(B(""), 0));
assert!(look.matches(B("\n"), 1));
assert!(look.matches(B("\na"), 0));
assert!(look.matches(B("\na"), 2));
assert!(look.matches(B("a\na"), 1));
assert!(!look.matches(B("a"), 0));
assert!(!look.matches(B("\na"), 1));
assert!(!look.matches(B("a\na"), 0));
assert!(!look.matches(B("a\na"), 2));
}
#[test]
fn look_matches_start_text() {
let look = Look::StartText;
assert!(look.matches(B(""), 0));
assert!(look.matches(B("\n"), 0));
assert!(look.matches(B("a"), 0));
assert!(!look.matches(B("\n"), 1));
assert!(!look.matches(B("\na"), 1));
assert!(!look.matches(B("a"), 1));
assert!(!look.matches(B("a\na"), 1));
}
#[test]
fn look_matches_end_text() {
let look = Look::EndText;
assert!(look.matches(B(""), 0));
assert!(look.matches(B("\n"), 1));
assert!(look.matches(B("\na"), 2));
assert!(!look.matches(B("\na"), 0));
assert!(!look.matches(B("a\na"), 1));
assert!(!look.matches(B("a"), 0));
assert!(!look.matches(B("\na"), 1));
assert!(!look.matches(B("a\na"), 0));
assert!(!look.matches(B("a\na"), 2));
}
#[test]
fn look_matches_word_unicode() {
let look = Look::WordBoundaryUnicode;
// \xF0\x9D\x9B\x83 = 𝛃 (in \w)
// \xF0\x90\x86\x80 = 𐆀 (not in \w)
// Simple ASCII word boundaries.
assert!(look.matches(B("a"), 0));
assert!(look.matches(B("a"), 1));
assert!(look.matches(B("a "), 1));
assert!(look.matches(B(" a "), 1));
assert!(look.matches(B(" a "), 2));
// Unicode word boundaries with a non-ASCII codepoint.
assert!(look.matches(B("𝛃"), 0));
assert!(look.matches(B("𝛃"), 4));
assert!(look.matches(B("𝛃 "), 4));
assert!(look.matches(B(" 𝛃 "), 1));
assert!(look.matches(B(" 𝛃 "), 5));
// Unicode word boundaries between non-ASCII codepoints.
assert!(look.matches(B("𝛃𐆀"), 0));
assert!(look.matches(B("𝛃𐆀"), 4));
// Non word boundaries for ASCII.
assert!(!look.matches(B(""), 0));
assert!(!look.matches(B("ab"), 1));
assert!(!look.matches(B("a "), 2));
assert!(!look.matches(B(" a "), 0));
assert!(!look.matches(B(" a "), 3));
// Non word boundaries with a non-ASCII codepoint.
assert!(!look.matches(B("𝛃b"), 4));
assert!(!look.matches(B("𝛃 "), 5));
assert!(!look.matches(B(" 𝛃 "), 0));
assert!(!look.matches(B(" 𝛃 "), 6));
assert!(!look.matches(B("𝛃"), 1));
assert!(!look.matches(B("𝛃"), 2));
assert!(!look.matches(B("𝛃"), 3));
// Non word boundaries with non-ASCII codepoints.
assert!(!look.matches(B("𝛃𐆀"), 1));
assert!(!look.matches(B("𝛃𐆀"), 2));
assert!(!look.matches(B("𝛃𐆀"), 3));
assert!(!look.matches(B("𝛃𐆀"), 5));
assert!(!look.matches(B("𝛃𐆀"), 6));
assert!(!look.matches(B("𝛃𐆀"), 7));
assert!(!look.matches(B("𝛃𐆀"), 8));
}
#[test]
fn look_matches_word_ascii() {
let look = Look::WordBoundaryAscii;
// \xF0\x9D\x9B\x83 = 𝛃 (in \w)
// \xF0\x90\x86\x80 = 𐆀 (not in \w)
// Simple ASCII word boundaries.
assert!(look.matches(B("a"), 0));
assert!(look.matches(B("a"), 1));
assert!(look.matches(B("a "), 1));
assert!(look.matches(B(" a "), 1));
assert!(look.matches(B(" a "), 2));
// Unicode word boundaries with a non-ASCII codepoint. Since this is
// an ASCII word boundary, none of these match.
assert!(!look.matches(B("𝛃"), 0));
assert!(!look.matches(B("𝛃"), 4));
assert!(!look.matches(B("𝛃 "), 4));
assert!(!look.matches(B(" 𝛃 "), 1));
assert!(!look.matches(B(" 𝛃 "), 5));
// Unicode word boundaries between non-ASCII codepoints. Again, since
// this is an ASCII word boundary, none of these match.
assert!(!look.matches(B("𝛃𐆀"), 0));
assert!(!look.matches(B("𝛃𐆀"), 4));
// Non word boundaries for ASCII.
assert!(!look.matches(B(""), 0));
assert!(!look.matches(B("ab"), 1));
assert!(!look.matches(B("a "), 2));
assert!(!look.matches(B(" a "), 0));
assert!(!look.matches(B(" a "), 3));
// Non word boundaries with a non-ASCII codepoint.
assert!(look.matches(B("𝛃b"), 4));
assert!(!look.matches(B("𝛃 "), 5));
assert!(!look.matches(B(" 𝛃 "), 0));
assert!(!look.matches(B(" 𝛃 "), 6));
assert!(!look.matches(B("𝛃"), 1));
assert!(!look.matches(B("𝛃"), 2));
assert!(!look.matches(B("𝛃"), 3));
// Non word boundaries with non-ASCII codepoints.
assert!(!look.matches(B("𝛃𐆀"), 1));
assert!(!look.matches(B("𝛃𐆀"), 2));
assert!(!look.matches(B("𝛃𐆀"), 3));
assert!(!look.matches(B("𝛃𐆀"), 5));
assert!(!look.matches(B("𝛃𐆀"), 6));
assert!(!look.matches(B("𝛃𐆀"), 7));
assert!(!look.matches(B("𝛃𐆀"), 8));
}
#[test]
fn look_matches_word_unicode_negate() {
let look = Look::WordBoundaryUnicodeNegate;
// \xF0\x9D\x9B\x83 = 𝛃 (in \w)
// \xF0\x90\x86\x80 = 𐆀 (not in \w)
// Simple ASCII word boundaries.
assert!(!look.matches(B("a"), 0));
assert!(!look.matches(B("a"), 1));
assert!(!look.matches(B("a "), 1));
assert!(!look.matches(B(" a "), 1));
assert!(!look.matches(B(" a "), 2));
// Unicode word boundaries with a non-ASCII codepoint.
assert!(!look.matches(B("𝛃"), 0));
assert!(!look.matches(B("𝛃"), 4));
assert!(!look.matches(B("𝛃 "), 4));
assert!(!look.matches(B(" 𝛃 "), 1));
assert!(!look.matches(B(" 𝛃 "), 5));
// Unicode word boundaries between non-ASCII codepoints.
assert!(!look.matches(B("𝛃𐆀"), 0));
assert!(!look.matches(B("𝛃𐆀"), 4));
// Non word boundaries for ASCII.
assert!(look.matches(B(""), 0));
assert!(look.matches(B("ab"), 1));
assert!(look.matches(B("a "), 2));
assert!(look.matches(B(" a "), 0));
assert!(look.matches(B(" a "), 3));
// Non word boundaries with a non-ASCII codepoint.
assert!(look.matches(B("𝛃b"), 4));
assert!(look.matches(B("𝛃 "), 5));
assert!(look.matches(B(" 𝛃 "), 0));
assert!(look.matches(B(" 𝛃 "), 6));
// These don't match because they could otherwise return an offset that
// splits the UTF-8 encoding of a codepoint.
assert!(!look.matches(B("𝛃"), 1));
assert!(!look.matches(B("𝛃"), 2));
assert!(!look.matches(B("𝛃"), 3));
// Non word boundaries with non-ASCII codepoints. These also don't
// match because they could otherwise return an offset that splits the
// UTF-8 encoding of a codepoint.
assert!(!look.matches(B("𝛃𐆀"), 1));
assert!(!look.matches(B("𝛃𐆀"), 2));
assert!(!look.matches(B("𝛃𐆀"), 3));
assert!(!look.matches(B("𝛃𐆀"), 5));
assert!(!look.matches(B("𝛃𐆀"), 6));
assert!(!look.matches(B("𝛃𐆀"), 7));
// But this one does, since 𐆀 isn't a word codepoint, and 8 is the end
// of the haystack. So the "end" of the haystack isn't a word and 𐆀
// isn't a word, thus, \B matches.
assert!(look.matches(B("𝛃𐆀"), 8));
}
#[test]
fn look_matches_word_ascii_negate() {
let look = Look::WordBoundaryAsciiNegate;
// \xF0\x9D\x9B\x83 = 𝛃 (in \w)
// \xF0\x90\x86\x80 = 𐆀 (not in \w)
// Simple ASCII word boundaries.
assert!(!look.matches(B("a"), 0));
assert!(!look.matches(B("a"), 1));
assert!(!look.matches(B("a "), 1));
assert!(!look.matches(B(" a "), 1));
assert!(!look.matches(B(" a "), 2));
// Unicode word boundaries with a non-ASCII codepoint. Since this is
// an ASCII word boundary, none of these match.
assert!(look.matches(B("𝛃"), 0));
assert!(look.matches(B("𝛃"), 4));
assert!(look.matches(B("𝛃 "), 4));
assert!(look.matches(B(" 𝛃 "), 1));
assert!(look.matches(B(" 𝛃 "), 5));
// Unicode word boundaries between non-ASCII codepoints. Again, since
// this is an ASCII word boundary, none of these match.
assert!(look.matches(B("𝛃𐆀"), 0));
assert!(look.matches(B("𝛃𐆀"), 4));
// Non word boundaries for ASCII.
assert!(look.matches(B(""), 0));
assert!(look.matches(B("ab"), 1));
assert!(look.matches(B("a "), 2));
assert!(look.matches(B(" a "), 0));
assert!(look.matches(B(" a "), 3));
// Non word boundaries with a non-ASCII codepoint.
assert!(!look.matches(B("𝛃b"), 4));
assert!(look.matches(B("𝛃 "), 5));
assert!(look.matches(B(" 𝛃 "), 0));
assert!(look.matches(B(" 𝛃 "), 6));
assert!(look.matches(B("𝛃"), 1));
assert!(look.matches(B("𝛃"), 2));
assert!(look.matches(B("𝛃"), 3));
// Non word boundaries with non-ASCII codepoints.
assert!(look.matches(B("𝛃𐆀"), 1));
assert!(look.matches(B("𝛃𐆀"), 2));
assert!(look.matches(B("𝛃𐆀"), 3));
assert!(look.matches(B("𝛃𐆀"), 5));
assert!(look.matches(B("𝛃𐆀"), 6));
assert!(look.matches(B("𝛃𐆀"), 7));
assert!(look.matches(B("𝛃𐆀"), 8));
}
fn B<'a, T: 'a + ?Sized + AsRef<[u8]>>(string: &'a T) -> &'a [u8] {
string.as_ref()
}
}
|
polygraph::schema!{
type Tree;
pub struct Surname(String);
pub struct Person {
surname: Key<Surname<'a>>,
name: String,
}
}
fn main() {
}
|
//! Displays debug lines using an orthographic camera.
use amethyst::{
core::{
transform::{Transform, TransformBundle},
Time,
},
ecs::{Read, ReadExpect, Resources, System, SystemData, Write},
prelude::*,
renderer::{
camera::Camera,
debug_drawing::{DebugLines, DebugLinesComponent, DebugLinesParams},
palette::Srgba,
pass::DrawDebugLinesDesc,
rendy::{
graph::present::PresentNode,
hal::command::{ClearDepthStencil, ClearValue},
},
types::DefaultBackend,
Backend, Factory, Format, GraphBuilder, GraphCreator, Kind, RenderGroupDesc,
RenderingSystem, SubpassBuilder,
},
utils::application_root_dir,
window::{ScreenDimensions, Window, WindowBundle},
};
struct ExampleLinesSystem;
impl<'s> System<'s> for ExampleLinesSystem {
type SystemData = (
ReadExpect<'s, ScreenDimensions>,
Write<'s, DebugLines>,
Read<'s, Time>,
);
fn run(&mut self, (screen_dimensions, mut debug_lines_resource, time): Self::SystemData) {
let t = (time.absolute_time_seconds() as f32).cos() / 2.0 + 0.5;
let screen_w = screen_dimensions.width();
let screen_h = screen_dimensions.height();
let y = t * screen_h;
debug_lines_resource.draw_line(
[0.0, y, 1.0].into(),
[screen_w, y + 2.0, 1.0].into(),
Srgba::new(0.3, 0.3, 1.0, 1.0),
);
}
}
struct ExampleState;
impl SimpleState for ExampleState {
fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) {
// Setup debug lines as a resource
data.world.add_resource(DebugLines::new());
// Configure width of lines. Optional step
data.world
.add_resource(DebugLinesParams { line_width: 2.0 });
// Setup debug lines as a component and add lines to render axis&grid
let mut debug_lines_component = DebugLinesComponent::new();
let (screen_w, screen_h) = {
let screen_dimensions = data.world.read_resource::<ScreenDimensions>();
(screen_dimensions.width(), screen_dimensions.height())
};
for y in (0..(screen_h as u16)).step_by(50).map(f32::from) {
debug_lines_component.add_line(
[0.0, y, 1.0].into(),
[screen_w, (y + 2.0), 1.0].into(),
Srgba::new(0.3, 0.3, 0.3, 1.0),
);
}
for x in (0..(screen_w as u16)).step_by(50).map(f32::from) {
debug_lines_component.add_line(
[x, 0.0, 1.0].into(),
[x, screen_h, 1.0].into(),
Srgba::new(0.3, 0.3, 0.3, 1.0),
);
}
debug_lines_component.add_line(
[20.0, 20.0, 1.0].into(),
[780.0, 580.0, 1.0].into(),
Srgba::new(1.0, 0.0, 0.2, 1.0), // Red
);
data.world
.create_entity()
.with(debug_lines_component)
.build();
// Setup camera
let mut local_transform = Transform::default();
local_transform.set_translation_xyz(screen_w / 2., screen_h / 2., 10.0);
data.world
.create_entity()
.with(Camera::standard_2d(screen_w, screen_h))
.with(local_transform)
.build();
}
}
fn main() -> amethyst::Result<()> {
amethyst::start_logger(Default::default());
let app_root = application_root_dir()?;
let display_config_path = app_root.join("examples/debug_lines_ortho/config/display.ron");
let assets_directory = app_root.join("examples/assets/");
let game_data = GameDataBuilder::default()
.with_bundle(WindowBundle::from_config_path(display_config_path))?
.with_bundle(TransformBundle::new())?
.with(ExampleLinesSystem, "example_lines_system", &["window"])
.with_thread_local(RenderingSystem::<DefaultBackend, _>::new(
ExampleGraph::default(),
));
let mut game = Application::new(assets_directory, ExampleState, game_data)?;
game.run();
Ok(())
}
#[derive(Default)]
struct ExampleGraph {
dimensions: Option<ScreenDimensions>,
dirty: bool,
}
#[allow(clippy::map_clone)]
impl<B: Backend> GraphCreator<B> for ExampleGraph {
fn rebuild(&mut self, res: &Resources) -> bool {
// Rebuild when dimensions change, but wait until at least two frames have the same.
let new_dimensions = res.try_fetch::<ScreenDimensions>();
use std::ops::Deref;
if self.dimensions.as_ref() != new_dimensions.as_ref().map(|d| d.deref()) {
self.dirty = true;
self.dimensions = new_dimensions.map(|d| d.clone());
return false;
}
self.dirty
}
fn builder(&mut self, factory: &mut Factory<B>, res: &Resources) -> GraphBuilder<B, Resources> {
self.dirty = false;
// Retrieve a reference to the target window, which is created by the WindowBundle
let window = <ReadExpect<'_, Window>>::fetch(res);
let dimensions = self.dimensions.as_ref().unwrap();
let window_kind = Kind::D2(dimensions.width() as u32, dimensions.height() as u32, 1, 1);
// Create a new drawing surface in our window
let surface = factory.create_surface(&window);
let surface_format = factory.get_surface_format(&surface);
let mut graph_builder = GraphBuilder::new();
let color = graph_builder.create_image(
window_kind,
1,
surface_format,
Some(ClearValue::Color([0.0, 0.0, 0.0, 1.0].into())),
);
let depth = graph_builder.create_image(
window_kind,
1,
Format::D32Sfloat,
Some(ClearValue::DepthStencil(ClearDepthStencil(1.0, 0))),
);
let pass = graph_builder.add_node(
SubpassBuilder::new()
.with_group(DrawDebugLinesDesc::new().builder())
.with_color(color)
.with_depth_stencil(depth)
.into_pass(),
);
let _present = graph_builder
.add_node(PresentNode::builder(factory, surface, color).with_dependency(pass));
graph_builder
}
}
|
// 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 crate::lexer::lexer::{Lexer, LocToken, Token};
use crate::lexer::preprocessor::context::PreprocContext;
use crate::parser::attributes::Attributes;
use crate::parser::expression::{ExprNode, ExpressionParser};
#[derive(Clone, Debug, PartialEq)]
pub struct Return {
pub(crate) attributes: Option<Attributes>,
pub(crate) val: Option<ExprNode>,
}
pub struct ReturnStmtParser<'a, 'b, PC: PreprocContext> {
lexer: &'b mut Lexer<'a, PC>,
}
impl<'a, 'b, PC: PreprocContext> ReturnStmtParser<'a, 'b, PC> {
pub(super) fn new(lexer: &'b mut Lexer<'a, PC>) -> Self {
Self { lexer }
}
pub(super) fn parse(
self,
attributes: Option<Attributes>,
) -> (Option<LocToken>, Option<Return>) {
let mut ep = ExpressionParser::new(self.lexer, Token::Eof);
let (tok, expr) = ep.parse(None);
(
tok,
Some(Return {
attributes,
val: expr,
}),
)
}
}
|
//! This crate provides C ABI interface for [battery](https://crates.io/crate/battery) crate.
//!
//! # Bindings generation
//!
//! Among library creation this crate generates `battery_ffi.h` file, enabled by default by `cbindgen` feature,
//! which might be useful for automatic bindings generation or just with plain `C`/`C++` development.
//!
//! After build it will be located somewhere at `target/*/build/battery-ffi-*/out/`,
//! depending on build profile (`debug`/`release`) and build hash.
//!
//! Disabling `cbindgen` feature might speed up compilation a little bit,
//! especially if you don't need the header file.
//!
//! # Examples
//!
//! ```c
//! #include "battery_ffi.h"
//!
//! void main() {
//! Manager *manager = battery_manager_new();
//! // .. handle `manager == NULL` here ..
//! Batteries *iterator = battery_manager_iter(manager);
//! // .. handle `iterator == NULL` here ..
//! while (true) {
//! Battery *battery = battery_iterator_next(iterator);
//! // .. handle possible error here ..
//! if (battery == NULL) {
//! break;
//! }
//!
//! // Use some `battery_get_*` functions here
//!
//! battery_free(battery);
//! }
//!
//! battery_iterator_free(iterator);
//! battery_manager_free(manager);
//! }
//! ```
//!
//! Also, check the `examples/` directory in the repository for examples with C and Python.
#![doc(html_root_url = "https://docs.rs/battery-ffi/0.7.5")]
#![allow(clippy::missing_safety_doc)]
// cbindgen==0.8.0 fails to export typedefs for opaque pointers
// from the battery crate, if this line is missing
extern crate battery as battery_lib;
mod battery;
mod errors;
mod iterator;
mod manager;
mod state;
mod technology;
/// Opaque struct representing battery manager.
///
/// End users should consider it as a some memory somewhere in the heap,
/// and work with it only via library methods.
pub type Manager = battery_lib::Manager;
/// Opaque struct representing batteries iterator.
///
/// End users should consider it as a some memory somewhere in the heap,
/// and work with it only via library methods.
pub type Batteries = battery_lib::Batteries;
/// Opaque struct representing battery.
///
/// End users should consider it as a some memory somewhere in the heap,
/// and work with it only via library methods.
pub type Battery = battery_lib::Battery;
pub use self::battery::*;
pub use self::errors::{battery_have_last_error, battery_last_error_length, battery_last_error_message};
pub use self::iterator::*;
pub use self::manager::*;
pub use self::state::*;
pub use self::technology::*;
|
use async_graphql::*;
#[tokio::test]
async fn test_flatten() {
#[derive(SimpleObject)]
struct A {
a: i32,
b: i32,
}
#[derive(SimpleObject)]
struct B {
#[graphql(flatten)]
a: A,
c: i32,
}
struct Query;
#[Object]
impl Query {
async fn obj(&self) -> B {
B {
a: A { a: 100, b: 200 },
c: 300,
}
}
}
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
let query = "{ __type(name: \"B\") { fields { name } } }";
assert_eq!(
schema.execute(query).await.data,
value!({
"__type": {
"fields": [
{"name": "a"},
{"name": "b"},
{"name": "c"}
]
}
})
);
let query = "{ obj { a b c } }";
assert_eq!(
schema.execute(query).await.data,
value!({
"obj": {
"a": 100,
"b": 200,
"c": 300,
}
})
);
}
#[tokio::test]
async fn recursive_fragment_definition() {
#[derive(SimpleObject)]
struct Hello {
world: String,
}
struct Query;
// this setup is actually completely irrelevant we just need to be able to
// execute a query
#[Object]
impl Query {
async fn obj(&self) -> Hello {
Hello {
world: "Hello World".into(),
}
}
}
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
let query = "fragment f on Query {...f} { __typename }";
assert!(schema.execute(query).await.into_result().is_err());
}
#[tokio::test]
async fn recursive_fragment_definition_nested() {
#[derive(SimpleObject)]
struct Hello {
world: String,
}
struct Query;
// this setup is actually completely irrelevant we just need to be able to
// execute a query
#[Object]
impl Query {
async fn obj(&self) -> Hello {
Hello {
world: "Hello World".into(),
}
}
}
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
let query = "fragment f on Query { a { ...f a { ...f } } } { __typename }";
assert!(schema.execute(query).await.into_result().is_err());
}
|
use self::ConfigError::*;
use super::*;
use std::error::Error;
#[derive(Debug)]
pub enum ConfigError {
/// The configuration file was not found.
NotFound,
/// There was an I/O error while reading the configuration file.
IoError,
/// The path at which the configuration file was found was invalid.
BadFilePath(PathBuf, &'static str),
/// An environment specified in `POEM_ENV` is invalid.
BadEnv(String),
/// An environment specified as a table `[environment]` is invalid.
BadEntry(String, PathBuf),
/// A config key was specified with a value of the wrong type.
BadType(String, &'static str, &'static str, Option<PathBuf>),
/// There was a TOML parsing error.
ParseError(String, PathBuf, String, Option<(usize, usize)>),
}
impl Error for ConfigError {
fn description(&self) -> &str {
match *self {
NotFound => "config file was not found",
IoError => "there was an I/O error while reading the config file",
BadFilePath(..) => "the config file path is invalid",
BadEnv(..) => "the environment specified in `ROCKET_ENV` is invalid",
BadEntry(..) => "an environment specified as `[environment]` is invalid",
BadType(..) => "a key was specified with a value of the wrong type",
ParseError(..) => "the config file contains invalid TOML",
}
}
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NotFound => write!(f, "config file was not found"),
IoError => write!(f, "I/O error while reading the config file"),
BadFilePath(ref p, _) => write!(f, "{:?} is not a valid config path", p),
BadEnv(ref e) => write!(f, "{:?} is not a valid `ROCKET_ENV` value", e),
BadEntry(ref e, _) => write!(f, "{:?} is not a valid `[environment]` entry", e),
BadType(ref n, e, a, _) => {
write!(f, "type mismatch for '{}'. expected {}, found {}", n, e, a)
}
ParseError(..) => write!(f, "the config file contains invalid TOML"),
}
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::super::qlib::linux_def::*;
use super::super::qlib::linux::time::*;
pub const MIN_TIME: Time = Time(core::i64::MIN);
pub const MAX_TIME: Time = Time(core::i64::MAX);
pub const ZERO_TIME: Time = Time(0);
#[derive(Debug)]
pub struct InterTimeSpec {
pub ATime: Time,
pub ATimeOmit: bool,
pub ATimeSetSystemTime: bool,
pub MTime: Time,
pub MTimeOmit: bool,
pub MTimeSetSystemTime: bool,
}
impl Default for InterTimeSpec {
fn default() -> Self {
return Self {
ATime: Default::default(),
ATimeOmit: false,
ATimeSetSystemTime: true,
MTime: Default::default(),
MTimeOmit: false,
MTimeSetSystemTime: true,
}
}
}
pub const MIN_DURATION: Duration = core::i64::MIN;
pub const MAX_DURATION: Duration = core::i64::MAX;
#[derive(Debug, Default, Copy, Clone)]
pub struct Time(pub i64); //how many ns
impl Time {
pub fn FromNs(ns: i64) -> Self {
return Self(ns)
}
pub fn FromSec(s: i64) -> Self {
return Self(s * 1000_000_000)
}
pub fn FromUnix(s: i64, ns: i64) -> Self {
if s > core::i64::MAX / 1000_000_000 {
return MAX_TIME.clone();
}
let t = s * 1000_000_000;
if t > core::i64::MAX - ns {
return MAX_TIME.clone();
}
return Time(t + ns)
}
pub fn FromStatxTimestamp(ts: &StatxTimestamp) -> Self {
return Self::FromUnix(ts.tv_sec, ts.tv_nsec as i64)
}
pub fn FromTimespec(ts: &Timespec) -> Self {
return Self::FromUnix(ts.tv_sec, ts.tv_nsec)
}
pub fn FromTimeval(tv: &Timeval) -> Self {
let s = tv.Sec;
let ns = tv.Usec * 1000;
return Self::FromUnix(s, ns)
}
pub fn Nanoseconds(&self) -> i64 {
return self.0;
}
pub fn Seconds(&self) -> i64 {
return self.0 / 1000_000_000;
}
pub fn Timespec(&self) -> Timespec {
return Timespec {
tv_sec: self.0 / 1000_000_000,
tv_nsec: self.0 % 1000_000_000,
}
}
pub fn Unix(&self) -> (i64, i64) {
return (self.0 / 1000_000_000, self.0 % 1000_000_000)
}
pub fn TimeT(&self) -> TimeT {
return NsecToTimeT(self.0)
}
pub fn Timeval(&self) -> Timeval {
return Timeval {
Sec: self.0 / 1000_000_000,
Usec: (self.0 % 1000_000_000) / 1000,
}
}
pub fn Add(&self, ns: i64) -> Self {
if self.0 > 0 && ns > core::i64::MAX - self.0 {
return MAX_TIME
}
if self.0 < 0 && ns < core::i64::MIN - self.0 {
return MIN_TIME
}
return Self(self.0 + ns)
}
pub fn AddTime(&self, u: Self) -> Self {
return self.Add(u.0)
}
pub fn Equal(&self, u: Self) -> bool {
return self.0 == u.0
}
pub fn Before(&self, u: Self) -> bool {
return self.0 < u.0
}
pub fn After(&self, u: Self) -> bool {
return self.0 > u.0
}
pub fn Sub(&self, u: Time) -> Duration {
let dur = (self.0 - u.0) * NANOSECOND;
if u.Add(dur).Equal(*self) {
return dur
} else if self.Before(u) {
return MIN_DURATION;
} else {
return MAX_DURATION;
}
}
pub fn IsMin(&self) -> bool {
return self.Equal(MIN_TIME)
}
pub fn IsZero(&self) -> bool {
return self.Equal(ZERO_TIME)
}
pub fn StatxTimestamp(&self) -> StatxTimestamp {
return StatxTimestamp::FromNs(self.Nanoseconds())
}
}
|
use super::widget::WidgetKind;
use crate::{
cpu::CPU,
debug::{util::FromHexString, widget::Widget},
disassembly::{Disassembler, InstructionWindow},
memory_map::{Mem, Mem16},
opcode::{Decoder, Opcode},
register::Reg16,
Src,
};
use crossterm::event::{KeyCode, KeyEvent};
use std::{borrow::Cow, io::Stdout};
use tui::{
backend::CrosstermBackend,
layout::Rect,
style::{Color, Style},
widgets::{Block, Borders, Paragraph, Text},
Frame,
};
enum Command {
Goto,
}
/// The widget responsible for the disassembly output.
pub struct Assembly {
instruction_window: Option<InstructionWindow>,
init: bool,
height: usize,
selected: bool,
pos: u16,
old_pc: u16,
sizes: [usize; 2],
command: Option<Command>,
}
impl Widget for Assembly {
fn refresh(&mut self, cpu: &CPU) {
let pc = Reg16::PC.read(cpu);
if self.old_pc != pc {
self.old_pc = pc;
self.pos = pc;
}
let (before, after) = Disassembler::new().surrounding_sizes(cpu, self.pos);
self.sizes[0] = before;
self.sizes[1] = after;
let instruction_window = InstructionWindow::build(
self.height / 2,
self.height - self.height / 2,
self.pos,
cpu,
);
self.instruction_window = Some(instruction_window);
}
fn draw(&mut self, f: &mut Frame<CrosstermBackend<Stdout>>, chunk: Rect, cpu: &CPU) {
self.height = chunk.height as usize;
if !self.init {
self.init = true;
self.refresh(cpu);
}
if let Some(instruction_window) = &self.instruction_window {
let items = instruction_window
.instructions
.iter()
.enumerate()
.map(|(i, (a, o))| {
let is_cursor = instruction_window.cursor == i;
let is_pc = instruction_window.pc.map(|a| a == i).unwrap_or(false);
let (cursor, bg, fg) = match (is_cursor, is_pc) {
(false, false) => (' ', None, Color::White),
(false, true) => ('>', None, Color::Red),
(true, false) => (' ', Some(Color::White), Color::Black),
(true, true) => ('>', Some(Color::White), Color::Red),
};
let style = if let Some(bg) = bg {
Style::default().fg(fg).bg(bg)
} else {
Style::default().fg(fg)
};
let instr = match o.try_display(cpu, Some(*a)) {
Ok(s) => s,
Err(s) => s,
};
Text::Styled(
Cow::Owned(format!("{} 0x{:04x} {}\n", cursor, *a, instr)),
style,
)
})
.collect::<Vec<_>>();
let paragraph = Paragraph::new(items.iter()).block(
Block::default()
.borders(Borders::ALL)
.title("Disassembly")
.title_style(self.title_style()),
);
f.render_widget(paragraph, chunk);
}
}
fn select(&mut self) {
self.selected = true;
}
fn deselect(&mut self) {
self.selected = false;
}
fn is_selected(&self) -> bool {
self.selected
}
fn handle_key(&mut self, key: KeyEvent, cpu: &mut CPU) -> Option<(WidgetKind, String)> {
match key.code {
KeyCode::Down => {
self.pos = self.pos.saturating_add(self.sizes[1] as u16);
None
}
KeyCode::Up => {
self.pos = self.pos.saturating_sub(self.sizes[0] as u16);
None
}
KeyCode::Char('g') => {
self.command = Some(Command::Goto);
Some((WidgetKind::Assembly, String::from("Go to instruction:")))
}
KeyCode::Char('j') => {
let opcode = Decoder::decode_with_context(cpu, self.pos);
if let Some(opcode) = opcode {
match opcode {
Opcode::CALL(_, _) => {
self.pos = Mem16(self.pos + 1).read(cpu);
}
Opcode::JP(_, _) => {
self.pos = Mem16(self.pos + 1).read(cpu);
}
Opcode::JPHL => {
self.pos = Reg16::HL.read(cpu);
}
Opcode::JR(_, _) => {
let offset = Mem(self.pos + 1).read(cpu) as i8;
self.pos = if offset < 0 {
self.pos.saturating_sub(((-offset) - 1) as u16)
} else {
self.pos.saturating_add((offset + 1) as u16)
};
println!("0x{:02x}", self.pos);
}
_ => {}
}
}
None
}
_ => None,
}
}
fn process_input(&mut self, input: String, cpu: &mut CPU) -> Result<(), Option<String>> {
if let Some(command) = &self.command {
match command {
Command::Goto => match u16::from_hex_string(input) {
Ok(addr) => {
if Disassembler::new().check_address(cpu, addr) {
self.pos = addr;
Ok(())
} else {
Err(Some(format!("Invalid instruction address: 0x{:04x}", addr)))
}
}
Err(_) => Err(None),
},
}
} else {
Ok(())
}
}
}
impl Assembly {
/// Returns a new Assembly widget.
pub fn new() -> Assembly {
Assembly {
instruction_window: None,
init: false,
height: 0,
selected: false,
pos: 0,
old_pc: 0,
sizes: [0, 0],
command: None,
}
}
}
|
use super::{BUTTON, LED};
use crate::app::App;
use drogue_device::{
actors::{button::Button, led::Led},
ActorContext, DeviceContext,
};
use embassy::executor::Spawner;
pub struct MyDevice {
app: ActorContext<'static, App>,
led1: ActorContext<'static, Led<LED>>,
led2: ActorContext<'static, Led<LED>>,
button: ActorContext<'static, Button<'static, BUTTON, App>>,
}
static DEVICE: DeviceContext<MyDevice> = DeviceContext::new();
impl MyDevice {
pub async fn start(button: BUTTON, led1: LED, led2: LED, spawner: Spawner) {
DEVICE.configure(MyDevice {
app: ActorContext::new(Default::default()),
button: ActorContext::new(Button::new(button)),
led1: ActorContext::new(Led::new(led1)),
led2: ActorContext::new(Led::new(led2)),
});
DEVICE
.mount(|device| async move {
let led1 = device.led1.mount((), spawner);
let led2 = device.led2.mount((), spawner);
let app = device.app.mount((led1, led2), spawner);
device.button.mount(app, spawner);
})
.await;
}
}
|
use super::join::Join;
use bit_set::BitSet;
use std::cell::RefCell;
use std::sync::{Arc, LockResult, Mutex, MutexGuard};
use super::resource::Fetch;
pub type Entity = usize;
#[derive(Derivative)]
#[derivative(Default(new = "true"))]
pub struct EntityStorage {
next_id: Arc<Mutex<RefCell<usize>>>,
alive: Arc<Mutex<RefCell<BitSet>>>,
limbo: Arc<Mutex<RefCell<Vec<usize>>>>,
}
pub type Entities<'a> = Fetch<'a, EntityStorage>;
const LOCK_POISOINED: &str = "Lock is poisoned!";
impl EntityStorage {
pub fn create(&self) -> Entity {
let id = if !self.is_limbo_empty() {
// self.limbo.remove(0);
self.unlock_mut(self.limbo.lock(), |limbo: &mut Vec<usize>| limbo.remove(0))
} else {
self.next_id()
};
self.unlock_mut(self.alive.lock(), |alive: &mut BitSet| alive.insert(id));
id as Entity
}
pub fn is_alive(&self, entity: Entity) -> bool {
self.unlock(self.alive.lock(), |alive: &BitSet| alive.contains(entity))
}
pub fn destroy(&self, entity: Entity) {
assert!(self.is_alive(entity), "Can't destroy dead entity!");
self.unlock_mut(self.limbo.lock(), |limbo: &mut Vec<usize>| {
limbo.push(entity)
});
self.unlock_mut(self.alive.lock(), |alive: &mut BitSet| alive.remove(entity));
}
fn is_limbo_empty(&self) -> bool {
self.unlock(self.limbo.lock(), |limbo: &Vec<usize>| limbo.is_empty())
}
fn next_id(&self) -> usize {
self.unlock_mut(self.next_id.lock(), |current: &mut usize| {
let id = *current;
*current = id + 1;
id
})
}
fn unlock<T, R, F>(&self, lock: LockResult<MutexGuard<RefCell<T>>>, cb: F) -> R
where
F: Fn(&T) -> R,
{
let value = lock.expect(LOCK_POISOINED);
let actual_value = value.borrow();
cb(&actual_value)
}
fn unlock_mut<T, R, F>(&self, lock: LockResult<MutexGuard<RefCell<T>>>, cb: F) -> R
where
F: Fn(&mut T) -> R,
{
let value = lock.expect(LOCK_POISOINED);
let mut actual_value = value.borrow_mut();
cb(&mut actual_value)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_entity() {
let mut entity_storage = EntityStorage::new();
let entity = entity_storage.create();
assert!(entity_storage.is_alive(entity));
}
#[test]
fn destroy_entity() {
let mut entity_storage = EntityStorage::new();
let entity = entity_storage.create();
entity_storage.destroy(entity);
assert!(!entity_storage.is_alive(entity));
}
#[test]
#[should_panic]
fn destroy_entity_dead() {
let mut entity_storage = EntityStorage::new();
let entity = entity_storage.create();
entity_storage.destroy(entity);
// some time later
entity_storage.destroy(entity);
}
#[test]
fn re_use_dead_entity() {
let mut entity_storage = EntityStorage::new();
let entity = entity_storage.create();
entity_storage.destroy(entity);
let new_entity = entity_storage.create();
assert_eq!(entity, new_entity);
}
#[test]
fn unique_ids() {
let mut entity_storage = EntityStorage::new();
let entity1 = entity_storage.create();
let entity2 = entity_storage.create();
assert_ne!(entity1, entity2);
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use alloc::sync::Arc;
use spin::Mutex;
use alloc::string::String;
use alloc::string::ToString;
use alloc::collections::btree_map::BTreeMap;
use super::super::super::qlib::auth::id::*;
use super::super::super::qlib::common::*;
use super::super::super::qlib::linux_def::*;
use super::super::super::task::*;
use super::super::filesystems::*;
use super::super::host::fs::*;
use super::super::inode::*;
use super::super::mount::*;
use super::tmpfs_dir::*;
// Set initial permissions for the root directory.
pub const MODE_KEY :&str = "mode";
// UID for the root directory.
pub const ROOT_UIDKEY :&str = "uid";
// GID for the root directory.
pub const ROOT_GIDKEY :&str = "gid";
// Permissions that exceed modeMask will be rejected.
pub const MODE_MASK :u16 = 0o1777;
// Default permissions are read/write/execute.
pub const DEFAULT_MODE :u16 = 0o777;
pub struct TmpfsFileSystem {}
impl Filesystem for TmpfsFileSystem {
fn Name(&self) -> String {
return "tmpfs".to_string();
}
fn Flags(&self) -> FilesystemFlags {
return 0;
}
fn Mount(&mut self, task: &Task, _device: &str, flags: &MountSourceFlags, data: &str) -> Result<Inode> {
info!("tmfps file system mount ...");
// Parse generic comma-separated key=value options, this file system expects them.
let mut options = WhitelistFileSystem::GenericMountSourceOptions(data);
// Parse the root directory permissions.
let mut perms = FilePermissions::FromMode(FileMode(DEFAULT_MODE));
match options.remove(MODE_KEY) {
None => (),
Some(m) => {
let i = match m.parse::<u16>() {
Ok(v) => v,
Err(e) => {
info!("mode value not parsable 'mode={}': {:?}", m, e);
return Err(Error::SysError(SysErr::EINVAL))
}
};
if i & !MODE_MASK != 0 {
info!("invalid mode {}: must be less than {}", m, MODE_MASK);
return Err(Error::SysError(SysErr::EINVAL))
}
perms = FilePermissions::FromMode(FileMode(i as u16))
}
}
let creds = task.Creds();
let userns = creds.lock().UserNamespace.clone();
let mut owner = task.FileOwner();
match options.remove(ROOT_UIDKEY) {
None => (),
Some(uidstr) => {
let uid = match uidstr.parse::<u32>() {
Ok(v) => v,
Err(e) => {
info!("uid value not parsable 'uid={}': {:?}", uidstr, e);
return Err(Error::SysError(SysErr::EINVAL))
}
};
owner.UID = userns.MapToKUID(UID(uid));
}
}
match options.remove(ROOT_GIDKEY) {
None => (),
Some(gidstr) => {
let gid = match gidstr.parse::<u32>() {
Ok(v) => v,
Err(e) => {
info!("gid value not parsable 'gid={}': {:?}", gidstr, e);
return Err(Error::SysError(SysErr::EINVAL))
}
};
owner.GID = userns.MapToKGID(GID(gid));
}
}
// Fail if the caller passed us more options than we can parse. They may be
// expecting us to set something we can't set.
if options.len() > 0 {
info!("unsupported mount options: {:?}", options);
return Err(Error::SysError(SysErr::EINVAL))
}
let msrc = MountSource::NewCachingMountSource(self, flags);
let inode = NewTmpfsDir(task, BTreeMap::new(), &owner, &perms, Arc::new(Mutex::new(msrc)));
return Ok(inode)
}
fn AllowUserMount(&self) -> bool {
return true;
}
fn AllowUserList(&self) -> bool {
return true;
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::mm::*;
// Dumpability describes if and how core dumps should be created.
pub type Dumpability = i32;
// NotDumpable indicates that core dumps should never be created.
pub const NOT_DUMPABLE : Dumpability = 0;
// UserDumpable indicates that core dumps should be created, owned by
// the current user.
pub const USER_DUMPABLE : Dumpability = 1;
// RootDumpable indicates that core dumps should be created, owned by
// root.
pub const ROOT_DUMPABLE : Dumpability = 2;
impl MemoryManager {
pub fn Dumpability(&self) -> Dumpability {
return self.metadata.lock().dumpability;
}
pub fn SetDumpability(&self, d: Dumpability) {
self.metadata.lock().dumpability = d;
}
} |
use advent::helpers;
use anyhow::{Context, Result};
use derive_more::Display;
use itertools::Itertools;
type LiteralType = u64;
#[derive(Debug, Display)]
enum BinaryOpKind {
#[display(fmt = "+")]
Add,
#[display(fmt = "*")]
Mul,
}
#[derive(Debug)]
enum MathExpr {
Literal(LiteralType),
BinaryOp(Box<MathExpr>, Box<MathExpr>, BinaryOpKind),
}
enum PrecedenceKind {
Equal,
GreaterAdd,
}
fn is_paren(c: &char) -> bool {
*c == '(' || *c == ')'
}
impl BinaryOpKind {
fn get_precedence(&self, precedence_kind: &PrecedenceKind) -> u8 {
match precedence_kind {
PrecedenceKind::Equal => 1,
PrecedenceKind::GreaterAdd => match self {
BinaryOpKind::Add => 2,
BinaryOpKind::Mul => 1,
},
}
}
}
fn char_to_binary_op_kind(c: &char) -> BinaryOpKind {
match c {
'+' => BinaryOpKind::Add,
'*' => BinaryOpKind::Mul,
_ => unreachable!(),
}
}
fn make_binary_op(c: &char, operands: &mut Vec<MathExpr>) {
let arg_1 = Box::new(operands.pop().unwrap());
let arg_2 = Box::new(operands.pop().unwrap());
let op_kind = char_to_binary_op_kind(c);
operands.push(MathExpr::BinaryOp(arg_1, arg_2, op_kind));
}
/// Returns a token iterator for given string, essentially splitting at whitespace and parenthesis,
/// while keeping the parenthesis.
/// Takes '1 + (2 * 3)'
/// Returns ['1', '+', '(', '2', '*', '3', ')']
fn make_tokenizer(s: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
s.split_whitespace()
.map(|token| {
// poor's man split_including_delim() that keeps the paranthesis delimiters as values.
let mut last_paren_idx = 0;
let mut parens_and_tokens = token
.match_indices(|c: char| is_paren(&c))
.map(|(idx, matched)| {
let res = if last_paren_idx != idx {
vec![&token[last_paren_idx..idx], matched]
} else {
vec![matched]
};
last_paren_idx = idx + matched.len();
res
})
.flatten()
.collect_vec();
if last_paren_idx < token.len() {
parens_and_tokens.push(&token[last_paren_idx..])
}
parens_and_tokens
})
.flatten()
}
fn parse_string_to_math_expr(s: &str, precedence_kind: &PrecedenceKind) -> MathExpr {
let mut operands = Vec::<MathExpr>::new();
let mut ops = Vec::<char>::new();
let tokenizer = make_tokenizer(s);
tokenizer.for_each(|token| {
// Implementation of shunting-yard.
match token.chars().next().unwrap() {
lit @ '0'..='9' => {
let lit = MathExpr::Literal(lit.to_digit(10).unwrap() as LiteralType);
operands.push(lit);
}
open_paren @ '(' => {
ops.push(open_paren);
}
')' => {
while !ops.is_empty() {
let op_char = ops.pop().unwrap();
match op_char {
'(' => break,
_ => make_binary_op(&op_char, &mut operands),
}
}
}
op_kind_char @ '+' | op_kind_char @ '*' => {
while !ops.is_empty() {
let top_stack_op_char = ops.last().unwrap();
match top_stack_op_char {
'(' => break,
_ => {
let stack_top_op_precedence_is_higher =
char_to_binary_op_kind(top_stack_op_char)
.get_precedence(precedence_kind)
>= char_to_binary_op_kind(&op_kind_char)
.get_precedence(precedence_kind);
if stack_top_op_precedence_is_higher {
make_binary_op(top_stack_op_char, &mut operands);
ops.pop();
} else {
break;
}
}
}
}
ops.push(op_kind_char);
}
_ => unreachable!(),
};
});
// Assemble the AST from the remaining operators.
while let Some(op_char) = ops.pop() {
make_binary_op(&op_char, &mut operands);
}
operands.pop().unwrap()
}
fn reduce_math_expr(expr: &MathExpr) -> LiteralType {
match expr {
MathExpr::Literal(lit) => *lit,
MathExpr::BinaryOp(arg_1, arg_2, op_kind) => {
let arg_1_reduced = reduce_math_expr(arg_1.as_ref());
let arg_2_reduced = reduce_math_expr(arg_2.as_ref());
match op_kind {
BinaryOpKind::Add => arg_1_reduced + arg_2_reduced,
BinaryOpKind::Mul => arg_1_reduced * arg_2_reduced,
}
}
}
}
impl std::fmt::Display for MathExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MathExpr::Literal(lit) => {
write!(f, "{}", lit)?;
}
MathExpr::BinaryOp(arg_1, arg_2, op_kind) => {
write!(f, "({} {} {})", arg_1.as_ref(), op_kind, arg_2.as_ref())?;
}
}
Ok(())
}
}
fn eval_math_expr(s: &str, precedence_kind: &PrecedenceKind) -> i64 {
let expr = parse_string_to_math_expr(s, precedence_kind);
println!("{} = {}", expr, reduce_math_expr(&expr));
reduce_math_expr(&expr) as i64
}
fn eval_homework_as_sum_of_expr(s: &str, precedence_kind: &PrecedenceKind) -> i64 {
s.lines().map(|l| eval_math_expr(l, precedence_kind)).sum()
}
fn eval_homework_as_sum_of_expr_equal_precedence(s: &str) -> i64 {
eval_homework_as_sum_of_expr(s, &PrecedenceKind::Equal)
}
fn eval_homework_as_sum_of_expr_greater_add_precedence(s: &str) -> i64 {
eval_homework_as_sum_of_expr(s, &PrecedenceKind::GreaterAdd)
}
fn solve_p1() -> Result<()> {
let input = helpers::get_data_from_file_res("d18").context("Coudn't read file contents.")?;
let result = eval_homework_as_sum_of_expr_equal_precedence(&input);
println!(
"The sum of the expression using regular precedence is: {}",
result
);
Ok(())
}
fn solve_p2() -> Result<()> {
let input = helpers::get_data_from_file_res("d18").context("Coudn't read file contents.")?;
let result = eval_homework_as_sum_of_expr_greater_add_precedence(&input);
println!(
"The sum of the expression using GreaterAdd precedence is: {}",
result
);
Ok(())
}
fn main() -> Result<()> {
solve_p1().ok();
solve_p2().ok();
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_p1() {
macro_rules! test {
($expr: literal, $solution: expr) => {
let input = $expr;
assert_eq!(
eval_homework_as_sum_of_expr_equal_precedence(input),
$solution
)
};
}
test!("1 + 2 * 3 + 4 * 5 + 6", 71);
test!("1 + (2 * 3) + (4 * (5 + 6))", 51);
test!("2 * 3 + (4 * 5)", 26);
test!("5 + (8 * 3 + 9 + 3 * 4 * 3)", 437);
test!("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))", 12240);
test!("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2", 13632);
}
#[test]
fn test_p2() {
macro_rules! test {
($expr: literal, $solution: expr) => {
let input = $expr;
assert_eq!(
eval_homework_as_sum_of_expr_greater_add_precedence(input),
$solution
)
};
}
test!("1 + 2 * 3 + 4 * 5 + 6", 231);
test!("1 + (2 * 3) + (4 * (5 + 6))", 51);
test!("2 * 3 + (4 * 5)", 46);
test!("5 + (8 * 3 + 9 + 3 * 4 * 3)", 1445);
test!("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))", 669060);
test!("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2", 23340);
}
}
|
use super::cso::{CSO, Cell, MAX_PURITY, SEWAGE_PURITY};
use super::random::Random;
use super::point::Point;
struct CellFactory {
pub point: Point,
pub cell: Cell,
pub interval: u8,
pub count: u8
}
struct CellDrain {
pub point: Point,
pub interval: u8,
}
pub struct Level {
factories: Vec<CellFactory>,
drains: Vec<CellDrain>,
frame_number: u8,
pub enable_water_factories: bool,
pub override_water_factory_count: Option<u8>,
pub sim: CSO,
}
pub const BMP_STATIC_COLOR: bmp::Pixel = bmp::consts::WHITE;
pub const BMP_EMPTY_COLOR: bmp::Pixel = bmp::consts::BLACK;
pub const BMP_SEWAGE_FACTORY_COLOR: bmp::Pixel = bmp::Pixel { r: 143, g: 86, b: 59 };
pub const BMP_WATER_FACTORY_COLOR: bmp::Pixel = bmp::Pixel { r: 95, g: 205, b: 228 };
pub const BMP_DRAIN_COLOR: bmp::Pixel = bmp::Pixel { r: 153, g: 229, b: 80 };
pub const BMP_WATER_COLOR: bmp::Pixel = bmp::Pixel { r: 91, g: 110, b: 225 };
fn clamped_u8(value: i32) -> u8 {
if value < u8::MIN as i32 {
u8::MIN
} else if value > u8::MAX as i32 {
u8::MAX
} else {
value as u8
}
}
fn lerp_u8(a: u8, b: u8, amount: f32) -> u8 {
let max_delta: i32 = b as i32 - a as i32;
let value = (a as f32 + max_delta as f32 * amount) as i32;
clamped_u8(value)
}
fn lerp_color(a: bmp::Pixel, b: bmp::Pixel, amount: f32) -> bmp::Pixel {
bmp::Pixel {
r: lerp_u8(a.r, b.r, amount),
g: lerp_u8(a.g, b.g, amount),
b: lerp_u8(a.b, b.b, amount),
}
}
impl Level {
pub fn from_bmp(image: bmp::Image) -> Level {
let mut sim = CSO::new(image.get_width(), image.get_height(), Random { seed: 5 });
let mut factories: Vec<CellFactory> = vec![];
let mut drains: Vec<CellDrain> = vec![];
for (x, y) in image.coordinates() {
let value = image.get_pixel(x, y);
let point = Point::at(x, y);
match value {
BMP_STATIC_COLOR => {
sim.set(&point, Cell::Static);
}
BMP_WATER_FACTORY_COLOR => {
factories.push(CellFactory {
point,
cell: Cell::Water(MAX_PURITY),
interval: 8,
count: 2
});
}
BMP_SEWAGE_FACTORY_COLOR => {
factories.push(CellFactory {
point,
cell: Cell::Water(SEWAGE_PURITY),
interval: 8,
count: 1
});
}
BMP_DRAIN_COLOR => {
drains.push(CellDrain {
point,
interval: 12
});
}
BMP_WATER_COLOR => {
sim.set(&point, Cell::Water(MAX_PURITY));
}
_ => {}
}
}
Level { sim, factories, drains, enable_water_factories: false, frame_number: 0, override_water_factory_count: None }
}
pub fn get_color(&self, point: &Point) -> bmp::Pixel {
match self.sim.get(&point) {
Cell::Empty => { BMP_EMPTY_COLOR }
Cell::Static => { BMP_STATIC_COLOR }
Cell::Sand => { BMP_SEWAGE_FACTORY_COLOR }
Cell::Water(purity) => {
lerp_color(BMP_SEWAGE_FACTORY_COLOR, BMP_WATER_COLOR, purity as f32 / MAX_PURITY as f32)
}
}
}
pub fn tick(&mut self) {
self.frame_number = (self.frame_number + 1) % 255;
let i = self.frame_number;
for factory in self.factories.iter() {
let mut count = factory.count;
if let Cell::Water(MAX_PURITY) = factory.cell {
if !self.enable_water_factories {
continue;
}
count = self.override_water_factory_count.unwrap_or(count);
}
if i % factory.interval < count && self.sim.is_empty_at(&factory.point) {
self.sim.set(&factory.point, factory.cell);
}
}
for drain in self.drains.iter() {
if i % drain.interval == 0 {
self.sim.set(&drain.point, Cell::Empty);
}
}
self.sim.tick();
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::any::Any;
use std::sync::Arc;
use common_catalog::table_args::TableArgs;
use common_config::InnerConfig;
use common_exception::ErrorCode;
use common_exception::Result;
use common_meta_app::schema::CountTablesReply;
use common_meta_app::schema::CountTablesReq;
use common_meta_app::schema::CreateDatabaseReply;
use common_meta_app::schema::CreateDatabaseReq;
use common_meta_app::schema::CreateTableReq;
use common_meta_app::schema::DropDatabaseReq;
use common_meta_app::schema::DropTableByIdReq;
use common_meta_app::schema::DropTableReply;
use common_meta_app::schema::GetTableCopiedFileReply;
use common_meta_app::schema::GetTableCopiedFileReq;
use common_meta_app::schema::RenameDatabaseReply;
use common_meta_app::schema::RenameDatabaseReq;
use common_meta_app::schema::RenameTableReply;
use common_meta_app::schema::RenameTableReq;
use common_meta_app::schema::TableIdent;
use common_meta_app::schema::TableInfo;
use common_meta_app::schema::TableMeta;
use common_meta_app::schema::TruncateTableReply;
use common_meta_app::schema::TruncateTableReq;
use common_meta_app::schema::UndropDatabaseReply;
use common_meta_app::schema::UndropDatabaseReq;
use common_meta_app::schema::UndropTableReply;
use common_meta_app::schema::UndropTableReq;
use common_meta_app::schema::UpdateTableMetaReply;
use common_meta_app::schema::UpdateTableMetaReq;
use common_meta_app::schema::UpsertTableOptionReply;
use common_meta_app::schema::UpsertTableOptionReq;
use common_meta_types::MetaId;
use tracing::info;
use crate::catalogs::catalog::Catalog;
use crate::catalogs::default::ImmutableCatalog;
use crate::catalogs::default::MutableCatalog;
use crate::databases::Database;
use crate::storages::StorageDescription;
use crate::storages::Table;
use crate::table_functions::TableFunction;
use crate::table_functions::TableFunctionFactory;
/// Combine two catalogs together
/// - read/search like operations are always performed at
/// upper layer first, and bottom layer later(if necessary)
/// - metadata are written to the bottom layer
#[derive(Clone)]
pub struct DatabaseCatalog {
/// the upper layer, read only
immutable_catalog: Arc<dyn Catalog>,
/// bottom layer, writing goes here
mutable_catalog: Arc<dyn Catalog>,
/// table function engine factories
table_function_factory: Arc<TableFunctionFactory>,
}
impl DatabaseCatalog {
pub fn create(
immutable_catalog: Arc<dyn Catalog>,
mutable_catalog: Arc<dyn Catalog>,
table_function_factory: Arc<TableFunctionFactory>,
) -> Self {
Self {
immutable_catalog,
mutable_catalog,
table_function_factory,
}
}
pub async fn try_create_with_config(conf: InnerConfig) -> Result<DatabaseCatalog> {
let immutable_catalog = ImmutableCatalog::try_create_with_config(&conf).await?;
let mutable_catalog = MutableCatalog::try_create_with_config(conf).await?;
let table_function_factory = TableFunctionFactory::create();
let res = DatabaseCatalog::create(
Arc::new(immutable_catalog),
Arc::new(mutable_catalog),
Arc::new(table_function_factory),
);
Ok(res)
}
}
#[async_trait::async_trait]
impl Catalog for DatabaseCatalog {
fn as_any(&self) -> &dyn Any {
self
}
async fn get_database(&self, tenant: &str, db_name: &str) -> Result<Arc<dyn Database>> {
if tenant.is_empty() {
return Err(ErrorCode::TenantIsEmpty(
"Tenant can not empty(while get database)",
));
}
let r = self.immutable_catalog.get_database(tenant, db_name).await;
match r {
Err(e) => {
if e.code() == ErrorCode::UNKNOWN_DATABASE {
self.mutable_catalog.get_database(tenant, db_name).await
} else {
Err(e)
}
}
Ok(db) => Ok(db),
}
}
async fn list_databases(&self, tenant: &str) -> Result<Vec<Arc<dyn Database>>> {
if tenant.is_empty() {
return Err(ErrorCode::TenantIsEmpty(
"Tenant can not empty(while list databases)",
));
}
let mut dbs = self.immutable_catalog.list_databases(tenant).await?;
let mut other = self.mutable_catalog.list_databases(tenant).await?;
dbs.append(&mut other);
Ok(dbs)
}
async fn create_database(&self, req: CreateDatabaseReq) -> Result<CreateDatabaseReply> {
if req.name_ident.tenant.is_empty() {
return Err(ErrorCode::TenantIsEmpty(
"Tenant can not empty(while create database)",
));
}
info!("Create database from req:{:?}", req);
if self
.immutable_catalog
.exists_database(&req.name_ident.tenant, &req.name_ident.db_name)
.await?
{
return Err(ErrorCode::DatabaseAlreadyExists(format!(
"{} database exists",
req.name_ident.db_name
)));
}
// create db in BOTTOM layer only
self.mutable_catalog.create_database(req).await
}
async fn drop_database(&self, req: DropDatabaseReq) -> Result<()> {
if req.name_ident.tenant.is_empty() {
return Err(ErrorCode::TenantIsEmpty(
"Tenant can not empty(while drop database)",
));
}
info!("Drop database from req:{:?}", req);
// drop db in BOTTOM layer only
if self
.immutable_catalog
.exists_database(&req.name_ident.tenant, &req.name_ident.db_name)
.await?
{
return self.immutable_catalog.drop_database(req).await;
}
self.mutable_catalog.drop_database(req).await
}
async fn rename_database(&self, req: RenameDatabaseReq) -> Result<RenameDatabaseReply> {
if req.name_ident.tenant.is_empty() {
return Err(ErrorCode::TenantIsEmpty(
"Tenant can not empty(while rename database)",
));
}
info!("Rename table from req:{:?}", req);
if self
.immutable_catalog
.exists_database(&req.name_ident.tenant, &req.name_ident.db_name)
.await?
|| self
.immutable_catalog
.exists_database(&req.name_ident.tenant, &req.new_db_name)
.await?
{
return self.immutable_catalog.rename_database(req).await;
}
self.mutable_catalog.rename_database(req).await
}
fn get_table_by_info(&self, table_info: &TableInfo) -> Result<Arc<dyn Table>> {
let res = self.immutable_catalog.get_table_by_info(table_info);
match res {
Ok(t) => Ok(t),
Err(e) => {
if e.code() == ErrorCode::UNKNOWN_TABLE {
self.mutable_catalog.get_table_by_info(table_info)
} else {
Err(e)
}
}
}
}
async fn get_table_meta_by_id(&self, table_id: MetaId) -> Result<(TableIdent, Arc<TableMeta>)> {
let res = self.immutable_catalog.get_table_meta_by_id(table_id).await;
if let Ok(x) = res {
Ok(x)
} else {
self.mutable_catalog.get_table_meta_by_id(table_id).await
}
}
async fn get_table(
&self,
tenant: &str,
db_name: &str,
table_name: &str,
) -> Result<Arc<dyn Table>> {
if tenant.is_empty() {
return Err(ErrorCode::TenantIsEmpty(
"Tenant can not empty(while get table)",
));
}
let res = self
.immutable_catalog
.get_table(tenant, db_name, table_name)
.await;
match res {
Ok(v) => Ok(v),
Err(e) => {
if e.code() == ErrorCode::UNKNOWN_DATABASE {
self.mutable_catalog
.get_table(tenant, db_name, table_name)
.await
} else {
Err(e)
}
}
}
}
async fn list_tables(&self, tenant: &str, db_name: &str) -> Result<Vec<Arc<dyn Table>>> {
if tenant.is_empty() {
return Err(ErrorCode::TenantIsEmpty(
"Tenant can not empty(while list tables)",
));
}
let r = self.immutable_catalog.list_tables(tenant, db_name).await;
match r {
Ok(x) => Ok(x),
Err(e) => {
if e.code() == ErrorCode::UNKNOWN_DATABASE {
self.mutable_catalog.list_tables(tenant, db_name).await
} else {
Err(e)
}
}
}
}
async fn list_tables_history(
&self,
tenant: &str,
db_name: &str,
) -> Result<Vec<Arc<dyn Table>>> {
if tenant.is_empty() {
return Err(ErrorCode::TenantIsEmpty(
"Tenant can not empty(while list tables)",
));
}
let r = self
.immutable_catalog
.list_tables_history(tenant, db_name)
.await;
match r {
Ok(x) => Ok(x),
Err(e) => {
if e.code() == ErrorCode::UNKNOWN_DATABASE {
self.mutable_catalog
.list_tables_history(tenant, db_name)
.await
} else {
Err(e)
}
}
}
}
async fn create_table(&self, req: CreateTableReq) -> Result<()> {
if req.tenant().is_empty() {
return Err(ErrorCode::TenantIsEmpty(
"Tenant can not empty(while create table)",
));
}
info!("Create table from req:{:?}", req);
if self
.immutable_catalog
.exists_database(req.tenant(), req.db_name())
.await?
{
return self.immutable_catalog.create_table(req).await;
}
self.mutable_catalog.create_table(req).await
}
async fn drop_table_by_id(&self, req: DropTableByIdReq) -> Result<DropTableReply> {
let res = self.mutable_catalog.drop_table_by_id(req).await?;
Ok(res)
}
async fn undrop_table(&self, req: UndropTableReq) -> Result<UndropTableReply> {
if req.tenant().is_empty() {
return Err(ErrorCode::TenantIsEmpty(
"Tenant can not empty(while undrop table)",
));
}
info!("Undrop table from req:{:?}", req);
if self
.immutable_catalog
.exists_database(req.tenant(), req.db_name())
.await?
{
return self.immutable_catalog.undrop_table(req).await;
}
self.mutable_catalog.undrop_table(req).await
}
async fn undrop_database(&self, req: UndropDatabaseReq) -> Result<UndropDatabaseReply> {
if req.tenant().is_empty() {
return Err(ErrorCode::TenantIsEmpty(
"Tenant can not empty(while undrop database)",
));
}
info!("Undrop database from req:{:?}", req);
if self
.immutable_catalog
.exists_database(req.tenant(), req.db_name())
.await?
{
return self.immutable_catalog.undrop_database(req).await;
}
self.mutable_catalog.undrop_database(req).await
}
async fn rename_table(&self, req: RenameTableReq) -> Result<RenameTableReply> {
if req.tenant().is_empty() {
return Err(ErrorCode::TenantIsEmpty(
"Tenant can not empty(while rename table)",
));
}
info!("Rename table from req:{:?}", req);
if self
.immutable_catalog
.exists_database(req.tenant(), req.db_name())
.await?
|| self
.immutable_catalog
.exists_database(req.tenant(), &req.new_db_name)
.await?
{
return Err(ErrorCode::Unimplemented(
"Cannot rename table from(to) system databases",
));
}
self.mutable_catalog.rename_table(req).await
}
async fn count_tables(&self, req: CountTablesReq) -> Result<CountTablesReply> {
if req.tenant.is_empty() {
return Err(ErrorCode::TenantIsEmpty(
"Tenant can not empty(while count tables)",
));
}
let res = self.mutable_catalog.count_tables(req).await?;
Ok(res)
}
async fn get_table_copied_file_info(
&self,
tenant: &str,
db_name: &str,
req: GetTableCopiedFileReq,
) -> Result<GetTableCopiedFileReply> {
self.mutable_catalog
.get_table_copied_file_info(tenant, db_name, req)
.await
}
async fn truncate_table(
&self,
table_info: &TableInfo,
req: TruncateTableReq,
) -> Result<TruncateTableReply> {
self.mutable_catalog.truncate_table(table_info, req).await
}
async fn upsert_table_option(
&self,
tenant: &str,
db_name: &str,
req: UpsertTableOptionReq,
) -> Result<UpsertTableOptionReply> {
self.mutable_catalog
.upsert_table_option(tenant, db_name, req)
.await
}
async fn update_table_meta(
&self,
table_info: &TableInfo,
req: UpdateTableMetaReq,
) -> Result<UpdateTableMetaReply> {
self.mutable_catalog
.update_table_meta(table_info, req)
.await
}
fn get_table_function(
&self,
func_name: &str,
tbl_args: TableArgs,
) -> Result<Arc<dyn TableFunction>> {
self.table_function_factory.get(func_name, tbl_args)
}
fn list_table_functions(&self) -> Vec<String> {
self.table_function_factory.list()
}
fn get_table_engines(&self) -> Vec<StorageDescription> {
// only return mutable_catalog storage table engines
self.mutable_catalog.get_table_engines()
}
}
|
use crate::audio::{GenericMusicStream, MusicStream};
use std::iter::Peekable;
// TODO maybe use higher quality resampling algorithm?
/// Resample a MusicStream using linear interpolation
pub struct Resample<I: Iterator<Item = f32> + Send> {
/// The iterator that yields interleaved audio samples
/// (e.g. an iterator for an audio stream with 3 channels would
/// yield samples for channel 1, then 2, then 3, then 1, then 2, ...
samples: Peekable<I>,
channel_count: usize,
from_sample_rate: u32,
to_sample_rate: u32,
/// What channel the next sample from the iterator corresponds with.
channel_offset: usize,
/// Some number between 0 and `to_sample_rate`.
///
/// This is divided by `to_sample_rate` to calculate the coefficient for
/// linear interpolation.
sampling_offset: u32,
/// Holds the previous audio frame (1 sample from each channel).
previous_values: Vec<f32>,
/// Holds the next audio frame (1 sample from each channel).
next_values: Vec<f32>,
}
impl<I: Iterator<Item = f32> + Send> Iterator for Resample<I> {
type Item = f32;
fn next(&mut self) -> Option<f32> {
let return_value = if self.previous_values.len() < self.channel_count && self.next_values.len() < self.channel_count {
let next_sample = match self.samples.next() {
Some(s) => s,
None => return None,
};
let next_next_sample = match self.samples.peek() {
Some(s) => *s,
None => return None,
};
self.previous_values.push(next_sample);
self.next_values.push(next_next_sample);
Some(next_sample)
} else {
if self.channel_offset == 0 {
self.sampling_offset += self.from_sample_rate;
while self.sampling_offset >= self.to_sample_rate {
self.sampling_offset -= self.to_sample_rate;
for n in 0..self.channel_count {
self.previous_values[n] = self.next_values[n];
let next_sample = match self.samples.next() {
Some(s) => s,
None => return None,
};
self.next_values[n] = next_sample;
}
}
}
let prev_sample = self.previous_values[self.channel_offset];
let next_sample = self.next_values[self.channel_offset];
Some(prev_sample
+ (next_sample - prev_sample)
* self.sampling_offset as f32 / self.to_sample_rate as f32)
};
self.channel_offset += 1;
if self.channel_offset >= self.channel_count {
self.channel_offset = 0;
}
return_value
}
}
pub(super) fn from_music_stream<I>(
stream: GenericMusicStream<I, f32>,
target_sample_rate: u32,
) -> MusicStream
where
I: Iterator<Item = f32> + Send + 'static
{
let le_samples = Resample {
samples: stream.samples.peekable(),
channel_count: stream.channel_count as usize,
from_sample_rate: stream.sample_rate,
to_sample_rate: target_sample_rate,
channel_offset: 0,
sampling_offset: 0,
previous_values: Vec::new(),
next_values: Vec::new(),
};
MusicStream {
samples: Box::new(le_samples),
}
}
|
use std::sync::Arc;
use proptest::prop_oneof;
use proptest::strategy::{BoxedStrategy, Just, Strategy};
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use crate::test::strategy::term::{is_binary, is_byte};
use crate::test::strategy::{DEPTH, MAX_LEN};
pub fn non_recursive_element(arc_process: Arc<Process>) -> BoxedStrategy<Term> {
prop_oneof![is_byte(arc_process.clone()), is_binary(arc_process.clone())].boxed()
}
pub fn recursive_element(arc_process: Arc<Process>) -> BoxedStrategy<Term> {
non_recursive_element(arc_process.clone())
.prop_recursive(
DEPTH,
(MAX_LEN * (DEPTH as usize + 1)) as u32,
MAX_LEN as u32,
move |element_strategy| {
let elements_strategy = proptest::collection::vec(element_strategy, 0..=MAX_LEN);
(
Just(arc_process.clone()),
elements_strategy,
tail(arc_process.clone()),
)
.prop_map(|(arc_process, elements, tail)| {
arc_process.improper_list_from_slice(&elements, tail)
})
.boxed()
},
)
.boxed()
}
pub fn recursive_elements(arc_process: Arc<Process>) -> BoxedStrategy<Vec<Term>> {
proptest::collection::vec(recursive_element(arc_process), 0..=MAX_LEN).boxed()
}
pub fn root(arc_process: Arc<Process>) -> BoxedStrategy<Term> {
(
Just(arc_process.clone()),
recursive_elements(arc_process.clone()),
tail(arc_process),
)
.prop_map(|(arc_process, elements, tail)| {
arc_process.improper_list_from_slice(&elements, tail)
})
.boxed()
}
pub fn tail(arc_process: Arc<Process>) -> BoxedStrategy<Term> {
prop_oneof![is_binary(arc_process.clone()), Just(Term::NIL)].boxed()
}
|
pub type IItemEnumerator = *mut ::core::ffi::c_void;
pub type ISettingsContext = *mut ::core::ffi::c_void;
pub type ISettingsEngine = *mut ::core::ffi::c_void;
pub type ISettingsIdentity = *mut ::core::ffi::c_void;
pub type ISettingsItem = *mut ::core::ffi::c_void;
pub type ISettingsNamespace = *mut ::core::ffi::c_void;
pub type ISettingsResult = *mut ::core::ffi::c_void;
pub type ITargetInfo = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const LIMITED_VALIDATION_MODE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const LINK_STORE_TO_ENGINE_INSTANCE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const SettingsEngine: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x9f7d7bb5_20b3_11da_81a5_0030f1642e3c);
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_ABORTOPERATION: ::windows_sys::core::HRESULT = -2145255384i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_ASSERTIONFAILED: ::windows_sys::core::HRESULT = -2145255398i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_ATTRIBUTENOTALLOWED: ::windows_sys::core::HRESULT = -2145255420i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_ATTRIBUTENOTFOUND: ::windows_sys::core::HRESULT = -2145255421i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_CONFLICTINGASSERTION: ::windows_sys::core::HRESULT = -2145255399i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_CYCLICREFERENCE: ::windows_sys::core::HRESULT = -2145255389i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_DUPLICATENAME: ::windows_sys::core::HRESULT = -2145255397i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_EXPRESSIONNOTFOUND: ::windows_sys::core::HRESULT = -2145255408i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_HANDLERNOTFOUND: ::windows_sys::core::HRESULT = -2145255394i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_INTERNALERROR: ::windows_sys::core::HRESULT = -2145255424i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_INVALIDATTRIBUTECOMBINATION: ::windows_sys::core::HRESULT = -2145255385i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_INVALIDDATATYPE: ::windows_sys::core::HRESULT = -2145255416i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_INVALIDEXPRESSIONSYNTAX: ::windows_sys::core::HRESULT = -2145255401i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_INVALIDHANDLERSYNTAX: ::windows_sys::core::HRESULT = -2145255393i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_INVALIDKEY: ::windows_sys::core::HRESULT = -2145255396i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_INVALIDLANGUAGEFORMAT: ::windows_sys::core::HRESULT = -2145255410i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_INVALIDPATH: ::windows_sys::core::HRESULT = -2145255413i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_INVALIDPROCESSORFORMAT: ::windows_sys::core::HRESULT = -2145255382i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_INVALIDSTREAM: ::windows_sys::core::HRESULT = -2145255395i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_INVALIDVALUE: ::windows_sys::core::HRESULT = -2145255419i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_INVALIDVALUEFORMAT: ::windows_sys::core::HRESULT = -2145255418i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_INVALIDVERSIONFORMAT: ::windows_sys::core::HRESULT = -2145255411i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_KEYNOTCHANGEABLE: ::windows_sys::core::HRESULT = -2145255409i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_MANIFESTCOMPILATIONFAILED: ::windows_sys::core::HRESULT = -2145255390i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_MISSINGCONFIGURATION: ::windows_sys::core::HRESULT = -2145255383i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_MIXTYPEASSERTION: ::windows_sys::core::HRESULT = -2145255388i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_NAMESPACEALREADYREGISTERED: ::windows_sys::core::HRESULT = -2145255403i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_NAMESPACENOTFOUND: ::windows_sys::core::HRESULT = -2145255404i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_NOTIFICATIONNOTFOUND: ::windows_sys::core::HRESULT = -2145255400i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_NOTPOSITIONED: ::windows_sys::core::HRESULT = -2145255415i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_NOTSUPPORTEDFUNCTION: ::windows_sys::core::HRESULT = -2145255387i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_READONLYITEM: ::windows_sys::core::HRESULT = -2145255414i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_RESTRICTIONFAILED: ::windows_sys::core::HRESULT = -2145255391i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_SOURCEMANEMPTYVALUE: ::windows_sys::core::HRESULT = -2145255381i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_STATENODENOTALLOWED: ::windows_sys::core::HRESULT = -2145255422i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_STATENODENOTFOUND: ::windows_sys::core::HRESULT = -2145255423i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_STORECORRUPTED: ::windows_sys::core::HRESULT = -2145255402i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_SUBSTITUTIONNOTFOUND: ::windows_sys::core::HRESULT = -2145255407i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_TYPENOTSPECIFIED: ::windows_sys::core::HRESULT = -2145255417i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_UNKNOWNRESULT: ::windows_sys::core::HRESULT = -2145251325i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_USERALREADYREGISTERED: ::windows_sys::core::HRESULT = -2145255406i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_USERNOTFOUND: ::windows_sys::core::HRESULT = -2145255405i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_VALIDATIONFAILED: ::windows_sys::core::HRESULT = -2145255392i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_VALUETOOBIG: ::windows_sys::core::HRESULT = -2145255386i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_E_WRONGESCAPESTRING: ::windows_sys::core::HRESULT = -2145255412i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_SETTINGS_ID_ARCHITECTURE: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("architecture");
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_SETTINGS_ID_FLAG_DEFINITION: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_SETTINGS_ID_FLAG_REFERENCE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_SETTINGS_ID_LANGUAGE: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("language");
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_SETTINGS_ID_NAME: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("name");
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_SETTINGS_ID_TOKEN: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("token");
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_SETTINGS_ID_URI: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("uri");
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_SETTINGS_ID_VERSION: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("version");
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_SETTINGS_ID_VERSION_SCOPE: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("versionScope");
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_S_ATTRIBUTENOTALLOWED: ::windows_sys::core::HRESULT = 2232325i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_S_ATTRIBUTENOTFOUND: ::windows_sys::core::HRESULT = 2232321i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_S_INTERNALERROR: ::windows_sys::core::HRESULT = 2232320i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_S_INVALIDATTRIBUTECOMBINATION: ::windows_sys::core::HRESULT = 2232324i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_S_LEGACYSETTINGWARNING: ::windows_sys::core::HRESULT = 2232322i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const WCM_S_NAMESPACENOTFOUND: ::windows_sys::core::HRESULT = 2232326i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub type WcmDataType = i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const dataTypeByte: WcmDataType = 1i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const dataTypeSByte: WcmDataType = 2i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const dataTypeUInt16: WcmDataType = 3i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const dataTypeInt16: WcmDataType = 4i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const dataTypeUInt32: WcmDataType = 5i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const dataTypeInt32: WcmDataType = 6i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const dataTypeUInt64: WcmDataType = 7i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const dataTypeInt64: WcmDataType = 8i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const dataTypeBoolean: WcmDataType = 11i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const dataTypeString: WcmDataType = 12i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const dataTypeFlagArray: WcmDataType = 32768i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub type WcmNamespaceAccess = i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const ReadOnlyAccess: WcmNamespaceAccess = 1i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const ReadWriteAccess: WcmNamespaceAccess = 2i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub type WcmNamespaceEnumerationFlags = i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const SharedEnumeration: WcmNamespaceEnumerationFlags = 1i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const UserEnumeration: WcmNamespaceEnumerationFlags = 2i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const AllEnumeration: WcmNamespaceEnumerationFlags = 3i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub type WcmRestrictionFacets = i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const restrictionFacetMaxLength: WcmRestrictionFacets = 1i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const restrictionFacetEnumeration: WcmRestrictionFacets = 2i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const restrictionFacetMaxInclusive: WcmRestrictionFacets = 4i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const restrictionFacetMinInclusive: WcmRestrictionFacets = 8i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub type WcmSettingType = i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const settingTypeScalar: WcmSettingType = 1i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const settingTypeComplex: WcmSettingType = 2i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const settingTypeList: WcmSettingType = 3i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub type WcmTargetMode = i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const OfflineMode: WcmTargetMode = 1i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const OnlineMode: WcmTargetMode = 2i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub type WcmUserStatus = i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const UnknownStatus: WcmUserStatus = 0i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const UserRegistered: WcmUserStatus = 1i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const UserUnregistered: WcmUserStatus = 2i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const UserLoaded: WcmUserStatus = 3i32;
#[doc = "*Required features: `\"Win32_System_SettingsManagementInfrastructure\"`*"]
pub const UserUnloaded: WcmUserStatus = 4i32;
|
use num::complex::Complex;
pub struct MandelbrotPoint {
pub x: u32,
pub y: u32,
pub color: image::Rgb<u8>
}
fn mandelbrot(z: Complex<f32>, c: Complex<f32>) -> Complex<f32> {
num::pow(z, 2) + c
}
pub fn in_mandelbrot_set(c: Complex<f32>, iterations: u32) -> (bool, u32) {
let mut z = c;
for i in 0..iterations {
if num::pow(z.re, 2) + num::pow(z.im, 2) > 4.0 {
return (false, i);
}
z = mandelbrot(z, c);
}
(true, iterations)
}
fn get_greyscale_pixel(ratio: f32) -> image::Rgb<u8> {
let color = (ratio * 255.0) as u8;
image::Rgb([
color,
color,
color
])
}
fn get_color_pixel(ratio: f32) -> image::Rgb<u8> {
let color_value = (ratio * 0xFFFFFF as f32) as u32;
let r = ((color_value & 0xFF0000) >> 16) as u8;
let g = ((color_value & 0x00FF00) >> 8) as u8;
let b = (color_value & 0x0000FF) as u8;
image::Rgb([r, g, b])
}
pub fn get_mandelbrot_color(c: Complex<f32>, iterations: u32, color: bool) -> image::Rgb<u8> {
let (in_set, iterations_taken) = in_mandelbrot_set(c, iterations);
if in_set {
image::Rgb([0, 0, 0])
} else {
if color {
get_color_pixel(iterations_taken as f32 / iterations as f32)
} else {
get_greyscale_pixel(iterations_taken as f32 / iterations as f32)
}
}
}
|
use proptest::prop_assert_eq;
use proptest::strategy::Just;
use liblumen_alloc::erts::term::prelude::*;
use crate::erlang::put_2::result;
use crate::test::strategy;
#[test]
fn without_key_returns_undefined_for_previous_value() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term(arc_process.clone()),
strategy::term(arc_process.clone()),
)
},
|(arc_process, key, value)| {
arc_process.erase_entries();
prop_assert_eq!(
result(&arc_process, key, value),
Atom::str_to_term("undefined")
);
prop_assert_eq!(arc_process.get_value_from_key(key), value);
Ok(())
},
);
}
#[test]
fn with_key_returns_previous_value() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term(arc_process.clone()),
strategy::term(arc_process.clone()),
strategy::term(arc_process),
)
},
|(arc_process, key, old_value, new_value)| {
arc_process.erase_entries();
arc_process.put(key, old_value);
prop_assert_eq!(result(&arc_process, key, new_value), old_value);
prop_assert_eq!(arc_process.get_value_from_key(key), new_value);
Ok(())
},
);
}
|
mod with_integer_integer;
use proptest::{prop_assert, prop_assert_eq};
use liblumen_alloc::erts::term::prelude::*;
use crate::erlang::integer_to_list_2::result;
use crate::test::strategy;
#[test]
fn without_integer_integer_errors_badarg() {
crate::test::without_integer_integer_with_base_errors_badarg(file!(), result);
}
|
use chrono::{Date, NaiveDate, Utc};
use serenity::{
async_trait,
client::{Context, EventHandler},
framework::{
standard::{
macros::{command, group},
CommandResult,
},
StandardFramework,
},
model::{channel::Message, id::UserId, prelude::Ready},
prelude::{RwLock, TypeMapKey},
Client,
};
use std::{
collections::{HashMap, HashSet},
env,
sync::Arc,
};
mod birthdays;
mod conversion;
use birthdays::*;
struct TodayDate;
impl TypeMapKey for TodayDate {
type Value = Arc<RwLock<Date<Utc>>>;
}
#[group]
#[commands(about, update_db, add_birthday, print_db, delete_birthday)]
struct General;
struct Handler;
#[async_trait]
impl EventHandler for Handler {
async fn message(&self, ctx: Context, msg: Message) {
// check if we've sent a birthday reminder today (if a flag_date has already been set to today's date then we have!)
let date = msg.timestamp.date();
let flag_date = {
let data_read = ctx.data.read().await;
let today_date_lock = data_read
.get::<TodayDate>()
.expect("expected a TodayDate")
.clone();
let today_date = today_date_lock.read().await;
today_date.clone()
};
if date != flag_date {
update_flag(&ctx, date)
.await
.expect("failed to update the date in the DB");
notify_users(&ctx, &msg).await;
}
if !msg.author.bot {
if let Some(reply) = conversion::respond_to_msg(&msg.content) {
msg.reply(&ctx, reply).await.unwrap();
println!("{:?}", msg.timestamp.date())
}
}
}
async fn ready(&self, ctx: Context, _ready: Ready) {
database_update(&ctx)
.await
.expect("failed to update database");
}
}
#[tokio::main]
async fn main() {
let token: String = env::var("DISCORD_API_TOKEN").expect("Token not found");
let mut owners = HashSet::new();
owners.insert(UserId::from(360433679111159808));
let framework = StandardFramework::new()
.configure(|c| c.prefix("!").owners(owners))
.group(&GENERAL_GROUP);
let mut client = Client::builder(token)
.event_handler(Handler)
.framework(framework)
.await
.expect("Could not start Discord");
// creating empty globals
{
let mut data = client.data.write().await;
data.insert::<BirthdaysDb>(Arc::new(RwLock::new(HashMap::default())));
data.insert::<TodayDate>(Arc::new(RwLock::new(Date::<Utc>::from_utc(
NaiveDate::from_yo(2021, 1),
Utc,
))));
}
client.start().await.expect("The bot stopped");
}
#[command]
async fn about(ctx: &Context, msg: &Message) -> CommandResult {
msg.reply(
ctx,
"I provide unit conversion capabilities! (and also track birthdays!)",
)
.await?;
Ok(())
}
|
use audio_core::{Buf, Channel, ChannelMut, Channels, ChannelsMut, ExactSizeBuf, WriteBuf};
/// Make a mutable buffer into a write adapter that implements [WriteBuf].
///
/// # Examples
///
/// ```rust
/// use audio::{Buf as _, ReadBuf as _, WriteBuf as _};
/// use audio::io;
///
/// let from = audio::interleaved![[1.0f32, 2.0f32, 3.0f32, 4.0f32]; 2];
/// let mut from = io::Read::new(from.skip(2));
///
/// let to = audio::interleaved![[0.0f32; 4]; 2];
/// let mut to = io::Write::new(to);
///
/// assert_eq!(to.remaining_mut(), 4);
/// io::copy_remaining(from, &mut to);
/// assert_eq!(to.remaining_mut(), 2);
///
/// assert_eq! {
/// to.as_ref().as_slice(),
/// &[3.0, 3.0, 4.0, 4.0, 0.0, 0.0, 0.0, 0.0],
/// };
/// ```
pub struct Write<B> {
buf: B,
available: usize,
}
impl<B> Write<B> {
/// Construct a new writing adapter.
///
/// The constructed writer will be initialized so that the number of bytes
/// available for writing are equal to what's reported by
/// [ExactSizeBuf::frames].
///
/// # Examples
///
/// ```rust
/// use audio::{WriteBuf, ExactSizeBuf};
/// use audio::io;
///
/// let buffer = audio::interleaved![[1, 2, 3, 4], [5, 6, 7, 8]];
/// assert_eq!(buffer.frames(), 4);
///
/// let buffer = io::Write::new(buffer);
///
/// assert!(buffer.has_remaining_mut());
/// assert_eq!(buffer.remaining_mut(), 4);
/// ```
pub fn new(buf: B) -> Self
where
B: ExactSizeBuf,
{
let available = buf.frames();
Self { buf, available }
}
/// Construct a new writing adapter.
///
/// The constructed reader will be initialized so that there are no frames
/// available to be written.
///
/// # Examples
///
/// ```rust
/// use audio::{WriteBuf, ExactSizeBuf};
/// use audio::io;
///
/// let buffer = audio::interleaved![[1, 2, 3, 4], [5, 6, 7, 8]];
/// assert_eq!(buffer.frames(), 4);
///
/// let buffer = io::Write::empty(buffer);
///
/// assert!(!buffer.has_remaining_mut());
/// assert_eq!(buffer.remaining_mut(), 0);
/// ```
pub fn empty(buf: B) -> Self {
Self { buf, available: 0 }
}
/// Access the underlying buffer.
///
/// # Examples
///
/// ```rust
/// use audio::{io, wrap};
///
/// let buffer: audio::Interleaved<i16> = audio::interleaved![[1, 2, 3, 4]; 4];
/// let mut buffer = io::Write::new(buffer);
///
/// io::copy_remaining(wrap::interleaved(&[0i16; 16][..], 4), &mut buffer);
///
/// assert_eq!(buffer.as_ref().channels(), 4);
/// ```
pub fn as_ref(&self) -> &B {
&self.buf
}
/// Access the underlying buffer mutably.
///
/// # Examples
///
/// ```rust
/// use audio::{io, wrap};
/// use audio::Buf as _;
///
/// let buffer: audio::Interleaved<i16> = audio::interleaved![[1, 2, 3, 4]; 4];
/// let mut buffer = io::Write::new(buffer);
///
/// io::copy_remaining(wrap::interleaved(&[0i16; 16][..], 4), &mut buffer);
///
/// buffer.as_mut().resize_channels(2);
///
/// assert_eq!(buffer.channels(), 2);
/// ```
pub fn as_mut(&mut self) -> &mut B {
&mut self.buf
}
/// Convert into the underlying buffer.
///
/// # Examples
///
/// ```rust
/// use audio::Buf as _;
/// use audio::io;
///
/// let buffer: audio::Interleaved<i16> = audio::interleaved![[1, 2, 3, 4]; 4];
/// let mut buffer = io::Write::new(buffer);
///
/// io::copy_remaining(audio::wrap::interleaved(&[0i16; 16][..], 4), &mut buffer);
///
/// let buffer = buffer.into_inner();
///
/// assert_eq!(buffer.channels(), 4);
/// ```
pub fn into_inner(self) -> B {
self.buf
}
/// Set the number of frames written.
///
/// This can be used to rewind the internal cursor to a previously written
/// frame if needed. Or, if the underlying buffer has changed for some
/// reason, like if it was read into through a call to [Write::as_mut].
///
/// # Examples
///
/// ```rust
/// use audio::{Buf, ChannelsMut, WriteBuf};
/// use audio::io;
///
/// fn write_to_buf(mut write: impl Buf + ChannelsMut<i16> + WriteBuf) {
/// let mut from = audio::interleaved![[0; 4]; 2];
/// io::copy_remaining(io::Read::new(&mut from), write);
/// }
///
/// let mut buffer = io::Write::new(audio::interleaved![[1, 2, 3, 4], [5, 6, 7, 8]]);
/// write_to_buf(&mut buffer);
///
/// assert!(!buffer.has_remaining_mut());
///
/// buffer.set_written(0);
///
/// assert!(buffer.has_remaining_mut());
/// ```
#[inline]
pub fn set_written(&mut self, written: usize)
where
B: ExactSizeBuf,
{
self.available = self.buf.frames().saturating_sub(written);
}
}
impl<B> WriteBuf for Write<B> {
/// Remaining number of frames available.
#[inline]
fn remaining_mut(&self) -> usize {
self.available
}
#[inline]
fn advance_mut(&mut self, n: usize) {
self.available = self.available.saturating_sub(n);
}
}
impl<B> ExactSizeBuf for Write<B>
where
B: ExactSizeBuf,
{
fn frames(&self) -> usize {
self.buf.frames()
}
}
impl<B> Buf for Write<B>
where
B: Buf,
{
fn frames_hint(&self) -> Option<usize> {
self.buf.frames_hint()
}
fn channels(&self) -> usize {
self.buf.channels()
}
}
impl<B, T> Channels<T> for Write<B>
where
B: Channels<T>,
{
fn channel(&self, channel: usize) -> Channel<'_, T> {
self.buf.channel(channel).tail(self.available)
}
}
impl<B, T> ChannelsMut<T> for Write<B>
where
B: ChannelsMut<T>,
{
#[inline]
fn channel_mut(&mut self, channel: usize) -> ChannelMut<'_, T> {
self.buf.channel_mut(channel).tail(self.available)
}
#[inline]
fn copy_channels(&mut self, from: usize, to: usize)
where
T: Copy,
{
self.buf.copy_channels(from, to);
}
}
|
use actix_identity::Identity;
use actix_web::web::{Data, Json, Path};
use auth::identity_matches_game_id;
use db::{get_conn, PgPool};
use errors;
use crate::handlers::{get_game_status, StatusResponse};
pub async fn status(
id: Identity,
game_id: Path<i32>,
pool: Data<PgPool>,
) -> Result<Json<StatusResponse>, errors::Error> {
let game_id = game_id.into_inner();
identity_matches_game_id(id, game_id)?;
let connection = get_conn(&pool)?;
let response = get_game_status(connection, game_id).await?;
Ok(Json(response))
}
#[cfg(test)]
mod tests {
use diesel::{self, RunQueryDsl};
use auth::{PrivateClaim, Role};
use db::{
get_conn,
models::Game,
new_pool,
schema::{games, rounds},
};
use crate::handlers::StatusResponse;
use crate::tests::helpers::tests::{get_auth_token, test_get};
#[derive(Insertable)]
#[table_name = "games"]
struct NewGame {
slug: Option<String>,
}
#[derive(Insertable)]
#[table_name = "rounds"]
struct NewRound {
pub player_one: String,
pub player_two: String,
pub game_id: i32,
pub locked: bool,
pub finished: bool,
}
#[actix_rt::test]
async fn test_get_game_status() {
let pool = new_pool();
let conn = get_conn(&pool).unwrap();
let game: Game = diesel::insert_into(games::table)
.values(NewGame {
slug: Some("abc123".to_string()),
})
.get_result(&conn)
.unwrap();
diesel::insert_into(rounds::table)
.values(NewRound {
player_one: "one".to_string(),
player_two: "two".to_string(),
game_id: game.id,
locked: true,
finished: false,
})
.execute(&conn)
.unwrap();
diesel::insert_into(rounds::table)
.values(NewRound {
player_one: "one".to_string(),
player_two: "two".to_string(),
game_id: game.id,
locked: true,
finished: false,
})
.execute(&conn)
.unwrap();
// isnt locked, but wrong game id
let other_game: Game = diesel::insert_into(games::table)
.values(NewGame {
slug: Some("dfg888".to_string()),
})
.get_result(&conn)
.unwrap();
diesel::insert_into(rounds::table)
.values(NewRound {
player_one: "one".to_string(),
player_two: "two".to_string(),
game_id: other_game.id,
locked: false,
finished: false,
})
.execute(&conn)
.unwrap();
let token = get_auth_token(PrivateClaim::new(
game.id,
game.slug.unwrap(),
game.id,
Role::Owner,
));
let res: (u16, StatusResponse) =
test_get(&format!("/api/games/{}", game.id), Some(token)).await;
assert_eq!(res.0, 200);
assert_eq!(res.1.slug, "abc123");
assert_eq!(res.1.open_round, false);
assert_eq!(res.1.unfinished_round, true);
diesel::delete(rounds::table).execute(&conn).unwrap();
diesel::delete(games::table).execute(&conn).unwrap();
}
#[actix_rt::test]
async fn test_get_game_status_open_round() {
let pool = new_pool();
let conn = get_conn(&pool).unwrap();
let game: Game = diesel::insert_into(games::table)
.values(NewGame {
slug: Some("abc123".to_string()),
})
.get_result(&conn)
.unwrap();
diesel::insert_into(rounds::table)
.values(NewRound {
player_one: "one".to_string(),
player_two: "two".to_string(),
game_id: game.id,
locked: true,
finished: true,
})
.execute(&conn)
.unwrap();
diesel::insert_into(rounds::table)
.values(NewRound {
player_one: "one".to_string(),
player_two: "two".to_string(),
game_id: game.id,
locked: true,
finished: true,
})
.execute(&conn)
.unwrap();
diesel::insert_into(rounds::table)
.values(NewRound {
player_one: "one".to_string(),
player_two: "two".to_string(),
game_id: game.id,
locked: false,
finished: true,
})
.execute(&conn)
.unwrap();
let token = get_auth_token(PrivateClaim::new(
game.id,
game.slug.unwrap(),
game.id,
Role::Owner,
));
let res: (u16, StatusResponse) =
test_get(&format!("/api/games/{}", game.id), Some(token)).await;
assert_eq!(res.0, 200);
assert_eq!(res.1.slug, "abc123");
assert_eq!(res.1.open_round, true);
assert_eq!(res.1.unfinished_round, false);
diesel::delete(rounds::table).execute(&conn).unwrap();
diesel::delete(games::table).execute(&conn).unwrap();
}
}
|
use smartcore::dataset::*;
// DenseMatrix wrapper around Vec
use smartcore::linalg::naive::dense_matrix::DenseMatrix;
// KNN
use smartcore::neighbors::knn_classifier::KNNClassifier;
use smartcore::neighbors::knn_regressor::KNNRegressor;
// Logistic/Linear Regression
use smartcore::linear::elastic_net::{ElasticNet, ElasticNetParameters};
use smartcore::linear::lasso::{Lasso, LassoParameters};
use smartcore::linear::linear_regression::LinearRegression;
use smartcore::linear::logistic_regression::LogisticRegression;
use smartcore::linear::ridge_regression::{RidgeRegression, RidgeRegressionParameters};
// Tree
use smartcore::tree::decision_tree_classifier::DecisionTreeClassifier;
use smartcore::tree::decision_tree_regressor::DecisionTreeRegressor;
// Random Forest
use smartcore::ensemble::random_forest_classifier::RandomForestClassifier;
use smartcore::ensemble::random_forest_regressor::RandomForestRegressor;
// SVM
use smartcore::svm::svc::{SVCParameters, SVC};
use smartcore::svm::svr::{SVRParameters, SVR};
use smartcore::svm::Kernels;
// Model performance
use smartcore::metrics::{mean_squared_error, roc_auc_score};
use smartcore::model_selection::train_test_split;
use crate::utils;
pub fn diabetes() {
// Load dataset
let diabetes_data = diabetes::load_dataset();
// Transform dataset into a NxM matrix
let x = DenseMatrix::from_array(
diabetes_data.num_samples,
diabetes_data.num_features,
&diabetes_data.data,
);
// These are our target values
let y = diabetes_data.target;
// Split dataset into training/test (80%/20%)
let (x_train, x_test, y_train, y_test) = train_test_split(&x, &y, 0.2, true);
// SVM
let y_hat_svm = SVR::fit(
&x_train,
&y_train,
SVRParameters::default()
.with_kernel(Kernels::rbf(0.5))
.with_c(2000.0)
.with_eps(10.0),
)
.and_then(|svm| svm.predict(&x_test))
.unwrap();
println!("{:?}", y_hat_svm);
println!("{:?}", y_test);
println!("MSE: {}", mean_squared_error(&y_test, &y_hat_svm));
}
pub fn breast_cancer() {
// Load dataset
let cancer_data = breast_cancer::load_dataset();
// Transform dataset into a NxM matrix
let x = DenseMatrix::from_array(
cancer_data.num_samples,
cancer_data.num_features,
&cancer_data.data,
);
// These are our target class labels
let y = cancer_data.target;
// Split dataset into training/test (80%/20%)
let (x_train, x_test, y_train, y_test) = train_test_split(&x, &y, 0.2, true);
// KNN classifier
let y_hat_knn = KNNClassifier::fit(&x_train, &y_train, Default::default())
.and_then(|knn| knn.predict(&x_test))
.unwrap();
// Logistic Regression
let y_hat_lr = LogisticRegression::fit(&x_train, &y_train, Default::default())
.and_then(|lr| lr.predict(&x_test))
.unwrap();
// Decision Tree
let y_hat_tree = DecisionTreeClassifier::fit(&x_train, &y_train, Default::default())
.and_then(|tree| tree.predict(&x_test))
.unwrap();
// Random Forest
let y_hat_rf = RandomForestClassifier::fit(&x_train, &y_train, Default::default())
.and_then(|rf| rf.predict(&x_test))
.unwrap();
// SVM
let y_hat_svm = SVC::fit(&x_train, &y_train, SVCParameters::default().with_c(2.0))
.and_then(|svm| svm.predict(&x_test))
.unwrap();
// Calculate test error
println!("AUC KNN: {}", roc_auc_score(&y_test, &y_hat_knn));
println!(
"AUC Logistic Regression: {}",
roc_auc_score(&y_test, &y_hat_lr)
);
println!("AUC Decision Tree: {}", roc_auc_score(&y_test, &y_hat_tree));
println!("AUC Random Forest: {}", roc_auc_score(&y_test, &y_hat_rf));
println!("AUC SVM: {}", roc_auc_score(&y_test, &y_hat_svm));
}
pub fn boston() {
// Load dataset
let boston_data = boston::load_dataset();
// Transform dataset into a NxM matrix
let x = DenseMatrix::from_array(
boston_data.num_samples,
boston_data.num_features,
&boston_data.data,
);
// These are our target values
let y = boston_data.target;
let (x_train, x_test, y_train, y_test) = train_test_split(&x, &y, 0.2, true);
// KNN regressor
let y_hat_knn = KNNRegressor::fit(&x_train, &y_train, Default::default())
.and_then(|knn| knn.predict(&x_test))
.unwrap();
// Linear Regression
let y_hat_lr = LinearRegression::fit(&x_train, &y_train, Default::default())
.and_then(|lr| lr.predict(&x_test))
.unwrap();
// Ridge Regression
let y_hat_rr = RidgeRegression::fit(
&x_train,
&y_train,
RidgeRegressionParameters::default().with_alpha(0.5),
)
.and_then(|rr| rr.predict(&x_test))
.unwrap();
// LASSO
let y_hat_lasso = Lasso::fit(
&x_train,
&y_train,
LassoParameters::default().with_alpha(0.5),
)
.and_then(|lr| lr.predict(&x_test))
.unwrap();
// Elastic Net
let y_hat_en = ElasticNet::fit(
&x_train,
&y_train,
ElasticNetParameters::default()
.with_alpha(0.5)
.with_l1_ratio(0.5),
)
.and_then(|lr| lr.predict(&x_test))
.unwrap();
// Decision Tree
let y_hat_tree = DecisionTreeRegressor::fit(&x_train, &y_train, Default::default())
.and_then(|tree| tree.predict(&x_test))
.unwrap();
// Random Forest
let y_hat_rf = RandomForestRegressor::fit(&x_train, &y_train, Default::default())
.and_then(|rf| rf.predict(&x_test))
.unwrap();
// Calculate test error
println!("MSE KNN: {}", mean_squared_error(&y_test, &y_hat_knn));
println!(
"MSE Linear Regression: {}",
mean_squared_error(&y_test, &y_hat_lr)
);
println!(
"MSE Ridge Regression: {}",
mean_squared_error(&y_test, &y_hat_rr)
);
println!("MSE LASSO: {}", mean_squared_error(&y_test, &y_hat_lasso));
println!(
"MSE Elastic Net: {}",
mean_squared_error(&y_test, &y_hat_en)
);
println!(
"MSE Decision Tree: {}",
mean_squared_error(&y_test, &y_hat_tree)
);
println!(
"MSE Random Forest: {}",
mean_squared_error(&y_test, &y_hat_rf)
);
}
/// Fits Support Vector Classifier (SVC) to generated dataset and plots the decision boundary for three SVC with different kernels.Default
/// The idea for this example is taken from https://scikit-learn.org/stable/auto_examples/svm/plot_iris_svc.html
pub fn svm() {
let num_samples = 100;
let num_features = 2;
// Generate a dataset with 100 sample, 2 features in each sample, split into 2 groups
let data = generator::make_blobs(num_samples, num_features, 2);
let y: Vec<f32> = data.target;
// Transform dataset into a NxM matrix
let x = DenseMatrix::from_array(data.num_samples, data.num_features, &data.data);
// We also need a 2x2 mesh grid that we will use to plot decision boundaries.
let mesh = utils::make_meshgrid(&x);
// SVC with linear kernel
let linear_svc = SVC::fit(&x, &y, Default::default()).unwrap();
utils::scatterplot_with_mesh(
&mesh,
&linear_svc.predict(&mesh).unwrap(),
&x,
&y,
"linear_svm",
)
.unwrap();
// SVC with Gaussian kernel
let rbf_svc = SVC::fit(
&x,
&y,
SVCParameters::default().with_kernel(Kernels::rbf(0.7)),
)
.unwrap();
utils::scatterplot_with_mesh(&mesh, &rbf_svc.predict(&mesh).unwrap(), &x, &y, "rbf_svm")
.unwrap();
// SVC with 3rd degree polynomial kernel
let poly_svc = SVC::fit(
&x,
&y,
SVCParameters::default().with_kernel(Kernels::polynomial_with_degree(3.0, num_features)),
)
.unwrap();
utils::scatterplot_with_mesh(
&mesh,
&poly_svc.predict(&mesh).unwrap(),
&x,
&y,
"polynomial_svm",
)
.unwrap();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.