text
stringlengths
8
4.13M
//! Integral range values. use std::ops; /// An integral range. pub type Range = ops::Range<u32>;
use anyhow::*; use image::GenericImageView; use std::path::Path; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use crate::asset::{Handle, Assets}; #[derive(Debug)] pub struct Texture { pub texture: wgpu::Texture, pub view: wgpu::TextureView, pub sampler: wgpu::Sampler, } impl Texture { pub fn get_or_load<P: AsRef<Path>>( textures: &mut Assets<Texture>, device: &wgpu::Device, queue: &wgpu::Queue, path: P, ) -> Result<Handle<Texture>> { let id = { let path_copy = path.as_ref().to_path_buf(); let path_str = path_copy.to_str(); let mut hasher = DefaultHasher::new(); path_str.hash(&mut hasher); hasher.finish() }; if let Some(handle) = textures.get_handle(id) { return Ok(handle); } let texture = Texture::load(device, queue, path)?; Ok(textures.add(texture, id)) } pub fn load<P: AsRef<Path>>( device: &wgpu::Device, queue: &wgpu::Queue, path: P, ) -> Result<Self> { let path_copy = path.as_ref().to_path_buf(); let label = path_copy.to_str(); let img = image::open(path)?; Self::from_image(device, queue, &img, label) } /*pub fn from_bytes( device: &wgpu::Device, queue: &wgpu::Queue, bytes: &[u8], label: &str, ) -> Result<Self> { let img = image::load_from_memory(bytes)?; Self::from_image(device, queue, &img, Some(label)) }*/ pub fn from_image( device: &wgpu::Device, queue: &wgpu::Queue, img: &image::DynamicImage, label: Option<&str>, ) -> Result<Self> { let rgba = img.to_rgba8(); let dimensions = img.dimensions(); let size = wgpu::Extent3d { width: dimensions.0, height: dimensions.1, depth: 1, }; let texture = device.create_texture(&wgpu::TextureDescriptor { label, size, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8UnormSrgb, usage: wgpu::TextureUsage::SAMPLED | wgpu::TextureUsage::COPY_DST, }); queue.write_texture( wgpu::TextureCopyView { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, }, &rgba, wgpu::TextureDataLayout { offset: 0, bytes_per_row: 4 * dimensions.0, rows_per_image: dimensions.1, }, size, ); let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); let sampler = device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Nearest, mipmap_filter: wgpu::FilterMode::Nearest, ..Default::default() }); Ok(Self { texture, view, sampler, }) } }
//! Used to test file I/O functions in Rust. use std::io::Write; use std::{fs, io}; fn main() -> io::Result<()> { let mut file = io::BufWriter::new(fs::File::create("test.txt")?); println!("going to write: \"hi there\\n\""); file.write_all(b"hi there\n")?; println!("going to write: \"hi there\\nmy name is Joey\\n\""); file.write_all(b"hi there\nmy name is Joey\n")?; Ok(()) }
use super::byteslice::ByteSliceExt; #[derive(Clone, Copy)] pub enum MatchResult { Unmatched, Matched { reduced_offset: u16, match_len: usize, match_len_expected: usize, match_len_min: usize, } } #[derive(Clone, Copy)] pub struct Bucket { head: u16, node_part1: [u32; super::LZ_MF_BUCKET_ITEM_SIZE], // pos:25 | match_len_expected:7 node_part2: [u8; super::LZ_MF_BUCKET_ITEM_SIZE], // match_len_min:8 /* match_len_expected: * the match length we got when searching match for this position * if no match is found, this value is set to 0. * * when a newer position matches this position, it is likely that the match length * is the same with this value. * * match_len_min: * the longest match of all newer position that matches this position * if no match is found, this value is set to LZ_MATCH_MIN_LEN-1. * * when a newer position matches this position, the match length is always * longer than this value, because shortter matches will stop at a newer position * that matches this position. * * A A A A A B B B B B A A A A A C C C C C A A A A A * | | * |<------------------| * | | * | match_len_expected=5 * match_len_min=6 */ } impl Bucket { pub fn new() -> Bucket { return Bucket { head: 0, node_part1: [0; super::LZ_MF_BUCKET_ITEM_SIZE], node_part2: [0; super::LZ_MF_BUCKET_ITEM_SIZE], }; } unsafe fn get_node_pos(&self, i: usize) -> usize { let self_node_part1 = &unchecked_index::unchecked_index(&self.node_part1); return self_node_part1[i] as usize & 0x01ff_ffff; } unsafe fn get_node_match_len_expected(&self, i: usize) -> usize { let self_node_part1 = &unchecked_index::unchecked_index(&self.node_part1); return self_node_part1[i] as usize >> 25; } unsafe fn get_node_match_len_min(&self, i: usize) -> usize { let self_node_part2 = unchecked_index::unchecked_index(&self.node_part2); return self_node_part2[i] as usize; } unsafe fn set_node(&mut self, i: usize, pos: usize, match_len_expected: usize, match_len_min: usize) { let self_node_part1 = &mut unchecked_index::unchecked_index(&mut self.node_part1); let self_node_part2 = &mut unchecked_index::unchecked_index(&mut self.node_part2); self_node_part1[i] = (pos | match_len_expected << 25) as u32; self_node_part2[i] = match_len_min as u8; } unsafe fn set_node_match_len_min(&mut self, i: usize, match_len_min: usize) { let self_node_part2 = &mut unchecked_index::unchecked_index(&mut self.node_part2); self_node_part2[i] = match_len_min as u8; } pub unsafe fn update(&mut self, pos: usize, reduced_offset: u16, match_len: usize) { let new_head = node_size_bounded_add(self.head, 1) as usize; // update match_len_min of matched position if match_len >= super::LZ_MATCH_MIN_LEN { let node_index = node_size_bounded_sub(self.head, reduced_offset) as usize; if self.get_node_match_len_min(node_index) <= match_len { self.set_node_match_len_min(node_index, match_len + 1); } } // update match_len_expected of incomping position let match_len_expected = match match_len { // match_len_expected < 128 because only 7 bits reserved 0 ..= 127 => match_len, _ => 0, }; self.set_node(new_head, pos, match_len_expected, 0); // move head to next node self.head = new_head as u16; } pub fn forward(&mut self, forward_len: usize) { unsafe { // update position of all nodes for i in 0 .. super::LZ_MF_BUCKET_ITEM_SIZE { self.set_node(i, self.get_node_pos(i).saturating_sub(forward_len), self.get_node_match_len_expected(i), self.get_node_match_len_min(i)); } } } pub unsafe fn get_match_pos_and_match_len(&self, reduced_offset: u16) -> (usize, usize, usize) { let node_index = node_size_bounded_sub(self.head, reduced_offset) as usize; return ( self.get_node_pos(node_index), std::cmp::max(self.get_node_match_len_expected(node_index), super::LZ_MATCH_MIN_LEN), std::cmp::max(self.get_node_match_len_min(node_index), super::LZ_MATCH_MIN_LEN), ); } } pub struct BucketMatcher { heads: [u16; super::LZ_MF_BUCKET_ITEM_HASH_SIZE], nexts: [u16; super::LZ_MF_BUCKET_ITEM_SIZE], } impl BucketMatcher { pub fn new() -> BucketMatcher { return BucketMatcher { heads: [u16::max_value(); super::LZ_MF_BUCKET_ITEM_HASH_SIZE], nexts: [u16::max_value(); super::LZ_MF_BUCKET_ITEM_SIZE], }; } pub unsafe fn update(&mut self, bucket: &Bucket, buf: &[u8], pos: usize) { let self_heads = &mut unchecked_index::unchecked_index(&mut self.heads); let self_nexts = &mut unchecked_index::unchecked_index(&mut self.nexts); let entry = hash_dword(buf, pos) % super::LZ_MF_BUCKET_ITEM_HASH_SIZE; self_nexts[bucket.head as usize] = self_heads[entry]; self_heads[entry] = bucket.head; } pub fn forward(&mut self, bucket: &Bucket) { unsafe { // clear all entries that points to out-of-date node self.heads.iter_mut() .filter(|head| **head != u16::max_value() && bucket.get_node_pos(**head as usize) == 0) .for_each(|head| *head = u16::max_value()); self.nexts.iter_mut() .filter(|next| **next != u16::max_value() && bucket.get_node_pos(**next as usize) == 0) .for_each(|next| *next = u16::max_value()); } } pub unsafe fn find_match(&self, bucket: &Bucket, buf: &[u8], pos: usize, match_depth: usize) -> MatchResult { let self_heads = &unchecked_index::unchecked_index(&self.heads); let self_nexts = &unchecked_index::unchecked_index(&self.nexts); let entry = hash_dword(buf, pos) % super::LZ_MF_BUCKET_ITEM_HASH_SIZE; let mut node_index = self_heads[entry] as usize; if node_index == u16::max_value() as usize { return MatchResult::Unmatched; } let mut max_len = super::LZ_MATCH_MIN_LEN - 1; let mut max_node_index = 0; let mut max_len_dword = buf.read(pos + max_len - 3); let mut max_match_len_min = 0; let mut max_match_len_expected = 0; for _ in 0..match_depth { let node_pos = bucket.get_node_pos(node_index); // check the last 4 bytes of longest match (fast) // then perform full LCP search if buf.read::<u32>(node_pos + max_len - 3) == max_len_dword { let lcp = super::mem::llcp_fast(buf, node_pos, pos, super::LZ_MATCH_MAX_LEN); if lcp > max_len { max_match_len_min = bucket.get_node_match_len_min(node_index); max_match_len_expected = bucket.get_node_match_len_expected(node_index); max_len = lcp; max_node_index = node_index; max_len_dword = buf.read(pos + max_len - 3); } if lcp == super::LZ_MATCH_MAX_LEN || (max_match_len_expected > 0 && lcp > max_match_len_expected) { /* * (1) (2) (3) * A A A A A B B B B B A A A A A C C C C C A A A A A C B * | | | * |<-5----------------| | * | | | * | match_len_expected=5| * match_len_min=6 | * |<-6----------------| * | * lcp=6 > max_match_len_expected * no need to continue searching because if there * exists a longer match, (2) will have matched it * and had got a longer match_len_expected. */ break; } } let node_next = self_nexts[node_index] as usize; if node_next == u16::max_value() as usize || node_pos <= bucket.get_node_pos(node_next) { break; } node_index = node_next; } if max_len >= super::LZ_MATCH_MIN_LEN && pos + max_len < buf.len() { return MatchResult::Matched { reduced_offset: node_size_bounded_sub(bucket.head, max_node_index as u16), match_len: max_len, match_len_expected: std::cmp::max(max_match_len_expected, super::LZ_MATCH_MIN_LEN), match_len_min: std::cmp::max(max_match_len_min, super::LZ_MATCH_MIN_LEN), }; } return MatchResult::Unmatched; } pub unsafe fn has_lazy_match(&self, bucket: &Bucket, buf: &[u8], pos: usize, min_match_len: usize, depth: usize) -> bool { let self_heads = &unchecked_index::unchecked_index(&self.heads); let self_nexts = &unchecked_index::unchecked_index(&self.nexts); let entry = hash_dword(buf, pos) % super::LZ_MF_BUCKET_ITEM_HASH_SIZE; let mut node_index = self_heads[entry] as usize; if node_index == u16::max_value() as usize { return false; } let max_len_dword = buf.read::<u32>(pos + min_match_len - 4); for _ in 0..depth { let node_pos = bucket.get_node_pos(node_index); // first check the last 4 bytes of longest match (fast) // then perform full comparison if buf.read::<u32>(node_pos + min_match_len - 4) == max_len_dword { if super::mem::memequ_hack_fast(buf, node_pos, pos, min_match_len - 4) { return true; } }; let node_next = self_nexts[node_index] as usize; if node_next == u16::max_value() as usize || node_pos <= bucket.get_node_pos(node_next) { break; } node_index = node_next; } return false; } } fn node_size_bounded_add(v1: u16, v2: u16) -> u16 { return (v1 + v2) % super::LZ_MF_BUCKET_ITEM_SIZE as u16; } fn node_size_bounded_sub(v1: u16, v2: u16) -> u16 { return (v1 + super::LZ_MF_BUCKET_ITEM_SIZE as u16 - v2) % super::LZ_MF_BUCKET_ITEM_SIZE as u16; } unsafe fn hash_dword(buf: &[u8], pos: usize) -> usize { return crc32c_hw::update(0, &buf.read::<[u8; 4]>(pos)) as usize; }
#![macro_use] pub mod hid; pub mod result; pub mod service;
#[cfg(test)] mod tests { #[test] fn it_works() { let x = 5; let y = &x; assert_eq!(5, x); assert_eq!(5, *y); } #[test] fn it_works_2() { let x = 5; let y = Box::new(x); assert_eq!(5, x); assert_eq!(5, *y); } mod my_box { use std::ops::{Deref, DerefMut}; struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } fn look(self) { let _value = self.0; println!("{}", "look") } } impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &T { // 通过引用访问字段,获取的是字段的引用 let df = &self.0; df } } impl<T> DerefMut for MyBox<T> { fn deref_mut(&mut self) -> &mut T { let df = &mut self.0; df } } #[test] fn it_works() { let x = 5; let y = MyBox::new(x); // let y = *y; assert_eq!(5, x); assert_eq!(5, *y); } fn hello(name: &str) { println!("Hello, {}!", name); } #[test] fn it_works_2() { let m = MyBox::new(String::from("Rust")); // 解引用强制多态 hello(&(*m)[..]); hello(&(m.deref())[..]); hello(&m); m.look(); // m.look(); 上一个m.look已move ownership } } }
extern crate gl; pub mod shader; pub mod program; pub mod color; pub mod math; pub mod rendertarget; pub mod mesh; pub use self::mesh::{Mesh,MeshBuilder}; pub use self::program::{GraphicsPipeline,PipelineBuilder}; pub use self::math::Vec2; pub use self::color::Color; pub use self::shader::{Shader, Uniform}; pub use self::rendertarget::{RenderTarget}; use gl::types::*; /// wrapper around raw opengl calls to interface with the graphics API pub struct GLContext; impl GLContext{ #[allow(unused_variables)] extern "system" fn gl_debug_message(source : GLenum, msg_type : GLenum, id : GLuint, severity : GLenum, length : GLsizei, message : *const GLchar, param : *mut super::std::os::raw::c_void) { unsafe { let msg = super::std::ffi::CStr::from_ptr(message); println!("GL: {}", msg.to_str().unwrap()); } } pub fn set_debug(&self) -> &Self { unsafe{ gl::Enable(gl::DEBUG_OUTPUT); gl::DebugMessageCallback(GLContext::gl_debug_message, super::std::ptr::null()); } self } /// Set's the current active viewport pub fn set_viewport(&self, x: i32, y: i32, width: i32, height: i32) -> &Self{ unsafe{ gl::Viewport(x,y,width,height); } self } /// Clears the current bound render target pub fn clear(&self, color : super::std::option::Option<Color>) -> &Self { unsafe { match color { Some(c) => gl::ClearColor(c.r as f32 / 255.0,c.g as f32 / 255.0,c.b as f32 / 255.0, c.a as f32 / 255.0), None => {} } gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); } self } /// Binds a shader program pub fn bind_pipeline(&self, program: &GraphicsPipeline){ unsafe{ gl::UseProgram(program.get_id()); } } /// Binds a render target for drawing pub fn bind_rt(&self, rt: &RenderTarget){ unsafe{ gl::BindFramebuffer(gl::FRAMEBUFFER, rt.get_fb()); } } }
use cpu::register::Register; use cpu::CPU; /// Move a value from register to register /// /// # Cycles /// /// * To/from register M: 7 /// * Other: 5 /// /// # Arguments /// * `cpu` - The cpu to perform the move in /// * `to` - The register to move the value to /// * `from` - The register to move the value from /// pub fn mov(cpu: &mut CPU, to: Register, from: Register) -> u8 { let val = match from { Register::A => cpu.a, Register::B => cpu.b, Register::C => cpu.c, Register::D => cpu.d, Register::E => cpu.e, Register::H => cpu.h, Register::L => cpu.l, Register::M => { let offset = (u16::from(cpu.h) << 8) + u16::from(cpu.l); cpu.memory[offset as usize] } unsupported => { panic!("mov doesn't support moving from {:?}", unsupported); } }; match to { Register::A => cpu.a = val, Register::B => cpu.b = val, Register::C => cpu.c = val, Register::D => cpu.d = val, Register::E => cpu.e = val, Register::H => cpu.h = val, Register::L => cpu.l = val, Register::M => { let offset = (u16::from(cpu.h) << 8) + u16::from(cpu.l); cpu.memory[offset as usize] = val; } unsupported => { panic!("mov doesn't support moving to {:?}", unsupported); } }; match (to, from) { (Register::M, _) | (_, Register::M) => 7, _ => 5, } } /// Move an immediate byte to a register /// /// # Cycles /// /// * Register M: 10 /// * Other: 7 /// /// # Arguments /// * `cpu` - The cpu to perform the move in /// * `to` - The register to move the value to /// pub fn mvi(cpu: &mut CPU, to: Register) -> u8 { let byte = cpu.read_byte().unwrap(); match to { Register::A => cpu.a = byte, Register::B => cpu.b = byte, Register::C => cpu.c = byte, Register::D => cpu.d = byte, Register::E => cpu.e = byte, Register::H => cpu.h = byte, Register::L => cpu.l = byte, Register::M => { let offset = (u16::from(cpu.h) << 8) + u16::from(cpu.l); cpu.memory[offset as usize] = byte; } unsupported => { panic!("mov doesn't support moving to {:?}", unsupported); } }; match to { Register::M => 10, _ => 7, } } #[cfg(test)] mod test { use super::*; #[test] fn mov_moves_between_registers() { let mut cpu = CPU { a: 2, b: 3, c: 4, ..CPU::default() }; mov(&mut cpu, Register::A, Register::B); assert_eq!(cpu.a, 3); mov(&mut cpu, Register::A, Register::C); assert_eq!(cpu.a, 4); mov(&mut cpu, Register::A, Register::A); assert_eq!(cpu.a, 4); } #[test] fn mov_moves_from_memory_address_if_from_m() { let mut cpu = CPU { memory: vec![0x00, 0x00, 0x00, 0x00, 0x00, 5], a: 2, h: 0x00, l: 0x05, ..CPU::default() }; mov(&mut cpu, Register::A, Register::M); assert_eq!(cpu.a, 5); } #[test] fn mov_moves_to_memory_address_if_to_m() { let mut cpu = CPU { memory: vec![0x00, 0x00, 0x00, 0x00, 0x00, 5], a: 2, h: 0x00, l: 0x05, ..CPU::default() }; mov(&mut cpu, Register::M, Register::A); assert_eq!(cpu.memory[5], 2); } #[test] fn mvi_sets_register_to_byte() { let mut cpu = CPU { memory: vec![0x11, 0x12], ..CPU::default() }; mvi(&mut cpu, Register::A); assert_eq!(cpu.a, 0x11); mvi(&mut cpu, Register::B); assert_eq!(cpu.b, 0x12); } #[test] fn mvi_sets_byte_in_memory_to_byte_for_register_m() { let mut cpu = CPU { memory: vec![0x11, 0x00, 0x00, 0x00, 0x00, 0x00], h: 0x00, l: 0x05, ..CPU::default() }; mvi(&mut cpu, Register::M); assert_eq!(cpu.memory[5], 0x11); } }
use std::{ collections::HashSet, marker::PhantomData, }; use crate::{prelude::*, material::*}; #[derive(Clone, Debug, Default)] pub struct TestMaterial<T: 'static> { phantom: PhantomData<T>, } impl<T> TestMaterial<T> { pub fn new() -> Self { Self { phantom: PhantomData } } } impl<T> Material for TestMaterial<T> { fn brightness(&self) -> f64 { 0.0 } } impl<T> Instance<MaterialClass> for TestMaterial<T> { fn source(_: &mut HashSet<u64>) -> String { String::new() } fn inst_name() -> String { "test_material".to_string() } } impl<T> Pack for TestMaterial<T> { fn size_int() -> usize { 0 } fn size_float() -> usize { 0 } fn pack_to(&self, _buffer_int: &mut [i32], _buffer_float: &mut [f32]) {} }
use std::{error, fmt}; /// Error that can happen when encoding some bytes into a multihash. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum EncodeError { /// The requested hash algorithm isn't supported by this library. UnsupportedType, /// The input length is too large for the hash algorithm. UnsupportedInputLength, } impl fmt::Display for EncodeError { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { EncodeError::UnsupportedType => write!(f, "This type is not supported yet"), EncodeError::UnsupportedInputLength => write!( f, "The length of the input for the given hash is not yet supported" ), } } } impl error::Error for EncodeError {} /// Error that can happen when decoding some bytes. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum DecodeError { /// The input doesn't have a correct length. BadInputLength, /// The code of the hashing algorithm is incorrect. UnknownCode, } impl fmt::Display for DecodeError { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { DecodeError::BadInputLength => write!(f, "Not matching input length"), DecodeError::UnknownCode => write!(f, "Found unknown code"), } } } impl error::Error for DecodeError {} /// Error that can happen when decoding some bytes. /// /// Same as `DecodeError`, but allows retreiving the data whose decoding was attempted. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DecodeOwnedError { /// The error. pub error: DecodeError, /// The data whose decoding was attempted. pub data: Vec<u8>, } impl fmt::Display for DecodeOwnedError { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.error) } } impl error::Error for DecodeOwnedError {}
use std::path::PathBuf; use bytes::Bytes; use tokio; use flyte::{local::LocalFilesystem, local::LocalFilesystemBuilder, Filesystem, FilesystemChain}; #[tokio::main] async fn main() -> anyhow::Result<()> { let strict_fs = LocalFilesystemBuilder::new() .with_prefix("secret".into()) .with_directory_permissions(0o700) .with_file_permissions(0o644) .into_boxed(); let public_fs = LocalFilesystemBuilder::new() .with_prefix("public".into()) .with_file_permissions(0o777) .into_boxed(); let chain = FilesystemChain::new(vec![strict_fs, public_fs]); let tmp_path = String::from("test"); chain.create_directory(&tmp_path).await?; for i in 1..=10 { chain .write_file( &format!("{}/foo{}.txt", tmp_path, i), Some(&Bytes::from(format!("bar{}", i))), ) .await?; } let nodes = chain.list_directory(&tmp_path).await?; for set in nodes { for node in set { println!("- {}", node); } } chain.delete_directory(&tmp_path).await?; Ok(()) }
//! Standard encryption and decryption. use super::*; /// Encryption key that may be shared publicly. #[derive(Debug,Clone)] pub struct EncryptionKey<I> { pub n: I, // the modulus nn: I, // the modulus squared } impl<I> ::traits::EncryptionKey for EncryptionKey<I> {} impl<'kp, I> From<&'kp Keypair<I>> for EncryptionKey<I> where I: Clone, for<'a, 'b> &'a I: Mul<&'b I, Output=I>, { fn from(keypair: &'kp Keypair<I>) -> EncryptionKey<I> { let ref modulus = &keypair.p * &keypair.q; EncryptionKey { n: modulus.clone(), nn: modulus * modulus, } } } /// Decryption key that should be kept private. #[derive(Debug,Clone)] pub struct DecryptionKey<I> { p: I, // first prime q: I, // second prime n: I, // the modulus (also in public key) nn: I, // the modulus squared lambda: I, // fixed at lambda = (p-1)*(q-1) mu: I, // fixed at lambda^{-1} } impl<I> ::traits::DecryptionKey for DecryptionKey<I> {} impl<'kp, I> From<&'kp Keypair<I>> for DecryptionKey<I> where I: One, I: Clone, I: ModInv, for<'a,'b> &'a I: Mul<&'b I, Output=I>, for<'a,'b> &'a I: Sub<&'b I, Output=I>, { fn from(keypair: &'kp Keypair<I>) -> DecryptionKey<I> { let ref one = I::one(); let modulus = &keypair.p * &keypair.q; let nn = &modulus * &modulus; let lambda = (&keypair.p - one) * (&keypair.q - one); let mu = I::modinv(&lambda, &modulus); DecryptionKey { p: keypair.p.clone(), // TODO store reference instead q: keypair.q.clone(), n: modulus, nn: nn, lambda: lambda, mu: mu, } } } impl<I, S> Rerandomisation<EncryptionKey<I>, Ciphertext<I>> for S where S: AbstractScheme<BigInteger=I>, I: Samplable, I: ModPow, for<'a> &'a I: Mul<I, Output=I>, for<'b> I: Rem<&'b I, Output=I>, { fn rerandomise(ek: &EncryptionKey<I>, c: &Ciphertext<I>) -> Ciphertext<I> { let r = I::sample_below(&ek.n); let d = (&c.0 * I::modpow(&r, &ek.n, &ek.nn)) % &ek.nn; Ciphertext(d) } } impl<I, S> Encryption<EncryptionKey<I>, Plaintext<I>, Ciphertext<I>> for S where S: AbstractScheme<BigInteger=I>, S: Rerandomisation<EncryptionKey<I>, Ciphertext<I>>, I: One, for<'a,'b> &'a I: Add<&'b I, Output=I>, for<'a> &'a I: Mul<I, Output=I>, for<'a,'b> &'a I: Mul<&'b I, Output=I>, for<'b> I: Rem<&'b I, Output=I>, { fn encrypt(ek: &EncryptionKey<I>, m: &Plaintext<I>) -> Ciphertext<I> { // here we assume that g = n+1 let nm = &m.0 * &ek.n; let gx = (&nm + &I::one()) % &ek.nn; Self::rerandomise(ek, &Ciphertext(gx)) } } impl<I, S> Addition<EncryptionKey<I>, Ciphertext<I>, Ciphertext<I>, Ciphertext<I>> for S where S: AbstractScheme<BigInteger=I>, for<'a,'b> &'a I: Mul<&'b I, Output=I>, for<'b> I: Rem<&'b I, Output=I>, { fn add(ek: &EncryptionKey<I>, c1: &Ciphertext<I>, c2: &Ciphertext<I>) -> Ciphertext<I> { let c = (&c1.0 * &c2.0) % &ek.nn; Ciphertext(c) } } impl<I, S> Multiplication<EncryptionKey<I>, Ciphertext<I>, Plaintext<I>, Ciphertext<I>> for S where S: AbstractScheme<BigInteger=I>, I: ModPow, { fn mul(ek: &EncryptionKey<I>, c1: &Ciphertext<I>, m2: &Plaintext<I>) -> Ciphertext<I> { let c = I::modpow(&c1.0, &m2.0, &ek.nn); Ciphertext(c) } } impl<I, S> Decryption<DecryptionKey<I>, Ciphertext<I>, Plaintext<I>> for S where S: AbstractScheme<BigInteger=I>, I: One, I: ModPow, for<'a> &'a I: Sub<I, Output=I>, for<'b> I: Mul<&'b I, Output=I>, for<'b> I: Div<&'b I, Output=I>, for<'a> I: Rem<&'a I, Output=I>, { fn decrypt(dk: &DecryptionKey<I>, c: &Ciphertext<I>) -> Plaintext<I> { let u = I::modpow(&c.0, &dk.lambda, &dk.nn); let m = (l(&u, &dk.n) * &dk.mu) % &dk.n; Plaintext(m) } }
//! Provides methods for gathering net informations, //! use super::{result::*, util::*}; use sigar_sys::*; use std::error::Error as stdError; use std::ffi::{CStr, CString}; use std::net; use std::os::raw::{c_int, c_ulong}; // C: sigar_net_info_get /// net info #[derive(Debug)] pub struct Info { pub default_gateway: Vec<u8>, pub default_gateway_interface: Vec<u8>, pub host_name: Vec<u8>, pub domain_name: Vec<u8>, pub primary_dns: Vec<u8>, pub secondary_dns: Vec<u8>, } /// Returns net info pub fn info() -> SigarResult<Info> { let raw = ffi_wrap!(sigar_net_info_get, sigar_net_info_t)?; Ok(Info { default_gateway: chars_to_bytes(&raw.default_gateway[..]), default_gateway_interface: chars_to_bytes(&raw.default_gateway_interface[..]), host_name: chars_to_bytes(&raw.host_name[..]), domain_name: chars_to_bytes(&raw.domain_name[..]), primary_dns: chars_to_bytes(&raw.primary_dns[..]), secondary_dns: chars_to_bytes(&raw.secondary_dns[..]), }) } // C: sigar_net_route_list_get #[derive(Debug)] pub enum AFFamily { UNSPEC, INET, INET6, LINK, } impl AFFamily { #[allow(non_upper_case_globals)] fn from_raw(raw: sigar_net_address_t__bindgen_ty_1) -> Self { match raw { sigar_net_address_t_SIGAR_AF_INET => AFFamily::INET, sigar_net_address_t_SIGAR_AF_INET6 => AFFamily::INET6, sigar_net_address_t_SIGAR_AF_LINK => AFFamily::LINK, _ => AFFamily::UNSPEC, } } } #[derive(Debug)] pub struct Address { inet4: net::Ipv4Addr, inet6: net::Ipv6Addr, mac: [u8; 8usize], } impl Address { fn from_raw(raw: &sigar_net_address_t__bindgen_ty_2) -> Address { const MASK_U16: u32 = !(0u32) >> 16; unsafe { let in6: [u32; 4] = [ u32_reverse(raw.in6[0]), u32_reverse(raw.in6[1]), u32_reverse(raw.in6[2]), u32_reverse(raw.in6[3]), ]; Address { inet4: net::Ipv4Addr::from(u32_reverse(raw.in_)), inet6: net::Ipv6Addr::new( (in6[0] >> 16) as u16, (in6[0] & MASK_U16) as u16, (in6[1] >> 16) as u16, (in6[1] & MASK_U16) as u16, (in6[2] >> 16) as u16, (in6[2] & MASK_U16) as u16, (in6[3] >> 16) as u16, (in6[3] & MASK_U16) as u16, ), mac: raw.mac.clone(), } } } } #[derive(Debug)] pub struct NetAddress { pub family: AFFamily, pub address: Address, } impl NetAddress { fn from_raw(raw: &sigar_net_address_t) -> Self { NetAddress { family: AFFamily::from_raw(raw.family), address: Address::from_raw(&raw.addr), } } } #[derive(Debug)] pub struct Route { pub destination: NetAddress, pub gateway: NetAddress, pub mask: NetAddress, pub flags: u64, pub refcnt: u64, pub use_: u64, pub metric: u64, pub mtu: u64, pub window: u64, pub irtt: u64, pub ifname: Vec<u8>, } impl Route { fn from_raw(raw: &sigar_net_route_t) -> Self { value_convert!( Route, raw, flags, refcnt, use_, metric, mtu, window, irtt, (destination: NetAddress::from_raw(&raw.destination)), (gateway: NetAddress::from_raw(&raw.gateway)), (mask: NetAddress::from_raw(&raw.mask)), (ifname: chars_to_bytes(&raw.ifname[..])), ) } } pub fn route_list() -> SigarResult<Vec<Route>> { ffi_wrap_destroy!( sigar_net_route_list_get, sigar_net_route_list_destroy, sigar_net_route_list_t, (|list_t: &sigar_net_route_list_t| ffi_extract_list!( list_t, (|one: &sigar_net_route_t| Route::from_raw(one)) )) ) } // C: sigar_net_interface_config_get #[derive(Debug)] pub struct InterfaceConfig { pub name: Vec<u8>, pub type_: Vec<u8>, pub description: Vec<u8>, pub hwaddr: NetAddress, pub address: NetAddress, pub destination: NetAddress, pub broadcast: NetAddress, pub netmask: NetAddress, pub address6: NetAddress, pub prefix6_length: i32, pub scope6: i32, pub flags: u64, pub mtu: u64, pub metric: u64, pub tx_queue_len: i32, } impl InterfaceConfig { fn from_raw(raw: &sigar_net_interface_config_t) -> Self { value_convert!( InterfaceConfig, raw, prefix6_length, scope6, flags, mtu, metric, tx_queue_len, (name: chars_to_bytes(&raw.name[..])), (type_: chars_to_bytes(&raw.type_[..])), (description: chars_to_bytes(&raw.description[..])), (hwaddr: NetAddress::from_raw(&raw.hwaddr)), (address: NetAddress::from_raw(&raw.address)), (destination: NetAddress::from_raw(&raw.destination)), (broadcast: NetAddress::from_raw(&raw.broadcast)), (netmask: NetAddress::from_raw(&raw.netmask)), (address6: NetAddress::from_raw(&raw.address6)), ) } } /// Returns interface config for given name pub fn interface_config(name: &str) -> SigarResult<InterfaceConfig> { let name_ptr = CString::new(name).map_err(|e| Error::CString(e.description().to_string()))?; let raw = ffi_wrap!( sigar_net_interface_config_get, (name_ptr.as_ptr()), sigar_net_interface_config_t )?; Ok(InterfaceConfig::from_raw(&raw)) } // C: sigar_net_interface_config_primary_get /// Returns config for primary interface pub fn interface_config_primary() -> SigarResult<InterfaceConfig> { let raw = ffi_wrap!( sigar_net_interface_config_primary_get, sigar_net_interface_config_t )?; Ok(InterfaceConfig::from_raw(&raw)) } // C: sigar_net_interface_stat_get #[derive(Debug)] pub struct InterfaceStat { pub rx_packets: u64, pub rx_bytes: u64, pub rx_errors: u64, pub rx_dropped: u64, pub rx_overruns: u64, pub rx_frame: u64, pub tx_packets: u64, pub tx_bytes: u64, pub tx_errors: u64, pub tx_dropped: u64, pub tx_overruns: u64, pub tx_collisions: u64, pub tx_carrier: u64, pub speed: u64, } /// Returns interface stat for give name pub fn interface_stat(name: &str) -> SigarResult<InterfaceStat> { let name_ptr = CString::new(name).map_err(|e| Error::CString(e.description().to_string()))?; let raw = ffi_wrap!( sigar_net_interface_stat_get, (name_ptr.as_ptr()), sigar_net_interface_stat_t )?; Ok(value_convert!( InterfaceStat, raw, rx_packets, rx_bytes, rx_errors, rx_dropped, rx_overruns, rx_frame, tx_packets, tx_bytes, tx_errors, tx_dropped, tx_overruns, tx_collisions, tx_carrier, speed, )) } // C: sigar_net_interface_list_get /// Returns interface names pub fn interface_list() -> SigarResult<Vec<CString>> { ffi_wrap_destroy!( sigar_net_interface_list_get, sigar_net_interface_list_destroy, sigar_net_interface_list_t, (|list_ptr: &sigar_net_interface_list_t| ffi_extract_list!( list_ptr, (|one: &*mut ::std::os::raw::c_char| CStr::from_ptr(*one).to_owned()) )) ) } // C: sigar_net_connection_list_get // C: sigar_net_connection_list_destroy #[derive(Debug)] pub struct Conn { pub local_port: u64, pub local_address: NetAddress, pub remote_port: u64, pub remote_address: NetAddress, pub uid: u32, pub inode: u64, pub type_: ConnType, pub state: ConnSate, pub send_queue: u64, pub receive_queue: u64, } #[allow(non_camel_case_types)] #[derive(Debug)] pub enum ConnType { TCP, UDP, RAW, UNIX, UNKNOWN, } impl ConnType { fn from_raw(raw: c_int) -> Self { match raw as u32 { SIGAR_NETCONN_TCP => ConnType::TCP, SIGAR_NETCONN_UDP => ConnType::UDP, SIGAR_NETCONN_RAW => ConnType::RAW, SIGAR_NETCONN_UNIX => ConnType::UNIX, _ => ConnType::UNKNOWN, } } } #[allow(non_camel_case_types)] #[derive(Debug)] pub enum ConnSate { TCP_ESTABLISHED, TCP_SYN_SENT, TCP_SYN_RECV, TCP_FIN_WAIT1, TCP_FIN_WAIT2, TCP_TIME_WAIT, TCP_CLOSE, TCP_CLOSE_WAIT, TCP_LAST_ACK, TCP_LISTEN, TCP_CLOSING, TCP_IDLE, TCP_BOUND, TCP_UNKNOWN, } impl ConnSate { fn from_raw(raw: c_int) -> Self { match raw as u32 { SIGAR_TCP_ESTABLISHED => ConnSate::TCP_ESTABLISHED, SIGAR_TCP_SYN_SENT => ConnSate::TCP_SYN_SENT, SIGAR_TCP_SYN_RECV => ConnSate::TCP_SYN_RECV, SIGAR_TCP_FIN_WAIT1 => ConnSate::TCP_FIN_WAIT1, SIGAR_TCP_FIN_WAIT2 => ConnSate::TCP_FIN_WAIT2, SIGAR_TCP_TIME_WAIT => ConnSate::TCP_TIME_WAIT, SIGAR_TCP_CLOSE => ConnSate::TCP_CLOSE, SIGAR_TCP_CLOSE_WAIT => ConnSate::TCP_CLOSE_WAIT, SIGAR_TCP_LAST_ACK => ConnSate::TCP_LAST_ACK, SIGAR_TCP_LISTEN => ConnSate::TCP_LISTEN, SIGAR_TCP_CLOSING => ConnSate::TCP_CLOSING, SIGAR_TCP_IDLE => ConnSate::TCP_IDLE, SIGAR_TCP_BOUND => ConnSate::TCP_BOUND, SIGAR_TCP_UNKNOWN => ConnSate::TCP_UNKNOWN, _ => ConnSate::TCP_UNKNOWN, } } } impl Conn { fn from_raw(raw: &sigar_net_connection_t) -> Self { value_convert!( Conn, raw, local_port, remote_port, uid, inode, send_queue, receive_queue, (local_address: NetAddress::from_raw(&raw.local_address)), (remote_address: NetAddress::from_raw(&raw.remote_address)), (state: ConnSate::from_raw(raw.state)), (type_: ConnType::from_raw(raw.type_)), ) } } type Flag = u32; pub const FLAG_NETCONN_CLIENT: Flag = SIGAR_NETCONN_CLIENT; pub const FLAG_NETCONN_SERVER: Flag = SIGAR_NETCONN_SERVER; pub const FLAG_NETCONN_TCP: Flag = SIGAR_NETCONN_TCP; pub const FLAG_NETCONN_UDP: Flag = SIGAR_NETCONN_UDP; pub const FLAG_NETCONN_RAW: Flag = SIGAR_NETCONN_RAW; pub const FLAG_NETCONN_UNIX: Flag = SIGAR_NETCONN_UNIX; /// Returns all connections for given flags pub fn connection_list(flags: Flag) -> SigarResult<Vec<Conn>> { ffi_wrap_destroy!( (|ptr: *mut sigar_t, connlist: *mut sigar_net_connection_list_t| { sigar_net_connection_list_get(ptr, connlist, flags as c_int) }), sigar_net_connection_list_destroy, sigar_net_connection_list_t, (|list_ptr: &sigar_net_connection_list_t| ffi_extract_list!( list_ptr, (|one: &sigar_net_connection_t| Conn::from_raw(one)) )) ) } // C: sigar_net_stat_get #[derive(Debug)] pub struct Stat { pub tcp_states: [i32; 14usize], pub tcp_inbound_total: u32, pub tcp_outbound_total: u32, pub all_inbound_total: u32, pub all_outbound_total: u32, } impl Stat { fn from_raw(raw: &sigar_net_stat_t) -> Self { let mut tcp_states: [i32; 14usize] = [0; 14usize]; let mut i = 0usize; while i < 14 { tcp_states[i] = raw.tcp_states[i] as i32; i += 1; } value_convert!( Stat, raw, tcp_inbound_total, tcp_outbound_total, all_inbound_total, all_outbound_total, (tcp_states: tcp_states), ) } } /// Returns connection stat summary for given flags pub fn stat_get(flags: Flag) -> SigarResult<Stat> { let raw = ffi_wrap!( (|sigar: *mut sigar_t, netstat: *mut sigar_net_stat_t| sigar_net_stat_get( sigar, netstat, flags as c_int )), sigar_net_stat_t )?; Ok(Stat::from_raw(&raw)) } // C: sigar_net_listen_address_get /// Returns the bind address for a given port pub fn listen_address_get(port: u64) -> SigarResult<NetAddress> { let raw = ffi_wrap!( sigar_net_listen_address_get, (port as c_ulong), sigar_net_address_t )?; Ok(NetAddress::from_raw(&raw)) } // TODO: // C: sigar_net_connection_walk // C: sigar_net_stat_port_get // C: sigar_net_address_equals // C: sigar_net_address_to_string // C: sigar_net_scope_to_string // C: sigar_net_address_hash // C: sigar_net_connection_type_get // C: sigar_net_connection_state_get // C: sigar_net_interface_flags_to_string // C: sigar_net_services_name_get
pub mod drawing; pub mod hexlife; pub mod power; use crate::prelude::*; pub trait App { fn new() -> Self; fn tick(&mut self, led_data: &mut [RGB8; NUM_LEDS]); }
//! Testing helpers. pub mod addresses { pub mod alice { use crate::address::Address; pub fn address() -> Address { Address::from_bech32("oasis1qrec770vrek0a9a5lcrv0zvt22504k68svq7kzve").unwrap() } } pub mod bob { use crate::address::Address; pub fn address() -> Address { Address::from_bech32("oasis1qrydpazemvuwtnp3efm7vmfvg3tde044qg6cxwzx").unwrap() } } pub mod charlie { use crate::address::Address; pub fn address() -> Address { Address::from_bech32("oasis1qr5kfjm8lx6mctjmwcx9225q5k3nxacqwqnjahkw").unwrap() } } pub mod dave { use crate::address::Address; pub fn address() -> Address { Address::from_bech32("oasis1qpufkctqruam5umugwn5jvxtrvvwl075rqrmxqmm").unwrap() } } }
use crate::exchange::order_processing::JsonOrder; use crate::exchange::queue::Queue; use crate::controller::Task; use tokio::net::{TcpListener, TcpStream}; use tokio::prelude::*; use std::sync::Arc; /// A simple tcp server that listens for incoming messages asynchronously. Each message /// is parsed from a JSON into the internal Order type used in the exchange. This function /// returns an AsnycTask to be used by the Controller module running Tokio. pub fn tcp_listener(queue: Arc<Queue>, address: String) -> Task { // Bind a TcpListener to a local port let addr = address.parse().unwrap(); let listener = TcpListener::bind(&addr).unwrap(); println!("Running server on {}", addr); // start a tcp server that accepts JSON objects let tcp_server = listener.incoming().for_each(move |socket| { // Clone the queue into the closure let queue = Arc::clone(&queue); // Deserialize the stream from the socket let deserialized = JsonOrder::deserialize(socket).map_err(|e| println!("ERR: {:?}", e)); // Spawn a task that converts JSON to an Order and adds to queue tokio::spawn(deserialized.for_each(move |msg| { JsonOrder::process_new(msg, Arc::clone(&queue)); Ok(()) })); Ok(()) }) .map_err(|_| ()); Task { task: Box::new(tcp_server), } } /// Creates an asynchronous task that opens a TCP connection and sends a JSON order pub fn tcp_send_json(json: serde_json::Value, address: String) -> Task{ // let (t_id, ot, tt, pl, ph, u) = order_params; // Creates a JSON from a reference of an order and sends it over TCP let addr = address.parse().unwrap(); let client = TcpStream::connect(&addr).and_then(move |socket| { // Make a new json writer let serialized = JsonOrder::serializer(socket); // Send the value serialized .send(json).map(|_| ()) }).map_err(|_| ()); Task { task: Box::new(client), } }
//! This module contains the set of software rendering tools used for this application. //! Text rendering, simple shape, and bitmap rendering is provided here. //! //! This module contains functions that draws directly to the provided canvas. //! All draw calls are done directly using the cpu. If you wish to use the gpu for rendering //! you will need to set it up yourself then paint it to the canvas. //! //! //! //! The interface is pixel based, with the origin at bottom left corner of the canvas. //! The example below shows how to draw a rectangle to WindowCanvas provided outside of this snips //! context. `C4_BLACK` is a const provided by the module for convenience. //! This example will draw a black rectangle, who's bottom left corner will inhabit canvas coordinate of //! (10, 10). The rectangle will be 50 pixels by 50 pixels. //! # Examples //! ``` //! pub fn example_program(os_package: &mut OsPackage, keyboardinfo: &KeyboardInfo, //! textinfo: &TextInfo, //! mouseinfo: &MouseInfo){ //! let canvas = &mut os_package.window_canvas; //! let rect = [10, 10, 50, 50]; //! draw_rect(canvas, rect, C4_BLACK, true); //! } //! ``` //! //! Images can be drawn in a similar fashion. `draw_bmp`, or `draw_stbi_image` are given for this //! purpose. `draw_bmp` is used when working with TGBitmap structs. TGBitmaps are this frame //! works bitmap structure. It must be noted that not all bitmap type are supported in with this //! format. `draw_stbi_image` should be used when working with most files as most files are //! supported through the stbi_image library. //! //! #![allow(unused)] #[macro_use] use crate::{timeit, DEBUG_timeit}; use crate::debug_tools::*; use crate::WindowCanvas; use crate::{null, null_mut}; use crate::stb_tt_sys::*; pub use crate::stb_image_sys::*; use std::fs::File; use std::io::prelude::*; pub const C4_WHITE :[f32;4] = [1.0, 1.0, 1.0, 1.0]; pub const C4_BLACK :[f32;4] = [0.0, 0.0, 0.0, 1.0]; pub const C4_GREY :[f32;4] = [0.5, 0.5, 0.5, 1.0]; pub const C4_LGREY :[f32;4] = [0.8, 0.8, 0.8, 1.0]; pub const C4_DGREY :[f32;4] = [0.2, 0.2, 0.2, 1.0]; pub const C4_BLUE :[f32;4] = [0.0, 0.0, 1.0, 1.0]; pub const C4_RED :[f32;4] = [1.0, 0.0, 0.0, 1.0]; pub const C4_GREEN :[f32;4] = [0.0, 1.0, 0.0, 1.0]; pub const C4_YELLOW :[f32;4] = [1.0, 1.0, 0.0, 1.0]; pub const C4_MAGENTA :[f32;4] = [1.0, 0.0, 1.0, 1.0]; pub const C4_CYAN :[f32;4] = [0.0, 1.0, 1.0, 1.0]; pub const C4_PURPLE :[f32;4] = [0.5, 0.0, 0.5, 1.0]; pub const C4_CREAM :[f32;4] = [1.0, 0.99, 0.82, 1.0]; pub const C4_DGREEN :[f32;4] = [0.0, 0.39, 0.0, 1.0]; pub const C4_MGREEN :[f32;4] = [0.0, 0.5, 0.0, 1.0]; pub const C3_WHITE :[f32;3] = [1.0, 1.0, 1.0]; pub const C3_BLACK :[f32;3] = [0.0, 0.0, 0.0]; pub const C3_GREY :[f32;3] = [0.5, 0.5, 0.5]; pub const C3_LGREY :[f32;3] = [0.8, 0.8, 0.8]; pub const C3_DGREY :[f32;3] = [0.2, 0.2, 0.2]; pub const C3_BLUE :[f32;3] = [0.0, 0.0, 1.0]; pub const C3_RED :[f32;3] = [1.0, 0.0, 0.0]; pub const C3_GREEN :[f32;3] = [0.0, 1.0, 0.0]; pub const C3_YELLOW :[f32;3] = [1.0, 1.0, 0.0]; pub const C3_PURPLE :[f32;3] = [1.0, 0.0, 1.0]; pub const C3_CYAN :[f32;3] = [0.0, 1.0, 1.0]; pub const C3_CREAM :[f32;3] = [1.0, 0.99, 0.82]; pub const C3_DGREEN :[f32;3] = [0.0, 0.39, 0.0]; pub const C3_MGREEN :[f32;3] = [0.0, 0.6, 0.0]; pub const DPMM_SCALE : f32 = 3.8; pub const DPMM_TOLERANCE : f32 = 0.2; use std::collections::HashMap; static mut GLOBAL_FONTINFO : stbtt_fontinfo = new_stbtt_fontinfo(); static mut FONT_BUFFER : Option<Vec<u8>> = Some(Vec::new()); static mut FONT_GLYPH_HASHMAP : Option<HashMap<usize, HashMap<(char, u32), Vec<u8>>>> = None; static mut CURRENT_KEY : usize = 0; ///Returns an array of length 4 that is the composite of the input array and alpha. /// /// # Example /// ``` /// let v = [1f32, 0.5f32, 0.1f32]; /// let a = 0.5f32; /// /// let v_a = [1f32, 0.5f32, 0.1f32, 0.5f32]; /// assert_eq!(c3_to_c4(v, a), v_a); /// ``` #[inline] pub fn c3_to_c4(c3: [f32; 3], alpha: f32)->[f32; 4]{ [c3[0], c3[1], c3[2], alpha] } /// Updates the static font buffer using the buffer provided. /// Returns a result indicating if the function succeeded. /// Note: This is not thread safe. Additionally, if the user /// constantly un(re)loading the same font files the user will /// incur performance penalties. pub fn change_font(buffer: &[u8])->Result<(), &str>{unsafe{ let font_glypth_hashmap = match FONT_GLYPH_HASHMAP.as_mut(){ Some(fgh)=>{ fgh }, None=>{ FONT_GLYPH_HASHMAP = Some( HashMap::with_capacity(10) ); FONT_GLYPH_HASHMAP.as_mut().unwrap() }, }; let key = buffer.as_ptr() as usize; CURRENT_KEY = key; if !font_glypth_hashmap.contains_key( &key ){ font_glypth_hashmap.insert( key, HashMap::with_capacity(100) ); } //NOTE TKG. We are using the original buffer pointer to hash. If the user continuously reloads from //disk this will will become a problem. let font_buffer_ref = match FONT_BUFFER.as_mut(){ Some(fb)=>{ fb.clear(); fb }, None=>{ FONT_BUFFER = Some(Vec::with_capacity(buffer.len())); FONT_BUFFER.as_mut().unwrap() } }; font_buffer_ref.extend_from_slice(buffer); if stbtt_InitFont(&mut GLOBAL_FONTINFO as *mut stbtt_fontinfo, font_buffer_ref.as_ptr(), 0) == 0{ println!("font was not able to load."); return Err("Font was not able to be loaded."); } return Ok(()); }} /// Returns the pixel width of the character. pub fn get_advance(character: char, size: f32)->i32{unsafe{ if GLOBAL_FONTINFO.data == null_mut() { println!("Global font has not been set."); return -1; } let mut adv = 0; let scale = stbtt_ScaleForPixelHeight(&GLOBAL_FONTINFO as *const stbtt_fontinfo, size); let glyph_index = stbtt_FindGlyphIndex(&GLOBAL_FONTINFO as *const stbtt_fontinfo, character as i32); stbtt_GetGlyphHMetrics(&GLOBAL_FONTINFO as *const stbtt_fontinfo, glyph_index, &mut adv as *mut i32, null_mut()); return (adv as f32 * scale) as i32; }} /// Returns the pixel width of the provided string. pub fn get_advance_string( string: &str, size: f32 )->i32{ let mut offset = 0; for it in string.chars(){ offset += get_advance(it, size); } return offset; } /// Draws the provided character to the canvas. `size` is rounded to the nearest integer. /// Returns character width in pixels. pub fn draw_char( canvas: &mut WindowCanvas, character: char, mut x: i32, mut y: i32, color: [f32; 4], mut size: f32 )->i32{unsafe{ //NOTE Check that globalfontinfo has been set if GLOBAL_FONTINFO.data == null_mut() { println!("Global font has not been set."); return -1; } let canvas_dpmm = if canvas.dpmm == 0f32 { DPMM_SCALE } else { canvas.dpmm }; let mut dpmm_ratio = 1f32;//canvas_dpmm / DPMM_SCALE; if (1f32 - dpmm_ratio).abs() < DPMM_TOLERANCE { dpmm_ratio = 1f32; } size = size.round(); let dpmm_size = (dpmm_ratio * size).round(); x = (dpmm_ratio * x as f32).round() as _; y = (dpmm_ratio * y as f32).round() as _; //Construct a char buffer let mut char_buffer; let cwidth; let cheight; let scale; { let mut x0 = 0i32; let mut x1 = 0i32; let mut y0 = 0i32; let mut y1 = 0i32; let mut ascent = 0; let mut descent = 0; stbtt_GetFontVMetrics(&mut GLOBAL_FONTINFO as *mut stbtt_fontinfo, &mut ascent as *mut i32, &mut descent as *mut i32, null_mut()); scale = stbtt_ScaleForPixelHeight(&GLOBAL_FONTINFO as *const stbtt_fontinfo, dpmm_size); let baseline = (ascent as f32 * scale ) as i32; cwidth = (scale * (ascent - descent) as f32 ) as usize + 4; //NOTE buffer term should be reduced. cheight = (scale * (ascent - descent) as f32 ) as usize + 4;//NOTE buffer term should be reduced. let glyph_index = stbtt_FindGlyphIndex(&GLOBAL_FONTINFO as *const stbtt_fontinfo, character as i32); char_buffer = match &mut FONT_GLYPH_HASHMAP{ Some(fbh)=>{ match fbh.get_mut(&CURRENT_KEY){ Some(font)=>{ match font.get(&(character, size as u32)){ Some(gi)=> { //NOTE //Sets the previously rendered monotone character bmp. gi }, None=>{ //NOTE //Generates a monotone character bmp and stores it in the hashmap. //The results of the render are returned. let mut _char_buffer = vec![0u8; cwidth * cheight]; stbtt_GetGlyphBitmapBoxSubpixel(&GLOBAL_FONTINFO as *const stbtt_fontinfo, glyph_index, scale, scale, 0.0,0.0, &mut x0 as *mut i32, &mut y0 as *mut i32, &mut x1 as *mut i32, &mut y1 as *mut i32); stbtt_MakeGlyphBitmapSubpixel( &GLOBAL_FONTINFO as *const stbtt_fontinfo, &mut _char_buffer[cwidth*(baseline + y0) as usize + (5 + x0) as usize ] as *mut u8, x1-x0+2, y1-y0, cwidth as i32, scale, scale,0.0, 0.0, glyph_index); font.insert((character, size as u32), _char_buffer); font.get(&(character, size as u32)).as_ref().unwrap() } } }, None=>{ panic!("FONT_GLYPH_HASHMAP does not recognize font."); } } }, None=>{ panic!("FONT_GLYPH_HASHMAP has not been init."); } }; } //NOTE //The character will not render if invisible. if character as u8 > 0x20{ //render char_buffer to main_buffer let buffer = canvas.buffer as *mut u32; let gwidth = canvas.w as isize; let gheight = canvas.h as isize; let offset = (x as isize + y as isize * gwidth); let instance = std::time::Instant::now(); let width_mod_4 = cwidth % 4; let a = color[3]; let orig_r = (color[0] * a); let orig_g = (color[1] * a); let orig_b = (color[2] * a); //NOTE simd feature. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] //if false { if is_x86_feature_detected!("sse2") {unsafe{ if true { if is_x86_feature_detected!("sse2") {unsafe{ //panic!("TODO {} {}", buffer as usize , buffer as usize & 15); //timeit!{{ #[cfg(target_arch = "x86_64")] use std::arch::x86_64::*; #[cfg(target_arch = "x86")] use std::arch::x864::*; let orig_r = _mm_set1_ps(orig_r); let orig_g = _mm_set1_ps(orig_g); let orig_b = _mm_set1_ps(orig_b); let mut simd_dst_r = _mm_set1_ps(0f32); let mut simd_dst_g = _mm_set1_ps(0f32); let mut simd_dst_b = _mm_set1_ps(0f32); let mut simd_r = _mm_set1_ps(0f32); let mut simd_g = _mm_set1_ps(0f32); let mut simd_b = _mm_set1_ps(0f32); let mut simd_a = _mm_set1_ps(a); let mut simd_invert_255 = _mm_set1_ps(1./255.); let mut simd_one = _mm_set1_ps(1f32); let mut simd_tmp_r = _mm_set1_ps(0f32); let mut simd_tmp_g = _mm_set1_ps(0f32); let mut simd_tmp_b = _mm_set1_ps(0f32); let mut simd_dst = _mm_set1_epi32(0); let simd_mask_rule_char_length = _mm_set1_epi32(char_buffer.len() as i32); let simd_mask_rule_width = _mm_set1_epi32(gwidth as i32); let mut text_alpha = [0f32;4]; for i in 0..cheight as isize{ if i + y as isize >= gheight {continue;} if i + y as isize <= 0 {continue;} for j in (0..cwidth as isize).step_by(4){ let mut mask = _mm_set1_epi32(0); let simd_buffer = buffer.offset( (j as isize + i*gwidth + offset) as isize ) as *mut _; simd_dst = _mm_loadu_si128(simd_buffer); //NOTE //simd mask implementation is WAY slower than looped equivilent and I'm not //sure why. There are three compare operations and two ands. Compared to the 12 //compares and 4 sets done in a loop one would think simd would be faster. More //exploration is required. //let j_plus_x = j as i32 + x; //let simd_mask_rule_gindex = _mm_set_epi32(j_plus_x + 3, // j_plus_x + 2, // j_plus_x + 1, // j_plus_x + 0); //let char_index_i32 = j as i32 + cwidth as i32 * (cheight as i32 - 1 - i as i32); //let simd_mask_rule_cindex = _mm_set_epi32(char_index_i32 + 3, // char_index_i32 + 2, // char_index_i32 + 1, // char_index_i32 + 0); //mask = _mm_cmplt_epi32(simd_mask_rule_gindex, simd_mask_rule_width); //mask = _mm_and_si128( mask, _mm_cmpgt_epi32(simd_mask_rule_gindex, _mm_setzero_si128()) ); //mask = _mm_and_si128( mask, _mm_cmplt_epi32(simd_mask_rule_cindex, simd_mask_rule_char_length) ); for _j in 0..4{ if j + _j + x as isize > gwidth {continue;} if j + _j + x as isize <= 0 {continue;} let _j = _j as isize; let dst_rgb = buffer.offset( (j+_j + i*gwidth + offset) as isize); let _j = _j as usize; let dst_r : &mut [f32; 4] = std::mem::transmute(&mut simd_dst_r); let dst_g : &mut [f32; 4] = std::mem::transmute(&mut simd_dst_g); let dst_b : &mut [f32; 4] = std::mem::transmute(&mut simd_dst_b); dst_r[_j] = *(dst_rgb as *const u8).offset(2) as f32; dst_g[_j] = *(dst_rgb as *const u8).offset(1) as f32; dst_b[_j] = *(dst_rgb as *const u8).offset(0) as f32; let _j = _j as usize; if (j as usize + _j) + cwidth * (cheight - 1 - i as usize) >= char_buffer.len() { continue; } text_alpha[_j] = char_buffer[(j as usize +_j) as usize + cwidth * (cheight - 1 - i as usize)] as f32; let r : &mut [f32; 4] = std::mem::transmute(&mut simd_r); let g : &mut [f32; 4] = std::mem::transmute(&mut simd_g); let b : &mut [f32; 4] = std::mem::transmute(&mut simd_b); r[_j] = text_alpha[_j]; g[_j] = text_alpha[_j]; b[_j] = text_alpha[_j]; let _mask: &mut [u32; 4] = std::mem::transmute(&mut mask); _mask[_j] = 0xFF_FF_FF_FF; } simd_tmp_r = _mm_mul_ps(simd_r, simd_invert_255); simd_tmp_g = _mm_mul_ps(simd_g, simd_invert_255); simd_tmp_b = _mm_mul_ps(simd_b, simd_invert_255); simd_tmp_r = _mm_mul_ps(simd_tmp_r, simd_a); simd_tmp_g = _mm_mul_ps(simd_tmp_g, simd_a); simd_tmp_b = _mm_mul_ps(simd_tmp_b, simd_a); simd_tmp_r = _mm_sub_ps(simd_one, simd_tmp_r); simd_tmp_g = _mm_sub_ps(simd_one, simd_tmp_g); simd_tmp_b = _mm_sub_ps(simd_one, simd_tmp_b); simd_dst_r = _mm_mul_ps(simd_tmp_r, simd_dst_r); simd_dst_g = _mm_mul_ps(simd_tmp_g, simd_dst_g); simd_dst_b = _mm_mul_ps(simd_tmp_b, simd_dst_b); simd_r = _mm_mul_ps(simd_r, orig_r); simd_g = _mm_mul_ps(simd_g, orig_g); simd_b = _mm_mul_ps(simd_b, orig_b); simd_dst_r = _mm_add_ps(simd_r, simd_dst_r); simd_dst_g = _mm_add_ps(simd_g, simd_dst_g); simd_dst_b = _mm_add_ps(simd_b, simd_dst_b); //NOTE converting from float to int for color channels let mut simd_dst_r_u32 = _mm_cvtps_epi32(simd_dst_r); simd_dst_r_u32 = _mm_slli_epi32(simd_dst_r_u32, 16); let mut simd_dst_g_u32 = _mm_cvtps_epi32(simd_dst_g); simd_dst_g_u32 = _mm_slli_epi32(simd_dst_g_u32, 8); let mut simd_dst_b_u32 = _mm_cvtps_epi32(simd_dst_b); //NOTE combining color channels let mut simd_rgba = _mm_or_si128(_mm_or_si128(simd_dst_r_u32, simd_dst_g_u32), simd_dst_b_u32); //NOTE applying pixel mask. simd_rgba = _mm_or_si128( _mm_and_si128(mask, simd_rgba), _mm_andnot_si128(mask, simd_dst)); _mm_storeu_si128(simd_buffer, simd_rgba); } } //}}//DEBUG REMOVE ME //TODO redundant with return at the end of function. //we should call the same code to avoid issues. let mut adv : i32 = 0; let mut lft_br : i32 = 0; // NOTE: Maybe remove this stbtt_GetCodepointHMetrics(&GLOBAL_FONTINFO as *const stbtt_fontinfo, character as i32, &mut adv as *mut i32, &mut lft_br as *mut i32); return (adv as f32 * scale) as i32; }}} let y_is = y as isize; let x_is = x as isize; for i in 0..cheight as isize{ if i + y_is > gheight {continue;} if i + y_is <= 0 {continue;} for j in 0..cwidth as isize{ if (j + i*gwidth + offset) > gwidth * gheight {continue;} if j + x_is > gwidth {continue;} if j + x_is <= 0 {continue;} let mut text_alpha = char_buffer[j as usize + cwidth * (cheight - 1 - i as usize)] as f32; let r = (orig_r * text_alpha) as u32; let g = (orig_g * text_alpha) as u32; let b = (orig_b * text_alpha) as u32; let dst_rgb = buffer.offset( (j + i*gwidth + offset) as isize); text_alpha = (255.0 - text_alpha * a) / 255.0; let _r = (*(dst_rgb as *const u8).offset(2) as f32 * text_alpha ) as u32; let _g = (*(dst_rgb as *const u8).offset(1) as f32 * text_alpha ) as u32; let _b = (*(dst_rgb as *const u8).offset(0) as f32 * text_alpha ) as u32; *buffer.offset( (j + i*gwidth + offset) as isize) = 0x00000000 + (r+_r << 16) + (g+_g << 8) + b+_b;// + (final_alpha << 24); } } } let mut adv : i32 = 0; let mut lft_br : i32 = 0; // NOTE: Maybe remove this stbtt_GetCodepointHMetrics(&GLOBAL_FONTINFO as *const stbtt_fontinfo, character as i32, &mut adv as *mut i32, &mut lft_br as *mut i32); return (adv as f32 * scale) as i32; }} /// Draws the string to the canvas provided. Returns string width in pixels. /// Position values x and y are indicate where the string will begin. /// NOTE there is about a 4 pixel buffer between x and the first pixel the function is able to draw /// to. pub fn draw_string( canvas: &mut WindowCanvas, string: &str, x: i32, y: i32, color: [f32; 4], size: f32 )->i32{ let mut offset = 0; //DEBUG_timeit!{"draw_string",{ for it in string.chars(){ offset += draw_char(canvas, it, x + offset, y, color, size); } //}} return offset; } /// Draws rectangle to the canvas provided. The dimensions of the rectangle should be given as follows /// [x, y, width, height]. x, and y are associated with the bottom left corner of the rectangle. pub fn draw_rect( canvas: &mut WindowCanvas, rect: [i32; 4], color: [f32; 4], filled: bool ){unsafe{ //TODO //- Set alpha on dst canvas use both dst and src to determine alpha //DEBUG_timeit!{"draw_rect", { let buffer = canvas.buffer as *mut u32; let c_w = canvas.w as isize; let c_h = canvas.h as isize; let canvas_dpmm = if canvas.dpmm == 0f32 { DPMM_SCALE } else { canvas.dpmm }; let mut dpmm_ratio = 1f32; //canvas_dpmm / DPMM_SCALE; if (1f32 - dpmm_ratio).abs() < DPMM_TOLERANCE { dpmm_ratio = 1f32; } let x = ( dpmm_ratio * rect[0] as f32 ).round() as isize + 1; //NOTE 1 is here to remove wrapping TODO let y = ( dpmm_ratio * rect[1] as f32 ).round() as isize; let _x = if x < 0 { 0 } else { x }; let _y = if y < 0 { 0 } else { y }; let w = (dpmm_ratio * rect[2] as f32) as isize; let h = (dpmm_ratio * rect[3] as f32) as isize; let _w = if x + w > c_w { c_w - x } else if x < 0 { x + w } else {w}; let _h = if y + h > c_h { c_h - y } else if y < 0 { y + h } else {h}; let a = color[3]; let r = (color[0] * a * 255.0) as u32; let g = (color[1] * a * 255.0) as u32; let b = (color[2] * a * 255.0) as u32; let one_minus_a = 1f32 - a; if x + w < 0 { return; } if y + h < 0 { return; } if x < c_w && y < c_h{ //TODO this is not correct } else { return; } if a >= 0.99 && filled == true{ let mut fast_rgba_buffer = vec![0x00000000 + (r << 16) + (g << 8) + b; _w as usize]; for _j in _y.._y+_h{ let j = _j as isize; std::ptr::copy::<u32>(fast_rgba_buffer.as_ptr(), buffer.offset(c_w*j + _x), _w as usize); } } else{ if filled == false { //Loop for non filled rect for _j in y..y+h{ let j = _j as isize; for _i in x..x+w{ let i = _i as isize; if i > c_w || j > c_h{ continue; } let dst_index = (i + c_w*j) as isize; let dst_rgb = buffer.offset(dst_index); let _r = (*(dst_rgb as *const u8).offset(2) as f32 * one_minus_a) as u32; let _g = (*(dst_rgb as *const u8).offset(1) as f32 * one_minus_a) as u32; let _b = (*(dst_rgb as *const u8).offset(0) as f32 * one_minus_a) as u32; if (_i - x) > 1 && (_i - x ) < w-2 && (_j - y) > 1 && (_j - y ) < h-2{continue;} *buffer.offset(dst_index) = 0x00000000 + (r+_r << 16) + (g+_g << 8) + b+_b; } } } else { //TODO //simd this for _j in _y.._y+_h{ let j = _j as isize; for _i in x..x+_w{ let i = _i as isize; let dst_index = (i + c_w*j) as isize; let dst_rgb = buffer.offset(dst_index); let _r = (*(dst_rgb as *const u8).offset(2) as f32 * one_minus_a) as u32; let _g = (*(dst_rgb as *const u8).offset(1) as f32 * one_minus_a) as u32; let _b = (*(dst_rgb as *const u8).offset(0) as f32 * one_minus_a) as u32; *buffer.offset(dst_index) = 0x00000000 + (r+_r << 16) + (g+_g << 8) + b+_b;; } } } } //}} }} #[derive(Clone, Debug, Copy)] pub struct TGBitmapHeaderInfo{ pub header_size: u32, pub width: i32, pub height: i32, pub planes: u16, pub bit_per_pixel: u16, pub compression: u32, pub image_size: u32, pub x_px_per_meter: i32, pub y_px_per_meter: i32, pub colors_used: u32, pub colors_important: u32, } #[repr(packed)] #[derive(Clone, Debug, Default, Copy)] pub struct TGBitmapFileHeader{ pub type_: u16, pub size_: u32, pub reserved_1: u16, pub reserved_2: u16, pub off_bits: u32, } #[derive(Clone)] pub struct TGBitmap{ pub file_header: TGBitmapFileHeader, pub info_header: TGBitmapHeaderInfo, pub rgba: Vec<u8>, //For ease of use pub width : i32, pub height : i32, } impl TGBitmap{ ///Generates a new bitmap of the given width and height. pub fn new(w: i32, h: i32)->TGBitmap{ TGBitmap{ file_header: TGBitmapFileHeader{ type_: 0x4d42, //BM size_: 0, reserved_1: 0, reserved_2: 0, off_bits: 0, }, info_header: TGBitmapHeaderInfo{ header_size: 54,//TODO width: w, height: h, planes: 1, bit_per_pixel: 32, compression: 0, image_size: 0, x_px_per_meter: 0, y_px_per_meter: 0, colors_used: 0, colors_important: 0, }, rgba: vec![0;4 * (w*h) as usize], width : w, height : h, } } ///Generates a new bitmap from a bitmap stored directly in memory. ///This functions copies data. ///NOTE: this is not the most efficient system. We are double the amount of memory we use ///and that may not be necessary. pub fn from_buffer(img_buffer: &[u8])->TGBitmap{unsafe{//TODO this is not the way we should switch to STB let mut rt = TGBitmap::new(0,0); let it = img_buffer.as_ptr() as *const u8; rt.file_header.type_ = *(it.offset(0) as *const u16);// == 0x42; rt.file_header.size_ = *(it.offset(2) as *const u32); rt.file_header.reserved_1 = *(it.offset(6) as *const u16); rt.file_header.reserved_2 = *(it.offset(8) as *const u16); rt.file_header.off_bits = *(it.offset(10) as *const u32); rt.info_header.header_size = *(it.offset(14) as *const u32); rt.info_header.width = *(it.offset(18) as *const i32); rt.info_header.height = *(it.offset(22) as *const i32); rt.info_header.planes = *(it.offset(26) as *const u16); rt.info_header.bit_per_pixel = *(it.offset(28) as *const u16); rt.info_header.compression = *(it.offset(30) as *const u32); rt.info_header.image_size = *(it.offset(34) as *const u32); rt.info_header.x_px_per_meter = *(it.offset(38) as *const i32); rt.info_header.y_px_per_meter = *(it.offset(42) as *const i32); rt.info_header.colors_used = *(it.offset(46) as *const u32); rt.info_header.colors_important = *(it.offset(50) as *const u32); let buffer = img_buffer[rt.file_header.off_bits as usize ..].to_vec(); rt.rgba = buffer; rt.width = rt.info_header.width; rt.height = rt.info_header.height; return rt; }} ///Generates a bmp from a file found in the given path. ///The function panics if file is not found. pub fn load_bmp(filename: &str)->TGBitmap{unsafe{ let mut rt = TGBitmap::new(0,0); let mut f = File::open(filename).expect("BMP file could not be opened."); let mut img_buffer = Vec::new(); f.read_to_end(&mut img_buffer).expect("Buffer could not be read."); rt = TGBitmap::from_buffer(&img_buffer); return rt; }} ///Write bmp to disk at given path. pub fn save_bmp(&self, filename: &str){unsafe{//TODO use std::mem::transmute; let filename = format!("{}", filename); let mut filebuffer = match File::create(filename){ Ok(_fb) => _fb, Err(_s) => { println!("BMP file could not be made. {}", _s); return; } }; { filebuffer.write( &transmute::<_, [u8; 2]>(self.file_header.type_) ).expect("BMP file_header.type could not be written."); filebuffer.write( &transmute::<_, [u8; 4]>(self.file_header.size_) ).expect("BMP file_header.size could not be written."); filebuffer.write( &transmute::<_, [u8; 2]>(self.file_header.reserved_1) ).expect("BMP file_header.reserverd_1 could not be written."); filebuffer.write( &transmute::<_, [u8; 2]>(self.file_header.reserved_2) ).expect("BMP file_header.reserved_2 could not be written."); filebuffer.write( &transmute::<_, [u8; 4]>(self.file_header.off_bits) ).expect("BMP file_header.off_bits could not be written."); } { filebuffer.write( &transmute::<_, [u8; 4]>(self.info_header.header_size) ).expect("BMP info_header.header_size could not be written."); filebuffer.write( &transmute::<_, [u8; 4]>(self.info_header.width) ).expect("BMP info_header.width could not be written."); filebuffer.write( &transmute::<_, [u8; 4]>(self.info_header.height) ).expect("BMP info_header.height could not be written."); filebuffer.write( &transmute::<_, [u8; 2]>(self.info_header.planes) ).expect("BMP info_header.planes could not be written."); filebuffer.write( &transmute::<_, [u8; 2]>(self.info_header.bit_per_pixel) ).expect("BMP info_header.bit_per_pixel could not be written."); filebuffer.write( &transmute::<_, [u8; 4]>(self.info_header.compression) ).expect("BMP info_header.compression could not be written."); filebuffer.write( &transmute::<_, [u8; 4]>(self.info_header.image_size) ).expect("BMP info_header.image_size could not be written."); filebuffer.write( &transmute::<_, [u8; 4]>(self.info_header.x_px_per_meter) ).expect("BMP info_header.x_px_per_meter could not be written."); filebuffer.write( &transmute::<_, [u8; 4]>(self.info_header.y_px_per_meter) ).expect("BMP info_header.y_px_per_meter could not be written."); filebuffer.write( &transmute::<_, [u8; 4]>(self.info_header.colors_used) ).expect("BMP info_header.colors_used could not be written."); filebuffer.write( &transmute::<_, [u8; 4]>(self.info_header.colors_important) ).expect("BMP info_header.colors_important could not be written."); } filebuffer.write( &self.rgba ).expect("BMP rgba arr could not be written."); }} ///Generates a TGBitmap from StbiImage format. pub fn from_stbi( image: StbiImage )->TGBitmap{ let mut buffer = vec![0u8; (4*image.width*image.height) as usize]; for i in (0..image.height as usize).rev(){ for j in 0..image.width as usize{ let offset_im = 4 * ( i*image.width as usize + j ); let offset_new = 4 * ((image.height as usize - i - 1)*image.width as usize + j); buffer[offset_new + 0] = image.buffer[offset_im + 2]; buffer[offset_new + 1] = image.buffer[offset_im + 1]; buffer[offset_new + 2] = image.buffer[offset_im + 0]; buffer[offset_new + 3] = image.buffer[offset_im + 3]; } } TGBitmap{ file_header: TGBitmapFileHeader{ type_: 0x4d42, //BM size_: 0, reserved_1: 0, reserved_2: 0, off_bits: 0, }, info_header: TGBitmapHeaderInfo{ header_size: 54,//TODO width: image.width, height: image.height, planes: 1, bit_per_pixel: 32, compression: 0, image_size: 0, x_px_per_meter: 0, y_px_per_meter: 0, colors_used: 0, colors_important: 0, }, rgba: buffer, width : image.width, height : image.height, } } } ///Returns a new bmp that is the resized version of the old bmp. ///The function resizes to the width and height specified. ///This function currently uses the sampling reduction algorithm. pub fn resize_bmp(source_bmp: &TGBitmap, w: i32, h: i32)->TGBitmap{unsafe{ return sampling_reduction_bmp(source_bmp, w, h); }} ///Returns a new bmp that is the resized version of the old bmp. ///The algorithm replaces each pixel with new pixel(s) of the same color. ///This technique may result is jaggedness. pub fn sampling_reduction_bmp(source_bmp: &TGBitmap, w: i32, h: i32)->TGBitmap{unsafe{ let mut bmp = TGBitmap::new(w, h); let scale_w = source_bmp.info_header.width as f32 / w as f32; let scale_h = source_bmp.info_header.height as f32 / h as f32; let dst_buffer = bmp.rgba.as_mut_ptr() as *mut u32; let src_buffer = source_bmp.rgba.as_ptr() as *const u32; for j in 0..h as isize{ for i in 0..w as isize{ let _i = j * w as isize + i; let src_i = (j as f32 * scale_h) as isize * source_bmp.width as isize + (i as f32 * scale_w) as isize; let rgb = dst_buffer.offset( _i ); *rgb = *src_buffer.offset( src_i); } } return bmp; }} ///Draws stbi_image to the canvas provided. x, and y dictate where the image is draws to the canvas. ///This point is associated with the bottom left corner of the image. pub fn draw_stbi_image( canvas: &mut WindowCanvas, bmp: &StbiImage, mut x: i32, mut y: i32, alpha: f32, mut _w: Option<i32>, mut _h: Option<i32>){unsafe{ if alpha < 0.0 { println!("A negative alpha as passed to drawBMP"); return; } let w; let h; let canvas_dpmm = if canvas.dpmm == 0f32 { DPMM_SCALE } else { canvas.dpmm }; let mut dpmm_ratio = 1f32;//canvas_dpmm / DPMM_SCALE; if (1f32 - dpmm_ratio).abs() < DPMM_TOLERANCE { dpmm_ratio = 1f32; } x = (dpmm_ratio * x as f32).round() as _; y = (dpmm_ratio * y as f32).round() as _; if dpmm_ratio != 1f32 { if _w.is_none() { _w = Some( bmp.width ); } if _h.is_none() { _h = Some( bmp.height ); } } match _w { Some(int) => w = (dpmm_ratio * int as f32).round() as _ , None => w = bmp.width, } match _h { Some(int) => h = (dpmm_ratio * int as f32).round() as _, None => h = bmp.height, } //TODO //let bmp = if w == source_bmp.width && // h == source_bmp.height{ // (*source_bmp).clone() // } else { // sampling_reduction_bmp(source_bmp, w, h) // }; { //render bmp_buffer to main_buffer let buffer = canvas.buffer as *mut u32; let gwidth = canvas.w as i32; let gheight = canvas.h as i32; let offset = (x + y * gwidth) as i32; let bit_stride = (bmp.bits_per_pixel / 8) as i32; let color = bmp.buffer.as_ptr(); if alpha >= 0.99 { for i in (0..bmp.height).rev(){ let _w = bmp.width as usize; let _off_src = i as isize * _w as isize * bit_stride as isize; let _off_dst = i as isize * gwidth as isize; std::ptr::copy::<u32>(color.offset(_off_src) as *const u32, buffer.offset( _off_dst + offset as isize), _w); } } else { for i in (0..bmp.height).rev(){ //TODO //when alpha is one copy the bmp bits instead of iterating through the array for j in 0..bmp.width{ if (j + i*gwidth + offset) < 0 {continue;} if (j + i*gwidth + offset) > gwidth * gheight {continue;} if j + x > gwidth {continue;} if i + y > gheight {continue;} let a = (*color.offset(( bit_stride * (j + i * bmp.width) + 3) as isize) as f32 ) / 255.0; let r = (*color.offset(( bit_stride * (j + i * bmp.width) + 2) as isize) as f32 * alpha * a ) as u32; let g = (*color.offset(( bit_stride * (j + i * bmp.width) + 1) as isize) as f32 * alpha * a ) as u32; let b = (*color.offset(( bit_stride * (j + i * bmp.width) + 0) as isize) as f32 * alpha * a ) as u32; let dst_rgb = buffer.offset( (j + i*gwidth + offset) as isize); let _r = (*(dst_rgb as *const u8).offset(2) as f32 * (1.0 - alpha * a )) as u32; let _g = (*(dst_rgb as *const u8).offset(1) as f32 * (1.0 - alpha * a )) as u32; let _b = (*(dst_rgb as *const u8).offset(0) as f32 * (1.0 - alpha * a )) as u32; let r_cmp = (r+_r).min(255).max(0); let g_cmp = (g+_g).min(255).max(0); let b_cmp = (b+_b).min(255).max(0); *buffer.offset( (j + i*gwidth + offset) as isize) = 0x00000000 + (r_cmp << 16) + (g_cmp << 8) + b_cmp; } } } } }} ///Draws TGBitmap to the canvas provided. x, and y dictate where the image is draws to the canvas. ///This point is associated with the bottom left corner of the image. pub fn draw_bmp( canvas: &mut WindowCanvas, source_bmp: &TGBitmap, mut x: i32, mut y: i32, alpha: f32, mut _w: Option<i32>, mut _h: Option<i32>){unsafe{ //DEBUG_timeit!{ "draw_bmp", { if alpha < 0.0 { println!("A negative alpha as passed to drawBMP"); return; } let w; let h; let canvas_dpmm = if canvas.dpmm == 0f32 { DPMM_SCALE } else { canvas.dpmm }; let mut dpmm_ratio = 1f32;//canvas_dpmm / DPMM_SCALE; if (1f32 - dpmm_ratio).abs() < DPMM_TOLERANCE { dpmm_ratio = 1f32; } x = (dpmm_ratio * x as f32).round() as _; y = (dpmm_ratio * y as f32).round() as _; if dpmm_ratio != 1f32 { if _w.is_none() { _w = Some( source_bmp.width ); } if _h.is_none() { _h = Some( source_bmp.height ); } } match _w { Some(int) => w = (dpmm_ratio * int as f32).round() as _, None => w = source_bmp.info_header.width, } match _h { Some(int) => h = (dpmm_ratio * int as f32).round() as _, None => h = source_bmp.info_header.height, } let bmp = if w == source_bmp.info_header.width && h == source_bmp.info_header.height{ (*source_bmp).clone() } else { sampling_reduction_bmp(source_bmp, w, h) }; { //render bmp_buffer to main_buffer let buffer = canvas.buffer as *mut u32; let gwidth = canvas.w as i32; let gheight = canvas.h as i32; let offset = (x + y * gwidth) as i32; let bit_stride = (bmp.info_header.bit_per_pixel / 8) as i32; let inv_255 = 1.0 / 255.0; let color = bmp.rgba.as_ptr(); if alpha >= 0.99 { for i in (0..bmp.info_header.height).rev(){ let _w = bmp.info_header.width as usize; let _off_src = i as isize * _w as isize * bit_stride as isize; let _off_dst = i as isize * gwidth as isize; std::ptr::copy::<u32>(color.offset(_off_src) as *const u32, buffer.offset( _off_dst + offset as isize), _w); } } else { for i in (0..bmp.info_header.height).rev(){ //TODO //simd for j in 0..bmp.info_header.width{ if (j + i*gwidth + offset) < 0 {continue;} if (j + i*gwidth + offset) > gwidth * gheight {continue;} if j + x > gwidth {continue;} if i + y > gheight {continue;} let a = (*color.offset(( bit_stride * (j + i * bmp.info_header.width) + 3) as isize) as f32 ) * inv_255; let r = (*color.offset(( bit_stride * (j + i * bmp.info_header.width) + 2) as isize) as f32 * alpha * a ) as u32; let g = (*color.offset(( bit_stride * (j + i * bmp.info_header.width) + 1) as isize) as f32 * alpha * a ) as u32; let b = (*color.offset(( bit_stride * (j + i * bmp.info_header.width) + 0) as isize) as f32 * alpha * a ) as u32; let dst_rgb = buffer.offset( (j + i*gwidth + offset) as isize); let _r = (*(dst_rgb as *const u8).offset(2) as f32 * (1.0 - alpha * a )) as u32; let _g = (*(dst_rgb as *const u8).offset(1) as f32 * (1.0 - alpha * a )) as u32; let _b = (*(dst_rgb as *const u8).offset(0) as f32 * (1.0 - alpha * a )) as u32; let r_cmp = (r+_r).min(255).max(0); let g_cmp = (g+_g).min(255).max(0); let b_cmp = (b+_b).min(255).max(0); *buffer.offset( (j + i*gwidth + offset) as isize) = 0x00000000 + (r_cmp << 16) + (g_cmp << 8) + b_cmp; } } } } //}} }} ///Draws a circle to the canvas provided. x, and y dictate where the image is draws to the canvas. ///This point(x,y) is the center of the circle. pub fn draw_circle(canvas: &mut WindowCanvas, mut _x: i32, mut _y: i32, r: f32, color: [f32; 4]){unsafe{ //TODO time test is needed. It is very likely this function is slow. let buffer = canvas.buffer as *mut u32; let c_w = canvas.w as isize; let c_h = canvas.h as isize; let canvas_dpmm = if canvas.dpmm == 0f32 { DPMM_SCALE } else { canvas.dpmm }; let mut dpmm_ratio = 1f32;//canvas_dpmm / DPMM_SCALE; if (1f32 - dpmm_ratio).abs() < DPMM_TOLERANCE { dpmm_ratio = 1f32; } _x = (dpmm_ratio * _x as f32).round() as _; _y = (dpmm_ratio * _y as f32).round() as _; let x = (_x - r as i32) as isize; let y = (_y - r as i32)as isize; let w = (2.0*r) as isize; let h = (2.0*r) as isize; let a = color[3].max(0f32).min(1f32); let mut index_i = 0; let mut index_j = 0; for _j in y..y+h{ let j = _j as isize; index_j += 1; index_i = 0; for _i in x..x+w{ let i = _i as isize; index_i += 1; if i >= c_w || j >= c_h || i < 0 || j < 0 { continue; } let dst_rgb = buffer.offset( (i + c_w*j) as isize); let radius = ((index_i as f32 - w as f32/2.0).powf(2.0) + (index_j as f32 - h as f32/2.0).powf(2.0)).sqrt(); let radius_factor = ( 1.4*(r-radius) / (1.0 + (1.4*(r-radius)).abs())).max(0.0) ; let _r = (*(dst_rgb as *const u8).offset(2) as f32 * (1.0 - a*radius_factor)) as u32; let _g = (*(dst_rgb as *const u8).offset(1) as f32 * (1.0 - a*radius_factor)) as u32; let _b = (*(dst_rgb as *const u8).offset(0) as f32 * (1.0 - a*radius_factor)) as u32; let r = (color[0] * a * radius_factor * 255.0) as u32; let g = (color[1] * a * radius_factor * 255.0) as u32; let b = (color[2] * a * radius_factor * 255.0) as u32; *buffer.offset(i + c_w*j) = 0x00000000 + (r+_r << 16) + (g+_g << 8) + b+_b; } } }} ///Draws a subcanvas to the canvas provided. x, and y dictate where the image is draws to the canvas. ///This point(x,y) is the center of the circle. pub fn draw_subcanvas(canvas: &mut WindowCanvas, subcanvas: &SubCanvas, mut x: i32, mut y: i32, alpha: f32 ){unsafe{ //TODO we need to scale with dpi let buffer = canvas.buffer as *mut u32; let subbuffer = subcanvas.canvas.buffer as *mut u32; let c_w = canvas.w as isize; let c_h = canvas.h as isize; let canvas_dpmm = if canvas.dpmm == 0f32 { DPMM_SCALE } else { canvas.dpmm }; let mut dpmm_ratio = 1f32;//canvas_dpmm / DPMM_SCALE; if (1f32 - dpmm_ratio).abs() < DPMM_TOLERANCE { dpmm_ratio = 1f32; } x = (dpmm_ratio * x as f32).round() as _; y = (dpmm_ratio * y as f32).round() as _; let x = x as isize; let y = y as isize; let w = subcanvas.canvas.w as isize; let h = subcanvas.canvas.h as isize - 1;//-1 is here to remove junk. We should look more closely at this TODO let a = alpha.max(0f32); if alpha < 0.99f32 { let mut j_ = 0; for _j in y..y+h{ let j = _j as isize; j_ += 1; let mut i_ = 0; for _i in x..x+w{ let i = _i as isize; i_ += 1; if i < 0 || j < 0 { continue; } if i > c_w || j >= c_h{ continue; } let dst_rgb = buffer.offset( (i + c_w*j) as isize); let src_rgb = subbuffer.offset( (i_ + w*j_) as isize); let _r = (*(dst_rgb as *const u8).offset(2) as f32 * (1.0 - a)) as u32; let _g = (*(dst_rgb as *const u8).offset(1) as f32 * (1.0 - a)) as u32; let _b = (*(dst_rgb as *const u8).offset(0) as f32 * (1.0 - a)) as u32; let r = (*(src_rgb as *const u8).offset(2) as f32 * a) as u32; let g = (*(src_rgb as *const u8).offset(1) as f32 * a) as u32; let b = (*(src_rgb as *const u8).offset(0) as f32 * a) as u32; *buffer.offset(i + c_w*j) = 0x00000000 + (r+_r << 16) + (g+_g << 8) + b+_b; } } } else { let mut j_ = 0; for _j in y..y+h{ let j = _j as isize; j_ += 1; let dst_rgb = buffer.offset( (x + c_w*j) as isize); let src_rgb = subbuffer.offset( w*j_ as isize); let _w = if x+w > canvas.w as isize { c_w - x } else { w }; if _w < 0 { break; } if j > c_h { break; } if j_ > c_h { break; } std::ptr::copy::<u32>(src_rgb as *const u32, dst_rgb as *mut u32, _w as usize); } } }} pub struct SubCanvas{ pub canvas: WindowCanvas, pub buffer: Vec<u8>, } impl SubCanvas{ pub fn new(w: i32, h: i32)->SubCanvas{unsafe{ use std::mem; let mut wc = WindowCanvas{ info: TGBitmapHeaderInfo{ header_size : mem::size_of::<TGBitmapHeaderInfo>() as u32, width : w, height : h, planes : 1, bit_per_pixel : 32, compression : 0,//BI_RGB, image_size: 0, x_px_per_meter: 0, y_px_per_meter: 0, colors_used: 0, colors_important: 0, }, buffer: null_mut(), w: w, h: h, display_width : 0, display_width_mm : 0, display_height : 0, display_height_mm: 0, dpmm: DPMM_SCALE, }; let buffer = vec![0u8; (w*h*4) as _]; let mut canvas = SubCanvas{ canvas: wc, buffer: buffer }; canvas.canvas.buffer = canvas.buffer.as_mut_ptr() as _; return canvas; }} } pub mod multithreaded_renderer{ //Should we use a subcanvas instead of a windowcanvas? use crate::WindowCanvas; use std::{thread, time}; use std::sync::atomic::{AtomicU8, Ordering}; use crate::rendertools::{SubCanvas, draw_subcanvas}; // //TODO need to get cpuid a //https://doc.rust-lang.org/stable/core/arch/x86/struct.CpuidResult.html //Rust/Documentations/(intel and amd) static mut THREAD_WINDOW : Option<SubCanvas> = None; static mut THREAD_POOL : Option<Vec<thread::JoinHandle<()>>> = None; static mut THREAD_STATUS : Option<Vec<AtomicU8>> = None; static mut THREAD_BOUNDING_RECT : Option<Vec<[i32; 4]>> = None; const CLOSED : u8 = 0; const OPEN : u8 = 1; const KILL : u8 = 3; static mut TRANSFORMATION_PIPELINE : Option<Vec<PixelShader>> = None; //TODO combine pixel and distance shaders //TODO enum for shader data? type PixelShader = fn([f32; 2], &[Vec<f32>])->[f32;4]; static mut PIXEL_SHADER_FUNCTION_PIPELINE : Option<Vec<PixelShader>> = None; static mut PIXEL_SHADER_DATA_PIPELINE : Option<Vec<Vec<Vec<f32>>>> = None; /*TODO pub type TransformationMaxtrix = [f32; 9]; */ #[derive(Debug)] pub enum MTError{ Err, PreviouslyInit, Default } pub fn mt_print_status(){unsafe{ if THREAD_STATUS.is_none(){ println!("Renderer has been improperly initialized."); return; } println!("Number of threads: {}", THREAD_POOL.as_ref().unwrap().len()); println!("Thread status: {:?}", THREAD_STATUS); let bounding_rects = THREAD_BOUNDING_RECT.as_ref().unwrap(); for i in 0..bounding_rects.len() { println!("Thread {}: rect {:?}", i, bounding_rects[i]); } if PIXEL_SHADER_FUNCTION_PIPELINE.is_none(){ println!("Pixel shader pipeline has not been set."); return; } let pixel_shaders = PIXEL_SHADER_FUNCTION_PIPELINE.as_ref().unwrap(); let pixel_function_inputs = PIXEL_SHADER_DATA_PIPELINE.as_ref().unwrap(); println!("Number of Pixel Shaders: {}", pixel_shaders.len()); println!("Number of Pixel Inputs: {}", pixel_function_inputs.len()); }} fn thread_function(){ let thread_id = thread::current().name().expect("Thread was not named.") .parse::<usize>().expect("Thread was not named a number."); unsafe{ if THREAD_STATUS.is_none(){ panic!("Renderer has been improperly initialized."); } } let mut thread_good = true; while thread_good { let status = unsafe{ THREAD_STATUS.as_ref().unwrap()[thread_id].load(Ordering::Relaxed) }; match status { OPEN => { thread::sleep(time::Duration::from_millis(1)); }, KILL => { thread_good = false; }, CLOSED => { //TODO //get bounding rect let rect = unsafe{ THREAD_BOUNDING_RECT.as_ref().unwrap()[thread_id] }; let canvas = unsafe{ &mut THREAD_WINDOW.as_mut().unwrap().canvas }; let pixel_functions = unsafe{ PIXEL_SHADER_FUNCTION_PIPELINE.as_ref().unwrap() }; let pixel_data = unsafe{ PIXEL_SHADER_DATA_PIPELINE.as_ref().unwrap() }; shaders(canvas, rect, //transformation_matrix: &[TransformationMaxtrix], pixel_functions, pixel_data); unsafe{ THREAD_STATUS.as_mut().unwrap()[thread_id].store(OPEN, Ordering::Relaxed); } }, _=>{ panic!("Unexpected thread status!"); } } } } pub fn init_multithread_renderer(n_threads: usize, window_width: i32, window_height: i32)->Result<(), MTError>{unsafe{ //TODO we know now many cores we have on this computer (Linux machine with 4 cores) //so we create 5 threads, making use of atleast 3 cores if n_threads == 0 { return Ok(()); } if THREAD_WINDOW.is_some(){ return Err(MTError::PreviouslyInit); } THREAD_WINDOW = Some(SubCanvas::new(window_width, window_height)); let mut arr_threads = vec![]; let mut arr_thread_status = vec![]; let mut arr_thread_rect = vec![]; for i in 0..n_threads{ arr_thread_status.push(AtomicU8::new(OPEN)); } THREAD_STATUS = Some(arr_thread_status); let _h = window_height / n_threads as i32; for i in 0..n_threads{ let mut h = _h; if i == n_threads - 1 { h = window_height - _h*i as i32; } let mut builder = thread::Builder::new().name(i.to_string()); arr_threads.push( builder.spawn(thread_function).expect("Thread could not be made.") ); arr_thread_rect.push([0, _h*i as i32,window_width, h]); } THREAD_POOL = Some(arr_threads); THREAD_BOUNDING_RECT = Some(arr_thread_rect); PIXEL_SHADER_FUNCTION_PIPELINE = Some(vec![]); PIXEL_SHADER_DATA_PIPELINE = Some(vec![]); return Ok(()); }} pub fn mt_render()->Result<(), MTError>{unsafe{ //tell threads to render the things //wait for threads to finish if THREAD_STATUS.is_none(){ return Err(MTError::Err); } let mut thread_status = THREAD_STATUS.as_mut().unwrap(); let mut threads_open = true; for i in 0..thread_status.len(){ if thread_status[i].load(Ordering::Relaxed) != OPEN{ threads_open = false; } } if threads_open { for i in 0..thread_status.len(){ thread_status[i].store(CLOSED, Ordering::Relaxed); } threads_open = false; } else { return Err(MTError::Err); } while threads_open == false { threads_open = true; for i in 0..thread_status.len(){ if thread_status[i].load(Ordering::Relaxed) != OPEN{ threads_open = false; } } } PIXEL_SHADER_FUNCTION_PIPELINE.as_mut().unwrap().clear(); PIXEL_SHADER_DATA_PIPELINE.as_mut().unwrap().clear(); return Ok(()); }} pub fn mt_render_to_canvas(canvas: &mut WindowCanvas, x: i32, y: i32, alpha: f32)->Result<(), MTError>{unsafe{ if THREAD_STATUS.is_none(){ return Err(MTError::Err); } if PIXEL_SHADER_FUNCTION_PIPELINE.as_mut().unwrap().len() > 0 { mt_render()?; } let subcanvas = THREAD_WINDOW.as_ref().unwrap(); draw_subcanvas(canvas, subcanvas, x, y, alpha); return Ok(()); }} pub fn mt_shader(pixel_function: PixelShader, p_data: &[&[f32]])->Result<(), MTError>{unsafe{ if THREAD_STATUS.is_none(){ return Err(MTError::Err); } PIXEL_SHADER_FUNCTION_PIPELINE.as_mut().unwrap().push(pixel_function); let _pipe = PIXEL_SHADER_DATA_PIPELINE.as_mut().unwrap(); _pipe.push(vec![]); let pipe_index = _pipe.len() - 1; for i in 0..p_data.len(){ _pipe[pipe_index].push(p_data[i].to_vec()); } return Ok(()); }} pub fn mt_clear()->Result<(), MTError>{unsafe{ if THREAD_STATUS.is_none(){ return Err(MTError::Err); } let window = THREAD_WINDOW.as_mut().unwrap(); let c = 0u8; std::ptr::write_bytes::<u8>(window.buffer.as_ptr() as *mut u8, c, window.buffer.len()); return Ok(()); }} pub fn mt_draw_rect(rect: [i32; 4], color: [f32; 4])->Result<(), MTError>{unsafe{ //TODO if THREAD_STATUS.is_none(){ return Err(MTError::Err); } let thread_window = THREAD_WINDOW.as_ref().unwrap(); let mut f_rect = {//TODO convert to -1 to 1 float representation let w = thread_window.canvas.w as f32; let h = thread_window.canvas.h as f32; let min_w_h = w.min(h); [ 2.0 * rect[0] as f32 / min_w_h - w/min_w_h, 2.0 * rect[1] as f32 / min_w_h - h/min_w_h, 2.0 * rect[2] as f32 / min_w_h, 2.0 * rect[3] as f32 / min_w_h, ] }; fn d_rect(mut p: [f32; 2], data: &[f32])->f32{ p[0] -= data[0]; p[1] -= data[1]; let b = [data[2], data[3]]; let mut d = [0f32; 2]; d[0] = p[0].abs()-b[0]; d[1] = p[1].abs()-b[1]; let d_0_m = d[0].max(0f32); let d_1_m = d[1].max(0f32); return (d_0_m.powi(2) + d_1_m.powi(2)).sqrt(); } fn fill_color(p: [f32; 2], inputs: &[Vec<f32>])->[f32; 4]{ if inputs.len() < 2 { panic!("fill_color did not get proper number of inputs"); } let d = d_rect(p, &inputs[0]); let r = inputs[1][0]; let g = inputs[1][1]; let b = inputs[1][2]; let a = inputs[1][3]; if d.is_finite(){ return [r,g,b,a*((-d*10f32).exp()).max(0.0).min(1.0)]; } else { return [r,g,b,a]; } } mt_shader(fill_color, &[&color]); return Ok(()); }} fn shaders(canvas : &mut WindowCanvas, rect: [i32; 4], //transformation_matrix: &[TransformationMaxtrix], pixel_func : &[PixelShader], pixel_function_inputs: &Vec<Vec<Vec<f32>>> ){unsafe{ if pixel_func.len() != pixel_function_inputs.len(){ panic!("shaders lengths are not the same."); } //if thread::current().name().expect("??") != "1"{ // return; //} let [mut x, mut y, mut w, mut h] = rect; let c_w = canvas.w; let c_h = canvas.h; if x == -1 && y == x && w == x && h == x { x = 0; y = 0; w = c_w; h = c_h; } let min_c_w_h = c_w.min(c_h) as f32; let f32_c_w = c_w as f32; let f32_c_h = c_h as f32; let buffer = canvas.buffer as *mut u32; for i in 0..w { if i + x > c_w { continue; } for j in 0..h { if j + y > c_h {//TODO window canvas bounderies continue; } let dst_rgb = buffer.offset( (i+x + c_w*(j+y)) as isize); let mut p = [(2f32*(i+x) as f32 ) / min_c_w_h - f32_c_w/min_c_w_h, (2f32*(j+y) as f32 ) / min_c_w_h - f32_c_h/min_c_w_h] ; let [mut r, mut g, mut b] = [0u32; 3]; for ii in 0..pixel_func.len(){ let _p = p;//transformation_matrix[ii].apply_tm(p); let [_r, _g, _b, a] = pixel_func[ii](p, &pixel_function_inputs[ii]); if a < 0.01 { continue; } let dst_r = (*(dst_rgb as *const u8).offset(2) as f32 * (1.0 - a)) as u32; let dst_g = (*(dst_rgb as *const u8).offset(1) as f32 * (1.0 - a)) as u32; let dst_b = (*(dst_rgb as *const u8).offset(0) as f32 * (1.0 - a)) as u32; r = (_r*a*255.0) as u32 + dst_r; g = (_g*a*255.0) as u32 + dst_g; b = (_b*a*255.0) as u32 + dst_b; *buffer.offset((i+x + c_w*(j+y)) as isize) = 0x00000000 + (r << 16) + (g << 8) + b; } } } }} }
use crate::Register; use once_cell::sync::Lazy; use std::{collections::HashMap, fmt}; /// The table that is used to lookup the format of a given opcode. /// /// 1: R format /// 2: I format /// 3: J format const FORMAT_TABLE: Lazy<HashMap<u8, u8>> = Lazy::new(|| { let mut map = HashMap::new(); map.insert(0b000000, 1); map.insert(0b001000, 2); map.insert(0b001001, 2); map.insert(0b001100, 2); map.insert(0b000100, 2); map.insert(0b000001, 2); map.insert(0b000111, 2); map.insert(0b000110, 2); map.insert(0b000101, 2); map.insert(0b000010, 3); map.insert(0b000011, 3); map.insert(0b100000, 2); map.insert(0b001111, 2); map.insert(0b100011, 2); map.insert(0b001101, 2); map.insert(0b101000, 2); map.insert(0b001010, 2); map.insert(0b001011, 2); map.insert(0b101011, 2); map.insert(0b001110, 2); map }); pub fn parse(raw: u32) -> Option<Instruction> { let opcode = ((raw >> 25) & 0x3F) as u8; let format = FORMAT_TABLE.get(&opcode)?.clone(); match format { // The R format // opcode(6) rs(5) rt(5) rd(5) shamt(5) funct(6) 1 => { let rs = ((raw >> 21) & 0x1F) as Register; let rt = ((raw >> 16) & 0x1F) as Register; let rd = ((raw >> 11) & 0x1F) as Register; let shamt = ((raw >> 6) & 0x1F) as u8; let funct = (raw & 0x3F) as u8; let kind = match funct { 0b000000 if shamt == 0 => Kind::Noop, 0b100000 => Kind::Add, 0b100001 => Kind::Addu, 0b100100 => Kind::And, 0b011010 => Kind::Div, 0b011011 => Kind::Divu, 0b001000 => Kind::Jr, 0b010000 => Kind::Mfhi, 0b010010 => Kind::Mflo, 0b011000 => Kind::Mult, 0b011001 => Kind::Multu, 0b100101 => Kind::Or, 0b000000 => Kind::Sll, 0b000100 => Kind::Sllv, 0b101010 => Kind::Slt, 0b101011 => Kind::Sltu, 0b000011 => Kind::Sra, 0b000010 => Kind::Srl, 0b000110 => Kind::Srlv, 0b100010 => Kind::Sub, 0b100011 => Kind::Subu, 0b100110 => Kind::Xor, 0b001100 => Kind::Syscall, _ => return None, }; let format = Format::R { rs, rt, rd, shamt, funct, }; Some(Instruction { raw, kind, format }) } // The I format // opcode(6) rs(5) rt(5) immediate(16) 2 => { let rs = ((raw >> 21) & 0x1F) as Register; let rt = ((raw >> 16) & 0x1F) as Register; let val = (raw & 0xFFFF) as u16; let kind = match (opcode, rt) { (0b001000, _) => Kind::Addi, (0b001001, _) => Kind::Addiu, (0b001100, _) => Kind::Andi, (0b000100, _) => Kind::Beq, (0b000001, 0b00001) => Kind::Bgez, (0b000001, 0b10001) => Kind::Bgezal, (0b000001, 0b00000) => Kind::Bltz, (0b000001, 0b10000) => Kind::Bltzal, (0b000111, 0b00000) => Kind::Bgtz, (0b000110, 0b00000) => Kind::Blez, (0b000101, _) => Kind::Bne, (0b100000, _) => Kind::Lb, (0b001111, _) => Kind::Lui, (0b100011, _) => Kind::Lw, (0b001101, _) => Kind::Ori, (0b101000, _) => Kind::Sb, (0b001010, _) => Kind::Slti, (0b001011, _) => Kind::Sltiu, (0b101011, _) => Kind::Sw, (0b001110, _) => Kind::Xori, _ => return None, }; let format = Format::I { rs, rt, val }; Some(Instruction { raw, format, kind }) } // The J format // opcode(6) address(26) 3 => { let val = raw & 0x3FFFFFF; Some(Instruction { raw, format: Format::J(val), kind: match opcode { 0b000010 => Kind::J, 0b000011 => Kind::Jal, _ => unreachable!(), }, }) } _ => unreachable!(), } } #[test] fn test() { let raw = 0x00220821; if let Some(result) = parse(raw) { println!("{}", result); } else { println!("None"); } } #[derive(Debug)] pub struct Instruction { raw: u32, kind: Kind, format: Format, } impl fmt::Display for Instruction { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} {}", self.kind, self.format) } } #[derive(Debug, Clone)] pub enum Format { R { rs: Register, rt: Register, rd: Register, shamt: u8, funct: u8, }, I { rs: Register, rt: Register, val: u16, }, J(u32), } impl fmt::Display for Format { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Format::R { rs, rt, rd, .. } => write!(f, "${} ${} ${}", rs, rt, rd), Format::I { rs, rt, val } => write!(f, "${} ${} {:x}", rs, rt, val), Format::J(addr) => write!(f, "{:x}", addr), } } } #[derive(Debug, Clone)] pub enum Kind { Add, Addi, Addiu, Addu, And, Andi, Beq, Bgez, Bgezal, Bgtz, Blez, Bltz, Bltzal, Bne, Div, Divu, J, Jal, Jr, Lb, Lui, Lw, Mfhi, Mflo, Mult, Multu, Noop, Or, Ori, Sb, Sll, Sllv, Slt, Slti, Sltiu, Sltu, Sra, Srl, Srlv, Sub, Subu, Sw, Syscall, Xor, Xori, } impl fmt::Display for Kind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let repr = match self { Kind::Add => "add", Kind::Addi => "addi", Kind::Addiu => "addiu", Kind::Addu => "addu", Kind::And => "and", Kind::Andi => "andi", Kind::Beq => "beq", Kind::Bgez => "bgez", Kind::Bgezal => "bgezal", Kind::Bgtz => "bgtz", Kind::Blez => "blez", Kind::Bltz => "bltz", Kind::Bltzal => "bltzal", Kind::Bne => "bne", Kind::Div => "div", Kind::Divu => "divu", Kind::J => "j", Kind::Jal => "jal", Kind::Jr => "jr", Kind::Lb => "lb", Kind::Lui => "lui", Kind::Lw => "lw", Kind::Mfhi => "mfhi", Kind::Mflo => "mflo", Kind::Mult => "mult", Kind::Multu => "multu", Kind::Noop => "noop", Kind::Or => "or", Kind::Ori => "ori", Kind::Sb => "sb", Kind::Sll => "sll", Kind::Sllv => "sllv", Kind::Slt => "slt", Kind::Slti => "slti", Kind::Sltiu => "sltiu", Kind::Sltu => "sltu", Kind::Sra => "sra", Kind::Srl => "srl", Kind::Srlv => "srlv", Kind::Sub => "sub", Kind::Subu => "subu", Kind::Sw => "sw", Kind::Syscall => "syscall", Kind::Xor => "xor", Kind::Xori => "xori", }; write!(f, "{}", repr) } }
use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{ braced, parse::{Parse, ParseStream, Result}, punctuated::Punctuated, Ident, ItemEnum, Token, Type, }; #[derive(Debug, PartialEq)] pub(crate) struct State { pub state_name: Ident, pub state_type: Type, } impl Parse for State { /// example state: /// /// ```text /// S1 = S1 /// ``` fn parse(input: ParseStream<'_>) -> Result<Self> { /// S1 = S1 /// __ let state_name: Ident = Ident::parse(input)?; /// S1 = S1 /// _ let _: Token![=] = input.parse()?; /// S1 = S1 /// __ let state_type: Type = Type::parse(input)?; Ok(State { state_name, state_type, }) } } impl ToTokens for State { fn to_tokens(&self, tokens: &mut TokenStream) { let state_name = &self.state_name; let state_type = &self.state_type; tokens.extend(quote!( #state_name(#state_type) )); } } #[derive(Debug, PartialEq)] pub(crate) struct States(Vec<State>); impl Parse for States { /// example states: /// /// ```text /// States { /// S1 = S1, /// S2 = S2, /// S3 = S3, /// S4 = S4, /// S5 = S5 /// } /// ``` fn parse(input: ParseStream<'_>) -> Result<Self> { /// States { ... } /// ----------- let states_magic = Ident::parse(input)?; if states_magic != "States" { return Err(input.error("expected States { ... }")); } let content; braced!(content in input); let mut transitions: Vec<State> = Vec::new(); let states: Punctuated<State, Token![,]> = content.parse_terminated(State::parse)?; Ok(States(states.into_iter().collect())) } } impl ToTokens for States { fn to_tokens(&self, tokens: &mut TokenStream) { let states = &self.0; tokens.extend(quote!( #[derive(Clone, Debug, PartialEq)] pub enum State { #(#states),* } )); } } #[cfg(test)] mod tests { use super::*; use proc_macro2::TokenStream; use syn::{self, parse_quote}; #[test] fn test_states_parse_and_to_tokens() { let states: States = syn::parse2(quote! { States { S1 = S1, S2 = S2 } }) .unwrap(); let left = quote! { #[derive(Clone, Debug, PartialEq)] pub enum State { S1(S1), S2(S2) } }; let mut right = TokenStream::new(); states.to_tokens(&mut right); assert_eq!(format!("{}", left), format!("{}", right)) } }
pub mod enums; pub mod process; pub mod core;
use rand::{seq::SliceRandom, SeedableRng}; /// 6t5-15t4+10t3. fn fade(t: f32) -> f32 { t * t * t * (10.0 + t * (6.0 * t - 15.0)) } pub fn make_permutation<R: SeedableRng + rand::RngCore>(rand: &mut R) -> Vec<u8> { let mut p: Vec<u8> = (0..255u8).collect(); p.shuffle(rand); for i in 0..p.len() { p.push(p[i]); } p } fn get_constant_vector(hash: usize) -> glam::Vec2 { let h = hash & 3; match h { 0 => glam::Vec2::one(), 1 => glam::Vec2::new(-1.0, 1.0), 2 => glam::Vec2::new(-1.0, -1.0), _ => glam::Vec2::new(1.0, -1.0), } } pub struct PermutationTable(Vec<u8>); impl PermutationTable { fn get1(&self, x: isize) -> usize { let idx = (x & 0xFF) as usize; self.0[idx] as usize } fn get2(&self, x: isize, y: isize) -> usize { let y = (y & 0xFF) as usize; self.0[self.get1(x) ^ y] as usize } } pub fn perlin2d(x: f32, y: f32, perm: &PermutationTable) -> f32 { let xf = x - x.floor(); let yf = y - y.floor(); let near_corner = [x.floor() as isize, y.floor() as isize]; let far_corner = [near_corner[0] + 1, near_corner[1] + 1]; let near_distance = [x - x.floor(), y - y.floor()]; let _far_distance = [near_distance[0] - 1.0, near_distance[1] - 1.0]; let top_right: glam::Vec2 = glam::vec2(xf - 1.0, yf - 1.0); let top_left: glam::Vec2 = glam::vec2(xf, yf - 1.0); let bottom_right: glam::Vec2 = glam::vec2(xf - 1.0, yf); let bottom_left: glam::Vec2 = glam::vec2(xf, yf); // select a value in the array for each of the corner. let value_top_right = perm.get2(far_corner[0], far_corner[1]); let value_top_left = perm.get2(near_corner[0], far_corner[1]); let value_bottom_right = perm.get2(far_corner[0], near_corner[1]); let value_bottom_left = perm.get2(near_corner[0], near_corner[1]); //perm[(perm[X] + Y) & 0xFF]; let dot_top_right = top_right.dot(get_constant_vector(value_top_right)); let dot_top_left = top_left.dot(get_constant_vector(value_top_left)); let dot_bottom_right = bottom_right.dot(get_constant_vector(value_bottom_right)); // near corner let dot_bottom_left = bottom_left.dot(get_constant_vector(value_bottom_left)); let u = fade(near_distance[0]); let v = fade(near_distance[1]); let res = bilinear_interpolation( u, v, dot_bottom_left, dot_top_left, dot_bottom_right, dot_top_right, ) * 2.0 * (2.0_f32).sqrt(); clamp((res + 1.0) / 2., 0.0, 1.0) } fn clamp(x: f32, min: f32, max: f32) -> f32 { if x < min { min } else if x > max { max } else { x } } #[inline(always)] fn bilinear_interpolation(u: f32, v: f32, g00: f32, g01: f32, g10: f32, g11: f32) -> f32 { let k0 = g00; let k1 = g10 - g00; let k2 = g01 - g00; let k3 = g00 + g11 - g10 - g01; k0 + k1 * u + k2 * v + k3 * u * v } pub struct Perlin { perm: PermutationTable, repeat: Option<usize>, } impl Perlin { pub fn new<R: SeedableRng + rand::RngCore>(rand: &mut R) -> Self { Self { perm: PermutationTable(make_permutation(rand)), repeat: None, } } pub fn with_repeat(mut self, repeat: usize) -> Self { self.repeat = Some(repeat); self } pub fn perlin(&self, x: f32, y: f32) -> f32 { perlin2d(x, y, &self.perm) } pub fn octave_perlin(&self, x: f32, y: f32, octaves: u32, persistence: f32) -> f32 { let mut freq = 1.0; let mut amplitude = 1.0; let mut max_value = 0.0; let mut total = 0.0; for _ in 0..octaves { total += perlin2d(x * freq, y * freq, &self.perm) * amplitude; max_value += amplitude; amplitude *= persistence; freq *= 2.0; } total / max_value } }
extern crate futures; extern crate hyper; extern crate hyper_tls; extern crate tokio_core; use ex_api; use ex_api::Api; use ex_api::ApiCall; use ex_api::exchanges::BitThumb; use net_client::Client; pub struct TradingMachine { connection: Client, exchange: BitThumb, api: ApiCall, } impl TradingMachine { pub fn new() -> TradingMachine { TradingMachine { connection: Client::new(), exchange: ex_api::exchanges::BitThumb::new("https://api.bithumb.com/public/ticker/".to_string()), api: ApiCall::new(), } } pub fn start_trading(&mut self, coin: &str) { self.api.current_price(&mut self.connection, &self.exchange, coin); } }
pub mod lib_table { pub mod lib_sub_mod { pub fn table(data:u32) { println!("We are in lib.rs"); for value in 1..=10 { println!{"{} x {} = {}",data,value,data*value}; } } } }
use crate::no_slog::log_via_log_crate; use crate::sample_module::{log_debug_mode, log_global}; use slog::{o, slog_info}; use slog_kickstarter::SlogKickstarter; use slog_scope::set_global_logger; use std::env; fn main() { // initialize a root logger let root_logger = SlogKickstarter::new("logging-example") .with_debug_log_for("full::sample_module") .init(); // set a global logger. The logger lives as long as the guard, so make sure the guard lives as long as the main-function let _guard = set_global_logger(root_logger.new(o!("scope" => "global"))); let json_log_status = if env::var("RUST_LOG_JSON") .map(|v| v == "1") .unwrap_or_default() { "RUST_JSON_LOG=1 set, logging in JSON format" } else { "RUST_JSON_LOG=1 not set, logging in compact format" }; // slog supports string formatting, and additional structured fields slog_info!(root_logger, "Hello World. {}", json_log_status; o!("type" => "example")); // example for a module with enforced debug-logging (set via `.with_debug_log_for()`) log_debug_mode(&root_logger.new(o!("scope" => "module-specific logger"))); log_via_log_crate(); log_global(); } mod sample_module { use slog::{o, slog_debug, slog_info, Logger}; use slog_scope::logger; pub fn log_debug_mode(logger: &Logger) { let example_value = 42; slog_debug!(logger, "This is debug log"; o!("example_value" => example_value)); } pub fn log_global() { // Sometimes it's not feasible to pass logging-instances around, then you may use the global logger, which // has been made available via `slog-scope::set_global_logger` // Be aware: slog discourages this usage. slog_info!(logger(), "Without explicitly passed logger") } } /// An external module/crate that knows nothing about slog, and just uses the log-facade crate. /// These case are covered by slog-stdlog mod no_slog { use log::info; pub fn log_via_log_crate() { // logging via well-known `log` crate. If a library does not know about `slog`, or for your own legacy code. info!("Using the well-known 'log' crate") } }
/* * @lc app=leetcode.cn id=26 lang=rust * * [26] 删除排序数组中的重复项 * * https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/description/ * * algorithms * Easy (43.07%) * Total Accepted: 95.7K * Total Submissions: 221.4K * Testcase Example: '[1,1,2]' * * 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 * * 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 * * 示例 1: * * 给定数组 nums = [1,1,2], * * 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 * * 你不需要考虑数组中超出新长度后面的元素。 * * 示例 2: * * 给定 nums = [0,0,1,1,1,2,2,3,3,4], * * 函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。 * * 你不需要考虑数组中超出新长度后面的元素。 * * * 说明: * * 为什么返回数值是整数,但输出的答案是数组呢? * * 请注意,输入数组是以“引用”方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。 * * 你可以想象内部操作如下: * * // nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝 * int len = removeDuplicates(nums); * * // 在函数里修改输入数组对于调用者是可见的。 * // 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。 * for (int i = 0; i < len; i++) { * print(nums[i]); * } * * */ impl Solution { pub fn remove_duplicates(nums: &mut Vec<i32>) -> i32 { if nums.is_empty() { return 0; } let mut i = 0; for j in 1..nums.len() { if nums[j] != nums[i] { i += 1; nums[i] = nums[j]; } } (i + 1) as i32 } } fn main() { let mut v = vec![1, 1, 2, 2, 2, 5, 6]; let s = Solution::remove_duplicates(&mut v); dbg!(v); dbg!(s); } struct Solution {}
//! messages. use std::any::TypeId; use actix::{dev::ToEnvelope, prelude::*}; use crate::{ broker::{ArbiterBroker, RegisteredBroker, SystemBroker}, msgs::*, }; /// The `BrokerSubscribe` trait has functions to register an actor's interest in different /// messages. pub trait BrokerSubscribe where Self: Actor, <Self as Actor>::Context: AsyncContext<Self>, { /// Asynchronously subscribe to a message. fn subscribe_async<T: RegisteredBroker, M: BrokerMsg>(&self, ctx: &mut Self::Context) where Self: Handler<M>, <Self as Actor>::Context: ToEnvelope<Self, M>, { let broker = T::get_broker(); let recipient = ctx.address().recipient::<M>(); broker.do_send(SubscribeAsync(recipient, TypeId::of::<Self>())); } /// Synchronously subscribe to a message. /// This actor will do nothing else until its interest is registered. /// If messages of that type have been sent to the broker previously, a copy of the latest /// message is sent to the calling actor after it has subscribed. fn subscribe_sync<T: RegisteredBroker, M: BrokerMsg>(&self, ctx: &mut Self::Context) where Self: Handler<M>, <Self as Actor>::Context: ToEnvelope<Self, M>, { let broker = T::get_broker(); let recipient = ctx.address().recipient::<M>(); broker .send(SubscribeSync(recipient, TypeId::of::<Self>())) .into_actor(self) .map(move |m, _, ctx| { if let Ok(Some(msg)) = m { ctx.notify(msg); } }) .wait(ctx); } /// Helper to asynchronously subscribe to a system broker /// This is the equivalent of `self.subscribe_async::<SystemBroker, M>(ctx);` fn subscribe_system_async<M: BrokerMsg>(&self, ctx: &mut Self::Context) where Self: Handler<M>, <Self as Actor>::Context: ToEnvelope<Self, M>, { self.subscribe_async::<SystemBroker, M>(ctx); } /// Helper to synchronously subscribe to a system broker /// This is the equivalent of `self.subscribe_sync::<SystemBroker, M>(ctx); fn subscribe_system_sync<M: BrokerMsg>(&self, ctx: &mut Self::Context) where Self: Handler<M>, <Self as Actor>::Context: ToEnvelope<Self, M>, { self.subscribe_sync::<SystemBroker, M>(ctx); } /// Helper to asynchronously subscribe to an arbiter-specific broker /// This is the equivalent of `self.subscribe_async::<ArbiterBroker, M>(ctx);` fn subscribe_arbiter_async<M: BrokerMsg>(&self, ctx: &mut Self::Context) where Self: Handler<M>, <Self as Actor>::Context: ToEnvelope<Self, M>, { self.subscribe_async::<ArbiterBroker, M>(ctx); } /// Helper to synchronously subscribe to an arbiter-specific broker /// This is the equivalent of `self.subscribe_sync::<ArbiterBroker, M>(ctx); fn subscribe_arbiter_sync<M: BrokerMsg>(&self, ctx: &mut Self::Context) where Self: Handler<M>, <Self as Actor>::Context: ToEnvelope<Self, M>, { self.subscribe_sync::<ArbiterBroker, M>(ctx); } } impl<A> BrokerSubscribe for A where A: Actor, <A as Actor>::Context: AsyncContext<A>, { }
use apilib::transfer::Transfer; use serde::Serialize; use serde::Deserialize; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct TRequest<T: Transfer> { pub value: T, } impl<T: Transfer> TRequest<T> { pub fn new(value: T) -> Self { TRequest { value } } } impl<'de, T: Transfer + Serialize + Deserialize<'de>> Transfer for TRequest<T> { fn clean(self) -> Self { TRequest { value: self.value.clean() } } } // TODO @mverleg: I would like to use derive so I don't have to type this impl<T> PartialEq for TRequest<T> where T: Transfer + PartialEq { fn eq(&self, other: &TRequest<T>) -> bool { self.value == other.value } }
use crate::army_setups_manager::ArmySetupsManager; use crate::ca_game::{get_ca_game_title, GameSelector}; use crate::central_panel_state::{AppState, CentralPanelState}; use crate::resources_panel; use eframe::{egui, epi}; /// We derive Deserialize/Serialize so we can persist app state on shutdown. #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] pub struct OwaaghApp { app_state: AppState, pub army_setups_manager: ArmySetupsManager, game_selector: GameSelector, } impl Default for OwaaghApp { fn default() -> Self { Self { army_setups_manager: Default::default(), app_state: Default::default(), game_selector: Default::default(), } } } //Git note on debugging impl epi::App for OwaaghApp { fn name(&self) -> &str { "WarbossWaaghit" } /// Called by the framework to load old app state (if any). #[cfg(feature = "persistence")] fn load(&mut self, storage: &dyn epi::Storage) { *self = epi::get_value(storage, epi::APP_KEY).unwrap_or_default() } /// Called by the frame work to save state before shutdown. #[cfg(feature = "persistence")] fn save(&mut self, storage: &mut dyn epi::Storage) { epi::set_value(storage, epi::APP_KEY, self); } /// Called each time the UI needs repainting, which may be many times per second. /// Put your widgets into a `SidePanel`, `TopPanel`, `CentralPanel`, `Window` or `Area`. fn update(&mut self, ctx: &egui::CtxRef, frame: &mut epi::Frame<'_>) { let OwaaghApp { army_setups_manager, app_state, game_selector, } = self; egui::SidePanel::left("side_panel", 200.0).show(ctx, |ui| { app_state.side_bar_ui(ui, ctx); ui.with_layout(egui::Layout::bottom_up(egui::Align::Center), |ui| { ui.add( egui::Hyperlink::new("https://github.com/emilk/egui/").text("powered by egui"), ); }); }); egui::CentralPanel::default().show(ctx, |ui| match app_state.central_panel_state.clone() { // CentralPanelState::OwaaghSettings => { // ui.label("To Do"); // } CentralPanelState::GameSelection => { game_selector.central_panel_ui(ui, army_setups_manager, app_state); } CentralPanelState::BuildManager => army_setups_manager.central_panel_ui(ui, ctx), CentralPanelState::TierList => { ui.label("Greenskins da Best"); } // CentralPanelState::Replays => { // ui.horizontal(|ui| { // ui.label("To Do In OWAAGH"); // ui.hyperlink("https://www.twitch.tv/gudgitz"); // }); // } CentralPanelState::Resources => { resources_panel::central_panel_ui(ui, ctx); } // CentralPanelState::Acknowledgements => { // ui.label("To Do"); // } _ => {} }); } } // ----------------------------------------------------------------------------
use crate::video::pixel::Pixel; use crate::video::FrameInfo; #[cfg(feature = "y4m-decode")] mod y4m; #[cfg(feature = "y4m-decode")] pub use self::y4m::*; /// A trait for allowing metrics to decode generic video formats. /// /// Currently, y4m decoding support using the `y4m` crate is built-in /// to this crate. This trait is extensible so users may implement /// their own decoders. pub trait Decoder { /// Read the next frame from the input video. /// /// Expected to return `Err` if the end of the video is reached. fn read_video_frame<T: Pixel>(&mut self) -> Result<FrameInfo<T>, ()>; /// Get the bit depth of the video. fn get_bit_depth(&self) -> usize; }
#[doc = "Reader of register RCC2"] pub type R = crate::R<u32, super::RCC2>; #[doc = "Writer for register RCC2"] pub type W = crate::W<u32, super::RCC2>; #[doc = "Register RCC2 `reset()`'s with value 0"] impl crate::ResetValue for super::RCC2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Oscillator Source 2\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum OSCSRC2_A { #[doc = "0: MOSC"] MO = 0, #[doc = "1: PIOSC"] IO = 1, #[doc = "2: PIOSC/4"] IO4 = 2, #[doc = "3: LFIOSC"] _30 = 3, #[doc = "7: 32.768 kHz"] _32 = 7, } impl From<OSCSRC2_A> for u8 { #[inline(always)] fn from(variant: OSCSRC2_A) -> Self { variant as _ } } #[doc = "Reader of field `OSCSRC2`"] pub type OSCSRC2_R = crate::R<u8, OSCSRC2_A>; impl OSCSRC2_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, OSCSRC2_A> { use crate::Variant::*; match self.bits { 0 => Val(OSCSRC2_A::MO), 1 => Val(OSCSRC2_A::IO), 2 => Val(OSCSRC2_A::IO4), 3 => Val(OSCSRC2_A::_30), 7 => Val(OSCSRC2_A::_32), i => Res(i), } } #[doc = "Checks if the value of the field is `MO`"] #[inline(always)] pub fn is_mo(&self) -> bool { *self == OSCSRC2_A::MO } #[doc = "Checks if the value of the field is `IO`"] #[inline(always)] pub fn is_io(&self) -> bool { *self == OSCSRC2_A::IO } #[doc = "Checks if the value of the field is `IO4`"] #[inline(always)] pub fn is_io4(&self) -> bool { *self == OSCSRC2_A::IO4 } #[doc = "Checks if the value of the field is `_30`"] #[inline(always)] pub fn is_30(&self) -> bool { *self == OSCSRC2_A::_30 } #[doc = "Checks if the value of the field is `_32`"] #[inline(always)] pub fn is_32(&self) -> bool { *self == OSCSRC2_A::_32 } } #[doc = "Write proxy for field `OSCSRC2`"] pub struct OSCSRC2_W<'a> { w: &'a mut W, } impl<'a> OSCSRC2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: OSCSRC2_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "MOSC"] #[inline(always)] pub fn mo(self) -> &'a mut W { self.variant(OSCSRC2_A::MO) } #[doc = "PIOSC"] #[inline(always)] pub fn io(self) -> &'a mut W { self.variant(OSCSRC2_A::IO) } #[doc = "PIOSC/4"] #[inline(always)] pub fn io4(self) -> &'a mut W { self.variant(OSCSRC2_A::IO4) } #[doc = "LFIOSC"] #[inline(always)] pub fn _30(self) -> &'a mut W { self.variant(OSCSRC2_A::_30) } #[doc = "32.768 kHz"] #[inline(always)] pub fn _32(self) -> &'a mut W { self.variant(OSCSRC2_A::_32) } #[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 << 4)) | (((value as u32) & 0x07) << 4); self.w } } #[doc = "Reader of field `BYPASS2`"] pub type BYPASS2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `BYPASS2`"] pub struct BYPASS2_W<'a> { w: &'a mut W, } impl<'a> BYPASS2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `PWRDN2`"] pub type PWRDN2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PWRDN2`"] pub struct PWRDN2_W<'a> { w: &'a mut W, } impl<'a> PWRDN2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `USBPWRDN`"] pub type USBPWRDN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USBPWRDN`"] pub struct USBPWRDN_W<'a> { w: &'a mut W, } impl<'a> USBPWRDN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `SYSDIV2LSB`"] pub type SYSDIV2LSB_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYSDIV2LSB`"] pub struct SYSDIV2LSB_W<'a> { w: &'a mut W, } impl<'a> SYSDIV2LSB_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 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `SYSDIV2`"] pub type SYSDIV2_R = crate::R<u8, u8>; #[doc = "Write proxy for field `SYSDIV2`"] pub struct SYSDIV2_W<'a> { w: &'a mut W, } impl<'a> SYSDIV2_W<'a> { #[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 & !(0x3f << 23)) | (((value as u32) & 0x3f) << 23); self.w } } #[doc = "Reader of field `DIV400`"] pub type DIV400_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DIV400`"] pub struct DIV400_W<'a> { w: &'a mut W, } impl<'a> DIV400_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `USERCC2`"] pub type USERCC2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USERCC2`"] pub struct USERCC2_W<'a> { w: &'a mut W, } impl<'a> USERCC2_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 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bits 4:6 - Oscillator Source 2"] #[inline(always)] pub fn oscsrc2(&self) -> OSCSRC2_R { OSCSRC2_R::new(((self.bits >> 4) & 0x07) as u8) } #[doc = "Bit 11 - PLL Bypass 2"] #[inline(always)] pub fn bypass2(&self) -> BYPASS2_R { BYPASS2_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 13 - Power-Down PLL 2"] #[inline(always)] pub fn pwrdn2(&self) -> PWRDN2_R { PWRDN2_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - Power-Down USB PLL"] #[inline(always)] pub fn usbpwrdn(&self) -> USBPWRDN_R { USBPWRDN_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 22 - Additional LSB for SYSDIV2"] #[inline(always)] pub fn sysdiv2lsb(&self) -> SYSDIV2LSB_R { SYSDIV2LSB_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bits 23:28 - System Clock Divisor 2"] #[inline(always)] pub fn sysdiv2(&self) -> SYSDIV2_R { SYSDIV2_R::new(((self.bits >> 23) & 0x3f) as u8) } #[doc = "Bit 30 - Divide PLL as 400 MHz vs. 200 MHz"] #[inline(always)] pub fn div400(&self) -> DIV400_R { DIV400_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - Use RCC2"] #[inline(always)] pub fn usercc2(&self) -> USERCC2_R { USERCC2_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 4:6 - Oscillator Source 2"] #[inline(always)] pub fn oscsrc2(&mut self) -> OSCSRC2_W { OSCSRC2_W { w: self } } #[doc = "Bit 11 - PLL Bypass 2"] #[inline(always)] pub fn bypass2(&mut self) -> BYPASS2_W { BYPASS2_W { w: self } } #[doc = "Bit 13 - Power-Down PLL 2"] #[inline(always)] pub fn pwrdn2(&mut self) -> PWRDN2_W { PWRDN2_W { w: self } } #[doc = "Bit 14 - Power-Down USB PLL"] #[inline(always)] pub fn usbpwrdn(&mut self) -> USBPWRDN_W { USBPWRDN_W { w: self } } #[doc = "Bit 22 - Additional LSB for SYSDIV2"] #[inline(always)] pub fn sysdiv2lsb(&mut self) -> SYSDIV2LSB_W { SYSDIV2LSB_W { w: self } } #[doc = "Bits 23:28 - System Clock Divisor 2"] #[inline(always)] pub fn sysdiv2(&mut self) -> SYSDIV2_W { SYSDIV2_W { w: self } } #[doc = "Bit 30 - Divide PLL as 400 MHz vs. 200 MHz"] #[inline(always)] pub fn div400(&mut self) -> DIV400_W { DIV400_W { w: self } } #[doc = "Bit 31 - Use RCC2"] #[inline(always)] pub fn usercc2(&mut self) -> USERCC2_W { USERCC2_W { w: self } } }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use fidl_fuchsia_net as fidl; #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub struct IpAddress(pub std::net::IpAddr); impl std::fmt::Display for IpAddress { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { let IpAddress(ip_address) = self; write!(f, "{}", ip_address) } } impl From<fidl::IpAddress> for IpAddress { fn from(addr: fidl::IpAddress) -> IpAddress { IpAddress(match addr { fidl::IpAddress::Ipv4(fidl::Ipv4Address { addr }) => addr.into(), fidl::IpAddress::Ipv6(fidl::Ipv6Address { addr }) => addr.into(), }) } } impl Into<fidl::IpAddress> for IpAddress { fn into(self) -> fidl::IpAddress { let IpAddress(ip_address) = self; match ip_address { std::net::IpAddr::V4(v4addr) => { fidl::IpAddress::Ipv4(fidl::Ipv4Address { addr: v4addr.octets() }) } std::net::IpAddr::V6(v6addr) => { fidl::IpAddress::Ipv6(fidl::Ipv6Address { addr: v6addr.octets() }) } } } } impl std::str::FromStr for IpAddress { type Err = failure::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(IpAddress(s.parse()?)) } } #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub struct Subnet { addr: IpAddress, prefix_len: u8, } impl std::fmt::Display for Subnet { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { let Self { addr, prefix_len } = self; write!(f, "{}/{}", addr, prefix_len) } } impl std::str::FromStr for Subnet { type Err = failure::Error; // Parse a Subnet from a CIDR-notated IP address. // // NB: if we need additional CIDR related functionality in the future, // we should consider pulling in https://crates.io/crates/cidr fn from_str(s: &str) -> Result<Self, Self::Err> { let mut pieces = s.split('/'); let addr = pieces .next() .expect("String#split should never return an empty iterator") .parse::<std::net::IpAddr>()?; let addr_len = match addr { std::net::IpAddr::V4(_) => 32, std::net::IpAddr::V6(_) => 128, }; let validated_prefix = match pieces.next() { Some(p) => { let parsed_len = p.parse::<u8>()?; if parsed_len > addr_len { Err(failure::format_err!( "prefix length provided ({} bits) too large. address {} is only {} bits long", parsed_len, addr, addr_len )) } else { Ok(parsed_len) } } None => Ok(addr_len), }; let () = match pieces.next() { Some(_) => Err(failure::format_err!( "more than one '/' separator found while attempting to parse CIDR string {}", s )), None => Ok(()), }?; let addr = IpAddress(addr); Ok(Subnet { addr, prefix_len: validated_prefix? }) } } impl From<fidl::Subnet> for Subnet { fn from(subnet: fidl::Subnet) -> Self { let fidl::Subnet { addr, prefix_len } = subnet; let addr = addr.into(); Self { addr, prefix_len } } } impl Into<fidl::Subnet> for Subnet { fn into(self) -> fidl::Subnet { let Self { addr, prefix_len } = self; let addr = addr.into(); fidl::Subnet { addr, prefix_len } } } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; #[test] fn test_ipaddr() { let want_ext = IpAddress(std::net::IpAddr::V4(std::net::Ipv4Addr::new(1, 2, 3, 4))); let want_fidl = fidl::IpAddress::Ipv4(fidl::Ipv4Address { addr: [1, 2, 3, 4] }); let got_fidl: fidl::IpAddress = want_ext.into(); let got_ext = IpAddress::from(got_fidl); assert_eq!(want_ext, got_ext); assert_eq!(want_fidl, got_fidl); } #[test] fn test_subnet() { let err_str_subnets = vec![ // Note "1.2.3.4" or "::" is a valid form. Subnet's FromStr trait allows // missing prefix, and assumes the legally maximum prefix length. "", "/32", // no ip address " /32", // no ip address "1.2.3.4/8/8", // too many slashes "1.2.3.4/33", // prefix too long "192.168.32.1:8080", // that's a port, not a prefix "e80::e1bf:4fe9:fb62:e3f4/129", // prefix too long "e80::e1bf:4fe9:fb62:e3f4/32%eth0", // zone index ]; for e in err_str_subnets { if Subnet::from_str(e).is_ok() { eprintln!( "a malformed str is wrongfully convertitable to Subnet struct: \"{}\"", e ); assert!(false); } } let want_str = "1.2.3.4/18"; let want_ext = Subnet { addr: IpAddress(std::net::IpAddr::V4(std::net::Ipv4Addr::new(1, 2, 3, 4))), prefix_len: 18, }; let want_fidl = fidl::Subnet { addr: fidl::IpAddress::Ipv4(fidl::Ipv4Address { addr: [1, 2, 3, 4] }), prefix_len: 18, }; let got_ext = Subnet::from_str(want_str).ok().expect("conversion error"); let got_fidl: fidl::Subnet = got_ext.into(); let got_ext_back = Subnet::from(got_fidl); let got_str = &format!("{}", got_ext_back); assert_eq!(want_ext, got_ext); assert_eq!(want_fidl, got_fidl); assert_eq!(got_ext, got_ext_back); assert_eq!(want_str, got_str); } }
use std::{cmp::Reverse, collections::BinaryHeap}; use proconio::{ input, marker::{Bytes, Usize1}, }; fn main() { input! { n: usize, a: [u64; n], s: [Bytes; n], q: usize, uv: [(Usize1, Usize1); q], }; let mut g = vec![vec![]; n]; for i in 0..n { for j in 0..n { if s[i][j] == b'Y' { g[i].push(j); } } } const INF: usize = std::usize::MAX; let mut ans = vec![vec![(INF, 0); n]; n]; for s in 0..n { let ans = &mut ans[s]; let mut heap = BinaryHeap::new(); ans[s] = (0, a[s]); heap.push((Reverse(0), a[s], s)); while let Some((Reverse(d), c, i)) = heap.pop() { let (dd, cc) = ans[i]; if dd < d || (dd == d && cc > c) { continue; } for &j in &g[i] { let (dd, cc) = ans[j]; if d + 1 < dd || (d + 1 == dd && c + a[j] > cc) { ans[j] = (d + 1, c + a[j]); heap.push((Reverse(d + 1), c + a[j], j)); } } } } for (u, v) in uv { let (d, c) = ans[u][v]; if d == INF { println!("Impossible"); } else { println!("{} {}", d, c); } } }
// Copyright © 2016-2017 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #[macro_use] mod macros; pub mod arbitrary; #[allow(dead_code)] pub mod vr_invariants; #[allow(dead_code)] pub mod op_invariants; #[allow(dead_code)] pub mod scheduler; #[allow(dead_code)] mod model; pub use self::model::Model; use std::panic; /// Taken (with slight modification) from quickcheck crate /// Wrap tests in a closure so that we can catch panics and treat them as errors #[allow(dead_code)] pub fn safe<T, F>(fun: F) -> Result<T, String> where F: FnOnce() -> T { panic::catch_unwind(panic::AssertUnwindSafe(fun)).map_err(|any_err| { // Extract common types of panic payload: // panic and assert produce &str or String if let Some(&s) = any_err.downcast_ref::<&str>() { s.to_owned() } else if let Some(s) = any_err.downcast_ref::<String>() { s.to_owned() } else { "UNABLE TO SHOW RESULT OF PANIC.".to_owned() } }) }
use na::{Matrix4, Vector3}; use nalgebra as na; use nalgebra_glm as glm; use sepia::app::*; use sepia::buffer::*; use sepia::camera::*; use sepia::shaderprogram::*; use sepia::vao::*; const ONES: &[GLfloat; 1] = &[1.0]; #[rustfmt::skip] const VERTEX_POSITIONS: &[GLfloat; 108] = &[ -0.25, 0.25, -0.25, -0.25, -0.25, -0.25, 0.25, -0.25, -0.25, 0.25, -0.25, -0.25, 0.25, 0.25, -0.25, -0.25, 0.25, -0.25, 0.25, -0.25, -0.25, 0.25, -0.25, 0.25, 0.25, 0.25, -0.25, 0.25, -0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, -0.25, 0.25, -0.25, 0.25, -0.25, -0.25, 0.25, 0.25, 0.25, 0.25, -0.25, -0.25, 0.25, -0.25, 0.25, 0.25, 0.25, 0.25, 0.25, -0.25, -0.25, 0.25, -0.25, -0.25, -0.25, -0.25, 0.25, 0.25, -0.25, -0.25, -0.25, -0.25, 0.25, -0.25, -0.25, 0.25, 0.25, -0.25, -0.25, 0.25, 0.25, -0.25, 0.25, 0.25, -0.25, -0.25, 0.25, -0.25, -0.25, -0.25, -0.25, -0.25, -0.25, -0.25, 0.25, -0.25, 0.25, -0.25, 0.25, 0.25, -0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, -0.25, 0.25, 0.25, -0.25, 0.25, -0.25 ]; #[derive(Default)] struct MainState { vao: VertexArrayObject, vbo: Buffer, shader_program: ShaderProgram, camera: Camera, } impl State for MainState { fn initialize(&mut self) { self.shader_program = ShaderProgram::new(); self.shader_program .vertex_shader_file("assets/shaders/spinny-cube/spinny-cube.vs.glsl") .fragment_shader_file("assets/shaders/spinny-cube/spinny-cube.fs.glsl") .link(); self.vao = VertexArrayObject::new(); self.vbo = Buffer::new(BufferKind::Array); self.vbo.add_data(VERTEX_POSITIONS); self.vbo.upload(&self.vao, DrawingHint::StaticDraw); self.vao.configure_attribute(0, 3, 3, 0); unsafe { gl::Enable(gl::CULL_FACE); gl::FrontFace(gl::CW); gl::Enable(gl::DEPTH_TEST); gl::DepthFunc(gl::LEQUAL); } } fn handle_events(&mut self, state_data: &mut StateData, event: &glfw::WindowEvent) { match *event { glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => { state_data.window.set_should_close(true); } WindowEvent::CursorPos(cursor_x, cursor_y) => { let (window_width, window_height) = state_data.window.get_size(); self.camera.process_mouse_movement( (window_width as f32 / 2.0) - cursor_x as f32, (window_height as f32 / 2.0) - cursor_y as f32, ); } _ => (), } } fn update(&mut self, state_data: &mut StateData) { if state_data.window.get_key(glfw::Key::W) == glfw::Action::Press { self.camera .translate(CameraDirection::Forward, state_data.delta_time); } if state_data.window.get_key(glfw::Key::A) == glfw::Action::Press { self.camera .translate(CameraDirection::Left, state_data.delta_time); } if state_data.window.get_key(glfw::Key::S) == glfw::Action::Press { self.camera .translate(CameraDirection::Backward, state_data.delta_time); } if state_data.window.get_key(glfw::Key::D) == glfw::Action::Press { self.camera .translate(CameraDirection::Right, state_data.delta_time); } let (window_width, window_height) = state_data.window.get_size(); state_data.window.set_cursor_pos( f64::from(window_width) / 2.0, f64::from(window_height) / 2.0, ); state_data.window.set_cursor_mode(CursorMode::Disabled); } fn render(&mut self, state_data: &mut StateData) { let projection = glm::perspective( state_data.aspect_ratio, 50_f32.to_degrees(), 0.1_f32, 1000_f32, ); self.vao.bind(); self.shader_program.activate(); self.shader_program .set_uniform_matrix4x4("projection_matrix", projection.as_slice()); unsafe { gl::ClearBufferfv(gl::DEPTH, 0, ONES as *const f32); } for cube_id in 0..24 { let factor: f32 = cube_id as f32 + (state_data.current_time as f32 * 0.3); let modelview = self.camera.view_matrix() * Matrix4::new_translation(&Vector3::new(0.0, 0.0, -4.0)) * Matrix4::new_rotation(Vector3::new( 0.0, (state_data.current_time as f32 * 45_f32).to_radians(), (state_data.current_time as f32 * 21_f32).to_radians(), )) * Matrix4::new_translation(&Vector3::new( (2.1 * factor).sin() * 2.0, (1.7 * factor).cos() * 2.0, (1.3 * factor).sin() * (1.5 * factor).cos() * 2.0, )); self.shader_program .set_uniform_matrix4x4("modelview_matrix", modelview.as_slice()); unsafe { gl::DrawArrays(gl::TRIANGLES, 0, 36); } } let modelview = self.camera.view_matrix() * Matrix4::new_translation(&Vector3::new(0.0, 10.0, 0.0)) * Matrix4::new_nonuniform_scaling(&Vector3::new(100.0, 0.2, 100.0)); self.shader_program .set_uniform_matrix4x4("modelview_matrix", modelview.as_slice()); unsafe { gl::DrawArrays(gl::TRIANGLES, 0, 36); } } } fn main() { let mut state = MainState::default(); let mut state_machine: Vec<&mut dyn State> = Vec::new(); state_machine.push(&mut state); App::new(state_machine).run(); }
extern crate toml; extern crate collections; use std::io; use std::io::{File, Open, ReadWrite}; use std::io::fs::PathExtensions; use std::collections::treemap::TreeMap; use self::action::Action; pub mod action; #[deriving(PartialEq, Show)] pub enum Direction { Do, Undo } pub struct Config { pub actions: Vec<Action>, pub current_action: uint, path: Path } impl Config { pub fn read(path: Option<String>) -> Result<Config, &'static str> { let path = try!(decide_config_path(&path)); let toml = match File::open(&path).read_to_string() { Err(error) => return Err(error.desc), Ok(file) => from_str(file.as_slice()).unwrap() }; let root = try!(lookup_root(&toml)); let current_action = try!(lookup_current_action(&toml)); let command = try!(lookup_command(&toml)); let special = try!(lookup_special(&toml)); let actions = try!(Action::find_actions(&root, &command, &special)); Ok(Config { actions: actions, current_action: current_action, path: path }) } pub fn set_current_action(&mut self, current_action: uint) -> Result<(), &'static str> { let mut exists = false; let ca_string = format!("current_action = {}", current_action); let mut file = match File::open_mode(&self.path, Open, ReadWrite) { Ok(file) => file, Err(error) => return Err(error.desc) }; let mut config = file.read_to_string().unwrap().as_slice().lines().map(|line| { if is_current_action(line) { exists = true; ca_string.as_slice() } else { line } }).collect::<Vec<&str>>().connect("\n"); config.push('\n'); if !exists { config.push_str(ca_string.as_slice()); config.push('\n'); } match file.seek(0, io::SeekSet) { Err(error) => Err(error.desc), Ok(_) => match file.write(config.as_bytes()) { Err(error) => Err(error.desc), Ok(_) => { self.current_action = current_action; Ok(()) } } } } pub fn perform(&mut self, direction: Direction) { let actions_count = self.actions.len(); let mut current_action = self.current_action; if current_action > actions_count { println!("'current_action' is invalid"); return } else if (direction == Do && current_action == actions_count) || (direction == Undo && current_action == 0) { println!("Nothing to do here"); return } { // Borrow actions mutably for this scope let ref mut actions = self.actions; let not_yet_performed_actions = match direction { Do => actions.slice_from_mut(current_action), Undo => { let actions = actions.slice_mut(0, current_action); actions.reverse(); actions } }; for action in not_yet_performed_actions.iter() { println!("Performing '{}' of {}", direction, action.name); let process = match direction { Do => action.do_command(), Undo => action.undo_command() }; match process { Err(error) => { println!("{}", error); break; }, Ok(output) => { println!("{}", output); match direction { Do => current_action += 1, Undo => current_action -= 1 } } } } } match self.set_current_action(current_action) { Err(error) => println!("{}", error), Ok(_) => () } } } fn lookup_root(toml: &toml::Value) -> Result<Path, &'static str> { let default_root = "."; match toml.lookup("root") { None => Ok(Path::new(default_root)), Some(value) => match value.as_str() { Some(value) => Ok(Path::new(value)), None => Err("'root' is invalid") } } } fn lookup_current_action(toml: &toml::Value) -> Result<uint, &'static str> { match toml.lookup("current_action") { None => Ok(0), Some(value) => match value.as_integer() { Some(value) => Ok(value.to_uint().unwrap()), None => Err("'current_action' is invalid") } } } fn lookup_command(toml: &toml::Value) -> Result<String, &'static str> { match toml.lookup("command") { None => Err("'command' is required option"), Some(value) => match value.as_str() { Some(value) => Ok(value.to_string()), None => Err("'commad' is invalid") } } } fn lookup_special(toml: &toml::Value) -> Result<TreeMap<String, toml::Value>, &'static str> { match toml.lookup("special") { None => Ok(TreeMap::new()), Some(value) => match value.as_table() { Some(value) => Ok(value.clone()), None => Err("'special' is invalid") } } } fn decide_config_path(path: &Option<String>) -> Result<Path, &'static str> { match path { &Some(ref path) => Ok(Path::new(path.clone())), &None => { let path = Path::new("./in-order.toml"); if path.exists() { Ok(path) } else { Err("Can't find config file in current directory") } } } } fn is_current_action(string: &str) -> bool { let string: String = string.chars().filter(|c| c != &' ').collect(); string.as_slice().starts_with("current_action") }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! ril-ctl is used for interacting with devices that expose the standard //! Fuchsia RIL (FRIL) //! //! Ex: ril-ctl //! //! or //! //! Ex: ril-ctl -d /dev/class/qmi-usb-transport/000 //! use { crate::commands::{Cmd, ReplControl}, failure::{format_err, Error, ResultExt}, fidl::endpoints, fidl_fuchsia_net::{IpAddress, Ipv4Address, Subnet}, fidl_fuchsia_net_stack::{ ForwardingDestination, ForwardingEntry, InterfaceAddress, StackMarker, }, fidl_fuchsia_net_stack_ext::FidlReturn, fidl_fuchsia_netstack::NetstackMarker, fidl_fuchsia_telephony_manager::ManagerMarker, fidl_fuchsia_telephony_ril::{ RadioInterfaceLayerMarker, RadioInterfaceLayerProxy, RadioPowerState, SetupMarker, *, }, fuchsia_async::{self as fasync, futures::select}, fuchsia_component::{ client::{connect_to_service, launch, launcher}, fuchsia_single_component_package_url, }, futures::{FutureExt, TryFutureExt}, parking_lot::Mutex, pin_utils::pin_mut, qmi, std::{fs::File, path::PathBuf, sync::Arc}, structopt::StructOpt, }; mod commands; mod repl; static PROMPT: &str = "\x1b[35mril>\x1b[0m "; const RIL_URI: &str = fuchsia_single_component_package_url!("ril-qmi"); // TODO count actual bit number fn u32_to_cidr(ip: u32) -> Result<u8, Error> { match ip & 0xFF { 255 => Ok(32), 254 => Ok(31), 252 => Ok(30), 248 => Ok(29), 240 => Ok(28), 224 => Ok(27), 192 => Ok(26), 128 => Ok(25), 0 => Ok(24), e => Err(format_err!("bad u32 to cidr conversion: {}", e)), } } fn u32_to_ip_str(ip: u32) -> String { format!( "{}.{}.{}.{}", ((ip >> 24) & 0xFF), ((ip >> 16) & 0xFF), ((ip >> 8) & 0xFF), (ip & 0xFF) ) } // only supports ipv4 now fn u32_to_netaddr(ip: u32, mask: u32) -> Result<InterfaceAddress, Error> { let cidr = u32_to_cidr(mask)?; Ok(InterfaceAddress { ip_address: IpAddress::Ipv4(Ipv4Address { addr: [ ((ip >> 24) & 0xFF) as u8, ((ip >> 16) & 0xFF) as u8, ((ip >> 8) & 0xFF) as u8, (ip & 0xFF) as u8, ], }), prefix_len: cidr, }) } async fn get_imei<'a>( _args: &'a [&'a str], ril_modem: &'a RadioInterfaceLayerProxy, ) -> Result<String, Error> { match ril_modem.get_device_identity().await? { Ok(imei) => Ok(imei), Err(_state) => Err(format_err!("error")), } } async fn connect<'a>( args: &'a [&'a str], ril_modem: &'a RadioInterfaceLayerProxy, ) -> Result<(NetworkSettings, NetworkConnectionProxy), Error> { match ril_modem.start_network(args[0]).await? { Ok(iface) => { let settings = ril_modem.get_network_settings().await?; if let Ok(settings) = settings { return Ok((settings, iface.into_proxy()?)); } Err(format_err!("error")) } Err(_e) => Err(format_err!("error")), } } async fn get_power<'a>( _args: &'a [&'a str], ril_modem: &'a RadioInterfaceLayerProxy, ) -> Result<String, Error> { match ril_modem.radio_power_status().await? { Ok(state) => match state { RadioPowerState::On => Ok(String::from("radio on")), RadioPowerState::Off => Ok(String::from("radio off")), }, Err(_e) => Err(format_err!("error")), } } async fn get_signal<'a>( _args: &'a [&'a str], ril_modem: &'a RadioInterfaceLayerProxy, ) -> Result<String, Error> { match ril_modem.get_signal_strength().await? { Ok(strength) => Ok(format!("{} dBm", strength)), Err(_e) => Err(format_err!("error")), } } pub struct Connections { pub net_conn: Option<NetworkConnectionProxy>, pub file_ref: Option<File>, } async fn handle_cmd<'a>( ril_modem: &'a RadioInterfaceLayerProxy, line: String, state: Arc<Mutex<Connections>>, ) -> Result<ReplControl, Error> { let components: Vec<_> = line.trim().split_whitespace().collect(); if let Some((raw_cmd, args)) = components.split_first() { let cmd = raw_cmd.parse(); let res = match cmd { Ok(Cmd::Connect) => { let (settings, iface) = connect(args, &ril_modem).await?; { state.lock().net_conn = Some(iface); } eprintln!("IP Addr: {}", u32_to_ip_str(settings.ip_v4_addr)); eprintln!("IP Subnet: {}", u32_to_ip_str(settings.ip_v4_subnet)); eprintln!("IP Gateway: {}", u32_to_ip_str(settings.ip_v4_gateway)); eprintln!("IP DNS: {}", u32_to_ip_str(settings.ip_v4_dns)); match state.lock().file_ref { Some(ref file_ref) => { // Set up the netstack. // TODO not hardcode to iface 3 qmi::set_network_status(file_ref, true).await?; let netstack = connect_to_service::<StackMarker>()?; let old_netstack = connect_to_service::<NetstackMarker>()?; let (client, server_end) = fidl::endpoints::create_proxy::<fidl_fuchsia_net_dhcp::ClientMarker>()?; old_netstack.get_dhcp_client(3, server_end).await?.map_err(fuchsia_zircon::Status::from_raw)?; client.stop().await?.map_err(fuchsia_zircon::Status::from_raw)?; let () = netstack .add_interface_address( 3, &mut u32_to_netaddr(settings.ip_v4_addr, settings.ip_v4_subnet)? ) .await .squash_result()?; let ip = settings.ip_v4_addr; let () = netstack.add_forwarding_entry(&mut ForwardingEntry { destination: ForwardingDestination::NextHop(IpAddress::Ipv4(Ipv4Address{ addr: [ ((settings.ip_v4_gateway >> 24) & 0xFF) as u8, ((settings.ip_v4_gateway >> 16) & 0xFF) as u8, ((settings.ip_v4_gateway >> 8) & 0xFF) as u8, (settings.ip_v4_gateway & 0xFF) as u8]})), subnet: Subnet { addr: IpAddress::Ipv4(Ipv4Address{ addr: [ ((ip >> 24) & 0xFF) as u8, ((ip >> 16) & 0xFF) as u8, ((ip >> 8) & 0xFF) as u8, (ip & 0xFF) as u8]}), prefix_len: u32_to_cidr(settings.ip_v4_subnet)? }, }).await.squash_result()?; Ok("connected".to_string()) } None => Ok("set up connection on radio. Did not configure ethernet device, exclusive access required".to_string()) } } Ok(Cmd::PowerStatus) => get_power(args, &ril_modem).await, Ok(Cmd::SignalStrength) => get_signal(args, &ril_modem).await, Ok(Cmd::Imei) => get_imei(args, &ril_modem).await, Ok(Cmd::Help) => Ok(Cmd::help_msg().to_string()), Ok(Cmd::Exit) | Ok(Cmd::Quit) => return Ok(ReplControl::Break), Err(_) => Ok(format!("\"{}\" is not a valid command", raw_cmd)), }?; if res != "" { println!("{}", res); } } Ok(ReplControl::Continue) } /// A basic example #[derive(StructOpt, Debug)] #[structopt(name = "basic")] struct Opt { /// Device path (e.g. /dev/class/qmi-transport/000) #[structopt(short = "d", long = "device", parse(from_os_str))] device: Option<PathBuf>, } pub fn main() -> Result<(), Error> { let mut exec = fasync::Executor::new().context("error creating event loop")?; let args = Opt::from_args(); let launcher = launcher().context("Failed to open launcher service")?; let file = match args.device { Some(ref device) => Some(File::open(device)?), None => None, }; let conns = Arc::new(Mutex::new(Connections { file_ref: file, net_conn: None })); let fut = async move { let app; // need outside the match so it won't drop let telephony_svc; let (ril, server) = endpoints::create_proxy()?; let ril_modem = match args.device { Some(device) => { eprintln!("Connecting with exclusive access to {}..", device.display()); let file = File::open(device)?; let chan = qmi::connect_transport_device(&file).await?; app = launch(&launcher, RIL_URI.to_string(), None) .context("Failed to launch ril-qmi service")?; let ril_modem_setup = app.connect_to_service::<SetupMarker>()?; let resp = ril_modem_setup.connect_transport(chan).await?; let ril_modem = app.connect_to_service::<RadioInterfaceLayerMarker>()?; if resp.is_err() { return Err(format_err!( "Failed to connect the driver to the RIL (check telephony svc is not running?)" )); } Ok::<_, Error>(ril_modem) } None => { eprintln!("Connecting through telephony service..."); telephony_svc = connect_to_service::<ManagerMarker>()?; let resp = telephony_svc.get_ril_handle(server).await?; if !resp { return Err(format_err!("Failed to get an active RIL")); } Ok::<_, Error>(ril) } }?; let repl = repl::run(&ril_modem, conns) .unwrap_or_else(|e| eprintln!("REPL failed unexpectedly {:?}", e)); pin_mut!(repl); select! { () = repl.fuse() => Ok(()), // TODO(bwb): events loop future } }; exec.run_singlethreaded(fut) }
#![no_main] #![feature(start)] extern crate olin; use blake2::{Blake2b, Digest}; use olin::{entrypoint, log}; entrypoint!(); fn main() -> Result<(), std::io::Error> { let json: &'static [u8] = include_bytes!("./bigjson.json"); let yaml: &'static [u8] = include_bytes!("./k8sparse.yaml"); for _ in 0..8 { let mut hasher = Blake2b::new(); hasher.input(json); hasher.input(yaml); hasher.result(); } Ok(()) }
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_operation_associate_admin_account( input: &crate::input::AssociateAdminAccountInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_associate_admin_account_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_apps_list( input: &crate::input::DeleteAppsListInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_apps_list_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_notification_channel( _input: &crate::input::DeleteNotificationChannelInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { Ok(smithy_http::body::SdkBody::from("{}")) } pub fn serialize_operation_delete_policy( input: &crate::input::DeletePolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_protocols_list( input: &crate::input::DeleteProtocolsListInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_protocols_list_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_disassociate_admin_account( _input: &crate::input::DisassociateAdminAccountInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { Ok(smithy_http::body::SdkBody::from("{}")) } pub fn serialize_operation_get_admin_account( _input: &crate::input::GetAdminAccountInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { Ok(smithy_http::body::SdkBody::from("{}")) } pub fn serialize_operation_get_apps_list( input: &crate::input::GetAppsListInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_apps_list_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_compliance_detail( input: &crate::input::GetComplianceDetailInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_compliance_detail_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_notification_channel( _input: &crate::input::GetNotificationChannelInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { Ok(smithy_http::body::SdkBody::from("{}")) } pub fn serialize_operation_get_policy( input: &crate::input::GetPolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_protection_status( input: &crate::input::GetProtectionStatusInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_protection_status_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_protocols_list( input: &crate::input::GetProtocolsListInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_protocols_list_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_violation_details( input: &crate::input::GetViolationDetailsInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_violation_details_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_list_apps_lists( input: &crate::input::ListAppsListsInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_list_apps_lists_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_list_compliance_status( input: &crate::input::ListComplianceStatusInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_list_compliance_status_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_list_member_accounts( input: &crate::input::ListMemberAccountsInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_list_member_accounts_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_list_policies( input: &crate::input::ListPoliciesInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_list_policies_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_list_protocols_lists( input: &crate::input::ListProtocolsListsInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_list_protocols_lists_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_list_tags_for_resource( input: &crate::input::ListTagsForResourceInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_list_tags_for_resource_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_put_apps_list( input: &crate::input::PutAppsListInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_put_apps_list_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_put_notification_channel( input: &crate::input::PutNotificationChannelInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_put_notification_channel_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_put_policy( input: &crate::input::PutPolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_put_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_put_protocols_list( input: &crate::input::PutProtocolsListInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_put_protocols_list_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_tag_resource( input: &crate::input::TagResourceInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_tag_resource_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_untag_resource( input: &crate::input::UntagResourceInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_untag_resource_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) }
// Copyright 2021 Chiral Ltd. // Licensed under the Apache-2.0 license (https://opensource.org/licenses/Apache-2.0) // This file may not be copied, modified, or distributed // except according to those terms. //! Cycle related operations //! use super::orbit_ops; use super::graph; /// Extend on edge in the graph, store all the cyclic routes and the open routes fn extend_one_edge<T: graph::Vertex>( open_route: &Vec<usize>, vv: &graph::VertexVec<T>, cyclic_routes: &mut Vec<Vec<usize>>, open_routes: &mut Vec<Vec<usize>> ) { let length = open_route.len(); for ni in vv[open_route[length - 1]].neighbour_indexes() { if open_route.contains(&ni) { if (ni == open_route[0]) && (open_route.len() > 2) { cyclic_routes.push(open_route.clone()); } } else { let mut indexes_tmp = open_route.clone(); indexes_tmp.push(ni); open_routes.push(indexes_tmp); } } } /// Find the size of the minimun cycle which the vertex belongs to. If the vertex is acylic, return 0 pub fn cycle_size<T: graph::Vertex>( vertex_index: usize, vv: &graph::VertexVec<T> ) -> usize { let mut open_routes: Vec<Vec<usize>> = vec![vec![vertex_index]]; let mut cyclic_routes: Vec<Vec<usize>> = vec![]; while open_routes.len() > 0 { let open_routes_tmp = open_routes.clone(); open_routes.clear(); for route in open_routes_tmp.iter() { extend_one_edge(route, vv, &mut cyclic_routes, &mut open_routes); if cyclic_routes.len() > 0 { return cyclic_routes[0].len() } } } 0 } /// Find cycles that the two specified vertices belong to. pub fn find_cycle_for_vertices<T: graph::Vertex>( vertice_idx_1: usize, vertice_idx_2: usize, vv: &graph::VertexVec<T>, max_steps: usize ) -> Option<Vec<usize>> { let mut open_routes: Vec<Vec<usize>> = vec![vec![vertice_idx_1]]; let mut cyclic_routes: Vec<Vec<usize>> = vec![]; for _ in 0..max_steps { let open_routes_tmp = open_routes.clone(); open_routes.clear(); for route in open_routes_tmp.iter() { extend_one_edge(route, vv, &mut cyclic_routes, &mut open_routes); } } cyclic_routes.sort_by_key(|r| r.len()); for route in cyclic_routes.iter() { if route.contains(&vertice_idx_2) { return Some(route.clone()) } } return None } /// Find vertex cycles that include the specified vertex, with a maximum size. If one cycle is found, return fn find_cycles<T: graph::Vertex>( vertex_index: usize, vv: &graph::VertexVec<T>, max_cycle_size: usize ) -> Vec<Vec<usize>> { let mut open_routes: Vec<Vec<usize>> = vec![vec![vertex_index]]; let mut cyclic_routes: Vec<Vec<usize>> = vec![]; while open_routes.len() > 0 && open_routes[0].len() <= max_cycle_size { let open_routes_tmp = open_routes.clone(); open_routes.clear(); for route in open_routes_tmp.iter() { extend_one_edge(route, vv, &mut cyclic_routes, &mut open_routes); if cyclic_routes.len() > 0 { return cyclic_routes } } } vec![] } /// Find all the cycles that include the specified vertex. pub fn find_all_cycles<T: graph::Vertex>( vertex_index: usize, vv: &graph::VertexVec<T>, max_cycle_size: usize ) -> Vec<Vec<usize>> { let mut open_routes: Vec<Vec<usize>> = vec![vec![vertex_index]]; let mut cyclic_routes: Vec<Vec<usize>> = vec![]; while open_routes.len() > 0 && open_routes[0].len() <= max_cycle_size { let open_routes_tmp = open_routes.clone(); open_routes.clear(); for route in open_routes_tmp.iter() { extend_one_edge(route, vv, &mut cyclic_routes, &mut open_routes); } } orbit_ops::orbits_sort(&mut cyclic_routes); cyclic_routes.dedup(); cyclic_routes } /// Find related cycles that include any vertex in the orbits pub fn get_cycles_from_orbits<T: graph::Vertex>( orbits: &Vec<orbit_ops::Orbit>, vv: &graph::VertexVec<T>, max_cycle_size: usize, ) -> Vec<Vec<usize>> { let mut cycles: Vec<Vec<usize>> = vec![]; for orbit in orbits.iter() { for &idx in orbit.iter() { cycles.append(&mut find_cycles(idx, vv, max_cycle_size)); } } cycles } /// Merge cycles that share any vertex in a given set of cycles. pub fn merge_cycles( cycles: &Vec<Vec<usize>> ) -> Vec<Vec<usize>> { let mut isolated_cycles: Vec<Vec<usize>> = vec![]; let mut cycles_cloned = cycles.to_vec(); while cycles_cloned.len() > 0 { if let Some(mut cycle) = cycles_cloned.pop() { let mut is_isolated: bool = true; for idx in 0..cycles_cloned.len() { if orbit_ops::orbit_overlap(&cycle, &cycles_cloned[idx]) { is_isolated = false; cycles_cloned[idx].append(&mut cycle); cycles_cloned[idx].sort_unstable(); cycles_cloned[idx].dedup(); break; } } if is_isolated { isolated_cycles.push(cycle); } } } isolated_cycles } #[cfg(test)] mod test_core_cycle_ops { use super::*; use crate::ext::molecule; #[test] fn test_extend_one_edge() { let smiles: String = "c1ccccc1CN".to_string(); let mol = molecule::Molecule::from_smiles(&smiles); let vv = graph::VertexVec::init((0..mol.atoms.len()).collect(), mol.atoms.clone()); let mut cyclic_routes: Vec<Vec<usize>> = vec![]; let mut open_routes: Vec<Vec<usize>> = vec![]; extend_one_edge(&vec![6], &vv, &mut cyclic_routes, &mut open_routes); assert_eq!(open_routes, vec![vec![6, 5], vec![6, 7]]); open_routes.clear(); cyclic_routes.clear(); extend_one_edge(&vec![6, 5], &vv, &mut cyclic_routes, &mut open_routes); assert_eq!(open_routes, vec![vec![6, 5, 4], vec![6, 5, 0]]); } #[test] fn test_cyclic_size_find_cycles() { let smiles: String = "NCCCNCCCCN(CCCN)C(=O)CCCCNC(=O)c1ccc(-c2c3nc(c(-c4ccc(C(=O)NCCCCC(=O)N(CCCN)CCCCNCCCN)cc4)c4ccc([nH]4)c(-c4ccc(C(=O)NCCCCC(=O)N(CCCN)CCCCNCCCN)cc4)c4nc(c(-c5ccc(C(=O)NCCCCC(=O)N(CCCN)CCCCNCCCN)cc5)c5ccc2[nH]5)C=C4)C=C3)cc1".to_string(); let mol = molecule::Molecule::from_smiles(&smiles); let vv = graph::VertexVec::init((0..mol.atoms.len()).collect(), mol.atoms.clone()); assert_eq!(cycle_size(65, &vv), 5); assert_eq!(find_cycles(65, &vv, 4).len(), 0); assert_eq!(find_cycles(65, &vv, 5)[0].len(), 5); assert_eq!(find_cycles(65, &vv, 6)[0].len(), 5); assert_eq!(cycle_size(31, &vv), 16); assert_eq!(cycle_size(1, &vv), 0); } #[test] fn tet_find_cycle_for_vertices() { let smiles: String = "c1ccccc1CN".to_string(); let mol = molecule::Molecule::from_smiles(&smiles); let vv = graph::VertexVec::init((0..mol.atoms.len()).collect(), mol.atoms.clone()); assert_eq!(find_cycle_for_vertices(0, 6, &vv, 6), None); assert_eq!(find_cycle_for_vertices(0, 5, &vv, 6), Some(vec![0, 5, 4, 3, 2, 1])); assert_eq!(find_cycle_for_vertices(0, 5, &vv, 5), None); } #[test] fn test_find_all_cycles() { type ParamType1 = String; type ParamType2 = usize; type ReturnType = usize; let test_data: Vec<(ParamType1, ParamType2, ReturnType)> = vec![ ("c1ccc2cc3ccccc3cc2c1", 1, 1), ("c1ccc2cc3ccccc3cc2c1", 3, 2), ("c1ccc2cc3ccccc3cc2c1", 11, 1), ("CCOC12c3c4cccc3Oc3cccc(c31)Oc1cccc(c12)O4", 3, 3), ("CCOC12c3c4cccc3Oc3cccc(c31)Oc1cccc(c12)O4", 4, 3), ("CCOC12c3c4cccc3Oc3cccc(c31)Oc1cccc(c12)O4", 16, 3), ].iter().map(|td| (td.0.to_string(), td.1.clone(), td.2.clone())).collect(); for td in test_data.iter() { let (smiles, vertex_index, cycle_count) = td; let mol = molecule::Molecule::from_smiles(&smiles); println!("{}", mol.smiles_with_index(&smiles, &vec![])); let vv = graph::VertexVec::init((0..mol.atoms.len()).collect(), mol.atoms.clone()); assert_eq!(find_all_cycles(*vertex_index, &vv, 6).len(), *cycle_count); } } #[test] fn test_get_cycles_from_orbits() { let smiles_vec: Vec<String> = vec![ "CC(C)(C)c1cc2c(OCCCCNC(=N)N)c(c1)Cc1cc(C(C)(C)C)cc(c1OCCCCNC(=N)N)Cc1cc(C(C)(C)C)cc(c1OCCCCNC(=N)N)Cc1cc(C(C)(C)C)cc(c1OCCCCNC(=N)N)C2".to_string() ].iter().map(|s| s.to_string()).collect(); let params: Vec<(Vec<orbit_ops::Orbit>, Vec<orbit_ops::Orbit>)> = vec![ ( vec![vec![4, 22], vec![7, 28], vec![79, 39]], vec![vec![4, 5, 6, 7, 17, 18], vec![4, 5, 6, 7, 17, 18], vec![20, 21, 22, 27, 28, 29], vec![20, 21, 22, 27, 28, 29]] ) ]; for idx in 0..smiles_vec.len() { let mol = molecule::Molecule::from_smiles(&smiles_vec[idx]); if cfg!(debug_assertions) { println!("{}", mol.smiles_with_index(&smiles_vec[idx], &vec![])); } let vv = graph::VertexVec::init((0..mol.atoms.len()).collect(), mol.atoms.clone()); let mut cycles = get_cycles_from_orbits(&params[idx].0, &vv, 6); orbit_ops::orbits_sort(&mut cycles); assert_eq!(cycles, params[idx].1); } } #[test] fn test_merge_cycles() { let params: Vec<(Vec<Vec<usize>>, Vec<Vec<usize>>)> = vec![ (vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]], vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]]), (vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8], vec![1, 9, 10]], vec![vec![1, 2, 3, 4, 9, 10], vec![5, 6, 7, 8]]), (vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8], vec![1, 9, 10], vec![5, 11, 12], vec![1, 5]], vec![vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]), ]; for param in params.iter() { let mut cycles_merged = merge_cycles(&param.0); orbit_ops::orbits_sort(&mut cycles_merged); assert_eq!(cycles_merged, param.1); } } }
use super::Part; use crate::codec::{Decode, Encode}; use crate::{remote_type, RemoteEnum, RemoteObject}; remote_type!( /// A wheel. Includes landing gear and rover wheels. Obtained by calling `Part::wheel()`. Can be /// used to control the motors, steering and deployment of wheels, among other things. object SpaceCenter.Wheel { properties: { { Part { /// Returns the part object for this wheel. /// /// **Game Scenes**: All get: part -> Part } } { State { /// Returns the current state of the wheel. /// /// **Game Scenes**: All get: state -> WheelState } } { Radius { /// Returns the radius of the wheel, in meters. /// /// **Game Scenes**: All get: radius -> f32 } } { Grounded { /// Returns whether the wheel is touching the ground. /// /// **Game Scenes**: All get: is_grounded -> bool } } { HasBrakes { /// Returns whether the wheel has brakes. /// /// **Game Scenes**: All get: has_brakes -> bool } } { Brakes { /// Returns the braking force, as a percentage of maximum, when the brakes are applied. /// /// **Game Scenes**: All get: braking_force -> f32, /// Sets the braking force, as a percentage of maximum, when the brakes are applied. /// /// **Game Scenes**: All set: set_braking_force(f32) } } { AutoFrictionControl { /// Returns whether automatic friction control is enabled. /// /// **Game Scenes**: All get: is_auto_friction_control_enabled -> bool, /// Sets whether automatic friction control is enabled. /// /// **Game Scenes**: All set: set_auto_friction_control_enabled(bool) } } { ManualFrictionControl { /// Returns the manual friction control value. A value between 0 and 5 inclusive. /// /// **Game Scenes**: All get: manual_friction_control -> f32, /// Sets the manual friction control value. Only has an effect if automatic friction /// control is disabled. A value between 0 and 5 inclusive. /// /// **Game Scenes**: All set: set_manual_friction_control(f32) } } { Deployable { /// Returns whether the wheel is deployable. /// /// **Game Scenes**: All get: is_deployable -> bool } } { Deployed { /// Returns whether the wheel is deployed. /// /// **Game Scenes**: All get: is_deployed -> bool, /// Sets whether the wheel is deployed. /// /// **Game Scenes**: All set: set_deployed(bool) } } { MotorEnabled { /// Returns whether the motor is enabled. /// /// **Game Scenes**: All get: is_motor_enabled -> bool, /// Sets whether the motor is enabled. /// /// **Game Scenes**: All set: set_motor_enabled(bool) } } { MotorInverted { /// Returns whether the motor is inverted. /// /// **Game Scenes**: All get: is_motor_inverted -> bool, /// Sets whether the motor is inverted. /// /// **Game Scenes**: All set: set_motor_inverted(bool) } } { MotorState { /// Returns the motor state. /// /// **Game Scenes**: All get: motor_state -> MotorState } } { MotorOutput { /// Returns the output of the motor. This is the torque currently being generated, /// in Newton meters. /// /// **Game Scenes**: All get: motor_output -> f32 } } { TractionControlEnabled { /// Returns whether automatic traction control is enabled. A wheel only has traction /// control if it is powered. /// /// **Game Scenes**: All get: is_traction_control_enabled -> bool, /// Sets whether automatic traction control is enabled. A wheel only has traction /// control if it is powered. /// /// **Game Scenes**: All set: set_traction_control_enabled(bool) } } { TractionControl { /// Returns the setting for the traction control. A value between 0 and 5 inclusive. /// /// **Game Scenes**: All get: traction_control -> f32, /// Sets the setting for the traction control. Only takes effect if the wheel has /// automatic traction control enabled. A value between 0 and 5 inclusive. /// /// **Game Scenes**: All set: set_traction_control(f32) } } { DriveLimiter { /// Returns the manual setting for the motor limiter. A value between /// 0 and 100 inclusive. /// /// **Game Scenes**: All get: drive_limiter -> f32, /// Sets the manual setting for the motor limiter. Only takes effect if the /// wheel has automatic traction control disabled. A value between 0 and 100 inclusive. /// /// **Game Scenes**: All set: set_drive_limiter(f32) } } { Steerable { /// Returns whether the wheel has steering. /// /// **Game Scenes**: All get: is_steerable -> bool } } { SteeringEnabled { /// Returns whether the wheel steering is enabled. /// /// **Game Scenes**: All get: is_steering_enabled -> bool, /// Sets whether the wheel steering is enabled. /// /// **Game Scenes**: All set: set_steering_enabled(bool) } } { SteeringInverted { /// Returns whether the wheel steering is inverted. /// /// **Game Scenes**: All get: is_steering_inverted -> bool, /// Sets whether the wheel steering is inverted. /// /// **Game Scenes**: All set: set_steering_inverted(bool) } } { HasSuspension { /// Returns whether the wheel has suspension. /// /// **Game Scenes**: All get: has_suspension -> bool } } { SuspensionSpringStrength { /// Returns the suspension spring strength, as set in the editor. /// /// **Game Scenes**: All get: suspension_spring_strength -> f32 } } { SuspensionDamperStrength { /// Returns the suspension damper strength, as set in the editor. /// /// **Game Scenes**: All get: suspension_damper_strength -> f32 } } { Broken { /// Returns whether the wheel is broken. /// /// **Game Scenes**: All get: is_broken -> bool } } { Repairable { /// Returns whether the wheel is repairable. /// /// **Game Scenes**: All get: is_repairable -> bool } } { Stress { /// Returns the current stress on the wheel. /// /// **Game Scenes**: All get: stress -> f32 } } { StressTolerance { /// Returns the stress tolerance of the wheel. /// /// **Game Scenes**: All get: stress_tolerance -> f32 } } { StressPercentage { /// Returns the current stress on the wheel as a percentage of its stress tolerance. /// /// **Game Scenes**: All get: stress_percentage -> f32 } } { Deflection { /// Returns the current deflection of the wheel. /// /// **Game Scenes**: All get: deflection -> f32 } } { Slip { /// Returns the current slip of the wheel. /// /// **Game Scenes**: All get: slip -> f32 } } } }); remote_type!( /// The state of a wheel. See `Wheel:state`. enum WheelState { /// Wheel is fully deployed. Deployed = 0, /// Wheel is fully retracted. Retracted = 1, /// Wheel is being deployed. Deploying = 2, /// Wheel is being retracted. Retracting = 3, /// Wheel is broken. Broken = 4, } ); remote_type!( /// The state of the motor on a powered wheel. See `Wheel::motor_state()`. enum MotorState { /// The motor is idle. Idle = 0, /// The motor is running. Running = 1, /// The motor is disabled. Disabled = 2, /// The motor is inoperable. Inoperable = 3, /// The motor does not have enough resources to run. NotEnoughResources = 4, } );
use crate::{ app::{ config::{self, Rgba}, sample::{create_sample_plume, create_sample_sounding, Sample}, AppContext, AppContextPointer, ZoomableDrawingAreas, }, coords::{ convert_pressure_to_y, convert_y_to_pressure, DeviceCoords, ScreenCoords, ScreenRect, TPCoords, XYCoords, }, errors::SondeError, gui::{ plot_context::{GenericContext, HasGenericContext}, utility::{check_overlap_then_add, plot_curve_from_points, plot_dashed_curve_from_points}, Drawable, DrawingArgs, MasterDrawable, PlotContext, PlotContextExt, }, }; use gtk::{ prelude::*, DrawingArea, EventControllerKey, EventControllerMotion, EventControllerScroll, EventControllerScrollFlags, GestureClick, Inhibit, }; use itertools::izip; use metfor::{Celsius, Feet, Quantity}; use sounding_analysis::{self, Parcel, ParcelProfile}; use std::rc::Rc; pub struct SkewTContext { generic: GenericContext, } impl SkewTContext { pub fn new() -> Self { SkewTContext { generic: GenericContext::new(), } } pub fn convert_tp_to_xy(coords: TPCoords) -> XYCoords { let y = convert_pressure_to_y(coords.pressure); let x = (coords.temperature - config::MINT) / (config::MAXT - config::MINT); // do the skew let x = x + y; XYCoords { x, y } } pub fn convert_xy_to_tp(coords: XYCoords) -> TPCoords { // undo the skew let x = coords.x - coords.y; let y = coords.y; let t = config::MINT + (config::MAXT - config::MINT) * x; let p = convert_y_to_pressure(y); TPCoords { temperature: t, pressure: p, } } pub fn convert_tp_to_screen(&self, coords: TPCoords) -> ScreenCoords { let xy = Self::convert_tp_to_xy(coords); self.convert_xy_to_screen(xy) } pub fn convert_screen_to_tp(&self, coords: ScreenCoords) -> TPCoords { let xy = self.convert_screen_to_xy(coords); Self::convert_xy_to_tp(xy) } pub fn convert_device_to_tp(&self, coords: DeviceCoords) -> TPCoords { let xy = self.convert_device_to_xy(coords); Self::convert_xy_to_tp(xy) } } impl HasGenericContext for SkewTContext { fn get_generic_context(&self) -> &GenericContext { &self.generic } } impl PlotContextExt for SkewTContext {} impl Drawable for SkewTContext { /*********************************************************************************************** * Initialization **********************************************************************************************/ fn set_up_drawing_area(acp: &AppContextPointer) -> Result<(), SondeError> { let da: DrawingArea = acp.fetch_widget("skew_t")?; // Set up the drawing function. let ac = Rc::clone(acp); da.set_draw_func(move |_da, cr, _width, _height| { ac.skew_t.draw_callback(cr, &ac); }); // Set up the scroll (or zoom in/out) callbacks. let ac = Rc::clone(acp); let scroll_control = EventControllerScroll::new(EventControllerScrollFlags::VERTICAL); scroll_control.connect_scroll(move |_scroll_control, _dx, dy| { ac.mark_background_dirty(); ac.skew_t.scroll_event(dy, &ac); Inhibit(true) }); da.add_controller(scroll_control); // Set up the button clicks. let left_mouse_button = GestureClick::builder().build(); let ac = Rc::clone(acp); left_mouse_button.connect_pressed(move |_mouse_button, _n_pressed, x, y| { ac.skew_t.left_button_press_event((x, y), &ac); }); let ac = Rc::clone(acp); left_mouse_button.connect_released(move |_mouse_button, _n_press, x, y| { ac.skew_t.left_button_release_event((x, y), &ac); }); da.add_controller(left_mouse_button); let right_mouse_button = GestureClick::builder().button(3).build(); let ac = Rc::clone(acp); right_mouse_button.connect_released(move |_mouse_button, _n_press, x, y| { ac.skew_t.right_button_release_event((x, y), &ac); }); da.add_controller(right_mouse_button); // Set up the mouse motion events let mouse_motion = EventControllerMotion::new(); let ac = Rc::clone(acp); mouse_motion.connect_motion(move |mouse_motion, x, y| { ac.skew_t.mouse_motion_event(mouse_motion, (x, y), &ac); }); let ac = Rc::clone(acp); mouse_motion.connect_enter(move |_mouse_motion, _x, _y| { ac.skew_t.enter_event(&ac); }); let ac = Rc::clone(acp); mouse_motion.connect_leave(move |_mouse_motion| { ac.skew_t.leave_event(&ac); }); da.add_controller(mouse_motion); // Set up the key presses. let key_press = EventControllerKey::new(); let ac = Rc::clone(acp); key_press.connect_key_pressed(move |_key_press, key, _code, _key_modifier| { SkewTContext::key_press_event(key, &ac) }); da.add_controller(key_press); let ac = Rc::clone(acp); da.connect_resize(move |da, width, height| { // TODO merge below methods into one. ac.skew_t.size_allocate_event(da); ac.skew_t.resize_event(width, height, &ac); }); Self::build_sounding_area_context_menu(acp)?; Ok(()) } /*********************************************************************************************** * Background Drawing. **********************************************************************************************/ fn draw_background_fill(&self, args: DrawingArgs<'_, '_>) { let config = args.ac.config.borrow(); self.draw_clear_background(args); if config.show_background_bands { self.draw_temperature_banding(args); } if config.show_hail_zone { self.draw_hail_growth_zone(args); } if config.show_dendritic_zone { self.draw_dendtritic_growth_zone(args); } } fn draw_background_lines(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow()); // Draws background lines from the bottom up. // Draw isentrops if config.show_isentrops { for pnts in config::ISENTROP_PNTS.iter() { let pnts = pnts .iter() .map(|xy_coords| self.convert_xy_to_screen(*xy_coords)); plot_curve_from_points( cr, config.background_line_width, config.isentrop_rgba, pnts, ); } } // Draw theta-e lines if config.show_iso_theta_e { for pnts in config::ISO_THETA_E_PNTS.iter() { let pnts = pnts .iter() .map(|xy_coords| self.convert_xy_to_screen(*xy_coords)); plot_curve_from_points( cr, config.background_line_width, config.iso_theta_e_rgba, pnts, ); } } // Draw mixing ratio lines if config.show_iso_mixing_ratio { for pnts in config::ISO_MIXING_RATIO_PNTS.iter() { let pnts = pnts .iter() .map(|xy_coords| self.convert_xy_to_screen(*xy_coords)); plot_dashed_curve_from_points( cr, config.background_line_width, config.iso_mixing_ratio_rgba, pnts, ); } } // Draw isotherms if config.show_isotherms { for pnts in config::ISOTHERM_PNTS.iter() { let pnts = pnts .iter() .map(|tp_coords| self.convert_xy_to_screen(*tp_coords)); plot_curve_from_points( cr, config.background_line_width, config.isotherm_rgba, pnts, ); } } // Draw isobars if config.show_isobars { for pnts in config::ISOBAR_PNTS.iter() { let pnts = pnts .iter() .map(|xy_coords| self.convert_xy_to_screen(*xy_coords)); plot_curve_from_points(cr, config.background_line_width, config.isobar_rgba, pnts); } } // Draw the freezing line if config.show_freezing_line { let pnts = &[ TPCoords { temperature: Celsius(0.0), pressure: config::MAXP, }, TPCoords { temperature: Celsius(0.0), pressure: config::MINP, }, ]; let pnts = pnts .iter() .map(|tp_coords| self.convert_tp_to_screen(*tp_coords)); plot_curve_from_points( cr, config.freezing_line_width, config.freezing_line_color, pnts, ); } } fn collect_labels(&self, args: DrawingArgs<'_, '_>) -> Vec<(String, ScreenRect)> { let (ac, cr, config) = (args.ac, args.cr, args.ac.config.borrow()); let mut labels = vec![]; let screen_edges = self.calculate_plot_edges(cr, ac); let ScreenRect { lower_left, .. } = screen_edges; if config.show_isobars { for &p in &config::ISOBARS { let label = format!("{:.0}", p.unpack()); let extents = cr.text_extents(&label).unwrap(); let ScreenCoords { y: screen_y, .. } = self.convert_tp_to_screen(TPCoords { temperature: Celsius(0.0), pressure: p, }); let screen_y = screen_y - extents.height() / 2.0; let label_lower_left = ScreenCoords { x: lower_left.x, y: screen_y, }; let label_upper_right = ScreenCoords { x: lower_left.x + extents.width(), y: screen_y + extents.height(), }; let pair = ( label, ScreenRect { lower_left: label_lower_left, upper_right: label_upper_right, }, ); check_overlap_then_add(cr, ac, &mut labels, &screen_edges, pair); } } if config.show_isotherms { let TPCoords { pressure: screen_max_p, .. } = self.convert_screen_to_tp(lower_left); for &t in &config::ISOTHERMS { let label = format!("{:.0}", t.unpack()); let extents = cr.text_extents(&label).unwrap(); let ScreenCoords { x: mut xpos, y: mut ypos, } = self.convert_tp_to_screen(TPCoords { temperature: t, pressure: screen_max_p, }); xpos -= extents.width() / 2.0; // Center ypos -= extents.height() / 2.0; // Center ypos += extents.height(); // Move up off bottom axis. xpos += extents.height(); // Move right for 45 degree angle from move up let label_lower_left = ScreenCoords { x: xpos, y: ypos }; let label_upper_right = ScreenCoords { x: xpos + extents.width(), y: ypos + extents.height(), }; let pair = ( label, ScreenRect { lower_left: label_lower_left, upper_right: label_upper_right, }, ); check_overlap_then_add(cr, ac, &mut labels, &screen_edges, pair); } } labels } fn build_legend_strings(ac: &AppContext) -> Vec<(String, Rgba)> { use chrono::Weekday::*; let color = ac.config.borrow().label_rgba; let mut result = vec![]; if let Some(anal) = ac.get_sounding_for_display() { if let Some(src_desc) = anal.borrow().sounding().source_description() { result.push((src_desc.to_owned(), color)); } } if let Some(anal) = ac.get_sounding_for_display() { let anal = anal.borrow(); let snd = anal.sounding(); // Build the valid time part if let Some(vt) = snd.valid_time() { use chrono::{Datelike, Timelike}; let mut temp_string = format!( "Valid: {} {:02}/{:02}/{:04} {:02}Z", match vt.weekday() { Sun => "Sunday", Mon => "Monday", Tue => "Tuesday", Wed => "Wednesday", Thu => "Thursday", Fri => "Friday", Sat => "Saturday", }, vt.month(), vt.day(), vt.year(), vt.hour() ); if let Some(lt) = snd.lead_time().into_option() { temp_string.push_str(&format!(" F{:03}", lt)); } result.push((temp_string, color)); } // Build location part. let coords = snd.station_info().location(); let elevation = snd.station_info().elevation(); if coords.is_some() || elevation.is_some() { let mut location = "".to_owned(); if let Some((lat, lon)) = coords { location.push_str(&format!("{:.2}, {:.2}", lat, lon)); if elevation.is_some() { location.push_str(", "); } } if let Some(el) = elevation.into_option() { location.push_str(&format!( "{:.0}m ({:.0}ft)", el.unpack(), Feet::from(el).unpack() )); } result.push((location, color)); } } result } /*********************************************************************************************** * Data Drawing. **********************************************************************************************/ fn draw_data(&self, args: DrawingArgs<'_, '_>) { Self::draw_temperature_profiles(args); Self::draw_wind_profile(args); Self::draw_data_overlays(args); // Drawing the precip icon requires self because it draws relative to the window (like the // legend) and not just in data or X-Y coordinates. self.draw_precip_icons(args); } /*********************************************************************************************** * Overlays Drawing. **********************************************************************************************/ fn create_active_readout_text(vals: &Sample, ac: &AppContext) -> Vec<(String, Rgba)> { let mut results = vec![]; let anal = if let Some(anal) = ac.get_sounding_for_display() { anal } else { return results; }; let anal = anal.borrow(); let config = ac.config.borrow(); match vals { Sample::Sounding { ref data, ref pcl_anal, } => { Self::create_active_readout_text_sounding( data, &anal, pcl_anal, &config, &mut results, ); } Sample::FirePlume { parcel_low, plume_anal_low, plume_anal_high, .. } => Self::create_active_readout_text_plume( parcel_low, &anal, plume_anal_low, plume_anal_high, &config, &mut results, ), Sample::None => {} } results } fn draw_active_readout(&self, args: DrawingArgs<'_, '_>) { let config = args.ac.config.borrow(); if config.show_active_readout { self.draw_active_sample(args); match *args.ac.get_sample() { Sample::Sounding { data, ref pcl_anal } => { if let Some(sample_parcel) = Parcel::from_datarow(data) { if config.show_sample_mix_down { Self::draw_sample_mix_down_profile(args, sample_parcel); } } if config.show_sample_parcel_profile { Self::draw_sample_parcel_profile(args, pcl_anal); } } Sample::FirePlume { parcel_low, ref profile_low, ref profile_high, .. } => { if config.show_sample_parcel_profile { Self::draw_plume_parcel_profiles( args, parcel_low, profile_low, profile_high, ); } } Sample::None => {} } } } /*********************************************************************************************** * Events **********************************************************************************************/ fn enter_event(&self, ac: &AppContextPointer) { ac.set_last_focus(ZoomableDrawingAreas::SkewT); } fn right_button_release_event(&self, _position: (f64, f64), ac: &AppContextPointer) { if let Ok(popover) = ac.fetch_widget::<gtk::PopoverMenu>("skew_t_popover") { if let Some(pos) = self.get_last_cursor_position() { let llx: i32 = pos.col as i32; let lly: i32 = pos.row as i32; let rect = gtk::gdk::Rectangle::new(llx, lly, 1, 1); popover.set_pointing_to(Some(&rect)); popover.popup(); } } } fn mouse_motion_event( &self, controller: &EventControllerMotion, new_position: (f64, f64), ac: &AppContextPointer, ) { let da: DrawingArea = controller.widget().downcast().unwrap(); da.grab_focus(); let position = DeviceCoords::from(new_position); if self.get_left_button_pressed() { if let Some(last_position) = self.get_last_cursor_position() { let old_position = self.convert_device_to_xy(last_position); let new_position = self.convert_device_to_xy(position); let delta = ( new_position.x - old_position.x, new_position.y - old_position.y, ); let mut translate = self.get_translate(); translate.x -= delta.0; translate.y -= delta.1; self.set_translate(translate); self.bound_view(); ac.mark_background_dirty(); crate::gui::draw_all(ac); crate::gui::text_area::update_text_highlight(ac); ac.set_sample(Sample::None); } } else if ac.plottable() { let tp_position = self.convert_device_to_tp(position); let sample = if let Some(max_p) = ac .get_sounding_for_display() .map(|anal| anal.borrow().max_pressure()) { if tp_position.pressure <= max_p { // This is a sample from some level in the sounding. ac.get_sounding_for_display() .and_then(|anal| { sounding_analysis::linear_interpolate_sounding( anal.borrow().sounding(), tp_position.pressure, ) .ok() .map(|data| create_sample_sounding(data, &anal.borrow())) }) .unwrap_or(Sample::None) } else { // We are below the lowest level in the sounding, so lets generate a plume // parcel! ac.get_sounding_for_display() .and_then(|anal| { let anal = anal.borrow(); anal.starting_parcel_for_blow_up_anal() .filter(|pcl| pcl.temperature < tp_position.temperature) .map(|parcel| { create_sample_plume(parcel, tp_position.temperature, &anal) }) }) .unwrap_or(Sample::None) } } else { Sample::None }; ac.set_sample(sample); ac.mark_overlay_dirty(); crate::gui::draw_all(ac); crate::gui::text_area::update_text_highlight(ac); } self.set_last_cursor_position(Some(position)); } } impl MasterDrawable for SkewTContext {} mod active_readout; mod background; mod data_layer; mod menu; mod wind; impl SkewTContext { fn draw_parcel_profile(args: DrawingArgs<'_, '_>, profile: &ParcelProfile, line_rgba: Rgba) { let (ac, cr) = (args.ac, args.cr); let config = ac.config.borrow(); let pres_data = &profile.pressure; let temp_data = &profile.parcel_t; let line_width = config.temperature_line_width; let profile_data = izip!(pres_data, temp_data).filter_map(|(&pressure, &temperature)| { if pressure > config::MINP { let tp_coords = TPCoords { temperature, pressure, }; Some(ac.skew_t.convert_tp_to_screen(tp_coords)) } else { None } }); plot_dashed_curve_from_points(cr, line_width, line_rgba, profile_data); } }
fn main() { let om_mat: f32 = 907.0; let tm_mat: f32 = 1050.0; let om_fsc: f32 = 918.0; let tm_fsc: f32 = 1100.0; let div_1: f32 = om_mat/tm_mat; let div_2: f32 = om_fsc/tm_fsc; let perc_mat = div_1 * 100.0; let perc_fsc = div_2 * 100.0; println!("Percentage (Matric) = {}", perc_mat); println!("Percentage (F.Sc) = {}", perc_fsc); }
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib::translate::*; use javascriptcore_sys; use std::fmt; #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] #[derive(Clone, Copy)] pub enum CheckSyntaxMode { Script, Module, #[doc(hidden)] __Unknown(i32), } impl fmt::Display for CheckSyntaxMode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "CheckSyntaxMode::{}", match *self { CheckSyntaxMode::Script => "Script", CheckSyntaxMode::Module => "Module", _ => "Unknown", }) } } #[doc(hidden)] impl ToGlib for CheckSyntaxMode { type GlibType = javascriptcore_sys::JSCCheckSyntaxMode; fn to_glib(&self) -> javascriptcore_sys::JSCCheckSyntaxMode { match *self { CheckSyntaxMode::Script => javascriptcore_sys::JSC_CHECK_SYNTAX_MODE_SCRIPT, CheckSyntaxMode::Module => javascriptcore_sys::JSC_CHECK_SYNTAX_MODE_MODULE, CheckSyntaxMode::__Unknown(value) => value } } } #[doc(hidden)] impl FromGlib<javascriptcore_sys::JSCCheckSyntaxMode> for CheckSyntaxMode { fn from_glib(value: javascriptcore_sys::JSCCheckSyntaxMode) -> Self { skip_assert_initialized!(); match value { 0 => CheckSyntaxMode::Script, 1 => CheckSyntaxMode::Module, value => CheckSyntaxMode::__Unknown(value), } } } #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] #[derive(Clone, Copy)] pub enum CheckSyntaxResult { Success, RecoverableError, IrrecoverableError, UnterminatedLiteralError, OutOfMemoryError, StackOverflowError, #[doc(hidden)] __Unknown(i32), } impl fmt::Display for CheckSyntaxResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "CheckSyntaxResult::{}", match *self { CheckSyntaxResult::Success => "Success", CheckSyntaxResult::RecoverableError => "RecoverableError", CheckSyntaxResult::IrrecoverableError => "IrrecoverableError", CheckSyntaxResult::UnterminatedLiteralError => "UnterminatedLiteralError", CheckSyntaxResult::OutOfMemoryError => "OutOfMemoryError", CheckSyntaxResult::StackOverflowError => "StackOverflowError", _ => "Unknown", }) } } #[doc(hidden)] impl ToGlib for CheckSyntaxResult { type GlibType = javascriptcore_sys::JSCCheckSyntaxResult; fn to_glib(&self) -> javascriptcore_sys::JSCCheckSyntaxResult { match *self { CheckSyntaxResult::Success => javascriptcore_sys::JSC_CHECK_SYNTAX_RESULT_SUCCESS, CheckSyntaxResult::RecoverableError => javascriptcore_sys::JSC_CHECK_SYNTAX_RESULT_RECOVERABLE_ERROR, CheckSyntaxResult::IrrecoverableError => javascriptcore_sys::JSC_CHECK_SYNTAX_RESULT_IRRECOVERABLE_ERROR, CheckSyntaxResult::UnterminatedLiteralError => javascriptcore_sys::JSC_CHECK_SYNTAX_RESULT_UNTERMINATED_LITERAL_ERROR, CheckSyntaxResult::OutOfMemoryError => javascriptcore_sys::JSC_CHECK_SYNTAX_RESULT_OUT_OF_MEMORY_ERROR, CheckSyntaxResult::StackOverflowError => javascriptcore_sys::JSC_CHECK_SYNTAX_RESULT_STACK_OVERFLOW_ERROR, CheckSyntaxResult::__Unknown(value) => value } } } #[doc(hidden)] impl FromGlib<javascriptcore_sys::JSCCheckSyntaxResult> for CheckSyntaxResult { fn from_glib(value: javascriptcore_sys::JSCCheckSyntaxResult) -> Self { skip_assert_initialized!(); match value { 0 => CheckSyntaxResult::Success, 1 => CheckSyntaxResult::RecoverableError, 2 => CheckSyntaxResult::IrrecoverableError, 3 => CheckSyntaxResult::UnterminatedLiteralError, 4 => CheckSyntaxResult::OutOfMemoryError, 5 => CheckSyntaxResult::StackOverflowError, value => CheckSyntaxResult::__Unknown(value), } } } #[cfg(any(feature = "v2_24", feature = "dox"))] #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] #[derive(Clone, Copy)] pub enum OptionType { Boolean, Int, Uint, Size, Double, String, RangeString, #[doc(hidden)] __Unknown(i32), } #[cfg(any(feature = "v2_24", feature = "dox"))] impl fmt::Display for OptionType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "OptionType::{}", match *self { OptionType::Boolean => "Boolean", OptionType::Int => "Int", OptionType::Uint => "Uint", OptionType::Size => "Size", OptionType::Double => "Double", OptionType::String => "String", OptionType::RangeString => "RangeString", _ => "Unknown", }) } } #[cfg(any(feature = "v2_24", feature = "dox"))] #[doc(hidden)] impl ToGlib for OptionType { type GlibType = javascriptcore_sys::JSCOptionType; fn to_glib(&self) -> javascriptcore_sys::JSCOptionType { match *self { OptionType::Boolean => javascriptcore_sys::JSC_OPTION_BOOLEAN, OptionType::Int => javascriptcore_sys::JSC_OPTION_INT, OptionType::Uint => javascriptcore_sys::JSC_OPTION_UINT, OptionType::Size => javascriptcore_sys::JSC_OPTION_SIZE, OptionType::Double => javascriptcore_sys::JSC_OPTION_DOUBLE, OptionType::String => javascriptcore_sys::JSC_OPTION_STRING, OptionType::RangeString => javascriptcore_sys::JSC_OPTION_RANGE_STRING, OptionType::__Unknown(value) => value } } } #[cfg(any(feature = "v2_24", feature = "dox"))] #[doc(hidden)] impl FromGlib<javascriptcore_sys::JSCOptionType> for OptionType { fn from_glib(value: javascriptcore_sys::JSCOptionType) -> Self { skip_assert_initialized!(); match value { 0 => OptionType::Boolean, 1 => OptionType::Int, 2 => OptionType::Uint, 3 => OptionType::Size, 4 => OptionType::Double, 5 => OptionType::String, 6 => OptionType::RangeString, value => OptionType::__Unknown(value), } } }
use super::expm1f; #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn tanhf(mut x: f32) -> f32 { /* x = |x| */ let mut ix = x.to_bits(); let sign = (ix >> 31) != 0; ix &= 0x7fffffff; x = f32::from_bits(ix); let w = ix; let tt = if w > 0x3f0c9f54 { /* |x| > log(3)/2 ~= 0.5493 or nan */ if w > 0x41200000 { /* |x| > 10 */ 1. + 0. / x } else { let t = expm1f(2. * x); 1. - 2. / (t + 2.) } } else if w > 0x3e82c578 { /* |x| > log(5/3)/2 ~= 0.2554 */ let t = expm1f(2. * x); t / (t + 2.) } else if w >= 0x00800000 { /* |x| >= 0x1p-126 */ let t = expm1f(-2. * x); -t / (t + 2.) } else { /* |x| is subnormal */ force_eval!(x * x); x }; if sign { -tt } else { tt } }
#![feature(bool_to_option, clamp)] // #![allow(dead_code)] // #![allow(unused_imports)] mod base_types; mod canvas; pub use base_types::*; pub use canvas::*;
use std::collections::HashSet; #[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)] struct Location { facing: i32, x: i32, y: i32 } impl Location { fn movement(&mut self, direction: String) { let turn = direction.chars().next(); let steps_string = &direction[1..direction.len()]; let steps = steps_string.parse::<i32> ().unwrap(); match turn { Some('L') => self.facing -= 1, Some('R') => self.facing += 1, Some(_) | None => panic!("Weird: Invalid Direction") } match self.facing { 1 | 5 => { self.facing = 1; self.y += steps; }, 2 => self.x += steps, 3 => self.y -= steps, 0 | 4 => { self.facing = 4; self.x -= steps; }, _ => panic!("Facing an Invalid Direction") }; } } pub fn find_distance(direction_string: String) { let mut start = Location { x: 0, y: 0, facing: 1 }; let location = direction_string.split(", ").fold(&mut start, |position, direction| { position.movement(String::from(direction)); return position; }); println!("{}", location.x.abs() + location.y.abs()); } pub fn find_twice_visited_place(direction_string: String) { let mut position = Location { x: 0, y: 0, facing: 1 }; let mut visited: HashSet<Location> = HashSet::new(); let visited_twice = direction_string.split(", ").map(|direction| { position.movement(String::from(direction)); return position; }).take_while(|&position| { visited.insert(position); println!("{:?}", visited); return !visited.contains(&position); }).count(); // println!("{}", visited_twice.x.abs() + visited_twice.y.abs()); println!("{}", visited_twice); }
pub type IAccessibleWinSAT = *mut ::core::ffi::c_void; pub type IInitiateWinSATAssessment = *mut ::core::ffi::c_void; pub type IProvideWinSATAssessmentInfo = *mut ::core::ffi::c_void; pub type IProvideWinSATResultsInfo = *mut ::core::ffi::c_void; pub type IProvideWinSATVisuals = *mut ::core::ffi::c_void; pub type IQueryAllWinSATAssessments = *mut ::core::ffi::c_void; pub type IQueryOEMWinSATCustomization = *mut ::core::ffi::c_void; pub type IQueryRecentWinSATAssessment = *mut ::core::ffi::c_void; pub type IWinSATInitiateEvents = *mut ::core::ffi::c_void; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const CAccessiblityWinSAT: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x6e18f9c6_a3eb_495a_89b7_956482e19f7a); #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const CInitiateWinSAT: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x489331dc_f5e0_4528_9fda_45331bf4a571); #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const CProvideWinSATVisuals: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x9f377d7e_e551_44f8_9f94_9db392b03b7b); #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const CQueryAllWinSAT: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x05df8d13_c355_47f4_a11e_851b338cefb8); #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const CQueryOEMWinSATCustomization: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xc47a41b7_b729_424f_9af9_5cb3934f2dfa); #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const CQueryWinSAT: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xf3bdfad3_f276_49e9_9b17_c474f48f0764); #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub type WINSAT_ASSESSMENT_STATE = i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_ASSESSMENT_STATE_MIN: WINSAT_ASSESSMENT_STATE = 0i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_ASSESSMENT_STATE_UNKNOWN: WINSAT_ASSESSMENT_STATE = 0i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_ASSESSMENT_STATE_VALID: WINSAT_ASSESSMENT_STATE = 1i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_ASSESSMENT_STATE_INCOHERENT_WITH_HARDWARE: WINSAT_ASSESSMENT_STATE = 2i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_ASSESSMENT_STATE_NOT_AVAILABLE: WINSAT_ASSESSMENT_STATE = 3i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_ASSESSMENT_STATE_INVALID: WINSAT_ASSESSMENT_STATE = 4i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_ASSESSMENT_STATE_MAX: WINSAT_ASSESSMENT_STATE = 4i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub type WINSAT_ASSESSMENT_TYPE = i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_ASSESSMENT_MEMORY: WINSAT_ASSESSMENT_TYPE = 0i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_ASSESSMENT_CPU: WINSAT_ASSESSMENT_TYPE = 1i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_ASSESSMENT_DISK: WINSAT_ASSESSMENT_TYPE = 2i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_ASSESSMENT_D3D: WINSAT_ASSESSMENT_TYPE = 3i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_ASSESSMENT_GRAPHICS: WINSAT_ASSESSMENT_TYPE = 4i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub type WINSAT_BITMAP_SIZE = i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_BITMAP_SIZE_SMALL: WINSAT_BITMAP_SIZE = 0i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_BITMAP_SIZE_NORMAL: WINSAT_BITMAP_SIZE = 1i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub type WINSAT_OEM_CUSTOMIZATION_STATE = i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_OEM_DATA_VALID: WINSAT_OEM_CUSTOMIZATION_STATE = 0i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_OEM_DATA_NON_SYS_CONFIG_MATCH: WINSAT_OEM_CUSTOMIZATION_STATE = 1i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_OEM_DATA_INVALID: WINSAT_OEM_CUSTOMIZATION_STATE = 2i32; #[doc = "*Required features: `\"Win32_System_AssessmentTool\"`*"] pub const WINSAT_OEM_NO_DATA_SUPPLIED: WINSAT_OEM_CUSTOMIZATION_STATE = 3i32;
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { _reserved0: [u8; 1536usize], #[doc = "0x600 - Address of first instruction to replace."] pub replaceaddr: [REPLACEADDR; 8], _reserved1: [u8; 96usize], #[doc = "0x680 - Relative address of patch instructions."] pub patchaddr: [PATCHADDR; 8], _reserved2: [u8; 96usize], #[doc = "0x700 - Patch enable register."] pub patchen: PATCHEN, #[doc = "0x704 - Patch enable register."] pub patchenset: PATCHENSET, #[doc = "0x708 - Patch disable register."] pub patchenclr: PATCHENCLR, } #[doc = "Address of first instruction to replace."] pub struct REPLACEADDR { register: ::vcell::VolatileCell<u32>, } #[doc = "Address of first instruction to replace."] pub mod replaceaddr; #[doc = "Relative address of patch instructions."] pub struct PATCHADDR { register: ::vcell::VolatileCell<u32>, } #[doc = "Relative address of patch instructions."] pub mod patchaddr; #[doc = "Patch enable register."] pub struct PATCHEN { register: ::vcell::VolatileCell<u32>, } #[doc = "Patch enable register."] pub mod patchen; #[doc = "Patch enable register."] pub struct PATCHENSET { register: ::vcell::VolatileCell<u32>, } #[doc = "Patch enable register."] pub mod patchenset; #[doc = "Patch disable register."] pub struct PATCHENCLR { register: ::vcell::VolatileCell<u32>, } #[doc = "Patch disable register."] pub mod patchenclr;
use std::env; use std::process; use rand::Rng; use std::fmt; #[derive(Debug)] struct Config { secret: u32, n: u32, k: u32, } #[derive(Debug)] struct Secret { fx: Vec<u128>, points: Vec<(u128, u128)>, } fn main() { //Create config struct let config = Config::new(env::args()).unwrap_or_else(|err| { eprintln!("Problem with parsing arguments: {}", err); process::exit(1); }); //Create the Secret struct and print out the results let secret = Secret::new(&config); println!("{}", secret); } impl Config { fn new(mut args: std::env::Args) -> Result<Config, &'static str> { //Skip the filename args.next(); let n = match args.next() { Some(arg) => arg.parse::<u32>().unwrap(), None => return Err("Didn't recieve a \'n\' number"), }; let k = match args.next() { Some(arg) => arg.parse::<u32>().unwrap(), None => return Err("Didn't recieve a \'k\' number"), }; let secret = match args.next() { Some(arg) => arg.parse::<u32>().unwrap(), None => return Err("Didn't recieve a \'secret\' number"), }; //Return the Config struct Ok(Config { secret, n, k, }) } } impl Secret { //Generate the polynomial fn new(config: &Config) -> Secret { let mut rng = rand::thread_rng(); let mut fx: Vec<u128> = vec![config.secret.into()]; let mut points: Vec< (u128, u128) > = vec![]; //Generate random k-1 numbers of the polynomial for _i in 1.. config.k { let number = rng.gen::<u16>(); fx.push(number.into()); } //Generate secret points for i in 1..config.n+1 { let mut power = 0; let mut sum = 0; for x in fx.iter() { sum += x * ((i.pow(power)) as u128); power += 1; } points.push( (i as u128, sum) ); } Secret { fx, points,} } } //Make the display more appealing impl fmt::Display for Secret { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut polynomial = String::from(""); let mut x = 0; for i in self.fx.iter() { polynomial.push_str(&format!("{}*x^{}", i, x)); if self.fx.len()-1 != x { polynomial.push_str(" + "); } x += 1; } write!(f, "===== Output ====\nPolynomial: {}\nShare points: {:?}\n=================", polynomial, self.points) } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { super::typeface::TypefaceAndLangScore, fidl_fuchsia_fonts::{Slant, TypefaceQuery, Width, WEIGHT_MEDIUM, WEIGHT_NORMAL}, }; /// Selects between typefaces `a` and `b` for the `request`. Typefaces are passed in /// `TypefaceAndLangScore` so the language match score is calculated only once for each typeface. If /// `a` and `b` are equivalent then `a` is returned. /// /// The style matching logic follows the CSS3 Fonts spec (see /// [Section 5.2, Item 4](https://www.w3.org/TR/css-fonts-3/#font-style-matching) with two /// additions: /// /// 1. Typefaces with a higher language match score are preferred. The score value is expected to /// be pre-calculated by `get_lang_match_score()`. Note that if the request specifies a code /// point then the typefaces are expected to be already filtered based on that code point, i.e. /// they both contain that character, so this function doesn't need to verify it. /// 2. If the request specifies a `fallback_family`, then fonts with the same `fallback_family` /// are preferred. pub fn select_best_match<'a, 'b>( a: TypefaceAndLangScore<'a>, b: TypefaceAndLangScore<'a>, query: &'b TypefaceQuery, ) -> TypefaceAndLangScore<'a> { if a.lang_score != b.lang_score { if a.lang_score < b.lang_score { return a; } else { return b; } } if let Some(fallback_family) = query.fallback_family { if a.typeface.generic_family != b.typeface.generic_family { if a.typeface.generic_family == Some(fallback_family) { return a; } else if b.typeface.generic_family == Some(fallback_family) { return b; } // If `generic_family` of `a` and `b` doesn't match the request, then fall through to // compare them based on style parameters. } } if let Some(query_style) = &query.style { // Select based on width, see CSS3 Section 5.2, Item 4.a. if let Some(query_width) = query_style.width { if a.typeface.width != b.typeface.width { // Reorder a and b, so a has lower width. let (a, b) = if a.typeface.width > b.typeface.width { (b, a) } else { (a, b) }; if query_width <= Width::Normal { if b.typeface.width <= query_width { return b; } else { return a; } } else { if a.typeface.width >= query_width { return a; } else { return b; } } } } // Select based on slant, CSS3 Section 5.2, Item 4.b. if let Some(query_slant) = query_style.slant { match (query_slant, a.typeface.slant, b.typeface.slant) { // If both fonts have the same slant then fall through to select based // on weight. (_, a_s, b_s) if a_s == b_s => (), // If we have a font that matches the request then use it. (r_s, a_s, _) if r_s == a_s => return a, (r_s, _, b_s) if r_s == b_s => return b, // In case italic or oblique font is requested pick italic or // oblique. (Slant::Italic, Slant::Oblique, _) => return a, (Slant::Italic, _, Slant::Oblique) => return b, (Slant::Oblique, Slant::Italic, _) => return a, (Slant::Oblique, _, Slant::Italic) => return b, // In case upright font is requested, but we have only italic and // oblique then fall through to select based on weight. (Slant::Upright, _, _) => (), // Patterns above cover all possible inputs, but exhaustiveness // checker doesn't see it. _ => (), } } // Select based on weight, CSS3 Section 5.2, Item 4.c. if let Some(query_weight) = query_style.weight { if a.typeface.weight != b.typeface.weight { // Reorder a and b, so a has lower weight. let ordered = if a.typeface.weight > b.typeface.weight { (b, a) } else { (a, b) }; let (a, b) = ordered; if a.typeface.weight == query_weight { return a; } if b.typeface.weight == query_weight { return b; } if query_weight < WEIGHT_NORMAL { // If query_weight < 400, then typefaces with weights <= query_weight are // preferred. if b.typeface.weight <= query_weight { return b; } else { return a; } } else if query_weight > WEIGHT_MEDIUM { // If request.weight > 500, then typefaces with weights >= query_weight are // preferred. if a.typeface.weight >= query_weight { return a; } else { return b; } } else { // request.weight is 400 or 500. if b.typeface.weight <= WEIGHT_MEDIUM { if (a.typeface.weight as i32 - query_weight as i32).abs() < (b.typeface.weight as i32 - query_weight as i32).abs() { return a; } else { return b; } } else { return a; } } } } } // If a and b are equivalent then give priority according to the order in the manifest. a }
pub type Item = (Vec<Row>, Vec<Col>); pub enum Row { Upper, Lower, } pub enum Col { Upper, Lower, } #[aoc_generator(day5)] pub fn input_generator(input: &str) -> Vec<Item> { input .lines() .map(|line| { let (rows, cols) = line.split_at(7); ( rows.chars() .map(|c| match c { 'F' => Row::Lower, 'B' => Row::Upper, _ => unreachable!(), }) .collect(), cols.chars() .map(|c| match c { 'L' => Col::Lower, 'R' => Col::Upper, _ => unreachable!(), }) .collect(), ) }) .collect() } fn get_seat_ids(input: &[Item]) -> Vec<usize> { input .iter() .map(|(rs, cs)| { let all_rows: Vec<usize> = (0..=127).collect(); let all_cols: Vec<usize> = (0..=7).collect(); let mut rows = &all_rows[..]; let mut cols = &all_cols[..]; for r in rs { let mid = (rows.len() + 1) / 2; match r { Row::Upper => { rows = &rows[mid..]; } Row::Lower => { rows = &rows[..mid]; } } } for c in cs { let mid = (cols.len() + 1) / 2; match c { Col::Upper => { cols = &cols[mid..]; } Col::Lower => { cols = &cols[..mid]; } } } seat_id(rows[0], cols[0]) }) .collect() } #[aoc(day5, part1)] pub fn solve_part1(input: &[Item]) -> usize { get_seat_ids(input).into_iter().max().unwrap() } #[aoc(day5, part2)] pub fn solve_part2(input: &[Item]) -> usize { let mut ids = input .iter() .map(|(rs, cs)| { let all_rows: Vec<usize> = (0..=127).collect(); let all_cols: Vec<usize> = (0..=7).collect(); let mut rows = &all_rows[..]; let mut cols = &all_cols[..]; for r in rs { let mid = (rows.len() + 1) / 2; match r { Row::Upper => { rows = &rows[mid..]; } Row::Lower => { rows = &rows[..mid]; } } } for c in cs { let mid = (cols.len() + 1) / 2; match c { Col::Upper => { cols = &cols[mid..]; } Col::Lower => { cols = &cols[..mid]; } } } seat_id(rows[0], cols[0]) }) .collect::<Vec<usize>>(); ids.sort(); let mut prev: Option<usize> = None; for id in ids { if let Some(prev) = prev { if id - prev > 1 { return id - 1; } } prev = Some(id) } unreachable!() } fn seat_id(row: usize, col: usize) -> usize { row * 8 + col } #[cfg(test)] mod tests { use super::*; const INPUT: &str = r##"FBFBBFFRLR BFFFBBFRRR FFFBBBFRRR BBFFBBFRLL"##; #[test] fn test1() { assert_eq!(820, solve_part1(&input_generator(INPUT))); } // #[test] // fn test2() { // assert_eq!(11, solve_part2(&input_generator(INPUT))); // } }
use std::time::Instant; use std::io::Read; use std::fs::File; use turbo_ir as ir; extern "win64" fn read_char() -> u8 { std::io::stdin() .bytes() .next() .unwrap_or(Ok(0)) .unwrap_or(0) } extern "win64" fn print_char(ch: u8) { print!("{}", ch as char); } fn main() { let input_file = std::env::args().nth(1).unwrap_or_else(|| { println!("Usage: brainfuck <source file>"); std::process::exit(1); }); let program = std::fs::read_to_string(input_file).unwrap(); let mut ir = ir::Module::new(); let input = unsafe { ir.create_external_function("read_char", Some(ir::Type::U8), vec![], read_char as usize) }; let output = unsafe { ir.create_external_function("print_char", None, vec![ir::Type::U8], print_char as usize) }; let function = ir.create_function("main", None, vec![ir::Type::U8.ptr()]); ir.switch_function(function); let buffer = ir.argument(0); let pos_one_u8 = ir.iconst(1u8, ir::Type::U8); let neg_one_u8 = ir.iconst(1u8.wrapping_neg(), ir::Type::U8); let pos_one_u64 = ir.iconst(1u64, ir::Type::U64); let neg_one_u64 = ir.iconst(1u64.wrapping_neg(), ir::Type::U64); let zero = ir.iconst(0u8, ir::Type::U8); let index = { let index = ir.stack_alloc(ir::Type::U64, 1); let init = ir.iconst(0u32, ir::Type::U64); ir.store(index, init); index }; macro_rules! get { () => {{ let index = ir.load(index); let ptr = ir.get_element_ptr(buffer, index); ir.load(ptr) }} } macro_rules! set { ($value: expr) => {{ let value = $value; let index = ir.load(index); let ptr = ir.get_element_ptr(buffer, index); ir.store(ptr, value); }} } let mut loops = Vec::new(); for ch in program.chars() { match ch { '>' | '<' => { let value = match ch { '>' => pos_one_u64, '<' => neg_one_u64, _ => unreachable!(), }; let i = ir.load(index); let i = ir.add(i, value); ir.store(index, i); } '+' | '-' => { let value = match ch { '+' => pos_one_u8, '-' => neg_one_u8, _ => unreachable!(), }; let new = get!(); let new = ir.add(new, value); set!(new); } ',' => { let value = ir.call(input, vec![]).unwrap(); set!(value); } '.' => { let value = get!(); ir.call(output, vec![value]); } '[' => { let header = ir.create_label(); let body = ir.create_label(); let after = ir.create_label(); ir.branch(header); ir.switch_label(header); let value = get!(); let cond = ir.compare_ne(value, zero); ir.branch_cond(cond, body, after); ir.switch_label(body); loops.push((header, after)); } ']' => { let (header, after) = loops.pop().unwrap(); ir.branch(header); ir.switch_label(after); } _ => {}, } } assert!(loops.is_empty(), "Unmatched loops."); ir.ret(None); let start = Instant::now(); ir.finalize(); let finalize_time = start.elapsed().as_secs_f64(); let passes = &[ ir::passes::const_propagate(), ir::passes::remove_ineffective_operations(), ir::passes::simplify_cfg(), ir::passes::simplify_compares(), ir::passes::simplify_expressions(), ir::passes::remove_dead_code(), ir::passes::memory_to_ssa(), ir::passes::deduplicate_fast(), ir::passes::remove_known_loads_fast(), ir::passes::remove_dead_stores_fast(), ir::passes::undefined_propagate(), ir::passes::minimize_phis(), ir::passes::branch_to_select(), ir::passes::reorder(), ]; let start = Instant::now(); ir.optimize(&ir::PassManager::with_passes(passes), false); let optimize_time = start.elapsed().as_secs_f64(); if true { ir.dump_function_text(function, &mut File::create("result.turboir").unwrap()).unwrap(); } type Func = unsafe extern "win64" fn(*mut u8); let start = Instant::now(); let machine_code = ir.generate_machine_code(&ir::backends::X86Backend); let function_ptr = unsafe { machine_code.function_ptr::<Func>(function) }; let codegen_time = start.elapsed().as_secs_f64(); println!(); println!("Finalization in {}s.", finalize_time); println!("Optimization in {}s.", optimize_time); println!("Codegen in {}s.", codegen_time); println!("Total in {}s.", finalize_time + codegen_time + optimize_time); println!(); let mut buffer = vec![0u8; 30 * 1000]; if true { std::fs::write("asm_dump.bin", machine_code.function_buffer(function)).unwrap(); } println!("Running..."); let start = Instant::now(); if true { unsafe { function_ptr(buffer.as_mut_ptr()); } } let running_time = start.elapsed().as_secs_f64(); println!("Executed in {}s.", running_time); }
use rand::prelude::*; use std::cmp::Ordering; use crate::hitable::*; use crate::ray::*; use crate::vec3::*; #[derive(Clone, Copy, Debug)] pub struct Aabb { pub min: Vec3, pub max: Vec3, } impl Aabb { pub fn new(min: Vec3, max: Vec3) -> Self { Self { min, max } } #[allow(dead_code)] pub fn slower_hit(&self, r: &Ray, mut t_min: f64, mut t_max: f64) -> bool { for a in 0..3 { let direction = r.direction()[a]; let min_a = self.min[a]; let max_a = self.max[a]; let origin_a = r.origin()[a]; let t0 = ffmin( (min_a - origin_a) / direction, (max_a - origin_a) / direction, ); let t1 = ffmax( (min_a - origin_a) / direction, (max_a - origin_a) / direction, ); t_min = ffmax(t0, t_min); t_max = ffmin(t1, t_max); if t_max <= t_min { return false; } } true } pub fn hit(&self, r: &Ray, mut t_min: f64, mut t_max: f64) -> bool { for a in 0..3 { let inv_d = 1.0 / r.direction()[a]; let mut t0 = (self.min[a] - r.origin()[a]) * inv_d; let mut t1 = (self.max[a] - r.origin()[a]) * inv_d; if inv_d < 0.0 { std::mem::swap(&mut t0, &mut t1); } t_min = if t0 > t_min { t0 } else { t_min }; t_max = if t1 < t_max { t1 } else { t_max }; if t_max <= t_min { return false; } } true } } fn ffmin(a: f64, b: f64) -> f64 { if a < b { a } else { b } } fn ffmax(a: f64, b: f64) -> f64 { if a > b { a } else { b } } pub fn surrounding_box(box0: Aabb, box1: Aabb) -> Aabb { let small = vec3( ffmin(box0.min.x, box1.min.x), ffmin(box0.min.y, box1.min.y), ffmin(box0.min.z, box1.min.z), ); let big = vec3( ffmax(box0.max.x, box1.max.x), ffmax(box0.max.y, box1.max.y), ffmax(box0.max.z, box1.max.z), ); return Aabb::new(small, big); } #[derive(Debug)] pub struct BvhNode<'a> { // Okay, this should either own it, or contain a specific item? pub contents: Option<&'a dyn Hitable>, pub left: Option<Box<BvhNode<'a>>>, pub right: Option<Box<BvhNode<'a>>>, pub boxy: Aabb, } impl<'a> BvhNode<'a> { pub fn new(l: &'a mut [&dyn Hitable], time0: f64, time1: f64) -> Self { let axis = (3.0 * rand::thread_rng().gen::<f64>()) as isize; l.sort_unstable_by(if axis == 0 { box_x_compare } else if axis == 1 { box_y_compare } else { box_z_compare }); // should be possible to avoid cloning and just box the remains of the vec in place if l.len() == 1 { Self { contents: Some(&*l[0]), left: None, right: None, boxy: l[0] .bounding_box(time0, time1) .expect("No bounding box in BvhNode::new() 1"), } } else { let (left_vec, right_vec) = l.split_at_mut(l.len() / 2); let left = Box::new(BvhNode::new(left_vec, time0, time1)); let right = Box::new(BvhNode::new(right_vec, time0, time1)); let box_left = left.bounding_box(time0, time1); let box_right = right.bounding_box(time0, time1); assert!( box_left.is_some() && box_right.is_some(), "No bounding box in BvhNode::new() 2" ); Self { contents: None, left: Some(left), right: Some(right), boxy: surrounding_box(box_left.unwrap(), box_right.unwrap()), } } } } fn box_x_compare(a: &&dyn Hitable, b: &&dyn Hitable) -> Ordering { let box_left = a.bounding_box(0.0, 0.0); let box_right = b.bounding_box(0.0, 0.0); assert!( box_left.is_some() && box_right.is_some(), "No bounding box in BvhNode::new()" ); if box_left.unwrap().min.x - box_right.unwrap().min.x < 0.0 { Ordering::Less } else { Ordering::Greater } } fn box_y_compare(a: &&dyn Hitable, b: &&dyn Hitable) -> Ordering { let box_left = a.bounding_box(0.0, 0.0); let box_right = b.bounding_box(0.0, 0.0); assert!( box_left.is_some() && box_right.is_some(), "No bounding box in BvhNode::new()" ); if box_left.unwrap().min.y - box_right.unwrap().min.y < 0.0 { Ordering::Less } else { Ordering::Greater } } fn box_z_compare(a: &&dyn Hitable, b: &&dyn Hitable) -> Ordering { let box_left = a.bounding_box(0.0, 0.0); let box_right = b.bounding_box(0.0, 0.0); assert!( box_left.is_some() && box_right.is_some(), "No bounding box in BvhNode::new()" ); if box_left.unwrap().min.z - box_right.unwrap().min.z < 0.0 { Ordering::Less } else { Ordering::Greater } } impl Hitable for BvhNode<'_> { fn hit(&self, r: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> { return if self.boxy.hit(r, t_min, t_max) { if let Some(hit_content) = self.contents.and_then(|h| h.hit(r, t_min, t_max)) { return Some(hit_content); } let hit_left: Option<HitRecord> = self .left .as_ref() .and_then(|h: &Box<BvhNode>| h.hit(r, t_min, t_max)); let hit_right: Option<HitRecord> = self .right .as_ref() .and_then(|h: &Box<BvhNode>| h.hit(r, t_min, t_max)); if hit_left.is_some() && hit_right.is_some() { if hit_left.as_ref().unwrap().t < hit_right.as_ref().unwrap().t { hit_left } else { hit_right } } else if hit_left.is_some() { hit_left } else if hit_right.is_some() { hit_right } else { None } } else { None }; } fn bounding_box(&self, _t0: f64, _t1: f64) -> Option<Aabb> { Some(self.boxy) } }
#![allow(clippy::comparison_chain)] #![allow(clippy::collapsible_if)] use std::cmp::Reverse; use std::cmp::{max, min}; use std::collections::{BTreeSet, HashMap, HashSet}; use std::fmt::Debug; use itertools::Itertools; use whiteread::parse_line; const ten97: usize = 1000_000_007; /// 2の逆元 mod ten97.割りたいときに使う const inv2ten97: u128 = 500_000_004; fn main() { let n: String = parse_line().unwrap(); let n: Vec<u32> = n .chars() .map(|c| c.to_digit(10).unwrap()) .sorted_by(|a, b| b.cmp(&a)) .collect_vec(); let vec = &n; let mut ans = 0; for mut bits in 0..2_u64.pow(vec.len() as u32) { let mut vv = vec![]; let mut nonvv = vec![]; for i in 0..vec.len() { if bits % 2 == 1 { vv.push(vec[i]); } else { nonvv.push(vec[i]); } bits /= 2; } // nonvv.sort_by(|a, b| b.cmp(&a)); // dbg!(&vv, &nonvv, vectonum(&vv)); let left = vectonum(&vv); let right = vectonum(&nonvv); if left == 0 || right == 0 { continue; } ans = ans.max(left * right); } println!("{}", ans); } fn vectonum(v: &Vec<u32>) -> usize { let mut ans = 0; for vv in v.iter() { ans *= 10; ans += *vv as usize; } ans }
use std::io::{ErrorKind, Read}; use std::iter::{FromIterator, FusedIterator}; #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum Literal { String(String), Character(char), Integer(String), } #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum Delimeter { Braces, Brackets, Parethesis, } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum TokenTree { Ident(String), Lit(Literal), Delimeted(Delimeter, TokenStream), Punct(char), } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct TokenStream { stream: Vec<TokenTree>, } impl TokenStream { pub fn iter(&self) -> Iter<'_> { Iter(self.stream.iter()) } } impl IntoIterator for TokenStream { type IntoIter = IntoIter; type Item = TokenTree; fn into_iter(self) -> IntoIter { IntoIter(self.stream.into_iter()) } } impl<'a> IntoIterator for &'a TokenStream { type IntoIter = Iter<'a>; type Item = &'a TokenTree; fn into_iter(self) -> Iter<'a> { self.iter() } } impl FromIterator<TokenTree> for TokenStream { fn from_iter<I: IntoIterator<Item = TokenTree>>(it: I) -> Self { Self { stream: it.into_iter().collect(), } } } impl FromIterator<TokenStream> for TokenStream { fn from_iter<I: IntoIterator<Item = TokenStream>>(it: I) -> Self { Self { stream: it.into_iter().flatten().collect(), } } } impl Extend<TokenTree> for TokenStream { fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, iter: I) { self.stream.extend(iter) } } impl Extend<TokenStream> for TokenStream { fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, iter: I) { self.stream.extend(iter.into_iter().flatten()) } } pub struct Iter<'a>(std::slice::Iter<'a, TokenTree>); impl<'a> Iterator for Iter<'a> { type Item = &'a TokenTree; fn next(&mut self) -> Option<Self::Item> { self.0.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() } } impl<'a> FusedIterator for Iter<'a> {} impl<'a> ExactSizeIterator for Iter<'a> {} pub struct IntoIter(std::vec::IntoIter<TokenTree>); impl<'a> Iterator for IntoIter { type Item = TokenTree; fn next(&mut self) -> Option<Self::Item> { self.0.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() } } impl FusedIterator for IntoIter {} impl ExactSizeIterator for IntoIter {} pub fn lex<R: Read>(input: R) -> std::io::Result<TokenStream> { let mut stream = Vec::new(); let mut iter = input.bytes(); while let Some(c) = iter.next() { stream.push(match c { Ok(punct @ (b'.' | b',')) => TokenTree::Punct(punct as char), Ok(start @ (b'A'..=b'Z' | b'a'..=b'z' | b'$' | b'_')) => { let mut result = String::new(); result.push(start as char); while let Some(Ok(c @ (b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'$' | b'_'))) = iter.next() { result.push(c as char); } TokenTree::Ident(result) } c => { return Err(std::io::Error::new( ErrorKind::InvalidData, format!("Unexpected Character on Stream {:?}", c), )) } }); } Ok(TokenStream { stream }) }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Media_Protection_PlayReady")] pub mod PlayReady; #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ComponentLoadFailedEventArgs(pub ::windows::core::IInspectable); impl ComponentLoadFailedEventArgs { pub fn Information(&self) -> ::windows::core::Result<RevocationAndRenewalInformation> { 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::<RevocationAndRenewalInformation>(result__) } } pub fn Completion(&self) -> ::windows::core::Result<MediaProtectionServiceCompletion> { 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::<MediaProtectionServiceCompletion>(result__) } } } unsafe impl ::windows::core::RuntimeType for ComponentLoadFailedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.ComponentLoadFailedEventArgs;{95972e93-7746-417e-8495-f031bbc5862c})"); } unsafe impl ::windows::core::Interface for ComponentLoadFailedEventArgs { type Vtable = IComponentLoadFailedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x95972e93_7746_417e_8495_f031bbc5862c); } impl ::windows::core::RuntimeName for ComponentLoadFailedEventArgs { const NAME: &'static str = "Windows.Media.Protection.ComponentLoadFailedEventArgs"; } impl ::core::convert::From<ComponentLoadFailedEventArgs> for ::windows::core::IUnknown { fn from(value: ComponentLoadFailedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&ComponentLoadFailedEventArgs> for ::windows::core::IUnknown { fn from(value: &ComponentLoadFailedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ComponentLoadFailedEventArgs { 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 ComponentLoadFailedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ComponentLoadFailedEventArgs> for ::windows::core::IInspectable { fn from(value: ComponentLoadFailedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&ComponentLoadFailedEventArgs> for ::windows::core::IInspectable { fn from(value: &ComponentLoadFailedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ComponentLoadFailedEventArgs { 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 ComponentLoadFailedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ComponentLoadFailedEventArgs {} unsafe impl ::core::marker::Sync for ComponentLoadFailedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ComponentLoadFailedEventHandler(::windows::core::IUnknown); impl ComponentLoadFailedEventHandler { pub fn new<F: FnMut(&::core::option::Option<MediaProtectionManager>, &::core::option::Option<ComponentLoadFailedEventArgs>) -> ::windows::core::Result<()> + 'static>(invoke: F) -> Self { let com = ComponentLoadFailedEventHandler_box::<F> { vtable: &ComponentLoadFailedEventHandler_box::<F>::VTABLE, count: ::windows::core::RefCount::new(1), invoke, }; unsafe { core::mem::transmute(::windows::core::alloc::boxed::Box::new(com)) } } pub fn Invoke<'a, Param0: ::windows::core::IntoParam<'a, MediaProtectionManager>, Param1: ::windows::core::IntoParam<'a, ComponentLoadFailedEventArgs>>(&self, sender: Param0, e: Param1) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).3)(::core::mem::transmute_copy(this), sender.into_param().abi(), e.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for ComponentLoadFailedEventHandler { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"delegate({95da643c-6db9-424b-86ca-091af432081c})"); } unsafe impl ::windows::core::Interface for ComponentLoadFailedEventHandler { type Vtable = ComponentLoadFailedEventHandler_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x95da643c_6db9_424b_86ca_091af432081c); } #[repr(C)] #[doc(hidden)] pub struct ComponentLoadFailedEventHandler_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, sender: ::windows::core::RawPtr, e: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(C)] struct ComponentLoadFailedEventHandler_box<F: FnMut(&::core::option::Option<MediaProtectionManager>, &::core::option::Option<ComponentLoadFailedEventArgs>) -> ::windows::core::Result<()> + 'static> { vtable: *const ComponentLoadFailedEventHandler_abi, invoke: F, count: ::windows::core::RefCount, } impl<F: FnMut(&::core::option::Option<MediaProtectionManager>, &::core::option::Option<ComponentLoadFailedEventArgs>) -> ::windows::core::Result<()> + 'static> ComponentLoadFailedEventHandler_box<F> { const VTABLE: ComponentLoadFailedEventHandler_abi = ComponentLoadFailedEventHandler_abi(Self::QueryInterface, Self::AddRef, Self::Release, Self::Invoke); unsafe extern "system" fn QueryInterface(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; *interface = if iid == &<ComponentLoadFailedEventHandler as ::windows::core::Interface>::IID || iid == &<::windows::core::IUnknown as ::windows::core::Interface>::IID || iid == &<::windows::core::IAgileObject as ::windows::core::Interface>::IID { &mut (*this).vtable as *mut _ as _ } else { ::core::ptr::null_mut() }; if (*interface).is_null() { ::windows::core::HRESULT(0x8000_4002) } else { (*this).count.add_ref(); ::windows::core::HRESULT(0) } } unsafe extern "system" fn AddRef(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; (*this).count.add_ref() } unsafe extern "system" fn Release(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; let remaining = (*this).count.release(); if remaining == 0 { ::windows::core::alloc::boxed::Box::from_raw(this); } remaining } unsafe extern "system" fn Invoke(this: ::windows::core::RawPtr, sender: ::windows::core::RawPtr, e: ::windows::core::RawPtr) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; ((*this).invoke)( &*(&sender as *const <MediaProtectionManager as ::windows::core::Abi>::Abi as *const <MediaProtectionManager as ::windows::core::DefaultType>::DefaultType), &*(&e as *const <ComponentLoadFailedEventArgs as ::windows::core::Abi>::Abi as *const <ComponentLoadFailedEventArgs as ::windows::core::DefaultType>::DefaultType), ) .into() } } pub struct ComponentRenewal {} impl ComponentRenewal { #[cfg(feature = "Foundation")] pub fn RenewSystemComponentsAsync<'a, Param0: ::windows::core::IntoParam<'a, RevocationAndRenewalInformation>>(information: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<RenewalStatus, u32>> { Self::IComponentRenewalStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), information.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<RenewalStatus, u32>>(result__) }) } pub fn IComponentRenewalStatics<R, F: FnOnce(&IComponentRenewalStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<ComponentRenewal, IComponentRenewalStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for ComponentRenewal { const NAME: &'static str = "Windows.Media.Protection.ComponentRenewal"; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GraphicsTrustStatus(pub i32); impl GraphicsTrustStatus { pub const TrustNotRequired: GraphicsTrustStatus = GraphicsTrustStatus(0i32); pub const TrustEstablished: GraphicsTrustStatus = GraphicsTrustStatus(1i32); pub const EnvironmentNotSupported: GraphicsTrustStatus = GraphicsTrustStatus(2i32); pub const DriverNotSupported: GraphicsTrustStatus = GraphicsTrustStatus(3i32); pub const DriverSigningFailure: GraphicsTrustStatus = GraphicsTrustStatus(4i32); pub const UnknownFailure: GraphicsTrustStatus = GraphicsTrustStatus(5i32); } impl ::core::convert::From<i32> for GraphicsTrustStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GraphicsTrustStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for GraphicsTrustStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.GraphicsTrustStatus;i4)"); } impl ::windows::core::DefaultType for GraphicsTrustStatus { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct HdcpProtection(pub i32); impl HdcpProtection { pub const Off: HdcpProtection = HdcpProtection(0i32); pub const On: HdcpProtection = HdcpProtection(1i32); pub const OnWithTypeEnforcement: HdcpProtection = HdcpProtection(2i32); } impl ::core::convert::From<i32> for HdcpProtection { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HdcpProtection { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for HdcpProtection { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.HdcpProtection;i4)"); } impl ::windows::core::DefaultType for HdcpProtection { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct HdcpSession(pub ::windows::core::IInspectable); impl HdcpSession { 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<HdcpSession, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } pub fn IsEffectiveProtectionAtLeast(&self, protection: HdcpProtection) -> ::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), protection, &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation")] pub fn GetEffectiveProtection(&self) -> ::windows::core::Result<super::super::Foundation::IReference<HdcpProtection>> { 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::IReference<HdcpProtection>>(result__) } } #[cfg(feature = "Foundation")] pub fn SetDesiredMinProtectionAsync(&self, protection: HdcpProtection) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<HdcpSetProtectionResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), protection, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<HdcpSetProtectionResult>>(result__) } } #[cfg(feature = "Foundation")] pub fn ProtectionChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<HdcpSession, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveProtectionChanged<'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() } } } unsafe impl ::windows::core::RuntimeType for HdcpSession { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.HdcpSession;{718845e9-64d7-426d-809b-1be461941a2a})"); } unsafe impl ::windows::core::Interface for HdcpSession { type Vtable = IHdcpSession_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x718845e9_64d7_426d_809b_1be461941a2a); } impl ::windows::core::RuntimeName for HdcpSession { const NAME: &'static str = "Windows.Media.Protection.HdcpSession"; } impl ::core::convert::From<HdcpSession> for ::windows::core::IUnknown { fn from(value: HdcpSession) -> Self { value.0 .0 } } impl ::core::convert::From<&HdcpSession> for ::windows::core::IUnknown { fn from(value: &HdcpSession) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HdcpSession { 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 HdcpSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<HdcpSession> for ::windows::core::IInspectable { fn from(value: HdcpSession) -> Self { value.0 } } impl ::core::convert::From<&HdcpSession> for ::windows::core::IInspectable { fn from(value: &HdcpSession) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HdcpSession { 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 HdcpSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<HdcpSession> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: HdcpSession) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&HdcpSession> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &HdcpSession) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for HdcpSession { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &HdcpSession { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for HdcpSession {} unsafe impl ::core::marker::Sync for HdcpSession {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct HdcpSetProtectionResult(pub i32); impl HdcpSetProtectionResult { pub const Success: HdcpSetProtectionResult = HdcpSetProtectionResult(0i32); pub const TimedOut: HdcpSetProtectionResult = HdcpSetProtectionResult(1i32); pub const NotSupported: HdcpSetProtectionResult = HdcpSetProtectionResult(2i32); pub const UnknownFailure: HdcpSetProtectionResult = HdcpSetProtectionResult(3i32); } impl ::core::convert::From<i32> for HdcpSetProtectionResult { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HdcpSetProtectionResult { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for HdcpSetProtectionResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.HdcpSetProtectionResult;i4)"); } impl ::windows::core::DefaultType for HdcpSetProtectionResult { type DefaultType = Self; } #[repr(transparent)] #[doc(hidden)] pub struct IComponentLoadFailedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IComponentLoadFailedEventArgs { type Vtable = IComponentLoadFailedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x95972e93_7746_417e_8495_f031bbc5862c); } #[repr(C)] #[doc(hidden)] pub struct IComponentLoadFailedEventArgs_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IComponentRenewalStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IComponentRenewalStatics { type Vtable = IComponentRenewalStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6ffbcd67_b795_48c5_8b7b_a7c4efe202e3); } #[repr(C)] #[doc(hidden)] pub struct IComponentRenewalStatics_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, information: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IHdcpSession(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IHdcpSession { type Vtable = IHdcpSession_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x718845e9_64d7_426d_809b_1be461941a2a); } #[repr(C)] #[doc(hidden)] pub struct IHdcpSession_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, protection: HdcpProtection, result__: *mut bool) -> ::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, protection: HdcpProtection, 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, ); #[repr(transparent)] #[doc(hidden)] pub struct IMediaProtectionManager(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMediaProtectionManager { type Vtable = IMediaProtectionManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x45694947_c741_434b_a79e_474c12d93d2f); } #[repr(C)] #[doc(hidden)] pub struct IMediaProtectionManager_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cookie: 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, cookie: 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, cookie: 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, ); #[repr(transparent)] #[doc(hidden)] pub struct IMediaProtectionPMPServer(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMediaProtectionPMPServer { type Vtable = IMediaProtectionPMPServer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0c111226_7b26_4d31_95bb_9c1b08ef7fc0); } #[repr(C)] #[doc(hidden)] pub struct IMediaProtectionPMPServer_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMediaProtectionPMPServerFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMediaProtectionPMPServerFactory { type Vtable = IMediaProtectionPMPServerFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x602c8e5e_f7d2_487e_af91_dbc4252b2182); } #[repr(C)] #[doc(hidden)] pub struct IMediaProtectionPMPServerFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pproperties: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IMediaProtectionServiceCompletion(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMediaProtectionServiceCompletion { type Vtable = IMediaProtectionServiceCompletion_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8b5cca18_cfd5_44ee_a2ed_df76010c14b5); } #[repr(C)] #[doc(hidden)] pub struct IMediaProtectionServiceCompletion_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, success: bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMediaProtectionServiceRequest(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IMediaProtectionServiceRequest { type Vtable = IMediaProtectionServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb1de0ea6_2094_478d_87a4_8b95200f85c6); } impl IMediaProtectionServiceRequest { pub fn ProtectionSystem(&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).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn Type(&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).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } } unsafe impl ::windows::core::RuntimeType for IMediaProtectionServiceRequest { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{b1de0ea6-2094-478d-87a4-8b95200f85c6}"); } impl ::core::convert::From<IMediaProtectionServiceRequest> for ::windows::core::IUnknown { fn from(value: IMediaProtectionServiceRequest) -> Self { value.0 .0 } } impl ::core::convert::From<&IMediaProtectionServiceRequest> for ::windows::core::IUnknown { fn from(value: &IMediaProtectionServiceRequest) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMediaProtectionServiceRequest { 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 IMediaProtectionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IMediaProtectionServiceRequest> for ::windows::core::IInspectable { fn from(value: IMediaProtectionServiceRequest) -> Self { value.0 } } impl ::core::convert::From<&IMediaProtectionServiceRequest> for ::windows::core::IInspectable { fn from(value: &IMediaProtectionServiceRequest) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IMediaProtectionServiceRequest { 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 IMediaProtectionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMediaProtectionServiceRequest_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::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IProtectionCapabilities(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IProtectionCapabilities { type Vtable = IProtectionCapabilities_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc7ac5d7e_7480_4d29_a464_7bcd913dd8e4); } #[repr(C)] #[doc(hidden)] pub struct IProtectionCapabilities_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, r#type: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, keysystem: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ProtectionCapabilityResult) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IRevocationAndRenewalInformation(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRevocationAndRenewalInformation { type Vtable = IRevocationAndRenewalInformation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf3a1937b_2501_439e_a6e7_6fc95e175fcf); } #[repr(C)] #[doc(hidden)] pub struct IRevocationAndRenewalInformation_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IRevocationAndRenewalItem(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRevocationAndRenewalItem { type Vtable = IRevocationAndRenewalItem_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3099c20c_3cf0_49ea_902d_caf32d2dde2c); } #[repr(C)] #[doc(hidden)] pub struct IRevocationAndRenewalItem_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 RevocationAndRenewalReasons) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IServiceRequestedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IServiceRequestedEventArgs { type Vtable = IServiceRequestedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x34283baf_abb4_4fc1_bd89_93f106573a49); } #[repr(C)] #[doc(hidden)] pub struct IServiceRequestedEventArgs_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IServiceRequestedEventArgs2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IServiceRequestedEventArgs2 { type Vtable = IServiceRequestedEventArgs2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x553c69d6_fafe_4128_8dfa_130e398a13a7); } #[repr(C)] #[doc(hidden)] pub struct IServiceRequestedEventArgs2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Media_Playback")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Media_Playback"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MediaProtectionManager(pub ::windows::core::IInspectable); impl MediaProtectionManager { 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<MediaProtectionManager, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn ServiceRequested<'a, Param0: ::windows::core::IntoParam<'a, ServiceRequestedEventHandler>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveServiceRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, cookie: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), cookie.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn RebootNeeded<'a, Param0: ::windows::core::IntoParam<'a, RebootNeededEventHandler>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveRebootNeeded<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, cookie: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), cookie.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn ComponentLoadFailed<'a, Param0: ::windows::core::IntoParam<'a, ComponentLoadFailedEventHandler>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveComponentLoadFailed<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, cookie: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), cookie.into_param().abi()).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn Properties(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IPropertySet> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IPropertySet>(result__) } } } unsafe impl ::windows::core::RuntimeType for MediaProtectionManager { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.MediaProtectionManager;{45694947-c741-434b-a79e-474c12d93d2f})"); } unsafe impl ::windows::core::Interface for MediaProtectionManager { type Vtable = IMediaProtectionManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x45694947_c741_434b_a79e_474c12d93d2f); } impl ::windows::core::RuntimeName for MediaProtectionManager { const NAME: &'static str = "Windows.Media.Protection.MediaProtectionManager"; } impl ::core::convert::From<MediaProtectionManager> for ::windows::core::IUnknown { fn from(value: MediaProtectionManager) -> Self { value.0 .0 } } impl ::core::convert::From<&MediaProtectionManager> for ::windows::core::IUnknown { fn from(value: &MediaProtectionManager) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MediaProtectionManager { 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 MediaProtectionManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MediaProtectionManager> for ::windows::core::IInspectable { fn from(value: MediaProtectionManager) -> Self { value.0 } } impl ::core::convert::From<&MediaProtectionManager> for ::windows::core::IInspectable { fn from(value: &MediaProtectionManager) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MediaProtectionManager { 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 MediaProtectionManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MediaProtectionManager {} unsafe impl ::core::marker::Sync for MediaProtectionManager {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MediaProtectionPMPServer(pub ::windows::core::IInspectable); impl MediaProtectionPMPServer { #[cfg(feature = "Foundation_Collections")] pub fn Properties(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IPropertySet> { 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::Foundation::Collections::IPropertySet>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn CreatePMPServer<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IPropertySet>>(pproperties: Param0) -> ::windows::core::Result<MediaProtectionPMPServer> { Self::IMediaProtectionPMPServerFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), pproperties.into_param().abi(), &mut result__).from_abi::<MediaProtectionPMPServer>(result__) }) } pub fn IMediaProtectionPMPServerFactory<R, F: FnOnce(&IMediaProtectionPMPServerFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<MediaProtectionPMPServer, IMediaProtectionPMPServerFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for MediaProtectionPMPServer { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.MediaProtectionPMPServer;{0c111226-7b26-4d31-95bb-9c1b08ef7fc0})"); } unsafe impl ::windows::core::Interface for MediaProtectionPMPServer { type Vtable = IMediaProtectionPMPServer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0c111226_7b26_4d31_95bb_9c1b08ef7fc0); } impl ::windows::core::RuntimeName for MediaProtectionPMPServer { const NAME: &'static str = "Windows.Media.Protection.MediaProtectionPMPServer"; } impl ::core::convert::From<MediaProtectionPMPServer> for ::windows::core::IUnknown { fn from(value: MediaProtectionPMPServer) -> Self { value.0 .0 } } impl ::core::convert::From<&MediaProtectionPMPServer> for ::windows::core::IUnknown { fn from(value: &MediaProtectionPMPServer) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MediaProtectionPMPServer { 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 MediaProtectionPMPServer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MediaProtectionPMPServer> for ::windows::core::IInspectable { fn from(value: MediaProtectionPMPServer) -> Self { value.0 } } impl ::core::convert::From<&MediaProtectionPMPServer> for ::windows::core::IInspectable { fn from(value: &MediaProtectionPMPServer) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MediaProtectionPMPServer { 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 MediaProtectionPMPServer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MediaProtectionPMPServer {} unsafe impl ::core::marker::Sync for MediaProtectionPMPServer {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct MediaProtectionServiceCompletion(pub ::windows::core::IInspectable); impl MediaProtectionServiceCompletion { pub fn Complete(&self, success: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), success).ok() } } } unsafe impl ::windows::core::RuntimeType for MediaProtectionServiceCompletion { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.MediaProtectionServiceCompletion;{8b5cca18-cfd5-44ee-a2ed-df76010c14b5})"); } unsafe impl ::windows::core::Interface for MediaProtectionServiceCompletion { type Vtable = IMediaProtectionServiceCompletion_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8b5cca18_cfd5_44ee_a2ed_df76010c14b5); } impl ::windows::core::RuntimeName for MediaProtectionServiceCompletion { const NAME: &'static str = "Windows.Media.Protection.MediaProtectionServiceCompletion"; } impl ::core::convert::From<MediaProtectionServiceCompletion> for ::windows::core::IUnknown { fn from(value: MediaProtectionServiceCompletion) -> Self { value.0 .0 } } impl ::core::convert::From<&MediaProtectionServiceCompletion> for ::windows::core::IUnknown { fn from(value: &MediaProtectionServiceCompletion) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MediaProtectionServiceCompletion { 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 MediaProtectionServiceCompletion { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<MediaProtectionServiceCompletion> for ::windows::core::IInspectable { fn from(value: MediaProtectionServiceCompletion) -> Self { value.0 } } impl ::core::convert::From<&MediaProtectionServiceCompletion> for ::windows::core::IInspectable { fn from(value: &MediaProtectionServiceCompletion) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MediaProtectionServiceCompletion { 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 MediaProtectionServiceCompletion { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for MediaProtectionServiceCompletion {} unsafe impl ::core::marker::Sync for MediaProtectionServiceCompletion {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ProtectionCapabilities(pub ::windows::core::IInspectable); impl ProtectionCapabilities { 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<ProtectionCapabilities, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IsTypeSupported<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, r#type: Param0, keysystem: Param1) -> ::windows::core::Result<ProtectionCapabilityResult> { let this = self; unsafe { let mut result__: ProtectionCapabilityResult = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), r#type.into_param().abi(), keysystem.into_param().abi(), &mut result__).from_abi::<ProtectionCapabilityResult>(result__) } } } unsafe impl ::windows::core::RuntimeType for ProtectionCapabilities { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.ProtectionCapabilities;{c7ac5d7e-7480-4d29-a464-7bcd913dd8e4})"); } unsafe impl ::windows::core::Interface for ProtectionCapabilities { type Vtable = IProtectionCapabilities_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc7ac5d7e_7480_4d29_a464_7bcd913dd8e4); } impl ::windows::core::RuntimeName for ProtectionCapabilities { const NAME: &'static str = "Windows.Media.Protection.ProtectionCapabilities"; } impl ::core::convert::From<ProtectionCapabilities> for ::windows::core::IUnknown { fn from(value: ProtectionCapabilities) -> Self { value.0 .0 } } impl ::core::convert::From<&ProtectionCapabilities> for ::windows::core::IUnknown { fn from(value: &ProtectionCapabilities) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ProtectionCapabilities { 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 ProtectionCapabilities { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ProtectionCapabilities> for ::windows::core::IInspectable { fn from(value: ProtectionCapabilities) -> Self { value.0 } } impl ::core::convert::From<&ProtectionCapabilities> for ::windows::core::IInspectable { fn from(value: &ProtectionCapabilities) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ProtectionCapabilities { 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 ProtectionCapabilities { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ProtectionCapabilities {} unsafe impl ::core::marker::Sync for ProtectionCapabilities {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ProtectionCapabilityResult(pub i32); impl ProtectionCapabilityResult { pub const NotSupported: ProtectionCapabilityResult = ProtectionCapabilityResult(0i32); pub const Maybe: ProtectionCapabilityResult = ProtectionCapabilityResult(1i32); pub const Probably: ProtectionCapabilityResult = ProtectionCapabilityResult(2i32); } impl ::core::convert::From<i32> for ProtectionCapabilityResult { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ProtectionCapabilityResult { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ProtectionCapabilityResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.ProtectionCapabilityResult;i4)"); } impl ::windows::core::DefaultType for ProtectionCapabilityResult { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct RebootNeededEventHandler(::windows::core::IUnknown); impl RebootNeededEventHandler { pub fn new<F: FnMut(&::core::option::Option<MediaProtectionManager>) -> ::windows::core::Result<()> + 'static>(invoke: F) -> Self { let com = RebootNeededEventHandler_box::<F> { vtable: &RebootNeededEventHandler_box::<F>::VTABLE, count: ::windows::core::RefCount::new(1), invoke, }; unsafe { core::mem::transmute(::windows::core::alloc::boxed::Box::new(com)) } } pub fn Invoke<'a, Param0: ::windows::core::IntoParam<'a, MediaProtectionManager>>(&self, sender: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).3)(::core::mem::transmute_copy(this), sender.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for RebootNeededEventHandler { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"delegate({64e12a45-973b-4a3a-b260-91898a49a82c})"); } unsafe impl ::windows::core::Interface for RebootNeededEventHandler { type Vtable = RebootNeededEventHandler_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x64e12a45_973b_4a3a_b260_91898a49a82c); } #[repr(C)] #[doc(hidden)] pub struct RebootNeededEventHandler_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, sender: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(C)] struct RebootNeededEventHandler_box<F: FnMut(&::core::option::Option<MediaProtectionManager>) -> ::windows::core::Result<()> + 'static> { vtable: *const RebootNeededEventHandler_abi, invoke: F, count: ::windows::core::RefCount, } impl<F: FnMut(&::core::option::Option<MediaProtectionManager>) -> ::windows::core::Result<()> + 'static> RebootNeededEventHandler_box<F> { const VTABLE: RebootNeededEventHandler_abi = RebootNeededEventHandler_abi(Self::QueryInterface, Self::AddRef, Self::Release, Self::Invoke); unsafe extern "system" fn QueryInterface(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; *interface = if iid == &<RebootNeededEventHandler as ::windows::core::Interface>::IID || iid == &<::windows::core::IUnknown as ::windows::core::Interface>::IID || iid == &<::windows::core::IAgileObject as ::windows::core::Interface>::IID { &mut (*this).vtable as *mut _ as _ } else { ::core::ptr::null_mut() }; if (*interface).is_null() { ::windows::core::HRESULT(0x8000_4002) } else { (*this).count.add_ref(); ::windows::core::HRESULT(0) } } unsafe extern "system" fn AddRef(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; (*this).count.add_ref() } unsafe extern "system" fn Release(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; let remaining = (*this).count.release(); if remaining == 0 { ::windows::core::alloc::boxed::Box::from_raw(this); } remaining } unsafe extern "system" fn Invoke(this: ::windows::core::RawPtr, sender: ::windows::core::RawPtr) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; ((*this).invoke)(&*(&sender as *const <MediaProtectionManager as ::windows::core::Abi>::Abi as *const <MediaProtectionManager as ::windows::core::DefaultType>::DefaultType)).into() } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RenewalStatus(pub i32); impl RenewalStatus { pub const NotStarted: RenewalStatus = RenewalStatus(0i32); pub const UpdatesInProgress: RenewalStatus = RenewalStatus(1i32); pub const UserCancelled: RenewalStatus = RenewalStatus(2i32); pub const AppComponentsMayNeedUpdating: RenewalStatus = RenewalStatus(3i32); pub const NoComponentsFound: RenewalStatus = RenewalStatus(4i32); } impl ::core::convert::From<i32> for RenewalStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RenewalStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for RenewalStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.RenewalStatus;i4)"); } impl ::windows::core::DefaultType for RenewalStatus { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct RevocationAndRenewalInformation(pub ::windows::core::IInspectable); impl RevocationAndRenewalInformation { #[cfg(feature = "Foundation_Collections")] pub fn Items(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<RevocationAndRenewalItem>> { 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::Foundation::Collections::IVector<RevocationAndRenewalItem>>(result__) } } } unsafe impl ::windows::core::RuntimeType for RevocationAndRenewalInformation { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.RevocationAndRenewalInformation;{f3a1937b-2501-439e-a6e7-6fc95e175fcf})"); } unsafe impl ::windows::core::Interface for RevocationAndRenewalInformation { type Vtable = IRevocationAndRenewalInformation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf3a1937b_2501_439e_a6e7_6fc95e175fcf); } impl ::windows::core::RuntimeName for RevocationAndRenewalInformation { const NAME: &'static str = "Windows.Media.Protection.RevocationAndRenewalInformation"; } impl ::core::convert::From<RevocationAndRenewalInformation> for ::windows::core::IUnknown { fn from(value: RevocationAndRenewalInformation) -> Self { value.0 .0 } } impl ::core::convert::From<&RevocationAndRenewalInformation> for ::windows::core::IUnknown { fn from(value: &RevocationAndRenewalInformation) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for RevocationAndRenewalInformation { 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 RevocationAndRenewalInformation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<RevocationAndRenewalInformation> for ::windows::core::IInspectable { fn from(value: RevocationAndRenewalInformation) -> Self { value.0 } } impl ::core::convert::From<&RevocationAndRenewalInformation> for ::windows::core::IInspectable { fn from(value: &RevocationAndRenewalInformation) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for RevocationAndRenewalInformation { 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 RevocationAndRenewalInformation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for RevocationAndRenewalInformation {} unsafe impl ::core::marker::Sync for RevocationAndRenewalInformation {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct RevocationAndRenewalItem(pub ::windows::core::IInspectable); impl RevocationAndRenewalItem { pub fn Reasons(&self) -> ::windows::core::Result<RevocationAndRenewalReasons> { let this = self; unsafe { let mut result__: RevocationAndRenewalReasons = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<RevocationAndRenewalReasons>(result__) } } pub fn HeaderHash(&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__) } } pub fn PublicKeyHash(&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__) } } pub fn Name(&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__) } } pub fn RenewalId(&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).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for RevocationAndRenewalItem { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.RevocationAndRenewalItem;{3099c20c-3cf0-49ea-902d-caf32d2dde2c})"); } unsafe impl ::windows::core::Interface for RevocationAndRenewalItem { type Vtable = IRevocationAndRenewalItem_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3099c20c_3cf0_49ea_902d_caf32d2dde2c); } impl ::windows::core::RuntimeName for RevocationAndRenewalItem { const NAME: &'static str = "Windows.Media.Protection.RevocationAndRenewalItem"; } impl ::core::convert::From<RevocationAndRenewalItem> for ::windows::core::IUnknown { fn from(value: RevocationAndRenewalItem) -> Self { value.0 .0 } } impl ::core::convert::From<&RevocationAndRenewalItem> for ::windows::core::IUnknown { fn from(value: &RevocationAndRenewalItem) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for RevocationAndRenewalItem { 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 RevocationAndRenewalItem { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<RevocationAndRenewalItem> for ::windows::core::IInspectable { fn from(value: RevocationAndRenewalItem) -> Self { value.0 } } impl ::core::convert::From<&RevocationAndRenewalItem> for ::windows::core::IInspectable { fn from(value: &RevocationAndRenewalItem) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for RevocationAndRenewalItem { 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 RevocationAndRenewalItem { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for RevocationAndRenewalItem {} unsafe impl ::core::marker::Sync for RevocationAndRenewalItem {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RevocationAndRenewalReasons(pub u32); impl RevocationAndRenewalReasons { pub const UserModeComponentLoad: RevocationAndRenewalReasons = RevocationAndRenewalReasons(1u32); pub const KernelModeComponentLoad: RevocationAndRenewalReasons = RevocationAndRenewalReasons(2u32); pub const AppComponent: RevocationAndRenewalReasons = RevocationAndRenewalReasons(4u32); pub const GlobalRevocationListLoadFailed: RevocationAndRenewalReasons = RevocationAndRenewalReasons(16u32); pub const InvalidGlobalRevocationListSignature: RevocationAndRenewalReasons = RevocationAndRenewalReasons(32u32); pub const GlobalRevocationListAbsent: RevocationAndRenewalReasons = RevocationAndRenewalReasons(4096u32); pub const ComponentRevoked: RevocationAndRenewalReasons = RevocationAndRenewalReasons(8192u32); pub const InvalidComponentCertificateExtendedKeyUse: RevocationAndRenewalReasons = RevocationAndRenewalReasons(16384u32); pub const ComponentCertificateRevoked: RevocationAndRenewalReasons = RevocationAndRenewalReasons(32768u32); pub const InvalidComponentCertificateRoot: RevocationAndRenewalReasons = RevocationAndRenewalReasons(65536u32); pub const ComponentHighSecurityCertificateRevoked: RevocationAndRenewalReasons = RevocationAndRenewalReasons(131072u32); pub const ComponentLowSecurityCertificateRevoked: RevocationAndRenewalReasons = RevocationAndRenewalReasons(262144u32); pub const BootDriverVerificationFailed: RevocationAndRenewalReasons = RevocationAndRenewalReasons(1048576u32); pub const ComponentSignedWithTestCertificate: RevocationAndRenewalReasons = RevocationAndRenewalReasons(16777216u32); pub const EncryptionFailure: RevocationAndRenewalReasons = RevocationAndRenewalReasons(268435456u32); } impl ::core::convert::From<u32> for RevocationAndRenewalReasons { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RevocationAndRenewalReasons { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for RevocationAndRenewalReasons { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.RevocationAndRenewalReasons;u4)"); } impl ::windows::core::DefaultType for RevocationAndRenewalReasons { type DefaultType = Self; } impl ::core::ops::BitOr for RevocationAndRenewalReasons { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for RevocationAndRenewalReasons { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for RevocationAndRenewalReasons { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for RevocationAndRenewalReasons { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for RevocationAndRenewalReasons { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ServiceRequestedEventArgs(pub ::windows::core::IInspectable); impl ServiceRequestedEventArgs { pub fn Request(&self) -> ::windows::core::Result<IMediaProtectionServiceRequest> { 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::<IMediaProtectionServiceRequest>(result__) } } pub fn Completion(&self) -> ::windows::core::Result<MediaProtectionServiceCompletion> { 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::<MediaProtectionServiceCompletion>(result__) } } #[cfg(feature = "Media_Playback")] pub fn MediaPlaybackItem(&self) -> ::windows::core::Result<super::Playback::MediaPlaybackItem> { let this = &::windows::core::Interface::cast::<IServiceRequestedEventArgs2>(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::Playback::MediaPlaybackItem>(result__) } } } unsafe impl ::windows::core::RuntimeType for ServiceRequestedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.ServiceRequestedEventArgs;{34283baf-abb4-4fc1-bd89-93f106573a49})"); } unsafe impl ::windows::core::Interface for ServiceRequestedEventArgs { type Vtable = IServiceRequestedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x34283baf_abb4_4fc1_bd89_93f106573a49); } impl ::windows::core::RuntimeName for ServiceRequestedEventArgs { const NAME: &'static str = "Windows.Media.Protection.ServiceRequestedEventArgs"; } impl ::core::convert::From<ServiceRequestedEventArgs> for ::windows::core::IUnknown { fn from(value: ServiceRequestedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&ServiceRequestedEventArgs> for ::windows::core::IUnknown { fn from(value: &ServiceRequestedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ServiceRequestedEventArgs { 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 ServiceRequestedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ServiceRequestedEventArgs> for ::windows::core::IInspectable { fn from(value: ServiceRequestedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&ServiceRequestedEventArgs> for ::windows::core::IInspectable { fn from(value: &ServiceRequestedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ServiceRequestedEventArgs { 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 ServiceRequestedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ServiceRequestedEventArgs {} unsafe impl ::core::marker::Sync for ServiceRequestedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ServiceRequestedEventHandler(::windows::core::IUnknown); impl ServiceRequestedEventHandler { pub fn new<F: FnMut(&::core::option::Option<MediaProtectionManager>, &::core::option::Option<ServiceRequestedEventArgs>) -> ::windows::core::Result<()> + 'static>(invoke: F) -> Self { let com = ServiceRequestedEventHandler_box::<F> { vtable: &ServiceRequestedEventHandler_box::<F>::VTABLE, count: ::windows::core::RefCount::new(1), invoke, }; unsafe { core::mem::transmute(::windows::core::alloc::boxed::Box::new(com)) } } pub fn Invoke<'a, Param0: ::windows::core::IntoParam<'a, MediaProtectionManager>, Param1: ::windows::core::IntoParam<'a, ServiceRequestedEventArgs>>(&self, sender: Param0, e: Param1) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).3)(::core::mem::transmute_copy(this), sender.into_param().abi(), e.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for ServiceRequestedEventHandler { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"delegate({d2d690ba-cac9-48e1-95c0-d38495a84055})"); } unsafe impl ::windows::core::Interface for ServiceRequestedEventHandler { type Vtable = ServiceRequestedEventHandler_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd2d690ba_cac9_48e1_95c0_d38495a84055); } #[repr(C)] #[doc(hidden)] pub struct ServiceRequestedEventHandler_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, sender: ::windows::core::RawPtr, e: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(C)] struct ServiceRequestedEventHandler_box<F: FnMut(&::core::option::Option<MediaProtectionManager>, &::core::option::Option<ServiceRequestedEventArgs>) -> ::windows::core::Result<()> + 'static> { vtable: *const ServiceRequestedEventHandler_abi, invoke: F, count: ::windows::core::RefCount, } impl<F: FnMut(&::core::option::Option<MediaProtectionManager>, &::core::option::Option<ServiceRequestedEventArgs>) -> ::windows::core::Result<()> + 'static> ServiceRequestedEventHandler_box<F> { const VTABLE: ServiceRequestedEventHandler_abi = ServiceRequestedEventHandler_abi(Self::QueryInterface, Self::AddRef, Self::Release, Self::Invoke); unsafe extern "system" fn QueryInterface(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; *interface = if iid == &<ServiceRequestedEventHandler as ::windows::core::Interface>::IID || iid == &<::windows::core::IUnknown as ::windows::core::Interface>::IID || iid == &<::windows::core::IAgileObject as ::windows::core::Interface>::IID { &mut (*this).vtable as *mut _ as _ } else { ::core::ptr::null_mut() }; if (*interface).is_null() { ::windows::core::HRESULT(0x8000_4002) } else { (*this).count.add_ref(); ::windows::core::HRESULT(0) } } unsafe extern "system" fn AddRef(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; (*this).count.add_ref() } unsafe extern "system" fn Release(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; let remaining = (*this).count.release(); if remaining == 0 { ::windows::core::alloc::boxed::Box::from_raw(this); } remaining } unsafe extern "system" fn Invoke(this: ::windows::core::RawPtr, sender: ::windows::core::RawPtr, e: ::windows::core::RawPtr) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; ((*this).invoke)( &*(&sender as *const <MediaProtectionManager as ::windows::core::Abi>::Abi as *const <MediaProtectionManager as ::windows::core::DefaultType>::DefaultType), &*(&e as *const <ServiceRequestedEventArgs as ::windows::core::Abi>::Abi as *const <ServiceRequestedEventArgs as ::windows::core::DefaultType>::DefaultType), ) .into() } }
use crate::config::Diff2HtmlConfig; use crate::parse; use crate::printers::{FileListPrinter, LineByLinePrinter, SideBySidePrinter}; static CSS: &'static str = include_str!("../templates/css.hbs"); pub struct PagePrinter { config: Diff2HtmlConfig, } impl PagePrinter { pub fn new(config: Diff2HtmlConfig) -> PagePrinter { PagePrinter { config: config } } pub fn render(&self, files: &Vec<parse::File>) -> String { let summary = if self.config.summary != "hidden" { FileListPrinter::new().render(&files) } else { "".to_owned() }; let content = if self.config.style == "line" { LineByLinePrinter::new(self.config.to_owned()).render(&files) } else { SideBySidePrinter::new(self.config.to_owned()).render(&files) }; format!( r#" <!DOCTYPE html> <html lang="en"> <head> <style type="text/css"> body {{ font-family: Roboto,sans-serif; font-size: 16px; line-height: 1.6; }} * {{ -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; }} table {{ background: white; }} {} </style> </head> <body> {} {} </body> </html> "#, CSS, &summary, &content ) } }
use crate::engine::Engine; use crate::hooks::hw; mod sampling; mod simple; pub use self::sampling::SamplingConverter; pub use self::simple::SimpleConverter; pub trait FPSConverter { /// Updates the FPS converter state. The converter may capture one frame using the provided /// closure. fn time_passed<F>(&mut self, engine: &mut Engine, frametime: f64, capture: F) where F: FnOnce(&mut Engine) -> hw::FrameCapture; } pub enum FPSConverters { Simple(SimpleConverter), Sampling(SamplingConverter), }
//! Client helpers for writing end to end ng tests use arrow::{datatypes::SchemaRef, record_batch::RecordBatch}; use data_types::{NamespaceId, TableId}; use dml::{DmlMeta, DmlWrite}; use futures::TryStreamExt; use http::Response; use hyper::{Body, Client, Request}; use influxdb_iox_client::{ connection::Connection, ingester::generated_types::{write_service_client::WriteServiceClient, WriteRequest}, }; use mutable_batch_lp::lines_to_batches; use mutable_batch_pb::encode::encode_write; use std::fmt::Display; use tonic::IntoRequest; /// Writes the line protocol to the write_base/api/v2/write endpoint (typically on the router) pub async fn write_to_router( line_protocol: impl Into<String>, org: impl AsRef<str>, bucket: impl AsRef<str>, write_base: impl AsRef<str>, authorization: Option<&str>, ) -> Response<Body> { let client = Client::new(); let url = format!( "{}/api/v2/write?org={}&bucket={}", write_base.as_ref(), org.as_ref(), bucket.as_ref() ); let mut builder = Request::builder().uri(url).method("POST"); if let Some(authorization) = authorization { builder = builder.header(hyper::header::AUTHORIZATION, authorization); }; let request = builder .body(Body::from(line_protocol.into())) .expect("failed to construct HTTP request"); client .request(request) .await .expect("http error sending write") } /// Writes the line protocol to the WriteService endpoint (typically on the ingester) pub async fn write_to_ingester( line_protocol: impl Into<String>, namespace_id: NamespaceId, table_id: TableId, ingester_connection: Connection, ) { let line_protocol = line_protocol.into(); let writes = lines_to_batches(&line_protocol, 0).unwrap(); let writes = writes .into_iter() .map(|(_name, data)| (table_id, data)) .collect(); let mut client = WriteServiceClient::new(ingester_connection.into_grpc_connection()); let op = DmlWrite::new( namespace_id, writes, "1970-01-01".into(), DmlMeta::unsequenced(None), ); client .write( tonic::Request::new(WriteRequest { payload: Some(encode_write(namespace_id.get(), &op)), }) .into_request(), ) .await .unwrap(); } /// Runs a SQL query using the flight API on the specified connection. pub async fn try_run_sql( sql_query: impl Into<String>, namespace: impl Into<String>, querier_connection: Connection, authorization: Option<&str>, with_debug: bool, ) -> Result<(Vec<RecordBatch>, SchemaRef), influxdb_iox_client::flight::Error> { let mut client = influxdb_iox_client::flight::Client::new(querier_connection); if with_debug { client.add_header("iox-debug", "true").unwrap(); } if let Some(authorization) = authorization { client.add_header("authorization", authorization).unwrap(); } // Test the client handshake implementation // Normally this would be done one per connection, not per query client.handshake().await?; let mut stream = client.sql(namespace.into(), sql_query.into()).await?; let batches = (&mut stream).try_collect().await?; // read schema AFTER collection, otherwise the stream does not have the schema data yet let schema = stream .inner() .schema() .cloned() .ok_or(influxdb_iox_client::flight::Error::NoSchema)?; Ok((batches, schema)) } /// Runs a InfluxQL query using the flight API on the specified connection. pub async fn try_run_influxql( influxql_query: impl Into<String>, namespace: impl Into<String>, querier_connection: Connection, authorization: Option<&str>, ) -> Result<(Vec<RecordBatch>, SchemaRef), influxdb_iox_client::flight::Error> { let mut client = influxdb_iox_client::flight::Client::new(querier_connection); if let Some(authorization) = authorization { client.add_header("authorization", authorization).unwrap(); } // Test the client handshake implementation // Normally this would be done one per connection, not per query client.handshake().await?; let mut stream = client .influxql(namespace.into(), influxql_query.into()) .await?; let batches = (&mut stream).try_collect().await?; // read schema AFTER collection, otherwise the stream does not have the schema data yet let schema = stream .inner() .schema() .cloned() .ok_or(influxdb_iox_client::flight::Error::NoSchema)?; Ok((batches, schema)) } /// Runs a SQL query using the flight API on the specified connection. /// /// Use [`try_run_sql`] if you want to check the error manually. pub async fn run_sql( sql: impl Into<String>, namespace: impl Into<String>, querier_connection: Connection, authorization: Option<&str>, with_debug: bool, ) -> (Vec<RecordBatch>, SchemaRef) { try_run_sql( sql, namespace, querier_connection, authorization, with_debug, ) .await .expect("Error executing sql query") } /// Runs an InfluxQL query using the flight API on the specified connection. /// /// Use [`try_run_influxql`] if you want to check the error manually. pub async fn run_influxql( influxql: impl Into<String> + Clone + Display, namespace: impl Into<String>, querier_connection: Connection, authorization: Option<&str>, ) -> (Vec<RecordBatch>, SchemaRef) { try_run_influxql( influxql.clone(), namespace, querier_connection, authorization, ) .await .unwrap_or_else(|_| panic!("Error executing InfluxQL query: {influxql}")) }
use super::ema::ema_func; use super::sma::{declare_ma_var, wma_func}; use super::tr::tr_func; use super::VarResult; use crate::ast::stat_expr_types::VarIndex; use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType}; use crate::helper::err_msgs::*; use crate::helper::str_replace; use crate::helper::{ ensure_srcs, ge1_param_i64, move_element, pine_ref_to_bool, pine_ref_to_f64, pine_ref_to_f64_series, pine_ref_to_i64, require_param, }; use crate::runtime::context::{downcast_ctx, Ctx}; use crate::runtime::InputSrc; use crate::types::{ downcast_pf_ref, int2float, Arithmetic, Callable, CallableCreator, CallableFactory, Evaluate, EvaluateVal, Float, Int, ParamCollectCall, PineRef, RefData, RuntimeErr, Series, SeriesCall, Tuple, }; use std::f64; use std::mem; use std::rc::Rc; pub type ValGenerator<'a> = fn((Float, Float, Float)) -> PineRef<'a>; fn kc_generator<'a>(vals: (Float, Float, Float)) -> PineRef<'a> { let (basis, ema1, ema2) = vals; PineRef::new(Tuple(vec![ PineRef::new_rc(Series::from(basis)), PineRef::new_rc(Series::from(ema1)), PineRef::new_rc(Series::from(ema2)), ])) } #[derive(Debug, Clone, PartialEq)] pub struct KcVal { close_index: VarIndex, low_index: VarIndex, high_index: VarIndex, prev_basis: Float, prev_range_ema: Float, val_gen: *mut (), } impl KcVal { pub fn new(val_gen: *mut ()) -> KcVal { KcVal { close_index: VarIndex::new(0, 0), low_index: VarIndex::new(0, 0), high_index: VarIndex::new(0, 0), prev_basis: None, prev_range_ema: None, val_gen: val_gen, } } fn handle_index<'a>(&mut self, ctx: &mut dyn Ctx<'a>) { ensure_srcs(ctx, vec!["close", "low", "high"], |indexs| { self.close_index = indexs[0]; self.low_index = indexs[1]; self.high_index = indexs[2]; }); } fn process_kc<'a>( &mut self, _ctx: &mut dyn Ctx<'a>, mut param: Vec<Option<PineRef<'a>>>, _func_type: FunctionType<'a>, ) -> Result<(Float, Float, Float), RuntimeErr> { self.handle_index(_ctx); move_tuplet!((series, length, multi, use_true_range) = param); let sval = pine_ref_to_f64(series); let length = ge1_param_i64("length", pine_ref_to_i64(length))?; let multi = require_param("multi", pine_ref_to_f64(multi))?; let use_true_range = pine_ref_to_bool(use_true_range).unwrap_or(true); let basis = ema_func(sval, length, self.prev_basis)?; let high = pine_ref_to_f64(_ctx.get_var(self.high_index).clone()); let low = pine_ref_to_f64(_ctx.get_var(self.low_index).clone()); let range = if use_true_range { let close = pine_ref_to_f64_series(_ctx.get_var(self.close_index).clone()).unwrap(); let preclose = close.index_value(1).unwrap(); tr_func(high, low, preclose) } else { high.minus(low) }; let range_ema = ema_func(range, length, self.prev_range_ema)?; self.prev_basis = basis; self.prev_range_ema = range_ema; let multi_ema = range_ema.mul(Some(multi)); Ok((basis, basis.add(multi_ema), basis.minus(multi_ema))) } } impl<'a> SeriesCall<'a> for KcVal { fn step( &mut self, _ctx: &mut dyn Ctx<'a>, param: Vec<Option<PineRef<'a>>>, _func_type: FunctionType<'a>, ) -> Result<PineRef<'a>, RuntimeErr> { let func = unsafe { mem::transmute::<_, ValGenerator<'a>>(self.val_gen) }; Ok(func(self.process_kc(_ctx, param, _func_type)?)) } fn copy(&self) -> Box<dyn SeriesCall<'a> + 'a> { Box::new(self.clone()) } } pub fn declare_var<'a>() -> VarResult<'a> { let value = PineRef::new(CallableFactory::new(|| { Callable::new( None, Some(Box::new(ParamCollectCall::new_with_caller(Box::new( KcVal::new(kc_generator as *mut ()), )))), ) })); let func_type = FunctionTypes(vec![FunctionType::new(( vec![ ("series", SyntaxType::float_series()), ("length", SyntaxType::int()), ("mult", SyntaxType::float()), ("useTrueRange", SyntaxType::bool()), ], SyntaxType::Tuple(Rc::new(vec![ SyntaxType::float_series(), SyntaxType::float_series(), SyntaxType::float_series(), ])), ))]); let syntax_type = SyntaxType::Function(Rc::new(func_type)); VarResult::new(value, syntax_type, "kc") } #[cfg(test)] mod tests { use super::*; use crate::ast::syntax_type::SyntaxType; use crate::runtime::VarOperate; use crate::runtime::{AnySeries, NoneCallback}; use crate::types::Series; use crate::{LibInfo, PineParser, PineRunner}; // use crate::libs::{floor, exp, }; #[test] fn alma_test() { let lib_info = LibInfo::new( vec![declare_var()], vec![ ("close", SyntaxType::float_series()), ("high", SyntaxType::float_series()), ("low", SyntaxType::float_series()), ], ); let src = "[m1, m2, m3] = kc(close, 3, 1)\n"; let blk = PineParser::new(src, &lib_info).parse_blk().unwrap(); let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback()); runner .run( &vec![ ( "close", AnySeries::from_float_vec(vec![Some(10f64), Some(20f64)]), ), ( "high", AnySeries::from_float_vec(vec![Some(6f64), Some(20f64)]), ), ( "low", AnySeries::from_float_vec(vec![Some(6f64), Some(20f64)]), ), ], None, ) .unwrap(); assert_eq!( runner.get_context().move_var(VarIndex::new(0, 0)), Some(PineRef::new(Series::from_vec(vec![ Some(5f64), Some(12.5f64) ]))) ); } }
pub mod block; pub mod chain; pub mod consensus; pub mod controller; pub mod proof_of_work; pub mod viewmodel; use chain::Chain; use std::sync::RwLock; use uuid::Uuid; use actix_web::{web, App, HttpServer}; #[actix_web::main] async fn main() -> std::io::Result<()> { let chain = web::Data::new(RwLock::new(Chain::new())); HttpServer::new(move || { App::new() .app_data(chain.clone()) .app_data(web::Data::new(format!("{}", Uuid::new_v4()))) .service(controller::mine) .service(controller::create_transaction) .service(controller::get_chain) .service(controller::add_node_to_network) .service(controller::resolve_conflicts) }) .bind("127.0.0.1:8080")? .run() .await }
/* * Copyright 2019 The Exonum 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 exonum::blockchain::{ExecutionError, ExecutionResult, Transaction, TransactionContext}; use exonum::messages::BinaryForm; use exonum::messages::RawTransaction; use jni::objects::{GlobalRef, JObject, JValue}; use jni::signature::{JavaType, Primitive}; use jni::JNIEnv; use serde; use std::fmt; use storage::View; use utils::{ describe_java_exception, get_and_clear_java_exception, get_exception_message, jni_cache::{classes_refs::transaction_execution_exception, transaction_adapter::execute_id}, to_handle, unwrap_jni, }; use {JniErrorKind, JniExecutor, JniResult, MainExecutor}; /// A proxy for `Transaction`s. #[derive(Clone)] pub struct TransactionProxy { exec: MainExecutor, transaction: GlobalRef, raw: RawTransaction, } // `TransactionProxy` is immutable, so it can be safely used in different threads. unsafe impl Sync for TransactionProxy {} impl fmt::Debug for TransactionProxy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "TransactionProxy") } } impl TransactionProxy { /// Creates a `TransactionProxy` of the given Java transaction. pub fn from_global_ref( exec: MainExecutor, transaction: GlobalRef, raw: RawTransaction, ) -> Self { TransactionProxy { exec, transaction, raw, } } } impl serde::Serialize for TransactionProxy { fn serialize<S>( &self, serializer: S, ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> where S: serde::Serializer, { serializer.serialize_bytes( &self .raw .encode() .expect("Could not serialize TransactionProxy"), ) } } impl Transaction for TransactionProxy { fn execute(&self, mut context: TransactionContext) -> ExecutionResult { let res = self.exec.with_attached(|env: &JNIEnv| { let tx_hash = context.tx_hash(); let author_pk = context.author(); let view_handle = to_handle(View::from_ref_fork(context.fork())); let tx_hash = JObject::from(env.byte_array_from_slice(tx_hash.as_ref())?); let author_pk = JObject::from(env.byte_array_from_slice(author_pk.as_ref())?); let res = unsafe { env.call_method_unsafe( self.transaction.as_obj(), execute_id(), JavaType::Primitive(Primitive::Void), &[ JValue::from(view_handle), JValue::from(tx_hash), JValue::from(author_pk), ], ) .and_then(JValue::v) }; Ok(check_transaction_execution_result(env, res)) }); unwrap_jni(res) } } /// Handles exceptions after executing transactions /// /// The TransactionExecutionException and its descendants are converted into `Error`s with their /// descriptions. The rest (Java and JNI errors) are treated as unrecoverable and result in a panic. /// /// Panics: /// - Panics if there is some JNI error. /// - If there is a pending Java throwable that IS NOT an instance of the /// `TransactionExecutionException`. fn check_transaction_execution_result<T>( env: &JNIEnv, result: JniResult<T>, ) -> Result<T, ExecutionError> { result.map_err(|jni_error| match jni_error.0 { JniErrorKind::JavaException => { let exception = get_and_clear_java_exception(env); let message = unwrap_jni(get_exception_message(env, exception)); if !unwrap_jni(env.is_instance_of(exception, &transaction_execution_exception())) { let panic_msg = describe_java_exception(env, exception); panic!(panic_msg); } let err_code = unwrap_jni(get_tx_error_code(env, exception)) as u8; match message { Some(msg) => ExecutionError::with_description(err_code, msg), None => ExecutionError::new(err_code), } } _ => unwrap_jni(Err(jni_error)), }) } /// Returns the error code of the `TransactionExecutionException` instance. fn get_tx_error_code(env: &JNIEnv, exception: JObject) -> JniResult<i8> { let err_code = env.call_method(exception, "getErrorCode", "()B", &[])?; err_code.b() }
// 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. mod builder; mod column_stat; mod datum; mod enforcer; mod histogram; #[allow(clippy::module_inception)] mod property; mod selectivity; pub use builder::RelExpr; pub use column_stat::ColumnStat; pub use column_stat::ColumnStatSet; pub use column_stat::NewStatistic; pub use datum::Datum; pub use enforcer::require_property; pub use histogram::histogram_from_ndv; pub use histogram::Histogram; pub use histogram::HistogramBucket; pub use histogram::InterleavedBucket; pub use histogram::UniformSampleSet; pub use histogram::DEFAULT_HISTOGRAM_BUCKETS; pub use property::ColumnSet; pub use property::Distribution; pub use property::PhysicalProperty; pub use property::RelationalProperty; pub use property::RequiredProperty; pub use property::Statistics; pub use property::TableSet; pub use selectivity::SelectivityEstimator; pub use selectivity::DEFAULT_SELECTIVITY; pub use selectivity::MAX_SELECTIVITY;
pub(crate) mod cpu_set; pub(crate) mod syscalls; pub(crate) mod types; pub(crate) mod wait;
use std::time::Duration; use smithay::{ backend::{ renderer::{ damage::OutputDamageTracker, element::surface::WaylandSurfaceRenderElement, gles::GlesRenderer, }, winit::{self, WinitError, WinitEvent, WinitEventLoop, WinitGraphicsBackend}, }, output::{Mode, Output, PhysicalProperties, Subpixel}, reexports::{ calloop::{ timer::{TimeoutAction, Timer}, EventLoop, LoopSignal, }, wayland_server::{protocol::wl_surface::WlSurface, Display}, }, utils::{Rectangle, Transform}, }; use crate::{state::Backend, CalloopData, Corrosion}; pub struct WinitData { loop_signal: LoopSignal, } impl Backend for WinitData { fn loop_signal(&self) -> &LoopSignal { &self.loop_signal } fn seat_name(&self) -> String { String::from("wayland-0") } fn early_import(&mut self, _output: &WlSurface) {} fn reset_buffers(&mut self, _surface: &Output) {} } pub fn init_winit<BackendData: Backend + 'static>() -> Result<(), Box<dyn std::error::Error>> { let mut event_loop = EventLoop::try_new().expect("Unable to create callback loop"); let mut display = Display::new().expect("Unable to create display :("); let backend_data = WinitData { loop_signal: event_loop.get_signal(), }; let mut state: Corrosion<WinitData> = Corrosion::new(event_loop.handle(), &mut display, backend_data); let (mut backend, mut winit) = winit::init()?; // This code creates a variable named mode that contains the size and refresh rate of the window. let mode = Mode { size: backend.window_size().physical_size, refresh: 60_000, }; let output = Output::new( String::from("Corrosionwm"), PhysicalProperties { size: (0, 0).into(), subpixel: Subpixel::Unknown, make: "Corrosionwm".into(), // name of the window manager if you are running a window manager inside a window manager this might matter to you model: "Winit".into(), }, ); let _global = output.create_global::<Corrosion<BackendData>>(&display.handle()); output.change_current_state( Some(mode), Some(Transform::Flipped180), None, Some((0, 0).into()), ); output.set_preferred(mode); state.space.map_output(&output, (0, 0)); let mut damage_tracked_renderer = OutputDamageTracker::from_output(&output); // Set the environment variable WAYLAND_DISPLAY to the socket name of the display. std::env::set_var("WAYLAND_DISPLAY", &state.socket_name); let mut full_redraw = 0u8; // This code creates a timer that will be used to redraw the window. let timer = Timer::immediate(); let mut data = CalloopData { state, display }; event_loop .handle() .insert_source(timer, move |_, _, data| { winit_dispatch( &mut backend, &mut winit, data, &output, &mut damage_tracked_renderer, &mut full_redraw, ) .unwrap(); TimeoutAction::ToDuration(Duration::from_millis(16)) })?; // aaand we run our loop :3 event_loop .run(None, &mut data, move |_| {}) .expect("Unable to initialize winit backend"); Ok(()) } pub fn winit_dispatch<BackendData: Backend>( backend: &mut WinitGraphicsBackend<GlesRenderer>, winit: &mut WinitEventLoop, data: &mut CalloopData<BackendData>, output: &Output, damage_tracked_renderer: &mut OutputDamageTracker, full_redraw: &mut u8, ) -> Result<(), Box<dyn std::error::Error>> { // This code dispatches new events, and if the window is closed, it stops the loop. let display = &mut data.display; let state = &mut data.state; // The callback function passed to dispatch_new_events() is called for every new event // that occurred since the last call to dispatch_new_events(). The code above // handles two types of events: window resize events and input events. When a new // window resize event is received, the output's current state is updated to reflect // the new window size. When a new input event is received, it is passed to the // state's process_input_event() function. let res = winit.dispatch_new_events(|event| match event { WinitEvent::Resized { size, .. } => { output.change_current_state( Some(Mode { size, refresh: 60_000, }), None, None, None, ); tracing::debug!("Resized to {:?}", size); } // TODO: make input event processor for winit backend // WinitEvent::Input(event) => state.process_input_event(event), _ => (), }); // windowbuilder to set the windows title to "corrosionWM" backend.window().set_title("corrosionWM"); // If the window is closed, stop the loop if let Err(WinitError::WindowClosed) = res { // Stop the loop return Ok(()); } else { res?; } *full_redraw = full_redraw.saturating_sub(1); let size = backend.window_size().physical_size; let damage = Rectangle::from_loc_and_size((0, 0), size); // This code renders the output, submits the frame, and refreshes the space. backend.bind()?; smithay::desktop::space::render_output::<_, WaylandSurfaceRenderElement<GlesRenderer>, _, _>( output, backend.renderer(), 0, [&state.space], &[], damage_tracked_renderer, [0.1, 0.1, 0.1, 1.0], )?; backend.submit(Some(&[damage]))?; // This code sends the frame to the clients. state.space.elements().for_each(|window| { window.send_frame( output, state.start_time.elapsed(), Some(Duration::ZERO), |_, _| Some(output.clone()), ) }); state.space.refresh(); display.flush_clients()?; Ok(()) // Return Ok if everything went well }
use helium_console::{oauth2, ttn}; use oauth2::{prelude::SecretNewType, AccessToken, AuthorizationCode}; use reset_router::{Request, RequestExtensions, Response}; use serde_derive::{Deserialize, Serialize}; pub async fn auth(req: Request) -> Result<Response, Response> { #[derive(Serialize, Debug)] pub struct Response { account_token: String, apps: Vec<ttn::App>, } if let Some(access_code) = req.captures().unwrap().get(1) { let auth_code = AuthorizationCode::new(access_code.to_string()); let ttn_client = ttn::Client::new().unwrap(); let account_token = match ttn_client.get_account_token(auth_code) { Ok(account_token) => account_token, Err(e) => { return Ok(http::Response::builder() .status(400) .body(format!("{}", e).into()) .unwrap()) } }; let apps = ttn_client.get_apps(&account_token).await.unwrap(); let response = Response { account_token: account_token.secret().clone(), apps, }; Ok(http::Response::builder() .status(200) .body(serde_json::to_string(&response).unwrap().into()) .unwrap()) } else { Ok(http::Response::builder() .status(404) .body("404".into()) .unwrap()) } } pub async fn exchange(req: Request) -> Result<Response, Response> { #[derive(Deserialize, Debug)] pub struct Request { account_token: String, apps: Vec<String>, } #[derive(Serialize, Debug)] pub struct Response { restricted_token: String, } let (_parts, body) = req.into_parts(); let bytes = hyper::body::to_bytes(body).await.unwrap(); let request: Result<Request, serde_json::error::Error> = serde_json::from_slice(&bytes); match request { Ok(request) => { let mut ttn_client = ttn::Client::new().unwrap(); let account_token = AccessToken::new(request.account_token); let restricted_token = match ttn_client .exchange_for_app_token(account_token, request.apps) .await { Ok(token) => token, Err(e) => { return Ok(http::Response::builder() .status(401) .body(format!("{}", e).into()) .unwrap()) } }; let response = Response { restricted_token }; Ok(http::Response::builder() .status(200) .body(serde_json::to_string(&response).unwrap().into()) .unwrap()) } Err(e) => Ok(http::Response::builder() .status(400) .body(format!("{}", e).into()) .unwrap()), } } pub async fn devices(req: Request) -> Result<Response, Response> { #[derive(Deserialize, Debug)] pub struct Request { restricted_token: String, appid: String, } let (_parts, body) = req.into_parts(); let bytes = hyper::body::to_bytes(body).await.unwrap(); let request: Result<Request, serde_json::error::Error> = serde_json::from_slice(&bytes); match request { Ok(request) => { let ttn_client = ttn::Client::new().unwrap(); let devices = match ttn_client .get_devices(&request.appid, request.restricted_token.as_str()) .await { Ok(devices) => devices, Err(e) => { return Ok(http::Response::builder() .status(401) .body(format!("{}", e).into()) .unwrap()) } }; #[derive(Serialize, Debug)] pub struct Response { devices: Vec<ttn::TtnDevice>, } let response = Response { devices }; Ok(http::Response::builder() .status(200) .body(serde_json::to_string(&response).unwrap().into()) .unwrap()) } Err(e) => Ok(http::Response::builder() .status(400) .body(format!("{}", e).into()) .unwrap()), } }
fn main() { tonic_build::configure() .build_server(false) .compile(&["protos/helloworld.proto"], &["protos"]) .unwrap(); }
use crate::target::Target; pub struct FileTarget { target: String, remove: bool, input_file: String, output_file: String, } impl FileTarget { pub fn new(target: &str, remove: bool, input_file: &str, output_file: &str) -> FileTarget { let input_file = String::from(input_file); let output_file = String::from(output_file); FileTarget { target: String::from(target), remove, input_file, output_file, } } } impl Target for FileTarget { fn compile(&self) { let args: Vec<&str> = vec![&self.target]; self.exe_ord("make", args, ("", "")); } fn run(&self) { let mut ordr = String::from("./"); let mut args: Vec<&str> = Vec::new(); ordr += &self.target; self.exe_ord(&ordr, args, (&self.input_file, &self.output_file)); } fn delet(&self) { let args: Vec<&str> = vec![&self.target]; self.exe_ord("rm", args, ("", "")); } fn print_self(&self) -> String { String::from("target: ") + &self.target } fn get_infile(&self) -> String { self.input_file.clone() } fn get_outfile(&self) -> String { self.output_file.clone() } fn main_loop(&mut self) { self.compile(); self.run(); if self.remove { self.delet(); } } }
fn contains_zero(values: &[i32]) -> bool { values.iter().any(|v| { v == &0 }) } fn main() { assert!(!contains_zero(&[1, 2, 3, 4, 5])); assert!(contains_zero(&[0, 2, 3, 4, 5])); assert!(contains_zero(&[1, 2, 0, 4, 5])); assert!(contains_zero(&[1, 2, 3, 4, 0])); }
#![allow(unused_variables)] extern crate simplemad; extern crate portaudio; #[macro_use] extern crate error_chain; use portaudio as pa; use simplemad::Decoder; use std::fs::File; use std::io; use std::env; const INTERLEAVED: bool = true; error_chain! { foreign_links { PortAudio(pa::Error); Io(io::Error); } errors { Simplemad(err: simplemad::SimplemadError) { description("something went wrong in simplemad") display("{:?}", err) } } } impl From<simplemad::SimplemadError> for Error { fn from(err: simplemad::SimplemadError) -> Error { ErrorKind::Simplemad(err).into() } } fn main() { fn try() -> Result<()> { // Open the input file let args = env::args(); let path = args.last().unwrap(); assert!(path.ends_with(".mp3")); let file = File::open(path)?; let mut decoder = Decoder::decode(file)?.peekable(); while let Some(&Err(_)) = decoder.peek() { decoder.next(); } let (sample_rate, num_channels, frames) = { let frame = match *decoder.peek().ok_or("No frames")? { Ok(ref frame) => frame, Err(ref err) => panic!(), }; (frame.sample_rate, frame.samples.len(), frame.samples[0].len()) }; println!("Sample rate: {}", sample_rate); println!("Channels : {}", num_channels); let pa = pa::PortAudio::new()?; println!("PortAudio"); println!("version: {}", pa.version()); println!("version text: {:?}", pa.version_text()); println!("host count: {}", pa.host_api_count()?); let default_host = pa.default_host_api()?; println!("default host: {:#?}", pa.host_api_info(default_host)); let def_output = pa.default_output_device()?; let output_info = pa.device_info(def_output)?; println!("Default output device info: {:#?}", &output_info); // Construct the output stream parameters. let latency = output_info.default_low_output_latency; let output_params = pa::StreamParameters::<f32>::new(def_output, num_channels as i32, INTERLEAVED, latency); // Check that the stream format is supported. try!(pa.is_output_format_supported(output_params, sample_rate as f64)); // Construct the settings with which we'll open our duplex stream. let settings = pa::OutputStreamSettings::new(output_params, sample_rate as f64, frames as u32); let mut stream = pa.open_blocking_stream(settings)?; stream.start()?; // Now start the main read/write loop! In this example, we pass the input buffer directly to // the output buffer, so watch out for feedback. while let Some(frame) = decoder.next() { let frame = frame?; assert_eq!(sample_rate, frame.sample_rate); assert_eq!(num_channels, frame.samples.len()); // How many frames are available for writing on the output stream? let mut out_frames = 0; while out_frames < frame.samples[0].len() { match stream.write_available()? { pa::StreamAvailable::Frames(frames) => { out_frames = frames as usize; } other => println!("{:?}", other), } } // Actually only write how many are available out_frames = frame.samples[0].len(); stream.write(out_frames as u32, |output| { for i in 0..out_frames { for j in 0..num_channels { output[i * num_channels + j] = frame.samples[j][i].to_f32(); } } // println!("Wrote {:?} frames to the output stream.", out_frames); })?; } Ok(()) } try().unwrap(); }
use math::big::{self, Int}; use strconv::NumErrorCause; mod helper; use helper::is_big_int_normalized as is_normalized; lazy_static::lazy_static! { static ref BITWISE_TESTS: Vec<BitwiseTest> = vec![ BitwiseTest::new("0x00", "0x00", "0x00", "0x00", "0x00", "0x00"), BitwiseTest::new("0x00", "0x01", "0x00", "0x01", "0x01", "0x00"), BitwiseTest::new("0x01", "0x00", "0x00", "0x01", "0x01", "0x01"), BitwiseTest::new("-0x01", "0x00", "0x00", "-0x01", "-0x01", "-0x01"), BitwiseTest::new("-0xaf", "-0x50", "-0xf0", "-0x0f", "0xe1", "0x41"), BitwiseTest::new("0x00", "-0x01", "0x00", "-0x01", "-0x01", "0x00"), BitwiseTest::new("0x01", "0x01", "0x01", "0x01", "0x00", "0x00"), BitwiseTest::new("-0x01", "-0x01", "-0x01", "-0x01", "0x00", "0x00"), BitwiseTest::new("0x07", "0x08", "0x00", "0x0f", "0x0f", "0x07"), BitwiseTest::new("0x05", "0x0f", "0x05", "0x0f", "0x0a", "0x00"), BitwiseTest::new("0xff", "-0x0a", "0xf6", "-0x01", "-0xf7", "0x09"), BitwiseTest::new("0x013ff6", "0x9a4e", "0x1a46", "0x01bffe", "0x01a5b8", "0x0125b0"), BitwiseTest::new("-0x013ff6", "0x9a4e", "0x800a", "-0x0125b2", "-0x01a5bc", "-0x01c000"), BitwiseTest::new("-0x013ff6", "-0x9a4e", "-0x01bffe", "-0x1a46", "0x01a5b8", "0x8008"), BitwiseTest::new( "0x1000009dc6e3d9822cba04129bcbe3401", "0xb9bd7d543685789d57cb918e833af352559021483cdb05cc21fd", "0x1000001186210100001000009048c2001", "0xb9bd7d543685789d57cb918e8bfeff7fddb2ebe87dfbbdfe35fd", "0xb9bd7d543685789d57ca918e8ae69d6fcdb2eae87df2b97215fc", "0x8c40c2d8822caa04120b8321400", ), BitwiseTest::new( "0x1000009dc6e3d9822cba04129bcbe3401", "-0xb9bd7d543685789d57cb918e833af352559021483cdb05cc21fd", "0x8c40c2d8822caa04120b8321401", "-0xb9bd7d543685789d57ca918e82229142459020483cd2014001fd", "-0xb9bd7d543685789d57ca918e8ae69d6fcdb2eae87df2b97215fe", "0x1000001186210100001000009048c2000", ), BitwiseTest::new( "-0x1000009dc6e3d9822cba04129bcbe3401", "-0xb9bd7d543685789d57cb918e833af352559021483cdb05cc21fd", "-0xb9bd7d543685789d57cb918e8bfeff7fddb2ebe87dfbbdfe35fd", "-0x1000001186210100001000009048c2001", "0xb9bd7d543685789d57ca918e8ae69d6fcdb2eae87df2b97215fc", "0xb9bd7d543685789d57ca918e82229142459020483cd2014001fc", ), ]; static ref CMP_ABS_TESTS: Vec<&'static str> = vec![ "0", "1", "2", "10", "10000000", "2783678367462374683678456387645876387564783686583485", "2783678367462374683678456387645876387564783686583486", "32957394867987420967976567076075976570670947609750670956097509670576075067076027578341538", ]; static ref LSH_TESTS: Vec<IntShiftTest> = vec![ IntShiftTest::new("0", 0, "0"), IntShiftTest::new("0", 1, "0"), IntShiftTest::new("0", 2, "0"), IntShiftTest::new("1", 0, "1"), IntShiftTest::new("1", 1, "2"), IntShiftTest::new("1", 2, "4"), IntShiftTest::new("2", 0, "2"), IntShiftTest::new("2", 1, "4"), IntShiftTest::new("2", 2, "8"), IntShiftTest::new("-87", 1, "-174"), IntShiftTest::new("4294967296", 0, "4294967296"), IntShiftTest::new("4294967296", 1, "8589934592"), IntShiftTest::new("4294967296", 2, "17179869184"), IntShiftTest::new("18446744073709551616", 0, "18446744073709551616"), IntShiftTest::new("9223372036854775808", 1, "18446744073709551616"), IntShiftTest::new("4611686018427387904", 2, "18446744073709551616"), IntShiftTest::new("1", 64, "18446744073709551616"), IntShiftTest::new( "18446744073709551616", 64, "340282366920938463463374607431768211456", ), IntShiftTest::new("1", 128, "340282366920938463463374607431768211456"), ]; static ref PRIMES: Vec<&'static str> = vec![ "2", "3", "5", "7", "11", "13756265695458089029", "13496181268022124907", "10953742525620032441", "17908251027575790097", // https://golang.org/issue/638 "18699199384836356663", "98920366548084643601728869055592650835572950932266967461790948584315647051443", "94560208308847015747498523884063394671606671904944666360068158221458669711639", // https://primes.utm.edu/lists/small/small3.html "449417999055441493994709297093108513015373787049558499205492347871729927573118262811508386655998299074566974373711472560655026288668094291699357843464363003144674940345912431129144354948751003607115263071543163", "230975859993204150666423538988557839555560243929065415434980904258310530753006723857139742334640122533598517597674807096648905501653461687601339782814316124971547968912893214002992086353183070342498989426570593", "5521712099665906221540423207019333379125265462121169655563495403888449493493629943498064604536961775110765377745550377067893607246020694972959780839151452457728855382113555867743022746090187341871655890805971735385789993", "203956878356401977405765866929034577280193993314348263094772646453283062722701277632936616063144088173312372882677123879538709400158306567338328279154499698366071906766440037074217117805690872792848149112022286332144876183376326512083574821647933992961249917319836219304274280243803104015000563790123", // ECC primes: https://tools.ietf.org/html/draft-ladd-safecurves-02 "3618502788666131106986593281521497120414687020801267626233049500247285301239", // Curve1174: 2^251-9 "57896044618658097711785492504343953926634992332820282019728792003956564819949", // Curve25519: 2^255-19 "9850501549098619803069760025035903451269934817616361666987073351061430442874302652853566563721228910201656997576599", // E-382: 2^382-105 "42307582002575910332922579714097346549017899709713998034217522897561970639123926132812109468141778230245837569601494931472367", // Curve41417: 2^414-17 "6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151", // E-521: 2^521-1 ]; static ref PROD_ZZ: Vec<ArgZz> = vec![ ArgZz::from_i64s(0, 0, 0), ArgZz::from_i64s(0, 1, 0), ArgZz::from_i64s(1, 1, 1), ArgZz::from_i64s(-991*991, 991, -991), ]; static ref RSH_TESTS: Vec<IntShiftTest> = vec![ IntShiftTest::new("0", 0, "0"), IntShiftTest::new("-0", 0, "0"), IntShiftTest::new("0", 1, "0"), IntShiftTest::new("0", 2, "0"), IntShiftTest::new("1", 0, "1"), IntShiftTest::new("1", 1, "0"), IntShiftTest::new("1", 2, "0"), IntShiftTest::new("2", 0, "2"), IntShiftTest::new("2", 1, "1"), IntShiftTest::new("-1", 0, "-1"), IntShiftTest::new("-1", 1, "-1"), IntShiftTest::new("-1", 10, "-1"), IntShiftTest::new("-100", 2, "-25"), IntShiftTest::new("-100", 3, "-13"), IntShiftTest::new("-100", 100, "-1"), IntShiftTest::new("4294967296", 0, "4294967296"), IntShiftTest::new("4294967296", 1, "2147483648"), IntShiftTest::new("4294967296", 2, "1073741824"), IntShiftTest::new("18446744073709551616", 0, "18446744073709551616"), IntShiftTest::new("18446744073709551616", 1, "9223372036854775808"), IntShiftTest::new("18446744073709551616", 2, "4611686018427387904"), IntShiftTest::new("18446744073709551616", 64, "1"), IntShiftTest::new( "340282366920938463463374607431768211456", 64, "18446744073709551616", ), IntShiftTest::new("340282366920938463463374607431768211456", 128, "1"), ]; static ref SUM_ZZ: Vec<ArgZz> = vec![ ArgZz::new(Int::new(0), Int::new(0), Int::new(0)), ArgZz::new(Int::new(1), Int::new(1), Int::new(0)), ArgZz::new(Int::new(1111111110), Int::new(123456789), Int::new(987654321)), ArgZz::from_i64s(-1, -1, 0), ArgZz::from_i64s(864197532, -123456789, 987654321), ArgZz::from_i64s(-1111111110, -123456789, -987654321), ]; } #[derive(Clone, Debug)] struct ArgZz { z: Int, x: Int, y: Int, } struct BitwiseTest { x: &'static str, y: &'static str, and: &'static str, or: &'static str, xor: &'static str, and_not: &'static str, } struct IntShiftTest { input: &'static str, shift: usize, out: &'static str, } impl ArgZz { fn new(z: Int, x: Int, y: Int) -> Self { Self { z, x, y } } fn from_i64s(z: i64, x: i64, y: i64) -> Self { Self { z: Int::new(z), x: Int::new(x), y: Int::new(y), } } } impl BitwiseTest { fn new( x: &'static str, y: &'static str, and: &'static str, or: &'static str, xor: &'static str, and_not: &'static str, ) -> Self { Self { x, y, and, or, xor, and_not, } } } impl IntShiftTest { fn new(input: &'static str, shift: usize, out: &'static str) -> Self { Self { input, shift, out } } } #[test] fn abs_z() { let zero = Int::default(); for a in SUM_ZZ.iter() { let mut z = Int::default(); z.abs(&a.z); let mut e = Int::default(); e.set(&a.z); if e.cmp(&zero) < 0 { let v = e.clone(); e.sub(&zero, &v); } assert_eq!(z, e); } } #[test] fn binomial() { struct Case { n: i64, k: i64, want: &'static str, } let new_case = |n, k, want| -> Case { Case { n, k, want } }; let test_vector = vec![ new_case(0, 0, "1"), new_case(0, 1, "0"), new_case(1, 0, "1"), new_case(1, 1, "1"), new_case(1, 10, "0"), new_case(4, 0, "1"), new_case(4, 1, "4"), new_case(4, 2, "6"), new_case(4, 3, "4"), new_case(4, 4, "1"), new_case(10, 1, "10"), new_case(10, 9, "10"), new_case(10, 5, "252"), new_case(11, 5, "462"), new_case(11, 6, "462"), new_case(100, 10, "17310309456440"), new_case(100, 90, "17310309456440"), new_case(1000, 10, "263409560461970212832400"), new_case(1000, 990, "263409560461970212832400"), ]; let mut z = Int::default(); for c in test_vector { let got = z.binomial(c.n, c.k).to_string(); assert_eq!(c.want, got, "binomial({},{})", c.n, c.k); } } #[test] fn bit_len() { struct Case { input: &'static str, out: usize, } let new_case = |input, out| Case { input, out }; let test_vector = vec![ new_case("-1", 1), new_case("0", 0), new_case("1", 1), new_case("2", 2), new_case("4", 3), new_case("0xabc", 12), new_case("0x8000", 16), new_case("0x80000000", 32), new_case("0x800000000000", 48), new_case("0x8000000000000000", 64), new_case("0x80000000000000000000", 80), new_case("-0x4000000000000000000000", 87), ]; for (i, c) in test_vector.iter().enumerate() { let mut x = Int::default(); assert!( x.set_string(c.input, 0).is_some(), "#{i} set_string({}, 0)", c.input ); assert_eq!(x.bit_len(), c.out, "#{i} bit_len"); } } #[test] fn bit_set() { struct Case { x: &'static str, i: usize, b: u8, } let new_case = |x, i, b| Case { x, i, b }; let bitset_test_vector = vec![ new_case("0", 0, 0), new_case("0", 200, 0), new_case("1", 0, 1), new_case("1", 1, 0), new_case("-1", 0, 1), new_case("-1", 200, 1), new_case("0x2000000000000000000000000000", 108, 0), new_case("0x2000000000000000000000000000", 109, 1), new_case("0x2000000000000000000000000000", 110, 0), new_case("-0x2000000000000000000000000001", 108, 1), new_case("-0x2000000000000000000000000001", 109, 0), new_case("-0x2000000000000000000000000001", 110, 1), ]; for c in BITWISE_TESTS.iter() { let x = int_from_str(c.x, None); test_bitset(&x); let y = int_from_str(c.y, None); test_bitset(&y); } for (i, c) in bitset_test_vector.iter().enumerate() { let x = int_from_str(c.x, None); assert_eq!(x.bit(c.i), c.b, "#{i} x={x}"); } } #[test] fn bits() { let test_vector = vec![ vec![0u32], vec![1], vec![0, 1, 2, 3, 4], vec![4, 3, 2, 1, 0], vec![4, 3, 2, 1, 0, 0, 0, 0], ]; for c in test_vector { let mut z = Int::default(); let got = z.set_bits(c.as_slice()); assert!(got.sign() >= 0, "set_bits({c:?}): get negative result"); let want = norm(c.as_slice()); let got: Vec<u32> = got.bits().collect(); assert_eq!(got, want, "set_bits({c:?})"); let bits: Vec<u32> = z.bits().collect(); assert_eq!( bits, want, "{:?}.bits() = {:?}; want {:?}", z.bytes(), bits, want ); } } #[test] fn bitwise() { let mut x = Int::default(); let mut y = Int::default(); for c in BITWISE_TESTS.iter() { x.set_string(c.x, 0) .expect(&format!("x.set_string({}, 0)", c.x)); y.set_string(c.y, 0) .expect(&format!("y.set_string({}, 0)", c.y)); test_bit_fun("and", Int::and, &x, &y, c.and); test_bit_fun("and_not", Int::and_not, &x, &y, c.and_not); test_bit_fun("or", Int::or, &x, &y, c.or); test_bit_fun("xor", Int::xor, &x, &y, c.xor); } } #[test] fn bytes() { let n = randn(128, 256); for _ in 0..n { let b = rand_bytes(randn(1, 64)); check_bytes(b.as_slice()); } // zero check_bytes(&[]); } #[test] fn cmp_abs() { let mut values = Vec::with_capacity(CMP_ABS_TESTS.len()); let mut prev = None::<Int>; for s in CMP_ABS_TESTS.iter() { let mut x = Int::default(); x.set_string(*s, 0).expect(&format!("set_string({s}, 0)")); if let Some(v) = prev { assert!( v.cmp(&x) < 0, "CMP_ABS_TESTS entries not sorted in ascending order" ); } values.push(x.clone()); prev = Some(x); } fn negate(x: &mut Int) { let mut v = Int::default(); v.neg(&x); *x = v; } for (i, x) in values.as_slice().iter().enumerate() { for (j, y) in values.as_slice().iter().enumerate() { for k in 0..4 { let mut a = x.clone(); let mut b = y.clone(); if (k & 1) != 0 { negate(&mut a); } if (k & 2) != 0 { negate(&mut b); } let got = a.cmp_abs(&b); let want = if i > j { 1 } else if i < j { -1 } else { 0 }; assert_eq!(got, want, "cmp_abs |{a}|, |{b}|"); } } } } #[test] fn division_signs() { struct Case { x: i64, y: i64, q: i64, r: i64, d: i64, m: i64, } let new_case = |x, y, q, r, d, m| Case { x, y, q, r, d, m }; let test_vector = vec![ new_case(5, 3, 1, 2, 1, 2), new_case(-5, 3, -1, -2, -2, 1), new_case(5, -3, -1, 2, -1, 2), new_case(-5, -3, 1, -2, 2, 1), new_case(1, 2, 0, 1, 0, 1), new_case(8, 4, 2, 0, 2, 0), ]; for (i, c) in test_vector.iter().enumerate() { let x = Int::new(c.x); let y = Int::new(c.y); let q = Int::new(c.q); let r = Int::new(c.r); let d = Int::new(c.d); let m = Int::new(c.m); let mut q1 = Int::default(); q1.quo(&x, &y); let mut r1 = Int::default(); r1.rem(&x, &y); assert!(is_normalized(&q1), "#{i} quo: {q1} is not normalized"); assert!(is_normalized(&r1), "#{i} rem: {r1} is not normalized"); assert!( (q1 == q) && (r1 == r), "#{i} quo/rem: got ({q1}, {r1}), want ({q}, {r})" ); let mut q2 = Int::default(); let mut r2 = Int::default(); q2.quo_rem(&x, &y, &mut r2); assert!(is_normalized(&q2), "#{i} quo: {q2} is not normalized"); assert!(is_normalized(&r2), "#{i} rem: {r2} is not normalized"); assert!( (q2 == q) && (r2 == r), "#{i} quo_rem: got ({q2}, {r2}), want ({q}, {r})" ); let mut d1 = Int::default(); let mut m1 = Int::default(); d1.div(&x, &y); m1.r#mod(&x, &y); assert!(is_normalized(&d1), "#{i} div: {d1} is not normalized"); assert!(is_normalized(&m1), "#{i} mod: {m1} is not normalized"); assert!( (d1 == d) && (m1 == m), "#{i} div/mod: got ({d1}, {m1}), want ({d}, {m})" ); let mut d2 = Int::default(); let mut m2 = Int::default(); d2.div_mod(&x, &y, &mut m2); assert!(is_normalized(&d2), "#{i} div: {d2} is not normalized"); assert!(is_normalized(&m2), "#{i} mod: {m2} is not normalized"); assert!( (d2 == d) && (m2 == m), "#{i} div_mod: got ({d2}, {m2}), want ({d}, {m})" ); } } #[test] fn exp() { struct Case { x: &'static str, y: &'static str, m: &'static str, out: &'static str, } let new_case = |x, y, m, out| Case { x, y, m, out }; let test_vector = vec![ // y <= 0 new_case("0", "0", "", "1"), new_case("1", "0", "", "1"), new_case("-10", "0", "", "1"), new_case("1234", "-1", "", "1"), new_case("1234", "-1", "0", "1"), new_case("17", "-100", "1234", "865"), new_case("2", "-100", "1234", ""), // m == 1 new_case("0", "0", "1", "0"), new_case("1", "0", "1", "0"), new_case("-10", "0", "1", "0"), new_case("1234", "-1", "1", "0"), // misc new_case("5", "1", "3", "2"), new_case("5", "-7", "", "1"), new_case("-5", "-7", "", "1"), new_case("5", "0", "", "1"), new_case("-5", "0", "", "1"), new_case("5", "1", "", "5"), new_case("-5", "1", "", "-5"), new_case("-5", "1", "7", "2"), new_case("-2", "3", "2", "0"), new_case("5", "2", "", "25"), new_case("1", "65537", "2", "1"), new_case("0x8000000000000000", "2", "", "0x40000000000000000000000000000000"), new_case("0x8000000000000000", "2", "6719", "4944"), new_case("0x8000000000000000", "3", "6719", "5447"), new_case("0x8000000000000000", "1000", "6719", "1603"), new_case("0x8000000000000000", "1000000", "6719", "3199"), new_case("0x8000000000000000", "-1000000", "6719", "3663"), // 3663 = ModInverse(3199, 6719) Issue #25865 new_case("0xffffffffffffffffffffffffffffffff", "0x12345678123456781234567812345678123456789", "0x01112222333344445555666677778889", "0x36168FA1DB3AAE6C8CE647E137F97A"), new_case( "2938462938472983472983659726349017249287491026512746239764525612965293865296239471239874193284792387498274256129746192347", "298472983472983471903246121093472394872319615612417471234712061", "29834729834729834729347290846729561262544958723956495615629569234729836259263598127342374289365912465901365498236492183464", "23537740700184054162508175125554701713153216681790245129157191391322321508055833908509185839069455749219131480588829346291", ), // test case for issue 8822 new_case( "11001289118363089646017359372117963499250546375269047542777928006103246876688756735760905680604646624353196869572752623285140408755420374049317646428185270079555372763503115646054602867593662923894140940837479507194934267532831694565516466765025434902348314525627418515646588160955862839022051353653052947073136084780742729727874803457643848197499548297570026926927502505634297079527299004267769780768565695459945235586892627059178884998772989397505061206395455591503771677500931269477503508150175717121828518985901959919560700853226255420793148986854391552859459511723547532575574664944815966793196961286234040892865", "0xB08FFB20760FFED58FADA86DFEF71AD72AA0FA763219618FE022C197E54708BB1191C66470250FCE8879487507CEE41381CA4D932F81C2B3F1AB20B539D50DCD", "0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73", "21484252197776302499639938883777710321993113097987201050501182909581359357618579566746556372589385361683610524730509041328855066514963385522570894839035884713051640171474186548713546686476761306436434146475140156284389181808675016576845833340494848283681088886584219750554408060556769486628029028720727393293111678826356480455433909233520504112074401376133077150471237549474149190242010469539006449596611576612573955754349042329130631128234637924786466585703488460540228477440853493392086251021228087076124706778899179648655221663765993962724699135217212118535057766739392069738618682722216712319320435674779146070442", ), new_case( "-0x1BCE04427D8032319A89E5C4136456671AC620883F2C4139E57F91307C485AD2D6204F4F87A58262652DB5DBBAC72B0613E51B835E7153BEC6068F5C8D696B74DBD18FEC316AEF73985CF0475663208EB46B4F17DD9DA55367B03323E5491A70997B90C059FB34809E6EE55BCFBD5F2F52233BFE62E6AA9E4E26A1D4C2439883D14F2633D55D8AA66A1ACD5595E778AC3A280517F1157989E70C1A437B849F1877B779CC3CDDEDE2DAA6594A6C66D181A00A5F777EE60596D8773998F6E988DEAE4CCA60E4DDCF9590543C89F74F603259FCAD71660D30294FBBE6490300F78A9D63FA660DC9417B8B9DDA28BEB3977B621B988E23D4D954F322C3540541BC649ABD504C50FADFD9F0987D58A2BF689313A285E773FF02899A6EF887D1D4A0D2", "0xB08FFB20760FFED58FADA86DFEF71AD72AA0FA763219618FE022C197E54708BB1191C66470250FCE8879487507CEE41381CA4D932F81C2B3F1AB20B539D50DCD", "0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73", "21484252197776302499639938883777710321993113097987201050501182909581359357618579566746556372589385361683610524730509041328855066514963385522570894839035884713051640171474186548713546686476761306436434146475140156284389181808675016576845833340494848283681088886584219750554408060556769486628029028720727393293111678826356480455433909233520504112074401376133077150471237549474149190242010469539006449596611576612573955754349042329130631128234637924786466585703488460540228477440853493392086251021228087076124706778899179648655221663765993962724699135217212118535057766739392069738618682722216712319320435674779146070442", ), // test cases for issue 13907 new_case("0xffffffff00000001", "0xffffffff00000001", "0xffffffff00000001", "0"), new_case("0xffffffffffffffff00000001", "0xffffffffffffffff00000001", "0xffffffffffffffff00000001", "0"), new_case("0xffffffffffffffffffffffff00000001", "0xffffffffffffffffffffffff00000001", "0xffffffffffffffffffffffff00000001", "0"), new_case("0xffffffffffffffffffffffffffffffff00000001", "0xffffffffffffffffffffffffffffffff00000001", "0xffffffffffffffffffffffffffffffff00000001", "0"), new_case( "2", "0xB08FFB20760FFED58FADA86DFEF71AD72AA0FA763219618FE022C197E54708BB1191C66470250FCE8879487507CEE41381CA4D932F81C2B3F1AB20B539D50DCD", "0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73", // odd "0x6AADD3E3E424D5B713FCAA8D8945B1E055166132038C57BBD2D51C833F0C5EA2007A2324CE514F8E8C2F008A2F36F44005A4039CB55830986F734C93DAF0EB4BAB54A6A8C7081864F44346E9BC6F0A3EB9F2C0146A00C6A05187D0C101E1F2D038CDB70CB5E9E05A2D188AB6CBB46286624D4415E7D4DBFAD3BCC6009D915C406EED38F468B940F41E6BEDC0430DD78E6F19A7DA3A27498A4181E24D738B0072D8F6ADB8C9809A5B033A09785814FD9919F6EF9F83EEA519BEC593855C4C10CBEEC582D4AE0792158823B0275E6AEC35242740468FAF3D5C60FD1E376362B6322F78B7ED0CA1C5BBCD2B49734A56C0967A1D01A100932C837B91D592CE08ABFF", ), new_case( "2", "0xB08FFB20760FFED58FADA86DFEF71AD72AA0FA763219618FE022C197E54708BB1191C66470250FCE8879487507CEE41381CA4D932F81C2B3F1AB20B539D50DCD", "0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF72", // even "0x7858794B5897C29F4ED0B40913416AB6C48588484E6A45F2ED3E26C941D878E923575AAC434EE2750E6439A6976F9BB4D64CEDB2A53CE8D04DD48CADCDF8E46F22747C6B81C6CEA86C0D873FBF7CEF262BAAC43A522BD7F32F3CDAC52B9337C77B3DCFB3DB3EDD80476331E82F4B1DF8EFDC1220C92656DFC9197BDC1877804E28D928A2A284B8DED506CBA304435C9D0133C246C98A7D890D1DE60CBC53A024361DA83A9B8775019083D22AC6820ED7C3C68F8E801DD4EC779EE0A05C6EB682EF9840D285B838369BA7E148FA27691D524FAEAF7C6ECE2A4B99A294B9F2C241857B5B90CC8BFFCFCF18DFA7D676131D5CD3855A5A3E8EBFA0CDFADB4D198B4A", ), ]; let from_decimal_string = |s: &str| { if s.is_empty() { return Ok(None); } let mut out = Int::default(); match out.set_string(s, 0) { Some(_) => Ok(Some(out)), None => Err(None::<Int>), } }; for (i, c) in test_vector.iter().enumerate() { let x = from_decimal_string(c.x) .expect(&format!("x.set_string({})", c.x)) .expect("unwrap x"); let y = from_decimal_string(c.y) .expect(&format!("y.set_string({})", c.y)) .expect("unwrap y"); let m = from_decimal_string(c.m).expect("parse m"); let out = from_decimal_string(c.out).expect("parse out"); let mut z1 = Int::default(); let zz = z1.exp(&x, &y, m.as_ref()); match &zz { Some(v) => assert!(is_normalized(*v), "#{i}: {v} is not normalized"), _ => {} } match &zz { None if out.is_none() => {} Some(v) if out.is_some() && (v.cmp(out.as_ref().unwrap()) == 0) => {} _ => panic!("#{i}: got {zz:?}, want {out:?}"), } if m.is_none() { let m = Int::default(); let mut z2 = Int::default(); z2.exp(&x, &y, Some(&m)); assert_eq!(z2, z1, "#{i}"); } } } #[test] fn fill_bytes() { fn check_result(ctx: &str, buf: &[u8], want: &Int) { let mut w = Int::default(); w.abs(want); let mut got = Int::default(); got.set_bytes(buf); assert_eq!(got, w, "{ctx}"); } let test_vector = vec![ "0", "1000", "0xffffffff", "-0xffffffff", "0xffffffffffffffff", "0x10000000000000000", "0xabababababababababababababababababababababababababa", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", ]; for n in test_vector { let x = int_from_str(n, Some(0)); // Perfectly sized buffer. let byte_len = (x.bit_len() + 7) / 8; let mut buf = vec![0u8; byte_len]; check_result(&format!("n={n}"), x.fill_bytes(&mut buf), &x); // Way larger, checking all bytes get zeroed. let mut buf = [0xffu8; 100]; check_result( &format!("check bytes zeroed for n={n}"), x.fill_bytes(&mut buf), &x, ); // Too small if byte_len > 0 { std::panic::catch_unwind(|| { let mut buf = vec![0u8; byte_len - 1]; x.fill_bytes(&mut buf); }) .expect_err(&format!("expected panic for small buffer and value {x}")); } } } #[test] fn gcd() { struct Case { d: &'static str, x: &'static str, y: &'static str, a: &'static str, b: &'static str, } let new_case = |d, x, y, a, b| Case { d, x, y, a, b }; let test_vector = vec![ // a <= 0 || b <= 0 new_case("0", "0", "0", "0", "0"), new_case("7", "0", "1", "0", "7"), new_case("7", "0", "-1", "0", "-7"), new_case("11", "1", "0", "11", "0"), new_case("7", "-1", "-2", "-77", "35"), new_case("935", "-3", "8", "64515", "24310"), new_case("935", "-3", "-8", "64515", "-24310"), new_case("935", "3", "-8", "-64515", "-24310"), new_case("1", "-9", "47", "120", "23"), new_case("7", "1", "-2", "77", "35"), new_case("935", "-3", "8", "64515", "24310"), new_case( "935000000000000000", "-3", "8", "64515000000000000000", "24310000000000000000", ), new_case( "1", "-221", "22059940471369027483332068679400581064239780177629666810348940098015901108344", "98920366548084643601728869055592650835572950932266967461790948584315647051443", "991", ), ]; fn must_from_decimal_str(s: &str) -> Int { let mut out = Int::default(); out.set_string(s, 0).expect(&format!("Int from {s}")); out } for c in test_vector { let d = must_from_decimal_str(c.d); let x = must_from_decimal_str(c.x); let y = must_from_decimal_str(c.y); let a = must_from_decimal_str(c.a); let b = must_from_decimal_str(c.b); test_gcd(&d, None, None, &a, &b); test_gcd(&d, Some(&x), None, &a, &b); test_gcd(&d, None, Some(&y), &a, &b); test_gcd(&d, Some(&x), Some(&y), &a, &b); } let n = randn(128, 256); for _ in 0..n { let a = rand_bytes(randn(1, 64)); let b = rand_bytes(randn(1, 64)); check_gcd(a.as_slice(), b.as_slice()); } } #[test] fn int64() { let test_vector = vec![ // int64 "0", "1", "-1", "4294967295", "-4294967295", "4294967296", "-4294967296", "9223372036854775807", "-9223372036854775807", "-9223372036854775808", // not int64 "0x8000000000000000", "-0x8000000000000001", "38579843757496759476987459679745", "-38579843757496759476987459679745", ]; for s in test_vector { let mut x = Int::default(); x.set_string(s, 0).expect(&format!("set_string({s}, 0)")); let want = match strconv::parse_int(s, 0, 64) { Err(err) => { match err.err { NumErrorCause::OutOfRangeSigned { .. } => { assert!(!x.is_int64(), "is_int64({x}) succeeded unexpectedly") } _ => panic!("parse_int({s}) failed"), } continue; } Ok(v) => v, }; assert!(x.is_int64(), "is_int64({x}) failed unexpectedly"); assert_eq!(x.int64(), want, "int64({s})"); } } #[test] fn int_cmp_self() { for s in CMP_ABS_TESTS.iter() { let mut x = Int::default(); x.set_string(s, 0).expect(&format!("set_string({s}, 0)")); let got = x.cmp(&x); assert_eq!(got, 0, "x = {x}: x.cmp(x)"); } } // ref: https://github.com/golang/go/issues/22830 #[test] fn golang_issue_22830() { let one = Int::new(1); let base = int_from_str("84555555300000000000", Some(10)); let m = int_from_str("66666670001111111111", Some(10)); let want = int_from_str("17888885298888888889", Some(10)); for n in [0, 1, -1] { let mut got = Int::new(n); got.exp(&base, &one, Some(&m)); assert_eq!(got, want, "({n}).exp({base}, 1, {m})"); } } #[test] fn jacobi() { struct Case { x: i64, y: i64, result: i32, } fn new_case(x: i64, y: i64, result: i32) -> Case { Case { x, y, result } } let test_vector = vec![ new_case(0, 1, 1), new_case(0, -1, 1), new_case(1, 1, 1), new_case(1, -1, 1), new_case(0, 5, 0), new_case(1, 5, 1), new_case(2, 5, -1), new_case(-2, 5, -1), new_case(2, -5, -1), new_case(-2, -5, 1), new_case(3, 5, -1), new_case(5, 5, 0), new_case(-5, 5, 0), new_case(6, 5, 1), new_case(6, -5, 1), new_case(-6, 5, 1), new_case(-6, -5, -1), ]; let mut x = Int::default(); let mut y = Int::default(); for (i, c) in test_vector.iter().enumerate() { x.set_int64(c.x); y.set_int64(c.y); assert_eq!( big::jacobi(&x, &y), c.result, "#{i} jacobi({}, {})", c.x, c.y ); } struct StringCase { x: &'static str, y: &'static str, result: i32, } fn new_string_case(x: &'static str, y: &'static str, result: i32) -> StringCase { StringCase { x, y, result } } let test_vector = vec![new_string_case( "-9285308306346108245", "13756265695458089029", 1, )]; for (i, c) in test_vector.iter().enumerate() { x.set_string(c.x, 10); y.set_string(c.y, 10); assert_eq!( big::jacobi(&x, &y), c.result, "#{i} string jacobi({}, {})", c.x, c.y ); } } #[test] fn jacobi_panic() { std::panic::catch_unwind(|| { let x = Int::new(1); let y = Int::new(2); let _ = big::jacobi(&x, &y); }) .expect_err("miss error"); } #[test] fn lsh() { for (i, c) in LSH_TESTS.iter().enumerate() { let input = int_from_decimal_str(c.input); let expected = int_from_decimal_str(c.out); let mut out = Int::default(); out.lsh(&input, c.shift); assert!(is_normalized(&out), "#{i}: {out} is not normalized"); assert_eq!(out, expected, "#{i}"); } } #[test] fn lsh_rsh() { for (i, c) in RSH_TESTS.iter().enumerate() { let input = int_from_decimal_str(c.input); let mut out = Int::default(); out.lsh(&input, c.shift); out.rsh(&out.clone(), c.shift); assert!( is_normalized(&out), "#{i} rsh test vector: {out} is not normalized" ); assert_eq!(out, input, "#{i} rsh test vector"); } for (i, c) in LSH_TESTS.iter().enumerate() { let input = int_from_decimal_str(c.input); let mut out = Int::default(); out.lsh(&input, c.shift); out.rsh(&out.clone(), c.shift); assert!( is_normalized(&out), "#{i} lsh test vector: {out} is not normalized" ); assert_eq!(out, input, "#{i} lsh test vector"); } } #[test] fn mod_inverse() { struct Case { element: &'static str, modulus: &'static str, } let new_case = |element, modulus| Case { element, modulus }; let test_vector = vec![ new_case("1234567", "458948883992"), new_case("239487239847", "2410312426921032588552076022197566074856950548502459942654116941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919"), new_case("-10", "13"), // issue #16984 new_case("10", "-13"), new_case("-17", "-13"), ]; let mut element = Int::default(); let mut modulus = Int::default(); //let mut gcd = Int::default(); let mut inverse = Int::default(); let one = Int::new(1); for c in test_vector { element.set_string(c.element, 10); modulus.set_string(c.modulus, 10); inverse.mod_inverse(&element, &modulus); let inv = inverse.clone(); inverse.mul(&inv, &element); let inv = inverse.clone(); inverse.r#mod(&inv, &modulus); assert_eq!( inverse, one, "mod_inverse({element},{modulus})*{element}%{modulus}={inverse}, not 1" ); } } #[test] fn mod_sqrt() { let mut elt = Int::default(); let mut m = Int::default(); let mut modx4 = Int::default(); let mut sq = Int::default(); let mut sqrt = Int::default(); let mut r = helper::rand::Reader::new(9); for (i, s) in PRIMES.iter().enumerate().skip(1) { m.set_string(s, 10); modx4.lsh(&m, 2); for _ in 1..5 { elt.rand(&mut r, &modx4); //if elt.to_string() != "9775475957825047973" { // continue; //} //println!("-----------------------------"); //println!("elt0 = {elt}"); //println!(" mod = {m}"); //println!("modx4 = {modx4}"); elt.sub(&elt.clone(), &m); //println!("elt = {elt}"); assert!( test_mod_sqrt(&elt, &m, &mut sq, &mut sqrt), "#{i}: failed (sqrt(e) = {sqrt})" ); } } // todo: exhaustive test for small values } #[test] fn mul() { let n = randn(128, 256); for _ in 0..n { let a = rand_bytes(randn(1, 64)); let b = rand_bytes(randn(1, 64)); assert!( check_mul(a.as_slice(), b.as_slice()), "a={:?}, b={:?}", a, b ); } } #[test] fn mul_range_z() { struct S<T> { a: T, b: T, prod: &'static str, } impl<T> S<T> { fn new(a: T, b: T, prod: &'static str) -> Self { Self { a, b, prod } } } let e9 = 10i64.pow(9); let e9u = 10u64.pow(9); let mul_ranges_n = vec![ S::new(0u64, 0, "0"), S::new(1, 1, "1"), S::new(1, 2, "2"), S::new(1, 3, "6"), S::new(10, 10, "10"), S::new(0, 100, "0"), S::new(0, e9u, "0"), S::new(1, 0, "1"), // empty range S::new(100, 1, "1"), // empty range S::new(1, 10, "3628800"), // 10! S::new(1, 20, "2432902008176640000"), // 20! S::new( 1, 100, concat!( "933262154439441526816992388562667004907159682643816214685929", "638952175999932299156089414639761565182862536979208272237582", "51185210916864000000000000000000000000" ), ), // 100! ]; let mul_ranges_z = vec![ // entirely positive ranges are covered by mulRangesN S::new(-1, 1, "0"), S::new(-2, -1, "2"), S::new(-3, -2, "6"), S::new(-3, -1, "-6"), S::new(1, 3, "6"), S::new(-10, -10, "-10"), S::new(0, -1, "1"), // empty range S::new(-1, -100, "1"), // empty range S::new(-1, 1, "0"), // range includes 0 S::new(-1 * e9, 0, "0"), // range includes 0 S::new(-1 * e9, e9, "0"), // range includes 0 S::new(-10, -1, "3628800"), // 10! S::new(-20, -2, "-2432902008176640000"), // -20! S::new( -99, -1, concat!( "-933262154439441526816992388562667004907159682643816214685929", "638952175999932299156089414639761565182862536979208272237582", "511852109168640000000000000000000000" ), // -99! ), ]; let mut tmp = Int::default(); for (i, r) in mul_ranges_n.iter().enumerate() { let prod = tmp.mul_range(r.a as i64, r.b as i64).string(); assert_eq!(&prod, r.prod, "{i}"); } for (i, r) in mul_ranges_z.iter().enumerate() { let prod = tmp.mul_range(r.a as i64, r.b as i64).string(); assert_eq!(&prod, r.prod, "{i}"); } } #[test] fn not() { struct Case { input: &'static str, output: &'static str, } fn new_case(input: &'static str, output: &'static str) -> Case { Case { input, output } } let test_vector = vec![ new_case("0", "-1"), new_case("1", "-2"), new_case("7", "-8"), new_case("0", "-1"), new_case("-81910", "81909"), new_case( "298472983472983471903246121093472394872319615612417471234712061", "-298472983472983471903246121093472394872319615612417471234712062", ), ]; let mut input = Int::default(); let mut output = Int::default(); let mut expected = Int::default(); for (i, c) in test_vector.iter().enumerate() { input.set_string(c.input, 10); expected.set_string(c.output, 10); output.not(&input); assert_eq!(output, expected, "#{i} 1st not"); output.not(&output.clone()); assert_eq!(output, input, "#{i} 2nd not"); } } #[test] fn prod_zz() { fn mul_zz<'a>(z: &'a mut Int, x: &Int, y: &Int) -> &'a mut Int { z.mul(x, y) } for a in PROD_ZZ.iter() { test_fun_zz("mul_zz", mul_zz, a); let arg = ArgZz::new(a.z.clone(), a.y.clone(), a.x.clone()); test_fun_zz("mul_zz symmetric", mul_zz, &arg); } } #[test] fn quo() { let n = randn(128, 256); for _ in 0..n { let a = rand_bytes(randn(1, 64)); let b = rand_bytes(randn(1, 64)); check_quo(a.as_slice(), b.as_slice()); } struct Case { x: &'static str, y: &'static str, q: &'static str, r: &'static str, } let new_case = |x, y, q, r| Case { x, y, q, r }; let test_vector = vec![ new_case( "476217953993950760840509444250624797097991362735329973741718102894495832294430498335824897858659711275234906400899559094370964723884706254265559534144986498357", "9353930466774385905609975137998169297361893554149986716853295022578535724979483772383667534691121982974895531435241089241440253066816724367338287092081996", "50911", "1", ), new_case("11510768301994997771168", "1328165573307167369775", "8", "885443715537658812968", ), ]; fn int_from_decimal_string(s: &str) -> Int { let mut out = Int::default(); out.set_string(s, 10); out } for (i, c) in test_vector.iter().enumerate() { let x = int_from_decimal_string(c.x); let y = int_from_decimal_string(c.y); let expected_q = int_from_decimal_string(c.q); let expected_r = int_from_decimal_string(c.r); let mut r = Int::default(); let mut q = Int::default(); q.quo_rem(&x, &y, &mut r); assert!( (q == expected_q) && (r == expected_r), "#{i} got ({q},{r}) want ({expected_q}, {expected_r})" ); } } #[test] fn quo_step_d6() { let u = { let mut v = Int::default(); let abs = [0, 0, 0, 0, 1, 1 << 31, u32::MAX, u32::MAX ^ (1 << 31)]; v.set_bits(&abs); v }; let v = { let mut v = Int::default(); let abs = [5, 0, 2, 1 << 31, 0, 1 << 31]; v.set_bits(&abs); v }; let mut r = Int::default(); let mut q = Int::default(); q.quo_rem(&u, &v, &mut r); const EXPECTED_Q64: &'static str = "18446744073709551613"; const EXPECTED_R64: &'static str = "3138550867693340382088035895064302439801311770021610913807"; //const EXPECTED_Q32: &'static str = "4294967293"; //const EXPECTED_R32: &'static str = "39614081266355540837921718287"; assert_eq!(q.to_string(), EXPECTED_Q64, "bad q64"); //assert_eq!(q.to_string(), EXPECTED_Q32, "bad q32"); assert_eq!(r.to_string(), EXPECTED_R64, "bad r64"); //assert_eq!(r.to_string(), EXPECTED_R32, "bad r32"); } #[test] fn rsh() { for (i, c) in RSH_TESTS.iter().enumerate() { let input = int_from_decimal_str(c.input); let expected = int_from_decimal_str(c.out); let mut out = Int::default(); out.rsh(&input, c.shift); assert!(is_normalized(&out), "#{i}: {out} is not normalized"); assert_eq!(out, expected, "#{i}"); } } #[test] fn set_bytes() { let n = randn(128, 256); for _ in 0..n { let b = rand_bytes(randn(1, 64)); check_set_bytes(b.as_slice()); } } #[test] fn set_z() { for a in SUM_ZZ.iter() { let mut z = Int::default(); z.set(&a.z); assert!(is_normalized(&z), "{z} is not normalized"); assert!(z.cmp(&a.z) == 0, "got z={}; want {}", z, a.z); } } #[test] fn sign_z() { let zero = Int::default(); for a in SUM_ZZ.iter() { let s = a.z.sign(); let e = a.z.cmp(&zero); assert_eq!(s, e, "z = {}", a.z); } } #[test] fn sqrt() { let mut root = 0; let mut r = Int::default(); for i in 0..10000 { if (root + 1) * (root + 1) <= i { root += 1; } let n = Int::new(i); r.set_int64(-2); r.sqrt(&n); assert_eq!(r, Int::new(root), "sqrt({n})"); } fn fake(prefix: &str, s: &str, count: usize) -> String { let mut out = String::with_capacity(prefix.len() + s.len() * count); out.push_str(prefix); for _ in 0..count { out.push_str(s); } out } for i in (0..1000).step_by(10) { let n = int_from_str(&fake("1", "0", i), Some(10)); let mut r = Int::default(); r.sqrt(&n); let root = int_from_str(&fake("1", "0", i / 2), Some(10)); assert_eq!(r, root, "sqrt(1e{i})"); } } #[test] fn sum_zz() { fn add_zz<'a>(z: &'a mut Int, x: &Int, y: &Int) -> &'a mut Int { z.add(x, y) } fn sub_zz<'a>(z: &'a mut Int, x: &Int, y: &Int) -> &'a mut Int { z.sub(x, y) } for a in SUM_ZZ.iter() { let arg = a; test_fun_zz("add_zz", add_zz, arg); let arg = ArgZz::new(a.z.clone(), a.y.clone(), a.x.clone()); test_fun_zz("add_zz symmetric", add_zz, &arg); let arg = ArgZz::new(a.x.clone(), a.z.clone(), a.y.clone()); test_fun_zz("sub_zz", sub_zz, &arg); let arg = ArgZz::new(a.y.clone(), a.z.clone(), a.x.clone()); test_fun_zz("sub_zz symmetric", sub_zz, &arg); } } #[test] fn trailing_zero_bits() { struct Case { input: &'static str, output: usize, } fn new_case(input: &'static str, output: usize) -> Case { Case { input, output } } let test_vector = vec![ new_case("0", 0), new_case("1", 0), new_case("-1", 0), new_case("4", 2), new_case("-8", 3), new_case("0x4000000000000000000", 74), new_case("-0x8000000000000000000", 75), ]; for (i, c) in test_vector.iter().enumerate() { let input = int_from_str(c.input, None); let got = input.trailing_zero_bits(); assert_eq!(got, c.output, "#{i}"); } } #[test] fn uint64() { let test_vector = vec![ // uint64 "0", "1", "4294967295", "4294967296", "8589934591", "8589934592", "9223372036854775807", "9223372036854775808", "0x08000000000000000", // not uint64 "0x10000000000000000", "-0x08000000000000000", "-1", ]; for s in test_vector { let mut x = Int::default(); assert!(x.set_string(s, 0).is_some(), "set_string({s}, 0) failed"); let want = match strconv::parse_uint(s, 0, 64) { Ok(v) => v, Err(err) => { let ok = s.starts_with('-') || match err.err { NumErrorCause::OutOfRangeUnsigned { .. } => true, _ => false, }; if ok { assert!(!x.is_uint64(), "is_uint64({s}) succeed unexpectedly"); } else { panic!("parse_uint({s}) failed"); } continue; } }; assert!(x.is_uint64(), "is_uint64({s}) failed unexpectedly"); assert_eq!(x.uint64(), want, "uint64({s})"); } } // private functions fn alt_bit(x: &Int, i: usize) -> u8 { let mut z = Int::default(); z.rsh(x, i); z.and(&z.clone(), &Int::new(1)); if z.cmp(&Int::new(0)) != 0 { 1 } else { 0 } } fn alt_set_bit(z: Int, x: &Int, i: usize, b: bool) -> Int { let mut m = Int::new(1); m.lsh(&m.clone(), i); let mut z = z; if b { z.or(x, &m); } else { z.and_not(x, &m); } z } fn check_bytes(b: &[u8]) { let b = { let mut v = b; while (v.len() > 0) && (v[0] == 0) { v = &v[1..]; } v }; let mut v = Int::default(); let b2 = v.set_bytes(b).bytes(); assert_eq!(b, b2.as_slice()) } fn check_gcd(a: &[u8], b: &[u8]) { let mut x = Int::default(); let mut y = Int::default(); let mut aa = Int::default(); aa.set_bytes(a); let mut bb = Int::default(); bb.set_bytes(b); let mut d = Int::default(); d.gcd(Some(&mut x), Some(&mut y), &aa, &bb); x.mul(&x.clone(), &aa); y.mul(&y.clone(), &bb); x.add(&x.clone(), &y); assert_eq!(x, d, "check_gcd({a:?},{b:?})"); } fn check_mul(a: &[u8], b: &[u8]) -> bool { let mut x = Int::default(); let mut y = Int::default(); let mut z1 = Int::default(); x.set_bytes(a); y.set_bytes(b); z1.mul(&x, &y); let mut z2 = Int::default(); z2.set_bytes(&mul_bytes(a, b)); z1 == z2 } fn check_quo(x: &[u8], y: &[u8]) { let mut u = Int::default(); u.set_bytes(x); let mut v = Int::default(); v.set_bytes(y); let zero = Int::default(); if &v == &zero { return; } let mut r = Int::default(); let mut q = Int::default(); q.quo_rem(&u, &v, &mut r); assert!(r.cmp(&v) < 0, "remainder not less than divisor"); let uprime = { let mut out = q.clone(); out.mul(&q, &v); let vv = out.clone(); out.add(&vv, &r); out }; assert_eq!(uprime, u); } fn check_set_bytes(b: &[u8]) { let b1 = { let mut v = Int::default(); v.set_bytes(b).bytes() }; fn normalize(b: &[u8]) -> &[u8] { let mut out = b; while (out.len() > 1) && (out[0] == 0) { out = &out[1..]; } out } assert_eq!(normalize(b1.as_slice()), normalize(b)); } fn int_from_decimal_str(s: &str) -> Int { let mut out = Int::default(); out.set_string(s, 10).expect("set_string"); out } fn int_from_str(s: &str, base: Option<u8>) -> Int { let mut out = Int::default(); out.set_string(s, base.unwrap_or_default()) .expect("set_string"); out } fn mul_bytes(x: &[u8], y: &[u8]) -> Vec<u8> { let mut z = vec![0u8; x.len() + y.len()]; let mut k0 = z.len() - 1; for j in (0..y.len()).rev() { let d = y[j] as i32; if d != 0 { let mut k = k0; let mut carry = 0; for i in (0..x.len()).rev() { let t = (z[k] as i32) + (x[i] as i32) * d + carry; z[k] = t as u8; carry = t >> 8; k -= 1; } z[k] = carry as u8; } k0 -= 1; } let mut i = 0; while (i < z.len()) && (z[i] == 0) { i += 1; } let (_, b) = z.split_at(i); b.to_vec() } fn norm(x: &[u32]) -> Vec<u32> { let mut i = x.len(); while (i > 0) && (x[i - 1] == 0) { i -= 1; } x[..i].to_vec() } fn rand_bytes(n: usize) -> Vec<u8> { let mut out = vec![0u8; n]; helper::rand::read(&mut out).unwrap(); out } fn randn(lo: u64, hi: u64) -> usize { let mut b = [0u8; 8]; helper::rand::read(&mut b).unwrap(); (u64::from_be_bytes(b) % (hi - lo) + lo) as usize } fn test_bit_fun<F>(msg: &'static str, f: F, x: &Int, y: &Int, exp: &'static str) where F: for<'a> Fn(&'a mut Int, &Int, &Int) -> &'a mut Int, { let mut expected = Int::default(); expected.set_string(exp, 0); let mut got = Int::default(); let _ = f(&mut got, x, y); assert_eq!(got, expected, "{msg}"); } fn test_bitset(x: &Int) { let n = x.bit_len(); let z = x.clone(); let z1 = x.clone(); for i in 0..(n + 10) { let old = z.bit(i); let old1 = alt_bit(&z1, i); assert_eq!(old, old1, "bitset: inconsistent value for bit({z1}, {i})"); let z0 = &z; let mut z = Int::default(); z.set_bit(z0, i, true); let z1 = alt_set_bit(Int::default(), &z1, i, true); assert_ne!(z.bit(i), 0, "bitset: bit {i} of {z}"); assert_eq!(z, z1, "bitset: inconsistent value after set_bit 1"); z.set_bit(&z.clone(), i, false); let z1 = alt_set_bit(Int::default(), &z1, i, false); assert_eq!(z.bit(i), 0, "bitset: bit {i} of {z}"); assert_eq!(z, z1, "bitset: inconsistent value after set_bit 0"); let z1 = alt_set_bit(z1.clone(), &z1, i, old == 1); z.set_bit(&z.clone(), i, old == 1); assert_eq!(z, z1, "bitset: inconsistent value after set_bit old={old}"); } assert_eq!(&z, x, "bitset"); } fn test_fun_zz<F>(msg: &str, f: F, a: &ArgZz) where F: for<'a> Fn(&'a mut Int, &Int, &Int) -> &'a mut Int, { let mut z = Int::default(); f(&mut z, &a.x, &a.y); assert!(is_normalized(&z), "{msg}{z} is not normalized"); assert_eq!(z, a.z, "{msg}{a:?}"); } fn test_gcd(d: &Int, x: Option<&Int>, y: Option<&Int>, a: &Int, b: &Int) { let mut xx = if x.is_some() { Some(Int::default()) } else { None }; let mut yy = if y.is_some() { Some(Int::default()) } else { None }; let mut dd = Int::default(); dd.gcd(xx.as_mut(), yy.as_mut(), a, b); assert_eq!(&dd, d, "gcd({x:?},{y:?},{a},{b}): bad d"); assert_eq!(x, xx.as_ref(), "gcd({x:?},{y:?},{a},{b}): bad x"); assert_eq!(y, yy.as_ref(), "gcd({x:?},{y:?},{a},{b}): bad y"); } fn test_mod_sqrt(elt: &Int, m: &Int, sq: &mut Int, sqrt: &mut Int) -> bool { let mut sq_chk = Int::default(); let mut sqrt_chk = Int::default(); sq.mul(&elt, &elt); sq.r#mod(&sq.clone(), m); let z = sqrt.mod_sqrt(sq, m); assert!(z.is_some(), "mod_sqrt returned wrong value {z:?}"); sq_chk.add(&sq, m); let z = sqrt_chk .mod_sqrt(&sq_chk, m) .expect("mod_sqrt return nil after add"); assert_eq!( z, sqrt, "mod_sqrt returned inconsistent value {z} after add" ); sq_chk.sub(&sq, m); let z = sqrt_chk .mod_sqrt(&sq_chk, m) .expect("mod_sqrt return nil after sub"); assert_eq!( z, sqrt, "mod_sqrt returned inconsistent value {z} after sub" ); if sqrt.cmp(elt) == 0 { return true; } let mut sqrt_sq = Int::default(); sqrt_sq.mul(&sqrt, &sqrt); sqrt_sq.r#mod(&sqrt_sq.clone(), m); sq.cmp(&sqrt_sq) == 0 }
/** * 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 na::Vector3; #[derive(Debug)] pub struct Light { pub color: Vector3<f64>, pub pos: Vector3<f64>, pub intensity: f64, } impl Light { pub fn new(x: f64, y: f64, z: f64, color: Vector3<f64>) -> Self { let pos = Vector3::new(x, y, z); let intensity = 1.0; Light { color, pos, intensity, } } }
struct S {} fn borrow_obj() -> S { let s = S {}; s //*s } #[test] fn test_borrow() { borrow_obj(); }
pub mod uni{ pub mod section{ pub fn section_name(){ println!("This is section 4B"); } } }
#![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 IMLOperatorAttributes(pub ::windows::core::IUnknown); impl IMLOperatorAttributes { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetAttributeElementCount<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, r#type: MLOperatorAttributeType) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(r#type), &mut result__).from_abi::<u32>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetAttribute<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, r#type: MLOperatorAttributeType, elementcount: u32, elementbytesize: usize, value: *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(r#type), ::core::mem::transmute(elementcount), ::core::mem::transmute(elementbytesize), ::core::mem::transmute(value)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetStringAttributeElementLength<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, elementindex: u32) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(elementindex), &mut result__).from_abi::<u32>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetStringAttributeElement<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, elementindex: u32, attributeelementbytesize: u32, attributeelement: super::super::super::Foundation::PSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(elementindex), ::core::mem::transmute(attributeelementbytesize), ::core::mem::transmute(attributeelement)).ok() } } unsafe impl ::windows::core::Interface for IMLOperatorAttributes { type Vtable = IMLOperatorAttributes_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4b1b1759_ec40_466c_aab4_beb5347fd24c); } impl ::core::convert::From<IMLOperatorAttributes> for ::windows::core::IUnknown { fn from(value: IMLOperatorAttributes) -> Self { value.0 } } impl ::core::convert::From<&IMLOperatorAttributes> for ::windows::core::IUnknown { fn from(value: &IMLOperatorAttributes) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMLOperatorAttributes { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMLOperatorAttributes { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMLOperatorAttributes_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, r#type: MLOperatorAttributeType, elementcount: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, r#type: MLOperatorAttributeType, elementcount: u32, elementbytesize: usize, value: *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, elementindex: u32, attributeelementbytesize: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, elementindex: u32, attributeelementbytesize: u32, attributeelement: super::super::super::Foundation::PSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMLOperatorKernel(pub ::windows::core::IUnknown); impl IMLOperatorKernel { pub unsafe fn Compute<'a, Param0: ::windows::core::IntoParam<'a, IMLOperatorKernelContext>>(&self, context: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), context.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IMLOperatorKernel { type Vtable = IMLOperatorKernel_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x11c4b4a0_b467_4eaa_a1a6_b961d8d0ed79); } impl ::core::convert::From<IMLOperatorKernel> for ::windows::core::IUnknown { fn from(value: IMLOperatorKernel) -> Self { value.0 } } impl ::core::convert::From<&IMLOperatorKernel> for ::windows::core::IUnknown { fn from(value: &IMLOperatorKernel) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMLOperatorKernel { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMLOperatorKernel { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMLOperatorKernel_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, context: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMLOperatorKernelContext(pub ::windows::core::IUnknown); impl IMLOperatorKernelContext { pub unsafe fn GetInputTensor(&self, inputindex: u32) -> ::windows::core::Result<IMLOperatorTensor> { let mut result__: <IMLOperatorTensor as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(inputindex), &mut result__).from_abi::<IMLOperatorTensor>(result__) } pub unsafe fn GetOutputTensor(&self, outputindex: u32, dimensioncount: u32, dimensionsizes: *const u32) -> ::windows::core::Result<IMLOperatorTensor> { let mut result__: <IMLOperatorTensor as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(outputindex), ::core::mem::transmute(dimensioncount), ::core::mem::transmute(dimensionsizes), &mut result__).from_abi::<IMLOperatorTensor>(result__) } pub unsafe fn GetOutputTensor2(&self, outputindex: u32) -> ::windows::core::Result<IMLOperatorTensor> { let mut result__: <IMLOperatorTensor as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(outputindex), &mut result__).from_abi::<IMLOperatorTensor>(result__) } pub unsafe fn AllocateTemporaryData(&self, size: usize) -> ::windows::core::Result<::windows::core::IUnknown> { let mut result__: <::windows::core::IUnknown as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(size), &mut result__).from_abi::<::windows::core::IUnknown>(result__) } pub unsafe fn GetExecutionInterface(&self, executionobject: *mut ::core::option::Option<::windows::core::IUnknown>) { ::core::mem::transmute((::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(executionobject))) } } unsafe impl ::windows::core::Interface for IMLOperatorKernelContext { type Vtable = IMLOperatorKernelContext_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x82536a28_f022_4769_9d3f_8b278f84c0c3); } impl ::core::convert::From<IMLOperatorKernelContext> for ::windows::core::IUnknown { fn from(value: IMLOperatorKernelContext) -> Self { value.0 } } impl ::core::convert::From<&IMLOperatorKernelContext> for ::windows::core::IUnknown { fn from(value: &IMLOperatorKernelContext) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMLOperatorKernelContext { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMLOperatorKernelContext { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMLOperatorKernelContext_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, inputindex: u32, tensor: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, outputindex: u32, dimensioncount: u32, dimensionsizes: *const u32, tensor: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, outputindex: u32, tensor: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, size: usize, data: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, executionobject: *mut ::windows::core::RawPtr), ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMLOperatorKernelCreationContext(pub ::windows::core::IUnknown); impl IMLOperatorKernelCreationContext { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetAttributeElementCount<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, r#type: MLOperatorAttributeType) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(r#type), &mut result__).from_abi::<u32>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetAttribute<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, r#type: MLOperatorAttributeType, elementcount: u32, elementbytesize: usize, value: *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(r#type), ::core::mem::transmute(elementcount), ::core::mem::transmute(elementbytesize), ::core::mem::transmute(value)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetStringAttributeElementLength<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, elementindex: u32) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(elementindex), &mut result__).from_abi::<u32>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetStringAttributeElement<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, elementindex: u32, attributeelementbytesize: u32, attributeelement: super::super::super::Foundation::PSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(elementindex), ::core::mem::transmute(attributeelementbytesize), ::core::mem::transmute(attributeelement)).ok() } pub unsafe fn GetInputCount(&self) -> u32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self))) } pub unsafe fn GetOutputCount(&self) -> u32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self))) } pub unsafe fn IsInputValid(&self, inputindex: u32) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(inputindex))) } pub unsafe fn IsOutputValid(&self, outputindex: u32) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(outputindex))) } pub unsafe fn GetInputEdgeDescription(&self, inputindex: u32) -> ::windows::core::Result<MLOperatorEdgeDescription> { let mut result__: <MLOperatorEdgeDescription as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(inputindex), &mut result__).from_abi::<MLOperatorEdgeDescription>(result__) } pub unsafe fn GetOutputEdgeDescription(&self, outputindex: u32) -> ::windows::core::Result<MLOperatorEdgeDescription> { let mut result__: <MLOperatorEdgeDescription as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(outputindex), &mut result__).from_abi::<MLOperatorEdgeDescription>(result__) } pub unsafe fn HasTensorShapeDescription(&self) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self))) } pub unsafe fn GetTensorShapeDescription(&self) -> ::windows::core::Result<IMLOperatorTensorShapeDescription> { let mut result__: <IMLOperatorTensorShapeDescription as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IMLOperatorTensorShapeDescription>(result__) } pub unsafe fn GetExecutionInterface(&self, executionobject: *mut ::core::option::Option<::windows::core::IUnknown>) { ::core::mem::transmute((::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(executionobject))) } } unsafe impl ::windows::core::Interface for IMLOperatorKernelCreationContext { type Vtable = IMLOperatorKernelCreationContext_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5459b53d_a0fc_4665_addd_70171ef7e631); } impl ::core::convert::From<IMLOperatorKernelCreationContext> for ::windows::core::IUnknown { fn from(value: IMLOperatorKernelCreationContext) -> Self { value.0 } } impl ::core::convert::From<&IMLOperatorKernelCreationContext> for ::windows::core::IUnknown { fn from(value: &IMLOperatorKernelCreationContext) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMLOperatorKernelCreationContext { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMLOperatorKernelCreationContext { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IMLOperatorKernelCreationContext> for IMLOperatorAttributes { fn from(value: IMLOperatorKernelCreationContext) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IMLOperatorKernelCreationContext> for IMLOperatorAttributes { fn from(value: &IMLOperatorKernelCreationContext) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMLOperatorAttributes> for IMLOperatorKernelCreationContext { fn into_param(self) -> ::windows::core::Param<'a, IMLOperatorAttributes> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMLOperatorAttributes> for &IMLOperatorKernelCreationContext { fn into_param(self) -> ::windows::core::Param<'a, IMLOperatorAttributes> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IMLOperatorKernelCreationContext_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, r#type: MLOperatorAttributeType, elementcount: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, r#type: MLOperatorAttributeType, elementcount: u32, elementbytesize: usize, value: *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, elementindex: u32, attributeelementbytesize: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, elementindex: u32, attributeelementbytesize: u32, attributeelement: super::super::super::Foundation::PSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, 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, inputindex: u32) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, outputindex: u32) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inputindex: u32, edgedescription: *mut MLOperatorEdgeDescription) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, outputindex: u32, edgedescription: *mut MLOperatorEdgeDescription) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, shapedescription: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, executionobject: *mut ::windows::core::RawPtr), ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMLOperatorKernelFactory(pub ::windows::core::IUnknown); impl IMLOperatorKernelFactory { pub unsafe fn CreateKernel<'a, Param0: ::windows::core::IntoParam<'a, IMLOperatorKernelCreationContext>>(&self, context: Param0) -> ::windows::core::Result<IMLOperatorKernel> { let mut result__: <IMLOperatorKernel as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), context.into_param().abi(), &mut result__).from_abi::<IMLOperatorKernel>(result__) } } unsafe impl ::windows::core::Interface for IMLOperatorKernelFactory { type Vtable = IMLOperatorKernelFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xef15ad6f_0dc9_4908_ab35_a575a30dfbf8); } impl ::core::convert::From<IMLOperatorKernelFactory> for ::windows::core::IUnknown { fn from(value: IMLOperatorKernelFactory) -> Self { value.0 } } impl ::core::convert::From<&IMLOperatorKernelFactory> for ::windows::core::IUnknown { fn from(value: &IMLOperatorKernelFactory) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMLOperatorKernelFactory { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMLOperatorKernelFactory { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMLOperatorKernelFactory_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, context: ::windows::core::RawPtr, kernel: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMLOperatorRegistry(pub ::windows::core::IUnknown); impl IMLOperatorRegistry { #[cfg(feature = "Win32_Foundation")] pub unsafe fn RegisterOperatorSetSchema<'a, Param4: ::windows::core::IntoParam<'a, IMLOperatorTypeInferrer>, Param5: ::windows::core::IntoParam<'a, IMLOperatorShapeInferrer>>(&self, operatorsetid: *const MLOperatorSetId, baselineversion: i32, schema: *const *const MLOperatorSchemaDescription, schemacount: u32, typeinferrer: Param4, shapeinferrer: Param5) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(operatorsetid), ::core::mem::transmute(baselineversion), ::core::mem::transmute(schema), ::core::mem::transmute(schemacount), typeinferrer.into_param().abi(), shapeinferrer.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn RegisterOperatorKernel<'a, Param1: ::windows::core::IntoParam<'a, IMLOperatorKernelFactory>, Param2: ::windows::core::IntoParam<'a, IMLOperatorShapeInferrer>>(&self, operatorkernel: *const MLOperatorKernelDescription, operatorkernelfactory: Param1, shapeinferrer: Param2) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(operatorkernel), operatorkernelfactory.into_param().abi(), shapeinferrer.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IMLOperatorRegistry { type Vtable = IMLOperatorRegistry_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2af9dd2d_b516_4672_9ab5_530c208493ad); } impl ::core::convert::From<IMLOperatorRegistry> for ::windows::core::IUnknown { fn from(value: IMLOperatorRegistry) -> Self { value.0 } } impl ::core::convert::From<&IMLOperatorRegistry> for ::windows::core::IUnknown { fn from(value: &IMLOperatorRegistry) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMLOperatorRegistry { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMLOperatorRegistry { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMLOperatorRegistry_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, operatorsetid: *const MLOperatorSetId, baselineversion: i32, schema: *const *const MLOperatorSchemaDescription, schemacount: u32, typeinferrer: ::windows::core::RawPtr, shapeinferrer: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, operatorkernel: *const MLOperatorKernelDescription, operatorkernelfactory: ::windows::core::RawPtr, shapeinferrer: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMLOperatorShapeInferenceContext(pub ::windows::core::IUnknown); impl IMLOperatorShapeInferenceContext { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetAttributeElementCount<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, r#type: MLOperatorAttributeType) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(r#type), &mut result__).from_abi::<u32>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetAttribute<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, r#type: MLOperatorAttributeType, elementcount: u32, elementbytesize: usize, value: *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(r#type), ::core::mem::transmute(elementcount), ::core::mem::transmute(elementbytesize), ::core::mem::transmute(value)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetStringAttributeElementLength<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, elementindex: u32) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(elementindex), &mut result__).from_abi::<u32>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetStringAttributeElement<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, elementindex: u32, attributeelementbytesize: u32, attributeelement: super::super::super::Foundation::PSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(elementindex), ::core::mem::transmute(attributeelementbytesize), ::core::mem::transmute(attributeelement)).ok() } pub unsafe fn GetInputCount(&self) -> u32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self))) } pub unsafe fn GetOutputCount(&self) -> u32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self))) } pub unsafe fn IsInputValid(&self, inputindex: u32) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(inputindex))) } pub unsafe fn IsOutputValid(&self, outputindex: u32) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(outputindex))) } pub unsafe fn GetInputEdgeDescription(&self, inputindex: u32) -> ::windows::core::Result<MLOperatorEdgeDescription> { let mut result__: <MLOperatorEdgeDescription as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(inputindex), &mut result__).from_abi::<MLOperatorEdgeDescription>(result__) } pub unsafe fn GetInputTensorDimensionCount(&self, inputindex: u32) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(inputindex), &mut result__).from_abi::<u32>(result__) } pub unsafe fn GetInputTensorShape(&self, inputindex: u32, dimensioncount: u32, dimensions: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(inputindex), ::core::mem::transmute(dimensioncount), ::core::mem::transmute(dimensions)).ok() } pub unsafe fn SetOutputTensorShape(&self, outputindex: u32, dimensioncount: u32, dimensions: *const u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(outputindex), ::core::mem::transmute(dimensioncount), ::core::mem::transmute(dimensions)).ok() } } unsafe impl ::windows::core::Interface for IMLOperatorShapeInferenceContext { type Vtable = IMLOperatorShapeInferenceContext_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x105b6b29_5408_4a68_9959_09b5955a3492); } impl ::core::convert::From<IMLOperatorShapeInferenceContext> for ::windows::core::IUnknown { fn from(value: IMLOperatorShapeInferenceContext) -> Self { value.0 } } impl ::core::convert::From<&IMLOperatorShapeInferenceContext> for ::windows::core::IUnknown { fn from(value: &IMLOperatorShapeInferenceContext) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMLOperatorShapeInferenceContext { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMLOperatorShapeInferenceContext { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IMLOperatorShapeInferenceContext> for IMLOperatorAttributes { fn from(value: IMLOperatorShapeInferenceContext) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IMLOperatorShapeInferenceContext> for IMLOperatorAttributes { fn from(value: &IMLOperatorShapeInferenceContext) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMLOperatorAttributes> for IMLOperatorShapeInferenceContext { fn into_param(self) -> ::windows::core::Param<'a, IMLOperatorAttributes> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMLOperatorAttributes> for &IMLOperatorShapeInferenceContext { fn into_param(self) -> ::windows::core::Param<'a, IMLOperatorAttributes> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IMLOperatorShapeInferenceContext_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, r#type: MLOperatorAttributeType, elementcount: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, r#type: MLOperatorAttributeType, elementcount: u32, elementbytesize: usize, value: *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, elementindex: u32, attributeelementbytesize: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, elementindex: u32, attributeelementbytesize: u32, attributeelement: super::super::super::Foundation::PSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, 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, inputindex: u32) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, outputindex: u32) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inputindex: u32, edgedescription: *mut MLOperatorEdgeDescription) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inputindex: u32, dimensioncount: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inputindex: u32, dimensioncount: u32, dimensions: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, outputindex: u32, dimensioncount: u32, dimensions: *const u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMLOperatorShapeInferrer(pub ::windows::core::IUnknown); impl IMLOperatorShapeInferrer { pub unsafe fn InferOutputShapes<'a, Param0: ::windows::core::IntoParam<'a, IMLOperatorShapeInferenceContext>>(&self, context: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), context.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IMLOperatorShapeInferrer { type Vtable = IMLOperatorShapeInferrer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x540be5be_a6c9_40ee_83f6_d2b8b40a7798); } impl ::core::convert::From<IMLOperatorShapeInferrer> for ::windows::core::IUnknown { fn from(value: IMLOperatorShapeInferrer) -> Self { value.0 } } impl ::core::convert::From<&IMLOperatorShapeInferrer> for ::windows::core::IUnknown { fn from(value: &IMLOperatorShapeInferrer) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMLOperatorShapeInferrer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMLOperatorShapeInferrer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMLOperatorShapeInferrer_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, context: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMLOperatorTensor(pub ::windows::core::IUnknown); impl IMLOperatorTensor { pub unsafe fn GetDimensionCount(&self) -> u32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self))) } pub unsafe fn GetShape(&self, dimensioncount: u32, dimensions: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(dimensioncount), ::core::mem::transmute(dimensions)).ok() } pub unsafe fn GetTensorDataType(&self) -> MLOperatorTensorDataType { ::core::mem::transmute((::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self))) } pub unsafe fn IsCpuData(&self) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self))) } pub unsafe fn IsDataInterface(&self) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self))) } pub unsafe fn GetData(&self) -> *mut ::core::ffi::c_void { ::core::mem::transmute((::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self))) } pub unsafe fn GetDataInterface(&self, datainterface: *mut ::core::option::Option<::windows::core::IUnknown>) { ::core::mem::transmute((::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(datainterface))) } } unsafe impl ::windows::core::Interface for IMLOperatorTensor { type Vtable = IMLOperatorTensor_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7fe41f41_f430_440e_aece_54416dc8b9db); } impl ::core::convert::From<IMLOperatorTensor> for ::windows::core::IUnknown { fn from(value: IMLOperatorTensor) -> Self { value.0 } } impl ::core::convert::From<&IMLOperatorTensor> for ::windows::core::IUnknown { fn from(value: &IMLOperatorTensor) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMLOperatorTensor { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMLOperatorTensor { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMLOperatorTensor_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) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dimensioncount: u32, dimensions: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> MLOperatorTensorDataType, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> *mut ::core::ffi::c_void, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, datainterface: *mut ::windows::core::RawPtr), ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMLOperatorTensorShapeDescription(pub ::windows::core::IUnknown); impl IMLOperatorTensorShapeDescription { pub unsafe fn GetInputTensorDimensionCount(&self, inputindex: u32) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(inputindex), &mut result__).from_abi::<u32>(result__) } pub unsafe fn GetInputTensorShape(&self, inputindex: u32, dimensioncount: u32, dimensions: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(inputindex), ::core::mem::transmute(dimensioncount), ::core::mem::transmute(dimensions)).ok() } pub unsafe fn HasOutputShapeDescription(&self) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self))) } pub unsafe fn GetOutputTensorDimensionCount(&self, outputindex: u32) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(outputindex), &mut result__).from_abi::<u32>(result__) } pub unsafe fn GetOutputTensorShape(&self, outputindex: u32, dimensioncount: u32, dimensions: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(outputindex), ::core::mem::transmute(dimensioncount), ::core::mem::transmute(dimensions)).ok() } } unsafe impl ::windows::core::Interface for IMLOperatorTensorShapeDescription { type Vtable = IMLOperatorTensorShapeDescription_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf20e8cbe_3b28_4248_be95_f96fbc6e4643); } impl ::core::convert::From<IMLOperatorTensorShapeDescription> for ::windows::core::IUnknown { fn from(value: IMLOperatorTensorShapeDescription) -> Self { value.0 } } impl ::core::convert::From<&IMLOperatorTensorShapeDescription> for ::windows::core::IUnknown { fn from(value: &IMLOperatorTensorShapeDescription) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMLOperatorTensorShapeDescription { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMLOperatorTensorShapeDescription { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMLOperatorTensorShapeDescription_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, inputindex: u32, dimensioncount: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inputindex: u32, dimensioncount: u32, dimensions: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, outputindex: u32, dimensioncount: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, outputindex: u32, dimensioncount: u32, dimensions: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMLOperatorTypeInferenceContext(pub ::windows::core::IUnknown); impl IMLOperatorTypeInferenceContext { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetAttributeElementCount<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, r#type: MLOperatorAttributeType) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(r#type), &mut result__).from_abi::<u32>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetAttribute<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, r#type: MLOperatorAttributeType, elementcount: u32, elementbytesize: usize, value: *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(r#type), ::core::mem::transmute(elementcount), ::core::mem::transmute(elementbytesize), ::core::mem::transmute(value)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetStringAttributeElementLength<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, elementindex: u32) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(elementindex), &mut result__).from_abi::<u32>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetStringAttributeElement<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PSTR>>(&self, name: Param0, elementindex: u32, attributeelementbytesize: u32, attributeelement: super::super::super::Foundation::PSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), name.into_param().abi(), ::core::mem::transmute(elementindex), ::core::mem::transmute(attributeelementbytesize), ::core::mem::transmute(attributeelement)).ok() } pub unsafe fn GetInputCount(&self) -> u32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self))) } pub unsafe fn GetOutputCount(&self) -> u32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self))) } pub unsafe fn IsInputValid(&self, inputindex: u32) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(inputindex))) } pub unsafe fn IsOutputValid(&self, outputindex: u32) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(outputindex))) } pub unsafe fn GetInputEdgeDescription(&self, inputindex: u32) -> ::windows::core::Result<MLOperatorEdgeDescription> { let mut result__: <MLOperatorEdgeDescription as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(inputindex), &mut result__).from_abi::<MLOperatorEdgeDescription>(result__) } pub unsafe fn SetOutputEdgeDescription(&self, outputindex: u32, edgedescription: *const MLOperatorEdgeDescription) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(outputindex), ::core::mem::transmute(edgedescription)).ok() } } unsafe impl ::windows::core::Interface for IMLOperatorTypeInferenceContext { type Vtable = IMLOperatorTypeInferenceContext_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xec893bb1_f938_427b_8488_c8dcf775f138); } impl ::core::convert::From<IMLOperatorTypeInferenceContext> for ::windows::core::IUnknown { fn from(value: IMLOperatorTypeInferenceContext) -> Self { value.0 } } impl ::core::convert::From<&IMLOperatorTypeInferenceContext> for ::windows::core::IUnknown { fn from(value: &IMLOperatorTypeInferenceContext) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMLOperatorTypeInferenceContext { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMLOperatorTypeInferenceContext { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IMLOperatorTypeInferenceContext> for IMLOperatorAttributes { fn from(value: IMLOperatorTypeInferenceContext) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IMLOperatorTypeInferenceContext> for IMLOperatorAttributes { fn from(value: &IMLOperatorTypeInferenceContext) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IMLOperatorAttributes> for IMLOperatorTypeInferenceContext { fn into_param(self) -> ::windows::core::Param<'a, IMLOperatorAttributes> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IMLOperatorAttributes> for &IMLOperatorTypeInferenceContext { fn into_param(self) -> ::windows::core::Param<'a, IMLOperatorAttributes> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IMLOperatorTypeInferenceContext_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, r#type: MLOperatorAttributeType, elementcount: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, r#type: MLOperatorAttributeType, elementcount: u32, elementbytesize: usize, value: *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, elementindex: u32, attributeelementbytesize: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PSTR, elementindex: u32, attributeelementbytesize: u32, attributeelement: super::super::super::Foundation::PSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, 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, inputindex: u32) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, outputindex: u32) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inputindex: u32, edgedescription: *mut MLOperatorEdgeDescription) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, outputindex: u32, edgedescription: *const MLOperatorEdgeDescription) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IMLOperatorTypeInferrer(pub ::windows::core::IUnknown); impl IMLOperatorTypeInferrer { pub unsafe fn InferOutputTypes<'a, Param0: ::windows::core::IntoParam<'a, IMLOperatorTypeInferenceContext>>(&self, context: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), context.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IMLOperatorTypeInferrer { type Vtable = IMLOperatorTypeInferrer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x781aeb48_9bcb_4797_bf77_8bf455217beb); } impl ::core::convert::From<IMLOperatorTypeInferrer> for ::windows::core::IUnknown { fn from(value: IMLOperatorTypeInferrer) -> Self { value.0 } } impl ::core::convert::From<&IMLOperatorTypeInferrer> for ::windows::core::IUnknown { fn from(value: &IMLOperatorTypeInferrer) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMLOperatorTypeInferrer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMLOperatorTypeInferrer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IMLOperatorTypeInferrer_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, context: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWinMLEvaluationContext(pub ::windows::core::IUnknown); impl IWinMLEvaluationContext { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] pub unsafe fn BindValue(&self, pdescriptor: *const WINML_BINDING_DESC) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pdescriptor)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] pub unsafe fn GetValueByName<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>>(&self, name: Param0) -> ::windows::core::Result<*mut WINML_BINDING_DESC> { let mut result__: <*mut WINML_BINDING_DESC as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), name.into_param().abi(), &mut result__).from_abi::<*mut WINML_BINDING_DESC>(result__) } pub unsafe fn Clear(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok() } } unsafe impl ::windows::core::Interface for IWinMLEvaluationContext { type Vtable = IWinMLEvaluationContext_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x95848f9e_583d_4054_af12_916387cd8426); } impl ::core::convert::From<IWinMLEvaluationContext> for ::windows::core::IUnknown { fn from(value: IWinMLEvaluationContext) -> Self { value.0 } } impl ::core::convert::From<&IWinMLEvaluationContext> for ::windows::core::IUnknown { fn from(value: &IWinMLEvaluationContext) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWinMLEvaluationContext { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IWinMLEvaluationContext { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWinMLEvaluationContext_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdescriptor: *const ::core::mem::ManuallyDrop<WINML_BINDING_DESC>) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: super::super::super::Foundation::PWSTR, pdescriptor: *mut *mut WINML_BINDING_DESC) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWinMLModel(pub ::windows::core::IUnknown); impl IWinMLModel { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetDescription(&self) -> ::windows::core::Result<*mut WINML_MODEL_DESC> { let mut result__: <*mut WINML_MODEL_DESC as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<*mut WINML_MODEL_DESC>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn EnumerateMetadata(&self, index: u32, pkey: *mut super::super::super::Foundation::PWSTR, pvalue: *mut super::super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(index), ::core::mem::transmute(pkey), ::core::mem::transmute(pvalue)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn EnumerateModelInputs(&self, index: u32) -> ::windows::core::Result<*mut WINML_VARIABLE_DESC> { let mut result__: <*mut WINML_VARIABLE_DESC as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(index), &mut result__).from_abi::<*mut WINML_VARIABLE_DESC>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn EnumerateModelOutputs(&self, index: u32) -> ::windows::core::Result<*mut WINML_VARIABLE_DESC> { let mut result__: <*mut WINML_VARIABLE_DESC as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(index), &mut result__).from_abi::<*mut WINML_VARIABLE_DESC>(result__) } } unsafe impl ::windows::core::Interface for IWinMLModel { type Vtable = IWinMLModel_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe2eeb6a9_f31f_4055_a521_e30b5b33664a); } impl ::core::convert::From<IWinMLModel> for ::windows::core::IUnknown { fn from(value: IWinMLModel) -> Self { value.0 } } impl ::core::convert::From<&IWinMLModel> for ::windows::core::IUnknown { fn from(value: &IWinMLModel) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWinMLModel { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IWinMLModel { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWinMLModel_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppdescription: *mut *mut WINML_MODEL_DESC) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, index: u32, pkey: *mut super::super::super::Foundation::PWSTR, pvalue: *mut super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, index: u32, ppinputdescriptor: *mut *mut WINML_VARIABLE_DESC) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, index: u32, ppoutputdescriptor: *mut *mut WINML_VARIABLE_DESC) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWinMLRuntime(pub ::windows::core::IUnknown); impl IWinMLRuntime { #[cfg(feature = "Win32_Foundation")] pub unsafe fn LoadModel<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>>(&self, path: Param0) -> ::windows::core::Result<IWinMLModel> { let mut result__: <IWinMLModel as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), path.into_param().abi(), &mut result__).from_abi::<IWinMLModel>(result__) } #[cfg(feature = "Win32_Graphics_Direct3D12")] pub unsafe fn CreateEvaluationContext<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Graphics::Direct3D12::ID3D12Device>>(&self, device: Param0) -> ::windows::core::Result<IWinMLEvaluationContext> { let mut result__: <IWinMLEvaluationContext as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), device.into_param().abi(), &mut result__).from_abi::<IWinMLEvaluationContext>(result__) } pub unsafe fn EvaluateModel<'a, Param0: ::windows::core::IntoParam<'a, IWinMLEvaluationContext>>(&self, pcontext: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), pcontext.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IWinMLRuntime { type Vtable = IWinMLRuntime_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa0425329_40ae_48d9_bce3_829ef7b8a41a); } impl ::core::convert::From<IWinMLRuntime> for ::windows::core::IUnknown { fn from(value: IWinMLRuntime) -> Self { value.0 } } impl ::core::convert::From<&IWinMLRuntime> for ::windows::core::IUnknown { fn from(value: &IWinMLRuntime) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWinMLRuntime { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IWinMLRuntime { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWinMLRuntime_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, path: super::super::super::Foundation::PWSTR, ppmodel: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Graphics_Direct3D12")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, device: ::windows::core::RawPtr, ppcontext: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Graphics_Direct3D12"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcontext: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWinMLRuntimeFactory(pub ::windows::core::IUnknown); impl IWinMLRuntimeFactory { pub unsafe fn CreateRuntime(&self, runtimetype: WINML_RUNTIME_TYPE) -> ::windows::core::Result<IWinMLRuntime> { let mut result__: <IWinMLRuntime as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(runtimetype), &mut result__).from_abi::<IWinMLRuntime>(result__) } } unsafe impl ::windows::core::Interface for IWinMLRuntimeFactory { type Vtable = IWinMLRuntimeFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa807b84d_4ae5_4bc0_a76a_941aa246bd41); } impl ::core::convert::From<IWinMLRuntimeFactory> for ::windows::core::IUnknown { fn from(value: IWinMLRuntimeFactory) -> Self { value.0 } } impl ::core::convert::From<&IWinMLRuntimeFactory> for ::windows::core::IUnknown { fn from(value: &IWinMLRuntimeFactory) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWinMLRuntimeFactory { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IWinMLRuntimeFactory { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWinMLRuntimeFactory_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, runtimetype: WINML_RUNTIME_TYPE, ppruntime: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[inline] pub unsafe fn MLCreateOperatorRegistry() -> ::windows::core::Result<IMLOperatorRegistry> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn MLCreateOperatorRegistry(registry: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT; } let mut result__: <IMLOperatorRegistry as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); MLCreateOperatorRegistry(&mut result__).from_abi::<IMLOperatorRegistry>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct MLOperatorAttribute { pub name: super::super::super::Foundation::PSTR, pub r#type: MLOperatorAttributeType, pub required: bool, } #[cfg(feature = "Win32_Foundation")] impl MLOperatorAttribute {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for MLOperatorAttribute { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for MLOperatorAttribute { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MLOperatorAttribute").field("name", &self.name).field("r#type", &self.r#type).field("required", &self.required).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for MLOperatorAttribute { fn eq(&self, other: &Self) -> bool { self.name == other.name && self.r#type == other.r#type && self.required == other.required } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for MLOperatorAttribute {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for MLOperatorAttribute { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct MLOperatorAttributeNameValue { pub name: super::super::super::Foundation::PSTR, pub r#type: MLOperatorAttributeType, pub valueCount: u32, pub Anonymous: MLOperatorAttributeNameValue_0, } #[cfg(feature = "Win32_Foundation")] impl MLOperatorAttributeNameValue {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for MLOperatorAttributeNameValue { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for MLOperatorAttributeNameValue { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for MLOperatorAttributeNameValue {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for MLOperatorAttributeNameValue { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union MLOperatorAttributeNameValue_0 { pub reserved: *mut ::core::ffi::c_void, pub ints: *mut i64, pub strings: *mut *mut i8, pub floats: *mut f32, } #[cfg(feature = "Win32_Foundation")] impl MLOperatorAttributeNameValue_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for MLOperatorAttributeNameValue_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for MLOperatorAttributeNameValue_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for MLOperatorAttributeNameValue_0 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for MLOperatorAttributeNameValue_0 { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MLOperatorAttributeType(pub u32); impl MLOperatorAttributeType { pub const Undefined: MLOperatorAttributeType = MLOperatorAttributeType(0u32); pub const Float: MLOperatorAttributeType = MLOperatorAttributeType(2u32); pub const Int: MLOperatorAttributeType = MLOperatorAttributeType(3u32); pub const String: MLOperatorAttributeType = MLOperatorAttributeType(4u32); pub const FloatArray: MLOperatorAttributeType = MLOperatorAttributeType(7u32); pub const IntArray: MLOperatorAttributeType = MLOperatorAttributeType(8u32); pub const StringArray: MLOperatorAttributeType = MLOperatorAttributeType(9u32); } impl ::core::convert::From<u32> for MLOperatorAttributeType { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MLOperatorAttributeType { type Abi = Self; } impl ::core::ops::BitOr for MLOperatorAttributeType { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for MLOperatorAttributeType { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for MLOperatorAttributeType { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for MLOperatorAttributeType { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for MLOperatorAttributeType { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct MLOperatorEdgeDescription { pub edgeType: MLOperatorEdgeType, pub Anonymous: MLOperatorEdgeDescription_0, } impl MLOperatorEdgeDescription {} impl ::core::default::Default for MLOperatorEdgeDescription { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for MLOperatorEdgeDescription { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for MLOperatorEdgeDescription {} unsafe impl ::windows::core::Abi for MLOperatorEdgeDescription { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub union MLOperatorEdgeDescription_0 { pub reserved: u64, pub tensorDataType: MLOperatorTensorDataType, } impl MLOperatorEdgeDescription_0 {} impl ::core::default::Default for MLOperatorEdgeDescription_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for MLOperatorEdgeDescription_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for MLOperatorEdgeDescription_0 {} unsafe impl ::windows::core::Abi for MLOperatorEdgeDescription_0 { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MLOperatorEdgeType(pub u32); impl MLOperatorEdgeType { pub const Undefined: MLOperatorEdgeType = MLOperatorEdgeType(0u32); pub const Tensor: MLOperatorEdgeType = MLOperatorEdgeType(1u32); } impl ::core::convert::From<u32> for MLOperatorEdgeType { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MLOperatorEdgeType { type Abi = Self; } impl ::core::ops::BitOr for MLOperatorEdgeType { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for MLOperatorEdgeType { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for MLOperatorEdgeType { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for MLOperatorEdgeType { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for MLOperatorEdgeType { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct MLOperatorEdgeTypeConstraint { pub typeLabel: super::super::super::Foundation::PSTR, pub allowedTypes: *mut MLOperatorEdgeDescription, pub allowedTypeCount: u32, } #[cfg(feature = "Win32_Foundation")] impl MLOperatorEdgeTypeConstraint {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for MLOperatorEdgeTypeConstraint { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for MLOperatorEdgeTypeConstraint { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MLOperatorEdgeTypeConstraint").field("typeLabel", &self.typeLabel).field("allowedTypes", &self.allowedTypes).field("allowedTypeCount", &self.allowedTypeCount).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for MLOperatorEdgeTypeConstraint { fn eq(&self, other: &Self) -> bool { self.typeLabel == other.typeLabel && self.allowedTypes == other.allowedTypes && self.allowedTypeCount == other.allowedTypeCount } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for MLOperatorEdgeTypeConstraint {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for MLOperatorEdgeTypeConstraint { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MLOperatorExecutionType(pub u32); impl MLOperatorExecutionType { pub const Undefined: MLOperatorExecutionType = MLOperatorExecutionType(0u32); pub const Cpu: MLOperatorExecutionType = MLOperatorExecutionType(1u32); pub const D3D12: MLOperatorExecutionType = MLOperatorExecutionType(2u32); } impl ::core::convert::From<u32> for MLOperatorExecutionType { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MLOperatorExecutionType { type Abi = Self; } impl ::core::ops::BitOr for MLOperatorExecutionType { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for MLOperatorExecutionType { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for MLOperatorExecutionType { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for MLOperatorExecutionType { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for MLOperatorExecutionType { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct MLOperatorKernelDescription { pub domain: super::super::super::Foundation::PSTR, pub name: super::super::super::Foundation::PSTR, pub minimumOperatorSetVersion: i32, pub executionType: MLOperatorExecutionType, pub typeConstraints: *mut MLOperatorEdgeTypeConstraint, pub typeConstraintCount: u32, pub defaultAttributes: *mut MLOperatorAttributeNameValue, pub defaultAttributeCount: u32, pub options: MLOperatorKernelOptions, pub executionOptions: u32, } #[cfg(feature = "Win32_Foundation")] impl MLOperatorKernelDescription {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for MLOperatorKernelDescription { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for MLOperatorKernelDescription { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MLOperatorKernelDescription") .field("domain", &self.domain) .field("name", &self.name) .field("minimumOperatorSetVersion", &self.minimumOperatorSetVersion) .field("executionType", &self.executionType) .field("typeConstraints", &self.typeConstraints) .field("typeConstraintCount", &self.typeConstraintCount) .field("defaultAttributes", &self.defaultAttributes) .field("defaultAttributeCount", &self.defaultAttributeCount) .field("options", &self.options) .field("executionOptions", &self.executionOptions) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for MLOperatorKernelDescription { fn eq(&self, other: &Self) -> bool { self.domain == other.domain && self.name == other.name && self.minimumOperatorSetVersion == other.minimumOperatorSetVersion && self.executionType == other.executionType && self.typeConstraints == other.typeConstraints && self.typeConstraintCount == other.typeConstraintCount && self.defaultAttributes == other.defaultAttributes && self.defaultAttributeCount == other.defaultAttributeCount && self.options == other.options && self.executionOptions == other.executionOptions } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for MLOperatorKernelDescription {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for MLOperatorKernelDescription { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MLOperatorKernelOptions(pub u32); impl MLOperatorKernelOptions { pub const None: MLOperatorKernelOptions = MLOperatorKernelOptions(0u32); pub const AllowDynamicInputShapes: MLOperatorKernelOptions = MLOperatorKernelOptions(1u32); } impl ::core::convert::From<u32> for MLOperatorKernelOptions { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MLOperatorKernelOptions { type Abi = Self; } impl ::core::ops::BitOr for MLOperatorKernelOptions { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for MLOperatorKernelOptions { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for MLOperatorKernelOptions { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for MLOperatorKernelOptions { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for MLOperatorKernelOptions { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MLOperatorParameterOptions(pub u32); impl MLOperatorParameterOptions { pub const Single: MLOperatorParameterOptions = MLOperatorParameterOptions(0u32); pub const Optional: MLOperatorParameterOptions = MLOperatorParameterOptions(1u32); pub const Variadic: MLOperatorParameterOptions = MLOperatorParameterOptions(2u32); } impl ::core::convert::From<u32> for MLOperatorParameterOptions { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MLOperatorParameterOptions { type Abi = Self; } impl ::core::ops::BitOr for MLOperatorParameterOptions { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for MLOperatorParameterOptions { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for MLOperatorParameterOptions { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for MLOperatorParameterOptions { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for MLOperatorParameterOptions { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct MLOperatorSchemaDescription { pub name: super::super::super::Foundation::PSTR, pub operatorSetVersionAtLastChange: i32, pub inputs: *mut MLOperatorSchemaEdgeDescription, pub inputCount: u32, pub outputs: *mut MLOperatorSchemaEdgeDescription, pub outputCount: u32, pub typeConstraints: *mut MLOperatorEdgeTypeConstraint, pub typeConstraintCount: u32, pub attributes: *mut MLOperatorAttribute, pub attributeCount: u32, pub defaultAttributes: *mut MLOperatorAttributeNameValue, pub defaultAttributeCount: u32, } #[cfg(feature = "Win32_Foundation")] impl MLOperatorSchemaDescription {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for MLOperatorSchemaDescription { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for MLOperatorSchemaDescription { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MLOperatorSchemaDescription") .field("name", &self.name) .field("operatorSetVersionAtLastChange", &self.operatorSetVersionAtLastChange) .field("inputs", &self.inputs) .field("inputCount", &self.inputCount) .field("outputs", &self.outputs) .field("outputCount", &self.outputCount) .field("typeConstraints", &self.typeConstraints) .field("typeConstraintCount", &self.typeConstraintCount) .field("attributes", &self.attributes) .field("attributeCount", &self.attributeCount) .field("defaultAttributes", &self.defaultAttributes) .field("defaultAttributeCount", &self.defaultAttributeCount) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for MLOperatorSchemaDescription { fn eq(&self, other: &Self) -> bool { self.name == other.name && self.operatorSetVersionAtLastChange == other.operatorSetVersionAtLastChange && self.inputs == other.inputs && self.inputCount == other.inputCount && self.outputs == other.outputs && self.outputCount == other.outputCount && self.typeConstraints == other.typeConstraints && self.typeConstraintCount == other.typeConstraintCount && self.attributes == other.attributes && self.attributeCount == other.attributeCount && self.defaultAttributes == other.defaultAttributes && self.defaultAttributeCount == other.defaultAttributeCount } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for MLOperatorSchemaDescription {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for MLOperatorSchemaDescription { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct MLOperatorSchemaEdgeDescription { pub options: MLOperatorParameterOptions, pub typeFormat: MLOperatorSchemaEdgeTypeFormat, pub Anonymous: MLOperatorSchemaEdgeDescription_0, } #[cfg(feature = "Win32_Foundation")] impl MLOperatorSchemaEdgeDescription {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for MLOperatorSchemaEdgeDescription { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for MLOperatorSchemaEdgeDescription { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for MLOperatorSchemaEdgeDescription {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for MLOperatorSchemaEdgeDescription { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union MLOperatorSchemaEdgeDescription_0 { pub reserved: *mut ::core::ffi::c_void, pub typeLabel: super::super::super::Foundation::PSTR, pub edgeDescription: MLOperatorEdgeDescription, } #[cfg(feature = "Win32_Foundation")] impl MLOperatorSchemaEdgeDescription_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for MLOperatorSchemaEdgeDescription_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for MLOperatorSchemaEdgeDescription_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for MLOperatorSchemaEdgeDescription_0 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for MLOperatorSchemaEdgeDescription_0 { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MLOperatorSchemaEdgeTypeFormat(pub i32); impl MLOperatorSchemaEdgeTypeFormat { pub const EdgeDescription: MLOperatorSchemaEdgeTypeFormat = MLOperatorSchemaEdgeTypeFormat(0i32); pub const Label: MLOperatorSchemaEdgeTypeFormat = MLOperatorSchemaEdgeTypeFormat(1i32); } impl ::core::convert::From<i32> for MLOperatorSchemaEdgeTypeFormat { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MLOperatorSchemaEdgeTypeFormat { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct MLOperatorSetId { pub domain: super::super::super::Foundation::PSTR, pub version: i32, } #[cfg(feature = "Win32_Foundation")] impl MLOperatorSetId {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for MLOperatorSetId { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for MLOperatorSetId { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MLOperatorSetId").field("domain", &self.domain).field("version", &self.version).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for MLOperatorSetId { fn eq(&self, other: &Self) -> bool { self.domain == other.domain && self.version == other.version } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for MLOperatorSetId {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for MLOperatorSetId { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MLOperatorTensorDataType(pub u32); impl MLOperatorTensorDataType { pub const Undefined: MLOperatorTensorDataType = MLOperatorTensorDataType(0u32); pub const Float: MLOperatorTensorDataType = MLOperatorTensorDataType(1u32); pub const UInt8: MLOperatorTensorDataType = MLOperatorTensorDataType(2u32); pub const Int8: MLOperatorTensorDataType = MLOperatorTensorDataType(3u32); pub const UInt16: MLOperatorTensorDataType = MLOperatorTensorDataType(4u32); pub const Int16: MLOperatorTensorDataType = MLOperatorTensorDataType(5u32); pub const Int32: MLOperatorTensorDataType = MLOperatorTensorDataType(6u32); pub const Int64: MLOperatorTensorDataType = MLOperatorTensorDataType(7u32); pub const String: MLOperatorTensorDataType = MLOperatorTensorDataType(8u32); pub const Bool: MLOperatorTensorDataType = MLOperatorTensorDataType(9u32); pub const Float16: MLOperatorTensorDataType = MLOperatorTensorDataType(10u32); pub const Double: MLOperatorTensorDataType = MLOperatorTensorDataType(11u32); pub const UInt32: MLOperatorTensorDataType = MLOperatorTensorDataType(12u32); pub const UInt64: MLOperatorTensorDataType = MLOperatorTensorDataType(13u32); pub const Complex64: MLOperatorTensorDataType = MLOperatorTensorDataType(14u32); pub const Complex128: MLOperatorTensorDataType = MLOperatorTensorDataType(15u32); } impl ::core::convert::From<u32> for MLOperatorTensorDataType { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MLOperatorTensorDataType { type Abi = Self; } impl ::core::ops::BitOr for MLOperatorTensorDataType { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for MLOperatorTensorDataType { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for MLOperatorTensorDataType { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for MLOperatorTensorDataType { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for MLOperatorTensorDataType { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] impl ::core::clone::Clone for WINML_BINDING_DESC { fn clone(&self) -> Self { unimplemented!() } } #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] pub struct WINML_BINDING_DESC { pub Name: super::super::super::Foundation::PWSTR, pub BindType: WINML_BINDING_TYPE, pub Anonymous: WINML_BINDING_DESC_0, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] impl WINML_BINDING_DESC {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] impl ::core::default::Default for WINML_BINDING_DESC { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] impl ::core::cmp::PartialEq for WINML_BINDING_DESC { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] impl ::core::cmp::Eq for WINML_BINDING_DESC {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] unsafe impl ::windows::core::Abi for WINML_BINDING_DESC { type Abi = ::core::mem::ManuallyDrop<Self>; } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] impl ::core::clone::Clone for WINML_BINDING_DESC_0 { fn clone(&self) -> Self { unimplemented!() } } #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] pub union WINML_BINDING_DESC_0 { pub Tensor: WINML_TENSOR_BINDING_DESC, pub Sequence: WINML_SEQUENCE_BINDING_DESC, pub Map: WINML_MAP_BINDING_DESC, pub Image: WINML_IMAGE_BINDING_DESC, pub Resource: ::core::mem::ManuallyDrop<WINML_RESOURCE_BINDING_DESC>, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] impl WINML_BINDING_DESC_0 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] impl ::core::default::Default for WINML_BINDING_DESC_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] impl ::core::cmp::PartialEq for WINML_BINDING_DESC_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] impl ::core::cmp::Eq for WINML_BINDING_DESC_0 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct3D12"))] unsafe impl ::windows::core::Abi for WINML_BINDING_DESC_0 { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct WINML_BINDING_TYPE(pub i32); pub const WINML_BINDING_UNDEFINED: WINML_BINDING_TYPE = WINML_BINDING_TYPE(0i32); pub const WINML_BINDING_TENSOR: WINML_BINDING_TYPE = WINML_BINDING_TYPE(1i32); pub const WINML_BINDING_SEQUENCE: WINML_BINDING_TYPE = WINML_BINDING_TYPE(2i32); pub const WINML_BINDING_MAP: WINML_BINDING_TYPE = WINML_BINDING_TYPE(3i32); pub const WINML_BINDING_IMAGE: WINML_BINDING_TYPE = WINML_BINDING_TYPE(4i32); pub const WINML_BINDING_RESOURCE: WINML_BINDING_TYPE = WINML_BINDING_TYPE(5i32); impl ::core::convert::From<i32> for WINML_BINDING_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for WINML_BINDING_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct WINML_FEATURE_TYPE(pub i32); pub const WINML_FEATURE_UNDEFINED: WINML_FEATURE_TYPE = WINML_FEATURE_TYPE(0i32); pub const WINML_FEATURE_TENSOR: WINML_FEATURE_TYPE = WINML_FEATURE_TYPE(1i32); pub const WINML_FEATURE_SEQUENCE: WINML_FEATURE_TYPE = WINML_FEATURE_TYPE(2i32); pub const WINML_FEATURE_MAP: WINML_FEATURE_TYPE = WINML_FEATURE_TYPE(3i32); pub const WINML_FEATURE_IMAGE: WINML_FEATURE_TYPE = WINML_FEATURE_TYPE(4i32); impl ::core::convert::From<i32> for WINML_FEATURE_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for WINML_FEATURE_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct WINML_IMAGE_BINDING_DESC { pub ElementType: WINML_TENSOR_DATA_TYPE, pub NumDimensions: u32, pub pShape: *mut i64, pub DataSize: u32, pub pData: *mut ::core::ffi::c_void, } impl WINML_IMAGE_BINDING_DESC {} impl ::core::default::Default for WINML_IMAGE_BINDING_DESC { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for WINML_IMAGE_BINDING_DESC { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("WINML_IMAGE_BINDING_DESC").field("ElementType", &self.ElementType).field("NumDimensions", &self.NumDimensions).field("pShape", &self.pShape).field("DataSize", &self.DataSize).field("pData", &self.pData).finish() } } impl ::core::cmp::PartialEq for WINML_IMAGE_BINDING_DESC { fn eq(&self, other: &Self) -> bool { self.ElementType == other.ElementType && self.NumDimensions == other.NumDimensions && self.pShape == other.pShape && self.DataSize == other.DataSize && self.pData == other.pData } } impl ::core::cmp::Eq for WINML_IMAGE_BINDING_DESC {} unsafe impl ::windows::core::Abi for WINML_IMAGE_BINDING_DESC { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct WINML_IMAGE_VARIABLE_DESC { pub ElementType: WINML_TENSOR_DATA_TYPE, pub NumDimensions: u32, pub pShape: *mut i64, } impl WINML_IMAGE_VARIABLE_DESC {} impl ::core::default::Default for WINML_IMAGE_VARIABLE_DESC { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for WINML_IMAGE_VARIABLE_DESC { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("WINML_IMAGE_VARIABLE_DESC").field("ElementType", &self.ElementType).field("NumDimensions", &self.NumDimensions).field("pShape", &self.pShape).finish() } } impl ::core::cmp::PartialEq for WINML_IMAGE_VARIABLE_DESC { fn eq(&self, other: &Self) -> bool { self.ElementType == other.ElementType && self.NumDimensions == other.NumDimensions && self.pShape == other.pShape } } impl ::core::cmp::Eq for WINML_IMAGE_VARIABLE_DESC {} unsafe impl ::windows::core::Abi for WINML_IMAGE_VARIABLE_DESC { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct WINML_MAP_BINDING_DESC { pub ElementCount: u32, pub KeyType: WINML_TENSOR_DATA_TYPE, pub Anonymous1: WINML_MAP_BINDING_DESC_0, pub Fields: WINML_TENSOR_DATA_TYPE, pub Anonymous2: WINML_MAP_BINDING_DESC_1, } #[cfg(feature = "Win32_Foundation")] impl WINML_MAP_BINDING_DESC {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for WINML_MAP_BINDING_DESC { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for WINML_MAP_BINDING_DESC { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for WINML_MAP_BINDING_DESC {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for WINML_MAP_BINDING_DESC { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union WINML_MAP_BINDING_DESC_0 { pub pStringKeys: *mut super::super::super::Foundation::PWSTR, pub pIntKeys: *mut i64, } #[cfg(feature = "Win32_Foundation")] impl WINML_MAP_BINDING_DESC_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for WINML_MAP_BINDING_DESC_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for WINML_MAP_BINDING_DESC_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for WINML_MAP_BINDING_DESC_0 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for WINML_MAP_BINDING_DESC_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union WINML_MAP_BINDING_DESC_1 { pub pStringFields: *mut super::super::super::Foundation::PWSTR, pub pIntFields: *mut i64, pub pFloatFields: *mut f32, pub pDoubleFields: *mut f64, } #[cfg(feature = "Win32_Foundation")] impl WINML_MAP_BINDING_DESC_1 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for WINML_MAP_BINDING_DESC_1 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for WINML_MAP_BINDING_DESC_1 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for WINML_MAP_BINDING_DESC_1 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for WINML_MAP_BINDING_DESC_1 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct WINML_MAP_VARIABLE_DESC { pub KeyType: WINML_TENSOR_DATA_TYPE, pub Fields: WINML_TENSOR_DATA_TYPE, } impl WINML_MAP_VARIABLE_DESC {} impl ::core::default::Default for WINML_MAP_VARIABLE_DESC { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for WINML_MAP_VARIABLE_DESC { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("WINML_MAP_VARIABLE_DESC").field("KeyType", &self.KeyType).field("Fields", &self.Fields).finish() } } impl ::core::cmp::PartialEq for WINML_MAP_VARIABLE_DESC { fn eq(&self, other: &Self) -> bool { self.KeyType == other.KeyType && self.Fields == other.Fields } } impl ::core::cmp::Eq for WINML_MAP_VARIABLE_DESC {} unsafe impl ::windows::core::Abi for WINML_MAP_VARIABLE_DESC { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct WINML_MODEL_DESC { pub Author: super::super::super::Foundation::PWSTR, pub Name: super::super::super::Foundation::PWSTR, pub Domain: super::super::super::Foundation::PWSTR, pub Description: super::super::super::Foundation::PWSTR, pub Version: usize, } #[cfg(feature = "Win32_Foundation")] impl WINML_MODEL_DESC {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for WINML_MODEL_DESC { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for WINML_MODEL_DESC { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("WINML_MODEL_DESC").field("Author", &self.Author).field("Name", &self.Name).field("Domain", &self.Domain).field("Description", &self.Description).field("Version", &self.Version).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for WINML_MODEL_DESC { fn eq(&self, other: &Self) -> bool { self.Author == other.Author && self.Name == other.Name && self.Domain == other.Domain && self.Description == other.Description && self.Version == other.Version } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for WINML_MODEL_DESC {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for WINML_MODEL_DESC { type Abi = Self; } #[derive(:: core :: clone :: Clone)] #[repr(C)] #[cfg(feature = "Win32_Graphics_Direct3D12")] pub struct WINML_RESOURCE_BINDING_DESC { pub ElementType: WINML_TENSOR_DATA_TYPE, pub NumDimensions: u32, pub pShape: *mut i64, pub pResource: ::core::option::Option<super::super::super::Graphics::Direct3D12::ID3D12Resource>, } #[cfg(feature = "Win32_Graphics_Direct3D12")] impl WINML_RESOURCE_BINDING_DESC {} #[cfg(feature = "Win32_Graphics_Direct3D12")] impl ::core::default::Default for WINML_RESOURCE_BINDING_DESC { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Graphics_Direct3D12")] impl ::core::fmt::Debug for WINML_RESOURCE_BINDING_DESC { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("WINML_RESOURCE_BINDING_DESC").field("ElementType", &self.ElementType).field("NumDimensions", &self.NumDimensions).field("pShape", &self.pShape).field("pResource", &self.pResource).finish() } } #[cfg(feature = "Win32_Graphics_Direct3D12")] impl ::core::cmp::PartialEq for WINML_RESOURCE_BINDING_DESC { fn eq(&self, other: &Self) -> bool { self.ElementType == other.ElementType && self.NumDimensions == other.NumDimensions && self.pShape == other.pShape && self.pResource == other.pResource } } #[cfg(feature = "Win32_Graphics_Direct3D12")] impl ::core::cmp::Eq for WINML_RESOURCE_BINDING_DESC {} #[cfg(feature = "Win32_Graphics_Direct3D12")] unsafe impl ::windows::core::Abi for WINML_RESOURCE_BINDING_DESC { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct WINML_RUNTIME_TYPE(pub i32); pub const WINML_RUNTIME_CNTK: WINML_RUNTIME_TYPE = WINML_RUNTIME_TYPE(0i32); impl ::core::convert::From<i32> for WINML_RUNTIME_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for WINML_RUNTIME_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct WINML_SEQUENCE_BINDING_DESC { pub ElementCount: u32, pub ElementType: WINML_TENSOR_DATA_TYPE, pub Anonymous: WINML_SEQUENCE_BINDING_DESC_0, } #[cfg(feature = "Win32_Foundation")] impl WINML_SEQUENCE_BINDING_DESC {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for WINML_SEQUENCE_BINDING_DESC { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for WINML_SEQUENCE_BINDING_DESC { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for WINML_SEQUENCE_BINDING_DESC {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for WINML_SEQUENCE_BINDING_DESC { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union WINML_SEQUENCE_BINDING_DESC_0 { pub pStrings: *mut super::super::super::Foundation::PWSTR, pub pInts: *mut i64, pub pFloats: *mut f32, pub pDoubles: *mut f64, } #[cfg(feature = "Win32_Foundation")] impl WINML_SEQUENCE_BINDING_DESC_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for WINML_SEQUENCE_BINDING_DESC_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for WINML_SEQUENCE_BINDING_DESC_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for WINML_SEQUENCE_BINDING_DESC_0 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for WINML_SEQUENCE_BINDING_DESC_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct WINML_SEQUENCE_VARIABLE_DESC { pub ElementType: WINML_TENSOR_DATA_TYPE, } impl WINML_SEQUENCE_VARIABLE_DESC {} impl ::core::default::Default for WINML_SEQUENCE_VARIABLE_DESC { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for WINML_SEQUENCE_VARIABLE_DESC { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("WINML_SEQUENCE_VARIABLE_DESC").field("ElementType", &self.ElementType).finish() } } impl ::core::cmp::PartialEq for WINML_SEQUENCE_VARIABLE_DESC { fn eq(&self, other: &Self) -> bool { self.ElementType == other.ElementType } } impl ::core::cmp::Eq for WINML_SEQUENCE_VARIABLE_DESC {} unsafe impl ::windows::core::Abi for WINML_SEQUENCE_VARIABLE_DESC { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct WINML_TENSOR_BINDING_DESC { pub DataType: WINML_TENSOR_DATA_TYPE, pub NumDimensions: u32, pub pShape: *mut i64, pub DataSize: u32, pub pData: *mut ::core::ffi::c_void, } impl WINML_TENSOR_BINDING_DESC {} impl ::core::default::Default for WINML_TENSOR_BINDING_DESC { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for WINML_TENSOR_BINDING_DESC { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("WINML_TENSOR_BINDING_DESC").field("DataType", &self.DataType).field("NumDimensions", &self.NumDimensions).field("pShape", &self.pShape).field("DataSize", &self.DataSize).field("pData", &self.pData).finish() } } impl ::core::cmp::PartialEq for WINML_TENSOR_BINDING_DESC { fn eq(&self, other: &Self) -> bool { self.DataType == other.DataType && self.NumDimensions == other.NumDimensions && self.pShape == other.pShape && self.DataSize == other.DataSize && self.pData == other.pData } } impl ::core::cmp::Eq for WINML_TENSOR_BINDING_DESC {} unsafe impl ::windows::core::Abi for WINML_TENSOR_BINDING_DESC { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct WINML_TENSOR_DATA_TYPE(pub i32); pub const WINML_TENSOR_UNDEFINED: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(0i32); pub const WINML_TENSOR_FLOAT: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(1i32); pub const WINML_TENSOR_UINT8: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(2i32); pub const WINML_TENSOR_INT8: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(3i32); pub const WINML_TENSOR_UINT16: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(4i32); pub const WINML_TENSOR_INT16: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(5i32); pub const WINML_TENSOR_INT32: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(6i32); pub const WINML_TENSOR_INT64: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(7i32); pub const WINML_TENSOR_STRING: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(8i32); pub const WINML_TENSOR_BOOLEAN: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(9i32); pub const WINML_TENSOR_FLOAT16: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(10i32); pub const WINML_TENSOR_DOUBLE: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(11i32); pub const WINML_TENSOR_UINT32: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(12i32); pub const WINML_TENSOR_UINT64: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(13i32); pub const WINML_TENSOR_COMPLEX64: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(14i32); pub const WINML_TENSOR_COMPLEX128: WINML_TENSOR_DATA_TYPE = WINML_TENSOR_DATA_TYPE(15i32); impl ::core::convert::From<i32> for WINML_TENSOR_DATA_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for WINML_TENSOR_DATA_TYPE { type Abi = Self; } pub const WINML_TENSOR_DIMENSION_COUNT_MAX: u32 = 4u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct WINML_TENSOR_VARIABLE_DESC { pub ElementType: WINML_TENSOR_DATA_TYPE, pub NumDimensions: u32, pub pShape: *mut i64, } impl WINML_TENSOR_VARIABLE_DESC {} impl ::core::default::Default for WINML_TENSOR_VARIABLE_DESC { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for WINML_TENSOR_VARIABLE_DESC { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("WINML_TENSOR_VARIABLE_DESC").field("ElementType", &self.ElementType).field("NumDimensions", &self.NumDimensions).field("pShape", &self.pShape).finish() } } impl ::core::cmp::PartialEq for WINML_TENSOR_VARIABLE_DESC { fn eq(&self, other: &Self) -> bool { self.ElementType == other.ElementType && self.NumDimensions == other.NumDimensions && self.pShape == other.pShape } } impl ::core::cmp::Eq for WINML_TENSOR_VARIABLE_DESC {} unsafe impl ::windows::core::Abi for WINML_TENSOR_VARIABLE_DESC { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct WINML_VARIABLE_DESC { pub Name: super::super::super::Foundation::PWSTR, pub Description: super::super::super::Foundation::PWSTR, pub FeatureType: WINML_FEATURE_TYPE, pub Required: super::super::super::Foundation::BOOL, pub Anonymous: WINML_VARIABLE_DESC_0, } #[cfg(feature = "Win32_Foundation")] impl WINML_VARIABLE_DESC {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for WINML_VARIABLE_DESC { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for WINML_VARIABLE_DESC { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for WINML_VARIABLE_DESC {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for WINML_VARIABLE_DESC { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union WINML_VARIABLE_DESC_0 { pub Tensor: WINML_TENSOR_VARIABLE_DESC, pub Sequence: WINML_SEQUENCE_VARIABLE_DESC, pub Map: WINML_MAP_VARIABLE_DESC, pub Image: WINML_IMAGE_VARIABLE_DESC, } #[cfg(feature = "Win32_Foundation")] impl WINML_VARIABLE_DESC_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for WINML_VARIABLE_DESC_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for WINML_VARIABLE_DESC_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for WINML_VARIABLE_DESC_0 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for WINML_VARIABLE_DESC_0 { type Abi = Self; } #[inline] pub unsafe fn WinMLCreateRuntime() -> ::windows::core::Result<IWinMLRuntime> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn WinMLCreateRuntime(runtime: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT; } let mut result__: <IWinMLRuntime as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); WinMLCreateRuntime(&mut result__).from_abi::<IWinMLRuntime>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); }
use numpy::{IntoPyArray, PyArray1}; use pyo3::prelude::{pyclass, pymethods, pymodule, Py, Python, PyObject, PyModule, PyResult}; use pyo3::type_object::PyTypeObject; use crate::camera::CameraParameters; #[pyclass] #[derive(Clone)] pub struct PyCameraParameters { pub inner: CameraParameters } #[pymethods] impl PyCameraParameters { #[new] pub fn new( _py: Python<'_>, focal_length: (f64, f64), offset: (f64, f64) ) -> Self { PyCameraParameters { inner: CameraParameters::new(focal_length, offset) } } #[getter] fn focal_length(&self, py: Python<'_>) -> Py<PyArray1<f64>> { let focal_length = self.inner.focal_length.to_owned(); focal_length.into_pyarray(py).to_owned() } #[getter] fn offset(&self, py: Python<'_>) -> Py<PyArray1<f64>> { let offset = self.inner.offset.to_owned(); offset.into_pyarray(py).to_owned() } } #[pymodule(camera)] fn mymodule(_py: Python, m: &PyModule) -> PyResult<()> { m.add("CameraParameters", <PyCameraParameters as PyTypeObject>::type_object())?; Ok(()) }
use super::*; use reqwest::Client as ReqwestClient; use std::collections::HashMap; use std::time::Duration; #[derive(Debug, Deserialize, Serialize)] pub struct Config { key: String, base_url: String, request_timeout: u64, } const DEFAULT_BASE_URL: &str = "https://console.helium.com"; const DEFAULT_TIMEOUT: u64 = 120; impl Config { pub fn new(key: String) -> Config { Self::new_with_url(key, DEFAULT_BASE_URL) } pub fn new_with_url(key: String, url: &str) -> Config { Config { key, base_url: url.to_string(), request_timeout: DEFAULT_TIMEOUT, } } } #[derive(Clone, Debug)] pub struct Client { base_url: String, key: String, client: ReqwestClient, // map label to uuid labels: HashMap<String, String>, } impl Client { pub fn new(config: Config) -> Result<Client> { let timeout = config.request_timeout; let client = ReqwestClient::builder() .timeout(Duration::from_secs(timeout)) .build()?; // verify API key let key = base64::decode(&config.key)?; if key.len() != 32 { println!("Invalid key in config file"); return Err(Error::InvalidApiKey.into()); } Ok(Client { base_url: config.base_url, key: config.key, client, labels: HashMap::new(), }) } fn get(&self, path: &str) -> Result<reqwest::RequestBuilder> { Ok(self .client .get(format!("{}/{}", self.base_url, path).as_str()) .header("key", self.key.as_str())) } fn post(&self, path: &str) -> Result<reqwest::RequestBuilder> { Ok(self .client .post(format!("{}/{}", self.base_url, path).as_str()) .header("key", self.key.as_str())) } fn delete(&self, path: &str) -> Result<reqwest::RequestBuilder> { Ok(self .client .delete(format!("{}/{}", self.base_url, path).as_str()) .header("key", self.key.as_str())) } pub async fn get_devices(&self) -> Result<Vec<Device>> { let request = self.get("api/v1/devices")?; let response = request.send().await?; if response.status() == 200 { let body = response.text().await.unwrap(); let devices: Vec<Device> = serde_json::from_str(&body)?; Ok(devices) } else if response.status() == 401 { let body = response.text().await.unwrap(); println!("{}", body); Err(Error::UnauthorizedApi.into()) } else { Err(Error::HttpErrorApi.into()) } } pub async fn get_device(&self, get_device: &GetDevice) -> Result<Device> { let request = self.get( format!( "api/v1/devices?dev_eui={}&app_eui={}&app_key={}", get_device.dev_eui(), get_device.app_eui(), get_device.app_key() ) .as_str(), )?; let response = request.send().await?; if response.status() == 200 { let body = response.text().await.unwrap(); let devices: Device = serde_json::from_str(&body)?; Ok(devices) } else if response.status() == 401 { let body = response.text().await.unwrap(); println!("{}", body); Err(Error::UnauthorizedApi.into()) } else { Err(Error::HttpErrorApi.into()) } } pub async fn get_device_by_id(&self, id: &str) -> Result<Device> { let request = self.get(format!("api/v1/devices/{}", id).as_str())?; let response = request.send().await?; if response.status() == 200 { let body = response.text().await.unwrap(); let device: Device = serde_json::from_str(&body)?; Ok(device) } else if response.status() == 401 { let body = response.text().await.unwrap(); println!("{}", body); Err(Error::UnauthorizedApi.into()) } else { Err(Error::HttpErrorApi.into()) } } pub async fn post_device(&self, new_device_request: &NewDevice) -> Result<Device> { let request = self.post("api/v1/devices")?.json(&new_device_request); let response = request.send().await?; if response.status() == 201 { let body = response.text().await?; let device: Device = serde_json::from_str(&body)?; Ok(device) } else if response.status() == 401 { let body = response.text().await.unwrap(); println!("{}", body); Err(Error::UnauthorizedApi.into()) } else if response.status() == 422 { Err(Error::NewDevice422.into()) } else { Err(Error::NewDeviceApi.into()) } } pub async fn delete_device(&self, id: &str) -> Result<()> { let request = self.delete(format!("api/v1/devices/{}", id).as_str())?; let response = request.send().await?; if response.status() == 200 { println!("Device delete successful"); let _response_body = response.text().await?; Ok(()) } else if response.status() == 401 { let body = response.text().await.unwrap(); println!("{}", body); Err(Error::UnauthorizedApi.into()) } else if response.status() == 404 { println!("Device not found. Delete failed."); Ok(()) } else { Err(Error::HttpErrorApi.into()) } } /// Labels pub async fn get_labels(&mut self) -> Result<Vec<Label>> { let request = self.get("api/v1/labels")?; let response = request.send().await?; let body = response.text().await.unwrap(); let labels: Vec<Label> = serde_json::from_str(&body)?; for label in &labels { self.labels.insert(label.name().clone(), label.id().clone()); } Ok(labels) } pub async fn post_label(&self, new_label_request: &NewLabel) -> Result<Label> { let request = self.post("api/v1/labels")?.json(&new_label_request); let response = request.send().await?; if response.status() == 201 { let body = response.text().await?; let label: Label = serde_json::from_str(&body)?; Ok(label) } else if response.status() == 422 { Err(Error::NewLabel422.into()) } else { Err(Error::NewLabelApi.into()) } } pub async fn delete_label(&self, id: &str) -> Result<()> { let request = self.delete(format!("api/v1/labels/{}", id).as_str())?; let response = request.send().await?; if response.status() == 200 { println!("Label delete successful"); } else if response.status() == 404 { println!("Label not found. Delete failed."); } let _response_body = response.text().await?; Ok(()) } /// Device Label pub async fn add_device_label( &self, device_id: String, device_label: &DeviceLabel, ) -> Result<()> { let request = self .post(format!("api/v1/devices/{:}/labels", device_id).as_str())? .json(&device_label); let response = request.send().await?; if response.status() == 201 || response.status() == 200 { let body = response.text().await?; println!("{}", body); Ok(()) } else { let body = response.text().await?; println!("{}", body); Err(Error::NewDeviceLabelApi.into()) } } pub async fn remove_device_label( &self, device_id: String, device_label: &DeviceLabel, ) -> Result<()> { let request = self.delete( format!( "api/v1/devices/{:}/labels/{:}", device_id, device_label.get_uuid() ) .as_str(), )?; let response = request.send().await?; if response.status() == 200 { let body = response.text().await?; println!("{:}", body); } else if response.status() == 404 { println!("Device label not found. Delete failed."); } Ok(()) } pub async fn get_label_uuid(&mut self, device_label: &str) -> Result<String> { let label_upper = device_label.to_uppercase(); // we probably haven't fetched labels if length is 0 if self.labels.is_empty() { self.get_labels().await?; } // if the uuid still doesn't exist even after an intial fetch // create it if !self.labels.contains_key(&label_upper) { println!("Label does not exist. Creating label: {}", label_upper); let request = NewLabel::from_string(&label_upper); let label = self.post_label(&request).await?; self.labels.insert(label.name().clone(), label.id().clone()); } // at this point, the above either errored or the label exists if let Some(id) = self.labels.get(&label_upper) { Ok(id.clone()) } else { panic!("Label should exist here. Error out.") } } }
// 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 alloc::string::ToString; use spin::Mutex; use alloc::collections::btree_map::BTreeMap; use super::super::super::super::qlib::common::*; use super::super::super::super::qlib::linux_def::*; use super::super::super::super::qlib::auth::*; use super::super::super::super::task::*; use super::super::super::attr::*; use super::super::super::file::*; use super::super::super::flags::*; use super::super::super::dirent::*; use super::super::super::mount::*; use super::super::super::inode::*; use super::super::super::ramfs::dir::*; use super::super::super::super::threadmgr::pid_namespace::*; use super::super::super::super::threadmgr::thread::*; use super::super::dir_proc::*; use super::super::proc::*; use super::super::inode::*; use super::auxvec::*; use super::exe::*; use super::exec_args::*; use super::comm::*; use super::fds::*; use super::uid_pid_map::*; use super::io::*; use super::maps::*; use super::mounts::*; use super::stat::*; use super::statm::*; use super::status::*; // taskDir represents a task-level directory. pub struct TaskDirNode { pub pidns: Option<PIDNamespace>, pub thread: Thread, } impl DirDataNode for TaskDirNode { fn Lookup(&self, d: &Dir, task: &Task, dir: &Inode, name: &str) -> Result<Dirent> { return d.Lookup(task, dir, name); } fn GetFile(&self, d: &Dir, task: &Task, dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> { return d.GetFile(task, dir, dirent, flags) } } impl ProcNode { pub fn NewTaskDir(&self, task: &Task, thread: &Thread, msrc: &Arc<Mutex<MountSource>>, showSubtasks: bool) -> Inode { let mut contents = BTreeMap::new(); contents.insert("auxv".to_string(), NewAUXVec(task, thread, msrc)); contents.insert("cmdline".to_string(), NewExecArg(task, thread, msrc, ExecArgType::CmdlineExecArg)); contents.insert("comm".to_string(), NewComm(task, thread, msrc)); contents.insert("environ".to_string(), NewExecArg(task, thread, msrc, ExecArgType::EnvironExecArg)); contents.insert("exe".to_string(), NewExe(task, thread, msrc)); contents.insert("fd".to_string(), NewFdDir(task, thread, msrc)); contents.insert("fdinfo".to_string(), NewFdInfoDir(task, thread, msrc)); contents.insert("gid_map".to_string(), NewIdMap(task, thread, msrc, true)); contents.insert("io".to_string(), NewIO(task, thread, msrc)); contents.insert("maps".to_string(), NewMaps(task, thread, msrc)); contents.insert("mountinfo".to_string(), NewMountInfoFile(task, thread, msrc)); contents.insert("mounts".to_string(), NewMountsFile(task, thread, msrc)); contents.insert("stat".to_string(), NewStat(task, thread, showSubtasks, self.lock().pidns.clone(), msrc)); contents.insert("statm".to_string(), NewStatm(task, thread, msrc)); contents.insert("status".to_string(), NewStatus(task, thread, msrc)); contents.insert("uid_map".to_string(), NewIdMap(task, thread, msrc, false)); if showSubtasks { contents.insert("task".to_string(), self.NewSubTasksDir(task, thread, msrc)); } let taskDir = DirNode { dir: Dir::New(task, contents, &ROOT_OWNER, &FilePermissions::FromMode(FileMode(0o0555))), data: TaskDirNode { pidns: None, thread: thread.clone(), } }; return NewProcInode(&Arc::new(taskDir), msrc, InodeType::SpecialDirectory, Some(thread.clone())) } }
use std::marker::PhantomData; #[cfg(feature = "sgx")] use std::prelude::v1::*; #[cfg(not(feature = "sgx"))] use std::sync::{Arc, Mutex, RwLock}; #[cfg(feature = "sgx")] use std::sync::{Arc, SgxMutex as Mutex, SgxRwLock as RwLock}; use crate::event::waiter::{Waiter, WaiterQueue}; use crate::file::tracker::SeqRdTracker; use crate::page_cache::{AsFd, Page, PageCache, PageHandle, PageState}; use crate::util::{align_down, align_up}; pub use self::flusher::Flusher; use io_uring_callback::{Fd, Handle, IoUring}; #[cfg(feature = "sgx")] use sgx_untrusted_alloc::UntrustedAllocator; mod flusher; mod tracker; /// An instance of file with async APIs. pub struct AsyncFile<Rt: AsyncFileRt + ?Sized> { fd: i32, len: RwLock<usize>, can_read: bool, can_write: bool, seq_rd_tracker: SeqRdTracker, waiter_queue: WaiterQueue, phantom_data: PhantomData<Rt>, } /// The runtime support for AsyncFile. /// /// AsyncFile cannot work on its own: it leverages PageCache to accelerate I/O, /// needs Flusher to persist data, and eventually depends on IoUring to perform /// async I/O. This trait provides a common interface for user-implemented runtimes /// that support AsyncFile. pub trait AsyncFileRt: Send + Sync + 'static { /// Returns the io_uring instance. fn io_uring() -> &'static IoUring; fn page_cache() -> &'static PageCache; fn flusher() -> &'static Flusher<Self>; fn auto_flush(); } impl<Rt: AsyncFileRt + ?Sized> AsyncFile<Rt> { /// Open a file at a given path. /// /// The three arguments have the same meaning as the open syscall. pub fn open(mut path: String, flags: i32, mode: u32) -> Result<Arc<Self>, i32> { let (can_read, can_write) = if flags & libc::O_WRONLY != 0 { (false, true) } else if flags & libc::O_RDWR != 0 { (true, true) } else { // libc::O_RDONLY = 0 (true, false) }; let fd = unsafe { let c_path = std::ffi::CString::new(path).unwrap(); let c_path_ptr = c_path.as_bytes_with_nul().as_ptr() as _; let flags = if flags & libc::O_WRONLY != 0 { (flags & !libc::O_WRONLY) | libc::O_RDWR } else { flags }; #[cfg(not(feature = "sgx"))] let fd = libc::open(c_path_ptr, flags, mode); #[cfg(feature = "sgx")] let fd = libc::ocall::open64(c_path_ptr, flags, mode as i32); fd }; if fd < 0 { return Err(errno()); } #[cfg(not(feature = "sgx"))] let len = unsafe { libc::lseek(fd, 0, libc::SEEK_END) }; #[cfg(feature = "sgx")] let len = unsafe { libc::ocall::lseek(fd, 0, libc::SEEK_END) }; if len < 0 { return Err(errno()); } Ok(Arc::new(Self { fd, len: RwLock::new(len as usize), can_read, can_write, seq_rd_tracker: SeqRdTracker::new(), waiter_queue: WaiterQueue::new(), phantom_data: PhantomData, })) } pub async fn read_at(self: &Arc<Self>, offset: usize, buf: &mut [u8]) -> i32 { if !self.can_read { return -libc::EBADF; } if buf.len() == 0 { return 0; } // Prevent offset calculation from overflow if offset >= usize::max_value() / 2 { return -libc::EINVAL; } // Prevent the return length (i32) from overflow if buf.len() > i32::max_value() as usize { return -libc::EINVAL; } // Fast path let retval = self.try_read_at(offset, buf); if retval != -libc::EAGAIN { return retval; } // Slow path let waiter = Waiter::new(); self.waiter_queue.enqueue(&waiter); let retval = loop { let retval = self.try_read_at(offset, buf); if retval != -libc::EAGAIN { break retval; } waiter.wait().await; }; self.waiter_queue.dequeue(&waiter); retval } fn try_read_at(self: &Arc<Self>, offset: usize, buf: &mut [u8]) -> i32 { let file_len = *self.len.read().unwrap(); // For reads beyond the end of the file if offset >= file_len { // EOF return 0; } // For reads within the bound of the file let file_remaining = file_len - offset; let buf_len = buf.len().min(file_remaining); let buf = &mut buf[..buf_len]; // Determine if it is a sequential read and how much data to prefetch let seq_rd = self.seq_rd_tracker.accept(offset, buf.len()); let prefetch_len = { let prefetch_len = seq_rd.as_ref().map_or(0, |seq_rd| seq_rd.prefetch_size()); let max_prefetch_len = file_remaining - buf.len(); prefetch_len.min(max_prefetch_len) }; // Fetch the data to the page cache and copy the data of the first ready pages // in the page cache to the output buffer. let mut read_nbytes = 0; self.fetch_pages(offset, buf_len, prefetch_len, |page_handle: &PageHandle| { let page_slice = unsafe { page_handle.page().as_slice() }; let inner_offset = offset + read_nbytes - page_handle.offset(); let page_remain = Page::size() - inner_offset; let buf_remain = buf_len - read_nbytes; let copy_size = buf_remain.min(page_remain); let src_buf = &page_slice[inner_offset..inner_offset + copy_size]; let target_buf = &mut buf[read_nbytes..read_nbytes + copy_size]; target_buf.copy_from_slice(src_buf); read_nbytes += copy_size; }); if read_nbytes > 0 { seq_rd.map(|seq_rd| seq_rd.complete(read_nbytes)); read_nbytes as i32 } else { -libc::EAGAIN } } // Fetch and prefetch pages. // // The first pages in the fetch range [offset, offset + len) that are ready to read are passed // to a closure so that the caller can access the data in these pages. Note that the state of the // page is locked while the closure is being executed. // // The pages that are within the range [offset, offset + len + prefetch_len] will be fetched into // the page cache, if they are not present in the page cache. // // The procedure works in two phases. The first phase is fetching, in which we iterate // the first pages that are ready to read. These pages are passed to the access closure // one-by-one. Upon reaching the first page that cannot be read or beyond the fetching // range [offset, offset + len), we transit to the second phase: prefetching. In this // phase, we will try out our best to bring the pages into the page cache, // issueing async reads if needed. fn fetch_pages( self: &Arc<Self>, offset: usize, len: usize, prefetch_len: usize, mut access_fn: impl FnMut(&PageHandle), ) { // If the first stage, the value is true; if the second stage, false. let mut should_call_access_fn = true; // Prepare for async read that fetches multiple consecutive pages let mut consecutive_pages = Vec::new(); // Enter the loop that fetches and prefetches pages. let page_cache = Rt::page_cache(); let page_begin = align_down(offset, Page::size()); let page_end = align_up(offset + len + prefetch_len, Page::size()); let fetch_end = align_up(offset + len, Page::size()); for page_offset in (page_begin..page_end).step_by(Page::size()) { if should_call_access_fn && page_offset >= fetch_end { should_call_access_fn = false; } let page = page_cache.acquire(self, page_offset).unwrap(); let mut state = page.state(); if should_call_access_fn { // The fetching phase match *state { PageState::UpToDate | PageState::Dirty | PageState::Flushing => { // Invoke the access function (access_fn)(&page); drop(state); page_cache.release(page); } PageState::Uninit => { // Start prefetching *state = PageState::Fetching; drop(state); consecutive_pages.push(page); // Transit to the prefetching phase should_call_access_fn = false; } PageState::Fetching => { // We do nothing here drop(state); page_cache.release(page); // Transit to the prefetching phase should_call_access_fn = false; } } } else { // The prefetching phase match *state { PageState::Uninit => { // Add one more page to prefetch *state = PageState::Fetching; drop(state); consecutive_pages.push(page); } PageState::UpToDate | PageState::Dirty | PageState::Flushing | PageState::Fetching => { drop(state); page_cache.release(page); // When reaching the end of consecutive pages, start the I/O if consecutive_pages.len() > 0 { self.fetch_consecutive_pages(consecutive_pages); consecutive_pages = Vec::new(); } } } } } // When reaching the end of consecutive pages, start the I/O if consecutive_pages.len() > 0 { self.fetch_consecutive_pages(consecutive_pages); } } fn fetch_consecutive_pages(self: &Arc<Self>, consecutive_pages: Vec<PageHandle>) { debug_assert!(!consecutive_pages.is_empty()); debug_assert!(consecutive_pages.windows(2).all(|two_pages| { let (p0, p1) = (&two_pages[0], &two_pages[1]); p0.offset() + Page::size() == p1.offset() })); debug_assert!(consecutive_pages .iter() .all(|page| { *page.state() == PageState::Fetching })); let first_offset = consecutive_pages[0].offset(); let self_ = self.clone(); let iovecs = Box::new( consecutive_pages .iter() .map(|page_handle| libc::iovec { iov_base: page_handle.page().as_mut_ptr() as _, iov_len: Page::size(), }) .collect::<Vec<libc::iovec>>(), ); #[cfg(not(feature = "sgx"))] let (iovecs_ptr, iovecs_len) = ((*iovecs).as_ptr(), (*iovecs).len()); #[cfg(feature = "sgx")] let (iovecs_ptr, iovecs_len, allocator, iovecs_ptr_u64, t_iovecs_ptr_u64) = { let iovecs_len = (*iovecs).len(); let t_iovecs_ptr = (*iovecs).as_ptr(); let iovecs_size = iovecs_len * core::mem::size_of::<libc::iovec>(); let size = iovecs_size + iovecs_len * Page::size(); let allocator = UntrustedAllocator::new(size, 8).unwrap(); let iovecs_ptr = allocator.as_mut_ptr() as *mut libc::iovec; let data_ptr = unsafe { iovecs_ptr.add(iovecs_size) as *mut u8 }; for idx in 0..iovecs_len { unsafe { *iovecs_ptr.add(idx) = libc::iovec { iov_base: data_ptr.add(idx * Page::size()) as _, iov_len: Page::size(), }; } } ( iovecs_ptr, iovecs_len, allocator, iovecs_ptr as u64, t_iovecs_ptr as u64, ) }; struct IovecsBox(Box<Vec<libc::iovec>>); unsafe impl Send for IovecsBox {} let iovecs_box = IovecsBox(iovecs); let handle_store: Arc<Mutex<Option<Handle>>> = Arc::new(Mutex::new(None)); let handle_store2 = handle_store.clone(); let callback = move |retval| { let page_cache = Rt::page_cache(); let read_nbytes = if retval >= 0 { retval } else { 0 } as usize; for page in consecutive_pages { let page_offset = page.offset(); debug_assert!(page_offset >= first_offset); // For a partial read, fill zeros or in the remaining part of the page. // TODO: are there partial reads that should not fill zeros? let page_valid_nbytes = if first_offset + read_nbytes > page_offset { (first_offset + read_nbytes - page_offset).min(Page::size()) } else { 0 }; if page_valid_nbytes < Page::size() { let page_slice = unsafe { page.page().as_slice_mut() }; page_slice[page_valid_nbytes..].fill(0); } // Update page state { let mut state = page.state(); debug_assert!(*state == PageState::Fetching); *state = PageState::UpToDate; } page_cache.release(page); } self_.waiter_queue.wake_all(); #[cfg(feature = "sgx")] { let iovecs_ptr = iovecs_ptr_u64 as *const libc::iovec; let t_iovecs_ptr = t_iovecs_ptr_u64 as *mut libc::iovec; for idx in 0..iovecs_len { unsafe { assert!((*t_iovecs_ptr.add(idx)).iov_len == Page::size()); std::ptr::copy_nonoverlapping( (*iovecs_ptr.add(idx)).iov_base, (*t_iovecs_ptr.add(idx)).iov_base, (*t_iovecs_ptr.add(idx)).iov_len, ); } } drop(allocator); } drop(iovecs_box); drop(handle_store); }; let io_uring = Rt::io_uring(); let handle = unsafe { io_uring.readv( Fd(self.fd), iovecs_ptr, iovecs_len as u32, first_offset as i64, 0, callback, ) }; let mut guard = handle_store2.lock().unwrap(); guard.replace(handle); } pub async fn write_at(self: &Arc<Self>, offset: usize, buf: &[u8]) -> i32 { if !self.can_write { return -libc::EBADF; } if buf.len() == 0 { return 0; } // Fast path let retval = self.try_write(offset, buf); if retval != -libc::EAGAIN { return retval; } // Slow path let waiter = Waiter::new(); self.waiter_queue.enqueue(&waiter); let retval = loop { let retval = self.try_write(offset, buf); if retval != -libc::EAGAIN { break retval; } waiter.wait().await; }; self.waiter_queue.dequeue(&waiter); retval } fn try_write(self: &Arc<Self>, offset: usize, buf: &[u8]) -> i32 { // Prevent offset calculation from overflow if offset >= usize::max_value() / 2 { return -libc::EINVAL; } // Prevent the return length (i32) from overflow if buf.len() > i32::max_value() as usize { return -libc::EINVAL; } let mut new_dirty_pages = false; let mut write_nbytes = 0; let page_cache = Rt::page_cache(); let page_begin = align_down(offset, Page::size()); let page_end = align_up(offset + buf.len(), Page::size()); for page_offset in (page_begin..page_end).step_by(Page::size()) { let page_handle = page_cache.acquire(self, page_offset).unwrap(); let inner_offset = offset + write_nbytes - page_offset; let copy_size = { let page_remain = Page::size() - inner_offset; let buf_remain = buf.len() - write_nbytes; buf_remain.min(page_remain) }; let to_write_full_page = copy_size == Page::size(); let mut do_write = || { let page_slice = unsafe { page_handle.page().as_slice_mut() }; let src_buf = &buf[write_nbytes..write_nbytes + copy_size]; let dst_buf = &mut page_slice[inner_offset..inner_offset + copy_size]; dst_buf.copy_from_slice(src_buf); write_nbytes += copy_size; }; let mut state = page_handle.state(); match *state { PageState::UpToDate => { (do_write)(); *state = PageState::Dirty; drop(state); page_cache.release(page_handle); new_dirty_pages = true; } PageState::Dirty => { (do_write)(); drop(state); page_cache.release(page_handle); } PageState::Uninit if to_write_full_page => { (do_write)(); *state = PageState::Dirty; drop(state); page_cache.release(page_handle); new_dirty_pages = true; } PageState::Uninit => { *state = PageState::Fetching; drop(state); self.fetch_consecutive_pages(vec![page_handle]); break; } PageState::Fetching | PageState::Flushing => { // We do nothing here drop(state); page_cache.release(page_handle); break; } } } if new_dirty_pages { Rt::auto_flush(); } if write_nbytes > 0 { // Update file length if necessary let mut file_len = self.len.write().unwrap(); if offset + write_nbytes > *file_len { *file_len = offset + write_nbytes; } write_nbytes as i32 } else { -libc::EAGAIN } } pub async fn flush(&self) { loop { const FLUSH_BATCH_SIZE: usize = 64; let num_flushed = Rt::flusher().flush_by_fd(self.fd, FLUSH_BATCH_SIZE).await; if num_flushed == 0 { return; } } } pub(crate) fn waiter_queue(&self) -> &WaiterQueue { &self.waiter_queue } } impl<Rt: AsyncFileRt + ?Sized> AsFd for AsyncFile<Rt> { fn as_fd(&self) -> i32 { self.fd } } impl<Rt: AsyncFileRt + ?Sized> Drop for AsyncFile<Rt> { fn drop(&mut self) { unsafe { #[cfg(not(feature = "sgx"))] libc::close(self.fd); #[cfg(feature = "sgx")] libc::ocall::close(self.fd); } } } #[cfg(not(feature = "sgx"))] fn errno() -> i32 { unsafe { *(libc::__errno_location()) // *(libc::__error()) } } #[cfg(feature = "sgx")] fn errno() -> i32 { libc::errno() }
use std::cmp::Ordering; use std::mem; // courtesy of https://stackoverflow.com/a/28294764 fn swap<T>(x: &mut [T], i: usize, j: usize) { let (lo, hi) = match i.cmp(&j) { // no swapping necessary Ordering::Equal => return, // get the smallest and largest of the two indices Ordering::Less => (i, j), Ordering::Greater => (j ,i), }; let (init, tail) = x.split_at_mut(hi); mem::swap(&mut init[lo], &mut tail[0]); } // Sorts a subarray by quicksort // Input: Subarray of array a[0..n-1], defined by its left and right indices l and r // Output: Subarray a[l..r] sorted in nondecreasing order fn quicksort(a: &mut [u8], l: usize, r: usize) { if l < r { let s = hoare_partition(a, l, r); quicksort(a, l, s - 1); quicksort(a, s + 1, r); } } // Partitions a subarray by Hoare's algorithm, using the first element as a pivot // Input: Subarray of array a[0..n-1], defined by its left and right indices l and r (l < r) // Output: Partition of a[l..r], with the split position returned as this function's value fn hoare_partition(a: &mut [u8], l: usize, r: usize) -> usize { let p = a[l]; let mut i = l; let mut j = r + 1; while i < j { loop { i = i + 1; if a[i] >= p { break; } } loop { j = j - 1; if a[j] <= p { break; } } swap(a, i, j); } swap(a, i, j); // undo last swap when i >= j swap(a, l, j); j } fn main() { // sort example array from book let mut a: [u8; 8] = [5, 3, 1, 9, 8, 2, 4, 7]; println!("Array before quicksort: {:?}", a); quicksort(&mut a, 0, 7); println!("Array after quicksort: {:?}", a); }
use arci::JointTrajectoryClient; use arci_urdf_viz::create_joint_trajectory_clients; use k::{Chain, Isometry3}; use log::info; use openrr_client::{ create_collision_check_clients, create_ik_clients, CollisionCheckClient, IkClient, }; use std::{collections::HashMap, sync::Arc, time::Duration}; use tokio::sync::Mutex; use crate::{Error, RobotConfig}; type ArcMutexIkClient = Arc<Mutex<IkClient<Arc<dyn JointTrajectoryClient>>>>; pub struct RobotClient { full_chain_for_collision_checker: Arc<Chain<f64>>, raw_joint_trajectory_clients: HashMap<String, Arc<dyn JointTrajectoryClient>>, all_joint_trajectory_clients: HashMap<String, Arc<dyn JointTrajectoryClient>>, collision_check_clients: HashMap<String, Arc<CollisionCheckClient<Arc<dyn JointTrajectoryClient>>>>, ik_clients: HashMap<String, ArcMutexIkClient>, } impl RobotClient { pub fn try_new(config: RobotConfig) -> Result<Self, Error> { #[cfg(not(feature = "ros"))] let raw_joint_trajectory_clients = if config.urdf_viz_clients_configs.is_empty() { return Err(Error::NoClientsConfigs("urdf_viz_clients".to_owned())); } else { create_joint_trajectory_clients(config.urdf_viz_clients_configs.clone()) }; #[cfg(feature = "ros")] let raw_joint_trajectory_clients = { let mut clients = if config.urdf_viz_clients_configs.is_empty() { HashMap::new() } else { create_joint_trajectory_clients(config.urdf_viz_clients_configs.clone()) }; clients.extend( arci_ros::create_joint_trajectory_clients(config.ros_clients_configs.clone()) .into_iter(), ); if clients.is_empty() { return Err(Error::NoClientsConfigs( "urdf_viz_clients_configs / ros_clients_configs".to_owned(), )); } clients }; let urdf_full_path = if let Some(p) = config.urdf_full_path().clone() { p } else { return Err(Error::NoUrdfPath); }; let full_chain_for_collision_checker = Arc::new(Chain::from_urdf_file(&urdf_full_path)?); let collision_check_clients = create_collision_check_clients( urdf_full_path, &config.self_collision_check_pairs, &config.collision_check_clients_configs, &raw_joint_trajectory_clients, full_chain_for_collision_checker.clone(), ); let mut all_joint_trajectory_clients = HashMap::new(); for (name, client) in &raw_joint_trajectory_clients { all_joint_trajectory_clients.insert(name.to_owned(), client.clone()); } for (name, client) in &collision_check_clients { all_joint_trajectory_clients.insert(name.to_owned(), client.clone()); } let ik_clients = create_ik_clients( &config.ik_clients_configs, &all_joint_trajectory_clients, &full_chain_for_collision_checker, ); Ok(Self { full_chain_for_collision_checker, raw_joint_trajectory_clients, all_joint_trajectory_clients, collision_check_clients, ik_clients, }) } pub fn set_raw_clients_joint_positions_to_full_chain_for_collision_checker( &self, ) -> Result<(), Error> { for client in self.raw_joint_trajectory_clients.values() { let positions = client.current_joint_positions()?; let joint_names = client.joint_names(); if positions.len() != joint_names.len() { return Err(Error::MismatchedLength(positions.len(), joint_names.len())); } for (index, joint_name) in joint_names.iter().enumerate() { if let Some(joint) = self.full_chain_for_collision_checker.find(joint_name) { joint.set_joint_position_clamped(positions[index]) } else { return Err(Error::NoJoint(joint_name.to_owned())); } } } self.full_chain_for_collision_checker.update_transforms(); Ok(()) } pub fn is_raw_joint_trajectory_client(&self, name: &str) -> bool { self.raw_joint_trajectory_clients.contains_key(name) } pub fn is_joint_trajectory_client(&self, name: &str) -> bool { self.all_joint_trajectory_clients.contains_key(name) } pub fn is_collision_check_client(&self, name: &str) -> bool { self.collision_check_clients.contains_key(name) } pub fn is_ik_client(&self, name: &str) -> bool { self.ik_clients.contains_key(name) } fn joint_trajectory_client( &self, name: &str, ) -> Result<&Arc<dyn JointTrajectoryClient>, Error> { if self.is_joint_trajectory_client(name) { Ok(&self.all_joint_trajectory_clients[name]) } else { Err(Error::NoJointTrajectoryClient(name.to_owned())) } } fn ik_client(&self, name: &str) -> Result<&ArcMutexIkClient, Error> { if self.is_ik_client(name) { Ok(&self.ik_clients[name]) } else { Err(Error::NoIkClient(name.to_owned())) } } pub async fn send_joint_positions( &self, name: &str, positions: &[f64], duration_sec: f64, ) -> Result<(), Error> { self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?; if self.is_ik_client(name) { Ok(self .ik_client(name)? .lock() .await .client .send_joint_positions(positions.to_owned(), Duration::from_secs_f64(duration_sec)) .await?) } else { Ok(self .joint_trajectory_client(name)? .send_joint_positions(positions.to_owned(), Duration::from_secs_f64(duration_sec)) .await?) } } pub async fn current_joint_positions(&self, name: &str) -> Result<Vec<f64>, Error> { if self.is_ik_client(name) { self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?; Ok(self .ik_client(name)? .lock() .await .current_joint_positions()?) } else { Ok(self .joint_trajectory_client(name)? .current_joint_positions()?) } } pub async fn current_end_transform(&self, name: &str) -> Result<Isometry3<f64>, Error> { self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?; Ok(self.ik_client(name)?.lock().await.current_end_transform()?) } pub async fn transform( &self, name: &str, pose: &Isometry3<f64>, ) -> Result<Isometry3<f64>, Error> { self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?; Ok(self.ik_client(name)?.lock().await.transform(pose)?) } pub async fn move_ik( &self, name: &str, target_pose: &Isometry3<f64>, duration_sec: f64, ) -> Result<(), Error> { self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?; Ok(self .ik_client(name)? .lock() .await .move_ik(target_pose, duration_sec) .await?) } pub async fn move_ik_with_interpolation( &self, name: &str, target_pose: &Isometry3<f64>, duration_sec: f64, ) -> Result<(), Error> { self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?; Ok(self .ik_client(name)? .lock() .await .move_ik_with_interpolation(target_pose, duration_sec) .await?) } pub async fn send_joint_positions_with_pose_interpolation( &self, name: &str, positions: &[f64], duration_sec: f64, ) -> Result<(), Error> { self.set_raw_clients_joint_positions_to_full_chain_for_collision_checker()?; let target_pose = { let ik_client = self.ik_client(name)?.lock().await; ik_client.chain.set_joint_positions_clamped(positions); ik_client.ik_solver_with_chain.end_transform() }; Ok(self .move_ik_with_interpolation(name, &target_pose, duration_sec) .await?) } pub fn list_clients(&self) { info!("Raw joint trajectory clients"); for name in self.raw_joint_trajectory_clients.keys() { info!(" {}", name); } info!("Joint trajectory clients"); for name in self.all_joint_trajectory_clients.keys() { info!(" {}", name); } info!("Collision check clients"); for name in self.collision_check_clients.keys() { info!(" {}", name); } info!("Ik clients"); for name in self.ik_clients.keys() { info!(" {}", name); } } }
use rust_tools::bench::Bench; use crate::mcts_tree::mcts_tree::M2; use crate::mcts_tree::mcts_indextree::M1; // pub const TREE_SIZE: usize = 10_000; pub const TREE_SIZE: usize = 20; pub const BRANCH_FACTOR: usize = 2; pub trait MCTS<T> { fn select_from(&mut self, node: &T) -> T; fn expand(&mut self, node: &T, max_children: usize); } #[derive(Clone, Debug)] pub struct MStats { pub explored: usize, pub wins: usize, pub depth: usize, pub leafs: usize, pub tree_size: usize, } impl MStats { pub(crate) fn new() -> MStats { MStats { explored: 0, wins: 0, depth: 0, leafs: 0, tree_size: 1, } } pub(crate) fn is_leaf(&self) -> bool { self.explored == 0 } }
/* * max_value(s, α, β) * if terminal(s) return U(s) * v = -∞ * for c in next_states(s) * v' = min_value(c, α, β) * if v' > v, v = v' * if v' ≥ β, return v * if v' > α, α = v' * return v * * min_value(s, α, β) * if terminal(s) return U(s) * v = ∞ * for c in next_states(s) * v' = max_value(c, α, β) * if v' < v, v = v' * if v' ≤ α, return v * if v' < β, β = v' * return v */ fn main() { println!("Hello, world!"); }
mod game_message; mod out_message; mod ws_client_message; pub mod messages { pub use super::game_message::*; pub use super::out_message::*; pub use super::ws_client_message::*; }
//! Pretty printing use syntax::ast::{Expr, Expr_}; use syntax::codemap::Source; /// Pretty prints an expression pub fn expr(expr: &Expr, source: &Source) -> String { let mut string = String::new(); expr_(&mut string, expr, source); string } fn expr_(string: &mut String, expr: &Expr, source: &Source) { fn seq(string: &mut String, exprs: &[Expr], source: &Source) { let mut is_first = true; for expr in exprs { if is_first { is_first = false; } else { string.push(' '); } expr_(string, expr, source) } } match expr.node { Expr_::Bool(bool) => string.push_str(&bool.to_string()), Expr_::Integer(integer) => string.push_str(&integer.to_string()), Expr_::Keyword(_) => string.push_str(&source[expr.span]), Expr_::List(ref exprs) => { string.push('('); seq(string, exprs, source); string.push(')'); }, Expr_::Nil => string.push_str("nil"), Expr_::Operator(_) => string.push_str(&source[expr.span]), Expr_::String => string.push_str(&source[expr.span]), Expr_::Symbol(_) => string.push_str(&source[expr.span]), Expr_::Vector(ref exprs) => { string.push('['); seq(string, exprs, source); string.push(']'); }, } }
use std::marker::PhantomData; use super::resource::{Fetch, FetchMut, Resource, Resources}; pub trait System<'a> { type SystemData: SystemData<'a>; fn run(&mut self, data: Self::SystemData); } pub trait SystemData<'a> { fn fetch(res: &'a Resources) -> Self; } impl<'a, T: ?Sized> SystemData<'a> for PhantomData<T> { fn fetch(_: &'a Resources) -> Self { PhantomData } } impl<'a, R> SystemData<'a> for Fetch<'a, R> where R: Resource, { fn fetch(res: &'a Resources) -> Self { res.fetch::<R>() } } impl<'a, R> SystemData<'a> for FetchMut<'a, R> where R: Resource, { fn fetch(res: &'a Resources) -> Self { res.fetch_mut::<R>() } } macro_rules! impl_data { ( $($ty:ident),* ) => { impl<'a, $($ty),*> SystemData<'a> for ( $( $ty , )* ) where $( $ty : SystemData<'a> ),* { fn fetch(res: &'a Resources) -> Self { #![allow(unused_variables)] ( $( <$ty as SystemData<'a>>::fetch(res), )* ) } } }; } mod impl_data { #![cfg_attr(rustfmt, rustfmt_skip)] use super::*; impl_data!(A); impl_data!(A, B); impl_data!(A, B, C); impl_data!(A, B, C, D); impl_data!(A, B, C, D, E); impl_data!(A, B, C, D, E, F); impl_data!(A, B, C, D, E, F, G); impl_data!(A, B, C, D, E, F, G, H); impl_data!(A, B, C, D, E, F, G, H, I); impl_data!(A, B, C, D, E, F, G, H, I, J); impl_data!(A, B, C, D, E, F, G, H, I, J, K); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y); impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z); }
mod hash_maps; mod strings; mod vectors; fn main() { vectors::main(); println!(); strings::main(); println!(); hash_maps::main(); }
use crate::{Valuable, Value}; pub trait Listable { fn len(&self) -> usize; fn iter(&self, f: &mut dyn FnMut(&mut dyn Iterator<Item = Value<'_>>)); } impl<T: Valuable> Listable for [T] { fn len(&self) -> usize { <[T]>::len(self) } fn iter(&self, f: &mut dyn FnMut(&mut dyn Iterator<Item = Value<'_>>)) { f(&mut <[T]>::iter(self).map(Valuable::as_value)); } } impl<T: Valuable> Listable for Vec<T> { fn len(&self) -> usize { Vec::len(self) } fn iter(&self, f: &mut dyn FnMut(&mut dyn Iterator<Item = Value<'_>>)) { f(&mut <[T]>::iter(self).map(Valuable::as_value)); } }
use std::env; use adventofcode::Config; mod day01; mod day02; mod day03; mod day04; mod day05; mod day06; mod day07; mod day08; mod day09; mod day10; mod day11; mod measure; fn main() { let config = Config::new(env::args()).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {}", err); std::process::exit(1); }); println!("Day {}", config.day); match config.day { 1 => day01::run(config.input), 2 => day02::run(config.input), 3 => day03::run(config.input), 4 => day04::run(config.input), 5 => day05::run(config.input), 6 => day06::run(config.input), 7 => day07::run(config.input), 8 => day08::run(config.input), 9 => day09::run(config.input), 10 => day10::run(config.input), 11 => day11::run(config.input), _ => { eprintln!("Day {} not implemented yet", config.day); std::process::exit(1); } } }
use super::{pure::PurenessInsights, OptimizeMir}; use crate::{ error::CompilerError, id::IdGenerator, mir::{Body, Expression, Id, VisibleExpressions}, TracingConfig, }; use rustc_hash::FxHashSet; use std::ops::{Deref, DerefMut}; pub struct Context<'a> { pub db: &'a dyn OptimizeMir, pub tracing: &'a TracingConfig, pub errors: &'a mut FxHashSet<CompilerError>, pub visible: &'a mut VisibleExpressions, pub id_generator: &'a mut IdGenerator<Id>, pub pureness: &'a mut PurenessInsights, } pub struct CurrentExpression<'a> { body: &'a mut Body, index: usize, } impl<'a> CurrentExpression<'a> { pub fn new(body: &'a mut Body, index: usize) -> Self { Self { body, index } } pub fn index(&self) -> usize { self.index } pub fn id(&self) -> Id { self.body.expressions[self.index].0 } pub fn prepend_optimized( &mut self, visible: &mut VisibleExpressions, optimized_expressions: impl IntoIterator<Item = (Id, Expression)>, ) { self.body.expressions.splice( self.index..self.index, optimized_expressions.into_iter().map(|(id, expression)| { visible.insert(id, expression); self.index += 1; (id, Expression::Parameter) }), ); } pub fn replace_with_multiple<I: DoubleEndedIterator<Item = (Id, Expression)>>( &mut self, expressions: impl IntoIterator<Item = (Id, Expression), IntoIter = I>, ) { let mut expressions = expressions.into_iter(); let (_, last_expression) = expressions.next_back().unwrap(); self.body.expressions.splice( self.index..(self.index + 1), expressions.chain([(self.id(), last_expression)]), ); } } impl Deref for CurrentExpression<'_> { type Target = Expression; fn deref(&self) -> &Self::Target { &self.body.expressions[self.index].1 } } impl DerefMut for CurrentExpression<'_> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.body.expressions[self.index].1 } }
use crate::vm::{ builtins::PyListRef, function::ArgSequence, stdlib::{os::OsPath, posix}, {PyObjectRef, PyResult, TryFromObject, VirtualMachine}, }; use nix::{errno::Errno, unistd}; #[cfg(not(target_os = "redox"))] use std::ffi::CStr; #[cfg(not(target_os = "redox"))] use std::os::unix::io::AsRawFd; use std::{ convert::Infallible as Never, ffi::CString, io::{self, prelude::*}, }; use unistd::{Gid, Uid}; pub(crate) use _posixsubprocess::make_module; #[pymodule] mod _posixsubprocess { use super::{exec, CStrPathLike, ForkExecArgs, ProcArgs}; use crate::vm::{convert::IntoPyException, PyResult, VirtualMachine}; #[pyfunction] fn fork_exec(args: ForkExecArgs, vm: &VirtualMachine) -> PyResult<libc::pid_t> { if args.preexec_fn.is_some() { return Err(vm.new_not_implemented_error("preexec_fn not supported yet".to_owned())); } let cstrs_to_ptrs = |cstrs: &[CStrPathLike]| { cstrs .iter() .map(|s| s.s.as_ptr()) .chain(std::iter::once(std::ptr::null())) .collect::<Vec<_>>() }; let argv = cstrs_to_ptrs(&args.args); let argv = &argv; let envp = args.env_list.as_ref().map(|s| cstrs_to_ptrs(s)); let envp = envp.as_deref(); match unsafe { nix::unistd::fork() }.map_err(|err| err.into_pyexception(vm))? { nix::unistd::ForkResult::Child => exec(&args, ProcArgs { argv, envp }), nix::unistd::ForkResult::Parent { child } => Ok(child.as_raw()), } } } macro_rules! gen_args { ($($field:ident: $t:ty),*$(,)?) => { #[allow(dead_code)] #[derive(FromArgs)] struct ForkExecArgs { $(#[pyarg(positional)] $field: $t,)* } }; } struct CStrPathLike { s: CString, } impl TryFromObject for CStrPathLike { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { let s = OsPath::try_from_object(vm, obj)?.into_cstring(vm)?; Ok(CStrPathLike { s }) } } gen_args! { args: ArgSequence<CStrPathLike> /* list */, exec_list: ArgSequence<CStrPathLike> /* list */, close_fds: bool, fds_to_keep: ArgSequence<i32>, cwd: Option<CStrPathLike>, env_list: Option<ArgSequence<CStrPathLike>>, p2cread: i32, p2cwrite: i32, c2pread: i32, c2pwrite: i32, errread: i32, errwrite: i32, errpipe_read: i32, errpipe_write: i32, restore_signals: bool, call_setsid: bool, // TODO: Difference between gid_to_set and gid_object. // One is a `gid_t` and the other is a `PyObject` in CPython. gid_to_set: Option<Option<Gid>>, gid_object: PyObjectRef, groups_list: Option<PyListRef>, uid: Option<Option<Uid>>, child_umask: i32, preexec_fn: Option<PyObjectRef>, use_vfork: bool, } // can't reallocate inside of exec(), so we reallocate prior to fork() and pass this along struct ProcArgs<'a> { argv: &'a [*const libc::c_char], envp: Option<&'a [*const libc::c_char]>, } fn exec(args: &ForkExecArgs, procargs: ProcArgs) -> ! { match exec_inner(args, procargs) { Ok(x) => match x {}, Err(e) => { let buf: &mut [u8] = &mut [0; 256]; let mut cur = io::Cursor::new(&mut *buf); // TODO: check if reached preexec, if not then have "noexec" after let _ = write!(cur, "OSError:{}:", e as i32); let pos = cur.position(); let _ = unistd::write(args.errpipe_write, &buf[..pos as usize]); std::process::exit(255) } } } fn exec_inner(args: &ForkExecArgs, procargs: ProcArgs) -> nix::Result<Never> { for &fd in args.fds_to_keep.as_slice() { if fd != args.errpipe_write { posix::raw_set_inheritable(fd, true)? } } for &fd in &[args.p2cwrite, args.c2pread, args.errread] { if fd != -1 { unistd::close(fd)?; } } unistd::close(args.errpipe_read)?; let c2pwrite = if args.c2pwrite == 0 { let fd = unistd::dup(args.c2pwrite)?; posix::raw_set_inheritable(fd, true)?; fd } else { args.c2pwrite }; let mut errwrite = args.errwrite; while errwrite == 0 || errwrite == 1 { errwrite = unistd::dup(errwrite)?; posix::raw_set_inheritable(errwrite, true)?; } let dup_into_stdio = |fd, io_fd| { if fd == io_fd { posix::raw_set_inheritable(fd, true) } else if fd != -1 { unistd::dup2(fd, io_fd).map(drop) } else { Ok(()) } }; dup_into_stdio(args.p2cread, 0)?; dup_into_stdio(c2pwrite, 1)?; dup_into_stdio(errwrite, 2)?; if let Some(ref cwd) = args.cwd { unistd::chdir(cwd.s.as_c_str())? } if args.child_umask >= 0 { // TODO: umask(child_umask); } if args.restore_signals { // TODO: restore signals SIGPIPE, SIGXFZ, SIGXFSZ to SIG_DFL } if args.call_setsid { #[cfg(not(target_os = "redox"))] unistd::setsid()?; } if let Some(_groups_list) = args.groups_list.as_ref() { // TODO: setgroups // unistd::setgroups(groups_size, groups); } if let Some(_gid) = args.gid_to_set.as_ref() { // TODO: setgid // unistd::setregid(gid, gid)?; } if let Some(_uid) = args.uid.as_ref() { // TODO: setuid // unistd::setreuid(uid, uid)?; } if args.close_fds { #[cfg(not(target_os = "redox"))] close_fds(3, &args.fds_to_keep)?; } let mut first_err = None; for exec in args.exec_list.as_slice() { // not using nix's versions of these functions because those allocate the char-ptr array, // and we can't allocate if let Some(envp) = procargs.envp { unsafe { libc::execve(exec.s.as_ptr(), procargs.argv.as_ptr(), envp.as_ptr()) }; } else { unsafe { libc::execv(exec.s.as_ptr(), procargs.argv.as_ptr()) }; } let e = Errno::last(); if e != Errno::ENOENT && e != Errno::ENOTDIR && first_err.is_none() { first_err = Some(e) } } Err(first_err.unwrap_or_else(Errno::last)) } #[cfg(not(target_os = "redox"))] fn close_fds(above: i32, keep: &[i32]) -> nix::Result<()> { use nix::{dir::Dir, fcntl::OFlag}; // TODO: close fds by brute force if readdir doesn't work: // https://github.com/python/cpython/blob/3.8/Modules/_posixsubprocess.c#L220 let mut dir = Dir::open( FD_DIR_NAME, OFlag::O_RDONLY | OFlag::O_DIRECTORY, nix::sys::stat::Mode::empty(), )?; let dirfd = dir.as_raw_fd(); for e in dir.iter() { if let Some(fd) = pos_int_from_ascii(e?.file_name()) { if fd != dirfd && fd > above && !keep.contains(&fd) { unistd::close(fd)? } } } Ok(()) } #[cfg(any( target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", target_vendor = "apple", ))] const FD_DIR_NAME: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"/dev/fd\0") }; #[cfg(any(target_os = "linux", target_os = "android"))] const FD_DIR_NAME: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"/proc/self/fd\0") }; #[cfg(not(target_os = "redox"))] fn pos_int_from_ascii(name: &CStr) -> Option<i32> { let mut num = 0; for c in name.to_bytes() { if !c.is_ascii_digit() { return None; } num = num * 10 + i32::from(c - b'0') } Some(num) }
extern crate xmlparser as xml; #[macro_use] mod token; use token::*; test!(cdata_01, "<p><![CDATA[content]]></p>", Token::ElementStart("", "p"), Token::ElementEnd(ElementEnd::Open), Token::Cdata("content"), Token::ElementEnd(ElementEnd::Close("", "p")) ); test!(cdata_02, "<p><![CDATA[&amping]]></p>", Token::ElementStart("", "p"), Token::ElementEnd(ElementEnd::Open), Token::Cdata("&amping"), Token::ElementEnd(ElementEnd::Close("", "p")) ); test!(cdata_03, "<p><![CDATA[&amping ]]]></p>", Token::ElementStart("", "p"), Token::ElementEnd(ElementEnd::Open), Token::Cdata("&amping ]"), Token::ElementEnd(ElementEnd::Close("", "p")) ); test!(cdata_04, "<p><![CDATA[&amping]] ]]></p>", Token::ElementStart("", "p"), Token::ElementEnd(ElementEnd::Open), Token::Cdata("&amping]] "), Token::ElementEnd(ElementEnd::Close("", "p")) ); test!(cdata_05, "<p><![CDATA[<message>text</message>]]></p>", Token::ElementStart("", "p"), Token::ElementEnd(ElementEnd::Open), Token::Cdata("<message>text</message>"), Token::ElementEnd(ElementEnd::Close("", "p")) ); test!(cdata_06, "<p><![CDATA[</this is malformed!</malformed</malformed & worse>]]></p>", Token::ElementStart("", "p"), Token::ElementEnd(ElementEnd::Open), Token::Cdata("</this is malformed!</malformed</malformed & worse>"), Token::ElementEnd(ElementEnd::Close("", "p")) ); test!(cdata_07, "<p><![CDATA[1]]><![CDATA[2]]></p>", Token::ElementStart("", "p"), Token::ElementEnd(ElementEnd::Open), Token::Cdata("1"), Token::Cdata("2"), Token::ElementEnd(ElementEnd::Close("", "p")) ); test!(cdata_08, "<p> \n <![CDATA[data]]> \t </p>", Token::ElementStart("", "p"), Token::ElementEnd(ElementEnd::Open), Token::Whitespaces(" \n "), Token::Cdata("data"), Token::Whitespaces(" \t "), Token::ElementEnd(ElementEnd::Close("", "p")) ); test!(cdata_09, "<p><![CDATA[bracket ]after]]></p>", Token::ElementStart("", "p"), Token::ElementEnd(ElementEnd::Open), Token::Cdata("bracket ]after"), Token::ElementEnd(ElementEnd::Close("", "p")) );
use serde::Serialize; pub mod config_instruction; pub mod config_processor; const CONFIG_PROGRAM_ID: [u8; 32] = [ 3, 6, 74, 163, 0, 47, 116, 220, 200, 110, 67, 49, 15, 12, 5, 42, 248, 197, 218, 39, 246, 16, 64, 25, 163, 35, 239, 160, 0, 0, 0, 0, ]; morgan_interface::morgan_program_id!(CONFIG_PROGRAM_ID); pub trait ConfigState: Serialize { /// Maximum space that the serialized representation will require fn max_space() -> u64; }
use crate::assets::prefab::Prefab; use crate::core::transform::Transform; use crate::gameplay::collision::BoundingBox; use crate::gameplay::health::{Health, Shield}; use crate::gameplay::physics::DynamicBody; use crate::gameplay::player::{Player, Stats, Weapon}; use crate::gameplay::trail::Trail; use crate::render::particle::ParticleEmitter; use crate::render::sprite::Sprite; use hecs::{Entity, EntityBuilder, World}; use serde_derive::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize, Default)] pub struct PlayerPrefab { pub dynamic_body: DynamicBody, pub transform: Transform, pub sprite: Sprite, pub bounding_box: BoundingBox, pub health: Health, pub shield: Option<Shield>, pub trail: ParticleEmitter, pub stats: Stats, } #[typetag::serde] impl Prefab for PlayerPrefab { fn spawn(&self, world: &mut World) -> Entity { let mut components = EntityBuilder::new(); components.add(self.dynamic_body.clone()); components.add(self.transform.clone()); components.add(self.sprite.clone()); components.add(self.bounding_box); components.add(self.health.clone()); if let Some(s) = self.shield.clone() { components.add(s); } let mut particles = self.trail.clone(); particles.init_pool(); components.add(particles); components.add(Trail { should_display: true, offset: 20.0, }); components.add(Player { weapon: Weapon::Simple, stats: self.stats.clone(), direction: glam::vec2(0.0, 1.0), }); world.spawn(components.build()) } }
use std::collections::HashMap; struct Solution; impl Solution { pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { let mut myhash:HashMap<i32, i32> = HashMap::new(); for (index, &num) in nums.iter().enumerate() { let target_to_check = target - num; if myhash.contains_key(&target_to_check) { return vec![*myhash.get(&target_to_check).unwrap(), index as i32]; } myhash.insert(num,index as i32); } return vec![]; } } fn main() { let nums = vec![2, 7, 11, 15]; let target = 9; println!("the result is {:?}", Solution::two_sum(nums, target)); }
#![crate_type = "lib"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![crate_name = "ntrumls"] // Coding conventions #![deny(non_upper_case_globals)] #![deny(non_camel_case_types)] #![deny(non_snake_case)] #![deny(unused_mut)] //#![warn(missing_docs)] #![cfg_attr(all(test, feature = "unstable"), feature(test))] extern crate libc; extern crate serde; extern crate serde_json; use serde::*; use serde::de; use serde::de::Visitor; use std::fmt; pub mod ffi; struct BytesVisitor { bytes: Vec<u8> } impl BytesVisitor { pub fn new() -> Self { BytesVisitor { bytes: Vec::new() } } } impl<'de> Visitor<'de> for BytesVisitor { type Value = Vec<u8>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "failed to parse byte array") } fn visit_bytes<E>(self, v: &[u8]) -> Result<<Self as Visitor<'de>>::Value, E> where E: de::Error, { Ok(Vec::from(v)) } fn visit_seq<A>(self, mut seq: A) -> Result<<Self as Visitor<'de>>::Value, <A as de::SeqAccess<'de>>::Error> where A: de::SeqAccess<'de>, { let mut vec = Vec::<u8>::with_capacity(seq.size_hint().unwrap_or(0)); while let Some(e) = seq.next_element()? { vec.push(e); } Ok(vec) } } #[derive(Debug, PartialEq, Eq, Clone)] pub struct PublicKey(pub Vec<u8>); impl Serialize for PublicKey { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer { serializer.serialize_bytes(&self.0) } } impl<'de> Deserialize<'de> for PublicKey { fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> where D: Deserializer<'de> { Ok(PublicKey(deserializer.deserialize_byte_buf(BytesVisitor::new())?)) } } //impl Deref for PublicKey { // type Target = [u8]; // // fn deref(&self) -> &[u8] { // &self.0 // } //} //impl DerefMut for PublicKey { // fn deref_mut(&mut self) -> &mut [u8] { // &mut self.0 // } //} #[derive(Debug, PartialEq, Eq, Clone)] pub struct PrivateKey(pub Vec<u8>); impl Serialize for PrivateKey { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer { serializer.serialize_bytes(&self.0) } } impl<'de> Deserialize<'de> for PrivateKey { fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> where D: Deserializer<'de> { Ok(PrivateKey(deserializer.deserialize_byte_buf(BytesVisitor::new())?)) } } //impl Deref for PrivateKey { // type Target = [u8]; // // fn deref(&self) -> &[u8] { // &self.0 // } //} //impl DerefMut for PrivateKey { // fn deref_mut(&mut self) -> &mut [u8] { // &mut self.0 // } //} #[derive(Debug, PartialEq, Eq, Clone)] pub struct Signature(pub Vec<u8>); impl Serialize for Signature { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer { // serializer.serialize_seq() serializer.serialize_bytes(&self.0) } } impl<'de> Deserialize<'de> for Signature { fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> where D: Deserializer<'de> { Ok(Signature(deserializer.deserialize_byte_buf(BytesVisitor::new())?)) } } //impl Deref for Signature { // type Target = [u8]; // // fn deref(&self) -> &[u8] { // &self.0 // } //} //impl DerefMut for Signature { // fn deref_mut(&mut self) -> &mut [u8] { // &mut self.0 // } //} pub enum PQParamSetID { Security82Bit, // XXX_20151024_401 Security88Bit, // XXX_20151024_443 Security126Bit, // XXX_20151024_563 Security179Bit, // XXX_20151024_743 Security269Bit, // XXX_20151024_907 } pub type PQParamSet = ffi::PQParamSet; pub struct NTRUMLS { p: PQParamSet, pubkey_packed_bytes_len: usize, privkey_packed_bytes_len: usize, } impl NTRUMLS { pub fn with_param_set(param_set: PQParamSetID) -> Self { unsafe { let p = match param_set { PQParamSetID::Security82Bit => ffi::PQParamSetID::Xxx20151024n401, PQParamSetID::Security88Bit => ffi::PQParamSetID::Xxx20151024n443, PQParamSetID::Security126Bit => ffi::PQParamSetID::Xxx20151024n563, PQParamSetID::Security179Bit => ffi::PQParamSetID::Xxx20151024n743, PQParamSetID::Security269Bit => ffi::PQParamSetID::Xxx20151024n907, }; let p = ffi::pq_get_param_set_by_id(p); if p.is_null() { panic!("Invalid PQParamSetID"); } let p = (*p).clone(); let oid_bytes_len = std::mem::size_of::<[u8; 3]>(); let packed_product_from_bytes_len = ((2 * (p.d1 + p.d2 + p.d3) as usize * p.n_bits as usize + 7) / 8) as usize; let packed_mod3_poly_bytes_len = (p.n + 4)/5; let packed_mod_q_poly_bytes_len = (p.n * p.q_bits as u16 + 7)/8; let hash_bytes_len = 64; let pubkey_packed_bytes_len = 2 + oid_bytes_len + packed_mod_q_poly_bytes_len as usize + hash_bytes_len; let privkey_packed_bytes_len = 2 + oid_bytes_len + 2 * packed_product_from_bytes_len as usize + packed_mod3_poly_bytes_len as usize; NTRUMLS { p, pubkey_packed_bytes_len, privkey_packed_bytes_len, } } } pub fn generate_keypair(&self) -> Option<(PrivateKey, PublicKey)> { unsafe { let p = &self.p; let privkey_blob_len = &mut (self.privkey_packed_bytes_len as isize) as *mut isize; let pubkey_blob_len = &mut (self.pubkey_packed_bytes_len as isize) as *mut isize; let mut privkey_blob = vec![0u8; *privkey_blob_len as usize]; let mut pubkey_blob = vec![0u8; *pubkey_blob_len as usize]; let rc = ffi::pq_gen_key(p as *const PQParamSet, privkey_blob_len, privkey_blob.as_mut_ptr(), pubkey_blob_len, pubkey_blob.as_mut_ptr()); if rc != 0 { return None; } return Some((PrivateKey(privkey_blob), PublicKey(pubkey_blob))); } } pub fn unpack_fg_from_private_key(&self, sk: &PrivateKey) -> Option<Vec<u16>> { let p = &self.p; let product_form_bytes_len = 2*(p.d1 + p.d2 + p.d3) as usize; let mut f_blob = vec![0u16; product_form_bytes_len as usize]; let mut g_blob = vec![0u16; product_form_bytes_len as usize]; unsafe { let rc = ffi::unpack_private_key(p as *const PQParamSet, f_blob.as_mut_ptr(), g_blob.as_mut_ptr(), std::ptr::null_mut(), self.privkey_packed_bytes_len as isize, sk.0.as_ptr()); if rc == 0 { let mut vec = Vec::<u16>::new(); vec.splice(.., f_blob.iter().cloned()); let offset = vec.len(); vec.splice(offset.., g_blob.iter().cloned()); return Some(vec); } None } } /** * Calculates keypair from 'fg' (concatenated ring elements 'f' and 'g') */ pub fn generate_keypair_from_fg(&self, fg: &[u16]) -> Option<(PrivateKey, PublicKey)> { unsafe { let p = &self.p; let d = ((p.d1 + p.d2 + p.d3) * 4) as usize; assert_eq!(d, fg.len()); let privkey_blob_len = &mut (self.privkey_packed_bytes_len as isize) as *mut isize; let pubkey_blob_len = &mut (self.pubkey_packed_bytes_len as isize) as *mut isize; let mut privkey_blob = vec![0u8; *privkey_blob_len as usize]; let mut pubkey_blob = vec![0u8; *pubkey_blob_len as usize]; let rc = ffi::pq_gen_key_fg(p as *const PQParamSet, fg.as_ptr(), privkey_blob_len, privkey_blob.as_mut_ptr(), pubkey_blob_len, pubkey_blob.as_mut_ptr()); if rc != 0 { return None; } return Some((PrivateKey(privkey_blob), PublicKey(pubkey_blob))); } } pub fn sign(&self, msg: &[u8], sk: &PrivateKey, pk: &PublicKey) -> Option<Signature> { unsafe { let p = &self.p; let mut sig_len = (((p.n * (p.q_bits-1) as u16) + 7)/8) as usize; let mut sig = vec![0u8; sig_len]; let rc = ffi::pq_sign(&mut sig_len as *mut usize, (&mut sig).as_mut_ptr(), sk.0.len(), sk.0.as_ptr(), pk.0.len(), pk.0.as_ptr(), msg.len(), msg.as_ptr()); if rc != 0 { return None; } return Some(Signature(sig)); } } pub fn verify(&self, msg: &[u8], sig: &Signature, pk: &PublicKey) -> bool { unsafe { 0 == ffi::pq_verify(sig.0.len(), sig.0.as_ptr(), pk.0.len(), pk.0.as_ptr(), msg.len(), msg.as_ptr()) } } } #[cfg(test)] pub mod tests { use super::NTRUMLS; use serde_json; #[test] fn capabilities() { let ntrumls = NTRUMLS::with_param_set(super::PQParamSetID::Security269Bit); let (sk, pk) = ntrumls.generate_keypair().expect("failed to generate keypair"); let fg = ntrumls.unpack_fg_from_private_key(&sk).expect("failed to get Fg"); let (sk2, pk2) = ntrumls.generate_keypair_from_fg(&fg).expect("failed to generate keypair \ from Fg"); assert_eq!(sk, sk2); assert_eq!(pk, pk2); let msg = "TEST MESSAGE"; let sig = ntrumls.sign(msg.as_bytes(), &sk, &pk).expect("failed to generate signature"); assert!(ntrumls.verify(msg.as_bytes(), &sig, &pk)); } #[test] fn serde() { let ntrumls = NTRUMLS::with_param_set(super::PQParamSetID::Security269Bit); let (sk, pk) = ntrumls.generate_keypair().expect("failed to generate keypair"); let pk_se = serde_json::to_string(&pk).expect("failed to serialize public key"); let pk_de = serde_json::from_str::<::PublicKey>(&pk_se).expect("failed to deserialize public key"); let sk_se = serde_json::to_string(&sk).expect("failed to serialize private key"); let sk_de = serde_json::from_str::<::PrivateKey>(&sk_se).expect("failed to deserialize private key"); } }
#![cfg_attr(not(feature = "std"), no_std)] use ink_lang as ink; #[ink::contract] mod PubCommentsChain { //参评者信息 #[ink(storage)] pub struct Participant { evaScore: f32, forecastBoxOffice: u64, participantfee: u64, participantRankScore u64, } //每场电影评定活动信息 #[ink(storage)] pub struct EvaActivity { sponsor: storage::Value<AccountId>,//活动发起者 filmScore: u8, //影评 darkHorseNum: u8,//黑马指数 //1表示评定状态(加密提交评定阶段);2表示加密数据解密阶段(明文提交评定阶段) 3.等待阶段 4.表示活动彻底关闭阶段 activityState: u8, participateNum: u32, //参与人数 participateAgainNum: u32, bonus: storage::Value<Balance>, pollToken: u32, pollDOT: u32, //DOT奖金池 totalScore: u64,//该电影所有参与者的影评总分 totalForecastBoxOffice: u64,//总的票房预测,单位为万, realFilmBoxOffice: u64, //实际票房 participantDataMap: storage::HashMap<AccountId,PubCommentsChain::Participant>,//所有参与者评分映射。 participantAddress: Vec<AccountId>, //用于获得上述map中所有元素 //参与者排名,之所以不放到上面的参与者数据中是因为排名只需要前30%即可,这样可以节省一些数据 partticipantRank: storage::HashMap<AccountId,u32> } // / Defines the storage of your contract. - huanglong #[ink(storage)] pub struct PubCommentsChain { // 技术地址 techAddr: storage::Value<AccountId>, //技术地址拿的总额度 totalTechAmount: storage::Value<Balance>, // 电影ID => 评定活动数据 filmEvaActivityMap: storage::HashMap<String,PubCommentsChain::EvaActivity>, //地址=>参评者数据。 participantMap: storage::HashMap<AccountId,PubCommentsChain::Participant>, //用户拥有的未提现token.之所以要这个是为了用户积累到一定数目的token后再进行体现,减少网络费用。 participantOwnTokenMap: storage::HashMap<AccountId,Balance>, filmBeEvaNum: u64, } //添加一些事件 #[ink(event)] struct Transfer { #[ink(topic)] from: Option<AccountId>, #[ink(topic)] to: Option<AccountId>, #[ink(topic)] value: Balance, } impl PubCommentsChain { // / Constructor func before 550loc - tanglinfeng // 构造函数 #[ink(constructor)] pub fn constructor(&mut self, _techAddr:AccountId) -> { // 高版本不需要public self.techAddr = _techAddr; return true; } /** * @dev 发起评定活动。 * @param filmId 电影ID */ #[ink(message)] fn createEvaActivityWithToken(&self,filmId:String, value:Balance) ->bool{ //注意在智能合约中如果函数添加payable,那么就会在生成封装类时会自动把value这个参数加入到入参中。 if(value>=10){ //看是否需要注册 // filmEvaActivityMap[filmId].tokenPoll+=value; //下面的有问题。 // SafeMath.add(FilmEvaActivity[filmId].tokenPoll,value); let msgSender = self.env().caller(); //消息发送者 //需要先创建activityMAP!!!,这里有点不一样。 let evaActivity:PubCommentsChain::EvaActivity; self.filmEvaActivityMap.insert(filmId,evaActivity); let mut tokenPoll=self.filmEvaActivityMap.get(filmId).pollToken+value; self.filmEvaActivityMap.get(filmId).pollToken=tokenPoll; // address sponsorAddress=msg.sender; // address payable sponsorAddress2=address( uint160(sponsorAddress)); // FilmEvaActivity[filmId].sponsor=address( uint160(sponsorAddress)); self.filmEvaActivityMap.get(filmId).sponsor=msgSender; //token的bonus是否需要?? //这里可能需要判别一下当前是否已经有owner及bonus了 // FilmEvaActivity[filmId].bonus=_eth; self.filmEvaActivityMap.get(filmId).activityState=1; //评定进行状态 //还需要记录一下结束时间。包括评定二次提交时间。 return true; } return false; } //把DOT作为活动发起奖金 #[ink(message)] fn createEvaActivityBonusDOT(&self,filmId:String, value:Balance) ->bool { //活动发起者可以参考这个函数 if(value>0){ let msgSender = self.env().caller(); //消息发送者 self.filmEvaActivityMap.get(filmId).ethPoll=filmEvaActivityMap[filmId].ethPoll.add(msg.value); let mut pollDOT=self.filmEvaActivityMap.get(filmId).pollDOT+value; self.filmEvaActivityMap.get(filmId).pollDOT=pollDOT; //这里可能需要判别一下当前是否已经有owner及bonus了 self.filmEvaActivityMap.get(filmId).bonus=value; // //注册用户 // register(msgSender, _superiorAddr); //之所以需要这个是因为这个可以直接发起,当庄时必须要是注册用户。 return true; } return false; } //这个状态是根据时间段来调用设置的, #[ink(message)] fn setActivityState(&self,filmId:String, activityState: u8)->bool{ //注意切换到状态2时必须保证参与人数达到最小值1000以上,不然活动失败,返还所有参与人的费用。 self.filmEvaActivityMap.get(filmId).activityState=activityState; // if((self.filmEvaActivityMap.get(filmId).activityState==3)&&(activityState==4)){ //活动顺利完成 // let filmBeEvaNum=self.filmBeEvaNum+1; // self.filmBeEvaNum=filmBeEvaNum; // } return true; } /** * @dev 争夺发起者,创建合约及争夺时都可以调用这个函数 * @param filmId 电影Id */ #[ink(message)] fn sponsorFight(&self,filmId:String,value:Balance) ->bool { //注意bonus需要统一一下到底是用什么币或者多种币 let msgSender = self.env().caller(); //消息发送者 if(self.filmEvaActivityMap.get(filmId).activityState!=4){ // 调用撤回资金的核心方法 // uint _ethBonus=msg.value; if(value>self.filmEvaActivityMap.get(filmId).bonus){ if(self.filmEvaActivityMap.get(filmId).bonus.bonus!=0){ // 返还出价时,简单地直接调用 highestBidder.send(highestBid) 函数, // 是有安全风险的,因为它有可能执行一个非信任合约。 // 更为安全的做法是让接收方自己提取金钱。 // sponsorReturns[FilmEvaActivity[filmId].sponsor] += FilmEvaActivity[filmId].bonus; //活动的发起者退回到原先发起者的转户资金处 // FilmEvaActivity[filmId].sponsor.transfer(FilmEvaActivity[filmId].bonus); //直接发送 self.filmEvaActivityMap.get(filmId).bonus=value; let pollDOT=self.filmEvaActivityMap.get(filmId).pollDOT-self.filmEvaActivityMap.get(filmId).bonus; self.filmEvaActivityMap.get(filmId).pollDOT =pollDOT; //奖金池先减去原来bonus } // payable(msgSender).transfervalue); //真实转账操作 self.filmEvaActivityMap.get(filmId).bonus=value; //奖金池改变 let pollDOT=self.filmEvaActivityMap.get(filmId).pollDOT+value; self.filmEvaActivityMap.get(filmId).pollDOT =pollDOT; //奖金池再加上新的bonus self.filmEvaActivityMap.get(filmId).sponsor=msgSender; return true; } } return false; } //首次提交加密评定 #[ink(message)] fn participateActivityWithBlind(&self,filmId:String, _hashScore:u32, _hashBoxOffice:u32, feeValue:Balance)->bool { if((self.filmEvaActivityMap.get(filmId)==1) &&(feeValue>1)){ let msgSender = self.env().caller(); //消息发送者 //获得参与者数据 // let participantData=self.filmEvaActivityMap.get(filmId).participantDataMap.get(msgSender); self.filmEvaActivityMap.get(filmId).participantAddress.push(msg.sender); //记录所有地址数据 // ButtToken(_tokenAddr).transfer(address(this), feeValue); //token实际转账,这里就必须先把账转到Token合约中,这样才能再转到本合约中 self.filmEvaActivityMap.get(filmId).participantDataMap.get(msgSender).hashEvaScore=_hashScore; self.filmEvaActivityMap.get(filmId).participantDataMap.get(msgSender).hashForecastBoxOffice=_hashBoxOffice; self.filmEvaActivityMap.get(filmId).participantDataMap.get(msgSender).participantfee=feeValue; //这个费用是扣除转账费用后的参加评定的费用 //下面数据必须在提交加密数据时就赋值,这些值需要较早的显示。 let participateNum=self.filmEvaActivityMap.get(filmId).participateNum+1; filmEvaActivityMap[filmId].participateNum =participateNum; //资金池需要修改 let pollToken=filmEvaActivityMap[filmId].pollToken+feeValue; filmEvaActivityMap[filmId].tokenPoll=pollToken; return true; } return false; } //第二次提交明文评定 。为了让用户体验更好,用户可以托管自己的评定到中心化后台,也可以自己在规定时间二次提交(加密数据一起都可以托管过来,) #[ink(message)] fn participateActivityWithReveal(&self,filmId:String, score:u32, forecastBoxOffice:u32) ->bool { //检验活动是否在进行 if(self.filmEvaActivityMap.get(filmId).activityState==2){ //注意这里还要实现加密加密校验!!!!!!!!! let msgSender = self.env().caller(); //消息发送者 //引用变量 // Data.ParticipantActivityData storage participantData=filmEvaActivityMap[filmId].participantDataMap[msg.sender]; self.filmEvaActivityMap.get(filmId).participantDataMap.get(msgSender).evaScore=score; self.filmEvaActivityMap.get(filmId).participantDataMap.get(msgSender).forecastBoxOffice=forecastBoxOffice; let totalScore=self.filmEvaActivityMap.get(filmId).totalScore+score; self.filmEvaActivityMap.get(filmId).totalScore =totalScore; let totalForecastBoxOffice=self.filmEvaActivityMap.get(filmId).totalForecastBoxOffice+forecastBoxOffice; self.filmEvaActivityMap.get(filmId).totalForecastBoxOffice =totalForecastBoxOffice; let participateAgainNum=self.filmEvaActivityMap.get(filmId).participateAgainNum+1; self.filmEvaActivityMap.get(filmId).participateAgainNum =participateAgainNum; return true; } return false; //加一个事件监听结果 } /** 评定阶段结束。 */ #[ink(message)] fn EvaActivityEnd(&self,filmId:String) ->bool{ //这里做一个时间判断,保证安全。 // require(block.timestamp>=FilmEvaActivity[filmId].endTime,"Evaluate activity has not reach the end time"); //活动必须处在revual阶段才可以进行结束 require(FilmEvaActivity[filmId].activityState!=2, "Evaluate state has already end."); if( self.filmEvaActivityMap.get(filmId).activityState!=2 ){ self.filmEvaActivityMap.get(filmId).activityState=3; //触发评分计算函数。 calculateFilmScore(filmId); let filmBeEvaNum=self.filmEvaActivityMap.get(filmId).filmBeEvaNum+1; self.filmEvaActivityMap.get(filmId).filmBeEvaNum=filmBeEvaNum; //一次评定完成,统计已经评定电影次数。 return true; } return false; } //let calcuateFactor: u32= 100; // 浮点计算放大因子,也就是说只保留两位小数。最终在最终值中除以100即可。 // 票房折合函数,实现票房折合为票房分,这个需要根据票房的实际数据确定函数,目前暂定一个线性函数 #[ink(message)] pub fn boxoffice2Score(&self, BoxOffice: u32) -> u32 { // 注意传入的票房单位为:千万 let mut boxOfficeScore: u32= 0; if BoxOffice < 100 { boxOfficeScore = BoxOffice/25 +3; } else { boxOfficeScore = 10; } return boxOfficeScore; } // 影评计算函数 pub fn calculateFilmScore(&self, filmId:String) { // 计算平均分,需要实现浮点数据,数据类型后面具体解决 let averageScore: u32 = self.filmEvaActivityMap.get(filmId).totalScore/self.filmEvaActivityMap.get(filmId).participateAgainNum; let averageForecastBoxOffice: u32 = self.filmEvaActivityMap.get(filmId).totalForecastBoxOffice/self.filmEvaActivityMap.get(filmId).participateAgainNum; // 计算最终影评分,当前采用线性函数进行关联两个因子 let boxOfficeScore: u32 = boxoffice2Score(averageForecastBoxOffice); // 根据平均主观评分和折算的票房预测分折算为最终的影评评分。 // 由于涉及到浮点数,且这部分为独立函数,后面找到最优浮点数计算方法后补充即可。 // if ){ // } // FilmEvaActivity[filmId].filmScore= } // 这个函数的触发有两种方案:一个是中心化触发,一个是去中心化触发。 // 电影下映或者达到最长时间时触发实际票房上传 #[ink(message)] pub fn setFilmRealBoxOffice(&self, filmId:String, realBoxOffice: u32) { self.filmEvaActivityMap.get(filmId).realFilmBoxOffice=realBoxOffice; // 调用参评者排名得分函数 calculateRankScore(filmId); // 调用计算排名函数 // 获得挖矿奖励 getTokenReward(filmId); // 根据获奖名单排名分发所有奖励 // 活动策底结束 } // 奖励算法 pub fn calculateRankScore(&self, filmId:String) { // 下述权重化为整型,解决浮点问题 let subWeight: u32 = 4; // 主观评分权重 let objWeight: u32 = 2; // 客观票房预测权重 let subAndObjWeight: u32 = 4; // 主客观权重 let AvFactory: u32 = 500; // 放大因子 let mut scoreCoefficient: u32; let mut boxOfficeCoefficient: u32; let mut subAndObjCoefficient: u32; let mut averageScore: u32 = self.filmEvaActivityMap.get(filmId).totalScore/self.filmEvaActivityMap.get(filmId).participateAgainNum; let mut averageForecastBoxOffice: u32 = self.filmEvaActivityMap.get(filmId).totalForecastBoxOffice/self.filmEvaActivityMap.get(filmId).participateAgainNum; let mut realFilmBoxOfficeScore: u32 = boxoffice2Score(self.filmEvaActivityMap.get(filmId).realFilmBoxOffice); // 把实际票房转换为票房分 // 这里分数暂时有最简单的线性除法计算各个因子的得分值。 let mut i = 0; while i < self.filmEvaActivityMap.get(filmId).participantAddress.len() { i += 1; // 变量引用 let msgSender = self.env().caller(); //消息发送者 //Data.ParticipantActivityData participantData=self.filmEvaActivityMap.get(filmId).participantDataMap[self.filmEvaActivityMap.get(filmId).participantAddress[i]]; if (self.filmEvaActivityMap.get(filmId).participantDataMap.get(msgSender).evaScore != 0) && (self.filmEvaActivityMap.get(filmId).participantDataMap.get(msgSender).forecastBoxOffice != 0) { let participantScore: u32 = self.filmEvaActivityMap.get(filmId).participantDataMap.get(msgSender).evaScore; let participantBoxOffice: u32 = self.filmEvaActivityMap.get(filmId).participantDataMap.get(msgSender).forecastBoxOffice; let forecastBoxOfficeScore: u32 = boxoffice2Score(participantBoxOffice); let averageScoreBoxOffice: u32 = (participantScore+forecastBoxOfficeScore)/2; if participantScore<averageScore{ scoreCoefficient = subWeight*AvFactory*(averageScore-participantScore)/averageScore; } else { scoreCoefficient = subWeight*AvFactory*(participantScore-averageScore)/averageScore; } if participantBoxOffice < averageForecastBoxOffice{ boxOfficeCoefficient = objWeight*AvFactory*(averageForecastBoxOffice-participantBoxOffice)/averageForecastBoxOffice; } else { boxOfficeCoefficient = objWeight*AvFactory*(participantBoxOffice-averageForecastBoxOffice)/averageForecastBoxOffice; } // 主客观误差,先按照最简单的方法实现 if averageScoreBoxOffice<realFilmBoxOfficeScore){ subAndObjCoefficient=(realFilmBoxOfficeScore-averageScoreBoxOffice) / realFilmBoxOfficeScore; }else{ subAndObjCoefficient=(averageScoreBoxOffice-realFilmBoxOfficeScore) / realFilmBoxOfficeScore; } self.filmEvaActivityMap.get(filmId).participantDataMap.get(msgSender).participantRankScore = scoreCoefficient+boxOfficeCoefficient+subAndObjCoefficient; } } } // 根据最终影评、实际票房及参与人数计算token挖矿收益并放入到奖金池中。 #[ink(message)] pub fn getTokenReward(&self, filmId:String, realBoxOffice: u32) { let reduceNumConstant: u8 = 200; // 每200部电影减半一次 let startTokenNum: u32 = 45000000; // 9千万进行挖矿,一千万进行预挖 let participantsMin: u32 = 1000; let averageBoxOfficInBase: u32 = 50; // 影视库中的均值票房5亿 let filmScore:u8 = self.filmEvaActivityMap.get(filmId).filmScore; let filmBoxOffice: u32 = self.filmEvaActivityMap.get(filmId).realFilmBoxOffice; let participants: u32 = self.filmEvaActivityMap.get(filmId).participateNum; let reduceNum: u32 = self.filmEvaActivityMap.get(filmId).filmBeEvaNum/reduceNumConstant; // 根据减半情况,计算本次影评能够挖到矿的总额。 // let countNum=reduceNum<<1; // 2^reduceNum let averageToken: u32 =startTokenNum/2.pow(reduceNum); // 影响因子的乘机 let mut tokenCalcuateNum: u32 = (participants/participantsMin)*(filmBoxOffice/averageBoxOfficInBase)*(filmScore/5); // 按照对数对tokenCalcuateNum计算数值 let mut logCalculateNum: u32 ; if tokenCalcuateNum>=2.pow(128) {tokenCalcuateNum>>=128;logCalculateNum+=128;} if tokenCalcuateNum>=2.pow(64) {tokenCalcuateNum>>=64;logCalculateNum+=64;} if tokenCalcuateNum>=2.pow(32) {tokenCalcuateNum>>=32;logCalculateNum+=32;} if tokenCalcuateNum>=2.pow(16) {tokenCalcuateNum>>=16;logCalculateNum+=16;} if tokenCalcuateNum>=2.pow(8) {tokenCalcuateNum>>=8;logCalculateNum+=8;} if tokenCalcuateNum>=2.pow(4) {tokenCalcuateNum>>=4;logCalculateNum+=4;} if tokenCalcuateNum>=2.pow(2) {tokenCalcuateNum>>=2;logCalculateNum+=2;} if tokenCalcuateNum>=2pow(1) {/*x>>=1;*/logCalculateNum+=1;} let tokenReward = averageToken+averageToken*logCalculateNum; self.filmEvaActivityMap.get(filmId).tokenPoll+=tokenReward; } // 用户自己触发获得奖励。该函数触发涉及转账是需要消耗 #[ink(message)] pub fn getReward(_tokenAddr: address, to: address){ ButtToken(_tokenAddr).distrabuteToken(to,participantOwnerTokenMap[to]); } // 获取对应活动的数据,主要是全局数据,参与人、评定数据等,放到一起一次性获得。 #[ink(message)] pub fn getParticipantNum(&self, filmId:String) -> u32{ return self.filmEvaActivityMap.get(filmId).participateNum; } #[ink(message)] pub fn getTokenPoll(filmId: memory) -> u32{ FilmEvaActivity[filmId].tokenPoll; } #[ink(message)] pub fn getEvaActivityData(filmId: memory) -> u32{ FilmEvaActivity[filmId].tokenPoll; } // getEvaActivityData和getParticipantActivityData多返回值待处理 }   // / Unit tests in Rust are normally defined within such a `#[cfg(test)]`     // / module and test functions are marked with a `#[test]` attribute.     // / The below code is technically just normal Rust code.     #[cfg(test)]     mod tests {         // / Imports all the definitions from the outer scope so we can use them here.         use super::*;         // / Imports `ink_lang` so we can use `#[ink::test]`.         use ink_lang as ink;         // / We test if the default constructor does its job.         #[ink::test]         fn test_createEvaActivityWithToken() {             assert_eq!(PubCommentsChain.createEvaActivityWithToken("20210520GZJ",100), true);         }         #[ink::test]         fn test_setActivityState() {             assert_eq!(PubCommentsChain.setActivityState("20210520GZJ",1), true);         }                  #[ink::test]         fn test_sponsorFight() {             assert_eq!(PubCommentsChain.sponsorFight("20210520GZJ",20), true);         }         #[ink::test]         fn test_participateActivityWithReveal() {             assert_eq!(PubCommentsChain.participateActivityWithReveal("20210520GZJ",8,100000), true);         }     } }
// 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 std::time::Duration; use fuchsia_criterion::{criterion, FuchsiaCriterion}; fn fibonacci(n: u64) -> u64 { match n { 0 => 1, 1 => 1, n => fibonacci(n - 1) + fibonacci(n - 2), } } fn main() { let mut c = FuchsiaCriterion::new( criterion::Criterion::default() .warm_up_time(Duration::new(0, 0)) .measurement_time(Duration::from_millis(1)), ); c.bench_function("fib 10", |b| b.iter(|| fibonacci(criterion::black_box(10)))); }
use register::*; use shared::*; use instructions::*; use mmu; use std::rc::*; use std::cell::*; use std::boxed::Box; use log; pub struct Cpu { ///CPU register register: CpuRegister, ///stupid hack way to not increment PC after jumping jumped: bool, ///are we halted for interrupts? halted: bool, } ///ALU logic impl Cpu { ///Adds an immediate ubyte to the A register with optional carry /// Sets Z,C,N(0),H fn add8(&mut self, reg: Reg8Name, imm: Du8, use_carry: bool) { let (res, carry, half) = add( self.register.get_reg8(reg.clone()), imm, use_carry & self.register.flag_is_set(BitFlag::C), ); self.register.set_flag_b(BitFlag::C, carry); self.register.set_flag_b(BitFlag::H, half); self.register.set_flag_b(BitFlag::Z, res == 0); self.register.set_flag_b(BitFlag::N, false); self.register.set_reg8(reg, res); } ///Subtracts an immediate ubyte from the A register with optional carry ///Sets Z,C,N(1),H fn sub8(&mut self, reg: Reg8Name, imm: Du8, use_carry: bool) { let (res, carry, half) = sub( self.register.get_reg8(reg.clone()), imm, use_carry & self.register.flag_is_set(BitFlag::C), ); self.register.set_flag_b(BitFlag::C, carry); self.register.set_flag_b(BitFlag::H, half); self.register.set_flag_b(BitFlag::Z, res == 0); self.register.set_flag_b(BitFlag::N, true); self.register.set_reg8(reg, res); } ///Logical AND with A register ///Sets Z,C(0),N(0),H(1) fn and8(&mut self, reg: Reg8Name, imm: Du8) { let val = self.register.get_reg8(reg.clone()) & imm; self.register.set_reg8(reg, val); if val == 0 { self.register.set_flag(BitFlag::Z); } self.register.set_flag(BitFlag::H); self.register.clear_flag(BitFlag::C); self.register.clear_flag(BitFlag::N); } ///Logical OR with A register ///Sets Z, C(0), N(0), H(0) fn or8(&mut self, reg: Reg8Name, imm: Du8) { let val = self.register.get_reg8(reg.clone()) | imm; self.register.set_reg8(reg, val); if val == 0 { self.register.set_flag(BitFlag::Z); } self.register.clear_flag(BitFlag::H); self.register.clear_flag(BitFlag::C); self.register.clear_flag(BitFlag::N); } ///Logical XOR with A register ///Sets Z, C(0), N(0), H(0) fn xor8(&mut self, reg: Reg8Name, imm: Du8) { let val = self.register.get_reg8(reg.clone()) ^ imm; self.register.set_reg8(reg, val); if val == 0 { self.register.set_flag(BitFlag::Z); } self.register.clear_flag(BitFlag::H); self.register.clear_flag(BitFlag::C); self.register.clear_flag(BitFlag::N); } ///Compares operand with A register by subtracting from A register ///Does not change A register, just flags ///Sets Z,C,N(1),H fn cp8(&mut self, reg: Reg8Name, imm: Du8) { let (res, carry, half) = sub(self.register.get_reg8(reg), imm, false); self.register.set_flag_b(BitFlag::C, carry); self.register.set_flag_b(BitFlag::H, half); self.register.set_flag_b(BitFlag::Z, res == 0); self.register.set_flag_b(BitFlag::N, true); } ///Increases the referenced value by one ///Sets Z,N(0),H fn inc8(&mut self, byte: &mut u8) { let val = match byte.clone() { 0xFF => 0, x => x + 1, }; *byte = val; self.register.set_flag_b(BitFlag::Z, *byte == 0); if nth_bit(val, 3) { self.register.set_flag(BitFlag::H); } self.register.clear_flag(BitFlag::N); } ///Increases the referenced register by one ///Sets Z,N(0),H fn inc8_reg(&mut self, reg: Reg8Name) { let val = match self.register.get_reg8(reg.clone()) { 0xFF => 0, x => x + 1, }; self.register.set_reg8(reg, val); self.register.set_flag_b(BitFlag::Z, val == 0); if nth_bit(val, 3) { self.register.set_flag(BitFlag::H); } self.register.clear_flag(BitFlag::N); } ///Decreases the referenced value by one ///Sets Z, N(0), H fn dec8(&mut self, byte: &mut u8) { let val = match byte.clone() { 0 => 0xFF, x => x - 1, }; *byte = val; if val == 0 { self.register.set_flag(BitFlag::Z); } if nth_bit(val, 3) { self.register.set_flag(BitFlag::H); } self.register.clear_flag(BitFlag::N); } ///Decreases the referenced value by one ///Sets Z, N(0), H fn dec8_reg(&mut self, reg: Reg8Name) { let val = match self.register.get_reg8(reg.clone()) { 0 => 0xFF, x => x - 1, }; self.register.set_reg8(reg, val); if val == 0 { self.register.set_flag(BitFlag::Z); } if nth_bit(val, 3) { self.register.set_flag(BitFlag::H); } self.register.clear_flag(BitFlag::N); } ///This instruction adds the contents of the given register pair to register pair HL ///Sets C, N(0) fn add16(&mut self, reg: Reg16Name, imm: u16) { let val = self.register.get_reg16(reg.clone()) as u32 + imm as u32; if val > 0xffff { self.register.set_flag(BitFlag::C) } self.register.clear_flag(BitFlag::N); self.register.set_reg16(reg, val as u16); } ///Increments the value of the given register pair ///Sets {} fn inc16(&mut self, reg: Reg16Name) { let val = match self.register.get_reg16(reg.clone()) { 0xffff => 0, x => x + 1, }; self.register.set_reg16(reg, val); } ///Decreases the value of the given register pair ///Sets {} fn dec16(&mut self, reg: Reg16Name) { let val = match self.register.get_reg16(reg.clone()) { 0 => 0xffff, x => x - 1, }; self.register.set_reg16(reg, val); } ///Rotate Left Circular Accumulator. This instruction rotates A left one bit, placing bit 7 at bit 0 AND in the Carry flag. ///Sets: C, N(0),H(0) fn rlca(&mut self) { let newcarry = nth_bit(self.register.a.clone(), 7); self.register.set_flag_b(BitFlag::C, newcarry); self.register.a = self.register.a.rotate_left(1); self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); } ///Rotate Left Circular. This instruction rotates either register r of the byte located at the address in HL left one bit, placing bit 7 at bit 0 AND in the Carry flag. /// Sets Z,C,N(0),H(0) fn rlc(&mut self, byte: &mut u8) { self.register .set_flag_b(BitFlag::C, nth_bit(byte.clone(), 7)); *byte = byte.rotate_left(1); self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, *byte == 0); } ///Rotate Left Circular. This instruction rotates either register r of the byte located at the address in HL left one bit, placing bit 7 at bit 0 AND in the Carry flag. /// Sets Z,C,N(0),H(0) fn rlc_reg(&mut self, reg: Reg8Name) { let old = self.register.get_reg8(reg.clone()).clone(); let new = old.clone().rotate_left(1); self.register.set_reg8(reg, new); self.register.set_flag_b(BitFlag::C, nth_bit(old, 7)); self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, new == 0); } /// Rotate Left Accumulator. This instruction rotates A left one bit, placing bit 7 into the Carry flag and the contents of the Carry flag into bit 0 of A /// Sets C,N(0),H(0) fn rla(&mut self) { let newcarry = nth_bit(self.register.a.clone(), 7); let carry: u8 = self.register.flag_is_set(BitFlag::C) as u8; self.register.set_flag_b(BitFlag::C, newcarry); self.register.a = (self.register.a << 1) | carry; self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); } /// Rotate Left. This instruction rotates either the byte located at the address in HL left one bit, placing bit 7 into the Carry flag and the contents of the Carry flag into bit 0 of A /// Sets Z,C,N(0),H(0) fn rl(&mut self, byte: &mut u8) { let carry: u8 = self.register.flag_is_set(BitFlag::C) as u8; self.register .set_flag_b(BitFlag::C, nth_bit(byte.clone(), 7)); *byte = (*byte << 1) | carry; self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, *byte == 0); } /// Rotate Left. This instruction rotates the register L left one bit, placing bit 7 into the Carry flag and the contents of the Carry flag into bit 0 of A /// Sets Z,C,N(0),H(0) fn rl_reg(&mut self, reg: Reg8Name) { let old = self.register.get_reg8(reg.clone()); let carry: u8 = self.register.flag_is_set(BitFlag::C) as u8; let new = old.clone() << 1 | carry; self.register .set_flag_b(BitFlag::C, nth_bit(old.clone(), 7)); self.register.set_reg8(reg, new); self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, new == 0); } /// Rotate Right Circular Accumulator. This instruction rotates A right one bit, placing bit 0 at bit 7 AND in the Carry flag. /// Sets C,N(0),H(0) fn rrca(&mut self) { let newcarry = nth_bit(self.register.a.clone(), 0); self.register.set_flag_b(BitFlag::C, newcarry); self.register.a = self.register.a.rotate_right(1); self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); } /// Rotate Right Circular. This instruction rotates the byte located at the address in HL right one bit, placing bit 0 at bit 7 AND in the Carry flag. /// Sets Z,C,N(0),H(0) fn rrc(&mut self, byte: &mut u8) { self.register .set_flag_b(BitFlag::C, nth_bit(byte.clone(), 0)); *byte = byte.rotate_right(1); self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, *byte == 0); } /// Rotate Right Circular. This instruction rotates the register right one bit, placing bit 0 at bit 7 AND in the Carry flag. /// Sets Z,C,N(0),H(0) fn rrc_reg(&mut self, reg: Reg8Name) { let old = self.register.get_reg8(reg.clone()); let new = old.rotate_right(1); self.register.set_flag_b(BitFlag::C, nth_bit(old, 0)); self.register.set_reg8(reg, new); self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, new == 0); } /// Rotate Right Accumulator. This instruction rotates A right one bit, placing bit 0 into the Carry flag and the contents of the Carry flag into bit 7 of A /// Sets C,N(0),H(0) fn rra(&mut self) { let newcarry = nth_bit(self.register.a.clone(), 0); let carry: u8 = (self.register.flag_is_set(BitFlag::C) as u8) << 7; self.register.set_flag_b(BitFlag::C, newcarry); self.register.a = (self.register.a >> 1) | carry; self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); } /// Rotate Right. This instruction rotates either register r or the byte located at the address in HL right one bit, placing bit 0 into the Carry flag and the contents of the Carry flag into bit 7 of A /// Sets Z,C,N(0),H(0) fn rr(&mut self, byte: &mut u8) { let carry: u8 = (self.register.flag_is_set(BitFlag::C) as u8) << 7; self.register .set_flag_b(BitFlag::C, nth_bit(byte.clone(), 0)); *byte = (*byte >> 1) | carry; self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, *byte == 0); } /// Rotate Right. This instruction rotates either register r or the byte located at the address in HL right one bit, placing bit 0 into the Carry flag and the contents of the Carry flag into bit 7 of A /// Sets Z,C,N(0),H(0) fn rr_reg(&mut self, reg: Reg8Name) { let old = self.register.get_reg8(reg.clone()); let carry: u8 = (self.register.flag_is_set(BitFlag::C) as u8) << 7; let new = old >> 1 | carry; self.register.set_flag_b(BitFlag::C, nth_bit(old, 0)); self.register.set_reg8(reg, new); self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, new == 0); } /// Shift Left Arithmetically. This instruction shifts either register r or the byte located at the address in HL left one bit, placing 0 into bit 0, and placing bit 7 into the Carry flag. /// Sets Z,C,N(0),H(0) fn sla(&mut self, byte: &mut u8) { self.register .set_flag_b(BitFlag::C, nth_bit(byte.clone(), 7)); *byte = *byte << 1; self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, *byte == 0); } /// Shift Left Arithmetically. This instruction shifts either register r or the byte located at the address in HL left one bit, placing 0 into bit 0, and placing bit 7 into the Carry flag. /// Sets Z,C,N(0),H(0) fn sla_reg(&mut self, reg: Reg8Name) { let old = self.register.get_reg8(reg.clone()); let new = old << 1; self.register.set_flag_b(BitFlag::C, nth_bit(old, 7)); self.register.set_reg8(reg, new); self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, new == 0); } /// Shift Right Arithmetically. This instruction shifts either register r or the byte located at the address in HL right one bit, placing bit 0 into the Carry flag, and leaving bit 7 untouched. /// Sets Z,C,N(0),H(0) fn sra(&mut self, byte: &mut u8) { let mask = *byte & 0b10000000; self.register .set_flag_b(BitFlag::C, nth_bit(byte.clone(), 0)); *byte = (*byte >> 1) | mask; self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, *byte == 0); } /// Shift Right Arithmetically. This instruction shifts either register r or the byte located at the address in HL right one bit, placing bit 0 into the Carry flag, and leaving bit 7 untouched. /// Sets Z,C,N(0),H(0) fn sra_reg(&mut self, reg: Reg8Name) { let old = self.register.get_reg8(reg.clone()); let mask = old & 0b10000000; let new = old >> 1 | mask; self.register.set_flag_b(BitFlag::C, nth_bit(old, 0)); self.register.set_reg8(reg, new); self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, new == 0); } /// Shift Right Logically. This instruction shifts either register r or the byte located at the address in HL right one bit, placing 0 into bit 7, and placing bit 0 into the Carry flag. /// Sets Z,C,H(0),N(0) fn srl(&mut self, byte: &mut u8) { self.register .set_flag_b(BitFlag::C, nth_bit(byte.clone(), 0)); *byte = *byte >> 1; self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, *byte == 0); } /// Shift Right Logically. This instruction shifts either register r or the byte located at the address in HL right one bit, placing 0 into bit 7, and placing bit 0 into the Carry flag. /// Sets Z,C,H(0),N(0) fn srl_reg(&mut self, reg: Reg8Name) { let old = self.register.get_reg8(reg.clone()); let new = old >> 1; self.register.set_flag_b(BitFlag::C, nth_bit(old, 0)); self.register.set_reg8(reg, new); self.register.clear_flag(BitFlag::N); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::Z, new == 0); } ///Tests bit b in register r or the byte addressed in HL. Basically the specified bit gets copied to the Z flag AND INVERTED. ///Sets Z, N(0),H(1) fn bit(&mut self, byte: &mut u8, b: u8) { self.register.set_flag_b(BitFlag::Z, !nth_bit(*byte, b)); self.register.set_flag(BitFlag::H); self.register.clear_flag(BitFlag::N); } ///Tests bit b in register r or the byte addressed in HL. Basically the specified bit gets copied to the Z flag AND INVERTED. ///Sets Z, N(0),H(1) fn bit_reg(&mut self, reg: Reg8Name, b: u8) { let old = self.register.get_reg8(reg); self.register.set_flag_b(BitFlag::Z, !nth_bit(old, b)); self.register.set_flag(BitFlag::H); self.register.clear_flag(BitFlag::N); } ///Sets (1) bit b in register r or the byte addressed in HL. ///No flags fn set(&mut self, byte: &mut u8, b: u8) { *byte |= 1 << b; } ///Sets (1) bit b in register r or the byte addressed in HL. ///No flags fn set_reg(&mut self, reg: Reg8Name, b: u8) { let old = self.register.get_reg8(reg.clone()); self.register.set_reg8(reg, old | 1 << b); } ///Resets (0) bit b in register r or the byte addressed in HL. ///No flags fn reset(&mut self, byte: &mut u8, b: u8) { let mut mask: u8 = 0b11111110; mask.rotate_left(b as u32); *byte &= mask; } ///Resets (0) bit b in register r or the byte addressed in HL. ///No flags fn reset_reg(&mut self, reg: Reg8Name, b: u8) { let mut mask: u8 = 0b11111110; mask.rotate_left(b as u32); let old = self.register.get_reg8(reg.clone()); self.register.set_reg8(reg, old & mask); } } ///Instruction logic impl Cpu { pub fn new() -> Self { Cpu { register: CpuRegister::new(), jumped: false, halted: false, } } pub fn step(&mut self, mmu: &mut mmu::Mmu) { if !self.halted { let ins = decode(mmu, self.register.sp); self.register.pc += ins.clone().get_size() as u16; println!("{:?}", ins); self.run_ins(mmu, ins); } } pub fn run_ins(&mut self, mmu: &mut mmu::Mmu, ins: Instruction) { //reset internal jump flag self.jumped = false; use instructions::Instruction::*; use register::Reg16Name::HL; match ins { Nop => (), Halt => self.halted = true, Stop => (), SwapR8(reg) => swap8(self.register.get_reg8_ref(reg)), SwapAR16(reg) => { let v = swap16(self.register.get_reg16(reg.clone())); self.register.set_reg16(reg.clone(), v) } LdR8D8(reg, imm) => *self.register.get_reg8_ref(reg) = imm, LdR8A16(reg, addr) => *self.register.get_reg8_ref(reg) = mmu.read8(addr), LdA16R8(addr, reg) => mmu.write8(addr, self.register.get_reg8(reg)), LdR8R8(to, from) => { let val = self.register.get_reg8(from); self.register.set_reg8(to, val); } LdR16D16(reg, imm) => self.register.set_reg16(reg, imm), LdR16R16(to, from) => { let val = self.register.get_reg16(from); self.register.set_reg16(to, val); } LdAR16R8(add_reg, reg) => { let addr = self.register.get_reg16(add_reg); mmu.write8(addr, self.register.get_reg8(reg)); } LdAR16D8(reg, imm) => mmu.write8(self.register.get_reg16(reg), imm), LdR8AR16(to, from) => { let val = mmu.read8(self.register.get_reg16(from)); *self.register.get_reg8_ref(to) = val; } LdA16R16(to, from) => mmu.write16(to, self.register.get_reg16(from)), LdiAR16R8(to, from) => { let val = self.register.get_reg8(from); let addr = self.register.get_reg16(to.clone()); mmu.write8(addr, val); self.register.inc_reg16(to); } LddAR16R8(to, from) => { let val = self.register.get_reg8(from); let addr = self.register.get_reg16(to.clone()); mmu.write8(addr, val); self.register.dec_reg16(to); } LdiR8AR16(to, from) => { let addr = self.register.get_reg16(from.clone()); let val = mmu.read8(addr); self.register.set_reg8(to, val); self.register.inc_reg16(from); } LddR8AR16(to, from) => { let addr = self.register.get_reg16(from.clone()); let val = mmu.read8(addr); self.register.set_reg8(to, val); self.register.dec_reg16(from); } LdhR8A8(to, from_lo) => { let val = mmu.read8(0xff00 | from_lo as u16); self.register.set_reg8(to, val); } LdhA8R8(to_lo, from) => { let val = self.register.get_reg8(from); mmu.write8(0xff00 | to_lo as u16, val); } LdhAR8R8(to_lo_reg, from) => { let addr = 0xff00 | self.register.get_reg8(to_lo_reg) as u16; mmu.write8(addr, self.register.get_reg8(from)); } //no clue if this is right LdhlR16D8(from, imm) => { let new = self.register .get_reg16(from) .clone() .wrapping_add(imm as u16); self.register.set_reg16(HL, new); } IncR8(reg) => self.inc8_reg(reg), IncR16(reg) => self.inc16(reg), IncAR16(reg) => { let addr = self.register.get_reg16(reg).clone(); let mut val = mmu.read8(addr); self.inc8(&mut val); mmu.write8(addr, val); } DecR8(reg) => self.dec8_reg(reg), DecR16(reg) => self.dec16(reg), DecAR16(reg) => { let addr = self.register.get_reg16(reg).clone(); let mut val = mmu.read8(addr); self.dec8(&mut val); mmu.write8(addr, val); } Scf => self.register.set_flag(BitFlag::C), Ccf => self.register.clear_flag(BitFlag::C), BitR8(bit, reg) => self.bit_reg(reg, bit), BitAR16(bit, reg) => { let addr = self.register.get_reg16(reg); let mut val = mmu.read8(addr); self.bit(&mut val, bit); mmu.write8(addr, val); } ResR8(bit, reg) => self.reset_reg(reg, bit), ResAR16(bit, reg) => { let addr = self.register.get_reg16(reg); let mut val = mmu.read8(addr); self.reset(&mut val, bit); mmu.write8(addr, val); } SetR8(bit, reg) => self.set_reg(reg, bit), SetAR16(bit, reg) => { let addr = self.register.get_reg16(reg); let mut val = mmu.read8(addr); self.set(&mut val, bit); mmu.write8(addr, val); } Cpl => { self.register.set_flag(BitFlag::N); self.register.set_flag(BitFlag::H); self.register.a = self.register.a ^ 0xff; } Rlca => self.rlca(), Rla => self.rla(), Rrca => self.rrca(), Rra => self.rra(), RlcR8(reg) => self.rlc_reg(reg), RlcAR16(reg) => { let addr = self.register.get_reg16(reg); let mut val = mmu.read8(addr.clone()); self.rlc(&mut val); mmu.write8(addr, val); } RlR8(reg) => self.rl_reg(reg), RlAR16(reg) => { let addr = self.register.get_reg16(reg); let mut val = mmu.read8(addr.clone()); self.rl(&mut val); mmu.write8(addr, val); } RrcR8(reg) => self.rrc_reg(reg), RrcAR16(reg) => { let addr = self.register.get_reg16(reg); let mut val = mmu.read8(addr.clone()); self.rrc(&mut val); mmu.write8(addr, val); } RrR8(reg) => self.rr_reg(reg), RrAR16(reg) => { let addr = self.register.get_reg16(reg); let mut val = mmu.read8(addr.clone()); self.rr(&mut val); mmu.write8(addr, val); } SlaR8(reg) => self.sla_reg(reg), SlaAR16(reg) => { let addr = self.register.get_reg16(reg); let mut val = mmu.read8(addr.clone()); self.sla(&mut val); mmu.write8(addr, val); } SraR8(reg) => self.sra_reg(reg), SraAR16(reg) => { let addr = self.register.get_reg16(reg); let mut val = mmu.read8(addr.clone()); self.sra(&mut val); mmu.write8(addr, val); } SrlR8(reg) => self.srl_reg(reg), SrlAR16(reg) => { let addr = self.register.get_reg16(reg); let mut val = mmu.read8(addr.clone()); self.srl(&mut val); mmu.write8(addr, val); } JpA16(addr) => { self.register.pc = addr; self.jumped = true; } JpAR16(reg) => { let addr = self.register.get_reg16(reg); self.register.pc = addr; self.jumped = true; } JpFA16(flag, addr) => { if self.register.flag_is_set(flag) { self.register.pc = addr; self.jumped = true; } } JpNfA16(flag, addr) => { if self.register.flag_is_unset(flag) { self.register.pc = addr; self.jumped = true; } } JrA8(offset) => { let val = (self.register.sp as i16).wrapping_add(offset as i16); self.register.sp = val as u16; self.jumped = true; } JrFA8(flag, offset) => { if self.register.flag_is_set(flag) { let val = (self.register.sp as i16).wrapping_add(offset as i16); self.register.sp = val as u16; self.jumped = true; } } JrNfA8(flag, offset) => { if self.register.flag_is_unset(flag) { let val = (self.register.sp as i16).wrapping_add(offset as i16); self.register.sp = val as u16; self.jumped = true; } } AddR8R8(to, from) => { let val = self.register.get_reg8(from); self.add8(to, val, false); } AddR8D8(reg, imm) => self.add8(reg, imm, false), AddR8AR16(to, from) => { let val = mmu.read8(self.register.get_reg16(from)); self.add8(to, val, false); } AddR16R16(to, from) => { let fval = self.register.get_reg16(from.clone()); let tval = self.register.get_reg16(to.clone()); let (res, carry, half) = add16(tval, fval, false); self.register.set_flag_b(BitFlag::C, carry); self.register.set_flag_b(BitFlag::H, half); self.register.set_flag_b(BitFlag::Z, res == 0); self.register.set_flag_b(BitFlag::N, false); self.register.set_reg16(to, res); } AddR16D8(to, imm) => self.add16(to, imm as u16), AdcR8R8(to, from) => { let val = self.register.get_reg8(from); self.add8(to, val, true); } AdcR8D8(reg, imm) => self.add8(reg, imm, true), AdcR8AR16(to, from) => { let val = mmu.read8(self.register.get_reg16(from)); self.add8(to, val, true); } SubR8R8(to, from) => { let val = self.register.get_reg8(from); self.sub8(to, val, false); } SubR8D8(to, imm) => self.sub8(to, imm, false), SubR8AR16(to, from) => { let val = mmu.read8(self.register.get_reg16(from)); self.sub8(to, val, false); } SbcR8R8(to, from) => { let val = self.register.get_reg8(from); self.sub8(to, val, true); } SbcR8AR16(to, from) => { let val = mmu.read8(self.register.get_reg16(from)); self.sub8(to, val, true); } SbcR8D8(to, imm) => self.sub8(to, imm, true), AndR8R8(to, from) => { let val = self.register.get_reg8(from); self.and8(to, val); } AndR8D8(to, imm) => self.and8(to, imm), AndR8AR16(to, from) => { let val = mmu.read8(self.register.get_reg16(from)); self.and8(to, val); } OrR8R8(to, from) => { let val = self.register.get_reg8(from); self.or8(to, val); } OrR8D8(to, imm) => self.or8(to, imm), OrR8AR16(to, from) => { let val = mmu.read8(self.register.get_reg16(from)); self.or8(to, val); } XorR8R8(to, from) => { let val = self.register.get_reg8(from); self.xor8(to, val); } XorR8D8(to, imm) => self.xor8(to, imm), XorR8AR16(to, from) => { let val = mmu.read8(self.register.get_reg16(from)); self.xor8(to, val); } Ei => mmu.enable_interrupts(), Di => mmu.disable_interrupts(), CpR8R8(to, from) => { let val = self.register.get_reg8(from).clone(); self.cp8(to, val); } CpR8AR16(to, from) => { let val = mmu.read8(self.register.get_reg16(from)); self.cp8(to, val); } CpR8D8(to, imm) => self.cp8(to, imm), DaaR8(reg) => { //todo: there is no way this shit is correct let val = self.register.get_reg8(reg.clone()) as u16; let lo = val % 0x10; let hi = ((val % 0x100) - lo) / 0x10; let rs = (hi << 4) | lo; self.register.set_flag_b(BitFlag::Z, rs == 0); self.register.clear_flag(BitFlag::H); self.register.set_flag_b(BitFlag::C, val >= 0x100); self.register.set_reg8(reg, val as u8); } PushR16(reg) => { let val = self.register.get_reg16(reg); mmu.push_stack(&mut self.register.sp, val); } PopR16(reg) => { let val = mmu.pop_stack(&mut self.register.sp); self.register.set_reg16(reg, val); } CallA16(addr) => { let pc = self.register.pc + 3; mmu.push_stack(&mut self.register.sp, pc); self.register.pc = addr; self.jumped = true; } CallFA16(flag, addr) => { if self.register.flag_is_set(flag) { let pc = self.register.pc + 3; mmu.push_stack(&mut self.register.sp, pc); self.register.pc = addr; self.jumped = true; } } CallNfA16(flag, addr) => { if self.register.flag_is_unset(flag) { let pc = self.register.pc + 3; mmu.push_stack(&mut self.register.sp, pc); self.register.pc = addr; self.jumped = true; } } Ret => { let pc = mmu.pop_stack(&mut self.register.sp); self.register.pc = pc; self.jumped = true; } Reti => { let pc = mmu.pop_stack(&mut self.register.sp); self.register.pc = pc; self.jumped = true; mmu.enable_interrupts(); } RetF(flag) => { if self.register.flag_is_set(flag) { let pc = mmu.read16(self.register.sp); self.register.sp += 2; self.register.pc = pc; self.jumped = true; } } RetNf(flag) => { if self.register.flag_is_unset(flag) { let pc = mmu.read16(self.register.sp); self.register.sp += 2; self.register.pc = pc; self.jumped = true; } } Rst(addr) => { let pc = self.register.pc + 1; mmu.push_stack(&mut self.register.sp, pc); self.register.pc = addr; self.jumped = true; } } } }
use file_reader; const INPUT_FILENAME: &str = "input.txt"; fn main() { let input_str = match file_reader::file_to_vec(INPUT_FILENAME) { Err(_) => { println!("Couldn't turn file into vec!"); return; }, Ok(v) => v, }; // Vec is (number of people, answers combined) let mut input_str_f: Vec<(u32, String)> = Vec::new(); let mut input_idx = 0; for line in input_str.into_iter() { if input_str_f.len() == input_idx { input_str_f.push((1, line)); } else if line == "" { input_idx += 1; } else { input_str_f[input_idx].0 += 1; input_str_f[input_idx].1.push_str(&line); } } let input: Vec<u32> = input_str_f.into_iter().map(num_valid_answers).collect(); let result = input.into_iter().fold(0, |acc, x| acc + x); println!("{:?}", result); } fn num_valid_answers(input: (u32, String)) -> u32 { let grp_size: u32 = input.0; let answers: String = input.1; let mut input_vec: Vec<char> = answers.chars().collect(); input_vec.sort(); let mut valid_answers = 0; let mut answer_cnt = 0; let mut curr_char = ' '; for c in input_vec.into_iter() { if c != curr_char { curr_char = c; answer_cnt = 1; } else { answer_cnt += 1; } if answer_cnt == grp_size { valid_answers += 1; } else if answer_cnt > grp_size { // Better than no error handling ...probably println!("BAD THINGS HAPPENING!"); } }; valid_answers }