text
stringlengths
8
4.13M
use crate::vm::{ builtins::PyListRef, builtins::PyModule, PyObject, PyObjectRef, PyRef, PyResult, TryFromObject, VirtualMachine, }; use std::{io, mem}; pub(crate) fn make_module(vm: &VirtualMachine) -> PyRef<PyModule> { #[cfg(windows)] crate::vm::stdlib::nt::init_winsock(); #[cfg(unix)] { use crate::vm::class::PyClassImpl; decl::poll::PyPoll::make_class(&vm.ctx); } decl::make_module(vm) } #[cfg(unix)] mod platform { pub use libc::{fd_set, select, timeval, FD_ISSET, FD_SET, FD_SETSIZE, FD_ZERO}; pub use std::os::unix::io::RawFd; pub fn check_err(x: i32) -> bool { x < 0 } } #[allow(non_snake_case)] #[cfg(windows)] mod platform { use winapi::um::winsock2; pub use winsock2::{fd_set, select, timeval, FD_SETSIZE, SOCKET as RawFd}; // based off winsock2.h: https://gist.github.com/piscisaureus/906386#file-winsock2-h-L128-L141 pub unsafe fn FD_SET(fd: RawFd, set: *mut fd_set) { let mut slot = std::ptr::addr_of_mut!((*set).fd_array).cast::<RawFd>(); let fd_count = (*set).fd_count; for _ in 0..fd_count { if *slot == fd { return; } slot = slot.add(1); } // slot == &fd_array[fd_count] at this point if fd_count < FD_SETSIZE as u32 { *slot = fd as RawFd; (*set).fd_count += 1; } } pub unsafe fn FD_ZERO(set: *mut fd_set) { (*set).fd_count = 0; } pub unsafe fn FD_ISSET(fd: RawFd, set: *mut fd_set) -> bool { use winapi::um::winsock2::__WSAFDIsSet; __WSAFDIsSet(fd as _, set) != 0 } pub fn check_err(x: i32) -> bool { x == winsock2::SOCKET_ERROR } } pub use platform::timeval; use platform::RawFd; #[derive(Traverse)] struct Selectable { obj: PyObjectRef, #[pytraverse(skip)] fno: RawFd, } impl TryFromObject for Selectable { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { let fno = obj.try_to_value(vm).or_else(|_| { let meth = vm.get_method_or_type_error( obj.clone(), vm.ctx.interned_str("fileno").unwrap(), || "select arg must be an int or object with a fileno() method".to_owned(), )?; meth.call((), vm)?.try_into_value(vm) })?; Ok(Selectable { obj, fno }) } } // Keep it in a MaybeUninit, since on windows FD_ZERO doesn't actually zero the whole thing #[repr(transparent)] pub struct FdSet(mem::MaybeUninit<platform::fd_set>); impl FdSet { pub fn new() -> FdSet { // it's just ints, and all the code that's actually // interacting with it is in C, so it's safe to zero let mut fdset = std::mem::MaybeUninit::zeroed(); unsafe { platform::FD_ZERO(fdset.as_mut_ptr()) }; FdSet(fdset) } pub fn insert(&mut self, fd: RawFd) { unsafe { platform::FD_SET(fd, self.0.as_mut_ptr()) }; } pub fn contains(&mut self, fd: RawFd) -> bool { unsafe { platform::FD_ISSET(fd, self.0.as_mut_ptr()) } } pub fn clear(&mut self) { unsafe { platform::FD_ZERO(self.0.as_mut_ptr()) }; } pub fn highest(&mut self) -> Option<RawFd> { (0..platform::FD_SETSIZE as RawFd) .rev() .find(|&i| self.contains(i)) } } pub fn select( nfds: libc::c_int, readfds: &mut FdSet, writefds: &mut FdSet, errfds: &mut FdSet, timeout: Option<&mut timeval>, ) -> io::Result<i32> { let timeout = match timeout { Some(tv) => tv as *mut timeval, None => std::ptr::null_mut(), }; let ret = unsafe { platform::select( nfds, readfds.0.as_mut_ptr(), writefds.0.as_mut_ptr(), errfds.0.as_mut_ptr(), timeout, ) }; if platform::check_err(ret) { Err(io::Error::last_os_error()) } else { Ok(ret) } } fn sec_to_timeval(sec: f64) -> timeval { timeval { tv_sec: sec.trunc() as _, tv_usec: (sec.fract() * 1e6) as _, } } #[pymodule(name = "select")] mod decl { use super::*; use crate::vm::{ builtins::PyTypeRef, convert::ToPyException, function::{Either, OptionalOption}, stdlib::time, PyObjectRef, PyResult, VirtualMachine, }; #[pyattr] fn error(vm: &VirtualMachine) -> PyTypeRef { vm.ctx.exceptions.os_error.to_owned() } #[pyfunction] fn select( rlist: PyObjectRef, wlist: PyObjectRef, xlist: PyObjectRef, timeout: OptionalOption<Either<f64, isize>>, vm: &VirtualMachine, ) -> PyResult<(PyListRef, PyListRef, PyListRef)> { let mut timeout = timeout.flatten().map(|e| match e { Either::A(f) => f, Either::B(i) => i as f64, }); if let Some(timeout) = timeout { if timeout < 0.0 { return Err(vm.new_value_error("timeout must be positive".to_owned())); } } let deadline = timeout.map(|s| time::time(vm).unwrap() + s); let seq2set = |list: &PyObject| -> PyResult<(Vec<Selectable>, FdSet)> { let v: Vec<Selectable> = list.try_to_value(vm)?; let mut fds = FdSet::new(); for fd in &v { fds.insert(fd.fno); } Ok((v, fds)) }; let (rlist, mut r) = seq2set(&rlist)?; let (wlist, mut w) = seq2set(&wlist)?; let (xlist, mut x) = seq2set(&xlist)?; if rlist.is_empty() && wlist.is_empty() && xlist.is_empty() { let empty = vm.ctx.new_list(vec![]); return Ok((empty.clone(), empty.clone(), empty)); } let nfds: i32 = [&mut r, &mut w, &mut x] .iter_mut() .filter_map(|set| set.highest()) .max() .map_or(0, |n| n + 1) as _; loop { let mut tv = timeout.map(sec_to_timeval); let res = super::select(nfds, &mut r, &mut w, &mut x, tv.as_mut()); match res { Ok(_) => break, Err(err) if err.kind() == io::ErrorKind::Interrupted => {} Err(err) => return Err(err.to_pyexception(vm)), } vm.check_signals()?; if let Some(ref mut timeout) = timeout { *timeout = deadline.unwrap() - time::time(vm).unwrap(); if *timeout < 0.0 { r.clear(); w.clear(); x.clear(); break; } // retry select() if we haven't reached the deadline yet } } let set2list = |list: Vec<Selectable>, mut set: FdSet| { vm.ctx.new_list( list.into_iter() .filter(|fd| set.contains(fd.fno)) .map(|fd| fd.obj) .collect(), ) }; let rlist = set2list(rlist, r); let wlist = set2list(wlist, w); let xlist = set2list(xlist, x); Ok((rlist, wlist, xlist)) } #[cfg(unix)] #[pyfunction] fn poll() -> poll::PyPoll { poll::PyPoll::default() } #[cfg(unix)] #[pyattr] use libc::{POLLERR, POLLHUP, POLLIN, POLLNVAL, POLLOUT, POLLPRI}; #[cfg(unix)] pub(super) mod poll { use super::*; use crate::vm::{ builtins::PyFloat, common::lock::PyMutex, convert::ToPyObject, function::OptionalArg, stdlib::io::Fildes, AsObject, PyPayload, }; use libc::pollfd; use num_traits::ToPrimitive; use std::time; #[pyclass(module = "select", name = "poll")] #[derive(Default, Debug, PyPayload)] pub struct PyPoll { // keep sorted fds: PyMutex<Vec<pollfd>>, } #[inline] fn search(fds: &[pollfd], fd: i32) -> Result<usize, usize> { fds.binary_search_by_key(&fd, |pfd| pfd.fd) } fn insert_fd(fds: &mut Vec<pollfd>, fd: i32, events: i16) { match search(fds, fd) { Ok(i) => fds[i].events = events, Err(i) => fds.insert( i, pollfd { fd, events, revents: 0, }, ), } } fn get_fd_mut(fds: &mut [pollfd], fd: i32) -> Option<&mut pollfd> { search(fds, fd).ok().map(move |i| &mut fds[i]) } fn remove_fd(fds: &mut Vec<pollfd>, fd: i32) -> Option<pollfd> { search(fds, fd).ok().map(|i| fds.remove(i)) } const DEFAULT_EVENTS: i16 = libc::POLLIN | libc::POLLPRI | libc::POLLOUT; #[pyclass] impl PyPoll { #[pymethod] fn register(&self, Fildes(fd): Fildes, eventmask: OptionalArg<u16>) { insert_fd( &mut self.fds.lock(), fd, eventmask.map_or(DEFAULT_EVENTS, |e| e as i16), ) } #[pymethod] fn modify(&self, Fildes(fd): Fildes, eventmask: u16) -> io::Result<()> { let mut fds = self.fds.lock(); let pfd = get_fd_mut(&mut fds, fd) .ok_or_else(|| io::Error::from_raw_os_error(libc::ENOENT))?; pfd.events = eventmask as i16; Ok(()) } #[pymethod] fn unregister(&self, Fildes(fd): Fildes, vm: &VirtualMachine) -> PyResult<()> { let removed = remove_fd(&mut self.fds.lock(), fd); removed .map(drop) .ok_or_else(|| vm.new_key_error(vm.ctx.new_int(fd).into())) } #[pymethod] fn poll( &self, timeout: OptionalOption, vm: &VirtualMachine, ) -> PyResult<Vec<PyObjectRef>> { let mut fds = self.fds.lock(); let timeout_ms = match timeout.flatten() { Some(ms) => { let ms = if let Some(float) = ms.payload::<PyFloat>() { float.to_f64().to_i32() } else if let Some(int) = ms.try_index_opt(vm) { int?.as_bigint().to_i32() } else { return Err(vm.new_type_error(format!( "expected an int or float for duration, got {}", ms.class() ))); }; ms.ok_or_else(|| vm.new_value_error("value out of range".to_owned()))? } None => -1, }; let timeout_ms = if timeout_ms < 0 { -1 } else { timeout_ms }; let deadline = (timeout_ms >= 0) .then(|| time::Instant::now() + time::Duration::from_millis(timeout_ms as u64)); let mut poll_timeout = timeout_ms; loop { let res = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as _, poll_timeout) }; let res = if res < 0 { Err(io::Error::last_os_error()) } else { Ok(()) }; match res { Ok(()) => break, Err(e) if e.kind() == io::ErrorKind::Interrupted => { vm.check_signals()?; if let Some(d) = deadline { match d.checked_duration_since(time::Instant::now()) { Some(remaining) => poll_timeout = remaining.as_millis() as i32, // we've timed out None => break, } } } Err(e) => return Err(e.to_pyexception(vm)), } } Ok(fds .iter() .filter(|pfd| pfd.revents != 0) .map(|pfd| (pfd.fd, pfd.revents & 0xfff).to_pyobject(vm)) .collect()) } } } }
extern crate quicksilver; use quicksilver::{ Result, geom::{Shape, Rectangle, Vector}, graphics::{Background::Col, Color}, input::MouseCursor, lifecycle::{Event, Settings, State, Window, run} }; struct RectangleState { grab_rect: Rectangle, crosshair_rect: Rectangle, } impl State for RectangleState { fn new() -> Result<Self> { Ok(RectangleState { grab_rect: Rectangle::new((0, 0), (200, 100)).with_center((400, 100)), crosshair_rect: Rectangle::new((0, 0), (200, 100)).with_center((400, 400)), }) } fn event(&mut self, event: &Event, window: &mut Window) -> Result<()> { match event { Event::MouseMoved(vector) => { if vector.overlaps_rectangle(&self.crosshair_rect) { window.set_cursor(MouseCursor::Crosshair); } else if vector.overlaps_rectangle(&self.grab_rect) { window.set_cursor(MouseCursor::Grab); } else { window.set_cursor(MouseCursor::Default); } } _ => {} }; Ok(()) } fn draw(&mut self, window: &mut Window) -> Result<()> { window.clear(Color::BLACK)?; window.draw(&self.grab_rect, Col(Color::RED)); window.draw(&self.crosshair_rect, Col(Color::GREEN)); Ok(()) } } fn main() { run::<RectangleState>("set-cursor", Vector::new(800, 600), Settings::default()); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GameSaveBlobGetResult(pub ::windows::core::IInspectable); impl GameSaveBlobGetResult { pub fn Status(&self) -> ::windows::core::Result<GameSaveErrorStatus> { let this = self; unsafe { let mut result__: GameSaveErrorStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GameSaveErrorStatus>(result__) } } #[cfg(all(feature = "Foundation_Collections", feature = "Storage_Streams"))] pub fn Value(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, super::super::super::Storage::Streams::IBuffer>> { 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::IMapView<::windows::core::HSTRING, super::super::super::Storage::Streams::IBuffer>>(result__) } } } unsafe impl ::windows::core::RuntimeType for GameSaveBlobGetResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.XboxLive.Storage.GameSaveBlobGetResult;{917281e0-7201-4953-aa2c-4008f03aef45})"); } unsafe impl ::windows::core::Interface for GameSaveBlobGetResult { type Vtable = IGameSaveBlobGetResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x917281e0_7201_4953_aa2c_4008f03aef45); } impl ::windows::core::RuntimeName for GameSaveBlobGetResult { const NAME: &'static str = "Windows.Gaming.XboxLive.Storage.GameSaveBlobGetResult"; } impl ::core::convert::From<GameSaveBlobGetResult> for ::windows::core::IUnknown { fn from(value: GameSaveBlobGetResult) -> Self { value.0 .0 } } impl ::core::convert::From<&GameSaveBlobGetResult> for ::windows::core::IUnknown { fn from(value: &GameSaveBlobGetResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameSaveBlobGetResult { 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 GameSaveBlobGetResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GameSaveBlobGetResult> for ::windows::core::IInspectable { fn from(value: GameSaveBlobGetResult) -> Self { value.0 } } impl ::core::convert::From<&GameSaveBlobGetResult> for ::windows::core::IInspectable { fn from(value: &GameSaveBlobGetResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameSaveBlobGetResult { 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 GameSaveBlobGetResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GameSaveBlobGetResult {} unsafe impl ::core::marker::Sync for GameSaveBlobGetResult {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GameSaveBlobInfo(pub ::windows::core::IInspectable); impl GameSaveBlobInfo { pub fn Name(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Size(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } } unsafe impl ::windows::core::RuntimeType for GameSaveBlobInfo { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.XboxLive.Storage.GameSaveBlobInfo;{add38034-baf0-4645-b6d0-46edaffb3c2b})"); } unsafe impl ::windows::core::Interface for GameSaveBlobInfo { type Vtable = IGameSaveBlobInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xadd38034_baf0_4645_b6d0_46edaffb3c2b); } impl ::windows::core::RuntimeName for GameSaveBlobInfo { const NAME: &'static str = "Windows.Gaming.XboxLive.Storage.GameSaveBlobInfo"; } impl ::core::convert::From<GameSaveBlobInfo> for ::windows::core::IUnknown { fn from(value: GameSaveBlobInfo) -> Self { value.0 .0 } } impl ::core::convert::From<&GameSaveBlobInfo> for ::windows::core::IUnknown { fn from(value: &GameSaveBlobInfo) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameSaveBlobInfo { 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 GameSaveBlobInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GameSaveBlobInfo> for ::windows::core::IInspectable { fn from(value: GameSaveBlobInfo) -> Self { value.0 } } impl ::core::convert::From<&GameSaveBlobInfo> for ::windows::core::IInspectable { fn from(value: &GameSaveBlobInfo) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameSaveBlobInfo { 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 GameSaveBlobInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GameSaveBlobInfo {} unsafe impl ::core::marker::Sync for GameSaveBlobInfo {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GameSaveBlobInfoGetResult(pub ::windows::core::IInspectable); impl GameSaveBlobInfoGetResult { pub fn Status(&self) -> ::windows::core::Result<GameSaveErrorStatus> { let this = self; unsafe { let mut result__: GameSaveErrorStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GameSaveErrorStatus>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Value(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<GameSaveBlobInfo>> { 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::IVectorView<GameSaveBlobInfo>>(result__) } } } unsafe impl ::windows::core::RuntimeType for GameSaveBlobInfoGetResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.XboxLive.Storage.GameSaveBlobInfoGetResult;{c7578582-3697-42bf-989c-665d923b5231})"); } unsafe impl ::windows::core::Interface for GameSaveBlobInfoGetResult { type Vtable = IGameSaveBlobInfoGetResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc7578582_3697_42bf_989c_665d923b5231); } impl ::windows::core::RuntimeName for GameSaveBlobInfoGetResult { const NAME: &'static str = "Windows.Gaming.XboxLive.Storage.GameSaveBlobInfoGetResult"; } impl ::core::convert::From<GameSaveBlobInfoGetResult> for ::windows::core::IUnknown { fn from(value: GameSaveBlobInfoGetResult) -> Self { value.0 .0 } } impl ::core::convert::From<&GameSaveBlobInfoGetResult> for ::windows::core::IUnknown { fn from(value: &GameSaveBlobInfoGetResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameSaveBlobInfoGetResult { 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 GameSaveBlobInfoGetResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GameSaveBlobInfoGetResult> for ::windows::core::IInspectable { fn from(value: GameSaveBlobInfoGetResult) -> Self { value.0 } } impl ::core::convert::From<&GameSaveBlobInfoGetResult> for ::windows::core::IInspectable { fn from(value: &GameSaveBlobInfoGetResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameSaveBlobInfoGetResult { 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 GameSaveBlobInfoGetResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GameSaveBlobInfoGetResult {} unsafe impl ::core::marker::Sync for GameSaveBlobInfoGetResult {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GameSaveBlobInfoQuery(pub ::windows::core::IInspectable); impl GameSaveBlobInfoQuery { #[cfg(feature = "Foundation")] pub fn GetBlobInfoAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<GameSaveBlobInfoGetResult>> { 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::IAsyncOperation<GameSaveBlobInfoGetResult>>(result__) } } #[cfg(feature = "Foundation")] pub fn GetBlobInfoWithIndexAndMaxAsync(&self, startindex: u32, maxnumberofitems: u32) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<GameSaveBlobInfoGetResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), startindex, maxnumberofitems, &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<GameSaveBlobInfoGetResult>>(result__) } } #[cfg(feature = "Foundation")] pub fn GetItemCountAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<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::super::Foundation::IAsyncOperation<u32>>(result__) } } } unsafe impl ::windows::core::RuntimeType for GameSaveBlobInfoQuery { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.XboxLive.Storage.GameSaveBlobInfoQuery;{9fdd74b2-eeee-447b-a9d2-7f96c0f83208})"); } unsafe impl ::windows::core::Interface for GameSaveBlobInfoQuery { type Vtable = IGameSaveBlobInfoQuery_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9fdd74b2_eeee_447b_a9d2_7f96c0f83208); } impl ::windows::core::RuntimeName for GameSaveBlobInfoQuery { const NAME: &'static str = "Windows.Gaming.XboxLive.Storage.GameSaveBlobInfoQuery"; } impl ::core::convert::From<GameSaveBlobInfoQuery> for ::windows::core::IUnknown { fn from(value: GameSaveBlobInfoQuery) -> Self { value.0 .0 } } impl ::core::convert::From<&GameSaveBlobInfoQuery> for ::windows::core::IUnknown { fn from(value: &GameSaveBlobInfoQuery) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameSaveBlobInfoQuery { 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 GameSaveBlobInfoQuery { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GameSaveBlobInfoQuery> for ::windows::core::IInspectable { fn from(value: GameSaveBlobInfoQuery) -> Self { value.0 } } impl ::core::convert::From<&GameSaveBlobInfoQuery> for ::windows::core::IInspectable { fn from(value: &GameSaveBlobInfoQuery) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameSaveBlobInfoQuery { 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 GameSaveBlobInfoQuery { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GameSaveBlobInfoQuery {} unsafe impl ::core::marker::Sync for GameSaveBlobInfoQuery {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GameSaveContainer(pub ::windows::core::IInspectable); impl GameSaveContainer { pub fn Name(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn Provider(&self) -> ::windows::core::Result<GameSaveProvider> { 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::<GameSaveProvider>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams"))] pub fn SubmitUpdatesAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, super::super::super::Storage::Streams::IBuffer>>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( &self, blobstowrite: Param0, blobstodelete: Param1, displayname: Param2, ) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<GameSaveOperationResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), blobstowrite.into_param().abi(), blobstodelete.into_param().abi(), displayname.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<GameSaveOperationResult>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams"))] pub fn ReadAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, super::super::super::Storage::Streams::IBuffer>>>(&self, blobstoread: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<GameSaveOperationResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), blobstoread.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<GameSaveOperationResult>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(&self, blobstoread: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<GameSaveBlobGetResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), blobstoread.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<GameSaveBlobGetResult>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn SubmitPropertySetUpdatesAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IPropertySet>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( &self, blobstowrite: Param0, blobstodelete: Param1, displayname: Param2, ) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<GameSaveOperationResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), blobstowrite.into_param().abi(), blobstodelete.into_param().abi(), displayname.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<GameSaveOperationResult>>(result__) } } pub fn CreateBlobInfoQuery<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, blobnameprefix: Param0) -> ::windows::core::Result<GameSaveBlobInfoQuery> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), blobnameprefix.into_param().abi(), &mut result__).from_abi::<GameSaveBlobInfoQuery>(result__) } } } unsafe impl ::windows::core::RuntimeType for GameSaveContainer { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.XboxLive.Storage.GameSaveContainer;{c3c08f89-563f-4ecd-9c6f-33fd0e323d10})"); } unsafe impl ::windows::core::Interface for GameSaveContainer { type Vtable = IGameSaveContainer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc3c08f89_563f_4ecd_9c6f_33fd0e323d10); } impl ::windows::core::RuntimeName for GameSaveContainer { const NAME: &'static str = "Windows.Gaming.XboxLive.Storage.GameSaveContainer"; } impl ::core::convert::From<GameSaveContainer> for ::windows::core::IUnknown { fn from(value: GameSaveContainer) -> Self { value.0 .0 } } impl ::core::convert::From<&GameSaveContainer> for ::windows::core::IUnknown { fn from(value: &GameSaveContainer) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameSaveContainer { 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 GameSaveContainer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GameSaveContainer> for ::windows::core::IInspectable { fn from(value: GameSaveContainer) -> Self { value.0 } } impl ::core::convert::From<&GameSaveContainer> for ::windows::core::IInspectable { fn from(value: &GameSaveContainer) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameSaveContainer { 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 GameSaveContainer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GameSaveContainer {} unsafe impl ::core::marker::Sync for GameSaveContainer {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GameSaveContainerInfo(pub ::windows::core::IInspectable); impl GameSaveContainerInfo { pub fn Name(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn TotalSize(&self) -> ::windows::core::Result<u64> { let this = self; unsafe { let mut result__: u64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__) } } pub fn DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn LastModifiedTime(&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).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::DateTime>(result__) } } pub fn NeedsSync(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for GameSaveContainerInfo { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.XboxLive.Storage.GameSaveContainerInfo;{b7e27300-155d-4bb4-b2ba-930306f391b5})"); } unsafe impl ::windows::core::Interface for GameSaveContainerInfo { type Vtable = IGameSaveContainerInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb7e27300_155d_4bb4_b2ba_930306f391b5); } impl ::windows::core::RuntimeName for GameSaveContainerInfo { const NAME: &'static str = "Windows.Gaming.XboxLive.Storage.GameSaveContainerInfo"; } impl ::core::convert::From<GameSaveContainerInfo> for ::windows::core::IUnknown { fn from(value: GameSaveContainerInfo) -> Self { value.0 .0 } } impl ::core::convert::From<&GameSaveContainerInfo> for ::windows::core::IUnknown { fn from(value: &GameSaveContainerInfo) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameSaveContainerInfo { 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 GameSaveContainerInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GameSaveContainerInfo> for ::windows::core::IInspectable { fn from(value: GameSaveContainerInfo) -> Self { value.0 } } impl ::core::convert::From<&GameSaveContainerInfo> for ::windows::core::IInspectable { fn from(value: &GameSaveContainerInfo) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameSaveContainerInfo { 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 GameSaveContainerInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GameSaveContainerInfo {} unsafe impl ::core::marker::Sync for GameSaveContainerInfo {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GameSaveContainerInfoGetResult(pub ::windows::core::IInspectable); impl GameSaveContainerInfoGetResult { pub fn Status(&self) -> ::windows::core::Result<GameSaveErrorStatus> { let this = self; unsafe { let mut result__: GameSaveErrorStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GameSaveErrorStatus>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Value(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<GameSaveContainerInfo>> { 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::IVectorView<GameSaveContainerInfo>>(result__) } } } unsafe impl ::windows::core::RuntimeType for GameSaveContainerInfoGetResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.XboxLive.Storage.GameSaveContainerInfoGetResult;{ffc50d74-c581-4f9d-9e39-30a10c1e4c50})"); } unsafe impl ::windows::core::Interface for GameSaveContainerInfoGetResult { type Vtable = IGameSaveContainerInfoGetResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xffc50d74_c581_4f9d_9e39_30a10c1e4c50); } impl ::windows::core::RuntimeName for GameSaveContainerInfoGetResult { const NAME: &'static str = "Windows.Gaming.XboxLive.Storage.GameSaveContainerInfoGetResult"; } impl ::core::convert::From<GameSaveContainerInfoGetResult> for ::windows::core::IUnknown { fn from(value: GameSaveContainerInfoGetResult) -> Self { value.0 .0 } } impl ::core::convert::From<&GameSaveContainerInfoGetResult> for ::windows::core::IUnknown { fn from(value: &GameSaveContainerInfoGetResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameSaveContainerInfoGetResult { 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 GameSaveContainerInfoGetResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GameSaveContainerInfoGetResult> for ::windows::core::IInspectable { fn from(value: GameSaveContainerInfoGetResult) -> Self { value.0 } } impl ::core::convert::From<&GameSaveContainerInfoGetResult> for ::windows::core::IInspectable { fn from(value: &GameSaveContainerInfoGetResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameSaveContainerInfoGetResult { 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 GameSaveContainerInfoGetResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GameSaveContainerInfoGetResult {} unsafe impl ::core::marker::Sync for GameSaveContainerInfoGetResult {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GameSaveContainerInfoQuery(pub ::windows::core::IInspectable); impl GameSaveContainerInfoQuery { #[cfg(feature = "Foundation")] pub fn GetContainerInfoAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<GameSaveContainerInfoGetResult>> { 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::IAsyncOperation<GameSaveContainerInfoGetResult>>(result__) } } #[cfg(feature = "Foundation")] pub fn GetContainerInfoWithIndexAndMaxAsync(&self, startindex: u32, maxnumberofitems: u32) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<GameSaveContainerInfoGetResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), startindex, maxnumberofitems, &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<GameSaveContainerInfoGetResult>>(result__) } } #[cfg(feature = "Foundation")] pub fn GetItemCountAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<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::super::Foundation::IAsyncOperation<u32>>(result__) } } } unsafe impl ::windows::core::RuntimeType for GameSaveContainerInfoQuery { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.XboxLive.Storage.GameSaveContainerInfoQuery;{3c94e863-6f80-4327-9327-ffc11afd42b3})"); } unsafe impl ::windows::core::Interface for GameSaveContainerInfoQuery { type Vtable = IGameSaveContainerInfoQuery_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c94e863_6f80_4327_9327_ffc11afd42b3); } impl ::windows::core::RuntimeName for GameSaveContainerInfoQuery { const NAME: &'static str = "Windows.Gaming.XboxLive.Storage.GameSaveContainerInfoQuery"; } impl ::core::convert::From<GameSaveContainerInfoQuery> for ::windows::core::IUnknown { fn from(value: GameSaveContainerInfoQuery) -> Self { value.0 .0 } } impl ::core::convert::From<&GameSaveContainerInfoQuery> for ::windows::core::IUnknown { fn from(value: &GameSaveContainerInfoQuery) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameSaveContainerInfoQuery { 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 GameSaveContainerInfoQuery { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GameSaveContainerInfoQuery> for ::windows::core::IInspectable { fn from(value: GameSaveContainerInfoQuery) -> Self { value.0 } } impl ::core::convert::From<&GameSaveContainerInfoQuery> for ::windows::core::IInspectable { fn from(value: &GameSaveContainerInfoQuery) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameSaveContainerInfoQuery { 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 GameSaveContainerInfoQuery { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GameSaveContainerInfoQuery {} unsafe impl ::core::marker::Sync for GameSaveContainerInfoQuery {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GameSaveErrorStatus(pub i32); impl GameSaveErrorStatus { pub const Ok: GameSaveErrorStatus = GameSaveErrorStatus(0i32); pub const Abort: GameSaveErrorStatus = GameSaveErrorStatus(-2147467260i32); pub const InvalidContainerName: GameSaveErrorStatus = GameSaveErrorStatus(-2138898431i32); pub const NoAccess: GameSaveErrorStatus = GameSaveErrorStatus(-2138898430i32); pub const OutOfLocalStorage: GameSaveErrorStatus = GameSaveErrorStatus(-2138898429i32); pub const UserCanceled: GameSaveErrorStatus = GameSaveErrorStatus(-2138898428i32); pub const UpdateTooBig: GameSaveErrorStatus = GameSaveErrorStatus(-2138898427i32); pub const QuotaExceeded: GameSaveErrorStatus = GameSaveErrorStatus(-2138898426i32); pub const ProvidedBufferTooSmall: GameSaveErrorStatus = GameSaveErrorStatus(-2138898425i32); pub const BlobNotFound: GameSaveErrorStatus = GameSaveErrorStatus(-2138898424i32); pub const NoXboxLiveInfo: GameSaveErrorStatus = GameSaveErrorStatus(-2138898423i32); pub const ContainerNotInSync: GameSaveErrorStatus = GameSaveErrorStatus(-2138898422i32); pub const ContainerSyncFailed: GameSaveErrorStatus = GameSaveErrorStatus(-2138898421i32); pub const UserHasNoXboxLiveInfo: GameSaveErrorStatus = GameSaveErrorStatus(-2138898420i32); pub const ObjectExpired: GameSaveErrorStatus = GameSaveErrorStatus(-2138898419i32); } impl ::core::convert::From<i32> for GameSaveErrorStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GameSaveErrorStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for GameSaveErrorStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Gaming.XboxLive.Storage.GameSaveErrorStatus;i4)"); } impl ::windows::core::DefaultType for GameSaveErrorStatus { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GameSaveOperationResult(pub ::windows::core::IInspectable); impl GameSaveOperationResult { pub fn Status(&self) -> ::windows::core::Result<GameSaveErrorStatus> { let this = self; unsafe { let mut result__: GameSaveErrorStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GameSaveErrorStatus>(result__) } } } unsafe impl ::windows::core::RuntimeType for GameSaveOperationResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.XboxLive.Storage.GameSaveOperationResult;{cf0f1a05-24a0-4582-9a55-b1bbbb9388d8})"); } unsafe impl ::windows::core::Interface for GameSaveOperationResult { type Vtable = IGameSaveOperationResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcf0f1a05_24a0_4582_9a55_b1bbbb9388d8); } impl ::windows::core::RuntimeName for GameSaveOperationResult { const NAME: &'static str = "Windows.Gaming.XboxLive.Storage.GameSaveOperationResult"; } impl ::core::convert::From<GameSaveOperationResult> for ::windows::core::IUnknown { fn from(value: GameSaveOperationResult) -> Self { value.0 .0 } } impl ::core::convert::From<&GameSaveOperationResult> for ::windows::core::IUnknown { fn from(value: &GameSaveOperationResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameSaveOperationResult { 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 GameSaveOperationResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GameSaveOperationResult> for ::windows::core::IInspectable { fn from(value: GameSaveOperationResult) -> Self { value.0 } } impl ::core::convert::From<&GameSaveOperationResult> for ::windows::core::IInspectable { fn from(value: &GameSaveOperationResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameSaveOperationResult { 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 GameSaveOperationResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GameSaveOperationResult {} unsafe impl ::core::marker::Sync for GameSaveOperationResult {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GameSaveProvider(pub ::windows::core::IInspectable); impl GameSaveProvider { #[cfg(feature = "System")] pub fn User(&self) -> ::windows::core::Result<super::super::super::System::User> { 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::System::User>(result__) } } pub fn CreateContainer<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, name: Param0) -> ::windows::core::Result<GameSaveContainer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), name.into_param().abi(), &mut result__).from_abi::<GameSaveContainer>(result__) } } #[cfg(feature = "Foundation")] pub fn DeleteContainerAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, name: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<GameSaveOperationResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), name.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<GameSaveOperationResult>>(result__) } } pub fn CreateContainerInfoQuery(&self) -> ::windows::core::Result<GameSaveContainerInfoQuery> { 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::<GameSaveContainerInfoQuery>(result__) } } pub fn CreateContainerInfoQueryWithName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, containernameprefix: Param0) -> ::windows::core::Result<GameSaveContainerInfoQuery> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), containernameprefix.into_param().abi(), &mut result__).from_abi::<GameSaveContainerInfoQuery>(result__) } } #[cfg(feature = "Foundation")] pub fn GetRemainingBytesInQuotaAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<i64>> { 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::IAsyncOperation<i64>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn ContainersChangedSinceLastSync(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__) } } #[cfg(all(feature = "Foundation", feature = "System"))] pub fn GetForUserAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::System::User>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(user: Param0, serviceconfigid: Param1) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<GameSaveProviderGetResult>> { Self::IGameSaveProviderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), user.into_param().abi(), serviceconfigid.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<GameSaveProviderGetResult>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "System"))] pub fn GetSyncOnDemandForUserAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::System::User>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(user: Param0, serviceconfigid: Param1) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<GameSaveProviderGetResult>> { Self::IGameSaveProviderStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), user.into_param().abi(), serviceconfigid.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<GameSaveProviderGetResult>>(result__) }) } pub fn IGameSaveProviderStatics<R, F: FnOnce(&IGameSaveProviderStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<GameSaveProvider, IGameSaveProviderStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for GameSaveProvider { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.XboxLive.Storage.GameSaveProvider;{90a60394-80fe-4211-97f8-a5de14dd95d2})"); } unsafe impl ::windows::core::Interface for GameSaveProvider { type Vtable = IGameSaveProvider_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x90a60394_80fe_4211_97f8_a5de14dd95d2); } impl ::windows::core::RuntimeName for GameSaveProvider { const NAME: &'static str = "Windows.Gaming.XboxLive.Storage.GameSaveProvider"; } impl ::core::convert::From<GameSaveProvider> for ::windows::core::IUnknown { fn from(value: GameSaveProvider) -> Self { value.0 .0 } } impl ::core::convert::From<&GameSaveProvider> for ::windows::core::IUnknown { fn from(value: &GameSaveProvider) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameSaveProvider { 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 GameSaveProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GameSaveProvider> for ::windows::core::IInspectable { fn from(value: GameSaveProvider) -> Self { value.0 } } impl ::core::convert::From<&GameSaveProvider> for ::windows::core::IInspectable { fn from(value: &GameSaveProvider) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameSaveProvider { 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 GameSaveProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GameSaveProvider {} unsafe impl ::core::marker::Sync for GameSaveProvider {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct GameSaveProviderGetResult(pub ::windows::core::IInspectable); impl GameSaveProviderGetResult { pub fn Status(&self) -> ::windows::core::Result<GameSaveErrorStatus> { let this = self; unsafe { let mut result__: GameSaveErrorStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GameSaveErrorStatus>(result__) } } pub fn Value(&self) -> ::windows::core::Result<GameSaveProvider> { 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::<GameSaveProvider>(result__) } } } unsafe impl ::windows::core::RuntimeType for GameSaveProviderGetResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.XboxLive.Storage.GameSaveProviderGetResult;{3ab90816-d393-4d65-ac16-41c3e67ab945})"); } unsafe impl ::windows::core::Interface for GameSaveProviderGetResult { type Vtable = IGameSaveProviderGetResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3ab90816_d393_4d65_ac16_41c3e67ab945); } impl ::windows::core::RuntimeName for GameSaveProviderGetResult { const NAME: &'static str = "Windows.Gaming.XboxLive.Storage.GameSaveProviderGetResult"; } impl ::core::convert::From<GameSaveProviderGetResult> for ::windows::core::IUnknown { fn from(value: GameSaveProviderGetResult) -> Self { value.0 .0 } } impl ::core::convert::From<&GameSaveProviderGetResult> for ::windows::core::IUnknown { fn from(value: &GameSaveProviderGetResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameSaveProviderGetResult { 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 GameSaveProviderGetResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<GameSaveProviderGetResult> for ::windows::core::IInspectable { fn from(value: GameSaveProviderGetResult) -> Self { value.0 } } impl ::core::convert::From<&GameSaveProviderGetResult> for ::windows::core::IInspectable { fn from(value: &GameSaveProviderGetResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameSaveProviderGetResult { 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 GameSaveProviderGetResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for GameSaveProviderGetResult {} unsafe impl ::core::marker::Sync for GameSaveProviderGetResult {} #[repr(transparent)] #[doc(hidden)] pub struct IGameSaveBlobGetResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGameSaveBlobGetResult { type Vtable = IGameSaveBlobGetResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x917281e0_7201_4953_aa2c_4008f03aef45); } #[repr(C)] #[doc(hidden)] pub struct IGameSaveBlobGetResult_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 GameSaveErrorStatus) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation_Collections", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation_Collections", feature = "Storage_Streams")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IGameSaveBlobInfo(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGameSaveBlobInfo { type Vtable = IGameSaveBlobInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xadd38034_baf0_4645_b6d0_46edaffb3c2b); } #[repr(C)] #[doc(hidden)] pub struct IGameSaveBlobInfo_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 u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGameSaveBlobInfoGetResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGameSaveBlobInfoGetResult { type Vtable = IGameSaveBlobInfoGetResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc7578582_3697_42bf_989c_665d923b5231); } #[repr(C)] #[doc(hidden)] pub struct IGameSaveBlobInfoGetResult_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 GameSaveErrorStatus) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IGameSaveBlobInfoQuery(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGameSaveBlobInfoQuery { type Vtable = IGameSaveBlobInfoQuery_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9fdd74b2_eeee_447b_a9d2_7f96c0f83208); } #[repr(C)] #[doc(hidden)] pub struct IGameSaveBlobInfoQuery_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, startindex: u32, maxnumberofitems: u32, 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 IGameSaveContainer(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGameSaveContainer { type Vtable = IGameSaveContainer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc3c08f89_563f_4ecd_9c6f_33fd0e323d10); } #[repr(C)] #[doc(hidden)] pub struct IGameSaveContainer_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::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, blobstowrite: ::windows::core::RawPtr, blobstodelete: ::windows::core::RawPtr, displayname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, blobstoread: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, blobstoread: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, blobstowrite: ::windows::core::RawPtr, blobstodelete: ::windows::core::RawPtr, displayname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, blobnameprefix: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGameSaveContainerInfo(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGameSaveContainerInfo { type Vtable = IGameSaveContainerInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb7e27300_155d_4bb4_b2ba_930306f391b5); } #[repr(C)] #[doc(hidden)] pub struct IGameSaveContainerInfo_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 u64) -> ::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 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, ); #[repr(transparent)] #[doc(hidden)] pub struct IGameSaveContainerInfoGetResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGameSaveContainerInfoGetResult { type Vtable = IGameSaveContainerInfoGetResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xffc50d74_c581_4f9d_9e39_30a10c1e4c50); } #[repr(C)] #[doc(hidden)] pub struct IGameSaveContainerInfoGetResult_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 GameSaveErrorStatus) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IGameSaveContainerInfoQuery(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGameSaveContainerInfoQuery { type Vtable = IGameSaveContainerInfoQuery_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c94e863_6f80_4327_9327_ffc11afd42b3); } #[repr(C)] #[doc(hidden)] pub struct IGameSaveContainerInfoQuery_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, startindex: u32, maxnumberofitems: u32, 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 IGameSaveOperationResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGameSaveOperationResult { type Vtable = IGameSaveOperationResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcf0f1a05_24a0_4582_9a55_b1bbbb9388d8); } #[repr(C)] #[doc(hidden)] pub struct IGameSaveOperationResult_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 GameSaveErrorStatus) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IGameSaveProvider(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGameSaveProvider { type Vtable = IGameSaveProvider_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x90a60394_80fe_4211_97f8_a5de14dd95d2); } #[repr(C)] #[doc(hidden)] pub struct IGameSaveProvider_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 = "System")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "System"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, containernameprefix: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IGameSaveProviderGetResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGameSaveProviderGetResult { type Vtable = IGameSaveProviderGetResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3ab90816_d393_4d65_ac16_41c3e67ab945); } #[repr(C)] #[doc(hidden)] pub struct IGameSaveProviderGetResult_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 GameSaveErrorStatus) -> ::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 IGameSaveProviderStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IGameSaveProviderStatics { type Vtable = IGameSaveProviderStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd01d3ed0_7b03_449d_8cbd_3402842a1048); } #[repr(C)] #[doc(hidden)] pub struct IGameSaveProviderStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "System"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, user: ::windows::core::RawPtr, serviceconfigid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "System")))] usize, #[cfg(all(feature = "Foundation", feature = "System"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, user: ::windows::core::RawPtr, serviceconfigid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "System")))] usize, );
/// Trait implemented by all drawable charts providing the interface for drawing functionality. pub trait Chart { /// Draws the chart specified for the instance that this function is called on. fn draw(&self); }
#[tokio::main(flavor = "multi_thread")] async fn main() { println!("#test-1-inv-broker-sub-proc started") }
// Box Widget // Extensible widget for the widget library - handles drawing a box with a border and a fill color // // 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 graphics::*; use opengl_graphics::GlGraphics; use piston::input::*; use crate::core::callbacks::*; use crate::core::point::Size; use crate::core::widget_store::WidgetContainer; use crate::widget::config::*; use crate::widget::widget::*; /// A `BoxWidget` is a `CanvasWidget` with a bounding box. Takes two additional options: /// * `CONFIG_BORDER_WIDTH` specifies the width of the border to be drawn in pixels. /// * `CONFIG_BORDER_COLOR` specifies the color of the border to be drawn. pub struct BoxWidget { config: Configurable, event_list: Vec<CallbackEvent>, widget_id: i32, callbacks: DefaultWidgetCallbacks, } impl BoxWidget { /// Constructor. pub fn new() -> Self { Self { config: Configurable::new(), event_list: vec![], widget_id: 0, callbacks: DefaultWidgetCallbacks::new(), } } fn draw_box(&mut self, c: Context, g: &mut GlGraphics, clip: &DrawState) { let size: crate::core::point::Size = self.config().get_size(CONFIG_BODY_SIZE); let border: f64 = self.config().get_numeric(CONFIG_BORDER_WIDTH) as f64; let color: types::Color = self.config().get_color(CONFIG_BORDER_COLOR); let fill_color: types::Color = self.config().get_color(CONFIG_MAIN_COLOR); g.rectangle( &Rectangle::new(fill_color), [0.0f64, 0.0f64, size.w as f64, size.h as f64], clip, c.transform.clone(), ); Rectangle::new_border(color, border).draw( [ 0.0 as f64 + border as f64, 0.0 as f64 + border as f64, size.w as f64 - (border as f64 * 2.0), size.h as f64 - (border as f64 * 2.0), ], clip, c.transform.clone(), g, ); } inject_event_handler!(); } impl Drawable for BoxWidget { fn draw(&mut self, c: Context, g: &mut GlGraphics, clip: &DrawState) { // Paint the box. self.draw_box(c, g, &clip); // Then clear invalidation. self.clear_invalidate(); } } impl InjectableSystemEvents for BoxWidget { fn inject_system_event(&mut self) -> Option<CallbackEvent> { self.event_list.pop().clone() } } impl InjectableCustomEvents for BoxWidget {} impl Widget for BoxWidget { fn config(&mut self) -> &mut Configurable { &mut self.config } fn set_config(&mut self, config: u8, config_value: Config) { self.config().set(config, config_value); self.invalidate(); } fn set_size(&mut self, config: u8, w: i32, h: i32) { self.set_config(config, Config::Size(Size { w, h })); if self.widget_id != 0 { self.event_list.push(CallbackEvent::WidgetResized { widget_id: self.widget_id, size: Size { w, h }, }); } self.invalidate(); } fn set_point(&mut self, config: u8, x: i32, y: i32) { self.set_config(config, Config::Point([x, y])); if self.widget_id != 0 { self.event_list.push(CallbackEvent::WidgetMoved { widget_id: self.widget_id, point: [x, y], }); } self.invalidate(); } fn handle_event( &mut self, injected: bool, _event: CallbackEvent, _widget_store: Option<&Vec<WidgetContainer>>, ) -> Option<CallbackEvent> { if !injected { self.handle_event_callbacks(_event, _widget_store); } None } fn handles_events(&mut self) -> bool { true } fn set_widget_id(&mut self, widget_id: i32) { self.widget_id = widget_id; } fn get_widget_id(&mut self) -> i32 { self.widget_id } fn injects_system_events(&mut self) -> bool { true } fn get_injectable_custom_events(&mut self) -> &mut dyn InjectableCustomEvents { self } fn get_injectable_system_events(&mut self) -> &mut dyn InjectableSystemEvents { self } fn get_drawable(&mut self) -> &mut dyn Drawable { self } fn get_callbacks(&mut self) -> &mut DefaultWidgetCallbacks { &mut self.callbacks } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] pub const DXCORE_ADAPTER_ATTRIBUTE_D3D11_GRAPHICS: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8c47866b_7583_450d_f0f0_6bada895af4b); pub const DXCORE_ADAPTER_ATTRIBUTE_D3D12_CORE_COMPUTE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x248e2800_a793_4724_abaa_23a6de1be090); pub const DXCORE_ADAPTER_ATTRIBUTE_D3D12_GRAPHICS: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0c9ece4d_2f6e_4f01_8c96_e89e331b47b1); #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DXCoreAdapterMemoryBudget { pub budget: u64, pub currentUsage: u64, pub availableForReservation: u64, pub currentReservation: u64, } impl DXCoreAdapterMemoryBudget {} impl ::core::default::Default for DXCoreAdapterMemoryBudget { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DXCoreAdapterMemoryBudget { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DXCoreAdapterMemoryBudget").field("budget", &self.budget).field("currentUsage", &self.currentUsage).field("availableForReservation", &self.availableForReservation).field("currentReservation", &self.currentReservation).finish() } } impl ::core::cmp::PartialEq for DXCoreAdapterMemoryBudget { fn eq(&self, other: &Self) -> bool { self.budget == other.budget && self.currentUsage == other.currentUsage && self.availableForReservation == other.availableForReservation && self.currentReservation == other.currentReservation } } impl ::core::cmp::Eq for DXCoreAdapterMemoryBudget {} unsafe impl ::windows::core::Abi for DXCoreAdapterMemoryBudget { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DXCoreAdapterMemoryBudgetNodeSegmentGroup { pub nodeIndex: u32, pub segmentGroup: DXCoreSegmentGroup, } impl DXCoreAdapterMemoryBudgetNodeSegmentGroup {} impl ::core::default::Default for DXCoreAdapterMemoryBudgetNodeSegmentGroup { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DXCoreAdapterMemoryBudgetNodeSegmentGroup { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DXCoreAdapterMemoryBudgetNodeSegmentGroup").field("nodeIndex", &self.nodeIndex).field("segmentGroup", &self.segmentGroup).finish() } } impl ::core::cmp::PartialEq for DXCoreAdapterMemoryBudgetNodeSegmentGroup { fn eq(&self, other: &Self) -> bool { self.nodeIndex == other.nodeIndex && self.segmentGroup == other.segmentGroup } } impl ::core::cmp::Eq for DXCoreAdapterMemoryBudgetNodeSegmentGroup {} unsafe impl ::windows::core::Abi for DXCoreAdapterMemoryBudgetNodeSegmentGroup { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct DXCoreAdapterPreference(pub u32); pub const Hardware: DXCoreAdapterPreference = DXCoreAdapterPreference(0u32); pub const MinimumPower: DXCoreAdapterPreference = DXCoreAdapterPreference(1u32); pub const HighPerformance: DXCoreAdapterPreference = DXCoreAdapterPreference(2u32); impl ::core::convert::From<u32> for DXCoreAdapterPreference { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DXCoreAdapterPreference { type Abi = Self; } impl ::core::ops::BitOr for DXCoreAdapterPreference { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for DXCoreAdapterPreference { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for DXCoreAdapterPreference { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for DXCoreAdapterPreference { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for DXCoreAdapterPreference { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct DXCoreAdapterProperty(pub u32); pub const InstanceLuid: DXCoreAdapterProperty = DXCoreAdapterProperty(0u32); pub const DriverVersion: DXCoreAdapterProperty = DXCoreAdapterProperty(1u32); pub const DriverDescription: DXCoreAdapterProperty = DXCoreAdapterProperty(2u32); pub const HardwareID: DXCoreAdapterProperty = DXCoreAdapterProperty(3u32); pub const KmdModelVersion: DXCoreAdapterProperty = DXCoreAdapterProperty(4u32); pub const ComputePreemptionGranularity: DXCoreAdapterProperty = DXCoreAdapterProperty(5u32); pub const GraphicsPreemptionGranularity: DXCoreAdapterProperty = DXCoreAdapterProperty(6u32); pub const DedicatedAdapterMemory: DXCoreAdapterProperty = DXCoreAdapterProperty(7u32); pub const DedicatedSystemMemory: DXCoreAdapterProperty = DXCoreAdapterProperty(8u32); pub const SharedSystemMemory: DXCoreAdapterProperty = DXCoreAdapterProperty(9u32); pub const AcgCompatible: DXCoreAdapterProperty = DXCoreAdapterProperty(10u32); pub const IsHardware: DXCoreAdapterProperty = DXCoreAdapterProperty(11u32); pub const IsIntegrated: DXCoreAdapterProperty = DXCoreAdapterProperty(12u32); pub const IsDetachable: DXCoreAdapterProperty = DXCoreAdapterProperty(13u32); pub const HardwareIDParts: DXCoreAdapterProperty = DXCoreAdapterProperty(14u32); impl ::core::convert::From<u32> for DXCoreAdapterProperty { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DXCoreAdapterProperty { type Abi = Self; } impl ::core::ops::BitOr for DXCoreAdapterProperty { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for DXCoreAdapterProperty { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for DXCoreAdapterProperty { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for DXCoreAdapterProperty { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for DXCoreAdapterProperty { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct DXCoreAdapterState(pub u32); pub const IsDriverUpdateInProgress: DXCoreAdapterState = DXCoreAdapterState(0u32); pub const AdapterMemoryBudget: DXCoreAdapterState = DXCoreAdapterState(1u32); impl ::core::convert::From<u32> for DXCoreAdapterState { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DXCoreAdapterState { type Abi = Self; } impl ::core::ops::BitOr for DXCoreAdapterState { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for DXCoreAdapterState { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for DXCoreAdapterState { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for DXCoreAdapterState { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for DXCoreAdapterState { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[inline] pub unsafe fn DXCoreCreateAdapterFactory<T: ::windows::core::Interface>() -> ::windows::core::Result<T> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DXCoreCreateAdapterFactory(riid: *const ::windows::core::GUID, ppvfactory: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT; } let mut result__ = ::core::option::Option::None; DXCoreCreateAdapterFactory(&<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DXCoreHardwareID { pub vendorID: u32, pub deviceID: u32, pub subSysID: u32, pub revision: u32, } impl DXCoreHardwareID {} impl ::core::default::Default for DXCoreHardwareID { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DXCoreHardwareID { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DXCoreHardwareID").field("vendorID", &self.vendorID).field("deviceID", &self.deviceID).field("subSysID", &self.subSysID).field("revision", &self.revision).finish() } } impl ::core::cmp::PartialEq for DXCoreHardwareID { fn eq(&self, other: &Self) -> bool { self.vendorID == other.vendorID && self.deviceID == other.deviceID && self.subSysID == other.subSysID && self.revision == other.revision } } impl ::core::cmp::Eq for DXCoreHardwareID {} unsafe impl ::windows::core::Abi for DXCoreHardwareID { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DXCoreHardwareIDParts { pub vendorID: u32, pub deviceID: u32, pub subSystemID: u32, pub subVendorID: u32, pub revisionID: u32, } impl DXCoreHardwareIDParts {} impl ::core::default::Default for DXCoreHardwareIDParts { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DXCoreHardwareIDParts { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DXCoreHardwareIDParts").field("vendorID", &self.vendorID).field("deviceID", &self.deviceID).field("subSystemID", &self.subSystemID).field("subVendorID", &self.subVendorID).field("revisionID", &self.revisionID).finish() } } impl ::core::cmp::PartialEq for DXCoreHardwareIDParts { fn eq(&self, other: &Self) -> bool { self.vendorID == other.vendorID && self.deviceID == other.deviceID && self.subSystemID == other.subSystemID && self.subVendorID == other.subVendorID && self.revisionID == other.revisionID } } impl ::core::cmp::Eq for DXCoreHardwareIDParts {} unsafe impl ::windows::core::Abi for DXCoreHardwareIDParts { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct DXCoreNotificationType(pub u32); pub const AdapterListStale: DXCoreNotificationType = DXCoreNotificationType(0u32); pub const AdapterNoLongerValid: DXCoreNotificationType = DXCoreNotificationType(1u32); pub const AdapterBudgetChange: DXCoreNotificationType = DXCoreNotificationType(2u32); pub const AdapterHardwareContentProtectionTeardown: DXCoreNotificationType = DXCoreNotificationType(3u32); impl ::core::convert::From<u32> for DXCoreNotificationType { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DXCoreNotificationType { type Abi = Self; } impl ::core::ops::BitOr for DXCoreNotificationType { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for DXCoreNotificationType { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for DXCoreNotificationType { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for DXCoreNotificationType { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for DXCoreNotificationType { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct DXCoreSegmentGroup(pub u32); pub const Local: DXCoreSegmentGroup = DXCoreSegmentGroup(0u32); pub const NonLocal: DXCoreSegmentGroup = DXCoreSegmentGroup(1u32); impl ::core::convert::From<u32> for DXCoreSegmentGroup { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DXCoreSegmentGroup { type Abi = Self; } impl ::core::ops::BitOr for DXCoreSegmentGroup { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for DXCoreSegmentGroup { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for DXCoreSegmentGroup { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for DXCoreSegmentGroup { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for DXCoreSegmentGroup { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IDXCoreAdapter(pub ::windows::core::IUnknown); impl IDXCoreAdapter { pub unsafe fn IsValid(&self) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self))) } pub unsafe fn IsAttributeSupported(&self, attributeguid: *const ::windows::core::GUID) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(attributeguid))) } pub unsafe fn IsPropertySupported(&self, property: DXCoreAdapterProperty) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(property))) } pub unsafe fn GetProperty(&self, property: DXCoreAdapterProperty, buffersize: usize, propertydata: *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(property), ::core::mem::transmute(buffersize), ::core::mem::transmute(propertydata)).ok() } pub unsafe fn GetPropertySize(&self, property: DXCoreAdapterProperty) -> ::windows::core::Result<usize> { let mut result__: <usize as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(property), &mut result__).from_abi::<usize>(result__) } pub unsafe fn IsQueryStateSupported(&self, property: DXCoreAdapterState) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(property))) } pub unsafe fn QueryState(&self, state: DXCoreAdapterState, inputstatedetailssize: usize, inputstatedetails: *const ::core::ffi::c_void, outputbuffersize: usize, outputbuffer: *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(state), ::core::mem::transmute(inputstatedetailssize), ::core::mem::transmute(inputstatedetails), ::core::mem::transmute(outputbuffersize), ::core::mem::transmute(outputbuffer)).ok() } pub unsafe fn IsSetStateSupported(&self, property: DXCoreAdapterState) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(property))) } pub unsafe fn SetState(&self, state: DXCoreAdapterState, inputstatedetailssize: usize, inputstatedetails: *const ::core::ffi::c_void, inputdatasize: usize, inputdata: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(state), ::core::mem::transmute(inputstatedetailssize), ::core::mem::transmute(inputstatedetails), ::core::mem::transmute(inputdatasize), ::core::mem::transmute(inputdata)).ok() } pub unsafe fn GetFactory<T: ::windows::core::Interface>(&self) -> ::windows::core::Result<T> { let mut result__ = ::core::option::Option::None; (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), &<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__) } } unsafe impl ::windows::core::Interface for IDXCoreAdapter { type Vtable = IDXCoreAdapter_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf0db4c7f_fe5a_42a2_bd62_f2a6cf6fc83e); } impl ::core::convert::From<IDXCoreAdapter> for ::windows::core::IUnknown { fn from(value: IDXCoreAdapter) -> Self { value.0 } } impl ::core::convert::From<&IDXCoreAdapter> for ::windows::core::IUnknown { fn from(value: &IDXCoreAdapter) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDXCoreAdapter { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDXCoreAdapter { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IDXCoreAdapter_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) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, attributeguid: *const ::windows::core::GUID) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, property: DXCoreAdapterProperty) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, property: DXCoreAdapterProperty, buffersize: usize, propertydata: *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, property: DXCoreAdapterProperty, buffersize: *mut usize) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, property: DXCoreAdapterState) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, state: DXCoreAdapterState, inputstatedetailssize: usize, inputstatedetails: *const ::core::ffi::c_void, outputbuffersize: usize, outputbuffer: *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, property: DXCoreAdapterState) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, state: DXCoreAdapterState, inputstatedetailssize: usize, inputstatedetails: *const ::core::ffi::c_void, inputdatasize: usize, inputdata: *const ::core::ffi::c_void) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, ppvfactory: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IDXCoreAdapterFactory(pub ::windows::core::IUnknown); impl IDXCoreAdapterFactory { pub unsafe fn CreateAdapterList<T: ::windows::core::Interface>(&self, numattributes: u32, filterattributes: *const ::windows::core::GUID) -> ::windows::core::Result<T> { let mut result__ = ::core::option::Option::None; (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(numattributes), ::core::mem::transmute(filterattributes), &<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetAdapterByLuid<T: ::windows::core::Interface>(&self, adapterluid: *const super::super::Foundation::LUID) -> ::windows::core::Result<T> { let mut result__ = ::core::option::Option::None; (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(adapterluid), &<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__) } pub unsafe fn IsNotificationTypeSupported(&self, notificationtype: DXCoreNotificationType) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(notificationtype))) } pub unsafe fn RegisterEventNotification<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, dxcoreobject: Param0, notificationtype: DXCoreNotificationType, callbackfunction: ::core::option::Option<PFN_DXCORE_NOTIFICATION_CALLBACK>, callbackcontext: *const ::core::ffi::c_void) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), dxcoreobject.into_param().abi(), ::core::mem::transmute(notificationtype), ::core::mem::transmute(callbackfunction), ::core::mem::transmute(callbackcontext), &mut result__).from_abi::<u32>(result__) } pub unsafe fn UnregisterEventNotification(&self, eventcookie: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(eventcookie)).ok() } } unsafe impl ::windows::core::Interface for IDXCoreAdapterFactory { type Vtable = IDXCoreAdapterFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x78ee5945_c36e_4b13_a669_005dd11c0f06); } impl ::core::convert::From<IDXCoreAdapterFactory> for ::windows::core::IUnknown { fn from(value: IDXCoreAdapterFactory) -> Self { value.0 } } impl ::core::convert::From<&IDXCoreAdapterFactory> for ::windows::core::IUnknown { fn from(value: &IDXCoreAdapterFactory) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDXCoreAdapterFactory { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDXCoreAdapterFactory { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IDXCoreAdapterFactory_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, numattributes: u32, filterattributes: *const ::windows::core::GUID, riid: *const ::windows::core::GUID, ppvadapterlist: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, adapterluid: *const super::super::Foundation::LUID, riid: *const ::windows::core::GUID, ppvadapter: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, notificationtype: DXCoreNotificationType) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dxcoreobject: ::windows::core::RawPtr, notificationtype: DXCoreNotificationType, callbackfunction: ::windows::core::RawPtr, callbackcontext: *const ::core::ffi::c_void, eventcookie: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, eventcookie: u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IDXCoreAdapterList(pub ::windows::core::IUnknown); impl IDXCoreAdapterList { pub unsafe fn GetAdapter<T: ::windows::core::Interface>(&self, index: u32) -> ::windows::core::Result<T> { let mut result__ = ::core::option::Option::None; (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(index), &<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__) } pub unsafe fn GetAdapterCount(&self) -> u32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self))) } pub unsafe fn IsStale(&self) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self))) } pub unsafe fn GetFactory<T: ::windows::core::Interface>(&self) -> ::windows::core::Result<T> { let mut result__ = ::core::option::Option::None; (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__) } pub unsafe fn Sort(&self, numpreferences: u32, preferences: *const DXCoreAdapterPreference) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(numpreferences), ::core::mem::transmute(preferences)).ok() } pub unsafe fn IsAdapterPreferenceSupported(&self, preference: DXCoreAdapterPreference) -> bool { ::core::mem::transmute((::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(preference))) } } unsafe impl ::windows::core::Interface for IDXCoreAdapterList { type Vtable = IDXCoreAdapterList_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x526c7776_40e9_459b_b711_f32ad76dfc28); } impl ::core::convert::From<IDXCoreAdapterList> for ::windows::core::IUnknown { fn from(value: IDXCoreAdapterList) -> Self { value.0 } } impl ::core::convert::From<&IDXCoreAdapterList> for ::windows::core::IUnknown { fn from(value: &IDXCoreAdapterList) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDXCoreAdapterList { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDXCoreAdapterList { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IDXCoreAdapterList_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, index: u32, riid: *const ::windows::core::GUID, ppvadapter: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> bool, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, ppvfactory: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, numpreferences: u32, preferences: *const DXCoreAdapterPreference) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, preference: DXCoreAdapterPreference) -> bool, ); pub type PFN_DXCORE_NOTIFICATION_CALLBACK = unsafe extern "system" fn(notificationtype: DXCoreNotificationType, object: ::windows::core::RawPtr, context: *const ::core::ffi::c_void); pub const _FACDXCORE: u32 = 2176u32;
use llvm; use llvm::prelude::*; use llvm::execution_engine::LLVMExecutionEngineRef; use std; use std::os::raw::c_char; use std::ffi::CString; use ir::Atom; use backend::Backend; const MEM_SIZE: isize = 30000; #[derive(Debug, Clone)] pub struct LLVMBackend { module: LLVMModuleRef, brainfuck_fn: LLVMValueRef, builder: LLVMBuilderRef, memory: LLVMValueRef, ptr: LLVMValueRef, putchar_fn: LLVMValueRef, getchar_fn: LLVMValueRef, free_fn: LLVMValueRef, } impl LLVMBackend { pub fn new() -> LLVMBackend { LLVMBackend { module: unsafe { llvm::core::LLVMModuleCreateWithName( b"main_module\0".as_ptr() as *const _ ) }, brainfuck_fn: std::ptr::null_mut(), builder: unsafe { llvm::core::LLVMCreateBuilder() }, memory: std::ptr::null_mut(), ptr: std::ptr::null_mut(), putchar_fn: std::ptr::null_mut(), getchar_fn: std::ptr::null_mut(), free_fn: std::ptr::null_mut() } } } macro_rules! offset_ptr { ($builder:expr, $ptr:expr, $offset:expr) => { { let ptr_value = llvm::core::LLVMBuildLoad( $builder, $ptr, b"ptr\0".as_ptr() as *const _ ); llvm::core::LLVMBuildGEP( $builder, ptr_value, [utils::get_int32_const($offset)].as_mut_ptr(), 1, b"ptr\0".as_ptr() as *const _ ) } } } impl Backend for LLVMBackend { type Payload = LLVMBrainfuckModule; type Error = CString; fn initialize(&mut self) -> Result<(), Self::Error> { macro_rules! add_function { ($module:expr, $name:expr, $ret_ty:expr, $args:expr) => { { let mut args = $args; let args_len = args.len(); let fn_ty = llvm::core::LLVMFunctionType( $ret_ty, args.as_mut_ptr(), args_len as _, 0 ); llvm::core::LLVMAddFunction( $module, $name.as_ptr() as *const _, fn_ty ) } }; ($module:expr, $name:expr, $ret_ty:expr, []) => { { let fn_ty = llvm::core::LLVMFunctionType( $ret_ty, std::ptr::null_mut(), 0, 0 ); llvm::core::LLVMAddFunction( $module, $name.as_ptr() as *const _, fn_ty ) } } } unsafe { let i8_ty = llvm::core::LLVMInt8Type(); let i32_ty = llvm::core::LLVMInt32Type(); let void_ty = llvm::core::LLVMVoidType(); let i8_ptr_ty = llvm::core::LLVMPointerType(i8_ty, 0); self.putchar_fn = add_function!(self.module, b"putchar\0", i32_ty, [i32_ty]); self.getchar_fn = add_function!(self.module, b"getchar\0", i32_ty, []); self.free_fn = add_function!(self.module, b"free\0", void_ty, [i8_ptr_ty]); self.brainfuck_fn = add_function!(self.module, b"brainfuck\0", void_ty, []); let entry_bb = llvm::core::LLVMAppendBasicBlock( self.brainfuck_fn, b"entry\0".as_ptr() as *const _ ); llvm::core::LLVMPositionBuilderAtEnd(self.builder, entry_bb); let calloc_fn = add_function!( self.module, b"calloc\0", i8_ptr_ty, [i32_ty, i32_ty] ); self.memory = llvm::core::LLVMBuildCall( self.builder, calloc_fn, [utils::get_int32_const(MEM_SIZE), utils::get_int32_const(1)].as_mut_ptr(), 2, b"memory\0".as_ptr() as *const _ ); self.ptr = llvm::core::LLVMBuildAlloca( self.builder, llvm::core::LLVMPointerType(i8_ty, 0), b"ptr_cell\0".as_ptr() as *const _ ); let ptr_init_value = llvm::core::LLVMBuildGEP( self.builder, self.memory, [utils::get_int32_const(0)].as_mut_ptr(), 1, b"ptr_init_value\0".as_ptr() as *const _ ); llvm::core::LLVMBuildStore( self.builder, ptr_init_value, self.ptr ); } Ok(()) } fn finalize(self) -> Result<Self::Payload, Self::Error> { unsafe { llvm::core::LLVMBuildCall( self.builder, self.free_fn, [self.memory].as_mut_ptr(), 1, b"\0".as_ptr() as *const _ ); llvm::core::LLVMBuildRetVoid(self.builder); let mut error: *mut c_char = std::ptr::null_mut(); if llvm::analysis::LLVMVerifyModule( self.module, llvm::analysis::LLVMVerifierFailureAction::LLVMReturnStatusAction, &mut error ) != 0 { return Err(CString::from_raw(error)) } LLVMBrainfuckModule::new(self.module, self.brainfuck_fn) } } fn push_move_ptr(&mut self, offset: isize) -> Result<(), Self::Error> { unsafe { let new_ptr_value = offset_ptr!(self.builder, self.ptr, offset); llvm::core::LLVMBuildStore( self.builder, new_ptr_value, self.ptr ); } Ok(()) } fn push_set_value(&mut self, value: i8, offset: isize) -> Result<(), Self::Error> { unsafe { let real_ptr = offset_ptr!(self.builder, self.ptr, offset); llvm::core::LLVMBuildStore( self.builder, utils::get_int8_const(value), real_ptr ); } Ok(()) } fn push_inc_value(&mut self, inc: i8, offset: isize) -> Result<(), Self::Error> { unsafe { let real_ptr = offset_ptr!(self.builder, self.ptr, offset); let value = llvm::core::LLVMBuildLoad( self.builder, real_ptr, b"value\0".as_ptr() as *const _ ); let value = llvm::core::LLVMBuildAdd( self.builder, value, utils::get_int8_const(inc), b"value\0".as_ptr() as *const _ ); llvm::core::LLVMBuildStore(self.builder, value, real_ptr); } Ok(()) } fn push_print(&mut self, offset: isize) -> Result<(), Self::Error> { unsafe { let real_ptr = offset_ptr!(self.builder, self.ptr, offset); let value = llvm::core::LLVMBuildLoad( self.builder, real_ptr, b"value\0".as_ptr() as *const _ ); let value = llvm::core::LLVMBuildZExt( self.builder, value, llvm::core::LLVMInt32Type(), b"value\0".as_ptr() as *const _ ); llvm::core::LLVMBuildCall( self.builder, self.putchar_fn, [value].as_mut_ptr(), 1, b"value\0".as_ptr() as *const _ ); } Ok(()) } fn push_read(&mut self, offset: isize) -> Result<(), Self::Error> { unsafe { let real_ptr = offset_ptr!(self.builder, self.ptr, offset); let c = llvm::core::LLVMBuildCall( self.builder, self.getchar_fn, std::ptr::null_mut(), 0, b"value\0".as_ptr() as *const _ ); let value = llvm::core::LLVMBuildTrunc( self.builder, c, llvm::core::LLVMInt8Type(), b"value\0".as_ptr() as *const _ ); llvm::core::LLVMBuildStore( self.builder, value, real_ptr ); } Ok(()) } fn push_multiply(&mut self, factor: i8, offset: isize) -> Result<(), Self::Error> { unsafe { let base_ptr = offset_ptr!(self.builder, self.ptr, 0); let offset_ptr = offset_ptr!(self.builder, self.ptr, offset); let base_value = llvm::core::LLVMBuildLoad( self.builder, base_ptr, b"offset_value\0".as_ptr() as *const _ ); let base_value = llvm::core::LLVMBuildMul( self.builder, base_value, utils::get_int8_const(factor), b"factored_value\0".as_ptr() as *const _ ); let offset_value = llvm::core::LLVMBuildLoad( self.builder, offset_ptr, b"base_value\0".as_ptr() as *const _ ); let value = llvm::core::LLVMBuildAdd( self.builder, base_value, offset_value, b"value\0".as_ptr() as *const _ ); llvm::core::LLVMBuildStore( self.builder, value, offset_ptr ); } Ok(()) } fn push_loop(&mut self, sub: &Vec<Atom>) -> Result<(), Self::Error> { unsafe { let loop_bb = llvm::core::LLVMAppendBasicBlock( self.brainfuck_fn, b"loop\0".as_ptr() as *const _ ); llvm::core::LLVMBuildBr(self.builder, loop_bb); let then_bb = llvm::core::LLVMAppendBasicBlock( self.brainfuck_fn, b"then\0".as_ptr() as *const _ ); let exit_bb = llvm::core::LLVMAppendBasicBlock( self.brainfuck_fn, b"exit\0".as_ptr() as *const _ ); llvm::core::LLVMPositionBuilderAtEnd(self.builder, loop_bb); let ptr = offset_ptr!(self.builder, self.ptr, 0); let value = llvm::core::LLVMBuildLoad( self.builder, ptr, b"value\0".as_ptr() as *const _ ); let cond = llvm::core::LLVMBuildIsNotNull( self.builder, value, b"cond\0".as_ptr() as *const _ ); llvm::core::LLVMBuildCondBr( self.builder, cond, then_bb, exit_bb ); llvm::core::LLVMPositionBuilderAtEnd(self.builder, then_bb); self.push_atoms(sub)?; llvm::core::LLVMBuildBr(self.builder, loop_bb); let last_bb = llvm::core::LLVMGetLastBasicBlock(self.brainfuck_fn); llvm::core::LLVMMoveBasicBlockAfter(exit_bb, last_bb); llvm::core::LLVMPositionBuilderAtEnd(self.builder, exit_bb); } Ok(()) } } impl Drop for LLVMBackend { fn drop(&mut self) { unsafe { llvm::core::LLVMDisposeBuilder(self.builder); } } } #[derive(Debug, Clone)] pub struct LLVMBrainfuckModule { exec_engine: LLVMExecutionEngineRef, module: LLVMModuleRef, brainfuck_fn: LLVMValueRef, } impl LLVMBrainfuckModule { fn new(module: LLVMModuleRef, brainfuck_fn: LLVMValueRef) -> Result<LLVMBrainfuckModule, CString> { use llvm::execution_engine::LLVMMCJITCompilerOptions; let mut exec_engine: LLVMExecutionEngineRef = std::ptr::null_mut(); unsafe { let mut error: *mut c_char = std::ptr::null_mut(); let mut options: LLVMMCJITCompilerOptions = std::mem::zeroed(); let options_size = std::mem::size_of::<LLVMMCJITCompilerOptions>(); llvm::execution_engine::LLVMInitializeMCJITCompilerOptions( &mut options, options_size ); options.OptLevel = 3; llvm::target::LLVM_InitializeNativeTarget(); llvm::target::LLVM_InitializeNativeAsmPrinter(); llvm::target::LLVM_InitializeNativeAsmParser(); llvm::execution_engine::LLVMLinkInMCJIT(); if llvm::execution_engine::LLVMCreateMCJITCompilerForModule( &mut exec_engine, module, &mut options, options_size, &mut error ) != 0 { return Err(CString::from_raw(error)); } } Ok(LLVMBrainfuckModule { exec_engine, module, brainfuck_fn }) } pub fn optimize(&mut self) { unsafe { let pass = llvm::core::LLVMCreatePassManager(); llvm::transforms::scalar::LLVMAddConstantPropagationPass(pass); llvm::transforms::scalar::LLVMAddInstructionCombiningPass(pass); llvm::transforms::scalar::LLVMAddPromoteMemoryToRegisterPass(pass); llvm::transforms::scalar::LLVMAddGVNPass(pass); llvm::transforms::scalar::LLVMAddCFGSimplificationPass(pass); llvm::core::LLVMRunPassManager(pass, self.module); llvm::core::LLVMDisposePassManager(pass); } } pub fn jit_run(&mut self) { unsafe { llvm::execution_engine::LLVMRunFunction( self.exec_engine, self.brainfuck_fn, 0, std::ptr::null_mut() ); } } } impl Drop for LLVMBrainfuckModule { fn drop(&mut self) { unsafe { llvm::execution_engine::LLVMDisposeExecutionEngine(self.exec_engine); // llvm::core::LLVMDisposeModule(self.module); llvm::core::LLVMShutdown(); } } } mod utils { use llvm; use llvm::prelude::LLVMValueRef; pub unsafe fn get_int8_const(c: i8) -> LLVMValueRef { llvm::core::LLVMConstInt( llvm::core::LLVMInt8Type(), c as _, false as _ ) } pub unsafe fn get_int32_const(c: isize) -> LLVMValueRef { llvm::core::LLVMConstInt( llvm::core::LLVMInt32Type(), c as _, false as _ ) } }
use clap::{App, Arg, ArgMatches, SubCommand}; pub fn build_cli() -> App<'static, 'static> { App::new("mender-rust") .version("0.1.0") .author("V. Hubert <v-hubert@laposte.net>") .about("A small command line tool to perform tasks on a Mender server using its APIs.") .after_help( "ENVIRONMENT VARIABLES: SERVER_URL Url of the mender server, must be provided TOKEN Authentication token, must be provided for all subcommands except login and help CERT_FILE Optional certificate for the SSL connection to the server", ) .subcommand( SubCommand::with_name("login") .about("Returns a token used in other subcommands") .arg( Arg::with_name("email") .help("User email used to login to Mender server") .required(true), ), ) .subcommand( SubCommand::with_name("getid") .about("Get the mender id of a device from its SerialNumber attribute") .arg( Arg::with_name("serial number") .help("SerialNumber attribute of the device") .required(true), ), ) .subcommand( SubCommand::with_name("getinfo") .about("Get info of a device") .arg( Arg::with_name("id") .help("Mender id of the device") .required(true), ), ) .subcommand( SubCommand::with_name("countartifacts") .about("List artifacts and count how much devices are using each"), ) .subcommand( SubCommand::with_name("deploy") .about("Deploy an update to a device or to a group of devices") .arg( Arg::with_name("group") .help("Name of the group to which the update will be deployed") .short("g") .required_unless("device") .conflicts_with("device") .takes_value(true), ) .arg( Arg::with_name("device") .help("Id of the device to which the update will be deployed") .short("d") .required_unless("group") .takes_value(true), ) .arg( Arg::with_name("artifact") .help("Name of the artifact to deploy") .required(true), ) .arg( Arg::with_name("name") .help("Name of the deployment, if not present device/group name is used"), ), ) } pub struct Config { pub command: Command, pub token: Option<String>, pub server_url: String, pub cert_file: Option<String>, } impl Config { pub fn new(command: Command) -> Result<Config, &'static str> { let server_url = if let Ok(url) = std::env::var("SERVER_URL") { url } else { return Err("SERVER_URL env variable must be defined"); }; let token = if let Ok(token) = std::env::var("TOKEN") { Some(token) } else { None }; let cert_file = if let Ok(cert) = std::env::var("CERT_FILE") { Some(cert) } else { None }; match &command { Command::Deploy { .. } | Command::GetId { .. } | Command::GetInfo { .. } | Command::CountArtifacts if token == None => { return Err( "TOKEN must be provided for deploy, getid, getinfo and countartifacts commands", ) } _ => (), } Ok(Config { command, token, server_url, cert_file, }) } } #[derive(PartialEq, Debug)] pub enum Command { Login { email: String, }, Deploy { group: Option<String>, device: Option<String>, artifact: String, name: Option<String>, }, GetId { serial_number: String, }, GetInfo { id: String, }, CountArtifacts, } impl Command { pub fn new(args: ArgMatches) -> Result<Command, &'static str> { match args.subcommand() { ("countartifacts", _) => Ok(Command::CountArtifacts), ("login", Some(sub_args)) => Ok(Command::Login { email: sub_args.value_of("email").unwrap().to_string(), }), ("deploy", Some(sub_args)) => Ok(Command::Deploy { group: sub_args.value_of("group").map(|s| s.to_string()), device: sub_args.value_of("device").map(|s| s.to_string()), artifact: sub_args.value_of("artifact").unwrap().to_string(), name: sub_args.value_of("name").map(|s| s.to_string()), }), ("getid", Some(sub_args)) => Ok(Command::GetId { serial_number: sub_args.value_of("serial number").unwrap().to_string(), }), ("getinfo", Some(sub_args)) => Ok(Command::GetInfo { id: sub_args.value_of("id").unwrap().to_string(), }), _ => return Err("unrecognized or no subcommand, see help for available subcommands"), } } }
fn main() { let mut v = vec![1,2,3]; let x = v.pop(); // fill up the missing parts match { => println!("stack empty"), Some() => println!("{}", ), } }
use crate::lib::math::vector::Vec2; use crate::lib::rendering::gl_render::{ImageRenderer, Texture}; use crate::lib::rendering::camera::*; use crate::lib::math::matrix::*; pub struct Bullet { position: Vec2<f32>, velocity: Vec2<f32>, } impl Bullet { pub fn new(position: Vec2<f32>, facing: Vec2<f32>) -> Bullet{ Bullet { position, velocity: facing.normalize()*0.01, } } } pub fn update_render_and_cull_bullets(bullets: &mut Vec<Bullet>, camera:&Camera, image_renderer:&ImageRenderer, texture:&Texture) { *bullets = bullets .iter_mut() .map(|bullet| Bullet{position:bullet.position + bullet.velocity, velocity:bullet.velocity}) .filter(|bullet| { let rel = bullet.position - camera.center; let res = rel.x.abs() < camera.dimensions.x * 0.5 && rel.y.abs() < camera.dimensions.y * 0.5; res }) .map(|bullet| { image_renderer.render( &texture, camera, &TranslationMat::translate_mat(bullet.position) .rotate(bullet.velocity.normalize()) .rotate(-std::f32::consts::FRAC_PI_2) .scale(0.15), ); bullet }) .collect(); }
#[doc = "Reader of register ICR"] pub type R = crate::R<u32, super::ICR>; #[doc = "Reader of field `SEIF`"] pub type SEIF_R = crate::R<bool, bool>; #[doc = "Reader of field `XONEIF`"] pub type XONEIF_R = crate::R<bool, bool>; #[doc = "Reader of field `KEIF`"] pub type KEIF_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - SEIF"] #[inline(always)] pub fn seif(&self) -> SEIF_R { SEIF_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Execute-only execute-Never Error Interrupt Flag clear"] #[inline(always)] pub fn xoneif(&self) -> XONEIF_R { XONEIF_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - KEIF"] #[inline(always)] pub fn keif(&self) -> KEIF_R { KEIF_R::new(((self.bits >> 2) & 0x01) != 0) } }
use crate::Point; use num_traits::Float; /// Returns the bearing to another Point in degrees. /// /// Bullock, R.: Great Circle Distances and Bearings Between Two Locations, 2007. /// (https://dtcenter.org/met/users/docs/write_ups/gc_simple.pdf) pub trait Bearing<T: Float> { /// Returns the bearing to another Point in degrees, where North is 0° and East is 90°. /// /// # Examples /// /// ``` /// # #[macro_use] extern crate approx; /// # /// use geo::algorithm::bearing::Bearing; /// use geo::Point; /// /// let p_1 = Point::<f64>::new(9.177789688110352, 48.776781529534965); /// let p_2 = Point::<f64>::new(9.274410083250379, 48.84033282787534); /// let bearing = p_1.bearing(p_2); /// assert_relative_eq!(bearing, 45., epsilon = 1.0e-6); /// ``` fn bearing(&self, point: Point<T>) -> T; } impl<T> Bearing<T> for Point<T> where T: Float, { fn bearing(&self, point: Point<T>) -> T { let (lng_a, lat_a) = (self.x().to_radians(), self.y().to_radians()); let (lng_b, lat_b) = (point.x().to_radians(), point.y().to_radians()); let delta_lng = lng_b - lng_a; let s = lat_b.cos() * delta_lng.sin(); let c = lat_a.cos() * lat_b.sin() - lat_a.sin() * lat_b.cos() * delta_lng.cos(); T::atan2(s, c).to_degrees() } } #[cfg(test)] mod test { use crate::algorithm::bearing::Bearing; use crate::algorithm::haversine_destination::HaversineDestination; use crate::point; #[test] fn returns_the_proper_bearing_to_another_point() { let p_1 = point!(x: 9.177789688110352f64, y: 48.776781529534965); let p_2 = p_1.haversine_destination(45., 10000.); let b_1 = p_1.bearing(p_2); assert_relative_eq!(b_1, 45., epsilon = 1.0e-6); let p_3 = point!(x: 9., y: 47.); let p_4 = point!(x: 9., y: 48.); let b_2 = p_3.bearing(p_4); assert_relative_eq!(b_2, 0., epsilon = 1.0e-6); } }
pub trait ModI: Sized + Copy + std::ops::Add<Output = Self> + std::ops::Sub<Output = Self> + std::ops::Mul<Output = Self> + std::ops::Div<Output = Self> + std::ops::AddAssign + std::ops::SubAssign + std::ops::MulAssign + std::ops::DivAssign + std::default::Default + std::fmt::Display + std::fmt::Debug { fn m() -> u64; fn new(x: u64) -> Self; fn pow(self, n: u64) -> Self; fn inv(&self) -> Self; } macro_rules! define_modint { ($n:ident,$m:expr) => { #[derive(Clone, Copy, Eq, PartialEq, PartialOrd, Ord)] struct $n(u64); #[allow(dead_code)] impl ModI for $n { fn m() -> u64 { $m } fn new(x: u64) -> $n { $n(x % $m) } fn pow(self, mut n: u64) -> $n { let mut ret = $n::new(1); let mut base = self; while n > 0 { if n & 1 == 1 { ret *= base; } base *= base; n >>= 1; } ret } fn inv(&self) -> $n { self.pow($m - 2) } } impl std::default::Default for $n { fn default() -> $n { $n::new(0u64) } } impl std::convert::From<u64> for $n { fn from(x: u64) -> $n { $n::new(x) } } // Binary operator impl std::ops::Add for $n { type Output = $n; fn add(self, rhs: $n) -> Self::Output { $n::new(self.0 + rhs.0) } } impl std::ops::Sub for $n { type Output = $n; fn sub(self, rhs: $n) -> Self::Output { if self.0 >= rhs.0 { $n::new(self.0 - rhs.0) } else { $n::new($m - rhs.0 + self.0) } } } impl std::ops::Mul for $n { type Output = $n; fn mul(self, rhs: $n) -> Self::Output { $n::new(self.0 * rhs.0) } } impl std::ops::Div for $n { type Output = $n; fn div(self, rhs: $n) -> Self::Output { $n::new(self.0 / rhs.0) } } // Assign impl std::ops::AddAssign for $n { fn add_assign(&mut self, rhs: $n) { *self = *self + rhs; } } impl std::ops::SubAssign for $n { fn sub_assign(&mut self, rhs: $n) { *self = *self - rhs; } } impl std::ops::MulAssign for $n { fn mul_assign(&mut self, rhs: $n) { *self = *self * rhs; } } impl std::ops::DivAssign for $n { fn div_assign(&mut self, rhs: $n) { *self = *self / rhs; } } impl std::fmt::Display for $n { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } impl std::fmt::Debug for $n { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } }; } // 10^8 < p < 10^9 // 167772161 = 5*2^25 + 1, 469762049 = 7*2^26 + 1, 998244353 = 119*2^23 + 1 define_modint!(ModInt998244353, 998244353); define_modint!(ModInt167772161, 167772161); define_modint!(ModInt469762049, 469762049); mod tests { use super::*; #[test] fn check_modint() { let mut a = ModInt998244353::new(1); let b = ModInt998244353::new(1); println!("{:?}", a); println!("{:?}", a.0); } } fn main() {} // for ntt trait pub trait ModI: Sized { fn m() -> u64; fn new(x: u64) -> Self; fn pow(self, mut n: u64) -> Self; fn inv(&self) -> Self; } macro_rules! define_modint { ($n:ident,$m:expr) => { #[derive(Clone, Copy, Eq, PartialEq, PartialOrd, Ord)] struct $n(u64); #[allow(dead_code)] impl ModI for $n { fn m() -> u64 { $m } fn new(x: u64) -> $n { $n(x % $m) } fn pow(self, mut n: u64) -> $n { let mut ret = $n::new(1); let mut base = self; while n > 0 { if n & 1 == 1 { ret *= base; } base *= base; n >>= 1; } ret } fn inv(&self) -> $n { self.pow($m - 2) } // when m is not prime // pub fn inv2(&self) -> $n { // let mut ab = (self, $n::new(0)); // let mut uv = ($n::new(1), $n::new(0)); // let mut t: i64; // while ab.1 != 0 { // t = ab.0 / ab.1; // ab = (ab.1, ab.0 - t * ab.1); // uv = (uv.1, uv.0 - t * uv.1); // } // if ab.0 != 1 { // panic!("{} and {} are not coprime g={}", a, m, ab.0); // } // let inv = uv.0 % m as i64; // if inv < 0 { // inv + m as i64 // } else { // inv as i64 // } // } } impl std::convert::From<u64> for $n { fn from(x: u64) -> $n { $n::new(x) } } // Binary operator impl std::ops::Add for $n { type Output = $n; fn add(self, rhs: $n) -> Self::Output { $n::new(self.0 + rhs.0) } } impl std::ops::Sub for $n { type Output = $n; fn sub(self, rhs: $n) -> Self::Output { if self.0 >= rhs.0 { $n::new(self.0 - rhs.0) } else { $n::new($m - rhs.0 + self.0) } } } impl std::ops::Mul for $n { type Output = $n; fn mul(self, rhs: $n) -> Self::Output { $n::new(self.0 * rhs.0) } } impl std::ops::Div for $n { type Output = $n; fn div(self, rhs: $n) -> Self::Output { $n::new(self.0 / rhs.0) } } // Assign impl std::ops::AddAssign for $n { fn add_assign(&mut self, rhs: $n) { *self = *self + rhs; } } impl std::ops::SubAssign for $n { fn sub_assign(&mut self, rhs: $n) { *self = *self - rhs; } } impl std::ops::MulAssign for $n { fn mul_assign(&mut self, rhs: $n) { *self = *self * rhs; } } impl std::ops::DivAssign for $n { fn div_assign(&mut self, rhs: $n) { *self = *self / rhs; } } impl std::fmt::Display for $n { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } impl std::fmt::Debug for $n { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } }; }
use diesel::prelude::*; use super::context::Context; use super::resolver::Member; use crate::schema::members; pub struct MutationRoot; #[juniper::object(Context = Context)] impl MutationRoot { fn create_member(context: &Context, data: NewMember) -> Member { let connection = context.db.get().unwrap();; diesel::insert_into(members::table) .values(&data) .get_result(&connection) .expect("Error saving new post") } } #[derive(juniper::GraphQLInputObject, Insertable)] #[table_name = "members"] pub struct NewMember { pub name: String, pub knockouts: i32, pub team_id: i32, }
use serde::{Deserialize, Serialize}; use std::fs; #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BlackmagicCameraProtocol { pub information: Information, pub groups: Vec<Group>, #[serde(rename = "bluetooth_services")] pub bluetooth_services: Vec<BluetoothService>, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Information { pub readme: String, pub source: String, pub git: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Group { pub name: String, #[serde(rename = "normalized_name")] pub normalized_name: String, pub id: i64, pub parameters: Vec<Parameter>, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Parameter { pub id: i64, pub group: String, #[serde(rename = "group_id")] pub group_id: i64, pub parameter: String, #[serde(rename = "type")] pub type_field: String, pub index: Vec<String>, pub interpretation: Option<String>, pub minimum: Option<f64>, pub maximum: Option<f64>, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BluetoothService { pub name: String, #[serde(rename = "normalized_name")] pub normalized_name: String, pub uuid: String, pub characteristics: Vec<Characteristic>, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Characteristic { pub name: String, #[serde(rename = "normalized_name")] pub normalized_name: String, pub uuid: String, pub description: Option<String>, pub decription: Option<String>, } fn main() { let data = fs::read_to_string("../../PROTOCOL.json").unwrap(); let cfg: BlackmagicCameraProtocol = serde_json::from_str(&data).unwrap(); dbg!(cfg); }
pub use game_1::{Game1}; use std::ops::{Deref,DerefMut}; pub type LowerGame = Game1; pub struct SpellGame{ pub lower_game: LowerGame } impl Deref for SpellGame{ type Target = LowerGame; fn deref(&self)->&Self::Target{ &self.lower_game } } impl DerefMut for SpellGame{ fn deref_mut(&mut self)->&mut Self::Target{ &mut self.lower_game } } impl SpellGame{ pub fn new()->Self{ let lower_game=LowerGame::new_spelled(); SpellGame{lower_game: lower_game} } pub fn step(&mut self){ self.timer+=1; self.lower_game.begin_step(); self.lower_game.step(); for i in 0..self.casters.len(){ if let Some(mut caster)=self.casters[i].take(){ if caster.cooldown>0{ caster.casting=None; caster.cooldown-=1; self.casters[i]=Some(caster); continue; } let caster_x=self.movers.at(caster.mover_id.id).x; let caster_y=self.movers.at(caster.mover_id.id).y; let casting=caster.casting.take(); if let Some((spell_id, x, y))=casting{ if spell_id>=caster.spell_slots.len(){ println!("Warning: attempting to cast spell above number of spells assigned"); } else { let spell_slot=caster.spell_slots[spell_id].take(); if !spell_slot.is_some(){ println!("Warning: Attempting to cast empty spell"); } else{ let mut spell_slot=spell_slot.unwrap(); let result=spell_slot.cast(&mut self.lower_game, &mut caster, x as f64 + caster_x, y as f64 + caster_y); caster.spell_slots[spell_id]=Some(spell_slot); caster.cooldown=result.cooldown; if result.channel_for>0{ caster.channeling=Some((spell_id, result.channel_for)); } } } } self.casters[i]=Some(caster); } } self.lower_game.end_step(); } }
//! is-terminal is a simple utility that answers one question: //! //! > Is this a terminal? //! //! A "terminal", also known as a "tty", is an I/O device which may be //! interactive and may support color and other special features. This crate //! doesn't provide any of those features; it just answers this one question. //! //! On Unix-family platforms, this is effectively the same as the [`isatty`] //! function for testing whether a given stream is a terminal, though it //! accepts high-level stream types instead of raw file descriptors. //! //! On Windows, it uses a variety of techniques to determine whether the //! given stream is a terminal. //! //! # Example //! //! ```rust //! use is_terminal::IsTerminal; //! //! if std::io::stdout().is_terminal() { //! println!("stdout is a terminal") //! } //! ``` //! //! [`isatty`]: https://man7.org/linux/man-pages/man3/isatty.3.html #![cfg_attr(unix, no_std)] #[cfg(not(any(windows, target_os = "hermit", target_os = "unknown")))] use rustix::fd::AsFd; #[cfg(target_os = "hermit")] use std::os::hermit::io::AsFd; #[cfg(windows)] use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle}; #[cfg(windows)] use windows_sys::Win32::Foundation::HANDLE; /// Extension trait to check whether something is a terminal. pub trait IsTerminal { /// Returns true if this is a terminal. /// /// # Example /// /// ``` /// use is_terminal::IsTerminal; /// /// if std::io::stdout().is_terminal() { /// println!("stdout is a terminal") /// } /// ``` fn is_terminal(&self) -> bool; } /// Returns `true` if `this` is a terminal. /// /// This is equivalent to calling `this.is_terminal()` and exists only as a /// convenience to calling the trait method [`IsTerminal::is_terminal`] /// without importing the trait. /// /// # Example /// /// ``` /// if is_terminal::is_terminal(&std::io::stdout()) { /// println!("stdout is a terminal") /// } /// ``` pub fn is_terminal<T: IsTerminal>(this: T) -> bool { this.is_terminal() } #[cfg(not(any(windows, target_os = "unknown")))] impl<Stream: AsFd> IsTerminal for Stream { #[inline] fn is_terminal(&self) -> bool { #[cfg(any(unix, target_os = "wasi"))] { rustix::termios::isatty(self) } #[cfg(target_os = "hermit")] { use std::os::hermit::io::AsRawFd; hermit_abi::isatty(self.as_fd().as_fd().as_raw_fd()) } } } #[cfg(windows)] impl<Stream: AsHandle> IsTerminal for Stream { #[inline] fn is_terminal(&self) -> bool { handle_is_console(self.as_handle()) } } // The Windows implementation here is copied from `handle_is_console` in // std/src/sys/windows/io.rs in Rust at revision // d7b0bcb20f2f7d5f3ea3489d56ece630147e98f5. #[cfg(windows)] fn handle_is_console(handle: BorrowedHandle<'_>) -> bool { use windows_sys::Win32::System::Console::{ GetConsoleMode, GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, }; let handle = handle.as_raw_handle(); unsafe { // A null handle means the process has no console. if handle.is_null() { return false; } let mut out = 0; if GetConsoleMode(handle as HANDLE, &mut out) != 0 { // False positives aren't possible. If we got a console then we definitely have a console. return true; } // At this point, we *could* have a false negative. We can determine that this is a true // negative if we can detect the presence of a console on any of the standard I/O streams. If // another stream has a console, then we know we're in a Windows console and can therefore // trust the negative. for std_handle in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] { let std_handle = GetStdHandle(std_handle); if std_handle != 0 && std_handle != handle as HANDLE && GetConsoleMode(std_handle, &mut out) != 0 { return false; } } // Otherwise, we fall back to an msys hack to see if we can detect the presence of a pty. msys_tty_on(handle as HANDLE) } } /// Returns true if there is an MSYS tty on the given handle. /// /// This incoproates d7b0bcb20f2f7d5f3ea3489d56ece630147e98f5 #[cfg(windows)] unsafe fn msys_tty_on(handle: HANDLE) -> bool { use std::ffi::c_void; use windows_sys::Win32::{ Foundation::MAX_PATH, Storage::FileSystem::{ FileNameInfo, GetFileInformationByHandleEx, GetFileType, FILE_TYPE_PIPE, }, }; // Early return if the handle is not a pipe. if GetFileType(handle) != FILE_TYPE_PIPE { return false; } /// Mirrors windows_sys::Win32::Storage::FileSystem::FILE_NAME_INFO, giving /// it a fixed length that we can stack allocate #[repr(C)] #[allow(non_snake_case)] struct FILE_NAME_INFO { FileNameLength: u32, FileName: [u16; MAX_PATH as usize], } let mut name_info = FILE_NAME_INFO { FileNameLength: 0, FileName: [0; MAX_PATH as usize], }; // Safety: buffer length is fixed. let res = GetFileInformationByHandleEx( handle, FileNameInfo, &mut name_info as *mut _ as *mut c_void, std::mem::size_of::<FILE_NAME_INFO>() as u32, ); if res == 0 { return false; } // Use `get` because `FileNameLength` can be out of range. let s = match name_info .FileName .get(..name_info.FileNameLength as usize / 2) { None => return false, Some(s) => s, }; let name = String::from_utf16_lossy(s); // Get the file name only. let name = name.rsplit('\\').next().unwrap_or(&name); // This checks whether 'pty' exists in the file name, which indicates that // a pseudo-terminal is attached. To mitigate against false positives // (e.g., an actual file name that contains 'pty'), we also require that // the file name begins with either the strings 'msys-' or 'cygwin-'.) let is_msys = name.starts_with("msys-") || name.starts_with("cygwin-"); let is_pty = name.contains("-pty"); is_msys && is_pty } #[cfg(target_os = "unknown")] impl IsTerminal for std::io::Stdin { #[inline] fn is_terminal(&self) -> bool { false } } #[cfg(target_os = "unknown")] impl IsTerminal for std::io::Stdout { #[inline] fn is_terminal(&self) -> bool { false } } #[cfg(target_os = "unknown")] impl IsTerminal for std::io::Stderr { #[inline] fn is_terminal(&self) -> bool { false } } #[cfg(target_os = "unknown")] impl<'a> IsTerminal for std::io::StdinLock<'a> { #[inline] fn is_terminal(&self) -> bool { false } } #[cfg(target_os = "unknown")] impl<'a> IsTerminal for std::io::StdoutLock<'a> { #[inline] fn is_terminal(&self) -> bool { false } } #[cfg(target_os = "unknown")] impl<'a> IsTerminal for std::io::StderrLock<'a> { #[inline] fn is_terminal(&self) -> bool { false } } #[cfg(target_os = "unknown")] impl<'a> IsTerminal for std::fs::File { #[inline] fn is_terminal(&self) -> bool { false } } #[cfg(target_os = "unknown")] impl IsTerminal for std::process::ChildStdin { #[inline] fn is_terminal(&self) -> bool { false } } #[cfg(target_os = "unknown")] impl IsTerminal for std::process::ChildStdout { #[inline] fn is_terminal(&self) -> bool { false } } #[cfg(target_os = "unknown")] impl IsTerminal for std::process::ChildStderr { #[inline] fn is_terminal(&self) -> bool { false } } #[cfg(test)] mod tests { #[cfg(not(target_os = "unknown"))] use super::IsTerminal; #[test] #[cfg(windows)] fn stdin() { assert_eq!( atty::is(atty::Stream::Stdin), std::io::stdin().is_terminal() ) } #[test] #[cfg(windows)] fn stdout() { assert_eq!( atty::is(atty::Stream::Stdout), std::io::stdout().is_terminal() ) } #[test] #[cfg(windows)] fn stderr() { assert_eq!( atty::is(atty::Stream::Stderr), std::io::stderr().is_terminal() ) } #[test] #[cfg(any(unix, target_os = "wasi"))] fn stdin() { assert_eq!( atty::is(atty::Stream::Stdin), rustix::stdio::stdin().is_terminal() ) } #[test] #[cfg(any(unix, target_os = "wasi"))] fn stdout() { assert_eq!( atty::is(atty::Stream::Stdout), rustix::stdio::stdout().is_terminal() ) } #[test] #[cfg(any(unix, target_os = "wasi"))] fn stderr() { assert_eq!( atty::is(atty::Stream::Stderr), rustix::stdio::stderr().is_terminal() ) } #[test] #[cfg(any(unix, target_os = "wasi"))] fn stdin_vs_libc() { unsafe { assert_eq!( libc::isatty(libc::STDIN_FILENO) != 0, rustix::stdio::stdin().is_terminal() ) } } #[test] #[cfg(any(unix, target_os = "wasi"))] fn stdout_vs_libc() { unsafe { assert_eq!( libc::isatty(libc::STDOUT_FILENO) != 0, rustix::stdio::stdout().is_terminal() ) } } #[test] #[cfg(any(unix, target_os = "wasi"))] fn stderr_vs_libc() { unsafe { assert_eq!( libc::isatty(libc::STDERR_FILENO) != 0, rustix::stdio::stderr().is_terminal() ) } } // Verify that the msys_tty_on function works with long path. #[test] #[cfg(windows)] fn msys_tty_on_path_length() { use std::{fs::File, os::windows::io::AsRawHandle}; use windows_sys::Win32::Foundation::MAX_PATH; let dir = tempfile::tempdir().expect("Unable to create temporary directory"); let file_path = dir.path().join("ten_chars_".repeat(25)); // Ensure that the path is longer than MAX_PATH. assert!(file_path.to_string_lossy().len() > MAX_PATH as usize); let file = File::create(file_path).expect("Unable to create file"); assert!(!unsafe { crate::msys_tty_on(file.as_raw_handle() as isize) }); } }
use std::fs::File; use std::io::{Read}; extern crate html5ever; extern crate clap; extern crate regex; use html5ever::{parse, one_input}; use html5ever::rcdom::RcDom; use clap::{Arg, App, SubCommand}; use regex::Regex; struct ModelValues { main_values: String, comparisons: Vec<String> } fn open_file(path: &str, mut buffer: &mut String)-> std::io::Result<()> { let mut f = try!(File::open(path)); try!(f.read_to_string(&mut buffer)); Ok(()) } fn main() { let matches = App::new("clp_gen") .version("1.0") .author("Jason Cardinal <jason.brogrammer@gmail.com>") .arg(Arg::with_name("INPUT_FILE") .help("Sets the file to use") .takes_value(true) .required(true) .short("i") .long("input")) .arg(Arg::with_name("VALUES") .help("Sets the values to use") .takes_value(true) .required(true) .short("v") .long("vals")) .get_matches(); let input_file = match matches.value_of("INPUT_FILE") { Some(file_path) => file_path, None => panic!("No file specified") }; let values_file = match matches.value_of("VALUES") { Some(file_path) => file_path, None => panic!("No value file specified") }; let mut input_file_buffer = String::new(); let mut values_file_buffer = String::new(); open_file(input_file, &mut input_file_buffer).unwrap(); open_file(values_file, &mut values_file_buffer).unwrap(); let re = Regex::new(r"<!--[\s]*[\w-]+[\s]*-->").unwrap(); for (s, e) in re.find_iter(&input_file_buffer[..]){ println!("mathc: {:?}", &input_file_buffer[s..e]); } }
// 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::BTreeMap; use std::sync::Arc; use common_catalog::table::Table; use common_meta_app::schema::TableIdent; use common_meta_app::schema::TableInfo; use common_meta_app::schema::TableMeta; use common_storages_view::view_table::ViewTable; use common_storages_view::view_table::QUERY; pub struct TablesTable {} impl TablesTable { pub fn create(table_id: u64) -> Arc<dyn Table> { let query = "SELECT database AS table_catalog, database AS table_schema, name AS table_name, 'BASE TABLE' AS table_type, engine AS engine, created_on AS create_time, dropped_on AS drop_time, data_size AS data_length, index_size AS index_length, '' AS table_comment FROM system.tables;"; let mut options = BTreeMap::new(); options.insert(QUERY.to_string(), query.to_string()); let table_info = TableInfo { desc: "'information_schema'.'tables'".to_string(), name: "tables".to_string(), ident: TableIdent::new(table_id, 0), meta: TableMeta { options, engine: "VIEW".to_string(), ..Default::default() }, ..Default::default() }; ViewTable::create(table_info) } }
use crate::{HdbError, HdbResult}; #[cfg(feature = "sync")] use byteorder::WriteBytesExt; use byteorder::{BigEndian, LittleEndian, ReadBytesExt}; pub(crate) const MAX_1_BYTE_LENGTH: u8 = 245; pub(crate) const MAX_2_BYTE_LENGTH: i16 = i16::max_value(); const LENGTH_INDICATOR_2BYTE: u8 = 246; const LENGTH_INDICATOR_4BYTE: u8 = 247; pub(crate) const LENGTH_INDICATOR_NULL: u8 = 255; #[allow(clippy::cast_possible_truncation)] #[cfg(feature = "sync")] pub(crate) fn sync_emit(l: usize, w: &mut dyn std::io::Write) -> HdbResult<()> { match l { l if l <= MAX_1_BYTE_LENGTH as usize => w.write_u8(l as u8)?, l if l <= 0xFFFF => { w.write_u8(LENGTH_INDICATOR_2BYTE)?; w.write_u16::<LittleEndian>(l as u16)?; } l if l <= 0xFFFF_FFFF => { w.write_u8(LENGTH_INDICATOR_4BYTE)?; w.write_u32::<LittleEndian>(l as u32)?; } l => { return Err(HdbError::ImplDetailed(format!("Value too big: {l}"))); } } Ok(()) } #[cfg(feature = "async")] #[allow(clippy::cast_possible_truncation)] pub(crate) async fn async_emit<W: std::marker::Unpin + tokio::io::AsyncWriteExt>( l: usize, w: &mut W, ) -> HdbResult<()> { match l { l if l <= MAX_1_BYTE_LENGTH as usize => w.write_u8(l as u8).await?, l if l <= 0xFFFF => { w.write_u8(LENGTH_INDICATOR_2BYTE).await?; w.write_u16_le(l as u16).await?; } l if l <= 0xFFFF_FFFF => { w.write_u8(LENGTH_INDICATOR_4BYTE).await?; w.write_u32_le(l as u32).await?; } l => { return Err(HdbError::ImplDetailed(format!("Value too big: {l}"))); } } Ok(()) } // is also used in async context pub(crate) fn parse_sync(l8: u8, rdr: &mut dyn std::io::Read) -> HdbResult<usize> { match l8 { 0..=MAX_1_BYTE_LENGTH => Ok(l8 as usize), LENGTH_INDICATOR_2BYTE => Ok(rdr.read_u16::<LittleEndian>()? as usize), LENGTH_INDICATOR_4BYTE => Ok(rdr.read_u32::<LittleEndian>()? as usize), LENGTH_INDICATOR_NULL => Ok(rdr.read_u16::<BigEndian>()? as usize), _ => Err(HdbError::ImplDetailed(format!( "Unknown length indicator for AuthField: {l8}", ))), } } #[cfg(feature = "async")] pub(crate) async fn parse_async<R: std::marker::Unpin + tokio::io::AsyncReadExt>( l8: u8, rdr: &mut R, ) -> HdbResult<usize> { match l8 { 0..=MAX_1_BYTE_LENGTH => Ok(l8 as usize), LENGTH_INDICATOR_2BYTE => Ok(rdr.read_u16_le().await? as usize), LENGTH_INDICATOR_4BYTE => Ok(rdr.read_u32_le().await? as usize), LENGTH_INDICATOR_NULL => Ok(rdr.read_u16().await? as usize), _ => Err(HdbError::ImplDetailed(format!( "Unknown length indicator for AuthField: {l8}", ))), } }
#[macro_export] macro_rules! extend_module { ( $vm:expr, $module:expr, { $($name:expr => $value:expr),* $(,)? }) => {{ $( $vm.__module_set_attr($module, $vm.ctx.intern_str($name), $value).unwrap(); )* }}; } #[macro_export] macro_rules! py_class { ( $ctx:expr, $class_name:expr, $class_base:expr, { $($name:tt => $value:expr),* $(,)* }) => { py_class!($ctx, $class_name, $class_base, $crate::types::PyTypeFlags::BASETYPE, { $($name => $value),* }) }; ( $ctx:expr, $class_name:expr, $class_base:expr, $flags:expr, { $($name:tt => $value:expr),* $(,)* }) => { { #[allow(unused_mut)] let mut slots = $crate::types::PyTypeSlots::heap_default(); slots.flags = $flags; $($crate::py_class!(@extract_slots($ctx, &mut slots, $name, $value));)* let py_class = $ctx.new_class(None, $class_name, $class_base, slots); $($crate::py_class!(@extract_attrs($ctx, &py_class, $name, $value));)* py_class } }; (@extract_slots($ctx:expr, $slots:expr, (slot $slot_name:ident), $value:expr)) => { $slots.$slot_name.store(Some($value)); }; (@extract_slots($ctx:expr, $class:expr, $name:expr, $value:expr)) => {}; (@extract_attrs($ctx:expr, $slots:expr, (slot $slot_name:ident), $value:expr)) => {}; (@extract_attrs($ctx:expr, $class:expr, $name:expr, $value:expr)) => { $class.set_attr($name, $value); }; } #[macro_export] macro_rules! extend_class { ( $ctx:expr, $class:expr, { $($name:expr => $value:expr),* $(,)* }) => { $( $class.set_attr($ctx.intern_str($name), $value.into()); )* }; } #[macro_export] macro_rules! py_namespace { ( $vm:expr, { $($name:expr => $value:expr),* $(,)* }) => { { let namespace = $crate::builtins::PyNamespace::new_ref(&$vm.ctx); let obj = $crate::object::AsObject::as_object(&namespace); $( obj.generic_setattr($vm.ctx.intern_str($name), $crate::function::PySetterValue::Assign($value.into()), $vm).unwrap(); )* namespace } } } /// Macro to match on the built-in class of a Python object. /// /// Like `match`, `match_class!` must be exhaustive, so a default arm without /// casting is required. /// /// # Examples /// /// ``` /// use malachite_bigint::ToBigInt; /// use num_traits::Zero; /// /// use rustpython_vm::match_class; /// use rustpython_vm::builtins::{PyFloat, PyInt}; /// use rustpython_vm::{PyPayload}; /// /// # rustpython_vm::Interpreter::without_stdlib(Default::default()).enter(|vm| { /// let obj = PyInt::from(0).into_pyobject(vm); /// assert_eq!( /// "int", /// match_class!(match obj { /// PyInt => "int", /// PyFloat => "float", /// _ => "neither", /// }) /// ); /// # }); /// /// ``` /// /// With a binding to the downcasted type: /// /// ``` /// use malachite_bigint::ToBigInt; /// use num_traits::Zero; /// /// use rustpython_vm::match_class; /// use rustpython_vm::builtins::{PyFloat, PyInt}; /// use rustpython_vm::{ PyPayload}; /// /// # rustpython_vm::Interpreter::without_stdlib(Default::default()).enter(|vm| { /// let obj = PyInt::from(0).into_pyobject(vm); /// /// let int_value = match_class!(match obj { /// i @ PyInt => i.as_bigint().clone(), /// f @ PyFloat => f.to_f64().to_bigint().unwrap(), /// obj => panic!("non-numeric object {:?}", obj), /// }); /// /// assert!(int_value.is_zero()); /// # }); /// ``` #[macro_export] macro_rules! match_class { // The default arm. (match ($obj:expr) { _ => $default:expr $(,)? }) => { $default }; // The default arm, binding the original object to the specified identifier. (match ($obj:expr) { $binding:ident => $default:expr $(,)? }) => {{ let $binding = $obj; $default }}; (match ($obj:expr) { ref $binding:ident => $default:expr $(,)? }) => {{ let $binding = &$obj; $default }}; // An arm taken when the object is an instance of the specified built-in // class and binding the downcasted object to the specified identifier and // the target expression is a block. (match ($obj:expr) { $binding:ident @ $class:ty => $expr:block $($rest:tt)* }) => { $crate::match_class!(match ($obj) { $binding @ $class => ($expr), $($rest)* }) }; (match ($obj:expr) { ref $binding:ident @ $class:ty => $expr:block $($rest:tt)* }) => { $crate::match_class!(match ($obj) { ref $binding @ $class => ($expr), $($rest)* }) }; // An arm taken when the object is an instance of the specified built-in // class and binding the downcasted object to the specified identifier. (match ($obj:expr) { $binding:ident @ $class:ty => $expr:expr, $($rest:tt)* }) => { match $obj.downcast::<$class>() { Ok($binding) => $expr, Err(_obj) => $crate::match_class!(match (_obj) { $($rest)* }), } }; (match ($obj:expr) { ref $binding:ident @ $class:ty => $expr:expr, $($rest:tt)* }) => { match $obj.payload::<$class>() { ::std::option::Option::Some($binding) => $expr, ::std::option::Option::None => $crate::match_class!(match ($obj) { $($rest)* }), } }; // An arm taken when the object is an instance of the specified built-in // class and the target expression is a block. (match ($obj:expr) { $class:ty => $expr:block $($rest:tt)* }) => { $crate::match_class!(match ($obj) { $class => ($expr), $($rest)* }) }; // An arm taken when the object is an instance of the specified built-in // class. (match ($obj:expr) { $class:ty => $expr:expr, $($rest:tt)* }) => { if $obj.payload_is::<$class>() { $expr } else { $crate::match_class!(match ($obj) { $($rest)* }) } }; // To allow match expressions without parens around the match target (match $($rest:tt)*) => { $crate::match_class!(@parse_match () ($($rest)*)) }; (@parse_match ($($target:tt)*) ({ $($inner:tt)* })) => { $crate::match_class!(match ($($target)*) { $($inner)* }) }; (@parse_match ($($target:tt)*) ($next:tt $($rest:tt)*)) => { $crate::match_class!(@parse_match ($($target)* $next) ($($rest)*)) }; } #[macro_export] macro_rules! identifier( ($as_ctx:expr, $name:ident) => { $as_ctx.as_ref().names.$name }; ); /// Super detailed logging. Might soon overflow your log buffers /// Default, this logging is discarded, except when a the `vm-tracing-logging` /// build feature is enabled. macro_rules! vm_trace { ($($arg:tt)+) => { #[cfg(feature = "vm-tracing-logging")] trace!($($arg)+); } } macro_rules! flame_guard { ($name:expr) => { #[cfg(feature = "flame-it")] let _guard = ::flame::start_guard($name); }; } #[macro_export] macro_rules! class_or_notimplemented { ($t:ty, $obj:expr) => {{ let a: &$crate::PyObject = &*$obj; match $crate::PyObject::downcast_ref::<$t>(&a) { Some(pyref) => pyref, None => return Ok($crate::function::PyArithmeticValue::NotImplemented), } }}; } #[macro_export] macro_rules! named_function { ($ctx:expr, $module:ident, $func:ident) => {{ #[allow(unused_variables)] // weird lint, something to do with paste probably let ctx: &$crate::Context = &$ctx; $crate::__exports::paste::expr! { ctx.new_method_def( stringify!($func), [<$module _ $func>], ::rustpython_vm::function::PyMethodFlags::empty(), ) .to_function() .with_module(ctx.intern_str(stringify!($module)).into()) .into_ref(ctx) } }}; } // can't use PyThreadingConstraint for stuff like this since it's not an auto trait, and // therefore we can't add it ad-hoc to a trait object cfg_if::cfg_if! { if #[cfg(feature = "threading")] { macro_rules! py_dyn_fn { (dyn Fn($($arg:ty),*$(,)*) -> $ret:ty) => { dyn Fn($($arg),*) -> $ret + Send + Sync + 'static }; } } else { macro_rules! py_dyn_fn { (dyn Fn($($arg:ty),*$(,)*) -> $ret:ty) => { dyn Fn($($arg),*) -> $ret + 'static }; } } }
use std::collections::HashMap; use crate::idl; use super::errors::ValidationError; use super::namespace::Namespace; use super::r#type::Type; use super::typemap::TypeMap; pub struct Service { pub name: String, pub methods: Vec<Method>, } pub struct Method { pub name: String, pub input: Option<Type>, pub output: Option<Type>, } impl Service { pub(crate) fn from_idl( iservice: &idl::Service, ns: &Namespace, builtin_types: &HashMap<String, String>, ) -> Self { Self { name: iservice.name.clone(), methods: iservice .methods .iter() .map(|imethod| Method { name: imethod.name.clone(), input: imethod .input .as_ref() .map(|x| Type::from_idl(x, ns, &builtin_types)), output: imethod .output .as_ref() .map(|x| Type::from_idl(x, ns, &builtin_types)), }) .collect(), } } pub(crate) fn resolve(&mut self, type_map: &TypeMap) -> Result<(), ValidationError> { for method in self.methods.iter_mut() { if let Some(input) = &mut method.input { input.resolve(type_map)?; } if let Some(output) = &mut method.output { output.resolve(type_map)?; } } Ok(()) } }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::sync::Arc; use common_exception::ErrorCode; use common_exception::Result; use common_expression::BlockThresholds; use common_expression::DataBlock; use super::Compactor; use super::TransformCompact; pub struct BlockCompactorNoSplit { thresholds: BlockThresholds, aborting: Arc<AtomicBool>, // call block.memory_size() only once. // we may no longer need it if we start using jsonb, otherwise it should be put in CompactorState accumulated_rows: usize, accumulated_bytes: usize, } impl BlockCompactorNoSplit { pub fn new(thresholds: BlockThresholds) -> Self { BlockCompactorNoSplit { thresholds, accumulated_rows: 0, accumulated_bytes: 0, aborting: Arc::new(AtomicBool::new(false)), } } } impl Compactor for BlockCompactorNoSplit { fn name() -> &'static str { "BlockCompactTransform" } fn use_partial_compact() -> bool { true } fn interrupt(&self) { self.aborting.store(true, Ordering::Release); } fn compact_partial(&mut self, blocks: &mut Vec<DataBlock>) -> Result<Vec<DataBlock>> { if blocks.is_empty() { return Ok(vec![]); } let size = blocks.len(); let mut res = Vec::with_capacity(size); let block = blocks[size - 1].clone(); let num_rows = block.num_rows(); let num_bytes = block.memory_size(); if self.thresholds.check_large_enough(num_rows, num_bytes) { // pass through the new data block just arrived res.push(block); blocks.remove(size - 1); } else { let accumulated_rows_new = self.accumulated_rows + num_rows; let accumulated_bytes_new = self.accumulated_bytes + num_bytes; if self .thresholds .check_large_enough(accumulated_rows_new, accumulated_bytes_new) { // avoid call concat_blocks for each new block let merged = DataBlock::concat(blocks)?; blocks.clear(); self.accumulated_rows = 0; self.accumulated_bytes = 0; res.push(merged); } else { self.accumulated_rows = accumulated_rows_new; self.accumulated_bytes = accumulated_bytes_new; } } Ok(res) } fn compact_final(&self, blocks: &[DataBlock]) -> Result<Vec<DataBlock>> { let mut res = vec![]; if self.accumulated_rows != 0 { if self.aborting.load(Ordering::Relaxed) { return Err(ErrorCode::AbortedQuery( "Aborted query, because the server is shutting down or the query was killed.", )); } let block = DataBlock::concat(blocks)?; res.push(block); } Ok(res) } } pub type TransformBlockCompact = TransformCompact<BlockCompactorNoSplit>;
use futures01::Future; use snafu::Snafu; #[cfg(feature = "sources-docker")] pub mod docker; #[cfg(feature = "sources-file")] pub mod file; #[cfg(feature = "sources-generator")] pub mod generator; #[cfg(feature = "sources-http")] pub mod http; #[cfg(feature = "sources-internal_metrics")] pub mod internal_metrics; #[cfg(all(feature = "sources-journald", feature = "unix"))] pub mod journald; #[cfg(all(feature = "sources-kafka", feature = "rdkafka"))] pub mod kafka; #[cfg(feature = "sources-kubernetes-logs")] pub mod kubernetes_logs; #[cfg(feature = "sources-logplex")] pub mod logplex; #[cfg(feature = "sources-prometheus")] pub mod prometheus; #[cfg(feature = "sources-socket")] pub mod socket; #[cfg(feature = "sources-splunk_hec")] pub mod splunk_hec; #[cfg(feature = "sources-statsd")] pub mod statsd; #[cfg(feature = "sources-stdin")] pub mod stdin; #[cfg(feature = "sources-syslog")] pub mod syslog; #[cfg(feature = "sources-vector")] pub mod vector; mod util; pub type Source = Box<dyn Future<Item = (), Error = ()> + Send>; /// Common build errors #[derive(Debug, Snafu)] enum BuildError { #[snafu(display("URI parse error: {}", source))] UriParseError { source: ::http::uri::InvalidUri }, }
#![feature(const_fn)] extern crate glfw; extern crate gl; extern crate state; use engine::*; use glfw::{Action, Context, Key, WindowHint, OpenGlProfileHint, WindowMode, Window, WindowEvent, CursorMode}; use std::sync::mpsc::Receiver; use ecs::components::*; use specs::prelude::*; use ecs::systems::*; use ecs::resources::*; use crate::shaders::diffuse::DiffuseShader; use crate::ecs::components::PointLight; use glfw::ffi::{glfwSwapInterval}; use nalgebra_glm::{vec3, Mat3}; use crate::containers::*; use nalgebra::{Vector}; use ncollide3d::shape::{ShapeHandle, Cuboid}; use nphysics3d::object::{BodyStatus}; use nphysics3d::material::BasicMaterial; use nphysics3d::algebra::Velocity3; use crate::shaders::outline::OutlineShader; use crate::shaders::post_processing::{KernelShader, GaussianBlurShader}; use engine::shaders::cube_map::CubeMapShader; use engine::gl_wrapper::texture_cube_map::TextureCubeMap; use engine::shapes::PredefinedShapes; use std::sync::Arc; use debugging::debug_message_callback; use std::os::raw::c_void; use engine::voxel_2d::{ResourceManager, BlockCatalog, VoxelWorld}; use std::path::Path; use engine::shaders::voxel::VoxelShader; fn setup_window(title: &str, width: u32, height: u32, mode: WindowMode) -> (Window, Receiver<(f64, WindowEvent)>) { let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(WindowHint::ContextVersionMajor(4)); glfw.window_hint(WindowHint::ContextVersionMinor(5)); glfw.window_hint(WindowHint::OpenGlProfile(OpenGlProfileHint::Core)); glfw.window_hint(WindowHint::OpenGlDebugContext(true)); let (mut window, events) = glfw.create_window(width, height, title, mode).unwrap(); window.set_key_polling(true); window.set_cursor_enter_polling(true); window.set_cursor_pos_polling(true); window.set_cursor_mode(CursorMode::Disabled); window.set_cursor_pos(300.0, 300.0); window.set_raw_mouse_motion(true); window.make_current(); gl::load_with(|s| window.get_proc_address(s) as *const _); unsafe { glfwSwapInterval(0) }; (window, events) } fn main() { pretty_env_logger::init(); let (mut window, events) = setup_window("Window", 1920, 1080, glfw::WindowMode::Windowed); let mut i = 0; gl_call!(gl::GetIntegerv(gl::MAX_ARRAY_TEXTURE_LAYERS, &mut i)); println!("MAX LAYERS: {}", i); let mut world = World::new(); world.register::<Transform>(); world.register::<MeshRenderer>(); world.register::<Camera>(); world.insert(ActiveCamera::default()); world.register::<DirLight>(); world.register::<PointLight>(); world.register::<Spotlight>(); world.register::<Input>(); world.insert(InputEventQueue::default()); world.insert(InputCache::default()); world.insert(Time::default()); world.register::<Outliner>(); // Physics stuff world.insert(PhysicsWorld { world: { let mut physics_world = nphysics3d::world::World::<f32>::new(); physics_world.set_gravity(Vector::y() * -9.81); physics_world }, ..PhysicsWorld::default() }); world.register::<RigidBody>(); world.register::<BoxCollider>(); world.register::<Collider>(); CONTAINER.set_local(ModelLoader::default); CONTAINER.set_local(TextureCache::default); CONTAINER.set_local(CubeMapShader::default); CONTAINER.set_local(DiffuseShader::default); CONTAINER.set_local(OutlineShader::default); CONTAINER.set_local(KernelShader::default); CONTAINER.set_local(GaussianBlurShader::default); CONTAINER.set_local(PredefinedShapes::default); // let model_loader = CONTAINER.get_local::<ModelLoader>(); // let mesh_renderer = model_loader.load("models/cube/box_test.obj"); // let gun = model_loader.load("models/gun/modified_gun.obj"); let transform_system = { let mut comps = world.write_storage::<Transform>(); TransformSystem { reader_id: comps.register_reader(), dirty: BitSet::new(), } }; let sync_bodies_to_physics_system = { let mut transforms = world.write_storage::<Transform>(); let mut rigidbodies = world.write_storage::<RigidBody>(); SyncBodiesToPhysicsSystem { transforms_reader_id: transforms.register_reader(), rigidbodies_reader_id: rigidbodies.register_reader(), } }; let sync_colliders_to_physics_system = { let mut colliders = world.write_storage::<Collider>(); SyncCollidersToPhysicsSystem { colliders_reader_id: colliders.register_reader(), } }; let physics_stepper = { let mut physics_world = world.write_resource::<PhysicsWorld>(); PhysicsStepperSystem::new(&mut physics_world.world, 128) }; let mut dispatcher = DispatcherBuilder::new() // Physics .with(sync_bodies_to_physics_system, "sync_bodies_to_physics_system", &[]) .with(sync_colliders_to_physics_system, "sync_colliders_to_physics_system", &[ "sync_bodies_to_physics_system" ]) .with(physics_stepper, "physics_stepper", &[ "sync_bodies_to_physics_system", "sync_colliders_to_physics_system" ]) .with(SyncBodiesFromPhysicsSystem, "sync_bodies_from_physics_system", &[ "physics_stepper" ]) .with_barrier() .with(transform_system, "transform_system", &[]) .with_thread_local(MeshRendererSystem::default()) .build(); // Scene objects & resources // let _floor = world.create_entity() // .with(Transform { // position: vec3(0.0, 0.0, 0.0), // scale: 10.0.to_vec3(), // ..Transform::default() // }) // .with(mesh_renderer.clone()) // .with(RigidBody { // status: BodyStatus::Static, // ..RigidBody::default() // }) // .with(Collider { // shape: ShapeHandle::new(Cuboid::new(vec3(0.25, 0.25, 0.25) * 10.0)), // material: BasicMaterial::default(), // }) // .with(Outliner { // scale: 1.05f32, // color: vec3(1.0, 1.0, 0.0), // }) // .build(); CONTAINER.set_local(|| ResourceManager::gen_blocks_texture_atlas(Path::new("models/papercraft/textures/blocks"))); CONTAINER.set_local(VoxelShader::default); let mut voxel_world = VoxelWorld::new((16, 16)); voxel_world.place_some_blocks(); use std::f32; let camera_entity = world.create_entity() .with(Transform { position: vec3(0.0, 0.0, 10.0), rotation: vec3(0.0, -f32::consts::PI / 2.0, 0.0), ..Transform::default() }) .with(Camera::new( // Projection::Perspective(70.0f32.to_radians()), Projection::Orthographic(35.0f32), 1920.0f32 / 1080.0f32, 0.1, 1000.0, Background::Color(0.8, 0.8, 0.8), vec![ // Box::new(Kernel::new(vec![ // 1.0, 1.0, 1.0, // 1.0, -8.0, 1.0, // 1.0, 1.0, 1.0 // ])), // Box::new(GaussianBlur::new(vec![0.034619, 0.044859, 0.055857, 0.066833, 0.076841, 0.084894, 0.090126, 0.09194, 0.090126, 0.084894, 0.076841, 0.066833, 0.055857, 0.044859, 0.034619])), ])) .with(Input) .build(); world.write_resource::<ActiveCamera>().entity = Some(camera_entity); let mut input_system = InputSystem; let mut print_framerate = PrintFramerate::default(); gl_call!(gl::Enable(gl::DEBUG_OUTPUT)); gl_call!(gl::Enable(gl::DEBUG_OUTPUT_SYNCHRONOUS)); gl_call!(gl::DebugMessageCallback(debug_message_callback, 0 as *const c_void)); gl_call!(gl::DebugMessageControl(gl::DONT_CARE, gl::DONT_CARE, gl::DONT_CARE, 0, 0 as *const u32, gl::TRUE)); gl_call!(gl::Enable(gl::CULL_FACE)); gl_call!(gl::CullFace(gl::BACK)); gl_call!(gl::Enable(gl::DEPTH_TEST)); gl_call!(gl::Enable(gl::STENCIL_TEST)); gl_call!(gl::Enable(gl::BLEND)); gl_call!(gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA)); while !window.should_close() { for (_, event) in glfw::flush_messages(&events) { match event { glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => { window.set_should_close(true); } _ => { world.write_resource::<InputEventQueue>().queue.push_back(event); } }; }; dispatcher.dispatch(&world); gl_call!(gl::Disable(gl::CULL_FACE)); voxel_world.render(); input_system.run_now(&world); world.maintain(); window.swap_buffers(); window.glfw.poll_events(); world.write_resource::<Time>().tick(); print_framerate.run_now(&world); } }
use super::not_found; use crate::{ error::AppError, models::{entry, entry_tag, tag}, state::AppState, }; use axum::{ http::{header, StatusCode}, response::{IntoResponse, Response}, }; use minijinja::context; use sea_orm::{entity::prelude::*, query::*, sea_query::Query}; use std::sync::Arc; pub async fn view( app_state: Arc<AppState>, results: Vec<(entry::Model, Vec<tag::Model>)>, template_override: Option<String>, content_type: String, may_redirect: bool, ) -> anyhow::Result<Response, AppError> { if let Some((entry, entry_tags)) = results.get(0) { if let Some(permalink) = if !may_redirect { None } else { entry.clone().permalink } { Ok(( [(header::LOCATION, permalink)], StatusCode::MOVED_PERMANENTLY, ) .into_response()) } else { let feed = match entry.feed { Some(entry::feed::Feed::Category) => Some( entry::Entity::find() .filter(entry::Column::Category.eq(entry.slug.clone())) .order_by(entry::Column::Date, Order::Desc) .find_with_related(tag::Entity) .all(&app_state.database) .await?, ), Some(entry::feed::Feed::Tag) => Some( entry::Entity::find() .filter( entry::Column::Id.in_subquery( Query::select() .from(entry_tag::Entity) .left_join( tag::Entity, Expr::col((tag::Entity, tag::Column::Id)) .equals((entry_tag::Entity, entry_tag::Column::TagId)), ) .column(entry_tag::Column::EntryId) .and_where(tag::Column::Slug.eq(entry.slug.clone())) .to_owned(), ), ) .order_by(entry::Column::Date, Order::Desc) .find_with_related(tag::Entity) .all(&app_state.database) .await?, ), None => None, }; let template = template_override.unwrap_or( entry .clone() .template .unwrap_or("layouts/entry.jinja".to_string()), ); let html = app_state .templates .get_template(template.as_str()) .and_then(|template| { template.render(context! { entry => entry, feed => feed, entry_tags => entry_tags, }) })?; let body = html.as_bytes().to_vec(); Ok(([(header::CONTENT_TYPE, content_type)], body).into_response()) } } else if content_type == *"text/html; charset=utf-8" { not_found::view(app_state) } else { Ok(StatusCode::NOT_FOUND.into_response()) } }
#![cfg_attr(not(feature = "std"), no_std)] use ink_env::{ hash::{Blake2x256, CryptoHash, HashOutput}, AccountId, }; use ink_prelude::vec::Vec; use ink_prelude::string::String; use ink_storage::traits::{PackedLayout, SpreadLayout}; /// 主合约错误信息 #[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum NFTicketError{ ControllerError, // 模板合约的 controller 信息错误 OnlyTemplateContractCall, // 仅能通过模板合约调用 OnlyMeetingContractCall, // 仅限通过活动合约调用 OnlyMeetingContractOrAdministor, // 仅活动合约或者系统管理员可调用 LessThanMinCreateMeetingFee, // 小于创建会议的费用 LessThanMinCreateTicketFee, // 小于创建门票的费用 ClassIdNotFound, // 没有找到 class id } #[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub struct TickeResult { pub price: u128, pub maker: ink_env::AccountId, } #[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum MeetingError { LessThanCreateTicketFee, // 票价低于最低创建门票费用 LessThanSoldTickets, // 设置的门票数小于已经售出的门票数 NotOwner, CallBuyTickerError, TransferError, } #[derive(Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout)] #[cfg_attr( feature = "std", derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout) )] pub struct Ticket { template_addr: AccountId, //模板id meeting: AccountId, //活动地址 hash: Vec<u8>, //hash值 price: u128, //价格 zone_id: u32, //区域. seat_id: Option<(u32, u32)>, } /// 模板状态 #[derive(Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout)] #[cfg_attr( feature = "std", derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout) )] pub enum TemplateStatus { Active, Stop, } /// 模板合约错误信息 #[derive(Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout)] #[cfg_attr( feature = "std", derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout) )] pub enum TemplateError { LessThanCreateMeetingFee, // 小于创建活动需要的费用 MeetingDeployFail, // 活动合约部署失败 } // 模板数据结构 #[derive(Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout)] #[cfg_attr( feature = "std", derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout) )] pub struct Template { pub template_addr: AccountId, pub name: String, // 模板名称 pub desc: String, // 介绍内容 pub uri: String, // 介绍网址 pub ratio: u128, // 服务费提成比例 pub status: TemplateStatus, } /// 活动数据 #[derive(Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout)] #[cfg_attr( feature = "std", derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout) )] pub struct Meeting { pub template: AccountId, pub meeting: AccountId, pub name: String, pub desc: String, pub poster: String, pub uri: String, pub start_time: u64, pub end_time: u64, pub start_sale_time: u64, pub end_sale_time: u64, pub status: MeetingStatus, } /// 活动状态 #[derive(Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout)] #[cfg_attr( feature = "std", derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout) )] pub enum MeetingStatus { Active, Stop, } impl Ticket { pub fn new( template_addr: AccountId, meeting: AccountId, price: u128, zone_id: u32, seat_id: Option<(u32, u32)>, ticket_id: u32, ) -> Self { // 此处的生成hash的方法极度不合理.需要将template+meeting+price一起生成encode后得到进行hash运算. // let mut template_code=scale::Encode::encode(&template); let mut meeting_code = scale::Encode::encode(&meeting); let mut ticket_id_byte = ticket_id.to_be_bytes().to_vec(); meeting_code.append(&mut ticket_id_byte); // let random_hash:[u8] = ink_env::random(template_code).unwrap().0; // template_code.append(random_hash); let hash = scale::Encode::encode(&meeting_code); let mut hash_output = <<Blake2x256 as HashOutput>::Type as Default>::default(); <Blake2x256 as CryptoHash>::hash(&hash, &mut hash_output); Self { template_addr, meeting, hash: hash_output.into(), price, zone_id, seat_id, } } } // 检票历史记录 #[derive(Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode, SpreadLayout, PackedLayout)] #[cfg_attr( feature = "std", derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout) )] pub struct CheckRecord{ pub inspector: AccountId, // 检票人 pub timestamp: u64, // 检票时间戳 pub block: u32, // 检票记录区块 }
use serde::Deserialize; use sqs_executor::{ errors::{ CheckedError, Recoverable, }, event_decoder::PayloadDecoder, }; use crate::decoder::decompress::PayloadDecompressionError; #[derive(thiserror::Error, Debug)] pub enum JsonDecoderError { #[error("DecompressionError")] DecompressionError(#[from] PayloadDecompressionError), #[error("JsonError")] JsonError(#[from] serde_json::Error), } impl CheckedError for JsonDecoderError { fn error_type(&self) -> Recoverable { match self { Self::DecompressionError(_) => Recoverable::Persistent, Self::JsonError(_) => Recoverable::Persistent, } } } #[derive(Debug, Clone, Default)] pub struct JsonDecoder; impl<D> PayloadDecoder<D> for JsonDecoder where for<'a> D: Deserialize<'a>, { type DecoderError = JsonDecoderError; fn decode(&mut self, body: Vec<u8>) -> Result<D, Self::DecoderError> { let decompressed = super::decompress::maybe_decompress(body.as_slice())?; serde_json::from_slice(&decompressed).map_err(|e| e.into()) } }
use std::convert::TryInto; use std::ffi::c_void; use std::mem; use std::ptr::NonNull; use liblumen_alloc::erts::apply::find_symbol; use liblumen_alloc::erts::exception::InternalResult; use liblumen_alloc::erts::term::closure::{Definition, OldUnique}; use liblumen_alloc::erts::term::prelude::*; use liblumen_alloc::erts::Process; use liblumen_alloc::ModuleFunctionArity; use super::{atom, decode_vec_term, isize, u32, u8, Pid}; use crate::distribution::external_term_format::try_split_at; pub fn decode<'a>( process: &Process, safe: bool, bytes: &'a [u8], ) -> InternalResult<(Term, &'a [u8])> { let (total_byte_len, after_size_bytes) = u32::decode(bytes)?; let (arity, after_arity_bytes) = u8::decode(after_size_bytes)?; let (uniq, after_uniq_bytes) = decode_uniq(after_arity_bytes)?; let (index, after_index_bytes) = u32::decode(after_uniq_bytes)?; let (num_free, after_num_free_bytes) = u32::decode(after_index_bytes)?; let (module, after_module_bytes) = atom::decode_tagged(safe, after_num_free_bytes)?; let (old_index, after_old_index_bytes) = isize::decode(after_module_bytes)?; assert_eq!(old_index, index as isize); let (old_uniq, after_old_uniq_bytes) = isize::decode(after_old_index_bytes)?; let old_unique = old_uniq as OldUnique; let (creator, after_creator_bytes) = Pid::decode(safe, after_old_uniq_bytes)?; let env_len: usize = num_free as usize; let (env_vec, after_vec_term_bytes) = decode_vec_term(process, safe, after_creator_bytes, env_len)?; assert_eq!( bytes.len() - after_vec_term_bytes.len(), total_byte_len as usize ); let definition = Definition::Anonymous { index: index as usize, unique: uniq, old_unique, }; let module_function_arity = ModuleFunctionArity { module, function: definition.function_name(), arity, }; let option_native = find_symbol(&module_function_arity).map(|dynamic_callee| unsafe { let ptr = mem::transmute::<_, *mut c_void>(dynamic_callee); NonNull::new_unchecked(ptr) }); let closure = process.anonymous_closure_with_env_from_slice( module, index, old_unique, uniq, arity, option_native, creator.into(), &env_vec, ); Ok((closure, after_vec_term_bytes)) } const UNIQ_LEN: usize = 16; fn decode_uniq(bytes: &[u8]) -> InternalResult<([u8; UNIQ_LEN], &[u8])> { try_split_at(bytes, UNIQ_LEN).map(|(uniq_bytes, after_uniq_bytes)| { let uniq_array = uniq_bytes.try_into().unwrap(); (uniq_array, after_uniq_bytes) }) }
use ipfs_unixfs::file::adder::FileAdder; use basex_rs::{BaseX, BITCOIN, Encode}; use ipfs_unixfs::file::adder::Chunker; use ipfs_unixfs::file::adder::BalancedCollector; /* 【输入】 digest 需要计算hash的文件字节流 【输出】 Option类型、计算后的hash */ pub fn only_hash(digest : &Vec<u8>) -> Option<String> { // let mut file_addr = FileAdder::builder().build(); // file_addr.push( &digest ); // println!("finish: {:#?}", file_addr); // let mut finish = file_addr.finish(); // if let Some( (cid, _block) ) = finish.next() { // let data = cid.to_bytes(); // let hash = BaseX::new(BITCOIN).encode( &data ); // return Some( hash ); // } // None // only_hash_chunk(&digest) // only_hash_v3(&digest) only_hash_v4(&digest) } pub fn only_hash_chunk(digest: &Vec<u8>) -> Option<String> { let mut file_addr = FileAdder::builder().build(); file_addr.push( &digest ); println!("finish: {:#?}", file_addr); let mut finish = file_addr.finish(); let cid = finish.next().unwrap().0; println!("cid: {:?}", cid); { let data = cid.to_bytes(); let hash = BaseX::new(BITCOIN).encode( &data ); return Some( hash ); } None } pub fn only_hash_v3(digest: &Vec<u8>) -> Option<String> { let mut adder = FileAdder::default(); let mut last_block = String::new(); // println!("digest.len: {}", digest.len()); let mut total = 0; loop { if total >= digest.len() { // eprintln!("finishing"); // println!("adder: {:#?}", adder); let mut blocks = adder.finish(); let next = blocks.next(); let item = next.unwrap().0; // println!("cid : {:?}", item); let hash = BaseX::new(BITCOIN).encode( &item.to_bytes() ); // println!("hash: xxx {:?}", hash); last_block = hash; break; } while total < digest.len() { let (blocks, consumed) = adder.push(&digest[total..]); total += consumed; // println!("totoal: {}", total); // println!("consumed: {}", consumed); } } Some( last_block ) } pub fn only_hash_v4(digest: &Vec<u8>) -> Option<String> { let mut adder = FileAdder::default(); let mut amt = 0; let mut written = 0; let mut blocks_received = Vec::new(); if amt == 0 { amt = digest.len(); } while written < digest.len() { let end = written + (digest.len() - written).min(amt); let slice = &digest[written..end]; let (blocks, pushed) = adder.push(slice); blocks_received.extend(blocks); written += pushed; } let last_blocks = adder.finish(); blocks_received.extend(last_blocks); let blocks_len = blocks_received.len(); if blocks_len > 0 { let last = &blocks_received[blocks_len - 1].0.to_bytes(); let hash = BaseX::new(BITCOIN).encode( &last ); return Some( hash ); } None } // --------------------------------------------------------------------------------------------------------- // // ipfs 测试用例 // // --------------------------------------------------------------------------------------------------------- // cargo test api::ipfs::hash::tests::only_hash_test #[cfg(test)] mod tests { use super::*; #[test] fn only_hash_test() { let target = "Qmf412jQZiuVUtdgnB36FXFX7xg5V6KEbSJ4dpQuhkLyfD".to_owned(); let digest = "hello world".as_bytes().to_vec(); let hash = only_hash( &digest ).unwrap(); assert_eq!(hash, target); } }
// 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. #![deny(unused_crate_dependencies)] use std::pin::Pin; use std::sync::Arc; use std::task::Context; use std::task::Poll; use common_grpc::RpcClientConf; use common_meta_client::ClientHandle; use common_meta_client::MetaGrpcClient; use common_meta_embedded::MetaEmbedded; use common_meta_kvapi::kvapi; use common_meta_kvapi::kvapi::GetKVReply; use common_meta_kvapi::kvapi::ListKVReply; use common_meta_kvapi::kvapi::MGetKVReply; use common_meta_kvapi::kvapi::UpsertKVReply; use common_meta_kvapi::kvapi::UpsertKVReq; use common_meta_types::protobuf::WatchRequest; use common_meta_types::protobuf::WatchResponse; use common_meta_types::MetaError; use common_meta_types::TxnReply; use common_meta_types::TxnRequest; use tokio_stream::Stream; use tracing::info; pub type WatchStream = Pin<Box<dyn Stream<Item = Result<WatchResponse, MetaError>> + Send + 'static>>; #[derive(Clone)] pub struct MetaStoreProvider { rpc_conf: RpcClientConf, } /// MetaStore is impl with either a local embedded meta store, or a grpc-client of metasrv #[derive(Clone)] pub enum MetaStore { L(Arc<MetaEmbedded>), R(Arc<ClientHandle>), } impl MetaStore { pub fn arc(self) -> Arc<Self> { Arc::new(self) } pub fn is_local(&self) -> bool { match self { MetaStore::L(_) => true, MetaStore::R(_) => false, } } pub async fn get_local_addr(&self) -> std::result::Result<Option<String>, MetaError> { match self { MetaStore::L(_) => Ok(None), MetaStore::R(grpc_client) => { let client_info = grpc_client.get_client_info().await?; Ok(Some(client_info.client_addr)) } } } pub async fn watch(&self, request: WatchRequest) -> Result<WatchStream, MetaError> { match self { MetaStore::L(_) => unreachable!(), MetaStore::R(grpc_client) => { let streaming = grpc_client.request(request).await?; Ok(Box::pin(WatchResponseStream::create(streaming))) } } } } #[async_trait::async_trait] impl kvapi::KVApi for MetaStore { type Error = MetaError; async fn upsert_kv(&self, act: UpsertKVReq) -> Result<UpsertKVReply, MetaError> { match self { MetaStore::L(x) => x.upsert_kv(act).await, MetaStore::R(x) => x.upsert_kv(act).await, } } async fn get_kv(&self, key: &str) -> Result<GetKVReply, MetaError> { match self { MetaStore::L(x) => x.get_kv(key).await, MetaStore::R(x) => x.get_kv(key).await, } } async fn mget_kv(&self, key: &[String]) -> Result<MGetKVReply, MetaError> { match self { MetaStore::L(x) => x.mget_kv(key).await, MetaStore::R(x) => x.mget_kv(key).await, } } async fn prefix_list_kv(&self, prefix: &str) -> Result<ListKVReply, MetaError> { match self { MetaStore::L(x) => x.prefix_list_kv(prefix).await, MetaStore::R(x) => x.prefix_list_kv(prefix).await, } } async fn transaction(&self, txn: TxnRequest) -> Result<TxnReply, MetaError> { match self { MetaStore::L(x) => x.transaction(txn).await, MetaStore::R(x) => x.transaction(txn).await, } } } impl MetaStoreProvider { pub fn new(rpc_conf: RpcClientConf) -> Self { MetaStoreProvider { rpc_conf } } pub async fn create_meta_store(&self) -> Result<MetaStore, MetaError> { if self.rpc_conf.local_mode() { info!( conf = debug(&self.rpc_conf), "use embedded meta, data will be removed when process exits" ); // NOTE: This can only be used for test: data will be removed when program quit. let meta_store = MetaEmbedded::get_meta().await?; Ok(MetaStore::L(meta_store)) } else { info!(conf = debug(&self.rpc_conf), "use remote meta"); let client = MetaGrpcClient::try_new(&self.rpc_conf)?; Ok(MetaStore::R(client)) } } } pub struct WatchResponseStream<E, S> where E: Into<MetaError> + Send + 'static, S: Stream<Item = Result<WatchResponse, E>> + Send + Unpin + 'static, { inner: S, } impl<E, S> WatchResponseStream<E, S> where E: Into<MetaError> + Send + 'static, S: Stream<Item = Result<WatchResponse, E>> + Send + Unpin + 'static, { pub fn create(inner: S) -> WatchResponseStream<E, S> { WatchResponseStream { inner } } } impl<E, S> Stream for WatchResponseStream<E, S> where E: Into<MetaError> + Send + 'static, S: Stream<Item = Result<WatchResponse, E>> + Send + Unpin + 'static, { type Item = Result<WatchResponse, MetaError>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { Pin::new(&mut self.inner).poll_next(cx).map(|x| match x { None => None, Some(Ok(resp)) => Some(Ok(resp)), Some(Err(e)) => Some(Err(e.into())), }) } }
// 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::net::SocketAddr; use common_base::base::tokio; use common_exception::Result; use common_meta_app::principal::UserInfo; use common_settings::Settings; use databend_query::sessions::SessionContext; #[tokio::test(flavor = "multi_thread")] async fn test_session_context() -> Result<()> { let settings = Settings::default_test_settings()?; let session_ctx = SessionContext::try_create(settings)?; // Abort status. { session_ctx.set_abort(true); let val = session_ctx.get_abort(); assert!(val); } // Current database status. { session_ctx.set_current_database("bend".to_string()); let val = session_ctx.get_current_database(); assert_eq!("bend", val); } // Client host. { let demo = "127.0.0.1:80"; let server: SocketAddr = demo.parse().unwrap(); session_ctx.set_client_host(Some(server)); let val = session_ctx.get_client_host(); assert_eq!(Some(server), val); } // Current user. { let user_info = UserInfo::new_no_auth("user1", ""); session_ctx.set_current_user(user_info); let val = session_ctx.get_current_user().unwrap(); assert_eq!("user1".to_string(), val.name); } // io shutdown tx. { session_ctx.set_io_shutdown_tx(|| {}); let val = session_ctx.take_io_shutdown_tx(); assert!(val.is_some()); let val = session_ctx.take_io_shutdown_tx(); assert!(val.is_none()); } Ok(()) }
use askama::Template; use serde::Deserialize; use crate::database as db; use deadpool_postgres::Pool; use crate::{utils::cache_long, socket}; #[derive(Template)] #[template(path = "login.html")] struct LoginTemplate { redirect_url: String, google_auth_url: String, } #[derive(Deserialize)] pub struct LoginQuery { redirect: String, } pub async fn login(query: LoginQuery) -> Result<impl warp::Reply, warp::Rejection> { let mut google_auth_url = format!( "https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https://localhost/api/auth&response_type=code&scope=profile&client_id={}&state=", include_str!("../../api/client_id.txt") ); google_auth_url.extend(form_urlencoded::byte_serialize(query.redirect.as_bytes())); Ok(cache_long(LoginTemplate { redirect_url: query.redirect, google_auth_url, })) } pub async fn logout(pool: Pool, socket_ctx: socket::Context, session_id: db::SessionID) -> Result<impl warp::Reply, warp::Rejection> { if let Some(user_id) = db::session_user_id(pool.clone(), &session_id).await? { db::delete_user_sessions(pool, user_id).await?; socket_ctx.kick_user(user_id).await; } Ok(login(LoginQuery { redirect: "/".to_owned() }).await?) }
mod shared; #[cfg(feature = "local-testing")] #[tokio::test] async fn test_activity() { use shared::ds::{self, activity}; shared::init_logger(); let dual = shared::make_dual_clients(ds::Subscriptions::ACTIVITY) .await .expect("failed to start clients"); let shared::DualClients { one, two } = dual; let mut events = one.events; tokio::task::spawn(async move { while let Some(event) = events.recv().await { tracing::debug!(which = 1, event = ?event); } }); let (invite_tx, invite_rx) = tokio::sync::oneshot::channel(); let (join_tx, join_rx) = tokio::sync::oneshot::channel(); let mut events = two.events; tokio::task::spawn(async move { let mut invite_tx = Some(invite_tx); let mut join_tx = Some(join_tx); while let Some(event) = events.recv().await { tracing::debug!(which = 2, event = ?event); match event { shared::Msg::Event(ds::Event::ActivityInvite(invite)) => { if let Some(tx) = invite_tx.take() { tx.send(invite).unwrap(); } } shared::Msg::Event(ds::Event::ActivityJoin(secret)) => { if let Some(tx) = join_tx.take() { tx.send(secret).unwrap(); } } _ => {} } } }); let _one_user = one.user; let two_user = two.user; let one = one.discord; let two = two.discord; let party_id = "partyfun123"; tracing::info!( "1 => updating activity: {:#?}", one.update_activity( activity::ActivityBuilder::new() .state("test 1") .details("much presence very details") .party( party_id, std::num::NonZeroU32::new(1), std::num::NonZeroU32::new(2), activity::PartyPrivacy::Public, ) .secrets(activity::Secrets { join: Some("muchsecretverysecurity".to_owned()), ..Default::default() }), ) .await .expect("failed to update presence") ); // wait a few seconds on windows, just to see if it's because of slow I/O? #[cfg(windows)] { tokio::time::sleep(std::time::Duration::from_secs(2)).await; } tracing::info!("1 => inviting {}", two_user); one.invite_user( two_user.id, "please join or the test will fail", activity::ActivityActionKind::Join, ) .await .expect("failed to send invite"); tracing::info!("2 => waiting for invite"); let invite = tokio::time::timeout(std::time::Duration::from_secs(5), invite_rx) .await .expect("timed out waiting for invite") .expect("event task dropped"); two.accept_invite(&invite).await.unwrap(); tracing::info!("2 => waiting for join"); let secret = tokio::time::timeout(std::time::Duration::from_secs(5), join_rx) .await .expect("timed out waiting for join") .expect("event task dropped"); assert_eq!(secret.secret, "muchsecretverysecurity",); one.disconnect().await; two.disconnect().await; }
#[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let influx_url = "some-url"; let token = "some-token"; let client = influxdb2_client::Client::new(influx_url, token); println!("{:?}", client.ready().await?); Ok(()) }
mod lib; fn main() { match lib::INIContext::new( "./test.ini", true ) { Ok( tree ) => { println!( "{:?} ou {:?}", tree.search( "generaly".to_string(), "name".to_string() ), tree.search( "generaly".to_string(), "rien".to_string() ) ); }, Err( err ) => println!( "err : {:?}", err ) } }
// 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::iter::repeat; use std::iter::TrustedLen; use std::sync::atomic::Ordering; use common_arrow::arrow::bitmap::MutableBitmap; use common_exception::ErrorCode; use common_exception::Result; use common_expression::DataBlock; use common_hashtable::HashtableEntryRefLike; use common_hashtable::HashtableLike; use crate::pipelines::processors::transforms::hash_join::desc::JOIN_MAX_BLOCK_SIZE; use crate::pipelines::processors::transforms::hash_join::row::RowPtr; use crate::pipelines::processors::transforms::hash_join::ProbeState; use crate::pipelines::processors::JoinHashTable; /// Semi join contain semi join and semi-anti join impl JoinHashTable { pub(crate) fn probe_left_semi_join<'a, H: HashtableLike<Value = Vec<RowPtr>>, IT>( &self, hash_table: &H, probe_state: &mut ProbeState, keys_iter: IT, input: &DataBlock, ) -> Result<Vec<DataBlock>> where IT: Iterator<Item = &'a H::Key> + TrustedLen, H::Key: 'a, { match self.hash_join_desc.other_predicate.is_none() { true => { self.left_semi_anti_join::<true, _, _>(hash_table, probe_state, keys_iter, input) } false => self.left_semi_anti_join_with_other_conjunct::<true, _, _>( hash_table, probe_state, keys_iter, input, ), } } pub(crate) fn probe_left_anti_semi_join<'a, H: HashtableLike<Value = Vec<RowPtr>>, IT>( &self, hash_table: &H, probe_state: &mut ProbeState, keys_iter: IT, input: &DataBlock, ) -> Result<Vec<DataBlock>> where IT: Iterator<Item = &'a H::Key> + TrustedLen, H::Key: 'a, { match self.hash_join_desc.other_predicate.is_none() { true => { self.left_semi_anti_join::<false, _, _>(hash_table, probe_state, keys_iter, input) } false => self.left_semi_anti_join_with_other_conjunct::<false, _, _>( hash_table, probe_state, keys_iter, input, ), } } fn left_semi_anti_join<'a, const SEMI: bool, H: HashtableLike<Value = Vec<RowPtr>>, IT>( &self, hash_table: &H, probe_state: &mut ProbeState, keys_iter: IT, input: &DataBlock, ) -> Result<Vec<DataBlock>> where IT: Iterator<Item = &'a H::Key> + TrustedLen, H::Key: 'a, { // If there is no build key, the result is input // Eg: select * from onecolumn as a right semi join twocolumn as b on true order by b.x let mut probe_indexes = Vec::with_capacity(input.num_rows()); let valids = &probe_state.valids; for (i, key) in keys_iter.enumerate() { let probe_result_ptr = if self.hash_join_desc.from_correlated_subquery { hash_table.entry(key) } else { self.probe_key(hash_table, key, valids, i) }; match (probe_result_ptr, SEMI) { (Some(_), true) | (None, false) => { probe_indexes.push(i as u32); } _ => {} } } Ok(vec![DataBlock::take(input, &probe_indexes)?]) } fn left_semi_anti_join_with_other_conjunct< 'a, const SEMI: bool, H: HashtableLike<Value = Vec<RowPtr>>, IT, >( &self, hash_table: &H, probe_state: &mut ProbeState, keys_iter: IT, input: &DataBlock, ) -> Result<Vec<DataBlock>> where IT: Iterator<Item = &'a H::Key> + TrustedLen, H::Key: 'a, { let valids = &probe_state.valids; // The semi join will return multiple data chunks of similar size let mut probed_blocks = vec![]; let mut probe_indexes = Vec::with_capacity(JOIN_MAX_BLOCK_SIZE); let mut build_indexes = Vec::with_capacity(JOIN_MAX_BLOCK_SIZE); let other_predicate = self.hash_join_desc.other_predicate.as_ref().unwrap(); // For semi join, it defaults to all let mut row_state = vec![0_u32; input.num_rows()]; let dummy_probed_rows = vec![RowPtr { chunk_index: 0, row_index: 0, marker: None, }]; for (i, key) in keys_iter.enumerate() { let probe_result_ptr = match self.hash_join_desc.from_correlated_subquery { true => hash_table.entry(key), false => self.probe_key(hash_table, key, valids, i), }; let probed_rows = match probe_result_ptr { None if SEMI => { continue; } None => &dummy_probed_rows, Some(v) => v.get(), }; if probe_result_ptr.is_some() && !SEMI { row_state[i] += probed_rows.len() as u32; } if probe_indexes.len() + probed_rows.len() < probe_indexes.capacity() { build_indexes.extend_from_slice(probed_rows); probe_indexes.extend(repeat(i as u32).take(probed_rows.len())); } else { let mut index = 0_usize; let mut remain = probed_rows.len(); while index < probed_rows.len() { if probe_indexes.len() + remain < probe_indexes.capacity() { build_indexes.extend_from_slice(&probed_rows[index..]); probe_indexes.extend(repeat(i as u32).take(remain)); index += remain; } else { if self.interrupt.load(Ordering::Relaxed) { return Err(ErrorCode::AbortedQuery( "Aborted query, because the server is shutting down or the query was killed.", )); } let addition = probe_indexes.capacity() - probe_indexes.len(); let new_index = index + addition; build_indexes.extend_from_slice(&probed_rows[index..new_index]); probe_indexes.extend(repeat(i as u32).take(addition)); let probe_block = DataBlock::take(input, &probe_indexes)?; let build_block = self.row_space.gather(&build_indexes)?; let merged_block = self.merge_eq_block(&build_block, &probe_block)?; let mut bm = match self.get_other_filters(&merged_block, other_predicate)? { (Some(b), _, _) => b.into_mut().right().unwrap(), (_, true, _) => MutableBitmap::from_len_set(merged_block.num_rows()), (_, _, true) => MutableBitmap::from_len_zeroed(merged_block.num_rows()), _ => unreachable!(), }; if SEMI { self.fill_null_for_semi_join(&mut bm, &probe_indexes, &mut row_state); } else { self.fill_null_for_anti_join(&mut bm, &probe_indexes, &mut row_state); } let probed_data_block = DataBlock::filter_with_bitmap(probe_block, &bm.into())?; if !probed_data_block.is_empty() { probed_blocks.push(probed_data_block); } index = new_index; remain -= addition; build_indexes.clear(); probe_indexes.clear(); } } } } if self.interrupt.load(Ordering::Relaxed) { return Err(ErrorCode::AbortedQuery( "Aborted query, because the server is shutting down or the query was killed.", )); } let probe_block = DataBlock::take(input, &probe_indexes)?; let build_block = self.row_space.gather(&build_indexes)?; let merged_block = self.merge_eq_block(&build_block, &probe_block)?; let mut bm = match self.get_other_filters(&merged_block, other_predicate)? { (Some(b), _, _) => b.into_mut().right().unwrap(), (_, true, _) => MutableBitmap::from_len_set(merged_block.num_rows()), (_, _, true) => MutableBitmap::from_len_zeroed(merged_block.num_rows()), _ => unreachable!(), }; if SEMI { self.fill_null_for_semi_join(&mut bm, &probe_indexes, &mut row_state); } else { self.fill_null_for_anti_join(&mut bm, &probe_indexes, &mut row_state); } let probed_data_chunk = DataBlock::filter_with_bitmap(probe_block, &bm.into())?; if !probed_data_chunk.is_empty() { probed_blocks.push(probed_data_chunk); } Ok(probed_blocks) } // modify the bm by the value row_state // keep the index of the first positive state // bitmap: [1, 1, 1] with row_state [0, 0], probe_index: [0, 0, 0] (repeat the first element 3 times) // bitmap will be [1, 1, 1] -> [1, 1, 1] -> [1, 0, 1] -> [1, 0, 0] // row_state will be [0, 0] -> [1, 0] -> [1,0] -> [1, 0] fn fill_null_for_semi_join( &self, bm: &mut MutableBitmap, probe_indexes: &[u32], row_state: &mut [u32], ) { for (index, row) in probe_indexes.iter().enumerate() { let row = *row as usize; if bm.get(index) { if row_state[row] == 0 { row_state[row] = 1; } else { bm.set(index, false); } } } } // keep the index of the negative state // bitmap: [1, 1, 1] with row_state [3, 0], probe_index: [0, 0, 0] (repeat the first element 3 times) // bitmap will be [1, 1, 1] -> [0, 1, 1] -> [0, 0, 1] -> [0, 0, 0] // row_state will be [3, 0] -> [3, 0] -> [3, 0] -> [3, 0] fn fill_null_for_anti_join( &self, bm: &mut MutableBitmap, probe_indexes: &[u32], row_state: &mut [u32], ) { for (index, row) in probe_indexes.iter().enumerate() { let row = *row as usize; if row_state[row] == 0 { // if state is not matched, anti result will take one bm.set(index, true); } else if row_state[row] == 1 { // if state has just one, anti reverse the result row_state[row] -= 1; bm.set(index, !bm.get(index)) } else if !bm.get(index) { row_state[row] -= 1; } else { bm.set(index, false); } } } }
use std::ops::{Deref, DerefMut}; use crate::ast; use crate::code::Code; use crate::context::{Build, CloneSafe, Context}; use crate::error::{Result, TensorNodeError}; use crate::execs::ExecIR; use crate::externs::ExternIR; use crate::graph::{RefGraph, Values}; use crate::nodes::{builtins, ASTBuild, NodeIR, NodeRoot}; use crate::seed::Seed; #[derive(Default, Debug, PartialEq)] pub struct TensorGraph(Vec<TensorNode>); impl Deref for TensorGraph { type Target = Vec<TensorNode>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for TensorGraph { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[derive(Debug, PartialEq)] pub enum TensorNode { Node(NodeIR), Extern(ExternIR), Exec(ExecIR), } #[derive(Clone, Debug)] pub struct IRData { pub id: u64, pub name: String, pub graph: RefGraph, pub input: ast::Outs, pub output: ast::Outs, } impl PartialEq for IRData { fn eq(&self, other: &Self) -> bool { // id should not be compared self.name.eq(&other.name) && self.graph.eq(&other.graph) && self.input.eq(&other.input) && self.output.eq(&other.output) } } impl From<NodeIR> for TensorNode { fn from(node: NodeIR) -> Self { Self::Node(node) } } impl From<ExternIR> for TensorNode { fn from(node: ExternIR) -> Self { Self::Extern(node) } } impl From<ExecIR> for TensorNode { fn from(node: ExecIR) -> Self { Self::Exec(node) } } impl From<Vec<TensorNode>> for TensorGraph { fn from(nodes: Vec<TensorNode>) -> Self { Self(nodes) } } impl TensorGraph { pub fn empty() -> Self { Self(vec![]) } pub fn new_one(node: TensorNode) -> Self { Self(vec![node]) } pub fn is_some(&self) -> bool { !self.is_empty() } pub fn get_input_shapes(&self) -> Option<&ast::Shapes> { let input_node = &self.0[0]; if input_node.is_input() { input_node.get_output_shapes() } else { input_node.get_input_shapes() } } pub fn get_output_shapes(&self) -> Option<&ast::Shapes> { for node in self.0.iter().rev() { if let Some(shapes) = node.get_output_shapes() { let shapes_ref = shapes.0.borrow(); // filter dynamic size if shapes_ref.len() == 1 { if let Some(None) = shapes_ref.get("x") { continue; } } return Some(shapes); } } self.0.last().map(|x| x.get_output_shapes()).flatten() } pub fn try_borrow_extern_node(&self) -> Option<&ExternIR> { if self.0.len() == 1 { self.0[0].try_borrow_extern() } else { None } } pub fn build(self, root: &NodeRoot) -> Result<Vec<Code>> { self.0.into_iter().map(|x| x.build_to_code(root)).collect() } } impl TensorNode { pub fn is_input(&self) -> bool { builtins::INPUTS.contains(&self.name()) } pub fn name(&self) -> &str { &self.get_data().name } fn ty(&self) -> ast::FinalNodeType { match self { Self::Node(_) | Self::Extern(_) => ast::FinalNodeType::Default, Self::Exec(_) => ast::FinalNodeType::Exec, } } pub fn get_id(&self) -> u64 { self.get_data().id } pub fn set_id(&mut self, id: u64) { self.get_data_mut().id = id; } pub fn set_repeat(&mut self, value: Option<ast::Value>) { match self { Self::Node(node) => node.repeat = value, _ => unreachable!("Only the default nodes can repeat."), } } fn get_data(&self) -> &IRData { match self { Self::Node(node) => &node.data, Self::Extern(node) => &node.data, Self::Exec(node) => &node.data, } } fn get_data_mut(&mut self) -> &mut IRData { match self { Self::Node(node) => &mut node.data, Self::Extern(node) => &mut node.data, Self::Exec(node) => &mut node.data, } } pub fn get_graph(&self) -> &RefGraph { &self.get_data().graph } pub fn get_inputs(&self) -> &ast::Outs { &self.get_data().input } pub fn get_inputs_mut(&mut self) -> &mut ast::Outs { &mut self.get_data_mut().input } pub fn get_outputs_mut(&mut self) -> &mut ast::Outs { &mut self.get_data_mut().output } pub fn get_input_shapes(&self) -> Option<&ast::Shapes> { match self { Self::Node(node) => node.get_input_shapes(), Self::Extern(node) => node.get_input_shapes(), Self::Exec(_) => exec_node_cannot_have_shapes(), } } pub fn get_output_shapes(&self) -> Option<&ast::Shapes> { match self { Self::Node(node) => node.get_output_shapes(), Self::Extern(node) => node.get_output_shapes(), Self::Exec(_) => exec_node_cannot_have_shapes(), } } pub fn build_to_code(self, root: &NodeRoot) -> Result<Code> { match self { Self::Node(node) => node.build(root), Self::Extern(node) => Ok(node.build()?.into()), Self::Exec(_) => unreachable!("The ExecIR should be built using ExecIR::build."), } } pub fn apply_variables(&mut self, variables: Values, shortcut: bool) -> Result<()> { self.get_graph().borrow().apply(variables, shortcut) } pub fn unwrap_node(self) -> Result<NodeIR> { match self { Self::Node(node) => Ok(node), _ => TensorNodeError::MismatchedType { expected: ast::FinalNodeType::Default, given: self.ty(), } .into(), } } pub fn unwrap_extern(self) -> Result<ExternIR> { match self { Self::Extern(node) => Ok(node), _ => TensorNodeError::MismatchedType { expected: ast::FinalNodeType::Default, given: self.ty(), } .into(), } } pub fn unwrap_exec(self) -> Result<ExecIR> { match self { Self::Exec(node) => Ok(node), _ => TensorNodeError::MismatchedType { expected: ast::FinalNodeType::Exec, given: self.ty(), } .into(), } } pub fn try_borrow_extern(&self) -> Option<&ExternIR> { match self { Self::Extern(node) => Some(node), _ => None, } } } fn exec_node_cannot_have_shapes() -> ! { unreachable!("The exec node cannot have the shapes"); } impl CloneSafe for TensorGraph { fn clone_safe(&self, seed: &Seed, variables: &mut Vec<ast::RefVariable>) -> Self { Self(self.0.clone_safe(seed, variables)) } } impl CloneSafe for TensorNode { fn clone_safe(&self, seed: &Seed, variables: &mut Vec<ast::RefVariable>) -> Self { match self { Self::Node(node) => node.clone_safe(seed, variables).into(), Self::Extern(node) => node.clone_safe(seed, variables).into(), Self::Exec(node) => node.clone_safe(seed, variables).into(), } } } impl CloneSafe for IRData { fn clone_safe(&self, seed: &Seed, variables: &mut Vec<ast::RefVariable>) -> Self { Self { id: self.id, name: self.name.clone(), graph: self.graph.clone_safe(seed, variables), input: self.input.clone(), output: self.output.clone(), } } } impl Build for TensorNode { type Output = Self; fn build(root: &NodeRoot, name: &str, source: String) -> Result<Self::Output> { let file = root.parser.parse_file(&source)?; // test name if file.node.name != name { TensorNodeError::MismatchedName { expected: name.to_string(), given: file.node.name, } .into() } else { let mut ctx = Context::new(root); file.build(&mut ctx, Default::default()) } } } impl IRData { pub fn with_tensor_graph(name: String, graph: RefGraph, tensor_graph: &TensorGraph) -> Self { Self::with_shapes( name, graph, tensor_graph.get_input_shapes(), tensor_graph.get_output_shapes(), ) } pub fn with_shapes( name: String, graph: RefGraph, input: Option<&ast::Shapes>, output: Option<&ast::Shapes>, ) -> Self { Self { id: 0, name, graph, input: shapes_to_outs(1, input), output: shapes_to_outs(1, output), } } pub fn with_no_shapes(name: String, graph: RefGraph) -> Self { Self { id: 0, name, graph, input: Default::default(), output: Default::default(), } } } fn shapes_to_outs(id: u64, shapes: Option<&ast::Shapes>) -> ast::Outs { match shapes { Some(shapes) => shapes.to_outs(id), None => [("x")] .iter() .map(|x| x.to_string()) .map(|x| (x.clone(), ast::Out::new(id, x))) .collect(), } }
fn main() { // define a variable // let x = 5; // this is wrong! // coz x is immutable // x = 10; // define a immutable variable let mut x = 5; x = 10; // define a tuple let (y,z) = (1,2); let mut z = 5; let w = ( z = 6 ); // w has the value `()`, not `6` // w cannot be printed, as it is a tuple // println!("w is: {}", w); // define a variable with type let a: i32 =5; print_number(5); print_sum(5, 6); add_one(6); array_sample(); slice_sample(); tuple_sample(); if_sample(); while_sample(); for_sample(); // sample of function pointer let fnpointer: fn(i32) -> i32 = add_one; let b: i32 = diverges(); let c: String = diverges(); } fn print_number(x: i32) { println!("x is: {}", x); } fn print_sum(x: i32, y: i32) { println!("sum is: {}", x + y); } fn add_one(x: i32) -> i32 { x + 1 } // following is also accepted, but we prefer above one fn foo(x: i32) -> i32 { return x + 1; } fn diverges() -> ! { panic!("This function never returns!"); } fn array_sample() { let a = [1,2,3]; println!("a has {} elements", a.len()); let mut m = [1,2,3]; let aa = [0; 20]; // aa: [i32;20] let names = ["Graydon", "Brian", "niko"]; println!("The second name is: {}", names[1]); } fn slice_sample() { let a = [0,1,2,3,4]; let middle = &a[1..4]; let complete = &a[..]; } fn tuple_sample() { let x = (1, "hello"); let y: (i32, &str) = (1, "hello"); let mut z = (1,2); let w = (2,3); z = w; let (a, b, c) = (1,2,3); println!("a is {}", a); let tuple = (1,2,3); let tx = tuple.0; let ty = tuple.1; let tz = tuple.2; println!("tx is {}", tx); } fn if_sample() { let x = 5; if x == 5 { println!("x is five!"); } else if x == 6 { println!("x is six!"); } else { println!("x is not five or six :("); } let y = if x == 5 { 10 } else { 15 }; let z = if x == 5 { 10 } else { 15 }; } fn while_sample() { let mut x = 5; let mut done = false; while !done { x += x - 3; println!("{}", x); if x % 5 == 0 { done = true; } } } fn for_sample() { for (i, j) in (5..10).enumerate() { println!("i = {} and j = {}", i, j); } for x in 0u32..10 { if x % 2 == 0 { continue; } println!("{}", x); } 'outer: for x in 0..10 { 'inner: for y in 0..10 { if x % 2 == 0 { continue 'outer; } if y % 2 == 0 { continue 'inner; } println!("x: {}, y:{}", x, y); } } }
//! Contains the `RSmallBox<_>` type. use crate::{ pointer_trait::{ AsMutPtr, AsPtr, CallReferentDrop, CanTransmuteElement, Deallocate, GetPointerKind, OwnedPointer, PK_SmartPointer, }, sabi_types::MovePtr, std_types::RBox, }; use std::{ alloc::{self, Layout}, fmt::{self, Display}, marker::PhantomData, mem::{self, ManuallyDrop}, ops::{Deref, DerefMut}, ptr, }; #[allow(unused_imports)] use core_extensions::SelfOps; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::inline_storage::ScratchSpace; pub use crate::inline_storage::{alignment, InlineStorage}; pub use self::private::RSmallBox; mod private { use super::*; /// /// A box type which stores small values inline as an optimization. /// /// # Inline storage /// /// The `Inline` type parameter /// is the storage space on the stack (as in inline with the `RSmallBox` struct) /// where small values get stored,instead of storing them on the heap. /// /// It has to have an alignment greater than or equal to the value being stored, /// otherwise storing the value on the heap. /// /// To ensure that the inline storage has enough alignemnt you can use one of the /// `AlignTo*` types from the (reexported) alignment submodule, /// or from `abi_stable::inline_storage::alignment`. /// /// # Examples /// /// ### In a nonexhaustive enum /// /// Using an RSmallBox to store a generic type in a nonexhaustive enum. /// /// ``` /// use abi_stable::{reexports::SelfOps, sabi_types::RSmallBox, std_types::RString, StableAbi}; /// /// #[repr(u8)] /// #[derive(StableAbi, Debug, Clone, PartialEq)] /// #[sabi(kind(WithNonExhaustive( /// // Determines the maximum size of this enum in semver compatible versions. /// // This is 7 usize large because: /// // - The enum discriminant occupies 1 usize(because the enum is usize aligned). /// // - RSmallBox<T,[usize;4]>: is 6 usize large /// size = [usize;7], /// // Determines the traits that are required when wrapping this enum in NonExhaustive, /// // and are then available with it. /// traits(Debug,Clone,PartialEq), /// )))] /// #[non_exhaustive] /// pub enum SomeEnum<T> { /// Foo, /// Bar, /// // This variant was added in a newer (compatible) version of the library. /// Baz(RSmallBox<T, [usize; 4]>), /// } /// /// impl<T> SomeEnum<T> { /// pub fn is_inline(&self) -> bool { /// match self { /// SomeEnum::Foo => true, /// SomeEnum::Bar => true, /// SomeEnum::Baz(rsbox) => RSmallBox::is_inline(rsbox), /// _ => true, /// } /// } /// /// pub fn is_heap_allocated(&self) -> bool { /// !self.is_inline() /// } /// } /// /// #[repr(C)] /// #[derive(StableAbi, Debug, Clone, PartialEq)] /// pub struct FullName { /// pub name: RString, /// pub surname: RString, /// } /// /// # fn main(){ /// /// let rstring = "Oh boy!" /// .piped(RString::from) /// .piped(RSmallBox::new) /// .piped(SomeEnum::Baz); /// /// let full_name = FullName { /// name: "R__e".into(), /// surname: "L_____e".into(), /// } /// .piped(RSmallBox::new) /// .piped(SomeEnum::Baz); /// /// assert!(rstring.is_inline()); /// assert!(full_name.is_heap_allocated()); /// /// # } /// /// ``` /// /// ### Trying out different `Inline` type parameters /// /// This example demonstrates how changing the `Inline` type parameter can /// change whether an RString is stored inline or on the heap. /// /// ``` /// use abi_stable::{ /// inline_storage::alignment::AlignToUsize, sabi_types::RSmallBox, std_types::RString, /// StableAbi, /// }; /// /// use std::mem; /// /// type JustRightInlineBox<T> = RSmallBox<T, AlignToUsize<[u8; mem::size_of::<usize>() * 4]>>; /// /// let string = RString::from("What is that supposed to mean?"); /// /// let small = RSmallBox::<_, [usize; 3]>::new(string.clone()); /// let medium = RSmallBox::<_, [usize; 4]>::new(string.clone()); /// let large = RSmallBox::<_, [usize; 16]>::new(string.clone()); /// let not_enough_alignment = RSmallBox::<_, [u8; 64]>::new(string.clone()); /// let just_right = JustRightInlineBox::new(string.clone()); /// /// assert!(RSmallBox::is_heap_allocated(&small)); /// assert!(RSmallBox::is_inline(&medium)); /// assert!(RSmallBox::is_inline(&large)); /// assert!(RSmallBox::is_heap_allocated(&not_enough_alignment)); /// assert!(RSmallBox::is_inline(&just_right)); /// /// ``` #[repr(C)] #[derive(StableAbi)] #[sabi(not_stableabi(Inline))] pub struct RSmallBox<T, Inline> { // This is an opaque field since we only care about its size and alignment #[sabi(unsafe_opaque_field)] inline: ScratchSpace<(), Inline>, ptr: *mut T, destroy: unsafe extern "C" fn(*mut T, CallReferentDrop, Deallocate), _marker: PhantomData<T>, } impl<T, Inline> RSmallBox<T, Inline> { /// Constructs this RSmallBox from a value. /// /// # Example /// /// ``` /// use abi_stable::{sabi_types::RSmallBox, std_types::RString}; /// /// let xbox = RSmallBox::<_, [usize; 4]>::new(RString::from("one")); /// /// ``` #[inline] pub fn new(value: T) -> RSmallBox<T, Inline> where Inline: InlineStorage, { let mut value = ManuallyDrop::new(value); unsafe { RSmallBox::from_move_ptr(MovePtr::new(&mut *value)) } } /// Gets a raw pointer into the underlying data. /// /// # Example /// /// ``` /// use abi_stable::{sabi_types::RSmallBox, std_types::RString}; /// /// let mut play = RSmallBox::<_, [usize; 4]>::new(RString::from("station")); /// /// let play_addr = &mut play as *mut RSmallBox<_, _> as usize; /// let heap_addr = RSmallBox::as_mut_ptr(&mut play) as usize; /// /// assert_eq!(play_addr, heap_addr); /// /// ``` #[inline] pub fn as_mut_ptr(this: &mut Self) -> *mut T { if this.ptr.is_null() { &mut this.inline as *mut ScratchSpace<(), Inline> as *mut T } else { this.ptr } } /// Gets a raw pointer into the underlying data. /// /// # Example /// /// ``` /// use abi_stable::{reexports::SelfOps, sabi_types::RSmallBox, std_types::RVec}; /// /// let mut generations = vec![1, 2, 3, 4, 5, 6, 7, 8] /// .piped(RVec::from) /// .piped(RSmallBox::<_, [usize; 2]>::new); /// /// let generations_addr = &generations as *const RSmallBox<_, _> as usize; /// let heap_addr = RSmallBox::as_ptr(&generations) as usize; /// /// assert_ne!(generations_addr, heap_addr); /// /// ``` #[inline] pub fn as_ptr(this: &Self) -> *const T { if this.ptr.is_null() { &this.inline as *const ScratchSpace<(), Inline> as *const T } else { this.ptr } } /// Constructs this `RSmallBox` from a `MovePtr`. /// /// # Example /// /// ``` /// use abi_stable::{pointer_trait::OwnedPointer, sabi_types::RSmallBox, std_types::RBox}; /// /// let rbox = RBox::new(1000_u64); /// let rsbox: RSmallBox<u64, [u64; 1]> = /// rbox.in_move_ptr(|x| RSmallBox::<u64, [u64; 1]>::from_move_ptr(x)); /// /// assert_eq!(*rsbox, 1000_u64); /// /// ``` pub fn from_move_ptr(from_ptr: MovePtr<'_, T>) -> Self where Inline: InlineStorage, { let destroy = destroy::<T>; let inline_size = mem::size_of::<Inline>(); let value_size = mem::size_of::<T>(); let inline_align = mem::align_of::<Inline>(); let value_align = mem::align_of::<T>(); unsafe { let mut inline: ScratchSpace<(), Inline> = ScratchSpace::uninit(); let (storage_ptr, ptr) = if inline_size < value_size || inline_align < value_align { let x = alloc::alloc(Layout::new::<T>()); (x, x as *mut T) } else { ( (&mut inline as *mut ScratchSpace<(), Inline> as *mut u8), ptr::null_mut(), ) }; (MovePtr::into_raw(from_ptr) as *const T as *const u8) .copy_to_nonoverlapping(storage_ptr, value_size); Self { inline, ptr, destroy, _marker: PhantomData, } } } /// Converts this `RSmallBox` into another one with a differnet inline size. /// /// # Example /// /// ``` /// use abi_stable::sabi_types::RSmallBox; /// /// let old = RSmallBox::<u64, [u8; 4]>::new(599_u64); /// assert!(!RSmallBox::is_inline(&old)); /// /// let new = RSmallBox::move_::<[u64; 1]>(old); /// assert!(RSmallBox::is_inline(&new)); /// assert_eq!(*new, 599_u64); /// /// ``` #[inline] pub fn move_<Inline2>(this: Self) -> RSmallBox<T, Inline2> where Inline2: InlineStorage, { Self::with_move_ptr(ManuallyDrop::new(this), RSmallBox::from_move_ptr) } /// Queries whether the value is stored inline. /// /// # Example /// /// ``` /// use abi_stable::{sabi_types::RSmallBox, std_types::RString}; /// /// let heap = RSmallBox::<u64, [u8; 4]>::new(599_u64); /// assert!(!RSmallBox::is_inline(&heap)); /// /// let inline = RSmallBox::<RString, [usize; 4]>::new("hello".into()); /// assert!(RSmallBox::is_inline(&inline)); /// /// ``` pub fn is_inline(this: &Self) -> bool { this.ptr.is_null() } /// Queries whether the value is stored on the heap. /// /// # Example /// /// ``` /// use abi_stable::{sabi_types::RSmallBox, std_types::RHashMap}; /// /// let heap = RSmallBox::<_, [u8; 4]>::new(String::new()); /// assert!(RSmallBox::is_heap_allocated(&heap)); /// /// let inline = RSmallBox::<_, [usize; 3]>::new(RHashMap::<u8, ()>::new()); /// assert!(!RSmallBox::is_heap_allocated(&inline)); /// /// ``` pub fn is_heap_allocated(this: &Self) -> bool { !this.ptr.is_null() } /// Unwraps this pointer into its owned value. /// /// # Example /// /// ``` /// use abi_stable::sabi_types::RSmallBox; /// /// let rbox = RSmallBox::<_, [usize; 3]>::new(vec![0, 1, 2]); /// assert_eq!(RSmallBox::into_inner(rbox), vec![0, 1, 2]); /// /// ``` #[allow(clippy::redundant_closure)] pub fn into_inner(this: Self) -> T { Self::with_move_ptr(ManuallyDrop::new(this), |x| MovePtr::into_inner(x)) } pub(super) unsafe fn drop_in_place(this: &mut Self, drop_referent: CallReferentDrop) { let (ptr, dealloc) = if this.ptr.is_null() { ( &mut this.inline as *mut ScratchSpace<(), Inline> as *mut T, Deallocate::No, ) } else { (this.ptr, Deallocate::Yes) }; unsafe { (this.destroy)(ptr, drop_referent, dealloc) }; } } /// Converts an RBox into an RSmallBox,currently this allocates. impl<T, Inline> From<RBox<T>> for RSmallBox<T, Inline> where Inline: InlineStorage, { fn from(this: RBox<T>) -> Self { RBox::with_move_ptr(ManuallyDrop::new(this), Self::from_move_ptr) } } /// Converts a RSmallBox into an RBox,currently this allocates. impl<T, Inline> From<RSmallBox<T, Inline>> for RBox<T> where Inline: InlineStorage, { fn from(this: RSmallBox<T, Inline>) -> RBox<T> { OwnedPointer::with_move_ptr(ManuallyDrop::new(this), |x| MovePtr::into_rbox(x)) } } } /////////////////////////////////////////////////////////////////////////////// unsafe impl<T, Inline> GetPointerKind for RSmallBox<T, Inline> { type Kind = PK_SmartPointer; type PtrTarget = T; } impl<T, Inline> Deref for RSmallBox<T, Inline> { type Target = T; fn deref(&self) -> &T { unsafe { &*Self::as_ptr(self) } } } impl<T, Inline> DerefMut for RSmallBox<T, Inline> { fn deref_mut(&mut self) -> &mut T { unsafe { &mut *Self::as_mut_ptr(self) } } } unsafe impl<T, Inline> AsPtr for RSmallBox<T, Inline> { fn as_ptr(&self) -> *const T { Self::as_ptr(self) } } unsafe impl<T, Inline> AsMutPtr for RSmallBox<T, Inline> { fn as_mut_ptr(&mut self) -> *mut T { Self::as_mut_ptr(self) } } impl<T, Inline> Default for RSmallBox<T, Inline> where T: Default, Inline: InlineStorage, { fn default() -> Self { Self::new(T::default()) } } impl<T, Inline> Clone for RSmallBox<T, Inline> where T: Clone, Inline: InlineStorage, { fn clone(&self) -> Self { RSmallBox::new((**self).clone()) } } impl<T, Inline> Display for RSmallBox<T, Inline> where T: Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Display::fmt(&**self, f) } } shared_impls! { mod=box_impls new_type=RSmallBox[][T,Inline], original_type=Box, } unsafe impl<T, O, Inline> CanTransmuteElement<O> for RSmallBox<T, Inline> { type TransmutedPtr = RSmallBox<O, Inline>; unsafe fn transmute_element_(self) -> Self::TransmutedPtr { unsafe { core_extensions::utils::transmute_ignore_size(self) } } } unsafe impl<T: Send, Inline> Send for RSmallBox<T, Inline> {} unsafe impl<T: Sync, Inline> Sync for RSmallBox<T, Inline> {} /////////////////////////////////////////////////////////////////////////////// impl<T, Inline> Serialize for RSmallBox<T, Inline> where T: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { (**self).serialize(serializer) } } impl<'de, T, Inline> Deserialize<'de> for RSmallBox<T, Inline> where Inline: InlineStorage, T: Deserialize<'de>, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { T::deserialize(deserializer).map(Self::new) } } ////////////////////////////////////////////////////////////////////////////// unsafe impl<T, Inline> OwnedPointer for RSmallBox<T, Inline> { #[inline] unsafe fn get_move_ptr(this: &mut ManuallyDrop<Self>) -> MovePtr<'_, T> { unsafe { MovePtr::new(&mut **this) } } #[inline] unsafe fn drop_allocation(this: &mut ManuallyDrop<Self>) { unsafe { Self::drop_in_place(&mut **this, CallReferentDrop::No); } } } impl<T, Inline> Drop for RSmallBox<T, Inline> { fn drop(&mut self) { unsafe { Self::drop_in_place(self, CallReferentDrop::Yes); } } } unsafe extern "C" fn destroy<T>(ptr: *mut T, drop_referent: CallReferentDrop, dealloc: Deallocate) { extern_fn_panic_handling! {no_early_return; if let CallReferentDrop::Yes=drop_referent{ unsafe { ptr::drop_in_place(ptr); } } if let Deallocate::Yes = dealloc{ unsafe { drop(Box::from_raw(ptr as *mut ManuallyDrop<T>)); } } } } ////////////////////////////////////////////////////////////////////////////// #[cfg(all(test, not(feature = "only_new_tests")))] mod tests;
mod error; mod audio; mod events; //mod events_term; mod token; use std::path::PathBuf; use events::Event; use hex_database::{Instance, Token, GossipConf}; fn main() { env_logger::init(); let (conf, path) = match hex_conf::Conf::new() { Ok(x) => x, Err(err) => { eprintln!("Error: Could not load configuration {:?}", err); (hex_conf::Conf::default(), PathBuf::from("/opt/music/")) } }; let data_path = path.join("data"); let db_path = path.join("music.db"); let mut gossip = GossipConf::new(); if let Some(ref peer) = conf.peer { gossip = gossip.addr((conf.host, peer.port)); gossip = gossip.id(peer.id()); gossip = gossip.network_key(peer.network_key()); } let instance = Instance::from_file(&db_path, gossip); let (read, write) = (instance.reader(), instance.writer()); //let (sender, receiver): (Sender<TrackKey>, Receiver<TrackKey>) = channel(); let (events, push_new) = events::events(); let mut audio = audio::AudioDevice::new(); let mut token: Option<token::Current> = None; let mut create_counter = 0; loop { if let Ok(events) = events.try_recv() { println!("Got events {:?}", events); for event in events { match event { Event::ButtonPressed(x) => { if let Some(ref mut token) = token { match x { 3 => {audio.clear(); token.next_track()}, 1 => {audio.clear(); token.prev_track()}, 0 => {create_counter += 1; token.shuffle()}, 2 => { if let Some(ref stream) = token.stream { if let Err(err) = write.vote_for_track(stream.track.key) { eprintln!("Error: Could not vote for track {:?}: {:?}", token.track_key(), err); } } }, x => eprintln!("Error: Input {} not supported yet", x) } } else { create_counter = 0; } }, Event::NewCard(num) => { println!("Got card with number {}", num); match read.get_token(num as i64) { Ok((a, Some((_, b)))) => { token = Some(token::Current::new(a, b, instance.files(), data_path.clone())); }, Ok((a, None)) => { token = Some(token::Current::new(a, Vec::new(), instance.files(), data_path.clone())); }, Err(hex_database::Error::NotFound) => { println!("Not found!"); let id = read.last_token_id().unwrap() + 1; let token = Token { token: id, key: None, played: Vec::new(), pos: None, last_use: 0 }; write.add_token(token).expect("Error: Could not create a new token!"); push_new.send(id as u32).unwrap(); }, Err(err) => eprintln!("Error: Could not get token with error: {:?}", err) } if let Some(ref token) = token { if let Err(err) = write.use_token(token.token.token) { eprintln!("Error: Could not user token {:?} because {:?}", token.token.token, err); } } }, Event::CardLost => { if let Some(ref mut token) = token { let current_track = token.track(); let Token { token, mut played, pos, .. } = token.data(); // push current track as last element of played tracks if let Some(current_track) = current_track { if !played.contains(&current_track.key) { played.push(current_track.key); } } if let Err(err) = write.update_token(token, None, Some(played), pos) { eprintln!("Error: Could not update token {:?} because {:?}", token, err); } } token = None; audio.clear(); } } } } if create_counter == 3 { println!("Reset token to new id .."); let id = read.last_token_id().unwrap() + 1; let token = Token { token: id, key: None, played: Vec::new(), pos: None, last_use: 0 }; write.add_token(token).expect("Error: Could not create a new token!"); push_new.send(id as u32).unwrap(); create_counter = 0; } if let Some(ref mut token) = token { if token.has_tracks() { if let Some(packet) = token.next_packet() { audio.buffer(&packet); } } else { } } } }
use crate::types::*; use neo4rs_macros::BoltStruct; #[derive(Debug, PartialEq, Clone, BoltStruct)] #[signature(0xB3, 0x58)] pub struct BoltPoint2D { pub sr_id: BoltInteger, pub x: BoltFloat, pub y: BoltFloat, } #[derive(Debug, PartialEq, Clone, BoltStruct)] #[signature(0xB4, 0x59)] pub struct BoltPoint3D { pub sr_id: BoltInteger, pub x: BoltFloat, pub y: BoltFloat, pub z: BoltFloat, } #[cfg(test)] mod tests { use super::*; use crate::version::Version; use bytes::*; use std::cell::RefCell; use std::rc::Rc; #[test] fn should_serialize_2d_point() { let sr_id = BoltInteger::new(42); let x = BoltFloat::new(1.0); let y = BoltFloat::new(2.0); let point = BoltPoint2D { sr_id, x, y }; let bytes: Bytes = point.into_bytes(Version::V4_1).unwrap(); assert_eq!( &bytes[..], Bytes::from_static(&[ 0xB3, 0x58, 0x2A, 0xC1, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC1, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]) ); } #[test] fn should_deserialize_2d_point() { let input = Rc::new(RefCell::new(Bytes::from_static(&[ 0xB3, 0x58, 0x2A, 0xC1, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC1, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]))); let point: BoltPoint2D = BoltPoint2D::parse(Version::V4_1, input).unwrap(); assert_eq!(point.sr_id, BoltInteger::new(42)); assert_eq!(point.x, BoltFloat::new(1.0)); assert_eq!(point.y, BoltFloat::new(2.0)); } #[test] fn should_serialize_3d_point() { let sr_id = BoltInteger::new(42); let x = BoltFloat::new(1.0); let y = BoltFloat::new(2.0); let z = BoltFloat::new(3.0); let point = BoltPoint3D { sr_id, x, y, z }; let bytes: Bytes = point.into_bytes(Version::V4_1).unwrap(); assert_eq!( &bytes[..], Bytes::from_static(&[ 0xB4, 0x59, 0x2A, 0xC1, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC1, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC1, 0x40, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]) ); } #[test] fn should_deserialize_3d_point() { let input = Rc::new(RefCell::new(Bytes::from_static(&[ 0xB4, 0x59, 0x2A, 0xC1, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC1, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC1, 0x40, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]))); let point: BoltPoint3D = BoltPoint3D::parse(Version::V4_1, input).unwrap(); assert_eq!(point.sr_id, BoltInteger::new(42)); assert_eq!(point.x, BoltFloat::new(1.0)); assert_eq!(point.y, BoltFloat::new(2.0)); assert_eq!(point.z, BoltFloat::new(3.0)); } }
const START: u32 = 347_312; const END: u32 = 805_915 + 1; // +1 so we can use exclusive ranges which are much more performant pub fn part1() -> usize { (START..END) .map(digits) .filter(|digits| is_in_order(digits) && has_multiple(digits)) .count() } pub fn part2() -> usize { (START..END) .map(digits) .filter(|digits| is_in_order(digits) && has_double(digits)) .count() } /// splits a number into its digits fn digits(mut n: u32) -> [usize; 6] { let mut digits = [0; 6]; for i in (0..6).rev() { digits[i] = (n % 10) as usize; n /= 10; } digits } /// makes sure the digits are in ascending order fn is_in_order(digits: &[usize; 6]) -> bool { for i in 1..6 { if digits[i] < digits[i - 1] { return false; } } true } /// makes sure there's at least one repeated digit in the number fn has_multiple(digits: &[usize; 6]) -> bool { for i in 1..6 { if digits[i] == digits[i - 1] { return true; } } false } /// makes sure there's a group of exactly 2 matching digits in the number fn has_double(digits: &[usize; 6]) -> bool { let mut consecutive = 1; for i in 1..6 { if digits[i] == digits[i - 1] { consecutive += 1; } else if consecutive == 2 { return true; } else { consecutive = 1; } } consecutive == 2 } #[cfg(test)] mod tests { use super::*; #[test] fn day04_part1() { assert_eq!(part1(), 594); } #[test] fn day04_part2() { assert_eq!(part2(), 364); } }
#[cfg(test)] mod tests { fn bad(a: DoesNotExist) { // ^^^^^^^^^^^^ERR(<1.16.0) undefined or not in scope // ^^^^^^^^^^^^ERR(<1.16.0) type name // ^^^^^^^^^^^^HELP(<1.16.0) no candidates // ^^^^^^^^^^^^ERR(>=1.16.0,test) not found in this scope // ^^^^^^^^^^^^ERR(>=1.16.0,test) cannot find type `DoesNotExist` } #[test] fn it_works() { asdf // ^^^^ERR(<1.16.0) unresolved name // ^^^^ERR(<1.16.0) unresolved name // ^^^^ERR(>=1.16.0,test) not found in this scope // ^^^^ERR(>=1.16.0,test) cannot find value } }
//! Named pipes use std::ffi::OsStr; use std::fs::{OpenOptions, File}; use std::io::prelude::*; use std::io; use std::os::windows::ffi::*; use std::os::windows::io::*; use std::time::Duration; use winapi::*; use kernel32::*; use handle::Handle; /// Readable half of an anonymous pipe. #[derive(Debug)] pub struct AnonRead(Handle); /// Writable half of an anonymous pipe. #[derive(Debug)] pub struct AnonWrite(Handle); /// A named pipe that can accept connections. #[derive(Debug)] pub struct NamedPipe(Handle); /// A builder structure for creating a new named pipe. #[derive(Debug)] pub struct NamedPipeBuilder { name: Vec<u16>, dwOpenMode: DWORD, dwPipeMode: DWORD, nMaxInstances: DWORD, nOutBufferSize: DWORD, nInBufferSize: DWORD, nDefaultTimeOut: DWORD, } /// Creates a new anonymous in-memory pipe, returning the read/write ends of the /// pipe. /// /// The buffer size for this pipe may also be specified, but the system will /// normally use this as a suggestion and it's not guaranteed that the buffer /// will be precisely this size. pub fn anonymous(buffer_size: u32) -> io::Result<(AnonRead, AnonWrite)> { let mut read = 0 as HANDLE; let mut write = 0 as HANDLE; try!(::cvt(unsafe { CreatePipe(&mut read, &mut write, 0 as *mut _, buffer_size) })); Ok((AnonRead(Handle::new(read)), AnonWrite(Handle::new(write)))) } impl Read for AnonRead { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } } impl<'a> Read for &'a AnonRead { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } } impl AsRawHandle for AnonRead { fn as_raw_handle(&self) -> HANDLE { self.0.raw() } } impl FromRawHandle for AnonRead { unsafe fn from_raw_handle(handle: HANDLE) -> AnonRead { AnonRead(Handle::new(handle)) } } impl IntoRawHandle for AnonRead { fn into_raw_handle(self) -> HANDLE { self.0.into_raw() } } impl Write for AnonWrite { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl<'a> Write for &'a AnonWrite { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl AsRawHandle for AnonWrite { fn as_raw_handle(&self) -> HANDLE { self.0.raw() } } impl FromRawHandle for AnonWrite { unsafe fn from_raw_handle(handle: HANDLE) -> AnonWrite { AnonWrite(Handle::new(handle)) } } impl IntoRawHandle for AnonWrite { fn into_raw_handle(self) -> HANDLE { self.0.into_raw() } } /// A convenience function to connect to a named pipe. /// /// This function will block the calling process until it can connect to the /// pipe server specified by `addr`. This will use `NamedPipe::wait` internally /// to block until it can connect. pub fn connect<A: AsRef<OsStr>>(addr: A) -> io::Result<File> { _connect(addr.as_ref()) } fn _connect(addr: &OsStr) -> io::Result<File> { let mut r = OpenOptions::new(); let mut w = OpenOptions::new(); let mut rw = OpenOptions::new(); r.read(true); w.write(true); rw.read(true).write(true); loop { let res = rw.open(addr).or_else(|_| r.open(addr)) .or_else(|_| w.open(addr)); match res { Ok(f) => return Ok(f), Err(ref e) if e.raw_os_error() == Some(ERROR_PIPE_BUSY as i32) => {} Err(e) => return Err(e), } try!(NamedPipe::wait(addr, Some(Duration::new(20, 0)))); } } impl NamedPipe { /// Creates a new initial named pipe. /// /// This function is equivalent to: /// /// ``` /// use miow::pipe::NamedPipeBuilder; /// /// # let addr = "foo"; /// NamedPipeBuilder::new(addr) /// .first(true) /// .inbound(true) /// .outbound(true) /// .out_buffer_size(65536) /// .in_buffer_size(65536) /// .create(); /// ``` pub fn new<A: AsRef<OsStr>>(addr: A) -> io::Result<NamedPipe> { NamedPipeBuilder::new(addr).create() } /// Waits until either a time-out interval elapses or an instance of the /// specified named pipe is available for connection. /// /// If this function succeeds the process can create a `File` to connect to /// the named pipe. pub fn wait<A: AsRef<OsStr>>(addr: A, timeout: Option<Duration>) -> io::Result<()> { NamedPipe::_wait(addr.as_ref(), timeout) } fn _wait(addr: &OsStr, timeout: Option<Duration>) -> io::Result<()> { let addr = addr.encode_wide().chain(Some(0)).collect::<Vec<_>>(); let timeout = ::dur2ms(timeout); ::cvt(unsafe { WaitNamedPipeW(addr.as_ptr(), timeout) }).map(|_| ()) } /// Connects this named pipe to a client, blocking until one becomes /// available. /// /// This function will call the `ConnectNamedPipe` function to await for a /// client to connect. This can be called immediately after the pipe is /// created, or after it has been disconnected from a previous client. pub fn connect(&self) -> io::Result<()> { match ::cvt(unsafe { ConnectNamedPipe(self.0.raw(), 0 as *mut _) }) { Ok(_) => Ok(()), Err(ref e) if e.raw_os_error() == Some(ERROR_PIPE_CONNECTED as i32) => Ok(()), Err(e) => Err(e), } } /// Issue a connection request with the specified overlapped operation. /// /// This function will issue a request to connect a client to this server, /// returning immediately after starting the overlapped operation. /// /// If this function immediately succeeds then `Ok(true)` is returned. If /// the overlapped operation is enqueued and pending, then `Ok(false)` is /// returned. Otherwise an error is returned indicating what went wrong. /// /// # Unsafety /// /// This function is unsafe because the kernel requires that the /// `overlapped` pointer is valid until the end of the I/O operation. The /// kernel also requires that `overlapped` is unique for this I/O operation /// and is not in use for any other I/O. /// /// To safely use this function callers must ensure that this pointer is /// valid until the I/O operation is completed, typically via completion /// ports and waiting to receive the completion notification on the port. pub unsafe fn connect_overlapped(&self, overlapped: *mut OVERLAPPED) -> io::Result<bool> { match ::cvt(ConnectNamedPipe(self.0.raw(), overlapped)) { Ok(_) => Ok(true), Err(ref e) if e.raw_os_error() == Some(ERROR_PIPE_CONNECTED as i32) => Ok(true), Err(ref e) if e.raw_os_error() == Some(ERROR_IO_PENDING as i32) => Ok(false), Err(e) => Err(e), } } /// Disconnects this named pipe from any connected client. pub fn disconnect(&self) -> io::Result<()> { ::cvt(unsafe { DisconnectNamedPipe(self.0.raw()) }).map(|_| ()) } /// Issues an overlapped read operation to occur on this pipe. /// /// This function will issue an asynchronous read to occur in an overlapped /// fashion, returning immediately. The `buf` provided will be filled in /// with data and the request is tracked by the `overlapped` function /// provided. /// /// If the operation succeeds immediately, `Ok(Some(n))` is returned where /// `n` is the number of bytes read. If an asynchronous operation is /// enqueued, then `Ok(None)` is returned. Otherwise if an error occurred /// it is returned. /// /// When this operation completes (or if it completes immediately), another /// mechanism must be used to learn how many bytes were transferred (such as /// looking at the filed in the IOCP status message). /// /// # Unsafety /// /// This function is unsafe because the kernel requires that the `buf` and /// `overlapped` pointers to be valid until the end of the I/O operation. /// The kernel also requires that `overlapped` is unique for this I/O /// operation and is not in use for any other I/O. /// /// To safely use this function callers must ensure that the pointers are /// valid until the I/O operation is completed, typically via completion /// ports and waiting to receive the completion notification on the port. pub unsafe fn read_overlapped(&self, buf: &mut [u8], overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>> { self.0.read_overlapped(buf, overlapped) } /// Issues an overlapped write operation to occur on this pipe. /// /// This function will issue an asynchronous write to occur in an overlapped /// fashion, returning immediately. The `buf` provided will be filled in /// with data and the request is tracked by the `overlapped` function /// provided. /// /// If the operation succeeds immediately, `Ok(Some(n))` is returned where /// `n` is the number of bytes written. If an asynchronous operation is /// enqueued, then `Ok(None)` is returned. Otherwise if an error occurred /// it is returned. /// /// When this operation completes (or if it completes immediately), another /// mechanism must be used to learn how many bytes were transferred (such as /// looking at the filed in the IOCP status message). /// /// # Unsafety /// /// This function is unsafe because the kernel requires that the `buf` and /// `overlapped` pointers to be valid until the end of the I/O operation. /// The kernel also requires that `overlapped` is unique for this I/O /// operation and is not in use for any other I/O. /// /// To safely use this function callers must ensure that the pointers are /// valid until the I/O operation is completed, typically via completion /// ports and waiting to receive the completion notification on the port. pub unsafe fn write_overlapped(&self, buf: &[u8], overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>> { self.0.write_overlapped(buf, overlapped) } /// Calls the `GetOverlappedResult` function to get the result of an /// overlapped operation for this handle. /// /// This function takes the `OVERLAPPED` argument which must have been used /// to initiate an overlapped I/O operation, and returns either the /// successful number of bytes transferred during the operation or an error /// if one occurred. /// /// # Unsafety /// /// This function is unsafe as `overlapped` must have previously been used /// to execute an operation for this handle, and it must also be a valid /// pointer to an `Overlapped` instance. /// /// # Panics /// /// This function will panic pub unsafe fn result(&self, overlapped: *mut OVERLAPPED) -> io::Result<usize> { let mut transferred = 0; let r = GetOverlappedResult(self.0.raw(), overlapped, &mut transferred, FALSE); if r == 0 { Err(io::Error::last_os_error()) } else { Ok(transferred as usize) } } } impl Read for NamedPipe { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } } impl<'a> Read for &'a NamedPipe { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } } impl Write for NamedPipe { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } fn flush(&mut self) -> io::Result<()> { <&NamedPipe as Write>::flush(&mut &*self) } } impl<'a> Write for &'a NamedPipe { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } fn flush(&mut self) -> io::Result<()> { ::cvt(unsafe { FlushFileBuffers(self.0.raw()) }).map(|_| ()) } } impl AsRawHandle for NamedPipe { fn as_raw_handle(&self) -> HANDLE { self.0.raw() } } impl FromRawHandle for NamedPipe { unsafe fn from_raw_handle(handle: HANDLE) -> NamedPipe { NamedPipe(Handle::new(handle)) } } impl IntoRawHandle for NamedPipe { fn into_raw_handle(self) -> HANDLE { self.0.into_raw() } } fn flag(slot: &mut DWORD, on: bool, val: DWORD) { if on { *slot |= val; } else { *slot &= !val; } } impl NamedPipeBuilder { /// Creates a new named pipe builder with the default settings. pub fn new<A: AsRef<OsStr>>(addr: A) -> NamedPipeBuilder { NamedPipeBuilder { name: addr.as_ref().encode_wide().chain(Some(0)).collect(), dwOpenMode: PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED, dwPipeMode: PIPE_TYPE_BYTE, nMaxInstances: PIPE_UNLIMITED_INSTANCES, nOutBufferSize: 65536, nInBufferSize: 65536, nDefaultTimeOut: 0, } } /// Indicates whether data is allowed to flow from the client to the server. pub fn inbound(&mut self, allowed: bool) -> &mut Self { flag(&mut self.dwOpenMode, allowed, PIPE_ACCESS_INBOUND); self } /// Indicates whether data is allowed to flow from the server to the client. pub fn outbound(&mut self, allowed: bool) -> &mut Self { flag(&mut self.dwOpenMode, allowed, PIPE_ACCESS_OUTBOUND); self } /// Indicates that this pipe must be the first instance. /// /// If set to true, then creation will fail if there's already an instance /// elsewhere. pub fn first(&mut self, first: bool) -> &mut Self { flag(&mut self.dwOpenMode, first, FILE_FLAG_FIRST_PIPE_INSTANCE); self } /// Indicates whether this server can accept remote clients or not. pub fn accept_remote(&mut self, accept: bool) -> &mut Self { flag(&mut self.dwPipeMode, !accept, PIPE_REJECT_REMOTE_CLIENTS); self } /// Specifies the maximum number of instances of the server pipe that are /// allowed. /// /// The first instance of a pipe can specify this value. A value of 255 /// indicates that there is no limit to the number of instances. pub fn max_instances(&mut self, instances: u8) -> &mut Self { self.nMaxInstances = instances as DWORD; self } /// Specifies the number of bytes to reserver for the output buffer pub fn out_buffer_size(&mut self, buffer: u32) -> &mut Self { self.nOutBufferSize = buffer as DWORD; self } /// Specifies the number of bytes to reserver for the input buffer pub fn in_buffer_size(&mut self, buffer: u32) -> &mut Self { self.nInBufferSize = buffer as DWORD; self } /// Using the options in this builder, attempt to create a new named pipe. /// /// This function will call the `CreateNamedPipe` function and return the /// result. pub fn create(&mut self) -> io::Result<NamedPipe> { let h = unsafe { CreateNamedPipeW(self.name.as_ptr(), self.dwOpenMode, self.dwPipeMode, self.nMaxInstances, self.nOutBufferSize, self.nInBufferSize, self.nDefaultTimeOut, 0 as *mut _) }; if h == INVALID_HANDLE_VALUE { Err(io::Error::last_os_error()) } else { Ok(NamedPipe(Handle::new(h))) } } } #[cfg(test)] mod tests { use std::fs::{File, OpenOptions}; use std::io::prelude::*; use std::sync::mpsc::channel; use std::thread; use std::time::Duration; use rand::{thread_rng, Rng}; use super::{anonymous, NamedPipe, NamedPipeBuilder}; use iocp::CompletionPort; use Overlapped; fn name() -> String { let name = thread_rng().gen_ascii_chars().take(30).collect::<String>(); format!(r"\\.\pipe\{}", name) } #[test] fn anon() { let (mut read, mut write) = t!(anonymous(256)); assert_eq!(t!(write.write(&[1, 2, 3])), 3); let mut b = [0; 10]; assert_eq!(t!(read.read(&mut b)), 3); assert_eq!(&b[..3], &[1, 2, 3]); } #[test] fn named_not_first() { let name = name(); let _a = t!(NamedPipe::new(&name)); assert!(NamedPipe::new(&name).is_err()); t!(NamedPipeBuilder::new(&name).first(false).create()); } #[test] fn named_connect() { let name = name(); let a = t!(NamedPipe::new(&name)); let t = thread::spawn(move || { t!(File::open(name)); }); t!(a.connect()); t!(a.disconnect()); t!(t.join()); } #[test] fn named_wait() { let name = name(); let a = t!(NamedPipe::new(&name)); let (tx, rx) = channel(); let t = thread::spawn(move || { t!(NamedPipe::wait(&name, None)); t!(File::open(&name)); assert!(NamedPipe::wait(&name, Some(Duration::from_millis(1))).is_err()); t!(tx.send(())); }); t!(a.connect()); t!(rx.recv()); t!(a.disconnect()); t!(t.join()); } #[test] fn named_connect_overlapped() { let name = name(); let a = t!(NamedPipe::new(&name)); let t = thread::spawn(move || { t!(File::open(name)); }); let cp = t!(CompletionPort::new(1)); t!(cp.add_handle(2, &a)); let over = Overlapped::zero(); unsafe { t!(a.connect_overlapped(over.raw())); } let status = t!(cp.get(None)); assert_eq!(status.bytes_transferred(), 0); assert_eq!(status.token(), 2); assert_eq!(status.overlapped(), over.raw()); t!(t.join()); } #[test] fn named_read_write() { let name = name(); let mut a = t!(NamedPipe::new(&name)); let t = thread::spawn(move || { let mut f = t!(OpenOptions::new().read(true).write(true).open(name)); t!(f.write_all(&[1, 2, 3])); let mut b = [0; 10]; assert_eq!(t!(f.read(&mut b)), 3); assert_eq!(&b[..3], &[1, 2, 3]); }); t!(a.connect()); let mut b = [0; 10]; assert_eq!(t!(a.read(&mut b)), 3); assert_eq!(&b[..3], &[1, 2, 3]); t!(a.write_all(&[1, 2, 3])); t!(a.flush()); t!(a.disconnect()); t!(t.join()); } #[test] fn named_read_overlapped() { let name = name(); let a = t!(NamedPipe::new(&name)); let t = thread::spawn(move || { let mut f = t!(File::create(name)); t!(f.write_all(&[1, 2, 3])); }); let cp = t!(CompletionPort::new(1)); t!(cp.add_handle(3, &a)); t!(a.connect()); let mut b = [0; 10]; let over = Overlapped::zero(); unsafe { t!(a.read_overlapped(&mut b, over.raw())); } let status = t!(cp.get(None)); assert_eq!(status.bytes_transferred(), 3); assert_eq!(status.token(), 3); assert_eq!(status.overlapped(), over.raw()); assert_eq!(&b[..3], &[1, 2, 3]); t!(t.join()); } #[test] fn named_write_overlapped() { let name = name(); let a = t!(NamedPipe::new(&name)); let t = thread::spawn(move || { let mut f = t!(super::connect(name)); let mut b = [0; 10]; assert_eq!(t!(f.read(&mut b)), 3); assert_eq!(&b[..3], &[1, 2, 3]) }); let cp = t!(CompletionPort::new(1)); t!(cp.add_handle(3, &a)); t!(a.connect()); let over = Overlapped::zero(); unsafe { t!(a.write_overlapped(&[1, 2, 3], over.raw())); } let status = t!(cp.get(None)); assert_eq!(status.bytes_transferred(), 3); assert_eq!(status.token(), 3); assert_eq!(status.overlapped(), over.raw()); t!(t.join()); } }
const LINE_DBF: &str = "./tests/data/line.dbf"; const NONE_FLOAT_DBF: &str = "./tests/data/contain_none_float.dbf"; extern crate dbase; use std::collections::HashMap; use std::io::{Cursor, Seek, SeekFrom}; #[test] fn test_none_float() { let records = dbase::read(NONE_FLOAT_DBF).unwrap(); assert_eq!(records.len(), 1); let mut expected_fields = HashMap::new(); expected_fields.insert( "name".to_owned(), dbase::FieldValue::Character(Some("tralala".to_owned())), ); expected_fields.insert( "value_f".to_owned(), dbase::FieldValue::Float(Some(12.345)), ); expected_fields.insert( "value_f_non".to_owned(), dbase::FieldValue::Float(None), ); expected_fields.insert( "value_n".to_owned(), dbase::FieldValue::Numeric(Some(4.0)), ); expected_fields.insert( "value_n_non".to_owned(), dbase::FieldValue::Numeric(None), ); assert_eq!(records[0], expected_fields); } #[test] fn test_simple_file() { let records = dbase::read(LINE_DBF).unwrap(); assert_eq!(records.len(), 1); let mut expected_fields = HashMap::new(); expected_fields.insert( "name".to_owned(), dbase::FieldValue::Character(Some("linestring1".to_owned())), ); assert_eq!(records[0], expected_fields); } #[test] fn test_read_write_simple_file() { let mut expected_fields = HashMap::new(); expected_fields.insert( "name".to_owned(), dbase::FieldValue::Character(Some("linestring1".to_owned())), ); use std::fs::File; let records = dbase::read(LINE_DBF).unwrap(); assert_eq!(records.len(), 1); assert_eq!(records[0], expected_fields); let file = File::create("lol.dbf").unwrap(); let writer = dbase::Writer::new(file); writer.write(&records).unwrap(); let records = dbase::read("lol.dbf").unwrap(); assert_eq!(records.len(), 1); assert_eq!(records[0], expected_fields); } #[test] fn from_scratch() { let mut fst = dbase::Record::new(); fst.insert( "Name".to_string(), dbase::FieldValue::from("Fallujah"), ); let mut scnd = dbase::Record::new(); scnd.insert( "Name".to_string(), dbase::FieldValue::from("Beyond Creation"), ); let records = vec![fst, scnd]; let cursor = Cursor::new(Vec::<u8>::new()); let writer = dbase::Writer::new(cursor); let mut cursor = writer.write(&records).unwrap(); cursor.seek(SeekFrom::Start(0)).unwrap(); let reader = dbase::Reader::new(cursor).unwrap(); let read_records = reader.read().unwrap(); assert_eq!(read_records.len(), 2); match read_records[0].get("Name").unwrap() { dbase::FieldValue::Character(s) => assert_eq!(s, &Some(String::from("Fallujah"))), _ => assert!(false), } match read_records[1].get("Name").unwrap() { dbase::FieldValue::Character(s) => assert_eq!(s, &Some(String::from("Beyond Creation"))), _ => assert!(false), } }
extern crate libc; #[no_mangle] pub extern "C" fn count_substrings(value: *const libc::c_char, substr: *const libc::c_char) -> i32 { let mut count: i32 = -1; let c_value = unsafe { std::ffi::CStr::from_ptr(value) }; let value = c_value.to_str(); let c_substr = unsafe { std::ffi::CStr::from_ptr(substr) }; let substr = c_substr.to_str(); if value.is_ok() && substr.is_ok() { let unwrapped_value = value.unwrap(); let unwrapped_substr = substr.unwrap(); count = unwrapped_value.match_indices(unwrapped_substr).count() as i32; } count }
// 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 {failure::Error, fidl_fuchsia_settings::*}; pub async fn command( proxy: PrivacyProxy, user_data_sharing_consent: Option<bool>, ) -> Result<String, Error> { if let Some(user_data_sharing_consent_value) = user_data_sharing_consent { let mut settings = PrivacySettings::empty(); settings.user_data_sharing_consent = Some(user_data_sharing_consent_value); let mutate_result = proxy.set(settings).await?; match mutate_result { Ok(_) => Ok(format!( "Successfully set user_data_sharing_consent to {}", user_data_sharing_consent_value )), Err(err) => Ok(format!("{:?}", err)), } } else { let setting = proxy.watch().await?; match setting { Ok(setting_value) => Ok(format!("{:?}", setting_value)), Err(err) => Ok(format!("{:?}", err)), } } }
use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] pub struct RigidBody { pub name: String, pub status: RigidBodyStatus, } #[derive(Serialize, Deserialize, Debug)] pub enum RigidBodyStatus { Static, Dynamic, Kinematic, } #[derive(Serialize, Deserialize, Debug)] pub struct Collider { pub name: String, pub shape: Shape, } #[derive(Serialize, Deserialize, Debug)] pub enum Shape { Cuboid(f32, f32), Blubb, }
use super::search::get_all_files; use chrono::{Duration, DateTime, Local}; pub fn get_tracker_stats_all(password: &String) -> Vec<(String, Vec<(String, Vec<f64>, Vec<String>)>)> { let files = get_all_files(password); let mut return_vec = vec!(); for (filename, plaintext) in files { let mut obj: serde_json::Value = serde_json::from_str(&plaintext).unwrap(); let trackers = obj["trackers"].as_array_mut(); let trackers = match trackers { None => continue, Some(arr) => arr, }; let mut tracker_vec = vec!(); for tracker_obj in trackers { // Make an owned copy of the tracker so we don't borrow twice let mut owned_tracker_1 = tracker_obj.clone(); let owned_tracker_2 = tracker_obj.clone(); // Get json arrays let tracker_data_json = tracker_obj["data"].as_array_mut().unwrap(); let tracker_data_times_json = owned_tracker_1["data_time"].as_array_mut().unwrap(); let tracker_name = owned_tracker_2["tracker_name"].as_str().unwrap().to_string(); // Create normal arrays let mut tracker_data = vec!(); let mut tracker_data_times = vec!(); // Get values out of the json arrays for datum in tracker_data_json { let owned_datum = datum.to_owned(); // Take ownership of value let datum_f64: f64 = serde_json::from_value(owned_datum).unwrap(); // Convert value to f64 tracker_data.push(datum_f64); } for datum_date in tracker_data_times_json { tracker_data_times.push(datum_date.as_str().unwrap().to_string()); // Convert json value to string } println!("File with name {} has tracker with name {}.\n Data \n {:?} \n Times \n {:?}. \n", filename, tracker_name, tracker_data, tracker_data_times); tracker_vec.push((tracker_name, tracker_data, tracker_data_times)); } return_vec.push((filename.clone(), tracker_vec)) } return return_vec; } pub fn get_tracker_stats_time(password: &String, start: &DateTime<Local>, end: &DateTime<Local>) -> Vec<(Vec<f64>,Vec<String>)> { let files = get_all_files(password); let mut return_vec = vec!(); for (filename, plaintext) in files { let mut obj: serde_json::Value = serde_json::from_str(&plaintext).unwrap(); let trackers = obj["trackers"].as_array_mut(); let trackers = match trackers { None => continue, Some(arr) => arr, }; for tracker_obj in trackers { // Make an owned copy of the tracker so we don't borrow twice let mut owned_tracker = tracker_obj.to_owned(); // Get json arrays let tracker_data_json = tracker_obj["data"].as_array_mut().unwrap(); let tracker_data_times_json = owned_tracker["data_time"].as_array_mut().unwrap(); // Create normal arrays let mut tracker_data = vec!(); let mut tracker_data_times = vec!(); for i in 0..tracker_data_json.len() { let datum_date = tracker_data_times_json[i].to_owned(); // Take time str and convert to datetime let time = DateTime::parse_from_rfc2822(datum_date.as_str().unwrap()).unwrap(); // If time of data is within range then add it to the output if time >= *start && time <= *end { let datum_f64: f64 = serde_json::from_value(tracker_data_json[i].to_owned()).unwrap(); // Convert value to f64 tracker_data.push(datum_f64); tracker_data_times.push(time.to_rfc2822()); // Convert json value to string } } println!("File with name {} has tracker with data \n {:?} \n and times \n {:?}. \n", filename, tracker_data, tracker_data_times); return_vec.push((tracker_data, tracker_data_times)); } } return return_vec; } fn get_task_duration(task_obj: &serde_json::Value) -> Duration { // Get task start and end times let task_start = task_obj["time_added"].to_owned(); let task_end = task_obj["time_completed"].to_owned(); let mut task_duration: Duration = Duration::seconds(0); // If both start and end times are not null, then calculate duration taken if !task_start.is_null() && !task_end.is_null() { let datetime_start = DateTime::parse_from_rfc2822(task_start.as_str().unwrap()).unwrap(); let datetime_end = DateTime::parse_from_rfc2822(task_start.as_str().unwrap()).unwrap(); task_duration = datetime_end - datetime_start; } return task_duration; } pub fn get_task_stats(password: &String){ let files = get_all_files(password); for (filename, plaintext) in files { let mut obj: serde_json::Value = serde_json::from_str(&plaintext).unwrap(); let tasks = obj["tasks"].as_array_mut(); let tasks = match tasks { None => continue, Some(arr) => arr, }; for task_obj in tasks { let task_duration = get_task_duration(&task_obj); println!("File with name {} has task with name {}. This task took {} minutes to complete", filename, task_obj["task_name"], task_duration.num_minutes()); let subtasks = task_obj["subtasks"].to_owned(); // Check subtask names if !subtasks.is_null() { let subtasks = task_obj["subtasks"].as_array_mut().unwrap(); for subtask_obj in subtasks { let subtask_duration = get_task_duration(&subtask_obj); println!("File with name {} has subtask with name {}. This subtask took {} minutes to complete", filename, subtask_obj["task_name"], subtask_duration.num_minutes()); } } } } } pub fn get_tag_stats(password: &String, tags_input: Vec<String>) -> Vec<String>{ let files = get_all_files(password); let mut return_vec = vec!(); for (filename, plaintext) in files { let mut obj: serde_json::Value = serde_json::from_str(&plaintext).unwrap(); let tags = obj["tags"].as_array_mut(); let tags = match tags { None => continue, Some(arr) => arr, }; let mut tag_remaining = tags_input.len(); for tag in tags { // For each tag in the tag list, if it is a tag that we search for, // then reduce the tag remaining by one if tags_input.contains(&tag.to_owned().as_str().unwrap().to_string()) { tag_remaining -= 1; } } // If all tags were found, remaining should be zero if tag_remaining <= 0 { return_vec.push(filename.clone()); println!("File with name {} contains tags {:?}", filename, tags_input); } } return return_vec; } fn mean(data: &Vec<f64>) -> f64{ let sum: f64 = Iterator::sum(data.iter()); return sum / (data.len() as f64); } fn net_change(data: &Vec<f64>) -> f64{ return data[data.len() - 1] - data[0]; } fn median(data: &Vec<f64>) -> f64 { if data.len() % 2 != 0 { return data[(data.len()/2 as usize)] } else { let mut two_middle_elements = vec!(); two_middle_elements.push(data[(data.len()/2-1 as usize)]); two_middle_elements.push(data[(data.len()/2 as usize)]); return mean(&two_middle_elements); } } pub fn get_advanced_stats(password: &String) -> Vec<(String, Vec<(String, f64, f64, f64)>)>{ let tracker_files = get_tracker_stats_all(password); let mut return_vec = vec!(); for (filename, trackers) in tracker_files { println!("File with name {}", filename); let mut tracker_vec = vec!(); for (tracker_name, tracker_data, _) in trackers { let mean = mean(&tracker_data); let net_change = net_change(&tracker_data); let median = median(&tracker_data); println!("Tracker with name {}", tracker_name.clone()); println!("Average: {}", mean); println!("Net gain/loss: {}", net_change); println!("Median: {}", median); tracker_vec.push((tracker_name.clone(), mean, net_change, median)); } return_vec.push((filename.clone(), tracker_vec)); } return return_vec; } #[cfg(test)] mod tests{ use super::{mean, net_change, median, get_tag_stats}; use std::fs; use crate::note::tag::add_tag; fn teardown(file_path: &str) { fs::remove_file(file_path).unwrap(); } fn setup_vec() -> Vec<f64>{ let mut test_vec: Vec<f64> = vec!(); test_vec.push(1.0); test_vec.push(2.0); test_vec.push(3.0); test_vec.push(4.0); test_vec.push(5.0); return test_vec; } fn setup_tag() -> (String, String, String, String, String) { let password = "abcd".to_string(); // Create random filename let x = rand::random::<u64>(); let filename1 = "temp".to_string(); let filename1 = [filename1, x.to_string()].concat(); let tag1 = "tag1".to_string(); let tag2 = "tag2".to_string(); let filename2 = "temp".to_string(); let filename2 = [filename2, x.to_string(), "2".to_string()].concat(); // Add both tags to first file add_tag(&password, &filename1, &tag1).unwrap(); add_tag(&password, &filename1, &tag2).unwrap(); // Add only one tag to second file add_tag(&password, &filename2, &tag1).unwrap(); return (password, filename1, filename2, tag1, tag2); } /// Test if the mean is calculated correctly #[test] fn test_mean() { let test_vec = setup_vec(); let actual_mean = 3.0; assert_eq!(actual_mean, mean(&test_vec)) } /// Test if the net change is calculated correctly #[test] fn test_net_change() { let test_vec = setup_vec(); let actual_net_change = 4.0; assert_eq!(actual_net_change, net_change(&test_vec)) } /// Test if the median is the correct data point, if the data list has an odd number of elements #[test] fn test_median_odd() { let test_vec = setup_vec(); let actual_median = 3.0; assert_eq!(actual_median, median(&test_vec)) } /// Test if the median is the correct data point, if the data list has an even number of elements #[test] fn test_median_even() { let mut test_vec = setup_vec(); test_vec.push(6.0); let actual_median = 3.5; assert_eq!(actual_median, median(&test_vec)) } /// Test tag stats returns both files with shared tag. #[test] fn test_tag_stats_two_files() { // Filename1 has both tags, filename1 only has tag1 let (password, filename1, filename2, tag1, _) = setup_tag(); let mut tag_input = vec!(); tag_input.push(tag1); let filenames = get_tag_stats(&password, tag_input); let file_path_1 = ["./files/", &filename1].concat(); let file_path_2 = ["./files/", &filename2].concat(); teardown(&file_path_1); teardown(&file_path_2); assert!(filenames.contains(&filename1)); assert!(filenames.contains(&filename2)); } /// Test tag stats returns one file with unshared tag. #[test] fn test_tag_stats_one_file() { // Filename1 has both tags, filename1 only has tag1 let (password, filename1, filename2, _, tag2) = setup_tag(); let mut tag_input = vec!(); tag_input.push(tag2); let filenames = get_tag_stats(&password, tag_input); let file_path_1 = ["./files/", &filename1].concat(); let file_path_2 = ["./files/", &filename2].concat(); teardown(&file_path_1); teardown(&file_path_2); assert!(filenames.contains(&filename1)); assert!(!filenames.contains(&filename2)); } }
extern crate futures; use futures::*; use futures::stream::Stream; struct CounterStream { index: i32, limit: i32, } fn counter(limit: i32) -> CounterStream { CounterStream{index: 0, limit: limit} } impl Stream for CounterStream { type Item = i32; type Error = (); fn poll(&mut self, _task: &mut Task) -> Poll<Option<Self::Item>, Self::Error> { if self.index == self.limit { return Poll::Ok(None); } let v = self.index; self.index += 1; Poll::Ok(Some(v)) } fn schedule(&mut self, _task: &mut Task) { return } } fn main() { counter(10).for_each(|v| { println!("v: {:?}", v); Ok(()) }).forget(); }
//! I2C use core::ops::Deref; use crate::hal::blocking::i2c::{Read, Write, WriteRead}; use crate::gpio::gpioa::{PA10, PA13, PA9}; use crate::gpio::gpiob::{PB6, PB7}; use crate::gpio::{AltMode, OpenDrain, Output}; use crate::pac::{i2c1::RegisterBlock, I2C1}; use crate::rcc::Rcc; use crate::time::Hertz; use cast::u8; #[cfg(feature = "stm32l0x1")] use crate::gpio::gpioa::PA4; #[cfg(feature = "stm32l0x2")] use crate::{ gpio::{ gpioa::PA8, gpiob::{PB11, PB14, PB4, PB8, PB9}, gpioc::{PC0, PC1}, }, pac::{I2C2, I2C3}, }; /// I2C abstraction pub struct I2c<I2C, SDA, SCL> { i2c: I2C, sda: SDA, scl: SCL, } impl<I, SDA, SCL> I2c<I, SDA, SCL> where I: Instance, { pub fn new(i2c: I, sda: SDA, scl: SCL, freq: Hertz, rcc: &mut Rcc) -> Self where I: Instance, SDA: SDAPin<I>, SCL: SCLPin<I>, { sda.setup(); scl.setup(); i2c.initialize(rcc); let freq = freq.0; assert!(freq <= 1_000_000); // TODO review compliance with the timing requirements of I2C // t_I2CCLK = 1 / PCLK1 // t_PRESC = (PRESC + 1) * t_I2CCLK // t_SCLL = (SCLL + 1) * t_PRESC // t_SCLH = (SCLH + 1) * t_PRESC // // t_SYNC1 + t_SYNC2 > 4 * t_I2CCLK // t_SCL ~= t_SYNC1 + t_SYNC2 + t_SCLL + t_SCLH let i2cclk = rcc.clocks.apb1_clk().0; let ratio = i2cclk / freq - 4; let (presc, scll, sclh, sdadel, scldel) = if freq >= 100_000 { // fast-mode or fast-mode plus // here we pick SCLL + 1 = 2 * (SCLH + 1) let presc = ratio / 387; let sclh = ((ratio / (presc + 1)) - 3) / 3; let scll = 2 * (sclh + 1) - 1; let (sdadel, scldel) = if freq > 400_000 { // fast-mode plus let sdadel = 0; let scldel = i2cclk / 4_000_000 / (presc + 1) - 1; (sdadel, scldel) } else { // fast-mode let sdadel = i2cclk / 8_000_000 / (presc + 1); let scldel = i2cclk / 2_000_000 / (presc + 1) - 1; (sdadel, scldel) }; (presc, scll, sclh, sdadel, scldel) } else { // standard-mode // here we pick SCLL = SCLH let presc = ratio / 514; let sclh = ((ratio / (presc + 1)) - 2) / 2; let scll = sclh; let sdadel = i2cclk / 2_000_000 / (presc + 1); let scldel = i2cclk / 800_000 / (presc + 1) - 1; (presc, scll, sclh, sdadel, scldel) }; let presc = u8(presc).unwrap(); assert!(presc < 16); let scldel = u8(scldel).unwrap(); assert!(scldel < 16); let sdadel = u8(sdadel).unwrap(); assert!(sdadel < 16); let sclh = u8(sclh).unwrap(); let scll = u8(scll).unwrap(); // Configure for "fast mode" (400 KHz) i2c.timingr.write(|w| { w.presc() .bits(presc) .scll() .bits(scll) .sclh() .bits(sclh) .sdadel() .bits(sdadel) .scldel() .bits(scldel) }); // Enable the peripheral i2c.cr1.write(|w| w.pe().set_bit()); I2c { i2c, sda, scl } } pub fn release(self) -> (I, SDA, SCL) { (self.i2c, self.sda, self.scl) } fn send_byte(&self, byte: u8) -> Result<(), Error> { // Wait until we're ready for sending while self.i2c.isr.read().txe().bit_is_clear() {} // Push out a byte of data self.i2c.txdr.write(|w| w.txdata().bits(byte)); // While until byte is transferred loop { let isr = self.i2c.isr.read(); if isr.berr().bit_is_set() { self.i2c.icr.write(|w| w.berrcf().set_bit()); return Err(Error::BusError); } else if isr.arlo().bit_is_set() { self.i2c.icr.write(|w| w.arlocf().set_bit()); return Err(Error::ArbitrationLost); } else if isr.nackf().bit_is_set() { self.i2c.icr.write(|w| w.nackcf().set_bit()); return Err(Error::Nack); } return Ok(()); } } fn recv_byte(&self) -> Result<u8, Error> { while self.i2c.isr.read().rxne().bit_is_clear() {} let value = self.i2c.rxdr.read().rxdata().bits(); Ok(value) } } impl<I, SDA, SCL> WriteRead for I2c<I, SDA, SCL> where I: Instance, { type Error = Error; fn write_read(&mut self, addr: u8, bytes: &[u8], buffer: &mut [u8]) -> Result<(), Self::Error> { self.write(addr, bytes)?; self.read(addr, buffer)?; Ok(()) } } impl<I, SDA, SCL> Write for I2c<I, SDA, SCL> where I: Instance, { type Error = Error; fn write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Self::Error> { while self.i2c.isr.read().busy().is_busy() {} self.i2c.cr2.write(|w| { w.start() .set_bit() .nbytes() .bits(bytes.len() as u8) .sadd() .bits((addr << 1) as u16) .rd_wrn() .clear_bit() .autoend() .set_bit() }); // Send bytes for c in bytes { self.send_byte(*c)?; } Ok(()) } } impl<I, SDA, SCL> Read for I2c<I, SDA, SCL> where I: Instance, { type Error = Error; fn read(&mut self, addr: u8, buffer: &mut [u8]) -> Result<(), Self::Error> { while self.i2c.isr.read().busy().is_busy() {} self.i2c.cr2.write(|w| { w.start() .set_bit() .nbytes() .bits(buffer.len() as u8) .sadd() .bits((addr << 1) as u16) // Request read transfer .rd_wrn() .read() .autoend() .set_bit() }); // Receive bytes into buffer for c in buffer { *c = self.recv_byte()?; } Ok(()) } } pub trait Instance: Deref<Target = RegisterBlock> { fn initialize(&self, rcc: &mut Rcc); } // I2C SDA pin pub trait SDAPin<I2C> { fn setup(&self); } // I2C SCL pin pub trait SCLPin<I2C> { fn setup(&self); } // I2C error #[derive(Debug)] pub enum Error { Overrun, Nack, PECError, BusError, ArbitrationLost, } pub trait I2cExt<I2C> { fn i2c<SDA, SCL>(self, sda: SDA, scl: SCL, freq: Hertz, rcc: &mut Rcc) -> I2c<I2C, SDA, SCL> where SDA: SDAPin<I2C>, SCL: SCLPin<I2C>; } macro_rules! i2c { ($I2CX:ident, $i2cxen:ident, $i2crst:ident, sda: [ $(($PSDA:ty, $afsda:expr),)+ ], scl: [ $(($PSCL:ty, $afscl:expr),)+ ], ) => { $( impl SDAPin<$I2CX> for $PSDA { fn setup(&self) { self.set_alt_mode($afsda) } } )+ $( impl SCLPin<$I2CX> for $PSCL { fn setup(&self) { self.set_alt_mode($afscl) } } )+ impl I2cExt<$I2CX> for $I2CX { fn i2c<SDA, SCL>( self, sda: SDA, scl: SCL, freq: Hertz, rcc: &mut Rcc, ) -> I2c<$I2CX, SDA, SCL> where SDA: SDAPin<$I2CX>, SCL: SCLPin<$I2CX>, { I2c::new(self, sda, scl, freq, rcc) } } impl Instance for $I2CX { fn initialize(&self, rcc: &mut Rcc) { // Enable clock for I2C rcc.rb.apb1enr.modify(|_, w| w.$i2cxen().set_bit()); // Reset I2C rcc.rb.apb1rstr.modify(|_, w| w.$i2crst().set_bit()); rcc.rb.apb1rstr.modify(|_, w| w.$i2crst().clear_bit()); } } }; } #[cfg(feature = "stm32l0x1")] i2c!( I2C1, i2c1en, i2c1rst, sda: [ (PB7<Output<OpenDrain>>, AltMode::AF1), (PA10<Output<OpenDrain>>, AltMode::AF1), (PA13<Output<OpenDrain>>, AltMode::AF3), ], scl: [ (PB6<Output<OpenDrain>>, AltMode::AF1), (PA9<Output<OpenDrain>>, AltMode::AF1), (PA4<Output<OpenDrain>>, AltMode::AF3), ], ); #[cfg(feature = "stm32l0x2")] i2c!( I2C1, i2c1en, i2c1rst, sda: [ (PA10<Output<OpenDrain>>, AltMode::AF6), (PB7<Output<OpenDrain>>, AltMode::AF1), (PB9<Output<OpenDrain>>, AltMode::AF4), ], scl: [ (PA9<Output<OpenDrain>>, AltMode::AF6), (PB6<Output<OpenDrain>>, AltMode::AF1), (PB8<Output<OpenDrain>>, AltMode::AF4), ], ); #[cfg(feature = "stm32l0x2")] i2c!( I2C2, i2c2en, i2c2rst, sda: [ (PB11<Output<OpenDrain>>, AltMode::AF6), (PB14<Output<OpenDrain>>, AltMode::AF5), ], scl: [ (PA10<Output<OpenDrain>>, AltMode::AF6), (PA13<Output<OpenDrain>>, AltMode::AF5), ], ); #[cfg(feature = "stm32l0x2")] i2c!( I2C3, i2c3en, i2c3rst, sda: [ (PB4<Output<OpenDrain>>, AltMode::AF7), (PC1<Output<OpenDrain>>, AltMode::AF7), ], scl: [ (PA8<Output<OpenDrain>>, AltMode::AF7), (PC0<Output<OpenDrain>>, AltMode::AF7), ], );
use xassembler::{compile, Target}; pub trait Compile: Target { const BUILD_DIR_NAME: &'static str; const PRELUDE: &'static str; const TERMINATE: &'static str; fn compile_subcommand(compiled: &str, dependeny_paths: Vec<&str>, output_path: &str) -> Result<(), String>; fn run_subcommand(compiled: &str, dependeny_paths: Vec<&str>) -> Result<(), String>; fn build(compiled: &str, dependeny_paths: Vec<&str>) -> Result<(), String>; fn assemble(script: &str) -> Result<String, String> where Self: Sized, { Ok(format!( "{} {} {}", Self::PRELUDE, compile::<Self>(script)?, Self::TERMINATE )) } fn home_dir() -> Result<String, String> { let home = dirs::home_dir().ok_or_else(|| String::from("No home directory in this environment"))?; Ok(home .to_str() .ok_or_else(|| String::from("No home directory in this environment"))? .to_string()) } fn build_dir() -> Result<String, String> { Ok(Self::home_dir()? + "/" + Self::BUILD_DIR_NAME) } }
pub fn cleanup_temp_files() { println!("Cleaning up temp files.. not implemented. Cannot delete temp* files"); }
use crate::monsters::Monster; pub mod lava_dragon; pub trait Dragon: Monster {}
use crate::ir::eval::prelude::*; impl IrEval for ir::IrBinary { type Output = IrValue; fn eval( &self, interp: &mut IrInterpreter<'_>, used: Used, ) -> Result<Self::Output, IrEvalOutcome> { use std::ops::{Add, Mul, Shl, Shr, Sub}; let span = self.span(); interp.budget.take(span)?; let a = self.lhs.eval(interp, used)?; let b = self.rhs.eval(interp, used)?; match (a, b) { (IrValue::Integer(a), IrValue::Integer(b)) => match self.op { ir::IrBinaryOp::Add => { return Ok(IrValue::Integer(a.add(&b))); } ir::IrBinaryOp::Sub => { return Ok(IrValue::Integer(a.sub(&b))); } ir::IrBinaryOp::Mul => { return Ok(IrValue::Integer(a.mul(&b))); } ir::IrBinaryOp::Div => { let number = a .checked_div(&b) .ok_or_else(|| IrError::msg(span, "division by zero"))?; return Ok(IrValue::Integer(number)); } ir::IrBinaryOp::Shl => { let b = u32::try_from(b).map_err(|_| { IrError::msg(&self.rhs, "cannot be converted to shift operand") })?; let n = a.shl(b); return Ok(IrValue::Integer(n)); } ir::IrBinaryOp::Shr => { let b = u32::try_from(b).map_err(|_| { IrError::msg(&self.rhs, "cannot be converted to shift operand") })?; let n = a.shr(b); return Ok(IrValue::Integer(n)); } ir::IrBinaryOp::Lt => return Ok(IrValue::Bool(a < b)), ir::IrBinaryOp::Lte => return Ok(IrValue::Bool(a <= b)), ir::IrBinaryOp::Eq => return Ok(IrValue::Bool(a == b)), ir::IrBinaryOp::Gt => return Ok(IrValue::Bool(a > b)), ir::IrBinaryOp::Gte => return Ok(IrValue::Bool(a >= b)), }, (IrValue::Float(a), IrValue::Float(b)) => { #[allow(clippy::float_cmp)] match self.op { ir::IrBinaryOp::Add => return Ok(IrValue::Float(a + b)), ir::IrBinaryOp::Sub => return Ok(IrValue::Float(a - b)), ir::IrBinaryOp::Mul => return Ok(IrValue::Float(a * b)), ir::IrBinaryOp::Div => return Ok(IrValue::Float(a / b)), ir::IrBinaryOp::Lt => return Ok(IrValue::Bool(a < b)), ir::IrBinaryOp::Lte => return Ok(IrValue::Bool(a <= b)), ir::IrBinaryOp::Eq => return Ok(IrValue::Bool(a == b)), ir::IrBinaryOp::Gt => return Ok(IrValue::Bool(a > b)), ir::IrBinaryOp::Gte => return Ok(IrValue::Bool(a >= b)), _ => (), }; } (IrValue::String(a), IrValue::String(b)) => { if let ir::IrBinaryOp::Add = self.op { return Ok(IrValue::String(add_strings(span, &a, &b)?)); } } _ => (), } Err(IrEvalOutcome::not_const(span)) } } fn add_strings( span: Span, a: &Shared<String>, b: &Shared<String>, ) -> Result<Shared<String>, IrError> { let a = a.borrow_ref().map_err(|e| IrError::new(span, e))?; let b = b.borrow_ref().map_err(|e| IrError::new(span, e))?; let mut a = String::from(&*a); a.push_str(&b); Ok(Shared::new(a)) }
#[cfg(not(feature = "binary"))] fn main() {} #[cfg(feature = "binary")] fn address_from_env(env: &'static str) -> Option<u64> { use std::env; match env::var(env) { Err(env::VarError::NotPresent) => None, Err(env::VarError::NotUnicode(_)) => { panic!("The `{}` environment variable must be valid unicode", env,) } Ok(s) => { let addr = if s.starts_with("0x") { u64::from_str_radix(&s[2..], 16) } else { u64::from_str_radix(&s, 10) }; let addr = addr.expect(&format!( "The `{}` environment variable must be an integer\ (is `{}`).", env, s )); if addr % 0x1000 != 0 { panic!( "The `{}` environment variable must be aligned to 0x1000 (is `{:#x}`).", env, addr ); } Some(addr) } } } #[cfg(feature = "binary")] fn main() { use std::{ env, fs::File, io::Write, path::{Path, PathBuf}, process::{self, Command}, }; let target = env::var("TARGET").expect("TARGET not set"); if Path::new(&target) .file_stem() .expect("target has no file stem") != "x86_64-bootloader" { panic!("The bootloader must be compiled for the `x86_64-bootloader.json` target."); } let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set")); let kernel = PathBuf::from(match env::var("KERNEL") { Ok(kernel) => kernel, Err(_) => { eprintln!( "The KERNEL environment variable must be set for building the bootloader.\n\n\ If you use `bootimage` for building you need at least version 0.7.0. You can \ update `bootimage` by running `cargo install bootimage --force`." ); process::exit(1); } }); let kernel_file_name = kernel .file_name() .expect("KERNEL has no valid file name") .to_str() .expect("kernel file name not valid utf8"); // check that the kernel file exists assert!( kernel.exists(), format!("KERNEL does not exist: {}", kernel.display()) ); // get access to llvm tools shipped in the llvm-tools-preview rustup component let llvm_tools = match llvm_tools::LlvmTools::new() { Ok(tools) => tools, Err(llvm_tools::Error::NotFound) => { eprintln!("Error: llvm-tools not found"); eprintln!("Maybe the rustup component `llvm-tools-preview` is missing?"); eprintln!(" Install it through: `rustup component add llvm-tools-preview`"); process::exit(1); } Err(err) => { eprintln!("Failed to retrieve llvm-tools component: {:?}", err); process::exit(1); } }; // check that kernel executable has code in it let llvm_size = llvm_tools .tool(&llvm_tools::exe("llvm-size")) .expect("llvm-size not found in llvm-tools"); let mut cmd = Command::new(llvm_size); cmd.arg(&kernel); let output = cmd.output().expect("failed to run llvm-size"); let output_str = String::from_utf8_lossy(&output.stdout); let second_line_opt = output_str.lines().skip(1).next(); let second_line = second_line_opt.expect("unexpected llvm-size line output"); let text_size_opt = second_line.split_ascii_whitespace().next(); let text_size = text_size_opt.expect("unexpected llvm-size output"); if text_size == "0" { panic!("Kernel executable has an empty text section. Perhaps the entry point was set incorrectly?\n\n\ Kernel executable at `{}`\n", kernel.display()); } // strip debug symbols from kernel for faster loading let stripped_kernel_file_name = format!("kernel_stripped-{}", kernel_file_name); let stripped_kernel = out_dir.join(&stripped_kernel_file_name); let objcopy = llvm_tools .tool(&llvm_tools::exe("llvm-objcopy")) .expect("llvm-objcopy not found in llvm-tools"); let mut cmd = Command::new(&objcopy); cmd.arg("--strip-debug"); cmd.arg(&kernel); cmd.arg(&stripped_kernel); let exit_status = cmd .status() .expect("failed to run objcopy to strip debug symbols"); if !exit_status.success() { eprintln!("Error: Stripping debug symbols failed"); process::exit(1); } // wrap the kernel executable as binary in a new ELF file let stripped_kernel_file_name_replaced = stripped_kernel_file_name.replace('-', "_"); let kernel_bin = out_dir.join(format!("kernel_bin-{}.o", kernel_file_name)); let kernel_archive = out_dir.join(format!("libkernel_bin-{}.a", kernel_file_name)); let mut cmd = Command::new(&objcopy); cmd.arg("-I").arg("binary"); cmd.arg("-O").arg("elf64-x86-64"); cmd.arg("--binary-architecture=i386:x86-64"); cmd.arg("--rename-section").arg(".data=.kernel"); cmd.arg("--redefine-sym").arg(format!( "_binary_{}_start=_kernel_start_addr", stripped_kernel_file_name_replaced )); cmd.arg("--redefine-sym").arg(format!( "_binary_{}_end=_kernel_end_addr", stripped_kernel_file_name_replaced )); cmd.arg("--redefine-sym").arg(format!( "_binary_{}_size=_kernel_size", stripped_kernel_file_name_replaced )); cmd.current_dir(&out_dir); cmd.arg(&stripped_kernel_file_name); cmd.arg(&kernel_bin); let exit_status = cmd.status().expect("failed to run objcopy"); if !exit_status.success() { eprintln!("Error: Running objcopy failed"); process::exit(1); } // create an archive for linking let ar = llvm_tools .tool(&llvm_tools::exe("llvm-ar")) .unwrap_or_else(|| { eprintln!("Failed to retrieve llvm-ar component"); eprint!("This component is available since nightly-2019-03-29,"); eprintln!("so try updating your toolchain if you're using an older nightly"); process::exit(1); }); let mut cmd = Command::new(ar); cmd.arg("crs"); cmd.arg(&kernel_archive); cmd.arg(&kernel_bin); let exit_status = cmd.status().expect("failed to run ar"); if !exit_status.success() { eprintln!("Error: Running ar failed"); process::exit(1); } // create a file with the `PHYSICAL_MEMORY_OFFSET` constant let file_path = out_dir.join("physical_memory_offset.rs"); let mut file = File::create(file_path).expect("failed to create physical_memory_offset.rs"); let physical_memory_offset = address_from_env("BOOTLOADER_PHYSICAL_MEMORY_OFFSET"); file.write_all( format!( "const PHYSICAL_MEMORY_OFFSET: Option<u64> = {:?};", physical_memory_offset ) .as_bytes(), ) .expect("write to physical_memory_offset.rs failed"); // create a file with the `KERNEL_STACK_ADDRESS` constant let file_path = out_dir.join("kernel_stack_address.rs"); let mut file = File::create(file_path).expect("failed to create kernel_stack_address.rs"); let kernel_stack_address = address_from_env("BOOTLOADER_KERNEL_STACK_ADDRESS"); file.write_all( format!( "const KERNEL_STACK_ADDRESS: Option<u64> = {:?};", kernel_stack_address, ) .as_bytes(), ) .expect("write to kernel_stack_address.rs failed"); // pass link arguments to rustc println!("cargo:rustc-link-search=native={}", out_dir.display()); println!( "cargo:rustc-link-lib=static=kernel_bin-{}", kernel_file_name ); println!("cargo:rerun-if-env-changed=KERNEL"); println!("cargo:rerun-if-env-changed=BOOTLOADER_PHYSICAL_MEMORY_OFFSET"); println!("cargo:rerun-if-env-changed=BOOTLOADER_KERNEL_STACK_ADDRESS"); println!("cargo:rerun-if-changed={}", kernel.display()); println!("cargo:rerun-if-changed=build.rs"); }
#![deny(rustdoc::broken_intra_doc_links, rust_2018_idioms)] #![warn( clippy::clone_on_ref_ptr, clippy::dbg_macro, clippy::explicit_iter_loop, // See https://github.com/influxdata/influxdb_iox/pull/1671 clippy::future_not_send, clippy::todo, clippy::use_self, missing_debug_implementations, unused_crate_dependencies )] #![allow(clippy::default_constructed_unit_structs)] // Workaround for "unused crate" lint false positives. use workspace_hack as _; use std::{ fmt::{Debug, Display}, sync::Arc, }; use async_trait::async_trait; use authz::{Authorizer, AuthorizerInstrumentation, IoxAuthorizer}; use clap_blocks::{gossip::GossipConfig, router::RouterConfig}; use data_types::NamespaceName; use hashbrown::HashMap; use hyper::{Body, Request, Response}; use iox_catalog::interface::Catalog; use ioxd_common::{ add_service, http::error::{HttpApiError, HttpApiErrorSource}, reexport::{ generated_types::influxdata::iox::{ catalog::v1::catalog_service_server, namespace::v1::namespace_service_server, object_store::v1::object_store_service_server, schema::v1::schema_service_server, table::v1::table_service_server, }, tonic::transport::Endpoint, }, rpc::RpcBuilderInput, serve_builder, server_type::{CommonServerState, RpcError, ServerType}, setup_builder, }; use metric::Registry; use mutable_batch::MutableBatch; use object_store::DynObjectStore; use router::{ dml_handlers::{ lazy_connector::LazyConnector, DmlHandler, DmlHandlerChainExt, FanOutAdaptor, InstrumentationDecorator, Partitioner, RetentionValidator, RpcWrite, SchemaValidator, }, gossip::{ dispatcher::GossipMessageDispatcher, namespace_cache::NamespaceSchemaGossip, schema_change_observer::SchemaChangeObserver, }, namespace_cache::{ metrics::InstrumentedCache, MaybeLayer, MemoryNamespaceCache, NamespaceCache, ReadThroughCache, ShardedCache, }, namespace_resolver::{ MissingNamespaceAction, NamespaceAutocreation, NamespaceResolver, NamespaceSchemaResolver, }, server::{ grpc::RpcWriteGrpcDelegate, http::{ write::{ multi_tenant::MultiTenantRequestUnifier, single_tenant::SingleTenantRequestUnifier, WriteRequestUnifier, }, HttpDelegate, }, RpcWriteRouterServer, }, }; use thiserror::Error; use tokio_util::sync::CancellationToken; use trace::TraceCollector; #[derive(Debug, Error)] pub enum Error { #[error("Catalog error: {0}")] Catalog(#[from] iox_catalog::interface::Error), #[error("Catalog DSN error: {0}")] CatalogDsn(#[from] clap_blocks::catalog_dsn::Error), #[error("authz configuration error for '{addr}': '{source}'")] AuthzConfig { source: Box<dyn std::error::Error>, addr: String, }, /// An error binding the UDP socket for gossip communication. #[error("failed to bind udp gossip socket: {0}")] GossipBind(std::io::Error), } pub type Result<T, E = Error> = std::result::Result<T, E>; pub struct RpcWriteRouterServerType<D, N> { server: RpcWriteRouterServer<D, N>, shutdown: CancellationToken, trace_collector: Option<Arc<dyn TraceCollector>>, } impl<D, N> RpcWriteRouterServerType<D, N> { pub fn new(server: RpcWriteRouterServer<D, N>, common_state: &CommonServerState) -> Self { Self { server, shutdown: CancellationToken::new(), trace_collector: common_state.trace_collector(), } } } impl<D, N> std::fmt::Debug for RpcWriteRouterServerType<D, N> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Router") } } #[async_trait] impl<D, N> ServerType for RpcWriteRouterServerType<D, N> where D: DmlHandler<WriteInput = HashMap<String, MutableBatch>, WriteOutput = ()> + 'static, N: NamespaceResolver + 'static, { fn name(&self) -> &str { "rpc_write_router" } /// Return the [`metric::Registry`] used by the router. fn metric_registry(&self) -> Arc<Registry> { self.server.metric_registry() } /// Returns the trace collector for router traces. fn trace_collector(&self) -> Option<Arc<dyn TraceCollector>> { self.trace_collector.as_ref().map(Arc::clone) } /// Dispatches `req` to the router [`HttpDelegate`] delegate. /// /// [`HttpDelegate`]: router::server::http::HttpDelegate async fn route_http_request( &self, req: Request<Body>, ) -> Result<Response<Body>, Box<dyn HttpApiErrorSource>> { self.server .http() .route(req) .await .map_err(IoxHttpErrorAdaptor) .map_err(|e| Box::new(e) as _) } /// Registers the services exposed by the router [`RpcWriteGrpcDelegate`] delegate. /// /// [`RpcWriteGrpcDelegate`]: router::server::grpc::RpcWriteGrpcDelegate async fn server_grpc(self: Arc<Self>, builder_input: RpcBuilderInput) -> Result<(), RpcError> { let builder = setup_builder!(builder_input, self); add_service!( builder, schema_service_server::SchemaServiceServer::new(self.server.grpc().schema_service()) ); add_service!( builder, catalog_service_server::CatalogServiceServer::new(self.server.grpc().catalog_service()) ); add_service!( builder, object_store_service_server::ObjectStoreServiceServer::new( self.server.grpc().object_store_service() ) ); add_service!( builder, namespace_service_server::NamespaceServiceServer::new( self.server.grpc().namespace_service() ) ); add_service!( builder, table_service_server::TableServiceServer::new(self.server.grpc().table_service()) ); serve_builder!(builder); Ok(()) } async fn join(self: Arc<Self>) { self.shutdown.cancelled().await; } fn shutdown(&self, frontend: CancellationToken) { frontend.cancel(); self.shutdown.cancel(); } } /// This adaptor converts the `router` http error type into a type that /// satisfies the requirements of ioxd's runner framework, keeping the /// two decoupled. #[derive(Debug)] pub struct IoxHttpErrorAdaptor(router::server::http::Error); impl Display for IoxHttpErrorAdaptor { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Display::fmt(&self.0, f) } } impl std::error::Error for IoxHttpErrorAdaptor {} impl HttpApiErrorSource for IoxHttpErrorAdaptor { fn to_http_api_error(&self) -> HttpApiError { HttpApiError::new(self.0.as_status_code(), self.to_string()) } } /// Instantiate a router server that uses the RPC write path pub async fn create_router_server_type( common_state: &CommonServerState, metrics: Arc<metric::Registry>, catalog: Arc<dyn Catalog>, object_store: Arc<DynObjectStore>, router_config: &RouterConfig, gossip_config: &GossipConfig, trace_context_header_name: String, ) -> Result<Arc<dyn ServerType>> { let ingester_connections = router_config.ingester_addresses.iter().map(|addr| { let addr = addr.to_string(); let endpoint = Endpoint::from_shared(hyper::body::Bytes::from(addr.clone())) .expect("invalid ingester connection address"); ( LazyConnector::new( endpoint, router_config.rpc_write_timeout_seconds, router_config.rpc_write_max_outgoing_bytes, trace_context_header_name.clone(), ), addr, ) }); // Initialise the DML handler that sends writes to the ingester using the RPC write path. let rpc_writer = RpcWrite::new( ingester_connections, router_config.rpc_write_replicas, &metrics, router_config.rpc_write_health_num_probes, ); let rpc_writer = InstrumentationDecorator::new("rpc_writer", &metrics, rpc_writer); // # Namespace cache // // Initialise an instrumented namespace cache to be shared with the schema // validator, and namespace auto-creator that reports cache hit/miss/update // metrics. let ns_cache = Arc::new(InstrumentedCache::new( Arc::new(ShardedCache::new( std::iter::repeat_with(|| Arc::new(MemoryNamespaceCache::default())).take(10), )), &metrics, )); // Pre-warm the cache before adding the gossip layer to avoid broadcasting // the full cache content at startup. pre_warm_schema_cache(&ns_cache, &*catalog) .await .expect("namespace cache pre-warming failed"); // Optionally initialise the schema gossip subsystem. // // The schema gossip primitives sit in the stack of NamespaceCache layers: // // ┌───────────────────────────┐ // │ ReadThroughCache │ // └───────────────────────────┘ // │ // ▼ // ┌───────────────────────────┐ // │ SchemaChangeObserver │◀ ─ ─ ─ ─ // └───────────────────────────┘ │ // │ peers // ▼ ▲ // ┌───────────────────────────┐ │ // │ Incoming Gossip Apply │─ ─ ─ ─ ─ // └───────────────────────────┘ // │ // ▼ // ┌───────────────────────────┐ // │ Underlying Impl │ // └───────────────────────────┘ // // // - SchemaChangeObserver: sends outgoing gossip schema diffs // - NamespaceSchemaGossip: applies incoming gossip diffs locally // // The SchemaChangeObserver is responsible for gossiping any diffs that pass // through it - it MUST sit above the NamespaceSchemaGossip layer // responsible for applying gossip diffs from peers (otherwise the local // node will receive a gossip diff and apply it, which passes through the // diff layer, and causes the local node to gossip it again). // // These gossip layers sit below the catalog lookups, so that they do not // drive catalog queries themselves (defeating the point of the gossiping!). // If a local node has to perform a catalog lookup, it gossips the result to // other peers, helping converge them. let ns_cache = match gossip_config.gossip_bind_address { Some(bind_addr) => { // Initialise the NamespaceSchemaGossip responsible for applying the // incoming gossip schema diffs. let gossip_reader = Arc::new(NamespaceSchemaGossip::new(Arc::clone(&ns_cache))); // Adapt it to the gossip subsystem via the "Dispatcher" trait let dispatcher = GossipMessageDispatcher::new(Arc::clone(&gossip_reader), 100); // Initialise the gossip subsystem, delegating message processing to // the above dispatcher. let handle = gossip::Builder::new( gossip_config.seed_list.clone(), dispatcher, Arc::clone(&metrics), ) .bind(*bind_addr) .await .map_err(Error::GossipBind)?; // Initialise the local diff observer responsible for gossiping any // local changes made to the cache content. // // This sits above / wraps the NamespaceSchemaGossip layer. let ns_cache = SchemaChangeObserver::new(ns_cache, Arc::new(handle)); MaybeLayer::With(ns_cache) } None => MaybeLayer::Without(ns_cache), }; // Wrap the NamespaceCache in a read-through layer that queries the catalog // for cache misses, and populates the local cache with the result. let ns_cache = Arc::new(ReadThroughCache::new(ns_cache, Arc::clone(&catalog))); // # Schema validator // // Initialise and instrument the schema validator let schema_validator = SchemaValidator::new(Arc::clone(&catalog), Arc::clone(&ns_cache), &metrics); let schema_validator = InstrumentationDecorator::new("schema_validator", &metrics, schema_validator); // # Retention validator // // Add a retention validator into handler stack to reject data outside the retention period let retention_validator = RetentionValidator::new(); let retention_validator = InstrumentationDecorator::new("retention_validator", &metrics, retention_validator); // # Write partitioner // // Add a write partitioner into the handler stack that splits by the date // portion of the write's timestamp (the default table partition template) let partitioner = Partitioner::default(); let partitioner = InstrumentationDecorator::new("partitioner", &metrics, partitioner); // # Namespace resolver // // Initialise the Namespace ID lookup + cache let namespace_resolver = NamespaceSchemaResolver::new(Arc::clone(&ns_cache)); let namespace_resolver = NamespaceAutocreation::new( namespace_resolver, Arc::clone(&ns_cache), Arc::clone(&catalog), { if router_config.namespace_autocreation_enabled { MissingNamespaceAction::AutoCreate( router_config .new_namespace_retention_hours .map(|hours| hours as i64 * 60 * 60 * 1_000_000_000), ) } else { MissingNamespaceAction::Reject } }, ); // //////////////////////////////////////////////////////////////////////////// // # Parallel writer let parallel_write = FanOutAdaptor::new(rpc_writer); // # Handler stack // // Build the chain of DML handlers that forms the request processing pipeline let handler_stack = retention_validator .and_then(schema_validator) .and_then(partitioner) // Once writes have been partitioned, they are processed in parallel. // // This block initialises a fan-out adaptor that parallelises partitioned // writes into the handler chain it decorates (schema validation, and then // into the ingester RPC), and instruments the parallelised // operation. .and_then(InstrumentationDecorator::new( "parallel_write", &metrics, parallel_write, )); // Record the overall request handling latency let handler_stack = InstrumentationDecorator::new("request", &metrics, handler_stack); // Initialize the HTTP API delegate let write_request_unifier: Result<Box<dyn WriteRequestUnifier>> = match ( router_config.single_tenant_deployment, &router_config.authz_address, ) { (true, Some(addr)) => { let authz = IoxAuthorizer::connect_lazy(addr.clone()) .map(|c| { Arc::new(AuthorizerInstrumentation::new(&metrics, c)) as Arc<dyn Authorizer> }) .map_err(|source| Error::AuthzConfig { source, addr: addr.clone(), })?; authz.probe().await.expect("Authz connection test failed."); Ok(Box::new(SingleTenantRequestUnifier::new(authz))) } (true, None) => { // Single tenancy was requested, but no auth was provided - the // router's clap flag parse configuration should not allow this // combination to be accepted and therefore execution should // never reach here. unreachable!("INFLUXDB_IOX_SINGLE_TENANCY is set, but could not create an authz service. Check the INFLUXDB_IOX_AUTHZ_ADDR") } (false, None) => Ok(Box::<MultiTenantRequestUnifier>::default()), (false, Some(_)) => { // As above, this combination should be prevented by the // router's clap flag parse configuration. unreachable!("INFLUXDB_IOX_AUTHZ_ADDR is set, but authz only exists for single_tenancy. Check the INFLUXDB_IOX_SINGLE_TENANCY") } }; let http = HttpDelegate::new( common_state.run_config().max_http_request_size, router_config.http_request_limit, namespace_resolver, handler_stack, &metrics, write_request_unifier?, ); // Initialize the gRPC API delegate that creates the services relevant to the RPC // write router path and use it to create the relevant `RpcWriteRouterServer` and // `RpcWriteRouterServerType`. let grpc = RpcWriteGrpcDelegate::new(catalog, object_store); let router_server = RpcWriteRouterServer::new(http, grpc, metrics, common_state.trace_collector()); let server_type = Arc::new(RpcWriteRouterServerType::new(router_server, common_state)); Ok(server_type) } /// Pre-populate `cache` with the all existing schemas in `catalog`. async fn pre_warm_schema_cache<T>( cache: &T, catalog: &dyn Catalog, ) -> Result<(), iox_catalog::interface::Error> where T: NamespaceCache, { iox_catalog::interface::list_schemas(catalog) .await? .for_each(|(ns, schema)| { let name = NamespaceName::try_from(ns.name) .expect("cannot convert existing namespace string to a `NamespaceName` instance"); cache.put_schema(name, schema); }); Ok(()) } #[cfg(test)] mod tests { use data_types::ColumnType; use iox_catalog::{ mem::MemCatalog, test_helpers::{arbitrary_namespace, arbitrary_table}, }; use super::*; #[tokio::test] async fn test_pre_warm_cache() { let catalog = Arc::new(MemCatalog::new(Default::default())); let mut repos = catalog.repositories().await; let namespace = arbitrary_namespace(&mut *repos, "test_ns").await; let table = arbitrary_table(&mut *repos, "name", &namespace).await; let _column = repos .columns() .create_or_get("name", table.id, ColumnType::U64) .await .unwrap(); drop(repos); // Or it'll deadlock. let cache = Arc::new(MemoryNamespaceCache::default()); pre_warm_schema_cache(&cache, &*catalog) .await .expect("pre-warming failed"); let name = NamespaceName::new("test_ns").unwrap(); let got = cache .get_schema(&name) .await .expect("should contain a schema"); assert!(got.tables.get("name").is_some()); } }
pub mod assembler; pub mod instructions; pub mod repl; pub mod vm; extern crate nom; fn main() { let mut r = repl::REPL::new(); r.run(); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn CryptSIPAddProvider(psnewprov: *mut SIP_ADD_NEWPROVIDER) -> super::super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CryptSIPAddProvider(psnewprov: *mut SIP_ADD_NEWPROVIDER) -> super::super::super::Foundation::BOOL; } ::core::mem::transmute(CryptSIPAddProvider(::core::mem::transmute(psnewprov))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] #[inline] pub unsafe fn CryptSIPCreateIndirectData(psubjectinfo: *mut SIP_SUBJECTINFO, pcbindirectdata: *mut u32, pindirectdata: *mut SIP_INDIRECT_DATA) -> super::super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CryptSIPCreateIndirectData(psubjectinfo: *mut SIP_SUBJECTINFO, pcbindirectdata: *mut u32, pindirectdata: *mut SIP_INDIRECT_DATA) -> super::super::super::Foundation::BOOL; } ::core::mem::transmute(CryptSIPCreateIndirectData(::core::mem::transmute(psubjectinfo), ::core::mem::transmute(pcbindirectdata), ::core::mem::transmute(pindirectdata))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] #[inline] pub unsafe fn CryptSIPGetCaps(psubjinfo: *const SIP_SUBJECTINFO, pcaps: *mut SIP_CAP_SET_V3) -> super::super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CryptSIPGetCaps(psubjinfo: *const SIP_SUBJECTINFO, pcaps: *mut SIP_CAP_SET_V3) -> super::super::super::Foundation::BOOL; } ::core::mem::transmute(CryptSIPGetCaps(::core::mem::transmute(psubjinfo), ::core::mem::transmute(pcaps))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] #[inline] pub unsafe fn CryptSIPGetSealedDigest(psubjectinfo: *const SIP_SUBJECTINFO, psig: *const u8, dwsig: u32, pbdigest: *mut u8, pcbdigest: *mut u32) -> super::super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CryptSIPGetSealedDigest(psubjectinfo: *const SIP_SUBJECTINFO, psig: *const u8, dwsig: u32, pbdigest: *mut u8, pcbdigest: *mut u32) -> super::super::super::Foundation::BOOL; } ::core::mem::transmute(CryptSIPGetSealedDigest(::core::mem::transmute(psubjectinfo), ::core::mem::transmute(psig), ::core::mem::transmute(dwsig), ::core::mem::transmute(pbdigest), ::core::mem::transmute(pcbdigest))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] #[inline] pub unsafe fn CryptSIPGetSignedDataMsg(psubjectinfo: *mut SIP_SUBJECTINFO, pdwencodingtype: *mut super::CERT_QUERY_ENCODING_TYPE, dwindex: u32, pcbsigneddatamsg: *mut u32, pbsigneddatamsg: *mut u8) -> super::super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CryptSIPGetSignedDataMsg(psubjectinfo: *mut SIP_SUBJECTINFO, pdwencodingtype: *mut super::CERT_QUERY_ENCODING_TYPE, dwindex: u32, pcbsigneddatamsg: *mut u32, pbsigneddatamsg: *mut u8) -> super::super::super::Foundation::BOOL; } ::core::mem::transmute(CryptSIPGetSignedDataMsg(::core::mem::transmute(psubjectinfo), ::core::mem::transmute(pdwencodingtype), ::core::mem::transmute(dwindex), ::core::mem::transmute(pcbsigneddatamsg), ::core::mem::transmute(pbsigneddatamsg))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] #[inline] pub unsafe fn CryptSIPLoad(pgsubject: *const ::windows::core::GUID, dwflags: u32, psipdispatch: *mut SIP_DISPATCH_INFO) -> super::super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CryptSIPLoad(pgsubject: *const ::windows::core::GUID, dwflags: u32, psipdispatch: *mut ::core::mem::ManuallyDrop<SIP_DISPATCH_INFO>) -> super::super::super::Foundation::BOOL; } ::core::mem::transmute(CryptSIPLoad(::core::mem::transmute(pgsubject), ::core::mem::transmute(dwflags), ::core::mem::transmute(psipdispatch))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] #[inline] pub unsafe fn CryptSIPPutSignedDataMsg(psubjectinfo: *mut SIP_SUBJECTINFO, dwencodingtype: super::CERT_QUERY_ENCODING_TYPE, pdwindex: *mut u32, cbsigneddatamsg: u32, pbsigneddatamsg: *mut u8) -> super::super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CryptSIPPutSignedDataMsg(psubjectinfo: *mut SIP_SUBJECTINFO, dwencodingtype: super::CERT_QUERY_ENCODING_TYPE, pdwindex: *mut u32, cbsigneddatamsg: u32, pbsigneddatamsg: *mut u8) -> super::super::super::Foundation::BOOL; } ::core::mem::transmute(CryptSIPPutSignedDataMsg(::core::mem::transmute(psubjectinfo), ::core::mem::transmute(dwencodingtype), ::core::mem::transmute(pdwindex), ::core::mem::transmute(cbsigneddatamsg), ::core::mem::transmute(pbsigneddatamsg))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn CryptSIPRemoveProvider(pgprov: *mut ::windows::core::GUID) -> super::super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CryptSIPRemoveProvider(pgprov: *mut ::windows::core::GUID) -> super::super::super::Foundation::BOOL; } ::core::mem::transmute(CryptSIPRemoveProvider(::core::mem::transmute(pgprov))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] #[inline] pub unsafe fn CryptSIPRemoveSignedDataMsg(psubjectinfo: *mut SIP_SUBJECTINFO, dwindex: u32) -> super::super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CryptSIPRemoveSignedDataMsg(psubjectinfo: *mut SIP_SUBJECTINFO, dwindex: u32) -> super::super::super::Foundation::BOOL; } ::core::mem::transmute(CryptSIPRemoveSignedDataMsg(::core::mem::transmute(psubjectinfo), ::core::mem::transmute(dwindex))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn CryptSIPRetrieveSubjectGuid<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::HANDLE>>(filename: Param0, hfilein: Param1, pgsubject: *mut ::windows::core::GUID) -> super::super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CryptSIPRetrieveSubjectGuid(filename: super::super::super::Foundation::PWSTR, hfilein: super::super::super::Foundation::HANDLE, pgsubject: *mut ::windows::core::GUID) -> super::super::super::Foundation::BOOL; } ::core::mem::transmute(CryptSIPRetrieveSubjectGuid(filename.into_param().abi(), hfilein.into_param().abi(), ::core::mem::transmute(pgsubject))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn CryptSIPRetrieveSubjectGuidForCatalogFile<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::HANDLE>>(filename: Param0, hfilein: Param1, pgsubject: *mut ::windows::core::GUID) -> super::super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CryptSIPRetrieveSubjectGuidForCatalogFile(filename: super::super::super::Foundation::PWSTR, hfilein: super::super::super::Foundation::HANDLE, pgsubject: *mut ::windows::core::GUID) -> super::super::super::Foundation::BOOL; } ::core::mem::transmute(CryptSIPRetrieveSubjectGuidForCatalogFile(filename.into_param().abi(), hfilein.into_param().abi(), ::core::mem::transmute(pgsubject))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] #[inline] pub unsafe fn CryptSIPVerifyIndirectData(psubjectinfo: *mut SIP_SUBJECTINFO, pindirectdata: *mut SIP_INDIRECT_DATA) -> super::super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CryptSIPVerifyIndirectData(psubjectinfo: *mut SIP_SUBJECTINFO, pindirectdata: *mut SIP_INDIRECT_DATA) -> super::super::super::Foundation::BOOL; } ::core::mem::transmute(CryptSIPVerifyIndirectData(::core::mem::transmute(psubjectinfo), ::core::mem::transmute(pindirectdata))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } pub const MSSIP_FLAGS_MULTI_HASH: u32 = 262144u32; pub const MSSIP_FLAGS_PROHIBIT_RESIZE_ON_CREATE: u32 = 65536u32; pub const MSSIP_FLAGS_USE_CATALOG: u32 = 131072u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct MS_ADDINFO_BLOB { pub cbStruct: u32, pub cbMemObject: u32, pub pbMemObject: *mut u8, pub cbMemSignedMsg: u32, pub pbMemSignedMsg: *mut u8, } impl MS_ADDINFO_BLOB {} impl ::core::default::Default for MS_ADDINFO_BLOB { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for MS_ADDINFO_BLOB { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MS_ADDINFO_BLOB").field("cbStruct", &self.cbStruct).field("cbMemObject", &self.cbMemObject).field("pbMemObject", &self.pbMemObject).field("cbMemSignedMsg", &self.cbMemSignedMsg).field("pbMemSignedMsg", &self.pbMemSignedMsg).finish() } } impl ::core::cmp::PartialEq for MS_ADDINFO_BLOB { fn eq(&self, other: &Self) -> bool { self.cbStruct == other.cbStruct && self.cbMemObject == other.cbMemObject && self.pbMemObject == other.pbMemObject && self.cbMemSignedMsg == other.cbMemSignedMsg && self.pbMemSignedMsg == other.pbMemSignedMsg } } impl ::core::cmp::Eq for MS_ADDINFO_BLOB {} unsafe impl ::windows::core::Abi for MS_ADDINFO_BLOB { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] pub struct MS_ADDINFO_CATALOGMEMBER { pub cbStruct: u32, pub pStore: *mut super::Catalog::CRYPTCATSTORE, pub pMember: *mut super::Catalog::CRYPTCATMEMBER, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl MS_ADDINFO_CATALOGMEMBER {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::default::Default for MS_ADDINFO_CATALOGMEMBER { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::fmt::Debug for MS_ADDINFO_CATALOGMEMBER { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MS_ADDINFO_CATALOGMEMBER").field("cbStruct", &self.cbStruct).field("pStore", &self.pStore).field("pMember", &self.pMember).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::cmp::PartialEq for MS_ADDINFO_CATALOGMEMBER { fn eq(&self, other: &Self) -> bool { self.cbStruct == other.cbStruct && self.pStore == other.pStore && self.pMember == other.pMember } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::cmp::Eq for MS_ADDINFO_CATALOGMEMBER {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] unsafe impl ::windows::core::Abi for MS_ADDINFO_CATALOGMEMBER { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct MS_ADDINFO_FLAT { pub cbStruct: u32, pub pIndirectData: *mut SIP_INDIRECT_DATA, } #[cfg(feature = "Win32_Foundation")] impl MS_ADDINFO_FLAT {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for MS_ADDINFO_FLAT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for MS_ADDINFO_FLAT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("MS_ADDINFO_FLAT").field("cbStruct", &self.cbStruct).field("pIndirectData", &self.pIndirectData).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for MS_ADDINFO_FLAT { fn eq(&self, other: &Self) -> bool { self.cbStruct == other.cbStruct && self.pIndirectData == other.pIndirectData } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for MS_ADDINFO_FLAT {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for MS_ADDINFO_FLAT { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct SIP_ADD_NEWPROVIDER { pub cbStruct: u32, pub pgSubject: *mut ::windows::core::GUID, pub pwszDLLFileName: super::super::super::Foundation::PWSTR, pub pwszMagicNumber: super::super::super::Foundation::PWSTR, pub pwszIsFunctionName: super::super::super::Foundation::PWSTR, pub pwszGetFuncName: super::super::super::Foundation::PWSTR, pub pwszPutFuncName: super::super::super::Foundation::PWSTR, pub pwszCreateFuncName: super::super::super::Foundation::PWSTR, pub pwszVerifyFuncName: super::super::super::Foundation::PWSTR, pub pwszRemoveFuncName: super::super::super::Foundation::PWSTR, pub pwszIsFunctionNameFmt2: super::super::super::Foundation::PWSTR, pub pwszGetCapFuncName: super::super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl SIP_ADD_NEWPROVIDER {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for SIP_ADD_NEWPROVIDER { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for SIP_ADD_NEWPROVIDER { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SIP_ADD_NEWPROVIDER") .field("cbStruct", &self.cbStruct) .field("pgSubject", &self.pgSubject) .field("pwszDLLFileName", &self.pwszDLLFileName) .field("pwszMagicNumber", &self.pwszMagicNumber) .field("pwszIsFunctionName", &self.pwszIsFunctionName) .field("pwszGetFuncName", &self.pwszGetFuncName) .field("pwszPutFuncName", &self.pwszPutFuncName) .field("pwszCreateFuncName", &self.pwszCreateFuncName) .field("pwszVerifyFuncName", &self.pwszVerifyFuncName) .field("pwszRemoveFuncName", &self.pwszRemoveFuncName) .field("pwszIsFunctionNameFmt2", &self.pwszIsFunctionNameFmt2) .field("pwszGetCapFuncName", &self.pwszGetCapFuncName) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for SIP_ADD_NEWPROVIDER { fn eq(&self, other: &Self) -> bool { self.cbStruct == other.cbStruct && self.pgSubject == other.pgSubject && self.pwszDLLFileName == other.pwszDLLFileName && self.pwszMagicNumber == other.pwszMagicNumber && self.pwszIsFunctionName == other.pwszIsFunctionName && self.pwszGetFuncName == other.pwszGetFuncName && self.pwszPutFuncName == other.pwszPutFuncName && self.pwszCreateFuncName == other.pwszCreateFuncName && self.pwszVerifyFuncName == other.pwszVerifyFuncName && self.pwszRemoveFuncName == other.pwszRemoveFuncName && self.pwszIsFunctionNameFmt2 == other.pwszIsFunctionNameFmt2 && self.pwszGetCapFuncName == other.pwszGetCapFuncName } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for SIP_ADD_NEWPROVIDER {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for SIP_ADD_NEWPROVIDER { type Abi = Self; } pub const SIP_CAP_FLAG_SEALING: u32 = 1u32; pub const SIP_CAP_SET_CUR_VER: u32 = 3u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct SIP_CAP_SET_V2 { pub cbSize: u32, pub dwVersion: u32, pub isMultiSign: super::super::super::Foundation::BOOL, pub dwReserved: u32, } #[cfg(feature = "Win32_Foundation")] impl SIP_CAP_SET_V2 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for SIP_CAP_SET_V2 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for SIP_CAP_SET_V2 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SIP_CAP_SET_V2").field("cbSize", &self.cbSize).field("dwVersion", &self.dwVersion).field("isMultiSign", &self.isMultiSign).field("dwReserved", &self.dwReserved).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for SIP_CAP_SET_V2 { fn eq(&self, other: &Self) -> bool { self.cbSize == other.cbSize && self.dwVersion == other.dwVersion && self.isMultiSign == other.isMultiSign && self.dwReserved == other.dwReserved } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for SIP_CAP_SET_V2 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for SIP_CAP_SET_V2 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct SIP_CAP_SET_V3 { pub cbSize: u32, pub dwVersion: u32, pub isMultiSign: super::super::super::Foundation::BOOL, pub Anonymous: SIP_CAP_SET_V3_0, } #[cfg(feature = "Win32_Foundation")] impl SIP_CAP_SET_V3 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for SIP_CAP_SET_V3 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for SIP_CAP_SET_V3 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for SIP_CAP_SET_V3 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for SIP_CAP_SET_V3 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union SIP_CAP_SET_V3_0 { pub dwFlags: u32, pub dwReserved: u32, } #[cfg(feature = "Win32_Foundation")] impl SIP_CAP_SET_V3_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for SIP_CAP_SET_V3_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for SIP_CAP_SET_V3_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for SIP_CAP_SET_V3_0 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for SIP_CAP_SET_V3_0 { type Abi = Self; } pub const SIP_CAP_SET_VERSION_2: u32 = 2u32; pub const SIP_CAP_SET_VERSION_3: u32 = 3u32; #[derive(:: core :: clone :: Clone)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] pub struct SIP_DISPATCH_INFO { pub cbSize: u32, pub hSIP: super::super::super::Foundation::HANDLE, pub pfGet: ::core::option::Option<pCryptSIPGetSignedDataMsg>, pub pfPut: ::core::option::Option<pCryptSIPPutSignedDataMsg>, pub pfCreate: ::core::option::Option<pCryptSIPCreateIndirectData>, pub pfVerify: ::core::option::Option<pCryptSIPVerifyIndirectData>, pub pfRemove: ::core::option::Option<pCryptSIPRemoveSignedDataMsg>, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl SIP_DISPATCH_INFO {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::default::Default for SIP_DISPATCH_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::fmt::Debug for SIP_DISPATCH_INFO { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SIP_DISPATCH_INFO").field("cbSize", &self.cbSize).field("hSIP", &self.hSIP).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::cmp::PartialEq for SIP_DISPATCH_INFO { fn eq(&self, other: &Self) -> bool { self.cbSize == other.cbSize && self.hSIP == other.hSIP && self.pfGet.map(|f| f as usize) == other.pfGet.map(|f| f as usize) && self.pfPut.map(|f| f as usize) == other.pfPut.map(|f| f as usize) && self.pfCreate.map(|f| f as usize) == other.pfCreate.map(|f| f as usize) && self.pfVerify.map(|f| f as usize) == other.pfVerify.map(|f| f as usize) && self.pfRemove.map(|f| f as usize) == other.pfRemove.map(|f| f as usize) } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::cmp::Eq for SIP_DISPATCH_INFO {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] unsafe impl ::windows::core::Abi for SIP_DISPATCH_INFO { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct SIP_INDIRECT_DATA { pub Data: super::CRYPT_ATTRIBUTE_TYPE_VALUE, pub DigestAlgorithm: super::CRYPT_ALGORITHM_IDENTIFIER, pub Digest: super::CRYPTOAPI_BLOB, } #[cfg(feature = "Win32_Foundation")] impl SIP_INDIRECT_DATA {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for SIP_INDIRECT_DATA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for SIP_INDIRECT_DATA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SIP_INDIRECT_DATA").field("Data", &self.Data).field("DigestAlgorithm", &self.DigestAlgorithm).field("Digest", &self.Digest).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for SIP_INDIRECT_DATA { fn eq(&self, other: &Self) -> bool { self.Data == other.Data && self.DigestAlgorithm == other.DigestAlgorithm && self.Digest == other.Digest } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for SIP_INDIRECT_DATA {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for SIP_INDIRECT_DATA { type Abi = Self; } pub const SIP_MAX_MAGIC_NUMBER: u32 = 4u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] pub struct SIP_SUBJECTINFO { pub cbSize: u32, pub pgSubjectType: *mut ::windows::core::GUID, pub hFile: super::super::super::Foundation::HANDLE, pub pwsFileName: super::super::super::Foundation::PWSTR, pub pwsDisplayName: super::super::super::Foundation::PWSTR, pub dwReserved1: u32, pub dwIntVersion: u32, pub hProv: usize, pub DigestAlgorithm: super::CRYPT_ALGORITHM_IDENTIFIER, pub dwFlags: u32, pub dwEncodingType: u32, pub dwReserved2: u32, pub fdwCAPISettings: u32, pub fdwSecuritySettings: u32, pub dwIndex: u32, pub dwUnionChoice: u32, pub Anonymous: SIP_SUBJECTINFO_0, pub pClientData: *mut ::core::ffi::c_void, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl SIP_SUBJECTINFO {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::default::Default for SIP_SUBJECTINFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::cmp::PartialEq for SIP_SUBJECTINFO { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::cmp::Eq for SIP_SUBJECTINFO {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] unsafe impl ::windows::core::Abi for SIP_SUBJECTINFO { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] pub union SIP_SUBJECTINFO_0 { pub psFlat: *mut MS_ADDINFO_FLAT, pub psCatMember: *mut MS_ADDINFO_CATALOGMEMBER, pub psBlob: *mut MS_ADDINFO_BLOB, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl SIP_SUBJECTINFO_0 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::default::Default for SIP_SUBJECTINFO_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::cmp::PartialEq for SIP_SUBJECTINFO_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] impl ::core::cmp::Eq for SIP_SUBJECTINFO_0 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] unsafe impl ::windows::core::Abi for SIP_SUBJECTINFO_0 { type Abi = Self; } pub const SPC_DIGEST_GENERATE_FLAG: u32 = 512u32; pub const SPC_DIGEST_SIGN_EX_FLAG: u32 = 16384u32; pub const SPC_DIGEST_SIGN_FLAG: u32 = 1024u32; pub const SPC_EXC_PE_PAGE_HASHES_FLAG: u32 = 16u32; pub const SPC_INC_PE_DEBUG_INFO_FLAG: u32 = 64u32; pub const SPC_INC_PE_IMPORT_ADDR_TABLE_FLAG: u32 = 32u32; pub const SPC_INC_PE_PAGE_HASHES_FLAG: u32 = 256u32; pub const SPC_INC_PE_RESOURCES_FLAG: u32 = 128u32; pub const SPC_MARKER_CHECK_CURRENTLY_SUPPORTED_FLAGS: u32 = 1u32; pub const SPC_MARKER_CHECK_SKIP_SIP_INDIRECT_DATA_FLAG: u32 = 1u32; pub const SPC_RELAXED_PE_MARKER_CHECK: u32 = 2048u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] pub type pCryptSIPCreateIndirectData = unsafe extern "system" fn(psubjectinfo: *mut SIP_SUBJECTINFO, pcbindirectdata: *mut u32, pindirectdata: *mut SIP_INDIRECT_DATA) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] pub type pCryptSIPGetCaps = unsafe extern "system" fn(psubjinfo: *const SIP_SUBJECTINFO, pcaps: *mut SIP_CAP_SET_V3) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] pub type pCryptSIPGetSealedDigest = unsafe extern "system" fn(psubjectinfo: *const SIP_SUBJECTINFO, psig: *const u8, dwsig: u32, pbdigest: *mut u8, pcbdigest: *mut u32) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] pub type pCryptSIPGetSignedDataMsg = unsafe extern "system" fn(psubjectinfo: *mut SIP_SUBJECTINFO, pdwencodingtype: *mut u32, dwindex: u32, pcbsigneddatamsg: *mut u32, pbsigneddatamsg: *mut u8) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] pub type pCryptSIPPutSignedDataMsg = unsafe extern "system" fn(psubjectinfo: *mut SIP_SUBJECTINFO, dwencodingtype: u32, pdwindex: *mut u32, cbsigneddatamsg: u32, pbsigneddatamsg: *mut u8) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] pub type pCryptSIPRemoveSignedDataMsg = unsafe extern "system" fn(psubjectinfo: *mut SIP_SUBJECTINFO, dwindex: u32) -> super::super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography_Catalog"))] pub type pCryptSIPVerifyIndirectData = unsafe extern "system" fn(psubjectinfo: *mut SIP_SUBJECTINFO, pindirectdata: *mut SIP_INDIRECT_DATA) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub type pfnIsFileSupported = unsafe extern "system" fn(hfile: super::super::super::Foundation::HANDLE, pgsubject: *mut ::windows::core::GUID) -> super::super::super::Foundation::BOOL; #[cfg(feature = "Win32_Foundation")] pub type pfnIsFileSupportedName = unsafe extern "system" fn(pwszfilename: super::super::super::Foundation::PWSTR, pgsubject: *mut ::windows::core::GUID) -> super::super::super::Foundation::BOOL;
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type GattCharacteristic = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct GattCharacteristicProperties(pub u32); impl GattCharacteristicProperties { pub const None: Self = Self(0u32); pub const Broadcast: Self = Self(1u32); pub const Read: Self = Self(2u32); pub const WriteWithoutResponse: Self = Self(4u32); pub const Write: Self = Self(8u32); pub const Notify: Self = Self(16u32); pub const Indicate: Self = Self(32u32); pub const AuthenticatedSignedWrites: Self = Self(64u32); pub const ExtendedProperties: Self = Self(128u32); pub const ReliableWrites: Self = Self(256u32); pub const WritableAuxiliaries: Self = Self(512u32); } impl ::core::marker::Copy for GattCharacteristicProperties {} impl ::core::clone::Clone for GattCharacteristicProperties { fn clone(&self) -> Self { *self } } pub type GattCharacteristicsResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct GattClientCharacteristicConfigurationDescriptorValue(pub i32); impl GattClientCharacteristicConfigurationDescriptorValue { pub const None: Self = Self(0i32); pub const Notify: Self = Self(1i32); pub const Indicate: Self = Self(2i32); } impl ::core::marker::Copy for GattClientCharacteristicConfigurationDescriptorValue {} impl ::core::clone::Clone for GattClientCharacteristicConfigurationDescriptorValue { fn clone(&self) -> Self { *self } } pub type GattClientNotificationResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct GattCommunicationStatus(pub i32); impl GattCommunicationStatus { pub const Success: Self = Self(0i32); pub const Unreachable: Self = Self(1i32); pub const ProtocolError: Self = Self(2i32); pub const AccessDenied: Self = Self(3i32); } impl ::core::marker::Copy for GattCommunicationStatus {} impl ::core::clone::Clone for GattCommunicationStatus { fn clone(&self) -> Self { *self } } pub type GattDescriptor = *mut ::core::ffi::c_void; pub type GattDescriptorsResult = *mut ::core::ffi::c_void; pub type GattDeviceService = *mut ::core::ffi::c_void; pub type GattDeviceServicesResult = *mut ::core::ffi::c_void; pub type GattLocalCharacteristic = *mut ::core::ffi::c_void; pub type GattLocalCharacteristicParameters = *mut ::core::ffi::c_void; pub type GattLocalCharacteristicResult = *mut ::core::ffi::c_void; pub type GattLocalDescriptor = *mut ::core::ffi::c_void; pub type GattLocalDescriptorParameters = *mut ::core::ffi::c_void; pub type GattLocalDescriptorResult = *mut ::core::ffi::c_void; pub type GattLocalService = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct GattOpenStatus(pub i32); impl GattOpenStatus { pub const Unspecified: Self = Self(0i32); pub const Success: Self = Self(1i32); pub const AlreadyOpened: Self = Self(2i32); pub const NotFound: Self = Self(3i32); pub const SharingViolation: Self = Self(4i32); pub const AccessDenied: Self = Self(5i32); } impl ::core::marker::Copy for GattOpenStatus {} impl ::core::clone::Clone for GattOpenStatus { fn clone(&self) -> Self { *self } } pub type GattPresentationFormat = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct GattProtectionLevel(pub i32); impl GattProtectionLevel { pub const Plain: Self = Self(0i32); pub const AuthenticationRequired: Self = Self(1i32); pub const EncryptionRequired: Self = Self(2i32); pub const EncryptionAndAuthenticationRequired: Self = Self(3i32); } impl ::core::marker::Copy for GattProtectionLevel {} impl ::core::clone::Clone for GattProtectionLevel { fn clone(&self) -> Self { *self } } pub type GattReadClientCharacteristicConfigurationDescriptorResult = *mut ::core::ffi::c_void; pub type GattReadRequest = *mut ::core::ffi::c_void; pub type GattReadRequestedEventArgs = *mut ::core::ffi::c_void; pub type GattReadResult = *mut ::core::ffi::c_void; pub type GattReliableWriteTransaction = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct GattRequestState(pub i32); impl GattRequestState { pub const Pending: Self = Self(0i32); pub const Completed: Self = Self(1i32); pub const Canceled: Self = Self(2i32); } impl ::core::marker::Copy for GattRequestState {} impl ::core::clone::Clone for GattRequestState { fn clone(&self) -> Self { *self } } pub type GattRequestStateChangedEventArgs = *mut ::core::ffi::c_void; pub type GattServiceProvider = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct GattServiceProviderAdvertisementStatus(pub i32); impl GattServiceProviderAdvertisementStatus { pub const Created: Self = Self(0i32); pub const Stopped: Self = Self(1i32); pub const Started: Self = Self(2i32); pub const Aborted: Self = Self(3i32); pub const StartedWithoutAllAdvertisementData: Self = Self(4i32); } impl ::core::marker::Copy for GattServiceProviderAdvertisementStatus {} impl ::core::clone::Clone for GattServiceProviderAdvertisementStatus { fn clone(&self) -> Self { *self } } pub type GattServiceProviderAdvertisementStatusChangedEventArgs = *mut ::core::ffi::c_void; pub type GattServiceProviderAdvertisingParameters = *mut ::core::ffi::c_void; pub type GattServiceProviderResult = *mut ::core::ffi::c_void; pub type GattSession = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct GattSessionStatus(pub i32); impl GattSessionStatus { pub const Closed: Self = Self(0i32); pub const Active: Self = Self(1i32); } impl ::core::marker::Copy for GattSessionStatus {} impl ::core::clone::Clone for GattSessionStatus { fn clone(&self) -> Self { *self } } pub type GattSessionStatusChangedEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct GattSharingMode(pub i32); impl GattSharingMode { pub const Unspecified: Self = Self(0i32); pub const Exclusive: Self = Self(1i32); pub const SharedReadOnly: Self = Self(2i32); pub const SharedReadAndWrite: Self = Self(3i32); } impl ::core::marker::Copy for GattSharingMode {} impl ::core::clone::Clone for GattSharingMode { fn clone(&self) -> Self { *self } } pub type GattSubscribedClient = *mut ::core::ffi::c_void; pub type GattValueChangedEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct GattWriteOption(pub i32); impl GattWriteOption { pub const WriteWithResponse: Self = Self(0i32); pub const WriteWithoutResponse: Self = Self(1i32); } impl ::core::marker::Copy for GattWriteOption {} impl ::core::clone::Clone for GattWriteOption { fn clone(&self) -> Self { *self } } pub type GattWriteRequest = *mut ::core::ffi::c_void; pub type GattWriteRequestedEventArgs = *mut ::core::ffi::c_void; pub type GattWriteResult = *mut ::core::ffi::c_void;
const INPUT: &str = include_str!("../../input/01"); fn solution(input: &str) -> i32 { input.lines().filter_map(|x| x.parse::<i32>().ok()).sum() } fn main() { println!("Solution: {}", solution(INPUT)); } #[cfg(test)] mod tests { use super::*; #[test] fn chronal_calibration_part_1() { assert_eq!(574, solution(INPUT)); } }
#[doc = "Reader of register SECWM1R2"] pub type R = crate::R<u32, super::SECWM1R2>; #[doc = "Writer for register SECWM1R2"] pub type W = crate::W<u32, super::SECWM1R2>; #[doc = "Register SECWM1R2 `reset()`'s with value 0x0f00_0f00"] impl crate::ResetValue for super::SECWM1R2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0f00_0f00 } } #[doc = "Reader of field `PCROP1_PSTRT`"] pub type PCROP1_PSTRT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PCROP1_PSTRT`"] pub struct PCROP1_PSTRT_W<'a> { w: &'a mut W, } impl<'a> PCROP1_PSTRT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x7f) | ((value as u32) & 0x7f); self.w } } #[doc = "Reader of field `PCROP1EN`"] pub type PCROP1EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PCROP1EN`"] pub struct PCROP1EN_W<'a> { w: &'a mut W, } impl<'a> PCROP1EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `HDP1_PEND`"] pub type HDP1_PEND_R = crate::R<u8, u8>; #[doc = "Write proxy for field `HDP1_PEND`"] pub struct HDP1_PEND_W<'a> { w: &'a mut W, } impl<'a> HDP1_PEND_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x7f << 16)) | (((value as u32) & 0x7f) << 16); self.w } } #[doc = "Reader of field `HDP1EN`"] pub type HDP1EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HDP1EN`"] pub struct HDP1EN_W<'a> { w: &'a mut W, } impl<'a> HDP1EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bits 0:6 - PCROP1_PSTRT"] #[inline(always)] pub fn pcrop1_pstrt(&self) -> PCROP1_PSTRT_R { PCROP1_PSTRT_R::new((self.bits & 0x7f) as u8) } #[doc = "Bit 15 - PCROP1EN"] #[inline(always)] pub fn pcrop1en(&self) -> PCROP1EN_R { PCROP1EN_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bits 16:22 - HDP1_PEND"] #[inline(always)] pub fn hdp1_pend(&self) -> HDP1_PEND_R { HDP1_PEND_R::new(((self.bits >> 16) & 0x7f) as u8) } #[doc = "Bit 31 - HDP1EN"] #[inline(always)] pub fn hdp1en(&self) -> HDP1EN_R { HDP1EN_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 0:6 - PCROP1_PSTRT"] #[inline(always)] pub fn pcrop1_pstrt(&mut self) -> PCROP1_PSTRT_W { PCROP1_PSTRT_W { w: self } } #[doc = "Bit 15 - PCROP1EN"] #[inline(always)] pub fn pcrop1en(&mut self) -> PCROP1EN_W { PCROP1EN_W { w: self } } #[doc = "Bits 16:22 - HDP1_PEND"] #[inline(always)] pub fn hdp1_pend(&mut self) -> HDP1_PEND_W { HDP1_PEND_W { w: self } } #[doc = "Bit 31 - HDP1EN"] #[inline(always)] pub fn hdp1en(&mut self) -> HDP1EN_W { HDP1EN_W { w: self } } }
use std::sync::{ Once, ONCE_INIT }; use std::intrinsics::abort; use std::{ mem, ptr }; use rand::{ thread_rng, Rng, OsRng }; use errno::{ Errno, set_errno }; const GARBAGE_VALUE: u8 = 0xd0; const CANARY_SIZE: usize = 16; static ALLOC_INIT: Once = ONCE_INIT; static mut PAGE_SIZE: usize = 0; static mut CANARY: [u8; CANARY_SIZE] = [0; CANARY_SIZE]; // -- alloc init -- unsafe fn alloc_init() { #[cfg(unix)] { let page_size = ::libc::sysconf(::libc::_SC_PAGESIZE); if page_size > 0 { PAGE_SIZE = page_size as usize; } } #[cfg(windows)] { let si = mem::uninitialized(); ::kernel32::GetSystemInfo(si); PAGE_SIZE = ptr::read(si).dwPageSize as usize; } if PAGE_SIZE < CANARY_SIZE || PAGE_SIZE < mem::size_of::<usize>() { abort(); } match OsRng::new() { Ok(mut rng) => rng.fill_bytes(&mut CANARY), Err(_) => thread_rng().fill_bytes(&mut CANARY) } } // -- aligned alloc / aligned free -- #[cfg(unix)] unsafe fn alloc_aligned<T>(size: usize) -> Option<*mut T> { let mut memptr = mem::uninitialized(); match ::libc::posix_memalign(&mut memptr, PAGE_SIZE, size) { 0 => Some(memptr as *mut T), ::libc::EINVAL => panic!("EINVAL: invalid alignmen. {}", PAGE_SIZE), ::libc::ENOMEM => None, _ => unreachable!() } } #[cfg(windows)] unsafe fn alloc_aligned<T>(size: usize) -> Option<*mut T> { Some(::kernel32::VirtualAlloc( ptr::null(), size, ::winapi::MEM_COMMIT | ::winapi::MEM_RESERVE, ::winapi::PAGE_READWRITE ) as *mut T) } #[cfg(unix)] unsafe fn free_aligned<T>(memptr: *mut T) { ::libc::free(memptr as *mut ::libc::c_void); } #[cfg(windows)] unsafe fn free_aligned<T>(memptr: *mut T) { ::kernel32::VirtualFree(memptr as ::winapi::LPVOID, 0, ::winapi::MEM_RELEASE); } // -- malloc / free -- #[inline] unsafe fn page_round(size: usize) -> usize { let page_mask = PAGE_SIZE - 1; (size + page_mask) & (!page_mask) } unsafe fn unprotected_ptr_from_user_ptr<T>(memptr: *const T) -> *mut T { let canary_ptr = memptr.offset(-(mem::size_of_val(&CANARY) as isize)); let page_mask = PAGE_SIZE - 1; let unprotected_ptr_u = canary_ptr as usize & !page_mask; if unprotected_ptr_u <= PAGE_SIZE * 2 { abort(); } unprotected_ptr_u as *mut T } unsafe fn _malloc<T>(size: usize) -> Option<*mut T> { ALLOC_INIT.call_once(|| alloc_init()); if size >= ::std::usize::MAX - PAGE_SIZE * 4 { set_errno(Errno(::libc::ENOMEM)); return None; } if PAGE_SIZE <= mem::size_of_val(&CANARY) || PAGE_SIZE < mem::size_of::<usize>() { abort(); } // aligned alloc ptr let size_with_canary = mem::size_of_val(&CANARY) + size; let unprotected_size = page_round(size_with_canary); let total_size = PAGE_SIZE + PAGE_SIZE + unprotected_size + PAGE_SIZE; let base_ptr = match alloc_aligned(total_size) { Some(memptr) => memptr, None => return None }; // canary offset let unprotected_ptr = base_ptr.offset(PAGE_SIZE as isize * 2); ::mprotect(base_ptr.offset(PAGE_SIZE as isize), PAGE_SIZE, ::Prot::NoAccess); ptr::copy( CANARY.as_ptr(), unprotected_ptr.offset(unprotected_size as isize) as *mut u8, mem::size_of_val(&CANARY) ); // mprotect ptr ::mprotect(unprotected_ptr.offset(unprotected_size as isize), PAGE_SIZE, ::Prot::NoAccess); ::mlock(unprotected_ptr, unprotected_size); let canary_ptr = unprotected_ptr .offset(page_round(size_with_canary) as isize) .offset(-(size_with_canary as isize)); let user_ptr = canary_ptr.offset(mem::size_of_val(&CANARY) as isize); ptr::copy(CANARY.as_ptr(), canary_ptr as *mut u8, mem::size_of_val(&CANARY)); ptr::write(base_ptr as *mut usize, unprotected_size); ::mprotect(base_ptr, PAGE_SIZE, ::Prot::ReadOnly); debug_assert_eq!(unprotected_ptr_from_user_ptr(user_ptr), unprotected_ptr); Some(user_ptr) } /// Secure malloc. pub unsafe fn malloc<T>(size: usize) -> Option<*mut T> { _malloc(size) .map(|memptr| { ::memset(memptr, GARBAGE_VALUE as i32, size); memptr }) } /// Alloc array. /// /// ``` /// use std::{ slice, mem }; /// use memsec::{ allocarray, free, memzero, memset, memcmp }; /// /// let memptr: *mut u8 = unsafe { allocarray(8).unwrap() }; /// let array = unsafe { slice::from_raw_parts_mut(memptr, 8) }; /// assert_eq!(array, [0xd0; 8]); /// unsafe { memzero(memptr, 8) }; /// assert_eq!(array, [0; 8]); /// array[0] = 1; /// assert_eq!(unsafe { memcmp(memptr, [1, 0, 0, 0, 0, 0, 0, 0].as_ptr(), 8) }, 0); /// unsafe { free(memptr) }; /// ``` pub unsafe fn allocarray<T>(count: usize) -> Option<*mut T> { let size = mem::size_of::<T>(); if count > mem::size_of::<usize>() && size >= ::std::usize::MAX / count { set_errno(Errno(::libc::ENOMEM)); None } else { malloc(count * size) } } /// Secure free. pub unsafe fn free<T>(memptr: *mut T) { if memptr.is_null() { return () }; // get unprotected ptr let canary_ptr = memptr.offset(-(mem::size_of_val(&CANARY) as isize)); let unprotected_ptr = unprotected_ptr_from_user_ptr(memptr); let base_ptr = unprotected_ptr.offset(-(PAGE_SIZE as isize * 2)); let unprotected_size = ptr::read(base_ptr as *const usize); let total_size = PAGE_SIZE + PAGE_SIZE + unprotected_size + PAGE_SIZE; ::mprotect(base_ptr, total_size, ::Prot::ReadWrite); // check debug_assert_eq!(::memcmp(canary_ptr as *const u8, CANARY.as_ptr(), mem::size_of_val(&CANARY)), 0); debug_assert_eq!(::memcmp( unprotected_ptr.offset(unprotected_size as isize) as *const u8, CANARY.as_ptr(), mem::size_of_val(&CANARY) ), 0); // free ::munlock(unprotected_ptr, unprotected_size); free_aligned(base_ptr); } // -- unprotected mprotect -- /// Secure mprotect. pub unsafe fn unprotected_mprotect<T>(ptr: *mut T, prot: ::Prot) -> bool { let unprotected_ptr = unprotected_ptr_from_user_ptr(ptr); let base_ptr = unprotected_ptr.offset(-(PAGE_SIZE as isize * 2)); let unprotected_size = ptr::read(base_ptr as *const usize); ::mprotect(unprotected_ptr, unprotected_size, prot) } #[cfg(all(unix, test))] mod test { use std::mem; #[should_panic] #[test] fn mprotect_test() { use nix::sys::signal; super::ALLOC_INIT.call_once(|| unsafe { super::alloc_init() }); extern fn sigsegv(_: i32) { panic!() } let sigaction = signal::SigAction::new( signal::SigHandler::Handler(sigsegv), signal::SA_SIGINFO, signal::SigSet::empty(), ); unsafe { signal::sigaction(signal::SIGSEGV, &sigaction).ok() }; let x: *mut u8 = unsafe { super::alloc_aligned(16 * mem::size_of::<u8>()).unwrap() }; unsafe { ::mprotect(x, 16 * mem::size_of::<u8>(), ::Prot::NoAccess) }; unsafe { ::memzero(x, 16 * mem::size_of::<u8>()) }; // SIGSEGV! } }
//! Device module docs. use std::{borrow::Borrow, fmt::Debug}; use resource; use fence::FenceCreateInfo; /// Abstract logical device. /// It inherits methods to allocate memory and create resources. pub trait Device: resource::Device { /// Semaphore type that can be used with this device. type Semaphore: Debug + 'static; /// Fence type that can be used with this device. type Fence: Debug + 'static; /// Finished command buffer that can be submitted to the queues of this device. type Submit: 'static; /// Command pool type that can be used with this device. type CommandPool: 'static; /// Command buffer type that can be used with this device. type CommandBuffer: CommandBuffer<Submit = Self::Submit> + 'static; /// Command queue type that can be used with this device. type CommandQueue: CommandQueue< Semaphore = Self::Semaphore, Fence = Self::Fence, Submit = Self::Submit, > + 'static; /// Create new fence. unsafe fn create_fence(&self, info: FenceCreateInfo) -> Self::Fence; /// Reset fence. unsafe fn reset_fence(&self, fence: &Self::Fence) { self.reset_fences(Some(fence)) } /// Reset multiple fences at once. unsafe fn reset_fences<F>(&self, fences: F) where F: IntoIterator, F::Item: Borrow<Self::Fence>, { fences.into_iter().for_each(|fence| self.reset_fence(fence.borrow())); } } /// Abstract command buffer. /// It defines all methods required to begin/end recording and record commands. pub trait CommandBuffer { /// This type is `Device::CommandBuffer` of device that created pool from which this buffer is allocated. /// Raw command buffer can be cloned. type Submit; /// Get submittable object. /// Buffer must be in executable state. unsafe fn submit(&self) -> Self::Submit; } impl<'a, B: 'a> CommandBuffer for &'a mut B where B: CommandBuffer, { type Submit = B::Submit; unsafe fn submit(&self) -> B::Submit { B::submit(&**self) } } /// Abstract command queue. /// It defines methods for submitting command buffers along with semaphores and fences. pub trait CommandQueue { /// Semaphore type that can be used with this device. type Semaphore: Debug + 'static; /// Fence type that can be used with this device. type Fence: Debug + 'static; /// Finished command buffer that can be submitted to the queue. type Submit: 'static; } impl<'a, Q: 'a> CommandQueue for &'a mut Q where Q: CommandQueue, { type Semaphore = Q::Semaphore; type Fence = Q::Fence; type Submit = Q::Submit; }
#![allow(non_snake_case, non_camel_case_types, dead_code)] #[repr(C)] pub struct stbtt__buf{ data: *mut u8, cursor: i32, size: i32, } #[inline] pub const fn new_stbtt__buf()->stbtt__buf{ stbtt__buf{ data: std::ptr::null_mut(), cursor: 0, size: 0, } } #[repr(C)] pub struct stbtt_fontinfo{ userdata: *mut std::ffi::c_void, pub data: *mut u8, // pointer to .ttf file fontstart: i32, // offset of start of font umGlyphs: i32, // number of glyphs, needed for range checking loca: i32, head: i32, glyf: i32, hhea: i32, hmtx: i32, kern: i32, gpos: i32, // table locations as offset from start of .ttf index_map: i32, // a cmap mapping for our chosen character encoding indexToLocFormat: i32, // format needed to map from glyph index to glyph cff: stbtt__buf, // cff font data charstrings: stbtt__buf, // the charstring index gsubrs: stbtt__buf, // global charstring subroutines index subrs: stbtt__buf, // private charstring subroutines index fontdicts: stbtt__buf, // array of font dicts fdselect: stbtt__buf, // map from glyph to fontdict } #[inline] pub const fn new_stbtt_fontinfo()->stbtt_fontinfo{ stbtt_fontinfo{ userdata: std::ptr::null_mut(), data: std::ptr::null_mut(), // pointer to .ttf file fontstart: 0, // offset of start of font umGlyphs: 0, // number of glyphs, needed for range checking loca: 0, head: 0, glyf: 0, hhea: 0, hmtx: 0, kern: 0, gpos: 0, // table locations as offset from start of .ttf index_map: 0, // a cmap mapping for our chosen character encoding indexToLocFormat: 0, // format needed to map from glyph index to glyph cff: new_stbtt__buf(), // cff font data charstrings: new_stbtt__buf(), // the charstring index gsubrs: new_stbtt__buf(), // global charstring subroutines index subrs: new_stbtt__buf(), // private charstring subroutines index fontdicts: new_stbtt__buf(), // array of font dicts fdselect: new_stbtt__buf(), // map from glyph to fontdict } } pub fn new__buf()->stbtt__buf{ stbtt__buf{ data: std::ptr::null_mut(), cursor: 0, size: 0, } } pub fn new_fontinfo()->stbtt_fontinfo{ stbtt_fontinfo{ userdata: std::ptr::null_mut(), data: std::ptr::null_mut(), fontstart: 0, umGlyphs: 0, loca: 0, head: 0, glyf: 0, hhea: 0, hmtx: 0, kern: 0, gpos: 0, index_map: 0, indexToLocFormat: 0, cff: new__buf(), // cff font data charstrings: new__buf(), // the charstring index gsubrs: new__buf(), // global charstring subroutines index subrs: new__buf(), // private charstring subroutines index fontdicts: new__buf(), // array of font dicts fdselect: new__buf(), // map from glyph to fontdict } } extern{ pub fn stbtt_InitFont(font: *mut stbtt_fontinfo, buffer: *const u8, offset: i32)->i32; pub fn stbtt_ScaleForPixelHeight(font : *const stbtt_fontinfo, size: f32)->f32; pub fn stbtt_GetFontVMetrics(font: *const stbtt_fontinfo, ascent: *mut i32, descent: *mut i32, lineGap: *mut i32); pub fn stbtt_GetCodepointHMetrics(font: *const stbtt_fontinfo, char: i32, advance: *mut i32, leftSideBearing: *mut i32); pub fn stbtt_GetCodepointBitmapBoxSubpixel(font: *const stbtt_fontinfo, char: i32, scale_x: f32, scale_y: f32, x_shift: f32, y_shift: f32, x0: *mut i32, y0: *mut i32, x1: *mut i32, y1: *mut i32); pub fn stbtt_MakeCodepointBitmapSubpixel(stbtt_fontinfo: *const stbtt_fontinfo, output: *mut u8, out_w: i32, out_h: i32, out_stride: i32, scale_x: f32, scale_y: f32, x_shift: f32, y_shift: f32,codepoint: i32); pub fn stbtt_GetFontBoundingBox( info: *const stbtt_fontinfo, x0: *mut i32, y0: *mut i32, x1: *mut i32, y1: *mut i32); pub fn stbtt_FindGlyphIndex( info: *const stbtt_fontinfo, unicode_codepoint: i32)->i32; pub fn stbtt_GetGlyphHMetrics(info: *const stbtt_fontinfo, glyph_index: i32, advanceWidth: *mut i32, leftSideBearing: *mut i32); pub fn stbtt_GetGlyphBitmapBoxSubpixel(font: *const stbtt_fontinfo, glyph: i32, scale_x: f32, scale_y: f32, x_shift: f32, y_shift: f32, x0: *mut i32, y0: *mut i32, x1: *mut i32, y1: *mut i32); pub fn stbtt_MakeGlyphBitmapSubpixel(stbtt_fontinfo: *const stbtt_fontinfo, output: *mut u8, out_w: i32, out_h: i32, out_stride: i32, scale_x: f32, scale_y: f32, x_shift: f32, y_shift: f32, glyph: i32); }
//! `cargo run --example bulb` fn main() -> Result<(), Box<dyn std::error::Error>> { env_logger::init(); let mut bulb = tplink::Bulb::new([192, 168, 1, 107]); bulb.turn_on()?; assert_eq!(bulb.is_on()?, true); if let Err(e) = bulb.set_brightness(0) { println!("{}", e); } bulb.turn_off()?; assert_eq!(bulb.is_on()?, false); println!("supports brightness: {}", bulb.is_dimmable()?); println!("supports color: {}", bulb.is_color()?); println!("supports color temp: {}", bulb.is_variable_color_temp()?); println!("has emeter: {}", bulb.has_emeter()?); println!("time: {}", bulb.time()?); match bulb.hsv() { Ok(hsv) => println!( "hue: {}, saturation: {}, value: {}", hsv.hue(), hsv.saturation(), hsv.value() ), Err(e) => println!("error: {}", e), } Ok(()) }
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //! Find topocentric coordinates use angle; use coords; use planet; /** Computes the equatorial horizontal parallax of a celestial body # Returns * `eq_hz_parllx`: Equatorial horizontal parallax of the celestial body *| in radians* # Arguments * `dist_to_earth`: The celestial body's distance to the Earth *| in AU* **/ #[inline] pub fn eq_hz_parallax(dist_to_earth: f64) -> f64 { (angle::deg_frm_dms(0, 0, 8.794).to_radians().sin() / dist_to_earth).asin() } /** Computes the topocentric equatorial coordinates of a celestial body # Returns * `topocent_eq_point`: Topocentric equatorial point of the celestial body *| in radians* # Arguments * `eq_point` : Equatorial point of the celestial body *| in radians* * `eq_hz_parllx` : Equatorial horizontal parallax of the celestial body *| in radians* * `geograph_point` : Geographic point of the observer *| in radians* * `observer_ht` : Height of the observer above sea level *| in meters* * `greenw_sidr`: Sidereal time at Greenwhich *| in radians* **/ pub fn topocent_eq_coords(eq_point: &coords::EqPoint, eq_hz_parllx: f64, geograph_point: &coords::GeographPoint, observer_ht: f64, greenw_sidr: f64) -> coords::EqPoint { let (rho_sin, rho_cos) = planet::earth::rho_sin_cos_phi ( geograph_point.lat, observer_ht ); let geocent_hr_angl = coords::hr_angl_frm_observer_long ( greenw_sidr, geograph_point.long, eq_point.asc ); let eq_hz_parllx_sin = eq_hz_parllx.sin(); let del_asc = (-rho_cos * eq_hz_parllx_sin * geocent_hr_angl.sin()).atan2( eq_point.dec.cos() - rho_cos * eq_hz_parllx_sin * geocent_hr_angl.cos() ); let dec_1 = ( (eq_point.dec.sin() - rho_sin * eq_hz_parllx_sin) * del_asc.cos() ).atan2( eq_point.dec.cos() - rho_cos * eq_hz_parllx_sin * geocent_hr_angl.cos() ); coords::EqPoint { asc: eq_point.asc + del_asc, dec: dec_1 } } /** Computes the topocentric ecliptic coordinates of a celestial body # Returns `(topocent_ecl_point, topocent_geocent_semidia)` * `topocent_ecl_point` : Topocentric ecliptic point of the celestial body *| in radians* * `topocent_geocent_semidia`: Topocentric semidiameter of the celestial body *| in radians* # Arguments * `ecl_point` : Ecliptic point of the celestial body *| in radians* * `eq_hz_parllx` : Equatorial horizontal parallax of the celestial body *| in radians* * `geograph_point`: Geographic point of the observer *| in radians* * `observer_ht` : Height of the observer above sea level *| in meters* * `loc_sidr` : Local sidereal time *| in radians* * `eclip_oblq` : Obliquity of the ecliptic *| in radians* * `geocent_semdia` : Geocentric semidiameter of the celestial body *| in radians* **/ pub fn topopcent_ecl_coords(ecl_point: &coords::EclPoint, eq_hz_parllx: f64, geograph_point: &coords::GeographPoint, observer_ht: f64, loc_sidr: f64, eclip_oblq: f64, geocent_semdia: f64) -> (coords::EclPoint, f64) { let (rho_sin, rho_cos) = planet::earth::rho_sin_cos_phi ( geograph_point.lat, observer_ht ); let eq_hz_parllx_sin = eq_hz_parllx.sin(); let loc_sidr_sin = loc_sidr.sin(); let eclip_oblq_sin = eclip_oblq.sin(); let eclip_oblq_cos = eclip_oblq.cos(); let ecl_point_lat_cos = ecl_point.lat.cos(); let N = ecl_point.long.cos() * ecl_point_lat_cos - rho_cos * eq_hz_parllx_sin * loc_sidr.cos(); let ecl_long_1 = ( ecl_point.long.sin() * ecl_point_lat_cos - eq_hz_parllx_sin * ( rho_sin * eclip_oblq_sin + rho_cos * eclip_oblq_cos * loc_sidr_sin ) ).atan2(N); let ecl_lat_1 = ( ecl_long_1.cos() * ( ecl_point.lat.sin() - eq_hz_parllx_sin * ( rho_sin * eclip_oblq_cos - rho_cos * eclip_oblq_sin * loc_sidr_sin ) ) ).atan2(N); let geocent_semdia_1 = ( ecl_long_1.cos() * ecl_lat_1.cos() * geocent_semdia.sin() / N ).asin(); ( coords::EclPoint { long: angle::limit_to_two_PI(ecl_long_1), lat: ecl_lat_1 }, geocent_semdia_1 ) }
pub mod component; pub mod entity; pub mod light; pub mod material; pub mod model; pub mod transform; use std::cell::{Cell, RefCell}; use std::fmt::Debug; use std::rc::{Rc, Weak}; use crate::core::input::Input; use self::component::camera_component::CameraComponent; use self::entity::Entity; use self::light::Light; use self::model::Model; use self::transform::{Transform, TransformData}; pub struct Scene { pub(crate) root_entity: RefCell<Rc<Entity>>, pub(crate) main_camera: RefCell<Weak<CameraComponent>>, id_counter: Cell<u64>, } impl Scene { pub(crate) fn new() -> Rc<Self> { let mut root = Entity::new_root(); let res = Rc::new(Self { root_entity: RefCell::new(Rc::new(Entity::new_root())), main_camera: RefCell::new(Weak::new()), id_counter: Cell::new(0), }); root.scene = Rc::downgrade(&res); *res.root_entity.borrow_mut() = Rc::new(root); res } pub(crate) fn new_entity_id(&self) -> u64 { let res = self.id_counter.get(); self.id_counter.set(res + 1); res } pub fn new_entity(self: &Rc<Self>, name: String) -> Rc<Entity> { Entity::new(self, &self.root_entity.borrow(), name) } pub fn new_entity_with_transform( self: &Rc<Self>, name: String, transform: Transform, ) -> Rc<Entity> { Entity::new_with_transform(self, &self.root_entity.borrow(), name, transform) } pub fn load(&self) { self.root_entity.borrow().load(); } pub(crate) fn collect_renderables(&self) -> (Vec<(TransformData, Rc<Model>)>, Vec<Light>) { profile_function!(); let mut models = Vec::new(); let mut lights = Vec::new(); self.root_entity .borrow() .collect_renderables(&mut models, &mut lights); (models, lights) } pub(crate) fn update(&self, input: &Input, delta: f32) { profile_function!(); self.root_entity.borrow().update(input, delta); } pub(crate) fn set_main_camera(&self, cam: Weak<CameraComponent>) { *self.main_camera.borrow_mut() = cam; } } impl Debug for Scene { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Scene") } }
#[cfg(test)] extern crate statechart; use statechart::interpreter::Interpreter; #[test] fn common_ancestor() { let l = vec![0, 1, 1, 3, 4]; let r = vec![0, 1, 2, 3, 1]; let a = Interpreter::common_ancestor(&l, &r); assert_eq!(a, vec![0, 1]); let a = Interpreter::common_ancestor(&r, &l); assert_eq!(a, vec![0, 1]); let l = vec![0, 1, 1]; let r = vec![0, 1, 1, 2, 0]; let a = Interpreter::common_ancestor(&l, &r); assert_eq!(a, vec![0, 1, 1]); let a = Interpreter::common_ancestor(&r, &l); assert_eq!(a, vec![0, 1, 1]); let l = vec![]; let r = vec![0, 1]; let a = Interpreter::common_ancestor(&l, &r); assert_eq!(a, vec![]); let a = Interpreter::common_ancestor(&r, &l); assert_eq!(a, vec![]); } #[test] fn exit_states() { let l = vec![0, 1, 1, 3, 4]; let r = vec![0, 1, 1]; let exits = Interpreter::exit_states(&l, &r); assert_eq!(exits, vec![vec![0, 1, 1, 3, 4], vec![0, 1, 1, 3]]); let exits = Interpreter::exit_states(&r, &l); assert!(exits.is_empty()); } #[test] fn entry_states() { let l = vec![0, 1, 1]; let r = vec![0, 1, 1, 3, 4]; let entries = Interpreter::entry_states(&l, &r); assert_eq!(entries, vec![vec![0, 1, 1, 3], vec![0, 1, 1, 3, 4]]); let entries = Interpreter::entry_states(&r, &l); assert!(entries.is_empty()); }
use image::DynamicImage; use image::GenericImage; use image::GenericImageView; use image::Rgba; use std::cmp::min; use std::path::PathBuf; use std::time::Instant; fn main() { // 何分の一にするか let mut ratio = String::new(); std::io::stdin().read_line(&mut ratio).ok(); // u32型に変換 let ratio: u32 = ratio.trim().parse().ok().unwrap(); // 入力ファイル名 let mut input_file_name = String::new(); std::io::stdin().read_line(&mut input_file_name).ok(); // 入力するファイルのパスを作成 let input = PathBuf::from(&("./input/".to_string() + &input_file_name.trim())); // 時間計測のための変数 let mut now = Instant::now(); // ファイルの入力 let img_input: DynamicImage = image::open(input).unwrap(); // ファイル入力にかかった時間をログ println!( "Reading the file took {} seconds.", now.elapsed().as_secs_f64() ); // 出力するファイルのファイル名を作成 // 一旦ピリオドで区切る let mut output_file_name_vec: Vec<&str> = input_file_name.split('.').collect(); // 拡張子の直前に after_resize と入れる output_file_name_vec.insert(output_file_name_vec.len() - 1, "after_resize"); // ファイル名 let mut output_file_name = String::new(); for s in output_file_name_vec { output_file_name = output_file_name + "." + s; } // 余分な先頭のピリオドを取り除く output_file_name.remove(0); // 出力先のファイルのパスを作成 let output = PathBuf::from(&("./output/".to_string() + &output_file_name.trim())); // リサイズにかかった時間も計測したいのでnowを更新 now = Instant::now(); // リサイズする let img_output = image_resize(img_input, ratio); // リサイズにかかった時間をログ println!("Resizing took {} seconds.", now.elapsed().as_secs_f64()); // ファイルを出力 img_output.save(output).unwrap(); } // リサイズ関数 // ratio分の1のサイズにする fn image_resize(img_input: DynamicImage, ratio: u32) -> DynamicImage { // 元画像のサイズ let (width, height) = img_input.dimensions(); // 新しい画像のサイズを決める // 割り切れない分は切り上げ let new_width: u32 = (width + ratio - 1) / ratio; let new_height: u32 = (height + ratio - 1) / ratio; // とりあえず画像を生成 let mut img_output = DynamicImage::new_rgb8(new_width, new_height); // 各ピクセルを決定していく for i in 0..new_width { for j in 0..new_height { // 元画像のうち、x座標がi*ratioから(i+1)*ratio-1、y座標がj*ratioから(j+1)*ratio-1までの範囲のピクセルの平均を取る // 一旦u32型で合計を取って、割って、そのあとu8型にまた戻す let mut red: u32 = 0; let mut green: u32 = 0; let mut blue: u32 = 0; let mut alpha: u32 = 0; // widthやheightがratioで割り切れなかった場合は端だけ数が変わるのでそこを加味して上端と下端を設定 let il = i * ratio; let ir = min((i + 1) * ratio, width); let jl = j * ratio; let jr = min((j + 1) * ratio, height); // 一旦足す for x in il..ir { for y in jl..jr { // get_pixelで一つのピクセルを取ってくる let pixel: Rgba<u8> = img_input.get_pixel(x, y); red += pixel[0] as u32; green += pixel[1] as u32; blue += pixel[2] as u32; alpha += pixel[3] as u32; } } // 割って平均を取る red /= (ir - il) * (jr - jl); green /= (ir - il) * (jr - jl); blue /= (ir - il) * (jr - jl); alpha /= (ir - il) * (jr - jl); // 新しい画像に平均値を代入 img_output.put_pixel( i, j, Rgba([red as u8, green as u8, blue as u8, alpha as u8]), ); } } img_output }
use super::Exception; #[repr(C)] #[derive(Clone, Copy, Debug)] pub enum Fault { Syscall, Interrupt, Exception(Exception), } impl Default for Fault { fn default() -> Self { Fault::Syscall } }
use serenity::prelude::*; use serenity::model::prelude::*; use serenity::framework::standard::{ Args, CommandResult, macros::command, }; use serenity::utils::Colour; use requests::ToJson; use std::collections::HashMap; use std::env; use std::time::Instant; use std::sync::mpsc; use std::thread; use std::sync::mpsc::Sender; const BITS_ITEM_COST_VEC: [i32; 18] = [2000, 500, 3000, 300, 8000, 1200, 4000, 1500, 2000, 4000, 200, 12000, 15000, 4000, 4000, 21000, 5000, 1350]; const ITEM_ARRAY: &[&str; 18] = &["God Potion", "Kat Flower", "Heat Core", "Hyper Catalyst Upgrade", "Ultimate Carrot Candy Upgrade", "Colossal Experience Bottle Upgrade", "Jumbo Backpack Upgrade", "Minion Storage X-pender", "Hologram", "Expertise", "Accessory Enrichment Swapper", "Builder's Wand", "Bits Talisman", "Compact", "Cultivating", "Autopet Rules 2-Pack", "Block Zapper", "Kismet Feather"]; const EBOOK: &str = "Enchanted Book"; const ENCHANTS: &[&str; 3] = &["Expertise", "Compact", "Cultivating"]; #[command] pub async fn bits(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let mut fame_rank = args.single::<usize>()?; if fame_rank <= 0 { fame_rank = 1; } else if fame_rank > 11 { fame_rank = 11; } let fame_rank_array: [f32; 11] = [1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 1.8, 1.9, 2.0, 2.04, 2.08]; let hypixel_token = env::var("HYPIXEL_TOKEN") .expect("Expected hypixel token in the environment"); let start = Instant::now(); msg.channel_id.say(&ctx.http, "Working...").await?; let skyblock_bazaar_cookie = format!("https://api.hypixel.net/skyblock/bazaar?key={}", hypixel_token); let response = requests::get(skyblock_bazaar_cookie).unwrap(); let data = response.json().unwrap(); let buy_cookie_price = &data["products"]["BOOSTER_COOKIE"]["sell_summary"][0]["pricePerUnit"].as_f32().unwrap(); let default_bits: f32 = 4800.0 * fame_rank_array[fame_rank - 1]; let default_coins_per_bit = (buy_cookie_price/ default_bits).abs(); // let mojang_response = requests::get("https://api.mojang.com/users/profiles/minecraft/PikachuPals").unwrap(); // let mojang_data = mojang_response.json().unwrap(); // let user_uuid = mojang_data["id"].as_str().unwrap(); // let mut skyblock_request = String::from("https://api.hypixel.net/Skyblock/profiles?key=...&uuid="); // skyblock_request.push_str(&user_uuid); // let response = requests::get(skyblock_request).unwrap(); // let data = response.json().unwrap(); let skyblock_auctions = String::from("https://api.hypixel.net/skyblock/auctions?page=0"); let response = requests::get(skyblock_auctions).unwrap(); let data = response.json().unwrap(); let auction_pages = data["totalPages"].as_i32().unwrap(); let bits_items_lowest_prices = get_lowest_bin_values(auction_pages); let mut bits_item_vec = Vec::with_capacity(ITEM_ARRAY.len()); for (item, price) in bits_items_lowest_prices.iter(){ let index = ITEM_ARRAY.iter().position(|x| x == item).unwrap(); bits_item_vec.push(BitsItemPrices::new(item, BITS_ITEM_COST_VEC[index], *price)); } let cookie_output = format!("*Booster Cookie Price:* `{}`\n*Current $/b:* `{:.1}`\nItems are organised into highest coins per bit.\nᅠᅠ", buy_cookie_price, default_coins_per_bit); let mut output_fields_vec = Vec::with_capacity(32); bits_item_vec.sort_by(|a, b| b.coins_per_bit().cmp(&a.coins_per_bit())); for listing in bits_item_vec { if listing.lowest_cost < 1000000 { output_fields_vec.push((format!("{:.15}", listing.bits_item), format!("BIN: *{}*\n$/b: *{}*\nᅠᅠ", listing.lowest_cost, listing.coins_per_bit()), true,)); } else if listing.lowest_cost < 1010000 { output_fields_vec.push((format!("{:.15}", listing.bits_item), format!("BIN: *{}*\n$/b: *{}*\nᅠᅠ", listing.lowest_cost, listing.coins_per_bit_million_exact()), true,)); } else { output_fields_vec.push((format!("{:.15}", listing.bits_item), format!("BIN: *{}*\n$/b: *{}*\nᅠᅠ", listing.lowest_cost, listing.coins_per_bit_million()), true,)); } } let timed_search = format!("Completed in {:.2?}.", start.elapsed()); let title = format!("Fame Rank: {}", fame_rank); msg.channel_id.send_message(&ctx.http, |m|{ m.content(timed_search); m.embed(|e| { e.title(title); e.description(cookie_output); e.thumbnail("https://i.imgur.com/JNpxJ7I.png"); e.colour(Colour::FOOYOO); e.fields(output_fields_vec); e.footer(|f| { f.text("$/b takes into account auction fees and taxes!"); f }); e }); m }).await?; Ok(()) } #[derive(Hash, Eq, PartialEq, Debug)] struct BitsItemPrices{ bits_item: String, bits_cost: i32, lowest_cost: i32, } impl BitsItemPrices{ fn new(bits_item: &str, bits_cost: i32, lowest_cost: i32) -> BitsItemPrices{ BitsItemPrices {bits_item: bits_item.to_string(), bits_cost: bits_cost, lowest_cost: lowest_cost} } fn coins_per_bit(&self) -> i32 { ((self.lowest_cost as f32 - (self.lowest_cost as f32 * 0.01)) / self.bits_cost as f32).abs() as i32 } fn coins_per_bit_million(&self) -> i32 { ((self.lowest_cost as f32 - (self.lowest_cost as f32 * 0.01) - (self.lowest_cost as f32 * 0.01)) / self.bits_cost as f32).abs() as i32 } fn coins_per_bit_million_exact(&self) -> i32 { ((1000000 as f32 - (self.lowest_cost as f32 * 0.01)) / self.bits_cost as f32).abs() as i32 } } fn get_lowest_bin_values(auction_pages: i32) -> HashMap<String, i32>{ let mut lowest_prices: HashMap<String, i32> = HashMap::new(); for item in ITEM_ARRAY.iter(){ lowest_prices.insert(item.to_string(), 999999999); } let mut sender_vector: Vec<Sender<i32>> = Vec::with_capacity(ITEM_ARRAY.len()); let mut receiver_vector = Vec::with_capacity(ITEM_ARRAY.len()); for _n in 0..ITEM_ARRAY.len(){ let (tx, rx) = mpsc::channel(); sender_vector.push(tx); receiver_vector.push(rx); } let mut handles = vec![]; let mut threads_pages: Vec<i32> = vec![0]; let threads: i32 = 8; let pages_per_thread: i32 = auction_pages / threads; let rem_pages: i32 = auction_pages % threads; for thread in 1..=threads{ if thread != threads{ threads_pages.push(thread * pages_per_thread); } else{ threads_pages.push((thread * pages_per_thread) + rem_pages); } } for i in 0..threads_pages.len() - 1 { let mut sender_vector_clone: Vec<Sender<i32>> = Vec::with_capacity(ITEM_ARRAY.len()); let start_page = threads_pages[i].clone(); let end_page = threads_pages[i + 1].clone(); for tx in &sender_vector{ let tx_clone = tx.clone(); sender_vector_clone.push(tx_clone); } let handle = thread::spawn(move || work_thread(sender_vector_clone, start_page, end_page)); handles.push(handle); } for handle in handles{ handle.join().unwrap(); } for sender in sender_vector{ drop(sender); } for item in ITEM_ARRAY.iter() { let index = ITEM_ARRAY.iter().position(|x| x == item).unwrap(); for price in &receiver_vector[index]{ if price < *lowest_prices.get(&item.to_string()).unwrap() { lowest_prices.insert(item.to_string(), price); } } } return lowest_prices; } fn work_thread(sender_vector: Vec<Sender<i32>>, i: i32, e: i32){ for page in i..e{ let mut page_auctions = String::from(" https://api.hypixel.net/skyblock/auctions?page="); let page_number = page.to_string(); page_auctions.push_str(&page_number); let response = requests::get(page_auctions).unwrap(); let data = response.json().unwrap(); for auc in data["auctions"].members(){ for auc_item in ITEM_ARRAY.iter() { if auc["bin"].as_bool() != None{ if &auc["item_name"].as_str().unwrap() == auc_item { let index = ITEM_ARRAY.iter().position(|x| x == auc_item).unwrap(); let auc_item_price = auc["starting_bid"].as_i32().unwrap(); sender_vector[index].send(auc_item_price).unwrap(); } else if auc["item_name"].as_str().unwrap() == EBOOK { for enchant in ENCHANTS.iter() { if auc["item_lore"].as_str().unwrap().contains(enchant){ let index = ITEM_ARRAY.iter().position(|x| x == enchant).unwrap(); let auc_item_price = auc["starting_bid"].as_i32().unwrap(); sender_vector[index].send(auc_item_price).unwrap(); } } } } } } } }
#[ic_cdk_macros::query] fn print() { ic_cdk::print("Hello World"); }
#[derive(Clone)] pub struct Timer { interrupt: u8, div: u8, tima: u8, tma: u8, tac: u8, } impl Timer { pub fn init() -> Self { Self { interrupt: 0, div: 0, tima: 0, tma: 0, tac: 0, } } } impl Timer { pub fn step(&mut self, cycles: usize) { // TODO: idk } pub fn get_interrupt(&mut self) -> u8 { let ret = self.interrupt; self.interrupt = 0; ret } } impl Timer { pub fn read_io_byte(&self, idx: u16) -> u8 { match idx { 0xff04 => self.div, 0xff05 => self.tima, 0xff06 => self.tma, 0xff07 => self.tac, _ => { //println!("Unhandled Timer Read from Address [{:#04x?}]", idx); 0 } } } pub fn write_io_byte(&mut self, idx: u16, val: u8) { match idx { 0xff04 => self.div = 0x00, 0xff05 => self.tima = val, 0xff06 => self.tma = val, 0xff07 => self.tac = val, _ => { println!("Unhandled Timer Read from Address [{:#04x?}] [{:#02x?}]", idx, val); } } } }
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //prior to fixing `everybody_loops` to preserve items, rustdoc would crash on this file, as it //didn't see that `SomeStruct` implemented `Clone` //FIXME(misdreavus): whenever rustdoc shows traits impl'd inside bodies, make sure this test //reflects that pub struct Bounded<T: Clone>(T); pub struct SomeStruct; fn asdf() -> Bounded<SomeStruct> { impl Clone for SomeStruct { fn clone(&self) -> SomeStruct { SomeStruct } } Bounded(SomeStruct) }
#![feature(test)] use rand; extern crate test; #[macro_use] extern crate morgan; use rand::seq::SliceRandom; use rand::{thread_rng, Rng}; use morgan::blockBufferPool::{get_tmp_ledger_path, Blocktree}; use morgan::entryInfo::{make_large_test_entries, make_tiny_test_entries, EntrySlice}; use morgan::packet::{Blob, BLOB_HEADER_SIZE}; use test::Bencher; // Given some blobs and a ledger at ledger_path, benchmark writing the blobs to the ledger fn bench_write_blobs(bench: &mut Bencher, blobs: &mut Vec<Blob>, ledger_path: &str) { let blocktree = Blocktree::open(&ledger_path).expect("Expected to be able to open database ledger"); let num_blobs = blobs.len(); bench.iter(move || { for blob in blobs.iter_mut() { let index = blob.index(); blocktree .put_data_blob_bytes( blob.slot(), index, &blob.data[..BLOB_HEADER_SIZE + blob.size()], ) .unwrap(); blob.set_index(index + num_blobs as u64); } }); Blocktree::destroy(&ledger_path).expect("Expected successful database destruction"); } // Insert some blobs into the ledger in preparation for read benchmarks fn setup_read_bench( blocktree: &mut Blocktree, num_small_blobs: u64, num_large_blobs: u64, slot: u64, ) { // Make some big and small entries let mut entries = make_large_test_entries(num_large_blobs as usize); entries.extend(make_tiny_test_entries(num_small_blobs as usize)); // Convert the entries to blobs, write the blobs to the ledger let mut blobs = entries.to_blobs(); for (index, b) in blobs.iter_mut().enumerate() { b.set_index(index as u64); b.set_slot(slot); } blocktree .write_blobs(&blobs) .expect("Expectd successful insertion of blobs into ledger"); } // Write small blobs to the ledger #[bench] #[ignore] fn bench_write_small(bench: &mut Bencher) { let ledger_path = get_tmp_ledger_path!(); let num_entries = 32 * 1024; let entries = make_tiny_test_entries(num_entries); let mut blobs = entries.to_blobs(); for (index, b) in blobs.iter_mut().enumerate() { b.set_index(index as u64); } bench_write_blobs(bench, &mut blobs, &ledger_path); } // Write big blobs to the ledger #[bench] #[ignore] fn bench_write_big(bench: &mut Bencher) { let ledger_path = get_tmp_ledger_path!(); let num_entries = 32 * 1024; let entries = make_large_test_entries(num_entries); let mut blobs = entries.to_blobs(); for (index, b) in blobs.iter_mut().enumerate() { b.set_index(index as u64); } bench_write_blobs(bench, &mut blobs, &ledger_path); } #[bench] #[ignore] fn bench_read_sequential(bench: &mut Bencher) { let ledger_path = get_tmp_ledger_path!(); let mut blocktree = Blocktree::open(&ledger_path).expect("Expected to be able to open database ledger"); // Insert some big and small blobs into the ledger let num_small_blobs = 32 * 1024; let num_large_blobs = 32 * 1024; let total_blobs = num_small_blobs + num_large_blobs; let slot = 0; setup_read_bench(&mut blocktree, num_small_blobs, num_large_blobs, slot); let num_reads = total_blobs / 15; let mut rng = rand::thread_rng(); bench.iter(move || { // Generate random starting point in the range [0, total_blobs - 1], read num_reads blobs sequentially let start_index = rng.gen_range(0, num_small_blobs + num_large_blobs); for i in start_index..start_index + num_reads { let _ = blocktree.get_data_blob(slot, i as u64 % total_blobs); } }); Blocktree::destroy(&ledger_path).expect("Expected successful database destruction"); } #[bench] #[ignore] fn bench_read_random(bench: &mut Bencher) { let ledger_path = get_tmp_ledger_path!(); let mut blocktree = Blocktree::open(&ledger_path).expect("Expected to be able to open database ledger"); // Insert some big and small blobs into the ledger let num_small_blobs = 32 * 1024; let num_large_blobs = 32 * 1024; let total_blobs = num_small_blobs + num_large_blobs; let slot = 0; setup_read_bench(&mut blocktree, num_small_blobs, num_large_blobs, slot); let num_reads = total_blobs / 15; // Generate a num_reads sized random sample of indexes in range [0, total_blobs - 1], // simulating random reads let mut rng = rand::thread_rng(); let indexes: Vec<usize> = (0..num_reads) .map(|_| rng.gen_range(0, total_blobs) as usize) .collect(); bench.iter(move || { for i in indexes.iter() { let _ = blocktree.get_data_blob(slot, *i as u64); } }); Blocktree::destroy(&ledger_path).expect("Expected successful database destruction"); } #[bench] #[ignore] fn bench_insert_data_blob_small(bench: &mut Bencher) { let ledger_path = get_tmp_ledger_path!(); let blocktree = Blocktree::open(&ledger_path).expect("Expected to be able to open database ledger"); let num_entries = 32 * 1024; let entries = make_tiny_test_entries(num_entries); let mut blobs = entries.to_blobs(); blobs.shuffle(&mut thread_rng()); bench.iter(move || { for blob in blobs.iter_mut() { let index = blob.index(); blob.set_index(index + num_entries as u64); } blocktree.write_blobs(&blobs).unwrap(); }); Blocktree::destroy(&ledger_path).expect("Expected successful database destruction"); } #[bench] #[ignore] fn bench_insert_data_blob_big(bench: &mut Bencher) { let ledger_path = get_tmp_ledger_path!(); let blocktree = Blocktree::open(&ledger_path).expect("Expected to be able to open database ledger"); let num_entries = 32 * 1024; let entries = make_large_test_entries(num_entries); let mut shared_blobs = entries.to_shared_blobs(); shared_blobs.shuffle(&mut thread_rng()); bench.iter(move || { for blob in shared_blobs.iter_mut() { let index = blob.read().unwrap().index(); blocktree.write_shared_blobs(vec![blob.clone()]).unwrap(); blob.write().unwrap().set_index(index + num_entries as u64); } }); Blocktree::destroy(&ledger_path).expect("Expected successful database destruction"); }
extern crate multiinput; use multiinput::*; fn main() { let mut manager = RawInputManager::new().unwrap(); manager.register_devices(DeviceType::Joysticks(XInputInclude::True)); manager.register_devices(DeviceType::Keyboards); manager.register_devices(DeviceType::Mice); manager.print_device_list(); 'outer: loop{ if let Some(event) = manager.get_event(){ match event{ RawEvent::KeyboardEvent(_, KeyId::Escape, State::Pressed) => break 'outer, _ => (), } println!("{:?}", event); } else { std::thread::sleep(std::time::Duration::from_millis(10)); } } println!("Finishing"); }
use actix_web::http::StatusCode; use failure::Fail; #[derive(Debug, Fail)] pub enum ServiceError { #[fail(display = "invalid username: {}", _0)] InvalidUsername(String), #[fail(display = "failed to send request with error: {}", _0)] SendRequest(String), #[fail(display = "unexpected status code: {}", _0)] UnexpectedStatusCode(StatusCode), #[fail(display = "failed to get response body with error: {}", _0)] GetResponseBody(String), #[fail(display = "no trailing newline at end of body: {}", _0)] NoTrailingNewline(String), #[fail(display = "redis error: {}", _0)] RedisError(#[fail(cause)] redis::RedisError), }
// Boats to Save People // https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/580/week-2-january-8th-january-14th/3602/ pub struct Solution; impl Solution { pub fn num_rescue_boats(people: Vec<i32>, limit: i32) -> i32 { let mut people = people.clone(); people.sort_unstable(); let mut low = 0; let mut high = people.len(); let mut res = 0; while high > low { high -= 1; if low != high && people[high] + people[low] <= limit { low += 1; } res += 1; } res } } #[cfg(test)] mod tests { use super::*; #[test] fn example1() { assert_eq!(Solution::num_rescue_boats(vec![1, 2], 3), 1); } #[test] fn example2() { assert_eq!(Solution::num_rescue_boats(vec![3, 2, 2, 1], 3), 3); } #[test] fn example3() { assert_eq!(Solution::num_rescue_boats(vec![3, 5, 3, 4], 5), 4); } }
pub trait Stringable { fn to_s(&self) -> String; }
// This file is part of syslog2. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/syslog2/master/COPYRIGHT. No part of syslog2, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2016 The developers of syslog2. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/syslog2/master/COPYRIGHT. extern crate string_utilities; extern crate libc; pub use self::rfc3164Facility::Rfc3164Facility; mod rfc3164Facility; pub use self::syslogSender::SyslogSender; mod syslogSender; pub use self::insecureBlockingUdpSyslogSender::InsecureBlockingUdpSyslogSender; mod insecureBlockingUdpSyslogSender; pub use self::insecureThreadUnsafeBlockingTcpSyslogSender::InsecureThreadUnsafeBlockingTcpSyslogSender; mod insecureThreadUnsafeBlockingTcpSyslogSender; pub use self::posixSyslogSender::PosixSyslogSender; mod posixSyslogSender; // #[test] // fn format_message_rfc3164_test() // { // let overlongHostName = "0123456789012345678901234567890123456789"; // let process = Process // { // hostName: overlongHostName.to_owned(), // hostNameWithoutDomain: "macpro".to_owned(), // programName: "myprogram".to_owned(), // pid: 5 // }; // let rfc3164Facility = Rfc3164Facility::user; // let severity = Severity::LOG_ERR; // let message = "HelloWorld"; // let time = Tm { tm_sec: 19, tm_min: 23, tm_hour: 14, tm_mday: 8, tm_mon: 4, tm_year: 116, tm_wday: 0, tm_yday: 128, tm_isdst: 0, tm_utcoff: 0, tm_nsec: 854377000 }; // let result = format_message_rfc3164(&process.hostName, &process.programName, &process.pid, time, rfc3164Facility, severity, message); // assert_eq!(result, "<3>May 08 14:23:19 01234567890123456789012345678901 myprogram[5]: HelloWorld"); // }
use crate::Position; #[derive(Copy, Clone, Debug)] pub enum Key { // FIXME there has to be a more generic way A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, N0, N1, N2, N3, N4, N5, N6, N7, N8, N9, Enter, Backspace, Space, ArrowUp, ArrowRight, ArrowDown, ArrowLeft, Del, Tab, Comma, Period, Minus, } #[derive(Copy, Clone, Debug)] pub enum Modifier { None, Shift, Alt, AltShift, Ctrl, CtrlAlt, CtrlShift, } pub trait ToStr { fn to_str(&self) -> Option<&str>; } impl ToStr for (Key, Modifier) { fn to_str(&self) -> Option<&str> { let options = match self.0 { Key::A => Some(("a", "A", "A", "ä")), Key::B => Some(("b", "B", "B", "{")), Key::C => Some(("c", "C", "C", "&")), Key::D => Some(("d", "D", "D", "Đ")), Key::E => Some(("e", "E", "E", "Ä")), Key::F => Some(("f", "F", "F", "[")), Key::G => Some(("g", "G", "G", "]")), Key::H => Some(("h", "H", "H", "")), Key::I => Some(("i", "I", "I", "Í")), Key::J => Some(("j", "J", "J", "í")), Key::K => Some(("k", "K", "K", "ł")), Key::L => Some(("l", "L", "L", "Ł")), Key::M => Some(("m", "M", "M", "<")), Key::N => Some(("n", "N", "N", "}")), Key::O => Some(("o", "O", "O", "")), Key::P => Some(("p", "P", "P", "")), Key::Q => Some(("q", "Q", "Q", "\\")), Key::R => Some(("r", "R", "R", "")), Key::S => Some(("s", "S", "S", "đ")), Key::T => Some(("t", "T", "T", "")), Key::U => Some(("u", "U", "U", "€")), Key::V => Some(("v", "V", "V", "@")), Key::W => Some(("w", "W", "W", "|")), Key::X => Some(("x", "X", "X", "#")), Key::Y => Some(("y", "Y", "Y", ">")), Key::Z => Some(("z", "Z", "Z", "")), Key::N0 => Some(("0", "§", "0", "")), Key::N1 => Some(("1", "'", "1", "~")), Key::N2 => Some(("2", "\"", "2", "ˇ")), Key::N3 => Some(("3", "+", "3", "^")), Key::N4 => Some(("4", "!", "4", "˘")), Key::N5 => Some(("5", "%", "5", "°")), Key::N6 => Some(("6", "/", "6", "˛")), Key::N7 => Some(("7", "=", "7", "`")), Key::N8 => Some(("8", "(", "8", "˙")), Key::N9 => Some(("9", ")", "9", "´")), Key::Space => Some((" ", " ", " ", " ")), Key::Comma => Some((",", "?", ",", " ")), Key::Period => Some((".", ":", ".", ">")), Key::Minus => Some(("-", "_", "-", "*")), Key::Enter => Some(("\n", "\n", "\n", "\n")), Key::Tab => Some(("\t", "\t", "\t", "\t")), _ => None, }; options.and_then(|choices| match self.1 { Modifier::None => Some(choices.0), Modifier::Shift => Some(choices.1), Modifier::Alt | Modifier::CtrlAlt => Some(choices.3), Modifier::AltShift | Modifier::Ctrl | Modifier::CtrlShift => None, }) } } #[derive(Copy, Clone, Debug)] pub enum InputEvent { Cancel, KeyEvent(KeyEvent), PointerEvent(Position, PointerEvent), ScrollEvent(ScrollEvent), } #[derive(Copy, Clone, Debug)] pub enum KeyEvent { KeyDown(Key, Modifier, u32), KeyUp(Key, Modifier), } #[derive(Copy, Clone, Debug)] pub enum PointerEvent { Hover, Down, Drag, Up, } #[derive(Copy, Clone, Debug)] pub enum ScrollEvent { HorizontalScroll(i32), VerticalScroll(i32), } pub enum SelectionModifier { None, GrabSelection(Position), TempSelection(Position), }
use std::env; use std::error; use std::fs; fn main() -> Result<(), Box<dyn error::Error>> { let file = fs::File::open(wordcount_core::parse_file_name(env::args())?)?; let config = wordcount_core::Config::new(file)?; let word_count = wordcount_core::WordCount::new(config, |a, b| b.cmp(&a)); print!("{}", word_count); Ok(()) }
use std::fs::File; fn main() -> Result<(), std::io::Error> { let f = File::open("bar.txt")?; Ok(()) }
#![allow(non_upper_case_globals)] extern crate spatialos_sdk_sys; pub(crate) mod ptr; pub mod worker;
/////////////////////////////////////////////////////////////////////// /// /// https://adventofcode.com/2019/day/1 /// /// This binary calculates day 1 part 1 and 2 results. /////////////////////////////////////////////////////////////////////// use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; use io::BufReader; fn fuel_calculation(weight: i32) -> i32 { // Negative weights need no fuel if weight < 0 { return 0; } let fuel: i32 = (((weight as f32 / 3.0).floor()) - 2.0) as i32; // This is just convenient and realistic. We'd never // need 'negative' fuel. if fuel < 0 { return 0; } else { return fuel; } } fn open_input_file(filename: &str) -> io::Result<File> { let input = Path::new(filename); File::open(&input) } fn gather_input_numbers(filename: &str) -> Result<Vec<i32>, std::io::Error> { let input = open_input_file(filename)?; let reader = BufReader::new(input); Ok(reader .lines() .map(|line| { (line.expect("Could not parse input!").parse::<i32>()) .expect("Could not convert input!") }) .collect()) } fn display_naive_calculation(input: &Vec<i32>) { let fuel_value: i32 = input.iter().map(|&weight| fuel_calculation(weight)).sum(); println!("Naive Fuel weight: {}", fuel_value); } fn realistic_fuel_calculation(weight: i32) -> i32 { let fuel = fuel_calculation(weight); if fuel > 0 { return fuel + realistic_fuel_calculation(fuel); } else { return fuel; } } fn display_calculation_with_fuel(input: &Vec<i32>) { let fuel_value: i32 = input .iter() .map(|&weight| realistic_fuel_calculation(weight)) .sum(); println!("More realistic Fuel weight: {}", fuel_value); } fn do_rocket_calculation_cases(filename: &str) -> i32 { let input = match gather_input_numbers(filename) { Ok(input_collection) => input_collection, Err(why) => { eprintln!("Could not read input from {}: Reason: {}", filename, why); return 1; } }; display_naive_calculation(&input); display_calculation_with_fuel(&input); 0 } fn main() { let args: Vec<String> = env::args().collect(); let exitcode = match args.len() { 2 => { do_rocket_calculation_cases(&args[1]) } 1 => { eprintln!("You must specify a filename!"); 1 } _ => { eprintln!("You may only specify a filename!"); eprintln!("Arguments passed: {:?}", args); 1 } }; std::process::exit(exitcode); }
pub struct Stream<'a> { data: &'a [u8], seek: usize, shift: usize, } impl<'a> Stream<'a> { pub fn new(data: &'a [u8]) -> Stream { Stream { data: data, seek: 0, shift: 0, } } pub fn has_next(&self) -> bool { self.seek < self.data.len() } pub fn next_byte(&mut self) -> u8 { assert!(self.has_next()); let bit = (self.data[self.seek] >> self.shift) & 1; self.shift += 1; if self.shift == 8 { self.shift = 0; self.seek += 1; } bit } pub fn remain(&self) -> usize { (self.data.len() - self.seek) * 8 - self.shift } }
// Workaround for clippy bug. #![allow(clippy::unnecessary_wraps)] mod print; mod lexer; mod ast; mod ty; use lexer::{Keyword, Token, Literal, IntegerSuffix, Lexer, Base}; pub use ast::{UnaryOp, BinaryOp, Expr, TypedExpr, Stmt, Body, BodyRef}; pub use ty::{TyKind, Ty}; #[derive(Clone, Debug, PartialEq, Eq)] pub struct FunctionPrototype { pub name: String, pub args: Vec<(String, Ty)>, pub return_ty: Ty, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Function { pub prototype: FunctionPrototype, pub body: Option<Body>, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct ParsedModule { pub functions: Vec<Function>, } struct Parser { lexer: Lexer, } impl Parser { fn new(lexer: Lexer) -> Self { Self { lexer, } } fn parse_ty(&mut self) -> Ty { let current = self.lexer.eat(); let mut ty = Ty::from_token(current) .unwrap_or_else(|| panic!("Invalid type keyword {:?}.", current)); loop { if self.lexer.current() != &Token::Mul { break; } ty = ty.ptr(); let _ = self.lexer.eat(); } ty } fn parse_argument_list(&mut self, mut callback: impl FnMut(&mut Self)) { self.lexer.eat_expect(&Token::ParenOpen); loop { if self.lexer.current() == &Token::ParenClose { let _ = self.lexer.eat(); break; } callback(self); let current = self.lexer.current(); if current == &Token::Comma { let _ = self.lexer.eat(); } else { assert_eq!(current, &Token::ParenClose, "Expected comma or closing paren in argument list. Got {:?}", current); } } } fn parse_call_expression(&mut self, target: String) -> TypedExpr { let mut args = Vec::new(); self.parse_argument_list(|parser| { args.push(parser.parse_expression()); }); TypedExpr::new(Expr::Call { target, args, }) } fn parse_primary_expression(&mut self) -> TypedExpr { let current = self.lexer.current(); if let Some(unary) = UnaryOp::from_token(current) { return self.parse_unary_expression(unary); } let mut result = match current { Token::Literal(Literal::Number { value, suffix, base }) => { let ty = if let Some(suffix) = suffix { match suffix { IntegerSuffix::U8 => Ty::U8, IntegerSuffix::U16 => Ty::U16, IntegerSuffix::U32 => Ty::U32, IntegerSuffix::U64 => Ty::U64, IntegerSuffix::I8 => Ty::I8, IntegerSuffix::I16 => Ty::I16, IntegerSuffix::I32 => Ty::I32, IntegerSuffix::I64 => Ty::I64, } } else { let signed = *base == Base::Dec; let value = *value; let bigger = match signed { true => !(value as i64 <= i32::MAX as i64 && value as i64 >= i32::MIN as i64), false => !(value as u64 <= u32::MAX as u64 && value as u64 >= u32::MIN as u64), }; match signed { true => if bigger { Ty::I64 } else { Ty::I32 }, false => if bigger { Ty::U64 } else { Ty::U32 }, } }; let value = *value; let _ = self.lexer.eat(); TypedExpr::new(Expr::Number { value, ty, }) } Token::Literal(Literal::Char(value)) => { let value = *value as u64; let _ = self.lexer.eat(); TypedExpr::new(Expr::Number { value, ty: Ty::U8, }) } Token::Literal(..) => { panic!("Literal {:?} is not supported. Only number literals are supported.", current); } Token::Identifier(ident) => { let ident = ident.clone(); let _ = self.lexer.eat(); if self.lexer.current() == &Token::ParenOpen { self.parse_call_expression(ident) } else { TypedExpr::new(Expr::Variable(ident)) } } Token::ParenOpen => { let _ = self.lexer.eat(); if Ty::from_token(self.lexer.current()).is_some() { let ty = self.parse_ty(); let _ = self.lexer.eat_expect(&Token::ParenClose); let expr = self.parse_primary_expression(); TypedExpr::new(Expr::Cast { value: Box::new(expr), ty, }) } else { self.lexer.restore(1); self.parse_paren_expression() } } _ => panic!("Unexpected token in primary expression: {:?}.", current), }; if self.lexer.current() == &Token::BracketOpen { let _ = self.lexer.eat(); let index = self.parse_expression(); let _ = self.lexer.eat_expect(&Token::BracketClose); result = TypedExpr::new(Expr::Array { array: Box::new(result), index: Box::new(index), }); } result } fn parse_binary_expression(&mut self, mininal_precedence: i32, mut expr: TypedExpr) -> TypedExpr { let get_token_precedence = |parser: &Self| { BinaryOp::from_token(parser.lexer.current()) .map(|op| op.precedence()) .unwrap_or(-1) }; loop { let precedence = get_token_precedence(self); if precedence < mininal_precedence { return expr; } let op = BinaryOp::from_token(self.lexer.current()).unwrap(); let _ = self.lexer.eat(); let mut right = self.parse_primary_expression(); let next_precedence = get_token_precedence(self); if next_precedence > precedence { right = self.parse_binary_expression(precedence + 1, right); } expr = TypedExpr::new(Expr::Binary { left: Box::new(expr), right: Box::new(right), op, }); } } fn parse_expression(&mut self) -> TypedExpr { let left = self.parse_primary_expression(); self.parse_binary_expression(0, left) } fn parse_paren_expression(&mut self) -> TypedExpr { let _ = self.lexer.eat_expect(&Token::ParenOpen); let expr = self.parse_expression(); let _ = self.lexer.eat_expect(&Token::ParenClose); expr } fn parse_unary_expression(&mut self, op: UnaryOp) -> TypedExpr { let _ = self.lexer.eat(); let expr = self.parse_primary_expression(); TypedExpr::new(Expr::Unary { op, value: Box::new(expr), }) } fn parse_expression_statement(&mut self) -> Stmt { let expr = self.parse_expression(); let mut stmt = None; let mut combined = None; match self.lexer.current() { Token::Assign => { let _ = self.lexer.eat(); stmt = Some(Stmt::Assign { variable: expr.clone(), value: self.parse_expression(), }); } // TODO: This is broken. Fix this. // *get_ptr() += 15; // In this case get_ptr() will be called 2 times. Token::AddAssign => combined = Some(BinaryOp::Add), Token::SubAssign => combined = Some(BinaryOp::Sub), Token::MulAssign => combined = Some(BinaryOp::Mul), Token::ModAssign => combined = Some(BinaryOp::Mod), Token::DivAssign => combined = Some(BinaryOp::Div), Token::ShrAssign => combined = Some(BinaryOp::Shr), Token::ShlAssign => combined = Some(BinaryOp::Shl), Token::AndAssign => combined = Some(BinaryOp::And), Token::OrAssign => combined = Some(BinaryOp::Or), Token::XorAssign => combined = Some(BinaryOp::Xor), _ => (), } if let Some(combined) = combined { let _ = self.lexer.eat(); let second = self.parse_expression(); stmt = Some(Stmt::Assign { variable: expr.clone(), value: TypedExpr::new(Expr::Binary { left: Box::new(expr.clone()), op: combined, right: Box::new(second), }) }); } stmt.unwrap_or(Stmt::Expr(expr)) } fn parse_declaration(&mut self) -> Stmt { let decl_ty = self.parse_ty(); let name = self.lexer.eat_identifier().to_string(); let mut ty = decl_ty; let mut array = None; if self.lexer.current() == &Token::BracketOpen { let _ = self.lexer.eat(); array = Some(self.parse_expression()); ty = ty.ptr(); self.lexer.eat_expect(&Token::BracketClose); } let mut value = None; if self.lexer.current() == &Token::Assign { let _ = self.lexer.eat(); value = Some(self.parse_expression()); } Stmt::Declare { ty, decl_ty, name, array, value, } } fn parse_if(&mut self) -> Stmt { let _ = self.lexer.eat_expect(&Token::Keyword(Keyword::If)); let main_cond = self.parse_paren_expression(); let main_body = self.parse_body(); let mut default = None; let mut arms = Vec::new(); arms.push((main_cond, main_body)); loop { if self.lexer.current() != &Token::Keyword(Keyword::Else) { break; } let _ = self.lexer.eat(); let elseif = if self.lexer.current() == &Token::Keyword(Keyword::If) { let _ = self.lexer.eat(); true } else { false }; let mut condition = None; if elseif { condition = Some(self.parse_paren_expression()); } let body = self.parse_body(); if let Some(condition) = condition { arms.push((condition, body)); } else { default = Some(body); break; } } Stmt::If { arms, default, } } fn parse_for(&mut self) -> Stmt { self.lexer.eat_expect(&Token::Keyword(Keyword::For)); self.lexer.eat_expect(&Token::ParenOpen); let mut init = None; let mut condition = None; let mut step = None; if self.lexer.current() != &Token::Semicolon { init = Some(Box::new(self.parse_statement())); } self.lexer.eat_expect(&Token::Semicolon); if self.lexer.current() != &Token::Semicolon { condition = Some(self.parse_expression()); } self.lexer.eat_expect(&Token::Semicolon); if self.lexer.current() != &Token::ParenClose { step = Some(Box::new(self.parse_statement())); } self.lexer.eat_expect(&Token::ParenClose); let body = self.parse_body(); Stmt::For { init, condition, step, body, } } fn parse_statement(&mut self) -> Stmt { match self.lexer.current() { x if Ty::from_token(x).is_some() => self.parse_declaration(), Token::Keyword(Keyword::If) => self.parse_if(), Token::Keyword(Keyword::For) => self.parse_for(), Token::Keyword(Keyword::Return) => { let _ = self.lexer.eat(); let value = if self.lexer.current() != &Token::Semicolon { Some(self.parse_expression()) } else { None }; Stmt::Return(value) } Token::Keyword(Keyword::While) => { let _ = self.lexer.eat(); let cond = self.parse_paren_expression(); let body = self.parse_body(); Stmt::While { condition: cond, body, } } Token::Keyword(Keyword::Continue) => { self.lexer.eat(); Stmt::Continue } Token::Keyword(Keyword::Break) => { self.lexer.eat(); Stmt::Break } _ => self.parse_expression_statement(), } } fn parse_body(&mut self) -> Body { self.lexer.eat_expect(&Token::BraceOpen); let mut body = Vec::new(); while self.lexer.current() != &Token::BraceClose { let stmt = self.parse_statement(); let require_semicolon = match stmt { Stmt::While { .. } | Stmt::If { .. } | Stmt::For { .. } => { false } _ => true, }; if require_semicolon { self.lexer.eat_expect(&Token::Semicolon); } body.push(stmt); } self.lexer.eat_expect(&Token::BraceClose); body } fn parse_prototype(&mut self) -> FunctionPrototype { let return_ty = self.parse_ty(); let name = self.lexer.eat_identifier().to_string(); let mut args = Vec::new(); self.parse_argument_list(|parser| { let ty = parser.parse_ty(); let name = parser.lexer.eat_identifier().to_string(); args.push((name, ty)); }); FunctionPrototype { return_ty, name, args, } } fn parse_function(&mut self) -> Function { let is_extern = self.lexer.current() == &Token::Keyword(Keyword::Extern); if is_extern { self.lexer.eat(); } let prototype = self.parse_prototype(); let body = match is_extern { true => { self.lexer.eat_expect(&Token::Semicolon); None } false => { Some(self.parse_body()) } }; Function { prototype, body, } } fn parse_functions(&mut self) -> Vec<Function> { let mut functions = Vec::new(); while self.lexer.current() != &Token::Eof { functions.push(self.parse_function()); } functions } } pub fn parse(source: &str) -> ParsedModule { let lexer = Lexer::new(source); let mut parser = Parser::new(lexer); let functions = parser.parse_functions(); ParsedModule { functions, } }
use crate::core::transform::Transform; use crate::gameplay::collision::{CollisionLayer, CollisionWorld, Ray}; use hecs::Entity; use rand::Rng; const CLOSE_ENOUGH: f32 = 50.0; pub mod behavior; /// Will compute the force to move towards a target without slowing down. /// /// # Returns /// the force to apply to the entity pub fn seek( position: glam::Vec2, velocity: glam::Vec2, target: glam::Vec2, max_speed: f32, ) -> glam::Vec2 { (max_speed * (target - position).normalize()) - velocity } /// Random movements that do not look too weird pub fn wander(velocity: glam::Vec2, wander_strength: f32) -> glam::Vec2 { let circle_center = velocity.normalize() * 20.0; // TODO Circle distance somewhere else. let mut rng = rand::thread_rng(); let displacement = glam::Mat2::from_angle(rng.gen_range(0.0, 2.0 * std::f32::consts::PI)) * glam::Vec2::unit_x() * wander_strength; circle_center + displacement } /// STOP pub fn halt(velocity: glam::Vec2) -> glam::Vec2 { -velocity } pub fn avoid( myself: Entity, transform: &Transform, velocity: glam::Vec2, look_ahead: f32, collision_world: &CollisionWorld, avoidance_strength: f32, ignore_mask: CollisionLayer, ) -> Option<glam::Vec2> { let ray = Ray { c: transform.translation, d: velocity.normalize(), }; let collisions = collision_world.ray_with_offset(ray, ignore_mask, transform.scale.x / 2.0); let mut current_t = std::f32::INFINITY; let mut collision_data = None; for (e, t, pos, center) in collisions { if e == myself { continue; } debug!("Collide with entity = {:?} in {} at {:?}", e, t, pos); if t < look_ahead && t < current_t { current_t = t; // there will be a collisions. collision_data = Some((pos, center)); } } if let Some((_obstacle_pos, obstacle_center)) = collision_data { let d = (obstacle_center - transform.translation).length(); let avoidance_force = glam::vec2(velocity.y, -velocity.x); Some(avoidance_force.normalize() * avoidance_strength * look_ahead / d) } else { None } } /// Follow the target. If it;s close enough, then it will return None pub fn go_to_path_point( target: glam::Vec2, position: glam::Vec2, velocity: glam::Vec2, max_speed: f32, ) -> Option<glam::Vec2> { // Compute distance from position to current. If it's close enough, move to next point. if (target - position).length() > CLOSE_ENOUGH { // go to next. Some(seek(position, velocity, target, max_speed)) } else { None } }
macro_rules! deconstruction { ($id:ident, $t:pat, $($p: expr),*) => { let mut bar = Vec::new(); for i in $id { match i { $t => {$(bar.push($p);)*}, _ => {}, } } let mut $id = bar.clone(); } } fn main() { let foo = vec![(1,((1,2),(3,4))),(1,((1,2),(3,4)))]; deconstruction!(foo,(e,((f,g),(h,j))),e,f,g,h,j); for i in foo { print!("{} ", i); } }
use super::*; #[derive(Default)] pub struct RenderState { pub(crate) visible: bool, pub render_skeleton: bool, pub render_position: bool, pub render_particles: bool, pub render_physics: bool, // Taken from http://urraka.github.io/soldat-map/#171/Airpirates pub disable_background: bool, pub disable_polygon: bool, pub disable_texture: bool, pub render_wireframe: bool, pub render_colliders: bool, pub disable_scenery: bool, pub disable_scenery_back: bool, pub disable_scenery_middle: bool, pub disable_scenery_front: bool, pub render_spawns: bool, pub render_spawns_team: [bool; 17], pub highlight_polygons: bool, pub hlt_poly_normal: bool, pub hlt_poly_only_bullets_coll: bool, pub hlt_poly_only_players_coll: bool, pub hlt_poly_no_coll: bool, pub hlt_poly_ice: bool, pub hlt_poly_deadly: bool, pub hlt_poly_bloody_deadly: bool, pub hlt_poly_hurts: bool, pub hlt_poly_regenerates: bool, pub hlt_poly_lava: bool, pub hlt_poly_alpha_bullets: bool, pub hlt_poly_alpha_players: bool, pub hlt_poly_bravo_bullets: bool, pub hlt_poly_bravo_players: bool, pub hlt_poly_charlie_bullets: bool, pub hlt_poly_charlie_players: bool, pub hlt_poly_delta_bullets: bool, pub hlt_poly_delta_players: bool, pub hlt_poly_bouncy: bool, pub hlt_poly_explosive: bool, pub hlt_poly_hurt_flaggers: bool, pub hlt_poly_flagger_coll: bool, pub hlt_poly_non_flagger_coll: bool, pub hlt_poly_flag_coll: bool, pub hlt_poly_background: bool, pub hlt_poly_background_transition: bool, } impl IVisit for RenderState { fn visit(&mut self, f: &mut dyn FnMut(&mut dyn INode)) { f(&mut cvar::Property("visible", &mut self.visible, false)); f(&mut cvar::Property( "render_skeleton", &mut self.render_skeleton, false, )); f(&mut cvar::Property( "render_position", &mut self.render_position, false, )); f(&mut cvar::Property( "render_particles", &mut self.render_particles, false, )); f(&mut cvar::Property( "render_physics", &mut self.render_physics, false, )); f(&mut cvar::Property( "disable_background", &mut self.disable_background, false, )); f(&mut cvar::Property( "disable_polygon", &mut self.disable_polygon, false, )); f(&mut cvar::Property( "disable_texture", &mut self.disable_texture, false, )); f(&mut cvar::Property( "render_wireframe", &mut self.render_wireframe, false, )); f(&mut cvar::Property( "render_colliders", &mut self.render_colliders, false, )); f(&mut cvar::Property( "disable_scenery", &mut self.disable_scenery, false, )); f(&mut cvar::Property( "disable_scenery_back", &mut self.disable_scenery_back, false, )); f(&mut cvar::Property( "disable_scenery_middle", &mut self.disable_scenery_middle, false, )); f(&mut cvar::Property( "disable_scenery_front", &mut self.disable_scenery_front, false, )); } } impl RenderState { pub fn build_ui(&mut self, egui_ctx: &egui::CtxRef) { let mut visible = self.visible; egui::Window::new("Renderer") .open(&mut visible) .resizable(false) .scroll(true) .show(egui_ctx, |ui| { toggle_state(ui, &mut self.render_skeleton, "Skeleton"); toggle_state(ui, &mut self.render_position, "Position"); toggle_state(ui, &mut self.render_particles, "Particles"); toggle_state(ui, &mut self.render_physics, "Physics"); ui.separator(); toggle_state_inv(ui, &mut self.disable_background, "Background"); toggle_state_inv(ui, &mut self.disable_polygon, "Polygons"); // toggle_state_inv(ui, &mut state.disable_texture, "Texture"); toggle_state(ui, &mut self.render_wireframe, "Wireframe"); toggle_state(ui, &mut self.render_colliders, "Colliders"); ui.collapsing("Scenery", |ui| { toggle_state_inv(ui, &mut self.disable_scenery_back, "Back"); toggle_state_inv(ui, &mut self.disable_scenery_middle, "Middle"); toggle_state_inv(ui, &mut self.disable_scenery_front, "Front"); }); ui.collapsing("Spawns", |ui| { toggle_state(ui, &mut self.render_spawns_team[0], "General"); toggle_state(ui, &mut self.render_spawns_team[1], "Alpha"); toggle_state(ui, &mut self.render_spawns_team[2], "Bravo"); toggle_state(ui, &mut self.render_spawns_team[3], "Charlie"); toggle_state(ui, &mut self.render_spawns_team[4], "Delta"); toggle_state(ui, &mut self.render_spawns_team[5], "Alpha Flag"); toggle_state(ui, &mut self.render_spawns_team[6], "Bravo Flag"); toggle_state(ui, &mut self.render_spawns_team[7], "Grenades"); toggle_state(ui, &mut self.render_spawns_team[8], "Medkits"); toggle_state(ui, &mut self.render_spawns_team[9], "Clusters"); toggle_state(ui, &mut self.render_spawns_team[10], "Vest"); toggle_state(ui, &mut self.render_spawns_team[11], "Flamer"); toggle_state(ui, &mut self.render_spawns_team[12], "Berserker"); toggle_state(ui, &mut self.render_spawns_team[13], "Predator"); toggle_state(ui, &mut self.render_spawns_team[14], "Yellow Flag"); toggle_state(ui, &mut self.render_spawns_team[15], "Rambo Bow"); toggle_state(ui, &mut self.render_spawns_team[16], "Stat Gun"); }); self.render_spawns = self .render_spawns_team .iter() .any(|spawn| *spawn); #[rustfmt::skip] ui.collapsing("Highlight polygons", |ui| { toggle_state(ui, &mut self.hlt_poly_normal, "Normal"); toggle_state(ui, &mut self.hlt_poly_only_bullets_coll, "Only Bullets Collide"); toggle_state(ui, &mut self.hlt_poly_only_players_coll, "Only Players Collide"); toggle_state(ui, &mut self.hlt_poly_no_coll, "No Collide"); toggle_state(ui, &mut self.hlt_poly_ice, "Ice"); toggle_state(ui, &mut self.hlt_poly_deadly, "Deadly"); toggle_state(ui, &mut self.hlt_poly_bloody_deadly, "Bloody deadly"); toggle_state(ui, &mut self.hlt_poly_hurts, "Hurts"); toggle_state(ui, &mut self.hlt_poly_regenerates, "Regenerates"); toggle_state(ui, &mut self.hlt_poly_lava, "Lava"); toggle_state(ui, &mut self.hlt_poly_alpha_bullets, "Alpha Bullets"); toggle_state(ui, &mut self.hlt_poly_alpha_players, "Alpha Players"); toggle_state(ui, &mut self.hlt_poly_bravo_bullets, "Bravo Bullets"); toggle_state(ui, &mut self.hlt_poly_bravo_players, "Bravo Players"); toggle_state(ui, &mut self.hlt_poly_charlie_bullets, "Charlie Bullets"); toggle_state(ui, &mut self.hlt_poly_charlie_players, "Charlie Players"); toggle_state(ui, &mut self.hlt_poly_delta_bullets, "Delta Bullets"); toggle_state(ui, &mut self.hlt_poly_delta_players, "Delta Players"); toggle_state(ui, &mut self.hlt_poly_bouncy, "Bouncy"); toggle_state(ui, &mut self.hlt_poly_explosive, "Explosive"); toggle_state(ui, &mut self.hlt_poly_hurt_flaggers, "Hurt Flaggers"); toggle_state(ui, &mut self.hlt_poly_flagger_coll, "Flagger Collides"); toggle_state(ui, &mut self.hlt_poly_non_flagger_coll, "Non Flagger Collides"); toggle_state(ui, &mut self.hlt_poly_flag_coll, "Flag Collides"); toggle_state(ui, &mut self.hlt_poly_background, "Background"); toggle_state(ui, &mut self.hlt_poly_background_transition, "Background Transition"); }); self.highlight_polygons = self.hlt_poly_normal || self.hlt_poly_only_bullets_coll || self.hlt_poly_only_players_coll || self.hlt_poly_no_coll || self.hlt_poly_ice || self.hlt_poly_deadly || self.hlt_poly_bloody_deadly || self.hlt_poly_hurts || self.hlt_poly_regenerates || self.hlt_poly_lava || self.hlt_poly_alpha_bullets || self.hlt_poly_alpha_players || self.hlt_poly_bravo_bullets || self.hlt_poly_bravo_players || self.hlt_poly_charlie_bullets || self.hlt_poly_charlie_players || self.hlt_poly_delta_bullets || self.hlt_poly_delta_players || self.hlt_poly_bouncy || self.hlt_poly_explosive || self.hlt_poly_hurt_flaggers || self.hlt_poly_flagger_coll || self.hlt_poly_non_flagger_coll || self.hlt_poly_flag_coll || self.hlt_poly_background || self.hlt_poly_background_transition; }, ); self.visible = visible; } }
/*! see https://github.com/thewebdevel/codeframe for high level description of the library */ pub mod capture; pub mod codeframe_builder; pub mod codeframe_macro; pub mod color; mod utils; pub use crate::capture as capture_codeframe; pub use crate::codeframe_builder::Codeframe; pub use color::Color;
// plotters use plotters::prelude::*; // DenseMatrix wrapper around Vec use smartcore::linalg::naive::dense_matrix::DenseMatrix; use smartcore::linalg::BaseMatrix; use smartcore::math::num::RealNumber; /// Get min value of `x` along axis `axis` pub fn min<T: RealNumber>(x: &DenseMatrix<T>, axis: usize) -> T { let n = x.shape().0; x.slice(0..n, axis..axis + 1) .iter() .min_by(|a, b| a.partial_cmp(b).unwrap()) .unwrap() } /// Get max value of `x` along axis `axis` pub fn max<T: RealNumber>(x: &DenseMatrix<T>, axis: usize) -> T { let n = x.shape().0; x.slice(0..n, axis..axis + 1) .iter() .max_by(|a, b| a.partial_cmp(b).unwrap()) .unwrap() } /// Draw a mesh grid defined by `mesh` with a scatterplot of `data` on top /// We use Plotters library to draw scatter plot. /// https://docs.rs/plotters/0.3.0/plotters/ pub fn scatterplot_with_mesh( mesh: &DenseMatrix<f32>, mesh_labels: &Vec<f32>, data: &DenseMatrix<f32>, labels: &Vec<f32>, title: &str, ) -> Result<(), Box<dyn std::error::Error>> { let path = format!("{}.svg", title); let root = SVGBackend::new(&path, (800, 600)).into_drawing_area(); root.fill(&WHITE)?; let root = root.margin(15, 15, 15, 15); let x_min = (min(mesh, 0) - 1.0) as f64; let x_max = (max(mesh, 0) + 1.0) as f64; let y_min = (min(mesh, 1) - 1.0) as f64; let y_max = (max(mesh, 1) + 1.0) as f64; let mesh_labels: Vec<usize> = mesh_labels.into_iter().map(|&v| v as usize).collect(); let mesh: Vec<f64> = mesh.iter().map(|v| v as f64).collect(); let labels: Vec<usize> = labels.into_iter().map(|&v| v as usize).collect(); let data: Vec<f64> = data.iter().map(|v| v as f64).collect(); let mut scatter_ctx = ChartBuilder::on(&root) .x_label_area_size(20) .y_label_area_size(20) .build_cartesian_2d(x_min..x_max, y_min..y_max)?; scatter_ctx .configure_mesh() .disable_x_mesh() .disable_y_mesh() .draw()?; scatter_ctx.draw_series(mesh.chunks(2).zip(mesh_labels.iter()).map(|(xy, &l)| { EmptyElement::at((xy[0], xy[1])) + Circle::new((0, 0), 1, ShapeStyle::from(&Palette99::pick(l)).filled()) }))?; scatter_ctx.draw_series(data.chunks(2).zip(labels.iter()).map(|(xy, &l)| { EmptyElement::at((xy[0], xy[1])) + Circle::new( (0, 0), 3, ShapeStyle::from(&Palette99::pick(l + 3)).filled(), ) }))?; Ok(()) } /// Draw a scatterplot of `data` with labels `labels` /// We use Plotters library to draw scatter plot. /// https://docs.rs/plotters/0.3.0/plotters/ pub fn scatterplot( data: &DenseMatrix<f32>, labels: Option<&Vec<usize>>, title: &str, ) -> Result<(), Box<dyn std::error::Error>> { let path = format!("{}.svg", title); let root = SVGBackend::new(&path, (800, 600)).into_drawing_area(); let x_min = (min(data, 0) - 1.0) as f64; let x_max = (max(data, 0) + 1.0) as f64; let y_min = (min(data, 1) - 1.0) as f64; let y_max = (max(data, 1) + 1.0) as f64; root.fill(&WHITE)?; let root = root.margin(15, 15, 15, 15); let data_values: Vec<f64> = data.iter().map(|v| v as f64).collect(); let mut scatter_ctx = ChartBuilder::on(&root) .x_label_area_size(20) .y_label_area_size(20) .build_cartesian_2d(x_min..x_max, y_min..y_max)?; scatter_ctx .configure_mesh() .disable_x_mesh() .disable_y_mesh() .draw()?; match labels { Some(labels) => { scatter_ctx.draw_series(data_values.chunks(2).zip(labels.iter()).map(|(xy, &l)| { EmptyElement::at((xy[0], xy[1])) + Circle::new((0, 0), 3, ShapeStyle::from(&Palette99::pick(l)).filled()) + Text::new(format!("{}", l), (6, 0), ("sans-serif", 15.0).into_font()) }))?; } None => { scatter_ctx.draw_series(data_values.chunks(2).map(|xy| { EmptyElement::at((xy[0], xy[1])) + Circle::new((0, 0), 3, ShapeStyle::from(&Palette99::pick(3)).filled()) }))?; } } Ok(()) } /// Generates 2x2 mesh grid from `x` pub fn make_meshgrid(x: &DenseMatrix<f32>) -> DenseMatrix<f32> { let n = x.shape().0; let x_min = min(x, 0) - 1.0; let x_max = max(x, 0) + 1.0; let y_min = min(x, 1) - 1.0; let y_max = max(x, 1) + 1.0; let x_step = (x_max - x_min) / n as f32; let x_axis: Vec<f32> = (0..n).map(|v| (v as f32 * x_step) + x_min).collect(); let y_step = (y_max - y_min) / n as f32; let y_axis: Vec<f32> = (0..n).map(|v| (v as f32 * y_step) + y_min).collect(); let x_new: Vec<Vec<f32>> = x_axis .clone() .into_iter() .flat_map(move |v1| y_axis.clone().into_iter().map(move |v2| vec![v1, v2])) .collect(); DenseMatrix::from_2d_vec(&x_new) }
//! File system with inode support //! //! Create a filesystem that has a notion of inodes and blocks, by implementing the [`FileSysSupport`], //! the [`BlockSupport`] and the [`InodeSupport`] traits together (again, all earlier traits are //! supertraits of the later ones). //! //! [`FileSysSupport`]: ../../cplfs_api/fs/trait.FileSysSupport.html //! [`BlockSupport`]: ../../cplfs_api/fs/trait.BlockSupport.html //! [`InodeSupport`]: ../../cplfs_api/fs/trait.InodeSupport.html //! Make sure this file does not contain any unaddressed ` //! //! # Status //! //! //! indicate the status of this assignment. If you want to tell something //! about this assignment to the grader, e.g., you have a bug you can't fix, //! or you want to explain your approach, write it down after the comments //! section. If you had no major issues and everything works, there is no need to write any comments. //! //! COMPLETED: YES //! //! COMMENTS: //! //! //use crate::a_block_support::FileSystem; use cplfs_api::fs::{BlockSupport, FileSysSupport, InodeSupport}; use cplfs_api::types::{DInode, FType, Inode, InodeLike, DINODE_SIZE}; use crate::filesystem_errors::FileSystemError; use crate::helpers::{get_inode_block, trunc}; use std::borrow::BorrowMut; use cplfs_api::controller::Device; use cplfs_api::types::{Block, SuperBlock}; use std::path::Path; use crate::helpers::*; /// You are free to choose the name for your file system. As we will use /// automated tests when grading your assignment, indicate here the name of /// your file system data type so we can just use `FSName` instead of /// having to manually figure out the name. /// * pub type FSName = FileSystem; #[derive(Debug)] /// This is the filesystem structure that wa are going to use in the whole project pub struct FileSystem { /// We keep a reference to the superblock cause it can come in hand pub superblock: SuperBlock, /// This is the device we work on, it is optional at the start and can be filled in later pub device: Option<Device>, } impl FileSystem { /// This function creates a filesystem struct given a superblock and a optional device pub fn create_filesystem(superblock: SuperBlock, device: Option<Device>) -> FileSystem { FileSystem { superblock, device } } } impl FileSysSupport for FileSystem { type Error = FileSystemError; fn sb_valid(sb: &SuperBlock) -> bool { return sb_valid(sb); } fn mkfs<P: AsRef<Path>>(path: P, sb: &SuperBlock) -> Result<Self, Self::Error> { if !FSName::sb_valid(sb) { Err(FileSystemError::InvalidSuperBlock()) } else { let device_result = Device::new(path, sb.block_size, sb.nblocks); match device_result { Ok(mut device) => { //place superblock at index 0 write_sb(sb, &mut device)?; allocate_inoderegionblocks(&sb, &mut device)?; allocate_bitmapregion(&sb, &mut device)?; allocate_dataregion(&sb, &mut device)?; let mut fs = FileSystem::mountfs(device)?; allocate_inodes(&mut fs)?; Ok(fs) } Err(e) => Err(FileSystemError::DeviceAPIError(e)), } } } fn mountfs(dev: Device) -> Result<Self, Self::Error> { match dev.read_block(0) { Ok(block) => { let sb = &block.deserialize_from::<SuperBlock>(0)?; if FSName::sb_valid(sb) && dev.block_size == sb.block_size && dev.nblocks == sb.nblocks { let fs = FileSystem::create_filesystem(*sb, Some(dev)); Ok(fs) } else { Err(FileSystemError::InvalidSuperBlock()) } } Err(e) => Err(FileSystemError::DeviceAPIError(e)), } } fn unmountfs(mut self) -> Device { let deviceoption = self.device.take(); let device = deviceoption.unwrap(); return device; } } impl BlockSupport for FileSystem { fn b_get(&self, i: u64) -> Result<Block, Self::Error> { let dev = self .device .as_ref() .ok_or_else(|| FileSystemError::DeviceNotSet())?; return Ok(read_block(dev, i)?); } fn b_put(&mut self, b: &Block) -> Result<(), Self::Error> { let dev = self .device .as_mut() .ok_or_else(|| FileSystemError::DeviceNotSet())?; return Ok(write_block(dev, b)?); } fn b_free(&mut self, i: u64) -> Result<(), Self::Error> { let dev = self .device .as_mut() .ok_or_else(|| FileSystemError::DeviceNotSet())?; set_bitmapbit(&self.superblock, dev, i, false)?; Ok(()) } fn b_zero(&mut self, i: u64) -> Result<(), Self::Error> { let datablock_index = i + self.superblock.datastart; let newzeroblock = Block::new( datablock_index, vec![0; self.superblock.block_size as usize].into_boxed_slice(), ); self.b_put(&newzeroblock)?; Ok(()) } fn b_alloc(&mut self) -> Result<u64, Self::Error> { let nbitmapblocks = get_nbitmapblocks(&self.superblock); let mut bmstart_index = self.superblock.bmapstart; // get the index let mut block; // get the first block let mut byte_array; // create an empty data buffer let mut byteindex; //block index for blockindex in 0..nbitmapblocks { block = self.b_get(bmstart_index + blockindex)?; //next block //byte_array = block.contents_as_ref(); //get the block's array byte_array = block.contents_as_ref(); byteindex = get_bytesarray_free_index(byte_array); if byteindex.is_err() { // HERE WE ARE LOOKING FOR THE NEXT BLOCK bmstart_index += 1; //next block index } else { // The current bm_block has a free spot let byteindex = byteindex.unwrap(); //get the index of the byte that has a free spot let byte = byte_array.get(usize::from(byteindex)).unwrap(); let bitindex = 8 - 1 - byte.trailing_ones(); //moves the 1 to the correct position let mutator = 0b00000001u8 << byte.trailing_ones(); //moves the 1 to the correct position let to_write_byte = &[(*byte | mutator)]; block.write_data(to_write_byte, byteindex as u64)?; let byteindex: u64 = u64::from(byteindex); let datablockindex = blockindex * self.superblock.block_size * 8 + (byteindex) * 8 + u64::from(7 - bitindex); if datablockindex < self.superblock.ndatablocks { self.b_zero(datablockindex)?; self.b_put(&block)?; return Ok(datablockindex); } } } Err(FileSystemError::AllocationError()) } fn sup_get(&self) -> Result<SuperBlock, Self::Error> { let block = self.b_get(0)?; let sb = block.deserialize_from::<SuperBlock>(0)?; Ok(sb) } fn sup_put(&mut self, sup: &SuperBlock) -> Result<(), Self::Error> { let mut firstblock = self.b_get(0)?; firstblock.serialize_into(&sup, 0)?; self.b_put(&firstblock)?; Ok(()) } } impl InodeSupport for FileSystem { type Inode = Inode; fn i_get(&self, i: u64) -> Result<Self::Inode, Self::Error> { let inodes_per_block = self.superblock.block_size / *DINODE_SIZE; let block = get_inode_block(self, i, inodes_per_block)?; let block_inode_offset = i % inodes_per_block * *DINODE_SIZE; let disk_node = block.deserialize_from::<DInode>(block_inode_offset)?; return Ok(Inode::new(i, disk_node)); } fn i_put(&mut self, ino: &Self::Inode) -> Result<(), Self::Error> { let inodes_per_block = self.superblock.block_size / *DINODE_SIZE; let mut block = get_inode_block(self, ino.inum, inodes_per_block)?; let block_inode_offset = ino.inum % inodes_per_block * *DINODE_SIZE; block.serialize_into(&ino.disk_node, block_inode_offset)?; self.b_put(&block)?; Ok(()) } fn i_free(&mut self, i: u64) -> Result<(), Self::Error> { let mut ino = self.i_get(i)?; if ino.disk_node.nlink == 0 && ino.inum > 0 { trunc(self, ino.borrow_mut())?; ino.disk_node.ft = FType::TFree; self.i_put(&ino)?; Ok(()) } else { Err(FileSystemError::INodeNotFreeable()) } } fn i_alloc(&mut self, ft: FType) -> Result<u64, Self::Error> { let inode_alloc_start = 1; for i in inode_alloc_start..self.superblock.ninodes { let mut ino = self.i_get(i)?; if ino.get_ft() == FType::TFree { ino.disk_node.ft = ft; self.i_put(&ino)?; return Ok(i); } } return Err(FileSystemError::AllocationError()); } fn i_trunc(&mut self, inode: &mut Self::Inode) -> Result<(), Self::Error> { let ino = self.i_get(inode.inum)?; if &ino == inode { trunc(self, inode)?; self.i_put(&inode)?; } else { } Ok(()) } } // WARNING: DO NOT TOUCH THE BELOW CODE -- IT IS REQUIRED FOR TESTING -- YOU WILL LOSE POINTS IF I MANUALLY HAVE TO FIX YOUR TESTS #[cfg(all(test, any(feature = "b", feature = "all")))] #[path = "../../api/fs-tests/b_test.rs"] mod tests;
enum Order { Asc, Desc, } struct QueryBuilder { table: String, fields: Vec<String>, filters: Vec<String>, order: Option<Order>, order_field: Option<String>, } impl<'a> QueryBuilder { fn new() -> QueryBuilder { return QueryBuilder { table: String::new(), fields: Vec::new(), filters: Vec::new(), order: None, order_field: None, }; } fn filter(&mut self, filter: &'a str) -> &mut Self { self.filters.push(String::from(format!("{}", filter))); return self; } fn select(&mut self, fields: &[&'a str]) -> &mut Self { for field in fields { self.fields.push(String::from(format!("{}", field))); } return self; } fn from(&mut self, table: &'a str) -> &mut Self { self.table = String::from(format!("{}", table)); return self; } fn order_by(&mut self, order_field: &'a str, order: Order) -> &mut Self { self.order = Some(order); self.order_field = Some(String::from(format!("{}", order_field))); return self; } fn build(&mut self) -> Option<String> { let mut query = String::new(); query.push_str("SELECT "); let last_field = match self.fields.pop() { None => String::new(), Some(field) => field, }; if last_field.is_empty() { return None; } for field in &(self.fields) { query.push_str(field.as_str()); query.push_str(", "); } query.push_str(last_field.as_str()); query.push_str(" FROM "); query.push_str(self.table.as_str()); if !self.filters.is_empty() { query.push_str(" WHERE "); let last_filter = match self.filters.pop() { None => String::new(), Some(filter) => filter, }; for filter in &(self.filters) { query.push_str(filter.as_str()); query.push_str(" AND "); } query.push_str(last_filter.as_str()); } if self.order.is_some() && self.order_field.is_some() { let order = match &(self.order) { None => panic!(), Some(o) => o, }; let order_field = match &(self.order_field) { None => panic!(), Some(f) => f, }; query.push_str(" ORDER BY "); query.push_str(order_field.as_str()); match order { Order::Asc => query.push_str(" ASC"), Order::Desc => query.push_str(" DESC"), } } query.push_str(";"); return Some(query); } } fn main() { let mut query_builder = QueryBuilder::new(); let query = match query_builder .from("users") .select(&["name", "email", "password"]) .filter("name = $1") .order_by("name", Order::Desc) .build() { None => panic!(), Some(query) => query, }; println!("{}", query); }
// 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. //! Traits for use with the rust client library for cobalt. /// `AsEventCodes` is any type that can be converted into a `Vec<u32>` for the purposes of storing /// in a `fidl_fuchsia_cobalt::CobaltEvent`. pub trait AsEventCodes { /// Converts the source type into a `Vec<u32>` of event codes. fn as_event_codes(&self) -> Vec<u32>; } impl AsEventCodes for () { fn as_event_codes(&self) -> Vec<u32> { Vec::new() } } impl AsEventCodes for u32 { fn as_event_codes(&self) -> Vec<u32> { vec![*self] } } impl AsEventCodes for Vec<u32> { fn as_event_codes(&self) -> Vec<u32> { self.to_owned() } } impl AsEventCodes for [u32] { fn as_event_codes(&self) -> Vec<u32> { Vec::from(self) } } macro_rules! array_impls { ($($N:expr)+) => { $( impl AsEventCodes for [u32; $N] { fn as_event_codes(&self) -> Vec<u32> { self[..].as_event_codes() } } )+ } } array_impls! {0 1 2 3 4 5 6} #[cfg(test)] mod tests { use super::*; #[test] fn test_as_event_codes() { assert_eq!(().as_event_codes(), vec![]); assert_eq!([].as_event_codes(), vec![]); assert_eq!(1.as_event_codes(), vec![1]); assert_eq!([1].as_event_codes(), vec![1]); assert_eq!(vec![1].as_event_codes(), vec![1]); assert_eq!([1, 2].as_event_codes(), vec![1, 2]); assert_eq!(vec![1, 2].as_event_codes(), vec![1, 2]); assert_eq!([1, 2, 3].as_event_codes(), vec![1, 2, 3]); assert_eq!(vec![1, 2, 3].as_event_codes(), vec![1, 2, 3]); assert_eq!([1, 2, 3, 4].as_event_codes(), vec![1, 2, 3, 4]); assert_eq!(vec![1, 2, 3, 4].as_event_codes(), vec![1, 2, 3, 4]); assert_eq!([1, 2, 3, 4, 5].as_event_codes(), vec![1, 2, 3, 4, 5]); assert_eq!(vec![1, 2, 3, 4, 5].as_event_codes(), vec![1, 2, 3, 4, 5]); } }
//! 2D physics ECS pub use collide2d::*; pub use core::physics2d::*; pub use physics::setup_dispatch_2d; use cgmath::{Basis2, Point2, Vector2}; use collision::primitive::Primitive2; use collision::Aabb2; use physics::{ ContactResolutionSystem, CurrentFrameUpdateSystem, DeltaTime, NextFrameSetupSystem, PhysicalEntityParts, }; /// Current frame integrator system for 2D /// /// ### Type parameters: /// /// - `S`: Scalar type (f32 or f64) /// - `T`: Transform pub type CurrentFrameUpdateSystem2<S, T> = CurrentFrameUpdateSystem<Point2<S>, Basis2<S>, S, T>; /// Resolution system for 2D /// /// ### Type parameters: /// /// - `S`: Scalar type (f32 or f64) /// - `T`: Transform type (`BodyPose2` or similar) pub type ContactResolutionSystem2<S, T> = ContactResolutionSystem<Point2<S>, Basis2<S>, S, S, S, T>; /// Next frame setup system for 2D /// /// ### Type parameters: /// /// - `S`: Scalar type (f32 or f64) /// - `T`: Transform type (`BodyPose2` or similar) pub type NextFrameSetupSystem2<S, T> = NextFrameSetupSystem<Point2<S>, Basis2<S>, S, S, T, DeltaTime<S>>; /// SystemData for 2D /// /// ### Type parameters: /// /// - `S`: Scalar type (f32 or f64) /// - `T`: Transform type (`BodyPose2` or similar) /// - `Y`: Collision shape type, see `Collider` pub type PhysicalEntityParts2<'a, S, T, Y> = PhysicalEntityParts<'a, Primitive2<S>, Y, Basis2<S>, Vector2<S>, S, S, Aabb2<S>, T>;
// 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::error::Error; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::sync::Arc; use common_exception::ErrorCode; use futures::Future; use tokio::sync::broadcast; use tracing::error; use tracing::info; use super::Stoppable; /// Handle a group of `Stoppable` tasks. /// When a user press ctrl-c, it calls the `stop()` method on every task to close them. /// If a second ctrl-c is pressed, it sends a `()` through the `force` channel to notify tasks to shutdown at once. /// /// Once `StopHandle` is dropped, it triggers a force stop on every tasks in it. pub struct StopHandle<E: Error + Send + 'static> { stopping: Arc<AtomicBool>, pub(crate) stoppable_tasks: Vec<Box<dyn Stoppable<Error = E> + Send>>, } impl<E: Error + Send + 'static> StopHandle<E> { pub fn create() -> Self { StopHandle { stopping: Arc::new(AtomicBool::new(false)), stoppable_tasks: vec![], } } /// Call `Stoppable::stop` on every task, with an arg of **force shutdown signal receiver**. /// /// It blocks until all `Stoppable::stop()` return. pub fn stop_all( &mut self, force_tx: Option<broadcast::Sender<()>>, ) -> Result<impl Future<Output = ()> + Send + '_, ErrorCode> { if self .stopping .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed) .is_err() { return Err(ErrorCode::AlreadyStopped("StopHandle is shutting down")); } let mut handles = vec![]; for s in &mut self.stoppable_tasks { let rx = force_tx.as_ref().map(|x| x.subscribe()); handles.push(s.stop(rx)); } let join_all = futures::future::join_all(handles); Ok(async move { let _ = join_all.await; }) } /// Impl a two phase shutting down procedure(graceful then force): /// /// - The first signal initiates a **graceful** shutdown by calling /// `Stoppable::stop(Option<rx>)` on every managed tasks. /// /// - The second signal will be passed through `rx`, and it's the impl's duty to decide /// whether to forcefully shutdown or just ignore the second signal. pub fn wait_to_terminate( mut self, signal: broadcast::Sender<()>, ) -> impl Future<Output = ()> + 'static { let mut rx = signal.subscribe(); async move { // The first termination signal triggers graceful shutdown // Ignore the result let _ = rx.recv().await; info!("Received termination signal."); info!("Press Ctrl + C again to force shutdown."); // A second signal indicates a force shutdown. // It is the task's responsibility to decide whether to deal with it. let fut = self.stop_all(Some(signal)); if let Ok(f) = fut { f.await; } } } /// Build a Sender `tx` for user to send **stop** signal to all tasks managed by this StopHandle. /// It also installs a `ctrl-c` monitor to let user send a signal to the `tx` by press `ctrl-c`. /// Thus there are two ways to stop tasks: `ctrl-c` or `tx.send()`. /// /// How to deal with the signal is not defined in this method. pub fn install_termination_handle() -> broadcast::Sender<()> { let (tx, _rx) = broadcast::channel(16); let t = tx.clone(); ctrlc::set_handler(move || { if let Err(error) = t.send(()) { error!("Could not send signal on channel {}", error); std::process::exit(1); } }) .expect("Error setting Ctrl-C handler"); tx } pub fn push(&mut self, s: Box<dyn Stoppable<Error = E> + Send>) { self.stoppable_tasks.push(s); } } impl<E: Error + Send + 'static> Drop for StopHandle<E> { fn drop(&mut self) { let (tx, _rx) = broadcast::channel::<()>(16); // let every task subscribe the channel, then send a force stop signal `()` let fut = self.stop_all(Some(tx.clone())); if let Ok(fut) = fut { let _ = tx.send(()); futures::executor::block_on(fut); } } }