text
stringlengths
8
4.13M
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use super::sys_file::*; use super::super::task::*; use super::super::qlib::common::*; use super::super::qlib::linux_def::*; use super::super::qlib::device::*; use super::super::fs::dirent::*; use super::super::fs::file::*; use super::super::fs::attr::*; use super::super::syscalls::syscalls::*; pub fn SysStat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; let statAddr = args.arg1 as u64; return Stat(task, addr, statAddr) } pub fn Stat(task: &Task, addr: u64, statAddr: u64) -> Result<i64> { let (path, dirPath) = copyInPath(task, addr, false)?; info!("Stat path is {}", &path); fileOpOn(task, ATType::AT_FDCWD, &path, true, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> { return stat(task, d, dirPath, statAddr) })?; return Ok(0); } pub fn SysFstatat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let addr = args.arg1 as u64; let statAddr = args.arg2 as u64; let flags = args.arg3 as i32; return Fstatat(task, fd, addr, statAddr, flags) } pub fn Fstatat(task: &Task, fd: i32, addr: u64, statAddr: u64, flags: i32) -> Result<i64> { let (path, dirPath) = copyInPath(task, addr, flags & ATType::AT_EMPTY_PATH != 0)?; info!("Fstatat path is {}", &path); if path.len() == 0 { let file = task.GetFile(fd)?; fstat(task, &file, statAddr)?; return Ok(0) } let resolve = dirPath || flags & ATType::AT_SYMLINK_NOFOLLOW == 0; fileOpOn(task, fd, &path, resolve, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> { return stat(task, d, dirPath, statAddr) })?; return Ok(0) } pub fn SysLstat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; let statAddr = args.arg1 as u64; return Lstat(task, addr, statAddr) } pub fn Lstat(task: &Task, addr: u64, statAddr: u64) -> Result<i64> { let (path, dirPath) = copyInPath(task, addr, false)?; info!("Lstat path is {}", &path); let resolve = dirPath; fileOpOn(task, ATType::AT_FDCWD, &path, resolve, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> { return stat(task, d, dirPath, statAddr) })?; return Ok(0) } pub fn SysFstat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let statAddr = args.arg1 as u64; return Fstat(task, fd, statAddr) } pub fn SysStatx(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let pathAddr = args.arg1 as u64; let flags = args.arg2 as i32; let mask = args.arg3 as u32; let statxAddr = args.arg4 as u64; if mask & StatxMask::STATX__RESERVED != 0 { return Err(Error::SysError(SysErr::EINVAL)) } if flags & !(ATType::AT_SYMLINK_NOFOLLOW | ATType::AT_EMPTY_PATH | StatxFlags::AT_STATX_SYNC_TYPE as i32) != 0 { return Err(Error::SysError(SysErr::EINVAL)) } if flags as u32 & StatxFlags::AT_STATX_SYNC_TYPE == StatxFlags::AT_STATX_SYNC_TYPE { return Err(Error::SysError(SysErr::EINVAL)) } let (path, dirPath) = copyInPath(task, pathAddr, flags & ATType::AT_EMPTY_PATH != 0)?; if path.len() == 0 { let file = task.GetFile(fd)?; let uattr = file.UnstableAttr(task)?; let inode = file.Dirent.Inode(); let sattr = inode.StableAttr(); statx(task, &sattr, &uattr, statxAddr)?; return Ok(0) } let resolve = dirPath || flags & ATType::AT_SYMLINK_NOFOLLOW == 0; fileOpOn(task, fd, &path, resolve, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> { let inode = d.Inode(); let sattr = inode.StableAttr(); if dirPath && !sattr.IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } let uattr = inode.UnstableAttr(task)?; statx(task, &sattr, &uattr, statxAddr)?; return Ok(()) })?; return Ok(0) } pub fn Fstat(task: &Task, fd: i32, statAddr: u64) -> Result<i64> { let file = task.GetFile(fd)?; fstat(task, &file, statAddr)?; return Ok(0) } pub fn SysStatfs(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; let statfsAddr = args.arg1 as u64; let res = Statfs(task, addr, statfsAddr)?; return Ok(res as i64) } pub fn Statfs(task: &Task, addr: u64, statfsAddr: u64) -> Result<u64> { let (path, _dirPath) = copyInPath(task, addr, false)?; info!("Statfs path is {}", &path); fileOpOn(task, ATType::AT_FDCWD, &path, true, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> { return statfsImpl(task, d, statfsAddr) })?; return Ok(0) } pub fn SysFstatfs(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let statfsAddr = args.arg1 as u64; let file = task.GetFile(fd)?; statfsImpl(task, &file.Dirent, statfsAddr)?; return Ok(0) } fn stat(task: &Task, d: &Dirent, dirPath: bool, statAddr: u64) -> Result<()> { let inode = d.Inode(); if dirPath && !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } let uattr = inode.UnstableAttr(task)?; let sattr = inode.StableAttr(); copyOutStat(task, statAddr, &sattr, &uattr)?; return Ok(()) } fn fstat(task: &Task, f: &File, statAddr: u64) -> Result<()> { let inode = f.Dirent.Inode(); let uattr = f.UnstableAttr(task)?; let sattr = inode.StableAttr(); copyOutStat(task, statAddr, &sattr, &uattr)?; return Ok(()) } fn copyOutStat(task: &Task, statAddr: u64, sattr: &StableAttr, uattr: &UnstableAttr) -> Result<()> { //let mut s: &mut LibcStat = task.GetTypeMut(statAddr)?; let mut s : LibcStat = LibcStat::default(); //*s = LibcStat::default(); let creds = task.creds.clone(); let ns = creds.lock().UserNamespace.clone(); s.st_dev = sattr.DeviceId as u64; s.st_ino = sattr.InodeId; s.st_nlink = uattr.Links; s.st_mode = sattr.Type.LinuxType() as u32 | uattr.Perms.LinuxMode(); s.st_uid = uattr.Owner.UID.In(&ns).OrOverflow().0; s.st_gid = uattr.Owner.GID.In(&ns).OrOverflow().0; s.st_rdev = MakeDeviceID(sattr.DeviceFileMajor, sattr.DeviceFileMinor) as u64; s.st_size = uattr.Size; s.st_blksize = sattr.BlockSize; s.st_blocks = uattr.Usage / 512; let atime = uattr.AccessTime.Timespec(); s.st_atime = atime.tv_sec; s.st_atime_nsec = atime.tv_nsec; let mtime = uattr.ModificationTime.Timespec(); s.st_mtime = mtime.tv_sec; s.st_mtime_nsec = mtime.tv_nsec; let ctime = uattr.StatusChangeTime.Timespec(); s.st_ctime = ctime.tv_sec; s.st_ctime_nsec = ctime.tv_nsec; task.CopyOutObj(&s, statAddr)?; // error!("copyOutStat stat is {:x?}", s); return Ok(()) } fn statx(task: &Task, sattr: &StableAttr, uattr: &UnstableAttr, statxAddr: u64) -> Result<()> { let (devMajor, devMinor) = DecodeDeviceId(sattr.DeviceId as u32); let creds = task.creds.clone(); let ns = creds.lock().UserNamespace.clone(); //let out: &mut Statx = task.GetTypeMut::<Statx>(statxAddr)?; let s = Statx { stx_mask: StatxMask::STATX_BASIC_STATS, stx_blksize: sattr.BlockSize as u32, stx_attributes: 0, stx_nlink: uattr.Links as u32, stx_uid: uattr.Owner.UID.In(&ns).OrOverflow().0, stx_gid: uattr.Owner.GID.In(&ns).OrOverflow().0, stx_mode: (sattr.Type.LinuxType() as u32 | uattr.Perms.LinuxMode()) as u16, __statx_pad1: [0; 1], stx_ino: sattr.InodeId, stx_size: uattr.Size as u64, stx_attributes_mask: 0, stx_blocks: uattr.Usage as u64 / 512, stx_atime: uattr.AccessTime.StatxTimestamp(), stx_btime: StatxTimestamp::default(), stx_ctime: uattr.StatusChangeTime.StatxTimestamp(), stx_mtime: uattr.ModificationTime.StatxTimestamp(), stx_rdev_major: sattr.DeviceFileMajor as u32, stx_rdev_minor: sattr.DeviceFileMinor, stx_dev_major: devMajor as u32, stx_dev_minor: devMinor, __statx_pad2: [0; 14], }; //*out = s; task.CopyOutObj(&s, statxAddr)?; return Ok(()) } fn statfsImpl(task: &Task, d: &Dirent, addr: u64) -> Result<()> { let inode = d.Inode(); let sattr = inode.lock().StableAttr().clone(); let info = inode.StatFS(task)?; let statfs = LibcStatfs { Type: info.Type, BlockSize: sattr.BlockSize, Blocks: info.TotalBlocks, BlocksFree: info.FreeBlocks, BlocksAvailable: info.FreeBlocks, Files: info.TotalFiles, FilesFree: info.FreeFiles, NameLength: NAME_MAX as u64, FragmentSize: sattr.BlockSize, ..Default::default() }; //let out: &mut LibcStatfs = task.GetTypeMut::<LibcStatfs>(addr)?; //*out = statfs; task.CopyOutObj(&statfs, addr)?; return Ok(()) }
use crate::IdTokenPayload; use jsonwebtoken::errors::Result as JwtResult; use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation}; pub fn decode_id_token(id_token: &str, secret: &str) -> JwtResult<IdTokenPayload> { let key = DecodingKey::from_secret(secret.as_bytes()); let validation = Validation::default(); Ok(jsonwebtoken::decode(id_token, &key, &validation)?.claims) } pub fn encode_id_token(payload: &IdTokenPayload, secret: &str) -> JwtResult<String> { let header = Header::default(); let key = EncodingKey::from_secret(secret.as_bytes()); Ok(jsonwebtoken::encode(&header, &payload, &key)?) }
pub mod forget_password_form;
use super::*; impl Mask { pub fn count(self) -> u32 { self.0.count_ones() } pub fn has_mote_than_one_bit_set(self) -> bool { self.0 & (self.0.wrapping_sub(1)) != 0 } pub fn index_of_least_significant_bit(self) -> u32 { self.0.trailing_zeros() } pub fn index_of_most_significant_bit(self) -> u32 { self.0.leading_zeros() ^ 63 } pub fn most_significant_bit(self) -> Mask { let mut bb = self.0; bb |= bb.wrapping_shr(32); bb |= bb.wrapping_shr(16); bb |= bb.wrapping_shr(8); bb |= bb.wrapping_shr(4); bb |= bb.wrapping_shr(2); bb |= bb.wrapping_shr(1); bb = bb.wrapping_shr(1); Mask(bb.wrapping_add(1)) } pub fn least_significant_bit(self) -> Mask { let bb = self.0; Mask(bb & bb.wrapping_neg()) } } #[cfg(test)] mod tests { use super::super::*; use test::Bencher; use itertools::*; use rand::random; #[test] fn count() { let m = masks::B | masks::_2; assert_eq!(m.count(), 15); } #[test] fn has_mote_than_one_bit_set() { assert_eq!(masks::B.has_mote_than_one_bit_set(), true); assert_eq!(masks::B2.has_mote_than_one_bit_set(), false); assert_eq!(masks::EMPTY.has_mote_than_one_bit_set(), false); } #[test] fn least_significant_bit() { for (bits, shift) in (0..1000).map(random_bits_shift) { let m = Mask((bits | RIGHT).wrapping_shl(shift)); assert_eq!(m.least_significant_bit().0, RIGHT << shift); } } #[test] fn index_of_least_significant_bit() { for (bits, shift) in (0..1000).map(random_bits_shift) { let m = Mask((bits | RIGHT).wrapping_shl(shift)); assert_eq!(m.index_of_least_significant_bit(), shift); } } #[test] fn most_significant_bit() { for (bits, shift) in (0..1000).map(random_bits_shift) { let mask = Mask((bits | LEFT).wrapping_shr(shift)); assert_eq!(mask.most_significant_bit().0, LEFT >> shift); } } #[test] fn index_of_most_significant_bit() { for (bits, shift) in (0..1000).map(random_bits_shift) { let mask = Mask((bits | LEFT).wrapping_shr(shift)); assert_eq!(mask.index_of_most_significant_bit(), 63 - shift); } } #[test] fn single_bits_back_and_forth() { for m in (0..1000).map(|_| Mask(random())) { assert_equal(m.single_bits().rev(), m.single_bits().collect_vec().into_iter().rev()); } } #[test] fn single_bit_indices_back_and_forth() { for m in (0..1000).map(|_| Mask(random())) { assert_equal(m.single_bit_indices().rev(), m.single_bit_indices().collect_vec().into_iter().rev()); } } #[bench] fn bench_has_mote_than_one_bit_set(b: &mut Bencher) { let max: u64 = ::test::black_box(1000); b.iter(|| { let mut count = 0; for n in 0..max { if Mask(n).has_mote_than_one_bit_set() { count += 1 } } count }); } #[bench] fn bench_count(b: &mut Bencher) { let max: u64 = ::test::black_box(1000); b.iter(|| { let mut count = 0; for n in 0..max { if Mask(n).count() > 1 { count += 1 } } count }); } fn random_bits_shift(_: i32) -> (u64, u32) { (random::<u64>(), random::<u32>() % 64) } const LEFT: u64 = 1u64 << 63; const RIGHT: u64 = 1u64; }
use commons::math::{lerp_2, map_value, p2, v2, P2, PI, TWO_PI, V2}; use ggez::conf::WindowMode; use ggez::event::{self, EventHandler, KeyCode, KeyMods, MouseButton}; use ggez::graphics::{Color, DrawMode, DrawParam, Rect}; use ggez::{graphics, Context, ContextBuilder, GameResult}; use nalgebra::{Point2, Vector2}; use noise::{NoiseFn, Perlin}; use rand::prelude::StdRng; use rand::{Rng, SeedableRng}; const WIDTH: f32 = 800.0; const HEIGHT: f32 = 600.0; #[derive(Debug)] struct App { noise: Perlin, seed: f64, } impl App { pub fn new(ctx: &mut Context) -> GameResult<App> { Ok(App { noise: Default::default(), seed: 0.0, }) } } fn draw_planet(app: &mut App, ctx: &mut Context, pos: P2, radius: f32) -> GameResult<()> { let mut rng: StdRng = SeedableRng::seed_from_u64(app.seed as u64); let mut mb = graphics::MeshBuilder::new(); let segments = 50; let per_segment_angle = TWO_PI / segments as f32; let noise_radius = 2.0; let mut points = vec![]; for i in 0..segments { let angle = i as f32 * per_segment_angle; let x = angle.cos() * noise_radius; let y = angle.sin() * noise_radius; let nois_pos = [x as f64, y as f64, app.seed]; let noise = app.noise.get(nois_pos) as f32; let current_radius = map_value(noise, -1.0, 1.0, radius * 0.8, radius * 1.25); let x = angle.cos() * current_radius + pos.x; let y = angle.sin() * current_radius + pos.y; points.push(p2(x, y)); mb.line(&[pos, p2(x, y)], 1.0, Color::new(0.0, 1.0, 0.0, 1.0)); } mb.polygon( DrawMode::stroke(1.0), &points, Color::new(1.0, 0.0, 0.0, 1.0), )?; let mesh = mb.build(ctx)?; graphics::draw(ctx, &mesh, DrawParam::default())?; for i in 0..3 { let angle = rng.gen_range(0.0, TWO_PI); let distance = rng.gen_range(radius * 0.7, radius * 0.9); let size = radius - distance; let x = angle.cos() * distance + pos.x; let y = angle.sin() * distance + pos.y; let circle = graphics::Mesh::new_circle( ctx, DrawMode::stroke(1.0), p2(x, y), size, 1.0, Color::new(0.0, 0.0, 1.0, 1.0), )?; graphics::draw(ctx, &circle, DrawParam::default())?; } Ok(()) } impl EventHandler<ggez::GameError> for App { fn update(&mut self, ctx: &mut Context) -> GameResult<()> { if ggez::input::keyboard::is_key_pressed(ctx, KeyCode::Space) { self.seed = ggez::timer::ticks(ctx) as f64 / 100.0; } Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { graphics::clear(ctx, graphics::Color::BLACK); draw_planet(self, ctx, p2(WIDTH / 2.0, HEIGHT / 2.0), HEIGHT * 0.4); graphics::present(ctx) } fn mouse_button_down_event(&mut self, _ctx: &mut Context, button: MouseButton, x: f32, y: f32) { } fn mouse_button_up_event(&mut self, _ctx: &mut Context, button: MouseButton, x: f32, y: f32) {} fn mouse_motion_event(&mut self, _ctx: &mut Context, x: f32, y: f32, _dx: f32, _dy: f32) {} } fn main() -> GameResult<()> { // Make a Context. let mut window_mode: WindowMode = Default::default(); window_mode.width = WIDTH; window_mode.height = HEIGHT; let (mut ctx, mut event_loop) = ContextBuilder::new("template", "Sisso") .window_mode(window_mode) .build() .unwrap(); let mut app = App::new(&mut ctx)?; // Run! event::run(ctx, event_loop, app); }
use serde_derive::Deserialize; use serde_derive::Serialize; #[derive(Serialize, Deserialize, Debug)] pub struct ResponseMessage { pub message: String, }
#[cfg(feature = "jit")] mod jitfunc; use super::{ tuple::PyTupleTyped, PyAsyncGen, PyCode, PyCoroutine, PyDictRef, PyGenerator, PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef, }; #[cfg(feature = "jit")] use crate::common::lock::OnceCell; use crate::common::lock::PyMutex; use crate::convert::ToPyObject; use crate::function::ArgMapping; use crate::object::{Traverse, TraverseFn}; use crate::{ bytecode, class::PyClassImpl, frame::Frame, function::{FuncArgs, OptionalArg, PyComparisonValue, PySetterValue}, scope::Scope, types::{ Callable, Comparable, Constructor, GetAttr, GetDescriptor, PyComparisonOp, Representable, }, AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, }; use itertools::Itertools; #[cfg(feature = "jit")] use rustpython_jit::CompiledCode; #[pyclass(module = false, name = "function", traverse = "manual")] #[derive(Debug)] pub struct PyFunction { code: PyRef<PyCode>, globals: PyDictRef, closure: Option<PyTupleTyped<PyCellRef>>, defaults_and_kwdefaults: PyMutex<(Option<PyTupleRef>, Option<PyDictRef>)>, name: PyMutex<PyStrRef>, qualname: PyMutex<PyStrRef>, #[cfg(feature = "jit")] jitted_code: OnceCell<CompiledCode>, } unsafe impl Traverse for PyFunction { fn traverse(&self, tracer_fn: &mut TraverseFn) { self.globals.traverse(tracer_fn); self.closure.traverse(tracer_fn); self.defaults_and_kwdefaults.traverse(tracer_fn); } } impl PyFunction { pub(crate) fn new( code: PyRef<PyCode>, globals: PyDictRef, closure: Option<PyTupleTyped<PyCellRef>>, defaults: Option<PyTupleRef>, kw_only_defaults: Option<PyDictRef>, qualname: PyMutex<PyStrRef>, ) -> Self { let name = PyMutex::new(code.obj_name.to_owned()); PyFunction { code, globals, closure, defaults_and_kwdefaults: PyMutex::new((defaults, kw_only_defaults)), name, qualname, #[cfg(feature = "jit")] jitted_code: OnceCell::new(), } } fn fill_locals_from_args( &self, frame: &Frame, func_args: FuncArgs, vm: &VirtualMachine, ) -> PyResult<()> { let code = &*self.code; let nargs = func_args.args.len(); let nexpected_args = code.arg_count as usize; let total_args = code.arg_count as usize + code.kwonlyarg_count as usize; // let arg_names = self.code.arg_names(); // This parses the arguments from args and kwargs into // the proper variables keeping into account default values // and starargs and kwargs. // See also: PyEval_EvalCodeWithName in cpython: // https://github.com/python/cpython/blob/main/Python/ceval.c#L3681 let mut fastlocals = frame.fastlocals.lock(); let mut args_iter = func_args.args.into_iter(); // Copy positional arguments into local variables // zip short-circuits if either iterator returns None, which is the behavior we want -- // only fill as much as there is to fill with as much as we have for (local, arg) in Iterator::zip( fastlocals.iter_mut().take(nexpected_args), args_iter.by_ref().take(nargs), ) { *local = Some(arg); } let mut vararg_offset = total_args; // Pack other positional arguments in to *args: if code.flags.contains(bytecode::CodeFlags::HAS_VARARGS) { let vararg_value = vm.ctx.new_tuple(args_iter.collect()); fastlocals[vararg_offset] = Some(vararg_value.into()); vararg_offset += 1; } else { // Check the number of positional arguments if nargs > nexpected_args { return Err(vm.new_type_error(format!( "{}() takes {} positional arguments but {} were given", self.qualname(), nexpected_args, nargs ))); } } // Do we support `**kwargs` ? let kwargs = if code.flags.contains(bytecode::CodeFlags::HAS_VARKEYWORDS) { let d = vm.ctx.new_dict(); fastlocals[vararg_offset] = Some(d.clone().into()); Some(d) } else { None }; let argpos = |range: std::ops::Range<_>, name: &str| { code.varnames .iter() .enumerate() .skip(range.start) .take(range.end - range.start) .find(|(_, s)| s.as_str() == name) .map(|(p, _)| p) }; let mut posonly_passed_as_kwarg = Vec::new(); // Handle keyword arguments for (name, value) in func_args.kwargs { // Check if we have a parameter with this name: if let Some(pos) = argpos(code.posonlyarg_count as usize..total_args, &name) { let slot = &mut fastlocals[pos]; if slot.is_some() { return Err(vm.new_type_error(format!( "{}() got multiple values for argument '{}'", self.qualname(), name ))); } *slot = Some(value); } else if let Some(kwargs) = kwargs.as_ref() { kwargs.set_item(&name, value, vm)?; } else if argpos(0..code.posonlyarg_count as usize, &name).is_some() { posonly_passed_as_kwarg.push(name); } else { return Err(vm.new_type_error(format!( "{}() got an unexpected keyword argument '{}'", self.qualname(), name ))); } } if !posonly_passed_as_kwarg.is_empty() { return Err(vm.new_type_error(format!( "{}() got some positional-only arguments passed as keyword arguments: '{}'", self.qualname(), posonly_passed_as_kwarg.into_iter().format(", "), ))); } let mut defaults_and_kwdefaults = None; // can't be a closure cause it returns a reference to a captured variable :/ macro_rules! get_defaults { () => {{ defaults_and_kwdefaults .get_or_insert_with(|| self.defaults_and_kwdefaults.lock().clone()) }}; } // Add missing positional arguments, if we have fewer positional arguments than the // function definition calls for if nargs < nexpected_args { let defaults = get_defaults!().0.as_ref().map(|tup| tup.as_slice()); let ndefs = defaults.map_or(0, |d| d.len()); let nrequired = code.arg_count as usize - ndefs; // Given the number of defaults available, check all the arguments for which we // _don't_ have defaults; if any are missing, raise an exception let mut missing: Vec<_> = (nargs..nrequired) .filter_map(|i| { if fastlocals[i].is_none() { Some(&code.varnames[i]) } else { None } }) .collect(); let missing_args_len = missing.len(); if !missing.is_empty() { let last = if missing.len() > 1 { missing.pop() } else { None }; let (and, right) = if let Some(last) = last { ( if missing.len() == 1 { "' and '" } else { "', and '" }, last.as_str(), ) } else { ("", "") }; return Err(vm.new_type_error(format!( "{}() missing {} required positional argument{}: '{}{}{}'", self.qualname(), missing_args_len, if missing_args_len == 1 { "" } else { "s" }, missing.iter().join("', '"), and, right, ))); } if let Some(defaults) = defaults { let n = std::cmp::min(nargs, nexpected_args); let i = n.saturating_sub(nrequired); // We have sufficient defaults, so iterate over the corresponding names and use // the default if we don't already have a value for i in i..defaults.len() { let slot = &mut fastlocals[nrequired + i]; if slot.is_none() { *slot = Some(defaults[i].clone()); } } } }; if code.kwonlyarg_count > 0 { // TODO: compile a list of missing arguments // let mut missing = vec![]; // Check if kw only arguments are all present: for (slot, kwarg) in fastlocals .iter_mut() .zip(&*code.varnames) .skip(code.arg_count as usize) .take(code.kwonlyarg_count as usize) .filter(|(slot, _)| slot.is_none()) { if let Some(defaults) = &get_defaults!().1 { if let Some(default) = defaults.get_item_opt(&**kwarg, vm)? { *slot = Some(default); continue; } } // No default value and not specified. return Err( vm.new_type_error(format!("Missing required kw only argument: '{kwarg}'")) ); } } if let Some(cell2arg) = code.cell2arg.as_deref() { for (cell_idx, arg_idx) in cell2arg.iter().enumerate().filter(|(_, i)| **i != -1) { let x = fastlocals[*arg_idx as usize].take(); frame.cells_frees[cell_idx].set(x); } } Ok(()) } pub fn invoke_with_locals( &self, func_args: FuncArgs, locals: Option<ArgMapping>, vm: &VirtualMachine, ) -> PyResult { #[cfg(feature = "jit")] if let Some(jitted_code) = self.jitted_code.get() { match jitfunc::get_jit_args(self, &func_args, jitted_code, vm) { Ok(args) => { return Ok(args.invoke().to_pyobject(vm)); } Err(err) => info!( "jit: function `{}` is falling back to being interpreted because of the \ error: {}", self.code.obj_name, err ), } } let code = &self.code; let locals = if self.code.flags.contains(bytecode::CodeFlags::NEW_LOCALS) { ArgMapping::from_dict_exact(vm.ctx.new_dict()) } else if let Some(locals) = locals { locals } else { ArgMapping::from_dict_exact(self.globals.clone()) }; // Construct frame: let frame = Frame::new( code.clone(), Scope::new(Some(locals), self.globals.clone()), vm.builtins.dict(), self.closure.as_ref().map_or(&[], |c| c.as_slice()), vm, ) .into_ref(&vm.ctx); self.fill_locals_from_args(&frame, func_args, vm)?; // If we have a generator, create a new generator let is_gen = code.flags.contains(bytecode::CodeFlags::IS_GENERATOR); let is_coro = code.flags.contains(bytecode::CodeFlags::IS_COROUTINE); match (is_gen, is_coro) { (true, false) => Ok(PyGenerator::new(frame, self.name()).into_pyobject(vm)), (false, true) => Ok(PyCoroutine::new(frame, self.name()).into_pyobject(vm)), (true, true) => Ok(PyAsyncGen::new(frame, self.name()).into_pyobject(vm)), (false, false) => vm.run_frame(frame), } } #[inline(always)] pub fn invoke(&self, func_args: FuncArgs, vm: &VirtualMachine) -> PyResult { self.invoke_with_locals(func_args, None, vm) } } impl PyPayload for PyFunction { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.function_type } } #[pyclass( with(GetDescriptor, Callable, Representable), flags(HAS_DICT, METHOD_DESCRIPTOR) )] impl PyFunction { #[pygetset(magic)] fn code(&self) -> PyRef<PyCode> { self.code.clone() } #[pygetset(magic)] fn defaults(&self) -> Option<PyTupleRef> { self.defaults_and_kwdefaults.lock().0.clone() } #[pygetset(magic, setter)] fn set_defaults(&self, defaults: Option<PyTupleRef>) { self.defaults_and_kwdefaults.lock().0 = defaults } #[pygetset(magic)] fn kwdefaults(&self) -> Option<PyDictRef> { self.defaults_and_kwdefaults.lock().1.clone() } #[pygetset(magic, setter)] fn set_kwdefaults(&self, kwdefaults: Option<PyDictRef>) { self.defaults_and_kwdefaults.lock().1 = kwdefaults } // {"__closure__", T_OBJECT, OFF(func_closure), READONLY}, // {"__doc__", T_OBJECT, OFF(func_doc), 0}, // {"__globals__", T_OBJECT, OFF(func_globals), READONLY}, // {"__module__", T_OBJECT, OFF(func_module), 0}, // {"__builtins__", T_OBJECT, OFF(func_builtins), READONLY}, #[pymember(magic)] fn globals(vm: &VirtualMachine, zelf: PyObjectRef) -> PyResult { let zelf = Self::_as_pyref(&zelf, vm)?; Ok(zelf.globals.clone().into()) } #[pymember(magic)] fn closure(vm: &VirtualMachine, zelf: PyObjectRef) -> PyResult { let zelf = Self::_as_pyref(&zelf, vm)?; Ok(vm.unwrap_or_none(zelf.closure.clone().map(|x| x.to_pyobject(vm)))) } #[pygetset(magic)] fn name(&self) -> PyStrRef { self.name.lock().clone() } #[pygetset(magic, setter)] fn set_name(&self, name: PyStrRef) { *self.name.lock() = name; } #[pygetset(magic)] fn qualname(&self) -> PyStrRef { self.qualname.lock().clone() } #[pygetset(magic, setter)] fn set_qualname(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { match value { PySetterValue::Assign(value) => { let Ok(qualname) = value.downcast::<PyStr>() else { return Err(vm.new_type_error( "__qualname__ must be set to a string object".to_string(), )); }; *self.qualname.lock() = qualname; } PySetterValue::Delete => { return Err( vm.new_type_error("__qualname__ must be set to a string object".to_string()) ); } } Ok(()) } #[cfg(feature = "jit")] #[pymethod(magic)] fn jit(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<()> { zelf.jitted_code .get_or_try_init(|| { let arg_types = jitfunc::get_jit_arg_types(&zelf, vm)?; rustpython_jit::compile(&zelf.code.code, &arg_types) .map_err(|err| jitfunc::new_jit_error(err.to_string(), vm)) }) .map(drop) } } impl GetDescriptor for PyFunction { fn descr_get( zelf: PyObjectRef, obj: Option<PyObjectRef>, cls: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { let (_zelf, obj) = Self::_unwrap(&zelf, obj, vm)?; let obj = if vm.is_none(&obj) && !Self::_cls_is(&cls, obj.class()) { zelf } else { PyBoundMethod::new_ref(obj, zelf, &vm.ctx).into() }; Ok(obj) } } impl Callable for PyFunction { type Args = FuncArgs; #[inline] fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult { zelf.invoke(args, vm) } } impl Representable for PyFunction { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { Ok(format!( "<function {} at {:#x}>", zelf.qualname(), zelf.get_id() )) } } #[pyclass(module = false, name = "method", traverse)] #[derive(Debug)] pub struct PyBoundMethod { object: PyObjectRef, function: PyObjectRef, } impl Callable for PyBoundMethod { type Args = FuncArgs; #[inline] fn call(zelf: &Py<Self>, mut args: FuncArgs, vm: &VirtualMachine) -> PyResult { args.prepend_arg(zelf.object.clone()); zelf.function.call(args, vm) } } impl Comparable for PyBoundMethod { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, _vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { op.eq_only(|| { let other = class_or_notimplemented!(Self, other); Ok(PyComparisonValue::Implemented( zelf.function.is(&other.function) && zelf.object.is(&other.object), )) }) } } impl GetAttr for PyBoundMethod { fn getattro(zelf: &Py<Self>, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult { let class_attr = vm .ctx .interned_str(name) .and_then(|attr_name| zelf.get_class_attr(attr_name)); if let Some(obj) = class_attr { return vm.call_if_get_descriptor(&obj, zelf.to_owned().into()); } zelf.function.get_attr(name, vm) } } #[derive(FromArgs)] pub struct PyBoundMethodNewArgs { #[pyarg(positional)] function: PyObjectRef, #[pyarg(positional)] object: PyObjectRef, } impl Constructor for PyBoundMethod { type Args = PyBoundMethodNewArgs; fn py_new( cls: PyTypeRef, Self::Args { function, object }: Self::Args, vm: &VirtualMachine, ) -> PyResult { PyBoundMethod::new(object, function) .into_ref_with_type(vm, cls) .map(Into::into) } } impl PyBoundMethod { fn new(object: PyObjectRef, function: PyObjectRef) -> Self { PyBoundMethod { object, function } } pub fn new_ref(object: PyObjectRef, function: PyObjectRef, ctx: &Context) -> PyRef<Self> { PyRef::new_ref( Self::new(object, function), ctx.types.bound_method_type.to_owned(), None, ) } } #[pyclass( with(Callable, Comparable, GetAttr, Constructor, Representable), flags(HAS_DICT) )] impl PyBoundMethod { #[pymethod(magic)] fn reduce( &self, vm: &VirtualMachine, ) -> (Option<PyObjectRef>, (PyObjectRef, Option<PyObjectRef>)) { let builtins_getattr = vm.builtins.get_attr("getattr", vm).ok(); let funcself = self.object.clone(); let funcname = self.function.get_attr("__name__", vm).ok(); (builtins_getattr, (funcself, funcname)) } #[pygetset(magic)] fn doc(&self, vm: &VirtualMachine) -> PyResult { self.function.get_attr("__doc__", vm) } #[pygetset(magic)] fn func(&self) -> PyObjectRef { self.function.clone() } #[pygetset(name = "__self__")] fn get_self(&self) -> PyObjectRef { self.object.clone() } #[pygetset(magic)] fn module(&self, vm: &VirtualMachine) -> Option<PyObjectRef> { self.function.get_attr("__module__", vm).ok() } #[pygetset(magic)] fn qualname(&self, vm: &VirtualMachine) -> PyResult { if self .function .fast_isinstance(vm.ctx.types.builtin_function_or_method_type) { // Special case: we work with `__new__`, which is not really a method. // It is a function, so its `__qualname__` is just `__new__`. // We need to add object's part manually. let obj_name = vm.get_attribute_opt(self.object.clone(), "__qualname__")?; let obj_name: Option<PyStrRef> = obj_name.and_then(|o| o.downcast().ok()); return Ok(vm .ctx .new_str(format!( "{}.__new__", obj_name.as_ref().map_or("?", |s| s.as_str()) )) .into()); } self.function.get_attr("__qualname__", vm) } } impl PyPayload for PyBoundMethod { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.bound_method_type } } impl Representable for PyBoundMethod { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { #[allow(clippy::needless_match)] // False positive on nightly let funcname = if let Some(qname) = vm.get_attribute_opt(zelf.function.clone(), "__qualname__")? { Some(qname) } else { vm.get_attribute_opt(zelf.function.clone(), "__name__")? }; let funcname: Option<PyStrRef> = funcname.and_then(|o| o.downcast().ok()); Ok(format!( "<bound method {} of {}>", funcname.as_ref().map_or("?", |s| s.as_str()), &zelf.object.repr(vm)?.as_str(), )) } } #[pyclass(module = false, name = "cell", traverse)] #[derive(Debug, Default)] pub(crate) struct PyCell { contents: PyMutex<Option<PyObjectRef>>, } pub(crate) type PyCellRef = PyRef<PyCell>; impl PyPayload for PyCell { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.cell_type } } impl Constructor for PyCell { type Args = OptionalArg; fn py_new(cls: PyTypeRef, value: Self::Args, vm: &VirtualMachine) -> PyResult { Self::new(value.into_option()) .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(Constructor))] impl PyCell { pub fn new(contents: Option<PyObjectRef>) -> Self { Self { contents: PyMutex::new(contents), } } pub fn get(&self) -> Option<PyObjectRef> { self.contents.lock().clone() } pub fn set(&self, x: Option<PyObjectRef>) { *self.contents.lock() = x; } #[pygetset] fn cell_contents(&self, vm: &VirtualMachine) -> PyResult { self.get() .ok_or_else(|| vm.new_value_error("Cell is empty".to_owned())) } #[pygetset(setter)] fn set_cell_contents(&self, x: PyObjectRef) { self.set(Some(x)) } } pub fn init(context: &Context) { PyFunction::extend_class(context, context.types.function_type); PyBoundMethod::extend_class(context, context.types.bound_method_type); PyCell::extend_class(context, context.types.cell_type); }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fmt::Display; use chrono::DateTime; use chrono::Utc; use crate::storage::StorageParams; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum CatalogType { Default = 1, Hive = 2, Iceberg = 3, } impl Display for CatalogType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { CatalogType::Default => write!(f, "DEFAULT"), CatalogType::Hive => write!(f, "HIVE"), CatalogType::Iceberg => write!(f, "ICEBERG"), } } } /// Option for creating a iceberg catalog #[derive(Clone, Debug, PartialEq, Eq)] pub struct IcebergCatalogOption { pub storage_params: Box<StorageParams>, /// is the remote iceberg storage storing /// tables directly in the root directory pub flatten: bool, } /// different options for creating catalogs #[derive(Debug, Clone, PartialEq, Eq)] pub enum CatalogOption { // hms_address Hive(String), // Uri location for iceberg Iceberg(IcebergCatalogOption), } #[derive(Clone, Debug, PartialEq, Eq)] pub struct CatalogMeta { pub catalog_option: CatalogOption, pub created_on: DateTime<Utc>, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct CatalogNameIdent { pub tenant: String, pub catalog_name: String, } impl Display for CatalogNameIdent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "'{}'/'{}'", self.tenant, self.catalog_name) } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct CreateCatalogReq { pub if_not_exists: bool, pub name_ident: CatalogNameIdent, pub meta: CatalogMeta, } impl Display for CreateCatalogReq { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "create_catalog(if_not_exists={}):{}/{}={:?}", self.if_not_exists, self.name_ident.tenant, self.name_ident.catalog_name, self.meta ) } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct DropCatalogReq { pub if_exists: bool, pub name_ident: CatalogNameIdent, } impl Display for DropCatalogReq { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "drop_catalog(if_exists={}):{}/{}", self.if_exists, self.name_ident.tenant, self.name_ident.catalog_name ) } }
use dirs::home_dir; use log::{debug, trace}; use serde::{Deserialize, Serialize}; use std::fmt; use std::fs; use std::io::{self, Read, Write}; #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Item { pub id: u64, pub name: String, pub obtained: bool, pub created_at: String, } impl fmt::Display for &Item { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let obtained_s = if self.obtained { "[X]" } else { "[ ]" }; write!(f, "{}: {} {}", self.id, self.name, obtained_s) } } pub trait Store { fn persist_items(&self) -> io::Result<()>; fn load_items(&mut self) -> io::Result<()>; fn get_items(&self) -> io::Result<&Vec<Item>>; fn get_item(&self, id: u64) -> io::Result<&Item>; fn add_item(&mut self, name: String) -> io::Result<&Item>; fn remove_item(&mut self, id: u64) -> io::Result<u64>; } pub struct FileStorage { items: Vec<Item>, } impl Default for FileStorage { fn default() -> Self { Self { items: Vec::new() } } } impl FileStorage { pub fn new() -> Self { FileStorage::default() } pub fn json_file_path(&self) -> io::Result<String> { let config_path = self.config_dir_path()?; Ok(format!("{}/{}", config_path, "items.json")) } pub fn config_dir_path(&self) -> io::Result<String> { home_dir() .map(|home| format!("{}/{}", home.display(), ".pickup")) .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound)) } pub fn config_dir_exists(&self) -> bool { self.config_dir_path().and_then(fs::metadata).is_ok() } pub fn create_config_dir(&self) -> io::Result<()> { if self.config_dir_exists() { return Ok(()); } fs::create_dir_all(self.config_dir_path()?)?; Ok(()) } pub fn items_file_exists(&self) -> bool { self.json_file_path().and_then(fs::metadata).is_ok() } pub fn create_items_file(&self) -> io::Result<()> { if self.config_dir_exists() { fs::File::create(self.json_file_path()?)?; } Ok(()) } } impl Store for FileStorage { fn load_items(&mut self) -> io::Result<()> { trace!("Getting store from user config..."); let path = self.json_file_path()?; let mut file = fs::File::open(path)?; let mut buf = String::new(); file.read_to_string(&mut buf)?; let items: Vec<Item> = serde_json::from_str(&buf)?; self.items = items; debug!("JSON file parsed. Adding storage..."); Ok(()) } fn persist_items(&self) -> io::Result<()> { trace!("Persisting items to disk..."); let path = self.json_file_path()?; let mut file = fs::OpenOptions::new() .write(true) .truncate(true) .open(path)?; let buf = serde_json::to_string(&self.items)?; file.write_all(buf.as_bytes())?; file.flush()?; Ok(()) } fn get_item(&self, id: u64) -> io::Result<&Item> { for item in &self.items { if item.id == id { return Ok(&item); } } Err(io::Error::new( io::ErrorKind::NotFound, "Invalid path to storage file", )) } fn get_items(&self) -> io::Result<&Vec<Item>> { Ok(&self.items) } fn add_item(&mut self, name: String) -> io::Result<&Item> { let items = self.get_items()?; let id = items.last().map(|i| i.id + 1).unwrap_or(1); let now = chrono::Local::now(); let item = Item { id, name, obtained: false, created_at: now.to_rfc3339(), }; self.items.push(item); self.persist_items()?; Ok(self.get_item(id)?) } fn remove_item(&mut self, id: u64) -> io::Result<u64> { if let Some(pos) = self.items.iter().position(|i| i.id == id) { self.items.remove(pos); self.persist_items()?; Ok(id) } else { Err(io::Error::new( io::ErrorKind::NotFound, "ID to item is invalid", )) } } } #[cfg(test)] mod test { use super::{FileStorage, Item, Store}; use std::env; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::PathBuf; use tempfile::TempDir; type TestResult = Result<(), Box<dyn std::error::Error>>; #[test] fn test_config_path() -> TestResult { let storage = FileStorage::new(); let tmp_dir = set_config_dir()?; let actual = storage.config_dir_path()?; let expected = tmp_dir .path() .join(".pickup") .to_owned() .into_os_string() .into_string() .unwrap(); assert_eq!(actual, expected); env::remove_var("HOME"); Ok(()) } #[test] fn test_json_file_path() -> TestResult { let storage = FileStorage::new(); let tmp_dir = set_config_dir()?; let actual = storage.json_file_path()?; let expected = format!( "{}/{}/{}", tmp_dir.path().display(), ".pickup", "items.json" ); assert_eq!(actual, expected); env::remove_var("HOME"); Ok(()) } #[test] fn test_load_items() -> TestResult { let (_tmp, mut storage) = storage_with_item()?; storage.load_items()?; assert_eq!(storage.items.len(), 1); env::remove_var("HOME"); Ok(()) } #[test] fn test_add_item() -> TestResult { let (_tmp, mut storage) = storage_with_item()?; storage.load_items()?; let item = storage.add_item(String::from("sup"))?; assert!(item.id > 0); assert_eq!(item.name, "sup"); assert_eq!(storage.items.len(), 2); env::remove_var("HOME"); Ok(()) } #[test] fn test_get_item() -> TestResult { let (_tmp, mut storage) = storage_with_item()?; storage.load_items()?; let item = storage.get_item(1)?; assert_eq!(item.name, "foo item"); assert_eq!(item.obtained, false); env::remove_var("HOME"); Ok(()) } #[test] fn test_remove_item() -> TestResult { let (_tmp, mut storage) = storage_with_item()?; storage.load_items()?; let id = storage.remove_item(1)?; println!("{:?}", storage.items); assert_eq!(storage.items.len(), 0); assert_eq!(id, 1); env::remove_var("HOME"); Ok(()) } fn storage_with_item() -> io::Result<(TempDir, FileStorage)> { let tmp_dir = set_config_dir()?; let storage = FileStorage::new(); let json_storage_buf = b"[{ \"id\": 1, \"name\": \"foo item\", \"obtained\": false, \"created_at\": \"2021-04-30T05:23:39.821Z\" }]"; let json_path = storage.json_file_path()?; let mut f = fs::OpenOptions::new() .read(true) .write(true) .create_new(true) .open(json_path)?; f.write_all(json_storage_buf)?; Ok((tmp_dir, storage)) } fn set_config_dir() -> io::Result<TempDir> { let tmp_dir = TempDir::new()?; env::set_var("HOME", tmp_dir.path()); let config_dir = format!("{}/{}", tmp_dir.path().display(), ".pickup"); fs::create_dir_all(config_dir)?; Ok(tmp_dir) } }
use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct TemporaryUser { pub email: String, pub password: String, }
use crate::api::v1::ceo::product::model::ShopInfo; use crate::api::v1::user::shop::model::{GetList, GetWithId}; use crate::errors::ServiceError; use crate::models::msg::Msg; use crate::models::shop::Shop; use crate::models::DbExecutor; use crate::schema::shop::dsl::{id, shop as tb}; use actix::Handler; use diesel; use diesel::prelude::*; use diesel::sql_query; use diesel::sql_types::Uuid; use serde_json::json; impl Handler<GetWithId> for DbExecutor { type Result = Result<Msg, ServiceError>; fn handle(&mut self, msg: GetWithId, _: &mut Self::Context) -> Self::Result { let conn = &self.0.get()?; let shop = tb.filter(&id.eq(&msg.id)).load::<Shop>(conn)?.pop(); match shop { Some(_shop) => { let res = sql_query( " select s_id,s_info from view_shop_info_user where s_id = $1 ", ) .bind::<Uuid, _>(&msg.id) .get_result::<ShopInfo>(conn)?; let payload = json!({ "shop_info": res, }); Ok(Msg { status: 200, data: payload, }) } None => Err(ServiceError::BadRequest("없다".into())), } } } impl Handler<GetList> for DbExecutor { type Result = Result<Msg, ServiceError>; fn handle(&mut self, _msg: GetList, _: &mut Self::Context) -> Self::Result { let conn = &self.0.get()?; let shops = tb.load::<Shop>(conn)?; let payload = json!({ "shops": shops, }); Ok(Msg { status: 200, data: payload, }) } }
use crate::smb2::requests::session_setup::SessionSetup; /// Serializes the session setup request body. pub fn serialize_session_setup_request_body(request: &SessionSetup) -> Vec<u8> { let mut serialized_request: Vec<u8> = Vec::new(); serialized_request.append(&mut request.structure_size.clone()); serialized_request.append(&mut request.flags.clone()); serialized_request.append(&mut request.security_mode.clone()); serialized_request.append(&mut request.capabilities.clone()); serialized_request.append(&mut request.channel.clone()); serialized_request.append(&mut request.security_buffer_offset.clone()); serialized_request.append(&mut request.security_buffer_length.clone()); serialized_request.append(&mut request.previous_session_id.clone()); serialized_request.append(&mut request.buffer.clone()); serialized_request } #[cfg(test)] mod tests { use super::*; use crate::builder::session_setup_negotiate_request::INITIAL_SECURITY_BLOB; struct Setup { session_setup: SessionSetup, } impl Setup { pub fn new() -> Self { let mut session_setup = SessionSetup::default(); session_setup.flags = vec![0]; session_setup.security_mode = vec![1]; session_setup.capabilities = b"\x01\x00\x00\x00".to_vec(); session_setup.security_buffer_offset = b"\x58\x00".to_vec(); session_setup.security_buffer_length = b"\x4a\x00".to_vec(); session_setup.previous_session_id = vec![0; 8]; session_setup.buffer = INITIAL_SECURITY_BLOB.to_vec(); Setup { session_setup } } } #[test] fn test_serialize_session_setup_request_body() { let setup = Setup::new(); let mut expected_byte_array = b"\x19\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\ \x58\x00\x4a\x00\x00\x00\x00\x00\x00\x00\x00\x00" .to_vec(); expected_byte_array.append(&mut INITIAL_SECURITY_BLOB.to_vec()); assert_eq!( expected_byte_array, serialize_session_setup_request_body(&setup.session_setup) ); } }
#![no_std] #![feature(allocator_api)] #![feature(test)] #![feature(trusted_len)] #![feature(exact_size_is_empty)] #![feature(let_else)] #![feature(str_internals)] #![feature(const_option_ext)] #![feature(slice_take)] #![feature(arbitrary_enum_discriminant)] #![feature(min_specialization)] #![feature(extend_one)] #![feature(can_vector)] extern crate alloc; #[cfg(any(test, feature = "std"))] extern crate std; #[cfg(test)] extern crate test; use core::fmt; mod bitvec; mod flags; pub mod helpers; mod iter; mod matcher; mod select; mod spec; mod traits; pub use self::bitvec::BitVec; pub use self::flags::{BinaryFlags, Encoding}; pub use self::iter::{BitsIter, ByteIter}; pub use self::matcher::Matcher; pub use self::select::{MaybePartialByte, Selection}; pub use self::spec::BinaryEntrySpecifier; pub use self::traits::{Aligned, Binary, Bitstring, FromEndianBytes, ToEndianBytes}; /// Represents how bytes of a value are laid out in memory: /// /// Big-endian systems store the most-significant byte at the lowest memory address, and the least-significant /// byte at the highest memory address. /// /// Little-endian systems store the least-significant byte at the lowest memory address, and the most-significant /// byte at the highest memory address. /// /// When thinking about values like memory addresses or integers, we tend to think about the textual representation, /// as this is most often what we are presented with when printing them or viewing them in a debugger, and it can be /// a useful mental model too, however it can be a bit confusing to read them and reason about endianness. /// /// This is because, generally, when we visualize memory the following rules are used: /// /// * Bytes of memory are printed left-to-right, i.e. the left is the lowest memory address, and increases as you read towards the right. /// * Bits of a byte are the opposite; the most-significant bits appear first, decreasing to the least-significant. /// /// So lets apply that to an example, a 16-bit integer 64542, as viewed on a little-endian machine: /// /// * 0xfc1e (little-endian hex) /// * 0x1efc (big-endian hex) /// * 0b1111110000011110 (little-endian binary) /// * 0b0001111011111100 (big-endian binary) /// /// Well that's confusing, The bytes appear to be backwards! The little-endian version has the most-significant bits in the least-significant /// byte, and the big-endian version has the least-significant bits in the most-significant byte. What's going on here? /// /// What I find helps with this is to use the following rules instead: /// /// * Define `origin` as the right-most byte in the sequence /// * Read bytes starting from the origin, i.e. right-to-left /// * Read bits within a byte left-to-right as normal (i.e. most-significant bit is on the left) /// * Endianness determines how to read the bytes from the origin; big-endian has the most-significant byte at the origin, /// and little-endian has the least-significant byte at the origin /// /// If we apply those rules to the previous examples, we can see that the textual representation makes more sense now. /// The little-endian hex is read starting with the least-significant byte 0x1e, followed by 0xfc; while the big-endian /// integer is read starting with the most-significant byte 0xfc, followed by 0x1e. /// /// But this can make calculating the value from the text representation a bit awkward still, is there a trick for that? /// The answer is to normalize out the endianness, so that we can always read a value from most-significant bytes (and bits) /// left-to-right. When the native endianness matches the endianness of the value (i.e. little-endian value on little-endian /// machine, or big-endian value on big-endian machine), this is already the case. When reading a value with non-native endianness /// though, we need to swap the order of the bytes first. /// #[repr(u8)] #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Endianness { /// Most-significant bits "first" Big = 0, Little, Native, } impl fmt::Display for Endianness { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Big => f.write_str("big"), Self::Little => f.write_str("little"), Self::Native => f.write_str("native"), } } }
use proconio::input; fn main() { input! { x:i32, y:i32, z:i32, } println!("{} {} {}", z, x, y); }
//! <div align="center"> //! <h1>awto</h1> //! //! <p> //! <strong>Awtomate your 🦀 microservices with awto</strong> //! </p> //! //! </div> //! //! # awto-cli //! //! Command-line-interface for compiling projects built with [`awto`](https://docs.rs/awto). //! //! See more on the [repository](https://github.com/awto-rs/awto). use std::io::Write; use anyhow::Result; use async_trait::async_trait; use clap::Parser; use colored::Colorize; use compile::Compile; use log::{error, Level, LevelFilter}; mod compile; mod macros; mod util; /// Awto cli #[derive(Parser)] struct Opts { #[clap(subcommand)] pub subcmd: SubCommand, } #[derive(Parser)] enum SubCommand { Compile(Compile), } #[tokio::main] async fn main() { let opts: Opts = Opts::parse(); let mut cmd = match opts.subcmd { SubCommand::Compile(compile) => match compile.subcmd { Some(compile::SubCommand::Database(database)) => runnable_cmd!(database), Some(compile::SubCommand::Protobuf(protobuf)) => runnable_cmd!(protobuf), None => runnable_cmd!(compile), }, }; let log_level = if cmd.is_verbose() { LevelFilter::Debug } else { LevelFilter::Info }; env_logger::Builder::new() .filter_level(log_level) .format(|buf, record| { let prefix = match record.level() { Level::Error => "error".red(), Level::Warn => "warn".yellow(), Level::Info => "info".blue(), Level::Debug => "debug".purple(), Level::Trace => "trace".cyan(), } .bold(); writeln!(buf, "{} {}", prefix, record.args()) }) .init(); if let Err(err) = cmd.run().await { error!("{}", err); if cmd.is_verbose() { let err_chain = err.chain().skip(1); if err_chain.clone().next().is_some() { eprintln!("{}", "\nCaused by:".italic().truecolor(190, 190, 190)); } err_chain .for_each(|cause| eprintln!(" - {}", cause.to_string().truecolor(190, 190, 190))); } #[cfg(not(debug_assertions))] eprintln!( "\nIf the problem persists, please submit an issue on the Github repository.\n{}", "https://github.com/awto-rs/awto/issues/new".underline() ); std::process::exit(1); } } #[async_trait] pub trait Runnable { async fn run(&mut self) -> Result<()>; fn is_verbose(&self) -> bool { false } }
#[macro_use] extern crate clap; extern crate da_lab; use da_lab::*; use clap::App; pub const SETTING_JSON: &'static str = "setting.json"; fn main() { task::init(); let cli = load_yaml!("exec.yml"); let m = App::from_yaml(cli).get_matches(); let setting_json = m.value_of("setting").unwrap_or(SETTING_JSON); let setting_path = ::std::path::Path::new(setting_json); let setting = io::read_json(&setting_path).expect("Invalid JSON"); task::execute(setting); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ContentAccessRestrictionLevel(pub i32); impl ContentAccessRestrictionLevel { pub const Allow: ContentAccessRestrictionLevel = ContentAccessRestrictionLevel(0i32); pub const Warn: ContentAccessRestrictionLevel = ContentAccessRestrictionLevel(1i32); pub const Block: ContentAccessRestrictionLevel = ContentAccessRestrictionLevel(2i32); pub const Hide: ContentAccessRestrictionLevel = ContentAccessRestrictionLevel(3i32); } impl ::core::convert::From<i32> for ContentAccessRestrictionLevel { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ContentAccessRestrictionLevel { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ContentAccessRestrictionLevel { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.ContentRestrictions.ContentAccessRestrictionLevel;i4)"); } impl ::windows::core::DefaultType for ContentAccessRestrictionLevel { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ContentRestrictionsBrowsePolicy(pub ::windows::core::IInspectable); impl ContentRestrictionsBrowsePolicy { pub fn GeographicRegion(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn MaxBrowsableAgeRating(&self) -> ::windows::core::Result<super::super::Foundation::IReference<u32>> { 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<u32>>(result__) } } #[cfg(feature = "Foundation")] pub fn PreferredAgeRating(&self) -> ::windows::core::Result<super::super::Foundation::IReference<u32>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<u32>>(result__) } } } unsafe impl ::windows::core::RuntimeType for ContentRestrictionsBrowsePolicy { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.ContentRestrictions.ContentRestrictionsBrowsePolicy;{8c0133a4-442e-461a-8757-fad2f5bd37e4})"); } unsafe impl ::windows::core::Interface for ContentRestrictionsBrowsePolicy { type Vtable = IContentRestrictionsBrowsePolicy_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8c0133a4_442e_461a_8757_fad2f5bd37e4); } impl ::windows::core::RuntimeName for ContentRestrictionsBrowsePolicy { const NAME: &'static str = "Windows.Media.ContentRestrictions.ContentRestrictionsBrowsePolicy"; } impl ::core::convert::From<ContentRestrictionsBrowsePolicy> for ::windows::core::IUnknown { fn from(value: ContentRestrictionsBrowsePolicy) -> Self { value.0 .0 } } impl ::core::convert::From<&ContentRestrictionsBrowsePolicy> for ::windows::core::IUnknown { fn from(value: &ContentRestrictionsBrowsePolicy) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ContentRestrictionsBrowsePolicy { 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 ContentRestrictionsBrowsePolicy { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ContentRestrictionsBrowsePolicy> for ::windows::core::IInspectable { fn from(value: ContentRestrictionsBrowsePolicy) -> Self { value.0 } } impl ::core::convert::From<&ContentRestrictionsBrowsePolicy> for ::windows::core::IInspectable { fn from(value: &ContentRestrictionsBrowsePolicy) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ContentRestrictionsBrowsePolicy { 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 ContentRestrictionsBrowsePolicy { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ContentRestrictionsBrowsePolicy {} unsafe impl ::core::marker::Sync for ContentRestrictionsBrowsePolicy {} #[repr(transparent)] #[doc(hidden)] pub struct IContentRestrictionsBrowsePolicy(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IContentRestrictionsBrowsePolicy { type Vtable = IContentRestrictionsBrowsePolicy_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8c0133a4_442e_461a_8757_fad2f5bd37e4); } #[repr(C)] #[doc(hidden)] pub struct IContentRestrictionsBrowsePolicy_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IRatedContentDescription(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRatedContentDescription { type Vtable = IRatedContentDescription_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x694866df_66b2_4dc3_96b1_f090eedee255); } #[repr(C)] #[doc(hidden)] pub struct IRatedContentDescription_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut RatedContentCategory) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: RatedContentCategory) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IRatedContentDescriptionFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRatedContentDescriptionFactory { type Vtable = IRatedContentDescriptionFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2e38df62_9b90_4fa6_89c1_4b8d2ffb3573); } #[repr(C)] #[doc(hidden)] pub struct IRatedContentDescriptionFactory_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, id: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, title: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, category: RatedContentCategory, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IRatedContentRestrictions(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRatedContentRestrictions { type Vtable = IRatedContentRestrictions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3f7f23cb_ba07_4401_a49d_8b9222205723); } #[repr(C)] #[doc(hidden)] pub struct IRatedContentRestrictions_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ratedcontentdescription: ::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, ratedcontentdescription: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::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 IRatedContentRestrictionsFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRatedContentRestrictionsFactory { type Vtable = IRatedContentRestrictionsFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfb4b2996_c3bd_4910_9619_97cfd0694d56); } #[repr(C)] #[doc(hidden)] pub struct IRatedContentRestrictionsFactory_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, maxagerating: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RatedContentCategory(pub i32); impl RatedContentCategory { pub const General: RatedContentCategory = RatedContentCategory(0i32); pub const Application: RatedContentCategory = RatedContentCategory(1i32); pub const Game: RatedContentCategory = RatedContentCategory(2i32); pub const Movie: RatedContentCategory = RatedContentCategory(3i32); pub const Television: RatedContentCategory = RatedContentCategory(4i32); pub const Music: RatedContentCategory = RatedContentCategory(5i32); } impl ::core::convert::From<i32> for RatedContentCategory { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RatedContentCategory { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for RatedContentCategory { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.ContentRestrictions.RatedContentCategory;i4)"); } impl ::windows::core::DefaultType for RatedContentCategory { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct RatedContentDescription(pub ::windows::core::IInspectable); impl RatedContentDescription { pub fn Id(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Title(&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 SetTitle<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Storage_Streams")] pub fn Image(&self) -> ::windows::core::Result<super::super::Storage::Streams::IRandomAccessStreamReference> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Storage::Streams::IRandomAccessStreamReference>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn SetImage<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IRandomAccessStreamReference>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Category(&self) -> ::windows::core::Result<RatedContentCategory> { let this = self; unsafe { let mut result__: RatedContentCategory = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<RatedContentCategory>(result__) } } pub fn SetCategory(&self, value: RatedContentCategory) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn Ratings(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<::windows::core::HSTRING>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn SetRatings<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IVector<::windows::core::HSTRING>>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(id: Param0, title: Param1, category: RatedContentCategory) -> ::windows::core::Result<RatedContentDescription> { Self::IRatedContentDescriptionFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), id.into_param().abi(), title.into_param().abi(), category, &mut result__).from_abi::<RatedContentDescription>(result__) }) } pub fn IRatedContentDescriptionFactory<R, F: FnOnce(&IRatedContentDescriptionFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<RatedContentDescription, IRatedContentDescriptionFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for RatedContentDescription { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.ContentRestrictions.RatedContentDescription;{694866df-66b2-4dc3-96b1-f090eedee255})"); } unsafe impl ::windows::core::Interface for RatedContentDescription { type Vtable = IRatedContentDescription_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x694866df_66b2_4dc3_96b1_f090eedee255); } impl ::windows::core::RuntimeName for RatedContentDescription { const NAME: &'static str = "Windows.Media.ContentRestrictions.RatedContentDescription"; } impl ::core::convert::From<RatedContentDescription> for ::windows::core::IUnknown { fn from(value: RatedContentDescription) -> Self { value.0 .0 } } impl ::core::convert::From<&RatedContentDescription> for ::windows::core::IUnknown { fn from(value: &RatedContentDescription) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for RatedContentDescription { 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 RatedContentDescription { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<RatedContentDescription> for ::windows::core::IInspectable { fn from(value: RatedContentDescription) -> Self { value.0 } } impl ::core::convert::From<&RatedContentDescription> for ::windows::core::IInspectable { fn from(value: &RatedContentDescription) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for RatedContentDescription { 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 RatedContentDescription { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for RatedContentDescription {} unsafe impl ::core::marker::Sync for RatedContentDescription {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct RatedContentRestrictions(pub ::windows::core::IInspectable); impl RatedContentRestrictions { 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<RatedContentRestrictions, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn GetBrowsePolicyAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<ContentRestrictionsBrowsePolicy>> { 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::IAsyncOperation<ContentRestrictionsBrowsePolicy>>(result__) } } #[cfg(feature = "Foundation")] pub fn GetRestrictionLevelAsync<'a, Param0: ::windows::core::IntoParam<'a, RatedContentDescription>>(&self, ratedcontentdescription: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<ContentAccessRestrictionLevel>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), ratedcontentdescription.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<ContentAccessRestrictionLevel>>(result__) } } #[cfg(feature = "Foundation")] pub fn RequestContentAccessAsync<'a, Param0: ::windows::core::IntoParam<'a, RatedContentDescription>>(&self, ratedcontentdescription: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), ratedcontentdescription.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn RestrictionsChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventHandler<::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 RemoveRestrictionsChanged<'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() } } pub fn CreateWithMaxAgeRating(maxagerating: u32) -> ::windows::core::Result<RatedContentRestrictions> { Self::IRatedContentRestrictionsFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), maxagerating, &mut result__).from_abi::<RatedContentRestrictions>(result__) }) } pub fn IRatedContentRestrictionsFactory<R, F: FnOnce(&IRatedContentRestrictionsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<RatedContentRestrictions, IRatedContentRestrictionsFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for RatedContentRestrictions { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.ContentRestrictions.RatedContentRestrictions;{3f7f23cb-ba07-4401-a49d-8b9222205723})"); } unsafe impl ::windows::core::Interface for RatedContentRestrictions { type Vtable = IRatedContentRestrictions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3f7f23cb_ba07_4401_a49d_8b9222205723); } impl ::windows::core::RuntimeName for RatedContentRestrictions { const NAME: &'static str = "Windows.Media.ContentRestrictions.RatedContentRestrictions"; } impl ::core::convert::From<RatedContentRestrictions> for ::windows::core::IUnknown { fn from(value: RatedContentRestrictions) -> Self { value.0 .0 } } impl ::core::convert::From<&RatedContentRestrictions> for ::windows::core::IUnknown { fn from(value: &RatedContentRestrictions) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for RatedContentRestrictions { 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 RatedContentRestrictions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<RatedContentRestrictions> for ::windows::core::IInspectable { fn from(value: RatedContentRestrictions) -> Self { value.0 } } impl ::core::convert::From<&RatedContentRestrictions> for ::windows::core::IInspectable { fn from(value: &RatedContentRestrictions) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for RatedContentRestrictions { 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 RatedContentRestrictions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for RatedContentRestrictions {} unsafe impl ::core::marker::Sync for RatedContentRestrictions {}
use proconio::input; fn main() { input! { n: usize, ss: [String; n], }; for i in (0..n).rev() { println!("{}", ss[i]); } }
//! A generic event loop for games and interactive applications #![deny(missing_docs)] #![deny(missing_copy_implementations)] extern crate clock_ticks; extern crate window; use std::thread::sleep_ms; use std::cmp; use std::marker::PhantomData; use std::cell::RefCell; use std::rc::Rc; use window::Window; /// Render arguments #[derive(Copy, Clone, PartialEq, Debug)] pub struct RenderArgs { /// Extrapolated time in seconds, used to do smooth animation. pub ext_dt: f64, /// The width of rendered area. pub width: u32, /// The height of rendered area. pub height: u32, } /// After render arguments. #[derive(Copy, Clone, PartialEq, Debug)] pub struct AfterRenderArgs; /// Update arguments, such as delta time in seconds #[derive(Copy, Clone, PartialEq, Debug)] pub struct UpdateArgs { /// Delta time in seconds. pub dt: f64, } /// Idle arguments, such as expected idle time in seconds. #[derive(Copy, Clone, PartialEq, Debug)] pub struct IdleArgs { /// Expected idle time in seconds. pub dt: f64 } /// Methods required to map from consumed event to emitted event. pub trait EventMap<I> { /// Creates a render event. fn render(args: RenderArgs) -> Self; /// Creates an after render event. fn after_render(args: AfterRenderArgs) -> Self; /// Creates an update event. fn update(args: UpdateArgs) -> Self; /// Creates an input event. fn input(args: I) -> Self; /// Creates an idle event. fn idle(IdleArgs) -> Self; } /// Tells whether last emitted event was idle or not. #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum Idle { No, Yes } #[derive(Copy, Clone, Debug)] enum State { Render, SwapBuffers, UpdateLoop(Idle), HandleEvents, Update, } /// An event loop iterator /// /// *Warning: Because the iterator polls events from the window back-end, /// it must be used on the same thread as the window back-end (usually main thread), /// unless the window back-end supports multi-thread event polling.* /// /// Example: /// /// ~~~ignore /// fn main() { /// let opengl = shader_version::opengl::OpenGL_3_2; /// let window = Sdl2Window::new( /// opengl, /// WindowSettings { /// title: "Example".to_string(), /// size: [500, 500], /// fullscreen: false, /// exit_on_esc: true, /// samples: 0, /// } /// ) /// let ref mut gl = Gl::new(); /// let window = RefCell::new(window); /// for e in Events::new(&window) /// .set(Ups(120)) /// .set(MaxFps(60)) { /// use event::RenderEvent; /// e.render(|args| { /// // Set the viewport in window to render graphics. /// gl.viewport(0, 0, args.width as i32, args.height as i32); /// // Create graphics context with absolute coordinates. /// let c = Context::abs(args.width as f64, args.height as f64); /// // Do rendering here. /// }); /// } /// } /// ~~~ pub struct Events<W, E> where W: Window, E: EventMap<<W as Window>::Event> { window: Rc<RefCell<W>>, state: State, last_update: u64, last_frame: u64, dt_update_in_ns: u64, dt_frame_in_ns: u64, dt: f64, swap_buffers: bool, _marker_e: PhantomData<E>, } static BILLION: u64 = 1_000_000_000; fn ns_to_ms(ns: u64) -> u32 { (ns / 1_000_000) as u32 } /// The default updates per second. pub const DEFAULT_UPS: u64 = 120; /// The default maximum frames per second. pub const DEFAULT_MAX_FPS: u64 = 60; impl<W, E> Events<W, E> where W: Window, E: EventMap<<W as Window>::Event> { /// Creates a new event iterator with default UPS and FPS settings. pub fn new(window: Rc<RefCell<W>>) -> Events<W, E> { let start = clock_ticks::precise_time_ns(); let updates_per_second = DEFAULT_UPS; let max_frames_per_second = DEFAULT_MAX_FPS; Events { window: window, state: State::Render, last_update: start, last_frame: start, dt_update_in_ns: BILLION / updates_per_second, dt_frame_in_ns: BILLION / max_frames_per_second, dt: 1.0 / updates_per_second as f64, swap_buffers: true, _marker_e: PhantomData, } } /// The number of updates per second /// /// This is the fixed update rate on average over time. /// If the event loop lags, it will try to catch up. pub fn ups(mut self, frames: u64) -> Self { self.dt_update_in_ns = BILLION / frames; self.dt = 1.0 / frames as f64; self } /// The maximum number of frames per second /// /// The frame rate can be lower because the /// next frame is always scheduled from the previous frame. /// This causes the frames to "slip" over time. pub fn max_fps(mut self, frames: u64) -> Self { self.dt_frame_in_ns = BILLION / frames; self } /// Enable or disable automatic swapping of buffers. pub fn swap_buffers(mut self, enable: bool) -> Self { self.swap_buffers = enable; self } } impl<W, E> Iterator for Events<W, E> where W: Window, E: EventMap<<W as Window>::Event>, { type Item = E; /// Returns the next game event. fn next(&mut self) -> Option<E> { loop { self.state = match self.state { State::Render => { if self.window.borrow().should_close() { return None; } let start_render = clock_ticks::precise_time_ns(); self.last_frame = start_render; let size = self.window.borrow().size(); if size.width != 0 && size.height != 0 { // Swap buffers next time. self.state = State::SwapBuffers; return Some(EventMap::render(RenderArgs { // Extrapolate time forward to allow smooth motion. ext_dt: (start_render - self.last_update) as f64 / BILLION as f64, width: size.width, height: size.height, })); } State::UpdateLoop(Idle::No) } State::SwapBuffers => { if self.swap_buffers { self.window.borrow_mut().swap_buffers(); self.state = State::UpdateLoop(Idle::No); return Some(EventMap::after_render(AfterRenderArgs)); } else { State::UpdateLoop(Idle::No) } } State::UpdateLoop(ref mut idle) => { let current_time = clock_ticks::precise_time_ns(); let next_frame = self.last_frame + self.dt_frame_in_ns; let next_update = self.last_update + self.dt_update_in_ns; let next_event = cmp::min(next_frame, next_update); if next_event > current_time { if let Some(x) = self.window.borrow_mut().poll_event() { *idle = Idle::No; return Some(EventMap::input(x)); } else if *idle == Idle::No { *idle = Idle::Yes; let seconds = ((next_event - current_time) as f64) / (BILLION as f64); return Some(EventMap::idle(IdleArgs { dt: seconds })) } sleep_ms(ns_to_ms(next_event - current_time)); State::UpdateLoop(Idle::No) } else if next_event == next_frame { State::Render } else { State::HandleEvents } } State::HandleEvents => { // Handle all events before updating. match self.window.borrow_mut().poll_event() { None => State::Update, Some(x) => { return Some(EventMap::input(x)); }, } } State::Update => { self.state = State::UpdateLoop(Idle::No); self.last_update += self.dt_update_in_ns; return Some(EventMap::update(UpdateArgs{ dt: self.dt })); } }; } } }
//! IOx authorization client. //! //! Authorization client interface to be used by IOx components to //! restrict access to authorized requests where required. #![deny(rustdoc::broken_intra_doc_links, rust_2018_idioms)] #![warn( missing_copy_implementations, missing_docs, clippy::explicit_iter_loop, // See https://github.com/influxdata/influxdb_iox/pull/1671 clippy::future_not_send, clippy::use_self, clippy::clone_on_ref_ptr, clippy::todo, clippy::dbg_macro, unused_crate_dependencies )] #![allow(rustdoc::private_intra_doc_links)] // Workaround for "unused crate" lint false positives. use workspace_hack as _; use base64::{prelude::BASE64_STANDARD, Engine}; use generated_types::influxdata::iox::authz::v1::{self as proto}; use observability_deps::tracing::warn; mod authorizer; pub use authorizer::Authorizer; mod iox_authorizer; pub use iox_authorizer::{Error, IoxAuthorizer}; mod instrumentation; pub use instrumentation::AuthorizerInstrumentation; mod permission; pub use permission::{Action, Permission, Resource}; #[cfg(feature = "http")] pub mod http; /// Extract a token from an HTTP header or gRPC metadata value. pub fn extract_token<T: AsRef<[u8]> + ?Sized>(value: Option<&T>) -> Option<Vec<u8>> { let mut parts = value?.as_ref().splitn(2, |&v| v == b' '); let token = match parts.next()? { b"Token" | b"Bearer" => parts.next()?.to_vec(), b"Basic" => parts .next() .and_then(|v| BASE64_STANDARD.decode(v).ok())? .splitn(2, |&v| v == b':') .nth(1)? .to_vec(), _ => return None, }; if token.is_empty() { None } else { Some(token) } } #[cfg(test)] mod tests { use super::*; #[test] fn verify_error_from_tonic_status() { let s = tonic::Status::resource_exhausted("test error"); let e = Error::from(s); assert_eq!( "token verification not possible: test error", format!("{e}") ) } #[test] fn test_extract_token() { assert_eq!(None, extract_token::<&str>(None)); assert_eq!(None, extract_token(Some(""))); assert_eq!(None, extract_token(Some("Basic"))); assert_eq!(None, extract_token(Some("Basic Og=="))); // ":" assert_eq!(None, extract_token(Some("Basic dXNlcm5hbWU6"))); // "username:" assert_eq!(None, extract_token(Some("Basic Og=="))); // ":" assert_eq!( Some(b"password".to_vec()), extract_token(Some("Basic OnBhc3N3b3Jk")) ); // ":password" assert_eq!( Some(b"password2".to_vec()), extract_token(Some("Basic dXNlcm5hbWU6cGFzc3dvcmQy")) ); // "username:password2" assert_eq!(None, extract_token(Some("Bearer"))); assert_eq!(None, extract_token(Some("Bearer "))); assert_eq!(Some(b"token".to_vec()), extract_token(Some("Bearer token"))); assert_eq!(None, extract_token(Some("Token"))); assert_eq!(None, extract_token(Some("Token "))); assert_eq!( Some(b"token2".to_vec()), extract_token(Some("Token token2")) ); } }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::HashMap; use std::sync::Arc; use common_base::base::tokio; use common_exception::Result; use common_expression::DataBlock; use common_storages_fuse::operations::AppendOperationLogEntry; use databend_query::api::PrecommitBlock; use storages_common_table_meta::meta::BlockMeta; use storages_common_table_meta::meta::Compression; use storages_common_table_meta::meta::SegmentInfo; use storages_common_table_meta::meta::Statistics; #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_precommit_ser_and_deser() -> Result<()> { let block_meta = BlockMeta::new( 1, 2, 3, HashMap::new(), HashMap::new(), None, ("_b/1.json".to_string(), 1), None, 4, Compression::Lz4Raw, ); let segment_info = SegmentInfo::new(vec![Arc::new(block_meta)], Statistics::default()); let log_entry = AppendOperationLogEntry::new("/_sg/1.json".to_string(), Arc::new(segment_info)); let precommit_block = DataBlock::try_from(log_entry)?; let test_precommit = PrecommitBlock(precommit_block); let mut bytes = vec![]; PrecommitBlock::write(test_precommit.clone(), &mut bytes)?; let mut read = bytes.as_slice(); assert_eq!( test_precommit.0.to_string(), PrecommitBlock::read(&mut read)?.0.to_string() ); Ok(()) }
pub use self::{ module::{Module, ModuleFromPathError, ModuleKind}, module_provider::{ FileSystemModuleProvider, InMemoryModuleProvider, ModuleProvider, OverlayModuleProvider, }, module_provider_owner::{ModuleProviderOwner, MutableModuleProviderOwner}, package::{Package, PackagesPath}, use_path::UsePath, }; use salsa::query_group; use std::sync::Arc; #[allow(clippy::module_inception)] mod module; mod module_provider; mod module_provider_owner; mod package; mod use_path; #[query_group(ModuleDbStorage)] pub trait ModuleDb: ModuleProviderOwner { fn get_module_content_as_string(&self, module: Module) -> Option<Arc<String>>; fn get_module_content(&self, module: Module) -> Option<Arc<Vec<u8>>>; } fn get_module_content_as_string(db: &dyn ModuleDb, module: Module) -> Option<Arc<String>> { let content = get_module_content(db, module)?; String::from_utf8((*content).clone()).ok().map(Arc::new) } fn get_module_content(db: &dyn ModuleDb, module: Module) -> Option<Arc<Vec<u8>>> { // The following line of code shouldn't be neccessary, but it is. // // We call `GetModuleContentQuery.in_db_mut(self).invalidate(module);` // in `Database.did_open_module(…)`, `.did_change_module(…)`, and // `.did_close_module(…)` which correctly forces Salsa to re-run this query // function the next time this module is used. However, even though the // return value changes, Salsa doesn't record an updated `changed_at` value // in its internal `ActiveQuery` struct. `Runtime.report_untracked_read()` // manually sets this to the current revision. db.salsa_runtime().report_untracked_read(); db.get_module_provider().get_content(&module) }
use super::{CelestialBody, Contract}; use crate::codec::{Decode, Encode}; use crate::{remote_type, RemoteObject}; use std::collections::BTreeMap; remote_type!( /// Waypoints are the location markers you can see on the map view showing you where contracts /// are targeted for. With this structure, you can obtain coordinate data for the locations of /// these waypoints. Obtained by calling `SpaceCenter::waypoint_manager()`. object SpaceCenter.WaypointManager { properties: { { Waypoints { /// Returns a list of all existing waypoints. /// /// **Game Scenes**: All get: waypoints -> Vec<Waypoint> } } { Colors { /// Returns an example map of known color - seed pairs. Any other integers /// may be used as seed. /// /// **Game Scenes**: All get: colors -> BTreeMap<String, i32> } } { Icons { /// Returns all available icons (from “GameData/Squad/Contracts/Icons/”). /// /// **Game Scenes**: All get: icons -> Vec<String> } } } methods: { { /// Creates a waypoint at the given position at ground level, and /// returns a `Waypoint` object that can be used to modify it. /// /// **Game Scenes**: All /// /// # Arguments /// * `latitude` - Longitude of the waypoint. /// * `longitude` - Longitude of the waypoint. /// * `body` - Celestial body the waypoint is attached to. /// * `name` - Name of the waypoint. fn add_waypoint(latitude: f64, longitude: f64, body: &CelestialBody, name: &str) -> Waypoint { AddWaypoint(latitude, longitude, body, name) } } { /// Creates a waypoint at the given position and altitude, and /// returns a `Waypoint` object that can be used to modify it. /// /// **Game Scenes**: All /// /// # Arguments /// * `latitude` - Longitude of the waypoint. /// * `longitude` - Longitude of the waypoint. /// * `altitude` - Altitude (above sea level) of the waypoint. /// * `body` - Celestial body the waypoint is attached to. /// * `name` - Name of the waypoint. fn add_waypoint_at_altitude(latitude: f64, longitude: f64, altitude: f64, body: &CelestialBody, name: &str) -> Waypoint { AddWaypointAtAltitude(latitude, longitude, altitude, body, name) } } } }); remote_type!( /// Represents a waypoint. Can be created using `WaypointManager::add_waypoint()`. object SpaceCenter.Waypoint { properties: { { Body { /// Returns the celestial body the waypoint is attached to. /// /// **Game Scenes**: Flight get: body -> CelestialBody, /// Sets the celestial body the waypoint is attached to. /// /// **Game Scenes**: Flight set: set_body(&CelestialBody) } } { Name { /// Returns the name of the waypoint as it appears on the map and the contract. /// /// **Game Scenes**: Flight get: name -> String, /// Sets the name of the waypoint as it appears on the map and the contract. /// /// **Game Scenes**: Flight set: set_name(&str) } } { Color { /// Returns the seed of the icon color. See `WaypointManager::colors()` /// for example colors. /// /// **Game Scenes**: Flight get: color -> i32, /// Sets the seed of the icon color. See `WaypointManager::colors()` /// for example colors. /// /// **Game Scenes**: Flight set: set_color(i32) } } { Icon { /// Returns the icon of the waypoint. /// /// **Game Scenes**: Flight get: icon -> String, /// Sets the icon of the waypoint. /// /// **Game Scenes**: Flight set: set_icon(&str) } } { Latitude { /// Returns the latitude of the waypoint. /// /// **Game Scenes**: Flight get: latitude -> f64, /// Sets the latitude of the waypoint. /// /// **Game Scenes**: Flight set: set_latitude(f64) } } { Longitude { /// Returns the longitude of the waypoint. /// /// **Game Scenes**: Flight get: longitude -> f64, /// Sets the longitude of the waypoint. /// /// **Game Scenes**: Flight set: set_longitude(f64) } } { MeanAltitude { /// Returns the altitude of the waypoint above sea level, in meters. /// /// **Game Scenes**: Flight get: mean_altitude -> f64, /// Sets the altitude of the waypoint above sea level, in meters. /// /// **Game Scenes**: Flight set: set_mean_altitude(f64) } } { SurfaceAltitude { /// Returns the altitude of the waypoint above the surface of the body or /// sea level, whichever is closer, in meters. /// /// **Game Scenes**: Flight get: surface_altitude -> f64, /// Sets the altitude of the waypoint above the surface of the body or /// sea level, whichever is closer, in meters. /// /// **Game Scenes**: Flight set: set_surface_altitude(f64) } } { BedrockAltitude { /// Returns the altitude of the waypoint above the surface of the body, in meters. /// When over water, this is the altitude above the sea floor. /// /// **Game Scenes**: Flight get: bedrock_altitude -> f64, /// Sets the altitude of the waypoint above the surface of the body, in meters. /// When over water, this is the altitude above the sea floor. /// /// **Game Scenes**: Flight set: set_bedrock_altitude(f64) } } { NearSurface { /// Returns `true` if the waypoint is near to the surface of a body. /// /// **Game Scenes**: Flight get: is_near_surface -> bool } } { Grounded { /// Returns `true` if the waypoint is attached to the ground. /// /// **Game Scenes**: Flight get: is_grounded -> bool } } { Index { /// Returns the integer index of this waypoint within its cluster of sibling /// waypoints. In other words, when you have a cluster of waypoints called /// “Somewhere Alpha”, “Somewhere Beta” and “Somewhere Gamma”, the alpha site has /// index 0, the beta site has index 1 and the gamma site has index 2. /// When `Waypoint::is_clustered()` is `false`, this is zero. /// /// **Game Scenes**: Flight get: index -> i32 } } { Clustered { /// Returns `true` if this waypoint is part of a set of clustered waypoints with /// greek letter names appended (Alpha, Beta, Gamma, etc). If true, there is a /// one-to-one correspondence with the greek letter name and the `Waypoint::index()`. /// /// **Game Scenes**: Flight get: is_clustered -> bool } } { HasContract { /// Returns whether the waypoint belongs to a contract. /// /// **Game Scenes**: Flight get: has_contract -> bool } } { Contract { /// Returns the associated contract. /// /// **Game Scenes**: Flight get: contract -> Option<Contract> } } } methods: { { /// Removes the waypoint. /// /// **Game Scenes**: Flight fn remove() { Remove() } } } });
fn solve(n: usize, a: &Vec<Vec<usize>>) { let mut ymins = vec![n; 10]; let mut ymaxs = vec![1; 10]; let mut xmins = vec![n; 10]; let mut xmaxs = vec![1; 10]; for i in 0..n { for j in 0..n { let d = a[i][j]; let y = i + 1; let x = j + 1; ymins[d] = std::cmp::min(ymins[d], y); ymaxs[d] = std::cmp::max(ymaxs[d], y); xmins[d] = std::cmp::min(xmins[d], x); xmaxs[d] = std::cmp::max(xmaxs[d], x); } } macro_rules! chmax { ($a:expr, $b:expr) => { $a = std::cmp::max($a, $b); }; } let mut ans = vec![0; 10]; for i in 0..n { for j in 0..n { let d = a[i][j]; let y = i + 1; let x = j + 1; let ymin = ymins[d]; let ymax = ymaxs[d]; let xmin = xmins[d]; let xmax = xmaxs[d]; let mut s = 0; chmax!(s, (n - y) * (xmax - x)); chmax!(s, (n - y) * (x - xmin)); chmax!(s, (n - x) * (ymax - y)); chmax!(s, (n - x) * (y - ymin)); chmax!(s, (y - 1) * (xmax - x)); chmax!(s, (y - 1) * (x - xmin)); chmax!(s, (x - 1) * (ymax - y)); chmax!(s, (x - 1) * (y - ymin)); chmax!(ans[d], s); } } // println!("ymin={} ymax={} xmin={} xmax={}", ymins[2], ymaxs[2], xmins[2], xmaxs[2]); println!( "{}", ans.iter() .map(|ans| ans.to_string()) .collect::<Vec<String>>() .join(" ") ); } fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let t: usize = rd.get(); for _ in 0..t { let n: usize = rd.get(); let a: Vec<Vec<usize>> = (0..n) .map(|_| { let s: String = rd.get(); s.chars().map(|ch| ch as usize - '0' as usize).collect() }) .collect(); solve(n, &a); } } pub struct ProconReader<R: std::io::Read> { reader: R, } impl<R: std::io::Read> ProconReader<R> { pub fn new(reader: R) -> Self { Self { reader } } pub fn get<T: std::str::FromStr>(&mut self) -> T { use std::io::Read; let buf = self .reader .by_ref() .bytes() .map(|b| b.unwrap()) .skip_while(|&byte| byte == b' ' || byte == b'\n' || byte == b'\r') .take_while(|&byte| byte != b' ' && byte != b'\n' && byte != b'\r') .collect::<Vec<_>>(); std::str::from_utf8(&buf) .unwrap() .parse() .ok() .expect("Parse Error.") } }
use std::{ fs::{self}, io::Cursor, ops::Deref, path::{Path, PathBuf}, sync::Arc, }; use super::database::SenseiDatabase; use crate::{disk::FilesystemLogger, node::NetworkGraph}; use bitcoin::{ blockdata::constants::genesis_block, hashes::hex::FromHex, BlockHash, Network, Txid, }; use lightning::util::ser::ReadableArgs; use lightning::{ chain::{ channelmonitor::ChannelMonitor, keysinterface::{KeysInterface, Sign}, }, routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters}, util::{persist::KVStorePersister, ser::Writeable}, }; use lightning_persister::FilesystemPersister; pub trait KVStoreReader { fn read(&self, key: &str) -> std::io::Result<Option<Vec<u8>>>; fn list(&self, key: &str) -> std::io::Result<Vec<String>>; } pub struct DatabaseStore { database: Arc<SenseiDatabase>, node_id: String, } impl KVStorePersister for DatabaseStore { fn persist<W: Writeable>(&self, key: &str, object: &W) -> std::io::Result<()> { let _entry = self.database .set_value_sync(self.node_id.clone(), key.to_string(), object.encode())?; Ok(()) } } impl KVStoreReader for DatabaseStore { fn read(&self, key: &str) -> std::io::Result<Option<Vec<u8>>> { Ok(self .database .get_value_sync(self.node_id.clone(), key.to_string())? .map(|entry| entry.v)) } fn list(&self, key: &str) -> std::io::Result<Vec<String>> { self.database .list_keys_sync(self.node_id.clone(), key) .map(|full_keys| { let replace_str = format!("{}/", key); full_keys .iter() .map(|full_key| full_key.replace(&replace_str, "")) .collect() }) .map_err(|e| e.into()) } } impl DatabaseStore { pub fn new(database: Arc<SenseiDatabase>, node_id: String) -> Self { Self { database, node_id } } } pub struct FileStore { filesystem_persister: FilesystemPersister, } impl KVStorePersister for FileStore { fn persist<W: Writeable>(&self, key: &str, object: &W) -> std::io::Result<()> { self.filesystem_persister.persist(key, object) } } impl KVStoreReader for FileStore { fn read(&self, key: &str) -> std::io::Result<Option<Vec<u8>>> { let full_path = format!("{}/{}", self.filesystem_persister.get_data_dir(), key); let path = PathBuf::from(full_path); match fs::read(path) { Ok(contents) => Ok(Some(contents)), Err(_) => Ok(None), } } fn list(&self, key: &str) -> std::io::Result<Vec<String>> { let path = format!("{}/{}", self.filesystem_persister.get_data_dir(), key); if !Path::new(&PathBuf::from(&path)).exists() { return Ok(Vec::new()); } let mut res = Vec::new(); for file_option in fs::read_dir(path).unwrap() { let file = file_option.unwrap(); let owned_file_name = file.file_name(); if let Some(filename) = owned_file_name.to_str() { res.push(filename.to_string()) } } Ok(res) } } impl FileStore { pub fn new(root: String) -> Self { Self { filesystem_persister: FilesystemPersister::new(root), } } } pub enum AnyKVStore { File(FileStore), Database(DatabaseStore), } impl KVStorePersister for AnyKVStore { fn persist<W: Writeable>(&self, key: &str, object: &W) -> std::io::Result<()> { match self { AnyKVStore::File(store) => store.persist(key, object), AnyKVStore::Database(store) => store.persist(key, object), } } } impl KVStoreReader for AnyKVStore { fn read(&self, key: &str) -> std::io::Result<Option<Vec<u8>>> { match self { AnyKVStore::File(store) => store.read(key), AnyKVStore::Database(store) => store.read(key), } } fn list(&self, key: &str) -> std::io::Result<Vec<String>> { match self { AnyKVStore::File(store) => store.list(key), AnyKVStore::Database(store) => store.list(key), } } } pub struct SenseiPersister { store: AnyKVStore, network: Network, logger: Arc<FilesystemLogger>, } impl SenseiPersister { pub fn new(store: AnyKVStore, network: Network, logger: Arc<FilesystemLogger>) -> Self { Self { store, network, logger, } } pub fn read_channel_manager(&self) -> std::io::Result<Option<Vec<u8>>> { self.store.read("manager") } pub fn read_network_graph(&self) -> NetworkGraph { if let Ok(Some(contents)) = self.store.read("graph") { let mut cursor = Cursor::new(contents); if let Ok(graph) = NetworkGraph::read(&mut cursor, self.logger.clone()) { return graph; } } let genesis_hash = genesis_block(self.network).header.block_hash(); NetworkGraph::new(genesis_hash, self.logger.clone()) } pub fn read_scorer( &self, network_graph: Arc<NetworkGraph>, ) -> ProbabilisticScorer<Arc<NetworkGraph>, Arc<FilesystemLogger>> { let params = ProbabilisticScoringParameters::default(); if let Ok(Some(contents)) = self.store.read("scorer") { let mut cursor = Cursor::new(contents); if let Ok(scorer) = ProbabilisticScorer::read( &mut cursor, ( params.clone(), Arc::clone(&network_graph), self.logger.clone(), ), ) { return scorer; } } ProbabilisticScorer::new(params, network_graph, self.logger.clone()) } pub fn persist_scorer( &self, scorer: &ProbabilisticScorer<Arc<NetworkGraph>, Arc<FilesystemLogger>>, ) -> std::io::Result<()> { self.store.persist("scorer", scorer) } pub fn persist_graph(&self, graph: &NetworkGraph) -> std::io::Result<()> { self.store.persist("graph", graph) } /// Read `ChannelMonitor`s from disk. pub fn read_channelmonitors<Signer: Sign, K: Deref>( &self, keys_manager: K, ) -> Result<Vec<(BlockHash, ChannelMonitor<Signer>)>, std::io::Error> where K::Target: KeysInterface<Signer = Signer> + Sized, { let filenames = self.store.list("monitors").unwrap(); let mut res = Vec::new(); for filename in filenames { if !filename.is_ascii() || filename.len() < 65 { return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, "Invalid ChannelMonitor file name", )); } if filename.ends_with(".tmp") { // If we were in the middle of committing an new update and crashed, it should be // safe to ignore the update - we should never have returned to the caller and // irrevocably committed to the new state in any way. continue; } let txid = Txid::from_hex(filename.split_at(64).0); if txid.is_err() { return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, "Invalid tx ID in filename", )); } let index: Result<u16, _> = filename.split_at(65).1.parse(); if index.is_err() { return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, "Invalid tx index in filename", )); } let monitor_path = format!("monitors/{}", filename); let contents = self.store.read(&monitor_path)?.unwrap(); let mut buffer = Cursor::new(&contents); match <(BlockHash, ChannelMonitor<Signer>)>::read(&mut buffer, &*keys_manager) { Ok((blockhash, channel_monitor)) => { if channel_monitor.get_funding_txo().0.txid != txid.unwrap() || channel_monitor.get_funding_txo().0.index != index.unwrap() { return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, "ChannelMonitor was stored in the wrong file", )); } res.push((blockhash, channel_monitor)); } Err(e) => { return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, format!("Failed to deserialize ChannelMonitor: {}", e), )) } } } Ok(res) } } impl KVStorePersister for SenseiPersister { fn persist<W: Writeable>(&self, key: &str, object: &W) -> std::io::Result<()> { self.store.persist(key, object) } }
use scheme::LispResult; use scheme::error::LispError::*; use scheme::value::Sexp; use scheme::value::Sexp::*; // pair? // Predicates non-empty list pub fn is_pair(args: &[Sexp]) -> LispResult<Sexp> { let arity = args.len(); if arity != 1 { return Err(ArityMismatch("pair?".to_string(), 1, arity)); } Ok(Sexp::bool(args[0].is_pair())) } // number? pub fn is_number(args: &[Sexp]) -> LispResult<Sexp> { let arity = args.len(); if arity != 1 { return Err(ArityMismatch("number?".to_string(), 1, arity)); } if let Number(_) = args[0] { Ok(True) } else { Ok(False) } } pub fn is_integer(args: &[Sexp]) -> LispResult<Sexp> { let arity = args.len(); if arity != 1 { return Err(ArityMismatch("integer?".to_string(), 1, arity)); } match args[0] { Number(_) => Ok(True), _ => Ok(False), } } pub fn is_rational(args: &[Sexp]) -> LispResult<Sexp> { let arity = args.len(); if arity != 1 { return Err(ArityMismatch("rational?".to_string(), 1, arity)); } match args[0] { Number(_) => Ok(True), _ => Ok(False), } } pub fn is_real(args: &[Sexp]) -> LispResult<Sexp> { let arity = args.len(); if arity != 1 { return Err(ArityMismatch("real?".to_string(), 1, arity)); } match args[0] { Number(_) => Ok(True), _ => Ok(False), } } pub fn is_complex(args: &[Sexp]) -> LispResult<Sexp> { let arity = args.len(); if arity != 1 { return Err(ArityMismatch("complex?".to_string(), 1, arity)); } match args[0] { Number(_) => Ok(True), _ => Ok(False), } } pub fn is_exact(args: &[Sexp]) -> LispResult<Sexp> { let arity = args.len(); if arity != 1 { return Err(ArityMismatch("exact?".to_string(), 1, arity)); } match args[0] { Number(_) => Ok(True), _ => Ok(False), } } pub fn is_inexact(args: &[Sexp]) -> LispResult<Sexp> { let arity = args.len(); if arity != 1 { return Err(ArityMismatch("inexact?".to_string(), 1, arity)); } match args[0] { Number(_) => Ok(False), _ => Ok(False), } } pub fn is_string(args: &[Sexp]) -> LispResult<Sexp> { let arity = args.len(); if arity != 1 { return Err(ArityMismatch("string?".to_string(), 1, arity)); } match args[0] { Str(_, _) => Ok(True), _ => Ok(False), } } pub fn is_char(args: &[Sexp]) -> LispResult<Sexp> { let arity = args.len(); if arity != 1 { return Err(ArityMismatch("char?".to_string(), 1, arity)); } match args[0] { Char(_) => Ok(True), _ => Ok(False), } } pub fn is_symbol(args: &[Sexp]) -> LispResult<Sexp> { let arity = args.len(); if arity != 1 { return Err(ArityMismatch("symbol?".to_string(), 1, arity)); } Ok(Sexp::bool(args[0].is_symbol())) } pub fn is_procedure(args: &[Sexp]) -> LispResult<Sexp> { let arity = args.len(); if arity != 1 { return Err(ArityMismatch("procedure?".to_string(), 1, arity)); } match args[0] { Procedure { .. } => Ok(True), Closure { .. } => Ok(True), _ => Ok(False), } }
/// /// Creates a retina map that can be used to simulate nyctalopia. /// /// # Arguments /// /// - `res` - resolution of the returned retina map /// - `severity` - the severity of the disease, value between 0 and 100 /// pub fn generate(res: (u32, u32), severity: u64) -> image::ImageBuffer<image::Rgba<u8>, Vec<u8>> { let mut mapbuffer = image::ImageBuffer::new(res.0, res.1); for (_, _, pixel) in mapbuffer.enumerate_pixels_mut() { let r = 255; let g = 255; let b = 255; let mut a = 255; a = a - a * severity / 100; *pixel = image::Rgba([r as u8, g as u8, b as u8, a as u8]); } mapbuffer }
use std::cmp; pub type CartId = String; pub type CatalogId = String; pub type PromotionId = String; pub type Quantity = u32; pub type Amount = i32; #[derive(Debug, Clone)] pub struct Product { pub catalog_id: CatalogId, pub unit_price: Amount, } #[derive(Debug, Clone)] pub struct CartItem { item: Product, qty: Quantity, } #[derive(Debug, Clone)] pub enum Cart { Nothing, Empty { id: CartId }, NonEmpty { id: CartId, items: Vec<CartItem> }, PromotingSales { id: CartId, items: Vec<CartItem>, promotions: Vec<SalesPromotion> }, CheckOutReady { id: CartId, items: Vec<CartItem>, promotions: Vec<SalesPromotion>, subtotal: Amount }, } #[derive(Debug, Clone)] pub enum SalesPromotion { Discount { promotion_id: PromotionId, discount: Amount }, } impl Cart { pub fn create(&self, id: CartId) -> Option<Self> { match self { Self::Nothing => Some(Self::Empty { id }), _ => None } } pub fn add_item(&self, item: Product, qty: Quantity) -> Option<Self> { if qty <= 0 || item.unit_price < 0 { None } else { match self { Self::Empty { id } => { let item = CartItem { item, qty }; Some(Self::NonEmpty { id: id.clone(), items: vec![item] }) } Self::NonEmpty { id, items } | Self::CheckOutReady { id, items, .. } => { let mut upd = false; let mut new_items = items.iter().map(|i| { if i.item.catalog_id == item.catalog_id { upd = true; CartItem { item: i.item.clone(), qty: i.qty + qty } } else { i.clone() } }).collect::<Vec<_>>(); if !upd { new_items.push(CartItem { item, qty }); } Some(Self::NonEmpty { id: id.clone(), items: new_items }) } Self::Nothing | Self::PromotingSales { .. } => None, } } } pub fn begin_promotion(&self) -> Option<Self> { match self { Self::NonEmpty { id, items } => { Some(Self::PromotingSales { id: id.clone(), items: items.clone(), promotions: vec![] }) } _ => None } } pub fn add_promotion(&self, promotion: SalesPromotion) -> Option<Self> { match self { Self::PromotingSales { id, items, promotions } if promotion.discount() > 0 => { let promotions = [promotions.clone(), vec![promotion]].concat(); if Self::amount_items(items) >= Self::amount_promotions(&promotions) { Some(Self::PromotingSales { id: id.clone(), items: items.clone(), promotions }) } else { None } } _ => None } } pub fn end_promotion(&self) -> Option<Self> { match self { Self::PromotingSales { id, items, promotions } => { Some(Self::CheckOutReady { id: id.clone(), items: items.clone(), promotions: promotions.clone(), subtotal: self.subtotal() }) } _ => None } } pub fn cancel_promotion(&self) -> Option<Self> { match self { Self::PromotingSales { id, items, .. } => { Some(Self::NonEmpty { id:id.clone(), items: items.clone() }) } _ => None } } fn subtotal(&self) -> Amount { match self { Self::NonEmpty { items, .. } => { Self::amount_items(items) } Self::PromotingSales { items, promotions, .. } => { cmp::max(0, Self::amount_items(items) - Self::amount_promotions(promotions)) } Self::CheckOutReady { subtotal, .. } => { subtotal.clone() } _ => 0 } } fn amount_items(items: &Vec<CartItem>) -> Amount { items.iter().fold(0, |acc, i| acc + i.amount()) } fn amount_promotions(promotions: &Vec<SalesPromotion>) -> Amount { promotions.iter().fold(0, |acc, p| acc + p.discount()) } } impl CartItem { pub fn amount(&self) -> Amount { self.item.unit_price * self.qty.try_into().unwrap_or(0) } } impl SalesPromotion { pub fn discount(&self) -> Amount { match self { Self::Discount { discount, .. } => discount.clone(), } } } #[cfg(test)] mod tests { use super::*; #[test] fn create() { let state = Cart::Nothing; if let Some(c) = state.create("cart-1".to_string()) { if let Cart::Empty { id } = c { assert_eq!(id, "cart-1"); } else { assert!(false); } } else { assert!(false); } } #[test] fn add_item_to_empty() { let state = Cart::Empty { id: "cart-1".to_string() }; let item = Product { catalog_id: "item-1".to_string(), unit_price: 1000 }; if let Some(c) = state.add_item(item, 2) { if let Cart::NonEmpty { id, items } = c { assert_eq!(id, "cart-1"); assert_eq!(items.len(), 1); let it = items.last().unwrap(); assert_eq!(it.item.catalog_id, "item-1"); assert_eq!(it.item.unit_price, 1000); assert_eq!(it.qty, 2); } else { assert!(false); } } else { assert!(false); } } #[test] fn add_other_item() { let item = Product { catalog_id: "item-1".to_string(), unit_price: 1000 }; let state = Cart::NonEmpty { id: "cart-1".to_string(), items: vec![CartItem { item, qty: 2 }] }; let item2 = Product { catalog_id: "item-2".to_string(), unit_price: 2000 }; if let Some(c) = state.add_item(item2, 1) { if let Cart::NonEmpty { id: _, items } = c { assert_eq!(items.len(), 2); let it = items.last().unwrap(); assert_eq!(it.item.catalog_id, "item-2"); assert_eq!(it.item.unit_price, 2000); assert_eq!(it.qty, 1); } else { assert!(false); } } else { assert!(false); } } #[test] fn add_same_item() { let item = Product { catalog_id: "item-1".to_string(), unit_price: 1000 }; let state = Cart::NonEmpty { id: "cart-1".to_string(), items: vec![CartItem { item: item.clone(), qty: 2 }] }; if let Some(c) = state.add_item(item, 1) { if let Cart::NonEmpty { id: _, items } = c { assert_eq!(items.len(), 1); let it = items.last().unwrap(); assert_eq!(it.item.catalog_id, "item-1"); assert_eq!(it.qty, 3); } else { assert!(false); } } else { assert!(false); } } #[test] fn add_promotion() { let item = Product { catalog_id: "item-1".to_string(), unit_price: 1000 }; let state = Cart::PromotingSales { id: "cart-1".to_string(), items: vec![CartItem { item: item.clone(), qty: 2 }], promotions: vec![] }; let sp = SalesPromotion::Discount { promotion_id: "d1".to_string(), discount: 50 }; if let Some(c) = state.add_promotion(sp) { if let Cart::PromotingSales { promotions, .. } = c { assert_eq!(promotions.len(), 1); } else { assert!(false); } } else { assert!(false); } } #[test] fn add_promotion_over_single_discount() { let item = Product { catalog_id: "item-1".to_string(), unit_price: 1000 }; let state = Cart::PromotingSales { id: "cart-1".to_string(), items: vec![CartItem { item: item.clone(), qty: 2 }], promotions: vec![] }; let sp = SalesPromotion::Discount { promotion_id: "d1".to_string(), discount: 2001 }; assert!(state.add_promotion(sp).is_none()); } #[test] fn add_promotion_second() { let item = Product { catalog_id: "item-1".to_string(), unit_price: 1000 }; let sp = SalesPromotion::Discount { promotion_id: "d1".to_string(), discount: 500 }; let state = Cart::PromotingSales { id: "cart-1".to_string(), items: vec![CartItem { item: item.clone(), qty: 2 }], promotions: vec![sp] }; let sp2 = SalesPromotion::Discount { promotion_id: "d2".to_string(), discount: 300 }; if let Some(c) = state.add_promotion(sp2) { if let Cart::PromotingSales { promotions, .. } = c { assert_eq!(promotions.len(), 2); } else { assert!(false); } } else { assert!(false); } } #[test] fn add_promotion_over_discount() { let item = Product { catalog_id: "item-1".to_string(), unit_price: 1000 }; let sp = SalesPromotion::Discount { promotion_id: "d1".to_string(), discount: 500 }; let state = Cart::PromotingSales { id: "cart-1".to_string(), items: vec![CartItem { item: item.clone(), qty: 2 }], promotions: vec![sp] }; let sp2 = SalesPromotion::Discount { promotion_id: "d1".to_string(), discount: 1501 }; assert!(state.add_promotion(sp2).is_none()); } }
use super::*; // A collection of terms to be added #[derive(Clone)] pub struct TermSum { pub terms: Vec<Term> } impl TermSum { pub fn new(terms: Vec<Term>) -> TermSum { TermSum { terms: terms, } } } impl From<Term> for TermSum { fn from(term: Term) -> TermSum { TermSum::new(vec![term]) } } impl fmt::Display for TermSum { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut result = "".to_string(); for (i, term) in self.terms.iter().enumerate() { if i == 0 { result = format!("{}", term); } else { result = format!("{} + {}", term, result) } } write!(f, "{}", result) } } impl Evaluate for TermSum { fn evaluate_f64(&self, a: &Vec<Assignment>) -> Result<f64,String> { println!("Evaluating {}", self); // Evaluate all Terms and add let mut result = 0f64; for term in self.terms.iter() { let eval = term.evaluate_f64(a); if let Ok(x) = eval { result += x; } else { return eval; } } Ok(result) } }
fn main() { let mut book = Vec::new(); book.push(1); { let r = &mut book; // var book tidak dapat diakses krn masih di pinjam via muttable refernce // `&mut` // println!("{:?}", book.len()); r.push(2); println!("{:?}", r); } book.push(3); println!("{:?}", book); }
use std::env; use std::fs::File; use std::io; use std::io::{BufWriter, Write}; use rand::prelude::*; use delaunay_mesh::geo::{Bbox, Vec2}; use delaunay_mesh::DelaunayMesh; pub fn main() -> io::Result<()> { let npoints = env::args() .skip(1) .next() .and_then(|n| n.parse().ok()) .unwrap_or(50); let mut bbox = Bbox::new(Vec2::zero()); bbox.expand(Vec2::new(f64::from(npoints), f64::from(npoints))); let mut rng = thread_rng(); let mut mesh = DelaunayMesh::new(bbox); for i in 0..npoints { if (i + 1) % (npoints / 100).max(1) == 0 { let perc = i * 100 / npoints; print!("\rprogress: {}%", perc); io::stdout().flush()?; } let x: f64 = rng .gen_range(bbox.min().x as u32, bbox.max().x as u32) .into(); let y: f64 = rng .gen_range(bbox.min().y as u32, bbox.max().y as u32) .into(); assert!(x.is_finite()); assert!(y.is_finite()); mesh.insert(Vec2::new(x, y)); } println!("\rprogress: 100% vertices: {}", mesh.vertices().count()); let mut out = BufWriter::new(File::create("triangulation.svg")?); dump_svg(&mut out, &mesh)?; Ok(()) } pub fn dump_svg(out: &mut impl Write, dmesh: &DelaunayMesh) -> io::Result<()> { let bbox = dmesh.bbox(); let d = bbox.dimensions(); writeln!( out, r#"<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="{x} {y} {w} {h}"> <rect x="{x}" y="{y}" width="{w}" height="{h}" stroke="none" fill="white" /> "#, x = bbox.min().x, y = bbox.min().y, w = d.x, h = d.y, )?; for (tri, _) in dmesh.triangles() { let [a, b, c] = dmesh.triangle_vertices(tri); writeln!( out, r#"<polygon points="{},{} {},{} {},{}" fill="none" stroke="black" />"#, a.x, a.y, b.x, b.y, c.x, c.y )?; } writeln!(out, "</svg>") }
use crate::vector2::Vector2; const PI: f32 = 3.14159265359; #[derive(Debug, Copy, Clone)] pub struct Circle { pub origin: Vector2, pub radius: f32 } impl Circle { #![allow(unused)] pub fn new(x: f32, y: f32, radius: f32) -> Self { Self { origin: Vector2::new(x, y), radius: radius } } pub fn area(&self) -> f32 { 2.0 * self.radius * PI } pub fn diameter(&self) -> f32 { 2.0 * self.radius } pub fn is_point_in_circle(&self, point: &Vector2) -> bool { if point.x.abs() <= self.origin.x + self.radius && point.y.abs() <= self.origin.y + self.radius{ true } else { false } } } // TESTS #[cfg(test)] mod tests { use super::*; #[test] fn new_circle() { let circle = Circle::new(20.0, 20.0, 20.0); assert_eq!(circle.origin.x, 20.0); assert_eq!(circle.origin.y, 20.0); assert_eq!(circle.radius, 20.0); } #[test] fn point_is_in_circle() { let circle = Circle::new(0.0, 0.0, 20.0); let point = Vector2::new(-15.0, 5.0); assert_eq!(circle.is_point_in_circle(&point), true); } #[test] fn point_is_not_in_circle() { let circle = Circle::new(0.0, 0.0, 20.0); let point = Vector2::new(-50.0, 25.0); assert_eq!(circle.is_point_in_circle(&point), false); } #[test] fn area() { let circle = Circle::new(0.0, 0.0, 20.0); assert_eq!(circle.area(), 125.66371); } #[test] fn diameter() { let circle = Circle::new(0.0, 0.0, 20.0); assert_eq!(circle.diameter(), 40.0); } }
//! This is the testsuite for `deploy`. It runs the tests in `test/src/bin/` first directly, and then deployed to a local `fabric`. //! //! At the top of each test is some JSON, denoted with the special comment syntax `//=`. //! `output` is a hashmap of file descriptor to a regex of expected output. As it is a regex ensure that any literal `\.+*?()|[]{}^$#&-~` are escaped. #![feature(allocator_api, try_from)] #![warn( // missing_copy_implementations, missing_debug_implementations, // missing_docs, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results, clippy::pedantic, )] // from https://github.com/rust-unofficial/patterns/blob/master/anti_patterns/deny-warnings.md #![allow( clippy::if_not_else, clippy::type_complexity, clippy::cast_possible_truncation, clippy::derive_hash_xor_eq )] extern crate serde; #[macro_use] extern crate serde_derive; extern crate constellation_internal; // extern crate either; extern crate escargot; extern crate itertools; extern crate multiset; extern crate regex; extern crate serde_json; mod ext; use constellation_internal::ExitStatus; use std::{ collections::HashMap, env, fs, hash, io::{self, BufRead}, iter, os, path::{Path, PathBuf}, process, str, thread, time }; const DEPLOY: &str = "src/bin/deploy.rs"; const FABRIC: &str = "src/bin/constellation/main.rs"; const BRIDGE: &str = "src/bin/bridge.rs"; const TESTS: &str = "tests/"; const SELF: &str = "tests/tester/main.rs"; const FABRIC_ADDR: &str = "127.0.0.1:12360"; const BRIDGE_ADDR: &str = "127.0.0.1:12340"; #[global_allocator] static GLOBAL: std::alloc::System = std::alloc::System; #[derive(PartialEq, Eq, Serialize, Debug)] struct Output { output: HashMap< os::unix::io::RawFd, (ext::serialize_as_regex_string::SerializeAsRegexString, bool), >, #[serde(with = "ext::serde_multiset")] children: multiset::HashMultiSet<Output>, exit: ExitStatus, } impl hash::Hash for Output { fn hash<H>(&self, state: &mut H) where H: hash::Hasher, { let mut output = self.output.iter().collect::<Vec<_>>(); output.sort_by(|&(ref a_fd, _), &(ref b_fd, _)| a_fd.cmp(b_fd)); for output in output { output.hash(state); } // self.children.hash(state); // TODO self.exit.hash(state); } } #[derive(PartialEq, Eq, Serialize, Deserialize, Debug)] struct OutputTest { output: HashMap<os::unix::io::RawFd, (ext::serde_regex::SerdeRegex, bool)>, #[serde(with = "ext::serde_multiset")] children: multiset::HashMultiSet<OutputTest>, exit: ExitStatus, } impl hash::Hash for OutputTest { fn hash<H>(&self, state: &mut H) where H: hash::Hasher, { let mut output = self.output.iter().collect::<Vec<_>>(); output.sort_by(|&(ref a_fd, _), &(ref b_fd, _)| a_fd.cmp(b_fd)); for output in output { output.hash(state); } // self.children.hash(state); // TODO self.exit.hash(state); } } impl OutputTest { fn is_match(&self, output: &Output) -> bool { if self.exit != output.exit || self.output.len() != output.output.len() || self.children.len() != output.children.len() { return false; } for (_, test, output) in ext::hashmap::intersection(&self.output, &output.output) { if test.1 != output.1 || !test.0.is_match(&(output.0).0) { return false; } } let mut check = (0..self.children.len()) .map(|_| (false, false)) .collect::<Vec<_>>(); for (i, test) in self.children.iter().enumerate() { for (j, output) in output.children.iter().enumerate() { if !(check[i].0 && check[j].1) && test.is_match(output) { check[i].0 = true; check[j].1 = true; } } } if !check.into_iter().all(|(a, b)| a && b) { return false; } true } } fn parse_output(output: &process::Output) -> Result<Output, Option<serde_json::Error>> { if !output.stderr.is_empty() { return Err(None); // println!("{}", std::str::from_utf8(&output.stderr).unwrap()); // Useful if FORWARD_STDERR is disabled } let mut log = HashMap::new(); let mut top = None; for message in serde_json::Deserializer::from_slice(&output.stdout) .into_iter::<constellation_internal::DeployOutputEvent>() { match message? { constellation_internal::DeployOutputEvent::Output(a, b, c) => { if top.is_none() { top = Some(a); let _ = log.insert(a, (HashMap::new(), Vec::new(), None)); } let output = log .get_mut(&a) .unwrap() .0 .entry(b) .or_insert((Vec::new(), false)); assert!(!output.1); if !c.is_empty() { output.0.extend(c); } else { output.1 = true; } } constellation_internal::DeployOutputEvent::Spawn(a, b) => { if top.is_none() { top = Some(a); let _ = log.insert(a, (HashMap::new(), Vec::new(), None)); } log.get_mut(&a).unwrap().1.push(b); let x = log.insert(b, (HashMap::new(), Vec::new(), None)); assert!(x.is_none()); } constellation_internal::DeployOutputEvent::Exit(a, b) => { if top.is_none() { top = Some(a); let _ = log.insert(a, (HashMap::new(), Vec::new(), None)); } log.get_mut(&a).unwrap().2 = Some(b); } } } let top = top.unwrap(); Ok(treeize(log.remove(&top).unwrap(), &mut log)) } fn treeize( output: ( HashMap<os::unix::io::RawFd, (Vec<u8>, bool)>, Vec<constellation_internal::Pid>, Option<ExitStatus>, ), nodes: &mut HashMap< constellation_internal::Pid, ( HashMap<os::unix::io::RawFd, (Vec<u8>, bool)>, Vec<constellation_internal::Pid>, Option<ExitStatus>, ), >, ) -> Output { Output { output: output .0 .into_iter() // .chain(iter::once((2,(vec![],true)))) // Useful if FORWARD_STDERR is disabled .map(|(k, (v, v1))| { ( k, ( ext::serialize_as_regex_string::SerializeAsRegexString(v), v1, ), ) }) .collect(), children: output .1 .into_iter() .map(|pid| treeize(nodes.remove(&pid).unwrap(), nodes)) .collect(), exit: output.2.unwrap(), } } fn main() { let start = time::Instant::now(); let _ = thread::Builder::new() .spawn(move || loop { thread::sleep(time::Duration::new(10, 0)); println!("{:?}", start.elapsed()); }) .unwrap(); let current_dir = env::current_dir().unwrap(); let mut products = HashMap::new(); let mut args = env::args().skip(1); let iterations = args .next() .and_then(|arg| arg.parse::<usize>().ok()) .unwrap_or(10); let args = iter::once(String::from("build")) .chain(iter::once(String::from("--tests"))) .chain(iter::once(String::from("--message-format=json"))) .chain(iter::once(format!("--target={}", escargot::CURRENT_TARGET))) .chain(args) .collect::<Vec<_>>(); let output = process::Command::new("cargo") .args(&args) .stderr(process::Stdio::inherit()) .output() .expect("Failed to invoke cargo"); if !output.status.success() { panic!("cargo build failed"); } for message in serde_json::Deserializer::from_slice(&output.stdout) .into_iter::<constellation_internal::cargo_metadata::Message>() { if let constellation_internal::cargo_metadata::Message::CompilerArtifact { artifact } = message.unwrap_or_else(|_| { panic!( "Failed to parse output of cargo {}", itertools::join(args.iter(), " ") ) }) { if let Ok(path) = PathBuf::from(&artifact.target.src_path).strip_prefix(&current_dir) { if (artifact.target.kind == vec![String::from("bin")] && !artifact.profile.test) || artifact.target.kind == vec![String::from("test")] { // println!("{:#?}", artifact); // assert_eq!(artifact.filenames.len(), 1, "{:?}", artifact); let x = products.insert( path.to_owned(), artifact.filenames.into_iter().nth(0).unwrap(), ); assert!(x.is_none()); } } } } let (deploy, fabric, bridge) = ( &products[Path::new(DEPLOY)], &products[Path::new(FABRIC)], &products[Path::new(BRIDGE)], ); if std::net::TcpStream::connect(FABRIC_ADDR).is_ok() { panic!("Service already running on FABRIC_ADDR {}", FABRIC_ADDR); } if std::net::TcpStream::connect(BRIDGE_ADDR).is_ok() { panic!("Service already running on BRIDGE_ADDR {}", BRIDGE_ADDR); } let mut fabric = process::Command::new(fabric) .args(&[ "master", FABRIC_ADDR, "4GiB", "4", bridge.to_str().unwrap(), BRIDGE_ADDR, ]) .stdin(process::Stdio::null()) .stdout(process::Stdio::null()) .stderr(process::Stdio::null()) .spawn() .unwrap(); let start_ = time::Instant::now(); while std::net::TcpStream::connect(FABRIC_ADDR).is_err() { // TODO: parse output rather than this loop and timeout if start_.elapsed() > time::Duration::new(2, 0) { panic!("Fabric not up within 2s"); } thread::sleep(std::time::Duration::new(0, 1_000_000)); } let start_ = time::Instant::now(); while std::net::TcpStream::connect(BRIDGE_ADDR).is_err() { // TODO: parse output rather than this loop and timeout if start_.elapsed() > time::Duration::new(10, 0) { panic!("Bridge not up within 10s"); } thread::sleep(std::time::Duration::new(0, 1_000_000)); } let mut products = products .iter() .filter(|&(src, _bin)| src.starts_with(Path::new(TESTS)) && src != Path::new(SELF)) .collect::<Vec<_>>(); products.sort_by(|&(ref a_src, _), &(ref b_src, _)| a_src.cmp(b_src)); let (mut succeeded, mut failed) = (0, 0); for (src, bin) in products { println!("{}", src.display()); let file: Result<OutputTest, _> = serde_json::from_str( &io::BufReader::new(fs::File::open(src).unwrap()) .lines() .map(|x| x.unwrap()) .take_while(|x| x.get(0..3) == Some("//=")) .flat_map(|x| ext::string::Chars::new(x).skip(3)) .collect::<String>(), ); let mut x = |command: &mut process::Command| { let result = command.output().unwrap(); let output = parse_output(&result); if output.is_err() || file.is_err() || !file.as_ref().unwrap().is_match(output.as_ref().unwrap()) { println!("Error in {:?}", src); match file { Ok(ref file) => println!( "Documented:\n{}", serde_json::to_string_pretty(file).unwrap() ), Err(ref e) => println!("Documented:\nInvalid result JSON: {:?}\n", e), } match output { Ok(ref output) => { println!("Actual:\n{}", serde_json::to_string_pretty(output).unwrap()) } Err(ref e) => println!("Actual:\nFailed to parse: {:?}\n{:?}", result, e), } failed += 1; } else { succeeded += 1; } }; println!(" native"); for i in 0..iterations { println!(" {}", i); x(process::Command::new(bin) .env_remove("CONSTELLATION_VERSION") .env("CONSTELLATION_FORMAT", "json")); } println!(" deployed"); for i in 0..iterations { println!(" {}", i); x(process::Command::new(deploy) .env_remove("CONSTELLATION_VERSION") .env_remove("CONSTELLATION_FORMAT") .args(&["--format=json", BRIDGE_ADDR, bin.to_str().unwrap()])); } } fabric.kill().unwrap(); println!( "{}/{} succeeded in {:?}", succeeded, succeeded + failed, start.elapsed() ); if failed > 0 { process::exit(1); } }
#[macro_use] extern crate clap; extern crate sisterm; use sisterm::flag; use sisterm::setting; use std::env; use clap::{App, AppSettings, Arg, SubCommand}; use serialport::available_ports; #[tokio::main] async fn main() { let matches = build_app().get_matches(); #[cfg(windows)] enable_ansi_support(); // SSH if let Some(matches) = matches.subcommand_matches("ssh") { use sisterm::ssh; // Hostname let host = matches.values_of("host[:port]").unwrap().collect::<Vec<_>>().join(":"); // Parse arguments let (flags, params) = parse_arguments(matches); // Login user let login_user = matches.value_of("login_user"); ssh::run(&host, flags, params, login_user).await; println!("\n\x1b[0mDisconnected."); // Telnet } else if let Some(matches) = matches.subcommand_matches("telnet") { use sisterm::telnet; // Hostname let host = matches.values_of("host[:port]").unwrap().collect::<Vec<_>>().join(":"); // Parse arguments let (flags, params) = parse_arguments(matches); // Login user let login_user = matches.value_of("login_user"); telnet::run(&host, flags, params, login_user).await; println!("\n\x1b[0mDisconnected."); // TCP connection witout telnet } else if let Some(matches) = matches.subcommand_matches("tcp") { use sisterm::tcp; // Hostname let host = matches.values_of("host:port").unwrap().collect::<Vec<_>>().join(":"); // Parse arguments let (flags, params) = parse_arguments(matches); tcp::run(&host, flags, params).await; println!("\n\x1b[0mDisconnected."); } else { // Parse arguments let (flags, params) = parse_arguments(&matches); // If "read file (-r)" is specified // Output text from the file if let Some(path) = matches.value_of("read file") { use sisterm::file_read; file_read::run(path, flags, params); // Serialport } else { use sisterm::serial; let (port_name, baud_rate) = if let Some(params) = &params { // If "port (-l)" is specified let port_name = if let Some(port) = matches.value_of("port") { port.to_string() } else if let Some(port) = &params.port { port.to_string() } else { match available_ports() { Ok(port) if !port.is_empty() => port[0].port_name.to_string(), _ => panic!("No serial port"), } }; // If "baudrate (-s)" is specified let baud_rate = if let Some(baud) = &params.speed { baud } else if let Some(baud) = matches.value_of("baud") { baud } else { panic!("No baud rate"); }.to_string(); (port_name, baud_rate) } else { // If "port (-l)" is specified let port_name = if let Some(port) = matches.value_of("port") { port.to_string() } else { match available_ports() { Ok(port) if !port.is_empty() => port[0].port_name.to_string(), _ => panic!("No serial port"), } }; // If "baudrate (-s)" is specified let baud_rate = matches.value_of("baud").expect("No baud rate"); (port_name, baud_rate.to_string()) }; let baud_rate = match baud_rate.parse::<u32>() { Ok(br) => br, Err(_) => { eprintln!("Error: Invalid baud rate '{}' specified", baud_rate); std::process::exit(1); } }; serial::run(port_name, baud_rate, flags, params).await; println!("\n\x1b[0mDisconnected."); } } } fn parse_arguments(matches: &clap::ArgMatches) -> (flag::Flags, Option<setting::Params>) { use chrono::Local; // If "config file (-c)" is specified let config_file = if let Some(file) = matches.value_of("config file") { file.to_string() } else { get_config_file_path() }; // Parse configuration file let params = setting::Params::new(&config_file); // Color display flag let nocolor = matches.is_present("nocolor"); // Timestamp flag let timestamp = matches.is_present("timestamp"); let timestamp = if let Some(ref params) = params { if timestamp { true } else { params.timestamp } } else { timestamp }; // Append flag let append = matches.is_present("append"); // CRLF flag let crlf = matches.is_present("crlf"); let crlf = if let Some(ref params) = params { if crlf { true } else { params.crlf } } else { crlf }; // Hexdumo flag let hexdump = matches.is_present("hexdump"); // Debug mode flag let debug = if let Some(ref params) = params { params.debug } else { false }; // If "write file (-w)" is specified let write_file = matches.value_of("write file"); let write_file = if let Some(write_file) = write_file { Some(write_file.to_string()) } else if let Some(ref params) = params { if params.auto_save_log { #[cfg(windows)] let fmt = format!("{}\\{}", params.log_destination.trim_end_matches('\\'), params.log_format); #[cfg(not(windows))] let fmt = format!("{}/{}", params.log_destination.trim_end_matches('/'), params.log_format); Some(Local::now().format(&fmt).to_string()) } else { None } } else { None }; // Setting flags let flags = flag::Flags::new(nocolor, timestamp, append, crlf, hexdump, debug, write_file); (flags, params) } fn build_app() -> App<'static, 'static> { App::new("sisterm") .version(crate_version!()) .about(crate_description!()) .setting(AppSettings::DeriveDisplayOrder) .arg(Arg::with_name("port") .help("The device path to a serial port (auto detection)") .short("l") .long("line") .value_name("PORT") .takes_value(true) ) .arg(Arg::with_name("baud") .help("The baud rate to connect at") .short("s") .long("speed") .value_name("BAUD") .takes_value(true) .default_value("9600") ) .arg(Arg::with_name("read file") .help("Output text from file") .short("r") .long("read") .value_name("FILE") .takes_value(true) .conflicts_with_all(&[ "port", "baud", "write file", "timestamp", "append", "crlf" ]) ) .arg(Arg::with_name("write file") .help("Saved log") .short("w") .long("write") .value_name("FILE") .takes_value(true) .global(true) ) .arg(Arg::with_name("config file") .help(config_file_help_message()) .short("c") .long("config") .value_name("FILE") .takes_value(true) .global(true) ) .arg(Arg::with_name("nocolor") .help("Without color") .short("n") .long("no-color") .global(true) ) .arg(Arg::with_name("timestamp") .help("Add timestamp to log") .short("t") .long("time-stamp") .global(true) ) .arg(Arg::with_name("append") .help("Append to log (default overwrite)") .short("a") .long("append") .global(true) ) .arg(Arg::with_name("crlf") .help("Send '\\r\\n' instead of '\\r'") .short("i") .long("instead-crlf") .global(true) ) .arg(Arg::with_name("hexdump") .help("Prints in hex") .short("x") .long("hexdump") .global(true) ) .subcommands(vec![SubCommand::with_name("ssh") .about("Login to remote system host with ssh") .usage("sist ssh [FLAGS] [OPTIONS] <HOST[:PORT]>") .setting(AppSettings::DeriveDisplayOrder) .arg(Arg::with_name("host[:port]") .help("Port number can be omitted. Then 22") .value_name("HOST[:PORT]") .takes_value(true) .required(true) .min_values(1) .max_values(2) //.hidden(true) ) .arg(Arg::with_name("login_user") .help("Specify login user") .short("l") .long("login-user") .value_name("USERNAME") .takes_value(true) ), SubCommand::with_name("telnet") .about("Login to remote system host with telnet") .usage("sist telnet [FLAGS] [OPTIONS] <HOST[:PORT]>") .setting(AppSettings::DeriveDisplayOrder) .arg(Arg::with_name("host[:port]") .help("Port number can be omitted. Then 23") .value_name("HOST[:PORT]") .takes_value(true) .required(true) .min_values(1) .max_values(2) //.hidden(true) ) .arg(Arg::with_name("login_user") .help("Specify login user") .short("l") .long("login-user") .value_name("USERNAME") .takes_value(true) ), SubCommand::with_name("tcp") .about("TCP connection without telnet") .setting(AppSettings::DeriveDisplayOrder) .arg(Arg::with_name("host:port") .help("Host and port number") .takes_value(true) .required(true) .min_values(1) ), ]) } fn get_config_file_path() -> String { #[cfg(windows)] return format!("{}/sisterm/config.toml", if let Ok(ref user) = env::var("LOCALAPPDATA") { user } else { "%LOCALAPPDATA%" } ); #[cfg(not(windows))] return format!("{}/.config/sisterm/config.toml", if let Ok(ref home) = env::var("HOME") { home } else { "$HOME" } ); } fn config_file_help_message() -> &'static str { #[cfg(windows)] return "Specify configuration file\n[default %LOCALAPPDATA%/sisterm/config.toml]"; #[cfg(not(windows))] return "Specify configuration file\n[default $HOME/.config/sisterm/config.toml]"; } #[cfg(windows)] #[allow(clippy::collapsible_if)] fn enable_ansi_support() { use winapi::um::consoleapi::{GetConsoleMode, SetConsoleMode}; use winapi::um::handleapi::INVALID_HANDLE_VALUE; use winapi::um::processenv::GetStdHandle; use winapi::um::winbase::STD_INPUT_HANDLE; use winapi::um::wincon::ENABLE_VIRTUAL_TERMINAL_PROCESSING; unsafe { let input_handle = GetStdHandle(STD_INPUT_HANDLE); let mut console_mode: u32 = 0; if input_handle == INVALID_HANDLE_VALUE { return; } if GetConsoleMode(input_handle, &mut console_mode) != 0 { if console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING == 0 { SetConsoleMode(input_handle, console_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING); } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_get_config_file_path() { assert_ne!(get_config_file_path(), "%LOCALAPPDATA%/sisterm/config.toml"); assert_ne!(get_config_file_path(), "$HOME/sisterm/config.toml"); } #[test] fn test_config_file_help_message() { #[cfg(windows)] assert_eq!( config_file_help_message(), "Specify configuration file\n[default %LOCALAPPDATA%/sisterm/config.toml]" ); #[cfg(not(windows))] assert_eq!( config_file_help_message(), "Specify configuration file\n[default $HOME/.config/sisterm/config.toml]" ); } }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // For use of const fn: `Option::<T>::unwrap` at compile time. #![feature(const_option)] #![feature(box_into_inner)] #![allow(clippy::uninlined_format_args)] //! Provides conversion from and to protobuf defined meta data, which is used for transport. //! //! Thus protobuf messages has the maximized compatibility. //! I.e., a protobuf message is able to contain several different versions of metadata in one format. //! This mod will convert protobuf message to the current version of meta data used in databend-query. //! //! # Versioning and compatibility //! //! Alice and Bob can talk with each other if they are compatible. //! Alice and Bob both have two versioning related field: //! - `ver`: the version of the subject, //! - and the minimal version of the target it can talk to. //! //! And out algorithm defines that Alice and Bob are compatible iff: //! - `Alice.min_bob_ver <= Bob.ver` //! - `Bob.min_alice_ver <= Alice.ver` //! //! E.g.: //! - `A: (ver=3, min_b_ver=1)` is compatible with `B: (ver=3, min_a_ver=2)`. //! - `A: (ver=4, min_b_ver=4)` is **NOT** compatible with `B: (ver=3, min_a_ver=2)`. //! Because although `A.ver(4) >= B.min_a_ver(3)` holds, //! but `B.ver(3) >= A.min_b_ver(4)` does not hold. //! //! ```text //! B.ver: 1 3 4 //! B --------+-------------+------+------------> //! ^ .------' ^ //! | | | //! '-------------. | //! | | | //! v | | //! A ---------------+------+------+------------> //! A.ver: 2 3 4 //! ``` //! //! # Versioning implementation //! //! Since a client writes and reads data to meta-service, it is Alice and Bob at the same time(data producer and consumer). //! Thus it has three version attributes(not 4, because Alice.ver==Bob.ver): //! - `reader.VER` and `message.VER` are the version of the reader and the writer. //! - `reader.MIN_MSG_VER` is the minimal message version this program can read. //! - `message.MIN_READER_VER` is the minimal reader(program) version that can read this message. mod config_from_to_protobuf_impl; mod database_from_to_protobuf_impl; mod datetime_from_to_protobuf_impl; mod from_to_protobuf; mod schema_from_to_protobuf_impl; mod share_from_to_protobuf_impl; mod table_from_to_protobuf_impl; mod user_from_to_protobuf_impl; mod util; pub use from_to_protobuf::FromToProto; pub use from_to_protobuf::Incompatible; pub use util::missing; pub use util::reader_check_msg; pub use util::MIN_MSG_VER; pub use util::MIN_READER_VER; pub use util::VER;
use super::*; use crate::{ inline_storage::alignment::{AlignTo1, AlignTo16, AlignTo2, AlignTo4, AlignTo8}, nonexhaustive_enum::{ examples::{ command_a, command_b, command_c, command_h_mismatched_discriminant, command_serde, const_expr_size_align, generic_a, generic_b, many_ranges_a, many_ranges_b, }, GetEnumInfo, }, test_utils::{check_formatting_equivalence, must_panic}, }; use core_extensions::SelfOps; use std::{ cmp::{Ord, Ordering, PartialEq, PartialOrd}, collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, sync::Arc, }; #[test] fn construct_deconstruct() { macro_rules! construct_deconstruct_cases { ($NE:ident :: $ctor:ident($($extra_args:tt)*)) => { { use self::command_a::Foo as FooA; let mut variant_a = $NE::$ctor(FooA::A, $($extra_args)*); let mut variant_b = $NE::$ctor(FooA::B(11), $($extra_args)*); assert_eq!(variant_a.as_enum(), Ok(&FooA::A)); assert_eq!(variant_b.as_enum(), Ok(&FooA::B(11))); assert_eq!(variant_a.as_enum_mut(), Ok(&mut FooA::A)); assert_eq!(variant_b.as_enum_mut(), Ok(&mut FooA::B(11))); assert_eq!(variant_a.into_enum(), Ok(FooA::A)); assert_eq!(variant_b.into_enum(), Ok(FooA::B(11))); } { use self::command_b::Foo as FooB; let mut variant_a = $NE::$ctor(FooB::A, $($extra_args)*); let mut variant_b = $NE::$ctor(FooB::B(11), $($extra_args)*); let mut variant_c = $NE::$ctor(FooB::C, $($extra_args)*); assert_eq!(variant_a.as_enum(), Ok(&FooB::A)); assert_eq!(variant_b.as_enum(), Ok(&FooB::B(11))); assert_eq!(variant_c.as_enum(), Ok(&FooB::C)); assert_eq!(variant_a.as_enum_mut(), Ok(&mut FooB::A)); assert_eq!(variant_b.as_enum_mut(), Ok(&mut FooB::B(11))); assert_eq!(variant_c.as_enum_mut(), Ok(&mut FooB::C)); assert_eq!(variant_a.into_enum(), Ok(FooB::A)); assert_eq!(variant_b.into_enum(), Ok(FooB::B(11))); assert_eq!(variant_c.into_enum(), Ok(FooB::C)); } }; } construct_deconstruct_cases! {NonExhaustive::new()} construct_deconstruct_cases! {NonExhaustiveFor::new()} } #[test] fn construct_panic() { use self::generic_b::{Foo, Foo_Interface, Foo_Storage}; type NE<E> = NonExhaustive<E, Foo_Storage, Foo_Interface>; macro_rules! passing_ctor { ($enum_ty:ty) => {{ type ET = $enum_ty; let runtime = <NE<ET>>::with_storage_and_interface(ET::A); let const_ = <NE<ET>>::new(ET::B); assert_eq!(runtime, ET::A); assert_eq!(const_, ET::B); }}; } macro_rules! failing_ctor { ($enum_ty:ty) => {{ type ET = $enum_ty; must_panic(|| <NE<ET>>::with_storage_and_interface(ET::B)).unwrap(); must_panic(|| <NE<ET>>::new(ET::A)).unwrap(); }}; } passing_ctor! {Foo<AlignTo8<[u8; 0]>>} passing_ctor! {Foo<AlignTo8<[u8; 56]>>} // too large failing_ctor! {Foo<AlignTo8<[u8; 64]>>} // too aligned failing_ctor! {Foo<AlignTo16<[u8; 0]>>} // too large, too aligned failing_ctor! {Foo<AlignTo16<[u8; 64]>>} } #[test] fn const_expr_size_align_test() { use self::const_expr_size_align::{Foo, Foo_Interface, Foo_Storage}; type NE<E> = NonExhaustive<E, Foo_Storage, Foo_Interface>; macro_rules! passing_ctor { ($enum_ty:ty) => {{ type ET = $enum_ty; let const_ = <NE<ET>>::new(ET::B); assert_eq!(const_, ET::B); }}; } macro_rules! failing_ctor { ($enum_ty:ty) => {{ type ET = $enum_ty; must_panic(|| <NE<ET>>::new(ET::A)).unwrap(); }}; } passing_ctor! {Foo<AlignTo2<[u8; 0]>>} passing_ctor! {Foo<AlignTo1<[u8; 9]>>} passing_ctor! {Foo<AlignTo2<[u8; 8]>>} // too large failing_ctor! {Foo<AlignTo2<[u8; 9]>>} // too aligned failing_ctor! {Foo<AlignTo4<[u8; 0]>>} // too large, too aligned failing_ctor! {Foo<AlignTo4<[u8; 64]>>} } #[test] fn get_discriminant() { { use self::command_c::Foo as FooC; let wrapped_a = NonExhaustive::new(FooC::A); let wrapped_b = NonExhaustive::new(FooC::B(11)); let wrapped_c = NonExhaustive::new(FooC::C); let wrapped_d = NonExhaustive::new(FooC::D { name: "what".into(), }); assert_eq!(wrapped_a.get_discriminant(), 0); assert_eq!(wrapped_b.get_discriminant(), 1); assert_eq!(wrapped_c.get_discriminant(), 2); assert_eq!(wrapped_d.get_discriminant(), 3); } { use self::command_h_mismatched_discriminant::Foo; let wrapped_a = NonExhaustive::new(Foo::A); let wrapped_b = NonExhaustive::new(Foo::B); let wrapped_c = NonExhaustive::new(Foo::C); assert_eq!(wrapped_a.get_discriminant(), 40); assert_eq!(wrapped_b.get_discriminant(), 41); assert_eq!(wrapped_c.get_discriminant(), 42); } } #[test] fn is_valid_discriminant() { { use self::command_c::Foo as FooC; assert_eq!(FooC::is_valid_discriminant(0), true); assert_eq!(FooC::is_valid_discriminant(1), true); assert_eq!(FooC::is_valid_discriminant(2), true); assert_eq!(FooC::is_valid_discriminant(3), true); assert_eq!(FooC::is_valid_discriminant(4), false); assert_eq!(FooC::is_valid_discriminant(5), false); } { use self::command_h_mismatched_discriminant::Foo; assert_eq!(Foo::is_valid_discriminant(0), false); assert_eq!(Foo::is_valid_discriminant(39), false); assert_eq!(Foo::is_valid_discriminant(40), true); assert_eq!(Foo::is_valid_discriminant(41), true); assert_eq!(Foo::is_valid_discriminant(42), true); assert_eq!(Foo::is_valid_discriminant(43), false); assert_eq!(Foo::is_valid_discriminant(44), false); } { use self::many_ranges_a::Foo; assert_eq!(Foo::is_valid_discriminant(0), true); assert_eq!(Foo::is_valid_discriminant(1), false); assert_eq!(Foo::is_valid_discriminant(2), false); assert_eq!(Foo::is_valid_discriminant(39), false); assert_eq!(Foo::is_valid_discriminant(40), true); assert_eq!(Foo::is_valid_discriminant(41), true); assert_eq!(Foo::is_valid_discriminant(42), true); assert_eq!(Foo::is_valid_discriminant(43), false); assert_eq!(Foo::is_valid_discriminant(44), false); assert_eq!(Foo::is_valid_discriminant(58), false); assert_eq!(Foo::is_valid_discriminant(59), false); assert_eq!(Foo::is_valid_discriminant(60), true); assert_eq!(Foo::is_valid_discriminant(61), true); assert_eq!(Foo::is_valid_discriminant(62), false); assert_eq!(Foo::is_valid_discriminant(63), false); } { use self::many_ranges_b::Foo; assert_eq!(Foo::is_valid_discriminant(0), true); assert_eq!(Foo::is_valid_discriminant(1), false); assert_eq!(Foo::is_valid_discriminant(2), false); assert_eq!(Foo::is_valid_discriminant(39), false); assert_eq!(Foo::is_valid_discriminant(40), true); assert_eq!(Foo::is_valid_discriminant(41), true); assert_eq!(Foo::is_valid_discriminant(42), false); assert_eq!(Foo::is_valid_discriminant(43), false); assert_eq!(Foo::is_valid_discriminant(58), false); assert_eq!(Foo::is_valid_discriminant(59), false); assert_eq!(Foo::is_valid_discriminant(60), true); assert_eq!(Foo::is_valid_discriminant(62), false); assert_eq!(Foo::is_valid_discriminant(63), false); } } // This also tests what happens between dynamic libraries. #[test] fn transmuting_enums() { unsafe { use self::{command_a::Foo as FooA, command_c::Foo as FooC}; let mut variant_a = NonExhaustive::new(FooC::A).transmute_enum::<FooA>(); let mut variant_b = NonExhaustive::new(FooC::B(11)).transmute_enum::<FooA>(); let mut variant_c = NonExhaustive::new(FooC::C).transmute_enum::<FooA>(); let mut variant_d = FooC::D { name: "what".into(), } .piped(NonExhaustive::new) .transmute_enum::<FooA>(); assert_eq!(variant_c.is_valid_discriminant(), false); assert_eq!(variant_d.is_valid_discriminant(), false); assert_eq!(variant_a.as_enum(), Ok(&FooA::A)); assert_eq!(variant_b.as_enum(), Ok(&FooA::B(11))); assert_eq!(variant_c.as_enum().ok(), None); assert_eq!(variant_d.as_enum().ok(), None); assert_eq!(variant_a.as_enum_mut(), Ok(&mut FooA::A)); assert_eq!(variant_b.as_enum_mut(), Ok(&mut FooA::B(11))); assert_eq!(variant_c.as_enum_mut().ok(), None); assert_eq!(variant_d.as_enum_mut().ok(), None); assert_eq!(variant_a.into_enum(), Ok(FooA::A)); assert_eq!(variant_b.into_enum(), Ok(FooA::B(11))); assert_eq!(variant_c.into_enum().ok(), None); assert_eq!(variant_d.into_enum().ok(), None); } } #[test] fn clone_test() { use self::generic_a::Foo; let arc = Arc::new(100); assert_eq!(Arc::strong_count(&arc), 1); let variant_a = NonExhaustive::new(Foo::<Arc<i32>>::A); let variant_b = NonExhaustive::new(Foo::<Arc<i32>>::B); let variant_c = NonExhaustive::new(Foo::<Arc<i32>>::C(arc.clone())); assert_eq!(Arc::strong_count(&arc), 2); assert_eq!(variant_a.clone(), variant_a); assert_eq!(variant_b.clone(), variant_b); { let clone_c = variant_c.clone(); assert_eq!(Arc::strong_count(&arc), 3); assert_eq!(clone_c, variant_c); } assert_eq!(Arc::strong_count(&arc), 2); assert_eq!(variant_a, Foo::A); assert_eq!(variant_b, Foo::B); { let clone_c = variant_c.clone(); assert_eq!(Arc::strong_count(&arc), 3); assert_eq!(clone_c, Foo::C(arc.clone())); } assert_eq!(Arc::strong_count(&arc), 2); drop(variant_c); assert_eq!(Arc::strong_count(&arc), 1); } #[test] fn fmt_test() { use self::command_serde::Foo as FooC; let variant_a = FooC::A; let wrapped_a = NonExhaustive::new(variant_a.clone()); let variant_b = FooC::B(11); let wrapped_b = NonExhaustive::new(variant_b.clone()); let variant_c = FooC::C; let wrapped_c = NonExhaustive::new(variant_c.clone()); let variant_d = FooC::D { name: "what".into(), }; let wrapped_d = NonExhaustive::new(variant_d.clone()); check_formatting_equivalence(&variant_a, &wrapped_a); check_formatting_equivalence(&variant_b, &wrapped_b); check_formatting_equivalence(&variant_c, &wrapped_c); check_formatting_equivalence(&variant_d, &wrapped_d); } #[test] fn cmp_test() { use self::generic_a::Foo; let variant_a = Foo::<String>::A; let wrapped_a = NonExhaustive::new(variant_a.clone()); let variant_b = Foo::<String>::B; let wrapped_b = NonExhaustive::new(variant_b.clone()); let variant_c = Foo::<String>::C("what".into()); let wrapped_c = NonExhaustive::new(variant_c.clone()); for wrapped in [&wrapped_a, &wrapped_b, &wrapped_c] { assert_eq!(wrapped.cmp(wrapped), Ordering::Equal); } assert_eq!(wrapped_a.cmp(&wrapped_b), Ordering::Less); assert_eq!(wrapped_b.cmp(&wrapped_c), Ordering::Less); macro_rules! cmp_tests { ( loop_variables=$variant:ident,$wrapped:ident,$which_one:ident; var_b=$var_b:ident; var_c=$var_c:ident; ) => { #[allow(unused_variables)] for ($variant, $wrapped) in [ (&variant_a, &wrapped_a), (&variant_b, &wrapped_b), (&variant_c, &wrapped_c), ] { assert_eq!($wrapped == $which_one, true); assert_eq!($wrapped <= $which_one, true); assert_eq!($wrapped >= $which_one, true); assert_eq!($wrapped < $which_one, false); assert_eq!($wrapped > $which_one, false); assert_eq!($wrapped != $which_one, false); assert_eq!($wrapped.partial_cmp($which_one), Some(Ordering::Equal)); assert_eq!($wrapped.eq($which_one), true); assert_eq!($wrapped.ne($which_one), false); } assert_eq!(wrapped_a == $var_b, false); assert_eq!(wrapped_a <= $var_b, true); assert_eq!(wrapped_a >= $var_b, false); assert_eq!(wrapped_a < $var_b, true); assert_eq!(wrapped_a > $var_b, false); assert_eq!(wrapped_a != $var_b, true); assert_eq!(wrapped_a.partial_cmp(&$var_b), Some(Ordering::Less)); assert_eq!(wrapped_a.eq(&$var_b), false); assert_eq!(wrapped_a.ne(&$var_b), true); assert_eq!(wrapped_b == $var_c, false); assert_eq!(wrapped_b <= $var_c, true); assert_eq!(wrapped_b >= $var_c, false); assert_eq!(wrapped_b < $var_c, true); assert_eq!(wrapped_b > $var_c, false); assert_eq!(wrapped_b != $var_c, true); assert_eq!(wrapped_b.partial_cmp(&$var_c), Some(Ordering::Less)); assert_eq!(wrapped_b.eq(&$var_c), false); assert_eq!(wrapped_b.ne(&$var_c), true); }; } cmp_tests! { loop_variables=variant,wrapped,variant; var_b=variant_b; var_c=variant_c; } cmp_tests! { loop_variables=variant,wrapped,wrapped; var_b=wrapped_b; var_c=wrapped_c; } } #[test] fn hash_test() { use self::generic_a::Foo; fn hash_value<H: Hash>(v: &H) -> u64 { let mut hasher = DefaultHasher::new(); v.hash(&mut hasher); hasher.finish() } let variant_a = Foo::<String>::A; let wrapped_a = NonExhaustive::new(variant_a.clone()); let variant_b = Foo::<String>::B; let wrapped_b = NonExhaustive::new(variant_b.clone()); let variant_c = Foo::<String>::C("what".into()); let wrapped_c = NonExhaustive::new(variant_c.clone()); for (variant, wrapped) in [ (&variant_a, &wrapped_a), (&variant_b, &wrapped_b), (&variant_c, &wrapped_c), ] { assert_eq!(hash_value(variant), hash_value(wrapped)); } } #[test] fn serde_test() { use self::command_serde::Foo as FooC; let variant_a = FooC::A; let variant_b = FooC::B(10); let variant_c = FooC::C; let variant_d = FooC::D { name: "what".into(), }; let expected_a = NonExhaustive::new(variant_a.clone()); let expected_b = NonExhaustive::new(variant_b.clone()); let expected_c = NonExhaustive::new(variant_c.clone()); let expected_d = NonExhaustive::new(variant_d.clone()); let json_a = r#""A""#; let json_dd_a = serde_json::to_string(&json_a).unwrap(); let json_b = r#"{"B":10}"#; let json_dd_b = serde_json::to_string(&json_b).unwrap(); let json_c = r#""C""#; let json_dd_c = serde_json::to_string(&json_c).unwrap(); let json_d = r#"{"D":{"name":"what"}}"#; let json_dd_d = serde_json::to_string(&json_d).unwrap(); assert_eq!( serde_json::from_str::<NonExhaustiveFor<FooC>>(r#" "oinoiasnd" "#).map_err(drop), Err(()), ); assert_eq!( NonExhaustiveFor::<FooC>::deserialize_from_proxy(r#"oinoiasnd"#.into()).map_err(drop), Err(()), ); for (json_dd, json, expected, variant) in [ (&*json_dd_a, json_a, &expected_a, &variant_a), (&*json_dd_b, json_b, &expected_b, &variant_b), (&*json_dd_c, json_c, &expected_c, &variant_c), (&*json_dd_d, json_d, &expected_d, &variant_d), ] { { let deserialized = serde_json::from_str::<NonExhaustiveFor<FooC>>(json_dd).unwrap(); assert_eq!(deserialized, *expected); assert_eq!(deserialized, *variant); } { let deserialized = NonExhaustiveFor::<FooC>::deserialize_from_proxy(json.into()).unwrap(); assert_eq!(deserialized, *expected); assert_eq!(deserialized, *variant); } assert_eq!(&*serde_json::to_string(&expected).unwrap(), json_dd); assert_eq!(&*expected.serialize_into_proxy().unwrap(), json); assert_eq!(&*serde_json::to_string(&variant).unwrap(), json); } }
use crate::{NumBytes, Read, UnsignedInt, Write}; use alloc::string::String; use core::fmt; macro_rules! key_type { ($ident:ident, $bytes:literal) => { /// TODO depreciate, newer signature types cannot be represented as a fixed size structure /// EOSIO Public Key /// <https://github.com/EOSIO/eosio.cdt/blob/4985359a30da1f883418b7133593f835927b8046/libraries/eosiolib/core/eosio/crypto.hpp#L22-L48> #[derive(Read, Write, NumBytes, Clone)] #[eosio(crate_path = "crate::bytes")] pub struct $ident { /// Type of the public key, could be either K1 or R1 pub type_: UnsignedInt, /// Bytes of the public key pub data: [u8; $bytes], } impl $ident { /// TODO docs. #[must_use] pub fn as_bytes(&self) -> &[u8] { &self.data } /// TODO docs. #[must_use] pub const fn to_bytes(&self) -> [u8; $bytes] { self.data } } impl Default for $ident { #[must_use] fn default() -> Self { Self { type_: UnsignedInt::default(), data: [0_u8; $bytes], } } } impl PartialEq for $ident { #[must_use] fn eq(&self, other: &Self) -> bool { self.type_ == other.type_ && self.as_bytes() == other.as_bytes() } } impl fmt::Debug for $ident { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.type_, f)?; fmt::Debug::fmt(self.as_bytes(), f) } } }; } key_type!(PublicKey, 34); key_type!(Signature, 66); /// TODO docs #[derive(Read, Write, NumBytes, Clone)] #[eosio(crate_path = "crate::bytes")] pub struct PrivateKey(String);
use chrono::prelude::*; pub fn construct_calendar_url(query: &str) -> String { if query == "cal" { let google_calendar = "https://calendar.google.com/calendar/u/0/r/"; google_calendar.to_string() } else { construct_calendar_url_date(&query[4..]) } } pub fn construct_calendar_url_date(query: &str) -> String { let mut split_query = query.split_whitespace(); let display = match split_query.next().unwrap() { "d" => "day", "w" => "week", "m" => "month", "y" => "year", _ => "month" }; let current_time = Local::now(); let twitter_search_url = format!("https://calendar.google.com/calendar/u/0/r/{}/{}/{}/{}", display, split_query.next().unwrap_or(&current_time.year().to_string()[..]), split_query.next().unwrap_or(&current_time.month().to_string()[..]), split_query.next().unwrap_or(&current_time.day().to_string()[..])); twitter_search_url } #[cfg(test)] mod tests { use super::*; #[test] fn test_construct_calendar_url_date() { let fake_query = "d 2020 11 3"; let expected_value = "https://calendar.google.com/calendar/u/0/r/day/2020/11/3"; assert_eq!(construct_calendar_url_date(fake_query), expected_value); } #[test] fn test_construct_calendar_url() { let fake_query = "cal d 2020 11 3"; let expected_value = "https://calendar.google.com/calendar/u/0/r/day/2020/11/3"; assert_eq!(construct_calendar_url(fake_query), expected_value); } }
use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::io::Error; use crate::util; const PROP_FILE_NAME: &str = "/slackrypt.properties"; pub fn get_properties() -> Result<HashMap<String, String>, Error> { let mut props = HashMap::new(); let path = util::default_dir() + PROP_FILE_NAME; match File::open(&path) { Ok(file) => { let reader = BufReader::new(file); for l in reader.lines() { let line: String = l.unwrap(); let kv: Vec<&str> = line.splitn(2, '=').collect(); if kv.len() == 2 { props.insert(String::from(kv[0]), String::from(kv[1])); } } } Err(_e) => { log::warn!("slackrypt.properties file does not exist."); } } Ok(props) } pub fn get_property(key: &str, default: &str) -> String { match get_properties() { Ok(props) => { if props.contains_key(key) { props.get(key).unwrap().to_string() } else { String::from(default) } } Err(_) => String::from(default), } } pub fn upsert_property(key: &str, new_value: &str) -> Result<(), Error> { let mut curr_props: HashMap<String, String> = get_properties().unwrap(); if curr_props.contains_key(key) { if let Some(curr_value) = curr_props.get_mut(key) { *curr_value = new_value.to_string(); } } else { curr_props.insert(key.to_string(), new_value.to_string()); } write_properties(curr_props) } fn write_properties(props: HashMap<String, String>) -> Result<(), Error> { let path = util::default_dir() + PROP_FILE_NAME; let mut f = File::create(path)?; let mut s = String::new(); for (k, v) in props { s.push_str(&k); s.push('='); s.push_str(&v); s.push('\n'); } f.write_all(s.as_bytes()) }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct INDClient(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDClient { type Vtable = INDClient_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3bd6781b_61b8_46e2_99a5_8abcb6b9f7d6); } #[repr(C)] #[doc(hidden)] pub struct INDClient_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::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, contenturl: ::windows::core::RawPtr, startasyncoptions: u32, registrationcustomdata: ::windows::core::RawPtr, licensefetchdescriptor: ::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, licensefetchdescriptor: ::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, registrationcustomdata: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct INDClientFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDClientFactory { type Vtable = INDClientFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3e53dd62_fee8_451f_b0d4_f706cca3e037); } #[repr(C)] #[doc(hidden)] pub struct INDClientFactory_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, downloadengine: ::windows::core::RawPtr, streamparser: ::windows::core::RawPtr, pmessenger: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDClosedCaptionDataReceivedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDClosedCaptionDataReceivedEventArgs { type Vtable = INDClosedCaptionDataReceivedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4738d29f_c345_4649_8468_b8c5fc357190); } impl INDClosedCaptionDataReceivedEventArgs { #[cfg(feature = "deprecated")] pub fn ClosedCaptionDataFormat(&self) -> ::windows::core::Result<NDClosedCaptionFormat> { let this = self; unsafe { let mut result__: NDClosedCaptionFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<NDClosedCaptionFormat>(result__) } } #[cfg(feature = "deprecated")] pub fn PresentationTimestamp(&self) -> ::windows::core::Result<i64> { let this = self; unsafe { let mut result__: i64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i64>(result__) } } #[cfg(feature = "deprecated")] pub fn ClosedCaptionData(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } } unsafe impl ::windows::core::RuntimeType for INDClosedCaptionDataReceivedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{4738d29f-c345-4649-8468-b8c5fc357190}"); } impl ::core::convert::From<INDClosedCaptionDataReceivedEventArgs> for ::windows::core::IUnknown { fn from(value: INDClosedCaptionDataReceivedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&INDClosedCaptionDataReceivedEventArgs> for ::windows::core::IUnknown { fn from(value: &INDClosedCaptionDataReceivedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDClosedCaptionDataReceivedEventArgs { 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 INDClosedCaptionDataReceivedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDClosedCaptionDataReceivedEventArgs> for ::windows::core::IInspectable { fn from(value: INDClosedCaptionDataReceivedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&INDClosedCaptionDataReceivedEventArgs> for ::windows::core::IInspectable { fn from(value: &INDClosedCaptionDataReceivedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDClosedCaptionDataReceivedEventArgs { 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 INDClosedCaptionDataReceivedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDClosedCaptionDataReceivedEventArgs_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 NDClosedCaptionFormat) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDCustomData(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDCustomData { type Vtable = INDCustomData_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf5cb0fdc_2d09_4f19_b5e1_76a0b3ee9267); } impl INDCustomData { #[cfg(feature = "deprecated")] pub fn CustomDataTypeID(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } #[cfg(feature = "deprecated")] pub fn CustomData(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } } unsafe impl ::windows::core::RuntimeType for INDCustomData { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{f5cb0fdc-2d09-4f19-b5e1-76a0b3ee9267}"); } impl ::core::convert::From<INDCustomData> for ::windows::core::IUnknown { fn from(value: INDCustomData) -> Self { value.0 .0 } } impl ::core::convert::From<&INDCustomData> for ::windows::core::IUnknown { fn from(value: &INDCustomData) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDCustomData { 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 INDCustomData { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDCustomData> for ::windows::core::IInspectable { fn from(value: INDCustomData) -> Self { value.0 } } impl ::core::convert::From<&INDCustomData> for ::windows::core::IInspectable { fn from(value: &INDCustomData) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDCustomData { 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 INDCustomData { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDCustomData_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_size__: *mut u32, result__: *mut *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct INDCustomDataFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDCustomDataFactory { type Vtable = INDCustomDataFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd65405ab_3424_4833_8c9a_af5fdeb22872); } #[repr(C)] #[doc(hidden)] pub struct INDCustomDataFactory_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, customDataTypeIDBytes_array_size: u32, customdatatypeidbytes: *const u8, customDataBytes_array_size: u32, customdatabytes: *const u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDDownloadEngine(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDDownloadEngine { type Vtable = INDDownloadEngine_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2d223d65_c4b6_4438_8d46_b96e6d0fb21f); } impl INDDownloadEngine { #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn Open<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>>(&self, uri: Param0, sessionidbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), uri.into_param().abi(), sessionidbytes.len() as u32, ::core::mem::transmute(sessionidbytes.as_ptr())).ok() } } #[cfg(feature = "deprecated")] pub fn Pause(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "deprecated")] pub fn Resume(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "deprecated")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn Seek<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TimeSpan>>(&self, startposition: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), startposition.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] pub fn CanSeek(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "deprecated")] pub fn BufferFullMinThresholdInSamples(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } #[cfg(feature = "deprecated")] pub fn BufferFullMaxThresholdInSamples(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } #[cfg(feature = "deprecated")] pub fn Notifier(&self) -> ::windows::core::Result<NDDownloadEngineNotifier> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<NDDownloadEngineNotifier>(result__) } } } unsafe impl ::windows::core::RuntimeType for INDDownloadEngine { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{2d223d65-c4b6-4438-8d46-b96e6d0fb21f}"); } impl ::core::convert::From<INDDownloadEngine> for ::windows::core::IUnknown { fn from(value: INDDownloadEngine) -> Self { value.0 .0 } } impl ::core::convert::From<&INDDownloadEngine> for ::windows::core::IUnknown { fn from(value: &INDDownloadEngine) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDDownloadEngine { 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 INDDownloadEngine { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDDownloadEngine> for ::windows::core::IInspectable { fn from(value: INDDownloadEngine) -> Self { value.0 } } impl ::core::convert::From<&INDDownloadEngine> for ::windows::core::IInspectable { fn from(value: &INDDownloadEngine) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDDownloadEngine { 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 INDDownloadEngine { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDDownloadEngine_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, uri: ::windows::core::RawPtr, sessionIDBytes_array_size: u32, sessionidbytes: *const u8) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, startposition: super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDDownloadEngineNotifier(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDDownloadEngineNotifier { type Vtable = INDDownloadEngineNotifier_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd720b4d4_f4b8_4530_a809_9193a571e7fc); } impl INDDownloadEngineNotifier { #[cfg(feature = "deprecated")] pub fn OnStreamOpened(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "deprecated")] pub fn OnPlayReadyObjectReceived(&self, databytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), databytes.len() as u32, ::core::mem::transmute(databytes.as_ptr())).ok() } } #[cfg(feature = "deprecated")] pub fn OnContentIDReceived<'a, Param0: ::windows::core::IntoParam<'a, INDLicenseFetchDescriptor>>(&self, licensefetchdescriptor: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), licensefetchdescriptor.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] pub fn OnDataReceived(&self, databytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], bytesreceived: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), databytes.len() as u32, ::core::mem::transmute(databytes.as_ptr()), bytesreceived).ok() } } #[cfg(feature = "deprecated")] pub fn OnEndOfStream(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "deprecated")] pub fn OnNetworkError(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this)).ok() } } } unsafe impl ::windows::core::RuntimeType for INDDownloadEngineNotifier { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{d720b4d4-f4b8-4530-a809-9193a571e7fc}"); } impl ::core::convert::From<INDDownloadEngineNotifier> for ::windows::core::IUnknown { fn from(value: INDDownloadEngineNotifier) -> Self { value.0 .0 } } impl ::core::convert::From<&INDDownloadEngineNotifier> for ::windows::core::IUnknown { fn from(value: &INDDownloadEngineNotifier) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDDownloadEngineNotifier { 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 INDDownloadEngineNotifier { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDDownloadEngineNotifier> for ::windows::core::IInspectable { fn from(value: INDDownloadEngineNotifier) -> Self { value.0 } } impl ::core::convert::From<&INDDownloadEngineNotifier> for ::windows::core::IInspectable { fn from(value: &INDDownloadEngineNotifier) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDDownloadEngineNotifier { 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 INDDownloadEngineNotifier { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDDownloadEngineNotifier_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dataBytes_array_size: u32, databytes: *const u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, licensefetchdescriptor: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dataBytes_array_size: u32, databytes: *const u8, bytesreceived: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDLicenseFetchCompletedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDLicenseFetchCompletedEventArgs { type Vtable = INDLicenseFetchCompletedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1ee30a1a_11b2_4558_8865_e3a516922517); } impl INDLicenseFetchCompletedEventArgs { #[cfg(feature = "deprecated")] pub fn ResponseCustomData(&self) -> ::windows::core::Result<INDCustomData> { 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::<INDCustomData>(result__) } } } unsafe impl ::windows::core::RuntimeType for INDLicenseFetchCompletedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{1ee30a1a-11b2-4558-8865-e3a516922517}"); } impl ::core::convert::From<INDLicenseFetchCompletedEventArgs> for ::windows::core::IUnknown { fn from(value: INDLicenseFetchCompletedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&INDLicenseFetchCompletedEventArgs> for ::windows::core::IUnknown { fn from(value: &INDLicenseFetchCompletedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDLicenseFetchCompletedEventArgs { 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 INDLicenseFetchCompletedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDLicenseFetchCompletedEventArgs> for ::windows::core::IInspectable { fn from(value: INDLicenseFetchCompletedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&INDLicenseFetchCompletedEventArgs> for ::windows::core::IInspectable { fn from(value: &INDLicenseFetchCompletedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDLicenseFetchCompletedEventArgs { 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 INDLicenseFetchCompletedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDLicenseFetchCompletedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDLicenseFetchDescriptor(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDLicenseFetchDescriptor { type Vtable = INDLicenseFetchDescriptor_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5498d33a_e686_4935_a567_7ca77ad20fa4); } impl INDLicenseFetchDescriptor { #[cfg(feature = "deprecated")] pub fn ContentIDType(&self) -> ::windows::core::Result<NDContentIDType> { let this = self; unsafe { let mut result__: NDContentIDType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<NDContentIDType>(result__) } } #[cfg(feature = "deprecated")] pub fn ContentID(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } #[cfg(feature = "deprecated")] pub fn LicenseFetchChallengeCustomData(&self) -> ::windows::core::Result<INDCustomData> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<INDCustomData>(result__) } } #[cfg(feature = "deprecated")] pub fn SetLicenseFetchChallengeCustomData<'a, Param0: ::windows::core::IntoParam<'a, INDCustomData>>(&self, licensefetchchallengecustomdata: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), licensefetchchallengecustomdata.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for INDLicenseFetchDescriptor { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{5498d33a-e686-4935-a567-7ca77ad20fa4}"); } impl ::core::convert::From<INDLicenseFetchDescriptor> for ::windows::core::IUnknown { fn from(value: INDLicenseFetchDescriptor) -> Self { value.0 .0 } } impl ::core::convert::From<&INDLicenseFetchDescriptor> for ::windows::core::IUnknown { fn from(value: &INDLicenseFetchDescriptor) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDLicenseFetchDescriptor { 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 INDLicenseFetchDescriptor { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDLicenseFetchDescriptor> for ::windows::core::IInspectable { fn from(value: INDLicenseFetchDescriptor) -> Self { value.0 } } impl ::core::convert::From<&INDLicenseFetchDescriptor> for ::windows::core::IInspectable { fn from(value: &INDLicenseFetchDescriptor) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDLicenseFetchDescriptor { 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 INDLicenseFetchDescriptor { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDLicenseFetchDescriptor_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 NDContentIDType) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut u8) -> ::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, licensefetchchallengecustomdata: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct INDLicenseFetchDescriptorFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDLicenseFetchDescriptorFactory { type Vtable = INDLicenseFetchDescriptorFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd0031202_cfac_4f00_ae6a_97af80b848f2); } #[repr(C)] #[doc(hidden)] pub struct INDLicenseFetchDescriptorFactory_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, contentidtype: NDContentIDType, contentIDBytes_array_size: u32, contentidbytes: *const u8, licensefetchchallengecustomdata: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDLicenseFetchResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDLicenseFetchResult { type Vtable = INDLicenseFetchResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x21d39698_aa62_45ff_a5ff_8037e5433825); } impl INDLicenseFetchResult { #[cfg(feature = "deprecated")] pub fn ResponseCustomData(&self) -> ::windows::core::Result<INDCustomData> { 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::<INDCustomData>(result__) } } } unsafe impl ::windows::core::RuntimeType for INDLicenseFetchResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{21d39698-aa62-45ff-a5ff-8037e5433825}"); } impl ::core::convert::From<INDLicenseFetchResult> for ::windows::core::IUnknown { fn from(value: INDLicenseFetchResult) -> Self { value.0 .0 } } impl ::core::convert::From<&INDLicenseFetchResult> for ::windows::core::IUnknown { fn from(value: &INDLicenseFetchResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDLicenseFetchResult { 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 INDLicenseFetchResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDLicenseFetchResult> for ::windows::core::IInspectable { fn from(value: INDLicenseFetchResult) -> Self { value.0 } } impl ::core::convert::From<&INDLicenseFetchResult> for ::windows::core::IInspectable { fn from(value: &INDLicenseFetchResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDLicenseFetchResult { 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 INDLicenseFetchResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDLicenseFetchResult_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDMessenger(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDMessenger { type Vtable = INDMessenger_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd42df95d_a75b_47bf_8249_bc83820da38a); } impl INDMessenger { #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn SendRegistrationRequestAsync(&self, sessionidbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], challengedatabytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<INDSendResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), sessionidbytes.len() as u32, ::core::mem::transmute(sessionidbytes.as_ptr()), challengedatabytes.len() as u32, ::core::mem::transmute(challengedatabytes.as_ptr()), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<INDSendResult>>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn SendProximityDetectionStartAsync(&self, pdtype: NDProximityDetectionType, transmitterchannelbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], sessionidbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], challengedatabytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<INDSendResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)( ::core::mem::transmute_copy(this), pdtype, transmitterchannelbytes.len() as u32, ::core::mem::transmute(transmitterchannelbytes.as_ptr()), sessionidbytes.len() as u32, ::core::mem::transmute(sessionidbytes.as_ptr()), challengedatabytes.len() as u32, ::core::mem::transmute(challengedatabytes.as_ptr()), &mut result__, ) .from_abi::<super::super::super::Foundation::IAsyncOperation<INDSendResult>>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn SendProximityDetectionResponseAsync(&self, pdtype: NDProximityDetectionType, transmitterchannelbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], sessionidbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], responsedatabytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<INDSendResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)( ::core::mem::transmute_copy(this), pdtype, transmitterchannelbytes.len() as u32, ::core::mem::transmute(transmitterchannelbytes.as_ptr()), sessionidbytes.len() as u32, ::core::mem::transmute(sessionidbytes.as_ptr()), responsedatabytes.len() as u32, ::core::mem::transmute(responsedatabytes.as_ptr()), &mut result__, ) .from_abi::<super::super::super::Foundation::IAsyncOperation<INDSendResult>>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn SendLicenseFetchRequestAsync(&self, sessionidbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], challengedatabytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<INDSendResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), sessionidbytes.len() as u32, ::core::mem::transmute(sessionidbytes.as_ptr()), challengedatabytes.len() as u32, ::core::mem::transmute(challengedatabytes.as_ptr()), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<INDSendResult>>(result__) } } } unsafe impl ::windows::core::RuntimeType for INDMessenger { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{d42df95d-a75b-47bf-8249-bc83820da38a}"); } impl ::core::convert::From<INDMessenger> for ::windows::core::IUnknown { fn from(value: INDMessenger) -> Self { value.0 .0 } } impl ::core::convert::From<&INDMessenger> for ::windows::core::IUnknown { fn from(value: &INDMessenger) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDMessenger { 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 INDMessenger { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDMessenger> for ::windows::core::IInspectable { fn from(value: INDMessenger) -> Self { value.0 } } impl ::core::convert::From<&INDMessenger> for ::windows::core::IInspectable { fn from(value: &INDMessenger) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDMessenger { 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 INDMessenger { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDMessenger_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, sessionIDBytes_array_size: u32, sessionidbytes: *const u8, challengeDataBytes_array_size: u32, challengedatabytes: *const u8, 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, pdtype: NDProximityDetectionType, transmitterChannelBytes_array_size: u32, transmitterchannelbytes: *const u8, sessionIDBytes_array_size: u32, sessionidbytes: *const u8, challengeDataBytes_array_size: u32, challengedatabytes: *const u8, 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, pdtype: NDProximityDetectionType, transmitterChannelBytes_array_size: u32, transmitterchannelbytes: *const u8, sessionIDBytes_array_size: u32, sessionidbytes: *const u8, responseDataBytes_array_size: u32, responsedatabytes: *const u8, 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, sessionIDBytes_array_size: u32, sessionidbytes: *const u8, challengeDataBytes_array_size: u32, challengedatabytes: *const u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDProximityDetectionCompletedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDProximityDetectionCompletedEventArgs { type Vtable = INDProximityDetectionCompletedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2a706328_da25_4f8c_9eb7_5d0fc3658bca); } impl INDProximityDetectionCompletedEventArgs { #[cfg(feature = "deprecated")] pub fn ProximityDetectionRetryCount(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } } unsafe impl ::windows::core::RuntimeType for INDProximityDetectionCompletedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{2a706328-da25-4f8c-9eb7-5d0fc3658bca}"); } impl ::core::convert::From<INDProximityDetectionCompletedEventArgs> for ::windows::core::IUnknown { fn from(value: INDProximityDetectionCompletedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&INDProximityDetectionCompletedEventArgs> for ::windows::core::IUnknown { fn from(value: &INDProximityDetectionCompletedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDProximityDetectionCompletedEventArgs { 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 INDProximityDetectionCompletedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDProximityDetectionCompletedEventArgs> for ::windows::core::IInspectable { fn from(value: INDProximityDetectionCompletedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&INDProximityDetectionCompletedEventArgs> for ::windows::core::IInspectable { fn from(value: &INDProximityDetectionCompletedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDProximityDetectionCompletedEventArgs { 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 INDProximityDetectionCompletedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDProximityDetectionCompletedEventArgs_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 u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDRegistrationCompletedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDRegistrationCompletedEventArgs { type Vtable = INDRegistrationCompletedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9e39b64d_ab5b_4905_acdc_787a77c6374d); } impl INDRegistrationCompletedEventArgs { #[cfg(feature = "deprecated")] pub fn ResponseCustomData(&self) -> ::windows::core::Result<INDCustomData> { 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::<INDCustomData>(result__) } } #[cfg(feature = "deprecated")] pub fn TransmitterProperties(&self) -> ::windows::core::Result<INDTransmitterProperties> { 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::<INDTransmitterProperties>(result__) } } #[cfg(feature = "deprecated")] pub fn TransmitterCertificateAccepted(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "deprecated")] pub fn SetTransmitterCertificateAccepted(&self, accept: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), accept).ok() } } } unsafe impl ::windows::core::RuntimeType for INDRegistrationCompletedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{9e39b64d-ab5b-4905-acdc-787a77c6374d}"); } impl ::core::convert::From<INDRegistrationCompletedEventArgs> for ::windows::core::IUnknown { fn from(value: INDRegistrationCompletedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&INDRegistrationCompletedEventArgs> for ::windows::core::IUnknown { fn from(value: &INDRegistrationCompletedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDRegistrationCompletedEventArgs { 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 INDRegistrationCompletedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDRegistrationCompletedEventArgs> for ::windows::core::IInspectable { fn from(value: INDRegistrationCompletedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&INDRegistrationCompletedEventArgs> for ::windows::core::IInspectable { fn from(value: &INDRegistrationCompletedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDRegistrationCompletedEventArgs { 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 INDRegistrationCompletedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDRegistrationCompletedEventArgs_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, accept: bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDSendResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDSendResult { type Vtable = INDSendResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe3685517_a584_479d_90b7_d689c7bf7c80); } impl INDSendResult { #[cfg(feature = "deprecated")] pub fn Response(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } } unsafe impl ::windows::core::RuntimeType for INDSendResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{e3685517-a584-479d-90b7-d689c7bf7c80}"); } impl ::core::convert::From<INDSendResult> for ::windows::core::IUnknown { fn from(value: INDSendResult) -> Self { value.0 .0 } } impl ::core::convert::From<&INDSendResult> for ::windows::core::IUnknown { fn from(value: &INDSendResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDSendResult { 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 INDSendResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDSendResult> for ::windows::core::IInspectable { fn from(value: INDSendResult) -> Self { value.0 } } impl ::core::convert::From<&INDSendResult> for ::windows::core::IInspectable { fn from(value: &INDSendResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDSendResult { 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 INDSendResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDSendResult_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_size__: *mut u32, result__: *mut *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDStartResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDStartResult { type Vtable = INDStartResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79f6e96e_f50f_4015_8ba4_c2bc344ebd4e); } impl INDStartResult { #[cfg(feature = "deprecated")] #[cfg(feature = "Media_Core")] pub fn MediaStreamSource(&self) -> ::windows::core::Result<super::super::Core::MediaStreamSource> { 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::Core::MediaStreamSource>(result__) } } } unsafe impl ::windows::core::RuntimeType for INDStartResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{79f6e96e-f50f-4015-8ba4-c2bc344ebd4e}"); } impl ::core::convert::From<INDStartResult> for ::windows::core::IUnknown { fn from(value: INDStartResult) -> Self { value.0 .0 } } impl ::core::convert::From<&INDStartResult> for ::windows::core::IUnknown { fn from(value: &INDStartResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDStartResult { 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 INDStartResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDStartResult> for ::windows::core::IInspectable { fn from(value: INDStartResult) -> Self { value.0 } } impl ::core::convert::From<&INDStartResult> for ::windows::core::IInspectable { fn from(value: &INDStartResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDStartResult { 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 INDStartResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDStartResult_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_Core")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Media_Core"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDStorageFileHelper(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDStorageFileHelper { type Vtable = INDStorageFileHelper_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd8f0bef8_91d2_4d47_a3f9_eaff4edb729f); } impl INDStorageFileHelper { #[cfg(feature = "deprecated")] #[cfg(all(feature = "Foundation_Collections", feature = "Storage"))] pub fn GetFileURLs<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Storage::IStorageFile>>(&self, file: Param0) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), file.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<::windows::core::HSTRING>>(result__) } } } unsafe impl ::windows::core::RuntimeType for INDStorageFileHelper { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{d8f0bef8-91d2-4d47-a3f9-eaff4edb729f}"); } impl ::core::convert::From<INDStorageFileHelper> for ::windows::core::IUnknown { fn from(value: INDStorageFileHelper) -> Self { value.0 .0 } } impl ::core::convert::From<&INDStorageFileHelper> for ::windows::core::IUnknown { fn from(value: &INDStorageFileHelper) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDStorageFileHelper { 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 INDStorageFileHelper { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDStorageFileHelper> for ::windows::core::IInspectable { fn from(value: INDStorageFileHelper) -> Self { value.0 } } impl ::core::convert::From<&INDStorageFileHelper> for ::windows::core::IInspectable { fn from(value: &INDStorageFileHelper) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDStorageFileHelper { 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 INDStorageFileHelper { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDStorageFileHelper_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation_Collections", feature = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, file: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation_Collections", feature = "Storage")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDStreamParser(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDStreamParser { type Vtable = INDStreamParser_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe0baa198_9796_41c9_8695_59437e67e66a); } impl INDStreamParser { #[cfg(feature = "deprecated")] pub fn ParseData(&self, databytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), databytes.len() as u32, ::core::mem::transmute(databytes.as_ptr())).ok() } } #[cfg(feature = "deprecated")] #[cfg(feature = "Media_Core")] pub fn GetStreamInformation<'a, Param0: ::windows::core::IntoParam<'a, super::super::Core::IMediaStreamDescriptor>>(&self, descriptor: Param0, streamtype: &mut NDMediaStreamType) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), descriptor.into_param().abi(), streamtype, &mut result__).from_abi::<u32>(result__) } } #[cfg(feature = "deprecated")] pub fn BeginOfStream(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "deprecated")] pub fn EndOfStream(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "deprecated")] pub fn Notifier(&self) -> ::windows::core::Result<NDStreamParserNotifier> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<NDStreamParserNotifier>(result__) } } } unsafe impl ::windows::core::RuntimeType for INDStreamParser { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{e0baa198-9796-41c9-8695-59437e67e66a}"); } impl ::core::convert::From<INDStreamParser> for ::windows::core::IUnknown { fn from(value: INDStreamParser) -> Self { value.0 .0 } } impl ::core::convert::From<&INDStreamParser> for ::windows::core::IUnknown { fn from(value: &INDStreamParser) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDStreamParser { 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 INDStreamParser { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDStreamParser> for ::windows::core::IInspectable { fn from(value: INDStreamParser) -> Self { value.0 } } impl ::core::convert::From<&INDStreamParser> for ::windows::core::IInspectable { fn from(value: &INDStreamParser) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDStreamParser { 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 INDStreamParser { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDStreamParser_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, dataBytes_array_size: u32, databytes: *const u8) -> ::windows::core::HRESULT, #[cfg(feature = "Media_Core")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, descriptor: ::windows::core::RawPtr, streamtype: *mut NDMediaStreamType, result__: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Media_Core"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDStreamParserNotifier(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDStreamParserNotifier { type Vtable = INDStreamParserNotifier_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc167acd0_2ce6_426c_ace5_5e9275fea715); } impl INDStreamParserNotifier { #[cfg(feature = "deprecated")] pub fn OnContentIDReceived<'a, Param0: ::windows::core::IntoParam<'a, INDLicenseFetchDescriptor>>(&self, licensefetchdescriptor: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), licensefetchdescriptor.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] #[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))] pub fn OnMediaStreamDescriptorCreated<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IVector<super::super::Core::AudioStreamDescriptor>>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IVector<super::super::Core::VideoStreamDescriptor>>>(&self, audiostreamdescriptors: Param0, videostreamdescriptors: Param1) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), audiostreamdescriptors.into_param().abi(), videostreamdescriptors.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] #[cfg(feature = "Media_Core")] pub fn OnSampleParsed<'a, Param2: ::windows::core::IntoParam<'a, super::super::Core::MediaStreamSample>>(&self, streamid: u32, streamtype: NDMediaStreamType, streamsample: Param2, pts: i64, ccformat: NDClosedCaptionFormat, ccdatabytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), streamid, streamtype, streamsample.into_param().abi(), pts, ccformat, ccdatabytes.len() as u32, ::core::mem::transmute(ccdatabytes.as_ptr())).ok() } } #[cfg(feature = "deprecated")] #[cfg(feature = "Media_Core")] pub fn OnBeginSetupDecryptor<'a, Param0: ::windows::core::IntoParam<'a, super::super::Core::IMediaStreamDescriptor>, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, descriptor: Param0, keyid: Param1, probytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), descriptor.into_param().abi(), keyid.into_param().abi(), probytes.len() as u32, ::core::mem::transmute(probytes.as_ptr())).ok() } } } unsafe impl ::windows::core::RuntimeType for INDStreamParserNotifier { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{c167acd0-2ce6-426c-ace5-5e9275fea715}"); } impl ::core::convert::From<INDStreamParserNotifier> for ::windows::core::IUnknown { fn from(value: INDStreamParserNotifier) -> Self { value.0 .0 } } impl ::core::convert::From<&INDStreamParserNotifier> for ::windows::core::IUnknown { fn from(value: &INDStreamParserNotifier) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDStreamParserNotifier { 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 INDStreamParserNotifier { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDStreamParserNotifier> for ::windows::core::IInspectable { fn from(value: INDStreamParserNotifier) -> Self { value.0 } } impl ::core::convert::From<&INDStreamParserNotifier> for ::windows::core::IInspectable { fn from(value: &INDStreamParserNotifier) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDStreamParserNotifier { 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 INDStreamParserNotifier { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDStreamParserNotifier_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, licensefetchdescriptor: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, audiostreamdescriptors: ::windows::core::RawPtr, videostreamdescriptors: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation_Collections", feature = "Media_Core")))] usize, #[cfg(feature = "Media_Core")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, streamid: u32, streamtype: NDMediaStreamType, streamsample: ::windows::core::RawPtr, pts: i64, ccformat: NDClosedCaptionFormat, ccDataBytes_array_size: u32, ccdatabytes: *const u8) -> ::windows::core::HRESULT, #[cfg(not(feature = "Media_Core"))] usize, #[cfg(feature = "Media_Core")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, descriptor: ::windows::core::RawPtr, keyid: ::windows::core::GUID, proBytes_array_size: u32, probytes: *const u8) -> ::windows::core::HRESULT, #[cfg(not(feature = "Media_Core"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct INDTCPMessengerFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDTCPMessengerFactory { type Vtable = INDTCPMessengerFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7dd85cfe_1b99_4f68_8f82_8177f7cedf2b); } #[repr(C)] #[doc(hidden)] pub struct INDTCPMessengerFactory_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, remotehostname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, remotehostport: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct INDTransmitterProperties(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for INDTransmitterProperties { type Vtable = INDTransmitterProperties_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe536af23_ac4f_4adc_8c66_4ff7c2702dd6); } impl INDTransmitterProperties { #[cfg(feature = "deprecated")] pub fn CertificateType(&self) -> ::windows::core::Result<NDCertificateType> { let this = self; unsafe { let mut result__: NDCertificateType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<NDCertificateType>(result__) } } #[cfg(feature = "deprecated")] pub fn PlatformIdentifier(&self) -> ::windows::core::Result<NDCertificatePlatformID> { let this = self; unsafe { let mut result__: NDCertificatePlatformID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<NDCertificatePlatformID>(result__) } } #[cfg(feature = "deprecated")] pub fn SupportedFeatures(&self) -> ::windows::core::Result<::windows::core::Array<NDCertificateFeature>> { let this = self; unsafe { let mut result__: ::windows::core::Array<NDCertificateFeature> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), ::windows::core::Array::<NDCertificateFeature>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } #[cfg(feature = "deprecated")] pub fn SecurityLevel(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } #[cfg(feature = "deprecated")] pub fn SecurityVersion(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn ExpirationDate(&self) -> ::windows::core::Result<super::super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::DateTime>(result__) } } #[cfg(feature = "deprecated")] pub fn ClientID(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } #[cfg(feature = "deprecated")] pub fn ModelDigest(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } #[cfg(feature = "deprecated")] pub fn ModelManufacturerName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "deprecated")] pub fn ModelName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "deprecated")] pub fn ModelNumber(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } } unsafe impl ::windows::core::RuntimeType for INDTransmitterProperties { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{e536af23-ac4f-4adc-8c66-4ff7c2702dd6}"); } impl ::core::convert::From<INDTransmitterProperties> for ::windows::core::IUnknown { fn from(value: INDTransmitterProperties) -> Self { value.0 .0 } } impl ::core::convert::From<&INDTransmitterProperties> for ::windows::core::IUnknown { fn from(value: &INDTransmitterProperties) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INDTransmitterProperties { 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 INDTransmitterProperties { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<INDTransmitterProperties> for ::windows::core::IInspectable { fn from(value: INDTransmitterProperties) -> Self { value.0 } } impl ::core::convert::From<&INDTransmitterProperties> for ::windows::core::IInspectable { fn from(value: &INDTransmitterProperties) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INDTransmitterProperties { 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 INDTransmitterProperties { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct INDTransmitterProperties_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 NDCertificateType) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut NDCertificatePlatformID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut NDCertificateFeature) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut u8) -> ::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 IPlayReadyContentHeader(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyContentHeader { type Vtable = IPlayReadyContentHeader_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9a438a6a_7f4c_452e_88bd_0148c6387a2c); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyContentHeader_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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PlayReadyEncryptionAlgorithm) -> ::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 PlayReadyDecryptorSetup) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut u8) -> ::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 IPlayReadyContentHeader2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyContentHeader2 { type Vtable = IPlayReadyContentHeader2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x359c79f4_2180_498c_965b_e754d875eab2); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyContentHeader2_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_size__: *mut u32, result__: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyContentHeaderFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyContentHeaderFactory { type Vtable = IPlayReadyContentHeaderFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcb97c8ff_b758_4776_bf01_217a8b510b2c); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyContentHeaderFactory_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, headerBytes_array_size: u32, headerbytes: *const u8, licenseacquisitionurl: ::windows::core::RawPtr, licenseacquisitionuserinterfaceurl: ::windows::core::RawPtr, customattributes: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, domainserviceid: ::windows::core::GUID, 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, contentkeyid: ::windows::core::GUID, contentkeyidstring: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, contentencryptionalgorithm: PlayReadyEncryptionAlgorithm, licenseacquisitionurl: ::windows::core::RawPtr, licenseacquisitionuserinterfaceurl: ::windows::core::RawPtr, customattributes: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, domainserviceid: ::windows::core::GUID, result__: *mut ::windows::core::RawPtr, ) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, headerBytes_array_size: u32, headerbytes: *const u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyContentHeaderFactory2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyContentHeaderFactory2 { type Vtable = IPlayReadyContentHeaderFactory2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd1239cf5_ae6d_4778_97fd_6e3a2eeadbeb); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyContentHeaderFactory2_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, dwflags: u32, contentKeyIds_array_size: u32, contentkeyids: *const ::windows::core::GUID, contentKeyIdStrings_array_size: u32, contentkeyidstrings: *const ::core::mem::ManuallyDrop<::windows::core::HSTRING>, contentencryptionalgorithm: PlayReadyEncryptionAlgorithm, licenseacquisitionurl: ::windows::core::RawPtr, licenseacquisitionuserinterfaceurl: ::windows::core::RawPtr, customattributes: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, domainserviceid: ::windows::core::GUID, result__: *mut ::windows::core::RawPtr, ) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyContentResolver(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyContentResolver { type Vtable = IPlayReadyContentResolver_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfbfd2523_906d_4982_a6b8_6849565a7ce8); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyContentResolver_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, contentheader: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPlayReadyDomain(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyDomain { type Vtable = IPlayReadyDomain_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xadcc93ac_97e6_43ef_95e4_d7868f3b16a9); } impl IPlayReadyDomain { pub fn AccountId(&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 ServiceId(&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__) } } pub fn Revision(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn FriendlyName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn DomainJoinUrl(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } } unsafe impl ::windows::core::RuntimeType for IPlayReadyDomain { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{adcc93ac-97e6-43ef-95e4-d7868f3b16a9}"); } impl ::core::convert::From<IPlayReadyDomain> for ::windows::core::IUnknown { fn from(value: IPlayReadyDomain) -> Self { value.0 .0 } } impl ::core::convert::From<&IPlayReadyDomain> for ::windows::core::IUnknown { fn from(value: &IPlayReadyDomain) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPlayReadyDomain { 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 IPlayReadyDomain { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IPlayReadyDomain> for ::windows::core::IInspectable { fn from(value: IPlayReadyDomain) -> Self { value.0 } } impl ::core::convert::From<&IPlayReadyDomain> for ::windows::core::IInspectable { fn from(value: &IPlayReadyDomain) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IPlayReadyDomain { 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 IPlayReadyDomain { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyDomain_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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyDomainIterableFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyDomainIterableFactory { type Vtable = IPlayReadyDomainIterableFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4df384ee_3121_4df3_a5e8_d0c24c0500fc); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyDomainIterableFactory_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, domainaccountid: ::windows::core::GUID, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyDomainJoinServiceRequest(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyDomainJoinServiceRequest { type Vtable = IPlayReadyDomainJoinServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x171b4a5a_405f_4739_b040_67b9f0c38758); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyDomainJoinServiceRequest_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, value: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::GUID) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyDomainLeaveServiceRequest(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyDomainLeaveServiceRequest { type Vtable = IPlayReadyDomainLeaveServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x062d58be_97ad_4917_aa03_46d4c252d464); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyDomainLeaveServiceRequest_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, value: ::windows::core::GUID) -> ::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, value: ::windows::core::GUID) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyITADataGenerator(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyITADataGenerator { type Vtable = IPlayReadyITADataGenerator_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x24446b8e_10b9_4530_b25b_901a8029a9b2); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyITADataGenerator_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, guidcpsystemid: ::windows::core::GUID, countofstreams: u32, configuration: ::windows::core::RawPtr, format: PlayReadyITADataFormat, result_size__: *mut u32, result__: *mut *mut u8) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyIndividualizationServiceRequest(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyIndividualizationServiceRequest { type Vtable = IPlayReadyIndividualizationServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x21f5a86b_008c_4611_ab2f_aaa6c69f0e24); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyIndividualizationServiceRequest_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPlayReadyLicense(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyLicense { type Vtable = IPlayReadyLicense_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xee474c4e_fa3c_414d_a9f2_3ffc1ef832d4); } impl IPlayReadyLicense { pub fn FullyEvaluated(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn UsableForPlay(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation")] pub fn ExpirationDate(&self) -> ::windows::core::Result<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>>(result__) } } pub fn ExpireAfterFirstPlay(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn DomainAccountID(&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).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn ChainDepth(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn GetKIDAtChainDepth(&self, chaindepth: u32) -> ::windows::core::Result<::windows::core::GUID> { let this = self; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), chaindepth, &mut result__).from_abi::<::windows::core::GUID>(result__) } } } unsafe impl ::windows::core::RuntimeType for IPlayReadyLicense { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{ee474c4e-fa3c-414d-a9f2-3ffc1ef832d4}"); } impl ::core::convert::From<IPlayReadyLicense> for ::windows::core::IUnknown { fn from(value: IPlayReadyLicense) -> Self { value.0 .0 } } impl ::core::convert::From<&IPlayReadyLicense> for ::windows::core::IUnknown { fn from(value: &IPlayReadyLicense) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPlayReadyLicense { 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 IPlayReadyLicense { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IPlayReadyLicense> for ::windows::core::IInspectable { fn from(value: IPlayReadyLicense) -> Self { value.0 } } impl ::core::convert::From<&IPlayReadyLicense> for ::windows::core::IInspectable { fn from(value: &IPlayReadyLicense) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IPlayReadyLicense { 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 IPlayReadyLicense { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyLicense_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, chaindepth: u32, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyLicense2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyLicense2 { type Vtable = IPlayReadyLicense2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x30f4e7a7_d8e3_48a0_bcda_ff9f40530436); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyLicense2_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 u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPlayReadyLicenseAcquisitionServiceRequest(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyLicenseAcquisitionServiceRequest { type Vtable = IPlayReadyLicenseAcquisitionServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5d85ff45_3e9f_4f48_93e1_9530c8d58c3e); } impl IPlayReadyLicenseAcquisitionServiceRequest { pub fn ContentHeader(&self) -> ::windows::core::Result<PlayReadyContentHeader> { 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::<PlayReadyContentHeader>(result__) } } pub fn SetContentHeader<'a, Param0: ::windows::core::IntoParam<'a, PlayReadyContentHeader>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn DomainServiceId(&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).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn SetDomainServiceId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ProtectionSystem(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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 = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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__) } } #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } #[cfg(feature = "Foundation")] pub fn SetUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ResponseCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 ChallengeCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 SetChallengeCustomData<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn BeginServiceRequest(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } pub fn NextServiceRequest(&self) -> ::windows::core::Result<IPlayReadyServiceRequest> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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::<IPlayReadyServiceRequest>(result__) } } pub fn GenerateManualEnablingChallenge(&self) -> ::windows::core::Result<PlayReadySoapMessage> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlayReadySoapMessage>(result__) } } pub fn ProcessManualEnablingResponse(&self, responsebytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<::windows::core::HRESULT> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), responsebytes.len() as u32, ::core::mem::transmute(responsebytes.as_ptr()), &mut result__).from_abi::<::windows::core::HRESULT>(result__) } } } unsafe impl ::windows::core::RuntimeType for IPlayReadyLicenseAcquisitionServiceRequest { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{5d85ff45-3e9f-4f48-93e1-9530c8d58c3e}"); } impl ::core::convert::From<IPlayReadyLicenseAcquisitionServiceRequest> for ::windows::core::IUnknown { fn from(value: IPlayReadyLicenseAcquisitionServiceRequest) -> Self { value.0 .0 } } impl ::core::convert::From<&IPlayReadyLicenseAcquisitionServiceRequest> for ::windows::core::IUnknown { fn from(value: &IPlayReadyLicenseAcquisitionServiceRequest) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPlayReadyLicenseAcquisitionServiceRequest { 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 IPlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IPlayReadyLicenseAcquisitionServiceRequest> for ::windows::core::IInspectable { fn from(value: IPlayReadyLicenseAcquisitionServiceRequest) -> Self { value.0 } } impl ::core::convert::From<&IPlayReadyLicenseAcquisitionServiceRequest> for ::windows::core::IInspectable { fn from(value: &IPlayReadyLicenseAcquisitionServiceRequest) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IPlayReadyLicenseAcquisitionServiceRequest { 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 IPlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<IPlayReadyLicenseAcquisitionServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: IPlayReadyLicenseAcquisitionServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&IPlayReadyLicenseAcquisitionServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &IPlayReadyLicenseAcquisitionServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for IPlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for &IPlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::core::convert::TryInto::<super::IMediaProtectionServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } impl ::core::convert::TryFrom<IPlayReadyLicenseAcquisitionServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: IPlayReadyLicenseAcquisitionServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&IPlayReadyLicenseAcquisitionServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &IPlayReadyLicenseAcquisitionServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for IPlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for &IPlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::core::convert::TryInto::<IPlayReadyServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyLicenseAcquisitionServiceRequest_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, value: ::windows::core::RawPtr) -> ::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, value: ::windows::core::GUID) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyLicenseAcquisitionServiceRequest2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyLicenseAcquisitionServiceRequest2 { type Vtable = IPlayReadyLicenseAcquisitionServiceRequest2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb7fa5eb5_fe0c_b225_bc60_5a9edd32ceb5); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyLicenseAcquisitionServiceRequest2_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyLicenseAcquisitionServiceRequest3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyLicenseAcquisitionServiceRequest3 { type Vtable = IPlayReadyLicenseAcquisitionServiceRequest3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x394e5f4d_7f75_430d_b2e7_7f75f34b2d75); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyLicenseAcquisitionServiceRequest3_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, contentheader: ::windows::core::RawPtr, fullyevaluated: bool, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyLicenseIterableFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyLicenseIterableFactory { type Vtable = IPlayReadyLicenseIterableFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd4179f08_0837_4978_8e68_be4293c8d7a6); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyLicenseIterableFactory_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, contentheader: ::windows::core::RawPtr, fullyevaluated: bool, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyLicenseManagement(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyLicenseManagement { type Vtable = IPlayReadyLicenseManagement_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaaeb2141_0957_4405_b892_8bf3ec5dadd9); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyLicenseManagement_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, contentheader: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPlayReadyLicenseSession(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyLicenseSession { type Vtable = IPlayReadyLicenseSession_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa1723a39_87fa_4fdd_abbb_a9720e845259); } impl IPlayReadyLicenseSession { pub fn CreateLAServiceRequest(&self) -> ::windows::core::Result<IPlayReadyLicenseAcquisitionServiceRequest> { 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::<IPlayReadyLicenseAcquisitionServiceRequest>(result__) } } pub fn ConfigureMediaProtectionManager<'a, Param0: ::windows::core::IntoParam<'a, super::MediaProtectionManager>>(&self, mpm: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), mpm.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for IPlayReadyLicenseSession { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{a1723a39-87fa-4fdd-abbb-a9720e845259}"); } impl ::core::convert::From<IPlayReadyLicenseSession> for ::windows::core::IUnknown { fn from(value: IPlayReadyLicenseSession) -> Self { value.0 .0 } } impl ::core::convert::From<&IPlayReadyLicenseSession> for ::windows::core::IUnknown { fn from(value: &IPlayReadyLicenseSession) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPlayReadyLicenseSession { 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 IPlayReadyLicenseSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IPlayReadyLicenseSession> for ::windows::core::IInspectable { fn from(value: IPlayReadyLicenseSession) -> Self { value.0 } } impl ::core::convert::From<&IPlayReadyLicenseSession> for ::windows::core::IInspectable { fn from(value: &IPlayReadyLicenseSession) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IPlayReadyLicenseSession { 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 IPlayReadyLicenseSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyLicenseSession_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, mpm: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPlayReadyLicenseSession2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyLicenseSession2 { type Vtable = IPlayReadyLicenseSession2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4909be3a_3aed_4656_8ad7_ee0fd7799510); } impl IPlayReadyLicenseSession2 { pub fn CreateLAServiceRequest(&self) -> ::windows::core::Result<IPlayReadyLicenseAcquisitionServiceRequest> { let this = &::windows::core::Interface::cast::<IPlayReadyLicenseSession>(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::<IPlayReadyLicenseAcquisitionServiceRequest>(result__) } } pub fn ConfigureMediaProtectionManager<'a, Param0: ::windows::core::IntoParam<'a, super::MediaProtectionManager>>(&self, mpm: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyLicenseSession>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), mpm.into_param().abi()).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn CreateLicenseIterable<'a, Param0: ::windows::core::IntoParam<'a, PlayReadyContentHeader>>(&self, contentheader: Param0, fullyevaluated: bool) -> ::windows::core::Result<PlayReadyLicenseIterable> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), contentheader.into_param().abi(), fullyevaluated, &mut result__).from_abi::<PlayReadyLicenseIterable>(result__) } } } unsafe impl ::windows::core::RuntimeType for IPlayReadyLicenseSession2 { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{4909be3a-3aed-4656-8ad7-ee0fd7799510}"); } impl ::core::convert::From<IPlayReadyLicenseSession2> for ::windows::core::IUnknown { fn from(value: IPlayReadyLicenseSession2) -> Self { value.0 .0 } } impl ::core::convert::From<&IPlayReadyLicenseSession2> for ::windows::core::IUnknown { fn from(value: &IPlayReadyLicenseSession2) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPlayReadyLicenseSession2 { 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 IPlayReadyLicenseSession2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IPlayReadyLicenseSession2> for ::windows::core::IInspectable { fn from(value: IPlayReadyLicenseSession2) -> Self { value.0 } } impl ::core::convert::From<&IPlayReadyLicenseSession2> for ::windows::core::IInspectable { fn from(value: &IPlayReadyLicenseSession2) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IPlayReadyLicenseSession2 { 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 IPlayReadyLicenseSession2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<IPlayReadyLicenseSession2> for IPlayReadyLicenseSession { type Error = ::windows::core::Error; fn try_from(value: IPlayReadyLicenseSession2) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&IPlayReadyLicenseSession2> for IPlayReadyLicenseSession { type Error = ::windows::core::Error; fn try_from(value: &IPlayReadyLicenseSession2) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyLicenseSession> for IPlayReadyLicenseSession2 { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyLicenseSession> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyLicenseSession> for &IPlayReadyLicenseSession2 { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyLicenseSession> { ::core::convert::TryInto::<IPlayReadyLicenseSession>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyLicenseSession2_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, contentheader: ::windows::core::RawPtr, fullyevaluated: bool, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyLicenseSessionFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyLicenseSessionFactory { type Vtable = IPlayReadyLicenseSessionFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x62492699_6527_429e_98be_48d798ac2739); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyLicenseSessionFactory_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, configuration: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyMeteringReportServiceRequest(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyMeteringReportServiceRequest { type Vtable = IPlayReadyMeteringReportServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc12b231c_0ecd_4f11_a185_1e24a4a67fb7); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyMeteringReportServiceRequest_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_size__: *mut u32, result__: *mut *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, meteringCertBytes_array_size: u32, meteringcertbytes: *const u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyRevocationServiceRequest(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyRevocationServiceRequest { type Vtable = IPlayReadyRevocationServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x543d66ac_faf0_4560_84a5_0e4acec939e4); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyRevocationServiceRequest_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadySecureStopIterableFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadySecureStopIterableFactory { type Vtable = IPlayReadySecureStopIterableFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5f1f0165_4214_4d9e_81eb_e89f9d294aee); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadySecureStopIterableFactory_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, publisherCertBytes_array_size: u32, publishercertbytes: *const u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPlayReadySecureStopServiceRequest(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadySecureStopServiceRequest { type Vtable = IPlayReadySecureStopServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb5501ee5_01bf_4401_9677_05630a6a4cc8); } impl IPlayReadySecureStopServiceRequest { pub fn SessionID(&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__) } } #[cfg(feature = "Foundation")] pub fn StartTime(&self) -> ::windows::core::Result<super::super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::DateTime>(result__) } } #[cfg(feature = "Foundation")] pub fn UpdateTime(&self) -> ::windows::core::Result<super::super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::DateTime>(result__) } } pub fn Stopped(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn PublisherCertificate(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } pub fn ProtectionSystem(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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 = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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__) } } #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } #[cfg(feature = "Foundation")] pub fn SetUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ResponseCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 ChallengeCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 SetChallengeCustomData<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn BeginServiceRequest(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } pub fn NextServiceRequest(&self) -> ::windows::core::Result<IPlayReadyServiceRequest> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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::<IPlayReadyServiceRequest>(result__) } } pub fn GenerateManualEnablingChallenge(&self) -> ::windows::core::Result<PlayReadySoapMessage> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlayReadySoapMessage>(result__) } } pub fn ProcessManualEnablingResponse(&self, responsebytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<::windows::core::HRESULT> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), responsebytes.len() as u32, ::core::mem::transmute(responsebytes.as_ptr()), &mut result__).from_abi::<::windows::core::HRESULT>(result__) } } } unsafe impl ::windows::core::RuntimeType for IPlayReadySecureStopServiceRequest { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{b5501ee5-01bf-4401-9677-05630a6a4cc8}"); } impl ::core::convert::From<IPlayReadySecureStopServiceRequest> for ::windows::core::IUnknown { fn from(value: IPlayReadySecureStopServiceRequest) -> Self { value.0 .0 } } impl ::core::convert::From<&IPlayReadySecureStopServiceRequest> for ::windows::core::IUnknown { fn from(value: &IPlayReadySecureStopServiceRequest) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPlayReadySecureStopServiceRequest { 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 IPlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IPlayReadySecureStopServiceRequest> for ::windows::core::IInspectable { fn from(value: IPlayReadySecureStopServiceRequest) -> Self { value.0 } } impl ::core::convert::From<&IPlayReadySecureStopServiceRequest> for ::windows::core::IInspectable { fn from(value: &IPlayReadySecureStopServiceRequest) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IPlayReadySecureStopServiceRequest { 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 IPlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<IPlayReadySecureStopServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: IPlayReadySecureStopServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&IPlayReadySecureStopServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &IPlayReadySecureStopServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for IPlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for &IPlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::core::convert::TryInto::<super::IMediaProtectionServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } impl ::core::convert::TryFrom<IPlayReadySecureStopServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: IPlayReadySecureStopServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&IPlayReadySecureStopServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &IPlayReadySecureStopServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for IPlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for &IPlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::core::convert::TryInto::<IPlayReadyServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(C)] #[doc(hidden)] pub struct IPlayReadySecureStopServiceRequest_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, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadySecureStopServiceRequestFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadySecureStopServiceRequestFactory { type Vtable = IPlayReadySecureStopServiceRequestFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0e448ac9_e67e_494e_9f49_6285438c76cf); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadySecureStopServiceRequestFactory_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, publisherCertBytes_array_size: u32, publishercertbytes: *const u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sessionid: ::windows::core::GUID, publisherCertBytes_array_size: u32, publishercertbytes: *const u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPlayReadyServiceRequest(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyServiceRequest { type Vtable = IPlayReadyServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8bad2836_a703_45a6_a180_76f3565aa725); } impl IPlayReadyServiceRequest { #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } #[cfg(feature = "Foundation")] pub fn SetUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ResponseCustomData(&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 ChallengeCustomData(&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 SetChallengeCustomData<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn BeginServiceRequest(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } pub fn NextServiceRequest(&self) -> ::windows::core::Result<IPlayReadyServiceRequest> { 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::<IPlayReadyServiceRequest>(result__) } } pub fn GenerateManualEnablingChallenge(&self) -> ::windows::core::Result<PlayReadySoapMessage> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlayReadySoapMessage>(result__) } } pub fn ProcessManualEnablingResponse(&self, responsebytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<::windows::core::HRESULT> { let this = self; unsafe { let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), responsebytes.len() as u32, ::core::mem::transmute(responsebytes.as_ptr()), &mut result__).from_abi::<::windows::core::HRESULT>(result__) } } pub fn ProtectionSystem(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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 = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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 IPlayReadyServiceRequest { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{8bad2836-a703-45a6-a180-76f3565aa725}"); } impl ::core::convert::From<IPlayReadyServiceRequest> for ::windows::core::IUnknown { fn from(value: IPlayReadyServiceRequest) -> Self { value.0 .0 } } impl ::core::convert::From<&IPlayReadyServiceRequest> for ::windows::core::IUnknown { fn from(value: &IPlayReadyServiceRequest) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPlayReadyServiceRequest { 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 IPlayReadyServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IPlayReadyServiceRequest> for ::windows::core::IInspectable { fn from(value: IPlayReadyServiceRequest) -> Self { value.0 } } impl ::core::convert::From<&IPlayReadyServiceRequest> for ::windows::core::IInspectable { fn from(value: &IPlayReadyServiceRequest) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IPlayReadyServiceRequest { 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 IPlayReadyServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<IPlayReadyServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: IPlayReadyServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&IPlayReadyServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &IPlayReadyServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for IPlayReadyServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for &IPlayReadyServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::core::convert::TryInto::<super::IMediaProtectionServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyServiceRequest_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, 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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, responseBytes_array_size: u32, responsebytes: *const u8, result__: *mut ::windows::core::HRESULT) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadySoapMessage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadySoapMessage { type Vtable = IPlayReadySoapMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb659fcb5_ce41_41ba_8a0d_61df5fffa139); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadySoapMessage_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_size__: *mut u32, result__: *mut *mut u8) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyStatics { type Vtable = IPlayReadyStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5e69c00d_247c_469a_8f31_5c1a1571d9c6); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyStatics_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, 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, 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, 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 u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyStatics2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyStatics2 { type Vtable = IPlayReadyStatics2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1f8d6a92_5f9a_423e_9466_b33969af7a3d); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyStatics2_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 u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyStatics3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyStatics3 { type Vtable = IPlayReadyStatics3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3fa33f71_2dd3_4bed_ae49_f7148e63e710); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyStatics3_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, hwdrmfeature: PlayReadyHardwareDRMFeatures, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyStatics4(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyStatics4 { type Vtable = IPlayReadyStatics4_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x50a91300_d824_4231_9d5e_78ef8844c7d7); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyStatics4_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlayReadyStatics5(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlayReadyStatics5 { type Vtable = IPlayReadyStatics5_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x230a7075_dfa0_4f8e_a779_cefea9c6824b); } #[repr(C)] #[doc(hidden)] pub struct IPlayReadyStatics5_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct NDCertificateFeature(pub i32); impl NDCertificateFeature { pub const Transmitter: NDCertificateFeature = NDCertificateFeature(1i32); pub const Receiver: NDCertificateFeature = NDCertificateFeature(2i32); pub const SharedCertificate: NDCertificateFeature = NDCertificateFeature(3i32); pub const SecureClock: NDCertificateFeature = NDCertificateFeature(4i32); pub const AntiRollBackClock: NDCertificateFeature = NDCertificateFeature(5i32); pub const CRLS: NDCertificateFeature = NDCertificateFeature(9i32); pub const PlayReady3Features: NDCertificateFeature = NDCertificateFeature(13i32); } impl ::core::convert::From<i32> for NDCertificateFeature { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for NDCertificateFeature { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for NDCertificateFeature { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.PlayReady.NDCertificateFeature;i4)"); } impl ::windows::core::DefaultType for NDCertificateFeature { 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 NDCertificatePlatformID(pub i32); impl NDCertificatePlatformID { pub const Windows: NDCertificatePlatformID = NDCertificatePlatformID(0i32); pub const OSX: NDCertificatePlatformID = NDCertificatePlatformID(1i32); pub const WindowsOnARM: NDCertificatePlatformID = NDCertificatePlatformID(2i32); pub const WindowsMobile7: NDCertificatePlatformID = NDCertificatePlatformID(5i32); pub const iOSOnARM: NDCertificatePlatformID = NDCertificatePlatformID(6i32); pub const XBoxOnPPC: NDCertificatePlatformID = NDCertificatePlatformID(7i32); pub const WindowsPhone8OnARM: NDCertificatePlatformID = NDCertificatePlatformID(8i32); pub const WindowsPhone8OnX86: NDCertificatePlatformID = NDCertificatePlatformID(9i32); pub const XboxOne: NDCertificatePlatformID = NDCertificatePlatformID(10i32); pub const AndroidOnARM: NDCertificatePlatformID = NDCertificatePlatformID(11i32); pub const WindowsPhone81OnARM: NDCertificatePlatformID = NDCertificatePlatformID(12i32); pub const WindowsPhone81OnX86: NDCertificatePlatformID = NDCertificatePlatformID(13i32); } impl ::core::convert::From<i32> for NDCertificatePlatformID { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for NDCertificatePlatformID { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for NDCertificatePlatformID { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.PlayReady.NDCertificatePlatformID;i4)"); } impl ::windows::core::DefaultType for NDCertificatePlatformID { 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 NDCertificateType(pub i32); impl NDCertificateType { pub const Unknown: NDCertificateType = NDCertificateType(0i32); pub const PC: NDCertificateType = NDCertificateType(1i32); pub const Device: NDCertificateType = NDCertificateType(2i32); pub const Domain: NDCertificateType = NDCertificateType(3i32); pub const Issuer: NDCertificateType = NDCertificateType(4i32); pub const CrlSigner: NDCertificateType = NDCertificateType(5i32); pub const Service: NDCertificateType = NDCertificateType(6i32); pub const Silverlight: NDCertificateType = NDCertificateType(7i32); pub const Application: NDCertificateType = NDCertificateType(8i32); pub const Metering: NDCertificateType = NDCertificateType(9i32); pub const KeyFileSigner: NDCertificateType = NDCertificateType(10i32); pub const Server: NDCertificateType = NDCertificateType(11i32); pub const LicenseSigner: NDCertificateType = NDCertificateType(12i32); } impl ::core::convert::From<i32> for NDCertificateType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for NDCertificateType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for NDCertificateType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.PlayReady.NDCertificateType;i4)"); } impl ::windows::core::DefaultType for NDCertificateType { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct NDClient(pub ::windows::core::IInspectable); impl NDClient { #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn RegistrationCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<NDClient, INDRegistrationCompletedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn RemoveRegistrationCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn ProximityDetectionCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<NDClient, INDProximityDetectionCompletedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn RemoveProximityDetectionCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn LicenseFetchCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<NDClient, INDLicenseFetchCompletedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn RemoveLicenseFetchCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn ReRegistrationNeeded<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<NDClient, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn RemoveReRegistrationNeeded<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn ClosedCaptionDataReceived<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<NDClient, INDClosedCaptionDataReceivedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn RemoveClosedCaptionDataReceived<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn StartAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>, Param2: ::windows::core::IntoParam<'a, INDCustomData>, Param3: ::windows::core::IntoParam<'a, INDLicenseFetchDescriptor>>(&self, contenturl: Param0, startasyncoptions: u32, registrationcustomdata: Param2, licensefetchdescriptor: Param3) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<INDStartResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), contenturl.into_param().abi(), startasyncoptions, registrationcustomdata.into_param().abi(), licensefetchdescriptor.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<INDStartResult>>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn LicenseFetchAsync<'a, Param0: ::windows::core::IntoParam<'a, INDLicenseFetchDescriptor>>(&self, licensefetchdescriptor: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<INDLicenseFetchResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), licensefetchdescriptor.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<INDLicenseFetchResult>>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn ReRegistrationAsync<'a, Param0: ::windows::core::IntoParam<'a, INDCustomData>>(&self, registrationcustomdata: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), registrationcustomdata.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "deprecated")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "deprecated")] pub fn CreateInstance<'a, Param0: ::windows::core::IntoParam<'a, INDDownloadEngine>, Param1: ::windows::core::IntoParam<'a, INDStreamParser>, Param2: ::windows::core::IntoParam<'a, INDMessenger>>(downloadengine: Param0, streamparser: Param1, pmessenger: Param2) -> ::windows::core::Result<NDClient> { Self::INDClientFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), downloadengine.into_param().abi(), streamparser.into_param().abi(), pmessenger.into_param().abi(), &mut result__).from_abi::<NDClient>(result__) }) } pub fn INDClientFactory<R, F: FnOnce(&INDClientFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<NDClient, INDClientFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for NDClient { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.NDClient;{3bd6781b-61b8-46e2-99a5-8abcb6b9f7d6})"); } unsafe impl ::windows::core::Interface for NDClient { type Vtable = INDClient_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3bd6781b_61b8_46e2_99a5_8abcb6b9f7d6); } impl ::windows::core::RuntimeName for NDClient { const NAME: &'static str = "Windows.Media.Protection.PlayReady.NDClient"; } impl ::core::convert::From<NDClient> for ::windows::core::IUnknown { fn from(value: NDClient) -> Self { value.0 .0 } } impl ::core::convert::From<&NDClient> for ::windows::core::IUnknown { fn from(value: &NDClient) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for NDClient { 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 NDClient { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<NDClient> for ::windows::core::IInspectable { fn from(value: NDClient) -> Self { value.0 } } impl ::core::convert::From<&NDClient> for ::windows::core::IInspectable { fn from(value: &NDClient) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for NDClient { 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 NDClient { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct NDClosedCaptionFormat(pub i32); impl NDClosedCaptionFormat { pub const ATSC: NDClosedCaptionFormat = NDClosedCaptionFormat(0i32); pub const SCTE20: NDClosedCaptionFormat = NDClosedCaptionFormat(1i32); pub const Unknown: NDClosedCaptionFormat = NDClosedCaptionFormat(2i32); } impl ::core::convert::From<i32> for NDClosedCaptionFormat { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for NDClosedCaptionFormat { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for NDClosedCaptionFormat { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.PlayReady.NDClosedCaptionFormat;i4)"); } impl ::windows::core::DefaultType for NDClosedCaptionFormat { 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 NDContentIDType(pub i32); impl NDContentIDType { pub const KeyID: NDContentIDType = NDContentIDType(1i32); pub const PlayReadyObject: NDContentIDType = NDContentIDType(2i32); pub const Custom: NDContentIDType = NDContentIDType(3i32); } impl ::core::convert::From<i32> for NDContentIDType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for NDContentIDType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for NDContentIDType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.PlayReady.NDContentIDType;i4)"); } impl ::windows::core::DefaultType for NDContentIDType { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct NDCustomData(pub ::windows::core::IInspectable); impl NDCustomData { #[cfg(feature = "deprecated")] pub fn CustomDataTypeID(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } #[cfg(feature = "deprecated")] pub fn CustomData(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } #[cfg(feature = "deprecated")] pub fn CreateInstance(customdatatypeidbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], customdatabytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<NDCustomData> { Self::INDCustomDataFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), customdatatypeidbytes.len() as u32, ::core::mem::transmute(customdatatypeidbytes.as_ptr()), customdatabytes.len() as u32, ::core::mem::transmute(customdatabytes.as_ptr()), &mut result__).from_abi::<NDCustomData>(result__) }) } pub fn INDCustomDataFactory<R, F: FnOnce(&INDCustomDataFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<NDCustomData, INDCustomDataFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for NDCustomData { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.NDCustomData;{f5cb0fdc-2d09-4f19-b5e1-76a0b3ee9267})"); } unsafe impl ::windows::core::Interface for NDCustomData { type Vtable = INDCustomData_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf5cb0fdc_2d09_4f19_b5e1_76a0b3ee9267); } impl ::windows::core::RuntimeName for NDCustomData { const NAME: &'static str = "Windows.Media.Protection.PlayReady.NDCustomData"; } impl ::core::convert::From<NDCustomData> for ::windows::core::IUnknown { fn from(value: NDCustomData) -> Self { value.0 .0 } } impl ::core::convert::From<&NDCustomData> for ::windows::core::IUnknown { fn from(value: &NDCustomData) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for NDCustomData { 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 NDCustomData { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<NDCustomData> for ::windows::core::IInspectable { fn from(value: NDCustomData) -> Self { value.0 } } impl ::core::convert::From<&NDCustomData> for ::windows::core::IInspectable { fn from(value: &NDCustomData) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for NDCustomData { 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 NDCustomData { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<NDCustomData> for INDCustomData { fn from(value: NDCustomData) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&NDCustomData> for INDCustomData { fn from(value: &NDCustomData) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, INDCustomData> for NDCustomData { fn into_param(self) -> ::windows::core::Param<'a, INDCustomData> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, INDCustomData> for &NDCustomData { fn into_param(self) -> ::windows::core::Param<'a, INDCustomData> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct NDDownloadEngineNotifier(pub ::windows::core::IInspectable); impl NDDownloadEngineNotifier { 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<NDDownloadEngineNotifier, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "deprecated")] pub fn OnStreamOpened(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "deprecated")] pub fn OnPlayReadyObjectReceived(&self, databytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), databytes.len() as u32, ::core::mem::transmute(databytes.as_ptr())).ok() } } #[cfg(feature = "deprecated")] pub fn OnContentIDReceived<'a, Param0: ::windows::core::IntoParam<'a, INDLicenseFetchDescriptor>>(&self, licensefetchdescriptor: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), licensefetchdescriptor.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] pub fn OnDataReceived(&self, databytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], bytesreceived: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), databytes.len() as u32, ::core::mem::transmute(databytes.as_ptr()), bytesreceived).ok() } } #[cfg(feature = "deprecated")] pub fn OnEndOfStream(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "deprecated")] pub fn OnNetworkError(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this)).ok() } } } unsafe impl ::windows::core::RuntimeType for NDDownloadEngineNotifier { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.NDDownloadEngineNotifier;{d720b4d4-f4b8-4530-a809-9193a571e7fc})"); } unsafe impl ::windows::core::Interface for NDDownloadEngineNotifier { type Vtable = INDDownloadEngineNotifier_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd720b4d4_f4b8_4530_a809_9193a571e7fc); } impl ::windows::core::RuntimeName for NDDownloadEngineNotifier { const NAME: &'static str = "Windows.Media.Protection.PlayReady.NDDownloadEngineNotifier"; } impl ::core::convert::From<NDDownloadEngineNotifier> for ::windows::core::IUnknown { fn from(value: NDDownloadEngineNotifier) -> Self { value.0 .0 } } impl ::core::convert::From<&NDDownloadEngineNotifier> for ::windows::core::IUnknown { fn from(value: &NDDownloadEngineNotifier) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for NDDownloadEngineNotifier { 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 NDDownloadEngineNotifier { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<NDDownloadEngineNotifier> for ::windows::core::IInspectable { fn from(value: NDDownloadEngineNotifier) -> Self { value.0 } } impl ::core::convert::From<&NDDownloadEngineNotifier> for ::windows::core::IInspectable { fn from(value: &NDDownloadEngineNotifier) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for NDDownloadEngineNotifier { 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 NDDownloadEngineNotifier { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<NDDownloadEngineNotifier> for INDDownloadEngineNotifier { fn from(value: NDDownloadEngineNotifier) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&NDDownloadEngineNotifier> for INDDownloadEngineNotifier { fn from(value: &NDDownloadEngineNotifier) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, INDDownloadEngineNotifier> for NDDownloadEngineNotifier { fn into_param(self) -> ::windows::core::Param<'a, INDDownloadEngineNotifier> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, INDDownloadEngineNotifier> for &NDDownloadEngineNotifier { fn into_param(self) -> ::windows::core::Param<'a, INDDownloadEngineNotifier> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct NDLicenseFetchDescriptor(pub ::windows::core::IInspectable); impl NDLicenseFetchDescriptor { #[cfg(feature = "deprecated")] pub fn ContentIDType(&self) -> ::windows::core::Result<NDContentIDType> { let this = self; unsafe { let mut result__: NDContentIDType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<NDContentIDType>(result__) } } #[cfg(feature = "deprecated")] pub fn ContentID(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } #[cfg(feature = "deprecated")] pub fn LicenseFetchChallengeCustomData(&self) -> ::windows::core::Result<INDCustomData> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<INDCustomData>(result__) } } #[cfg(feature = "deprecated")] pub fn SetLicenseFetchChallengeCustomData<'a, Param0: ::windows::core::IntoParam<'a, INDCustomData>>(&self, licensefetchchallengecustomdata: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), licensefetchchallengecustomdata.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] pub fn CreateInstance<'a, Param2: ::windows::core::IntoParam<'a, INDCustomData>>(contentidtype: NDContentIDType, contentidbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], licensefetchchallengecustomdata: Param2) -> ::windows::core::Result<NDLicenseFetchDescriptor> { Self::INDLicenseFetchDescriptorFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), contentidtype, contentidbytes.len() as u32, ::core::mem::transmute(contentidbytes.as_ptr()), licensefetchchallengecustomdata.into_param().abi(), &mut result__).from_abi::<NDLicenseFetchDescriptor>(result__) }) } pub fn INDLicenseFetchDescriptorFactory<R, F: FnOnce(&INDLicenseFetchDescriptorFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<NDLicenseFetchDescriptor, INDLicenseFetchDescriptorFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for NDLicenseFetchDescriptor { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.NDLicenseFetchDescriptor;{5498d33a-e686-4935-a567-7ca77ad20fa4})"); } unsafe impl ::windows::core::Interface for NDLicenseFetchDescriptor { type Vtable = INDLicenseFetchDescriptor_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5498d33a_e686_4935_a567_7ca77ad20fa4); } impl ::windows::core::RuntimeName for NDLicenseFetchDescriptor { const NAME: &'static str = "Windows.Media.Protection.PlayReady.NDLicenseFetchDescriptor"; } impl ::core::convert::From<NDLicenseFetchDescriptor> for ::windows::core::IUnknown { fn from(value: NDLicenseFetchDescriptor) -> Self { value.0 .0 } } impl ::core::convert::From<&NDLicenseFetchDescriptor> for ::windows::core::IUnknown { fn from(value: &NDLicenseFetchDescriptor) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for NDLicenseFetchDescriptor { 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 NDLicenseFetchDescriptor { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<NDLicenseFetchDescriptor> for ::windows::core::IInspectable { fn from(value: NDLicenseFetchDescriptor) -> Self { value.0 } } impl ::core::convert::From<&NDLicenseFetchDescriptor> for ::windows::core::IInspectable { fn from(value: &NDLicenseFetchDescriptor) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for NDLicenseFetchDescriptor { 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 NDLicenseFetchDescriptor { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<NDLicenseFetchDescriptor> for INDLicenseFetchDescriptor { fn from(value: NDLicenseFetchDescriptor) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&NDLicenseFetchDescriptor> for INDLicenseFetchDescriptor { fn from(value: &NDLicenseFetchDescriptor) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, INDLicenseFetchDescriptor> for NDLicenseFetchDescriptor { fn into_param(self) -> ::windows::core::Param<'a, INDLicenseFetchDescriptor> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, INDLicenseFetchDescriptor> for &NDLicenseFetchDescriptor { fn into_param(self) -> ::windows::core::Param<'a, INDLicenseFetchDescriptor> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct NDMediaStreamType(pub i32); impl NDMediaStreamType { pub const Audio: NDMediaStreamType = NDMediaStreamType(1i32); pub const Video: NDMediaStreamType = NDMediaStreamType(2i32); } impl ::core::convert::From<i32> for NDMediaStreamType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for NDMediaStreamType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for NDMediaStreamType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.PlayReady.NDMediaStreamType;i4)"); } impl ::windows::core::DefaultType for NDMediaStreamType { 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 NDProximityDetectionType(pub i32); impl NDProximityDetectionType { pub const UDP: NDProximityDetectionType = NDProximityDetectionType(1i32); pub const TCP: NDProximityDetectionType = NDProximityDetectionType(2i32); pub const TransportAgnostic: NDProximityDetectionType = NDProximityDetectionType(4i32); } impl ::core::convert::From<i32> for NDProximityDetectionType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for NDProximityDetectionType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for NDProximityDetectionType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.PlayReady.NDProximityDetectionType;i4)"); } impl ::windows::core::DefaultType for NDProximityDetectionType { 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 NDStartAsyncOptions(pub i32); impl NDStartAsyncOptions { pub const MutualAuthentication: NDStartAsyncOptions = NDStartAsyncOptions(1i32); pub const WaitForLicenseDescriptor: NDStartAsyncOptions = NDStartAsyncOptions(2i32); } impl ::core::convert::From<i32> for NDStartAsyncOptions { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for NDStartAsyncOptions { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for NDStartAsyncOptions { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.PlayReady.NDStartAsyncOptions;i4)"); } impl ::windows::core::DefaultType for NDStartAsyncOptions { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct NDStorageFileHelper(pub ::windows::core::IInspectable); impl NDStorageFileHelper { 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<NDStorageFileHelper, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "deprecated")] #[cfg(all(feature = "Foundation_Collections", feature = "Storage"))] pub fn GetFileURLs<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Storage::IStorageFile>>(&self, file: Param0) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), file.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<::windows::core::HSTRING>>(result__) } } } unsafe impl ::windows::core::RuntimeType for NDStorageFileHelper { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.NDStorageFileHelper;{d8f0bef8-91d2-4d47-a3f9-eaff4edb729f})"); } unsafe impl ::windows::core::Interface for NDStorageFileHelper { type Vtable = INDStorageFileHelper_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd8f0bef8_91d2_4d47_a3f9_eaff4edb729f); } impl ::windows::core::RuntimeName for NDStorageFileHelper { const NAME: &'static str = "Windows.Media.Protection.PlayReady.NDStorageFileHelper"; } impl ::core::convert::From<NDStorageFileHelper> for ::windows::core::IUnknown { fn from(value: NDStorageFileHelper) -> Self { value.0 .0 } } impl ::core::convert::From<&NDStorageFileHelper> for ::windows::core::IUnknown { fn from(value: &NDStorageFileHelper) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for NDStorageFileHelper { 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 NDStorageFileHelper { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<NDStorageFileHelper> for ::windows::core::IInspectable { fn from(value: NDStorageFileHelper) -> Self { value.0 } } impl ::core::convert::From<&NDStorageFileHelper> for ::windows::core::IInspectable { fn from(value: &NDStorageFileHelper) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for NDStorageFileHelper { 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 NDStorageFileHelper { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<NDStorageFileHelper> for INDStorageFileHelper { fn from(value: NDStorageFileHelper) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&NDStorageFileHelper> for INDStorageFileHelper { fn from(value: &NDStorageFileHelper) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, INDStorageFileHelper> for NDStorageFileHelper { fn into_param(self) -> ::windows::core::Param<'a, INDStorageFileHelper> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, INDStorageFileHelper> for &NDStorageFileHelper { fn into_param(self) -> ::windows::core::Param<'a, INDStorageFileHelper> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct NDStreamParserNotifier(pub ::windows::core::IInspectable); impl NDStreamParserNotifier { 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<NDStreamParserNotifier, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "deprecated")] pub fn OnContentIDReceived<'a, Param0: ::windows::core::IntoParam<'a, INDLicenseFetchDescriptor>>(&self, licensefetchdescriptor: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), licensefetchdescriptor.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] #[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))] pub fn OnMediaStreamDescriptorCreated<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IVector<super::super::Core::AudioStreamDescriptor>>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IVector<super::super::Core::VideoStreamDescriptor>>>(&self, audiostreamdescriptors: Param0, videostreamdescriptors: Param1) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), audiostreamdescriptors.into_param().abi(), videostreamdescriptors.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] #[cfg(feature = "Media_Core")] pub fn OnSampleParsed<'a, Param2: ::windows::core::IntoParam<'a, super::super::Core::MediaStreamSample>>(&self, streamid: u32, streamtype: NDMediaStreamType, streamsample: Param2, pts: i64, ccformat: NDClosedCaptionFormat, ccdatabytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), streamid, streamtype, streamsample.into_param().abi(), pts, ccformat, ccdatabytes.len() as u32, ::core::mem::transmute(ccdatabytes.as_ptr())).ok() } } #[cfg(feature = "deprecated")] #[cfg(feature = "Media_Core")] pub fn OnBeginSetupDecryptor<'a, Param0: ::windows::core::IntoParam<'a, super::super::Core::IMediaStreamDescriptor>, Param1: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, descriptor: Param0, keyid: Param1, probytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), descriptor.into_param().abi(), keyid.into_param().abi(), probytes.len() as u32, ::core::mem::transmute(probytes.as_ptr())).ok() } } } unsafe impl ::windows::core::RuntimeType for NDStreamParserNotifier { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.NDStreamParserNotifier;{c167acd0-2ce6-426c-ace5-5e9275fea715})"); } unsafe impl ::windows::core::Interface for NDStreamParserNotifier { type Vtable = INDStreamParserNotifier_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc167acd0_2ce6_426c_ace5_5e9275fea715); } impl ::windows::core::RuntimeName for NDStreamParserNotifier { const NAME: &'static str = "Windows.Media.Protection.PlayReady.NDStreamParserNotifier"; } impl ::core::convert::From<NDStreamParserNotifier> for ::windows::core::IUnknown { fn from(value: NDStreamParserNotifier) -> Self { value.0 .0 } } impl ::core::convert::From<&NDStreamParserNotifier> for ::windows::core::IUnknown { fn from(value: &NDStreamParserNotifier) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for NDStreamParserNotifier { 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 NDStreamParserNotifier { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<NDStreamParserNotifier> for ::windows::core::IInspectable { fn from(value: NDStreamParserNotifier) -> Self { value.0 } } impl ::core::convert::From<&NDStreamParserNotifier> for ::windows::core::IInspectable { fn from(value: &NDStreamParserNotifier) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for NDStreamParserNotifier { 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 NDStreamParserNotifier { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<NDStreamParserNotifier> for INDStreamParserNotifier { fn from(value: NDStreamParserNotifier) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&NDStreamParserNotifier> for INDStreamParserNotifier { fn from(value: &NDStreamParserNotifier) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, INDStreamParserNotifier> for NDStreamParserNotifier { fn into_param(self) -> ::windows::core::Param<'a, INDStreamParserNotifier> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, INDStreamParserNotifier> for &NDStreamParserNotifier { fn into_param(self) -> ::windows::core::Param<'a, INDStreamParserNotifier> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct NDTCPMessenger(pub ::windows::core::IInspectable); impl NDTCPMessenger { #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn SendRegistrationRequestAsync(&self, sessionidbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], challengedatabytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<INDSendResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), sessionidbytes.len() as u32, ::core::mem::transmute(sessionidbytes.as_ptr()), challengedatabytes.len() as u32, ::core::mem::transmute(challengedatabytes.as_ptr()), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<INDSendResult>>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn SendProximityDetectionStartAsync(&self, pdtype: NDProximityDetectionType, transmitterchannelbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], sessionidbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], challengedatabytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<INDSendResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)( ::core::mem::transmute_copy(this), pdtype, transmitterchannelbytes.len() as u32, ::core::mem::transmute(transmitterchannelbytes.as_ptr()), sessionidbytes.len() as u32, ::core::mem::transmute(sessionidbytes.as_ptr()), challengedatabytes.len() as u32, ::core::mem::transmute(challengedatabytes.as_ptr()), &mut result__, ) .from_abi::<super::super::super::Foundation::IAsyncOperation<INDSendResult>>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn SendProximityDetectionResponseAsync(&self, pdtype: NDProximityDetectionType, transmitterchannelbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], sessionidbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], responsedatabytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<INDSendResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)( ::core::mem::transmute_copy(this), pdtype, transmitterchannelbytes.len() as u32, ::core::mem::transmute(transmitterchannelbytes.as_ptr()), sessionidbytes.len() as u32, ::core::mem::transmute(sessionidbytes.as_ptr()), responsedatabytes.len() as u32, ::core::mem::transmute(responsedatabytes.as_ptr()), &mut result__, ) .from_abi::<super::super::super::Foundation::IAsyncOperation<INDSendResult>>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn SendLicenseFetchRequestAsync(&self, sessionidbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], challengedatabytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<INDSendResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), sessionidbytes.len() as u32, ::core::mem::transmute(sessionidbytes.as_ptr()), challengedatabytes.len() as u32, ::core::mem::transmute(challengedatabytes.as_ptr()), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<INDSendResult>>(result__) } } #[cfg(feature = "deprecated")] pub fn CreateInstance<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(remotehostname: Param0, remotehostport: u32) -> ::windows::core::Result<NDTCPMessenger> { Self::INDTCPMessengerFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), remotehostname.into_param().abi(), remotehostport, &mut result__).from_abi::<NDTCPMessenger>(result__) }) } pub fn INDTCPMessengerFactory<R, F: FnOnce(&INDTCPMessengerFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<NDTCPMessenger, INDTCPMessengerFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for NDTCPMessenger { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.NDTCPMessenger;{d42df95d-a75b-47bf-8249-bc83820da38a})"); } unsafe impl ::windows::core::Interface for NDTCPMessenger { type Vtable = INDMessenger_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd42df95d_a75b_47bf_8249_bc83820da38a); } impl ::windows::core::RuntimeName for NDTCPMessenger { const NAME: &'static str = "Windows.Media.Protection.PlayReady.NDTCPMessenger"; } impl ::core::convert::From<NDTCPMessenger> for ::windows::core::IUnknown { fn from(value: NDTCPMessenger) -> Self { value.0 .0 } } impl ::core::convert::From<&NDTCPMessenger> for ::windows::core::IUnknown { fn from(value: &NDTCPMessenger) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for NDTCPMessenger { 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 NDTCPMessenger { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<NDTCPMessenger> for ::windows::core::IInspectable { fn from(value: NDTCPMessenger) -> Self { value.0 } } impl ::core::convert::From<&NDTCPMessenger> for ::windows::core::IInspectable { fn from(value: &NDTCPMessenger) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for NDTCPMessenger { 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 NDTCPMessenger { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<NDTCPMessenger> for INDMessenger { fn from(value: NDTCPMessenger) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&NDTCPMessenger> for INDMessenger { fn from(value: &NDTCPMessenger) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, INDMessenger> for NDTCPMessenger { fn into_param(self) -> ::windows::core::Param<'a, INDMessenger> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, INDMessenger> for &NDTCPMessenger { fn into_param(self) -> ::windows::core::Param<'a, INDMessenger> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyContentHeader(pub ::windows::core::IInspectable); impl PlayReadyContentHeader { pub fn KeyId(&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 KeyIdString(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn LicenseAcquisitionUrl(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } #[cfg(feature = "Foundation")] pub fn LicenseAcquisitionUserInterfaceUrl(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } pub fn DomainServiceId(&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).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn EncryptionType(&self) -> ::windows::core::Result<PlayReadyEncryptionAlgorithm> { let this = self; unsafe { let mut result__: PlayReadyEncryptionAlgorithm = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlayReadyEncryptionAlgorithm>(result__) } } pub fn CustomAttributes(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn DecryptorSetup(&self) -> ::windows::core::Result<PlayReadyDecryptorSetup> { let this = self; unsafe { let mut result__: PlayReadyDecryptorSetup = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlayReadyDecryptorSetup>(result__) } } pub fn GetSerializedHeader(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } pub fn HeaderWithEmbeddedUpdates(&self) -> ::windows::core::Result<PlayReadyContentHeader> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlayReadyContentHeader>(result__) } } pub fn KeyIds(&self) -> ::windows::core::Result<::windows::core::Array<::windows::core::GUID>> { let this = &::windows::core::Interface::cast::<IPlayReadyContentHeader2>(self)?; unsafe { let mut result__: ::windows::core::Array<::windows::core::GUID> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), ::windows::core::Array::<::windows::core::GUID>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } pub fn KeyIdStrings(&self) -> ::windows::core::Result<::windows::core::Array<::windows::core::HSTRING>> { let this = &::windows::core::Interface::cast::<IPlayReadyContentHeader2>(self)?; unsafe { let mut result__: ::windows::core::Array<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), ::windows::core::Array::<::windows::core::HSTRING>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } #[cfg(feature = "Foundation")] pub fn CreateInstanceFromWindowsMediaDrmHeader<'a, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param4: ::windows::core::IntoParam<'a, ::windows::core::GUID>>( headerbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType], licenseacquisitionurl: Param1, licenseacquisitionuserinterfaceurl: Param2, customattributes: Param3, domainserviceid: Param4, ) -> ::windows::core::Result<PlayReadyContentHeader> { Self::IPlayReadyContentHeaderFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), headerbytes.len() as u32, ::core::mem::transmute(headerbytes.as_ptr()), licenseacquisitionurl.into_param().abi(), licenseacquisitionuserinterfaceurl.into_param().abi(), customattributes.into_param().abi(), domainserviceid.into_param().abi(), &mut result__).from_abi::<PlayReadyContentHeader>(result__) }) } #[cfg(feature = "Foundation")] pub fn CreateInstanceFromComponents<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>, Param4: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>, Param5: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param6: ::windows::core::IntoParam<'a, ::windows::core::GUID>>( contentkeyid: Param0, contentkeyidstring: Param1, contentencryptionalgorithm: PlayReadyEncryptionAlgorithm, licenseacquisitionurl: Param3, licenseacquisitionuserinterfaceurl: Param4, customattributes: Param5, domainserviceid: Param6, ) -> ::windows::core::Result<PlayReadyContentHeader> { Self::IPlayReadyContentHeaderFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)( ::core::mem::transmute_copy(this), contentkeyid.into_param().abi(), contentkeyidstring.into_param().abi(), contentencryptionalgorithm, licenseacquisitionurl.into_param().abi(), licenseacquisitionuserinterfaceurl.into_param().abi(), customattributes.into_param().abi(), domainserviceid.into_param().abi(), &mut result__, ) .from_abi::<PlayReadyContentHeader>(result__) }) } pub fn CreateInstanceFromPlayReadyHeader(headerbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<PlayReadyContentHeader> { Self::IPlayReadyContentHeaderFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), headerbytes.len() as u32, ::core::mem::transmute(headerbytes.as_ptr()), &mut result__).from_abi::<PlayReadyContentHeader>(result__) }) } #[cfg(feature = "Foundation")] pub fn CreateInstanceFromComponents2<'a, Param4: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>, Param5: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>, Param6: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param7: ::windows::core::IntoParam<'a, ::windows::core::GUID>>( dwflags: u32, contentkeyids: &[<::windows::core::GUID as ::windows::core::DefaultType>::DefaultType], contentkeyidstrings: &[<::windows::core::HSTRING as ::windows::core::DefaultType>::DefaultType], contentencryptionalgorithm: PlayReadyEncryptionAlgorithm, licenseacquisitionurl: Param4, licenseacquisitionuserinterfaceurl: Param5, customattributes: Param6, domainserviceid: Param7, ) -> ::windows::core::Result<PlayReadyContentHeader> { Self::IPlayReadyContentHeaderFactory2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)( ::core::mem::transmute_copy(this), dwflags, contentkeyids.len() as u32, ::core::mem::transmute(contentkeyids.as_ptr()), contentkeyidstrings.len() as u32, ::core::mem::transmute(contentkeyidstrings.as_ptr()), contentencryptionalgorithm, licenseacquisitionurl.into_param().abi(), licenseacquisitionuserinterfaceurl.into_param().abi(), customattributes.into_param().abi(), domainserviceid.into_param().abi(), &mut result__, ) .from_abi::<PlayReadyContentHeader>(result__) }) } pub fn IPlayReadyContentHeaderFactory<R, F: FnOnce(&IPlayReadyContentHeaderFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadyContentHeader, IPlayReadyContentHeaderFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IPlayReadyContentHeaderFactory2<R, F: FnOnce(&IPlayReadyContentHeaderFactory2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadyContentHeader, IPlayReadyContentHeaderFactory2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PlayReadyContentHeader { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyContentHeader;{9a438a6a-7f4c-452e-88bd-0148c6387a2c})"); } unsafe impl ::windows::core::Interface for PlayReadyContentHeader { type Vtable = IPlayReadyContentHeader_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9a438a6a_7f4c_452e_88bd_0148c6387a2c); } impl ::windows::core::RuntimeName for PlayReadyContentHeader { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyContentHeader"; } impl ::core::convert::From<PlayReadyContentHeader> for ::windows::core::IUnknown { fn from(value: PlayReadyContentHeader) -> Self { value.0 .0 } } impl ::core::convert::From<&PlayReadyContentHeader> for ::windows::core::IUnknown { fn from(value: &PlayReadyContentHeader) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyContentHeader { 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 PlayReadyContentHeader { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlayReadyContentHeader> for ::windows::core::IInspectable { fn from(value: PlayReadyContentHeader) -> Self { value.0 } } impl ::core::convert::From<&PlayReadyContentHeader> for ::windows::core::IInspectable { fn from(value: &PlayReadyContentHeader) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyContentHeader { 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 PlayReadyContentHeader { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } pub struct PlayReadyContentResolver {} impl PlayReadyContentResolver { pub fn ServiceRequest<'a, Param0: ::windows::core::IntoParam<'a, PlayReadyContentHeader>>(contentheader: Param0) -> ::windows::core::Result<IPlayReadyServiceRequest> { Self::IPlayReadyContentResolver(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), contentheader.into_param().abi(), &mut result__).from_abi::<IPlayReadyServiceRequest>(result__) }) } pub fn IPlayReadyContentResolver<R, F: FnOnce(&IPlayReadyContentResolver) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadyContentResolver, IPlayReadyContentResolver> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for PlayReadyContentResolver { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyContentResolver"; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PlayReadyDecryptorSetup(pub i32); impl PlayReadyDecryptorSetup { pub const Uninitialized: PlayReadyDecryptorSetup = PlayReadyDecryptorSetup(0i32); pub const OnDemand: PlayReadyDecryptorSetup = PlayReadyDecryptorSetup(1i32); } impl ::core::convert::From<i32> for PlayReadyDecryptorSetup { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PlayReadyDecryptorSetup { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PlayReadyDecryptorSetup { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.PlayReady.PlayReadyDecryptorSetup;i4)"); } impl ::windows::core::DefaultType for PlayReadyDecryptorSetup { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyDomain(pub ::windows::core::IInspectable); impl PlayReadyDomain { pub fn AccountId(&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 ServiceId(&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__) } } pub fn Revision(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn FriendlyName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn DomainJoinUrl(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } } unsafe impl ::windows::core::RuntimeType for PlayReadyDomain { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyDomain;{adcc93ac-97e6-43ef-95e4-d7868f3b16a9})"); } unsafe impl ::windows::core::Interface for PlayReadyDomain { type Vtable = IPlayReadyDomain_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xadcc93ac_97e6_43ef_95e4_d7868f3b16a9); } impl ::windows::core::RuntimeName for PlayReadyDomain { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyDomain"; } impl ::core::convert::From<PlayReadyDomain> for ::windows::core::IUnknown { fn from(value: PlayReadyDomain) -> Self { value.0 .0 } } impl ::core::convert::From<&PlayReadyDomain> for ::windows::core::IUnknown { fn from(value: &PlayReadyDomain) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyDomain { 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 PlayReadyDomain { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlayReadyDomain> for ::windows::core::IInspectable { fn from(value: PlayReadyDomain) -> Self { value.0 } } impl ::core::convert::From<&PlayReadyDomain> for ::windows::core::IInspectable { fn from(value: &PlayReadyDomain) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyDomain { 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 PlayReadyDomain { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<PlayReadyDomain> for IPlayReadyDomain { fn from(value: PlayReadyDomain) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&PlayReadyDomain> for IPlayReadyDomain { fn from(value: &PlayReadyDomain) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyDomain> for PlayReadyDomain { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyDomain> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyDomain> for &PlayReadyDomain { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyDomain> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Foundation_Collections")] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyDomainIterable(pub ::windows::core::IInspectable); #[cfg(feature = "Foundation_Collections")] impl PlayReadyDomainIterable { #[cfg(feature = "Foundation_Collections")] pub fn First(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IIterator<IPlayReadyDomain>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IIterator<IPlayReadyDomain>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn CreateInstance<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(domainaccountid: Param0) -> ::windows::core::Result<PlayReadyDomainIterable> { Self::IPlayReadyDomainIterableFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), domainaccountid.into_param().abi(), &mut result__).from_abi::<PlayReadyDomainIterable>(result__) }) } pub fn IPlayReadyDomainIterableFactory<R, F: FnOnce(&IPlayReadyDomainIterableFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadyDomainIterable, IPlayReadyDomainIterableFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } #[cfg(feature = "Foundation_Collections")] unsafe impl ::windows::core::RuntimeType for PlayReadyDomainIterable { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyDomainIterable;pinterface({faa585ea-6214-4217-afda-7f46de5869b3};{adcc93ac-97e6-43ef-95e4-d7868f3b16a9}))"); } #[cfg(feature = "Foundation_Collections")] unsafe impl ::windows::core::Interface for PlayReadyDomainIterable { type Vtable = super::super::super::Foundation::Collections::IIterable_abi<IPlayReadyDomain>; const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<super::super::super::Foundation::Collections::IIterable<IPlayReadyDomain> as ::windows::core::RuntimeType>::SIGNATURE); } #[cfg(feature = "Foundation_Collections")] impl ::windows::core::RuntimeName for PlayReadyDomainIterable { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyDomainIterable"; } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadyDomainIterable> for ::windows::core::IUnknown { fn from(value: PlayReadyDomainIterable) -> Self { value.0 .0 } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadyDomainIterable> for ::windows::core::IUnknown { fn from(value: &PlayReadyDomainIterable) -> Self { value.0 .0.clone() } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyDomainIterable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PlayReadyDomainIterable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadyDomainIterable> for ::windows::core::IInspectable { fn from(value: PlayReadyDomainIterable) -> Self { value.0 } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadyDomainIterable> for ::windows::core::IInspectable { fn from(value: &PlayReadyDomainIterable) -> Self { value.0.clone() } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyDomainIterable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PlayReadyDomainIterable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadyDomainIterable> for super::super::super::Foundation::Collections::IIterable<IPlayReadyDomain> { fn from(value: PlayReadyDomainIterable) -> Self { unsafe { ::core::mem::transmute(value) } } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadyDomainIterable> for super::super::super::Foundation::Collections::IIterable<IPlayReadyDomain> { fn from(value: &PlayReadyDomainIterable) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterable<IPlayReadyDomain>> for PlayReadyDomainIterable { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::Collections::IIterable<IPlayReadyDomain>> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterable<IPlayReadyDomain>> for &PlayReadyDomainIterable { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::Collections::IIterable<IPlayReadyDomain>> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[cfg(all(feature = "Foundation_Collections"))] impl ::core::iter::IntoIterator for PlayReadyDomainIterable { type Item = IPlayReadyDomain; type IntoIter = super::super::super::Foundation::Collections::IIterator<Self::Item>; fn into_iter(self) -> Self::IntoIter { ::core::iter::IntoIterator::into_iter(&self) } } #[cfg(all(feature = "Foundation_Collections"))] impl ::core::iter::IntoIterator for &PlayReadyDomainIterable { type Item = IPlayReadyDomain; type IntoIter = super::super::super::Foundation::Collections::IIterator<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.First().unwrap() } } #[cfg(feature = "Foundation_Collections")] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyDomainIterator(pub ::windows::core::IInspectable); #[cfg(feature = "Foundation_Collections")] impl PlayReadyDomainIterator { #[cfg(feature = "Foundation_Collections")] pub fn Current(&self) -> ::windows::core::Result<IPlayReadyDomain> { 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::<IPlayReadyDomain>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn HasCurrent(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn MoveNext(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn GetMany(&self, items: &mut [<IPlayReadyDomain as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), items.len() as u32, ::core::mem::transmute_copy(&items), &mut result__).from_abi::<u32>(result__) } } } #[cfg(feature = "Foundation_Collections")] unsafe impl ::windows::core::RuntimeType for PlayReadyDomainIterator { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyDomainIterator;pinterface({6a79e863-4300-459a-9966-cbb660963ee1};{adcc93ac-97e6-43ef-95e4-d7868f3b16a9}))"); } #[cfg(feature = "Foundation_Collections")] unsafe impl ::windows::core::Interface for PlayReadyDomainIterator { type Vtable = super::super::super::Foundation::Collections::IIterator_abi<IPlayReadyDomain>; const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<super::super::super::Foundation::Collections::IIterator<IPlayReadyDomain> as ::windows::core::RuntimeType>::SIGNATURE); } #[cfg(feature = "Foundation_Collections")] impl ::windows::core::RuntimeName for PlayReadyDomainIterator { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyDomainIterator"; } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadyDomainIterator> for ::windows::core::IUnknown { fn from(value: PlayReadyDomainIterator) -> Self { value.0 .0 } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadyDomainIterator> for ::windows::core::IUnknown { fn from(value: &PlayReadyDomainIterator) -> Self { value.0 .0.clone() } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyDomainIterator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PlayReadyDomainIterator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadyDomainIterator> for ::windows::core::IInspectable { fn from(value: PlayReadyDomainIterator) -> Self { value.0 } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadyDomainIterator> for ::windows::core::IInspectable { fn from(value: &PlayReadyDomainIterator) -> Self { value.0.clone() } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyDomainIterator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PlayReadyDomainIterator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadyDomainIterator> for super::super::super::Foundation::Collections::IIterator<IPlayReadyDomain> { fn from(value: PlayReadyDomainIterator) -> Self { unsafe { ::core::mem::transmute(value) } } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadyDomainIterator> for super::super::super::Foundation::Collections::IIterator<IPlayReadyDomain> { fn from(value: &PlayReadyDomainIterator) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterator<IPlayReadyDomain>> for PlayReadyDomainIterator { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::Collections::IIterator<IPlayReadyDomain>> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterator<IPlayReadyDomain>> for &PlayReadyDomainIterator { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::Collections::IIterator<IPlayReadyDomain>> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyDomainJoinServiceRequest(pub ::windows::core::IInspectable); impl PlayReadyDomainJoinServiceRequest { 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<PlayReadyDomainJoinServiceRequest, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn DomainAccountId(&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 SetDomainAccountId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn DomainFriendlyName(&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 SetDomainFriendlyName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn DomainServiceId(&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).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn SetDomainServiceId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ProtectionSystem(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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 = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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__) } } #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } #[cfg(feature = "Foundation")] pub fn SetUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ResponseCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 ChallengeCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 SetChallengeCustomData<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn BeginServiceRequest(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } pub fn NextServiceRequest(&self) -> ::windows::core::Result<IPlayReadyServiceRequest> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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::<IPlayReadyServiceRequest>(result__) } } pub fn GenerateManualEnablingChallenge(&self) -> ::windows::core::Result<PlayReadySoapMessage> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlayReadySoapMessage>(result__) } } pub fn ProcessManualEnablingResponse(&self, responsebytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<::windows::core::HRESULT> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), responsebytes.len() as u32, ::core::mem::transmute(responsebytes.as_ptr()), &mut result__).from_abi::<::windows::core::HRESULT>(result__) } } } unsafe impl ::windows::core::RuntimeType for PlayReadyDomainJoinServiceRequest { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyDomainJoinServiceRequest;{171b4a5a-405f-4739-b040-67b9f0c38758})"); } unsafe impl ::windows::core::Interface for PlayReadyDomainJoinServiceRequest { type Vtable = IPlayReadyDomainJoinServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x171b4a5a_405f_4739_b040_67b9f0c38758); } impl ::windows::core::RuntimeName for PlayReadyDomainJoinServiceRequest { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyDomainJoinServiceRequest"; } impl ::core::convert::From<PlayReadyDomainJoinServiceRequest> for ::windows::core::IUnknown { fn from(value: PlayReadyDomainJoinServiceRequest) -> Self { value.0 .0 } } impl ::core::convert::From<&PlayReadyDomainJoinServiceRequest> for ::windows::core::IUnknown { fn from(value: &PlayReadyDomainJoinServiceRequest) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyDomainJoinServiceRequest { 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 PlayReadyDomainJoinServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlayReadyDomainJoinServiceRequest> for ::windows::core::IInspectable { fn from(value: PlayReadyDomainJoinServiceRequest) -> Self { value.0 } } impl ::core::convert::From<&PlayReadyDomainJoinServiceRequest> for ::windows::core::IInspectable { fn from(value: &PlayReadyDomainJoinServiceRequest) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyDomainJoinServiceRequest { 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 PlayReadyDomainJoinServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<PlayReadyDomainJoinServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadyDomainJoinServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadyDomainJoinServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadyDomainJoinServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for PlayReadyDomainJoinServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for &PlayReadyDomainJoinServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::core::convert::TryInto::<super::IMediaProtectionServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } impl ::core::convert::TryFrom<PlayReadyDomainJoinServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadyDomainJoinServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadyDomainJoinServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadyDomainJoinServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for PlayReadyDomainJoinServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for &PlayReadyDomainJoinServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::core::convert::TryInto::<IPlayReadyServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyDomainLeaveServiceRequest(pub ::windows::core::IInspectable); impl PlayReadyDomainLeaveServiceRequest { 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<PlayReadyDomainLeaveServiceRequest, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn DomainAccountId(&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 SetDomainAccountId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn DomainServiceId(&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).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn SetDomainServiceId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ProtectionSystem(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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 = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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__) } } #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } #[cfg(feature = "Foundation")] pub fn SetUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ResponseCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 ChallengeCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 SetChallengeCustomData<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn BeginServiceRequest(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } pub fn NextServiceRequest(&self) -> ::windows::core::Result<IPlayReadyServiceRequest> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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::<IPlayReadyServiceRequest>(result__) } } pub fn GenerateManualEnablingChallenge(&self) -> ::windows::core::Result<PlayReadySoapMessage> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlayReadySoapMessage>(result__) } } pub fn ProcessManualEnablingResponse(&self, responsebytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<::windows::core::HRESULT> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), responsebytes.len() as u32, ::core::mem::transmute(responsebytes.as_ptr()), &mut result__).from_abi::<::windows::core::HRESULT>(result__) } } } unsafe impl ::windows::core::RuntimeType for PlayReadyDomainLeaveServiceRequest { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyDomainLeaveServiceRequest;{062d58be-97ad-4917-aa03-46d4c252d464})"); } unsafe impl ::windows::core::Interface for PlayReadyDomainLeaveServiceRequest { type Vtable = IPlayReadyDomainLeaveServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x062d58be_97ad_4917_aa03_46d4c252d464); } impl ::windows::core::RuntimeName for PlayReadyDomainLeaveServiceRequest { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyDomainLeaveServiceRequest"; } impl ::core::convert::From<PlayReadyDomainLeaveServiceRequest> for ::windows::core::IUnknown { fn from(value: PlayReadyDomainLeaveServiceRequest) -> Self { value.0 .0 } } impl ::core::convert::From<&PlayReadyDomainLeaveServiceRequest> for ::windows::core::IUnknown { fn from(value: &PlayReadyDomainLeaveServiceRequest) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyDomainLeaveServiceRequest { 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 PlayReadyDomainLeaveServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlayReadyDomainLeaveServiceRequest> for ::windows::core::IInspectable { fn from(value: PlayReadyDomainLeaveServiceRequest) -> Self { value.0 } } impl ::core::convert::From<&PlayReadyDomainLeaveServiceRequest> for ::windows::core::IInspectable { fn from(value: &PlayReadyDomainLeaveServiceRequest) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyDomainLeaveServiceRequest { 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 PlayReadyDomainLeaveServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<PlayReadyDomainLeaveServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadyDomainLeaveServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadyDomainLeaveServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadyDomainLeaveServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for PlayReadyDomainLeaveServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for &PlayReadyDomainLeaveServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::core::convert::TryInto::<super::IMediaProtectionServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } impl ::core::convert::TryFrom<PlayReadyDomainLeaveServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadyDomainLeaveServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadyDomainLeaveServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadyDomainLeaveServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for PlayReadyDomainLeaveServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for &PlayReadyDomainLeaveServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::core::convert::TryInto::<IPlayReadyServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PlayReadyEncryptionAlgorithm(pub i32); impl PlayReadyEncryptionAlgorithm { pub const Unprotected: PlayReadyEncryptionAlgorithm = PlayReadyEncryptionAlgorithm(0i32); pub const Aes128Ctr: PlayReadyEncryptionAlgorithm = PlayReadyEncryptionAlgorithm(1i32); pub const Cocktail: PlayReadyEncryptionAlgorithm = PlayReadyEncryptionAlgorithm(4i32); pub const Aes128Cbc: PlayReadyEncryptionAlgorithm = PlayReadyEncryptionAlgorithm(5i32); pub const Unspecified: PlayReadyEncryptionAlgorithm = PlayReadyEncryptionAlgorithm(65535i32); pub const Uninitialized: PlayReadyEncryptionAlgorithm = PlayReadyEncryptionAlgorithm(2147483647i32); } impl ::core::convert::From<i32> for PlayReadyEncryptionAlgorithm { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PlayReadyEncryptionAlgorithm { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PlayReadyEncryptionAlgorithm { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.PlayReady.PlayReadyEncryptionAlgorithm;i4)"); } impl ::windows::core::DefaultType for PlayReadyEncryptionAlgorithm { 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 PlayReadyHardwareDRMFeatures(pub i32); impl PlayReadyHardwareDRMFeatures { pub const HardwareDRM: PlayReadyHardwareDRMFeatures = PlayReadyHardwareDRMFeatures(1i32); pub const HEVC: PlayReadyHardwareDRMFeatures = PlayReadyHardwareDRMFeatures(2i32); pub const Aes128Cbc: PlayReadyHardwareDRMFeatures = PlayReadyHardwareDRMFeatures(3i32); } impl ::core::convert::From<i32> for PlayReadyHardwareDRMFeatures { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PlayReadyHardwareDRMFeatures { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PlayReadyHardwareDRMFeatures { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.PlayReady.PlayReadyHardwareDRMFeatures;i4)"); } impl ::windows::core::DefaultType for PlayReadyHardwareDRMFeatures { 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 PlayReadyITADataFormat(pub i32); impl PlayReadyITADataFormat { pub const SerializedProperties: PlayReadyITADataFormat = PlayReadyITADataFormat(0i32); pub const SerializedProperties_WithContentProtectionWrapper: PlayReadyITADataFormat = PlayReadyITADataFormat(1i32); } impl ::core::convert::From<i32> for PlayReadyITADataFormat { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PlayReadyITADataFormat { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PlayReadyITADataFormat { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.Protection.PlayReady.PlayReadyITADataFormat;i4)"); } impl ::windows::core::DefaultType for PlayReadyITADataFormat { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyITADataGenerator(pub ::windows::core::IInspectable); impl PlayReadyITADataGenerator { 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<PlayReadyITADataGenerator, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation_Collections")] pub fn GenerateData<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IPropertySet>>(&self, guidcpsystemid: Param0, countofstreams: u32, configuration: Param2, format: PlayReadyITADataFormat) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), guidcpsystemid.into_param().abi(), countofstreams, configuration.into_param().abi(), format, ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } } unsafe impl ::windows::core::RuntimeType for PlayReadyITADataGenerator { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyITADataGenerator;{24446b8e-10b9-4530-b25b-901a8029a9b2})"); } unsafe impl ::windows::core::Interface for PlayReadyITADataGenerator { type Vtable = IPlayReadyITADataGenerator_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x24446b8e_10b9_4530_b25b_901a8029a9b2); } impl ::windows::core::RuntimeName for PlayReadyITADataGenerator { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyITADataGenerator"; } impl ::core::convert::From<PlayReadyITADataGenerator> for ::windows::core::IUnknown { fn from(value: PlayReadyITADataGenerator) -> Self { value.0 .0 } } impl ::core::convert::From<&PlayReadyITADataGenerator> for ::windows::core::IUnknown { fn from(value: &PlayReadyITADataGenerator) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyITADataGenerator { 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 PlayReadyITADataGenerator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlayReadyITADataGenerator> for ::windows::core::IInspectable { fn from(value: PlayReadyITADataGenerator) -> Self { value.0 } } impl ::core::convert::From<&PlayReadyITADataGenerator> for ::windows::core::IInspectable { fn from(value: &PlayReadyITADataGenerator) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyITADataGenerator { 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 PlayReadyITADataGenerator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyIndividualizationServiceRequest(pub ::windows::core::IInspectable); impl PlayReadyIndividualizationServiceRequest { 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<PlayReadyIndividualizationServiceRequest, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn ProtectionSystem(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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 = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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__) } } #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } #[cfg(feature = "Foundation")] pub fn SetUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ResponseCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 ChallengeCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 SetChallengeCustomData<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn BeginServiceRequest(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } pub fn NextServiceRequest(&self) -> ::windows::core::Result<IPlayReadyServiceRequest> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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::<IPlayReadyServiceRequest>(result__) } } pub fn GenerateManualEnablingChallenge(&self) -> ::windows::core::Result<PlayReadySoapMessage> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlayReadySoapMessage>(result__) } } pub fn ProcessManualEnablingResponse(&self, responsebytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<::windows::core::HRESULT> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), responsebytes.len() as u32, ::core::mem::transmute(responsebytes.as_ptr()), &mut result__).from_abi::<::windows::core::HRESULT>(result__) } } } unsafe impl ::windows::core::RuntimeType for PlayReadyIndividualizationServiceRequest { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyIndividualizationServiceRequest;{21f5a86b-008c-4611-ab2f-aaa6c69f0e24})"); } unsafe impl ::windows::core::Interface for PlayReadyIndividualizationServiceRequest { type Vtable = IPlayReadyIndividualizationServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x21f5a86b_008c_4611_ab2f_aaa6c69f0e24); } impl ::windows::core::RuntimeName for PlayReadyIndividualizationServiceRequest { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyIndividualizationServiceRequest"; } impl ::core::convert::From<PlayReadyIndividualizationServiceRequest> for ::windows::core::IUnknown { fn from(value: PlayReadyIndividualizationServiceRequest) -> Self { value.0 .0 } } impl ::core::convert::From<&PlayReadyIndividualizationServiceRequest> for ::windows::core::IUnknown { fn from(value: &PlayReadyIndividualizationServiceRequest) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyIndividualizationServiceRequest { 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 PlayReadyIndividualizationServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlayReadyIndividualizationServiceRequest> for ::windows::core::IInspectable { fn from(value: PlayReadyIndividualizationServiceRequest) -> Self { value.0 } } impl ::core::convert::From<&PlayReadyIndividualizationServiceRequest> for ::windows::core::IInspectable { fn from(value: &PlayReadyIndividualizationServiceRequest) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyIndividualizationServiceRequest { 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 PlayReadyIndividualizationServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<PlayReadyIndividualizationServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadyIndividualizationServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadyIndividualizationServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadyIndividualizationServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for PlayReadyIndividualizationServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for &PlayReadyIndividualizationServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::core::convert::TryInto::<super::IMediaProtectionServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } impl ::core::convert::TryFrom<PlayReadyIndividualizationServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadyIndividualizationServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadyIndividualizationServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadyIndividualizationServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for PlayReadyIndividualizationServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for &PlayReadyIndividualizationServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::core::convert::TryInto::<IPlayReadyServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyLicense(pub ::windows::core::IInspectable); impl PlayReadyLicense { pub fn FullyEvaluated(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn UsableForPlay(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation")] pub fn ExpirationDate(&self) -> ::windows::core::Result<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>>(result__) } } pub fn ExpireAfterFirstPlay(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn DomainAccountID(&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).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn ChainDepth(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn GetKIDAtChainDepth(&self, chaindepth: u32) -> ::windows::core::Result<::windows::core::GUID> { let this = self; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), chaindepth, &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn SecureStopId(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<IPlayReadyLicense2>(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 SecurityLevel(&self) -> ::windows::core::Result<u32> { let this = &::windows::core::Interface::cast::<IPlayReadyLicense2>(self)?; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn InMemoryOnly(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IPlayReadyLicense2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn ExpiresInRealTime(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IPlayReadyLicense2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for PlayReadyLicense { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyLicense;{ee474c4e-fa3c-414d-a9f2-3ffc1ef832d4})"); } unsafe impl ::windows::core::Interface for PlayReadyLicense { type Vtable = IPlayReadyLicense_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xee474c4e_fa3c_414d_a9f2_3ffc1ef832d4); } impl ::windows::core::RuntimeName for PlayReadyLicense { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyLicense"; } impl ::core::convert::From<PlayReadyLicense> for ::windows::core::IUnknown { fn from(value: PlayReadyLicense) -> Self { value.0 .0 } } impl ::core::convert::From<&PlayReadyLicense> for ::windows::core::IUnknown { fn from(value: &PlayReadyLicense) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyLicense { 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 PlayReadyLicense { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlayReadyLicense> for ::windows::core::IInspectable { fn from(value: PlayReadyLicense) -> Self { value.0 } } impl ::core::convert::From<&PlayReadyLicense> for ::windows::core::IInspectable { fn from(value: &PlayReadyLicense) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyLicense { 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 PlayReadyLicense { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<PlayReadyLicense> for IPlayReadyLicense { fn from(value: PlayReadyLicense) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&PlayReadyLicense> for IPlayReadyLicense { fn from(value: &PlayReadyLicense) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyLicense> for PlayReadyLicense { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyLicense> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyLicense> for &PlayReadyLicense { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyLicense> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyLicenseAcquisitionServiceRequest(pub ::windows::core::IInspectable); impl PlayReadyLicenseAcquisitionServiceRequest { 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<PlayReadyLicenseAcquisitionServiceRequest, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn ContentHeader(&self) -> ::windows::core::Result<PlayReadyContentHeader> { 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::<PlayReadyContentHeader>(result__) } } pub fn SetContentHeader<'a, Param0: ::windows::core::IntoParam<'a, PlayReadyContentHeader>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn DomainServiceId(&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).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } pub fn SetDomainServiceId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ProtectionSystem(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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 = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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__) } } #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } #[cfg(feature = "Foundation")] pub fn SetUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ResponseCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 ChallengeCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 SetChallengeCustomData<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn BeginServiceRequest(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } pub fn NextServiceRequest(&self) -> ::windows::core::Result<IPlayReadyServiceRequest> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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::<IPlayReadyServiceRequest>(result__) } } pub fn GenerateManualEnablingChallenge(&self) -> ::windows::core::Result<PlayReadySoapMessage> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlayReadySoapMessage>(result__) } } pub fn ProcessManualEnablingResponse(&self, responsebytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<::windows::core::HRESULT> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), responsebytes.len() as u32, ::core::mem::transmute(responsebytes.as_ptr()), &mut result__).from_abi::<::windows::core::HRESULT>(result__) } } pub fn SessionId(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<IPlayReadyLicenseAcquisitionServiceRequest2>(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__) } } #[cfg(feature = "Foundation_Collections")] pub fn CreateLicenseIterable<'a, Param0: ::windows::core::IntoParam<'a, PlayReadyContentHeader>>(&self, contentheader: Param0, fullyevaluated: bool) -> ::windows::core::Result<PlayReadyLicenseIterable> { let this = &::windows::core::Interface::cast::<IPlayReadyLicenseAcquisitionServiceRequest3>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), contentheader.into_param().abi(), fullyevaluated, &mut result__).from_abi::<PlayReadyLicenseIterable>(result__) } } } unsafe impl ::windows::core::RuntimeType for PlayReadyLicenseAcquisitionServiceRequest { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyLicenseAcquisitionServiceRequest;{5d85ff45-3e9f-4f48-93e1-9530c8d58c3e})"); } unsafe impl ::windows::core::Interface for PlayReadyLicenseAcquisitionServiceRequest { type Vtable = IPlayReadyLicenseAcquisitionServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5d85ff45_3e9f_4f48_93e1_9530c8d58c3e); } impl ::windows::core::RuntimeName for PlayReadyLicenseAcquisitionServiceRequest { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyLicenseAcquisitionServiceRequest"; } impl ::core::convert::From<PlayReadyLicenseAcquisitionServiceRequest> for ::windows::core::IUnknown { fn from(value: PlayReadyLicenseAcquisitionServiceRequest) -> Self { value.0 .0 } } impl ::core::convert::From<&PlayReadyLicenseAcquisitionServiceRequest> for ::windows::core::IUnknown { fn from(value: &PlayReadyLicenseAcquisitionServiceRequest) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyLicenseAcquisitionServiceRequest { 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 PlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlayReadyLicenseAcquisitionServiceRequest> for ::windows::core::IInspectable { fn from(value: PlayReadyLicenseAcquisitionServiceRequest) -> Self { value.0 } } impl ::core::convert::From<&PlayReadyLicenseAcquisitionServiceRequest> for ::windows::core::IInspectable { fn from(value: &PlayReadyLicenseAcquisitionServiceRequest) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyLicenseAcquisitionServiceRequest { 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 PlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<PlayReadyLicenseAcquisitionServiceRequest> for IPlayReadyLicenseAcquisitionServiceRequest { fn from(value: PlayReadyLicenseAcquisitionServiceRequest) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&PlayReadyLicenseAcquisitionServiceRequest> for IPlayReadyLicenseAcquisitionServiceRequest { fn from(value: &PlayReadyLicenseAcquisitionServiceRequest) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyLicenseAcquisitionServiceRequest> for PlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyLicenseAcquisitionServiceRequest> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyLicenseAcquisitionServiceRequest> for &PlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyLicenseAcquisitionServiceRequest> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } impl ::core::convert::TryFrom<PlayReadyLicenseAcquisitionServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadyLicenseAcquisitionServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadyLicenseAcquisitionServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadyLicenseAcquisitionServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for PlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for &PlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::core::convert::TryInto::<super::IMediaProtectionServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } impl ::core::convert::TryFrom<PlayReadyLicenseAcquisitionServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadyLicenseAcquisitionServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadyLicenseAcquisitionServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadyLicenseAcquisitionServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for PlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for &PlayReadyLicenseAcquisitionServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::core::convert::TryInto::<IPlayReadyServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[cfg(feature = "Foundation_Collections")] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyLicenseIterable(pub ::windows::core::IInspectable); #[cfg(feature = "Foundation_Collections")] impl PlayReadyLicenseIterable { 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<PlayReadyLicenseIterable, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation_Collections")] pub fn First(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IIterator<IPlayReadyLicense>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IIterator<IPlayReadyLicense>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn CreateInstance<'a, Param0: ::windows::core::IntoParam<'a, PlayReadyContentHeader>>(contentheader: Param0, fullyevaluated: bool) -> ::windows::core::Result<PlayReadyLicenseIterable> { Self::IPlayReadyLicenseIterableFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), contentheader.into_param().abi(), fullyevaluated, &mut result__).from_abi::<PlayReadyLicenseIterable>(result__) }) } pub fn IPlayReadyLicenseIterableFactory<R, F: FnOnce(&IPlayReadyLicenseIterableFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadyLicenseIterable, IPlayReadyLicenseIterableFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } #[cfg(feature = "Foundation_Collections")] unsafe impl ::windows::core::RuntimeType for PlayReadyLicenseIterable { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyLicenseIterable;pinterface({faa585ea-6214-4217-afda-7f46de5869b3};{ee474c4e-fa3c-414d-a9f2-3ffc1ef832d4}))"); } #[cfg(feature = "Foundation_Collections")] unsafe impl ::windows::core::Interface for PlayReadyLicenseIterable { type Vtable = super::super::super::Foundation::Collections::IIterable_abi<IPlayReadyLicense>; const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<super::super::super::Foundation::Collections::IIterable<IPlayReadyLicense> as ::windows::core::RuntimeType>::SIGNATURE); } #[cfg(feature = "Foundation_Collections")] impl ::windows::core::RuntimeName for PlayReadyLicenseIterable { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyLicenseIterable"; } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadyLicenseIterable> for ::windows::core::IUnknown { fn from(value: PlayReadyLicenseIterable) -> Self { value.0 .0 } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadyLicenseIterable> for ::windows::core::IUnknown { fn from(value: &PlayReadyLicenseIterable) -> Self { value.0 .0.clone() } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyLicenseIterable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PlayReadyLicenseIterable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadyLicenseIterable> for ::windows::core::IInspectable { fn from(value: PlayReadyLicenseIterable) -> Self { value.0 } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadyLicenseIterable> for ::windows::core::IInspectable { fn from(value: &PlayReadyLicenseIterable) -> Self { value.0.clone() } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyLicenseIterable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PlayReadyLicenseIterable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadyLicenseIterable> for super::super::super::Foundation::Collections::IIterable<IPlayReadyLicense> { fn from(value: PlayReadyLicenseIterable) -> Self { unsafe { ::core::mem::transmute(value) } } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadyLicenseIterable> for super::super::super::Foundation::Collections::IIterable<IPlayReadyLicense> { fn from(value: &PlayReadyLicenseIterable) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterable<IPlayReadyLicense>> for PlayReadyLicenseIterable { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::Collections::IIterable<IPlayReadyLicense>> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterable<IPlayReadyLicense>> for &PlayReadyLicenseIterable { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::Collections::IIterable<IPlayReadyLicense>> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[cfg(all(feature = "Foundation_Collections"))] impl ::core::iter::IntoIterator for PlayReadyLicenseIterable { type Item = IPlayReadyLicense; type IntoIter = super::super::super::Foundation::Collections::IIterator<Self::Item>; fn into_iter(self) -> Self::IntoIter { ::core::iter::IntoIterator::into_iter(&self) } } #[cfg(all(feature = "Foundation_Collections"))] impl ::core::iter::IntoIterator for &PlayReadyLicenseIterable { type Item = IPlayReadyLicense; type IntoIter = super::super::super::Foundation::Collections::IIterator<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.First().unwrap() } } #[cfg(feature = "Foundation_Collections")] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyLicenseIterator(pub ::windows::core::IInspectable); #[cfg(feature = "Foundation_Collections")] impl PlayReadyLicenseIterator { #[cfg(feature = "Foundation_Collections")] pub fn Current(&self) -> ::windows::core::Result<IPlayReadyLicense> { 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::<IPlayReadyLicense>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn HasCurrent(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn MoveNext(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn GetMany(&self, items: &mut [<IPlayReadyLicense as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), items.len() as u32, ::core::mem::transmute_copy(&items), &mut result__).from_abi::<u32>(result__) } } } #[cfg(feature = "Foundation_Collections")] unsafe impl ::windows::core::RuntimeType for PlayReadyLicenseIterator { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyLicenseIterator;pinterface({6a79e863-4300-459a-9966-cbb660963ee1};{ee474c4e-fa3c-414d-a9f2-3ffc1ef832d4}))"); } #[cfg(feature = "Foundation_Collections")] unsafe impl ::windows::core::Interface for PlayReadyLicenseIterator { type Vtable = super::super::super::Foundation::Collections::IIterator_abi<IPlayReadyLicense>; const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<super::super::super::Foundation::Collections::IIterator<IPlayReadyLicense> as ::windows::core::RuntimeType>::SIGNATURE); } #[cfg(feature = "Foundation_Collections")] impl ::windows::core::RuntimeName for PlayReadyLicenseIterator { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyLicenseIterator"; } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadyLicenseIterator> for ::windows::core::IUnknown { fn from(value: PlayReadyLicenseIterator) -> Self { value.0 .0 } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadyLicenseIterator> for ::windows::core::IUnknown { fn from(value: &PlayReadyLicenseIterator) -> Self { value.0 .0.clone() } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyLicenseIterator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PlayReadyLicenseIterator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadyLicenseIterator> for ::windows::core::IInspectable { fn from(value: PlayReadyLicenseIterator) -> Self { value.0 } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadyLicenseIterator> for ::windows::core::IInspectable { fn from(value: &PlayReadyLicenseIterator) -> Self { value.0.clone() } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyLicenseIterator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PlayReadyLicenseIterator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadyLicenseIterator> for super::super::super::Foundation::Collections::IIterator<IPlayReadyLicense> { fn from(value: PlayReadyLicenseIterator) -> Self { unsafe { ::core::mem::transmute(value) } } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadyLicenseIterator> for super::super::super::Foundation::Collections::IIterator<IPlayReadyLicense> { fn from(value: &PlayReadyLicenseIterator) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterator<IPlayReadyLicense>> for PlayReadyLicenseIterator { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::Collections::IIterator<IPlayReadyLicense>> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterator<IPlayReadyLicense>> for &PlayReadyLicenseIterator { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::Collections::IIterator<IPlayReadyLicense>> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } pub struct PlayReadyLicenseManagement {} impl PlayReadyLicenseManagement { #[cfg(feature = "Foundation")] pub fn DeleteLicenses<'a, Param0: ::windows::core::IntoParam<'a, PlayReadyContentHeader>>(contentheader: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { Self::IPlayReadyLicenseManagement(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), contentheader.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) }) } pub fn IPlayReadyLicenseManagement<R, F: FnOnce(&IPlayReadyLicenseManagement) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadyLicenseManagement, IPlayReadyLicenseManagement> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for PlayReadyLicenseManagement { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyLicenseManagement"; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyLicenseSession(pub ::windows::core::IInspectable); impl PlayReadyLicenseSession { pub fn CreateLAServiceRequest(&self) -> ::windows::core::Result<IPlayReadyLicenseAcquisitionServiceRequest> { 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::<IPlayReadyLicenseAcquisitionServiceRequest>(result__) } } pub fn ConfigureMediaProtectionManager<'a, Param0: ::windows::core::IntoParam<'a, super::MediaProtectionManager>>(&self, mpm: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), mpm.into_param().abi()).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn CreateInstance<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IPropertySet>>(configuration: Param0) -> ::windows::core::Result<PlayReadyLicenseSession> { Self::IPlayReadyLicenseSessionFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), configuration.into_param().abi(), &mut result__).from_abi::<PlayReadyLicenseSession>(result__) }) } #[cfg(feature = "Foundation_Collections")] pub fn CreateLicenseIterable<'a, Param0: ::windows::core::IntoParam<'a, PlayReadyContentHeader>>(&self, contentheader: Param0, fullyevaluated: bool) -> ::windows::core::Result<PlayReadyLicenseIterable> { let this = &::windows::core::Interface::cast::<IPlayReadyLicenseSession2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), contentheader.into_param().abi(), fullyevaluated, &mut result__).from_abi::<PlayReadyLicenseIterable>(result__) } } pub fn IPlayReadyLicenseSessionFactory<R, F: FnOnce(&IPlayReadyLicenseSessionFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadyLicenseSession, IPlayReadyLicenseSessionFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PlayReadyLicenseSession { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyLicenseSession;{a1723a39-87fa-4fdd-abbb-a9720e845259})"); } unsafe impl ::windows::core::Interface for PlayReadyLicenseSession { type Vtable = IPlayReadyLicenseSession_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa1723a39_87fa_4fdd_abbb_a9720e845259); } impl ::windows::core::RuntimeName for PlayReadyLicenseSession { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyLicenseSession"; } impl ::core::convert::From<PlayReadyLicenseSession> for ::windows::core::IUnknown { fn from(value: PlayReadyLicenseSession) -> Self { value.0 .0 } } impl ::core::convert::From<&PlayReadyLicenseSession> for ::windows::core::IUnknown { fn from(value: &PlayReadyLicenseSession) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyLicenseSession { 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 PlayReadyLicenseSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlayReadyLicenseSession> for ::windows::core::IInspectable { fn from(value: PlayReadyLicenseSession) -> Self { value.0 } } impl ::core::convert::From<&PlayReadyLicenseSession> for ::windows::core::IInspectable { fn from(value: &PlayReadyLicenseSession) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyLicenseSession { 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 PlayReadyLicenseSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<PlayReadyLicenseSession> for IPlayReadyLicenseSession { fn from(value: PlayReadyLicenseSession) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&PlayReadyLicenseSession> for IPlayReadyLicenseSession { fn from(value: &PlayReadyLicenseSession) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyLicenseSession> for PlayReadyLicenseSession { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyLicenseSession> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyLicenseSession> for &PlayReadyLicenseSession { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyLicenseSession> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } impl ::core::convert::TryFrom<PlayReadyLicenseSession> for IPlayReadyLicenseSession2 { type Error = ::windows::core::Error; fn try_from(value: PlayReadyLicenseSession) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadyLicenseSession> for IPlayReadyLicenseSession2 { type Error = ::windows::core::Error; fn try_from(value: &PlayReadyLicenseSession) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyLicenseSession2> for PlayReadyLicenseSession { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyLicenseSession2> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyLicenseSession2> for &PlayReadyLicenseSession { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyLicenseSession2> { ::core::convert::TryInto::<IPlayReadyLicenseSession2>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyMeteringReportServiceRequest(pub ::windows::core::IInspectable); impl PlayReadyMeteringReportServiceRequest { 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<PlayReadyMeteringReportServiceRequest, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn MeteringCertificate(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } pub fn SetMeteringCertificate(&self, meteringcertbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), meteringcertbytes.len() as u32, ::core::mem::transmute(meteringcertbytes.as_ptr())).ok() } } pub fn ProtectionSystem(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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 = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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__) } } #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } #[cfg(feature = "Foundation")] pub fn SetUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ResponseCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 ChallengeCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 SetChallengeCustomData<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn BeginServiceRequest(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } pub fn NextServiceRequest(&self) -> ::windows::core::Result<IPlayReadyServiceRequest> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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::<IPlayReadyServiceRequest>(result__) } } pub fn GenerateManualEnablingChallenge(&self) -> ::windows::core::Result<PlayReadySoapMessage> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlayReadySoapMessage>(result__) } } pub fn ProcessManualEnablingResponse(&self, responsebytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<::windows::core::HRESULT> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), responsebytes.len() as u32, ::core::mem::transmute(responsebytes.as_ptr()), &mut result__).from_abi::<::windows::core::HRESULT>(result__) } } } unsafe impl ::windows::core::RuntimeType for PlayReadyMeteringReportServiceRequest { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyMeteringReportServiceRequest;{c12b231c-0ecd-4f11-a185-1e24a4a67fb7})"); } unsafe impl ::windows::core::Interface for PlayReadyMeteringReportServiceRequest { type Vtable = IPlayReadyMeteringReportServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc12b231c_0ecd_4f11_a185_1e24a4a67fb7); } impl ::windows::core::RuntimeName for PlayReadyMeteringReportServiceRequest { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyMeteringReportServiceRequest"; } impl ::core::convert::From<PlayReadyMeteringReportServiceRequest> for ::windows::core::IUnknown { fn from(value: PlayReadyMeteringReportServiceRequest) -> Self { value.0 .0 } } impl ::core::convert::From<&PlayReadyMeteringReportServiceRequest> for ::windows::core::IUnknown { fn from(value: &PlayReadyMeteringReportServiceRequest) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyMeteringReportServiceRequest { 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 PlayReadyMeteringReportServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlayReadyMeteringReportServiceRequest> for ::windows::core::IInspectable { fn from(value: PlayReadyMeteringReportServiceRequest) -> Self { value.0 } } impl ::core::convert::From<&PlayReadyMeteringReportServiceRequest> for ::windows::core::IInspectable { fn from(value: &PlayReadyMeteringReportServiceRequest) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyMeteringReportServiceRequest { 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 PlayReadyMeteringReportServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<PlayReadyMeteringReportServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadyMeteringReportServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadyMeteringReportServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadyMeteringReportServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for PlayReadyMeteringReportServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for &PlayReadyMeteringReportServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::core::convert::TryInto::<super::IMediaProtectionServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } impl ::core::convert::TryFrom<PlayReadyMeteringReportServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadyMeteringReportServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadyMeteringReportServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadyMeteringReportServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for PlayReadyMeteringReportServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for &PlayReadyMeteringReportServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::core::convert::TryInto::<IPlayReadyServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadyRevocationServiceRequest(pub ::windows::core::IInspectable); impl PlayReadyRevocationServiceRequest { 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<PlayReadyRevocationServiceRequest, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn ProtectionSystem(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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 = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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__) } } #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } #[cfg(feature = "Foundation")] pub fn SetUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ResponseCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 ChallengeCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 SetChallengeCustomData<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn BeginServiceRequest(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } pub fn NextServiceRequest(&self) -> ::windows::core::Result<IPlayReadyServiceRequest> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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::<IPlayReadyServiceRequest>(result__) } } pub fn GenerateManualEnablingChallenge(&self) -> ::windows::core::Result<PlayReadySoapMessage> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlayReadySoapMessage>(result__) } } pub fn ProcessManualEnablingResponse(&self, responsebytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<::windows::core::HRESULT> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), responsebytes.len() as u32, ::core::mem::transmute(responsebytes.as_ptr()), &mut result__).from_abi::<::windows::core::HRESULT>(result__) } } } unsafe impl ::windows::core::RuntimeType for PlayReadyRevocationServiceRequest { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadyRevocationServiceRequest;{543d66ac-faf0-4560-84a5-0e4acec939e4})"); } unsafe impl ::windows::core::Interface for PlayReadyRevocationServiceRequest { type Vtable = IPlayReadyRevocationServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x543d66ac_faf0_4560_84a5_0e4acec939e4); } impl ::windows::core::RuntimeName for PlayReadyRevocationServiceRequest { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyRevocationServiceRequest"; } impl ::core::convert::From<PlayReadyRevocationServiceRequest> for ::windows::core::IUnknown { fn from(value: PlayReadyRevocationServiceRequest) -> Self { value.0 .0 } } impl ::core::convert::From<&PlayReadyRevocationServiceRequest> for ::windows::core::IUnknown { fn from(value: &PlayReadyRevocationServiceRequest) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadyRevocationServiceRequest { 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 PlayReadyRevocationServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlayReadyRevocationServiceRequest> for ::windows::core::IInspectable { fn from(value: PlayReadyRevocationServiceRequest) -> Self { value.0 } } impl ::core::convert::From<&PlayReadyRevocationServiceRequest> for ::windows::core::IInspectable { fn from(value: &PlayReadyRevocationServiceRequest) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadyRevocationServiceRequest { 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 PlayReadyRevocationServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<PlayReadyRevocationServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadyRevocationServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadyRevocationServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadyRevocationServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for PlayReadyRevocationServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for &PlayReadyRevocationServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::core::convert::TryInto::<super::IMediaProtectionServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } impl ::core::convert::TryFrom<PlayReadyRevocationServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadyRevocationServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadyRevocationServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadyRevocationServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for PlayReadyRevocationServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for &PlayReadyRevocationServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::core::convert::TryInto::<IPlayReadyServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[cfg(feature = "Foundation_Collections")] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadySecureStopIterable(pub ::windows::core::IInspectable); #[cfg(feature = "Foundation_Collections")] impl PlayReadySecureStopIterable { #[cfg(feature = "Foundation_Collections")] pub fn First(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IIterator<IPlayReadySecureStopServiceRequest>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IIterator<IPlayReadySecureStopServiceRequest>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn CreateInstance(publishercertbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<PlayReadySecureStopIterable> { Self::IPlayReadySecureStopIterableFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), publishercertbytes.len() as u32, ::core::mem::transmute(publishercertbytes.as_ptr()), &mut result__).from_abi::<PlayReadySecureStopIterable>(result__) }) } pub fn IPlayReadySecureStopIterableFactory<R, F: FnOnce(&IPlayReadySecureStopIterableFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadySecureStopIterable, IPlayReadySecureStopIterableFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } #[cfg(feature = "Foundation_Collections")] unsafe impl ::windows::core::RuntimeType for PlayReadySecureStopIterable { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadySecureStopIterable;pinterface({faa585ea-6214-4217-afda-7f46de5869b3};{b5501ee5-01bf-4401-9677-05630a6a4cc8}))"); } #[cfg(feature = "Foundation_Collections")] unsafe impl ::windows::core::Interface for PlayReadySecureStopIterable { type Vtable = super::super::super::Foundation::Collections::IIterable_abi<IPlayReadySecureStopServiceRequest>; const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<super::super::super::Foundation::Collections::IIterable<IPlayReadySecureStopServiceRequest> as ::windows::core::RuntimeType>::SIGNATURE); } #[cfg(feature = "Foundation_Collections")] impl ::windows::core::RuntimeName for PlayReadySecureStopIterable { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadySecureStopIterable"; } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadySecureStopIterable> for ::windows::core::IUnknown { fn from(value: PlayReadySecureStopIterable) -> Self { value.0 .0 } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadySecureStopIterable> for ::windows::core::IUnknown { fn from(value: &PlayReadySecureStopIterable) -> Self { value.0 .0.clone() } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadySecureStopIterable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PlayReadySecureStopIterable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadySecureStopIterable> for ::windows::core::IInspectable { fn from(value: PlayReadySecureStopIterable) -> Self { value.0 } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadySecureStopIterable> for ::windows::core::IInspectable { fn from(value: &PlayReadySecureStopIterable) -> Self { value.0.clone() } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadySecureStopIterable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PlayReadySecureStopIterable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadySecureStopIterable> for super::super::super::Foundation::Collections::IIterable<IPlayReadySecureStopServiceRequest> { fn from(value: PlayReadySecureStopIterable) -> Self { unsafe { ::core::mem::transmute(value) } } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadySecureStopIterable> for super::super::super::Foundation::Collections::IIterable<IPlayReadySecureStopServiceRequest> { fn from(value: &PlayReadySecureStopIterable) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterable<IPlayReadySecureStopServiceRequest>> for PlayReadySecureStopIterable { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::Collections::IIterable<IPlayReadySecureStopServiceRequest>> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterable<IPlayReadySecureStopServiceRequest>> for &PlayReadySecureStopIterable { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::Collections::IIterable<IPlayReadySecureStopServiceRequest>> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[cfg(all(feature = "Foundation_Collections"))] impl ::core::iter::IntoIterator for PlayReadySecureStopIterable { type Item = IPlayReadySecureStopServiceRequest; type IntoIter = super::super::super::Foundation::Collections::IIterator<Self::Item>; fn into_iter(self) -> Self::IntoIter { ::core::iter::IntoIterator::into_iter(&self) } } #[cfg(all(feature = "Foundation_Collections"))] impl ::core::iter::IntoIterator for &PlayReadySecureStopIterable { type Item = IPlayReadySecureStopServiceRequest; type IntoIter = super::super::super::Foundation::Collections::IIterator<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.First().unwrap() } } #[cfg(feature = "Foundation_Collections")] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadySecureStopIterator(pub ::windows::core::IInspectable); #[cfg(feature = "Foundation_Collections")] impl PlayReadySecureStopIterator { #[cfg(feature = "Foundation_Collections")] pub fn Current(&self) -> ::windows::core::Result<IPlayReadySecureStopServiceRequest> { 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::<IPlayReadySecureStopServiceRequest>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn HasCurrent(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn MoveNext(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn GetMany(&self, items: &mut [<IPlayReadySecureStopServiceRequest as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), items.len() as u32, ::core::mem::transmute_copy(&items), &mut result__).from_abi::<u32>(result__) } } } #[cfg(feature = "Foundation_Collections")] unsafe impl ::windows::core::RuntimeType for PlayReadySecureStopIterator { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadySecureStopIterator;pinterface({6a79e863-4300-459a-9966-cbb660963ee1};{b5501ee5-01bf-4401-9677-05630a6a4cc8}))"); } #[cfg(feature = "Foundation_Collections")] unsafe impl ::windows::core::Interface for PlayReadySecureStopIterator { type Vtable = super::super::super::Foundation::Collections::IIterator_abi<IPlayReadySecureStopServiceRequest>; const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<super::super::super::Foundation::Collections::IIterator<IPlayReadySecureStopServiceRequest> as ::windows::core::RuntimeType>::SIGNATURE); } #[cfg(feature = "Foundation_Collections")] impl ::windows::core::RuntimeName for PlayReadySecureStopIterator { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadySecureStopIterator"; } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadySecureStopIterator> for ::windows::core::IUnknown { fn from(value: PlayReadySecureStopIterator) -> Self { value.0 .0 } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadySecureStopIterator> for ::windows::core::IUnknown { fn from(value: &PlayReadySecureStopIterator) -> Self { value.0 .0.clone() } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadySecureStopIterator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PlayReadySecureStopIterator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadySecureStopIterator> for ::windows::core::IInspectable { fn from(value: PlayReadySecureStopIterator) -> Self { value.0 } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadySecureStopIterator> for ::windows::core::IInspectable { fn from(value: &PlayReadySecureStopIterator) -> Self { value.0.clone() } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadySecureStopIterator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PlayReadySecureStopIterator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<PlayReadySecureStopIterator> for super::super::super::Foundation::Collections::IIterator<IPlayReadySecureStopServiceRequest> { fn from(value: PlayReadySecureStopIterator) -> Self { unsafe { ::core::mem::transmute(value) } } } #[cfg(feature = "Foundation_Collections")] impl ::core::convert::From<&PlayReadySecureStopIterator> for super::super::super::Foundation::Collections::IIterator<IPlayReadySecureStopServiceRequest> { fn from(value: &PlayReadySecureStopIterator) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterator<IPlayReadySecureStopServiceRequest>> for PlayReadySecureStopIterator { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::Collections::IIterator<IPlayReadySecureStopServiceRequest>> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Foundation_Collections")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterator<IPlayReadySecureStopServiceRequest>> for &PlayReadySecureStopIterator { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::Collections::IIterator<IPlayReadySecureStopServiceRequest>> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadySecureStopServiceRequest(pub ::windows::core::IInspectable); impl PlayReadySecureStopServiceRequest { pub fn SessionID(&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__) } } #[cfg(feature = "Foundation")] pub fn StartTime(&self) -> ::windows::core::Result<super::super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::DateTime>(result__) } } #[cfg(feature = "Foundation")] pub fn UpdateTime(&self) -> ::windows::core::Result<super::super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::DateTime>(result__) } } pub fn Stopped(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn PublisherCertificate(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } pub fn ProtectionSystem(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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 = &::windows::core::Interface::cast::<super::IMediaProtectionServiceRequest>(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__) } } #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } #[cfg(feature = "Foundation")] pub fn SetUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ResponseCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 ChallengeCustomData(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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 SetChallengeCustomData<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn BeginServiceRequest(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } pub fn NextServiceRequest(&self) -> ::windows::core::Result<IPlayReadyServiceRequest> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(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::<IPlayReadyServiceRequest>(result__) } } pub fn GenerateManualEnablingChallenge(&self) -> ::windows::core::Result<PlayReadySoapMessage> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlayReadySoapMessage>(result__) } } pub fn ProcessManualEnablingResponse(&self, responsebytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<::windows::core::HRESULT> { let this = &::windows::core::Interface::cast::<IPlayReadyServiceRequest>(self)?; unsafe { let mut result__: ::windows::core::HRESULT = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), responsebytes.len() as u32, ::core::mem::transmute(responsebytes.as_ptr()), &mut result__).from_abi::<::windows::core::HRESULT>(result__) } } pub fn CreateInstance(publishercertbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<PlayReadySecureStopServiceRequest> { Self::IPlayReadySecureStopServiceRequestFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), publishercertbytes.len() as u32, ::core::mem::transmute(publishercertbytes.as_ptr()), &mut result__).from_abi::<PlayReadySecureStopServiceRequest>(result__) }) } pub fn CreateInstanceFromSessionID<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(sessionid: Param0, publishercertbytes: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<PlayReadySecureStopServiceRequest> { Self::IPlayReadySecureStopServiceRequestFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), sessionid.into_param().abi(), publishercertbytes.len() as u32, ::core::mem::transmute(publishercertbytes.as_ptr()), &mut result__).from_abi::<PlayReadySecureStopServiceRequest>(result__) }) } pub fn IPlayReadySecureStopServiceRequestFactory<R, F: FnOnce(&IPlayReadySecureStopServiceRequestFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadySecureStopServiceRequest, IPlayReadySecureStopServiceRequestFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PlayReadySecureStopServiceRequest { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadySecureStopServiceRequest;{b5501ee5-01bf-4401-9677-05630a6a4cc8})"); } unsafe impl ::windows::core::Interface for PlayReadySecureStopServiceRequest { type Vtable = IPlayReadySecureStopServiceRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb5501ee5_01bf_4401_9677_05630a6a4cc8); } impl ::windows::core::RuntimeName for PlayReadySecureStopServiceRequest { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadySecureStopServiceRequest"; } impl ::core::convert::From<PlayReadySecureStopServiceRequest> for ::windows::core::IUnknown { fn from(value: PlayReadySecureStopServiceRequest) -> Self { value.0 .0 } } impl ::core::convert::From<&PlayReadySecureStopServiceRequest> for ::windows::core::IUnknown { fn from(value: &PlayReadySecureStopServiceRequest) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadySecureStopServiceRequest { 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 PlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlayReadySecureStopServiceRequest> for ::windows::core::IInspectable { fn from(value: PlayReadySecureStopServiceRequest) -> Self { value.0 } } impl ::core::convert::From<&PlayReadySecureStopServiceRequest> for ::windows::core::IInspectable { fn from(value: &PlayReadySecureStopServiceRequest) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadySecureStopServiceRequest { 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 PlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<PlayReadySecureStopServiceRequest> for IPlayReadySecureStopServiceRequest { fn from(value: PlayReadySecureStopServiceRequest) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&PlayReadySecureStopServiceRequest> for IPlayReadySecureStopServiceRequest { fn from(value: &PlayReadySecureStopServiceRequest) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadySecureStopServiceRequest> for PlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadySecureStopServiceRequest> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadySecureStopServiceRequest> for &PlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadySecureStopServiceRequest> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } impl ::core::convert::TryFrom<PlayReadySecureStopServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadySecureStopServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadySecureStopServiceRequest> for super::IMediaProtectionServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadySecureStopServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for PlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, super::IMediaProtectionServiceRequest> for &PlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, super::IMediaProtectionServiceRequest> { ::core::convert::TryInto::<super::IMediaProtectionServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } impl ::core::convert::TryFrom<PlayReadySecureStopServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: PlayReadySecureStopServiceRequest) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&PlayReadySecureStopServiceRequest> for IPlayReadyServiceRequest { type Error = ::windows::core::Error; fn try_from(value: &PlayReadySecureStopServiceRequest) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for PlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IPlayReadyServiceRequest> for &PlayReadySecureStopServiceRequest { fn into_param(self) -> ::windows::core::Param<'a, IPlayReadyServiceRequest> { ::core::convert::TryInto::<IPlayReadyServiceRequest>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlayReadySoapMessage(pub ::windows::core::IInspectable); impl PlayReadySoapMessage { pub fn GetMessageBody(&self) -> ::windows::core::Result<::windows::core::Array<u8>> { let this = self; unsafe { let mut result__: ::windows::core::Array<u8> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), ::windows::core::Array::<u8>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__) } } #[cfg(feature = "Foundation_Collections")] pub fn MessageHeaders(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IPropertySet> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IPropertySet>(result__) } } #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::super::Foundation::Uri> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Uri>(result__) } } } unsafe impl ::windows::core::RuntimeType for PlayReadySoapMessage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.Protection.PlayReady.PlayReadySoapMessage;{b659fcb5-ce41-41ba-8a0d-61df5fffa139})"); } unsafe impl ::windows::core::Interface for PlayReadySoapMessage { type Vtable = IPlayReadySoapMessage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb659fcb5_ce41_41ba_8a0d_61df5fffa139); } impl ::windows::core::RuntimeName for PlayReadySoapMessage { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadySoapMessage"; } impl ::core::convert::From<PlayReadySoapMessage> for ::windows::core::IUnknown { fn from(value: PlayReadySoapMessage) -> Self { value.0 .0 } } impl ::core::convert::From<&PlayReadySoapMessage> for ::windows::core::IUnknown { fn from(value: &PlayReadySoapMessage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlayReadySoapMessage { 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 PlayReadySoapMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlayReadySoapMessage> for ::windows::core::IInspectable { fn from(value: PlayReadySoapMessage) -> Self { value.0 } } impl ::core::convert::From<&PlayReadySoapMessage> for ::windows::core::IInspectable { fn from(value: &PlayReadySoapMessage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlayReadySoapMessage { 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 PlayReadySoapMessage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } pub struct PlayReadyStatics {} impl PlayReadyStatics { pub fn DomainJoinServiceRequestType() -> ::windows::core::Result<::windows::core::GUID> { Self::IPlayReadyStatics(|this| 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 DomainLeaveServiceRequestType() -> ::windows::core::Result<::windows::core::GUID> { Self::IPlayReadyStatics(|this| 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__) }) } pub fn IndividualizationServiceRequestType() -> ::windows::core::Result<::windows::core::GUID> { Self::IPlayReadyStatics(|this| unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) }) } pub fn LicenseAcquirerServiceRequestType() -> ::windows::core::Result<::windows::core::GUID> { Self::IPlayReadyStatics(|this| unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) }) } pub fn MeteringReportServiceRequestType() -> ::windows::core::Result<::windows::core::GUID> { Self::IPlayReadyStatics(|this| unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) }) } pub fn RevocationServiceRequestType() -> ::windows::core::Result<::windows::core::GUID> { Self::IPlayReadyStatics(|this| unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) }) } pub fn MediaProtectionSystemId() -> ::windows::core::Result<::windows::core::GUID> { Self::IPlayReadyStatics(|this| unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) }) } pub fn PlayReadySecurityVersion() -> ::windows::core::Result<u32> { Self::IPlayReadyStatics(|this| unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) }) } pub fn PlayReadyCertificateSecurityLevel() -> ::windows::core::Result<u32> { Self::IPlayReadyStatics2(|this| unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) }) } pub fn SecureStopServiceRequestType() -> ::windows::core::Result<::windows::core::GUID> { Self::IPlayReadyStatics3(|this| 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 CheckSupportedHardware(hwdrmfeature: PlayReadyHardwareDRMFeatures) -> ::windows::core::Result<bool> { Self::IPlayReadyStatics3(|this| unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), hwdrmfeature, &mut result__).from_abi::<bool>(result__) }) } pub fn InputTrustAuthorityToCreate() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IPlayReadyStatics4(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn ProtectionSystemId() -> ::windows::core::Result<::windows::core::GUID> { Self::IPlayReadyStatics4(|this| 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__) }) } #[cfg(feature = "Foundation")] pub fn HardwareDRMDisabledAtTime() -> ::windows::core::Result<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>> { Self::IPlayReadyStatics5(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>>(result__) }) } #[cfg(feature = "Foundation")] pub fn HardwareDRMDisabledUntilTime() -> ::windows::core::Result<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>> { Self::IPlayReadyStatics5(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>>(result__) }) } pub fn ResetHardwareDRMDisabled() -> ::windows::core::Result<()> { Self::IPlayReadyStatics5(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this)).ok() }) } pub fn IPlayReadyStatics<R, F: FnOnce(&IPlayReadyStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadyStatics, IPlayReadyStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IPlayReadyStatics2<R, F: FnOnce(&IPlayReadyStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadyStatics, IPlayReadyStatics2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IPlayReadyStatics3<R, F: FnOnce(&IPlayReadyStatics3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadyStatics, IPlayReadyStatics3> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IPlayReadyStatics4<R, F: FnOnce(&IPlayReadyStatics4) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadyStatics, IPlayReadyStatics4> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IPlayReadyStatics5<R, F: FnOnce(&IPlayReadyStatics5) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlayReadyStatics, IPlayReadyStatics5> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for PlayReadyStatics { const NAME: &'static str = "Windows.Media.Protection.PlayReady.PlayReadyStatics"; }
// run-rustfix #![warn(clippy::unseparated_literal_suffix)] #![allow(dead_code)] fn main() { let _ok1 = 1234_i32; let _ok2 = 1234_isize; let _ok3 = 0x123_isize; let _fail1 = 1234i32; let _fail2 = 1234u32; let _fail3 = 1234isize; let _fail4 = 1234usize; let _fail5 = 0x123isize; let _okf1 = 1.5_f32; let _okf2 = 1_f32; let _failf1 = 1.5f32; let _failf2 = 1f32; }
use crate::AppState; use actix_web::{web, Error, HttpResponse}; use biscuit::jwa; use biscuit::jwa::Algorithm; use biscuit::jwk::*; use biscuit::jws::Secret; use biscuit::Empty; use num::BigUint; use ring::signature::KeyPair; use serde_json::json; use std::format; pub async fn keys(state: web::Data<AppState>) -> Result<HttpResponse, Error> { let rsa_key = state.rsa_key_pair.clone(); let jwk_set = create_jwk_set(rsa_key); Ok(HttpResponse::Ok().json(jwk_set)) } pub fn create_jwk_set(secret: Secret) -> JWKSet<Empty> { let public_key = match secret { Secret::RsaKeyPair(ring_pair) => { let s = ring_pair.clone(); let pk = s.public_key().clone(); Some(pk) } _ => None, } .expect("There is no RsaKeyPair with a public key found"); let jwk_set: JWKSet<Empty> = JWKSet { keys: vec![JWK { common: CommonParameters { algorithm: Some(Algorithm::Signature(jwa::SignatureAlgorithm::RS256)), key_id: Some("2020-01-29".to_string()), ..Default::default() }, algorithm: AlgorithmParameters::RSA(RSAKeyParameters { n: BigUint::from_bytes_be(public_key.modulus().big_endian_without_leading_zero()), e: BigUint::from_bytes_be(public_key.exponent().big_endian_without_leading_zero()), ..Default::default() }), additional: Default::default(), }], }; jwk_set } pub async fn openid_configuration(state: web::Data<AppState>) -> Result<HttpResponse, Error> { let keys_response = json!( { "issuer": format!("{}", state.exposed_host), "authorization_endpoint": format!("{}/auth", state.exposed_host), "token_endpoint": format!("{}/token", state.exposed_host), "jwks_uri": format!("{}/keys", state.exposed_host), "userinfo_endpoint": format!("{}/userinfo", state.exposed_host), "response_types_supported": [ "code", "id_token", "token" ], "subject_types_supported": [ "public" ], "id_token_signing_alg_values_supported": [ "RS256" ], "scopes_supported": [ "openid", "email", "groups", "profile", "offline_access" ], "token_endpoint_auth_methods_supported": [ "client_secret_basic" ], "claims_supported": [ "aud", "email", "email_verified", "exp", "iat", "iss", "locale", "name", "sub" ] }); Ok(HttpResponse::Ok().json(keys_response)) } #[cfg(test)] mod tests { use super::*; use actix_web::{http, test, web, App}; use serde_json::json; use serde_json::Value; use std::str; #[actix_rt::test] async fn test_route_keys() -> Result<(), Error> { let exposed_host = "http://localhost:8080".to_string(); let rsa_keys = Secret::rsa_keypair_from_file("./keys/private_key.der") .expect("Cannot read RSA keypair"); let app = test::init_service( App::new() .app_data(web::Data::new(AppState::new(rsa_keys, exposed_host))) .service(web::resource("/").route(web::get().to(keys))), ) .await; let req = test::TestRequest::get().uri("/").to_request(); let resp = test::call_service(&app, req).await; assert_eq!(resp.status(), http::StatusCode::OK); let response_body = test::read_body(resp).await; let body_str = match str::from_utf8(&response_body) { Ok(v) => v, Err(_e) => "Error with parsing result from bytes to string", }; let p: Value = serde_json::from_str(body_str).unwrap(); println!("Value : {:?}", p); assert_eq!(p["keys"][0]["e"], json!("AQAB")); Ok(()) } }
#![no_std] #![no_main] extern crate panic_halt; extern crate stm32f1xx_hal as hal; use cortex_m::asm; use cortex_m_rt::entry; use hal::prelude::*; use embedded_hal::digital::v2::OutputPin; use hal::rcc::{Rcc, Clocks}; use hal::flash::Parts; #[entry] fn main() -> ! { // 获取 Peripherals let peripherals = hal::pac::Peripherals::take().unwrap(); // 将 RCC 寄存器结构体转换为进一步抽象的 hal 结构体 let mut rcc:Rcc = peripherals.RCC.constrain(); // 获取 GPIOC 实例,这里会自动打开总线开关 let mut gpio_c = peripherals.GPIOC.split(&mut rcc.apb2); // 获取 PC13 实例,并进行引脚配置 let mut led = gpio_c.pc13.into_push_pull_output(&mut gpio_c.crh); //https://pic3.zhimg.com/80/v2-6165f61bc28c9e94b23d44cee04b0e2a_720w.jpg loop { delay(); // 输出低电平 let _ =led.set_low(); delay(); // 输出高电平 let _ = led.set_high(); } } fn delay() { let _ = asm::delay(2000000); } #[allow(dead_code)] fn rcc_clock_init(rcc: Rcc, mut flash: Parts) -> Clocks{ let clocks = rcc .cfgr .use_hse(8.mhz()) // 高速外部时钟源 .sysclk(72.mhz()) // 系统时钟 .hclk(72.mhz()) // AHB 高速总线 .pclk1(36.mhz()) // APB1 低速外设总线 .pclk2(72.mhz()) // APB2 高速外设总线 .freeze(&mut flash.acr); // 应用时钟配置 return clocks; } //https://www.zhihu.com/column/embedded-rust #[allow(dead_code)] fn rcc_clock_init_1(rcc: &mut stm32f1::stm32f103::RCC, flash: &mut stm32f1::stm32f103::FLASH) { // 启动外部高速时钟 (HSE) rcc.cr.write(|w| w.hseon().set_bit()); // 等待外部高速时钟稳定 while !rcc.cr.read().hserdy().bit_is_set() {} // 设置分频 AHB(HCLK) = SYSCLK, APB1(PCLK1) = SYSCLK / 2, APB2(PCK2) = SYSCLK rcc.cfgr .write(|w| w.hpre().div1().ppre1().div2().ppre2().div1()); // 设置锁相环为 9 x HSE rcc.cfgr .write(|w| w.pllsrc().hse_div_prediv().pllxtpre().div1().pllmul().mul9()); // 设置 flash : two wait states, 启用预读取 flash.acr.write(|w| w.latency().ws2().prftbe().set_bit()); // 启动锁相环 rcc.cr.write(|w| w.pllon().set_bit()); // 等待锁相环锁定 while !rcc.cr.read().pllrdy().bit_is_set() {} // 使用锁相环输出作为 SYSCLK rcc.cfgr.write(|w| w.sw().pll()); // 等待 SYSCLK 切换为锁相环 while !rcc.cfgr.read().sws().is_pll() {} }
/* * Copyright 2020 Fluence Labs Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use super::{FunctionRouter, SwarmEventType}; use faas_api::ProtocolMessage; use std::error::Error; use std::task::{Context, Poll}; use libp2p::{ core::{ connection::{ConnectedPoint, ConnectionId, ListenerId}, either::EitherOutput, Multiaddr, }, kad::{record::store::MemoryStore, Kademlia, KademliaEvent}, swarm::{ IntoProtocolsHandler, IntoProtocolsHandlerSelect, NetworkBehaviour, NetworkBehaviourAction, NetworkBehaviourEventProcess, OneShotHandler, PollParameters, ProtocolsHandler, }, PeerId, }; impl NetworkBehaviour for FunctionRouter { type ProtocolsHandler = IntoProtocolsHandlerSelect< OneShotHandler<ProtocolMessage, ProtocolMessage, ProtocolMessage>, <Kademlia<MemoryStore> as NetworkBehaviour>::ProtocolsHandler, >; type OutEvent = (); fn new_handler(&mut self) -> Self::ProtocolsHandler { IntoProtocolsHandler::select(Default::default(), self.kademlia.new_handler()) } fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec<Multiaddr> { log::info!("addresses_of_peer {}", peer_id); self.kademlia.addresses_of_peer(peer_id) } fn inject_connected(&mut self, peer_id: &PeerId) { log::debug!("{} got inject_connected {}", self.config.peer_id, peer_id); self.connected(peer_id.clone()); self.kademlia.inject_connected(peer_id); } fn inject_disconnected(&mut self, peer_id: &PeerId) { log::debug!( "{} got inject_disconnected {}", self.config.peer_id, peer_id ); self.disconnected(peer_id); self.kademlia.inject_disconnected(peer_id); } fn inject_connection_established(&mut self, p: &PeerId, i: &ConnectionId, c: &ConnectedPoint) { #[rustfmt::skip] log::debug!("{} got connection_established {} {:?} {:?}", self.config.peer_id, p, i, c); self.kademlia.inject_connection_established(p, i, c); } fn inject_connection_closed(&mut self, p: &PeerId, i: &ConnectionId, c: &ConnectedPoint) { #[rustfmt::skip] log::debug!("{} got connection_closed {} {:?} {:?}", self.config.peer_id, p, i, c); self.kademlia.inject_connection_closed(p, i, c) } fn inject_event( &mut self, source: PeerId, connection_id: ConnectionId, event: <<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent, ) { use EitherOutput::{First, Second}; match event { First(ProtocolMessage::FunctionCall(call)) => { #[rustfmt::skip] log::info!("{} got FunctionCall! from {} {:?}", self.config.peer_id, source, call); self.call(call) } Second(kademlia_event) => { log::debug!( "{} got Kademlia event: {:?}", self.config.peer_id, kademlia_event ); #[rustfmt::skip] self.kademlia.inject_event(source, connection_id, kademlia_event); } _ => {} } } fn inject_addr_reach_failure(&mut self, p: Option<&PeerId>, a: &Multiaddr, e: &dyn Error) { self.kademlia.inject_addr_reach_failure(p, a, e); } fn inject_dial_failure(&mut self, peer_id: &PeerId) { // TODO: clear connected_peers on inject_listener_closed? self.disconnected(peer_id); self.kademlia.inject_dial_failure(peer_id); } fn inject_new_listen_addr(&mut self, a: &Multiaddr) { self.kademlia.inject_new_listen_addr(a) } fn inject_expired_listen_addr(&mut self, a: &Multiaddr) { self.kademlia.inject_expired_listen_addr(a) } fn inject_new_external_addr(&mut self, a: &Multiaddr) { self.kademlia.inject_new_external_addr(a) } fn inject_listener_error(&mut self, i: ListenerId, e: &(dyn Error + 'static)) { self.kademlia.inject_listener_error(i, e) } fn inject_listener_closed(&mut self, i: ListenerId, reason: Result<(), &std::io::Error>) { self.kademlia.inject_listener_closed(i, reason) } fn poll( &mut self, cx: &mut Context<'_>, params: &mut impl PollParameters, ) -> Poll<SwarmEventType> { use NetworkBehaviourAction::*; use NetworkBehaviourEventProcess as NBEP; if let Some(event) = self.events.pop_front() { return Poll::Ready(event); } // TODO: would be nice to generate that with macro loop { match self.kademlia.poll(cx, params) { Poll::Ready(GenerateEvent(event)) => NBEP::inject_event(self, event), Poll::Ready(NotifyHandler { peer_id, event, handler, }) => { return Poll::Ready(NotifyHandler { peer_id, event: EitherOutput::Second(event), handler, }) } Poll::Ready(DialAddress { address }) => { return Poll::Ready(DialAddress { address }) } Poll::Ready(ReportObservedAddr { address }) => { return Poll::Ready(ReportObservedAddr { address }) } Poll::Ready(DialPeer { peer_id, condition }) => { return Poll::Ready(DialPeer { peer_id, condition }) } Poll::Pending => break, } } Poll::Pending } } impl libp2p::swarm::NetworkBehaviourEventProcess<KademliaEvent> for FunctionRouter { fn inject_event(&mut self, event: KademliaEvent) { use libp2p::kad::QueryResult::{GetClosestPeers, GetRecord, PutRecord}; use libp2p::kad::{GetClosestPeersError, GetClosestPeersOk}; use KademliaEvent::QueryResult; log::debug!("Kademlia inject: {:?}", event); match event { QueryResult { result, .. } => match result { GetClosestPeers(result) => { let (key, peers) = match result { Ok(GetClosestPeersOk { key, peers }) => (key, peers), Err(GetClosestPeersError::Timeout { key, peers }) => (key, peers), }; self.found_closest(key, peers); } GetRecord(result) => self.name_resolved(result), PutRecord(Err(result)) => self.name_publish_failed(result), _ => {} }, _ => {} }; } }
extern crate regex; use std::collections::VecDeque; use std::collections::HashSet; use std::collections::HashMap; fn main() { let mut input = part1_input(); println!("{:?}", input.ring); for _ in 0..100 { input.do_move(); // println!("{:?}", input.ring); } println!("After 100 moves: {:?}", input.ring); let input2 = part2_input(); let mut circle = EfficientCircle::from_values(input2.ring.iter().map(|i| *i).collect()); let mut current_cup = *input.ring.front().unwrap(); for i in 0..10_000_000 { if i % 100_000 == 0 { println!("{} iterations", i); } current_cup = circle.next_current_cup(current_cup); } println!("After 10m moves: {:?} and {:?}", circle.cups.get(&1), circle.cups.get(circle.cups.get(&1).unwrap())); } struct InputData { max: usize, ring: VecDeque<usize>, } struct EfficientCircle { max: usize, cups: HashMap<usize, usize> } impl EfficientCircle { fn from_values(values: Vec<usize>) -> EfficientCircle { let mut cups = HashMap::new(); cups.insert(*values.last().unwrap(), values[0]); for i in 0..values.len() - 1 { cups.insert(values[i], values[i + 1]); } EfficientCircle { max: values.iter().max().map(|i| *i).unwrap(), cups: cups, } } fn next_current_cup(&mut self, current_cup: usize) -> usize { let first_cup = *self.cups.get(&current_cup).unwrap(); let second_cup = *self.cups.get(&first_cup).unwrap(); let third_cup = *self.cups.get(&second_cup).unwrap(); let fourth_cup = *self.cups.get(&third_cup).unwrap(); let next_cup = self.next_cup( current_cup, &vec![first_cup, second_cup, third_cup], ); let after_cup = *self.cups.get(&next_cup).unwrap(); self.cups.insert(current_cup, fourth_cup); self.cups.insert(next_cup, first_cup); self.cups.insert(third_cup, after_cup); fourth_cup } fn next_cup(&self, current_cup: usize, picked_up_cups: &Vec<usize>) -> usize { let cups_to_move_set: HashSet<_> = picked_up_cups.iter().map(|i| *i).collect(); let mut cup_to_place_after = current_cup - 1; if cup_to_place_after == 0 { cup_to_place_after = self.max; } while cups_to_move_set.contains(&cup_to_place_after) { cup_to_place_after -= 1; if cup_to_place_after == 0 { cup_to_place_after = self.max; } } cup_to_place_after } } impl InputData { fn do_move(&mut self) { let mut work_space = VecDeque::new(); let current_cup_num = self.ring.pop_front().unwrap(); work_space.push_back(current_cup_num); let cups_to_move = self.pick_up(); let cup_to_place_after = self.next_cup(current_cup_num, &cups_to_move); let mut next_cup = self.ring.pop_front().unwrap(); work_space.push_back(next_cup); while next_cup != cup_to_place_after { next_cup = self.ring.pop_front().unwrap(); work_space.push_back(next_cup); } cups_to_move.iter().rev().for_each(|i| { self.ring.push_front(*i); }); work_space.iter().rev().for_each(|i| { self.ring.push_front(*i); }); self.ring.rotate_left(1); } fn pick_up(&mut self) -> Vec<usize> { vec![ self.ring.pop_front().unwrap(), self.ring.pop_front().unwrap(), self.ring.pop_front().unwrap(), ] } fn next_cup(&self, current_cup: usize, picked_up_cups: &Vec<usize>) -> usize { let cups_to_move_set: HashSet<_> = picked_up_cups.iter().map(|i| *i).collect(); let mut cup_to_place_after = current_cup - 1; if cup_to_place_after == 0 { cup_to_place_after = self.max; } while cups_to_move_set.contains(&cup_to_place_after) { cup_to_place_after -= 1; if cup_to_place_after == 0 { cup_to_place_after = self.max; } } cup_to_place_after } } fn part2_input() -> InputData { let mut input = part1_input(); for i in 10..=1_000_000 { input.ring.push_back(i); } input.max = 1_000_000; input } fn part1_input() -> InputData { let deque = vec![6, 2, 4, 3, 9, 7, 1, 5, 8].iter().map(|i| *i).collect(); InputData { max: 9, ring: deque, } }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::hash_map::Entry; use std::collections::HashMap; use std::collections::HashSet; use common_ast::ast::Expr; use common_ast::ast::GroupBy; use common_ast::ast::Literal; use common_ast::ast::SelectTarget; use common_exception::ErrorCode; use common_exception::Result; use common_expression::types::DataType; use common_expression::types::NumberDataType; use itertools::Itertools; use super::prune_by_children; use crate::binder::scalar::ScalarBinder; use crate::binder::select::SelectList; use crate::binder::Binder; use crate::binder::ColumnBinding; use crate::binder::Visibility; use crate::optimizer::SExpr; use crate::plans::Aggregate; use crate::plans::AggregateFunction; use crate::plans::AggregateMode; use crate::plans::AndExpr; use crate::plans::BoundColumnRef; use crate::plans::CastExpr; use crate::plans::ComparisonExpr; use crate::plans::EvalScalar; use crate::plans::FunctionCall; use crate::plans::NotExpr; use crate::plans::OrExpr; use crate::plans::ScalarExpr; use crate::plans::ScalarItem; use crate::BindContext; use crate::IndexType; use crate::MetadataRef; #[derive(Default, Clone, PartialEq, Eq, Debug)] pub struct AggregateInfo { /// Aggregation functions pub aggregate_functions: Vec<ScalarItem>, /// Arguments of aggregation functions pub aggregate_arguments: Vec<ScalarItem>, /// Group items of aggregation pub group_items: Vec<ScalarItem>, /// Output columns of aggregation, including group items and aggregate functions. pub output_columns: Vec<ColumnBinding>, /// Mapping: (aggregate function display name) -> (index of agg func in `aggregate_functions`) /// This is used to find a aggregate function in current context. pub aggregate_functions_map: HashMap<String, usize>, /// Mapping: (group item) -> (index of group item in `group_items`) /// This is used to check if a scalar expression is a group item. /// For example, `SELECT count(*) FROM t GROUP BY a+1 HAVING a+1+1`. /// The group item `a+1` is involved in `a+1+1`, so it's a valid `HAVING`. /// We will check the validity by lookup this map with display name. pub group_items_map: HashMap<ScalarExpr, usize>, /// Index for virtual column `grouping_id`. It's valid only if `grouping_sets` is not empty. pub grouping_id_column: Option<ColumnBinding>, /// Each grouping set is a list of column indices in `group_items`. pub grouping_sets: Vec<Vec<IndexType>>, } pub(super) struct AggregateRewriter<'a> { pub bind_context: &'a mut BindContext, pub metadata: MetadataRef, } impl<'a> AggregateRewriter<'a> { pub fn new(bind_context: &'a mut BindContext, metadata: MetadataRef) -> Self { Self { bind_context, metadata, } } pub fn visit(&mut self, scalar: &ScalarExpr) -> Result<ScalarExpr> { match scalar { ScalarExpr::BoundColumnRef(_) => Ok(scalar.clone()), ScalarExpr::BoundInternalColumnRef(_) => Ok(scalar.clone()), ScalarExpr::ConstantExpr(_) => Ok(scalar.clone()), ScalarExpr::AndExpr(scalar) => Ok(AndExpr { left: Box::new(self.visit(&scalar.left)?), right: Box::new(self.visit(&scalar.right)?), } .into()), ScalarExpr::OrExpr(scalar) => Ok(OrExpr { left: Box::new(self.visit(&scalar.left)?), right: Box::new(self.visit(&scalar.right)?), } .into()), ScalarExpr::NotExpr(scalar) => Ok(NotExpr { argument: Box::new(self.visit(&scalar.argument)?), } .into()), ScalarExpr::ComparisonExpr(scalar) => Ok(ComparisonExpr { op: scalar.op.clone(), left: Box::new(self.visit(&scalar.left)?), right: Box::new(self.visit(&scalar.right)?), } .into()), ScalarExpr::FunctionCall(func) => { if func.func_name.eq_ignore_ascii_case("grouping") { return self.replace_grouping(func); } let new_args = func .arguments .iter() .map(|arg| self.visit(arg)) .collect::<Result<Vec<_>>>()?; Ok(FunctionCall { span: func.span, func_name: func.func_name.clone(), params: func.params.clone(), arguments: new_args, } .into()) } ScalarExpr::CastExpr(cast) => Ok(CastExpr { span: cast.span, is_try: cast.is_try, argument: Box::new(self.visit(&cast.argument)?), target_type: cast.target_type.clone(), } .into()), // TODO(leiysky): should we recursively process subquery here? ScalarExpr::SubqueryExpr(_) => Ok(scalar.clone()), ScalarExpr::AggregateFunction(agg_func) => self.replace_aggregate_function(agg_func), ScalarExpr::WindowFunction(_) => Err(ErrorCode::SemanticError( "bind aggregate functions should not reach to window functions.", )), } } /// Replace the arguments of aggregate function with a BoundColumnRef, and /// add the replaced aggregate function and the arguments into `AggregateInfo`. fn replace_aggregate_function(&mut self, aggregate: &AggregateFunction) -> Result<ScalarExpr> { let agg_info = &mut self.bind_context.aggregate_info; let mut replaced_args: Vec<ScalarExpr> = Vec::with_capacity(aggregate.args.len()); for (i, arg) in aggregate.args.iter().enumerate() { let name = format!("{}_arg_{}", &aggregate.func_name, i); if let ScalarExpr::BoundColumnRef(column_ref) = arg { replaced_args.push(column_ref.clone().into()); agg_info.aggregate_arguments.push(ScalarItem { index: column_ref.column.index, scalar: arg.clone(), }); } else { let index = self .metadata .write() .add_derived_column(name.clone(), arg.data_type()?); // Generate a ColumnBinding for each argument of aggregates let column_binding = ColumnBinding { database_name: None, table_name: None, // TODO(leiysky): use a more reasonable name, since aggregate arguments // can not be referenced, the name is only for debug column_name: name, index, data_type: Box::new(arg.data_type()?), visibility: Visibility::Visible, }; replaced_args.push( BoundColumnRef { span: arg.span(), column: column_binding.clone(), } .into(), ); agg_info.aggregate_arguments.push(ScalarItem { index, scalar: arg.clone(), }); } } let index = self.metadata.write().add_derived_column( aggregate.display_name.clone(), *aggregate.return_type.clone(), ); let replaced_agg = AggregateFunction { display_name: aggregate.display_name.clone(), func_name: aggregate.func_name.clone(), distinct: aggregate.distinct, params: aggregate.params.clone(), args: replaced_args, return_type: aggregate.return_type.clone(), }; agg_info.aggregate_functions.push(ScalarItem { scalar: replaced_agg.clone().into(), index, }); agg_info.aggregate_functions_map.insert( replaced_agg.display_name.clone(), agg_info.aggregate_functions.len() - 1, ); Ok(replaced_agg.into()) } fn replace_grouping(&mut self, function: &FunctionCall) -> Result<ScalarExpr> { let agg_info = &mut self.bind_context.aggregate_info; if agg_info.grouping_id_column.is_none() { return Err(ErrorCode::SemanticError( "grouping can only be called in GROUP BY GROUPING SETS clauses", )); } let grouping_id_column = agg_info.grouping_id_column.clone().unwrap(); // Rewrite the args to params. // The params are the index offset in `grouping_id`. // Here is an example: // If the query is `select grouping(b, a) from group by grouping sets ((a, b), (a));` // The group-by items are: [a, b]. // The group ids will be (a: 0, b: 1): // ba -> 00 -> 0 // _a -> 01 -> 1 // grouping(b, a) will be rewritten to grouping<1, 0>(grouping_id). let mut replaced_params = Vec::with_capacity(function.arguments.len()); for arg in &function.arguments { if let Some(index) = agg_info.group_items_map.get(arg) { replaced_params.push(*index); } else { return Err(ErrorCode::BadArguments( "Arguments of grouping should be group by expressions", )); } } let replaced_func = FunctionCall { span: function.span, func_name: function.func_name.clone(), params: replaced_params, arguments: vec![ScalarExpr::BoundColumnRef(BoundColumnRef { span: function.span, column: grouping_id_column, })], }; Ok(replaced_func.into()) } } impl Binder { /// Analyze aggregates in select clause, this will rewrite aggregate functions. /// See `AggregateRewriter` for more details. pub(crate) fn analyze_aggregate_select( &mut self, bind_context: &mut BindContext, select_list: &mut SelectList, ) -> Result<()> { for item in select_list.items.iter_mut() { let mut rewriter = AggregateRewriter::new(bind_context, self.metadata.clone()); let new_scalar = rewriter.visit(&item.scalar)?; item.scalar = new_scalar; } Ok(()) } /// We have supported three kinds of `group by` items: /// /// - Index, a integral literal, e.g. `GROUP BY 1`. It choose the 1st item in select as /// group item. /// - Alias, the aliased expressions specified in `SELECT` clause, e.g. column `b` in /// `SELECT a as b, COUNT(a) FROM t GROUP BY b`. /// - Scalar expressions that can be evaluated in current scope(doesn't contain aliases), e.g. /// column `a` and expression `a+1` in `SELECT a as b, COUNT(a) FROM t GROUP BY a, a+1`. pub async fn analyze_group_items<'a>( &mut self, bind_context: &mut BindContext, select_list: &SelectList<'a>, group_by: &GroupBy, ) -> Result<()> { let mut available_aliases = vec![]; // Extract available aliases from `SELECT` clause, for item in select_list.items.iter() { if let SelectTarget::AliasedExpr { alias: Some(_), .. } = item.select_target { let column = if let ScalarExpr::BoundColumnRef(column_ref) = &item.scalar { let mut column = column_ref.column.clone(); column.column_name = item.alias.clone(); column } else { self.create_column_binding( None, None, item.alias.clone(), item.scalar.data_type()?, ) }; available_aliases.push((column, item.scalar.clone())); } } match group_by { GroupBy::Normal(exprs) => { self.resolve_group_items( bind_context, select_list, exprs, &available_aliases, false, &mut vec![], ) .await } GroupBy::GroupingSets(sets) => { self.resolve_grouping_sets(bind_context, select_list, sets, &available_aliases) .await } // TODO: avoid too many clones. GroupBy::Rollup(exprs) => { // ROLLUP (a,b,c) => GROUPING SETS ((a,b,c), (a,b), (a), ()) let mut sets = Vec::with_capacity(exprs.len() + 1); for i in (0..=exprs.len()).rev() { sets.push(exprs[0..i].to_vec()); } self.resolve_grouping_sets(bind_context, select_list, &sets, &available_aliases) .await } GroupBy::Cube(exprs) => { // CUBE (a,b) => GROUPING SETS ((a,b),(a),(b),()) // All subsets let sets = (0..=exprs.len()) .flat_map(|count| exprs.clone().into_iter().combinations(count)) .collect::<Vec<_>>(); self.resolve_grouping_sets(bind_context, select_list, &sets, &available_aliases) .await } } } pub(super) async fn bind_aggregate( &mut self, bind_context: &mut BindContext, child: SExpr, ) -> Result<SExpr> { // Enter in_grouping state bind_context.in_grouping = true; // Build a ProjectPlan, which will produce aggregate arguments and group items let agg_info = &bind_context.aggregate_info; let mut scalar_items: Vec<ScalarItem> = Vec::with_capacity(agg_info.aggregate_arguments.len() + agg_info.group_items.len()); for arg in agg_info.aggregate_arguments.iter() { scalar_items.push(arg.clone()); } for item in agg_info.group_items.iter() { scalar_items.push(item.clone()); } let mut new_expr = child; if !scalar_items.is_empty() { let eval_scalar = EvalScalar { items: scalar_items, }; new_expr = SExpr::create_unary(eval_scalar.into(), new_expr); } let aggregate_plan = Aggregate { mode: AggregateMode::Initial, group_items: bind_context.aggregate_info.group_items.clone(), aggregate_functions: bind_context.aggregate_info.aggregate_functions.clone(), from_distinct: false, limit: None, grouping_sets: agg_info.grouping_sets.clone(), grouping_id_index: agg_info .grouping_id_column .as_ref() .map(|g| g.index) .unwrap_or(0), }; new_expr = SExpr::create_unary(aggregate_plan.into(), new_expr); Ok(new_expr) } async fn resolve_grouping_sets( &mut self, bind_context: &mut BindContext, select_list: &SelectList<'_>, sets: &[Vec<Expr>], available_aliases: &[(ColumnBinding, ScalarExpr)], ) -> Result<()> { let mut grouping_sets = Vec::with_capacity(sets.len()); for set in sets { self.resolve_group_items( bind_context, select_list, set, available_aliases, true, &mut grouping_sets, ) .await?; } let agg_info = &mut bind_context.aggregate_info; // `grouping_sets` stores formatted `ScalarExpr` for each grouping set. let grouping_sets = grouping_sets .into_iter() .map(|set| { let mut set = set .into_iter() .map(|s| { let offset = *agg_info.group_items_map.get(&s).unwrap(); agg_info.group_items[offset].index }) .collect::<Vec<_>>(); // Grouping sets with the same items should be treated as the same. set.sort(); set }) .collect::<Vec<_>>(); let grouping_sets = grouping_sets.into_iter().unique().collect(); agg_info.grouping_sets = grouping_sets; // Add a virtual column `_grouping_id` to group items. let grouping_id_column = self.create_column_binding( None, None, "_grouping_id".to_string(), DataType::Number(NumberDataType::UInt32), ); let index = grouping_id_column.index; agg_info.grouping_id_column = Some(grouping_id_column.clone()); agg_info.group_items_map.insert( ScalarExpr::BoundColumnRef(BoundColumnRef { span: None, column: grouping_id_column.clone(), }), agg_info.group_items.len(), ); agg_info.group_items.push(ScalarItem { index, scalar: ScalarExpr::BoundColumnRef(BoundColumnRef { span: None, column: grouping_id_column, }), }); Ok(()) } async fn resolve_group_items( &mut self, bind_context: &mut BindContext, select_list: &SelectList<'_>, group_by: &[Expr], available_aliases: &[(ColumnBinding, ScalarExpr)], collect_grouping_sets: bool, grouping_sets: &mut Vec<Vec<ScalarExpr>>, ) -> Result<()> { if collect_grouping_sets { grouping_sets.push(Vec::with_capacity(group_by.len())); } // Resolve group items with `FROM` context. Since the alias item can not be resolved // from the context, we can detect the failure and fallback to resolving with `available_aliases`. for expr in group_by.iter() { // If expr is a number literal, then this is a index group item. if let Expr::Literal { lit: Literal::UInt64(index), .. } = expr { let (scalar, alias) = Self::resolve_index_item(expr, *index, select_list)?; if let Entry::Vacant(entry) = bind_context .aggregate_info .group_items_map .entry(scalar.clone()) { // Add group item if it's not duplicated let column_binding = if let ScalarExpr::BoundColumnRef(ref column_ref) = scalar { column_ref.column.clone() } else { self.create_column_binding(None, None, alias, scalar.data_type()?) }; bind_context.aggregate_info.group_items.push(ScalarItem { scalar: scalar.clone(), index: column_binding.index, }); entry.insert(bind_context.aggregate_info.group_items.len() - 1); } if collect_grouping_sets && !grouping_sets.last().unwrap().contains(&scalar) { grouping_sets.last_mut().unwrap().push(scalar); } continue; } // Resolve scalar item and alias item let mut scalar_binder = ScalarBinder::new( bind_context, self.ctx.clone(), &self.name_resolution_ctx, self.metadata.clone(), &[], ); let (scalar_expr, _) = scalar_binder .bind(expr) .await .or_else(|e| Self::resolve_alias_item(bind_context, expr, available_aliases, e))?; if collect_grouping_sets && !grouping_sets.last().unwrap().contains(&scalar_expr) { grouping_sets.last_mut().unwrap().push(scalar_expr.clone()); } if bind_context .aggregate_info .group_items_map .get(&scalar_expr) .is_some() { // The group key is duplicated continue; } let group_item_name = format!("{:#}", expr); let index = if let ScalarExpr::BoundColumnRef(BoundColumnRef { column: ColumnBinding { index, .. }, .. }) = &scalar_expr { *index } else { self.metadata .write() .add_derived_column(group_item_name.clone(), scalar_expr.data_type()?) }; bind_context.aggregate_info.group_items.push(ScalarItem { scalar: scalar_expr.clone(), index, }); bind_context.aggregate_info.group_items_map.insert( scalar_expr, bind_context.aggregate_info.group_items.len() - 1, ); } // If it's `GROUP BY GROUPING SETS`, ignore the optimization below. if collect_grouping_sets { return Ok(()); } // Remove dependent group items, group by a, f(a, b), f(a), b ---> group by a,b let mut results = vec![]; for item in bind_context.aggregate_info.group_items.iter() { let columns: HashSet<ScalarExpr> = bind_context .aggregate_info .group_items .iter() .filter(|p| p.scalar != item.scalar) .map(|p| p.scalar.clone()) .collect(); if prune_by_children(&item.scalar, &columns) { continue; } results.push(item.clone()); } bind_context.aggregate_info.group_items_map.clear(); for (i, item) in results.iter().enumerate() { bind_context .aggregate_info .group_items_map .insert(item.scalar.clone(), i); } bind_context.aggregate_info.group_items = results; Ok(()) } fn resolve_index_item( expr: &Expr, index: u64, select_list: &SelectList, ) -> Result<(ScalarExpr, String)> { // Convert to zero-based index debug_assert!(index > 0); let index = index as usize - 1; if index >= select_list.items.len() { return Err(ErrorCode::SemanticError(format!( "GROUP BY position {} is not in select list", index + 1 )) .set_span(expr.span())); } let item = select_list .items .get(index) .ok_or_else(|| ErrorCode::Internal("Should not fail"))?; let scalar = item.scalar.clone(); let alias = item.alias.clone(); Ok((scalar, alias)) } fn resolve_alias_item( bind_context: &mut BindContext, expr: &Expr, available_aliases: &[(ColumnBinding, ScalarExpr)], original_error: ErrorCode, ) -> Result<(ScalarExpr, DataType)> { let mut result: Vec<usize> = vec![]; // If cannot resolve group item, then try to find an available alias for (i, (column_binding, _)) in available_aliases.iter().enumerate() { // Alias of the select item let col_name = column_binding.column_name.as_str(); if let Expr::ColumnRef { column, database: None, table: None, .. } = expr { if col_name.eq_ignore_ascii_case(column.name.as_str()) { result.push(i); } } } if result.is_empty() { Err(original_error) } else if result.len() > 1 { Err( ErrorCode::SemanticError(format!("GROUP BY \"{}\" is ambiguous", expr)) .set_span(expr.span()), ) } else { let (column_binding, scalar) = available_aliases[result[0]].clone(); // We will add the alias to BindContext, so we can reference it // in `HAVING` and `ORDER BY` clause. bind_context.columns.push(column_binding.clone()); let index = column_binding.index; bind_context.aggregate_info.group_items.push(ScalarItem { scalar: scalar.clone(), index, }); bind_context.aggregate_info.group_items_map.insert( scalar.clone(), bind_context.aggregate_info.group_items.len() - 1, ); // Add a mapping (alias -> scalar), so we can resolve the alias later let column_ref: ScalarExpr = BoundColumnRef { span: scalar.span(), column: column_binding, } .into(); bind_context.aggregate_info.group_items_map.insert( column_ref, bind_context.aggregate_info.group_items.len() - 1, ); Ok((scalar.clone(), scalar.data_type()?)) } } }
use yew::prelude::*; use yew::{InputData}; use js_sys::{Date}; use yew::services::websocket::{WebSocketService, WebSocketStatus, WebSocketTask}; use yew::format::Json; use anyhow::Error; use yew::services::ConsoleService; enum Msg { WsConnect, Received(Result<String, Error>), Open, Disconnect, PostMsg, UpdateMsgValue(String) } struct Message { text: String, date: String } struct Model { // `ComponentLink` is like a reference to a component. // It can be used to send messages to the component ws: Option<WebSocketTask>, link: ComponentLink<Self>, value: String, messages: Vec<Message> } impl Component for Model { type Message = Msg; type Properties = (); fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self { Self { ws: None, link, value: String::from(""), messages: vec![] } } fn update(&mut self, msg: Self::Message) -> ShouldRender { let mut post_message = |value: &String, is_from_server: bool| { let get_hours = Date::get_hours(&Date::new_0()); let get_minutes = Date::get_minutes(&Date::new_0()); let get_date = Date::get_date(&Date::new_0()); let get_month = Date::get_month(&Date::new_0()); let get_full_year = Date::get_full_year(&Date::new_0()); let time = String::from( get_hours.to_string() + ":" + &get_minutes.to_string() + " / " + &get_date.to_string() + "." + &get_month.to_string() + "." + &get_full_year.to_string() ); // Стандартные методы для отображения времени: std::time::SystemTime и библиотека chrono не работают в данном случае, на данный момент времени. Решние которое работает на данный момент - библиотека js_sys. Также использую String::from для привидения типа JsString в String. let message; if is_from_server { message = Message { text: value.clone(), date: time }; } else { message = Message { text: "your: ".to_string() + &self.value, date: time }; } self.messages.push(message); }; match msg { Msg::WsConnect => { let callback = self.link.callback(|Json(data)| Msg::Received(data)); let callback_notification = self.link.callback(|input| { match input { WebSocketStatus::Opened => { Msg::Open } WebSocketStatus::Closed | WebSocketStatus::Error => { Msg::Disconnect } } }); if self.ws.is_none() { self.ws = Some(WebSocketService::connect_text("ws://127.0.0.1:8081/ws/", callback, callback_notification).unwrap()); } true } Msg::Received(Ok(string)) => { post_message(&string, true); true } Msg::Received(Err(string)) => { /*post_message(&string.to_string(), true);*/ true } Msg::Open => { post_message(&"you joined the chat room".to_string(), true); true } Msg::Disconnect => { post_message(&"disconnect".to_string(), true); self.ws = None; true } Msg::PostMsg => { post_message(&"".to_string(), false); match self.ws { Some(ref mut task) => { task.send(Json(&self.value.clone())); self.value = String::from(""); true } None => { self.value = String::from(""); false } } } Msg::UpdateMsgValue(value) => { self.value = value; true } } } fn change(&mut self, _props: Self::Properties) -> ShouldRender { // Should only return "true" if new properties are different to // previously received properties. // This component has no properties so we will always return "false". false } fn view(&self) -> Html { html! { <div class="container"> <header> <nav> <h2>{"Simple chat"}</h2> <div class="connect_room_wrap"> /*<input type="text" class="text_input" placeholder="input room id" />*/ <button class="squareBtn" onclick=self.link.callback(|_| Msg::WsConnect)>{ if self.ws.is_none() { "connect to room" } else { "disconnect" } }</button> <p>{ "Connected: "}{ !self.ws.is_none() } </p> </div> </nav> </header> <main> <div class="wrap"> <div class="text_section_wrap"> <div class="text_section_head"> <h2>{"Messages:"}</h2> <hr class="margin-vertical-20"/> </div> <div class="text_section_content"> {if self.messages.len() > 0 { html! { {for self.messages.iter().map(|data| { html! { <div class="message"> <div class="padding-20"> <p>{&data.text}</p> </div> <div class="padding-20 messageDate"> <p>{&data.date}</p> </div> </div> } })} } } else { html! { <div class="padding-20"> <p>{"Currently there are no messages"}</p> </div> } }} </div> </div> <div class="form_section"> <textarea class="message_textarea" oninput=self.link.callback(|e: InputData| Msg::UpdateMsgValue(e.value)) placeholder="message" value={self.value.clone()}>{""}</textarea> <button class="squareBtn" onclick=self.link.callback(|_| Msg::PostMsg)>{ "send" }</button> </div> </div> </main> </div> } } } fn main() { yew::start_app::<Model>(); }
//! Timers use crate::time::Hertz; use embedded_hal::timer::{CountDown, Periodic}; // use void::Void; /// Hardware timers pub struct Timer<TIM> { clocks: rcu::Clocks, timer: TIM, } use crate::rcu; use crate::pac::TIMER2; impl Timer<TIMER2> { pub fn timer2<T>(timer2: TIMER2, timeout: T, clocks: rcu::Clocks, apb1: &mut rcu::APB1) -> Self where T: Into<Hertz> { riscv::interrupt::free(|_| { apb1.en().write(|w| w.timer2en().set_bit()); apb1.rst().write(|w| w.timer2rst().set_bit()); apb1.rst().write(|w| w.timer2rst().clear_bit()); }); let mut timer = Timer { clocks, timer: timer2 }; // timer.start(timeout); timer } } // impl CountDown for Timer<TIMER2> { // type Time = Hertz; // fn start<T>(&mut self, count: T) // where // T: Into<Self::Time> // { // unimplemented!() // } // fn wait(&mut self) -> nb::Result<(), Void> { // unimplemented!() // } // } // impl Periodic for Timer<TIMER2> {}
use crate::{DocBase, VarType}; const DESCRIPTION: &'static str = r#" The exp function of x is e^x, where x is the argument and e is Euler's number. "#; pub fn gen_doc() -> Vec<DocBase> { let fn_doc = DocBase { var_type: VarType::Function, name: "exp", signatures: vec![], description: DESCRIPTION, example: "", returns: "A number representing e^x.", arguments: "", remarks: "", links: "[pow](#fun-pow)", }; vec![fn_doc] }
pub mod windows; /// Check [CLICOLOR] status /// /// - When `true`, ANSI colors are supported and should be used when the program isn't piped, /// similar to [`term_supports_color`] /// - When `false`, don’t output ANSI color escape codes, similar to [`no_color`] /// /// See also: /// - [terminfo](https://crates.io/crates/terminfo) or [term](https://crates.io/crates/term) for /// checking termcaps /// - [termbg](https://crates.io/crates/termbg) for detecting background color /// /// [CLICOLOR]: https://bixense.com/clicolors/ #[inline] pub fn clicolor() -> Option<bool> { let value = std::env::var_os("CLICOLOR")?; Some(value != "0") } /// Check [CLICOLOR_FORCE] status /// /// ANSI colors should be enabled no matter what. /// /// [CLICOLOR_FORCE]: https://bixense.com/clicolors/ #[inline] pub fn clicolor_force() -> bool { let value = std::env::var_os("CLICOLOR_FORCE"); value .as_deref() .unwrap_or_else(|| std::ffi::OsStr::new("0")) != "0" } /// Check [NO_COLOR] status /// /// When `true`, should prevent the addition of ANSI color. /// /// User-level configuration files and per-instance command-line arguments should override /// [NO_COLOR]. A user should be able to export `$NO_COLOR` in their shell configuration file as a /// default, but configure a specific program in its configuration file to specifically enable /// color. /// /// [NO_COLOR]: https://no-color.org/ #[inline] pub fn no_color() -> bool { let value = std::env::var_os("NO_COLOR"); value.as_deref().unwrap_or_else(|| std::ffi::OsStr::new("")) != "" } /// Check `TERM` for color support #[inline] #[cfg(not(windows))] pub fn term_supports_color() -> bool { match std::env::var_os("TERM") { // If TERM isn't set, then we are in a weird environment that // probably doesn't support colors. None => return false, Some(k) => { if k == "dumb" { return false; } } } true } /// Check `TERM` for color support #[inline] #[cfg(windows)] pub fn term_supports_color() -> bool { // On Windows, if TERM isn't set, then we shouldn't automatically // assume that colors aren't allowed. This is unlike Unix environments // where TERM is more rigorously set. if let Some(k) = std::env::var_os("TERM") { if k == "dumb" { return false; } } true } /// Check `TERM` for ANSI color support #[inline] #[cfg(not(windows))] pub fn term_supports_ansi_color() -> bool { term_supports_color() } /// Check `TERM` for ANSI color support #[inline] #[cfg(windows)] pub fn term_supports_ansi_color() -> bool { match std::env::var_os("TERM") { // If TERM isn't set, then we are in a weird environment that // probably doesn't support ansi. None => return false, Some(k) => { // cygwin doesn't seem to support ANSI escape sequences // and instead has its own variety. However, the Windows // console API may be available. if k == "dumb" || k == "cygwin" { return false; } } } true } /// Check [COLORTERM] for truecolor support /// /// [COLORTERM]: https://github.com/termstandard/colors #[inline] pub fn truecolor() -> bool { let value = std::env::var_os("COLORTERM"); let value = value.as_deref().unwrap_or_default(); value == "truecolor" || value == "24bit" } /// Report whether this is running in CI /// /// CI is a common environment where, despite being piped, ansi color codes are supported /// /// This is not as exhaustive as you'd find in a crate like `is_ci` but it should work in enough /// cases. #[inline] pub fn is_ci() -> bool { // Assuming its CI based on presence because who would be setting `CI=false`? // // This makes it easier to all of the potential values when considering our known values: // - Gitlab and Github set it to `true` // - Woodpecker sets it to `woodpecker` std::env::var_os("CI").is_some() }
use bytemuck; use glam::vec2; use shaderc::CompileOptions; use wgpu::{ShaderModuleDescriptor, TextureView}; use winit::event::VirtualKeyCode; use super::{camera::Camera, Vertex, VertexBuffer}; use crate::{ rendering::{Display, PetriEventHandler}, simulation::Simulation, timing::timer::time_func, }; #[repr(C)] #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] struct CameraUniform { u_translation: [f32; 2], u_window_size: [f32; 2], u_zoom: [f32; 2], } impl From<&Camera> for CameraUniform { fn from(cam: &Camera) -> Self { CameraUniform { u_translation: cam.translation.into(), u_window_size: cam.window_size.into(), u_zoom: [cam.zoom; 2], } } } pub struct SimRenderer { uniforms_ubo: wgpu::Buffer, bind_group: wgpu::BindGroup, render_pipeline: wgpu::RenderPipeline, vertex_buffer: VertexBuffer, } impl SimRenderer { pub fn new(display: &Display, _simulation: &mut Simulation) -> Self { let uniforms_buffer_byte_size = std::mem::size_of::<CameraUniform>() as wgpu::BufferAddress; let uniforms_ubo = display.device.create_buffer(&wgpu::BufferDescriptor { label: Some("Uniforms ubo"), size: uniforms_buffer_byte_size, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); let bind_group_layout = display .device .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("Bind group layout"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: wgpu::BufferSize::new(uniforms_buffer_byte_size), }, count: None, }], }); let bind_group = display.device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("Bind group"), layout: &bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(uniforms_ubo.as_entire_buffer_binding()), }], }); let mut options = CompileOptions::new().unwrap(); options.set_optimization_level(shaderc::OptimizationLevel::Performance); let mut compiler = shaderc::Compiler::new().unwrap(); let vert_comp = compiler .compile_into_spirv( include_str!("shaders/particles.vert"), shaderc::ShaderKind::Vertex, "shaders/particles.vert", "main", Some(&options), ) .unwrap(); let frag_comp = compiler .compile_into_spirv( include_str!("shaders/particles.frag"), shaderc::ShaderKind::Fragment, "shaders/particles.frag", "main", Some(&options), ) .unwrap(); let shader_frag = &display.device.create_shader_module(&ShaderModuleDescriptor { label: Some("Fragment shader"), source: wgpu::util::make_spirv(frag_comp.as_binary_u8()), }); let shader_vert = &display.device.create_shader_module(&ShaderModuleDescriptor { label: Some("Vertex shader"), source: wgpu::util::make_spirv(vert_comp.as_binary_u8()), }); // Create render pipeline let render_pipeline_layout = display.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Render Pipeline Layout"), bind_group_layouts: &[&bind_group_layout], push_constant_ranges: &[], }); let render_pipeline = display.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("Render Pipeline"), layout: Some(&render_pipeline_layout), vertex: wgpu::VertexState { module: shader_vert, entry_point: "main", buffers: &[wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Vertex, attributes: &wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x4, 2 => Float32], }], }, fragment: Some(wgpu::FragmentState { module: shader_frag, entry_point: "main", targets: &[wgpu::ColorTargetState { format: display.surface_config.format, blend: Some(wgpu::BlendState::ALPHA_BLENDING), write_mask: wgpu::ColorWrites::ALL, }], }), primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::PointList, strip_index_format: None, front_face: wgpu::FrontFace::Ccw, cull_mode: None, // Setting this to anything other than Fill requires Features::NON_FILL_POLYGON_MODE polygon_mode: wgpu::PolygonMode::Point, // Requires Features::DEPTH_CLAMPING clamp_depth: false, // Requires Features::CONSERVATIVE_RASTERIZATION conservative: false, }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), }); Self { uniforms_ubo, bind_group, render_pipeline, vertex_buffer: VertexBuffer::default(display), } } pub fn render(&mut self, display: &Display, simulation: &Simulation, view: &TextureView) { time_func!(sim_render, render); let cam_uniform = CameraUniform::from(&display.cam); display .queue .write_buffer(&self.uniforms_ubo, 0, bytemuck::cast_slice(&[cam_uniform])); let mut encoder = display.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Render Encoder"), }); let n_vertices = self.vertex_buffer.update(display, simulation); { // Set up render pass and associate the render pipeline we made let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Render Pass"), color_attachments: &[wgpu::RenderPassColorAttachment { view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0, }), store: true, }, }], depth_stencil_attachment: None, }); render_pass.set_pipeline(&self.render_pipeline); render_pass.set_vertex_buffer(0, self.vertex_buffer.buf.slice(..)); render_pass.set_bind_group(0, &self.bind_group, &[]); render_pass.draw(0..n_vertices, 0..1); } // Submit will accept anything that implements IntoIter // Submits the command buffer display.queue.submit(std::iter::once(encoder.finish())); } } impl PetriEventHandler for SimRenderer { fn handle_resize( &mut self, display: &mut Display, _simulation: &mut Simulation, size: &winit::dpi::PhysicalSize<u32>, ) { display.cam.resize(size.width as _, size.height as _); } fn handle_scroll(&mut self, display: &mut Display, _simulation: &mut Simulation, delta: &f32) { display.cam.zoom *= 1.0 + delta.signum() * 0.1; } fn handle_mouse_move( &mut self, display: &mut Display, _simulation: &mut Simulation, _pos: &winit::dpi::PhysicalPosition<f64>, ) { if display.mouse.buttons[0].held { display.cam.translate_by(display.mouse.delta * vec2(1.0, -1.0)); } } fn handle_keyboard_input( &mut self, display: &mut Display, _simulation: &mut Simulation, input: &winit::event::KeyboardInput, ) { if input.virtual_keycode.is_some() { match input.virtual_keycode.unwrap() { VirtualKeyCode::Left => display.cam.translate_by([1.0, 0.0].into()), VirtualKeyCode::Right => display.cam.translate_by([-1.0, 0.0].into()), VirtualKeyCode::Up => display.cam.translate_by([0.0, -1.0].into()), VirtualKeyCode::Down => display.cam.translate_by([0.0, 1.0].into()), _ => {} } } } }
#![no_std] #[cfg(test)] #[macro_use] extern crate double; #[cfg(test)] #[macro_use] extern crate hamcrest2; extern crate quicksilver; #[macro_use] extern crate num_derive; extern crate futures; extern crate getrandom; extern crate num_traits; #[macro_use] extern crate alloc; mod controlled; mod field; mod gamestate; mod input; mod keybindings; mod lockdelay; mod position; mod random_bag; mod render; mod resources; mod shapes; mod tetromino; mod time; use alloc::boxed::Box; use futures::Async; use gamestate::{GameCondition, GameState}; use quicksilver::{ geom::Vector, input::{ButtonState, Key}, lifecycle::{run, Event, Settings, State, Window}, Result, }; use render::draw_field; use resources::{ResourceFuture, Resources}; use time::{GameClock, PausedClock}; pub struct Game { pub state: GameState, pub screen_size: Vector, pub resources: Resources, } enum GameScreen { Loading(Box<ResourceFuture>), Playing(Game, GameClock), Paused(Game, PausedClock), Won(Game), Lost(Game), Swap, } impl GameScreen { fn evolve(&mut self, window: &Window) { *self = match core::mem::replace(self, GameScreen::Swap) { GameScreen::Loading(mut resource_future) => match resource_future.poll() { Ok(Async::Ready(resources)) => { let (game_state, clock) = GameState::new(); GameScreen::Playing( Game { state: game_state, screen_size: window.screen_size(), resources: resources, }, clock, ) } _ => GameScreen::Loading(resource_future), }, other => other, }; } } struct GameWrapper { // Initialzied on the first loop loading_game: GameScreen, } impl State for GameWrapper { fn new() -> Result<GameWrapper> { Ok(GameWrapper { loading_game: GameScreen::Loading(Box::new(resources::load_resources())), }) } fn draw(&mut self, window: &mut Window) -> Result<()> { match &self.loading_game { GameScreen::Playing(g, _) | GameScreen::Paused(g, _) | GameScreen::Won(g) | GameScreen::Lost(g) => draw_field(window, g), _ => Ok(()), } } fn update(&mut self, window: &mut Window) -> Result<()> { self.loading_game.evolve(window); self.loading_game = match core::mem::replace(&mut self.loading_game, GameScreen::Swap) { GameScreen::Playing(mut game, clock) => { match game.state.update(window.keyboard(), clock.now()) { GameCondition::Won => GameScreen::Won(game), GameCondition::Lost => GameScreen::Lost(game), GameCondition::Playing => GameScreen::Playing(game, clock), } } other => other, }; Ok(()) } fn event(&mut self, event: &Event, _window: &mut Window) -> Result<()> { match event { Event::Key(Key::Escape, ButtonState::Pressed) => { self.loading_game = match core::mem::replace(&mut self.loading_game, GameScreen::Swap) { GameScreen::Playing(g, c) => GameScreen::Paused(g, c.pause()), GameScreen::Paused(g, c) => GameScreen::Playing(g, c.resume()), other => other, }; } _ => (), } Ok(()) } } fn main() { run::<GameWrapper>( "Blocks", Vector::new(800, 600), Settings { update_rate: 1000.0 / 120.0, ..Settings::default() }, ); }
use yaml_rust::YamlEmitter; use serde::Serialize; use frontmatter::parse_and_find_content; use pulldown_cmark::{html, Options, Parser}; use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] pub fn render_markdown(markdown_input: &str) -> String { let options = Options::empty(); let parser = Parser::new_ext(markdown_input, options); let mut html_output = String::new(); html::push_html(&mut html_output, parser); return html_output; } #[derive(Serialize)] pub struct Data { data: serde_json::Value, content: String, } #[wasm_bindgen] pub fn render(markdown_input: &str) -> JsValue { console_error_panic_hook::set_once(); // Helps return errors for debugging let parsed = parse_and_find_content(markdown_input); let (frontmatter, content) = parsed.unwrap(); if frontmatter.is_some() { let mut value = String::new(); let mut emitter = YamlEmitter::new(&mut value); emitter.dump(&frontmatter.unwrap()).unwrap(); let yaml_contents: serde_json::Value = serde_yaml::from_str(&value).unwrap(); let data = Data{data: yaml_contents, content: render_markdown(content)}; return JsValue::from_serde(&data).unwrap(); } else { let yaml_contents: serde_json::Value = serde_json::Value::Null; let data = Data{data: yaml_contents, content: render_markdown(content)}; return JsValue::from_serde(&data).unwrap(); } }
extern crate humansize; use humansize::{format_size, FormatSizeOptions, DECIMAL}; fn main() { // Create a new FormatSizeOptions struct starting from one of the defaults let custom_options = FormatSizeOptions::from(DECIMAL).decimal_places(5); // Then use it println!("{}", format_size(3024usize, custom_options)); }
use std::vec::Vec; pub struct RenderGroup { pub alpha: bool, pub posable: bool, pub specular: String, pub bump1_rep: bool, pub bump2_rep: bool, pub spec1_rep: bool, pub tex_count: i32, pub texture_types: Vec<std::ffi::CString>, } impl RenderGroup { pub fn new(render_group_num: i32) -> RenderGroup { let mut alpha = false; let mut posable = true; let mut specular = "Yes"; let mut bump1_rep = true; let mut bump2_rep = true; let mut spec1_rep = false; let mut tex_count = 6; let mut texture_types = vec!["diffuse", "mask", "mask", "mask", "mask", "mask"]; match render_group_num { 1 => { alpha = false; posable = true; specular = "Yes"; bump1_rep = true; bump2_rep = true; tex_count = 6; texture_types = vec!["diffuse", "lightmap", "bumpmap", "mask", "bump1", "bump2"]; } 2 => { alpha = false; posable = true; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 3; texture_types = vec!["diffuse", "lightmap", "bumpmap"]; } 3 => { alpha = false; posable = true; specular = "No"; bump1_rep = false; bump2_rep = false; tex_count = 2; texture_types = vec!["diffuse", "lightmap"]; } 4 => { alpha = false; posable = true; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 2; texture_types = vec!["diffuse", "bumpmap"]; } 5 => { alpha = false; posable = true; specular = "No"; bump1_rep = false; bump2_rep = false; tex_count = 1; texture_types = vec!["diffuse"]; } 6 => { alpha = true; posable = true; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 2; texture_types = vec!["diffuse", "bumpmap"]; } 7 => { alpha = true; posable = true; specular = "No"; bump1_rep = false; bump2_rep = false; tex_count = 1; texture_types = vec!["diffuse"]; } 8 => { alpha = true; posable = true; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 3; texture_types = vec!["diffuse", "lightmap", "bumpmap"]; } 9 => { alpha = true; posable = true; specular = "No"; bump1_rep = false; bump2_rep = false; tex_count = 2; texture_types = vec!["diffuse", "lightmap"]; } 10 => { alpha = false; posable = true; specular = "No"; bump1_rep = false; bump2_rep = false; tex_count = 1; texture_types = vec!["diffuse"]; } 11 => { alpha = false; posable = false; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 2; texture_types = vec!["diffuse", "bumpmap"]; } 12 => { alpha = true; posable = false; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 2; texture_types = vec!["diffuse", "bumpmap"]; } 13 => { alpha = false; posable = false; specular = "No"; bump1_rep = false; bump2_rep = false; tex_count = 1; texture_types = vec!["diffuse"]; } 14 => { alpha = false; posable = false; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 2; texture_types = vec!["diffuse", "bumpmap"]; } 15 => { alpha = true; posable = false; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 2; texture_types = vec!["diffuse", "bumpmap"]; } 16 => { alpha = false; posable = false; specular = "No"; bump1_rep = false; bump2_rep = false; tex_count = 1; texture_types = vec!["diffuse"]; } 17 => { alpha = false; posable = false; specular = "No"; bump1_rep = false; bump2_rep = false; tex_count = 2; texture_types = vec!["diffuse", "lightmap"]; } 18 => { alpha = true; posable = false; specular = "No"; bump1_rep = false; bump2_rep = false; tex_count = 1; texture_types = vec!["diffuse"]; } 19 => { alpha = true; posable = false; specular = "No"; bump1_rep = false; bump2_rep = false; tex_count = 2; texture_types = vec!["diffuse", "lightmap"]; } 20 => { alpha = true; posable = true; specular = "Yes"; bump1_rep = true; bump2_rep = true; tex_count = 6; texture_types = vec!["diffuse", "lightmap", "bumpmap", "mask", "bump1", "bump2"]; } 21 => { alpha = true; posable = true; specular = "No"; bump1_rep = false; bump2_rep = false; tex_count = 1; texture_types = vec!["diffuse"]; } 22 => { alpha = false; posable = true; specular = "Yes"; bump1_rep = true; bump2_rep = true; tex_count = 7; texture_types = vec![ "diffuse", "lightmap", "bumpmap", "mask", "bump1", "bump2", "specular", ]; } 23 => { alpha = true; posable = true; specular = "Yes"; bump1_rep = true; bump2_rep = true; tex_count = 7; texture_types = vec![ "diffuse", "lightmap", "bumpmap", "mask", "bump1", "bump2", "specular", ]; } 24 => { alpha = false; posable = true; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 4; texture_types = vec!["diffuse", "lightmap", "bumpmap", "specular"]; } 25 => { alpha = true; posable = true; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 4; texture_types = vec!["diffuse", "lightmap", "bumpmap", "specular"]; } 26 => { alpha = false; posable = true; specular = "Yes intensity"; bump1_rep = false; bump2_rep = false; tex_count = 4; texture_types = vec!["diffuse", "bumpmap", "enviroment", "mask"]; } 27 => { alpha = true; posable = true; specular = "Yes intensity"; bump1_rep = false; bump2_rep = false; tex_count = 4; texture_types = vec!["diffuse", "bumpmap", "enviroment", "mask"]; } 28 => { alpha = false; posable = true; specular = "Yes intensity"; bump1_rep = true; bump2_rep = true; tex_count = 6; texture_types = vec!["diffuse", "bumpmap", "mask", "bump1", "bump2", "enviroment"]; } 29 => { alpha = true; posable = true; specular = "Yes intensity"; bump1_rep = true; bump2_rep = true; tex_count = 6; texture_types = vec!["diffuse", "bumpmap", "mask", "bump1", "bump2", "enviroment"]; } 30 => { alpha = false; posable = true; specular = "Yes intensity"; bump1_rep = false; bump2_rep = false; tex_count = 3; texture_types = vec!["diffuse", "bumpmap", "emission"]; } 31 => { alpha = true; posable = true; specular = "Yes intensity"; bump1_rep = false; bump2_rep = false; tex_count = 3; texture_types = vec!["diffuse", "bumpmap", "emission"]; } 32 => { alpha = false; posable = true; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 1; texture_types = vec!["diffuse"]; } 33 => { alpha = true; posable = true; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 1; texture_types = vec!["diffuse"]; } 34 => {} 35 => {} 36 => { alpha = false; posable = true; specular = "Yes intensity"; bump1_rep = true; bump2_rep = false; tex_count = 3; texture_types = vec!["diffuse", "bumpmap", "emission_mini_map"]; } 37 => { alpha = true; posable = true; specular = "Yes intensity"; bump1_rep = true; bump2_rep = false; tex_count = 3; texture_types = vec!["diffuse", "bumpmap", "emission_mini_map"]; } 38 => { alpha = false; posable = true; specular = "Yes intensity"; bump1_rep = true; bump2_rep = false; tex_count = 4; texture_types = vec!["diffuse", "bumpmap", "specular", "emission"]; } 39 => { alpha = true; posable = true; specular = "Yes intensity"; bump1_rep = true; bump2_rep = false; tex_count = 4; texture_types = vec!["diffuse", "bumpmap", "specular", "emission"]; } 40 => { alpha = false; posable = true; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 3; texture_types = vec!["diffuse", "bumpmap", "specular"]; } 41 => { alpha = true; posable = true; specular = "Yes"; bump1_rep = false; bump2_rep = false; tex_count = 3; texture_types = vec!["diffuse", "bumpmap", "specular"]; } 42 => { alpha = false; posable = true; specular = "Yes"; bump1_rep = false; bump2_rep = false; spec1_rep = true; tex_count = 3; texture_types = vec!["diffuse", "bumpmap", "specular"]; } 43 => { alpha = true; posable = true; specular = "Yes"; bump1_rep = false; bump2_rep = false; spec1_rep = true; tex_count = 3; texture_types = vec!["diffuse", "bumpmap", "specular"]; } _ => (), }; RenderGroup { alpha: alpha, posable: posable, specular: specular.to_string(), bump1_rep: bump1_rep, bump2_rep: bump2_rep, spec1_rep: spec1_rep, tex_count: tex_count, texture_types: texture_types .into_iter() .map(|x| { std::ffi::CString::new(x.to_string()).unwrap_or(std::ffi::CString::new("").unwrap()) }) .collect(), } } }
use super::*; use std::collections::HashMap; #[derive(Debug, PartialEq)] pub struct Color { pub gui: String, pub cterm: String, } pub type ColorName = Option<&'static str>; pub type Palette = HashMap<&'static str, Color>; #[derive(Debug)] pub enum HighlightAttr { Nothing, None, Bold, Italic, Underline, Reverse, } #[derive(Debug)] pub struct Highlight { pub name: &'static str, pub fg: ColorName, pub bg: ColorName, pub sp: ColorName, pub attr: HighlightAttr, } macro_rules! highlight { ($name: ident, $fg: expr, $bg: expr, $sp: expr, $attr: ident) => { Highlight { name: stringify!($name), fg: $fg, bg: $bg, sp: $sp, attr: HighlightAttr::$attr, } }; } macro_rules! hi { ($name: ident, -, -, -, -) => { highlight!($name, None, None, None, Nothing) }; ($name: ident, $fg: ident, -, -, -) => { highlight!($name, Some(stringify!($fg)), None, None, Nothing) }; ($name: ident, -, $bg: ident, -, -) => { highlight!($name, None, Some(stringify!($bg)), None, Nothing) }; ($name: ident, -, -, $sp: ident, -) => { highlight!($name, None, None, Some(stringify!($sp)), Nothing) }; ($name: ident, -, -, -, $attr: ident) => { highlight!($name, None, None, None, $attr) }; ($name: ident, $fg: ident, $bg: ident, -, -) => { highlight!( $name, Some(stringify!($fg)), Some(stringify!($bg)), None, Nothing ) }; ($name: ident, $fg: ident, -, -, $attr: ident) => { highlight!($name, Some(stringify!($fg)), None, None, $attr) }; ($name: ident, -, $bg: ident, -, $attr: ident) => { highlight!($name, None, Some(stringify!($bg)), None, $attr) }; ($name: ident, $fg: ident, $bg: ident, -, -) => { highlight!( $name, Some(stringify!($fg)), Some(stringify!($bg)), None, Nothing ) }; ($name: ident, $fg: ident, $bg: ident, -, $attr: ident) => { highlight!( $name, Some(stringify!($fg)), Some(stringify!($bg)), None, $attr ) }; } pub fn get_palette() -> Palette { let mut p = HashMap::new(); macro_rules! def { ($name: ident, $hex: expr) => { assert_eq!( p.insert( stringify!($name), Color { gui: String::from($hex), cterm: conv::to_cterm($hex.to_string()).to_string(), } ), None ); }; } macro_rules! extends { ($parent: ident) => { match p.get(stringify!($parent)) { Some(highlight) => highlight.gui.to_string(), None => panic!(format!("\"{}\" does not exists", stringify!($parent))), } }; ($parent: ident, $h: expr, $s: expr, $v: expr) => { conv::hue(conv::saturate(conv::lighten(extends!($parent), $v), $s), $h) }; } // palettes def!(red, "#dc6f7a"); def!(darkred, extends!(red, 0.0, 0.0, -0.2)); def!(pink, "#b871b8"); def!(darkpink, extends!(pink, 0.0, -0.05, -0.35)); def!(purple, "#929be5"); def!(darkpurple, extends!(purple, 0.0, 0.05, -0.15)); def!(blue, "#589ec6"); def!(darkblue, extends!(blue, 0.0, 0.0, -0.2)); def!(darkestblue, extends!(blue, 0.0, 0.05, -0.48)); def!(cyan, "#59b6b6"); def!(darkcyan, extends!(cyan, 0.0, 0.0, -0.2)); def!(teal, "#73c1a9"); def!(darkteal, extends!(teal, 0.0, 0.0, -0.2)); def!(darkestteal, extends!(teal, 0.0, 0.05, -0.48)); def!(green, "#7cbe8c"); def!(darkgreen, extends!(green, 0.0, -0.05, -0.4)); def!(yellow, "#a8a384"); def!(darkyellow, extends!(yellow, 0.0, -0.15, -0.5)); def!(orange, "#ac8b83"); def!(darkorange, extends!(orange, 0.0, -0.05, -0.2)); // neutral def!(mainfg, "#9ea3c0"); def!(mainbg, "#222433"); def!(weakfg, extends!(mainbg, 0.0, 0.05, 0.35)); def!(weakbg, extends!(mainbg, 0.0, 0.0, 0.1)); def!(emphasisfg, extends!(mainfg, 0.0, 0.0, 0.15)); def!(emphasisbg, extends!(mainbg, 0.0, 0.0, 0.05)); def!(darkfg, extends!(mainbg, 0.0, 0.05, 0.15)); def!(darkbg, extends!(mainbg, 0.0, 0.0, 0.05)); def!(lightfg, extends!(mainfg, 0.0, 0.05, -0.1)); def!(lightbg, extends!(mainbg, 0.0, 0.0, 0.2)); def!(white, "#ffffff"); def!(black, "#000000"); // messages def!(morefg, extends!(teal)); def!(errorbg, extends!(mainbg)); def!(errorfg, extends!(red, 0.0, 0.0, 0.0)); def!(warningbg, extends!(mainbg)); def!(warningfg, extends!(orange, 0.0, 0.0, 0.0)); def!(infobg, extends!(mainbg)); def!(infofg, extends!(teal, 0.0, 0.0, 0.1)); // visual def!(visualbg, extends!(purple, 0.0, 0.2, -0.4)); // linenr def!(linenrfg, extends!(mainbg, 0.0, 0.0, 0.1)); def!(cursorlinebg, extends!(mainbg, 0.0, 0.0, 0.05)); def!(cursorlinenrfg, extends!(linenrfg, 0.0, 0.1, 0.3)); // pmenu def!(pmenubg, extends!(mainbg, 0.0, 0.0, 0.1)); def!(pmenufg, extends!(mainfg, 0.0, 0.0, 0.0)); def!(pmenuselbg, extends!(pmenubg, 0.0, 0.0, 0.1)); def!(pmenuselfg, extends!(mainfg, 0.0, 0.0, 0.0)); def!(pmenubar, extends!(pmenubg, 0.0, 0.0, -0.05)); def!(pmenuthumb, extends!(pmenubg, 0.0, 0.1, 0.2)); // fold def!(foldbg, extends!(mainbg, 0.0, 0.0, 0.1)); def!(foldfg, extends!(mainbg, 0.0, 0.0, 0.4)); // diff def!(diffaddbg, extends!(darkestblue)); def!(diffaddfg, extends!(mainfg, 0.0, 0.0, 0.2)); def!(diffchangebg, extends!(darkestteal)); def!(diffchangefg, extends!(mainfg, 0.0, 0.0, 0.2)); def!(diffdeletebg, extends!(darkpink)); def!(diffdeletefg, extends!(mainfg, 0.0, 0.0, 0.25)); def!(difftextbg, extends!(diffchangebg, 0.0, 0.2, 0.2)); def!(difftextfg, extends!(mainfg, 0.0, 0.0, 0.2)); // status & tab line def!(statuslinebg, extends!(mainbg, 0.0, 0.0, 0.05)); def!(statuslinefg, extends!(statuslinebg, 0.0, -0.05, 0.4)); def!(statuslinencbg, extends!(mainbg, 0.0, -0.03, 0.03)); def!(statuslinencfg, extends!(statuslinencbg, 0.0, 0.0, 0.2)); def!(tablineselbg, extends!(purple)); def!(tablineselfg, extends!(mainbg)); // misc def!(searchbg, extends!(purple, 0.0, 0.2, -0.05)); def!(searchfg, extends!(searchbg, 0.1, -0.1, -0.3)); def!(matchparenbg, extends!(mainbg, 0.1, 0.0, 0.08)); // terminal colors def!(termblack, extends!(mainbg, 0.0, 0.0, -0.1)); def!(termmaroon, extends!(red, 0.0, 0.0, -0.1)); def!(termgreen, extends!(green, 0.0, 0.0, 0.0)); def!(termolive, extends!(yellow, 0.0, 0.0, -0.1)); def!(termnavy, extends!(blue, 0.0, 0.0, -0.1)); def!(termpurple, extends!(purple, 0.0, 0.1, -0.1)); def!(termteal, extends!(teal)); def!(termsilver, extends!(mainfg)); def!(termgray, extends!(weakfg)); def!(termred, extends!(pink)); def!(termlime, extends!(green)); def!(termyellow, extends!(yellow)); def!(termblue, extends!(blue)); def!(termfuchsia, extends!(purple)); def!(termaqua, extends!(cyan)); def!(termwhite, extends!(mainfg)); // defx-icons def!(defxiconbrown, extends!(red, 0.0, 0.2, -0.2)); def!(defxiconaqua, extends!(cyan, 0.0, -0.1, -0.1)); def!(defxiconblue, extends!(blue, 0.0, -0.1, -0.1)); def!(defxicondarkblue, extends!(blue, 0.0, -0.2, -0.25)); def!(defxiconpurple, extends!(darkpurple)); def!(defxiconlightpurple, extends!(purple, 0.0, -0.1, -0.1)); def!(defxiconred, extends!(red, 0.0, -0.0, -0.1)); def!(defxiconbeige, extends!(yellow, 0.0, -0.2, -0.25)); def!(defxiconyellow, extends!(yellow, 0.0, 0.0, -0.1)); def!(defxiconorange, extends!(orange, 0.0, 0.0, 0.1)); def!(defxicondarkorange, extends!(orange, 0.0, 0.1, -0.2)); def!(defxiconpink, extends!(pink, 0.0, 0.0, -0.1)); def!(defxiconsalmon, extends!(pink, 0.0, 0.1, -0.05)); def!(defxicongreen, extends!(green, 0.0, 0.0, -0.15)); def!(defxiconlightgreen, extends!(green, 0.0, 0.1, -0.1)); def!(defxiconwhite, extends!(mainfg, 0.0, 0.0, -0.1)); // lightline def!(xlinebg, extends!(statuslinencbg)); def!(xlinefg, extends!(statuslinencfg)); def!(xlineedgebg, extends!(statuslinebg)); def!(xlineedgefg, extends!(statuslinefg)); def!(xlinegradientbg, extends!(statuslinencbg)); def!(xlinegradientfg, extends!(statuslinencfg)); return p; } pub fn get_highlights() -> Vec<Highlight> { return vec![ // general hi!(Normal, mainfg, mainbg, -, -), hi!(Delimiter, lightfg, -, -, -), hi!(NonText, darkfg, NONE, -, -), hi!(VertSplit, weakbg, NONE, -, None), hi!(LineNr, linenrfg, NONE, -, None), hi!(EndOfBuffer, darkfg, NONE, -, None), hi!(Comment, weakfg, -, -, None), hi!(Cursor, mainbg, mainfg, -, -), hi!(CursorIM, mainbg, mainfg, -, -), hi!(SignColumn, weakfg, NONE, -, -), hi!(ColorColumn, -, cursorlinebg, -, None), hi!(CursorColumn, -, cursorlinebg, -, None), hi!(CursorLine, -, cursorlinebg, -, None), hi!(CursorLineNr, cursorlinenrfg, NONE, -, None), hi!(Conceal, orange, mainbg, -, None), hi!(NormalFloat, mainfg, pmenubg, -, None), hi!(Folded, foldfg, foldbg, -, None), hi!(FoldColumn, linenrfg, NONE, -, None), hi!(MatchParen , -, matchparenbg, -, -), hi!(Directory , yellow, -, -, -), hi!(Underlined , -, -, -, Underline), hi!(String, green, -, -, -), hi!(Statement, purple, -, -, None), hi!(Label, purple, -, -, None), hi!(Function, purple, -, -, None), hi!(Constant, teal, -, -, -), hi!(Boolean, teal, -, -, -), hi!(Number, teal, -, -, -), hi!(Float, teal, -, -, -), hi!(Title, yellow, -, -, Bold), hi!(Keyword, orange, -, -, -), hi!(Identifier, orange, -, -, -), hi!(Exception, yellow, -, -, -), hi!(Type, yellow, -, -, None), hi!(TypeDef, yellow, -, -, None), hi!(PreProc, purple, -, -, -), hi!(Special, pink, -, -, -), hi!(SpecialKey, pink, -, -, -), hi!(SpecialChar, pink, -, -, -), hi!(SpecialComment, pink, -, -, -), hi!(Error, errorfg, errorbg, -, Bold), hi!(ErrorMsg, errorfg, NONE, -, Bold), hi!(WarningMsg, warningfg, -, -, Bold), hi!(MoreMsg, morefg, -, -, -), hi!(Todo, yellow, NONE, -, Bold), hi!(Pmenu, pmenufg, pmenubg, -, -), hi!(PmenuSel, pmenuselfg, pmenuselbg, -, -), hi!(PmenuSbar, -, pmenubar, -, -), hi!(PmenuThumb, -, pmenuthumb, -, -), hi!(Visual, -, visualbg, -, None), hi!(Search, searchfg, searchbg, -, -), hi!(IncSearch, searchfg, searchbg, -, -), hi!(Question, teal, -, -, Bold), hi!(WildMenu, mainbg, purple, -, -), hi!(SpellBad, errorfg, -, -, Underline), hi!(SpellCap, -, -, -, Underline), hi!(SpellLocal, errorfg, -, -, Underline), hi!(SpellRare, yellow, -, -, Underline), hi!(DiffAdd, -, diffaddbg, -, Bold), hi!(DiffChange, -, diffchangebg, -, Bold), hi!(DiffDelete, diffdeletefg, diffdeletebg, -, Bold), hi!(DiffText, -, difftextbg, -, None), hi!(QuickFixLine, mainfg, visualbg, -, -), hi!(StatusLine, statuslinefg, statuslinebg, -, Bold), hi!(StatusLineTerm, statuslinefg, statuslinebg, -, Bold), hi!(StatusLineNC, statuslinencfg, statuslinencbg, -, None), hi!(StatusLineTermNC, statuslinencfg, statuslinencbg, -, None), hi!(TabLine, statuslinefg, statuslinebg, -, None), hi!(TabLineFill, statuslinefg, statuslinebg, -, None), hi!(TabLineSel, tablineselfg, tablineselbg, -, Bold), hi!(qfFileName, teal, -, -, -), hi!(qfLineNr, weakfg, -, -, -), // treesitter // https://github.com/nvim-treesitter/nvim-treesitter hi!(TSConstBuiltin, teal, -, -, -), hi!(TSString, green, -, -, -), hi!(TSStringRegex, green, -, -, -), hi!(TSStringEscape, pink, -, -, -), hi!(TSParameter, purple, -, -, -), hi!(TSParameterReference, purple, -, -, -), hi!(TSField, purple, -, -, -), hi!(TSProperty, purple, -, -, -), hi!(TSConstructor, mainfg, -, -, -), hi!(TSKeyword, pink, -, -, -), hi!(TSType, orange, -, -, -), hi!(TSTypeBuiltin, orange, -, -, -), hi!(TSStructue, pink, -, -, -), hi!(TSInclude, purple, -, -, -), hi!(TSVariableBuiltin, orange, -, -, -), // html hi!(htmlTag, lightfg, -, -, -), hi!(htmlEndTag, lightfg, -, -, -), hi!(htmlSpecialTagName, orange, -, -, -), hi!(htmlArg, lightfg, -, -, -), // json hi!(jsonQuote, lightfg, -, -, -), // yaml hi!(yamlBlockMappingKey, purple, -, -, -), hi!(yamlAnchor, pink, -, -, -), // python hi!(pythonStatement, orange, -, -, -), hi!(pythonBuiltin, cyan, -, -, -), hi!(pythonRepeat, orange, -, -, -), hi!(pythonOperator, orange, -, -, -), hi!(pythonDecorator, pink, -, -, -), hi!(pythonDecoratorName, pink, -, -, -), // zsh hi!(zshVariableDef, purple, -, -, -), hi!(zshFunction, purple, -, -, -), hi!(zshKSHFunction, purple, -, -, -), // C hi!(cPreCondit, orange, -, -, -), hi!(cIncluded, pink, -, -, -), hi!(cStorageClass, orange, -, -, -), // C++ // octol/vim-cpp-enhanced-highlight hi!(cppStructure, pink, -, -, -), hi!(cppSTLnamespace, orange, -, -, -), // C# hi!(csStorage, orange, -, -, -), hi!(csModifier, purple, -, -, -), hi!(csClass, purple, -, -, -), hi!(csClassType, pink, -, -, -), hi!(csNewType, orange, -, -, -), // ruby hi!(rubyConstant, orange, -, -, -), hi!(rubySymbol, purple, -, -, -), hi!(rubyBlockParameter, purple, -, -, -), hi!(rubyClassName, pink, -, -, -), hi!(rubyInstanceVariable, pink, -, -, -), // vim-markdown // https://github.com/plasticboy/vim-markdown hi!(mkdHeading, weakfg, -, -, -), hi!(mkdLink, purple, -, -, -), hi!(mkdCode, purple, -, -, -), hi!(mkdCodeStart , purple, -, -, -), hi!(mkdCodeEnd, purple, -, -, -), hi!(mkdCodeDelimiter, purple, -, -, -), // yats.vim // https://github.com/HerringtonDarkholme/yats.vim hi!(typescriptImport, purple, -, -, -), hi!(typescriptDocRef, weakfg, -, -, Underline), // vim-markdown // https://github.com/plasticboy/vim-markdown hi!(mkdHeading, weakfg, -, -, -), hi!(mkdLink, purple, -, -, -), hi!(mkdCode, purple, -, -, -), hi!(mkdCodeStart , purple, -, -, -), hi!(mkdCodeEnd, purple, -, -, -), hi!(mkdCodeDelimiter, purple, -, -, -), // vim-toml // https://github.com/cespare/vim-toml hi!(tomlTable, purple, -, -, -), // rust.vim // https://github.com/rust-lang/rust.vim hi!(rustModPath, purple, -, -, -), hi!(rustTypedef, purple, -, -, -), hi!(rustStructure, purple, -, -, -), hi!(rustMacro, purple, -, -, -), hi!(rustExternCrate, purple, -, -, -), // vim-graphql // https://github.com/jparise/vim-graphql hi!(graphqlStructure, pink, -, -, -), hi!(graphqlDirective, pink, -, -, -), hi!(graphqlName, purple, -, -, -), hi!(graphqlTemplateString, mainfg, -, -, -), // vimfiler // https://github.com/Shougo/vimfiler.vim hi!(vimfilerOpenedFile, darkpurple, -, -, -), hi!(vimfilerClosedFile, darkpurple, -, -, -), hi!(vimfilerNonMark, teal, -, -, -), hi!(vimfilerLeaf, teal, -, -, -), // defx-icons // https://github.com/kristijanhusak/defx-icons hi!(DefxIconsMarkIcon, darkpurple, -, -, None), hi!(DefxIconsDirectory, darkpurple, -, -, None), hi!(DefxIconsParentDirectory, darkpurple, -, -, None), hi!(DefxIconsSymlinkDirectory, teal, -, -, None), hi!(DefxIconsOpenedTreeIcon, darkpurple, -, -, None), hi!(DefxIconsNestedTreeIcon, darkpurple, -, -, None), hi!(DefxIconsClosedTreeIcon, darkpurple, -, -, None), // defx-git // https://github.com/kristijanhusak/defx-git hi!(Defx_git_Untracked, purple, -, -, None), hi!(Defx_git_Ignored, weakfg, -, -, None), hi!(Defx_git_Unknown, weakfg, -, -, None), hi!(Defx_git_Renamed, diffchangebg, -, -, -), hi!(Defx_git_Modified, diffchangebg, -, -, -), hi!(Defx_git_Unmerged, pink, -, -, -), hi!(Defx_git_Deleted, diffdeletebg, -, -, -), hi!(Defx_git_Staged, teal, -, -, -), // fern.vim // https://github.com/lambdalisue/fern.vim hi!(FernBranchSymbol, darkpurple, -, -, None), hi!(FernBranchText, purple, -, -, None), hi!(FernLeafSymbol, darkteal, -, -, None), hi!(FernLeafText, mainfg, -, -, None), hi!(FernMarked, cyan, -, -, None), // vim-gitgutter // https://github.com/airblade/vim-gitgutter hi!(GitGutterAdd, green, -, -, -), hi!(GitGutterChange, yellow, -, -, -), hi!(GitGutterDelete, pink, -, -, -), hi!(GitGutterChangeDelete, difftextbg, -, -, -), // fugitive.vim // https://github.com/tpope/vim-fugitive hi!(fugitiveHeader, teal, -, -, Bold), // ale // https://github.com/dense-analysis/ale hi!(ALEWarningSign, warningfg, -, -, Bold), hi!(ALEInfoSign, infofg, -, -, None), // coc.nvim // https://github.com/neoclide/coc.nvim hi!(CocErrorSign, errorfg, -, -, Bold), hi!(CocWarningSign, warningfg, -, -, Bold), hi!(CocInfoSign, infofg, -, -, Bold), hi!(CocHintSign, infofg, -, -, Bold), // clever-f.vim // https://github.com/rhysd/clever-f.vim hi!(CleverFChar, searchfg, searchbg, -, Underline), // conflict-marker.vim // https://github.com/rhysd/conflict-marker.vim hi!(ConflictMarkerBegin, -, darkteal, -, Bold), hi!(ConflictMarkerOurs, -, darkestteal, -, None), hi!(ConflictMarkerTheirs, -, darkestblue, -, None), hi!(ConflictMarkerEnd, -, darkblue, -, Bold), hi!(ConflictMarkerSeparator, darkfg, -, -, Bold), // easymotion // https://github.com/easymotion/vim-easymotion hi!(EasyMotionTarget, yellow, -, -, Bold), hi!(EasyMotionShade, weakfg, mainbg, -, -), hi!(EasyMotionIncCursor, mainfg, mainbg, -, -), ]; }
//! A surface is the output of a [`compositor`](crate::compositor). //! //! A surface also implements the [`source`](crate::source) trait, //! meaning you can nest surfaces. //! //! Surfaces can be written to a file. mod surface_2d; pub use surface_2d::Surface2D;
// Draw some multi-colored geometry to the screen // This is a good place to get a feel for the basic structure of a Quicksilver app extern crate quicksilver; use quicksilver::{ Result, geom::{Circle, Line, Rectangle, Transform, Triangle, Vector}, graphics::{Background::Col, Color}, lifecycle::{Settings, State, Window, run}, }; // A unit struct that we're going to use to run the Quicksilver functions // If we wanted to store persistent state, we would put it in here. struct DrawGeometry; impl State for DrawGeometry { // Initialize the struct fn new() -> Result<DrawGeometry> { Ok(DrawGeometry) } fn draw(&mut self, window: &mut Window) -> Result<()> { // Remove any lingering artifacts from the previous frame window.clear(Color::WHITE)?; // Draw a rectangle with a top-left corner at (100, 100) and a width and height of 32 with // a blue background window.draw(&Rectangle::new((100, 100), (32, 32)), Col(Color::BLUE)); // Draw another rectangle, rotated by 45 degrees, with a z-height of 10 window.draw_ex(&Rectangle::new((400, 300), (32, 32)), Col(Color::BLUE), Transform::rotate(45), 10); // Draw a circle with its center at (400, 300) and a radius of 100, with a background of // green window.draw(&Circle::new((400, 300), 100), Col(Color::GREEN)); // Draw a line with a thickness of 2 pixels, a red background, // and a z-height of 5 window.draw_ex( &Line::new((50, 80),(600, 450)).with_thickness(2.0), Col(Color::RED), Transform::IDENTITY, 5 ); // Draw a triangle with a red background, rotated by 45 degrees, and scaled down to half // its size window.draw_ex( &Triangle::new((500, 50), (450, 100), (650, 150)), Col(Color::RED), Transform::rotate(45) * Transform::scale((0.5, 0.5)), 0 ); // We completed with no errors Ok(()) } } // The main isn't that important in Quicksilver: it just serves as an entrypoint into the event // loop fn main() { // Run with DrawGeometry as the event handler, with a window title of 'Draw Geometry' and a // size of (800, 600) run::<DrawGeometry>("Draw Geometry", Vector::new(800, 600), Settings::default()); }
extern crate sodiumoxide; extern crate byteorder; extern crate hex; extern crate bit_vec; extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; #[macro_use] pub mod encoding; #[macro_use] pub mod messages; pub mod crypto; pub mod storage;
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { crate::{ buffer_writer::{BufferWriter, ByteSliceMut}, mac::{self, FrameControl, HtControl, MgmtHdr, RawHtControl}, }, failure::{ensure, Error}, }; type MacAddr = [u8; 6]; #[derive(PartialEq)] pub struct FixedFields { pub frame_ctrl: FrameControl, pub addr1: MacAddr, pub addr2: MacAddr, pub addr3: MacAddr, pub seq_ctrl: u16, } impl FixedFields { pub fn sent_from_client( mut frame_ctrl: FrameControl, bssid: MacAddr, client_addr: MacAddr, seq_ctrl: u16, ) -> FixedFields { FixedFields { frame_ctrl, addr1: bssid, addr2: client_addr, addr3: bssid, seq_ctrl } } } impl std::fmt::Debug for FixedFields { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { writeln!( f, "fc: {:#b}, addr1: {:02X?}, addr2: {:02X?}, addr3: {:02X?}, seq: {}", self.frame_ctrl.value(), self.addr1, self.addr2, self.addr3, self.seq_ctrl )?; Ok(()) } } pub fn write_mgmt_hdr<B: ByteSliceMut>( w: BufferWriter<B>, mut fixed: FixedFields, ht_ctrl: Option<HtControl>, ) -> Result<BufferWriter<B>, Error> { fixed.frame_ctrl.set_frame_type(mac::FRAME_TYPE_MGMT); if ht_ctrl.is_some() { fixed.frame_ctrl.set_htc_order(true); } else { ensure!(!fixed.frame_ctrl.htc_order(), "htc_order bit set while HT-Control is absent"); } let (mut mgmt_hdr, mut w) = w.reserve_zeroed::<MgmtHdr>()?; mgmt_hdr.set_frame_ctrl(fixed.frame_ctrl.value()); mgmt_hdr.addr1 = fixed.addr1; mgmt_hdr.addr2 = fixed.addr2; mgmt_hdr.addr3 = fixed.addr3; mgmt_hdr.set_seq_ctrl(fixed.seq_ctrl); match ht_ctrl { None => Ok(w), Some(ht_ctrl_bitfield) => { let (mut ht_ctrl, mut w) = w.reserve_zeroed::<RawHtControl>()?; ht_ctrl.set(ht_ctrl_bitfield.value()); Ok(w) } } } #[cfg(test)] mod tests { use super::*; #[test] fn fixed_fields_sent_from_client() { let got = FixedFields::sent_from_client(FrameControl(1234), [1; 6], [2; 6], 4321); let expected = FixedFields { frame_ctrl: FrameControl(1234), addr1: [1; 6], addr2: [2; 6], addr3: [1; 6], seq_ctrl: 4321, }; assert_eq!(got, expected); } #[test] fn too_small_buffer() { let mut bytes = vec![0u8; 20]; let result = write_mgmt_hdr( BufferWriter::new(&mut bytes[..]), FixedFields { frame_ctrl: FrameControl(0b00110001_00110000), addr1: [1; 6], addr2: [2; 6], addr3: [3; 6], seq_ctrl: 0b11000000_10010000, }, None, ); assert!(result.is_err(), "expected failure when writing into too small buffer"); } #[test] fn invalid_ht_configuration() { let mut bytes = vec![0u8; 30]; let result = write_mgmt_hdr( BufferWriter::new(&mut bytes[..]), FixedFields { frame_ctrl: FrameControl(0b10110001_00110000), addr1: [1; 6], addr2: [2; 6], addr3: [3; 6], seq_ctrl: 0b11000000_10010000, }, None, ); assert!(result.is_err(), "expected failure due to invalid ht configuration"); } #[test] fn write_fixed_fields_only() { let mut bytes = vec![0u8; 30]; let w = write_mgmt_hdr( BufferWriter::new(&mut bytes[..]), FixedFields { frame_ctrl: FrameControl(0b00110001_00110000), addr1: [1; 6], addr2: [2; 6], addr3: [3; 6], seq_ctrl: 0b11000000_10010000, }, None, ) .expect("Failed writing mgmt frame"); assert_eq!(w.written_bytes(), 24); #[rustfmt::skip] assert_eq!( bytes, [ // Data Header 0b00110000u8, 0b00110001, // Frame Control 0, 0, // duration 1, 1, 1, 1, 1, 1, // addr1 2, 2, 2, 2, 2, 2, // addr2 3, 3, 3, 3, 3, 3, // addr3 0b10010000, 0b11000000, // Sequence Control // Trailing bytes 0, 0, 0, 0, 0, 0, ] ); } #[test] fn write_ht_ctrl() { let mut bytes = vec![0u8; 30]; let w = write_mgmt_hdr( BufferWriter::new(&mut bytes[..]), FixedFields { frame_ctrl: FrameControl(0b00110001_00110000), addr1: [1; 6], addr2: [2; 6], addr3: [3; 6], seq_ctrl: 0b11000000_10010000, }, Some(HtControl(0b10101111_11000011_11110000_10101010)), ) .expect("Failed writing mgmt frame"); assert_eq!(w.written_bytes(), 28); #[rustfmt::skip] assert_eq!( &bytes[..], &[ // Data Header 0b00110000u8, 0b10110001, // Frame Control 0, 0, // duration 1, 1, 1, 1, 1, 1, // addr1 2, 2, 2, 2, 2, 2, // addr2 3, 3, 3, 3, 3, 3, // addr3 0b10010000, 0b11000000, // Sequence Control // Ht Control 0b10101010, 0b11110000, 0b11000011, 0b10101111, // Trailing byte 0, 0, ][..] ); } }
fn main() { let a = "a1".to_string(); let b = "b1".to_string(); println!("sample1 = {:?}", sample1(&a)); println!("sample2 = {:?}", sample2(&a, &b)); println!("sample3 = {:?}", sample3(&a, &b)); println!("sample4 = {}", sample4(&a, &b)); let r1; { let b2 = "b2".to_string(); println!("nest sample1 = {:?}", sample1(&b2)); println!("nest sample2 = {:?}", sample2(&a, &b2)); println!("nest sample3 = {:?}", sample3(&a, &b2)); println!("nest sample4 = {}", sample4(&a, &b2)); r1 = sample4(&b2, &a); } println!("r1 = {}", r1); let r2; { // &'static str let b3 = "b3"; r2 = sample4(&a, b3); } println!("r2 = {}", r2); } fn sample1(x: &str) -> (&str,) { (x,) } fn sample2<'a, 'b>(x: &'a str, y: &'b str) -> (&'a str, &'b str) { (x, y) } fn sample3<'a>(x: &'a str, y: &'a str) -> (&'a str, &'a str) { (x, y) } fn sample4<'a, 'b>(_: &'a str, y: &'b str) -> &'b str { y }
use std::fmt; use crate::TargetJobId; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct JobId(uuid::Uuid); impl JobId { pub fn new() -> Self { Self(uuid::Uuid::new_v4()) } /// Binary reprensentation pub fn to_bytes(self) -> Vec<u8> { self.0.as_bytes().to_vec() } /// From binary reprensentation pub fn from_bytes(b: &[u8]) -> Result<Self, InvalidJobIdBytes> { Ok(Self( uuid::Uuid::from_slice(b).map_err(|_| InvalidJobIdBytes)?, )) } /// From text reprensentation pub fn parse(b: &str) -> Result<Self, InvalidJobIdString> { Ok(Self( uuid::Uuid::parse_str(b).map_err(|_| InvalidJobIdString)?, )) } } impl Default for JobId { fn default() -> Self { Self::new() } } impl std::fmt::Display for JobId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:x}", self.0) } } impl std::convert::TryFrom<TargetJobId> for JobId { type Error = InvalidJobIdBytes; fn try_from(target: TargetJobId) -> Result<Self, Self::Error> { Self::from_bytes(&target.jobid) } } impl From<JobId> for TargetJobId { fn from(id: JobId) -> TargetJobId { TargetJobId { jobid: id.to_bytes(), } } } /// Binary version was invalid #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct InvalidJobIdBytes; impl fmt::Display for InvalidJobIdBytes { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Invalid job id (UUID required)") } } impl std::error::Error for InvalidJobIdBytes { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&InvalidJobIdBytes) } } /// String representation was invalid #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct InvalidJobIdString; impl fmt::Display for InvalidJobIdString { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Invalid job id (UUID required)") } } impl std::error::Error for InvalidJobIdString { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&InvalidJobIdString) } }
#![link(name="git2")] extern crate git2; use git2::git2; #[test] fn test_config() { let repo = match git2::Repository::open(&Path::new("/storage/home/achin/devel/libgit2.rs/tests/data/repoA")) { Ok(r) => r, Err(e) => fail!("Failed to open repo:\n{}", e.message) }; assert!(repo.is_empty() == false); let config = match repo.config() { Err(e) => fail!("Failed to get config! {}", e), Ok(c) => c }; assert!(config.get_bool("core.bare").is_ok()); assert!(config.get_bool("core.doesnotexist").is_err()); assert!(config.get_bool("core.bare").unwrap() == repo.is_bare()); let entryR = config.get_entry("core.bare"); assert!(entryR.is_ok()); let entry = entryR.unwrap(); assert!(entry.name.as_slice() == "core.bare"); assert!(entry.value.as_slice() == repo.is_bare().to_string().as_slice()); println!("{}", config.get_entry("user.name")); for entry in config.iterator().unwrap() { println!("have item: {}", entry); } }
#![cfg(feature = "mppa")] use telamon_kernels::{linalg, Kernel}; use telamon_mppa as mppa; macro_rules! test_output { ($name:ident, $kernel:ty, $num_tests:expr, $params:expr) => { #[test] fn $name() { let _ = env_logger::try_init(); let mut context = mppa::Context::new(); <$kernel>::test_correctness($params, $num_tests, &mut context); } }; } test_output!(axpy, linalg::Axpy<f32>, 100, (1 << 16, true)); test_output!(mv, linalg::MatVec<f32>, 100, (1 << 4, 1 << 2, true)); test_output!(gesummv, linalg::Gesummv<f32>, 100, (1 << 4, 1 << 4, true)); test_output!( fused_mm_identity, linalg::FusedMM<f32>, 100, linalg::FusedMMP::new(16, 16, 16) ); test_output!( fused_mm_relu, linalg::FusedMM<f32>, 100, linalg::FusedMMP::new(16, 16, 16).activation_fun(linalg::ActivationFunction::ReLU) ); test_output!( fused_mm_sigmoid, linalg::FusedMM<f32>, 100, linalg::FusedMMP::new(16, 16, 16).activation_fun(linalg::ActivationFunction::Sigmoid) );
use crate::repositories::*; use diesel::r2d2::ConnectionManager; use diesel::r2d2::Pool; use diesel::PgConnection; use crate::dao::*; use crate::service::UserService; use crate::service::PsqlUserService; #[derive(Clone)] pub struct AppState { pub pool: Box<Pool<ConnectionManager<PgConnection>>>, } impl AppState { pub fn user_repository(&self) -> impl UserRepository { return UserDAO { pool: self.pool.clone(), app_state: Box::new(self.clone()) } } pub fn user_service(&self) -> impl UserService { return PsqlUserService { pool: self.pool.clone(), app_state: Box::new(self.clone()) } } }
#[allow(unused_imports)] use proconio::{ input, fastout }; fn solve(n: i32, a: i32, b: i32) -> i32 { n - a + b } fn run() -> Result<(), Box<dyn std::error::Error>> { input! { n: i32, a: i32, b: i32, } println!("{}", solve(n, a, b)); Ok(()) } fn main() { match run() { Err(err) => panic!("{}", err), _ => () }; }
//! Creating a blank window is all well and good, but drawing something to it is even better. //! //! Rendering in Quicksilver usually takes the form: //! ```no_run //! # use quicksilver::{graphics::{Background, Drawable}, lifecycle::Window}; //! # fn func(window: &mut Window, some_drawable: impl Drawable, some_background: Background) { //! window.draw(&some_drawable, some_background); //! # } //! ``` //! `Drawable` is a trait which allows an object to determine how to lay out some points to draw, //! like a rectangle or a circle. A Background is what to fill those points with, like a solid //! color or an image. For example, drawing a red rectangle with a top-left coordinate of (50, 50), //! a width of 100, and a height of 200 would look like: //! ```no_run //! # use quicksilver::{geom::{Rectangle}, graphics::{Background, Color, Drawable}, lifecycle::Window}; //! # fn func(window: &mut Window) { //! let area = Rectangle::new((50, 50), (100, 200)); //! let background = Background::Col(Color::RED); //! window.draw(&area, background); //! # } //! ``` //! If we wanted to switch out our rectangle for a Circle with a center at (100, 100) and a radius //! of 50, we could do: //! ```no_run //! # use quicksilver::{geom::{Circle, Rectangle}, graphics::{Background, Color, Drawable}, lifecycle::Window}; //! # fn func(window: &mut Window) { //! let area = Circle::new((100, 100), 50); //! let background = Background::Col(Color::RED); //! window.draw(&area, background); //! # } //! ``` //! The next step is actually integrating some drawing code into our blank window: //! ```no_run //! extern crate quicksilver; //! //! use quicksilver::{ //! Result, //! geom::{Rectangle, Vector}, // We'll need to import Rectangle now //! graphics::{Background, Color}, // Also Background and Color //! lifecycle::{State, Window, run} //! }; //! //! struct Screen; //! //! impl State for Screen { //! fn new() -> Result<Screen> { //! Ok(Screen) //! } //! //! fn draw(&mut self, window: &mut Window) -> Result<()> { //! // Clear the contents of the window to a white background //! window.clear(Color::WHITE)?; //! // Draw a red rectangle //! window.draw(&Rectangle::new((50, 50), (100, 200)), Background::Col(Color::RED)); //! Ok(()) //! } //! } //! //! fn main() { //! run::<Screen>("Hello World", Vector::new(800, 600), Default::default()); //! } //! ``` //! We've made two changes from the previous example: imported `Rectangle`, `Background`, and //! `Color`, as well as implementing the `draw` function. By default, `draw` will be called by the //! host environment whenever the screen refreshes. First we clear out the window's previous //! contents, then we draw a red rectangle. //! //! If we want the rectangle to be smaller, or bigger, or a different color, the code we wrote is //! sufficient. Just tweak the input values and you could have a blue Rectangle that's twice as //! big. But how could we do a rotation, or efficiently do a complex scaling or translation //! operation? The answer is the `Transform` struct. If you're familiar with matrix math or linear //! algebra, `Transform` is a 3x3 transformation matrix. If you don't know the underlying math, //! worry not! There are 4 main ways to create a transform: //! //! - `Transform::IDENTITY`: Create a Transform that does nothing. When you apply this transform, //! everything will look exactly the same //! - `Transform::rotate(angle)`: Create a Transform that rotates counter-clockwise by a given //! amount of degrees //! - `Transform::translate(vector)`: Create a Transform that moves an object by a given vector //! - `Transform::scale(vector)`: Create a Transform with a given x and y axis scale factor //! //! We combine Transform objects using the `*` operator, with the last transform in a chain being //! applied first. This means that //! ```no_run //! # use quicksilver::geom::Transform; //! Transform::rotate(30) * Transform::translate((0, -6)); //! ``` //! first translates an object up six pixels and then rotates it by 30 degrees. //! //! The last drawing concept for now is z-ordering. Sometimes you don't want to draw objects to the //! screen in the order they're drawn, but with some other sorting method. Here you use z-ordering: //! an object with a higher z value gets drawn on top of an object with a lower z value. //! //! If you want to use a transform or z-ordering, you need to use the more advanced draw function, //! which takes the form: //! ```no_run //! # use quicksilver::{geom::{Transform}, graphics::{Background, Drawable}, lifecycle::Window}; //! # fn func(window: &mut Window, some_drawable: impl Drawable, some_background: Background, //! # some_transform_value: Transform, some_z_value: f32) { //! window.draw_ex(&some_drawable, some_background, some_transform_value, some_z_value); //! # } //! ``` //! Armed with Transform values, we can turn our little red rectangle into a little red diamond: //! ```no_run //! extern crate quicksilver; //! //! use quicksilver::{ //! Result, //! geom::{Rectangle, Transform, Vector}, // Now we need Transform //! graphics::{Background, Color}, //! lifecycle::{State, Window, run} //! }; //! //! struct Screen; //! //! impl State for Screen { //! fn new() -> Result<Screen> { //! Ok(Screen) //! } //! //! fn draw(&mut self, window: &mut Window) -> Result<()> { //! window.clear(Color::WHITE)?; //! // Draw a red diamond //! window.draw_ex( //! &Rectangle::new((50, 50), (50, 50)), //! Background::Col(Color::RED), //! Transform::rotate(45), // Rotate by 45 degrees //! 0 // we don't really care about the Z value //! ); //! Ok(()) //! } //! } //! //! fn main() { //! run::<Screen>("Hello World", Vector::new(800, 600), Default::default()); //! } //! ``` //! Quicksilver gives you a number of `Drawable` objects to work with by default: `Rectangle`, //! `Vector`, `Circle`, `Line`, and `Triangle`. Most applications will only ever need these, or //! even just a subset of these, but you can feel free to define your own `Drawable` objects. This //! is covered later in the `mesh` tutorial.
use std::io::Read; fn main() { let mut buf = String::new(); // 標準入力から全部bufに読み込む std::io::stdin().read_to_string(&mut buf).unwrap(); let mut iter = buf.split_whitespace(); let K: i32 = iter.next().unwrap().parse().unwrap(); let S: i32 = iter.next().unwrap().parse().unwrap(); let mut result = 0; for x in 0..K + 1 { for y in 0..K + 1 { let z = S - x - y; if z >= 0 && z <= K { result += 1; } } } println!("{}", result); }
use std::collections::HashSet; use crate::core::{Part, Solution}; pub fn solve(part: Part, input: String) -> String { match part { Part::P1 => Day08::solve_part_one(input), Part::P2 => Day08::solve_part_two(input), } } struct Trail { knots: Vec<(i32, i32)>, length: usize, } impl Trail { fn new(length: usize) -> Self { Self { knots: vec![(0, 0); length], length, } } fn do_moves<I>(&mut self, moves: I) -> HashSet<(i32, i32)> where I: Iterator<Item = (char, usize)>, { moves .flat_map(|(mv, steps)| { (0..steps) .map(|_| { match mv { 'R' => self.knots[0].0 += 1, 'L' => self.knots[0].0 -= 1, 'U' => self.knots[0].1 += 1, 'D' => self.knots[0].1 -= 1, _ => panic!(), } self.catch_up(); self.knots[self.length - 1] }) .collect::<Vec<(i32, i32)>>() }) .collect() } fn catch_up(&mut self) { for i in 1..self.length { let head = self.knots[i - 1]; let slack = self.knots[i]; if !adjacent(&head, &slack) && !same(&head, &slack) { self.knots[i] = *self .peek_around(head) .iter() .find(|adj| adjacent(adj, &slack)) .unwrap(); } } } fn peek_around(&self, (x, y): (i32, i32)) -> [(i32, i32); 8] { [ (x, y - 1), (x, y + 1), (x - 1, y), (x + 1, y), (x + 1, y + 1), (x - 1, y - 1), (x + 1, y - 1), (x - 1, y + 1), ] } } struct Day08; impl Solution for Day08 { fn solve_part_one(input: String) -> String { Trail::new(2) .do_moves(input.lines().map(parse_move)) .len() .to_string() } fn solve_part_two(input: String) -> String { Trail::new(10) .do_moves(input.lines().map(parse_move)) .len() .to_string() } } fn parse_move(mv: &str) -> (char, usize) { let (direction, steps) = mv.split_once(' ').unwrap(); return ( direction.chars().collect::<Vec<char>>()[0], steps.parse().unwrap(), ); } fn adjacent(a: &(i32, i32), b: &(i32, i32)) -> bool { (a.0 - b.0).abs() <= 1 && (a.1 - b.1).abs() <= 1 } fn same(a: &(i32, i32), b: &(i32, i32)) -> bool { a.0 == b.0 && a.1 == b.1 }
#![feature(proc_macro_hygiene, decl_macro)] use rocket_contrib::json::Json; mod models; use models::ImgurImg; #[macro_use] extern crate rocket; #[get("/")] fn index() -> &'static str { "Hello, worldd!" } #[post("/image", format = "json", data = "<img>")] fn upload(img: Json<ImgurImg>) -> String { let comment = match img.comment { Some(inner) => inner.clone(), None => String::from(""), }; format!("The url is: '{}', the comment is: '{}'", img.url, comment) } fn main() { rocket::ignite().mount("/", routes![index, upload]).launch(); }
use backend::flow::FlowGraph; use backend::interference::Interference; use backend::liveness::Liveness; use backend::*; use hashbrown::{HashMap, HashSet}; use std::iter::FromIterator; pub fn alloc<P>(p: &mut P::Prg) where P: Platform, P::Reg: 'static, { for f in p.functions_mut() { alloc_function::<P>(f) } } fn alloc_function<P>(m: &mut P::Function) where P: Platform, P::Reg: 'static, { let colour_result = color::<P>(m); // println!("color: {:#?}", colour_result); if colour_result.spills.is_empty() { let sigma = |t| *colour_result.colouring.get(&t).unwrap_or(&t); m.rename(&sigma) } else { m.spill(&colour_result.spills); alloc_function::<P>(m) } } #[derive(Debug)] struct ColourResult<P> where P: Platform, P::Reg: 'static, { colouring: HashMap<P::Reg, P::Reg>, spills: Vec<P::Reg>, } fn color<P>(function: &P::Function) -> ColourResult<P> where P: Platform, { let flow = FlowGraph::<P>::new(function); let liveness = Liveness::<P>::new(flow); let interference = Interference::new(function, &liveness); let mut graph = interference.graph; let mut stack: Vec<P::Reg> = Vec::new(); let k = P::Reg::general_purpose_registers().len(); let mut low_degrees: Vec<P::Reg> = Vec::new(); let mut high_degrees: HashMap<P::Reg, usize> = HashMap::default(); low_degrees.reserve(graph.nodes().len()); for t in graph.nodes() { if t.is_physical() { continue; }; let deg = graph.out_degree(t); if deg >= k { high_degrees.insert(*t, deg); } else { low_degrees.push(*t); } } // Simplify and Spill while low_degrees.len() + high_degrees.len() > 0 { let next_temp = match low_degrees.pop() { Some(t) => t, None => { let mut next_temp = *high_degrees.iter().next().unwrap().0; let mut max_degree = 0; for (t, deg) in &high_degrees { if *deg > max_degree { next_temp = *t; max_degree = *deg; } } next_temp } }; stack.push(next_temp); high_degrees.remove(&next_temp); for t in graph.get_successors(next_temp) { let d = high_degrees.get_mut(t).map(|i| { *i -= 1; *i }); match d { None => (), Some(deg) => { if deg < k { high_degrees.remove(t); low_degrees.push(*t) } } } } } // Select let mut colouring: HashMap<P::Reg, P::Reg> = HashMap::default(); let n = graph.nodes().len(); colouring.reserve(n); for t in P::Reg::physical_registers() { colouring.insert(*t, *t); } let mut actual_spills = Vec::new(); let usable_colours = HashSet::<&P::Reg>::from_iter(P::Reg::general_purpose_registers().iter()); while let Some(s) = stack.pop() { let mut possible_colours = usable_colours.clone(); for t in graph.get_successors(s) { match colouring.get(t) { None => (), Some(ce) => { possible_colours.remove(ce); } } } if let Some(c) = possible_colours.iter().next() { colouring.insert(s, **c); } else { actual_spills.push(s); } } ColourResult { colouring: colouring, spills: actual_spills, } }
pub use common::*; pub mod common; pub use ts_36_331::*; pub mod ts_36_331;
use leptos::*; use crate::{auth, components::Button}; #[component] pub fn Account(cx: Scope) -> impl IntoView { let logout_action = auth::state(cx).logout_action; view! { cx, <div> <p>"Congrats, you're in!"</p> <Button on:click=move |_cx| { logout_action.dispatch(()) }>Logout</Button> </div> } }
use byteorder::{LittleEndian, ReadBytesExt}; use crate::decode::Decode; use crate::encode::Encode; use crate::mysql::protocol::TypeId; use crate::mysql::type_info::MySqlTypeInfo; use crate::mysql::{MySql, MySqlData, MySqlValue}; use crate::types::Type; use crate::Error; use std::str::from_utf8; /// The equivalent MySQL type for `f32` is `FLOAT`. /// /// ### Note /// While we added support for `f32` as `FLOAT` for completeness, we don't recommend using /// it for any real-life applications as it cannot precisely represent some fractional values, /// and may be implicitly widened to `DOUBLE` in some cases, resulting in a slightly different /// value: /// /// ```rust /// // Widening changes the equivalent decimal value, these two expressions are not equal /// // (This is expected behavior for floating points and happens both in Rust and in MySQL) /// assert_ne!(10.2f32 as f64, 10.2f64); /// ``` impl Type<MySql> for f32 { fn type_info() -> MySqlTypeInfo { MySqlTypeInfo::new(TypeId::FLOAT) } } impl Encode<MySql> for f32 { fn encode(&self, buf: &mut Vec<u8>) { <i32 as Encode<MySql>>::encode(&(self.to_bits() as i32), buf); } } impl<'de> Decode<'de, MySql> for f32 { fn decode(value: MySqlValue<'de>) -> crate::Result<Self> { match value.try_get()? { MySqlData::Binary(mut buf) => buf .read_i32::<LittleEndian>() .map_err(crate::Error::decode) .map(|value| f32::from_bits(value as u32)), MySqlData::Text(s) => from_utf8(s) .map_err(Error::decode)? .parse() .map_err(Error::decode), } } } /// The equivalent MySQL type for `f64` is `DOUBLE`. /// /// Note that `DOUBLE` is a floating-point type and cannot represent some fractional values /// exactly. impl Type<MySql> for f64 { fn type_info() -> MySqlTypeInfo { MySqlTypeInfo::new(TypeId::DOUBLE) } } impl Encode<MySql> for f64 { fn encode(&self, buf: &mut Vec<u8>) { <i64 as Encode<MySql>>::encode(&(self.to_bits() as i64), buf); } } impl<'de> Decode<'de, MySql> for f64 { fn decode(value: MySqlValue<'de>) -> crate::Result<Self> { match value.try_get()? { MySqlData::Binary(mut buf) => buf .read_i64::<LittleEndian>() .map_err(crate::Error::decode) .map(|value| f64::from_bits(value as u64)), MySqlData::Text(s) => from_utf8(s) .map_err(Error::decode)? .parse() .map_err(Error::decode), } } }
mod types; pub mod solver; pub mod dimacs; pub use types::*;
extern crate reqwest; extern crate jplaceholder; extern crate serde_json; use jplaceholder::*; fn generate_post(id: i32) -> Post { let mut response = reqwest::get(&format!("https://jsonplaceholder.typicode.com/posts/{}", id)).expect("failed"); let text = response.text().expect("failed"); let json: Post = serde_json::from_str(&text).expect("Failed to parse the json"); json } // posts #[test] fn find_post_id() { let post = Post::find(2); let json = generate_post(2); assert_eq!(post.is_none(), false); assert_eq!(post.expect("Post not found"), json); } #[test] fn not_found_post_id() { let post = Post::find(2000); assert_eq!(post.is_none(), true); } #[test] fn create_post() { let post = Post{id: 5, title: String::from("Hey"), body: String::from("hehe"), user_id: 5}; assert_eq!(Post::create(post).is_ok(), true); } #[test] fn get_all_post() { let posts = Post::all(); assert_eq!(posts[0].id, 1); } #[test] fn get_post_user() { let post: Post = Post::find(1).expect("Post not found"); let user = User::all().into_iter().filter(|u| u.id == post.user_id).nth(0); assert_eq!(user.expect("User not found"), post.user().expect("User not found")); }
use std::fs; use scraper::{Html, Selector}; use selectors::attr::CaseSensitivity; use clap::{App, Arg}; #[derive(Default)] struct RollResult { player_name: String, date: String, // die: String, // result: u8, } fn main() { // ARGs let matches = App::new("rust_test") .version("0.1.0") .author("Peter Forsythe") .arg( Arg::with_name("file") .short("f") .long("file") .takes_value(true) .help("HTML file to parse"), ) .get_matches(); // file setup let file = matches.value_of("file").unwrap_or( "/home/peter/Documents/git/data/Chat Log for The Seeds of Evil-small.html" // .unwrap_or("/home/peter/Documents/git/rust_test/data/Chat Log fragment.html"); ); // let's get to work println!("getting to work"); let contents = fs::read_to_string(file).expect("Something went wrong reading the file"); let html_doc = Html::parse_document(&contents); let div_message = Selector::parse(".message").unwrap(); let div_selector = Selector::parse("div").unwrap(); for message in html_doc.select(&div_message) { let fragment = Html::parse_fragment(&message.inner_html()); println!( "message.value().attr(general) {:?}", message .value() .has_class("general", CaseSensitivity::CaseSensitive) ); for div in fragment.select(&div_selector) { println!("class {:?}", div.value().); let all_selector = Selector::parse("*").unwrap(); for child in div.select(&all_selector) { println!("child {:?}", child.html()); } } std::process::exit(2) } }
//https://leetcode.com/problems/maximum-product-difference-between-two-pairs/submissions/ impl Solution { pub fn max_product_difference(nums: Vec<i32>) -> i32 { let max_first = next_max(&nums, 100000); let max_second = next_max(&nums, max_first); let min_first = next_min(&nums, 100000); let min_second = next_min(&nums, min_first); let mut max_product = nums[max_first] * nums[max_second]; let mut min_product = nums[min_first] * nums[min_second]; return max_product - min_product; } } fn next_max(nums: &Vec<i32>, used: usize) -> usize { let mut max_val = -1; let mut max_idx = 0 as usize; for i in 0..nums.len() { if i == used { continue; } if max_val < nums[i] { max_val = nums[i]; max_idx = i; } } return max_idx; } fn next_min(nums: &Vec<i32>, used: usize) -> usize { let mut min_val = 100000; let mut min_idx = 0 as usize; for i in 0..nums.len() { if i == used { continue; } if min_val > nums[i] { min_val = nums[i]; min_idx = i; } } return min_idx; }
pub(super) mod gc_works; pub(super) mod global; pub(super) mod mutator; pub use self::global::GenCopy; pub use self::global::GENCOPY_CONSTRAINTS;
use std::{convert::TryInto, num::NonZeroU8, str::FromStr}; #[cfg(feature = "fuzz")] use arbitrary::Unstructured; #[cfg(not(feature = "fuzz"))] use bonfida_bot::{ state::{unpack_assets, PoolHeader}, }; #[cfg(feature = "fuzz")] use crate::state::{unpack_assets, PoolHeader}; use solana_program::{instruction::{Instruction, InstructionError}, program_error::ProgramError, program_option::COption, program_pack::Pack, pubkey::Pubkey, rent::Rent, system_instruction}; use solana_program_test::{BanksClient, ProgramTest, ProgramTestBanksClientExt, ProgramTestContext, find_file, read_file}; use solana_sdk::{account::Account, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, transport::TransportError}; use spl_associated_token_account::{create_associated_token_account, get_associated_token_address}; use spl_token::{instruction::initialize_account, state::Mint}; const SRM_MINT_KEY: &str = "SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"; const FIDA_MINT_KEY: &str = "EchesyfXePKdLtoiZSL8pBe8Myagyy8ZRqsACNCFGnvp"; pub struct Context { pub bonfidabot_program_id: Pubkey, pub serum_program_id: Pubkey, pub test_state: ProgramTestContext, pub mint_authority: Keypair, pub fida_mint: MintInfo, pub srm_mint: MintInfo, pub pc_mint: MintInfo, pub coin_mint: MintInfo, } pub type MintInfo = (Pubkey, Mint); impl Context { pub async fn refresh_blockhash(&mut self){ self.test_state.last_blockhash = self.test_state.banks_client.get_new_blockhash(&self.test_state.last_blockhash).await.unwrap().0; } pub async fn init() -> Context { let bonfidabot_program_id = Pubkey::new_unique(); let serum_program_id = Pubkey::new_unique(); let mut program_test = ProgramTest::new( "bonfida_bot", bonfidabot_program_id, None ); // Load The Serum Dex program program_test.add_account( serum_program_id, Account { lamports: u32::MAX.into(), data: read_file(find_file("serum_dex.so").unwrap()), owner: solana_program::bpf_loader::id(), executable: true, ..Account::default() }, ); let payer = Keypair::new(); program_test.add_account( payer.pubkey(), Account { lamports: 1<<63, ..Account::default() } ); let mint_authority = Keypair::new(); let fida_mint = mint_bootstrap(Some(FIDA_MINT_KEY), 6, &mut program_test, &mint_authority.pubkey()); let srm_mint = mint_bootstrap(Some(SRM_MINT_KEY), 6, &mut program_test, &mint_authority.pubkey()); let pc_mint = mint_bootstrap(None, 6, &mut program_test, &mint_authority.pubkey()); let coin_mint = mint_bootstrap(None, 6, &mut program_test, &mint_authority.pubkey()); let mut test_state = program_test.start_with_context().await; test_state.payer = payer; Context { bonfidabot_program_id, serum_program_id, test_state, mint_authority, fida_mint, srm_mint, pc_mint, coin_mint, } } pub fn get_mints(&self) -> Vec<MintInfo> { vec![ self.fida_mint, self.srm_mint, self.pc_mint, self.coin_mint ] } } pub fn create_token_account( ctx: &Context, mint: &Pubkey, token_account: &Keypair, token_account_owner: &Pubkey, ) -> Transaction { let instructions = [ system_instruction::create_account( &ctx.test_state.payer.pubkey(), &token_account.pubkey(), Rent::default().minimum_balance(165), 165, &spl_token::id(), ), initialize_account( &spl_token::id(), &token_account.pubkey(), &mint, token_account_owner, ) .unwrap(), ]; let mut transaction = Transaction::new_with_payer(&instructions, Some(&ctx.test_state.payer.pubkey())); transaction.partial_sign(&[&ctx.test_state.payer, token_account], ctx.test_state.last_blockhash); transaction } #[derive(Debug)] pub struct OpenOrderView { pub market: Pubkey, pub owner: Pubkey, pub native_coin_free: u64, pub native_coin_total: u64, pub native_pc_free: u64, pub native_pc_total: u64, pub orders: Vec<u128>, } impl OpenOrderView { pub fn parse(data: Vec<u8>) -> Result<Self, TransportError> { if data.len() != 3228 { return Err(TransportError::TransactionError(TransactionError::InstructionError(0, InstructionError::InvalidAccountData))); } let stripped = &data[13..]; let market = Pubkey::new(&stripped[..32]); let owner = Pubkey::new(&stripped[32..64]); let native_coin_free = u64::from_le_bytes(stripped[64..72].try_into().unwrap()); let native_coin_total = u64::from_le_bytes(stripped[72..80].try_into().unwrap()); let native_pc_free = u64::from_le_bytes(stripped[80..88].try_into().unwrap()); let native_pc_total = u64::from_le_bytes(stripped[88..96].try_into().unwrap()); let mut orders = Vec::with_capacity(128); for i in 0..128 { orders.push(u128::from_le_bytes( stripped[(128 + 16 * i)..(144 + 16 * i)].try_into().unwrap(), )); } Ok(Self { market, owner, native_coin_free, native_coin_total, native_pc_free, native_pc_total, orders, }) } pub async fn get(key: Pubkey, banks_client: &BanksClient) -> Result<Self, TransportError> { Self::parse( banks_client .to_owned() .get_account(key) .await .unwrap() .unwrap() .data, ) } } pub async fn print_pool_data( pool_key: &Pubkey, banks_client: &BanksClient, ) -> Result<(), ProgramError> { let data = banks_client .to_owned() .get_account(*pool_key) .await .unwrap() .unwrap() .data; let pool_header = PoolHeader::unpack(&data[..PoolHeader::LEN]).unwrap(); let pool_asset_offset = PoolHeader::LEN + 32 * (pool_header.number_of_markets as usize); let pool_assets = unpack_assets(&data[pool_asset_offset..])?; for asset in pool_assets { print!("{:?}", asset); let pool_asset_key = get_associated_token_address(&pool_key, &asset.mint_address); let asset_data = banks_client .to_owned() .get_account(pool_asset_key) .await .unwrap() .unwrap() .data; let token_amount = spl_token::state::Account::unpack(&asset_data)?.amount; println!(" Token amount: {:?}", token_amount); } Ok(()) } pub fn create_and_get_associated_token_address( payer_key: &Pubkey, parent_key: &Pubkey, mint_key: &Pubkey, ) -> (Instruction, Pubkey) { let create_source_asset_instruction = create_associated_token_account(payer_key, parent_key, mint_key); let source_asset_key = get_associated_token_address(parent_key, mint_key); return (create_source_asset_instruction, source_asset_key); } pub async fn wrap_process_transaction( ctx: &Context, instructions: Vec<Instruction>, mut signers: Vec<&Keypair>, ) -> Result<(), TransportError> { let mut setup_transaction = Transaction::new_with_payer(&instructions, Some(&ctx.test_state.payer.pubkey())); &signers.push(&ctx.test_state.payer); setup_transaction.partial_sign(&signers, ctx.test_state.last_blockhash); ctx.test_state.banks_client .to_owned() .process_transaction(setup_transaction) .await } pub fn add_token_account( program_test: &mut ProgramTest, account_address: Pubkey, owner_address: Pubkey, mint_address: Pubkey, amount: u64, ) { let mut token_data = [0; spl_token::state::Account::LEN]; spl_token::state::Account { mint: mint_address, owner: owner_address, amount, delegate: COption::None, state: spl_token::state::AccountState::Initialized, is_native: COption::None, delegated_amount: 0, close_authority: COption::None, } .pack_into_slice(&mut token_data); program_test.add_account( account_address, Account { lamports: u32::MAX.into(), data: token_data.into(), owner: spl_token::id(), executable: false, ..Account::default() }, ); } pub fn mint_bootstrap( address: Option<&str>, decimals: u8, program_test: &mut ProgramTest, mint_authority: &Pubkey, ) -> MintInfo { let address = address .map(|s| Pubkey::from_str(s).unwrap()) .unwrap_or_else(|| Pubkey::new_unique()); let mint_info = Mint { mint_authority: Some(*mint_authority).into(), supply: u32::MAX.into(), decimals, is_initialized: true, freeze_authority: None.into(), }; let mut data = [0; Mint::LEN]; mint_info.pack_into_slice(&mut data); program_test.add_account( address, Account { lamports: u32::MAX.into(), data: data.into(), owner: spl_token::id(), executable: false, ..Account::default() }, ); (address, mint_info) } pub fn clone_keypair(k: &Keypair) -> Keypair { Keypair::from_bytes(&k.to_bytes()).unwrap() } #[cfg(feature = "fuzz")] pub fn arbitraryNonZeroU8(u: &mut Unstructured<'_>) -> arbitrary::Result<NonZeroU8>{ Ok(NonZeroU8::new(u.arbitrary()?).unwrap_or(NonZeroU8::new(1).unwrap())) } pub fn result_err_filter(e: Result<(), TransportError>) -> Result<(), TransportError>{ if let Err(TransportError::TransactionError(te)) = &e { match te { TransactionError::InstructionError(_, ie) => { match ie { InstructionError::InvalidArgument | InstructionError::InvalidInstructionData | InstructionError::InvalidAccountData | InstructionError::InsufficientFunds | InstructionError::AccountAlreadyInitialized | InstructionError::InvalidSeeds | InstructionError::Custom(2) | InstructionError::Custom(3) | InstructionError::Custom(0x10000e7) // Serum invalid openorder account owner error | InstructionError::Custom(0x1000683) // Serum invalid pc payer account | InstructionError::Custom(0x1000684) // Serum invalid coin payer account | InstructionError::Custom(4) => {Ok(())}, _ => { print!("{:?}", ie); e } } }, TransactionError::SignatureFailure | TransactionError::InvalidAccountForFee | TransactionError::InsufficientFundsForFee => {Ok(())}, _ => { print!("{:?}", te); e } } } else { e } } pub fn get_element_from_seed<T>(choices: &Vec<T>, seed: u8) -> &T{ &choices[(seed % choices.len() as u8) as usize] } // pub fn into_transport_error(e: ProgramError) -> TransportError { // TransportError::TransactionError(TransactionError::InstructionError(0, // match e { // ProgramError::Custom(u) => {InstructionError::Custom(u)} // ProgramError::InvalidArgument => {InstructionError::InvalidArgument} // ProgramError::InvalidInstructionData => {InstructionError::InvalidInstructionData} // ProgramError::InvalidAccountData => {InstructionError::InvalidAccountData} // ProgramError::AccountDataTooSmall => {InstructionError::AccountDataTooSmall} // ProgramError::InsufficientFunds => {InstructionError::InsufficientFunds} // ProgramError::IncorrectProgramId => {InstructionError::IncorrectProgramId} // ProgramError::MissingRequiredSignature => {InstructionError::MissingRequiredSignature} // ProgramError::AccountAlreadyInitialized => {InstructionError::AccountAlreadyInitialized} // ProgramError::UninitializedAccount => {InstructionError::UninitializedAccount} // ProgramError::NotEnoughAccountKeys => {InstructionError::NotEnoughAccountKeys} // ProgramError::AccountBorrowFailed => {InstructionError::AccountBorrowFailed} // ProgramError::MaxSeedLengthExceeded => {InstructionError::MaxSeedLengthExceeded} // ProgramError::InvalidSeeds => {InstructionError::InvalidSeeds} // } // )) // } pub fn into_transport_error(e: InstructionError) -> TransportError { TransportError::TransactionError(TransactionError::InstructionError(0, e)) }
#[doc = r"Value read from the register"] pub struct R { bits: u16, } #[doc = r"Value to write to the register"] pub struct W { bits: u16, } impl super::TXIS { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u16 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct USB_TXIS_EP0R { bits: bool, } impl USB_TXIS_EP0R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_TXIS_EP0W<'a> { w: &'a mut W, } impl<'a> _USB_TXIS_EP0W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u16) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct USB_TXIS_EP1R { bits: bool, } impl USB_TXIS_EP1R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_TXIS_EP1W<'a> { w: &'a mut W, } impl<'a> _USB_TXIS_EP1W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u16) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct USB_TXIS_EP2R { bits: bool, } impl USB_TXIS_EP2R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_TXIS_EP2W<'a> { w: &'a mut W, } impl<'a> _USB_TXIS_EP2W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u16) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct USB_TXIS_EP3R { bits: bool, } impl USB_TXIS_EP3R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_TXIS_EP3W<'a> { w: &'a mut W, } impl<'a> _USB_TXIS_EP3W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u16) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct USB_TXIS_EP4R { bits: bool, } impl USB_TXIS_EP4R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_TXIS_EP4W<'a> { w: &'a mut W, } impl<'a> _USB_TXIS_EP4W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u16) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct USB_TXIS_EP5R { bits: bool, } impl USB_TXIS_EP5R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_TXIS_EP5W<'a> { w: &'a mut W, } impl<'a> _USB_TXIS_EP5W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u16) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct USB_TXIS_EP6R { bits: bool, } impl USB_TXIS_EP6R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_TXIS_EP6W<'a> { w: &'a mut W, } impl<'a> _USB_TXIS_EP6W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 6); self.w.bits |= ((value as u16) & 1) << 6; self.w } } #[doc = r"Value of the field"] pub struct USB_TXIS_EP7R { bits: bool, } impl USB_TXIS_EP7R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_TXIS_EP7W<'a> { w: &'a mut W, } impl<'a> _USB_TXIS_EP7W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 7); self.w.bits |= ((value as u16) & 1) << 7; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u16 { self.bits } #[doc = "Bit 0 - TX and RX Endpoint 0 Interrupt"] #[inline(always)] pub fn usb_txis_ep0(&self) -> USB_TXIS_EP0R { let bits = ((self.bits >> 0) & 1) != 0; USB_TXIS_EP0R { bits } } #[doc = "Bit 1 - TX Endpoint 1 Interrupt"] #[inline(always)] pub fn usb_txis_ep1(&self) -> USB_TXIS_EP1R { let bits = ((self.bits >> 1) & 1) != 0; USB_TXIS_EP1R { bits } } #[doc = "Bit 2 - TX Endpoint 2 Interrupt"] #[inline(always)] pub fn usb_txis_ep2(&self) -> USB_TXIS_EP2R { let bits = ((self.bits >> 2) & 1) != 0; USB_TXIS_EP2R { bits } } #[doc = "Bit 3 - TX Endpoint 3 Interrupt"] #[inline(always)] pub fn usb_txis_ep3(&self) -> USB_TXIS_EP3R { let bits = ((self.bits >> 3) & 1) != 0; USB_TXIS_EP3R { bits } } #[doc = "Bit 4 - TX Endpoint 4 Interrupt"] #[inline(always)] pub fn usb_txis_ep4(&self) -> USB_TXIS_EP4R { let bits = ((self.bits >> 4) & 1) != 0; USB_TXIS_EP4R { bits } } #[doc = "Bit 5 - TX Endpoint 5 Interrupt"] #[inline(always)] pub fn usb_txis_ep5(&self) -> USB_TXIS_EP5R { let bits = ((self.bits >> 5) & 1) != 0; USB_TXIS_EP5R { bits } } #[doc = "Bit 6 - TX Endpoint 6 Interrupt"] #[inline(always)] pub fn usb_txis_ep6(&self) -> USB_TXIS_EP6R { let bits = ((self.bits >> 6) & 1) != 0; USB_TXIS_EP6R { bits } } #[doc = "Bit 7 - TX Endpoint 7 Interrupt"] #[inline(always)] pub fn usb_txis_ep7(&self) -> USB_TXIS_EP7R { let bits = ((self.bits >> 7) & 1) != 0; USB_TXIS_EP7R { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - TX and RX Endpoint 0 Interrupt"] #[inline(always)] pub fn usb_txis_ep0(&mut self) -> _USB_TXIS_EP0W { _USB_TXIS_EP0W { w: self } } #[doc = "Bit 1 - TX Endpoint 1 Interrupt"] #[inline(always)] pub fn usb_txis_ep1(&mut self) -> _USB_TXIS_EP1W { _USB_TXIS_EP1W { w: self } } #[doc = "Bit 2 - TX Endpoint 2 Interrupt"] #[inline(always)] pub fn usb_txis_ep2(&mut self) -> _USB_TXIS_EP2W { _USB_TXIS_EP2W { w: self } } #[doc = "Bit 3 - TX Endpoint 3 Interrupt"] #[inline(always)] pub fn usb_txis_ep3(&mut self) -> _USB_TXIS_EP3W { _USB_TXIS_EP3W { w: self } } #[doc = "Bit 4 - TX Endpoint 4 Interrupt"] #[inline(always)] pub fn usb_txis_ep4(&mut self) -> _USB_TXIS_EP4W { _USB_TXIS_EP4W { w: self } } #[doc = "Bit 5 - TX Endpoint 5 Interrupt"] #[inline(always)] pub fn usb_txis_ep5(&mut self) -> _USB_TXIS_EP5W { _USB_TXIS_EP5W { w: self } } #[doc = "Bit 6 - TX Endpoint 6 Interrupt"] #[inline(always)] pub fn usb_txis_ep6(&mut self) -> _USB_TXIS_EP6W { _USB_TXIS_EP6W { w: self } } #[doc = "Bit 7 - TX Endpoint 7 Interrupt"] #[inline(always)] pub fn usb_txis_ep7(&mut self) -> _USB_TXIS_EP7W { _USB_TXIS_EP7W { w: self } } }
#![feature(option_unwrap_none, try_blocks)] use std::process::exit; extern crate pest; #[macro_use] extern crate pest_derive; use parser::parser; mod compile; mod parser; fn main() { let ast = match parser("let x = 6\nx +6") { Ok(ast) => ast, Err(error) => { println!("{}", error); exit(-1); } }; dbg!(ast.run()); }
#![cfg(feature = "macros")] use std::time::Duration; use actix::prelude::*; use actix_rt::time::sleep; struct MyActor; impl Actor for MyActor { type Context = Context<Self>; fn started(&mut self, ctx: &mut Self::Context) { ctx.run_interval(Duration::from_millis(100), |_this, ctx| { if !ctx.connected() { ctx.stop(); } }); } fn stopped(&mut self, _ctx: &mut Self::Context) { System::current().stop() } } #[actix::test] async fn test_connected() { actix_rt::spawn(async move { let addr = MyActor::start(MyActor); sleep(Duration::from_millis(350)).await; drop(addr); }); }
#[doc = "Reader of register HWCFGR1"] pub type R = crate::R<u32, super::HWCFGR1>; #[doc = "Reader of field `NBIOPORT`"] pub type NBIOPORT_R = crate::R<u8, u8>; #[doc = "Reader of field `CPUEVTEN`"] pub type CPUEVTEN_R = crate::R<u8, u8>; #[doc = "Reader of field `NBCPUS`"] pub type NBCPUS_R = crate::R<u8, u8>; #[doc = "Reader of field `NBEVENTS`"] pub type NBEVENTS_R = crate::R<u8, u8>; impl R { #[doc = "Bits 16:23 - HW configuration of number of IO ports"] #[inline(always)] pub fn nbioport(&self) -> NBIOPORT_R { NBIOPORT_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bits 12:15 - HW configuration of CPU event output enable"] #[inline(always)] pub fn cpuevten(&self) -> CPUEVTEN_R { CPUEVTEN_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 8:11 - configuration number of CPUs"] #[inline(always)] pub fn nbcpus(&self) -> NBCPUS_R { NBCPUS_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 0:7 - configuration number of event"] #[inline(always)] pub fn nbevents(&self) -> NBEVENTS_R { NBEVENTS_R::new((self.bits & 0xff) as u8) } }
use std::f64; trait ArreaGet { fn area(&self) -> f64; } struct square { height: u32, width: u32, } impl square { fn new(w_t: u32, h_t: u32) -> Self { square { height: h_t, width: w_t, } } } impl ArreaGet for square { fn area(&self) -> f64 { (self.height * self.width) as f64 } } struct circle { radius: u32, } impl circle { fn new(r_t: u32) -> Self { circle { radius: r_t } } } impl ArreaGet for circle { fn area(&self) -> f64 { (self.radius * self.radius) as f64 * f64::consts::PI } } fn main() { let x_s = square::new(20, 18); let x_c = circle::new(10); println!("{}", x_s.area()); println!("{}", x_c.area()); }
use types::{char_t, int_t, void_t, size_t, ssize_t, uint_t}; use types::{off_t}; use types::{pid_t, uid_t, gid_t}; use syscalls::{sys_unlink, sys_rmdir, sys_read, sys_write, sys_close, sys_lseek}; use syscalls::{sys_getpid, sys_getuid, sys_geteuid, sys_setuid, sys_setgid, sys_setsid}; #[cfg(all(target_os = "linux", target_arch = "x86_64"))] use syscalls::{sys_pread64, sys_pwrite64}; #[cfg(all(target_os = "macos", target_arch = "x86_64"))] use syscalls::{sys_pread, sys_pwrite}; use libc::errno::{errno}; macro_rules! forward { ($sys:ident, $($p:expr),*) => { match $sys($($p),*) { n if n < 0 => { errno = -n; -1 }, n => n, } }; } // File and filesystem manipulation #[no_mangle] pub unsafe extern fn unlink(file: *const char_t) -> int_t { forward!(sys_unlink, file) } #[no_mangle] pub unsafe extern fn rmdir(file: *const char_t) -> int_t { forward!(sys_rmdir, file) } #[no_mangle] pub unsafe extern fn close(fd: int_t) -> int_t { forward!(sys_close, fd as uint_t) } #[no_mangle] pub unsafe extern fn read(fd: int_t, buf: *mut void_t, count: size_t) -> ssize_t { (forward!(sys_read, fd as uint_t, buf as *mut char_t, count)) as ssize_t } #[no_mangle] pub unsafe extern fn write(fd: int_t, buf: *const void_t, count: size_t) -> ssize_t { (forward!(sys_write, fd as uint_t, buf as *const char_t, count)) as ssize_t } #[no_mangle] #[cfg(all(target_os = "linux", target_arch = "x86_64"))] pub unsafe extern fn pread(fd: int_t, buf: *mut void_t, count: size_t, offset: off_t) -> ssize_t { (forward!(sys_pread64, fd as ulong_t, buf as *mut char_t, count, offset) as ssize_t) } #[no_mangle] #[cfg(all(target_os = "macos", target_arch = "x86_64"))] pub unsafe extern fn pread(fd: int_t, buf: *mut void_t, count: size_t, offset: off_t) -> ssize_t { (forward!(sys_pread, fd, buf as *mut char_t, count, offset) as ssize_t) } #[no_mangle] #[cfg(all(target_os = "linux", target_arch = "x86_64"))] pub unsafe extern fn pwrite(fd: int_t, buf: *const void_t, count: size_t, offset: off_t) -> ssize_t { (forward!(sys_pwrite64, fd as uint_t, buf as *const char_t, count, offset) as ssize_t) } #[no_mangle] #[cfg(all(target_os = "macos", target_arch = "x86_64"))] pub unsafe extern fn pwrite(fd: int_t, buf: *const void_t, count: size_t, offset: off_t) -> ssize_t { (forward!(sys_pwrite, fd, buf as *const char_t, count, offset) as ssize_t) } #[no_mangle] #[cfg(all(target_os = "linux", target_arch = "x86_64"))] pub unsafe extern fn lseek(fd: int_t, offset: off_t, whence: int_t) -> off_t { (forward!(sys_lseek, fd as uint_t, offset, whence as uint_t) as off_t) } #[no_mangle] #[cfg(all(target_os = "macos", target_arch = "x86_64"))] pub unsafe extern fn lseek(fd: int_t, offset: off_t, whence: int_t) -> off_t { (forward!(sys_lseek, fd, offset, whence) as off_t) } // Environment #[no_mangle] pub unsafe extern fn getpid() -> pid_t { (forward!(sys_getpid,) as pid_t) } #[no_mangle] pub unsafe extern fn getuid() -> uid_t { (forward!(sys_getuid,) as uid_t) } #[no_mangle] pub unsafe extern fn geteuid() -> uid_t { (forward!(sys_geteuid,) as uid_t) } #[no_mangle] pub unsafe extern fn setuid(uid: uid_t) -> int_t { forward!(sys_setuid, uid) } #[no_mangle] pub unsafe extern fn setgid(gid: gid_t) -> int_t { forward!(sys_setgid, gid) } #[no_mangle] pub unsafe extern fn setsid() -> pid_t { (forward!(sys_setsid,) as pid_t) }
use crate::ray::Ray; use crate::vec3::Vec3; #[derive(Debug)] pub struct Camera { pub origin: Vec3, pub lower_left_corner: Vec3, pub horizontal: Vec3, pub vertical: Vec3, } impl Camera { pub fn new() -> Self { Self { origin: Vec3::zero(), lower_left_corner: Vec3(-2.0, -1.0, -1.0), horizontal: Vec3(4.0, 0.0, 0.0), vertical: Vec3(0.0, 2.0, 0.0), } } pub fn get_ray(&self, u: f64, v: f64) -> Ray { Ray::new( self.origin, self.lower_left_corner + u * self.horizontal + v * self.vertical - self.origin, ) } }
extern crate pi_db; pub mod vec;
use std::ptr::NonNull; use std::sync::atomic::AtomicUsize; struct Buf<T> { data: *mut T, read: AtomicUsize, write: AtomicUsize, } pub struct Producer<T> { buf: NonNull<Buf<T>>, } impl<T> Producer<T> { pub fn push(&mut self, T) { } } pub struct Consumer<T> { buf: NonNull<Buf<T>>, }
use collectxyz::nft::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg}; use cosmwasm_std::{ entry_point, to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, }; use cw2::{get_contract_version, set_contract_version}; use crate::error::ContractError; use crate::execute as ExecHandler; use crate::query as QueryHandler; const CONTRACT_NAME: &str = "crates.io:collectxyz-nft-contract"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); #[entry_point] pub fn instantiate( deps: DepsMut, _env: Env, info: MessageInfo, msg: InstantiateMsg, ) -> StdResult<Response> { set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; ExecHandler::instantiate(deps, info, msg) } #[entry_point] pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result<Response, ContractError> { match msg { ExecuteMsg::Mint { coordinates, captcha_signature, } => ExecHandler::execute_mint(deps, env, info, coordinates, captcha_signature), ExecuteMsg::Move { token_id, coordinates, } => ExecHandler::execute_move(deps, env, info, token_id, coordinates), ExecuteMsg::UpdateConfig { config } => { ExecHandler::execute_update_config(deps, info, config) } ExecuteMsg::UpdateCaptchaPublicKey { public_key } => { ExecHandler::execute_update_captcha_public_key(deps, info, public_key) } ExecuteMsg::Withdraw { amount } => ExecHandler::execute_withdraw(deps, env, info, amount), _ => ExecHandler::cw721_base_execute(deps, env, info, msg), } } #[entry_point] pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::Config {} => to_binary(&QueryHandler::query_config(deps)?), QueryMsg::CaptchaPublicKey {} => to_binary(&QueryHandler::query_captcha_public_key(deps)?), QueryMsg::XyzNftInfo { token_id } => { to_binary(&QueryHandler::query_xyz_nft_info(deps, token_id)?) } QueryMsg::XyzNftInfoByCoords { coordinates } => to_binary( &QueryHandler::query_xyz_nft_info_by_coords(deps, coordinates)?, ), QueryMsg::XyzTokens { owner, start_after, limit, } => to_binary(&QueryHandler::query_xyz_tokens( deps, owner, start_after, limit, )?), QueryMsg::AllXyzTokens { start_after, limit } => to_binary( &QueryHandler::query_all_xyz_tokens(deps, start_after, limit)?, ), QueryMsg::NumTokensForOwner { owner } => { to_binary(&QueryHandler::query_num_tokens_for_owner(deps, owner)?) } QueryMsg::MoveParams { token_id, coordinates, } => to_binary(&QueryHandler::query_move_params( deps, token_id, coordinates, )?), _ => QueryHandler::cw721_base_query(deps, env, msg), } } #[entry_point] pub fn migrate(deps: DepsMut, env: Env, msg: MigrateMsg) -> StdResult<Response> { let version = get_contract_version(deps.storage)?; if version.contract != CONTRACT_NAME { return Err(StdError::generic_err( "can't migrate to contract with different name", )); } set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; ExecHandler::migrate(deps, env, msg) }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { crate::errors::QmuxError, crate::transport::{ClientId, SvcId}, crate::transport::{QmiResponse, QmiTransport}, bytes::{BufMut, BytesMut}, fidl::endpoints::ServerEnd, fidl_fuchsia_telephony_ril::NetworkConnectionMarker, fuchsia_syslog::macros::*, futures::lock::Mutex, parking_lot::RwLock, qmi_protocol::{Decodable, Encodable, QmiResult}, std::collections::HashMap, std::fmt::Debug, std::marker::Unpin, std::ops::Deref, std::sync::Arc, }; #[derive(Debug)] pub struct ClientSvcMap(RwLock<HashMap<SvcId, ClientId>>); impl Default for ClientSvcMap { fn default() -> Self { let mut m = HashMap::new(); // Requests for IDs occur on the CTL service (ID 0), // this default mapping allows the client to request an ID // without a unique client just for this functionality m.insert(SvcId(0), ClientId(0)); ClientSvcMap(RwLock::new(m)) } } impl Deref for ClientSvcMap { type Target = RwLock<HashMap<SvcId, ClientId>>; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Debug)] pub struct Connection { pub conn: ServerEnd<NetworkConnectionMarker>, pub pkt_handle: u32, } #[derive(Debug)] pub struct QmiClient { inner: Arc<QmiTransport>, clients: ClientSvcMap, data_conn: Mutex<Option<Connection>>, } impl Unpin for QmiClient {} impl QmiClient { pub fn new(inner: Arc<QmiTransport>) -> Self { QmiClient { inner: inner, clients: ClientSvcMap::default(), data_conn: Mutex::new(None) } } /// Connect a data bearer to a qmi client. /// TODO(bwb): support multiple connections pub async fn set_data_connection(&self, conn: Connection) { let mut data_conn = self.data_conn.lock().await; *data_conn = Some(conn); } /// Send a QMI message and allocate the client IDs for the service /// if they have not yet been pub async fn send_msg<'a, E: Encodable + 'a>( &'a self, msg: E, ) -> Result<QmiResult<E::DecodeResult>, QmuxError> where <E as Encodable>::DecodeResult: Decodable + Debug, { let svc_id = SvcId(msg.svc_id()); let mut need_id = false; { let map = self.clients.read(); // allocate a client id for this service if map.get(&svc_id).is_none() { need_id = true; } } if need_id { use qmi_protocol::CTL::{GetClientIdReq, GetClientIdResp}; fx_log_info!("allocating a client ID for service: {}", svc_id.0); let resp: QmiResult<GetClientIdResp> = self.send_msg_actual(GetClientIdReq::new(svc_id.0)).await?; let client_id_resp = resp.unwrap(); // TODO from trait for QmiError to QmuxError let mut map = self.clients.write(); assert_eq!(client_id_resp.svc_type, svc_id.0); map.insert(svc_id, ClientId(client_id_resp.client_id)); } Ok(self.send_msg_actual(msg).await?) } fn get_client_id(&self, svc_id: SvcId) -> ClientId { let clients = self.clients.read(); *clients .get(&svc_id) .expect("Precondition of calling get_client_id is to have verified an ID is allocated") } /// Send a QMI message without checking if a client ID has been allocated for the service async fn send_msg_actual<'a, E: Encodable + 'a, D: Decodable + Debug>( &'a self, msg: E, ) -> Result<QmiResult<D>, QmuxError> { fx_log_info!("Sending a structured QMI message"); let svc_id = SvcId(msg.svc_id()); let client_id = self.get_client_id(svc_id); let tx_id = self.inner.register_interest(svc_id, client_id); let mut msg_buf = BytesMut::new(); let (payload_bytes, payload_len) = msg.to_bytes(); // QMI header msg_buf.put_u8(0x01); // magic QMI number // 2 bytes total length msg_buf.put_u16_le( payload_len + 3 /* flags */ + 2 /* length byte length */ // additional length is bytes not captured in the payload length // They cannot be calculated there because multi-payload SDUs may // exist + 1 /* sdu control flag */ + msg.transaction_id_len() as u16, ); // 1 byte control flag msg_buf.put_u8(0x00); // 1 byte svc flag msg_buf.put_u8(svc_id.0); // 1 byte client id msg_buf.put_u8(client_id.0); // SDU // 1 byte control flag msg_buf.put_u8(0x00); // 1 or 2 byte transaction ID match msg.transaction_id_len() { 1 => msg_buf.put_u8(tx_id.0 as u8 + 1), // we know it's one byte 2 => msg_buf.put_u16_le(tx_id.0 + 1), _ => panic!( "Unknown transaction ID length. Please add client support or fix the message \ definitions" ), } // add the payload to the buffer msg_buf.extend(payload_bytes); let bytes = msg_buf.freeze(); if let Some(ref transport) = self.inner.transport_channel { if transport.is_closed() { fx_log_err!("Transport channel to modem is closed"); } transport.write(bytes.as_ref(), &mut Vec::new()).map_err(QmuxError::ClientWrite)? } let resp = QmiResponse { client_id: client_id, svc_id: svc_id, tx_id: tx_id, transport: Some(self.inner.clone()) }.await?; let buf = std::io::Cursor::new(resp.bytes()); let decoded = D::from_bytes(buf); Ok(decoded) } } #[cfg(test)] mod tests { use super::*; use { fuchsia_async::{self as fasync, DurationExt, TimeoutExt}, fuchsia_zircon::{self as zx, DurationNum}, futures::lock::Mutex, futures::{ future::{join, join3}, TryFutureExt, }, pretty_assertions::assert_eq, qmi_protocol::QmiError, std::io, }; #[should_panic] #[fasync::run_until_stalled(test)] async fn no_transport_channel() { // should stall without completing. let modem = Arc::new(Mutex::new(crate::QmiModem::new())); let sender = async { let modem_lock = modem.lock().await; let client = modem_lock.create_client().await; client }; sender.await; } #[test] fn connect_transport_after_client_request() { use qmi_protocol::WDA; let mut executor = fasync::Executor::new().unwrap(); let (client_end, server_end) = zx::Channel::create().unwrap(); let client_end = fasync::Channel::from_channel(client_end).unwrap(); let modem = Arc::new(Mutex::new(crate::QmiModem::new())); let server = fasync::Channel::from_channel(server_end).unwrap(); let mut buffer = zx::MessageBuf::new(); const EXPECTED: &[u8] = &[1, 15, 0, 0, 0, 0, 0, 1, 34, 0, 4, 0, 1, 1, 0, 26]; let sender = async { // hacky way of getting around two step client/lock requirements loop { if let Some(modem_lock) = modem.try_lock() { let client = modem_lock.create_client().await; // don't care about result, timeout let _: Result<WDA::SetDataFormatResp, QmiError> = client .send_msg(WDA::SetDataFormatReq::new(None, Some(0x01))) .map_err(|e| io::Error::new( io::ErrorKind::Other, &*format!("fidl error: {:?}", e) )) .on_timeout(30.millis().after_now(), || Ok(Err(QmiError::Aborted))).await .unwrap(); } return; } }; let receiver = async { server.recv_msg(&mut buffer).await.expect("failed to recv msg"); assert_eq!(EXPECTED, buffer.bytes()); }; let late_connect = async { let mut modem_lock = modem.lock().await; modem_lock.connect_transport(client_end.into()); }; executor.run_singlethreaded(join3(late_connect, sender, receiver)); } #[test] fn request_id() { use qmi_protocol::CTL; const EXPECTED: &[u8] = &[1, 15, 0, 0, 0, 0, 0, 1, 34, 0, 4, 0, 1, 1, 0, 66]; let mut executor = fasync::Executor::new().unwrap(); let (client_end, server_end) = zx::Channel::create().unwrap(); let client_end = fasync::Channel::from_channel(client_end).unwrap(); let mut modem = crate::QmiModem::new(); modem.connect_transport(client_end.into()); let modem = Arc::new(Mutex::new(modem)); let server = fasync::Channel::from_channel(server_end).unwrap(); let mut buffer = zx::MessageBuf::new(); let receiver = async { server.recv_msg(&mut buffer).await.expect("failed to recv msg"); assert_eq!(EXPECTED, buffer.bytes()); let bytes = &[1, 15, 0, 0, 0, 0, 1, 1, 34, 0, 12, 0, 0, 4, 0, 0, 0, 0, 0, 1, 0, 0, 42, 6]; let _ = server.write(bytes, &mut vec![]).expect("Server channel write failed"); }; let receiver = receiver .on_timeout(1000.millis().after_now(), || panic!("did not receiver message in time!")); let sender = async { let modem_lock = modem.lock().await; let client = modem_lock.create_client().await; let resp: QmiResult<CTL::GetClientIdResp> = client.send_msg_actual(CTL::GetClientIdReq::new(0x42)).await.unwrap(); let msg = resp.unwrap(); assert_eq!(msg.svc_type, 42); assert_eq!(msg.client_id, 6); }; let sender = sender .on_timeout(1000.millis().after_now(), || panic!("did not receive response in time!")); executor.run_singlethreaded(join(receiver, sender)); } }
/// HTTP parsing. /// /// Provides a `parse_message` function to parse incoming requests or responses from /// a stream. use std::collections::HashMap; use std::fmt; use std::hash::Hash; const CRLF: &str = "\r\n\r\n"; #[derive(Debug, PartialEq)] pub enum HttpError { ParsingError, InvalidStatusCode, } #[derive(Debug, Clone, PartialEq, Copy)] pub enum HttpVersion { V10, V11, } impl fmt::Display for HttpVersion { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { HttpVersion::V10 => write!(f, "HTTP/1.0"), HttpVersion::V11 => write!(f, "HTTP/1.1"), } } } impl HttpVersion { pub fn from_str(s: &str) -> HttpVersion { if s.starts_with("HTTP/1.0") { HttpVersion::V10 } else if s.starts_with("HTTP/1.1") { HttpVersion::V11 } else { panic!("Unsupported HTTP version") } } } #[derive(Debug, PartialEq)] pub struct StatusCode(u16); impl StatusCode { pub fn new(code: u16) -> StatusCode { StatusCode(code) } /// Parse status code from the first 3 bytes of the header string. /// /// # Errors /// /// Return an `Err` in case of a header line below 3 bytes length or if the code result non /// valid (e.g below 100 or over 599, according to the HTTP status codes) pub fn from_str(str: &String) -> Result<StatusCode, HttpError> { let bytes = str.as_bytes(); if bytes.len() < 3 { return Err(HttpError::InvalidStatusCode); } let a = bytes[0].wrapping_sub(b'0') as u16; let b = bytes[1].wrapping_sub(b'0') as u16; let c = bytes[2].wrapping_sub(b'0') as u16; if a == 0 || a > 5 || b > 9 || c > 9 { return Err(HttpError::InvalidStatusCode); } let status = (a * 100) + (b * 10) + c; Ok(StatusCode(status)) } } #[derive(Debug, Clone, PartialEq, Hash)] pub enum HttpMethod { Get(String), Post(String), Put(String), Delete(String), Connect(String), Head, } impl fmt::Display for HttpMethod { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { HttpMethod::Get(r) => write!(f, "GET {}", r), HttpMethod::Post(r) => write!(f, "POST {}", r), HttpMethod::Head => write!(f, "HEAD"), HttpMethod::Put(r) => write!(f, "PUT {}", r), HttpMethod::Delete(r) => write!(f, "DELETE {}", r), HttpMethod::Connect(r) => write!(f, "CONNECT {}", r), } } } #[derive(Debug, Clone, PartialEq)] pub enum HttpHeader { Method(HttpVersion, HttpMethod), Status(HttpVersion, String), } impl fmt::Display for HttpHeader { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { HttpHeader::Method(v, m) => write!(f, "{} {}", m, v), HttpHeader::Status(v, s) => write!(f, "{} {}", s, v), } } } pub struct HttpMessage { pub header: HttpHeader, pub headers: HashMap<String, String>, pub body: Option<String>, } impl HttpMessage { pub fn new(method: HttpMethod, headers: HashMap<String, String>) -> HttpMessage { HttpMessage { header: HttpHeader::Method(HttpVersion::V11, method), headers, body: None, } } /// Return the method of the request or `None` if it's an HTTP response pub fn method(&self) -> Option<&HttpMethod> { match &self.header { HttpHeader::Method(_, m) => Some(m), HttpHeader::Status(_, _) => None, } } /// Return the HTTP version of the request or `None` if it's an HTTP response pub fn http_version(&self) -> Option<&HttpVersion> { match &self.header { HttpHeader::Method(v, _) => Some(v), HttpHeader::Status(v, _) => Some(v), } } /// Return the `Transfer-Encoding` value of the response or `None` if it's an HTTP response or /// the value is not found. pub fn transfer_encoding(&self) -> Option<&String> { self.headers.get("Transfer-Encoding") } /// Return the route of the request or `None` if it's a response or an unknown request type. pub fn route(&self) -> Option<&String> { match self.method() { Some(method) => match method { HttpMethod::Get(route) | HttpMethod::Post(route) | HttpMethod::Put(route) | HttpMethod::Connect(route) | HttpMethod::Delete(route) => Some(route), _ => None, }, _ => None, } } /// Return the status code of the response or `None` if it's a request. pub fn status_code(&self) -> Option<StatusCode> { match &self.header { HttpHeader::Status(_, s) => match StatusCode::from_str(&s) { Ok(r) => Some(r), Err(_) => None, }, _ => None, } } } impl fmt::Display for HttpMessage { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut headers_str = String::new(); for (k, v) in self.headers.iter() { headers_str.push_str(&format!("{}: {}\r\n", k, v)); } let body = match &self.body { Some(b) => b, None => "", }; let repr = format!("{}\r\n{}{}{}", self.header, &headers_str, body, CRLF); write!(f, "{}", repr) } } /// Parse an HTTP message /// /// Receive a buffer argument representing a bytearray received from an /// open stream. /// /// # Errors /// /// Return an `Err(HttpError::ParsingError)` in case of an error parsing the header of the request, /// this can happen for example if an unknown method appears on the header line. /// /// # Panics /// /// The `parse_header` function will panic in case of missing mandatory fields /// like HTTP version, a supported valid method pub fn parse_message(buffer: &[u8]) -> Result<HttpMessage, HttpError> { let request_str = String::from_utf8_lossy(&buffer[..]); let content: Vec<&str> = request_str.split(CRLF).collect(); let first_line: Vec<&str> = content[0].split_whitespace().collect(); // Not really solid but separate version and route based on the start of the header line: // // - If the first line starts with HTTP it's an HTTP response so the HTTP version is the first // token we must extract and no route are provided; // - Otherwise the version is generally the third token ot be parsed, following the route one let (version, route) = if content[0].starts_with("HTTP") { (HttpVersion::from_str(&content[0]), None) } else { ( HttpVersion::from_str(&first_line[2]), Some(first_line[1].to_string()), ) }; // Parse the method (verb of the request) let headline = match first_line[0] { "GET" => HttpHeader::Method(version, HttpMethod::Get(route.unwrap())), "POST" => HttpHeader::Method(version, HttpMethod::Post(route.unwrap())), "PUT" => HttpHeader::Method(version, HttpMethod::Put(route.unwrap())), "DELETE" => HttpHeader::Method(version, HttpMethod::Delete(route.unwrap())), "CONNECT" => HttpHeader::Method(version, HttpMethod::Connect(route.unwrap())), "HEAD" => HttpHeader::Method(version, HttpMethod::Head), _ => HttpHeader::Status(version, first_line[1].to_string()), }; // Populate headers map, starting from 1 as index to skip the first line which // contains just the HTTP method and route let headers: HashMap<String, String> = content[0] .split("\r\n") .skip(1) .map(|x| x.splitn(2, ":")) .map(|mut x| (x.next().unwrap().to_string(), x.next().unwrap().to_string())) .collect(); let body = content[1].trim_end_matches(char::from(0)).to_string(); Ok(HttpMessage { header: headline, headers, body: Some(body), }) }
/*! This module contains code related to template support. */ use crate::app; use crate::error::{Blame, MainError, Result, ResultExt}; use regex::Regex; use std::borrow::Cow; use std::collections::HashMap; use std::fs; use std::path::PathBuf; lazy_static! { static ref RE_SUB: Regex = Regex::new(r#"#\{([A-Za-z_][A-Za-z0-9_]*)}"#).unwrap(); } #[derive(Debug)] pub enum Args { Dump { name: String }, List, Show { path: bool }, } impl Args { pub fn subcommand() -> clap::App<'static, 'static> { use clap::{AppSettings, Arg, SubCommand}; SubCommand::with_name("templates") .about("Manage Cargo Script expression templates.") .setting(AppSettings::SubcommandRequiredElseHelp) .subcommand(SubCommand::with_name("dump") .about("Outputs the contents of a template to standard output.") .arg(Arg::with_name("template") .help("Name of template to dump.") .index(1) .required(true) ) ) .subcommand(SubCommand::with_name("list") .about("List the available templates.") ) .subcommand(SubCommand::with_name("show") .about("Open the template folder in a file browser.") .arg(Arg::with_name("show_path") .help("Output the path to the template folder to standard output instead.") .long("path") ) ) } pub fn parse(m: &clap::ArgMatches) -> Self { match m.subcommand() { ("dump", Some(m)) => Args::Dump { name: m.value_of("template").unwrap().into(), }, ("list", _) => Args::List, ("show", Some(m)) => Args::Show { path: m.is_present("show_path"), }, (name, _) => panic!("bad subcommand: {:?}", name), } } } pub fn try_main(args: Args) -> Result<i32> { match args { Args::Dump { name } => dump(&name)?, Args::List => list()?, Args::Show { path } => show(path)?, } Ok(0) } pub fn expand(src: &str, subs: &HashMap<&str, &str>) -> Result<String> { // The estimate of final size is the sum of the size of all the input. let sub_size = subs.iter().map(|(_, v)| v.len()).sum::<usize>(); let est_size = src.len() + sub_size; let mut anchor = 0; let mut result = String::with_capacity(est_size); for m in RE_SUB.captures_iter(src) { // Concatenate the static bit just before the match. let (m_start, m_end) = { let m_0 = m.get(0).unwrap(); (m_0.start(), m_0.end()) }; let prior_slice = anchor..m_start; anchor = m_end; result.push_str(&src[prior_slice]); // Concat the substitution. let sub_name = m.get(1).unwrap().as_str(); match subs.get(sub_name) { Some(s) => result.push_str(s), None => { return Err(MainError::OtherOwned( Blame::Human, format!("substitution `{}` in template is unknown", sub_name), )) } } } result.push_str(&src[anchor..]); Ok(result) } /** Returns the path to the template directory. */ pub fn get_template_path() -> PathBuf { use std::env; if let Ok(path) = env::var("CARGO_EVAL_TEMPLATE_DIR") { return path.into(); } app::data_dir().unwrap().join("templates") } /** Attempts to locate and load the contents of the specified template. */ pub fn get_template(name: &str) -> Result<Cow<'static, str>> { use std::io::Read; let base = get_template_path(); let file = fs::File::open(base.join(format!("{}.rs", name))) .map_err(MainError::from) .err_tag(format!( "template file `{}.rs` does not exist in {}", name, base.display() )) .shift_blame(Blame::Human); // If the template is one of the built-in ones, do fallback if it wasn't found on disk. if file.is_err() { if let Some(text) = builtin_template(name) { return Ok(text.into()); } } let mut file = file?; let mut text = String::new(); file.read_to_string(&mut text)?; Ok(text.into()) } fn builtin_template(name: &str) -> Option<&'static str> { Some(match name { "expr" => include_str!("templates/expr.rs").trim_end(), "file" => include_str!("templates/file.rs").trim_end(), "loop" => include_str!("templates/loop.rs").trim_end(), "loop-count" => include_str!("templates/loop_count.rs").trim_end(), _ => return None, }) } fn dump(name: &str) -> Result<()> { let text = get_template(name)?; print!("{}", text); Ok(()) } fn list() -> Result<()> { use std::ffi::OsStr; let t_path = get_template_path(); if !t_path.exists() { return Err(format!( "cannot list template directory `{}`: it does not exist", t_path.display() ) .into()); } if !t_path.is_dir() { return Err(format!( "cannot list template directory `{}`: it is not a directory", t_path.display() ) .into()); } for entry in fs::read_dir(&t_path)? { let entry = entry?; if !entry.file_type()?.is_file() { continue; } let f_path = entry.path(); if f_path.extension() != Some(OsStr::new("rs")) { continue; } if let Some(stem) = f_path.file_stem() { println!("{}", stem.to_string_lossy()); } } Ok(()) } fn show(path: bool) -> Result<()> { let t_path = get_template_path(); if path { println!("{}", t_path.display()); Ok(()) } else { if !t_path.exists() { fs::create_dir_all(&t_path)?; } if t_path.is_dir() { open::that(&t_path)?; } else { return Err(format!( "cannot open directory `{}`; it isn't a directory", t_path.display() ) .into()); } Ok(()) } }
pub enum Event { QUIT, PAUSE, }
//! Construct cylinders that are curved sheets, not volumes. use surface::{Sheet, LatticeType}; use coord::{Coord, Direction, Translate, rotate_coords, rotate_planar_coords_to_alignment}; use describe::{unwrap_name, Describe}; use error::Result; use iterator::{ResidueIter, ResidueIterOut}; use system::*; use std::f64::consts::PI; use std::fmt; use std::fmt::{Display, Formatter}; impl_component![Cylinder]; impl_translate![Cylinder]; #[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)] /// Cylinders can be capped in either or both ends. pub enum CylinderCap { Top, Bottom, Both, } impl Display for CylinderCap { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { CylinderCap::Top => write!(f, "Top"), CylinderCap::Bottom => write!(f, "Bottom"), CylinderCap::Both => write!(f, "Both"), } } } #[derive(Clone, Debug, Deserialize, Serialize)] /// A 2D cylindrical surface. pub struct Cylinder { /// Name of cylinder in database. pub name: Option<String>, /// Optional residue placed at each coordinate. If not set the cylinder describes /// a general collection of coordinates. pub residue: Option<Residue>, /// lattice type used to construct the cylinder surface structure. pub lattice: LatticeType, /// The axis along which the cylinder is aligned. pub alignment: Direction, /// Cylinders can be capped at its ends. pub cap: Option<CylinderCap>, #[serde(skip)] /// Origin of the cylinder. Located in the center of the bottom. pub origin: Coord, #[serde(skip)] /// Radius of cylinder. pub radius: f64, #[serde(skip)] /// Height of cylinder. pub height: f64, #[serde(skip)] /// List of coordinates belonging to the cylinder. Relative to the `origin. pub coords: Vec<Coord>, } impl Cylinder { /// Construct the cylinder coordinates and return the object. /// /// # Errors /// Returns an error if either the radius or height is non-positive. pub fn construct(self) -> Result<Cylinder> { // Bend a `Sheet` of the chosen lattice type into the cylinder. let length = 2.0 * PI * self.radius; let width = self.height; let sheet = Sheet { name: None, residue: None, lattice: self.lattice.clone(), std_z: None, origin: Coord::default(), normal: Direction::Z, length, width, coords: vec![], }.construct()?; let final_radius = sheet.length / (2.0 * PI); let final_height = sheet.width; // The cylinder will be created aligned to the Y axis let mut coords: Vec<_> = sheet.coords .iter() .map(|coord| { let (x0, y, _) = coord.to_tuple(); let angle = (x0 * 360.0 / sheet.length).to_radians(); let x = final_radius * angle.sin(); let z = -final_radius * angle.cos(); Coord::new(x, y, z) }) .collect(); if let Some(cap) = self.cap { // The cylinder is aligned along the y axis. Construct a cap from // the same sheet and rotate it to match. let mut bottom = sheet.to_circle(final_radius); //.rotate(Direction::X); bottom.coords = rotate_planar_coords_to_alignment(&bottom.coords, Direction::Z, Direction::Y); // Get the top cap coordinates by shifting the bottom ones, not just the origin. let top_coords: Vec<_> = bottom.coords .iter() .map(|&coord| coord + Coord::new(0.0, final_height, 0.0)) .collect(); match cap { CylinderCap::Bottom => coords.extend_from_slice(&bottom.coords), CylinderCap::Top => coords.extend_from_slice(&top_coords), CylinderCap::Both => { coords.extend_from_slice(&bottom.coords); coords.extend_from_slice(&top_coords); } } } // Rotate the cylinder once along the x-axis to align them to the z-axis. Ok(Cylinder { alignment: Direction::Z, radius: final_radius, height: final_height, coords: rotate_coords(&coords, Direction::X), .. self }) } /// Calculate the box size. fn calc_box_size(&self) -> Coord { let diameter = 2.0 * self.radius; match self.alignment { Direction::X => Coord::new(self.height, diameter, diameter), Direction::Y => Coord::new(diameter, self.height, diameter), Direction::Z => Coord::new(diameter, diameter, self.height), } } } impl Describe for Cylinder { fn describe(&self) -> String { format!("{} (Cylinder surface of radius {:.2} and height {:.2} at {})", unwrap_name(&self.name), self.radius, self.height, self.origin) } fn describe_short(&self) -> String { format!("{} (Cylinder)", unwrap_name(&self.name)) } } #[cfg(test)] mod tests { use super::*; use surface::LatticeType::*; fn setup_cylinder(radius: f64, height: f64, lattice: &LatticeType) -> Cylinder { Cylinder { name: None, residue: None, lattice: lattice.clone(), alignment: Direction::Z, cap: None, origin: Coord::default(), radius, height, coords: vec![], } } #[test] fn cylinder_is_bent_from_sheet_as_expected() { let radius = 2.0; let height = 5.0; let density = 10.0; let lattice = PoissonDisc { density }; let cylinder = setup_cylinder(radius, height, &lattice).construct().unwrap(); // We should have a rough surface density match let expected = 2.0 * PI * radius * height * density; assert!((expected - cylinder.coords.len() as f64).abs() / expected < 0.1); // Not all coords should be at z = 0, ie. not still a sheet let sum_z = cylinder.coords.iter().map(|&Coord { x: _, y: _, z }| z.abs()).sum::<f64>(); assert!(sum_z > 0.0); // Currently the alignment should be along Z assert_eq!(Direction::Z, cylinder.alignment); // Rigorous test of coordinate structure for coord in cylinder.coords { let (r, h) = Coord::ORIGO.distance_cylindrical(coord, Direction::Z); assert!(r <= cylinder.radius); assert!(h >= 0.0 && h <= cylinder.height); } } #[test] fn cylinder_corrects_radius_and_height_to_match_lattice_spacing() { let radius = 1.0; // should give circumference = 2 * PI let height = 5.0; let a = 1.0; // not a match to the circumference let b = 1.1; // not a match to the height let lattice = Triclinic { a, b, gamma: 90.0 }; let cylinder = setup_cylinder(radius, height, &lattice).construct().unwrap(); assert_ne!(radius, cylinder.radius); assert_ne!(height, cylinder.height); // The best match to the circumference 2 * PI is the multiple 6 * a. assert_eq!(6.0 * a / (2.0 * PI), cylinder.radius); assert_eq!(5.0 * b, cylinder.height); } #[test] fn constructing_cylinder_with_negative_radius_or_height_returns_error() { let lattice = PoissonDisc { density: 10.0 }; assert!(setup_cylinder(-1.0, 1.0, &lattice).construct().is_err()); assert!(setup_cylinder(1.0, -1.0, &lattice).construct().is_err()); assert!(setup_cylinder(1.0, 1.0, &lattice).construct().is_ok()); } #[test] fn add_caps_to_cylinder() { let radius = 2.0; let height = 5.0; let lattice = Hexagonal { a: 0.1 }; let mut conf = setup_cylinder(radius, height, &lattice); // Without caps let cylinder = conf.clone().construct().unwrap(); let num_coords = cylinder.coords.len(); // With a bottom cap conf.cap = Some(CylinderCap::Bottom); let cylinder_cap = conf.clone().construct().unwrap(); // The first coordinates should be the original cylinder let (original, bottom) = cylinder_cap.coords.split_at(num_coords); assert_eq!(&original, &cylinder.coords.as_slice()); assert!(bottom.len() > 0); // All the bottom coordinates should be at z = 0 for coord in bottom { assert_eq!(coord.z, 0.0); } // A top cap conf.cap = Some(CylinderCap::Top); let cylinder_cap = conf.clone().construct().unwrap(); let (original, top) = cylinder_cap.coords.split_at(num_coords); assert_eq!(&original, &cylinder.coords.as_slice()); assert_eq!(top.len(), bottom.len()); // All the top coordinates should be at the cylinder height for coord in top { assert_eq!(coord.z, cylinder.height); } // Both caps conf.cap = Some(CylinderCap::Both); let cylinder_cap = conf.clone().construct().unwrap(); let (original, bottom_and_top) = cylinder_cap.coords.split_at(num_coords); assert_eq!(&original, &cylinder.coords.as_slice()); let (bottom_from_both, top_from_both) = bottom_and_top.split_at(bottom.len()); assert_eq!(bottom, bottom_from_both); assert_eq!(top, top_from_both); } #[test] fn calc_box_size_of_cylinder() { let radius = 2.0; let height = 5.0; let lattice = Hexagonal { a: 0.1 }; // Check each direction let mut cylinder = Cylinder { alignment: Direction::X, .. setup_cylinder(radius, height, &lattice) }; let diameter = 2.0 * radius; assert_eq!(Coord::new(height, diameter, diameter), cylinder.calc_box_size()); cylinder.alignment = Direction::Y; assert_eq!(Coord::new(diameter, height, diameter), cylinder.calc_box_size()); cylinder.alignment = Direction::Z; assert_eq!(Coord::new(diameter, diameter, height), cylinder.calc_box_size()); } }
use rustler; use rustler::{NifEnv, NifTerm, NifEncoder, NifResult}; #[derive(NifTuple)] struct AddTuple { lhs: i32, rhs: i32, } pub fn tuple_echo<'a>(env: NifEnv<'a>, args: &[NifTerm<'a>]) -> NifResult<NifTerm<'a>> { let tuple: AddTuple = try!(args[0].decode()); Ok(tuple.encode(env)) } #[derive(NifMap)] struct AddMap { lhs: i32, rhs: i32, } pub fn map_echo<'a>(env: NifEnv<'a>, args: &[NifTerm<'a>]) -> NifResult<NifTerm<'a>> { let map: AddMap = try!(args[0].decode()); Ok(map.encode(env)) } #[derive(NifStruct)] #[module = "AddStruct"] struct AddStruct { lhs: i32, rhs: i32, } pub fn struct_echo<'a>(env: NifEnv<'a>, args: &[NifTerm<'a>]) -> NifResult<NifTerm<'a>> { let add_struct: AddStruct = args[0].decode()?; Ok(add_struct.encode(env)) }
use proptest::strategy::{Just, Strategy}; use proptest::{prop_assert_eq, prop_oneof}; use crate::erlang::negate_1::result; use crate::test::strategy; #[test] fn without_number_errors_badarith() { run!( |arc_process| { ( Just(arc_process.clone()), strategy::term::is_not_number(arc_process.clone()), ) }, |(arc_process, number)| { prop_assert_badarith!( result(&arc_process, number), format!("number ({}) is neither an integer nor a float", number) ); Ok(()) }, ); } #[test] fn with_integer_returns_integer_of_opposite_sign() { run!( |arc_process| { ( Just(arc_process.clone()), prop_oneof![std::isize::MIN..=-1, 1..=std::isize::MAX], ) .prop_map(|(arc_process, i)| (arc_process.clone(), arc_process.integer(i), i)) }, |(arc_process, number, i)| { let negated = arc_process.integer(-i); prop_assert_eq!(result(&arc_process, number), Ok(negated)); Ok(()) }, ); } #[test] fn with_float_returns_float_of_opposite_sign() { run!( |arc_process| { ( Just(arc_process.clone()), prop_oneof![std::f64::MIN..=-1.0, 1.0..=std::f64::MAX], ) .prop_map(|(arc_process, f)| (arc_process.clone(), arc_process.float(f), f)) }, |(arc_process, number, f)| { let negated = arc_process.float(-f); prop_assert_eq!(result(&arc_process, number), Ok(negated)); Ok(()) }, ); }
/*! This create provides weak pointers for `Pin<std::rc::Rc<T>>` and `Pin<std::rc::Arc<T>>` ## Motivation `Pin<std::rc::Rc<T>>` and `Pin<std::rc::Arc<T>>` cannot be converted safely to their `Weak<T>` equivalent if `T` does not implement `Unpin`. That's because it would otherwise be possible to do something like this: ``` # use std::{pin::Pin, marker::PhantomPinned, rc::{Rc, Weak}}; struct SomeStruct(PhantomPinned); let pinned = Rc::pin(SomeStruct(PhantomPinned)); // This is unsafe ... let weak = unsafe { Rc::downgrade(&Pin::into_inner_unchecked(pinned.clone())) }; // ... because otherwise it would be possible to move the content of pinned: let mut unpinned_rc = weak.upgrade().unwrap(); std::mem::drop((pinned, weak)); // unpinned_rc is now the only reference so this will work: let x = std::mem::replace( Rc::get_mut(&mut unpinned_rc).unwrap(), SomeStruct(PhantomPinned), ); ``` In that example, `x` is the original `SomeStruct` which we moved in memory, **that is undefined behavior**, do not do that at home. ## `PinWeak` This crate simply provide a `rc::PinWeak` and `sync::PinWeak` which allow to get weak pointer from `Pin<std::rc::Rc>` and `Pin<srd::sync::Arc>`. This is safe because you can one can only get back a `Pin` out of it when trying to upgrade the weak pointer. `PinWeak` can be created using the `PinWeak` downgrade function. ## Example ``` use pin_weak::rc::*; # use std::marker::PhantomPinned; struct SomeStruct(PhantomPinned, usize); let pinned = Rc::pin(SomeStruct(PhantomPinned, 42)); let weak = PinWeak::downgrade(pinned.clone()); assert_eq!(weak.upgrade().unwrap().1, 42); std::mem::drop(pinned); assert!(weak.upgrade().is_none()); ``` */ #![no_std] extern crate alloc; /// The implementation is in a macro because it is repeated for Arc and Rc macro_rules! implementation { ($Rc:ident, $Weak:ident, $rc_lit:literal) => { #[doc(no_inline)] /// re-exported for convinience pub use core::pin::Pin; /// This is a safe wrapper around something that could be compared to `Pin<Weak<T>>` /// /// The typical way to obtain a `PinWeak` is to call `PinWeak::downgrade` #[derive(Debug)] pub struct PinWeak<T: ?Sized>(Weak<T>); impl<T> Default for PinWeak<T> { fn default() -> Self { Self(Weak::default()) } } impl<T: ?Sized> Clone for PinWeak<T> { fn clone(&self) -> Self { Self(self.0.clone()) } } impl<T: ?Sized> PinWeak<T> { /// Equivalent function to ` #[doc = $rc_lit] /// ::downgrade`, but taking a `Pin< #[doc = $rc_lit] /// <T>>` instead. pub fn downgrade(rc: Pin<$Rc<T>>) -> Self { // Safety: we will never return anythning else than a Pin<Rc> unsafe { Self($Rc::downgrade(&Pin::into_inner_unchecked(rc))) } } /// Equivalent function to `Weak::upgrade` but returning a `Pin< #[doc = $rc_lit] /// <T>>` instead. pub fn upgrade(&self) -> Option<Pin<$Rc<T>>> { // Safety: the weak was contructed from a Pin<Rc<T>> self.0.upgrade().map(|rc| unsafe { Pin::new_unchecked(rc) }) } } #[test] fn test() { struct Foo { _p: core::marker::PhantomPinned, u: u32, } impl Foo { fn new(u: u32) -> Self { Self { _p: core::marker::PhantomPinned, u } } } let c = $Rc::pin(Foo::new(44)); let weak1 = PinWeak::downgrade(c.clone()); assert_eq!(weak1.upgrade().unwrap().u, 44); assert_eq!(weak1.clone().upgrade().unwrap().u, 44); let weak2 = PinWeak::downgrade(c.clone()); assert_eq!(weak2.upgrade().unwrap().u, 44); assert_eq!(weak1.upgrade().unwrap().u, 44); // note that this moves c and therefore it will be dropped let weak3 = PinWeak::downgrade(c); assert!(weak3.upgrade().is_none()); assert!(weak2.upgrade().is_none()); assert!(weak1.upgrade().is_none()); assert!(weak1.clone().upgrade().is_none()); let def = PinWeak::<alloc::boxed::Box<&'static mut ()>>::default(); assert!(def.upgrade().is_none()); assert!(def.clone().upgrade().is_none()); } }; } pub mod rc { #[doc(no_inline)] /// re-exported for convinience pub use alloc::rc::{Rc, Weak}; implementation! {Rc, Weak, "Rc"} } pub mod sync { #[doc(no_inline)] /// re-exported for convinience pub use alloc::sync::{Arc, Weak}; implementation! {Arc, Weak, "Arc"} }
//! //! Traits for fields //! use crate::internal::Fields; use crate::Field; /// Provides methods to add fields to elements. pub trait FieldExt { /// Add a single field. fn add_field(&mut self, field: Field) -> &mut Self; /// Add multiple fields at once. fn add_fields<'a>(&mut self, fields: impl IntoIterator<Item = &'a Field>) -> &mut Self; } impl<T: Fields> FieldExt for T { /// Add a single field. fn add_field(&mut self, field: Field) -> &mut Self { self.fields_mut().push(field); self } /// Add multiple fields at once. fn add_fields<'a>(&mut self, fields: impl IntoIterator<Item = &'a Field>) -> &mut Self { self.fields_mut() .extend(fields.into_iter().map(ToOwned::to_owned)); self } }
#[allow(unused)] mod graphics; use graphics::{shader::*, vao::VertexArrayObject}; use sdl2::{ event::{Event, WindowEvent}, keyboard::{Mod, Scancode}, mouse::*, }; use std::path::Path; fn aspect_ratio(width: i32, height: i32) -> (f32, f32) { if width > height { (width as f32 / height as f32, 1.0) } else { (1.0, height as f32 / width as f32) } } fn main() -> Result<(), String> { let sdl = sdl2::init()?; // Initialize sdl2 crate let video_subsystem = sdl.video()?; // Get the video subsystem // Setup some opengl attributes let gl_attr = video_subsystem.gl_attr(); // Get the attributes gl_attr.set_context_profile(sdl2::video::GLProfile::Core); // Profile gl_attr.set_context_version(4, 0); // Version // Create a new window let window = video_subsystem .window("Mandelbrot", 500, 500) .resizable() .maximized() .opengl() .build() .unwrap(); // Make it the current opengl context let _glcontext = window.gl_create_context()?; // Load OpenGL functions let _gl = gl::load_with(|s| video_subsystem.gl_get_proc_address(s) as *const _); // Load the vertex shader form the file and compile it let vs_fractal = VertexShader::new(Path::new("shaders/fractal.vert"))?; // Load the fragment shader form the file and compile it let fs_fractal = FragmentShader::new(Path::new("shaders/dfractal.frag"))?; // Link the shaders to the program and compile it let fractal_program = Program::new(&vs_fractal, None, None, None, &fs_fractal)?; Program::bind(&fractal_program); // Retrive the location of the uniforms let aspect_loc = fractal_program.uniform_location("Aspect")?; let offset_loc = fractal_program.uniform_location("Offset")?; let iter_loc = fractal_program.uniform_location("iIterations")?; let zoom_loc = fractal_program.uniform_location("Zoom")?; let size_loc = fractal_program.uniform_location("iSize").unwrap_or(-1); // Initial window size let window_size = window.size(); unsafe { // Send the initial size to OpenGL gl::Uniform2i(size_loc, window_size.0 as i32, window_size.1 as i32); } // Tuple holding the normalized width and height of the window let mut aspect = aspect_ratio(window_size.0 as i32, window_size.1 as i32); unsafe { // Send the initial size to OpenGL gl::Uniform2f(aspect_loc, aspect.0, aspect.1); } // Tuple holding the offset from the center let mut offset = (-0.75, 0.0); unsafe { // Send the initial offset to OpenGL gl::Uniform2d(offset_loc, offset.0, offset.1); } let mut px_size = ( aspect.0 / window_size.0 as f32 * 2.0, aspect.1 / window_size.1 as f32 * 2.0, ); // Number of iterations to compute let mut iterations = 1; unsafe { // Send the initial number of maximum iterations to OpenGL gl::Uniform1i(iter_loc, iterations); } // Amount of zoom let mut zoom = 1.0; unsafe { // Send the initial zoom to OpenGL gl::Uniform1f(zoom_loc, zoom); } // Create and bind a vertex array object let vao = VertexArrayObject::new(); VertexArrayObject::bind(&vao); // Generate an event pump let mut event_pump = sdl.event_pump()?; // Flag that indicates whether or not the left mouse button is being pressed let mut pressing = false; // Flag that indicates if the screen needs to be updated let mut update = true; // Start the main loop 'main: loop { for event in event_pump.poll_iter() { match event { // Window is closing Event::Quit { .. } => return Ok(()), // ----- WINDOW EVENTS ----- Event::Window { win_event, .. } => match win_event { WindowEvent::Resized(width, height) => { // Normalize the size of the window aspect = aspect_ratio(width, height); // Calculate the new pixel size px_size.0 = aspect.0 / width as f32 * 2.0; px_size.1 = aspect.1 / height as f32 * 2.0; unsafe { // Update the OpenGL viewport gl::Viewport(0, 0, width, height); // Send the normalized size to OpenGL gl::Uniform2f(aspect_loc, aspect.0, aspect.1); gl::Uniform2i(size_loc, width, height); } update = true; } _ => {} }, // ----- KEYBOARD EVENTS ------ // A key was pressed Event::KeyDown { scancode: Some(key), keymod: k, .. } => match key { // The plus(+) was pressed Scancode::KpPlus => { if k.intersects(Mod::LCTRLMOD | Mod::RCTRLMOD) { iterations += 100; } else { iterations += 1; } unsafe { gl::Uniform1i(iter_loc, iterations); } update = true; } // The minus(-) was pressed Scancode::KpMinus if iterations > 1 => { if k.intersects(Mod::LCTRLMOD | Mod::RCTRLMOD) { if iterations > 100 { iterations -= 100; } else { iterations = 1; } } else { iterations -= 1; } unsafe { gl::Uniform1i(iter_loc, iterations); } update = true; } _ => {} }, // ----- MOUSE EVENTS ----- // A mouse button is being pressed Event::MouseButtonDown { mouse_btn, .. } => match mouse_btn { // If it's the left button MouseButton::Left => pressing = true, _ => {} }, // A mouse button is being released Event::MouseButtonUp { mouse_btn, .. } => match mouse_btn { // If it's the left button MouseButton::Left => pressing = false, _ => {} }, // The user is dragging Event::MouseMotion { xrel, yrel, .. } if pressing => { // Calculate the new offset offset.0 -= xrel as f64 * px_size.0 as f64 / zoom as f64; offset.1 += yrel as f64 * px_size.1 as f64 / zoom as f64; unsafe { // Update the offset uniform gl::Uniform2d(offset_loc, offset.0, offset.1); } update = true; } // The mouse wheel is being scrolled Event::MouseWheel { y, .. } => { // Increase/decrase the zoom zoom += y as f32 * zoom * 0.1; unsafe { // Update the zoom uniform gl::Uniform1f(zoom_loc, zoom); } update = true; } _ => {} } } if update { unsafe { gl::Clear(gl::COLOR_BUFFER_BIT); gl::DrawArrays(gl::TRIANGLES, 0, 6); } window.gl_swap_window(); update = false; // DEBUG MESSAGES // println!("Iterations: {}", iterations); // println!("Offset: {:4}, {:4}", offset.0, offset.1); // println!("Zoom: {}", zoom); // println!("Window: {:4}, {:4}", window.size().0, window.size().1); // println!("Aspect: {:4}, {:4}", aspect.0, aspect.1); } } }